upb.c 486 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913
  1. // Amalgamated source file
  2. #include "upb.h"
  3. /* Maps descriptor type -> upb field type. */
  4. static const uint8_t upb_desctype_to_fieldtype[] = {
  5. UPB_WIRE_TYPE_END_GROUP, /* ENDGROUP */
  6. UPB_TYPE_DOUBLE, /* DOUBLE */
  7. UPB_TYPE_FLOAT, /* FLOAT */
  8. UPB_TYPE_INT64, /* INT64 */
  9. UPB_TYPE_UINT64, /* UINT64 */
  10. UPB_TYPE_INT32, /* INT32 */
  11. UPB_TYPE_UINT64, /* FIXED64 */
  12. UPB_TYPE_UINT32, /* FIXED32 */
  13. UPB_TYPE_BOOL, /* BOOL */
  14. UPB_TYPE_STRING, /* STRING */
  15. UPB_TYPE_MESSAGE, /* GROUP */
  16. UPB_TYPE_MESSAGE, /* MESSAGE */
  17. UPB_TYPE_BYTES, /* BYTES */
  18. UPB_TYPE_UINT32, /* UINT32 */
  19. UPB_TYPE_ENUM, /* ENUM */
  20. UPB_TYPE_INT32, /* SFIXED32 */
  21. UPB_TYPE_INT64, /* SFIXED64 */
  22. UPB_TYPE_INT32, /* SINT32 */
  23. UPB_TYPE_INT64, /* SINT64 */
  24. };
  25. /* Data pertaining to the parse. */
  26. typedef struct {
  27. upb_env *env;
  28. /* Current decoding pointer. Points to the beginning of a field until we
  29. * have finished decoding the whole field. */
  30. const char *ptr;
  31. } upb_decstate;
  32. /* Data pertaining to a single message frame. */
  33. typedef struct {
  34. const char *limit;
  35. int32_t group_number; /* 0 if we are not parsing a group. */
  36. /* These members are unset for an unknown group frame. */
  37. char *msg;
  38. const upb_msglayout_msginit_v1 *m;
  39. } upb_decframe;
  40. #define CHK(x) if (!(x)) { return false; }
  41. static bool upb_skip_unknowngroup(upb_decstate *d, int field_number,
  42. const char *limit);
  43. static bool upb_decode_message(upb_decstate *d, const char *limit,
  44. int group_number, char *msg,
  45. const upb_msglayout_msginit_v1 *l);
  46. static bool upb_decode_varint(const char **ptr, const char *limit,
  47. uint64_t *val) {
  48. uint8_t byte;
  49. int bitpos = 0;
  50. const char *p = *ptr;
  51. *val = 0;
  52. do {
  53. CHK(bitpos < 70 && p < limit);
  54. byte = *p;
  55. *val |= (uint64_t)(byte & 0x7F) << bitpos;
  56. p++;
  57. bitpos += 7;
  58. } while (byte & 0x80);
  59. *ptr = p;
  60. return true;
  61. }
  62. static bool upb_decode_varint32(const char **ptr, const char *limit,
  63. uint32_t *val) {
  64. uint64_t u64;
  65. CHK(upb_decode_varint(ptr, limit, &u64) && u64 <= UINT32_MAX);
  66. *val = u64;
  67. return true;
  68. }
  69. static bool upb_decode_64bit(const char **ptr, const char *limit,
  70. uint64_t *val) {
  71. CHK(limit - *ptr >= 8);
  72. memcpy(val, *ptr, 8);
  73. *ptr += 8;
  74. return true;
  75. }
  76. static bool upb_decode_32bit(const char **ptr, const char *limit,
  77. uint32_t *val) {
  78. CHK(limit - *ptr >= 4);
  79. memcpy(val, *ptr, 4);
  80. *ptr += 4;
  81. return true;
  82. }
  83. static bool upb_decode_tag(const char **ptr, const char *limit,
  84. int *field_number, int *wire_type) {
  85. uint32_t tag = 0;
  86. CHK(upb_decode_varint32(ptr, limit, &tag));
  87. *field_number = tag >> 3;
  88. *wire_type = tag & 7;
  89. return true;
  90. }
  91. static int32_t upb_zzdecode_32(uint32_t n) {
  92. return (n >> 1) ^ -(int32_t)(n & 1);
  93. }
  94. static int64_t upb_zzdecode_64(uint64_t n) {
  95. return (n >> 1) ^ -(int64_t)(n & 1);
  96. }
  97. static bool upb_decode_string(const char **ptr, const char *limit,
  98. upb_stringview *val) {
  99. uint32_t len;
  100. CHK(upb_decode_varint32(ptr, limit, &len) &&
  101. len < INT32_MAX &&
  102. limit - *ptr >= (int32_t)len);
  103. *val = upb_stringview_make(*ptr, len);
  104. *ptr += len;
  105. return true;
  106. }
  107. static void upb_set32(void *msg, size_t ofs, uint32_t val) {
  108. memcpy((char*)msg + ofs, &val, sizeof(val));
  109. }
  110. static bool upb_append_unknown(upb_decstate *d, upb_decframe *frame,
  111. const char *start) {
  112. UPB_UNUSED(d);
  113. UPB_UNUSED(frame);
  114. UPB_UNUSED(start);
  115. return true;
  116. }
  117. static bool upb_skip_unknownfielddata(upb_decstate *d, upb_decframe *frame,
  118. int field_number, int wire_type) {
  119. switch (wire_type) {
  120. case UPB_WIRE_TYPE_VARINT: {
  121. uint64_t val;
  122. return upb_decode_varint(&d->ptr, frame->limit, &val);
  123. }
  124. case UPB_WIRE_TYPE_32BIT: {
  125. uint32_t val;
  126. return upb_decode_32bit(&d->ptr, frame->limit, &val);
  127. }
  128. case UPB_WIRE_TYPE_64BIT: {
  129. uint64_t val;
  130. return upb_decode_64bit(&d->ptr, frame->limit, &val);
  131. }
  132. case UPB_WIRE_TYPE_DELIMITED: {
  133. upb_stringview val;
  134. return upb_decode_string(&d->ptr, frame->limit, &val);
  135. }
  136. case UPB_WIRE_TYPE_START_GROUP:
  137. return upb_skip_unknowngroup(d, field_number, frame->limit);
  138. case UPB_WIRE_TYPE_END_GROUP:
  139. CHK(field_number == frame->group_number);
  140. frame->limit = d->ptr;
  141. return true;
  142. }
  143. return false;
  144. }
  145. static bool upb_array_grow(upb_array *arr, size_t elements) {
  146. size_t needed = arr->len + elements;
  147. size_t new_size = UPB_MAX(arr->size, 8);
  148. size_t new_bytes;
  149. size_t old_bytes;
  150. void *new_data;
  151. while (new_size < needed) {
  152. new_size *= 2;
  153. }
  154. old_bytes = arr->len * arr->element_size;
  155. new_bytes = new_size * arr->element_size;
  156. new_data = upb_realloc(arr->alloc, arr->data, old_bytes, new_bytes);
  157. CHK(new_data);
  158. arr->data = new_data;
  159. arr->size = new_size;
  160. return true;
  161. }
  162. static void *upb_array_reserve(upb_array *arr, size_t elements) {
  163. if (arr->size - arr->len < elements) {
  164. CHK(upb_array_grow(arr, elements));
  165. }
  166. return (char*)arr->data + (arr->len * arr->element_size);
  167. }
  168. static void *upb_array_add(upb_array *arr, size_t elements) {
  169. void *ret = upb_array_reserve(arr, elements);
  170. arr->len += elements;
  171. return ret;
  172. }
  173. static upb_array *upb_getarr(upb_decframe *frame,
  174. const upb_msglayout_fieldinit_v1 *field) {
  175. UPB_ASSERT(field->label == UPB_LABEL_REPEATED);
  176. return *(upb_array**)&frame->msg[field->offset];
  177. }
  178. static upb_array *upb_getorcreatearr(upb_decstate *d,
  179. upb_decframe *frame,
  180. const upb_msglayout_fieldinit_v1 *field) {
  181. upb_array *arr = upb_getarr(frame, field);
  182. if (!arr) {
  183. arr = upb_env_malloc(d->env, sizeof(*arr));
  184. if (!arr) {
  185. return NULL;
  186. }
  187. upb_array_init(arr, upb_desctype_to_fieldtype[field->type],
  188. upb_arena_alloc(upb_env_arena(d->env)));
  189. *(upb_array**)&frame->msg[field->offset] = arr;
  190. }
  191. return arr;
  192. }
  193. static void upb_sethasbit(upb_decframe *frame,
  194. const upb_msglayout_fieldinit_v1 *field) {
  195. UPB_ASSERT(field->hasbit != UPB_NO_HASBIT);
  196. frame->msg[field->hasbit / 8] |= (1 << (field->hasbit % 8));
  197. }
  198. static void upb_setoneofcase(upb_decframe *frame,
  199. const upb_msglayout_fieldinit_v1 *field) {
  200. UPB_ASSERT(field->oneof_index != UPB_NOT_IN_ONEOF);
  201. upb_set32(frame->msg, frame->m->oneofs[field->oneof_index].case_offset,
  202. field->number);
  203. }
  204. static char *upb_decode_prepareslot(upb_decstate *d,
  205. upb_decframe *frame,
  206. const upb_msglayout_fieldinit_v1 *field) {
  207. char *field_mem = frame->msg + field->offset;
  208. upb_array *arr;
  209. if (field->label == UPB_LABEL_REPEATED) {
  210. arr = upb_getorcreatearr(d, frame, field);
  211. field_mem = upb_array_reserve(arr, 1);
  212. }
  213. return field_mem;
  214. }
  215. static void upb_decode_setpresent(upb_decframe *frame,
  216. const upb_msglayout_fieldinit_v1 *field) {
  217. if (field->label == UPB_LABEL_REPEATED) {
  218. upb_array *arr = upb_getarr(frame, field);
  219. UPB_ASSERT(arr->len < arr->size);
  220. arr->len++;
  221. } else if (field->oneof_index != UPB_NOT_IN_ONEOF) {
  222. upb_setoneofcase(frame, field);
  223. } else if (field->hasbit != UPB_NO_HASBIT) {
  224. upb_sethasbit(frame, field);
  225. }
  226. }
  227. static bool upb_decode_submsg(upb_decstate *d,
  228. upb_decframe *frame,
  229. const char *limit,
  230. const upb_msglayout_fieldinit_v1 *field,
  231. int group_number) {
  232. char *submsg = *(void**)&frame->msg[field->offset];
  233. const upb_msglayout_msginit_v1 *subm;
  234. UPB_ASSERT(field->submsg_index != UPB_NO_SUBMSG);
  235. subm = frame->m->submsgs[field->submsg_index];
  236. UPB_ASSERT(subm);
  237. if (!submsg) {
  238. submsg = upb_env_malloc(d->env, upb_msg_sizeof((upb_msglayout *)subm));
  239. CHK(submsg);
  240. submsg = upb_msg_init(
  241. submsg, (upb_msglayout*)subm, upb_arena_alloc(upb_env_arena(d->env)));
  242. *(void**)&frame->msg[field->offset] = submsg;
  243. }
  244. upb_decode_message(d, limit, group_number, submsg, subm);
  245. return true;
  246. }
  247. static bool upb_decode_varintfield(upb_decstate *d, upb_decframe *frame,
  248. const char *field_start,
  249. const upb_msglayout_fieldinit_v1 *field) {
  250. uint64_t val;
  251. void *field_mem;
  252. field_mem = upb_decode_prepareslot(d, frame, field);
  253. CHK(field_mem);
  254. CHK(upb_decode_varint(&d->ptr, frame->limit, &val));
  255. switch ((upb_descriptortype_t)field->type) {
  256. case UPB_DESCRIPTOR_TYPE_INT64:
  257. case UPB_DESCRIPTOR_TYPE_UINT64:
  258. memcpy(field_mem, &val, sizeof(val));
  259. break;
  260. case UPB_DESCRIPTOR_TYPE_INT32:
  261. case UPB_DESCRIPTOR_TYPE_UINT32:
  262. case UPB_DESCRIPTOR_TYPE_ENUM: {
  263. uint32_t val32 = val;
  264. memcpy(field_mem, &val32, sizeof(val32));
  265. break;
  266. }
  267. case UPB_DESCRIPTOR_TYPE_BOOL: {
  268. bool valbool = val != 0;
  269. memcpy(field_mem, &valbool, sizeof(valbool));
  270. break;
  271. }
  272. case UPB_DESCRIPTOR_TYPE_SINT32: {
  273. int32_t decoded = upb_zzdecode_32(val);
  274. memcpy(field_mem, &decoded, sizeof(decoded));
  275. break;
  276. }
  277. case UPB_DESCRIPTOR_TYPE_SINT64: {
  278. int64_t decoded = upb_zzdecode_64(val);
  279. memcpy(field_mem, &decoded, sizeof(decoded));
  280. break;
  281. }
  282. default:
  283. return upb_append_unknown(d, frame, field_start);
  284. }
  285. upb_decode_setpresent(frame, field);
  286. return true;
  287. }
  288. static bool upb_decode_64bitfield(upb_decstate *d, upb_decframe *frame,
  289. const char *field_start,
  290. const upb_msglayout_fieldinit_v1 *field) {
  291. void *field_mem;
  292. uint64_t val;
  293. field_mem = upb_decode_prepareslot(d, frame, field);
  294. CHK(field_mem);
  295. CHK(upb_decode_64bit(&d->ptr, frame->limit, &val));
  296. switch ((upb_descriptortype_t)field->type) {
  297. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  298. case UPB_DESCRIPTOR_TYPE_FIXED64:
  299. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  300. memcpy(field_mem, &val, sizeof(val));
  301. break;
  302. default:
  303. return upb_append_unknown(d, frame, field_start);
  304. }
  305. upb_decode_setpresent(frame, field);
  306. return true;
  307. }
  308. static bool upb_decode_32bitfield(upb_decstate *d, upb_decframe *frame,
  309. const char *field_start,
  310. const upb_msglayout_fieldinit_v1 *field) {
  311. void *field_mem;
  312. uint32_t val;
  313. field_mem = upb_decode_prepareslot(d, frame, field);
  314. CHK(field_mem);
  315. CHK(upb_decode_32bit(&d->ptr, frame->limit, &val));
  316. switch ((upb_descriptortype_t)field->type) {
  317. case UPB_DESCRIPTOR_TYPE_FLOAT:
  318. case UPB_DESCRIPTOR_TYPE_FIXED32:
  319. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  320. memcpy(field_mem, &val, sizeof(val));
  321. break;
  322. default:
  323. return upb_append_unknown(d, frame, field_start);
  324. }
  325. upb_decode_setpresent(frame, field);
  326. return true;
  327. }
  328. static bool upb_decode_fixedpacked(upb_array *arr, upb_stringview data,
  329. int elem_size) {
  330. int elements = data.size / elem_size;
  331. void *field_mem;
  332. CHK((size_t)(elements * elem_size) == data.size);
  333. field_mem = upb_array_add(arr, elements);
  334. CHK(field_mem);
  335. memcpy(field_mem, data.data, data.size);
  336. return true;
  337. }
  338. static bool upb_decode_toarray(upb_decstate *d, upb_decframe *frame,
  339. const char *field_start,
  340. const upb_msglayout_fieldinit_v1 *field,
  341. upb_stringview val) {
  342. upb_array *arr = upb_getorcreatearr(d, frame, field);
  343. #define VARINT_CASE(ctype, decode) { \
  344. const char *ptr = val.data; \
  345. const char *limit = ptr + val.size; \
  346. while (ptr < limit) { \
  347. uint64_t val; \
  348. void *field_mem; \
  349. ctype decoded; \
  350. CHK(upb_decode_varint(&ptr, limit, &val)); \
  351. decoded = (decode)(val); \
  352. field_mem = upb_array_add(arr, 1); \
  353. CHK(field_mem); \
  354. memcpy(field_mem, &decoded, sizeof(ctype)); \
  355. } \
  356. return true; \
  357. }
  358. switch ((upb_descriptortype_t)field->type) {
  359. case UPB_DESCRIPTOR_TYPE_STRING:
  360. case UPB_DESCRIPTOR_TYPE_BYTES: {
  361. void *field_mem = upb_array_add(arr, 1);
  362. CHK(field_mem);
  363. memcpy(field_mem, &val, sizeof(val));
  364. return true;
  365. }
  366. case UPB_DESCRIPTOR_TYPE_FLOAT:
  367. case UPB_DESCRIPTOR_TYPE_FIXED32:
  368. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  369. return upb_decode_fixedpacked(arr, val, sizeof(int32_t));
  370. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  371. case UPB_DESCRIPTOR_TYPE_FIXED64:
  372. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  373. return upb_decode_fixedpacked(arr, val, sizeof(int64_t));
  374. case UPB_DESCRIPTOR_TYPE_INT32:
  375. case UPB_DESCRIPTOR_TYPE_UINT32:
  376. case UPB_DESCRIPTOR_TYPE_ENUM:
  377. /* TODO: proto2 enum field that isn't in the enum. */
  378. VARINT_CASE(uint32_t, uint32_t);
  379. case UPB_DESCRIPTOR_TYPE_INT64:
  380. case UPB_DESCRIPTOR_TYPE_UINT64:
  381. VARINT_CASE(uint64_t, uint64_t);
  382. case UPB_DESCRIPTOR_TYPE_BOOL:
  383. VARINT_CASE(bool, bool);
  384. case UPB_DESCRIPTOR_TYPE_SINT32:
  385. VARINT_CASE(int32_t, upb_zzdecode_32);
  386. case UPB_DESCRIPTOR_TYPE_SINT64:
  387. VARINT_CASE(int64_t, upb_zzdecode_64);
  388. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  389. CHK(val.size <= (size_t)(frame->limit - val.data));
  390. return upb_decode_submsg(d, frame, val.data + val.size, field, 0);
  391. case UPB_DESCRIPTOR_TYPE_GROUP:
  392. return upb_append_unknown(d, frame, field_start);
  393. }
  394. #undef VARINT_CASE
  395. UPB_UNREACHABLE();
  396. }
  397. static bool upb_decode_delimitedfield(upb_decstate *d, upb_decframe *frame,
  398. const char *field_start,
  399. const upb_msglayout_fieldinit_v1 *field) {
  400. upb_stringview val;
  401. CHK(upb_decode_string(&d->ptr, frame->limit, &val));
  402. if (field->label == UPB_LABEL_REPEATED) {
  403. return upb_decode_toarray(d, frame, field_start, field, val);
  404. } else {
  405. switch ((upb_descriptortype_t)field->type) {
  406. case UPB_DESCRIPTOR_TYPE_STRING:
  407. case UPB_DESCRIPTOR_TYPE_BYTES: {
  408. void *field_mem = upb_decode_prepareslot(d, frame, field);
  409. CHK(field_mem);
  410. memcpy(field_mem, &val, sizeof(val));
  411. break;
  412. }
  413. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  414. CHK(val.size <= (size_t)(frame->limit - val.data));
  415. CHK(upb_decode_submsg(d, frame, val.data + val.size, field, 0));
  416. break;
  417. default:
  418. /* TODO(haberman): should we accept the last element of a packed? */
  419. return upb_append_unknown(d, frame, field_start);
  420. }
  421. upb_decode_setpresent(frame, field);
  422. return true;
  423. }
  424. }
  425. static const upb_msglayout_fieldinit_v1 *upb_find_field(
  426. const upb_msglayout_msginit_v1 *l, uint32_t field_number) {
  427. /* Lots of optimization opportunities here. */
  428. int i;
  429. for (i = 0; i < l->field_count; i++) {
  430. if (l->fields[i].number == field_number) {
  431. return &l->fields[i];
  432. }
  433. }
  434. return NULL; /* Unknown field. */
  435. }
  436. static bool upb_decode_field(upb_decstate *d, upb_decframe *frame) {
  437. int field_number;
  438. int wire_type;
  439. const char *field_start = d->ptr;
  440. const upb_msglayout_fieldinit_v1 *field;
  441. CHK(upb_decode_tag(&d->ptr, frame->limit, &field_number, &wire_type));
  442. field = upb_find_field(frame->m, field_number);
  443. if (field) {
  444. switch (wire_type) {
  445. case UPB_WIRE_TYPE_VARINT:
  446. return upb_decode_varintfield(d, frame, field_start, field);
  447. case UPB_WIRE_TYPE_32BIT:
  448. return upb_decode_32bitfield(d, frame, field_start, field);
  449. case UPB_WIRE_TYPE_64BIT:
  450. return upb_decode_64bitfield(d, frame, field_start, field);
  451. case UPB_WIRE_TYPE_DELIMITED:
  452. return upb_decode_delimitedfield(d, frame, field_start, field);
  453. case UPB_WIRE_TYPE_START_GROUP:
  454. CHK(field->type == UPB_DESCRIPTOR_TYPE_GROUP);
  455. return upb_decode_submsg(d, frame, frame->limit, field, field_number);
  456. case UPB_WIRE_TYPE_END_GROUP:
  457. CHK(frame->group_number == field_number)
  458. frame->limit = d->ptr;
  459. return true;
  460. default:
  461. return false;
  462. }
  463. } else {
  464. CHK(field_number != 0);
  465. return upb_skip_unknownfielddata(d, frame, field_number, wire_type);
  466. }
  467. }
  468. static bool upb_skip_unknowngroup(upb_decstate *d, int field_number,
  469. const char *limit) {
  470. upb_decframe frame;
  471. frame.msg = NULL;
  472. frame.m = NULL;
  473. frame.group_number = field_number;
  474. frame.limit = limit;
  475. while (d->ptr < frame.limit) {
  476. int wire_type;
  477. int field_number;
  478. CHK(upb_decode_tag(&d->ptr, frame.limit, &field_number, &wire_type));
  479. CHK(upb_skip_unknownfielddata(d, &frame, field_number, wire_type));
  480. }
  481. return true;
  482. }
  483. static bool upb_decode_message(upb_decstate *d, const char *limit,
  484. int group_number, char *msg,
  485. const upb_msglayout_msginit_v1 *l) {
  486. upb_decframe frame;
  487. frame.group_number = group_number;
  488. frame.limit = limit;
  489. frame.msg = msg;
  490. frame.m = l;
  491. while (d->ptr < frame.limit) {
  492. CHK(upb_decode_field(d, &frame));
  493. }
  494. return true;
  495. }
  496. bool upb_decode(upb_stringview buf, void *msg,
  497. const upb_msglayout_msginit_v1 *l, upb_env *env) {
  498. upb_decstate state;
  499. state.ptr = buf.data;
  500. state.env = env;
  501. return upb_decode_message(&state, buf.data + buf.size, 0, msg, l);
  502. }
  503. #undef CHK
  504. #include <ctype.h>
  505. #include <stdlib.h>
  506. #include <string.h>
  507. typedef struct {
  508. size_t len;
  509. char str[1]; /* Null-terminated string data follows. */
  510. } str_t;
  511. static str_t *newstr(const char *data, size_t len) {
  512. str_t *ret = upb_gmalloc(sizeof(*ret) + len);
  513. if (!ret) return NULL;
  514. ret->len = len;
  515. memcpy(ret->str, data, len);
  516. ret->str[len] = '\0';
  517. return ret;
  518. }
  519. static void freestr(str_t *s) { upb_gfree(s); }
  520. /* isalpha() etc. from <ctype.h> are locale-dependent, which we don't want. */
  521. static bool upb_isbetween(char c, char low, char high) {
  522. return c >= low && c <= high;
  523. }
  524. static bool upb_isletter(char c) {
  525. return upb_isbetween(c, 'A', 'Z') || upb_isbetween(c, 'a', 'z') || c == '_';
  526. }
  527. static bool upb_isalphanum(char c) {
  528. return upb_isletter(c) || upb_isbetween(c, '0', '9');
  529. }
  530. static bool upb_isident(const char *str, size_t len, bool full, upb_status *s) {
  531. bool start = true;
  532. size_t i;
  533. for (i = 0; i < len; i++) {
  534. char c = str[i];
  535. if (c == '.') {
  536. if (start || !full) {
  537. upb_status_seterrf(s, "invalid name: unexpected '.' (%s)", str);
  538. return false;
  539. }
  540. start = true;
  541. } else if (start) {
  542. if (!upb_isletter(c)) {
  543. upb_status_seterrf(
  544. s, "invalid name: path components must start with a letter (%s)",
  545. str);
  546. return false;
  547. }
  548. start = false;
  549. } else {
  550. if (!upb_isalphanum(c)) {
  551. upb_status_seterrf(s, "invalid name: non-alphanumeric character (%s)",
  552. str);
  553. return false;
  554. }
  555. }
  556. }
  557. return !start;
  558. }
  559. static bool upb_isoneof(const upb_refcounted *def) {
  560. return def->vtbl == &upb_oneofdef_vtbl;
  561. }
  562. static bool upb_isfield(const upb_refcounted *def) {
  563. return def->vtbl == &upb_fielddef_vtbl;
  564. }
  565. static const upb_oneofdef *upb_trygetoneof(const upb_refcounted *def) {
  566. return upb_isoneof(def) ? (const upb_oneofdef*)def : NULL;
  567. }
  568. static const upb_fielddef *upb_trygetfield(const upb_refcounted *def) {
  569. return upb_isfield(def) ? (const upb_fielddef*)def : NULL;
  570. }
  571. /* upb_def ********************************************************************/
  572. upb_deftype_t upb_def_type(const upb_def *d) { return d->type; }
  573. const char *upb_def_fullname(const upb_def *d) { return d->fullname; }
  574. const char *upb_def_name(const upb_def *d) {
  575. const char *p;
  576. if (d->fullname == NULL) {
  577. return NULL;
  578. } else if ((p = strrchr(d->fullname, '.')) == NULL) {
  579. /* No '.' in the name, return the full string. */
  580. return d->fullname;
  581. } else {
  582. /* Return one past the last '.'. */
  583. return p + 1;
  584. }
  585. }
  586. bool upb_def_setfullname(upb_def *def, const char *fullname, upb_status *s) {
  587. UPB_ASSERT(!upb_def_isfrozen(def));
  588. if (!upb_isident(fullname, strlen(fullname), true, s)) {
  589. return false;
  590. }
  591. fullname = upb_gstrdup(fullname);
  592. if (!fullname) {
  593. upb_upberr_setoom(s);
  594. return false;
  595. }
  596. upb_gfree((void*)def->fullname);
  597. def->fullname = fullname;
  598. return true;
  599. }
  600. const upb_filedef *upb_def_file(const upb_def *d) { return d->file; }
  601. static bool upb_def_init(upb_def *def, upb_deftype_t type,
  602. const struct upb_refcounted_vtbl *vtbl,
  603. const void *owner) {
  604. if (!upb_refcounted_init(upb_def_upcast_mutable(def), vtbl, owner)) return false;
  605. def->type = type;
  606. def->fullname = NULL;
  607. def->came_from_user = false;
  608. def->file = NULL;
  609. return true;
  610. }
  611. static void upb_def_uninit(upb_def *def) {
  612. upb_gfree((void*)def->fullname);
  613. }
  614. static const char *msgdef_name(const upb_msgdef *m) {
  615. const char *name = upb_def_fullname(upb_msgdef_upcast(m));
  616. return name ? name : "(anonymous)";
  617. }
  618. static bool upb_validate_field(upb_fielddef *f, upb_status *s) {
  619. if (upb_fielddef_name(f) == NULL || upb_fielddef_number(f) == 0) {
  620. upb_status_seterrmsg(s, "fielddef must have name and number set");
  621. return false;
  622. }
  623. if (!f->type_is_set_) {
  624. upb_status_seterrmsg(s, "fielddef type was not initialized");
  625. return false;
  626. }
  627. if (upb_fielddef_lazy(f) &&
  628. upb_fielddef_descriptortype(f) != UPB_DESCRIPTOR_TYPE_MESSAGE) {
  629. upb_status_seterrmsg(s,
  630. "only length-delimited submessage fields may be lazy");
  631. return false;
  632. }
  633. if (upb_fielddef_hassubdef(f)) {
  634. const upb_def *subdef;
  635. if (f->subdef_is_symbolic) {
  636. upb_status_seterrf(s, "field '%s.%s' has not been resolved",
  637. msgdef_name(f->msg.def), upb_fielddef_name(f));
  638. return false;
  639. }
  640. subdef = upb_fielddef_subdef(f);
  641. if (subdef == NULL) {
  642. upb_status_seterrf(s, "field %s.%s is missing required subdef",
  643. msgdef_name(f->msg.def), upb_fielddef_name(f));
  644. return false;
  645. }
  646. if (!upb_def_isfrozen(subdef) && !subdef->came_from_user) {
  647. upb_status_seterrf(s,
  648. "subdef of field %s.%s is not frozen or being frozen",
  649. msgdef_name(f->msg.def), upb_fielddef_name(f));
  650. return false;
  651. }
  652. }
  653. if (upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  654. bool has_default_name = upb_fielddef_enumhasdefaultstr(f);
  655. bool has_default_number = upb_fielddef_enumhasdefaultint32(f);
  656. /* Previously verified by upb_validate_enumdef(). */
  657. UPB_ASSERT(upb_enumdef_numvals(upb_fielddef_enumsubdef(f)) > 0);
  658. /* We've already validated that we have an associated enumdef and that it
  659. * has at least one member, so at least one of these should be true.
  660. * Because if the user didn't set anything, we'll pick up the enum's
  661. * default, but if the user *did* set something we should at least pick up
  662. * the one they set (int32 or string). */
  663. UPB_ASSERT(has_default_name || has_default_number);
  664. if (!has_default_name) {
  665. upb_status_seterrf(s,
  666. "enum default for field %s.%s (%d) is not in the enum",
  667. msgdef_name(f->msg.def), upb_fielddef_name(f),
  668. upb_fielddef_defaultint32(f));
  669. return false;
  670. }
  671. if (!has_default_number) {
  672. upb_status_seterrf(s,
  673. "enum default for field %s.%s (%s) is not in the enum",
  674. msgdef_name(f->msg.def), upb_fielddef_name(f),
  675. upb_fielddef_defaultstr(f, NULL));
  676. return false;
  677. }
  678. /* Lift the effective numeric default into the field's default slot, in case
  679. * we were only getting it "by reference" from the enumdef. */
  680. upb_fielddef_setdefaultint32(f, upb_fielddef_defaultint32(f));
  681. }
  682. /* Ensure that MapEntry submessages only appear as repeated fields, not
  683. * optional/required (singular) fields. */
  684. if (upb_fielddef_type(f) == UPB_TYPE_MESSAGE &&
  685. upb_fielddef_msgsubdef(f) != NULL) {
  686. const upb_msgdef *subdef = upb_fielddef_msgsubdef(f);
  687. if (upb_msgdef_mapentry(subdef) && !upb_fielddef_isseq(f)) {
  688. upb_status_seterrf(s,
  689. "Field %s refers to mapentry message but is not "
  690. "a repeated field",
  691. upb_fielddef_name(f) ? upb_fielddef_name(f) :
  692. "(unnamed)");
  693. return false;
  694. }
  695. }
  696. return true;
  697. }
  698. static bool upb_validate_enumdef(const upb_enumdef *e, upb_status *s) {
  699. if (upb_enumdef_numvals(e) == 0) {
  700. upb_status_seterrf(s, "enum %s has no members (must have at least one)",
  701. upb_enumdef_fullname(e));
  702. return false;
  703. }
  704. return true;
  705. }
  706. /* All submessage fields are lower than all other fields.
  707. * Secondly, fields are increasing in order. */
  708. uint32_t field_rank(const upb_fielddef *f) {
  709. uint32_t ret = upb_fielddef_number(f);
  710. const uint32_t high_bit = 1 << 30;
  711. UPB_ASSERT(ret < high_bit);
  712. if (!upb_fielddef_issubmsg(f))
  713. ret |= high_bit;
  714. return ret;
  715. }
  716. int cmp_fields(const void *p1, const void *p2) {
  717. const upb_fielddef *f1 = *(upb_fielddef*const*)p1;
  718. const upb_fielddef *f2 = *(upb_fielddef*const*)p2;
  719. return field_rank(f1) - field_rank(f2);
  720. }
  721. static bool assign_msg_indices(upb_msgdef *m, upb_status *s) {
  722. /* Sort fields. upb internally relies on UPB_TYPE_MESSAGE fields having the
  723. * lowest indexes, but we do not publicly guarantee this. */
  724. upb_msg_field_iter j;
  725. upb_msg_oneof_iter k;
  726. int i;
  727. uint32_t selector;
  728. int n = upb_msgdef_numfields(m);
  729. upb_fielddef **fields;
  730. if (n == 0) {
  731. m->selector_count = UPB_STATIC_SELECTOR_COUNT;
  732. m->submsg_field_count = 0;
  733. return true;
  734. }
  735. fields = upb_gmalloc(n * sizeof(*fields));
  736. if (!fields) {
  737. upb_upberr_setoom(s);
  738. return false;
  739. }
  740. m->submsg_field_count = 0;
  741. for(i = 0, upb_msg_field_begin(&j, m);
  742. !upb_msg_field_done(&j);
  743. upb_msg_field_next(&j), i++) {
  744. upb_fielddef *f = upb_msg_iter_field(&j);
  745. UPB_ASSERT(f->msg.def == m);
  746. if (!upb_validate_field(f, s)) {
  747. upb_gfree(fields);
  748. return false;
  749. }
  750. if (upb_fielddef_issubmsg(f)) {
  751. m->submsg_field_count++;
  752. }
  753. fields[i] = f;
  754. }
  755. qsort(fields, n, sizeof(*fields), cmp_fields);
  756. selector = UPB_STATIC_SELECTOR_COUNT + m->submsg_field_count;
  757. for (i = 0; i < n; i++) {
  758. upb_fielddef *f = fields[i];
  759. f->index_ = i;
  760. f->selector_base = selector + upb_handlers_selectorbaseoffset(f);
  761. selector += upb_handlers_selectorcount(f);
  762. }
  763. m->selector_count = selector;
  764. #ifndef NDEBUG
  765. {
  766. /* Verify that all selectors for the message are distinct. */
  767. #define TRY(type) \
  768. if (upb_handlers_getselector(f, type, &sel)) upb_inttable_insert(&t, sel, v);
  769. upb_inttable t;
  770. upb_value v;
  771. upb_selector_t sel;
  772. upb_inttable_init(&t, UPB_CTYPE_BOOL);
  773. v = upb_value_bool(true);
  774. upb_inttable_insert(&t, UPB_STARTMSG_SELECTOR, v);
  775. upb_inttable_insert(&t, UPB_ENDMSG_SELECTOR, v);
  776. upb_inttable_insert(&t, UPB_UNKNOWN_SELECTOR, v);
  777. for(upb_msg_field_begin(&j, m);
  778. !upb_msg_field_done(&j);
  779. upb_msg_field_next(&j)) {
  780. upb_fielddef *f = upb_msg_iter_field(&j);
  781. /* These calls will assert-fail in upb_table if the value already
  782. * exists. */
  783. TRY(UPB_HANDLER_INT32);
  784. TRY(UPB_HANDLER_INT64)
  785. TRY(UPB_HANDLER_UINT32)
  786. TRY(UPB_HANDLER_UINT64)
  787. TRY(UPB_HANDLER_FLOAT)
  788. TRY(UPB_HANDLER_DOUBLE)
  789. TRY(UPB_HANDLER_BOOL)
  790. TRY(UPB_HANDLER_STARTSTR)
  791. TRY(UPB_HANDLER_STRING)
  792. TRY(UPB_HANDLER_ENDSTR)
  793. TRY(UPB_HANDLER_STARTSUBMSG)
  794. TRY(UPB_HANDLER_ENDSUBMSG)
  795. TRY(UPB_HANDLER_STARTSEQ)
  796. TRY(UPB_HANDLER_ENDSEQ)
  797. }
  798. upb_inttable_uninit(&t);
  799. }
  800. #undef TRY
  801. #endif
  802. for(upb_msg_oneof_begin(&k, m), i = 0;
  803. !upb_msg_oneof_done(&k);
  804. upb_msg_oneof_next(&k), i++) {
  805. upb_oneofdef *o = upb_msg_iter_oneof(&k);
  806. o->index = i;
  807. }
  808. upb_gfree(fields);
  809. return true;
  810. }
  811. bool _upb_def_validate(upb_def *const*defs, size_t n, upb_status *s) {
  812. size_t i;
  813. /* First perform validation, in two passes so we can check that we have a
  814. * transitive closure without needing to search. */
  815. for (i = 0; i < n; i++) {
  816. upb_def *def = defs[i];
  817. if (upb_def_isfrozen(def)) {
  818. /* Could relax this requirement if it's annoying. */
  819. upb_status_seterrmsg(s, "def is already frozen");
  820. goto err;
  821. } else if (def->type == UPB_DEF_FIELD) {
  822. upb_status_seterrmsg(s, "standalone fielddefs can not be frozen");
  823. goto err;
  824. } else {
  825. /* Set now to detect transitive closure in the second pass. */
  826. def->came_from_user = true;
  827. if (def->type == UPB_DEF_ENUM &&
  828. !upb_validate_enumdef(upb_dyncast_enumdef(def), s)) {
  829. goto err;
  830. }
  831. }
  832. }
  833. /* Second pass of validation. Also assign selector bases and indexes, and
  834. * compact tables. */
  835. for (i = 0; i < n; i++) {
  836. upb_def *def = defs[i];
  837. upb_msgdef *m = upb_dyncast_msgdef_mutable(def);
  838. upb_enumdef *e = upb_dyncast_enumdef_mutable(def);
  839. if (m) {
  840. upb_inttable_compact(&m->itof);
  841. if (!assign_msg_indices(m, s)) {
  842. goto err;
  843. }
  844. } else if (e) {
  845. upb_inttable_compact(&e->iton);
  846. }
  847. }
  848. return true;
  849. err:
  850. for (i = 0; i < n; i++) {
  851. upb_def *def = defs[i];
  852. def->came_from_user = false;
  853. }
  854. UPB_ASSERT(!(s && upb_ok(s)));
  855. return false;
  856. }
  857. bool upb_def_freeze(upb_def *const* defs, size_t n, upb_status *s) {
  858. /* Def graph contains FieldDefs between each MessageDef, so double the
  859. * limit. */
  860. const size_t maxdepth = UPB_MAX_MESSAGE_DEPTH * 2;
  861. if (!_upb_def_validate(defs, n, s)) {
  862. return false;
  863. }
  864. /* Validation all passed; freeze the objects. */
  865. return upb_refcounted_freeze((upb_refcounted *const*)defs, n, s, maxdepth);
  866. }
  867. /* upb_enumdef ****************************************************************/
  868. static void visitenum(const upb_refcounted *r, upb_refcounted_visit *visit,
  869. void *closure) {
  870. const upb_enumdef *e = (const upb_enumdef*)r;
  871. const upb_def *def = upb_enumdef_upcast(e);
  872. if (upb_def_file(def)) {
  873. visit(r, upb_filedef_upcast(upb_def_file(def)), closure);
  874. }
  875. }
  876. static void freeenum(upb_refcounted *r) {
  877. upb_enumdef *e = (upb_enumdef*)r;
  878. upb_inttable_iter i;
  879. upb_inttable_begin(&i, &e->iton);
  880. for( ; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  881. /* To clean up the upb_gstrdup() from upb_enumdef_addval(). */
  882. upb_gfree(upb_value_getcstr(upb_inttable_iter_value(&i)));
  883. }
  884. upb_strtable_uninit(&e->ntoi);
  885. upb_inttable_uninit(&e->iton);
  886. upb_def_uninit(upb_enumdef_upcast_mutable(e));
  887. upb_gfree(e);
  888. }
  889. const struct upb_refcounted_vtbl upb_enumdef_vtbl = {&visitenum, &freeenum};
  890. upb_enumdef *upb_enumdef_new(const void *owner) {
  891. upb_enumdef *e = upb_gmalloc(sizeof(*e));
  892. if (!e) return NULL;
  893. if (!upb_def_init(upb_enumdef_upcast_mutable(e), UPB_DEF_ENUM,
  894. &upb_enumdef_vtbl, owner)) {
  895. goto err2;
  896. }
  897. if (!upb_strtable_init(&e->ntoi, UPB_CTYPE_INT32)) goto err2;
  898. if (!upb_inttable_init(&e->iton, UPB_CTYPE_CSTR)) goto err1;
  899. return e;
  900. err1:
  901. upb_strtable_uninit(&e->ntoi);
  902. err2:
  903. upb_gfree(e);
  904. return NULL;
  905. }
  906. bool upb_enumdef_freeze(upb_enumdef *e, upb_status *status) {
  907. upb_def *d = upb_enumdef_upcast_mutable(e);
  908. return upb_def_freeze(&d, 1, status);
  909. }
  910. const char *upb_enumdef_fullname(const upb_enumdef *e) {
  911. return upb_def_fullname(upb_enumdef_upcast(e));
  912. }
  913. const char *upb_enumdef_name(const upb_enumdef *e) {
  914. return upb_def_name(upb_enumdef_upcast(e));
  915. }
  916. bool upb_enumdef_setfullname(upb_enumdef *e, const char *fullname,
  917. upb_status *s) {
  918. return upb_def_setfullname(upb_enumdef_upcast_mutable(e), fullname, s);
  919. }
  920. bool upb_enumdef_addval(upb_enumdef *e, const char *name, int32_t num,
  921. upb_status *status) {
  922. char *name2;
  923. if (!upb_isident(name, strlen(name), false, status)) {
  924. return false;
  925. }
  926. if (upb_enumdef_ntoiz(e, name, NULL)) {
  927. upb_status_seterrf(status, "name '%s' is already defined", name);
  928. return false;
  929. }
  930. if (!upb_strtable_insert(&e->ntoi, name, upb_value_int32(num))) {
  931. upb_status_seterrmsg(status, "out of memory");
  932. return false;
  933. }
  934. if (!upb_inttable_lookup(&e->iton, num, NULL)) {
  935. name2 = upb_gstrdup(name);
  936. if (!name2 || !upb_inttable_insert(&e->iton, num, upb_value_cstr(name2))) {
  937. upb_status_seterrmsg(status, "out of memory");
  938. upb_strtable_remove(&e->ntoi, name, NULL);
  939. return false;
  940. }
  941. }
  942. if (upb_enumdef_numvals(e) == 1) {
  943. bool ok = upb_enumdef_setdefault(e, num, NULL);
  944. UPB_ASSERT(ok);
  945. }
  946. return true;
  947. }
  948. int32_t upb_enumdef_default(const upb_enumdef *e) {
  949. UPB_ASSERT(upb_enumdef_iton(e, e->defaultval));
  950. return e->defaultval;
  951. }
  952. bool upb_enumdef_setdefault(upb_enumdef *e, int32_t val, upb_status *s) {
  953. UPB_ASSERT(!upb_enumdef_isfrozen(e));
  954. if (!upb_enumdef_iton(e, val)) {
  955. upb_status_seterrf(s, "number '%d' is not in the enum.", val);
  956. return false;
  957. }
  958. e->defaultval = val;
  959. return true;
  960. }
  961. int upb_enumdef_numvals(const upb_enumdef *e) {
  962. return upb_strtable_count(&e->ntoi);
  963. }
  964. void upb_enum_begin(upb_enum_iter *i, const upb_enumdef *e) {
  965. /* We iterate over the ntoi table, to account for duplicate numbers. */
  966. upb_strtable_begin(i, &e->ntoi);
  967. }
  968. void upb_enum_next(upb_enum_iter *iter) { upb_strtable_next(iter); }
  969. bool upb_enum_done(upb_enum_iter *iter) { return upb_strtable_done(iter); }
  970. bool upb_enumdef_ntoi(const upb_enumdef *def, const char *name,
  971. size_t len, int32_t *num) {
  972. upb_value v;
  973. if (!upb_strtable_lookup2(&def->ntoi, name, len, &v)) {
  974. return false;
  975. }
  976. if (num) *num = upb_value_getint32(v);
  977. return true;
  978. }
  979. const char *upb_enumdef_iton(const upb_enumdef *def, int32_t num) {
  980. upb_value v;
  981. return upb_inttable_lookup32(&def->iton, num, &v) ?
  982. upb_value_getcstr(v) : NULL;
  983. }
  984. const char *upb_enum_iter_name(upb_enum_iter *iter) {
  985. return upb_strtable_iter_key(iter);
  986. }
  987. int32_t upb_enum_iter_number(upb_enum_iter *iter) {
  988. return upb_value_getint32(upb_strtable_iter_value(iter));
  989. }
  990. /* upb_fielddef ***************************************************************/
  991. static void upb_fielddef_init_default(upb_fielddef *f);
  992. static void upb_fielddef_uninit_default(upb_fielddef *f) {
  993. if (f->type_is_set_ && f->default_is_string && f->defaultval.bytes)
  994. freestr(f->defaultval.bytes);
  995. }
  996. const char *upb_fielddef_fullname(const upb_fielddef *e) {
  997. return upb_def_fullname(upb_fielddef_upcast(e));
  998. }
  999. static void visitfield(const upb_refcounted *r, upb_refcounted_visit *visit,
  1000. void *closure) {
  1001. const upb_fielddef *f = (const upb_fielddef*)r;
  1002. const upb_def *def = upb_fielddef_upcast(f);
  1003. if (upb_fielddef_containingtype(f)) {
  1004. visit(r, upb_msgdef_upcast2(upb_fielddef_containingtype(f)), closure);
  1005. }
  1006. if (upb_fielddef_containingoneof(f)) {
  1007. visit(r, upb_oneofdef_upcast(upb_fielddef_containingoneof(f)), closure);
  1008. }
  1009. if (upb_fielddef_subdef(f)) {
  1010. visit(r, upb_def_upcast(upb_fielddef_subdef(f)), closure);
  1011. }
  1012. if (upb_def_file(def)) {
  1013. visit(r, upb_filedef_upcast(upb_def_file(def)), closure);
  1014. }
  1015. }
  1016. static void freefield(upb_refcounted *r) {
  1017. upb_fielddef *f = (upb_fielddef*)r;
  1018. upb_fielddef_uninit_default(f);
  1019. if (f->subdef_is_symbolic)
  1020. upb_gfree(f->sub.name);
  1021. upb_def_uninit(upb_fielddef_upcast_mutable(f));
  1022. upb_gfree(f);
  1023. }
  1024. static const char *enumdefaultstr(const upb_fielddef *f) {
  1025. const upb_enumdef *e;
  1026. UPB_ASSERT(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  1027. e = upb_fielddef_enumsubdef(f);
  1028. if (f->default_is_string && f->defaultval.bytes) {
  1029. /* Default was explicitly set as a string. */
  1030. str_t *s = f->defaultval.bytes;
  1031. return s->str;
  1032. } else if (e) {
  1033. if (!f->default_is_string) {
  1034. /* Default was explicitly set as an integer; look it up in enumdef. */
  1035. const char *name = upb_enumdef_iton(e, f->defaultval.sint);
  1036. if (name) {
  1037. return name;
  1038. }
  1039. } else {
  1040. /* Default is completely unset; pull enumdef default. */
  1041. if (upb_enumdef_numvals(e) > 0) {
  1042. const char *name = upb_enumdef_iton(e, upb_enumdef_default(e));
  1043. UPB_ASSERT(name);
  1044. return name;
  1045. }
  1046. }
  1047. }
  1048. return NULL;
  1049. }
  1050. static bool enumdefaultint32(const upb_fielddef *f, int32_t *val) {
  1051. const upb_enumdef *e;
  1052. UPB_ASSERT(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  1053. e = upb_fielddef_enumsubdef(f);
  1054. if (!f->default_is_string) {
  1055. /* Default was explicitly set as an integer. */
  1056. *val = f->defaultval.sint;
  1057. return true;
  1058. } else if (e) {
  1059. if (f->defaultval.bytes) {
  1060. /* Default was explicitly set as a str; try to lookup corresponding int. */
  1061. str_t *s = f->defaultval.bytes;
  1062. if (upb_enumdef_ntoiz(e, s->str, val)) {
  1063. return true;
  1064. }
  1065. } else {
  1066. /* Default is unset; try to pull in enumdef default. */
  1067. if (upb_enumdef_numvals(e) > 0) {
  1068. *val = upb_enumdef_default(e);
  1069. return true;
  1070. }
  1071. }
  1072. }
  1073. return false;
  1074. }
  1075. const struct upb_refcounted_vtbl upb_fielddef_vtbl = {visitfield, freefield};
  1076. upb_fielddef *upb_fielddef_new(const void *o) {
  1077. upb_fielddef *f = upb_gmalloc(sizeof(*f));
  1078. if (!f) return NULL;
  1079. if (!upb_def_init(upb_fielddef_upcast_mutable(f), UPB_DEF_FIELD,
  1080. &upb_fielddef_vtbl, o)) {
  1081. upb_gfree(f);
  1082. return NULL;
  1083. }
  1084. f->msg.def = NULL;
  1085. f->sub.def = NULL;
  1086. f->oneof = NULL;
  1087. f->subdef_is_symbolic = false;
  1088. f->msg_is_symbolic = false;
  1089. f->label_ = UPB_LABEL_OPTIONAL;
  1090. f->type_ = UPB_TYPE_INT32;
  1091. f->number_ = 0;
  1092. f->type_is_set_ = false;
  1093. f->tagdelim = false;
  1094. f->is_extension_ = false;
  1095. f->lazy_ = false;
  1096. f->packed_ = true;
  1097. /* For the moment we default this to UPB_INTFMT_VARIABLE, since it will work
  1098. * with all integer types and is in some since more "default" since the most
  1099. * normal-looking proto2 types int32/int64/uint32/uint64 use variable.
  1100. *
  1101. * Other options to consider:
  1102. * - there is no default; users must set this manually (like type).
  1103. * - default signed integers to UPB_INTFMT_ZIGZAG, since it's more likely to
  1104. * be an optimal default for signed integers. */
  1105. f->intfmt = UPB_INTFMT_VARIABLE;
  1106. return f;
  1107. }
  1108. bool upb_fielddef_typeisset(const upb_fielddef *f) {
  1109. return f->type_is_set_;
  1110. }
  1111. upb_fieldtype_t upb_fielddef_type(const upb_fielddef *f) {
  1112. UPB_ASSERT(f->type_is_set_);
  1113. return f->type_;
  1114. }
  1115. uint32_t upb_fielddef_index(const upb_fielddef *f) {
  1116. return f->index_;
  1117. }
  1118. upb_label_t upb_fielddef_label(const upb_fielddef *f) {
  1119. return f->label_;
  1120. }
  1121. upb_intfmt_t upb_fielddef_intfmt(const upb_fielddef *f) {
  1122. return f->intfmt;
  1123. }
  1124. bool upb_fielddef_istagdelim(const upb_fielddef *f) {
  1125. return f->tagdelim;
  1126. }
  1127. uint32_t upb_fielddef_number(const upb_fielddef *f) {
  1128. return f->number_;
  1129. }
  1130. bool upb_fielddef_isextension(const upb_fielddef *f) {
  1131. return f->is_extension_;
  1132. }
  1133. bool upb_fielddef_lazy(const upb_fielddef *f) {
  1134. return f->lazy_;
  1135. }
  1136. bool upb_fielddef_packed(const upb_fielddef *f) {
  1137. return f->packed_;
  1138. }
  1139. const char *upb_fielddef_name(const upb_fielddef *f) {
  1140. return upb_def_fullname(upb_fielddef_upcast(f));
  1141. }
  1142. size_t upb_fielddef_getjsonname(const upb_fielddef *f, char *buf, size_t len) {
  1143. const char *name = upb_fielddef_name(f);
  1144. size_t src, dst = 0;
  1145. bool ucase_next = false;
  1146. #define WRITE(byte) \
  1147. ++dst; \
  1148. if (dst < len) buf[dst - 1] = byte; \
  1149. else if (dst == len) buf[dst - 1] = '\0'
  1150. if (!name) {
  1151. WRITE('\0');
  1152. return 0;
  1153. }
  1154. /* Implement the transformation as described in the spec:
  1155. * 1. upper case all letters after an underscore.
  1156. * 2. remove all underscores.
  1157. */
  1158. for (src = 0; name[src]; src++) {
  1159. if (name[src] == '_') {
  1160. ucase_next = true;
  1161. continue;
  1162. }
  1163. if (ucase_next) {
  1164. WRITE(toupper(name[src]));
  1165. ucase_next = false;
  1166. } else {
  1167. WRITE(name[src]);
  1168. }
  1169. }
  1170. WRITE('\0');
  1171. return dst;
  1172. #undef WRITE
  1173. }
  1174. const upb_msgdef *upb_fielddef_containingtype(const upb_fielddef *f) {
  1175. return f->msg_is_symbolic ? NULL : f->msg.def;
  1176. }
  1177. const upb_oneofdef *upb_fielddef_containingoneof(const upb_fielddef *f) {
  1178. return f->oneof;
  1179. }
  1180. upb_msgdef *upb_fielddef_containingtype_mutable(upb_fielddef *f) {
  1181. return (upb_msgdef*)upb_fielddef_containingtype(f);
  1182. }
  1183. const char *upb_fielddef_containingtypename(upb_fielddef *f) {
  1184. return f->msg_is_symbolic ? f->msg.name : NULL;
  1185. }
  1186. static void release_containingtype(upb_fielddef *f) {
  1187. if (f->msg_is_symbolic) upb_gfree(f->msg.name);
  1188. }
  1189. bool upb_fielddef_setcontainingtypename(upb_fielddef *f, const char *name,
  1190. upb_status *s) {
  1191. char *name_copy;
  1192. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  1193. if (upb_fielddef_containingtype(f)) {
  1194. upb_status_seterrmsg(s, "field has already been added to a message.");
  1195. return false;
  1196. }
  1197. /* TODO: validate name (upb_isident() doesn't quite work atm because this name
  1198. * may have a leading "."). */
  1199. name_copy = upb_gstrdup(name);
  1200. if (!name_copy) {
  1201. upb_upberr_setoom(s);
  1202. return false;
  1203. }
  1204. release_containingtype(f);
  1205. f->msg.name = name_copy;
  1206. f->msg_is_symbolic = true;
  1207. return true;
  1208. }
  1209. bool upb_fielddef_setname(upb_fielddef *f, const char *name, upb_status *s) {
  1210. if (upb_fielddef_containingtype(f) || upb_fielddef_containingoneof(f)) {
  1211. upb_status_seterrmsg(s, "Already added to message or oneof");
  1212. return false;
  1213. }
  1214. return upb_def_setfullname(upb_fielddef_upcast_mutable(f), name, s);
  1215. }
  1216. static void chkdefaulttype(const upb_fielddef *f, upb_fieldtype_t type) {
  1217. UPB_UNUSED(f);
  1218. UPB_UNUSED(type);
  1219. UPB_ASSERT(f->type_is_set_ && upb_fielddef_type(f) == type);
  1220. }
  1221. int64_t upb_fielddef_defaultint64(const upb_fielddef *f) {
  1222. chkdefaulttype(f, UPB_TYPE_INT64);
  1223. return f->defaultval.sint;
  1224. }
  1225. int32_t upb_fielddef_defaultint32(const upb_fielddef *f) {
  1226. if (f->type_is_set_ && upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  1227. int32_t val;
  1228. bool ok = enumdefaultint32(f, &val);
  1229. UPB_ASSERT(ok);
  1230. return val;
  1231. } else {
  1232. chkdefaulttype(f, UPB_TYPE_INT32);
  1233. return f->defaultval.sint;
  1234. }
  1235. }
  1236. uint64_t upb_fielddef_defaultuint64(const upb_fielddef *f) {
  1237. chkdefaulttype(f, UPB_TYPE_UINT64);
  1238. return f->defaultval.uint;
  1239. }
  1240. uint32_t upb_fielddef_defaultuint32(const upb_fielddef *f) {
  1241. chkdefaulttype(f, UPB_TYPE_UINT32);
  1242. return f->defaultval.uint;
  1243. }
  1244. bool upb_fielddef_defaultbool(const upb_fielddef *f) {
  1245. chkdefaulttype(f, UPB_TYPE_BOOL);
  1246. return f->defaultval.uint;
  1247. }
  1248. float upb_fielddef_defaultfloat(const upb_fielddef *f) {
  1249. chkdefaulttype(f, UPB_TYPE_FLOAT);
  1250. return f->defaultval.flt;
  1251. }
  1252. double upb_fielddef_defaultdouble(const upb_fielddef *f) {
  1253. chkdefaulttype(f, UPB_TYPE_DOUBLE);
  1254. return f->defaultval.dbl;
  1255. }
  1256. const char *upb_fielddef_defaultstr(const upb_fielddef *f, size_t *len) {
  1257. UPB_ASSERT(f->type_is_set_);
  1258. UPB_ASSERT(upb_fielddef_type(f) == UPB_TYPE_STRING ||
  1259. upb_fielddef_type(f) == UPB_TYPE_BYTES ||
  1260. upb_fielddef_type(f) == UPB_TYPE_ENUM);
  1261. if (upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  1262. const char *ret = enumdefaultstr(f);
  1263. UPB_ASSERT(ret);
  1264. /* Enum defaults can't have embedded NULLs. */
  1265. if (len) *len = strlen(ret);
  1266. return ret;
  1267. }
  1268. if (f->default_is_string) {
  1269. str_t *str = f->defaultval.bytes;
  1270. if (len) *len = str->len;
  1271. return str->str;
  1272. }
  1273. return NULL;
  1274. }
  1275. static void upb_fielddef_init_default(upb_fielddef *f) {
  1276. f->default_is_string = false;
  1277. switch (upb_fielddef_type(f)) {
  1278. case UPB_TYPE_DOUBLE: f->defaultval.dbl = 0; break;
  1279. case UPB_TYPE_FLOAT: f->defaultval.flt = 0; break;
  1280. case UPB_TYPE_INT32:
  1281. case UPB_TYPE_INT64: f->defaultval.sint = 0; break;
  1282. case UPB_TYPE_UINT64:
  1283. case UPB_TYPE_UINT32:
  1284. case UPB_TYPE_BOOL: f->defaultval.uint = 0; break;
  1285. case UPB_TYPE_STRING:
  1286. case UPB_TYPE_BYTES:
  1287. f->defaultval.bytes = newstr("", 0);
  1288. f->default_is_string = true;
  1289. break;
  1290. case UPB_TYPE_MESSAGE: break;
  1291. case UPB_TYPE_ENUM:
  1292. /* This is our special sentinel that indicates "not set" for an enum. */
  1293. f->default_is_string = true;
  1294. f->defaultval.bytes = NULL;
  1295. break;
  1296. }
  1297. }
  1298. const upb_def *upb_fielddef_subdef(const upb_fielddef *f) {
  1299. return f->subdef_is_symbolic ? NULL : f->sub.def;
  1300. }
  1301. const upb_msgdef *upb_fielddef_msgsubdef(const upb_fielddef *f) {
  1302. const upb_def *def = upb_fielddef_subdef(f);
  1303. return def ? upb_dyncast_msgdef(def) : NULL;
  1304. }
  1305. const upb_enumdef *upb_fielddef_enumsubdef(const upb_fielddef *f) {
  1306. const upb_def *def = upb_fielddef_subdef(f);
  1307. return def ? upb_dyncast_enumdef(def) : NULL;
  1308. }
  1309. upb_def *upb_fielddef_subdef_mutable(upb_fielddef *f) {
  1310. return (upb_def*)upb_fielddef_subdef(f);
  1311. }
  1312. const char *upb_fielddef_subdefname(const upb_fielddef *f) {
  1313. if (f->subdef_is_symbolic) {
  1314. return f->sub.name;
  1315. } else if (f->sub.def) {
  1316. return upb_def_fullname(f->sub.def);
  1317. } else {
  1318. return NULL;
  1319. }
  1320. }
  1321. bool upb_fielddef_setnumber(upb_fielddef *f, uint32_t number, upb_status *s) {
  1322. if (upb_fielddef_containingtype(f)) {
  1323. upb_status_seterrmsg(
  1324. s, "cannot change field number after adding to a message");
  1325. return false;
  1326. }
  1327. if (number == 0 || number > UPB_MAX_FIELDNUMBER) {
  1328. upb_status_seterrf(s, "invalid field number (%u)", number);
  1329. return false;
  1330. }
  1331. f->number_ = number;
  1332. return true;
  1333. }
  1334. void upb_fielddef_settype(upb_fielddef *f, upb_fieldtype_t type) {
  1335. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  1336. UPB_ASSERT(upb_fielddef_checktype(type));
  1337. upb_fielddef_uninit_default(f);
  1338. f->type_ = type;
  1339. f->type_is_set_ = true;
  1340. upb_fielddef_init_default(f);
  1341. }
  1342. void upb_fielddef_setdescriptortype(upb_fielddef *f, int type) {
  1343. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  1344. switch (type) {
  1345. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  1346. upb_fielddef_settype(f, UPB_TYPE_DOUBLE);
  1347. break;
  1348. case UPB_DESCRIPTOR_TYPE_FLOAT:
  1349. upb_fielddef_settype(f, UPB_TYPE_FLOAT);
  1350. break;
  1351. case UPB_DESCRIPTOR_TYPE_INT64:
  1352. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  1353. case UPB_DESCRIPTOR_TYPE_SINT64:
  1354. upb_fielddef_settype(f, UPB_TYPE_INT64);
  1355. break;
  1356. case UPB_DESCRIPTOR_TYPE_UINT64:
  1357. case UPB_DESCRIPTOR_TYPE_FIXED64:
  1358. upb_fielddef_settype(f, UPB_TYPE_UINT64);
  1359. break;
  1360. case UPB_DESCRIPTOR_TYPE_INT32:
  1361. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  1362. case UPB_DESCRIPTOR_TYPE_SINT32:
  1363. upb_fielddef_settype(f, UPB_TYPE_INT32);
  1364. break;
  1365. case UPB_DESCRIPTOR_TYPE_UINT32:
  1366. case UPB_DESCRIPTOR_TYPE_FIXED32:
  1367. upb_fielddef_settype(f, UPB_TYPE_UINT32);
  1368. break;
  1369. case UPB_DESCRIPTOR_TYPE_BOOL:
  1370. upb_fielddef_settype(f, UPB_TYPE_BOOL);
  1371. break;
  1372. case UPB_DESCRIPTOR_TYPE_STRING:
  1373. upb_fielddef_settype(f, UPB_TYPE_STRING);
  1374. break;
  1375. case UPB_DESCRIPTOR_TYPE_BYTES:
  1376. upb_fielddef_settype(f, UPB_TYPE_BYTES);
  1377. break;
  1378. case UPB_DESCRIPTOR_TYPE_GROUP:
  1379. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  1380. upb_fielddef_settype(f, UPB_TYPE_MESSAGE);
  1381. break;
  1382. case UPB_DESCRIPTOR_TYPE_ENUM:
  1383. upb_fielddef_settype(f, UPB_TYPE_ENUM);
  1384. break;
  1385. default: UPB_ASSERT(false);
  1386. }
  1387. if (type == UPB_DESCRIPTOR_TYPE_FIXED64 ||
  1388. type == UPB_DESCRIPTOR_TYPE_FIXED32 ||
  1389. type == UPB_DESCRIPTOR_TYPE_SFIXED64 ||
  1390. type == UPB_DESCRIPTOR_TYPE_SFIXED32) {
  1391. upb_fielddef_setintfmt(f, UPB_INTFMT_FIXED);
  1392. } else if (type == UPB_DESCRIPTOR_TYPE_SINT64 ||
  1393. type == UPB_DESCRIPTOR_TYPE_SINT32) {
  1394. upb_fielddef_setintfmt(f, UPB_INTFMT_ZIGZAG);
  1395. } else {
  1396. upb_fielddef_setintfmt(f, UPB_INTFMT_VARIABLE);
  1397. }
  1398. upb_fielddef_settagdelim(f, type == UPB_DESCRIPTOR_TYPE_GROUP);
  1399. }
  1400. upb_descriptortype_t upb_fielddef_descriptortype(const upb_fielddef *f) {
  1401. switch (upb_fielddef_type(f)) {
  1402. case UPB_TYPE_FLOAT: return UPB_DESCRIPTOR_TYPE_FLOAT;
  1403. case UPB_TYPE_DOUBLE: return UPB_DESCRIPTOR_TYPE_DOUBLE;
  1404. case UPB_TYPE_BOOL: return UPB_DESCRIPTOR_TYPE_BOOL;
  1405. case UPB_TYPE_STRING: return UPB_DESCRIPTOR_TYPE_STRING;
  1406. case UPB_TYPE_BYTES: return UPB_DESCRIPTOR_TYPE_BYTES;
  1407. case UPB_TYPE_ENUM: return UPB_DESCRIPTOR_TYPE_ENUM;
  1408. case UPB_TYPE_INT32:
  1409. switch (upb_fielddef_intfmt(f)) {
  1410. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_INT32;
  1411. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_SFIXED32;
  1412. case UPB_INTFMT_ZIGZAG: return UPB_DESCRIPTOR_TYPE_SINT32;
  1413. }
  1414. case UPB_TYPE_INT64:
  1415. switch (upb_fielddef_intfmt(f)) {
  1416. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_INT64;
  1417. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_SFIXED64;
  1418. case UPB_INTFMT_ZIGZAG: return UPB_DESCRIPTOR_TYPE_SINT64;
  1419. }
  1420. case UPB_TYPE_UINT32:
  1421. switch (upb_fielddef_intfmt(f)) {
  1422. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_UINT32;
  1423. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_FIXED32;
  1424. case UPB_INTFMT_ZIGZAG: return -1;
  1425. }
  1426. case UPB_TYPE_UINT64:
  1427. switch (upb_fielddef_intfmt(f)) {
  1428. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_UINT64;
  1429. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_FIXED64;
  1430. case UPB_INTFMT_ZIGZAG: return -1;
  1431. }
  1432. case UPB_TYPE_MESSAGE:
  1433. return upb_fielddef_istagdelim(f) ?
  1434. UPB_DESCRIPTOR_TYPE_GROUP : UPB_DESCRIPTOR_TYPE_MESSAGE;
  1435. }
  1436. return 0;
  1437. }
  1438. void upb_fielddef_setisextension(upb_fielddef *f, bool is_extension) {
  1439. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  1440. f->is_extension_ = is_extension;
  1441. }
  1442. void upb_fielddef_setlazy(upb_fielddef *f, bool lazy) {
  1443. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  1444. f->lazy_ = lazy;
  1445. }
  1446. void upb_fielddef_setpacked(upb_fielddef *f, bool packed) {
  1447. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  1448. f->packed_ = packed;
  1449. }
  1450. void upb_fielddef_setlabel(upb_fielddef *f, upb_label_t label) {
  1451. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  1452. UPB_ASSERT(upb_fielddef_checklabel(label));
  1453. f->label_ = label;
  1454. }
  1455. void upb_fielddef_setintfmt(upb_fielddef *f, upb_intfmt_t fmt) {
  1456. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  1457. UPB_ASSERT(upb_fielddef_checkintfmt(fmt));
  1458. f->intfmt = fmt;
  1459. }
  1460. void upb_fielddef_settagdelim(upb_fielddef *f, bool tag_delim) {
  1461. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  1462. f->tagdelim = tag_delim;
  1463. f->tagdelim = tag_delim;
  1464. }
  1465. static bool checksetdefault(upb_fielddef *f, upb_fieldtype_t type) {
  1466. if (!f->type_is_set_ || upb_fielddef_isfrozen(f) ||
  1467. upb_fielddef_type(f) != type) {
  1468. UPB_ASSERT(false);
  1469. return false;
  1470. }
  1471. if (f->default_is_string) {
  1472. str_t *s = f->defaultval.bytes;
  1473. UPB_ASSERT(s || type == UPB_TYPE_ENUM);
  1474. if (s) freestr(s);
  1475. }
  1476. f->default_is_string = false;
  1477. return true;
  1478. }
  1479. void upb_fielddef_setdefaultint64(upb_fielddef *f, int64_t value) {
  1480. if (checksetdefault(f, UPB_TYPE_INT64))
  1481. f->defaultval.sint = value;
  1482. }
  1483. void upb_fielddef_setdefaultint32(upb_fielddef *f, int32_t value) {
  1484. if ((upb_fielddef_type(f) == UPB_TYPE_ENUM &&
  1485. checksetdefault(f, UPB_TYPE_ENUM)) ||
  1486. checksetdefault(f, UPB_TYPE_INT32)) {
  1487. f->defaultval.sint = value;
  1488. }
  1489. }
  1490. void upb_fielddef_setdefaultuint64(upb_fielddef *f, uint64_t value) {
  1491. if (checksetdefault(f, UPB_TYPE_UINT64))
  1492. f->defaultval.uint = value;
  1493. }
  1494. void upb_fielddef_setdefaultuint32(upb_fielddef *f, uint32_t value) {
  1495. if (checksetdefault(f, UPB_TYPE_UINT32))
  1496. f->defaultval.uint = value;
  1497. }
  1498. void upb_fielddef_setdefaultbool(upb_fielddef *f, bool value) {
  1499. if (checksetdefault(f, UPB_TYPE_BOOL))
  1500. f->defaultval.uint = value;
  1501. }
  1502. void upb_fielddef_setdefaultfloat(upb_fielddef *f, float value) {
  1503. if (checksetdefault(f, UPB_TYPE_FLOAT))
  1504. f->defaultval.flt = value;
  1505. }
  1506. void upb_fielddef_setdefaultdouble(upb_fielddef *f, double value) {
  1507. if (checksetdefault(f, UPB_TYPE_DOUBLE))
  1508. f->defaultval.dbl = value;
  1509. }
  1510. bool upb_fielddef_setdefaultstr(upb_fielddef *f, const void *str, size_t len,
  1511. upb_status *s) {
  1512. str_t *str2;
  1513. UPB_ASSERT(upb_fielddef_isstring(f) || f->type_ == UPB_TYPE_ENUM);
  1514. if (f->type_ == UPB_TYPE_ENUM && !upb_isident(str, len, false, s))
  1515. return false;
  1516. if (f->default_is_string) {
  1517. str_t *s = f->defaultval.bytes;
  1518. UPB_ASSERT(s || f->type_ == UPB_TYPE_ENUM);
  1519. if (s) freestr(s);
  1520. } else {
  1521. UPB_ASSERT(f->type_ == UPB_TYPE_ENUM);
  1522. }
  1523. str2 = newstr(str, len);
  1524. f->defaultval.bytes = str2;
  1525. f->default_is_string = true;
  1526. return true;
  1527. }
  1528. void upb_fielddef_setdefaultcstr(upb_fielddef *f, const char *str,
  1529. upb_status *s) {
  1530. UPB_ASSERT(f->type_is_set_);
  1531. upb_fielddef_setdefaultstr(f, str, str ? strlen(str) : 0, s);
  1532. }
  1533. bool upb_fielddef_enumhasdefaultint32(const upb_fielddef *f) {
  1534. int32_t val;
  1535. UPB_ASSERT(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  1536. return enumdefaultint32(f, &val);
  1537. }
  1538. bool upb_fielddef_enumhasdefaultstr(const upb_fielddef *f) {
  1539. UPB_ASSERT(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  1540. return enumdefaultstr(f) != NULL;
  1541. }
  1542. static bool upb_subdef_typecheck(upb_fielddef *f, const upb_def *subdef,
  1543. upb_status *s) {
  1544. if (f->type_ == UPB_TYPE_MESSAGE) {
  1545. if (upb_dyncast_msgdef(subdef)) return true;
  1546. upb_status_seterrmsg(s, "invalid subdef type for this submessage field");
  1547. return false;
  1548. } else if (f->type_ == UPB_TYPE_ENUM) {
  1549. if (upb_dyncast_enumdef(subdef)) return true;
  1550. upb_status_seterrmsg(s, "invalid subdef type for this enum field");
  1551. return false;
  1552. } else {
  1553. upb_status_seterrmsg(s, "only message and enum fields can have a subdef");
  1554. return false;
  1555. }
  1556. }
  1557. static void release_subdef(upb_fielddef *f) {
  1558. if (f->subdef_is_symbolic) {
  1559. upb_gfree(f->sub.name);
  1560. } else if (f->sub.def) {
  1561. upb_unref2(f->sub.def, f);
  1562. }
  1563. }
  1564. bool upb_fielddef_setsubdef(upb_fielddef *f, const upb_def *subdef,
  1565. upb_status *s) {
  1566. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  1567. UPB_ASSERT(upb_fielddef_hassubdef(f));
  1568. if (subdef && !upb_subdef_typecheck(f, subdef, s)) return false;
  1569. release_subdef(f);
  1570. f->sub.def = subdef;
  1571. f->subdef_is_symbolic = false;
  1572. if (f->sub.def) upb_ref2(f->sub.def, f);
  1573. return true;
  1574. }
  1575. bool upb_fielddef_setmsgsubdef(upb_fielddef *f, const upb_msgdef *subdef,
  1576. upb_status *s) {
  1577. return upb_fielddef_setsubdef(f, upb_msgdef_upcast(subdef), s);
  1578. }
  1579. bool upb_fielddef_setenumsubdef(upb_fielddef *f, const upb_enumdef *subdef,
  1580. upb_status *s) {
  1581. return upb_fielddef_setsubdef(f, upb_enumdef_upcast(subdef), s);
  1582. }
  1583. bool upb_fielddef_setsubdefname(upb_fielddef *f, const char *name,
  1584. upb_status *s) {
  1585. char *name_copy;
  1586. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  1587. if (!upb_fielddef_hassubdef(f)) {
  1588. upb_status_seterrmsg(s, "field type does not accept a subdef");
  1589. return false;
  1590. }
  1591. name_copy = upb_gstrdup(name);
  1592. if (!name_copy) {
  1593. upb_upberr_setoom(s);
  1594. return false;
  1595. }
  1596. /* TODO: validate name (upb_isident() doesn't quite work atm because this name
  1597. * may have a leading "."). */
  1598. release_subdef(f);
  1599. f->sub.name = name_copy;
  1600. f->subdef_is_symbolic = true;
  1601. return true;
  1602. }
  1603. bool upb_fielddef_issubmsg(const upb_fielddef *f) {
  1604. return upb_fielddef_type(f) == UPB_TYPE_MESSAGE;
  1605. }
  1606. bool upb_fielddef_isstring(const upb_fielddef *f) {
  1607. return upb_fielddef_type(f) == UPB_TYPE_STRING ||
  1608. upb_fielddef_type(f) == UPB_TYPE_BYTES;
  1609. }
  1610. bool upb_fielddef_isseq(const upb_fielddef *f) {
  1611. return upb_fielddef_label(f) == UPB_LABEL_REPEATED;
  1612. }
  1613. bool upb_fielddef_isprimitive(const upb_fielddef *f) {
  1614. return !upb_fielddef_isstring(f) && !upb_fielddef_issubmsg(f);
  1615. }
  1616. bool upb_fielddef_ismap(const upb_fielddef *f) {
  1617. return upb_fielddef_isseq(f) && upb_fielddef_issubmsg(f) &&
  1618. upb_msgdef_mapentry(upb_fielddef_msgsubdef(f));
  1619. }
  1620. bool upb_fielddef_haspresence(const upb_fielddef *f) {
  1621. if (upb_fielddef_isseq(f)) return false;
  1622. if (upb_fielddef_issubmsg(f)) return true;
  1623. /* Primitive field: return true unless there is a message that specifies
  1624. * presence should not exist. */
  1625. if (f->msg_is_symbolic || !f->msg.def) return true;
  1626. return f->msg.def->syntax == UPB_SYNTAX_PROTO2;
  1627. }
  1628. bool upb_fielddef_hassubdef(const upb_fielddef *f) {
  1629. return upb_fielddef_issubmsg(f) || upb_fielddef_type(f) == UPB_TYPE_ENUM;
  1630. }
  1631. static bool between(int32_t x, int32_t low, int32_t high) {
  1632. return x >= low && x <= high;
  1633. }
  1634. bool upb_fielddef_checklabel(int32_t label) { return between(label, 1, 3); }
  1635. bool upb_fielddef_checktype(int32_t type) { return between(type, 1, 11); }
  1636. bool upb_fielddef_checkintfmt(int32_t fmt) { return between(fmt, 1, 3); }
  1637. bool upb_fielddef_checkdescriptortype(int32_t type) {
  1638. return between(type, 1, 18);
  1639. }
  1640. /* upb_msgdef *****************************************************************/
  1641. static void visitmsg(const upb_refcounted *r, upb_refcounted_visit *visit,
  1642. void *closure) {
  1643. upb_msg_oneof_iter o;
  1644. const upb_msgdef *m = (const upb_msgdef*)r;
  1645. const upb_def *def = upb_msgdef_upcast(m);
  1646. upb_msg_field_iter i;
  1647. for(upb_msg_field_begin(&i, m);
  1648. !upb_msg_field_done(&i);
  1649. upb_msg_field_next(&i)) {
  1650. upb_fielddef *f = upb_msg_iter_field(&i);
  1651. visit(r, upb_fielddef_upcast2(f), closure);
  1652. }
  1653. for(upb_msg_oneof_begin(&o, m);
  1654. !upb_msg_oneof_done(&o);
  1655. upb_msg_oneof_next(&o)) {
  1656. upb_oneofdef *f = upb_msg_iter_oneof(&o);
  1657. visit(r, upb_oneofdef_upcast(f), closure);
  1658. }
  1659. if (upb_def_file(def)) {
  1660. visit(r, upb_filedef_upcast(upb_def_file(def)), closure);
  1661. }
  1662. }
  1663. static void freemsg(upb_refcounted *r) {
  1664. upb_msgdef *m = (upb_msgdef*)r;
  1665. upb_strtable_uninit(&m->ntof);
  1666. upb_inttable_uninit(&m->itof);
  1667. upb_def_uninit(upb_msgdef_upcast_mutable(m));
  1668. upb_gfree(m);
  1669. }
  1670. const struct upb_refcounted_vtbl upb_msgdef_vtbl = {visitmsg, freemsg};
  1671. upb_msgdef *upb_msgdef_new(const void *owner) {
  1672. upb_msgdef *m = upb_gmalloc(sizeof(*m));
  1673. if (!m) return NULL;
  1674. if (!upb_def_init(upb_msgdef_upcast_mutable(m), UPB_DEF_MSG, &upb_msgdef_vtbl,
  1675. owner)) {
  1676. goto err2;
  1677. }
  1678. if (!upb_inttable_init(&m->itof, UPB_CTYPE_PTR)) goto err2;
  1679. if (!upb_strtable_init(&m->ntof, UPB_CTYPE_PTR)) goto err1;
  1680. m->map_entry = false;
  1681. m->syntax = UPB_SYNTAX_PROTO2;
  1682. return m;
  1683. err1:
  1684. upb_inttable_uninit(&m->itof);
  1685. err2:
  1686. upb_gfree(m);
  1687. return NULL;
  1688. }
  1689. bool upb_msgdef_freeze(upb_msgdef *m, upb_status *status) {
  1690. upb_def *d = upb_msgdef_upcast_mutable(m);
  1691. return upb_def_freeze(&d, 1, status);
  1692. }
  1693. const char *upb_msgdef_fullname(const upb_msgdef *m) {
  1694. return upb_def_fullname(upb_msgdef_upcast(m));
  1695. }
  1696. const char *upb_msgdef_name(const upb_msgdef *m) {
  1697. return upb_def_name(upb_msgdef_upcast(m));
  1698. }
  1699. bool upb_msgdef_setfullname(upb_msgdef *m, const char *fullname,
  1700. upb_status *s) {
  1701. return upb_def_setfullname(upb_msgdef_upcast_mutable(m), fullname, s);
  1702. }
  1703. bool upb_msgdef_setsyntax(upb_msgdef *m, upb_syntax_t syntax) {
  1704. if (syntax != UPB_SYNTAX_PROTO2 && syntax != UPB_SYNTAX_PROTO3) {
  1705. return false;
  1706. }
  1707. m->syntax = syntax;
  1708. return true;
  1709. }
  1710. upb_syntax_t upb_msgdef_syntax(const upb_msgdef *m) {
  1711. return m->syntax;
  1712. }
  1713. /* Helper: check that the field |f| is safe to add to msgdef |m|. Set an error
  1714. * on status |s| and return false if not. */
  1715. static bool check_field_add(const upb_msgdef *m, const upb_fielddef *f,
  1716. upb_status *s) {
  1717. if (upb_fielddef_containingtype(f) != NULL) {
  1718. upb_status_seterrmsg(s, "fielddef already belongs to a message");
  1719. return false;
  1720. } else if (upb_fielddef_name(f) == NULL || upb_fielddef_number(f) == 0) {
  1721. upb_status_seterrmsg(s, "field name or number were not set");
  1722. return false;
  1723. } else if (upb_msgdef_itof(m, upb_fielddef_number(f))) {
  1724. upb_status_seterrmsg(s, "duplicate field number");
  1725. return false;
  1726. } else if (upb_strtable_lookup(&m->ntof, upb_fielddef_name(f), NULL)) {
  1727. upb_status_seterrmsg(s, "name conflicts with existing field or oneof");
  1728. return false;
  1729. }
  1730. return true;
  1731. }
  1732. static void add_field(upb_msgdef *m, upb_fielddef *f, const void *ref_donor) {
  1733. release_containingtype(f);
  1734. f->msg.def = m;
  1735. f->msg_is_symbolic = false;
  1736. upb_inttable_insert(&m->itof, upb_fielddef_number(f), upb_value_ptr(f));
  1737. upb_strtable_insert(&m->ntof, upb_fielddef_name(f), upb_value_ptr(f));
  1738. upb_ref2(f, m);
  1739. upb_ref2(m, f);
  1740. if (ref_donor) upb_fielddef_unref(f, ref_donor);
  1741. }
  1742. bool upb_msgdef_addfield(upb_msgdef *m, upb_fielddef *f, const void *ref_donor,
  1743. upb_status *s) {
  1744. /* TODO: extensions need to have a separate namespace, because proto2 allows a
  1745. * top-level extension (ie. one not in any package) to have the same name as a
  1746. * field from the message.
  1747. *
  1748. * This also implies that there needs to be a separate lookup-by-name method
  1749. * for extensions. It seems desirable for iteration to return both extensions
  1750. * and non-extensions though.
  1751. *
  1752. * We also need to validate that the field number is in an extension range iff
  1753. * it is an extension.
  1754. *
  1755. * This method is idempotent. Check if |f| is already part of this msgdef and
  1756. * return immediately if so. */
  1757. if (upb_fielddef_containingtype(f) == m) {
  1758. if (ref_donor) upb_fielddef_unref(f, ref_donor);
  1759. return true;
  1760. }
  1761. /* Check constraints for all fields before performing any action. */
  1762. if (!check_field_add(m, f, s)) {
  1763. return false;
  1764. } else if (upb_fielddef_containingoneof(f) != NULL) {
  1765. /* Fields in a oneof can only be added by adding the oneof to the msgdef. */
  1766. upb_status_seterrmsg(s, "fielddef is part of a oneof");
  1767. return false;
  1768. }
  1769. /* Constraint checks ok, perform the action. */
  1770. add_field(m, f, ref_donor);
  1771. return true;
  1772. }
  1773. bool upb_msgdef_addoneof(upb_msgdef *m, upb_oneofdef *o, const void *ref_donor,
  1774. upb_status *s) {
  1775. upb_oneof_iter it;
  1776. /* Check various conditions that would prevent this oneof from being added. */
  1777. if (upb_oneofdef_containingtype(o)) {
  1778. upb_status_seterrmsg(s, "oneofdef already belongs to a message");
  1779. return false;
  1780. } else if (upb_oneofdef_name(o) == NULL) {
  1781. upb_status_seterrmsg(s, "oneofdef name was not set");
  1782. return false;
  1783. } else if (upb_strtable_lookup(&m->ntof, upb_oneofdef_name(o), NULL)) {
  1784. upb_status_seterrmsg(s, "name conflicts with existing field or oneof");
  1785. return false;
  1786. }
  1787. /* Check that all of the oneof's fields do not conflict with names or numbers
  1788. * of fields already in the message. */
  1789. for (upb_oneof_begin(&it, o); !upb_oneof_done(&it); upb_oneof_next(&it)) {
  1790. const upb_fielddef *f = upb_oneof_iter_field(&it);
  1791. if (!check_field_add(m, f, s)) {
  1792. return false;
  1793. }
  1794. }
  1795. /* Everything checks out -- commit now. */
  1796. /* Add oneof itself first. */
  1797. o->parent = m;
  1798. upb_strtable_insert(&m->ntof, upb_oneofdef_name(o), upb_value_ptr(o));
  1799. upb_ref2(o, m);
  1800. upb_ref2(m, o);
  1801. /* Add each field of the oneof directly to the msgdef. */
  1802. for (upb_oneof_begin(&it, o); !upb_oneof_done(&it); upb_oneof_next(&it)) {
  1803. upb_fielddef *f = upb_oneof_iter_field(&it);
  1804. add_field(m, f, NULL);
  1805. }
  1806. if (ref_donor) upb_oneofdef_unref(o, ref_donor);
  1807. return true;
  1808. }
  1809. const upb_fielddef *upb_msgdef_itof(const upb_msgdef *m, uint32_t i) {
  1810. upb_value val;
  1811. return upb_inttable_lookup32(&m->itof, i, &val) ?
  1812. upb_value_getptr(val) : NULL;
  1813. }
  1814. const upb_fielddef *upb_msgdef_ntof(const upb_msgdef *m, const char *name,
  1815. size_t len) {
  1816. upb_value val;
  1817. if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
  1818. return NULL;
  1819. }
  1820. return upb_trygetfield(upb_value_getptr(val));
  1821. }
  1822. const upb_oneofdef *upb_msgdef_ntoo(const upb_msgdef *m, const char *name,
  1823. size_t len) {
  1824. upb_value val;
  1825. if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
  1826. return NULL;
  1827. }
  1828. return upb_trygetoneof(upb_value_getptr(val));
  1829. }
  1830. bool upb_msgdef_lookupname(const upb_msgdef *m, const char *name, size_t len,
  1831. const upb_fielddef **f, const upb_oneofdef **o) {
  1832. upb_value val;
  1833. if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
  1834. return false;
  1835. }
  1836. *o = upb_trygetoneof(upb_value_getptr(val));
  1837. *f = upb_trygetfield(upb_value_getptr(val));
  1838. UPB_ASSERT((*o != NULL) ^ (*f != NULL)); /* Exactly one of the two should be set. */
  1839. return true;
  1840. }
  1841. int upb_msgdef_numfields(const upb_msgdef *m) {
  1842. /* The number table contains only fields. */
  1843. return upb_inttable_count(&m->itof);
  1844. }
  1845. int upb_msgdef_numoneofs(const upb_msgdef *m) {
  1846. /* The name table includes oneofs, and the number table does not. */
  1847. return upb_strtable_count(&m->ntof) - upb_inttable_count(&m->itof);
  1848. }
  1849. void upb_msgdef_setmapentry(upb_msgdef *m, bool map_entry) {
  1850. UPB_ASSERT(!upb_msgdef_isfrozen(m));
  1851. m->map_entry = map_entry;
  1852. }
  1853. bool upb_msgdef_mapentry(const upb_msgdef *m) {
  1854. return m->map_entry;
  1855. }
  1856. void upb_msg_field_begin(upb_msg_field_iter *iter, const upb_msgdef *m) {
  1857. upb_inttable_begin(iter, &m->itof);
  1858. }
  1859. void upb_msg_field_next(upb_msg_field_iter *iter) { upb_inttable_next(iter); }
  1860. bool upb_msg_field_done(const upb_msg_field_iter *iter) {
  1861. return upb_inttable_done(iter);
  1862. }
  1863. upb_fielddef *upb_msg_iter_field(const upb_msg_field_iter *iter) {
  1864. return (upb_fielddef*)upb_value_getptr(upb_inttable_iter_value(iter));
  1865. }
  1866. void upb_msg_field_iter_setdone(upb_msg_field_iter *iter) {
  1867. upb_inttable_iter_setdone(iter);
  1868. }
  1869. void upb_msg_oneof_begin(upb_msg_oneof_iter *iter, const upb_msgdef *m) {
  1870. upb_strtable_begin(iter, &m->ntof);
  1871. /* We need to skip past any initial fields. */
  1872. while (!upb_strtable_done(iter) &&
  1873. !upb_isoneof(upb_value_getptr(upb_strtable_iter_value(iter)))) {
  1874. upb_strtable_next(iter);
  1875. }
  1876. }
  1877. void upb_msg_oneof_next(upb_msg_oneof_iter *iter) {
  1878. /* We need to skip past fields to return only oneofs. */
  1879. do {
  1880. upb_strtable_next(iter);
  1881. } while (!upb_strtable_done(iter) &&
  1882. !upb_isoneof(upb_value_getptr(upb_strtable_iter_value(iter))));
  1883. }
  1884. bool upb_msg_oneof_done(const upb_msg_oneof_iter *iter) {
  1885. return upb_strtable_done(iter);
  1886. }
  1887. upb_oneofdef *upb_msg_iter_oneof(const upb_msg_oneof_iter *iter) {
  1888. return (upb_oneofdef*)upb_value_getptr(upb_strtable_iter_value(iter));
  1889. }
  1890. void upb_msg_oneof_iter_setdone(upb_msg_oneof_iter *iter) {
  1891. upb_strtable_iter_setdone(iter);
  1892. }
  1893. /* upb_oneofdef ***************************************************************/
  1894. static void visitoneof(const upb_refcounted *r, upb_refcounted_visit *visit,
  1895. void *closure) {
  1896. const upb_oneofdef *o = (const upb_oneofdef*)r;
  1897. upb_oneof_iter i;
  1898. for (upb_oneof_begin(&i, o); !upb_oneof_done(&i); upb_oneof_next(&i)) {
  1899. const upb_fielddef *f = upb_oneof_iter_field(&i);
  1900. visit(r, upb_fielddef_upcast2(f), closure);
  1901. }
  1902. if (o->parent) {
  1903. visit(r, upb_msgdef_upcast2(o->parent), closure);
  1904. }
  1905. }
  1906. static void freeoneof(upb_refcounted *r) {
  1907. upb_oneofdef *o = (upb_oneofdef*)r;
  1908. upb_strtable_uninit(&o->ntof);
  1909. upb_inttable_uninit(&o->itof);
  1910. upb_gfree((void*)o->name);
  1911. upb_gfree(o);
  1912. }
  1913. const struct upb_refcounted_vtbl upb_oneofdef_vtbl = {visitoneof, freeoneof};
  1914. upb_oneofdef *upb_oneofdef_new(const void *owner) {
  1915. upb_oneofdef *o = upb_gmalloc(sizeof(*o));
  1916. if (!o) {
  1917. return NULL;
  1918. }
  1919. o->parent = NULL;
  1920. o->name = NULL;
  1921. if (!upb_refcounted_init(upb_oneofdef_upcast_mutable(o), &upb_oneofdef_vtbl,
  1922. owner)) {
  1923. goto err2;
  1924. }
  1925. if (!upb_inttable_init(&o->itof, UPB_CTYPE_PTR)) goto err2;
  1926. if (!upb_strtable_init(&o->ntof, UPB_CTYPE_PTR)) goto err1;
  1927. return o;
  1928. err1:
  1929. upb_inttable_uninit(&o->itof);
  1930. err2:
  1931. upb_gfree(o);
  1932. return NULL;
  1933. }
  1934. const char *upb_oneofdef_name(const upb_oneofdef *o) { return o->name; }
  1935. bool upb_oneofdef_setname(upb_oneofdef *o, const char *name, upb_status *s) {
  1936. UPB_ASSERT(!upb_oneofdef_isfrozen(o));
  1937. if (upb_oneofdef_containingtype(o)) {
  1938. upb_status_seterrmsg(s, "oneof already added to a message");
  1939. return false;
  1940. }
  1941. if (!upb_isident(name, strlen(name), true, s)) {
  1942. return false;
  1943. }
  1944. name = upb_gstrdup(name);
  1945. if (!name) {
  1946. upb_status_seterrmsg(s, "One of memory");
  1947. return false;
  1948. }
  1949. upb_gfree((void*)o->name);
  1950. o->name = name;
  1951. return true;
  1952. }
  1953. const upb_msgdef *upb_oneofdef_containingtype(const upb_oneofdef *o) {
  1954. return o->parent;
  1955. }
  1956. int upb_oneofdef_numfields(const upb_oneofdef *o) {
  1957. return upb_strtable_count(&o->ntof);
  1958. }
  1959. uint32_t upb_oneofdef_index(const upb_oneofdef *o) {
  1960. return o->index;
  1961. }
  1962. bool upb_oneofdef_addfield(upb_oneofdef *o, upb_fielddef *f,
  1963. const void *ref_donor,
  1964. upb_status *s) {
  1965. UPB_ASSERT(!upb_oneofdef_isfrozen(o));
  1966. UPB_ASSERT(!o->parent || !upb_msgdef_isfrozen(o->parent));
  1967. /* This method is idempotent. Check if |f| is already part of this oneofdef
  1968. * and return immediately if so. */
  1969. if (upb_fielddef_containingoneof(f) == o) {
  1970. return true;
  1971. }
  1972. /* The field must have an OPTIONAL label. */
  1973. if (upb_fielddef_label(f) != UPB_LABEL_OPTIONAL) {
  1974. upb_status_seterrmsg(s, "fields in oneof must have OPTIONAL label");
  1975. return false;
  1976. }
  1977. /* Check that no field with this name or number exists already in the oneof.
  1978. * Also check that the field is not already part of a oneof. */
  1979. if (upb_fielddef_name(f) == NULL || upb_fielddef_number(f) == 0) {
  1980. upb_status_seterrmsg(s, "field name or number were not set");
  1981. return false;
  1982. } else if (upb_oneofdef_itof(o, upb_fielddef_number(f)) ||
  1983. upb_oneofdef_ntofz(o, upb_fielddef_name(f))) {
  1984. upb_status_seterrmsg(s, "duplicate field name or number");
  1985. return false;
  1986. } else if (upb_fielddef_containingoneof(f) != NULL) {
  1987. upb_status_seterrmsg(s, "fielddef already belongs to a oneof");
  1988. return false;
  1989. }
  1990. /* We allow adding a field to the oneof either if the field is not part of a
  1991. * msgdef, or if it is and we are also part of the same msgdef. */
  1992. if (o->parent == NULL) {
  1993. /* If we're not in a msgdef, the field cannot be either. Otherwise we would
  1994. * need to magically add this oneof to a msgdef to remain consistent, which
  1995. * is surprising behavior. */
  1996. if (upb_fielddef_containingtype(f) != NULL) {
  1997. upb_status_seterrmsg(s, "fielddef already belongs to a message, but "
  1998. "oneof does not");
  1999. return false;
  2000. }
  2001. } else {
  2002. /* If we're in a msgdef, the user can add fields that either aren't in any
  2003. * msgdef (in which case they're added to our msgdef) or already a part of
  2004. * our msgdef. */
  2005. if (upb_fielddef_containingtype(f) != NULL &&
  2006. upb_fielddef_containingtype(f) != o->parent) {
  2007. upb_status_seterrmsg(s, "fielddef belongs to a different message "
  2008. "than oneof");
  2009. return false;
  2010. }
  2011. }
  2012. /* Commit phase. First add the field to our parent msgdef, if any, because
  2013. * that may fail; then add the field to our own tables. */
  2014. if (o->parent != NULL && upb_fielddef_containingtype(f) == NULL) {
  2015. if (!upb_msgdef_addfield((upb_msgdef*)o->parent, f, NULL, s)) {
  2016. return false;
  2017. }
  2018. }
  2019. release_containingtype(f);
  2020. f->oneof = o;
  2021. upb_inttable_insert(&o->itof, upb_fielddef_number(f), upb_value_ptr(f));
  2022. upb_strtable_insert(&o->ntof, upb_fielddef_name(f), upb_value_ptr(f));
  2023. upb_ref2(f, o);
  2024. upb_ref2(o, f);
  2025. if (ref_donor) upb_fielddef_unref(f, ref_donor);
  2026. return true;
  2027. }
  2028. const upb_fielddef *upb_oneofdef_ntof(const upb_oneofdef *o,
  2029. const char *name, size_t length) {
  2030. upb_value val;
  2031. return upb_strtable_lookup2(&o->ntof, name, length, &val) ?
  2032. upb_value_getptr(val) : NULL;
  2033. }
  2034. const upb_fielddef *upb_oneofdef_itof(const upb_oneofdef *o, uint32_t num) {
  2035. upb_value val;
  2036. return upb_inttable_lookup32(&o->itof, num, &val) ?
  2037. upb_value_getptr(val) : NULL;
  2038. }
  2039. void upb_oneof_begin(upb_oneof_iter *iter, const upb_oneofdef *o) {
  2040. upb_inttable_begin(iter, &o->itof);
  2041. }
  2042. void upb_oneof_next(upb_oneof_iter *iter) {
  2043. upb_inttable_next(iter);
  2044. }
  2045. bool upb_oneof_done(upb_oneof_iter *iter) {
  2046. return upb_inttable_done(iter);
  2047. }
  2048. upb_fielddef *upb_oneof_iter_field(const upb_oneof_iter *iter) {
  2049. return (upb_fielddef*)upb_value_getptr(upb_inttable_iter_value(iter));
  2050. }
  2051. void upb_oneof_iter_setdone(upb_oneof_iter *iter) {
  2052. upb_inttable_iter_setdone(iter);
  2053. }
  2054. /* upb_filedef ****************************************************************/
  2055. static void visitfiledef(const upb_refcounted *r, upb_refcounted_visit *visit,
  2056. void *closure) {
  2057. const upb_filedef *f = (const upb_filedef*)r;
  2058. size_t i;
  2059. for(i = 0; i < upb_filedef_defcount(f); i++) {
  2060. visit(r, upb_def_upcast(upb_filedef_def(f, i)), closure);
  2061. }
  2062. }
  2063. static void freefiledef(upb_refcounted *r) {
  2064. upb_filedef *f = (upb_filedef*)r;
  2065. size_t i;
  2066. for(i = 0; i < upb_filedef_depcount(f); i++) {
  2067. upb_filedef_unref(upb_filedef_dep(f, i), f);
  2068. }
  2069. upb_inttable_uninit(&f->defs);
  2070. upb_inttable_uninit(&f->deps);
  2071. upb_gfree((void*)f->name);
  2072. upb_gfree((void*)f->package);
  2073. upb_gfree((void*)f->phpprefix);
  2074. upb_gfree((void*)f->phpnamespace);
  2075. upb_gfree(f);
  2076. }
  2077. const struct upb_refcounted_vtbl upb_filedef_vtbl = {visitfiledef, freefiledef};
  2078. upb_filedef *upb_filedef_new(const void *owner) {
  2079. upb_filedef *f = upb_gmalloc(sizeof(*f));
  2080. if (!f) {
  2081. return NULL;
  2082. }
  2083. f->package = NULL;
  2084. f->name = NULL;
  2085. f->phpprefix = NULL;
  2086. f->phpnamespace = NULL;
  2087. f->syntax = UPB_SYNTAX_PROTO2;
  2088. if (!upb_refcounted_init(upb_filedef_upcast_mutable(f), &upb_filedef_vtbl,
  2089. owner)) {
  2090. goto err;
  2091. }
  2092. if (!upb_inttable_init(&f->defs, UPB_CTYPE_CONSTPTR)) {
  2093. goto err;
  2094. }
  2095. if (!upb_inttable_init(&f->deps, UPB_CTYPE_CONSTPTR)) {
  2096. goto err2;
  2097. }
  2098. return f;
  2099. err2:
  2100. upb_inttable_uninit(&f->defs);
  2101. err:
  2102. upb_gfree(f);
  2103. return NULL;
  2104. }
  2105. const char *upb_filedef_name(const upb_filedef *f) {
  2106. return f->name;
  2107. }
  2108. const char *upb_filedef_package(const upb_filedef *f) {
  2109. return f->package;
  2110. }
  2111. const char *upb_filedef_phpprefix(const upb_filedef *f) {
  2112. return f->phpprefix;
  2113. }
  2114. const char *upb_filedef_phpnamespace(const upb_filedef *f) {
  2115. return f->phpnamespace;
  2116. }
  2117. upb_syntax_t upb_filedef_syntax(const upb_filedef *f) {
  2118. return f->syntax;
  2119. }
  2120. size_t upb_filedef_defcount(const upb_filedef *f) {
  2121. return upb_inttable_count(&f->defs);
  2122. }
  2123. size_t upb_filedef_depcount(const upb_filedef *f) {
  2124. return upb_inttable_count(&f->deps);
  2125. }
  2126. const upb_def *upb_filedef_def(const upb_filedef *f, size_t i) {
  2127. upb_value v;
  2128. if (upb_inttable_lookup32(&f->defs, i, &v)) {
  2129. return upb_value_getconstptr(v);
  2130. } else {
  2131. return NULL;
  2132. }
  2133. }
  2134. const upb_filedef *upb_filedef_dep(const upb_filedef *f, size_t i) {
  2135. upb_value v;
  2136. if (upb_inttable_lookup32(&f->deps, i, &v)) {
  2137. return upb_value_getconstptr(v);
  2138. } else {
  2139. return NULL;
  2140. }
  2141. }
  2142. bool upb_filedef_setname(upb_filedef *f, const char *name, upb_status *s) {
  2143. name = upb_gstrdup(name);
  2144. if (!name) {
  2145. upb_upberr_setoom(s);
  2146. return false;
  2147. }
  2148. upb_gfree((void*)f->name);
  2149. f->name = name;
  2150. return true;
  2151. }
  2152. bool upb_filedef_setpackage(upb_filedef *f, const char *package,
  2153. upb_status *s) {
  2154. if (!upb_isident(package, strlen(package), true, s)) return false;
  2155. package = upb_gstrdup(package);
  2156. if (!package) {
  2157. upb_upberr_setoom(s);
  2158. return false;
  2159. }
  2160. upb_gfree((void*)f->package);
  2161. f->package = package;
  2162. return true;
  2163. }
  2164. bool upb_filedef_setphpprefix(upb_filedef *f, const char *phpprefix,
  2165. upb_status *s) {
  2166. phpprefix = upb_gstrdup(phpprefix);
  2167. if (!phpprefix) {
  2168. upb_upberr_setoom(s);
  2169. return false;
  2170. }
  2171. upb_gfree((void*)f->phpprefix);
  2172. f->phpprefix = phpprefix;
  2173. return true;
  2174. }
  2175. bool upb_filedef_setphpnamespace(upb_filedef *f, const char *phpnamespace,
  2176. upb_status *s) {
  2177. phpnamespace = upb_gstrdup(phpnamespace);
  2178. if (!phpnamespace) {
  2179. upb_upberr_setoom(s);
  2180. return false;
  2181. }
  2182. upb_gfree((void*)f->phpnamespace);
  2183. f->phpnamespace = phpnamespace;
  2184. return true;
  2185. }
  2186. bool upb_filedef_setsyntax(upb_filedef *f, upb_syntax_t syntax,
  2187. upb_status *s) {
  2188. UPB_UNUSED(s);
  2189. if (syntax != UPB_SYNTAX_PROTO2 &&
  2190. syntax != UPB_SYNTAX_PROTO3) {
  2191. upb_status_seterrmsg(s, "Unknown syntax value.");
  2192. return false;
  2193. }
  2194. f->syntax = syntax;
  2195. {
  2196. /* Set all messages in this file to match. */
  2197. size_t i;
  2198. for (i = 0; i < upb_filedef_defcount(f); i++) {
  2199. /* Casting const away is safe since all defs in mutable filedef must
  2200. * also be mutable. */
  2201. upb_def *def = (upb_def*)upb_filedef_def(f, i);
  2202. upb_msgdef *m = upb_dyncast_msgdef_mutable(def);
  2203. if (m) {
  2204. m->syntax = syntax;
  2205. }
  2206. }
  2207. }
  2208. return true;
  2209. }
  2210. bool upb_filedef_adddef(upb_filedef *f, upb_def *def, const void *ref_donor,
  2211. upb_status *s) {
  2212. if (def->file) {
  2213. upb_status_seterrmsg(s, "Def is already part of another filedef.");
  2214. return false;
  2215. }
  2216. if (upb_inttable_push(&f->defs, upb_value_constptr(def))) {
  2217. def->file = f;
  2218. upb_ref2(def, f);
  2219. upb_ref2(f, def);
  2220. if (ref_donor) upb_def_unref(def, ref_donor);
  2221. if (def->type == UPB_DEF_MSG) {
  2222. upb_downcast_msgdef_mutable(def)->syntax = f->syntax;
  2223. }
  2224. return true;
  2225. } else {
  2226. upb_upberr_setoom(s);
  2227. return false;
  2228. }
  2229. }
  2230. bool upb_filedef_adddep(upb_filedef *f, const upb_filedef *dep) {
  2231. if (upb_inttable_push(&f->deps, upb_value_constptr(dep))) {
  2232. /* Regular ref instead of ref2 because files can't form cycles. */
  2233. upb_filedef_ref(dep, f);
  2234. return true;
  2235. } else {
  2236. return false;
  2237. }
  2238. }
  2239. void upb_symtab_free(upb_symtab *s) {
  2240. upb_strtable_iter i;
  2241. upb_strtable_begin(&i, &s->symtab);
  2242. for (; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  2243. const upb_def *def = upb_value_getptr(upb_strtable_iter_value(&i));
  2244. upb_def_unref(def, s);
  2245. }
  2246. upb_strtable_uninit(&s->symtab);
  2247. upb_gfree(s);
  2248. }
  2249. upb_symtab *upb_symtab_new() {
  2250. upb_symtab *s = upb_gmalloc(sizeof(*s));
  2251. if (!s) {
  2252. return NULL;
  2253. }
  2254. upb_strtable_init(&s->symtab, UPB_CTYPE_PTR);
  2255. return s;
  2256. }
  2257. const upb_def *upb_symtab_lookup(const upb_symtab *s, const char *sym) {
  2258. upb_value v;
  2259. upb_def *ret = upb_strtable_lookup(&s->symtab, sym, &v) ?
  2260. upb_value_getptr(v) : NULL;
  2261. return ret;
  2262. }
  2263. const upb_msgdef *upb_symtab_lookupmsg(const upb_symtab *s, const char *sym) {
  2264. upb_value v;
  2265. upb_def *def = upb_strtable_lookup(&s->symtab, sym, &v) ?
  2266. upb_value_getptr(v) : NULL;
  2267. return def ? upb_dyncast_msgdef(def) : NULL;
  2268. }
  2269. const upb_enumdef *upb_symtab_lookupenum(const upb_symtab *s, const char *sym) {
  2270. upb_value v;
  2271. upb_def *def = upb_strtable_lookup(&s->symtab, sym, &v) ?
  2272. upb_value_getptr(v) : NULL;
  2273. return def ? upb_dyncast_enumdef(def) : NULL;
  2274. }
  2275. /* Given a symbol and the base symbol inside which it is defined, find the
  2276. * symbol's definition in t. */
  2277. static upb_def *upb_resolvename(const upb_strtable *t,
  2278. const char *base, const char *sym) {
  2279. if(strlen(sym) == 0) return NULL;
  2280. if(sym[0] == '.') {
  2281. /* Symbols starting with '.' are absolute, so we do a single lookup.
  2282. * Slice to omit the leading '.' */
  2283. upb_value v;
  2284. return upb_strtable_lookup(t, sym + 1, &v) ? upb_value_getptr(v) : NULL;
  2285. } else {
  2286. /* Remove components from base until we find an entry or run out.
  2287. * TODO: This branch is totally broken, but currently not used. */
  2288. (void)base;
  2289. UPB_ASSERT(false);
  2290. return NULL;
  2291. }
  2292. }
  2293. const upb_def *upb_symtab_resolve(const upb_symtab *s, const char *base,
  2294. const char *sym) {
  2295. upb_def *ret = upb_resolvename(&s->symtab, base, sym);
  2296. return ret;
  2297. }
  2298. /* TODO(haberman): we need a lot more testing of error conditions. */
  2299. static bool symtab_add(upb_symtab *s, upb_def *const*defs, size_t n,
  2300. void *ref_donor, upb_refcounted *freeze_also,
  2301. upb_status *status) {
  2302. size_t i;
  2303. size_t add_n;
  2304. size_t freeze_n;
  2305. upb_strtable_iter iter;
  2306. upb_refcounted **add_objs = NULL;
  2307. upb_def **add_defs = NULL;
  2308. size_t add_objs_size;
  2309. upb_strtable addtab;
  2310. if (n == 0 && !freeze_also) {
  2311. return true;
  2312. }
  2313. if (!upb_strtable_init(&addtab, UPB_CTYPE_PTR)) {
  2314. upb_status_seterrmsg(status, "out of memory");
  2315. return false;
  2316. }
  2317. /* Add new defs to our "add" set. */
  2318. for (i = 0; i < n; i++) {
  2319. upb_def *def = defs[i];
  2320. const char *fullname;
  2321. upb_fielddef *f;
  2322. if (upb_def_isfrozen(def)) {
  2323. upb_status_seterrmsg(status, "added defs must be mutable");
  2324. goto err;
  2325. }
  2326. UPB_ASSERT(!upb_def_isfrozen(def));
  2327. fullname = upb_def_fullname(def);
  2328. if (!fullname) {
  2329. upb_status_seterrmsg(
  2330. status, "Anonymous defs cannot be added to a symtab");
  2331. goto err;
  2332. }
  2333. f = upb_dyncast_fielddef_mutable(def);
  2334. if (f) {
  2335. if (!upb_fielddef_containingtypename(f)) {
  2336. upb_status_seterrmsg(status,
  2337. "Standalone fielddefs must have a containing type "
  2338. "(extendee) name set");
  2339. goto err;
  2340. }
  2341. } else {
  2342. if (upb_strtable_lookup(&addtab, fullname, NULL)) {
  2343. upb_status_seterrf(status, "Conflicting defs named '%s'", fullname);
  2344. goto err;
  2345. }
  2346. if (upb_strtable_lookup(&s->symtab, fullname, NULL)) {
  2347. upb_status_seterrf(status, "Symtab already has a def named '%s'",
  2348. fullname);
  2349. goto err;
  2350. }
  2351. if (!upb_strtable_insert(&addtab, fullname, upb_value_ptr(def)))
  2352. goto oom_err;
  2353. upb_def_donateref(def, ref_donor, s);
  2354. }
  2355. if (upb_dyncast_fielddef_mutable(def)) {
  2356. /* TODO(haberman): allow adding extensions attached to files. */
  2357. upb_status_seterrf(status, "Can't add extensions to symtab.\n");
  2358. goto err;
  2359. }
  2360. }
  2361. /* Now using the table, resolve symbolic references for subdefs. */
  2362. upb_strtable_begin(&iter, &addtab);
  2363. for (; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
  2364. const char *base;
  2365. upb_def *def = upb_value_getptr(upb_strtable_iter_value(&iter));
  2366. upb_msgdef *m = upb_dyncast_msgdef_mutable(def);
  2367. upb_msg_field_iter j;
  2368. if (!m) continue;
  2369. /* Type names are resolved relative to the message in which they appear. */
  2370. base = upb_msgdef_fullname(m);
  2371. for(upb_msg_field_begin(&j, m);
  2372. !upb_msg_field_done(&j);
  2373. upb_msg_field_next(&j)) {
  2374. upb_fielddef *f = upb_msg_iter_field(&j);
  2375. const char *name = upb_fielddef_subdefname(f);
  2376. if (name && !upb_fielddef_subdef(f)) {
  2377. /* Try the lookup in the current set of to-be-added defs first. If not
  2378. * there, try existing defs. */
  2379. upb_def *subdef = upb_resolvename(&addtab, base, name);
  2380. if (subdef == NULL) {
  2381. subdef = upb_resolvename(&s->symtab, base, name);
  2382. }
  2383. if (subdef == NULL) {
  2384. upb_status_seterrf(
  2385. status, "couldn't resolve name '%s' in message '%s'", name, base);
  2386. goto err;
  2387. } else if (!upb_fielddef_setsubdef(f, subdef, status)) {
  2388. goto err;
  2389. }
  2390. }
  2391. }
  2392. }
  2393. /* We need an array of the defs in addtab, for passing to
  2394. * upb_refcounted_freeze(). */
  2395. add_objs_size = upb_strtable_count(&addtab);
  2396. if (freeze_also) {
  2397. add_objs_size++;
  2398. }
  2399. add_defs = upb_gmalloc(sizeof(void*) * add_objs_size);
  2400. if (add_defs == NULL) goto oom_err;
  2401. upb_strtable_begin(&iter, &addtab);
  2402. for (add_n = 0; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
  2403. add_defs[add_n++] = upb_value_getptr(upb_strtable_iter_value(&iter));
  2404. }
  2405. /* Validate defs. */
  2406. if (!_upb_def_validate(add_defs, add_n, status)) {
  2407. goto err;
  2408. }
  2409. /* Cheat a little and give the array a new type.
  2410. * This is probably undefined behavior, but this code will be deleted soon. */
  2411. add_objs = (upb_refcounted**)add_defs;
  2412. freeze_n = add_n;
  2413. if (freeze_also) {
  2414. add_objs[freeze_n++] = freeze_also;
  2415. }
  2416. if (!upb_refcounted_freeze(add_objs, freeze_n, status,
  2417. UPB_MAX_MESSAGE_DEPTH * 2)) {
  2418. goto err;
  2419. }
  2420. /* This must be delayed until all errors have been detected, since error
  2421. * recovery code uses this table to cleanup defs. */
  2422. upb_strtable_uninit(&addtab);
  2423. /* TODO(haberman) we don't properly handle errors after this point (like
  2424. * OOM in upb_strtable_insert() below). */
  2425. for (i = 0; i < add_n; i++) {
  2426. upb_def *def = (upb_def*)add_objs[i];
  2427. const char *name = upb_def_fullname(def);
  2428. bool success;
  2429. success = upb_strtable_insert(&s->symtab, name, upb_value_ptr(def));
  2430. UPB_ASSERT(success);
  2431. }
  2432. upb_gfree(add_defs);
  2433. return true;
  2434. oom_err:
  2435. upb_status_seterrmsg(status, "out of memory");
  2436. err: {
  2437. /* We need to donate the refs back. */
  2438. upb_strtable_begin(&iter, &addtab);
  2439. for (; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
  2440. upb_def *def = upb_value_getptr(upb_strtable_iter_value(&iter));
  2441. upb_def_donateref(def, s, ref_donor);
  2442. }
  2443. }
  2444. upb_strtable_uninit(&addtab);
  2445. upb_gfree(add_defs);
  2446. UPB_ASSERT(!upb_ok(status));
  2447. return false;
  2448. }
  2449. bool upb_symtab_add(upb_symtab *s, upb_def *const*defs, size_t n,
  2450. void *ref_donor, upb_status *status) {
  2451. return symtab_add(s, defs, n, ref_donor, NULL, status);
  2452. }
  2453. bool upb_symtab_addfile(upb_symtab *s, upb_filedef *file, upb_status *status) {
  2454. size_t n;
  2455. size_t i;
  2456. upb_def **defs;
  2457. bool ret;
  2458. n = upb_filedef_defcount(file);
  2459. if (n == 0) {
  2460. return true;
  2461. }
  2462. defs = upb_gmalloc(sizeof(*defs) * n);
  2463. if (defs == NULL) {
  2464. upb_status_seterrmsg(status, "Out of memory");
  2465. return false;
  2466. }
  2467. for (i = 0; i < n; i++) {
  2468. defs[i] = upb_filedef_mutabledef(file, i);
  2469. }
  2470. ret = symtab_add(s, defs, n, NULL, upb_filedef_upcast_mutable(file), status);
  2471. upb_gfree(defs);
  2472. return ret;
  2473. }
  2474. /* Iteration. */
  2475. static void advance_to_matching(upb_symtab_iter *iter) {
  2476. if (iter->type == UPB_DEF_ANY)
  2477. return;
  2478. while (!upb_strtable_done(&iter->iter) &&
  2479. iter->type != upb_symtab_iter_def(iter)->type) {
  2480. upb_strtable_next(&iter->iter);
  2481. }
  2482. }
  2483. void upb_symtab_begin(upb_symtab_iter *iter, const upb_symtab *s,
  2484. upb_deftype_t type) {
  2485. upb_strtable_begin(&iter->iter, &s->symtab);
  2486. iter->type = type;
  2487. advance_to_matching(iter);
  2488. }
  2489. void upb_symtab_next(upb_symtab_iter *iter) {
  2490. upb_strtable_next(&iter->iter);
  2491. advance_to_matching(iter);
  2492. }
  2493. bool upb_symtab_done(const upb_symtab_iter *iter) {
  2494. return upb_strtable_done(&iter->iter);
  2495. }
  2496. const upb_def *upb_symtab_iter_def(const upb_symtab_iter *iter) {
  2497. return upb_value_getptr(upb_strtable_iter_value(&iter->iter));
  2498. }
  2499. /* We encode backwards, to avoid pre-computing lengths (one-pass encode). */
  2500. #define UPB_PB_VARINT_MAX_LEN 10
  2501. #define CHK(x) do { if (!(x)) { return false; } } while(0)
  2502. /* Maps descriptor type -> upb field type. */
  2503. static const uint8_t upb_desctype_to_fieldtype2[] = {
  2504. UPB_WIRE_TYPE_END_GROUP, /* ENDGROUP */
  2505. UPB_TYPE_DOUBLE, /* DOUBLE */
  2506. UPB_TYPE_FLOAT, /* FLOAT */
  2507. UPB_TYPE_INT64, /* INT64 */
  2508. UPB_TYPE_UINT64, /* UINT64 */
  2509. UPB_TYPE_INT32, /* INT32 */
  2510. UPB_TYPE_UINT64, /* FIXED64 */
  2511. UPB_TYPE_UINT32, /* FIXED32 */
  2512. UPB_TYPE_BOOL, /* BOOL */
  2513. UPB_TYPE_STRING, /* STRING */
  2514. UPB_TYPE_MESSAGE, /* GROUP */
  2515. UPB_TYPE_MESSAGE, /* MESSAGE */
  2516. UPB_TYPE_BYTES, /* BYTES */
  2517. UPB_TYPE_UINT32, /* UINT32 */
  2518. UPB_TYPE_ENUM, /* ENUM */
  2519. UPB_TYPE_INT32, /* SFIXED32 */
  2520. UPB_TYPE_INT64, /* SFIXED64 */
  2521. UPB_TYPE_INT32, /* SINT32 */
  2522. UPB_TYPE_INT64, /* SINT64 */
  2523. };
  2524. static size_t upb_encode_varint(uint64_t val, char *buf) {
  2525. size_t i;
  2526. if (val < 128) { buf[0] = val; return 1; }
  2527. i = 0;
  2528. while (val) {
  2529. uint8_t byte = val & 0x7fU;
  2530. val >>= 7;
  2531. if (val) byte |= 0x80U;
  2532. buf[i++] = byte;
  2533. }
  2534. return i;
  2535. }
  2536. static uint32_t upb_zzencode_32(int32_t n) { return (n << 1) ^ (n >> 31); }
  2537. static uint64_t upb_zzencode_64(int64_t n) { return (n << 1) ^ (n >> 63); }
  2538. typedef struct {
  2539. upb_env *env;
  2540. char *buf, *ptr, *limit;
  2541. } upb_encstate;
  2542. static size_t upb_roundup_pow2(size_t bytes) {
  2543. size_t ret = 128;
  2544. while (ret < bytes) {
  2545. ret *= 2;
  2546. }
  2547. return ret;
  2548. }
  2549. static bool upb_encode_growbuffer(upb_encstate *e, size_t bytes) {
  2550. size_t old_size = e->limit - e->buf;
  2551. size_t new_size = upb_roundup_pow2(bytes + (e->limit - e->ptr));
  2552. char *new_buf = upb_env_realloc(e->env, e->buf, old_size, new_size);
  2553. CHK(new_buf);
  2554. /* We want previous data at the end, realloc() put it at the beginning. */
  2555. memmove(e->limit - old_size, e->buf, old_size);
  2556. e->ptr = new_buf + new_size - (e->limit - e->ptr);
  2557. e->limit = new_buf + new_size;
  2558. e->buf = new_buf;
  2559. return true;
  2560. }
  2561. /* Call to ensure that at least "bytes" bytes are available for writing at
  2562. * e->ptr. Returns false if the bytes could not be allocated. */
  2563. static bool upb_encode_reserve(upb_encstate *e, size_t bytes) {
  2564. CHK(UPB_LIKELY((size_t)(e->ptr - e->buf) >= bytes) ||
  2565. upb_encode_growbuffer(e, bytes));
  2566. e->ptr -= bytes;
  2567. return true;
  2568. }
  2569. /* Writes the given bytes to the buffer, handling reserve/advance. */
  2570. static bool upb_put_bytes(upb_encstate *e, const void *data, size_t len) {
  2571. CHK(upb_encode_reserve(e, len));
  2572. memcpy(e->ptr, data, len);
  2573. return true;
  2574. }
  2575. static bool upb_put_fixed64(upb_encstate *e, uint64_t val) {
  2576. /* TODO(haberman): byte-swap for big endian. */
  2577. return upb_put_bytes(e, &val, sizeof(uint64_t));
  2578. }
  2579. static bool upb_put_fixed32(upb_encstate *e, uint32_t val) {
  2580. /* TODO(haberman): byte-swap for big endian. */
  2581. return upb_put_bytes(e, &val, sizeof(uint32_t));
  2582. }
  2583. static bool upb_put_varint(upb_encstate *e, uint64_t val) {
  2584. size_t len;
  2585. char *start;
  2586. CHK(upb_encode_reserve(e, UPB_PB_VARINT_MAX_LEN));
  2587. len = upb_encode_varint(val, e->ptr);
  2588. start = e->ptr + UPB_PB_VARINT_MAX_LEN - len;
  2589. memmove(start, e->ptr, len);
  2590. e->ptr = start;
  2591. return true;
  2592. }
  2593. static bool upb_put_double(upb_encstate *e, double d) {
  2594. uint64_t u64;
  2595. UPB_ASSERT(sizeof(double) == sizeof(uint64_t));
  2596. memcpy(&u64, &d, sizeof(uint64_t));
  2597. return upb_put_fixed64(e, u64);
  2598. }
  2599. static bool upb_put_float(upb_encstate *e, float d) {
  2600. uint32_t u32;
  2601. UPB_ASSERT(sizeof(float) == sizeof(uint32_t));
  2602. memcpy(&u32, &d, sizeof(uint32_t));
  2603. return upb_put_fixed32(e, u32);
  2604. }
  2605. static uint32_t upb_readcase(const char *msg, const upb_msglayout_msginit_v1 *m,
  2606. int oneof_index) {
  2607. uint32_t ret;
  2608. memcpy(&ret, msg + m->oneofs[oneof_index].case_offset, sizeof(ret));
  2609. return ret;
  2610. }
  2611. static bool upb_readhasbit(const char *msg,
  2612. const upb_msglayout_fieldinit_v1 *f) {
  2613. UPB_ASSERT(f->hasbit != UPB_NO_HASBIT);
  2614. return msg[f->hasbit / 8] & (1 << (f->hasbit % 8));
  2615. }
  2616. static bool upb_put_tag(upb_encstate *e, int field_number, int wire_type) {
  2617. return upb_put_varint(e, (field_number << 3) | wire_type);
  2618. }
  2619. static bool upb_put_fixedarray(upb_encstate *e, const upb_array *arr,
  2620. size_t size) {
  2621. size_t bytes = arr->len * size;
  2622. return upb_put_bytes(e, arr->data, bytes) && upb_put_varint(e, bytes);
  2623. }
  2624. bool upb_encode_message(upb_encstate *e, const char *msg,
  2625. const upb_msglayout_msginit_v1 *m,
  2626. size_t *size);
  2627. static bool upb_encode_array(upb_encstate *e, const char *field_mem,
  2628. const upb_msglayout_msginit_v1 *m,
  2629. const upb_msglayout_fieldinit_v1 *f) {
  2630. const upb_array *arr = *(const upb_array**)field_mem;
  2631. if (arr == NULL || arr->len == 0) {
  2632. return true;
  2633. }
  2634. UPB_ASSERT(arr->type == upb_desctype_to_fieldtype2[f->type]);
  2635. #define VARINT_CASE(ctype, encode) { \
  2636. ctype *start = arr->data; \
  2637. ctype *ptr = start + arr->len; \
  2638. size_t pre_len = e->limit - e->ptr; \
  2639. do { \
  2640. ptr--; \
  2641. CHK(upb_put_varint(e, encode)); \
  2642. } while (ptr != start); \
  2643. CHK(upb_put_varint(e, e->limit - e->ptr - pre_len)); \
  2644. } \
  2645. break; \
  2646. do { ; } while(0)
  2647. switch (f->type) {
  2648. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  2649. CHK(upb_put_fixedarray(e, arr, sizeof(double)));
  2650. break;
  2651. case UPB_DESCRIPTOR_TYPE_FLOAT:
  2652. CHK(upb_put_fixedarray(e, arr, sizeof(float)));
  2653. break;
  2654. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  2655. case UPB_DESCRIPTOR_TYPE_FIXED64:
  2656. CHK(upb_put_fixedarray(e, arr, sizeof(uint64_t)));
  2657. break;
  2658. case UPB_DESCRIPTOR_TYPE_FIXED32:
  2659. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  2660. CHK(upb_put_fixedarray(e, arr, sizeof(uint32_t)));
  2661. break;
  2662. case UPB_DESCRIPTOR_TYPE_INT64:
  2663. case UPB_DESCRIPTOR_TYPE_UINT64:
  2664. VARINT_CASE(uint64_t, *ptr);
  2665. case UPB_DESCRIPTOR_TYPE_UINT32:
  2666. case UPB_DESCRIPTOR_TYPE_INT32:
  2667. case UPB_DESCRIPTOR_TYPE_ENUM:
  2668. VARINT_CASE(uint32_t, *ptr);
  2669. case UPB_DESCRIPTOR_TYPE_BOOL:
  2670. VARINT_CASE(bool, *ptr);
  2671. case UPB_DESCRIPTOR_TYPE_SINT32:
  2672. VARINT_CASE(int32_t, upb_zzencode_32(*ptr));
  2673. case UPB_DESCRIPTOR_TYPE_SINT64:
  2674. VARINT_CASE(int64_t, upb_zzencode_64(*ptr));
  2675. case UPB_DESCRIPTOR_TYPE_STRING:
  2676. case UPB_DESCRIPTOR_TYPE_BYTES: {
  2677. upb_stringview *start = arr->data;
  2678. upb_stringview *ptr = start + arr->len;
  2679. do {
  2680. ptr--;
  2681. CHK(upb_put_bytes(e, ptr->data, ptr->size) &&
  2682. upb_put_varint(e, ptr->size) &&
  2683. upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
  2684. } while (ptr != start);
  2685. return true;
  2686. }
  2687. case UPB_DESCRIPTOR_TYPE_GROUP: {
  2688. void **start = arr->data;
  2689. void **ptr = start + arr->len;
  2690. const upb_msglayout_msginit_v1 *subm = m->submsgs[f->submsg_index];
  2691. do {
  2692. size_t size;
  2693. ptr--;
  2694. CHK(upb_put_tag(e, f->number, UPB_WIRE_TYPE_END_GROUP) &&
  2695. upb_encode_message(e, *ptr, subm, &size) &&
  2696. upb_put_tag(e, f->number, UPB_WIRE_TYPE_START_GROUP));
  2697. } while (ptr != start);
  2698. return true;
  2699. }
  2700. case UPB_DESCRIPTOR_TYPE_MESSAGE: {
  2701. void **start = arr->data;
  2702. void **ptr = start + arr->len;
  2703. const upb_msglayout_msginit_v1 *subm = m->submsgs[f->submsg_index];
  2704. do {
  2705. size_t size;
  2706. ptr--;
  2707. CHK(upb_encode_message(e, *ptr, subm, &size) &&
  2708. upb_put_varint(e, size) &&
  2709. upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
  2710. } while (ptr != start);
  2711. return true;
  2712. }
  2713. }
  2714. #undef VARINT_CASE
  2715. /* We encode all primitive arrays as packed, regardless of what was specified
  2716. * in the .proto file. Could special case 1-sized arrays. */
  2717. CHK(upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
  2718. return true;
  2719. }
  2720. static bool upb_encode_scalarfield(upb_encstate *e, const char *field_mem,
  2721. const upb_msglayout_msginit_v1 *m,
  2722. const upb_msglayout_fieldinit_v1 *f,
  2723. bool is_proto3) {
  2724. bool skip_zero_value = is_proto3 && f->oneof_index == UPB_NOT_IN_ONEOF;
  2725. #define CASE(ctype, type, wire_type, encodeval) do { \
  2726. ctype val = *(ctype*)field_mem; \
  2727. if (skip_zero_value && val == 0) { \
  2728. return true; \
  2729. } \
  2730. return upb_put_ ## type(e, encodeval) && \
  2731. upb_put_tag(e, f->number, wire_type); \
  2732. } while(0)
  2733. switch (f->type) {
  2734. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  2735. CASE(double, double, UPB_WIRE_TYPE_64BIT, val);
  2736. case UPB_DESCRIPTOR_TYPE_FLOAT:
  2737. CASE(float, float, UPB_WIRE_TYPE_32BIT, val);
  2738. case UPB_DESCRIPTOR_TYPE_INT64:
  2739. case UPB_DESCRIPTOR_TYPE_UINT64:
  2740. CASE(uint64_t, varint, UPB_WIRE_TYPE_VARINT, val);
  2741. case UPB_DESCRIPTOR_TYPE_UINT32:
  2742. case UPB_DESCRIPTOR_TYPE_INT32:
  2743. case UPB_DESCRIPTOR_TYPE_ENUM:
  2744. CASE(uint32_t, varint, UPB_WIRE_TYPE_VARINT, val);
  2745. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  2746. case UPB_DESCRIPTOR_TYPE_FIXED64:
  2747. CASE(uint64_t, fixed64, UPB_WIRE_TYPE_64BIT, val);
  2748. case UPB_DESCRIPTOR_TYPE_FIXED32:
  2749. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  2750. CASE(uint32_t, fixed32, UPB_WIRE_TYPE_32BIT, val);
  2751. case UPB_DESCRIPTOR_TYPE_BOOL:
  2752. CASE(bool, varint, UPB_WIRE_TYPE_VARINT, val);
  2753. case UPB_DESCRIPTOR_TYPE_SINT32:
  2754. CASE(int32_t, varint, UPB_WIRE_TYPE_VARINT, upb_zzencode_32(val));
  2755. case UPB_DESCRIPTOR_TYPE_SINT64:
  2756. CASE(int64_t, varint, UPB_WIRE_TYPE_VARINT, upb_zzencode_64(val));
  2757. case UPB_DESCRIPTOR_TYPE_STRING:
  2758. case UPB_DESCRIPTOR_TYPE_BYTES: {
  2759. upb_stringview view = *(upb_stringview*)field_mem;
  2760. if (skip_zero_value && view.size == 0) {
  2761. return true;
  2762. }
  2763. return upb_put_bytes(e, view.data, view.size) &&
  2764. upb_put_varint(e, view.size) &&
  2765. upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED);
  2766. }
  2767. case UPB_DESCRIPTOR_TYPE_GROUP: {
  2768. size_t size;
  2769. void *submsg = *(void**)field_mem;
  2770. const upb_msglayout_msginit_v1 *subm = m->submsgs[f->submsg_index];
  2771. if (skip_zero_value && submsg == NULL) {
  2772. return true;
  2773. }
  2774. return upb_put_tag(e, f->number, UPB_WIRE_TYPE_END_GROUP) &&
  2775. upb_encode_message(e, submsg, subm, &size) &&
  2776. upb_put_tag(e, f->number, UPB_WIRE_TYPE_START_GROUP);
  2777. }
  2778. case UPB_DESCRIPTOR_TYPE_MESSAGE: {
  2779. size_t size;
  2780. void *submsg = *(void**)field_mem;
  2781. const upb_msglayout_msginit_v1 *subm = m->submsgs[f->submsg_index];
  2782. if (skip_zero_value && submsg == NULL) {
  2783. return true;
  2784. }
  2785. return upb_encode_message(e, submsg, subm, &size) &&
  2786. upb_put_varint(e, size) &&
  2787. upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED);
  2788. }
  2789. }
  2790. #undef CASE
  2791. UPB_UNREACHABLE();
  2792. }
  2793. bool upb_encode_hasscalarfield(const char *msg,
  2794. const upb_msglayout_msginit_v1 *m,
  2795. const upb_msglayout_fieldinit_v1 *f) {
  2796. if (f->oneof_index != UPB_NOT_IN_ONEOF) {
  2797. return upb_readcase(msg, m, f->oneof_index) == f->number;
  2798. } else if (m->is_proto2) {
  2799. return upb_readhasbit(msg, f);
  2800. } else {
  2801. /* For proto3, we'll test for the field being empty later. */
  2802. return true;
  2803. }
  2804. }
  2805. bool upb_encode_message(upb_encstate* e, const char *msg,
  2806. const upb_msglayout_msginit_v1 *m,
  2807. size_t *size) {
  2808. int i;
  2809. char *buf_end = e->ptr;
  2810. if (msg == NULL) {
  2811. return true;
  2812. }
  2813. for (i = m->field_count - 1; i >= 0; i--) {
  2814. const upb_msglayout_fieldinit_v1 *f = &m->fields[i];
  2815. if (f->label == UPB_LABEL_REPEATED) {
  2816. CHK(upb_encode_array(e, msg + f->offset, m, f));
  2817. } else {
  2818. if (upb_encode_hasscalarfield(msg, m, f)) {
  2819. CHK(upb_encode_scalarfield(e, msg + f->offset, m, f, !m->is_proto2));
  2820. }
  2821. }
  2822. }
  2823. *size = buf_end - e->ptr;
  2824. return true;
  2825. }
  2826. char *upb_encode(const void *msg, const upb_msglayout_msginit_v1 *m,
  2827. upb_env *env, size_t *size) {
  2828. upb_encstate e;
  2829. e.env = env;
  2830. e.buf = NULL;
  2831. e.limit = NULL;
  2832. e.ptr = NULL;
  2833. if (!upb_encode_message(&e, msg, m, size)) {
  2834. *size = 0;
  2835. return NULL;
  2836. }
  2837. *size = e.limit - e.ptr;
  2838. if (*size == 0) {
  2839. static char ch;
  2840. return &ch;
  2841. } else {
  2842. UPB_ASSERT(e.ptr);
  2843. return e.ptr;
  2844. }
  2845. }
  2846. #undef CHK
  2847. /*
  2848. ** TODO(haberman): it's unclear whether a lot of the consistency checks should
  2849. ** UPB_ASSERT() or return false.
  2850. */
  2851. #include <string.h>
  2852. static void *upb_calloc(size_t size) {
  2853. void *mem = upb_gmalloc(size);
  2854. if (mem) {
  2855. memset(mem, 0, size);
  2856. }
  2857. return mem;
  2858. }
  2859. /* Defined for the sole purpose of having a unique pointer value for
  2860. * UPB_NO_CLOSURE. */
  2861. char _upb_noclosure;
  2862. static void freehandlers(upb_refcounted *r) {
  2863. upb_handlers *h = (upb_handlers*)r;
  2864. upb_inttable_iter i;
  2865. upb_inttable_begin(&i, &h->cleanup_);
  2866. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  2867. void *val = (void*)upb_inttable_iter_key(&i);
  2868. upb_value func_val = upb_inttable_iter_value(&i);
  2869. upb_handlerfree *func = upb_value_getfptr(func_val);
  2870. func(val);
  2871. }
  2872. upb_inttable_uninit(&h->cleanup_);
  2873. upb_msgdef_unref(h->msg, h);
  2874. upb_gfree(h->sub);
  2875. upb_gfree(h);
  2876. }
  2877. static void visithandlers(const upb_refcounted *r, upb_refcounted_visit *visit,
  2878. void *closure) {
  2879. const upb_handlers *h = (const upb_handlers*)r;
  2880. upb_msg_field_iter i;
  2881. for(upb_msg_field_begin(&i, h->msg);
  2882. !upb_msg_field_done(&i);
  2883. upb_msg_field_next(&i)) {
  2884. upb_fielddef *f = upb_msg_iter_field(&i);
  2885. const upb_handlers *sub;
  2886. if (!upb_fielddef_issubmsg(f)) continue;
  2887. sub = upb_handlers_getsubhandlers(h, f);
  2888. if (sub) visit(r, upb_handlers_upcast(sub), closure);
  2889. }
  2890. }
  2891. static const struct upb_refcounted_vtbl vtbl = {visithandlers, freehandlers};
  2892. typedef struct {
  2893. upb_inttable tab; /* maps upb_msgdef* -> upb_handlers*. */
  2894. upb_handlers_callback *callback;
  2895. const void *closure;
  2896. } dfs_state;
  2897. /* TODO(haberman): discard upb_handlers* objects that do not actually have any
  2898. * handlers set and cannot reach any upb_handlers* object that does. This is
  2899. * slightly tricky to do correctly. */
  2900. static upb_handlers *newformsg(const upb_msgdef *m, const void *owner,
  2901. dfs_state *s) {
  2902. upb_msg_field_iter i;
  2903. upb_handlers *h = upb_handlers_new(m, owner);
  2904. if (!h) return NULL;
  2905. if (!upb_inttable_insertptr(&s->tab, m, upb_value_ptr(h))) goto oom;
  2906. s->callback(s->closure, h);
  2907. /* For each submessage field, get or create a handlers object and set it as
  2908. * the subhandlers. */
  2909. for(upb_msg_field_begin(&i, m);
  2910. !upb_msg_field_done(&i);
  2911. upb_msg_field_next(&i)) {
  2912. upb_fielddef *f = upb_msg_iter_field(&i);
  2913. const upb_msgdef *subdef;
  2914. upb_value subm_ent;
  2915. if (!upb_fielddef_issubmsg(f)) continue;
  2916. subdef = upb_downcast_msgdef(upb_fielddef_subdef(f));
  2917. if (upb_inttable_lookupptr(&s->tab, subdef, &subm_ent)) {
  2918. upb_handlers_setsubhandlers(h, f, upb_value_getptr(subm_ent));
  2919. } else {
  2920. upb_handlers *sub_mh = newformsg(subdef, &sub_mh, s);
  2921. if (!sub_mh) goto oom;
  2922. upb_handlers_setsubhandlers(h, f, sub_mh);
  2923. upb_handlers_unref(sub_mh, &sub_mh);
  2924. }
  2925. }
  2926. return h;
  2927. oom:
  2928. upb_handlers_unref(h, owner);
  2929. return NULL;
  2930. }
  2931. /* Given a selector for a STARTSUBMSG handler, resolves to a pointer to the
  2932. * subhandlers for this submessage field. */
  2933. #define SUBH(h, selector) (h->sub[selector])
  2934. /* The selector for a submessage field is the field index. */
  2935. #define SUBH_F(h, f) SUBH(h, f->index_)
  2936. static int32_t trygetsel(upb_handlers *h, const upb_fielddef *f,
  2937. upb_handlertype_t type) {
  2938. upb_selector_t sel;
  2939. UPB_ASSERT(!upb_handlers_isfrozen(h));
  2940. if (upb_handlers_msgdef(h) != upb_fielddef_containingtype(f)) {
  2941. upb_status_seterrf(
  2942. &h->status_, "type mismatch: field %s does not belong to message %s",
  2943. upb_fielddef_name(f), upb_msgdef_fullname(upb_handlers_msgdef(h)));
  2944. return -1;
  2945. }
  2946. if (!upb_handlers_getselector(f, type, &sel)) {
  2947. upb_status_seterrf(
  2948. &h->status_,
  2949. "type mismatch: cannot register handler type %d for field %s",
  2950. type, upb_fielddef_name(f));
  2951. return -1;
  2952. }
  2953. return sel;
  2954. }
  2955. static upb_selector_t handlers_getsel(upb_handlers *h, const upb_fielddef *f,
  2956. upb_handlertype_t type) {
  2957. int32_t sel = trygetsel(h, f, type);
  2958. UPB_ASSERT(sel >= 0);
  2959. return sel;
  2960. }
  2961. static const void **returntype(upb_handlers *h, const upb_fielddef *f,
  2962. upb_handlertype_t type) {
  2963. return &h->table[handlers_getsel(h, f, type)].attr.return_closure_type_;
  2964. }
  2965. static bool doset(upb_handlers *h, int32_t sel, const upb_fielddef *f,
  2966. upb_handlertype_t type, upb_func *func,
  2967. upb_handlerattr *attr) {
  2968. upb_handlerattr set_attr = UPB_HANDLERATTR_INITIALIZER;
  2969. const void *closure_type;
  2970. const void **context_closure_type;
  2971. UPB_ASSERT(!upb_handlers_isfrozen(h));
  2972. if (sel < 0) {
  2973. upb_status_seterrmsg(&h->status_,
  2974. "incorrect handler type for this field.");
  2975. return false;
  2976. }
  2977. if (h->table[sel].func) {
  2978. upb_status_seterrmsg(&h->status_,
  2979. "cannot change handler once it has been set.");
  2980. return false;
  2981. }
  2982. if (attr) {
  2983. set_attr = *attr;
  2984. }
  2985. /* Check that the given closure type matches the closure type that has been
  2986. * established for this context (if any). */
  2987. closure_type = upb_handlerattr_closuretype(&set_attr);
  2988. if (type == UPB_HANDLER_STRING) {
  2989. context_closure_type = returntype(h, f, UPB_HANDLER_STARTSTR);
  2990. } else if (f && upb_fielddef_isseq(f) &&
  2991. type != UPB_HANDLER_STARTSEQ &&
  2992. type != UPB_HANDLER_ENDSEQ) {
  2993. context_closure_type = returntype(h, f, UPB_HANDLER_STARTSEQ);
  2994. } else {
  2995. context_closure_type = &h->top_closure_type;
  2996. }
  2997. if (closure_type && *context_closure_type &&
  2998. closure_type != *context_closure_type) {
  2999. /* TODO(haberman): better message for debugging. */
  3000. if (f) {
  3001. upb_status_seterrf(&h->status_,
  3002. "closure type does not match for field %s",
  3003. upb_fielddef_name(f));
  3004. } else {
  3005. upb_status_seterrmsg(
  3006. &h->status_, "closure type does not match for message-level handler");
  3007. }
  3008. return false;
  3009. }
  3010. if (closure_type)
  3011. *context_closure_type = closure_type;
  3012. /* If this is a STARTSEQ or STARTSTR handler, check that the returned pointer
  3013. * matches any pre-existing expectations about what type is expected. */
  3014. if (type == UPB_HANDLER_STARTSEQ || type == UPB_HANDLER_STARTSTR) {
  3015. const void *return_type = upb_handlerattr_returnclosuretype(&set_attr);
  3016. const void *table_return_type =
  3017. upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  3018. if (return_type && table_return_type && return_type != table_return_type) {
  3019. upb_status_seterrmsg(&h->status_, "closure return type does not match");
  3020. return false;
  3021. }
  3022. if (table_return_type && !return_type)
  3023. upb_handlerattr_setreturnclosuretype(&set_attr, table_return_type);
  3024. }
  3025. h->table[sel].func = (upb_func*)func;
  3026. h->table[sel].attr = set_attr;
  3027. return true;
  3028. }
  3029. /* Returns the effective closure type for this handler (which will propagate
  3030. * from outer frames if this frame has no START* handler). Not implemented for
  3031. * UPB_HANDLER_STRING at the moment since this is not needed. Returns NULL is
  3032. * the effective closure type is unspecified (either no handler was registered
  3033. * to specify it or the handler that was registered did not specify the closure
  3034. * type). */
  3035. const void *effective_closure_type(upb_handlers *h, const upb_fielddef *f,
  3036. upb_handlertype_t type) {
  3037. const void *ret;
  3038. upb_selector_t sel;
  3039. UPB_ASSERT(type != UPB_HANDLER_STRING);
  3040. ret = h->top_closure_type;
  3041. if (upb_fielddef_isseq(f) &&
  3042. type != UPB_HANDLER_STARTSEQ &&
  3043. type != UPB_HANDLER_ENDSEQ &&
  3044. h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSEQ)].func) {
  3045. ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  3046. }
  3047. if (type == UPB_HANDLER_STRING &&
  3048. h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSTR)].func) {
  3049. ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  3050. }
  3051. /* The effective type of the submessage; not used yet.
  3052. * if (type == SUBMESSAGE &&
  3053. * h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSUBMSG)].func) {
  3054. * ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  3055. * } */
  3056. return ret;
  3057. }
  3058. /* Checks whether the START* handler specified by f & type is missing even
  3059. * though it is required to convert the established type of an outer frame
  3060. * ("closure_type") into the established type of an inner frame (represented in
  3061. * the return closure type of this handler's attr. */
  3062. bool checkstart(upb_handlers *h, const upb_fielddef *f, upb_handlertype_t type,
  3063. upb_status *status) {
  3064. const void *closure_type;
  3065. const upb_handlerattr *attr;
  3066. const void *return_closure_type;
  3067. upb_selector_t sel = handlers_getsel(h, f, type);
  3068. if (h->table[sel].func) return true;
  3069. closure_type = effective_closure_type(h, f, type);
  3070. attr = &h->table[sel].attr;
  3071. return_closure_type = upb_handlerattr_returnclosuretype(attr);
  3072. if (closure_type && return_closure_type &&
  3073. closure_type != return_closure_type) {
  3074. upb_status_seterrf(status,
  3075. "expected start handler to return sub type for field %f",
  3076. upb_fielddef_name(f));
  3077. return false;
  3078. }
  3079. return true;
  3080. }
  3081. /* Public interface ***********************************************************/
  3082. upb_handlers *upb_handlers_new(const upb_msgdef *md, const void *owner) {
  3083. int extra;
  3084. upb_handlers *h;
  3085. UPB_ASSERT(upb_msgdef_isfrozen(md));
  3086. extra = sizeof(upb_handlers_tabent) * (md->selector_count - 1);
  3087. h = upb_calloc(sizeof(*h) + extra);
  3088. if (!h) return NULL;
  3089. h->msg = md;
  3090. upb_msgdef_ref(h->msg, h);
  3091. upb_status_clear(&h->status_);
  3092. if (md->submsg_field_count > 0) {
  3093. h->sub = upb_calloc(md->submsg_field_count * sizeof(*h->sub));
  3094. if (!h->sub) goto oom;
  3095. } else {
  3096. h->sub = 0;
  3097. }
  3098. if (!upb_refcounted_init(upb_handlers_upcast_mutable(h), &vtbl, owner))
  3099. goto oom;
  3100. if (!upb_inttable_init(&h->cleanup_, UPB_CTYPE_FPTR)) goto oom;
  3101. /* calloc() above initialized all handlers to NULL. */
  3102. return h;
  3103. oom:
  3104. freehandlers(upb_handlers_upcast_mutable(h));
  3105. return NULL;
  3106. }
  3107. const upb_handlers *upb_handlers_newfrozen(const upb_msgdef *m,
  3108. const void *owner,
  3109. upb_handlers_callback *callback,
  3110. const void *closure) {
  3111. dfs_state state;
  3112. upb_handlers *ret;
  3113. bool ok;
  3114. upb_refcounted *r;
  3115. state.callback = callback;
  3116. state.closure = closure;
  3117. if (!upb_inttable_init(&state.tab, UPB_CTYPE_PTR)) return NULL;
  3118. ret = newformsg(m, owner, &state);
  3119. upb_inttable_uninit(&state.tab);
  3120. if (!ret) return NULL;
  3121. r = upb_handlers_upcast_mutable(ret);
  3122. ok = upb_refcounted_freeze(&r, 1, NULL, UPB_MAX_HANDLER_DEPTH);
  3123. UPB_ASSERT(ok);
  3124. return ret;
  3125. }
  3126. const upb_status *upb_handlers_status(upb_handlers *h) {
  3127. UPB_ASSERT(!upb_handlers_isfrozen(h));
  3128. return &h->status_;
  3129. }
  3130. void upb_handlers_clearerr(upb_handlers *h) {
  3131. UPB_ASSERT(!upb_handlers_isfrozen(h));
  3132. upb_status_clear(&h->status_);
  3133. }
  3134. #define SETTER(name, handlerctype, handlertype) \
  3135. bool upb_handlers_set ## name(upb_handlers *h, const upb_fielddef *f, \
  3136. handlerctype func, upb_handlerattr *attr) { \
  3137. int32_t sel = trygetsel(h, f, handlertype); \
  3138. return doset(h, sel, f, handlertype, (upb_func*)func, attr); \
  3139. }
  3140. SETTER(int32, upb_int32_handlerfunc*, UPB_HANDLER_INT32)
  3141. SETTER(int64, upb_int64_handlerfunc*, UPB_HANDLER_INT64)
  3142. SETTER(uint32, upb_uint32_handlerfunc*, UPB_HANDLER_UINT32)
  3143. SETTER(uint64, upb_uint64_handlerfunc*, UPB_HANDLER_UINT64)
  3144. SETTER(float, upb_float_handlerfunc*, UPB_HANDLER_FLOAT)
  3145. SETTER(double, upb_double_handlerfunc*, UPB_HANDLER_DOUBLE)
  3146. SETTER(bool, upb_bool_handlerfunc*, UPB_HANDLER_BOOL)
  3147. SETTER(startstr, upb_startstr_handlerfunc*, UPB_HANDLER_STARTSTR)
  3148. SETTER(string, upb_string_handlerfunc*, UPB_HANDLER_STRING)
  3149. SETTER(endstr, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSTR)
  3150. SETTER(startseq, upb_startfield_handlerfunc*, UPB_HANDLER_STARTSEQ)
  3151. SETTER(startsubmsg, upb_startfield_handlerfunc*, UPB_HANDLER_STARTSUBMSG)
  3152. SETTER(endsubmsg, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSUBMSG)
  3153. SETTER(endseq, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSEQ)
  3154. #undef SETTER
  3155. bool upb_handlers_setunknown(upb_handlers *h, upb_unknown_handlerfunc *func,
  3156. upb_handlerattr *attr) {
  3157. return doset(h, UPB_UNKNOWN_SELECTOR, NULL, UPB_HANDLER_INT32,
  3158. (upb_func *)func, attr);
  3159. }
  3160. bool upb_handlers_setstartmsg(upb_handlers *h, upb_startmsg_handlerfunc *func,
  3161. upb_handlerattr *attr) {
  3162. return doset(h, UPB_STARTMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
  3163. (upb_func *)func, attr);
  3164. }
  3165. bool upb_handlers_setendmsg(upb_handlers *h, upb_endmsg_handlerfunc *func,
  3166. upb_handlerattr *attr) {
  3167. UPB_ASSERT(!upb_handlers_isfrozen(h));
  3168. return doset(h, UPB_ENDMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
  3169. (upb_func *)func, attr);
  3170. }
  3171. bool upb_handlers_setsubhandlers(upb_handlers *h, const upb_fielddef *f,
  3172. const upb_handlers *sub) {
  3173. UPB_ASSERT(sub);
  3174. UPB_ASSERT(!upb_handlers_isfrozen(h));
  3175. UPB_ASSERT(upb_fielddef_issubmsg(f));
  3176. if (SUBH_F(h, f)) return false; /* Can't reset. */
  3177. if (upb_msgdef_upcast(upb_handlers_msgdef(sub)) != upb_fielddef_subdef(f)) {
  3178. return false;
  3179. }
  3180. SUBH_F(h, f) = sub;
  3181. upb_ref2(sub, h);
  3182. return true;
  3183. }
  3184. const upb_handlers *upb_handlers_getsubhandlers(const upb_handlers *h,
  3185. const upb_fielddef *f) {
  3186. UPB_ASSERT(upb_fielddef_issubmsg(f));
  3187. return SUBH_F(h, f);
  3188. }
  3189. bool upb_handlers_getattr(const upb_handlers *h, upb_selector_t sel,
  3190. upb_handlerattr *attr) {
  3191. if (!upb_handlers_gethandler(h, sel))
  3192. return false;
  3193. *attr = h->table[sel].attr;
  3194. return true;
  3195. }
  3196. const upb_handlers *upb_handlers_getsubhandlers_sel(const upb_handlers *h,
  3197. upb_selector_t sel) {
  3198. /* STARTSUBMSG selector in sel is the field's selector base. */
  3199. return SUBH(h, sel - UPB_STATIC_SELECTOR_COUNT);
  3200. }
  3201. const upb_msgdef *upb_handlers_msgdef(const upb_handlers *h) { return h->msg; }
  3202. bool upb_handlers_addcleanup(upb_handlers *h, void *p, upb_handlerfree *func) {
  3203. bool ok;
  3204. if (upb_inttable_lookupptr(&h->cleanup_, p, NULL)) {
  3205. return false;
  3206. }
  3207. ok = upb_inttable_insertptr(&h->cleanup_, p, upb_value_fptr(func));
  3208. UPB_ASSERT(ok);
  3209. return true;
  3210. }
  3211. /* "Static" methods ***********************************************************/
  3212. bool upb_handlers_freeze(upb_handlers *const*handlers, int n, upb_status *s) {
  3213. /* TODO: verify we have a transitive closure. */
  3214. int i;
  3215. for (i = 0; i < n; i++) {
  3216. upb_msg_field_iter j;
  3217. upb_handlers *h = handlers[i];
  3218. if (!upb_ok(&h->status_)) {
  3219. upb_status_seterrf(s, "handlers for message %s had error status: %s",
  3220. upb_msgdef_fullname(upb_handlers_msgdef(h)),
  3221. upb_status_errmsg(&h->status_));
  3222. return false;
  3223. }
  3224. /* Check that there are no closure mismatches due to missing Start* handlers
  3225. * or subhandlers with different type-level types. */
  3226. for(upb_msg_field_begin(&j, h->msg);
  3227. !upb_msg_field_done(&j);
  3228. upb_msg_field_next(&j)) {
  3229. const upb_fielddef *f = upb_msg_iter_field(&j);
  3230. if (upb_fielddef_isseq(f)) {
  3231. if (!checkstart(h, f, UPB_HANDLER_STARTSEQ, s))
  3232. return false;
  3233. }
  3234. if (upb_fielddef_isstring(f)) {
  3235. if (!checkstart(h, f, UPB_HANDLER_STARTSTR, s))
  3236. return false;
  3237. }
  3238. if (upb_fielddef_issubmsg(f)) {
  3239. bool hashandler = false;
  3240. if (upb_handlers_gethandler(
  3241. h, handlers_getsel(h, f, UPB_HANDLER_STARTSUBMSG)) ||
  3242. upb_handlers_gethandler(
  3243. h, handlers_getsel(h, f, UPB_HANDLER_ENDSUBMSG))) {
  3244. hashandler = true;
  3245. }
  3246. if (upb_fielddef_isseq(f) &&
  3247. (upb_handlers_gethandler(
  3248. h, handlers_getsel(h, f, UPB_HANDLER_STARTSEQ)) ||
  3249. upb_handlers_gethandler(
  3250. h, handlers_getsel(h, f, UPB_HANDLER_ENDSEQ)))) {
  3251. hashandler = true;
  3252. }
  3253. if (hashandler && !upb_handlers_getsubhandlers(h, f)) {
  3254. /* For now we add an empty subhandlers in this case. It makes the
  3255. * decoder code generator simpler, because it only has to handle two
  3256. * cases (submessage has handlers or not) as opposed to three
  3257. * (submessage has handlers in enclosing message but no subhandlers).
  3258. *
  3259. * This makes parsing less efficient in the case that we want to
  3260. * notice a submessage but skip its contents (like if we're testing
  3261. * for submessage presence or counting the number of repeated
  3262. * submessages). In this case we will end up parsing the submessage
  3263. * field by field and throwing away the results for each, instead of
  3264. * skipping the whole delimited thing at once. If this is an issue we
  3265. * can revisit it, but do remember that this only arises when you have
  3266. * handlers (startseq/startsubmsg/endsubmsg/endseq) set for the
  3267. * submessage but no subhandlers. The uses cases for this are
  3268. * limited. */
  3269. upb_handlers *sub = upb_handlers_new(upb_fielddef_msgsubdef(f), &sub);
  3270. upb_handlers_setsubhandlers(h, f, sub);
  3271. upb_handlers_unref(sub, &sub);
  3272. }
  3273. /* TODO(haberman): check type of submessage.
  3274. * This is slightly tricky; also consider whether we should check that
  3275. * they match at setsubhandlers time. */
  3276. }
  3277. }
  3278. }
  3279. if (!upb_refcounted_freeze((upb_refcounted*const*)handlers, n, s,
  3280. UPB_MAX_HANDLER_DEPTH)) {
  3281. return false;
  3282. }
  3283. return true;
  3284. }
  3285. upb_handlertype_t upb_handlers_getprimitivehandlertype(const upb_fielddef *f) {
  3286. switch (upb_fielddef_type(f)) {
  3287. case UPB_TYPE_INT32:
  3288. case UPB_TYPE_ENUM: return UPB_HANDLER_INT32;
  3289. case UPB_TYPE_INT64: return UPB_HANDLER_INT64;
  3290. case UPB_TYPE_UINT32: return UPB_HANDLER_UINT32;
  3291. case UPB_TYPE_UINT64: return UPB_HANDLER_UINT64;
  3292. case UPB_TYPE_FLOAT: return UPB_HANDLER_FLOAT;
  3293. case UPB_TYPE_DOUBLE: return UPB_HANDLER_DOUBLE;
  3294. case UPB_TYPE_BOOL: return UPB_HANDLER_BOOL;
  3295. default: UPB_ASSERT(false); return -1; /* Invalid input. */
  3296. }
  3297. }
  3298. bool upb_handlers_getselector(const upb_fielddef *f, upb_handlertype_t type,
  3299. upb_selector_t *s) {
  3300. switch (type) {
  3301. case UPB_HANDLER_INT32:
  3302. case UPB_HANDLER_INT64:
  3303. case UPB_HANDLER_UINT32:
  3304. case UPB_HANDLER_UINT64:
  3305. case UPB_HANDLER_FLOAT:
  3306. case UPB_HANDLER_DOUBLE:
  3307. case UPB_HANDLER_BOOL:
  3308. if (!upb_fielddef_isprimitive(f) ||
  3309. upb_handlers_getprimitivehandlertype(f) != type)
  3310. return false;
  3311. *s = f->selector_base;
  3312. break;
  3313. case UPB_HANDLER_STRING:
  3314. if (upb_fielddef_isstring(f)) {
  3315. *s = f->selector_base;
  3316. } else if (upb_fielddef_lazy(f)) {
  3317. *s = f->selector_base + 3;
  3318. } else {
  3319. return false;
  3320. }
  3321. break;
  3322. case UPB_HANDLER_STARTSTR:
  3323. if (upb_fielddef_isstring(f) || upb_fielddef_lazy(f)) {
  3324. *s = f->selector_base + 1;
  3325. } else {
  3326. return false;
  3327. }
  3328. break;
  3329. case UPB_HANDLER_ENDSTR:
  3330. if (upb_fielddef_isstring(f) || upb_fielddef_lazy(f)) {
  3331. *s = f->selector_base + 2;
  3332. } else {
  3333. return false;
  3334. }
  3335. break;
  3336. case UPB_HANDLER_STARTSEQ:
  3337. if (!upb_fielddef_isseq(f)) return false;
  3338. *s = f->selector_base - 2;
  3339. break;
  3340. case UPB_HANDLER_ENDSEQ:
  3341. if (!upb_fielddef_isseq(f)) return false;
  3342. *s = f->selector_base - 1;
  3343. break;
  3344. case UPB_HANDLER_STARTSUBMSG:
  3345. if (!upb_fielddef_issubmsg(f)) return false;
  3346. /* Selectors for STARTSUBMSG are at the beginning of the table so that the
  3347. * selector can also be used as an index into the "sub" array of
  3348. * subhandlers. The indexes for the two into these two tables are the
  3349. * same, except that in the handler table the static selectors come first. */
  3350. *s = f->index_ + UPB_STATIC_SELECTOR_COUNT;
  3351. break;
  3352. case UPB_HANDLER_ENDSUBMSG:
  3353. if (!upb_fielddef_issubmsg(f)) return false;
  3354. *s = f->selector_base;
  3355. break;
  3356. }
  3357. UPB_ASSERT((size_t)*s < upb_fielddef_containingtype(f)->selector_count);
  3358. return true;
  3359. }
  3360. uint32_t upb_handlers_selectorbaseoffset(const upb_fielddef *f) {
  3361. return upb_fielddef_isseq(f) ? 2 : 0;
  3362. }
  3363. uint32_t upb_handlers_selectorcount(const upb_fielddef *f) {
  3364. uint32_t ret = 1;
  3365. if (upb_fielddef_isseq(f)) ret += 2; /* STARTSEQ/ENDSEQ */
  3366. if (upb_fielddef_isstring(f)) ret += 2; /* [STRING]/STARTSTR/ENDSTR */
  3367. if (upb_fielddef_issubmsg(f)) {
  3368. /* ENDSUBMSG (STARTSUBMSG is at table beginning) */
  3369. ret += 0;
  3370. if (upb_fielddef_lazy(f)) {
  3371. /* STARTSTR/ENDSTR/STRING (for lazy) */
  3372. ret += 3;
  3373. }
  3374. }
  3375. return ret;
  3376. }
  3377. /* upb_handlerattr ************************************************************/
  3378. void upb_handlerattr_init(upb_handlerattr *attr) {
  3379. upb_handlerattr from = UPB_HANDLERATTR_INITIALIZER;
  3380. memcpy(attr, &from, sizeof(*attr));
  3381. }
  3382. void upb_handlerattr_uninit(upb_handlerattr *attr) {
  3383. UPB_UNUSED(attr);
  3384. }
  3385. bool upb_handlerattr_sethandlerdata(upb_handlerattr *attr, const void *hd) {
  3386. attr->handler_data_ = hd;
  3387. return true;
  3388. }
  3389. bool upb_handlerattr_setclosuretype(upb_handlerattr *attr, const void *type) {
  3390. attr->closure_type_ = type;
  3391. return true;
  3392. }
  3393. const void *upb_handlerattr_closuretype(const upb_handlerattr *attr) {
  3394. return attr->closure_type_;
  3395. }
  3396. bool upb_handlerattr_setreturnclosuretype(upb_handlerattr *attr,
  3397. const void *type) {
  3398. attr->return_closure_type_ = type;
  3399. return true;
  3400. }
  3401. const void *upb_handlerattr_returnclosuretype(const upb_handlerattr *attr) {
  3402. return attr->return_closure_type_;
  3403. }
  3404. bool upb_handlerattr_setalwaysok(upb_handlerattr *attr, bool alwaysok) {
  3405. attr->alwaysok_ = alwaysok;
  3406. return true;
  3407. }
  3408. bool upb_handlerattr_alwaysok(const upb_handlerattr *attr) {
  3409. return attr->alwaysok_;
  3410. }
  3411. /* upb_bufhandle **************************************************************/
  3412. size_t upb_bufhandle_objofs(const upb_bufhandle *h) {
  3413. return h->objofs_;
  3414. }
  3415. /* upb_byteshandler ***********************************************************/
  3416. void upb_byteshandler_init(upb_byteshandler* h) {
  3417. memset(h, 0, sizeof(*h));
  3418. }
  3419. /* For when we support handlerfree callbacks. */
  3420. void upb_byteshandler_uninit(upb_byteshandler* h) {
  3421. UPB_UNUSED(h);
  3422. }
  3423. bool upb_byteshandler_setstartstr(upb_byteshandler *h,
  3424. upb_startstr_handlerfunc *func, void *d) {
  3425. h->table[UPB_STARTSTR_SELECTOR].func = (upb_func*)func;
  3426. h->table[UPB_STARTSTR_SELECTOR].attr.handler_data_ = d;
  3427. return true;
  3428. }
  3429. bool upb_byteshandler_setstring(upb_byteshandler *h,
  3430. upb_string_handlerfunc *func, void *d) {
  3431. h->table[UPB_STRING_SELECTOR].func = (upb_func*)func;
  3432. h->table[UPB_STRING_SELECTOR].attr.handler_data_ = d;
  3433. return true;
  3434. }
  3435. bool upb_byteshandler_setendstr(upb_byteshandler *h,
  3436. upb_endfield_handlerfunc *func, void *d) {
  3437. h->table[UPB_ENDSTR_SELECTOR].func = (upb_func*)func;
  3438. h->table[UPB_ENDSTR_SELECTOR].attr.handler_data_ = d;
  3439. return true;
  3440. }
  3441. static bool is_power_of_two(size_t val) {
  3442. return (val & (val - 1)) == 0;
  3443. }
  3444. /* Align up to the given power of 2. */
  3445. static size_t align_up(size_t val, size_t align) {
  3446. UPB_ASSERT(is_power_of_two(align));
  3447. return (val + align - 1) & ~(align - 1);
  3448. }
  3449. static size_t div_round_up(size_t n, size_t d) {
  3450. return (n + d - 1) / d;
  3451. }
  3452. bool upb_fieldtype_mapkeyok(upb_fieldtype_t type) {
  3453. return type == UPB_TYPE_BOOL || type == UPB_TYPE_INT32 ||
  3454. type == UPB_TYPE_UINT32 || type == UPB_TYPE_INT64 ||
  3455. type == UPB_TYPE_UINT64 || type == UPB_TYPE_STRING;
  3456. }
  3457. void *upb_array_pack(const upb_array *arr, void *p, size_t *ofs, size_t size);
  3458. void *upb_map_pack(const upb_map *map, void *p, size_t *ofs, size_t size);
  3459. #define PTR_AT(msg, ofs, type) (type*)((char*)msg + ofs)
  3460. #define VOIDPTR_AT(msg, ofs) PTR_AT(msg, ofs, void)
  3461. #define ENCODE_MAX_NESTING 64
  3462. #define CHECK_TRUE(x) if (!(x)) { return false; }
  3463. /** upb_msgval ****************************************************************/
  3464. #define upb_alignof(t) offsetof(struct { char c; t x; }, x)
  3465. /* These functions will generate real memcpy() calls on ARM sadly, because
  3466. * the compiler assumes they might not be aligned. */
  3467. static upb_msgval upb_msgval_read(const void *p, size_t ofs,
  3468. uint8_t size) {
  3469. upb_msgval val;
  3470. p = (char*)p + ofs;
  3471. memcpy(&val, p, size);
  3472. return val;
  3473. }
  3474. static void upb_msgval_write(void *p, size_t ofs, upb_msgval val,
  3475. uint8_t size) {
  3476. p = (char*)p + ofs;
  3477. memcpy(p, &val, size);
  3478. }
  3479. static size_t upb_msgval_sizeof(upb_fieldtype_t type) {
  3480. switch (type) {
  3481. case UPB_TYPE_DOUBLE:
  3482. case UPB_TYPE_INT64:
  3483. case UPB_TYPE_UINT64:
  3484. return 8;
  3485. case UPB_TYPE_ENUM:
  3486. case UPB_TYPE_INT32:
  3487. case UPB_TYPE_UINT32:
  3488. case UPB_TYPE_FLOAT:
  3489. return 4;
  3490. case UPB_TYPE_BOOL:
  3491. return 1;
  3492. case UPB_TYPE_BYTES:
  3493. case UPB_TYPE_MESSAGE:
  3494. return sizeof(void*);
  3495. case UPB_TYPE_STRING:
  3496. return sizeof(upb_stringview);
  3497. }
  3498. UPB_UNREACHABLE();
  3499. }
  3500. static uint8_t upb_msg_fieldsize(const upb_msglayout_fieldinit_v1 *field) {
  3501. if (field->label == UPB_LABEL_REPEATED) {
  3502. return sizeof(void*);
  3503. } else {
  3504. return upb_msgval_sizeof(field->type);
  3505. }
  3506. }
  3507. static uint8_t upb_msg_fielddefsize(const upb_fielddef *f) {
  3508. if (upb_fielddef_isseq(f)) {
  3509. return sizeof(void*);
  3510. } else {
  3511. return upb_msgval_sizeof(upb_fielddef_type(f));
  3512. }
  3513. }
  3514. /* TODO(haberman): this is broken right now because upb_msgval can contain
  3515. * a char* / size_t pair, which is too big for a upb_value. To fix this
  3516. * we'll probably need to dynamically allocate a upb_msgval and store a
  3517. * pointer to that in the tables for extensions/maps. */
  3518. static upb_value upb_toval(upb_msgval val) {
  3519. upb_value ret;
  3520. UPB_UNUSED(val);
  3521. memset(&ret, 0, sizeof(upb_value)); /* XXX */
  3522. return ret;
  3523. }
  3524. static upb_msgval upb_msgval_fromval(upb_value val) {
  3525. upb_msgval ret;
  3526. UPB_UNUSED(val);
  3527. memset(&ret, 0, sizeof(upb_msgval)); /* XXX */
  3528. return ret;
  3529. }
  3530. static upb_ctype_t upb_fieldtotabtype(upb_fieldtype_t type) {
  3531. switch (type) {
  3532. case UPB_TYPE_FLOAT: return UPB_CTYPE_FLOAT;
  3533. case UPB_TYPE_DOUBLE: return UPB_CTYPE_DOUBLE;
  3534. case UPB_TYPE_BOOL: return UPB_CTYPE_BOOL;
  3535. case UPB_TYPE_BYTES:
  3536. case UPB_TYPE_MESSAGE:
  3537. case UPB_TYPE_STRING: return UPB_CTYPE_CONSTPTR;
  3538. case UPB_TYPE_ENUM:
  3539. case UPB_TYPE_INT32: return UPB_CTYPE_INT32;
  3540. case UPB_TYPE_UINT32: return UPB_CTYPE_UINT32;
  3541. case UPB_TYPE_INT64: return UPB_CTYPE_INT64;
  3542. case UPB_TYPE_UINT64: return UPB_CTYPE_UINT64;
  3543. default: UPB_ASSERT(false); return 0;
  3544. }
  3545. }
  3546. static upb_msgval upb_msgval_fromdefault(const upb_fielddef *f) {
  3547. switch (upb_fielddef_type(f)) {
  3548. case UPB_TYPE_FLOAT:
  3549. return upb_msgval_float(upb_fielddef_defaultfloat(f));
  3550. case UPB_TYPE_DOUBLE:
  3551. return upb_msgval_double(upb_fielddef_defaultdouble(f));
  3552. case UPB_TYPE_BOOL:
  3553. return upb_msgval_bool(upb_fielddef_defaultbool(f));
  3554. case UPB_TYPE_STRING:
  3555. case UPB_TYPE_BYTES: {
  3556. size_t len;
  3557. const char *ptr = upb_fielddef_defaultstr(f, &len);
  3558. return upb_msgval_makestr(ptr, len);
  3559. }
  3560. case UPB_TYPE_MESSAGE:
  3561. return upb_msgval_msg(NULL);
  3562. case UPB_TYPE_ENUM:
  3563. case UPB_TYPE_INT32:
  3564. return upb_msgval_int32(upb_fielddef_defaultint32(f));
  3565. case UPB_TYPE_UINT32:
  3566. return upb_msgval_uint32(upb_fielddef_defaultuint32(f));
  3567. case UPB_TYPE_INT64:
  3568. return upb_msgval_int64(upb_fielddef_defaultint64(f));
  3569. case UPB_TYPE_UINT64:
  3570. return upb_msgval_uint64(upb_fielddef_defaultuint64(f));
  3571. default:
  3572. UPB_ASSERT(false);
  3573. return upb_msgval_msg(NULL);
  3574. }
  3575. }
  3576. /** upb_msglayout *************************************************************/
  3577. struct upb_msglayout {
  3578. struct upb_msglayout_msginit_v1 data;
  3579. };
  3580. static void upb_msglayout_free(upb_msglayout *l) {
  3581. upb_gfree(l->data.default_msg);
  3582. upb_gfree(l);
  3583. }
  3584. static size_t upb_msglayout_place(upb_msglayout *l, size_t size) {
  3585. size_t ret;
  3586. l->data.size = align_up(l->data.size, size);
  3587. ret = l->data.size;
  3588. l->data.size += size;
  3589. return ret;
  3590. }
  3591. static uint32_t upb_msglayout_offset(const upb_msglayout *l,
  3592. const upb_fielddef *f) {
  3593. return l->data.fields[upb_fielddef_index(f)].offset;
  3594. }
  3595. static uint32_t upb_msglayout_hasbit(const upb_msglayout *l,
  3596. const upb_fielddef *f) {
  3597. return l->data.fields[upb_fielddef_index(f)].hasbit;
  3598. }
  3599. static bool upb_msglayout_initdefault(upb_msglayout *l, const upb_msgdef *m) {
  3600. upb_msg_field_iter it;
  3601. if (upb_msgdef_syntax(m) == UPB_SYNTAX_PROTO2 && l->data.size) {
  3602. /* Allocate default message and set default values in it. */
  3603. l->data.default_msg = upb_gmalloc(l->data.size);
  3604. if (!l->data.default_msg) {
  3605. return false;
  3606. }
  3607. memset(l->data.default_msg, 0, l->data.size);
  3608. for (upb_msg_field_begin(&it, m); !upb_msg_field_done(&it);
  3609. upb_msg_field_next(&it)) {
  3610. const upb_fielddef* f = upb_msg_iter_field(&it);
  3611. if (upb_fielddef_containingoneof(f)) {
  3612. continue;
  3613. }
  3614. /* TODO(haberman): handle strings. */
  3615. if (!upb_fielddef_isstring(f) &&
  3616. !upb_fielddef_issubmsg(f) &&
  3617. !upb_fielddef_isseq(f)) {
  3618. upb_msg_set(l->data.default_msg,
  3619. upb_fielddef_index(f),
  3620. upb_msgval_fromdefault(f),
  3621. l);
  3622. }
  3623. }
  3624. }
  3625. return true;
  3626. }
  3627. static upb_msglayout *upb_msglayout_new(const upb_msgdef *m) {
  3628. upb_msg_field_iter it;
  3629. upb_msg_oneof_iter oit;
  3630. upb_msglayout *l;
  3631. size_t hasbit;
  3632. size_t submsg_count = 0;
  3633. const upb_msglayout_msginit_v1 **submsgs;
  3634. upb_msglayout_fieldinit_v1 *fields;
  3635. upb_msglayout_oneofinit_v1 *oneofs;
  3636. for (upb_msg_field_begin(&it, m);
  3637. !upb_msg_field_done(&it);
  3638. upb_msg_field_next(&it)) {
  3639. const upb_fielddef* f = upb_msg_iter_field(&it);
  3640. if (upb_fielddef_issubmsg(f)) {
  3641. submsg_count++;
  3642. }
  3643. }
  3644. l = upb_gmalloc(sizeof(*l));
  3645. if (!l) return NULL;
  3646. memset(l, 0, sizeof(*l));
  3647. fields = upb_gmalloc(upb_msgdef_numfields(m) * sizeof(*fields));
  3648. submsgs = upb_gmalloc(submsg_count * sizeof(*submsgs));
  3649. oneofs = upb_gmalloc(upb_msgdef_numoneofs(m) * sizeof(*oneofs));
  3650. if ((!fields && upb_msgdef_numfields(m)) ||
  3651. (!submsgs && submsg_count) ||
  3652. (!oneofs && upb_msgdef_numoneofs(m))) {
  3653. /* OOM. */
  3654. upb_gfree(l);
  3655. upb_gfree(fields);
  3656. upb_gfree(submsgs);
  3657. upb_gfree(oneofs);
  3658. return NULL;
  3659. }
  3660. l->data.field_count = upb_msgdef_numfields(m);
  3661. l->data.oneof_count = upb_msgdef_numoneofs(m);
  3662. l->data.fields = fields;
  3663. l->data.submsgs = submsgs;
  3664. l->data.oneofs = oneofs;
  3665. l->data.is_proto2 = (upb_msgdef_syntax(m) == UPB_SYNTAX_PROTO2);
  3666. /* Allocate data offsets in three stages:
  3667. *
  3668. * 1. hasbits.
  3669. * 2. regular fields.
  3670. * 3. oneof fields.
  3671. *
  3672. * OPT: There is a lot of room for optimization here to minimize the size.
  3673. */
  3674. /* Allocate hasbits and set basic field attributes. */
  3675. for (upb_msg_field_begin(&it, m), hasbit = 0;
  3676. !upb_msg_field_done(&it);
  3677. upb_msg_field_next(&it)) {
  3678. const upb_fielddef* f = upb_msg_iter_field(&it);
  3679. upb_msglayout_fieldinit_v1 *field = &fields[upb_fielddef_index(f)];
  3680. field->number = upb_fielddef_number(f);
  3681. field->type = upb_fielddef_type(f);
  3682. field->label = upb_fielddef_label(f);
  3683. if (upb_fielddef_containingoneof(f)) {
  3684. field->oneof_index = upb_oneofdef_index(upb_fielddef_containingoneof(f));
  3685. } else {
  3686. field->oneof_index = UPB_NOT_IN_ONEOF;
  3687. }
  3688. if (upb_fielddef_haspresence(f) && !upb_fielddef_containingoneof(f)) {
  3689. field->hasbit = hasbit++;
  3690. }
  3691. }
  3692. /* Account for space used by hasbits. */
  3693. l->data.size = div_round_up(hasbit, 8);
  3694. /* Allocate non-oneof fields. */
  3695. for (upb_msg_field_begin(&it, m); !upb_msg_field_done(&it);
  3696. upb_msg_field_next(&it)) {
  3697. const upb_fielddef* f = upb_msg_iter_field(&it);
  3698. size_t field_size = upb_msg_fielddefsize(f);
  3699. size_t index = upb_fielddef_index(f);
  3700. if (upb_fielddef_containingoneof(f)) {
  3701. /* Oneofs are handled separately below. */
  3702. continue;
  3703. }
  3704. fields[index].offset = upb_msglayout_place(l, field_size);
  3705. }
  3706. /* Allocate oneof fields. Each oneof field consists of a uint32 for the case
  3707. * and space for the actual data. */
  3708. for (upb_msg_oneof_begin(&oit, m); !upb_msg_oneof_done(&oit);
  3709. upb_msg_oneof_next(&oit)) {
  3710. const upb_oneofdef* o = upb_msg_iter_oneof(&oit);
  3711. upb_oneof_iter fit;
  3712. size_t case_size = sizeof(uint32_t); /* Could potentially optimize this. */
  3713. upb_msglayout_oneofinit_v1 *oneof = &oneofs[upb_oneofdef_index(o)];
  3714. size_t field_size = 0;
  3715. /* Calculate field size: the max of all field sizes. */
  3716. for (upb_oneof_begin(&fit, o);
  3717. !upb_oneof_done(&fit);
  3718. upb_oneof_next(&fit)) {
  3719. const upb_fielddef* f = upb_oneof_iter_field(&fit);
  3720. field_size = UPB_MAX(field_size, upb_msg_fielddefsize(f));
  3721. }
  3722. /* Align and allocate case offset. */
  3723. oneof->case_offset = upb_msglayout_place(l, case_size);
  3724. oneof->data_offset = upb_msglayout_place(l, field_size);
  3725. }
  3726. /* Size of the entire structure should be a multiple of its greatest
  3727. * alignment. TODO: track overall alignment for real? */
  3728. l->data.size = align_up(l->data.size, 8);
  3729. if (upb_msglayout_initdefault(l, m)) {
  3730. return l;
  3731. } else {
  3732. upb_msglayout_free(l);
  3733. return NULL;
  3734. }
  3735. }
  3736. /** upb_msgfactory ************************************************************/
  3737. struct upb_msgfactory {
  3738. const upb_symtab *symtab; /* We own a ref. */
  3739. upb_inttable layouts;
  3740. upb_inttable mergehandlers;
  3741. };
  3742. upb_msgfactory *upb_msgfactory_new(const upb_symtab *symtab) {
  3743. upb_msgfactory *ret = upb_gmalloc(sizeof(*ret));
  3744. ret->symtab = symtab;
  3745. upb_inttable_init(&ret->layouts, UPB_CTYPE_PTR);
  3746. upb_inttable_init(&ret->mergehandlers, UPB_CTYPE_CONSTPTR);
  3747. return ret;
  3748. }
  3749. void upb_msgfactory_free(upb_msgfactory *f) {
  3750. upb_inttable_iter i;
  3751. upb_inttable_begin(&i, &f->layouts);
  3752. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  3753. upb_msglayout *l = upb_value_getptr(upb_inttable_iter_value(&i));
  3754. upb_msglayout_free(l);
  3755. }
  3756. upb_inttable_begin(&i, &f->mergehandlers);
  3757. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  3758. const upb_handlers *h = upb_value_getconstptr(upb_inttable_iter_value(&i));
  3759. upb_handlers_unref(h, f);
  3760. }
  3761. upb_inttable_uninit(&f->layouts);
  3762. upb_inttable_uninit(&f->mergehandlers);
  3763. upb_gfree(f);
  3764. }
  3765. const upb_symtab *upb_msgfactory_symtab(const upb_msgfactory *f) {
  3766. return f->symtab;
  3767. }
  3768. const upb_msglayout *upb_msgfactory_getlayout(upb_msgfactory *f,
  3769. const upb_msgdef *m) {
  3770. upb_value v;
  3771. UPB_ASSERT(upb_symtab_lookupmsg(f->symtab, upb_msgdef_fullname(m)) == m);
  3772. UPB_ASSERT(!upb_msgdef_mapentry(m));
  3773. if (upb_inttable_lookupptr(&f->layouts, m, &v)) {
  3774. UPB_ASSERT(upb_value_getptr(v));
  3775. return upb_value_getptr(v);
  3776. } else {
  3777. upb_msgfactory *mutable_f = (void*)f;
  3778. upb_msglayout *l = upb_msglayout_new(m);
  3779. upb_inttable_insertptr(&mutable_f->layouts, m, upb_value_ptr(l));
  3780. UPB_ASSERT(l);
  3781. return l;
  3782. }
  3783. }
  3784. /* Our handlers that we don't expose externally. */
  3785. void *upb_msg_startstr(void *msg, const void *hd, size_t size_hint) {
  3786. uint32_t ofs = (uintptr_t)hd;
  3787. upb_alloc *alloc = upb_msg_alloc(msg);
  3788. upb_msgval val;
  3789. UPB_UNUSED(size_hint);
  3790. val = upb_msgval_read(msg, ofs, upb_msgval_sizeof(UPB_TYPE_STRING));
  3791. upb_free(alloc, (void*)val.str.data);
  3792. val.str.data = NULL;
  3793. val.str.size = 0;
  3794. upb_msgval_write(msg, ofs, val, upb_msgval_sizeof(UPB_TYPE_STRING));
  3795. return msg;
  3796. }
  3797. size_t upb_msg_str(void *msg, const void *hd, const char *ptr, size_t size,
  3798. const upb_bufhandle *handle) {
  3799. uint32_t ofs = (uintptr_t)hd;
  3800. upb_alloc *alloc = upb_msg_alloc(msg);
  3801. upb_msgval val;
  3802. size_t newsize;
  3803. UPB_UNUSED(handle);
  3804. val = upb_msgval_read(msg, ofs, upb_msgval_sizeof(UPB_TYPE_STRING));
  3805. newsize = val.str.size + size;
  3806. val.str.data = upb_realloc(alloc, (void*)val.str.data, val.str.size, newsize);
  3807. if (!val.str.data) {
  3808. return false;
  3809. }
  3810. memcpy((char*)val.str.data + val.str.size, ptr, size);
  3811. val.str.size = newsize;
  3812. upb_msgval_write(msg, ofs, val, upb_msgval_sizeof(UPB_TYPE_STRING));
  3813. return size;
  3814. }
  3815. static void callback(const void *closure, upb_handlers *h) {
  3816. upb_msgfactory *factory = (upb_msgfactory*)closure;
  3817. const upb_msgdef *md = upb_handlers_msgdef(h);
  3818. const upb_msglayout* layout = upb_msgfactory_getlayout(factory, md);
  3819. upb_msg_field_iter i;
  3820. UPB_UNUSED(factory);
  3821. for(upb_msg_field_begin(&i, md);
  3822. !upb_msg_field_done(&i);
  3823. upb_msg_field_next(&i)) {
  3824. const upb_fielddef *f = upb_msg_iter_field(&i);
  3825. size_t offset = upb_msglayout_offset(layout, f);
  3826. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  3827. upb_handlerattr_sethandlerdata(&attr, (void*)offset);
  3828. if (upb_fielddef_isseq(f)) {
  3829. } else if (upb_fielddef_isstring(f)) {
  3830. upb_handlers_setstartstr(h, f, upb_msg_startstr, &attr);
  3831. upb_handlers_setstring(h, f, upb_msg_str, &attr);
  3832. } else {
  3833. upb_msg_setscalarhandler(
  3834. h, f, offset, upb_msglayout_hasbit(layout, f));
  3835. }
  3836. }
  3837. }
  3838. const upb_handlers *upb_msgfactory_getmergehandlers(upb_msgfactory *f,
  3839. const upb_msgdef *m) {
  3840. upb_msgfactory *mutable_f = (void*)f;
  3841. /* TODO(haberman): properly cache these. */
  3842. const upb_handlers *ret = upb_handlers_newfrozen(m, f, callback, f);
  3843. upb_inttable_push(&mutable_f->mergehandlers, upb_value_constptr(ret));
  3844. return ret;
  3845. }
  3846. const upb_visitorplan *upb_msgfactory_getvisitorplan(upb_msgfactory *f,
  3847. const upb_handlers *h) {
  3848. const upb_msgdef *md = upb_handlers_msgdef(h);
  3849. return (const upb_visitorplan*)upb_msgfactory_getlayout(f, md);
  3850. }
  3851. /** upb_visitor ***************************************************************/
  3852. struct upb_visitor {
  3853. const upb_msglayout *layout;
  3854. upb_sink *sink;
  3855. };
  3856. static upb_selector_t getsel2(const upb_fielddef *f, upb_handlertype_t type) {
  3857. upb_selector_t ret;
  3858. bool ok = upb_handlers_getselector(f, type, &ret);
  3859. UPB_ASSERT(ok);
  3860. return ret;
  3861. }
  3862. static bool upb_visitor_hasfield(const upb_msg *msg, const upb_fielddef *f,
  3863. const upb_msglayout *layout) {
  3864. int field_index = upb_fielddef_index(f);
  3865. if (upb_fielddef_isseq(f)) {
  3866. return upb_msgval_getarr(upb_msg_get(msg, field_index, layout)) != NULL;
  3867. } else if (upb_msgdef_syntax(upb_fielddef_containingtype(f)) ==
  3868. UPB_SYNTAX_PROTO2) {
  3869. return upb_msg_has(msg, field_index, layout);
  3870. } else {
  3871. upb_msgval val = upb_msg_get(msg, field_index, layout);
  3872. switch (upb_fielddef_type(f)) {
  3873. case UPB_TYPE_FLOAT:
  3874. return upb_msgval_getfloat(val) != 0;
  3875. case UPB_TYPE_DOUBLE:
  3876. return upb_msgval_getdouble(val) != 0;
  3877. case UPB_TYPE_BOOL:
  3878. return upb_msgval_getbool(val);
  3879. case UPB_TYPE_ENUM:
  3880. case UPB_TYPE_INT32:
  3881. return upb_msgval_getint32(val) != 0;
  3882. case UPB_TYPE_UINT32:
  3883. return upb_msgval_getuint32(val) != 0;
  3884. case UPB_TYPE_INT64:
  3885. return upb_msgval_getint64(val) != 0;
  3886. case UPB_TYPE_UINT64:
  3887. return upb_msgval_getuint64(val) != 0;
  3888. case UPB_TYPE_STRING:
  3889. case UPB_TYPE_BYTES:
  3890. return upb_msgval_getstr(val).size > 0;
  3891. case UPB_TYPE_MESSAGE:
  3892. return upb_msgval_getmsg(val) != NULL;
  3893. }
  3894. UPB_UNREACHABLE();
  3895. }
  3896. }
  3897. static bool upb_visitor_visitmsg2(const upb_msg *msg,
  3898. const upb_msglayout *layout, upb_sink *sink,
  3899. int depth) {
  3900. const upb_msgdef *md = upb_handlers_msgdef(sink->handlers);
  3901. upb_msg_field_iter i;
  3902. upb_status status;
  3903. upb_sink_startmsg(sink);
  3904. /* Protect against cycles (possible because users may freely reassign message
  3905. * and repeated fields) by imposing a maximum recursion depth. */
  3906. if (depth > ENCODE_MAX_NESTING) {
  3907. return false;
  3908. }
  3909. for (upb_msg_field_begin(&i, md);
  3910. !upb_msg_field_done(&i);
  3911. upb_msg_field_next(&i)) {
  3912. upb_fielddef *f = upb_msg_iter_field(&i);
  3913. upb_msgval val;
  3914. if (!upb_visitor_hasfield(msg, f, layout)) {
  3915. continue;
  3916. }
  3917. val = upb_msg_get(msg, upb_fielddef_index(f), layout);
  3918. if (upb_fielddef_isseq(f)) {
  3919. const upb_array *arr = upb_msgval_getarr(val);
  3920. UPB_ASSERT(arr);
  3921. /* TODO: putary(ary, f, sink, depth);*/
  3922. } else if (upb_fielddef_issubmsg(f)) {
  3923. const upb_map *map = upb_msgval_getmap(val);
  3924. UPB_ASSERT(map);
  3925. /* TODO: putmap(map, f, sink, depth);*/
  3926. } else if (upb_fielddef_isstring(f)) {
  3927. /* TODO putstr(); */
  3928. } else {
  3929. upb_selector_t sel = getsel2(f, upb_handlers_getprimitivehandlertype(f));
  3930. UPB_ASSERT(upb_fielddef_isprimitive(f));
  3931. switch (upb_fielddef_type(f)) {
  3932. case UPB_TYPE_FLOAT:
  3933. CHECK_TRUE(upb_sink_putfloat(sink, sel, upb_msgval_getfloat(val)));
  3934. break;
  3935. case UPB_TYPE_DOUBLE:
  3936. CHECK_TRUE(upb_sink_putdouble(sink, sel, upb_msgval_getdouble(val)));
  3937. break;
  3938. case UPB_TYPE_BOOL:
  3939. CHECK_TRUE(upb_sink_putbool(sink, sel, upb_msgval_getbool(val)));
  3940. break;
  3941. case UPB_TYPE_ENUM:
  3942. case UPB_TYPE_INT32:
  3943. CHECK_TRUE(upb_sink_putint32(sink, sel, upb_msgval_getint32(val)));
  3944. break;
  3945. case UPB_TYPE_UINT32:
  3946. CHECK_TRUE(upb_sink_putuint32(sink, sel, upb_msgval_getuint32(val)));
  3947. break;
  3948. case UPB_TYPE_INT64:
  3949. CHECK_TRUE(upb_sink_putint64(sink, sel, upb_msgval_getint64(val)));
  3950. break;
  3951. case UPB_TYPE_UINT64:
  3952. CHECK_TRUE(upb_sink_putuint64(sink, sel, upb_msgval_getuint64(val)));
  3953. break;
  3954. case UPB_TYPE_STRING:
  3955. case UPB_TYPE_BYTES:
  3956. case UPB_TYPE_MESSAGE:
  3957. UPB_UNREACHABLE();
  3958. }
  3959. }
  3960. }
  3961. upb_sink_endmsg(sink, &status);
  3962. return true;
  3963. }
  3964. upb_visitor *upb_visitor_create(upb_env *e, const upb_visitorplan *vp,
  3965. upb_sink *output) {
  3966. upb_visitor *visitor = upb_env_malloc(e, sizeof(*visitor));
  3967. visitor->layout = (const upb_msglayout*)vp;
  3968. visitor->sink = output;
  3969. return visitor;
  3970. }
  3971. bool upb_visitor_visitmsg(upb_visitor *visitor, const upb_msg *msg) {
  3972. return upb_visitor_visitmsg2(msg, visitor->layout, visitor->sink, 0);
  3973. }
  3974. /** upb_msg *******************************************************************/
  3975. /* If we always read/write as a consistent type to each address, this shouldn't
  3976. * violate aliasing.
  3977. */
  3978. #define DEREF(msg, ofs, type) *PTR_AT(msg, ofs, type)
  3979. /* Internal members of a upb_msg. We can change this without breaking binary
  3980. * compatibility. We put these before the user's data. The user's upb_msg*
  3981. * points after the upb_msg_internal. */
  3982. /* Used when a message is not extendable. */
  3983. typedef struct {
  3984. /* TODO(haberman): add unknown fields. */
  3985. upb_alloc *alloc;
  3986. } upb_msg_internal;
  3987. /* Used when a message is extendable. */
  3988. typedef struct {
  3989. upb_inttable *extdict;
  3990. upb_msg_internal base;
  3991. } upb_msg_internal_withext;
  3992. static int upb_msg_internalsize(const upb_msglayout *l) {
  3993. return sizeof(upb_msg_internal) - l->data.extendable * sizeof(void*);
  3994. }
  3995. static upb_msg_internal *upb_msg_getinternal(upb_msg *msg) {
  3996. return VOIDPTR_AT(msg, -sizeof(upb_msg_internal));
  3997. }
  3998. static const upb_msg_internal *upb_msg_getinternal_const(const upb_msg *msg) {
  3999. return VOIDPTR_AT(msg, -sizeof(upb_msg_internal));
  4000. }
  4001. static upb_msg_internal_withext *upb_msg_getinternalwithext(
  4002. upb_msg *msg, const upb_msglayout *l) {
  4003. UPB_ASSERT(l->data.extendable);
  4004. return VOIDPTR_AT(msg, -sizeof(upb_msg_internal_withext));
  4005. }
  4006. static const upb_msglayout_fieldinit_v1 *upb_msg_checkfield(
  4007. int field_index, const upb_msglayout *l) {
  4008. UPB_ASSERT(field_index >= 0 && field_index < l->data.field_count);
  4009. return &l->data.fields[field_index];
  4010. }
  4011. static bool upb_msg_inoneof(const upb_msglayout_fieldinit_v1 *field) {
  4012. return field->oneof_index != UPB_NOT_IN_ONEOF;
  4013. }
  4014. static uint32_t *upb_msg_oneofcase(const upb_msg *msg, int field_index,
  4015. const upb_msglayout *l) {
  4016. const upb_msglayout_fieldinit_v1 *field = upb_msg_checkfield(field_index, l);
  4017. UPB_ASSERT(upb_msg_inoneof(field));
  4018. return PTR_AT(msg, l->data.oneofs[field->oneof_index].case_offset, uint32_t);
  4019. }
  4020. size_t upb_msg_sizeof(const upb_msglayout *l) {
  4021. return l->data.size + upb_msg_internalsize(l);
  4022. }
  4023. upb_msg *upb_msg_init(void *mem, const upb_msglayout *l, upb_alloc *a) {
  4024. upb_msg *msg = VOIDPTR_AT(mem, upb_msg_internalsize(l));
  4025. /* Initialize normal members. */
  4026. if (l->data.default_msg) {
  4027. memcpy(msg, l->data.default_msg, l->data.size);
  4028. } else {
  4029. memset(msg, 0, l->data.size);
  4030. }
  4031. /* Initialize internal members. */
  4032. upb_msg_getinternal(msg)->alloc = a;
  4033. if (l->data.extendable) {
  4034. upb_msg_getinternalwithext(msg, l)->extdict = NULL;
  4035. }
  4036. return msg;
  4037. }
  4038. void *upb_msg_uninit(upb_msg *msg, const upb_msglayout *l) {
  4039. if (l->data.extendable) {
  4040. upb_inttable *ext_dict = upb_msg_getinternalwithext(msg, l)->extdict;
  4041. if (ext_dict) {
  4042. upb_inttable_uninit2(ext_dict, upb_msg_alloc(msg));
  4043. upb_free(upb_msg_alloc(msg), ext_dict);
  4044. }
  4045. }
  4046. return VOIDPTR_AT(msg, -upb_msg_internalsize(l));
  4047. }
  4048. upb_msg *upb_msg_new(const upb_msglayout *l, upb_alloc *a) {
  4049. void *mem = upb_malloc(a, upb_msg_sizeof(l));
  4050. return mem ? upb_msg_init(mem, l, a) : NULL;
  4051. }
  4052. void upb_msg_free(upb_msg *msg, const upb_msglayout *l) {
  4053. upb_free(upb_msg_alloc(msg), upb_msg_uninit(msg, l));
  4054. }
  4055. upb_alloc *upb_msg_alloc(const upb_msg *msg) {
  4056. return upb_msg_getinternal_const(msg)->alloc;
  4057. }
  4058. bool upb_msg_has(const upb_msg *msg,
  4059. int field_index,
  4060. const upb_msglayout *l) {
  4061. const upb_msglayout_fieldinit_v1 *field = upb_msg_checkfield(field_index, l);
  4062. UPB_ASSERT(l->data.is_proto2);
  4063. if (upb_msg_inoneof(field)) {
  4064. /* Oneofs are set when the oneof number is set to this field. */
  4065. return *upb_msg_oneofcase(msg, field_index, l) == field->number;
  4066. } else {
  4067. /* Other fields are set when their hasbit is set. */
  4068. uint32_t hasbit = l->data.fields[field_index].hasbit;
  4069. return DEREF(msg, hasbit / 8, char) | (1 << (hasbit % 8));
  4070. }
  4071. }
  4072. upb_msgval upb_msg_get(const upb_msg *msg, int field_index,
  4073. const upb_msglayout *l) {
  4074. const upb_msglayout_fieldinit_v1 *field = upb_msg_checkfield(field_index, l);
  4075. int size = upb_msg_fieldsize(field);
  4076. if (upb_msg_inoneof(field)) {
  4077. if (*upb_msg_oneofcase(msg, field_index, l) == field->number) {
  4078. size_t ofs = l->data.oneofs[field->oneof_index].data_offset;
  4079. return upb_msgval_read(msg, ofs, size);
  4080. } else {
  4081. /* Return default. */
  4082. return upb_msgval_read(l->data.default_msg, field->offset, size);
  4083. }
  4084. } else {
  4085. return upb_msgval_read(msg, field->offset, size);
  4086. }
  4087. }
  4088. void upb_msg_set(upb_msg *msg, int field_index, upb_msgval val,
  4089. const upb_msglayout *l) {
  4090. const upb_msglayout_fieldinit_v1 *field = upb_msg_checkfield(field_index, l);
  4091. int size = upb_msg_fieldsize(field);
  4092. if (upb_msg_inoneof(field)) {
  4093. size_t ofs = l->data.oneofs[field->oneof_index].data_offset;
  4094. *upb_msg_oneofcase(msg, field_index, l) = field->number;
  4095. upb_msgval_write(msg, ofs, val, size);
  4096. } else {
  4097. upb_msgval_write(msg, field->offset, val, size);
  4098. }
  4099. }
  4100. /** upb_array *****************************************************************/
  4101. #define DEREF_ARR(arr, i, type) ((type*)arr->data)[i]
  4102. size_t upb_array_sizeof(upb_fieldtype_t type) {
  4103. UPB_UNUSED(type);
  4104. return sizeof(upb_array);
  4105. }
  4106. void upb_array_init(upb_array *arr, upb_fieldtype_t type, upb_alloc *alloc) {
  4107. arr->type = type;
  4108. arr->data = NULL;
  4109. arr->len = 0;
  4110. arr->size = 0;
  4111. arr->element_size = upb_msgval_sizeof(type);
  4112. arr->alloc = alloc;
  4113. }
  4114. void upb_array_uninit(upb_array *arr) {
  4115. upb_free(arr->alloc, arr->data);
  4116. }
  4117. upb_array *upb_array_new(upb_fieldtype_t type, upb_alloc *a) {
  4118. upb_array *ret = upb_malloc(a, upb_array_sizeof(type));
  4119. if (ret) {
  4120. upb_array_init(ret, type, a);
  4121. }
  4122. return ret;
  4123. }
  4124. void upb_array_free(upb_array *arr) {
  4125. upb_array_uninit(arr);
  4126. upb_free(arr->alloc, arr);
  4127. }
  4128. size_t upb_array_size(const upb_array *arr) {
  4129. return arr->len;
  4130. }
  4131. upb_fieldtype_t upb_array_type(const upb_array *arr) {
  4132. return arr->type;
  4133. }
  4134. upb_msgval upb_array_get(const upb_array *arr, size_t i) {
  4135. UPB_ASSERT(i < arr->len);
  4136. return upb_msgval_read(arr->data, i * arr->element_size, arr->element_size);
  4137. }
  4138. bool upb_array_set(upb_array *arr, size_t i, upb_msgval val) {
  4139. UPB_ASSERT(i <= arr->len);
  4140. if (i == arr->len) {
  4141. /* Extending the array. */
  4142. if (i == arr->size) {
  4143. /* Need to reallocate. */
  4144. size_t new_size = UPB_MAX(arr->size * 2, 8);
  4145. size_t new_bytes = new_size * arr->element_size;
  4146. size_t old_bytes = arr->size * arr->element_size;
  4147. upb_msgval *new_data =
  4148. upb_realloc(arr->alloc, arr->data, old_bytes, new_bytes);
  4149. if (!new_data) {
  4150. return false;
  4151. }
  4152. arr->data = new_data;
  4153. arr->size = new_size;
  4154. }
  4155. arr->len = i + 1;
  4156. }
  4157. upb_msgval_write(arr->data, i * arr->element_size, val, arr->element_size);
  4158. return true;
  4159. }
  4160. /** upb_map *******************************************************************/
  4161. struct upb_map {
  4162. upb_fieldtype_t key_type;
  4163. upb_fieldtype_t val_type;
  4164. /* We may want to optimize this to use inttable where possible, for greater
  4165. * efficiency and lower memory footprint. */
  4166. upb_strtable strtab;
  4167. upb_alloc *alloc;
  4168. };
  4169. static void upb_map_tokey(upb_fieldtype_t type, upb_msgval *key,
  4170. const char **out_key, size_t *out_len) {
  4171. switch (type) {
  4172. case UPB_TYPE_STRING:
  4173. /* Point to string data of the input key. */
  4174. *out_key = key->str.data;
  4175. *out_len = key->str.size;
  4176. return;
  4177. case UPB_TYPE_BOOL:
  4178. case UPB_TYPE_INT32:
  4179. case UPB_TYPE_UINT32:
  4180. case UPB_TYPE_INT64:
  4181. case UPB_TYPE_UINT64:
  4182. /* Point to the key itself. XXX: big-endian. */
  4183. *out_key = (const char*)key;
  4184. *out_len = upb_msgval_sizeof(type);
  4185. return;
  4186. case UPB_TYPE_BYTES:
  4187. case UPB_TYPE_DOUBLE:
  4188. case UPB_TYPE_ENUM:
  4189. case UPB_TYPE_FLOAT:
  4190. case UPB_TYPE_MESSAGE:
  4191. break; /* Cannot be a map key. */
  4192. }
  4193. UPB_UNREACHABLE();
  4194. }
  4195. static upb_msgval upb_map_fromkey(upb_fieldtype_t type, const char *key,
  4196. size_t len) {
  4197. switch (type) {
  4198. case UPB_TYPE_STRING:
  4199. return upb_msgval_makestr(key, len);
  4200. case UPB_TYPE_BOOL:
  4201. case UPB_TYPE_INT32:
  4202. case UPB_TYPE_UINT32:
  4203. case UPB_TYPE_INT64:
  4204. case UPB_TYPE_UINT64:
  4205. return upb_msgval_read(key, 0, upb_msgval_sizeof(type));
  4206. case UPB_TYPE_BYTES:
  4207. case UPB_TYPE_DOUBLE:
  4208. case UPB_TYPE_ENUM:
  4209. case UPB_TYPE_FLOAT:
  4210. case UPB_TYPE_MESSAGE:
  4211. break; /* Cannot be a map key. */
  4212. }
  4213. UPB_UNREACHABLE();
  4214. }
  4215. size_t upb_map_sizeof(upb_fieldtype_t ktype, upb_fieldtype_t vtype) {
  4216. /* Size does not currently depend on key/value type. */
  4217. UPB_UNUSED(ktype);
  4218. UPB_UNUSED(vtype);
  4219. return sizeof(upb_map);
  4220. }
  4221. bool upb_map_init(upb_map *map, upb_fieldtype_t ktype, upb_fieldtype_t vtype,
  4222. upb_alloc *a) {
  4223. upb_ctype_t vtabtype = upb_fieldtotabtype(vtype);
  4224. UPB_ASSERT(upb_fieldtype_mapkeyok(ktype));
  4225. map->key_type = ktype;
  4226. map->val_type = vtype;
  4227. map->alloc = a;
  4228. if (!upb_strtable_init2(&map->strtab, vtabtype, a)) {
  4229. return false;
  4230. }
  4231. return true;
  4232. }
  4233. void upb_map_uninit(upb_map *map) {
  4234. upb_strtable_uninit2(&map->strtab, map->alloc);
  4235. }
  4236. upb_map *upb_map_new(upb_fieldtype_t ktype, upb_fieldtype_t vtype,
  4237. upb_alloc *a) {
  4238. upb_map *map = upb_malloc(a, upb_map_sizeof(ktype, vtype));
  4239. if (!map) {
  4240. return NULL;
  4241. }
  4242. if (!upb_map_init(map, ktype, vtype, a)) {
  4243. return NULL;
  4244. }
  4245. return map;
  4246. }
  4247. void upb_map_free(upb_map *map) {
  4248. upb_map_uninit(map);
  4249. upb_free(map->alloc, map);
  4250. }
  4251. size_t upb_map_size(const upb_map *map) {
  4252. return upb_strtable_count(&map->strtab);
  4253. }
  4254. upb_fieldtype_t upb_map_keytype(const upb_map *map) {
  4255. return map->key_type;
  4256. }
  4257. upb_fieldtype_t upb_map_valuetype(const upb_map *map) {
  4258. return map->val_type;
  4259. }
  4260. bool upb_map_get(const upb_map *map, upb_msgval key, upb_msgval *val) {
  4261. upb_value tabval;
  4262. const char *key_str;
  4263. size_t key_len;
  4264. bool ret;
  4265. upb_map_tokey(map->key_type, &key, &key_str, &key_len);
  4266. ret = upb_strtable_lookup2(&map->strtab, key_str, key_len, &tabval);
  4267. if (ret) {
  4268. memcpy(val, &tabval, sizeof(tabval));
  4269. }
  4270. return ret;
  4271. }
  4272. bool upb_map_set(upb_map *map, upb_msgval key, upb_msgval val,
  4273. upb_msgval *removed) {
  4274. const char *key_str;
  4275. size_t key_len;
  4276. upb_value tabval = upb_toval(val);
  4277. upb_value removedtabval;
  4278. upb_alloc *a = map->alloc;
  4279. upb_map_tokey(map->key_type, &key, &key_str, &key_len);
  4280. /* TODO(haberman): add overwrite operation to minimize number of lookups. */
  4281. if (upb_strtable_lookup2(&map->strtab, key_str, key_len, NULL)) {
  4282. upb_strtable_remove3(&map->strtab, key_str, key_len, &removedtabval, a);
  4283. memcpy(&removed, &removedtabval, sizeof(removed));
  4284. }
  4285. return upb_strtable_insert3(&map->strtab, key_str, key_len, tabval, a);
  4286. }
  4287. bool upb_map_del(upb_map *map, upb_msgval key) {
  4288. const char *key_str;
  4289. size_t key_len;
  4290. upb_alloc *a = map->alloc;
  4291. upb_map_tokey(map->key_type, &key, &key_str, &key_len);
  4292. return upb_strtable_remove3(&map->strtab, key_str, key_len, NULL, a);
  4293. }
  4294. /** upb_mapiter ***************************************************************/
  4295. struct upb_mapiter {
  4296. upb_strtable_iter iter;
  4297. upb_fieldtype_t key_type;
  4298. };
  4299. size_t upb_mapiter_sizeof() {
  4300. return sizeof(upb_mapiter);
  4301. }
  4302. void upb_mapiter_begin(upb_mapiter *i, const upb_map *map) {
  4303. upb_strtable_begin(&i->iter, &map->strtab);
  4304. i->key_type = map->key_type;
  4305. }
  4306. upb_mapiter *upb_mapiter_new(const upb_map *t, upb_alloc *a) {
  4307. upb_mapiter *ret = upb_malloc(a, upb_mapiter_sizeof());
  4308. if (!ret) {
  4309. return NULL;
  4310. }
  4311. upb_mapiter_begin(ret, t);
  4312. return ret;
  4313. }
  4314. void upb_mapiter_free(upb_mapiter *i, upb_alloc *a) {
  4315. upb_free(a, i);
  4316. }
  4317. void upb_mapiter_next(upb_mapiter *i) {
  4318. upb_strtable_next(&i->iter);
  4319. }
  4320. bool upb_mapiter_done(const upb_mapiter *i) {
  4321. return upb_strtable_done(&i->iter);
  4322. }
  4323. upb_msgval upb_mapiter_key(const upb_mapiter *i) {
  4324. return upb_map_fromkey(i->key_type, upb_strtable_iter_key(&i->iter),
  4325. upb_strtable_iter_keylength(&i->iter));
  4326. }
  4327. upb_msgval upb_mapiter_value(const upb_mapiter *i) {
  4328. return upb_msgval_fromval(upb_strtable_iter_value(&i->iter));
  4329. }
  4330. void upb_mapiter_setdone(upb_mapiter *i) {
  4331. upb_strtable_iter_setdone(&i->iter);
  4332. }
  4333. bool upb_mapiter_isequal(const upb_mapiter *i1, const upb_mapiter *i2) {
  4334. return upb_strtable_iter_isequal(&i1->iter, &i2->iter);
  4335. }
  4336. /** Handlers for upb_msg ******************************************************/
  4337. typedef struct {
  4338. size_t offset;
  4339. int32_t hasbit;
  4340. } upb_msg_handlerdata;
  4341. /* Fallback implementation if the handler is not specialized by the producer. */
  4342. #define MSG_WRITER(type, ctype) \
  4343. bool upb_msg_set ## type (void *c, const void *hd, ctype val) { \
  4344. uint8_t *m = c; \
  4345. const upb_msg_handlerdata *d = hd; \
  4346. if (d->hasbit > 0) \
  4347. *(uint8_t*)&m[d->hasbit / 8] |= 1 << (d->hasbit % 8); \
  4348. *(ctype*)&m[d->offset] = val; \
  4349. return true; \
  4350. } \
  4351. MSG_WRITER(double, double)
  4352. MSG_WRITER(float, float)
  4353. MSG_WRITER(int32, int32_t)
  4354. MSG_WRITER(int64, int64_t)
  4355. MSG_WRITER(uint32, uint32_t)
  4356. MSG_WRITER(uint64, uint64_t)
  4357. MSG_WRITER(bool, bool)
  4358. bool upb_msg_setscalarhandler(upb_handlers *h, const upb_fielddef *f,
  4359. size_t offset, int32_t hasbit) {
  4360. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  4361. bool ok;
  4362. upb_msg_handlerdata *d = upb_gmalloc(sizeof(*d));
  4363. if (!d) return false;
  4364. d->offset = offset;
  4365. d->hasbit = hasbit;
  4366. upb_handlerattr_sethandlerdata(&attr, d);
  4367. upb_handlerattr_setalwaysok(&attr, true);
  4368. upb_handlers_addcleanup(h, d, upb_gfree);
  4369. #define TYPE(u, l) \
  4370. case UPB_TYPE_##u: \
  4371. ok = upb_handlers_set##l(h, f, upb_msg_set##l, &attr); break;
  4372. ok = false;
  4373. switch (upb_fielddef_type(f)) {
  4374. TYPE(INT64, int64);
  4375. TYPE(INT32, int32);
  4376. TYPE(ENUM, int32);
  4377. TYPE(UINT64, uint64);
  4378. TYPE(UINT32, uint32);
  4379. TYPE(DOUBLE, double);
  4380. TYPE(FLOAT, float);
  4381. TYPE(BOOL, bool);
  4382. default: UPB_ASSERT(false); break;
  4383. }
  4384. #undef TYPE
  4385. upb_handlerattr_uninit(&attr);
  4386. return ok;
  4387. }
  4388. bool upb_msg_getscalarhandlerdata(const upb_handlers *h,
  4389. upb_selector_t s,
  4390. upb_fieldtype_t *type,
  4391. size_t *offset,
  4392. int32_t *hasbit) {
  4393. const upb_msg_handlerdata *d;
  4394. upb_func *f = upb_handlers_gethandler(h, s);
  4395. if ((upb_int64_handlerfunc*)f == upb_msg_setint64) {
  4396. *type = UPB_TYPE_INT64;
  4397. } else if ((upb_int32_handlerfunc*)f == upb_msg_setint32) {
  4398. *type = UPB_TYPE_INT32;
  4399. } else if ((upb_uint64_handlerfunc*)f == upb_msg_setuint64) {
  4400. *type = UPB_TYPE_UINT64;
  4401. } else if ((upb_uint32_handlerfunc*)f == upb_msg_setuint32) {
  4402. *type = UPB_TYPE_UINT32;
  4403. } else if ((upb_double_handlerfunc*)f == upb_msg_setdouble) {
  4404. *type = UPB_TYPE_DOUBLE;
  4405. } else if ((upb_float_handlerfunc*)f == upb_msg_setfloat) {
  4406. *type = UPB_TYPE_FLOAT;
  4407. } else if ((upb_bool_handlerfunc*)f == upb_msg_setbool) {
  4408. *type = UPB_TYPE_BOOL;
  4409. } else {
  4410. return false;
  4411. }
  4412. d = upb_handlers_gethandlerdata(h, s);
  4413. *offset = d->offset;
  4414. *hasbit = d->hasbit;
  4415. return true;
  4416. }
  4417. /*
  4418. ** upb::RefCounted Implementation
  4419. **
  4420. ** Our key invariants are:
  4421. ** 1. reference cycles never span groups
  4422. ** 2. for ref2(to, from), we increment to's count iff group(from) != group(to)
  4423. **
  4424. ** The previous two are how we avoid leaking cycles. Other important
  4425. ** invariants are:
  4426. ** 3. for mutable objects "from" and "to", if there exists a ref2(to, from)
  4427. ** this implies group(from) == group(to). (In practice, what we implement
  4428. ** is even stronger; "from" and "to" will share a group if there has *ever*
  4429. ** been a ref2(to, from), but all that is necessary for correctness is the
  4430. ** weaker one).
  4431. ** 4. mutable and immutable objects are never in the same group.
  4432. */
  4433. #include <setjmp.h>
  4434. static void freeobj(upb_refcounted *o);
  4435. const char untracked_val;
  4436. const void *UPB_UNTRACKED_REF = &untracked_val;
  4437. /* arch-specific atomic primitives *******************************************/
  4438. #ifdef UPB_THREAD_UNSAFE /*---------------------------------------------------*/
  4439. static void atomic_inc(uint32_t *a) { (*a)++; }
  4440. static bool atomic_dec(uint32_t *a) { return --(*a) == 0; }
  4441. #elif defined(__GNUC__) || defined(__clang__) /*------------------------------*/
  4442. static void atomic_inc(uint32_t *a) { __sync_fetch_and_add(a, 1); }
  4443. static bool atomic_dec(uint32_t *a) { return __sync_sub_and_fetch(a, 1) == 0; }
  4444. #elif defined(WIN32) /*-------------------------------------------------------*/
  4445. #include <Windows.h>
  4446. static void atomic_inc(upb_atomic_t *a) { InterlockedIncrement(&a->val); }
  4447. static bool atomic_dec(upb_atomic_t *a) {
  4448. return InterlockedDecrement(&a->val) == 0;
  4449. }
  4450. #else
  4451. #error Atomic primitives not defined for your platform/CPU. \
  4452. Implement them or compile with UPB_THREAD_UNSAFE.
  4453. #endif
  4454. /* All static objects point to this refcount.
  4455. * It is special-cased in ref/unref below. */
  4456. uint32_t static_refcount = -1;
  4457. /* We can avoid atomic ops for statically-declared objects.
  4458. * This is a minor optimization but nice since we can avoid degrading under
  4459. * contention in this case. */
  4460. static void refgroup(uint32_t *group) {
  4461. if (group != &static_refcount)
  4462. atomic_inc(group);
  4463. }
  4464. static bool unrefgroup(uint32_t *group) {
  4465. if (group == &static_refcount) {
  4466. return false;
  4467. } else {
  4468. return atomic_dec(group);
  4469. }
  4470. }
  4471. /* Reference tracking (debug only) ********************************************/
  4472. #ifdef UPB_DEBUG_REFS
  4473. #ifdef UPB_THREAD_UNSAFE
  4474. static void upb_lock() {}
  4475. static void upb_unlock() {}
  4476. #else
  4477. /* User must define functions that lock/unlock a global mutex and link this
  4478. * file against them. */
  4479. void upb_lock();
  4480. void upb_unlock();
  4481. #endif
  4482. /* UPB_DEBUG_REFS mode counts on being able to malloc() memory in some
  4483. * code-paths that can normally never fail, like upb_refcounted_ref(). Since
  4484. * we have no way to propagage out-of-memory errors back to the user, and since
  4485. * these errors can only occur in UPB_DEBUG_REFS mode, we use an allocator that
  4486. * immediately aborts on failure (avoiding the global allocator, which might
  4487. * inject failures). */
  4488. #include <stdlib.h>
  4489. static void *upb_debugrefs_allocfunc(upb_alloc *alloc, void *ptr,
  4490. size_t oldsize, size_t size) {
  4491. UPB_UNUSED(alloc);
  4492. UPB_UNUSED(oldsize);
  4493. if (size == 0) {
  4494. free(ptr);
  4495. return NULL;
  4496. } else {
  4497. void *ret = realloc(ptr, size);
  4498. if (!ret) {
  4499. abort();
  4500. }
  4501. return ret;
  4502. }
  4503. }
  4504. upb_alloc upb_alloc_debugrefs = {&upb_debugrefs_allocfunc};
  4505. typedef struct {
  4506. int count; /* How many refs there are (duplicates only allowed for ref2). */
  4507. bool is_ref2;
  4508. } trackedref;
  4509. static trackedref *trackedref_new(bool is_ref2) {
  4510. trackedref *ret = upb_malloc(&upb_alloc_debugrefs, sizeof(*ret));
  4511. ret->count = 1;
  4512. ret->is_ref2 = is_ref2;
  4513. return ret;
  4514. }
  4515. static void track(const upb_refcounted *r, const void *owner, bool ref2) {
  4516. upb_value v;
  4517. UPB_ASSERT(owner);
  4518. if (owner == UPB_UNTRACKED_REF) return;
  4519. upb_lock();
  4520. if (upb_inttable_lookupptr(r->refs, owner, &v)) {
  4521. trackedref *ref = upb_value_getptr(v);
  4522. /* Since we allow multiple ref2's for the same to/from pair without
  4523. * allocating separate memory for each one, we lose the fine-grained
  4524. * tracking behavior we get with regular refs. Since ref2s only happen
  4525. * inside upb, we'll accept this limitation until/unless there is a really
  4526. * difficult upb-internal bug that can't be figured out without it. */
  4527. UPB_ASSERT(ref2);
  4528. UPB_ASSERT(ref->is_ref2);
  4529. ref->count++;
  4530. } else {
  4531. trackedref *ref = trackedref_new(ref2);
  4532. upb_inttable_insertptr2(r->refs, owner, upb_value_ptr(ref),
  4533. &upb_alloc_debugrefs);
  4534. if (ref2) {
  4535. /* We know this cast is safe when it is a ref2, because it's coming from
  4536. * another refcounted object. */
  4537. const upb_refcounted *from = owner;
  4538. UPB_ASSERT(!upb_inttable_lookupptr(from->ref2s, r, NULL));
  4539. upb_inttable_insertptr2(from->ref2s, r, upb_value_ptr(NULL),
  4540. &upb_alloc_debugrefs);
  4541. }
  4542. }
  4543. upb_unlock();
  4544. }
  4545. static void untrack(const upb_refcounted *r, const void *owner, bool ref2) {
  4546. upb_value v;
  4547. bool found;
  4548. trackedref *ref;
  4549. UPB_ASSERT(owner);
  4550. if (owner == UPB_UNTRACKED_REF) return;
  4551. upb_lock();
  4552. found = upb_inttable_lookupptr(r->refs, owner, &v);
  4553. /* This assert will fail if an owner attempts to release a ref it didn't have. */
  4554. UPB_ASSERT(found);
  4555. ref = upb_value_getptr(v);
  4556. UPB_ASSERT(ref->is_ref2 == ref2);
  4557. if (--ref->count == 0) {
  4558. free(ref);
  4559. upb_inttable_removeptr(r->refs, owner, NULL);
  4560. if (ref2) {
  4561. /* We know this cast is safe when it is a ref2, because it's coming from
  4562. * another refcounted object. */
  4563. const upb_refcounted *from = owner;
  4564. bool removed = upb_inttable_removeptr(from->ref2s, r, NULL);
  4565. UPB_ASSERT(removed);
  4566. }
  4567. }
  4568. upb_unlock();
  4569. }
  4570. static void checkref(const upb_refcounted *r, const void *owner, bool ref2) {
  4571. upb_value v;
  4572. bool found;
  4573. trackedref *ref;
  4574. upb_lock();
  4575. found = upb_inttable_lookupptr(r->refs, owner, &v);
  4576. UPB_ASSERT(found);
  4577. ref = upb_value_getptr(v);
  4578. UPB_ASSERT(ref->is_ref2 == ref2);
  4579. upb_unlock();
  4580. }
  4581. /* Populates the given UPB_CTYPE_INT32 inttable with counts of ref2's that
  4582. * originate from the given owner. */
  4583. static void getref2s(const upb_refcounted *owner, upb_inttable *tab) {
  4584. upb_inttable_iter i;
  4585. upb_lock();
  4586. upb_inttable_begin(&i, owner->ref2s);
  4587. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  4588. upb_value v;
  4589. upb_value count;
  4590. trackedref *ref;
  4591. bool found;
  4592. upb_refcounted *to = (upb_refcounted*)upb_inttable_iter_key(&i);
  4593. /* To get the count we need to look in the target's table. */
  4594. found = upb_inttable_lookupptr(to->refs, owner, &v);
  4595. UPB_ASSERT(found);
  4596. ref = upb_value_getptr(v);
  4597. count = upb_value_int32(ref->count);
  4598. upb_inttable_insertptr2(tab, to, count, &upb_alloc_debugrefs);
  4599. }
  4600. upb_unlock();
  4601. }
  4602. typedef struct {
  4603. upb_inttable ref2;
  4604. const upb_refcounted *obj;
  4605. } check_state;
  4606. static void visit_check(const upb_refcounted *obj, const upb_refcounted *subobj,
  4607. void *closure) {
  4608. check_state *s = closure;
  4609. upb_inttable *ref2 = &s->ref2;
  4610. upb_value v;
  4611. bool removed;
  4612. int32_t newcount;
  4613. UPB_ASSERT(obj == s->obj);
  4614. UPB_ASSERT(subobj);
  4615. removed = upb_inttable_removeptr(ref2, subobj, &v);
  4616. /* The following assertion will fail if the visit() function visits a subobj
  4617. * that it did not have a ref2 on, or visits the same subobj too many times. */
  4618. UPB_ASSERT(removed);
  4619. newcount = upb_value_getint32(v) - 1;
  4620. if (newcount > 0) {
  4621. upb_inttable_insert2(ref2, (uintptr_t)subobj, upb_value_int32(newcount),
  4622. &upb_alloc_debugrefs);
  4623. }
  4624. }
  4625. static void visit(const upb_refcounted *r, upb_refcounted_visit *v,
  4626. void *closure) {
  4627. /* In DEBUG_REFS mode we know what existing ref2 refs there are, so we know
  4628. * exactly the set of nodes that visit() should visit. So we verify visit()'s
  4629. * correctness here. */
  4630. check_state state;
  4631. state.obj = r;
  4632. upb_inttable_init2(&state.ref2, UPB_CTYPE_INT32, &upb_alloc_debugrefs);
  4633. getref2s(r, &state.ref2);
  4634. /* This should visit any children in the ref2 table. */
  4635. if (r->vtbl->visit) r->vtbl->visit(r, visit_check, &state);
  4636. /* This assertion will fail if the visit() function missed any children. */
  4637. UPB_ASSERT(upb_inttable_count(&state.ref2) == 0);
  4638. upb_inttable_uninit2(&state.ref2, &upb_alloc_debugrefs);
  4639. if (r->vtbl->visit) r->vtbl->visit(r, v, closure);
  4640. }
  4641. static void trackinit(upb_refcounted *r) {
  4642. r->refs = upb_malloc(&upb_alloc_debugrefs, sizeof(*r->refs));
  4643. r->ref2s = upb_malloc(&upb_alloc_debugrefs, sizeof(*r->ref2s));
  4644. upb_inttable_init2(r->refs, UPB_CTYPE_PTR, &upb_alloc_debugrefs);
  4645. upb_inttable_init2(r->ref2s, UPB_CTYPE_PTR, &upb_alloc_debugrefs);
  4646. }
  4647. static void trackfree(const upb_refcounted *r) {
  4648. upb_inttable_uninit2(r->refs, &upb_alloc_debugrefs);
  4649. upb_inttable_uninit2(r->ref2s, &upb_alloc_debugrefs);
  4650. upb_free(&upb_alloc_debugrefs, r->refs);
  4651. upb_free(&upb_alloc_debugrefs, r->ref2s);
  4652. }
  4653. #else
  4654. static void track(const upb_refcounted *r, const void *owner, bool ref2) {
  4655. UPB_UNUSED(r);
  4656. UPB_UNUSED(owner);
  4657. UPB_UNUSED(ref2);
  4658. }
  4659. static void untrack(const upb_refcounted *r, const void *owner, bool ref2) {
  4660. UPB_UNUSED(r);
  4661. UPB_UNUSED(owner);
  4662. UPB_UNUSED(ref2);
  4663. }
  4664. static void checkref(const upb_refcounted *r, const void *owner, bool ref2) {
  4665. UPB_UNUSED(r);
  4666. UPB_UNUSED(owner);
  4667. UPB_UNUSED(ref2);
  4668. }
  4669. static void trackinit(upb_refcounted *r) {
  4670. UPB_UNUSED(r);
  4671. }
  4672. static void trackfree(const upb_refcounted *r) {
  4673. UPB_UNUSED(r);
  4674. }
  4675. static void visit(const upb_refcounted *r, upb_refcounted_visit *v,
  4676. void *closure) {
  4677. if (r->vtbl->visit) r->vtbl->visit(r, v, closure);
  4678. }
  4679. #endif /* UPB_DEBUG_REFS */
  4680. /* freeze() *******************************************************************/
  4681. /* The freeze() operation is by far the most complicated part of this scheme.
  4682. * We compute strongly-connected components and then mutate the graph such that
  4683. * we preserve the invariants documented at the top of this file. And we must
  4684. * handle out-of-memory errors gracefully (without leaving the graph
  4685. * inconsistent), which adds to the fun. */
  4686. /* The state used by the freeze operation (shared across many functions). */
  4687. typedef struct {
  4688. int depth;
  4689. int maxdepth;
  4690. uint64_t index;
  4691. /* Maps upb_refcounted* -> attributes (color, etc). attr layout varies by
  4692. * color. */
  4693. upb_inttable objattr;
  4694. upb_inttable stack; /* stack of upb_refcounted* for Tarjan's algorithm. */
  4695. upb_inttable groups; /* array of uint32_t*, malloc'd refcounts for new groups */
  4696. upb_status *status;
  4697. jmp_buf err;
  4698. } tarjan;
  4699. static void release_ref2(const upb_refcounted *obj,
  4700. const upb_refcounted *subobj,
  4701. void *closure);
  4702. /* Node attributes -----------------------------------------------------------*/
  4703. /* After our analysis phase all nodes will be either GRAY or WHITE. */
  4704. typedef enum {
  4705. BLACK = 0, /* Object has not been seen. */
  4706. GRAY, /* Object has been found via a refgroup but may not be reachable. */
  4707. GREEN, /* Object is reachable and is currently on the Tarjan stack. */
  4708. WHITE /* Object is reachable and has been assigned a group (SCC). */
  4709. } color_t;
  4710. UPB_NORETURN static void err(tarjan *t) { longjmp(t->err, 1); }
  4711. UPB_NORETURN static void oom(tarjan *t) {
  4712. upb_status_seterrmsg(t->status, "out of memory");
  4713. err(t);
  4714. }
  4715. static uint64_t trygetattr(const tarjan *t, const upb_refcounted *r) {
  4716. upb_value v;
  4717. return upb_inttable_lookupptr(&t->objattr, r, &v) ?
  4718. upb_value_getuint64(v) : 0;
  4719. }
  4720. static uint64_t getattr(const tarjan *t, const upb_refcounted *r) {
  4721. upb_value v;
  4722. bool found = upb_inttable_lookupptr(&t->objattr, r, &v);
  4723. UPB_ASSERT(found);
  4724. return upb_value_getuint64(v);
  4725. }
  4726. static void setattr(tarjan *t, const upb_refcounted *r, uint64_t attr) {
  4727. upb_inttable_removeptr(&t->objattr, r, NULL);
  4728. upb_inttable_insertptr(&t->objattr, r, upb_value_uint64(attr));
  4729. }
  4730. static color_t color(tarjan *t, const upb_refcounted *r) {
  4731. return trygetattr(t, r) & 0x3; /* Color is always stored in the low 2 bits. */
  4732. }
  4733. static void set_gray(tarjan *t, const upb_refcounted *r) {
  4734. UPB_ASSERT(color(t, r) == BLACK);
  4735. setattr(t, r, GRAY);
  4736. }
  4737. /* Pushes an obj onto the Tarjan stack and sets it to GREEN. */
  4738. static void push(tarjan *t, const upb_refcounted *r) {
  4739. UPB_ASSERT(color(t, r) == BLACK || color(t, r) == GRAY);
  4740. /* This defines the attr layout for the GREEN state. "index" and "lowlink"
  4741. * get 31 bits, which is plenty (limit of 2B objects frozen at a time). */
  4742. setattr(t, r, GREEN | (t->index << 2) | (t->index << 33));
  4743. if (++t->index == 0x80000000) {
  4744. upb_status_seterrmsg(t->status, "too many objects to freeze");
  4745. err(t);
  4746. }
  4747. upb_inttable_push(&t->stack, upb_value_ptr((void*)r));
  4748. }
  4749. /* Pops an obj from the Tarjan stack and sets it to WHITE, with a ptr to its
  4750. * SCC group. */
  4751. static upb_refcounted *pop(tarjan *t) {
  4752. upb_refcounted *r = upb_value_getptr(upb_inttable_pop(&t->stack));
  4753. UPB_ASSERT(color(t, r) == GREEN);
  4754. /* This defines the attr layout for nodes in the WHITE state.
  4755. * Top of group stack is [group, NULL]; we point at group. */
  4756. setattr(t, r, WHITE | (upb_inttable_count(&t->groups) - 2) << 8);
  4757. return r;
  4758. }
  4759. static void tarjan_newgroup(tarjan *t) {
  4760. uint32_t *group = upb_gmalloc(sizeof(*group));
  4761. if (!group) oom(t);
  4762. /* Push group and empty group leader (we'll fill in leader later). */
  4763. if (!upb_inttable_push(&t->groups, upb_value_ptr(group)) ||
  4764. !upb_inttable_push(&t->groups, upb_value_ptr(NULL))) {
  4765. upb_gfree(group);
  4766. oom(t);
  4767. }
  4768. *group = 0;
  4769. }
  4770. static uint32_t idx(tarjan *t, const upb_refcounted *r) {
  4771. UPB_ASSERT(color(t, r) == GREEN);
  4772. return (getattr(t, r) >> 2) & 0x7FFFFFFF;
  4773. }
  4774. static uint32_t lowlink(tarjan *t, const upb_refcounted *r) {
  4775. if (color(t, r) == GREEN) {
  4776. return getattr(t, r) >> 33;
  4777. } else {
  4778. return UINT32_MAX;
  4779. }
  4780. }
  4781. static void set_lowlink(tarjan *t, const upb_refcounted *r, uint32_t lowlink) {
  4782. UPB_ASSERT(color(t, r) == GREEN);
  4783. setattr(t, r, ((uint64_t)lowlink << 33) | (getattr(t, r) & 0x1FFFFFFFF));
  4784. }
  4785. static uint32_t *group(tarjan *t, upb_refcounted *r) {
  4786. uint64_t groupnum;
  4787. upb_value v;
  4788. bool found;
  4789. UPB_ASSERT(color(t, r) == WHITE);
  4790. groupnum = getattr(t, r) >> 8;
  4791. found = upb_inttable_lookup(&t->groups, groupnum, &v);
  4792. UPB_ASSERT(found);
  4793. return upb_value_getptr(v);
  4794. }
  4795. /* If the group leader for this object's group has not previously been set,
  4796. * the given object is assigned to be its leader. */
  4797. static upb_refcounted *groupleader(tarjan *t, upb_refcounted *r) {
  4798. uint64_t leader_slot;
  4799. upb_value v;
  4800. bool found;
  4801. UPB_ASSERT(color(t, r) == WHITE);
  4802. leader_slot = (getattr(t, r) >> 8) + 1;
  4803. found = upb_inttable_lookup(&t->groups, leader_slot, &v);
  4804. UPB_ASSERT(found);
  4805. if (upb_value_getptr(v)) {
  4806. return upb_value_getptr(v);
  4807. } else {
  4808. upb_inttable_remove(&t->groups, leader_slot, NULL);
  4809. upb_inttable_insert(&t->groups, leader_slot, upb_value_ptr(r));
  4810. return r;
  4811. }
  4812. }
  4813. /* Tarjan's algorithm --------------------------------------------------------*/
  4814. /* See:
  4815. * http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm */
  4816. static void do_tarjan(const upb_refcounted *obj, tarjan *t);
  4817. static void tarjan_visit(const upb_refcounted *obj,
  4818. const upb_refcounted *subobj,
  4819. void *closure) {
  4820. tarjan *t = closure;
  4821. if (++t->depth > t->maxdepth) {
  4822. upb_status_seterrf(t->status, "graph too deep to freeze (%d)", t->maxdepth);
  4823. err(t);
  4824. } else if (subobj->is_frozen || color(t, subobj) == WHITE) {
  4825. /* Do nothing: we don't want to visit or color already-frozen nodes,
  4826. * and WHITE nodes have already been assigned a SCC. */
  4827. } else if (color(t, subobj) < GREEN) {
  4828. /* Subdef has not yet been visited; recurse on it. */
  4829. do_tarjan(subobj, t);
  4830. set_lowlink(t, obj, UPB_MIN(lowlink(t, obj), lowlink(t, subobj)));
  4831. } else if (color(t, subobj) == GREEN) {
  4832. /* Subdef is in the stack and hence in the current SCC. */
  4833. set_lowlink(t, obj, UPB_MIN(lowlink(t, obj), idx(t, subobj)));
  4834. }
  4835. --t->depth;
  4836. }
  4837. static void do_tarjan(const upb_refcounted *obj, tarjan *t) {
  4838. if (color(t, obj) == BLACK) {
  4839. /* We haven't seen this object's group; mark the whole group GRAY. */
  4840. const upb_refcounted *o = obj;
  4841. do { set_gray(t, o); } while ((o = o->next) != obj);
  4842. }
  4843. push(t, obj);
  4844. visit(obj, tarjan_visit, t);
  4845. if (lowlink(t, obj) == idx(t, obj)) {
  4846. tarjan_newgroup(t);
  4847. while (pop(t) != obj)
  4848. ;
  4849. }
  4850. }
  4851. /* freeze() ------------------------------------------------------------------*/
  4852. static void crossref(const upb_refcounted *r, const upb_refcounted *subobj,
  4853. void *_t) {
  4854. tarjan *t = _t;
  4855. UPB_ASSERT(color(t, r) > BLACK);
  4856. if (color(t, subobj) > BLACK && r->group != subobj->group) {
  4857. /* Previously this ref was not reflected in subobj->group because they
  4858. * were in the same group; now that they are split a ref must be taken. */
  4859. refgroup(subobj->group);
  4860. }
  4861. }
  4862. static bool freeze(upb_refcounted *const*roots, int n, upb_status *s,
  4863. int maxdepth) {
  4864. volatile bool ret = false;
  4865. int i;
  4866. upb_inttable_iter iter;
  4867. /* We run in two passes so that we can allocate all memory before performing
  4868. * any mutation of the input -- this allows us to leave the input unchanged
  4869. * in the case of memory allocation failure. */
  4870. tarjan t;
  4871. t.index = 0;
  4872. t.depth = 0;
  4873. t.maxdepth = maxdepth;
  4874. t.status = s;
  4875. if (!upb_inttable_init(&t.objattr, UPB_CTYPE_UINT64)) goto err1;
  4876. if (!upb_inttable_init(&t.stack, UPB_CTYPE_PTR)) goto err2;
  4877. if (!upb_inttable_init(&t.groups, UPB_CTYPE_PTR)) goto err3;
  4878. if (setjmp(t.err) != 0) goto err4;
  4879. for (i = 0; i < n; i++) {
  4880. if (color(&t, roots[i]) < GREEN) {
  4881. do_tarjan(roots[i], &t);
  4882. }
  4883. }
  4884. /* If we've made it this far, no further errors are possible so it's safe to
  4885. * mutate the objects without risk of leaving them in an inconsistent state. */
  4886. ret = true;
  4887. /* The transformation that follows requires care. The preconditions are:
  4888. * - all objects in attr map are WHITE or GRAY, and are in mutable groups
  4889. * (groups of all mutable objs)
  4890. * - no ref2(to, from) refs have incremented count(to) if both "to" and
  4891. * "from" are in our attr map (this follows from invariants (2) and (3)) */
  4892. /* Pass 1: we remove WHITE objects from their mutable groups, and add them to
  4893. * new groups according to the SCC's we computed. These new groups will
  4894. * consist of only frozen objects. None will be immediately collectible,
  4895. * because WHITE objects are by definition reachable from one of "roots",
  4896. * which the caller must own refs on. */
  4897. upb_inttable_begin(&iter, &t.objattr);
  4898. for(; !upb_inttable_done(&iter); upb_inttable_next(&iter)) {
  4899. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&iter);
  4900. /* Since removal from a singly-linked list requires access to the object's
  4901. * predecessor, we consider obj->next instead of obj for moving. With the
  4902. * while() loop we guarantee that we will visit every node's predecessor.
  4903. * Proof:
  4904. * 1. every node's predecessor is in our attr map.
  4905. * 2. though the loop body may change a node's predecessor, it will only
  4906. * change it to be the node we are currently operating on, so with a
  4907. * while() loop we guarantee ourselves the chance to remove each node. */
  4908. while (color(&t, obj->next) == WHITE &&
  4909. group(&t, obj->next) != obj->next->group) {
  4910. upb_refcounted *leader;
  4911. /* Remove from old group. */
  4912. upb_refcounted *move = obj->next;
  4913. if (obj == move) {
  4914. /* Removing the last object from a group. */
  4915. UPB_ASSERT(*obj->group == obj->individual_count);
  4916. upb_gfree(obj->group);
  4917. } else {
  4918. obj->next = move->next;
  4919. /* This may decrease to zero; we'll collect GRAY objects (if any) that
  4920. * remain in the group in the third pass. */
  4921. UPB_ASSERT(*move->group >= move->individual_count);
  4922. *move->group -= move->individual_count;
  4923. }
  4924. /* Add to new group. */
  4925. leader = groupleader(&t, move);
  4926. if (move == leader) {
  4927. /* First object added to new group is its leader. */
  4928. move->group = group(&t, move);
  4929. move->next = move;
  4930. *move->group = move->individual_count;
  4931. } else {
  4932. /* Group already has at least one object in it. */
  4933. UPB_ASSERT(leader->group == group(&t, move));
  4934. move->group = group(&t, move);
  4935. move->next = leader->next;
  4936. leader->next = move;
  4937. *move->group += move->individual_count;
  4938. }
  4939. move->is_frozen = true;
  4940. }
  4941. }
  4942. /* Pass 2: GRAY and WHITE objects "obj" with ref2(to, obj) references must
  4943. * increment count(to) if group(obj) != group(to) (which could now be the
  4944. * case if "to" was just frozen). */
  4945. upb_inttable_begin(&iter, &t.objattr);
  4946. for(; !upb_inttable_done(&iter); upb_inttable_next(&iter)) {
  4947. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&iter);
  4948. visit(obj, crossref, &t);
  4949. }
  4950. /* Pass 3: GRAY objects are collected if their group's refcount dropped to
  4951. * zero when we removed its white nodes. This can happen if they had only
  4952. * been kept alive by virtue of sharing a group with an object that was just
  4953. * frozen.
  4954. *
  4955. * It is important that we do this last, since the GRAY object's free()
  4956. * function could call unref2() on just-frozen objects, which will decrement
  4957. * refs that were added in pass 2. */
  4958. upb_inttable_begin(&iter, &t.objattr);
  4959. for(; !upb_inttable_done(&iter); upb_inttable_next(&iter)) {
  4960. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&iter);
  4961. if (obj->group == NULL || *obj->group == 0) {
  4962. if (obj->group) {
  4963. upb_refcounted *o;
  4964. /* We eagerly free() the group's count (since we can't easily determine
  4965. * the group's remaining size it's the easiest way to ensure it gets
  4966. * done). */
  4967. upb_gfree(obj->group);
  4968. /* Visit to release ref2's (done in a separate pass since release_ref2
  4969. * depends on o->group being unmodified so it can test merged()). */
  4970. o = obj;
  4971. do { visit(o, release_ref2, NULL); } while ((o = o->next) != obj);
  4972. /* Mark "group" fields as NULL so we know to free the objects later in
  4973. * this loop, but also don't try to delete the group twice. */
  4974. o = obj;
  4975. do { o->group = NULL; } while ((o = o->next) != obj);
  4976. }
  4977. freeobj(obj);
  4978. }
  4979. }
  4980. err4:
  4981. if (!ret) {
  4982. upb_inttable_begin(&iter, &t.groups);
  4983. for(; !upb_inttable_done(&iter); upb_inttable_next(&iter))
  4984. upb_gfree(upb_value_getptr(upb_inttable_iter_value(&iter)));
  4985. }
  4986. upb_inttable_uninit(&t.groups);
  4987. err3:
  4988. upb_inttable_uninit(&t.stack);
  4989. err2:
  4990. upb_inttable_uninit(&t.objattr);
  4991. err1:
  4992. return ret;
  4993. }
  4994. /* Misc internal functions ***************************************************/
  4995. static bool merged(const upb_refcounted *r, const upb_refcounted *r2) {
  4996. return r->group == r2->group;
  4997. }
  4998. static void merge(upb_refcounted *r, upb_refcounted *from) {
  4999. upb_refcounted *base;
  5000. upb_refcounted *tmp;
  5001. if (merged(r, from)) return;
  5002. *r->group += *from->group;
  5003. upb_gfree(from->group);
  5004. base = from;
  5005. /* Set all refcount pointers in the "from" chain to the merged refcount.
  5006. *
  5007. * TODO(haberman): this linear algorithm can result in an overall O(n^2) bound
  5008. * if the user continuously extends a group by one object. Prevent this by
  5009. * using one of the techniques in this paper:
  5010. * http://bioinfo.ict.ac.cn/~dbu/AlgorithmCourses/Lectures/Union-Find-Tarjan.pdf */
  5011. do { from->group = r->group; } while ((from = from->next) != base);
  5012. /* Merge the two circularly linked lists by swapping their next pointers. */
  5013. tmp = r->next;
  5014. r->next = base->next;
  5015. base->next = tmp;
  5016. }
  5017. static void unref(const upb_refcounted *r);
  5018. static void release_ref2(const upb_refcounted *obj,
  5019. const upb_refcounted *subobj,
  5020. void *closure) {
  5021. UPB_UNUSED(closure);
  5022. untrack(subobj, obj, true);
  5023. if (!merged(obj, subobj)) {
  5024. UPB_ASSERT(subobj->is_frozen);
  5025. unref(subobj);
  5026. }
  5027. }
  5028. static void unref(const upb_refcounted *r) {
  5029. if (unrefgroup(r->group)) {
  5030. const upb_refcounted *o;
  5031. upb_gfree(r->group);
  5032. /* In two passes, since release_ref2 needs a guarantee that any subobjs
  5033. * are alive. */
  5034. o = r;
  5035. do { visit(o, release_ref2, NULL); } while((o = o->next) != r);
  5036. o = r;
  5037. do {
  5038. const upb_refcounted *next = o->next;
  5039. UPB_ASSERT(o->is_frozen || o->individual_count == 0);
  5040. freeobj((upb_refcounted*)o);
  5041. o = next;
  5042. } while(o != r);
  5043. }
  5044. }
  5045. static void freeobj(upb_refcounted *o) {
  5046. trackfree(o);
  5047. o->vtbl->free((upb_refcounted*)o);
  5048. }
  5049. /* Public interface ***********************************************************/
  5050. bool upb_refcounted_init(upb_refcounted *r,
  5051. const struct upb_refcounted_vtbl *vtbl,
  5052. const void *owner) {
  5053. #ifndef NDEBUG
  5054. /* Endianness check. This is unrelated to upb_refcounted, it's just a
  5055. * convenient place to put the check that we can be assured will run for
  5056. * basically every program using upb. */
  5057. const int x = 1;
  5058. #ifdef UPB_BIG_ENDIAN
  5059. UPB_ASSERT(*(char*)&x != 1);
  5060. #else
  5061. UPB_ASSERT(*(char*)&x == 1);
  5062. #endif
  5063. #endif
  5064. r->next = r;
  5065. r->vtbl = vtbl;
  5066. r->individual_count = 0;
  5067. r->is_frozen = false;
  5068. r->group = upb_gmalloc(sizeof(*r->group));
  5069. if (!r->group) return false;
  5070. *r->group = 0;
  5071. trackinit(r);
  5072. upb_refcounted_ref(r, owner);
  5073. return true;
  5074. }
  5075. bool upb_refcounted_isfrozen(const upb_refcounted *r) {
  5076. return r->is_frozen;
  5077. }
  5078. void upb_refcounted_ref(const upb_refcounted *r, const void *owner) {
  5079. track(r, owner, false);
  5080. if (!r->is_frozen)
  5081. ((upb_refcounted*)r)->individual_count++;
  5082. refgroup(r->group);
  5083. }
  5084. void upb_refcounted_unref(const upb_refcounted *r, const void *owner) {
  5085. untrack(r, owner, false);
  5086. if (!r->is_frozen)
  5087. ((upb_refcounted*)r)->individual_count--;
  5088. unref(r);
  5089. }
  5090. void upb_refcounted_ref2(const upb_refcounted *r, upb_refcounted *from) {
  5091. UPB_ASSERT(!from->is_frozen); /* Non-const pointer implies this. */
  5092. track(r, from, true);
  5093. if (r->is_frozen) {
  5094. refgroup(r->group);
  5095. } else {
  5096. merge((upb_refcounted*)r, from);
  5097. }
  5098. }
  5099. void upb_refcounted_unref2(const upb_refcounted *r, upb_refcounted *from) {
  5100. UPB_ASSERT(!from->is_frozen); /* Non-const pointer implies this. */
  5101. untrack(r, from, true);
  5102. if (r->is_frozen) {
  5103. unref(r);
  5104. } else {
  5105. UPB_ASSERT(merged(r, from));
  5106. }
  5107. }
  5108. void upb_refcounted_donateref(
  5109. const upb_refcounted *r, const void *from, const void *to) {
  5110. UPB_ASSERT(from != to);
  5111. if (to != NULL)
  5112. upb_refcounted_ref(r, to);
  5113. if (from != NULL)
  5114. upb_refcounted_unref(r, from);
  5115. }
  5116. void upb_refcounted_checkref(const upb_refcounted *r, const void *owner) {
  5117. checkref(r, owner, false);
  5118. }
  5119. bool upb_refcounted_freeze(upb_refcounted *const*roots, int n, upb_status *s,
  5120. int maxdepth) {
  5121. int i;
  5122. bool ret;
  5123. for (i = 0; i < n; i++) {
  5124. UPB_ASSERT(!roots[i]->is_frozen);
  5125. }
  5126. ret = freeze(roots, n, s, maxdepth);
  5127. UPB_ASSERT(!s || ret == upb_ok(s));
  5128. return ret;
  5129. }
  5130. bool upb_bufsrc_putbuf(const char *buf, size_t len, upb_bytessink *sink) {
  5131. void *subc;
  5132. bool ret;
  5133. upb_bufhandle handle;
  5134. upb_bufhandle_init(&handle);
  5135. upb_bufhandle_setbuf(&handle, buf, 0);
  5136. ret = upb_bytessink_start(sink, len, &subc);
  5137. if (ret && len != 0) {
  5138. ret = (upb_bytessink_putbuf(sink, subc, buf, len, &handle) >= len);
  5139. }
  5140. if (ret) {
  5141. ret = upb_bytessink_end(sink);
  5142. }
  5143. upb_bufhandle_uninit(&handle);
  5144. return ret;
  5145. }
  5146. struct upb_bufsink {
  5147. upb_byteshandler handler;
  5148. upb_bytessink sink;
  5149. upb_env *env;
  5150. char *ptr;
  5151. size_t len, size;
  5152. };
  5153. static void *upb_bufsink_start(void *_sink, const void *hd, size_t size_hint) {
  5154. upb_bufsink *sink = _sink;
  5155. UPB_UNUSED(hd);
  5156. UPB_UNUSED(size_hint);
  5157. sink->len = 0;
  5158. return sink;
  5159. }
  5160. static size_t upb_bufsink_string(void *_sink, const void *hd, const char *ptr,
  5161. size_t len, const upb_bufhandle *handle) {
  5162. upb_bufsink *sink = _sink;
  5163. size_t new_size = sink->size;
  5164. UPB_ASSERT(new_size > 0);
  5165. UPB_UNUSED(hd);
  5166. UPB_UNUSED(handle);
  5167. while (sink->len + len > new_size) {
  5168. new_size *= 2;
  5169. }
  5170. if (new_size != sink->size) {
  5171. sink->ptr = upb_env_realloc(sink->env, sink->ptr, sink->size, new_size);
  5172. sink->size = new_size;
  5173. }
  5174. memcpy(sink->ptr + sink->len, ptr, len);
  5175. sink->len += len;
  5176. return len;
  5177. }
  5178. upb_bufsink *upb_bufsink_new(upb_env *env) {
  5179. upb_bufsink *sink = upb_env_malloc(env, sizeof(upb_bufsink));
  5180. upb_byteshandler_init(&sink->handler);
  5181. upb_byteshandler_setstartstr(&sink->handler, upb_bufsink_start, NULL);
  5182. upb_byteshandler_setstring(&sink->handler, upb_bufsink_string, NULL);
  5183. upb_bytessink_reset(&sink->sink, &sink->handler, sink);
  5184. sink->env = env;
  5185. sink->size = 32;
  5186. sink->ptr = upb_env_malloc(env, sink->size);
  5187. sink->len = 0;
  5188. return sink;
  5189. }
  5190. void upb_bufsink_free(upb_bufsink *sink) {
  5191. upb_env_free(sink->env, sink->ptr);
  5192. upb_env_free(sink->env, sink);
  5193. }
  5194. upb_bytessink *upb_bufsink_sink(upb_bufsink *sink) {
  5195. return &sink->sink;
  5196. }
  5197. const char *upb_bufsink_getdata(const upb_bufsink *sink, size_t *len) {
  5198. *len = sink->len;
  5199. return sink->ptr;
  5200. }
  5201. /*
  5202. ** upb_table Implementation
  5203. **
  5204. ** Implementation is heavily inspired by Lua's ltable.c.
  5205. */
  5206. #include <string.h>
  5207. #define UPB_MAXARRSIZE 16 /* 64k. */
  5208. /* From Chromium. */
  5209. #define ARRAY_SIZE(x) \
  5210. ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x])))))
  5211. static void upb_check_alloc(upb_table *t, upb_alloc *a) {
  5212. UPB_UNUSED(t);
  5213. UPB_UNUSED(a);
  5214. UPB_ASSERT_DEBUGVAR(t->alloc == a);
  5215. }
  5216. static const double MAX_LOAD = 0.85;
  5217. /* The minimum utilization of the array part of a mixed hash/array table. This
  5218. * is a speed/memory-usage tradeoff (though it's not straightforward because of
  5219. * cache effects). The lower this is, the more memory we'll use. */
  5220. static const double MIN_DENSITY = 0.1;
  5221. bool is_pow2(uint64_t v) { return v == 0 || (v & (v - 1)) == 0; }
  5222. int log2ceil(uint64_t v) {
  5223. int ret = 0;
  5224. bool pow2 = is_pow2(v);
  5225. while (v >>= 1) ret++;
  5226. ret = pow2 ? ret : ret + 1; /* Ceiling. */
  5227. return UPB_MIN(UPB_MAXARRSIZE, ret);
  5228. }
  5229. char *upb_strdup(const char *s, upb_alloc *a) {
  5230. return upb_strdup2(s, strlen(s), a);
  5231. }
  5232. char *upb_strdup2(const char *s, size_t len, upb_alloc *a) {
  5233. size_t n;
  5234. char *p;
  5235. /* Prevent overflow errors. */
  5236. if (len == SIZE_MAX) return NULL;
  5237. /* Always null-terminate, even if binary data; but don't rely on the input to
  5238. * have a null-terminating byte since it may be a raw binary buffer. */
  5239. n = len + 1;
  5240. p = upb_malloc(a, n);
  5241. if (p) {
  5242. memcpy(p, s, len);
  5243. p[len] = 0;
  5244. }
  5245. return p;
  5246. }
  5247. /* A type to represent the lookup key of either a strtable or an inttable. */
  5248. typedef union {
  5249. uintptr_t num;
  5250. struct {
  5251. const char *str;
  5252. size_t len;
  5253. } str;
  5254. } lookupkey_t;
  5255. static lookupkey_t strkey2(const char *str, size_t len) {
  5256. lookupkey_t k;
  5257. k.str.str = str;
  5258. k.str.len = len;
  5259. return k;
  5260. }
  5261. static lookupkey_t intkey(uintptr_t key) {
  5262. lookupkey_t k;
  5263. k.num = key;
  5264. return k;
  5265. }
  5266. typedef uint32_t hashfunc_t(upb_tabkey key);
  5267. typedef bool eqlfunc_t(upb_tabkey k1, lookupkey_t k2);
  5268. /* Base table (shared code) ***************************************************/
  5269. /* For when we need to cast away const. */
  5270. static upb_tabent *mutable_entries(upb_table *t) {
  5271. return (upb_tabent*)t->entries;
  5272. }
  5273. static bool isfull(upb_table *t) {
  5274. if (upb_table_size(t) == 0) {
  5275. return true;
  5276. } else {
  5277. return ((double)(t->count + 1) / upb_table_size(t)) > MAX_LOAD;
  5278. }
  5279. }
  5280. static bool init(upb_table *t, upb_ctype_t ctype, uint8_t size_lg2,
  5281. upb_alloc *a) {
  5282. size_t bytes;
  5283. t->count = 0;
  5284. t->ctype = ctype;
  5285. t->size_lg2 = size_lg2;
  5286. t->mask = upb_table_size(t) ? upb_table_size(t) - 1 : 0;
  5287. #ifndef NDEBUG
  5288. t->alloc = a;
  5289. #endif
  5290. bytes = upb_table_size(t) * sizeof(upb_tabent);
  5291. if (bytes > 0) {
  5292. t->entries = upb_malloc(a, bytes);
  5293. if (!t->entries) return false;
  5294. memset(mutable_entries(t), 0, bytes);
  5295. } else {
  5296. t->entries = NULL;
  5297. }
  5298. return true;
  5299. }
  5300. static void uninit(upb_table *t, upb_alloc *a) {
  5301. upb_check_alloc(t, a);
  5302. upb_free(a, mutable_entries(t));
  5303. }
  5304. static upb_tabent *emptyent(upb_table *t) {
  5305. upb_tabent *e = mutable_entries(t) + upb_table_size(t);
  5306. while (1) { if (upb_tabent_isempty(--e)) return e; UPB_ASSERT(e > t->entries); }
  5307. }
  5308. static upb_tabent *getentry_mutable(upb_table *t, uint32_t hash) {
  5309. return (upb_tabent*)upb_getentry(t, hash);
  5310. }
  5311. static const upb_tabent *findentry(const upb_table *t, lookupkey_t key,
  5312. uint32_t hash, eqlfunc_t *eql) {
  5313. const upb_tabent *e;
  5314. if (t->size_lg2 == 0) return NULL;
  5315. e = upb_getentry(t, hash);
  5316. if (upb_tabent_isempty(e)) return NULL;
  5317. while (1) {
  5318. if (eql(e->key, key)) return e;
  5319. if ((e = e->next) == NULL) return NULL;
  5320. }
  5321. }
  5322. static upb_tabent *findentry_mutable(upb_table *t, lookupkey_t key,
  5323. uint32_t hash, eqlfunc_t *eql) {
  5324. return (upb_tabent*)findentry(t, key, hash, eql);
  5325. }
  5326. static bool lookup(const upb_table *t, lookupkey_t key, upb_value *v,
  5327. uint32_t hash, eqlfunc_t *eql) {
  5328. const upb_tabent *e = findentry(t, key, hash, eql);
  5329. if (e) {
  5330. if (v) {
  5331. _upb_value_setval(v, e->val.val, t->ctype);
  5332. }
  5333. return true;
  5334. } else {
  5335. return false;
  5336. }
  5337. }
  5338. /* The given key must not already exist in the table. */
  5339. static void insert(upb_table *t, lookupkey_t key, upb_tabkey tabkey,
  5340. upb_value val, uint32_t hash,
  5341. hashfunc_t *hashfunc, eqlfunc_t *eql) {
  5342. upb_tabent *mainpos_e;
  5343. upb_tabent *our_e;
  5344. UPB_ASSERT(findentry(t, key, hash, eql) == NULL);
  5345. UPB_ASSERT_DEBUGVAR(val.ctype == t->ctype);
  5346. t->count++;
  5347. mainpos_e = getentry_mutable(t, hash);
  5348. our_e = mainpos_e;
  5349. if (upb_tabent_isempty(mainpos_e)) {
  5350. /* Our main position is empty; use it. */
  5351. our_e->next = NULL;
  5352. } else {
  5353. /* Collision. */
  5354. upb_tabent *new_e = emptyent(t);
  5355. /* Head of collider's chain. */
  5356. upb_tabent *chain = getentry_mutable(t, hashfunc(mainpos_e->key));
  5357. if (chain == mainpos_e) {
  5358. /* Existing ent is in its main posisiton (it has the same hash as us, and
  5359. * is the head of our chain). Insert to new ent and append to this chain. */
  5360. new_e->next = mainpos_e->next;
  5361. mainpos_e->next = new_e;
  5362. our_e = new_e;
  5363. } else {
  5364. /* Existing ent is not in its main position (it is a node in some other
  5365. * chain). This implies that no existing ent in the table has our hash.
  5366. * Evict it (updating its chain) and use its ent for head of our chain. */
  5367. *new_e = *mainpos_e; /* copies next. */
  5368. while (chain->next != mainpos_e) {
  5369. chain = (upb_tabent*)chain->next;
  5370. UPB_ASSERT(chain);
  5371. }
  5372. chain->next = new_e;
  5373. our_e = mainpos_e;
  5374. our_e->next = NULL;
  5375. }
  5376. }
  5377. our_e->key = tabkey;
  5378. our_e->val.val = val.val;
  5379. UPB_ASSERT(findentry(t, key, hash, eql) == our_e);
  5380. }
  5381. static bool rm(upb_table *t, lookupkey_t key, upb_value *val,
  5382. upb_tabkey *removed, uint32_t hash, eqlfunc_t *eql) {
  5383. upb_tabent *chain = getentry_mutable(t, hash);
  5384. if (upb_tabent_isempty(chain)) return false;
  5385. if (eql(chain->key, key)) {
  5386. /* Element to remove is at the head of its chain. */
  5387. t->count--;
  5388. if (val) _upb_value_setval(val, chain->val.val, t->ctype);
  5389. if (removed) *removed = chain->key;
  5390. if (chain->next) {
  5391. upb_tabent *move = (upb_tabent*)chain->next;
  5392. *chain = *move;
  5393. move->key = 0; /* Make the slot empty. */
  5394. } else {
  5395. chain->key = 0; /* Make the slot empty. */
  5396. }
  5397. return true;
  5398. } else {
  5399. /* Element to remove is either in a non-head position or not in the
  5400. * table. */
  5401. while (chain->next && !eql(chain->next->key, key)) {
  5402. chain = (upb_tabent*)chain->next;
  5403. }
  5404. if (chain->next) {
  5405. /* Found element to remove. */
  5406. upb_tabent *rm = (upb_tabent*)chain->next;
  5407. t->count--;
  5408. if (val) _upb_value_setval(val, chain->next->val.val, t->ctype);
  5409. if (removed) *removed = rm->key;
  5410. rm->key = 0; /* Make the slot empty. */
  5411. chain->next = rm->next;
  5412. return true;
  5413. } else {
  5414. /* Element to remove is not in the table. */
  5415. return false;
  5416. }
  5417. }
  5418. }
  5419. static size_t next(const upb_table *t, size_t i) {
  5420. do {
  5421. if (++i >= upb_table_size(t))
  5422. return SIZE_MAX;
  5423. } while(upb_tabent_isempty(&t->entries[i]));
  5424. return i;
  5425. }
  5426. static size_t begin(const upb_table *t) {
  5427. return next(t, -1);
  5428. }
  5429. /* upb_strtable ***************************************************************/
  5430. /* A simple "subclass" of upb_table that only adds a hash function for strings. */
  5431. static upb_tabkey strcopy(lookupkey_t k2, upb_alloc *a) {
  5432. char *str = upb_malloc(a, k2.str.len + sizeof(uint32_t) + 1);
  5433. if (str == NULL) return 0;
  5434. memcpy(str, &k2.str.len, sizeof(uint32_t));
  5435. memcpy(str + sizeof(uint32_t), k2.str.str, k2.str.len + 1);
  5436. return (uintptr_t)str;
  5437. }
  5438. static uint32_t strhash(upb_tabkey key) {
  5439. uint32_t len;
  5440. char *str = upb_tabstr(key, &len);
  5441. return MurmurHash2(str, len, 0);
  5442. }
  5443. static bool streql(upb_tabkey k1, lookupkey_t k2) {
  5444. uint32_t len;
  5445. char *str = upb_tabstr(k1, &len);
  5446. return len == k2.str.len && memcmp(str, k2.str.str, len) == 0;
  5447. }
  5448. bool upb_strtable_init2(upb_strtable *t, upb_ctype_t ctype, upb_alloc *a) {
  5449. return init(&t->t, ctype, 2, a);
  5450. }
  5451. void upb_strtable_uninit2(upb_strtable *t, upb_alloc *a) {
  5452. size_t i;
  5453. for (i = 0; i < upb_table_size(&t->t); i++)
  5454. upb_free(a, (void*)t->t.entries[i].key);
  5455. uninit(&t->t, a);
  5456. }
  5457. bool upb_strtable_resize(upb_strtable *t, size_t size_lg2, upb_alloc *a) {
  5458. upb_strtable new_table;
  5459. upb_strtable_iter i;
  5460. upb_check_alloc(&t->t, a);
  5461. if (!init(&new_table.t, t->t.ctype, size_lg2, a))
  5462. return false;
  5463. upb_strtable_begin(&i, t);
  5464. for ( ; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  5465. upb_strtable_insert3(
  5466. &new_table,
  5467. upb_strtable_iter_key(&i),
  5468. upb_strtable_iter_keylength(&i),
  5469. upb_strtable_iter_value(&i),
  5470. a);
  5471. }
  5472. upb_strtable_uninit2(t, a);
  5473. *t = new_table;
  5474. return true;
  5475. }
  5476. bool upb_strtable_insert3(upb_strtable *t, const char *k, size_t len,
  5477. upb_value v, upb_alloc *a) {
  5478. lookupkey_t key;
  5479. upb_tabkey tabkey;
  5480. uint32_t hash;
  5481. upb_check_alloc(&t->t, a);
  5482. if (isfull(&t->t)) {
  5483. /* Need to resize. New table of double the size, add old elements to it. */
  5484. if (!upb_strtable_resize(t, t->t.size_lg2 + 1, a)) {
  5485. return false;
  5486. }
  5487. }
  5488. key = strkey2(k, len);
  5489. tabkey = strcopy(key, a);
  5490. if (tabkey == 0) return false;
  5491. hash = MurmurHash2(key.str.str, key.str.len, 0);
  5492. insert(&t->t, key, tabkey, v, hash, &strhash, &streql);
  5493. return true;
  5494. }
  5495. bool upb_strtable_lookup2(const upb_strtable *t, const char *key, size_t len,
  5496. upb_value *v) {
  5497. uint32_t hash = MurmurHash2(key, len, 0);
  5498. return lookup(&t->t, strkey2(key, len), v, hash, &streql);
  5499. }
  5500. bool upb_strtable_remove3(upb_strtable *t, const char *key, size_t len,
  5501. upb_value *val, upb_alloc *alloc) {
  5502. uint32_t hash = MurmurHash2(key, len, 0);
  5503. upb_tabkey tabkey;
  5504. if (rm(&t->t, strkey2(key, len), val, &tabkey, hash, &streql)) {
  5505. upb_free(alloc, (void*)tabkey);
  5506. return true;
  5507. } else {
  5508. return false;
  5509. }
  5510. }
  5511. /* Iteration */
  5512. static const upb_tabent *str_tabent(const upb_strtable_iter *i) {
  5513. return &i->t->t.entries[i->index];
  5514. }
  5515. void upb_strtable_begin(upb_strtable_iter *i, const upb_strtable *t) {
  5516. i->t = t;
  5517. i->index = begin(&t->t);
  5518. }
  5519. void upb_strtable_next(upb_strtable_iter *i) {
  5520. i->index = next(&i->t->t, i->index);
  5521. }
  5522. bool upb_strtable_done(const upb_strtable_iter *i) {
  5523. return i->index >= upb_table_size(&i->t->t) ||
  5524. upb_tabent_isempty(str_tabent(i));
  5525. }
  5526. const char *upb_strtable_iter_key(const upb_strtable_iter *i) {
  5527. UPB_ASSERT(!upb_strtable_done(i));
  5528. return upb_tabstr(str_tabent(i)->key, NULL);
  5529. }
  5530. size_t upb_strtable_iter_keylength(const upb_strtable_iter *i) {
  5531. uint32_t len;
  5532. UPB_ASSERT(!upb_strtable_done(i));
  5533. upb_tabstr(str_tabent(i)->key, &len);
  5534. return len;
  5535. }
  5536. upb_value upb_strtable_iter_value(const upb_strtable_iter *i) {
  5537. UPB_ASSERT(!upb_strtable_done(i));
  5538. return _upb_value_val(str_tabent(i)->val.val, i->t->t.ctype);
  5539. }
  5540. void upb_strtable_iter_setdone(upb_strtable_iter *i) {
  5541. i->index = SIZE_MAX;
  5542. }
  5543. bool upb_strtable_iter_isequal(const upb_strtable_iter *i1,
  5544. const upb_strtable_iter *i2) {
  5545. if (upb_strtable_done(i1) && upb_strtable_done(i2))
  5546. return true;
  5547. return i1->t == i2->t && i1->index == i2->index;
  5548. }
  5549. /* upb_inttable ***************************************************************/
  5550. /* For inttables we use a hybrid structure where small keys are kept in an
  5551. * array and large keys are put in the hash table. */
  5552. static uint32_t inthash(upb_tabkey key) { return upb_inthash(key); }
  5553. static bool inteql(upb_tabkey k1, lookupkey_t k2) {
  5554. return k1 == k2.num;
  5555. }
  5556. static upb_tabval *mutable_array(upb_inttable *t) {
  5557. return (upb_tabval*)t->array;
  5558. }
  5559. static upb_tabval *inttable_val(upb_inttable *t, uintptr_t key) {
  5560. if (key < t->array_size) {
  5561. return upb_arrhas(t->array[key]) ? &(mutable_array(t)[key]) : NULL;
  5562. } else {
  5563. upb_tabent *e =
  5564. findentry_mutable(&t->t, intkey(key), upb_inthash(key), &inteql);
  5565. return e ? &e->val : NULL;
  5566. }
  5567. }
  5568. static const upb_tabval *inttable_val_const(const upb_inttable *t,
  5569. uintptr_t key) {
  5570. return inttable_val((upb_inttable*)t, key);
  5571. }
  5572. size_t upb_inttable_count(const upb_inttable *t) {
  5573. return t->t.count + t->array_count;
  5574. }
  5575. static void check(upb_inttable *t) {
  5576. UPB_UNUSED(t);
  5577. #if defined(UPB_DEBUG_TABLE) && !defined(NDEBUG)
  5578. {
  5579. /* This check is very expensive (makes inserts/deletes O(N)). */
  5580. size_t count = 0;
  5581. upb_inttable_iter i;
  5582. upb_inttable_begin(&i, t);
  5583. for(; !upb_inttable_done(&i); upb_inttable_next(&i), count++) {
  5584. UPB_ASSERT(upb_inttable_lookup(t, upb_inttable_iter_key(&i), NULL));
  5585. }
  5586. UPB_ASSERT(count == upb_inttable_count(t));
  5587. }
  5588. #endif
  5589. }
  5590. bool upb_inttable_sizedinit(upb_inttable *t, upb_ctype_t ctype,
  5591. size_t asize, int hsize_lg2, upb_alloc *a) {
  5592. size_t array_bytes;
  5593. if (!init(&t->t, ctype, hsize_lg2, a)) return false;
  5594. /* Always make the array part at least 1 long, so that we know key 0
  5595. * won't be in the hash part, which simplifies things. */
  5596. t->array_size = UPB_MAX(1, asize);
  5597. t->array_count = 0;
  5598. array_bytes = t->array_size * sizeof(upb_value);
  5599. t->array = upb_malloc(a, array_bytes);
  5600. if (!t->array) {
  5601. uninit(&t->t, a);
  5602. return false;
  5603. }
  5604. memset(mutable_array(t), 0xff, array_bytes);
  5605. check(t);
  5606. return true;
  5607. }
  5608. bool upb_inttable_init2(upb_inttable *t, upb_ctype_t ctype, upb_alloc *a) {
  5609. return upb_inttable_sizedinit(t, ctype, 0, 4, a);
  5610. }
  5611. void upb_inttable_uninit2(upb_inttable *t, upb_alloc *a) {
  5612. uninit(&t->t, a);
  5613. upb_free(a, mutable_array(t));
  5614. }
  5615. bool upb_inttable_insert2(upb_inttable *t, uintptr_t key, upb_value val,
  5616. upb_alloc *a) {
  5617. upb_tabval tabval;
  5618. tabval.val = val.val;
  5619. UPB_ASSERT(upb_arrhas(tabval)); /* This will reject (uint64_t)-1. Fix this. */
  5620. upb_check_alloc(&t->t, a);
  5621. if (key < t->array_size) {
  5622. UPB_ASSERT(!upb_arrhas(t->array[key]));
  5623. t->array_count++;
  5624. mutable_array(t)[key].val = val.val;
  5625. } else {
  5626. if (isfull(&t->t)) {
  5627. /* Need to resize the hash part, but we re-use the array part. */
  5628. size_t i;
  5629. upb_table new_table;
  5630. if (!init(&new_table, t->t.ctype, t->t.size_lg2 + 1, a)) {
  5631. return false;
  5632. }
  5633. for (i = begin(&t->t); i < upb_table_size(&t->t); i = next(&t->t, i)) {
  5634. const upb_tabent *e = &t->t.entries[i];
  5635. uint32_t hash;
  5636. upb_value v;
  5637. _upb_value_setval(&v, e->val.val, t->t.ctype);
  5638. hash = upb_inthash(e->key);
  5639. insert(&new_table, intkey(e->key), e->key, v, hash, &inthash, &inteql);
  5640. }
  5641. UPB_ASSERT(t->t.count == new_table.count);
  5642. uninit(&t->t, a);
  5643. t->t = new_table;
  5644. }
  5645. insert(&t->t, intkey(key), key, val, upb_inthash(key), &inthash, &inteql);
  5646. }
  5647. check(t);
  5648. return true;
  5649. }
  5650. bool upb_inttable_lookup(const upb_inttable *t, uintptr_t key, upb_value *v) {
  5651. const upb_tabval *table_v = inttable_val_const(t, key);
  5652. if (!table_v) return false;
  5653. if (v) _upb_value_setval(v, table_v->val, t->t.ctype);
  5654. return true;
  5655. }
  5656. bool upb_inttable_replace(upb_inttable *t, uintptr_t key, upb_value val) {
  5657. upb_tabval *table_v = inttable_val(t, key);
  5658. if (!table_v) return false;
  5659. table_v->val = val.val;
  5660. return true;
  5661. }
  5662. bool upb_inttable_remove(upb_inttable *t, uintptr_t key, upb_value *val) {
  5663. bool success;
  5664. if (key < t->array_size) {
  5665. if (upb_arrhas(t->array[key])) {
  5666. upb_tabval empty = UPB_TABVALUE_EMPTY_INIT;
  5667. t->array_count--;
  5668. if (val) {
  5669. _upb_value_setval(val, t->array[key].val, t->t.ctype);
  5670. }
  5671. mutable_array(t)[key] = empty;
  5672. success = true;
  5673. } else {
  5674. success = false;
  5675. }
  5676. } else {
  5677. success = rm(&t->t, intkey(key), val, NULL, upb_inthash(key), &inteql);
  5678. }
  5679. check(t);
  5680. return success;
  5681. }
  5682. bool upb_inttable_push2(upb_inttable *t, upb_value val, upb_alloc *a) {
  5683. upb_check_alloc(&t->t, a);
  5684. return upb_inttable_insert2(t, upb_inttable_count(t), val, a);
  5685. }
  5686. upb_value upb_inttable_pop(upb_inttable *t) {
  5687. upb_value val;
  5688. bool ok = upb_inttable_remove(t, upb_inttable_count(t) - 1, &val);
  5689. UPB_ASSERT(ok);
  5690. return val;
  5691. }
  5692. bool upb_inttable_insertptr2(upb_inttable *t, const void *key, upb_value val,
  5693. upb_alloc *a) {
  5694. upb_check_alloc(&t->t, a);
  5695. return upb_inttable_insert2(t, (uintptr_t)key, val, a);
  5696. }
  5697. bool upb_inttable_lookupptr(const upb_inttable *t, const void *key,
  5698. upb_value *v) {
  5699. return upb_inttable_lookup(t, (uintptr_t)key, v);
  5700. }
  5701. bool upb_inttable_removeptr(upb_inttable *t, const void *key, upb_value *val) {
  5702. return upb_inttable_remove(t, (uintptr_t)key, val);
  5703. }
  5704. void upb_inttable_compact2(upb_inttable *t, upb_alloc *a) {
  5705. /* A power-of-two histogram of the table keys. */
  5706. size_t counts[UPB_MAXARRSIZE + 1] = {0};
  5707. /* The max key in each bucket. */
  5708. uintptr_t max[UPB_MAXARRSIZE + 1] = {0};
  5709. upb_inttable_iter i;
  5710. size_t arr_count;
  5711. int size_lg2;
  5712. upb_inttable new_t;
  5713. upb_check_alloc(&t->t, a);
  5714. upb_inttable_begin(&i, t);
  5715. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5716. uintptr_t key = upb_inttable_iter_key(&i);
  5717. int bucket = log2ceil(key);
  5718. max[bucket] = UPB_MAX(max[bucket], key);
  5719. counts[bucket]++;
  5720. }
  5721. /* Find the largest power of two that satisfies the MIN_DENSITY
  5722. * definition (while actually having some keys). */
  5723. arr_count = upb_inttable_count(t);
  5724. for (size_lg2 = ARRAY_SIZE(counts) - 1; size_lg2 > 0; size_lg2--) {
  5725. if (counts[size_lg2] == 0) {
  5726. /* We can halve again without losing any entries. */
  5727. continue;
  5728. } else if (arr_count >= (1 << size_lg2) * MIN_DENSITY) {
  5729. break;
  5730. }
  5731. arr_count -= counts[size_lg2];
  5732. }
  5733. UPB_ASSERT(arr_count <= upb_inttable_count(t));
  5734. {
  5735. /* Insert all elements into new, perfectly-sized table. */
  5736. size_t arr_size = max[size_lg2] + 1; /* +1 so arr[max] will fit. */
  5737. size_t hash_count = upb_inttable_count(t) - arr_count;
  5738. size_t hash_size = hash_count ? (hash_count / MAX_LOAD) + 1 : 0;
  5739. size_t hashsize_lg2 = log2ceil(hash_size);
  5740. upb_inttable_sizedinit(&new_t, t->t.ctype, arr_size, hashsize_lg2, a);
  5741. upb_inttable_begin(&i, t);
  5742. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5743. uintptr_t k = upb_inttable_iter_key(&i);
  5744. upb_inttable_insert2(&new_t, k, upb_inttable_iter_value(&i), a);
  5745. }
  5746. UPB_ASSERT(new_t.array_size == arr_size);
  5747. UPB_ASSERT(new_t.t.size_lg2 == hashsize_lg2);
  5748. }
  5749. upb_inttable_uninit2(t, a);
  5750. *t = new_t;
  5751. }
  5752. /* Iteration. */
  5753. static const upb_tabent *int_tabent(const upb_inttable_iter *i) {
  5754. UPB_ASSERT(!i->array_part);
  5755. return &i->t->t.entries[i->index];
  5756. }
  5757. static upb_tabval int_arrent(const upb_inttable_iter *i) {
  5758. UPB_ASSERT(i->array_part);
  5759. return i->t->array[i->index];
  5760. }
  5761. void upb_inttable_begin(upb_inttable_iter *i, const upb_inttable *t) {
  5762. i->t = t;
  5763. i->index = -1;
  5764. i->array_part = true;
  5765. upb_inttable_next(i);
  5766. }
  5767. void upb_inttable_next(upb_inttable_iter *iter) {
  5768. const upb_inttable *t = iter->t;
  5769. if (iter->array_part) {
  5770. while (++iter->index < t->array_size) {
  5771. if (upb_arrhas(int_arrent(iter))) {
  5772. return;
  5773. }
  5774. }
  5775. iter->array_part = false;
  5776. iter->index = begin(&t->t);
  5777. } else {
  5778. iter->index = next(&t->t, iter->index);
  5779. }
  5780. }
  5781. bool upb_inttable_done(const upb_inttable_iter *i) {
  5782. if (i->array_part) {
  5783. return i->index >= i->t->array_size ||
  5784. !upb_arrhas(int_arrent(i));
  5785. } else {
  5786. return i->index >= upb_table_size(&i->t->t) ||
  5787. upb_tabent_isempty(int_tabent(i));
  5788. }
  5789. }
  5790. uintptr_t upb_inttable_iter_key(const upb_inttable_iter *i) {
  5791. UPB_ASSERT(!upb_inttable_done(i));
  5792. return i->array_part ? i->index : int_tabent(i)->key;
  5793. }
  5794. upb_value upb_inttable_iter_value(const upb_inttable_iter *i) {
  5795. UPB_ASSERT(!upb_inttable_done(i));
  5796. return _upb_value_val(
  5797. i->array_part ? i->t->array[i->index].val : int_tabent(i)->val.val,
  5798. i->t->t.ctype);
  5799. }
  5800. void upb_inttable_iter_setdone(upb_inttable_iter *i) {
  5801. i->index = SIZE_MAX;
  5802. i->array_part = false;
  5803. }
  5804. bool upb_inttable_iter_isequal(const upb_inttable_iter *i1,
  5805. const upb_inttable_iter *i2) {
  5806. if (upb_inttable_done(i1) && upb_inttable_done(i2))
  5807. return true;
  5808. return i1->t == i2->t && i1->index == i2->index &&
  5809. i1->array_part == i2->array_part;
  5810. }
  5811. #ifdef UPB_UNALIGNED_READS_OK
  5812. /* -----------------------------------------------------------------------------
  5813. * MurmurHash2, by Austin Appleby (released as public domain).
  5814. * Reformatted and C99-ified by Joshua Haberman.
  5815. * Note - This code makes a few assumptions about how your machine behaves -
  5816. * 1. We can read a 4-byte value from any address without crashing
  5817. * 2. sizeof(int) == 4 (in upb this limitation is removed by using uint32_t
  5818. * And it has a few limitations -
  5819. * 1. It will not work incrementally.
  5820. * 2. It will not produce the same results on little-endian and big-endian
  5821. * machines. */
  5822. uint32_t MurmurHash2(const void *key, size_t len, uint32_t seed) {
  5823. /* 'm' and 'r' are mixing constants generated offline.
  5824. * They're not really 'magic', they just happen to work well. */
  5825. const uint32_t m = 0x5bd1e995;
  5826. const int32_t r = 24;
  5827. /* Initialize the hash to a 'random' value */
  5828. uint32_t h = seed ^ len;
  5829. /* Mix 4 bytes at a time into the hash */
  5830. const uint8_t * data = (const uint8_t *)key;
  5831. while(len >= 4) {
  5832. uint32_t k = *(uint32_t *)data;
  5833. k *= m;
  5834. k ^= k >> r;
  5835. k *= m;
  5836. h *= m;
  5837. h ^= k;
  5838. data += 4;
  5839. len -= 4;
  5840. }
  5841. /* Handle the last few bytes of the input array */
  5842. switch(len) {
  5843. case 3: h ^= data[2] << 16;
  5844. case 2: h ^= data[1] << 8;
  5845. case 1: h ^= data[0]; h *= m;
  5846. };
  5847. /* Do a few final mixes of the hash to ensure the last few
  5848. * bytes are well-incorporated. */
  5849. h ^= h >> 13;
  5850. h *= m;
  5851. h ^= h >> 15;
  5852. return h;
  5853. }
  5854. #else /* !UPB_UNALIGNED_READS_OK */
  5855. /* -----------------------------------------------------------------------------
  5856. * MurmurHashAligned2, by Austin Appleby
  5857. * Same algorithm as MurmurHash2, but only does aligned reads - should be safer
  5858. * on certain platforms.
  5859. * Performance will be lower than MurmurHash2 */
  5860. #define MIX(h,k,m) { k *= m; k ^= k >> r; k *= m; h *= m; h ^= k; }
  5861. uint32_t MurmurHash2(const void * key, size_t len, uint32_t seed) {
  5862. const uint32_t m = 0x5bd1e995;
  5863. const int32_t r = 24;
  5864. const uint8_t * data = (const uint8_t *)key;
  5865. uint32_t h = seed ^ len;
  5866. uint8_t align = (uintptr_t)data & 3;
  5867. if(align && (len >= 4)) {
  5868. /* Pre-load the temp registers */
  5869. uint32_t t = 0, d = 0;
  5870. int32_t sl;
  5871. int32_t sr;
  5872. switch(align) {
  5873. case 1: t |= data[2] << 16;
  5874. case 2: t |= data[1] << 8;
  5875. case 3: t |= data[0];
  5876. }
  5877. t <<= (8 * align);
  5878. data += 4-align;
  5879. len -= 4-align;
  5880. sl = 8 * (4-align);
  5881. sr = 8 * align;
  5882. /* Mix */
  5883. while(len >= 4) {
  5884. uint32_t k;
  5885. d = *(uint32_t *)data;
  5886. t = (t >> sr) | (d << sl);
  5887. k = t;
  5888. MIX(h,k,m);
  5889. t = d;
  5890. data += 4;
  5891. len -= 4;
  5892. }
  5893. /* Handle leftover data in temp registers */
  5894. d = 0;
  5895. if(len >= align) {
  5896. uint32_t k;
  5897. switch(align) {
  5898. case 3: d |= data[2] << 16;
  5899. case 2: d |= data[1] << 8;
  5900. case 1: d |= data[0];
  5901. }
  5902. k = (t >> sr) | (d << sl);
  5903. MIX(h,k,m);
  5904. data += align;
  5905. len -= align;
  5906. /* ----------
  5907. * Handle tail bytes */
  5908. switch(len) {
  5909. case 3: h ^= data[2] << 16;
  5910. case 2: h ^= data[1] << 8;
  5911. case 1: h ^= data[0]; h *= m;
  5912. };
  5913. } else {
  5914. switch(len) {
  5915. case 3: d |= data[2] << 16;
  5916. case 2: d |= data[1] << 8;
  5917. case 1: d |= data[0];
  5918. case 0: h ^= (t >> sr) | (d << sl); h *= m;
  5919. }
  5920. }
  5921. h ^= h >> 13;
  5922. h *= m;
  5923. h ^= h >> 15;
  5924. return h;
  5925. } else {
  5926. while(len >= 4) {
  5927. uint32_t k = *(uint32_t *)data;
  5928. MIX(h,k,m);
  5929. data += 4;
  5930. len -= 4;
  5931. }
  5932. /* ----------
  5933. * Handle tail bytes */
  5934. switch(len) {
  5935. case 3: h ^= data[2] << 16;
  5936. case 2: h ^= data[1] << 8;
  5937. case 1: h ^= data[0]; h *= m;
  5938. };
  5939. h ^= h >> 13;
  5940. h *= m;
  5941. h ^= h >> 15;
  5942. return h;
  5943. }
  5944. }
  5945. #undef MIX
  5946. #endif /* UPB_UNALIGNED_READS_OK */
  5947. #include <errno.h>
  5948. #include <stdarg.h>
  5949. #include <stddef.h>
  5950. #include <stdint.h>
  5951. #include <stdio.h>
  5952. #include <stdlib.h>
  5953. #include <string.h>
  5954. bool upb_dumptostderr(void *closure, const upb_status* status) {
  5955. UPB_UNUSED(closure);
  5956. fprintf(stderr, "%s\n", upb_status_errmsg(status));
  5957. return false;
  5958. }
  5959. /* Guarantee null-termination and provide ellipsis truncation.
  5960. * It may be tempting to "optimize" this by initializing these final
  5961. * four bytes up-front and then being careful never to overwrite them,
  5962. * this is safer and simpler. */
  5963. static void nullz(upb_status *status) {
  5964. const char *ellipsis = "...";
  5965. size_t len = strlen(ellipsis);
  5966. UPB_ASSERT(sizeof(status->msg) > len);
  5967. memcpy(status->msg + sizeof(status->msg) - len, ellipsis, len);
  5968. }
  5969. /* upb_upberr *****************************************************************/
  5970. upb_errorspace upb_upberr = {"upb error"};
  5971. void upb_upberr_setoom(upb_status *status) {
  5972. status->error_space_ = &upb_upberr;
  5973. upb_status_seterrmsg(status, "Out of memory");
  5974. }
  5975. /* upb_status *****************************************************************/
  5976. void upb_status_clear(upb_status *status) {
  5977. if (!status) return;
  5978. status->ok_ = true;
  5979. status->code_ = 0;
  5980. status->msg[0] = '\0';
  5981. }
  5982. bool upb_ok(const upb_status *status) { return status->ok_; }
  5983. upb_errorspace *upb_status_errspace(const upb_status *status) {
  5984. return status->error_space_;
  5985. }
  5986. int upb_status_errcode(const upb_status *status) { return status->code_; }
  5987. const char *upb_status_errmsg(const upb_status *status) { return status->msg; }
  5988. void upb_status_seterrmsg(upb_status *status, const char *msg) {
  5989. if (!status) return;
  5990. status->ok_ = false;
  5991. strncpy(status->msg, msg, sizeof(status->msg));
  5992. nullz(status);
  5993. }
  5994. void upb_status_seterrf(upb_status *status, const char *fmt, ...) {
  5995. va_list args;
  5996. va_start(args, fmt);
  5997. upb_status_vseterrf(status, fmt, args);
  5998. va_end(args);
  5999. }
  6000. void upb_status_vseterrf(upb_status *status, const char *fmt, va_list args) {
  6001. if (!status) return;
  6002. status->ok_ = false;
  6003. _upb_vsnprintf(status->msg, sizeof(status->msg), fmt, args);
  6004. nullz(status);
  6005. }
  6006. void upb_status_copy(upb_status *to, const upb_status *from) {
  6007. if (!to) return;
  6008. *to = *from;
  6009. }
  6010. /* upb_alloc ******************************************************************/
  6011. static void *upb_global_allocfunc(upb_alloc *alloc, void *ptr, size_t oldsize,
  6012. size_t size) {
  6013. UPB_UNUSED(alloc);
  6014. UPB_UNUSED(oldsize);
  6015. if (size == 0) {
  6016. free(ptr);
  6017. return NULL;
  6018. } else {
  6019. return realloc(ptr, size);
  6020. }
  6021. }
  6022. upb_alloc upb_alloc_global = {&upb_global_allocfunc};
  6023. /* upb_arena ******************************************************************/
  6024. /* Be conservative and choose 16 in case anyone is using SSE. */
  6025. static const size_t maxalign = 16;
  6026. static size_t align_up_max(size_t size) {
  6027. return ((size + maxalign - 1) / maxalign) * maxalign;
  6028. }
  6029. typedef struct mem_block {
  6030. struct mem_block *next;
  6031. size_t size;
  6032. size_t used;
  6033. bool owned;
  6034. /* Data follows. */
  6035. } mem_block;
  6036. typedef struct cleanup_ent {
  6037. struct cleanup_ent *next;
  6038. upb_cleanup_func *cleanup;
  6039. void *ud;
  6040. } cleanup_ent;
  6041. static void upb_arena_addblock(upb_arena *a, void *ptr, size_t size,
  6042. bool owned) {
  6043. mem_block *block = ptr;
  6044. block->next = a->block_head;
  6045. block->size = size;
  6046. block->used = align_up_max(sizeof(mem_block));
  6047. block->owned = owned;
  6048. a->block_head = block;
  6049. /* TODO(haberman): ASAN poison. */
  6050. }
  6051. static mem_block *upb_arena_allocblock(upb_arena *a, size_t size) {
  6052. size_t block_size = UPB_MAX(size, a->next_block_size) + sizeof(mem_block);
  6053. mem_block *block = upb_malloc(a->block_alloc, block_size);
  6054. if (!block) {
  6055. return NULL;
  6056. }
  6057. upb_arena_addblock(a, block, block_size, true);
  6058. a->next_block_size = UPB_MIN(block_size * 2, a->max_block_size);
  6059. return block;
  6060. }
  6061. static void *upb_arena_doalloc(upb_alloc *alloc, void *ptr, size_t oldsize,
  6062. size_t size) {
  6063. upb_arena *a = (upb_arena*)alloc; /* upb_alloc is initial member. */
  6064. mem_block *block = a->block_head;
  6065. void *ret;
  6066. if (size == 0) {
  6067. return NULL; /* We are an arena, don't need individual frees. */
  6068. }
  6069. size = align_up_max(size);
  6070. /* TODO(haberman): special-case if this is a realloc of the last alloc? */
  6071. if (!block || block->size - block->used < size) {
  6072. /* Slow path: have to allocate a new block. */
  6073. block = upb_arena_allocblock(a, size);
  6074. if (!block) {
  6075. return NULL; /* Out of memory. */
  6076. }
  6077. }
  6078. ret = (char*)block + block->used;
  6079. block->used += size;
  6080. if (oldsize > 0) {
  6081. memcpy(ret, ptr, oldsize); /* Preserve existing data. */
  6082. }
  6083. /* TODO(haberman): ASAN unpoison. */
  6084. a->bytes_allocated += size;
  6085. return ret;
  6086. }
  6087. /* Public Arena API ***********************************************************/
  6088. void upb_arena_init(upb_arena *a) {
  6089. a->alloc.func = &upb_arena_doalloc;
  6090. a->block_alloc = &upb_alloc_global;
  6091. a->bytes_allocated = 0;
  6092. a->next_block_size = 256;
  6093. a->max_block_size = 16384;
  6094. a->cleanup_head = NULL;
  6095. a->block_head = NULL;
  6096. }
  6097. void upb_arena_init2(upb_arena *a, void *mem, size_t size, upb_alloc *alloc) {
  6098. upb_arena_init(a);
  6099. if (size > sizeof(mem_block)) {
  6100. upb_arena_addblock(a, mem, size, false);
  6101. }
  6102. if (alloc) {
  6103. a->block_alloc = alloc;
  6104. }
  6105. }
  6106. void upb_arena_uninit(upb_arena *a) {
  6107. cleanup_ent *ent = a->cleanup_head;
  6108. mem_block *block = a->block_head;
  6109. while (ent) {
  6110. ent->cleanup(ent->ud);
  6111. ent = ent->next;
  6112. }
  6113. /* Must do this after running cleanup functions, because this will delete
  6114. * the memory we store our cleanup entries in! */
  6115. while (block) {
  6116. mem_block *next = block->next;
  6117. if (block->owned) {
  6118. upb_free(a->block_alloc, block);
  6119. }
  6120. block = next;
  6121. }
  6122. /* Protect against multiple-uninit. */
  6123. a->cleanup_head = NULL;
  6124. a->block_head = NULL;
  6125. }
  6126. bool upb_arena_addcleanup(upb_arena *a, upb_cleanup_func *func, void *ud) {
  6127. cleanup_ent *ent = upb_malloc(&a->alloc, sizeof(cleanup_ent));
  6128. if (!ent) {
  6129. return false; /* Out of memory. */
  6130. }
  6131. ent->cleanup = func;
  6132. ent->ud = ud;
  6133. ent->next = a->cleanup_head;
  6134. a->cleanup_head = ent;
  6135. return true;
  6136. }
  6137. size_t upb_arena_bytesallocated(const upb_arena *a) {
  6138. return a->bytes_allocated;
  6139. }
  6140. /* Standard error functions ***************************************************/
  6141. static bool default_err(void *ud, const upb_status *status) {
  6142. UPB_UNUSED(ud);
  6143. UPB_UNUSED(status);
  6144. return false;
  6145. }
  6146. static bool write_err_to(void *ud, const upb_status *status) {
  6147. upb_status *copy_to = ud;
  6148. upb_status_copy(copy_to, status);
  6149. return false;
  6150. }
  6151. /* upb_env ********************************************************************/
  6152. void upb_env_initonly(upb_env *e) {
  6153. e->ok_ = true;
  6154. e->error_func_ = &default_err;
  6155. e->error_ud_ = NULL;
  6156. }
  6157. void upb_env_init(upb_env *e) {
  6158. upb_arena_init(&e->arena_);
  6159. upb_env_initonly(e);
  6160. }
  6161. void upb_env_init2(upb_env *e, void *mem, size_t n, upb_alloc *alloc) {
  6162. upb_arena_init2(&e->arena_, mem, n, alloc);
  6163. upb_env_initonly(e);
  6164. }
  6165. void upb_env_uninit(upb_env *e) {
  6166. upb_arena_uninit(&e->arena_);
  6167. }
  6168. void upb_env_seterrorfunc(upb_env *e, upb_error_func *func, void *ud) {
  6169. e->error_func_ = func;
  6170. e->error_ud_ = ud;
  6171. }
  6172. void upb_env_reporterrorsto(upb_env *e, upb_status *s) {
  6173. e->error_func_ = &write_err_to;
  6174. e->error_ud_ = s;
  6175. }
  6176. bool upb_env_reporterror(upb_env *e, const upb_status *status) {
  6177. e->ok_ = false;
  6178. return e->error_func_(e->error_ud_, status);
  6179. }
  6180. void *upb_env_malloc(upb_env *e, size_t size) {
  6181. return upb_malloc(&e->arena_.alloc, size);
  6182. }
  6183. void *upb_env_realloc(upb_env *e, void *ptr, size_t oldsize, size_t size) {
  6184. return upb_realloc(&e->arena_.alloc, ptr, oldsize, size);
  6185. }
  6186. void upb_env_free(upb_env *e, void *ptr) {
  6187. upb_free(&e->arena_.alloc, ptr);
  6188. }
  6189. bool upb_env_addcleanup(upb_env *e, upb_cleanup_func *func, void *ud) {
  6190. return upb_arena_addcleanup(&e->arena_, func, ud);
  6191. }
  6192. size_t upb_env_bytesallocated(const upb_env *e) {
  6193. return upb_arena_bytesallocated(&e->arena_);
  6194. }
  6195. /* This file was generated by upbc (the upb compiler) from the input
  6196. * file:
  6197. *
  6198. * upb/descriptor/descriptor.proto
  6199. *
  6200. * Do not edit -- your changes will be discarded when the file is
  6201. * regenerated. */
  6202. static const upb_msgdef msgs[22];
  6203. static const upb_fielddef fields[107];
  6204. static const upb_enumdef enums[5];
  6205. static const upb_tabent strentries[236];
  6206. static const upb_tabent intentries[18];
  6207. static const upb_tabval arrays[187];
  6208. #ifdef UPB_DEBUG_REFS
  6209. static upb_inttable reftables[268];
  6210. #endif
  6211. static const upb_msgdef msgs[22] = {
  6212. UPB_MSGDEF_INIT("google.protobuf.DescriptorProto", 41, 8, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[0], 11, 10), UPB_STRTABLE_INIT(10, 15, UPB_CTYPE_PTR, 4, &strentries[0]), false, UPB_SYNTAX_PROTO2, &reftables[0], &reftables[1]),
  6213. UPB_MSGDEF_INIT("google.protobuf.DescriptorProto.ExtensionRange", 5, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[11], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[16]), false, UPB_SYNTAX_PROTO2, &reftables[2], &reftables[3]),
  6214. UPB_MSGDEF_INIT("google.protobuf.DescriptorProto.ReservedRange", 5, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[14], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[20]), false, UPB_SYNTAX_PROTO2, &reftables[4], &reftables[5]),
  6215. UPB_MSGDEF_INIT("google.protobuf.EnumDescriptorProto", 12, 2, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[17], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[24]), false, UPB_SYNTAX_PROTO2, &reftables[6], &reftables[7]),
  6216. UPB_MSGDEF_INIT("google.protobuf.EnumOptions", 9, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[0], &arrays[21], 4, 2), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[28]), false, UPB_SYNTAX_PROTO2, &reftables[8], &reftables[9]),
  6217. UPB_MSGDEF_INIT("google.protobuf.EnumValueDescriptorProto", 9, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[25], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[32]), false, UPB_SYNTAX_PROTO2, &reftables[10], &reftables[11]),
  6218. UPB_MSGDEF_INIT("google.protobuf.EnumValueOptions", 8, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[2], &arrays[29], 2, 1), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[36]), false, UPB_SYNTAX_PROTO2, &reftables[12], &reftables[13]),
  6219. UPB_MSGDEF_INIT("google.protobuf.FieldDescriptorProto", 24, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[31], 11, 10), UPB_STRTABLE_INIT(10, 15, UPB_CTYPE_PTR, 4, &strentries[40]), false, UPB_SYNTAX_PROTO2, &reftables[14], &reftables[15]),
  6220. UPB_MSGDEF_INIT("google.protobuf.FieldOptions", 13, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[4], &arrays[42], 11, 6), UPB_STRTABLE_INIT(7, 15, UPB_CTYPE_PTR, 4, &strentries[56]), false, UPB_SYNTAX_PROTO2, &reftables[16], &reftables[17]),
  6221. UPB_MSGDEF_INIT("google.protobuf.FileDescriptorProto", 43, 6, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[53], 13, 12), UPB_STRTABLE_INIT(12, 15, UPB_CTYPE_PTR, 4, &strentries[72]), false, UPB_SYNTAX_PROTO2, &reftables[18], &reftables[19]),
  6222. UPB_MSGDEF_INIT("google.protobuf.FileDescriptorSet", 7, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[66], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[88]), false, UPB_SYNTAX_PROTO2, &reftables[20], &reftables[21]),
  6223. UPB_MSGDEF_INIT("google.protobuf.FileOptions", 38, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[6], &arrays[68], 42, 17), UPB_STRTABLE_INIT(18, 31, UPB_CTYPE_PTR, 5, &strentries[92]), false, UPB_SYNTAX_PROTO2, &reftables[22], &reftables[23]),
  6224. UPB_MSGDEF_INIT("google.protobuf.MessageOptions", 11, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[8], &arrays[110], 8, 4), UPB_STRTABLE_INIT(5, 7, UPB_CTYPE_PTR, 3, &strentries[124]), false, UPB_SYNTAX_PROTO2, &reftables[24], &reftables[25]),
  6225. UPB_MSGDEF_INIT("google.protobuf.MethodDescriptorProto", 16, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[118], 7, 6), UPB_STRTABLE_INIT(6, 7, UPB_CTYPE_PTR, 3, &strentries[132]), false, UPB_SYNTAX_PROTO2, &reftables[26], &reftables[27]),
  6226. UPB_MSGDEF_INIT("google.protobuf.MethodOptions", 8, 1, UPB_INTTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &intentries[10], &arrays[125], 1, 0), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[140]), false, UPB_SYNTAX_PROTO2, &reftables[28], &reftables[29]),
  6227. UPB_MSGDEF_INIT("google.protobuf.OneofDescriptorProto", 6, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[126], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[144]), false, UPB_SYNTAX_PROTO2, &reftables[30], &reftables[31]),
  6228. UPB_MSGDEF_INIT("google.protobuf.ServiceDescriptorProto", 12, 2, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[128], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[148]), false, UPB_SYNTAX_PROTO2, &reftables[32], &reftables[33]),
  6229. UPB_MSGDEF_INIT("google.protobuf.ServiceOptions", 8, 1, UPB_INTTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &intentries[14], &arrays[132], 1, 0), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[152]), false, UPB_SYNTAX_PROTO2, &reftables[34], &reftables[35]),
  6230. UPB_MSGDEF_INIT("google.protobuf.SourceCodeInfo", 7, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[133], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[156]), false, UPB_SYNTAX_PROTO2, &reftables[36], &reftables[37]),
  6231. UPB_MSGDEF_INIT("google.protobuf.SourceCodeInfo.Location", 20, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[135], 7, 5), UPB_STRTABLE_INIT(5, 7, UPB_CTYPE_PTR, 3, &strentries[160]), false, UPB_SYNTAX_PROTO2, &reftables[38], &reftables[39]),
  6232. UPB_MSGDEF_INIT("google.protobuf.UninterpretedOption", 19, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[142], 9, 7), UPB_STRTABLE_INIT(7, 15, UPB_CTYPE_PTR, 4, &strentries[168]), false, UPB_SYNTAX_PROTO2, &reftables[40], &reftables[41]),
  6233. UPB_MSGDEF_INIT("google.protobuf.UninterpretedOption.NamePart", 7, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[151], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[184]), false, UPB_SYNTAX_PROTO2, &reftables[42], &reftables[43]),
  6234. };
  6235. static const upb_fielddef fields[107] = {
  6236. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "aggregate_value", 8, &msgs[20], NULL, 16, 6, {0},&reftables[44], &reftables[45]),
  6237. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "allow_alias", 2, &msgs[4], NULL, 7, 1, {0},&reftables[46], &reftables[47]),
  6238. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "cc_enable_arenas", 31, &msgs[11], NULL, 24, 12, {0},&reftables[48], &reftables[49]),
  6239. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "cc_generic_services", 16, &msgs[11], NULL, 18, 6, {0},&reftables[50], &reftables[51]),
  6240. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "client_streaming", 5, &msgs[13], NULL, 14, 4, {0},&reftables[52], &reftables[53]),
  6241. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "csharp_namespace", 37, &msgs[11], NULL, 28, 14, {0},&reftables[54], &reftables[55]),
  6242. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "ctype", 1, &msgs[8], (const upb_def*)(&enums[2]), 7, 1, {0},&reftables[56], &reftables[57]),
  6243. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "default_value", 7, &msgs[7], NULL, 17, 7, {0},&reftables[58], &reftables[59]),
  6244. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_STRING, 0, false, false, false, false, "dependency", 3, &msgs[9], NULL, 31, 8, {0},&reftables[60], &reftables[61]),
  6245. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[8], NULL, 9, 3, {0},&reftables[62], &reftables[63]),
  6246. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 33, &msgs[14], NULL, 7, 1, {0},&reftables[64], &reftables[65]),
  6247. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[12], NULL, 9, 3, {0},&reftables[66], &reftables[67]),
  6248. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 23, &msgs[11], NULL, 22, 10, {0},&reftables[68], &reftables[69]),
  6249. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 1, &msgs[6], NULL, 7, 1, {0},&reftables[70], &reftables[71]),
  6250. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[4], NULL, 8, 2, {0},&reftables[72], &reftables[73]),
  6251. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 33, &msgs[17], NULL, 7, 1, {0},&reftables[74], &reftables[75]),
  6252. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_DOUBLE, 0, false, false, false, false, "double_value", 6, &msgs[20], NULL, 12, 4, {0},&reftables[76], &reftables[77]),
  6253. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "end", 2, &msgs[2], NULL, 4, 1, {0},&reftables[78], &reftables[79]),
  6254. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "end", 2, &msgs[1], NULL, 4, 1, {0},&reftables[80], &reftables[81]),
  6255. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "enum_type", 5, &msgs[9], (const upb_def*)(&msgs[3]), 14, 1, {0},&reftables[82], &reftables[83]),
  6256. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "enum_type", 4, &msgs[0], (const upb_def*)(&msgs[3]), 19, 2, {0},&reftables[84], &reftables[85]),
  6257. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "extendee", 2, &msgs[7], NULL, 8, 2, {0},&reftables[86], &reftables[87]),
  6258. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension", 6, &msgs[0], (const upb_def*)(&msgs[7]), 25, 4, {0},&reftables[88], &reftables[89]),
  6259. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension", 7, &msgs[9], (const upb_def*)(&msgs[7]), 20, 3, {0},&reftables[90], &reftables[91]),
  6260. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension_range", 5, &msgs[0], (const upb_def*)(&msgs[1]), 22, 3, {0},&reftables[92], &reftables[93]),
  6261. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "field", 2, &msgs[0], (const upb_def*)(&msgs[7]), 13, 0, {0},&reftables[94], &reftables[95]),
  6262. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "file", 1, &msgs[10], (const upb_def*)(&msgs[9]), 6, 0, {0},&reftables[96], &reftables[97]),
  6263. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "go_package", 11, &msgs[11], NULL, 15, 5, {0},&reftables[98], &reftables[99]),
  6264. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "identifier_value", 3, &msgs[20], NULL, 7, 1, {0},&reftables[100], &reftables[101]),
  6265. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "input_type", 2, &msgs[13], NULL, 8, 2, {0},&reftables[102], &reftables[103]),
  6266. UPB_FIELDDEF_INIT(UPB_LABEL_REQUIRED, UPB_TYPE_BOOL, 0, false, false, false, false, "is_extension", 2, &msgs[21], NULL, 6, 1, {0},&reftables[104], &reftables[105]),
  6267. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_generate_equals_and_hash", 20, &msgs[11], NULL, 21, 9, {0},&reftables[106], &reftables[107]),
  6268. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_generic_services", 17, &msgs[11], NULL, 19, 7, {0},&reftables[108], &reftables[109]),
  6269. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_multiple_files", 10, &msgs[11], NULL, 14, 4, {0},&reftables[110], &reftables[111]),
  6270. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "java_outer_classname", 8, &msgs[11], NULL, 10, 2, {0},&reftables[112], &reftables[113]),
  6271. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "java_package", 1, &msgs[11], NULL, 7, 1, {0},&reftables[114], &reftables[115]),
  6272. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_string_check_utf8", 27, &msgs[11], NULL, 23, 11, {0},&reftables[116], &reftables[117]),
  6273. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "javanano_use_deprecated_package", 38, &msgs[11], NULL, 31, 15, {0},&reftables[118], &reftables[119]),
  6274. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "json_name", 10, &msgs[7], NULL, 21, 9, {0},&reftables[120], &reftables[121]),
  6275. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "jstype", 6, &msgs[8], (const upb_def*)(&enums[3]), 11, 5, {0},&reftables[122], &reftables[123]),
  6276. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "label", 4, &msgs[7], (const upb_def*)(&enums[0]), 12, 4, {0},&reftables[124], &reftables[125]),
  6277. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "lazy", 5, &msgs[8], NULL, 10, 4, {0},&reftables[126], &reftables[127]),
  6278. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "leading_comments", 3, &msgs[19], NULL, 9, 2, {0},&reftables[128], &reftables[129]),
  6279. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_STRING, 0, false, false, false, false, "leading_detached_comments", 6, &msgs[19], NULL, 17, 4, {0},&reftables[130], &reftables[131]),
  6280. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "location", 1, &msgs[18], (const upb_def*)(&msgs[19]), 6, 0, {0},&reftables[132], &reftables[133]),
  6281. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "map_entry", 7, &msgs[12], NULL, 10, 4, {0},&reftables[134], &reftables[135]),
  6282. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "message_set_wire_format", 1, &msgs[12], NULL, 7, 1, {0},&reftables[136], &reftables[137]),
  6283. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "message_type", 4, &msgs[9], (const upb_def*)(&msgs[0]), 11, 0, {0},&reftables[138], &reftables[139]),
  6284. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "method", 2, &msgs[16], (const upb_def*)(&msgs[13]), 7, 0, {0},&reftables[140], &reftables[141]),
  6285. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "name", 2, &msgs[20], (const upb_def*)(&msgs[21]), 6, 0, {0},&reftables[142], &reftables[143]),
  6286. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[5], NULL, 5, 1, {0},&reftables[144], &reftables[145]),
  6287. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[9], NULL, 23, 6, {0},&reftables[146], &reftables[147]),
  6288. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[3], NULL, 9, 2, {0},&reftables[148], &reftables[149]),
  6289. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[16], NULL, 9, 2, {0},&reftables[150], &reftables[151]),
  6290. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[15], NULL, 3, 0, {0},&reftables[152], &reftables[153]),
  6291. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[13], NULL, 5, 1, {0},&reftables[154], &reftables[155]),
  6292. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[7], NULL, 5, 1, {0},&reftables[156], &reftables[157]),
  6293. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[0], NULL, 33, 8, {0},&reftables[158], &reftables[159]),
  6294. UPB_FIELDDEF_INIT(UPB_LABEL_REQUIRED, UPB_TYPE_STRING, 0, false, false, false, false, "name_part", 1, &msgs[21], NULL, 3, 0, {0},&reftables[160], &reftables[161]),
  6295. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT64, UPB_INTFMT_VARIABLE, false, false, false, false, "negative_int_value", 5, &msgs[20], NULL, 11, 3, {0},&reftables[162], &reftables[163]),
  6296. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "nested_type", 3, &msgs[0], (const upb_def*)(&msgs[0]), 16, 1, {0},&reftables[164], &reftables[165]),
  6297. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "no_standard_descriptor_accessor", 2, &msgs[12], NULL, 8, 2, {0},&reftables[166], &reftables[167]),
  6298. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "number", 3, &msgs[7], NULL, 11, 3, {0},&reftables[168], &reftables[169]),
  6299. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "number", 2, &msgs[5], NULL, 8, 2, {0},&reftables[170], &reftables[171]),
  6300. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "objc_class_prefix", 36, &msgs[11], NULL, 25, 13, {0},&reftables[172], &reftables[173]),
  6301. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "oneof_decl", 8, &msgs[0], (const upb_def*)(&msgs[15]), 29, 6, {0},&reftables[174], &reftables[175]),
  6302. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "oneof_index", 9, &msgs[7], NULL, 20, 8, {0},&reftables[176], &reftables[177]),
  6303. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "optimize_for", 9, &msgs[11], (const upb_def*)(&enums[4]), 13, 3, {0},&reftables[178], &reftables[179]),
  6304. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 7, &msgs[0], (const upb_def*)(&msgs[12]), 26, 5, {0},&reftables[180], &reftables[181]),
  6305. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 8, &msgs[9], (const upb_def*)(&msgs[11]), 21, 4, {0},&reftables[182], &reftables[183]),
  6306. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 8, &msgs[7], (const upb_def*)(&msgs[8]), 4, 0, {0},&reftables[184], &reftables[185]),
  6307. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 4, &msgs[13], (const upb_def*)(&msgs[14]), 4, 0, {0},&reftables[186], &reftables[187]),
  6308. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[16], (const upb_def*)(&msgs[17]), 8, 1, {0},&reftables[188], &reftables[189]),
  6309. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[3], (const upb_def*)(&msgs[4]), 8, 1, {0},&reftables[190], &reftables[191]),
  6310. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[5], (const upb_def*)(&msgs[6]), 4, 0, {0},&reftables[192], &reftables[193]),
  6311. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "output_type", 3, &msgs[13], NULL, 11, 3, {0},&reftables[194], &reftables[195]),
  6312. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "package", 2, &msgs[9], NULL, 26, 7, {0},&reftables[196], &reftables[197]),
  6313. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "packed", 2, &msgs[8], NULL, 8, 2, {0},&reftables[198], &reftables[199]),
  6314. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, true, "path", 1, &msgs[19], NULL, 5, 0, {0},&reftables[200], &reftables[201]),
  6315. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "php_class_prefix", 40, &msgs[11], NULL, 32, 16, {0},&reftables[202], &reftables[203]),
  6316. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "php_namespace", 41, &msgs[11], NULL, 35, 17, {0},&reftables[204], &reftables[205]),
  6317. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_UINT64, UPB_INTFMT_VARIABLE, false, false, false, false, "positive_int_value", 4, &msgs[20], NULL, 10, 2, {0},&reftables[206], &reftables[207]),
  6318. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "public_dependency", 10, &msgs[9], NULL, 36, 9, {0},&reftables[208], &reftables[209]),
  6319. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "py_generic_services", 18, &msgs[11], NULL, 20, 8, {0},&reftables[210], &reftables[211]),
  6320. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_STRING, 0, false, false, false, false, "reserved_name", 10, &msgs[0], NULL, 38, 9, {0},&reftables[212], &reftables[213]),
  6321. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "reserved_range", 9, &msgs[0], (const upb_def*)(&msgs[2]), 32, 7, {0},&reftables[214], &reftables[215]),
  6322. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "server_streaming", 6, &msgs[13], NULL, 15, 5, {0},&reftables[216], &reftables[217]),
  6323. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "service", 6, &msgs[9], (const upb_def*)(&msgs[16]), 17, 2, {0},&reftables[218], &reftables[219]),
  6324. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "source_code_info", 9, &msgs[9], (const upb_def*)(&msgs[18]), 22, 5, {0},&reftables[220], &reftables[221]),
  6325. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, true, "span", 2, &msgs[19], NULL, 8, 1, {0},&reftables[222], &reftables[223]),
  6326. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "start", 1, &msgs[2], NULL, 3, 0, {0},&reftables[224], &reftables[225]),
  6327. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "start", 1, &msgs[1], NULL, 3, 0, {0},&reftables[226], &reftables[227]),
  6328. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BYTES, 0, false, false, false, false, "string_value", 7, &msgs[20], NULL, 13, 5, {0},&reftables[228], &reftables[229]),
  6329. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "syntax", 12, &msgs[9], NULL, 40, 11, {0},&reftables[230], &reftables[231]),
  6330. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "trailing_comments", 4, &msgs[19], NULL, 12, 3, {0},&reftables[232], &reftables[233]),
  6331. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "type", 5, &msgs[7], (const upb_def*)(&enums[1]), 13, 5, {0},&reftables[234], &reftables[235]),
  6332. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "type_name", 6, &msgs[7], NULL, 14, 6, {0},&reftables[236], &reftables[237]),
  6333. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[12], (const upb_def*)(&msgs[20]), 6, 0, {0},&reftables[238], &reftables[239]),
  6334. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[17], (const upb_def*)(&msgs[20]), 6, 0, {0},&reftables[240], &reftables[241]),
  6335. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[11], (const upb_def*)(&msgs[20]), 6, 0, {0},&reftables[242], &reftables[243]),
  6336. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[14], (const upb_def*)(&msgs[20]), 6, 0, {0},&reftables[244], &reftables[245]),
  6337. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[8], (const upb_def*)(&msgs[20]), 6, 0, {0},&reftables[246], &reftables[247]),
  6338. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[6], (const upb_def*)(&msgs[20]), 6, 0, {0},&reftables[248], &reftables[249]),
  6339. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[4], (const upb_def*)(&msgs[20]), 6, 0, {0},&reftables[250], &reftables[251]),
  6340. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "value", 2, &msgs[3], (const upb_def*)(&msgs[5]), 7, 0, {0},&reftables[252], &reftables[253]),
  6341. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "weak", 10, &msgs[8], NULL, 12, 6, {0},&reftables[254], &reftables[255]),
  6342. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "weak_dependency", 11, &msgs[9], NULL, 39, 10, {0},&reftables[256], &reftables[257]),
  6343. };
  6344. static const upb_enumdef enums[5] = {
  6345. UPB_ENUMDEF_INIT("google.protobuf.FieldDescriptorProto.Label", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[188]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[154], 4, 3), 0, &reftables[258], &reftables[259]),
  6346. UPB_ENUMDEF_INIT("google.protobuf.FieldDescriptorProto.Type", UPB_STRTABLE_INIT(18, 31, UPB_CTYPE_INT32, 5, &strentries[192]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[158], 19, 18), 0, &reftables[260], &reftables[261]),
  6347. UPB_ENUMDEF_INIT("google.protobuf.FieldOptions.CType", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[224]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[177], 3, 3), 0, &reftables[262], &reftables[263]),
  6348. UPB_ENUMDEF_INIT("google.protobuf.FieldOptions.JSType", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[228]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[180], 3, 3), 0, &reftables[264], &reftables[265]),
  6349. UPB_ENUMDEF_INIT("google.protobuf.FileOptions.OptimizeMode", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[232]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[183], 4, 3), 0, &reftables[266], &reftables[267]),
  6350. };
  6351. static const upb_tabent strentries[236] = {
  6352. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "extension"), UPB_TABVALUE_PTR_INIT(&fields[22]), NULL},
  6353. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6354. {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "reserved_name"), UPB_TABVALUE_PTR_INIT(&fields[84]), NULL},
  6355. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[57]), NULL},
  6356. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6357. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6358. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6359. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "field"), UPB_TABVALUE_PTR_INIT(&fields[25]), &strentries[12]},
  6360. {UPB_TABKEY_STR("\017", "\000", "\000", "\000", "extension_range"), UPB_TABVALUE_PTR_INIT(&fields[24]), &strentries[14]},
  6361. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6362. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "nested_type"), UPB_TABVALUE_PTR_INIT(&fields[60]), NULL},
  6363. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6364. {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "reserved_range"), UPB_TABVALUE_PTR_INIT(&fields[85]), NULL},
  6365. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[68]), NULL},
  6366. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "oneof_decl"), UPB_TABVALUE_PTR_INIT(&fields[65]), NULL},
  6367. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "enum_type"), UPB_TABVALUE_PTR_INIT(&fields[20]), &strentries[13]},
  6368. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "start"), UPB_TABVALUE_PTR_INIT(&fields[91]), NULL},
  6369. {UPB_TABKEY_STR("\003", "\000", "\000", "\000", "end"), UPB_TABVALUE_PTR_INIT(&fields[18]), NULL},
  6370. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6371. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6372. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "start"), UPB_TABVALUE_PTR_INIT(&fields[90]), NULL},
  6373. {UPB_TABKEY_STR("\003", "\000", "\000", "\000", "end"), UPB_TABVALUE_PTR_INIT(&fields[17]), NULL},
  6374. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6375. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6376. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6377. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "value"), UPB_TABVALUE_PTR_INIT(&fields[104]), NULL},
  6378. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[73]), NULL},
  6379. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[52]), &strentries[26]},
  6380. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[103]), NULL},
  6381. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[14]), NULL},
  6382. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "allow_alias"), UPB_TABVALUE_PTR_INIT(&fields[1]), NULL},
  6383. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6384. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "number"), UPB_TABVALUE_PTR_INIT(&fields[63]), NULL},
  6385. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6386. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[74]), NULL},
  6387. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[50]), &strentries[34]},
  6388. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[102]), NULL},
  6389. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[13]), NULL},
  6390. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6391. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6392. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "oneof_index"), UPB_TABVALUE_PTR_INIT(&fields[66]), NULL},
  6393. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "label"), UPB_TABVALUE_PTR_INIT(&fields[40]), NULL},
  6394. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6395. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[56]), NULL},
  6396. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6397. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6398. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6399. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6400. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "number"), UPB_TABVALUE_PTR_INIT(&fields[62]), &strentries[53]},
  6401. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6402. {UPB_TABKEY_STR("\010", "\000", "\000", "\000", "extendee"), UPB_TABVALUE_PTR_INIT(&fields[21]), NULL},
  6403. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "type_name"), UPB_TABVALUE_PTR_INIT(&fields[96]), NULL},
  6404. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "json_name"), UPB_TABVALUE_PTR_INIT(&fields[38]), NULL},
  6405. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "type"), UPB_TABVALUE_PTR_INIT(&fields[95]), &strentries[50]},
  6406. {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "default_value"), UPB_TABVALUE_PTR_INIT(&fields[7]), NULL},
  6407. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[70]), NULL},
  6408. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[101]), NULL},
  6409. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6410. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "weak"), UPB_TABVALUE_PTR_INIT(&fields[105]), NULL},
  6411. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6412. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6413. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6414. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6415. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "packed"), UPB_TABVALUE_PTR_INIT(&fields[77]), NULL},
  6416. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "lazy"), UPB_TABVALUE_PTR_INIT(&fields[41]), NULL},
  6417. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6418. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "ctype"), UPB_TABVALUE_PTR_INIT(&fields[6]), NULL},
  6419. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6420. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "jstype"), UPB_TABVALUE_PTR_INIT(&fields[39]), NULL},
  6421. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[9]), NULL},
  6422. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6423. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6424. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "extension"), UPB_TABVALUE_PTR_INIT(&fields[23]), NULL},
  6425. {UPB_TABKEY_STR("\017", "\000", "\000", "\000", "weak_dependency"), UPB_TABVALUE_PTR_INIT(&fields[106]), NULL},
  6426. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6427. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[51]), NULL},
  6428. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "service"), UPB_TABVALUE_PTR_INIT(&fields[87]), NULL},
  6429. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6430. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "source_code_info"), UPB_TABVALUE_PTR_INIT(&fields[88]), NULL},
  6431. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6432. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6433. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "syntax"), UPB_TABVALUE_PTR_INIT(&fields[93]), NULL},
  6434. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "dependency"), UPB_TABVALUE_PTR_INIT(&fields[8]), NULL},
  6435. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "message_type"), UPB_TABVALUE_PTR_INIT(&fields[47]), NULL},
  6436. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "package"), UPB_TABVALUE_PTR_INIT(&fields[76]), NULL},
  6437. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[69]), &strentries[86]},
  6438. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "enum_type"), UPB_TABVALUE_PTR_INIT(&fields[19]), NULL},
  6439. {UPB_TABKEY_STR("\021", "\000", "\000", "\000", "public_dependency"), UPB_TABVALUE_PTR_INIT(&fields[82]), &strentries[85]},
  6440. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6441. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "file"), UPB_TABVALUE_PTR_INIT(&fields[26]), NULL},
  6442. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6443. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6444. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6445. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6446. {UPB_TABKEY_STR("\023", "\000", "\000", "\000", "cc_generic_services"), UPB_TABVALUE_PTR_INIT(&fields[3]), NULL},
  6447. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "csharp_namespace"), UPB_TABVALUE_PTR_INIT(&fields[5]), &strentries[116]},
  6448. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6449. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6450. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6451. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6452. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6453. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6454. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6455. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "go_package"), UPB_TABVALUE_PTR_INIT(&fields[27]), NULL},
  6456. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "java_package"), UPB_TABVALUE_PTR_INIT(&fields[35]), &strentries[120]},
  6457. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6458. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6459. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "java_outer_classname"), UPB_TABVALUE_PTR_INIT(&fields[34]), NULL},
  6460. {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "php_namespace"), UPB_TABVALUE_PTR_INIT(&fields[80]), &strentries[113]},
  6461. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6462. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6463. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6464. {UPB_TABKEY_STR("\023", "\000", "\000", "\000", "java_multiple_files"), UPB_TABVALUE_PTR_INIT(&fields[33]), &strentries[117]},
  6465. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[99]), NULL},
  6466. {UPB_TABKEY_STR("\025", "\000", "\000", "\000", "java_generic_services"), UPB_TABVALUE_PTR_INIT(&fields[32]), &strentries[118]},
  6467. {UPB_TABKEY_STR("\035", "\000", "\000", "\000", "java_generate_equals_and_hash"), UPB_TABVALUE_PTR_INIT(&fields[31]), NULL},
  6468. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "php_class_prefix"), UPB_TABVALUE_PTR_INIT(&fields[79]), NULL},
  6469. {UPB_TABKEY_STR("\037", "\000", "\000", "\000", "javanano_use_deprecated_package"), UPB_TABVALUE_PTR_INIT(&fields[37]), &strentries[123]},
  6470. {UPB_TABKEY_STR("\023", "\000", "\000", "\000", "py_generic_services"), UPB_TABVALUE_PTR_INIT(&fields[83]), NULL},
  6471. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "optimize_for"), UPB_TABVALUE_PTR_INIT(&fields[67]), NULL},
  6472. {UPB_TABKEY_STR("\026", "\000", "\000", "\000", "java_string_check_utf8"), UPB_TABVALUE_PTR_INIT(&fields[36]), NULL},
  6473. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[12]), &strentries[119]},
  6474. {UPB_TABKEY_STR("\021", "\000", "\000", "\000", "objc_class_prefix"), UPB_TABVALUE_PTR_INIT(&fields[64]), NULL},
  6475. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "cc_enable_arenas"), UPB_TABVALUE_PTR_INIT(&fields[2]), NULL},
  6476. {UPB_TABKEY_STR("\027", "\000", "\000", "\000", "message_set_wire_format"), UPB_TABVALUE_PTR_INIT(&fields[46]), &strentries[128]},
  6477. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6478. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6479. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6480. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[97]), NULL},
  6481. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[11]), NULL},
  6482. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "map_entry"), UPB_TABVALUE_PTR_INIT(&fields[45]), NULL},
  6483. {UPB_TABKEY_STR("\037", "\000", "\000", "\000", "no_standard_descriptor_accessor"), UPB_TABVALUE_PTR_INIT(&fields[61]), NULL},
  6484. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6485. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "client_streaming"), UPB_TABVALUE_PTR_INIT(&fields[4]), NULL},
  6486. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "server_streaming"), UPB_TABVALUE_PTR_INIT(&fields[86]), NULL},
  6487. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[55]), NULL},
  6488. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "input_type"), UPB_TABVALUE_PTR_INIT(&fields[29]), NULL},
  6489. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6490. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "output_type"), UPB_TABVALUE_PTR_INIT(&fields[75]), NULL},
  6491. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[71]), NULL},
  6492. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[100]), NULL},
  6493. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[10]), NULL},
  6494. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6495. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6496. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6497. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6498. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6499. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[54]), NULL},
  6500. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6501. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[72]), &strentries[150]},
  6502. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "method"), UPB_TABVALUE_PTR_INIT(&fields[48]), NULL},
  6503. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[53]), &strentries[149]},
  6504. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[98]), NULL},
  6505. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[15]), NULL},
  6506. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6507. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6508. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6509. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6510. {UPB_TABKEY_STR("\010", "\000", "\000", "\000", "location"), UPB_TABVALUE_PTR_INIT(&fields[44]), NULL},
  6511. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6512. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6513. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6514. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6515. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "span"), UPB_TABVALUE_PTR_INIT(&fields[89]), &strentries[167]},
  6516. {UPB_TABKEY_STR("\031", "\000", "\000", "\000", "leading_detached_comments"), UPB_TABVALUE_PTR_INIT(&fields[43]), &strentries[165]},
  6517. {UPB_TABKEY_STR("\021", "\000", "\000", "\000", "trailing_comments"), UPB_TABVALUE_PTR_INIT(&fields[94]), NULL},
  6518. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "leading_comments"), UPB_TABVALUE_PTR_INIT(&fields[42]), &strentries[164]},
  6519. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "path"), UPB_TABVALUE_PTR_INIT(&fields[78]), NULL},
  6520. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "double_value"), UPB_TABVALUE_PTR_INIT(&fields[16]), NULL},
  6521. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6522. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6523. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[49]), NULL},
  6524. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6525. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6526. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6527. {UPB_TABKEY_STR("\022", "\000", "\000", "\000", "negative_int_value"), UPB_TABVALUE_PTR_INIT(&fields[59]), NULL},
  6528. {UPB_TABKEY_STR("\017", "\000", "\000", "\000", "aggregate_value"), UPB_TABVALUE_PTR_INIT(&fields[0]), NULL},
  6529. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6530. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6531. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6532. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6533. {UPB_TABKEY_STR("\022", "\000", "\000", "\000", "positive_int_value"), UPB_TABVALUE_PTR_INIT(&fields[81]), NULL},
  6534. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "identifier_value"), UPB_TABVALUE_PTR_INIT(&fields[28]), NULL},
  6535. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "string_value"), UPB_TABVALUE_PTR_INIT(&fields[92]), &strentries[182]},
  6536. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6537. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6538. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "is_extension"), UPB_TABVALUE_PTR_INIT(&fields[30]), NULL},
  6539. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "name_part"), UPB_TABVALUE_PTR_INIT(&fields[58]), NULL},
  6540. {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "LABEL_REQUIRED"), UPB_TABVALUE_INT_INIT(2), &strentries[190]},
  6541. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6542. {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "LABEL_REPEATED"), UPB_TABVALUE_INT_INIT(3), NULL},
  6543. {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "LABEL_OPTIONAL"), UPB_TABVALUE_INT_INIT(1), NULL},
  6544. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "TYPE_FIXED64"), UPB_TABVALUE_INT_INIT(6), NULL},
  6545. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6546. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6547. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6548. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6549. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_STRING"), UPB_TABVALUE_INT_INIT(9), NULL},
  6550. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_FLOAT"), UPB_TABVALUE_INT_INIT(2), &strentries[221]},
  6551. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_DOUBLE"), UPB_TABVALUE_INT_INIT(1), NULL},
  6552. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6553. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_INT32"), UPB_TABVALUE_INT_INIT(5), NULL},
  6554. {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "TYPE_SFIXED32"), UPB_TABVALUE_INT_INIT(15), NULL},
  6555. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "TYPE_FIXED32"), UPB_TABVALUE_INT_INIT(7), NULL},
  6556. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6557. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "TYPE_MESSAGE"), UPB_TABVALUE_INT_INIT(11), &strentries[222]},
  6558. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6559. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6560. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_INT64"), UPB_TABVALUE_INT_INIT(3), &strentries[219]},
  6561. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6562. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6563. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6564. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6565. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "TYPE_ENUM"), UPB_TABVALUE_INT_INIT(14), NULL},
  6566. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_UINT32"), UPB_TABVALUE_INT_INIT(13), NULL},
  6567. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6568. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_UINT64"), UPB_TABVALUE_INT_INIT(4), &strentries[218]},
  6569. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6570. {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "TYPE_SFIXED64"), UPB_TABVALUE_INT_INIT(16), NULL},
  6571. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_BYTES"), UPB_TABVALUE_INT_INIT(12), NULL},
  6572. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_SINT64"), UPB_TABVALUE_INT_INIT(18), NULL},
  6573. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "TYPE_BOOL"), UPB_TABVALUE_INT_INIT(8), NULL},
  6574. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_GROUP"), UPB_TABVALUE_INT_INIT(10), NULL},
  6575. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_SINT32"), UPB_TABVALUE_INT_INIT(17), NULL},
  6576. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6577. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "CORD"), UPB_TABVALUE_INT_INIT(1), NULL},
  6578. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "STRING"), UPB_TABVALUE_INT_INIT(0), &strentries[225]},
  6579. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "STRING_PIECE"), UPB_TABVALUE_INT_INIT(2), NULL},
  6580. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6581. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "JS_NORMAL"), UPB_TABVALUE_INT_INIT(0), NULL},
  6582. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "JS_NUMBER"), UPB_TABVALUE_INT_INIT(2), NULL},
  6583. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "JS_STRING"), UPB_TABVALUE_INT_INIT(1), NULL},
  6584. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "CODE_SIZE"), UPB_TABVALUE_INT_INIT(2), NULL},
  6585. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "SPEED"), UPB_TABVALUE_INT_INIT(1), &strentries[235]},
  6586. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6587. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "LITE_RUNTIME"), UPB_TABVALUE_INT_INIT(3), NULL},
  6588. };
  6589. static const upb_tabent intentries[18] = {
  6590. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6591. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[103]), NULL},
  6592. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6593. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[102]), NULL},
  6594. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6595. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[101]), NULL},
  6596. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6597. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[99]), NULL},
  6598. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6599. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[97]), NULL},
  6600. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6601. {UPB_TABKEY_NUM(33), UPB_TABVALUE_PTR_INIT(&fields[10]), NULL},
  6602. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6603. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[100]), NULL},
  6604. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6605. {UPB_TABKEY_NUM(33), UPB_TABVALUE_PTR_INIT(&fields[15]), NULL},
  6606. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6607. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[98]), NULL},
  6608. };
  6609. static const upb_tabval arrays[187] = {
  6610. UPB_TABVALUE_EMPTY_INIT,
  6611. UPB_TABVALUE_PTR_INIT(&fields[57]),
  6612. UPB_TABVALUE_PTR_INIT(&fields[25]),
  6613. UPB_TABVALUE_PTR_INIT(&fields[60]),
  6614. UPB_TABVALUE_PTR_INIT(&fields[20]),
  6615. UPB_TABVALUE_PTR_INIT(&fields[24]),
  6616. UPB_TABVALUE_PTR_INIT(&fields[22]),
  6617. UPB_TABVALUE_PTR_INIT(&fields[68]),
  6618. UPB_TABVALUE_PTR_INIT(&fields[65]),
  6619. UPB_TABVALUE_PTR_INIT(&fields[85]),
  6620. UPB_TABVALUE_PTR_INIT(&fields[84]),
  6621. UPB_TABVALUE_EMPTY_INIT,
  6622. UPB_TABVALUE_PTR_INIT(&fields[91]),
  6623. UPB_TABVALUE_PTR_INIT(&fields[18]),
  6624. UPB_TABVALUE_EMPTY_INIT,
  6625. UPB_TABVALUE_PTR_INIT(&fields[90]),
  6626. UPB_TABVALUE_PTR_INIT(&fields[17]),
  6627. UPB_TABVALUE_EMPTY_INIT,
  6628. UPB_TABVALUE_PTR_INIT(&fields[52]),
  6629. UPB_TABVALUE_PTR_INIT(&fields[104]),
  6630. UPB_TABVALUE_PTR_INIT(&fields[73]),
  6631. UPB_TABVALUE_EMPTY_INIT,
  6632. UPB_TABVALUE_EMPTY_INIT,
  6633. UPB_TABVALUE_PTR_INIT(&fields[1]),
  6634. UPB_TABVALUE_PTR_INIT(&fields[14]),
  6635. UPB_TABVALUE_EMPTY_INIT,
  6636. UPB_TABVALUE_PTR_INIT(&fields[50]),
  6637. UPB_TABVALUE_PTR_INIT(&fields[63]),
  6638. UPB_TABVALUE_PTR_INIT(&fields[74]),
  6639. UPB_TABVALUE_EMPTY_INIT,
  6640. UPB_TABVALUE_PTR_INIT(&fields[13]),
  6641. UPB_TABVALUE_EMPTY_INIT,
  6642. UPB_TABVALUE_PTR_INIT(&fields[56]),
  6643. UPB_TABVALUE_PTR_INIT(&fields[21]),
  6644. UPB_TABVALUE_PTR_INIT(&fields[62]),
  6645. UPB_TABVALUE_PTR_INIT(&fields[40]),
  6646. UPB_TABVALUE_PTR_INIT(&fields[95]),
  6647. UPB_TABVALUE_PTR_INIT(&fields[96]),
  6648. UPB_TABVALUE_PTR_INIT(&fields[7]),
  6649. UPB_TABVALUE_PTR_INIT(&fields[70]),
  6650. UPB_TABVALUE_PTR_INIT(&fields[66]),
  6651. UPB_TABVALUE_PTR_INIT(&fields[38]),
  6652. UPB_TABVALUE_EMPTY_INIT,
  6653. UPB_TABVALUE_PTR_INIT(&fields[6]),
  6654. UPB_TABVALUE_PTR_INIT(&fields[77]),
  6655. UPB_TABVALUE_PTR_INIT(&fields[9]),
  6656. UPB_TABVALUE_EMPTY_INIT,
  6657. UPB_TABVALUE_PTR_INIT(&fields[41]),
  6658. UPB_TABVALUE_PTR_INIT(&fields[39]),
  6659. UPB_TABVALUE_EMPTY_INIT,
  6660. UPB_TABVALUE_EMPTY_INIT,
  6661. UPB_TABVALUE_EMPTY_INIT,
  6662. UPB_TABVALUE_PTR_INIT(&fields[105]),
  6663. UPB_TABVALUE_EMPTY_INIT,
  6664. UPB_TABVALUE_PTR_INIT(&fields[51]),
  6665. UPB_TABVALUE_PTR_INIT(&fields[76]),
  6666. UPB_TABVALUE_PTR_INIT(&fields[8]),
  6667. UPB_TABVALUE_PTR_INIT(&fields[47]),
  6668. UPB_TABVALUE_PTR_INIT(&fields[19]),
  6669. UPB_TABVALUE_PTR_INIT(&fields[87]),
  6670. UPB_TABVALUE_PTR_INIT(&fields[23]),
  6671. UPB_TABVALUE_PTR_INIT(&fields[69]),
  6672. UPB_TABVALUE_PTR_INIT(&fields[88]),
  6673. UPB_TABVALUE_PTR_INIT(&fields[82]),
  6674. UPB_TABVALUE_PTR_INIT(&fields[106]),
  6675. UPB_TABVALUE_PTR_INIT(&fields[93]),
  6676. UPB_TABVALUE_EMPTY_INIT,
  6677. UPB_TABVALUE_PTR_INIT(&fields[26]),
  6678. UPB_TABVALUE_EMPTY_INIT,
  6679. UPB_TABVALUE_PTR_INIT(&fields[35]),
  6680. UPB_TABVALUE_EMPTY_INIT,
  6681. UPB_TABVALUE_EMPTY_INIT,
  6682. UPB_TABVALUE_EMPTY_INIT,
  6683. UPB_TABVALUE_EMPTY_INIT,
  6684. UPB_TABVALUE_EMPTY_INIT,
  6685. UPB_TABVALUE_EMPTY_INIT,
  6686. UPB_TABVALUE_PTR_INIT(&fields[34]),
  6687. UPB_TABVALUE_PTR_INIT(&fields[67]),
  6688. UPB_TABVALUE_PTR_INIT(&fields[33]),
  6689. UPB_TABVALUE_PTR_INIT(&fields[27]),
  6690. UPB_TABVALUE_EMPTY_INIT,
  6691. UPB_TABVALUE_EMPTY_INIT,
  6692. UPB_TABVALUE_EMPTY_INIT,
  6693. UPB_TABVALUE_EMPTY_INIT,
  6694. UPB_TABVALUE_PTR_INIT(&fields[3]),
  6695. UPB_TABVALUE_PTR_INIT(&fields[32]),
  6696. UPB_TABVALUE_PTR_INIT(&fields[83]),
  6697. UPB_TABVALUE_EMPTY_INIT,
  6698. UPB_TABVALUE_PTR_INIT(&fields[31]),
  6699. UPB_TABVALUE_EMPTY_INIT,
  6700. UPB_TABVALUE_EMPTY_INIT,
  6701. UPB_TABVALUE_PTR_INIT(&fields[12]),
  6702. UPB_TABVALUE_EMPTY_INIT,
  6703. UPB_TABVALUE_EMPTY_INIT,
  6704. UPB_TABVALUE_EMPTY_INIT,
  6705. UPB_TABVALUE_PTR_INIT(&fields[36]),
  6706. UPB_TABVALUE_EMPTY_INIT,
  6707. UPB_TABVALUE_EMPTY_INIT,
  6708. UPB_TABVALUE_EMPTY_INIT,
  6709. UPB_TABVALUE_PTR_INIT(&fields[2]),
  6710. UPB_TABVALUE_EMPTY_INIT,
  6711. UPB_TABVALUE_EMPTY_INIT,
  6712. UPB_TABVALUE_EMPTY_INIT,
  6713. UPB_TABVALUE_EMPTY_INIT,
  6714. UPB_TABVALUE_PTR_INIT(&fields[64]),
  6715. UPB_TABVALUE_PTR_INIT(&fields[5]),
  6716. UPB_TABVALUE_PTR_INIT(&fields[37]),
  6717. UPB_TABVALUE_EMPTY_INIT,
  6718. UPB_TABVALUE_PTR_INIT(&fields[79]),
  6719. UPB_TABVALUE_PTR_INIT(&fields[80]),
  6720. UPB_TABVALUE_EMPTY_INIT,
  6721. UPB_TABVALUE_PTR_INIT(&fields[46]),
  6722. UPB_TABVALUE_PTR_INIT(&fields[61]),
  6723. UPB_TABVALUE_PTR_INIT(&fields[11]),
  6724. UPB_TABVALUE_EMPTY_INIT,
  6725. UPB_TABVALUE_EMPTY_INIT,
  6726. UPB_TABVALUE_EMPTY_INIT,
  6727. UPB_TABVALUE_PTR_INIT(&fields[45]),
  6728. UPB_TABVALUE_EMPTY_INIT,
  6729. UPB_TABVALUE_PTR_INIT(&fields[55]),
  6730. UPB_TABVALUE_PTR_INIT(&fields[29]),
  6731. UPB_TABVALUE_PTR_INIT(&fields[75]),
  6732. UPB_TABVALUE_PTR_INIT(&fields[71]),
  6733. UPB_TABVALUE_PTR_INIT(&fields[4]),
  6734. UPB_TABVALUE_PTR_INIT(&fields[86]),
  6735. UPB_TABVALUE_EMPTY_INIT,
  6736. UPB_TABVALUE_EMPTY_INIT,
  6737. UPB_TABVALUE_PTR_INIT(&fields[54]),
  6738. UPB_TABVALUE_EMPTY_INIT,
  6739. UPB_TABVALUE_PTR_INIT(&fields[53]),
  6740. UPB_TABVALUE_PTR_INIT(&fields[48]),
  6741. UPB_TABVALUE_PTR_INIT(&fields[72]),
  6742. UPB_TABVALUE_EMPTY_INIT,
  6743. UPB_TABVALUE_EMPTY_INIT,
  6744. UPB_TABVALUE_PTR_INIT(&fields[44]),
  6745. UPB_TABVALUE_EMPTY_INIT,
  6746. UPB_TABVALUE_PTR_INIT(&fields[78]),
  6747. UPB_TABVALUE_PTR_INIT(&fields[89]),
  6748. UPB_TABVALUE_PTR_INIT(&fields[42]),
  6749. UPB_TABVALUE_PTR_INIT(&fields[94]),
  6750. UPB_TABVALUE_EMPTY_INIT,
  6751. UPB_TABVALUE_PTR_INIT(&fields[43]),
  6752. UPB_TABVALUE_EMPTY_INIT,
  6753. UPB_TABVALUE_EMPTY_INIT,
  6754. UPB_TABVALUE_PTR_INIT(&fields[49]),
  6755. UPB_TABVALUE_PTR_INIT(&fields[28]),
  6756. UPB_TABVALUE_PTR_INIT(&fields[81]),
  6757. UPB_TABVALUE_PTR_INIT(&fields[59]),
  6758. UPB_TABVALUE_PTR_INIT(&fields[16]),
  6759. UPB_TABVALUE_PTR_INIT(&fields[92]),
  6760. UPB_TABVALUE_PTR_INIT(&fields[0]),
  6761. UPB_TABVALUE_EMPTY_INIT,
  6762. UPB_TABVALUE_PTR_INIT(&fields[58]),
  6763. UPB_TABVALUE_PTR_INIT(&fields[30]),
  6764. UPB_TABVALUE_EMPTY_INIT,
  6765. UPB_TABVALUE_PTR_INIT("LABEL_OPTIONAL"),
  6766. UPB_TABVALUE_PTR_INIT("LABEL_REQUIRED"),
  6767. UPB_TABVALUE_PTR_INIT("LABEL_REPEATED"),
  6768. UPB_TABVALUE_EMPTY_INIT,
  6769. UPB_TABVALUE_PTR_INIT("TYPE_DOUBLE"),
  6770. UPB_TABVALUE_PTR_INIT("TYPE_FLOAT"),
  6771. UPB_TABVALUE_PTR_INIT("TYPE_INT64"),
  6772. UPB_TABVALUE_PTR_INIT("TYPE_UINT64"),
  6773. UPB_TABVALUE_PTR_INIT("TYPE_INT32"),
  6774. UPB_TABVALUE_PTR_INIT("TYPE_FIXED64"),
  6775. UPB_TABVALUE_PTR_INIT("TYPE_FIXED32"),
  6776. UPB_TABVALUE_PTR_INIT("TYPE_BOOL"),
  6777. UPB_TABVALUE_PTR_INIT("TYPE_STRING"),
  6778. UPB_TABVALUE_PTR_INIT("TYPE_GROUP"),
  6779. UPB_TABVALUE_PTR_INIT("TYPE_MESSAGE"),
  6780. UPB_TABVALUE_PTR_INIT("TYPE_BYTES"),
  6781. UPB_TABVALUE_PTR_INIT("TYPE_UINT32"),
  6782. UPB_TABVALUE_PTR_INIT("TYPE_ENUM"),
  6783. UPB_TABVALUE_PTR_INIT("TYPE_SFIXED32"),
  6784. UPB_TABVALUE_PTR_INIT("TYPE_SFIXED64"),
  6785. UPB_TABVALUE_PTR_INIT("TYPE_SINT32"),
  6786. UPB_TABVALUE_PTR_INIT("TYPE_SINT64"),
  6787. UPB_TABVALUE_PTR_INIT("STRING"),
  6788. UPB_TABVALUE_PTR_INIT("CORD"),
  6789. UPB_TABVALUE_PTR_INIT("STRING_PIECE"),
  6790. UPB_TABVALUE_PTR_INIT("JS_NORMAL"),
  6791. UPB_TABVALUE_PTR_INIT("JS_STRING"),
  6792. UPB_TABVALUE_PTR_INIT("JS_NUMBER"),
  6793. UPB_TABVALUE_EMPTY_INIT,
  6794. UPB_TABVALUE_PTR_INIT("SPEED"),
  6795. UPB_TABVALUE_PTR_INIT("CODE_SIZE"),
  6796. UPB_TABVALUE_PTR_INIT("LITE_RUNTIME"),
  6797. };
  6798. #ifdef UPB_DEBUG_REFS
  6799. static upb_inttable reftables[268] = {
  6800. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6801. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6802. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6803. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6804. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6805. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6806. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6807. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6808. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6809. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6810. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6811. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6812. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6813. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6814. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6815. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6816. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6817. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6818. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6819. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6820. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6821. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6822. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6823. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6824. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6825. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6826. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6827. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6828. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6829. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6830. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6831. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6832. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6833. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6834. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6835. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6836. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6837. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6838. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6839. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6840. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6841. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6842. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6843. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6844. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6845. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6846. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6847. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6848. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6849. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6850. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6851. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6852. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6853. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6854. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6855. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6856. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6857. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6858. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6859. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6860. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6861. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6862. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6863. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6864. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6865. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6866. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6867. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6868. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6869. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6870. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6871. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6872. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6873. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6874. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6875. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6876. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6877. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6878. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6879. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6880. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6881. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6882. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6883. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6884. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6885. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6886. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6887. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6888. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6889. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6890. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6891. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6892. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6893. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6894. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6895. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6896. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6897. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6898. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6899. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6900. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6901. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6902. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6903. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6904. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6905. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6906. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6907. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6908. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6909. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6910. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6911. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6912. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6913. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6914. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6915. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6916. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6917. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6918. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6919. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6920. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6921. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6922. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6923. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6924. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6925. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6926. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6927. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6928. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6929. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6930. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6931. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6932. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6933. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6934. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6935. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6936. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6937. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6938. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6939. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6940. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6941. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6942. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6943. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6944. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6945. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6946. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6947. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6948. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6949. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6950. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6951. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6952. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6953. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6954. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6955. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6956. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6957. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6958. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6959. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6960. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6961. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6962. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6963. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6964. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6965. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6966. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6967. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6968. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6969. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6970. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6971. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6972. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6973. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6974. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6975. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6976. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6977. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6978. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6979. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6980. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6981. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6982. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6983. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6984. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6985. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6986. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6987. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6988. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6989. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6990. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6991. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6992. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6993. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6994. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6995. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6996. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6997. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6998. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6999. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7000. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7001. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7002. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7003. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7004. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7005. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7006. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7007. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7008. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7009. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7010. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7011. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7012. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7013. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7014. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7015. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7016. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7017. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7018. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7019. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7020. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7021. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7022. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7023. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7024. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7025. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7026. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7027. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7028. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7029. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7030. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7031. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7032. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7033. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7034. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7035. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7036. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7037. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7038. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7039. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7040. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7041. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7042. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7043. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7044. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7045. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7046. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7047. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7048. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7049. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7050. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7051. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7052. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7053. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7054. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7055. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7056. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7057. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7058. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7059. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7060. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7061. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7062. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7063. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7064. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7065. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7066. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7067. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7068. };
  7069. #endif
  7070. static const upb_msgdef *refm(const upb_msgdef *m, const void *owner) {
  7071. upb_msgdef_ref(m, owner);
  7072. return m;
  7073. }
  7074. static const upb_enumdef *refe(const upb_enumdef *e, const void *owner) {
  7075. upb_enumdef_ref(e, owner);
  7076. return e;
  7077. }
  7078. /* Public API. */
  7079. const upb_msgdef *upbdefs_google_protobuf_DescriptorProto_get(const void *owner) { return refm(&msgs[0], owner); }
  7080. const upb_msgdef *upbdefs_google_protobuf_DescriptorProto_ExtensionRange_get(const void *owner) { return refm(&msgs[1], owner); }
  7081. const upb_msgdef *upbdefs_google_protobuf_DescriptorProto_ReservedRange_get(const void *owner) { return refm(&msgs[2], owner); }
  7082. const upb_msgdef *upbdefs_google_protobuf_EnumDescriptorProto_get(const void *owner) { return refm(&msgs[3], owner); }
  7083. const upb_msgdef *upbdefs_google_protobuf_EnumOptions_get(const void *owner) { return refm(&msgs[4], owner); }
  7084. const upb_msgdef *upbdefs_google_protobuf_EnumValueDescriptorProto_get(const void *owner) { return refm(&msgs[5], owner); }
  7085. const upb_msgdef *upbdefs_google_protobuf_EnumValueOptions_get(const void *owner) { return refm(&msgs[6], owner); }
  7086. const upb_msgdef *upbdefs_google_protobuf_FieldDescriptorProto_get(const void *owner) { return refm(&msgs[7], owner); }
  7087. const upb_msgdef *upbdefs_google_protobuf_FieldOptions_get(const void *owner) { return refm(&msgs[8], owner); }
  7088. const upb_msgdef *upbdefs_google_protobuf_FileDescriptorProto_get(const void *owner) { return refm(&msgs[9], owner); }
  7089. const upb_msgdef *upbdefs_google_protobuf_FileDescriptorSet_get(const void *owner) { return refm(&msgs[10], owner); }
  7090. const upb_msgdef *upbdefs_google_protobuf_FileOptions_get(const void *owner) { return refm(&msgs[11], owner); }
  7091. const upb_msgdef *upbdefs_google_protobuf_MessageOptions_get(const void *owner) { return refm(&msgs[12], owner); }
  7092. const upb_msgdef *upbdefs_google_protobuf_MethodDescriptorProto_get(const void *owner) { return refm(&msgs[13], owner); }
  7093. const upb_msgdef *upbdefs_google_protobuf_MethodOptions_get(const void *owner) { return refm(&msgs[14], owner); }
  7094. const upb_msgdef *upbdefs_google_protobuf_OneofDescriptorProto_get(const void *owner) { return refm(&msgs[15], owner); }
  7095. const upb_msgdef *upbdefs_google_protobuf_ServiceDescriptorProto_get(const void *owner) { return refm(&msgs[16], owner); }
  7096. const upb_msgdef *upbdefs_google_protobuf_ServiceOptions_get(const void *owner) { return refm(&msgs[17], owner); }
  7097. const upb_msgdef *upbdefs_google_protobuf_SourceCodeInfo_get(const void *owner) { return refm(&msgs[18], owner); }
  7098. const upb_msgdef *upbdefs_google_protobuf_SourceCodeInfo_Location_get(const void *owner) { return refm(&msgs[19], owner); }
  7099. const upb_msgdef *upbdefs_google_protobuf_UninterpretedOption_get(const void *owner) { return refm(&msgs[20], owner); }
  7100. const upb_msgdef *upbdefs_google_protobuf_UninterpretedOption_NamePart_get(const void *owner) { return refm(&msgs[21], owner); }
  7101. const upb_enumdef *upbdefs_google_protobuf_FieldDescriptorProto_Label_get(const void *owner) { return refe(&enums[0], owner); }
  7102. const upb_enumdef *upbdefs_google_protobuf_FieldDescriptorProto_Type_get(const void *owner) { return refe(&enums[1], owner); }
  7103. const upb_enumdef *upbdefs_google_protobuf_FieldOptions_CType_get(const void *owner) { return refe(&enums[2], owner); }
  7104. const upb_enumdef *upbdefs_google_protobuf_FieldOptions_JSType_get(const void *owner) { return refe(&enums[3], owner); }
  7105. const upb_enumdef *upbdefs_google_protobuf_FileOptions_OptimizeMode_get(const void *owner) { return refe(&enums[4], owner); }
  7106. /*
  7107. ** XXX: The routines in this file that consume a string do not currently
  7108. ** support having the string span buffers. In the future, as upb_sink and
  7109. ** its buffering/sharing functionality evolve there should be an easy and
  7110. ** idiomatic way of correctly handling this case. For now, we accept this
  7111. ** limitation since we currently only parse descriptors from single strings.
  7112. */
  7113. #include <errno.h>
  7114. #include <stdlib.h>
  7115. #include <string.h>
  7116. /* Compares a NULL-terminated string with a non-NULL-terminated string. */
  7117. static bool upb_streq(const char *str, const char *buf, size_t n) {
  7118. return strlen(str) == n && memcmp(str, buf, n) == 0;
  7119. }
  7120. /* We keep a stack of all the messages scopes we are currently in, as well as
  7121. * the top-level file scope. This is necessary to correctly qualify the
  7122. * definitions that are contained inside. "name" tracks the name of the
  7123. * message or package (a bare name -- not qualified by any enclosing scopes). */
  7124. typedef struct {
  7125. char *name;
  7126. /* Index of the first def that is under this scope. For msgdefs, the
  7127. * msgdef itself is at start-1. */
  7128. int start;
  7129. uint32_t oneof_start;
  7130. uint32_t oneof_index;
  7131. } upb_descreader_frame;
  7132. /* The maximum number of nested declarations that are allowed, ie.
  7133. * message Foo {
  7134. * message Bar {
  7135. * message Baz {
  7136. * }
  7137. * }
  7138. * }
  7139. *
  7140. * This is a resource limit that affects how big our runtime stack can grow.
  7141. * TODO: make this a runtime-settable property of the Reader instance. */
  7142. #define UPB_MAX_MESSAGE_NESTING 64
  7143. struct upb_descreader {
  7144. upb_sink sink;
  7145. upb_inttable files;
  7146. upb_strtable files_by_name;
  7147. upb_filedef *file; /* The last file in files. */
  7148. upb_descreader_frame stack[UPB_MAX_MESSAGE_NESTING];
  7149. int stack_len;
  7150. upb_inttable oneofs;
  7151. uint32_t number;
  7152. char *name;
  7153. bool saw_number;
  7154. bool saw_name;
  7155. char *default_string;
  7156. upb_fielddef *f;
  7157. };
  7158. static char *upb_gstrndup(const char *buf, size_t n) {
  7159. char *ret = upb_gmalloc(n + 1);
  7160. if (!ret) return NULL;
  7161. memcpy(ret, buf, n);
  7162. ret[n] = '\0';
  7163. return ret;
  7164. }
  7165. /* Returns a newly allocated string that joins input strings together, for
  7166. * example:
  7167. * join("Foo.Bar", "Baz") -> "Foo.Bar.Baz"
  7168. * join("", "Baz") -> "Baz"
  7169. * Caller owns a ref on the returned string. */
  7170. static char *upb_join(const char *base, const char *name) {
  7171. if (!base || strlen(base) == 0) {
  7172. return upb_gstrdup(name);
  7173. } else {
  7174. char *ret = upb_gmalloc(strlen(base) + strlen(name) + 2);
  7175. if (!ret) {
  7176. return NULL;
  7177. }
  7178. ret[0] = '\0';
  7179. strcat(ret, base);
  7180. strcat(ret, ".");
  7181. strcat(ret, name);
  7182. return ret;
  7183. }
  7184. }
  7185. /* Qualify the defname for all defs starting with offset "start" with "str". */
  7186. static bool upb_descreader_qualify(upb_filedef *f, char *str, int32_t start) {
  7187. size_t i;
  7188. for (i = start; i < upb_filedef_defcount(f); i++) {
  7189. upb_def *def = upb_filedef_mutabledef(f, i);
  7190. char *name = upb_join(str, upb_def_fullname(def));
  7191. if (!name) {
  7192. /* Need better logic here; at this point we've qualified some names but
  7193. * not others. */
  7194. return false;
  7195. }
  7196. upb_def_setfullname(def, name, NULL);
  7197. upb_gfree(name);
  7198. }
  7199. return true;
  7200. }
  7201. /* upb_descreader ************************************************************/
  7202. static upb_msgdef *upb_descreader_top(upb_descreader *r) {
  7203. int index;
  7204. UPB_ASSERT(r->stack_len > 1);
  7205. index = r->stack[r->stack_len-1].start - 1;
  7206. UPB_ASSERT(index >= 0);
  7207. return upb_downcast_msgdef_mutable(upb_filedef_mutabledef(r->file, index));
  7208. }
  7209. static upb_def *upb_descreader_last(upb_descreader *r) {
  7210. return upb_filedef_mutabledef(r->file, upb_filedef_defcount(r->file) - 1);
  7211. }
  7212. /* Start/end handlers for FileDescriptorProto and DescriptorProto (the two
  7213. * entities that have names and can contain sub-definitions. */
  7214. void upb_descreader_startcontainer(upb_descreader *r) {
  7215. upb_descreader_frame *f = &r->stack[r->stack_len++];
  7216. f->start = upb_filedef_defcount(r->file);
  7217. f->oneof_start = upb_inttable_count(&r->oneofs);
  7218. f->oneof_index = 0;
  7219. f->name = NULL;
  7220. }
  7221. bool upb_descreader_endcontainer(upb_descreader *r) {
  7222. upb_descreader_frame *f = &r->stack[r->stack_len - 1];
  7223. while (upb_inttable_count(&r->oneofs) > f->oneof_start) {
  7224. upb_oneofdef *o = upb_value_getptr(upb_inttable_pop(&r->oneofs));
  7225. bool ok = upb_msgdef_addoneof(upb_descreader_top(r), o, &r->oneofs, NULL);
  7226. UPB_ASSERT(ok);
  7227. }
  7228. if (!upb_descreader_qualify(r->file, f->name, f->start)) {
  7229. return false;
  7230. }
  7231. upb_gfree(f->name);
  7232. f->name = NULL;
  7233. r->stack_len--;
  7234. return true;
  7235. }
  7236. void upb_descreader_setscopename(upb_descreader *r, char *str) {
  7237. upb_descreader_frame *f = &r->stack[r->stack_len-1];
  7238. upb_gfree(f->name);
  7239. f->name = str;
  7240. }
  7241. static upb_oneofdef *upb_descreader_getoneof(upb_descreader *r,
  7242. uint32_t index) {
  7243. bool found;
  7244. upb_value val;
  7245. upb_descreader_frame *f = &r->stack[r->stack_len-1];
  7246. /* DescriptorProto messages can be nested, so we will see the nested messages
  7247. * between when we see the FieldDescriptorProto and the OneofDescriptorProto.
  7248. * We need to preserve the oneofs in between these two things. */
  7249. index += f->oneof_start;
  7250. while (upb_inttable_count(&r->oneofs) <= index) {
  7251. upb_inttable_push(&r->oneofs, upb_value_ptr(upb_oneofdef_new(&r->oneofs)));
  7252. }
  7253. found = upb_inttable_lookup(&r->oneofs, index, &val);
  7254. UPB_ASSERT(found);
  7255. return upb_value_getptr(val);
  7256. }
  7257. /** Handlers for google.protobuf.FileDescriptorSet. ***************************/
  7258. static void *fileset_startfile(void *closure, const void *hd) {
  7259. upb_descreader *r = closure;
  7260. UPB_UNUSED(hd);
  7261. r->file = upb_filedef_new(&r->files);
  7262. upb_inttable_push(&r->files, upb_value_ptr(r->file));
  7263. return r;
  7264. }
  7265. /** Handlers for google.protobuf.FileDescriptorProto. *************************/
  7266. static bool file_start(void *closure, const void *hd) {
  7267. upb_descreader *r = closure;
  7268. UPB_UNUSED(hd);
  7269. upb_descreader_startcontainer(r);
  7270. return true;
  7271. }
  7272. static bool file_end(void *closure, const void *hd, upb_status *status) {
  7273. upb_descreader *r = closure;
  7274. UPB_UNUSED(hd);
  7275. UPB_UNUSED(status);
  7276. return upb_descreader_endcontainer(r);
  7277. }
  7278. static size_t file_onname(void *closure, const void *hd, const char *buf,
  7279. size_t n, const upb_bufhandle *handle) {
  7280. upb_descreader *r = closure;
  7281. char *name;
  7282. bool ok;
  7283. UPB_UNUSED(hd);
  7284. UPB_UNUSED(handle);
  7285. name = upb_gstrndup(buf, n);
  7286. upb_strtable_insert(&r->files_by_name, name, upb_value_ptr(r->file));
  7287. /* XXX: see comment at the top of the file. */
  7288. ok = upb_filedef_setname(r->file, name, NULL);
  7289. upb_gfree(name);
  7290. UPB_ASSERT(ok);
  7291. return n;
  7292. }
  7293. static size_t file_onpackage(void *closure, const void *hd, const char *buf,
  7294. size_t n, const upb_bufhandle *handle) {
  7295. upb_descreader *r = closure;
  7296. char *package;
  7297. bool ok;
  7298. UPB_UNUSED(hd);
  7299. UPB_UNUSED(handle);
  7300. package = upb_gstrndup(buf, n);
  7301. /* XXX: see comment at the top of the file. */
  7302. upb_descreader_setscopename(r, package);
  7303. ok = upb_filedef_setpackage(r->file, package, NULL);
  7304. UPB_ASSERT(ok);
  7305. return n;
  7306. }
  7307. static void *file_startphpnamespace(void *closure, const void *hd,
  7308. size_t size_hint) {
  7309. upb_descreader *r = closure;
  7310. bool ok;
  7311. UPB_UNUSED(hd);
  7312. UPB_UNUSED(size_hint);
  7313. ok = upb_filedef_setphpnamespace(r->file, "", NULL);
  7314. UPB_ASSERT(ok);
  7315. return closure;
  7316. }
  7317. static size_t file_onphpnamespace(void *closure, const void *hd,
  7318. const char *buf, size_t n,
  7319. const upb_bufhandle *handle) {
  7320. upb_descreader *r = closure;
  7321. char *php_namespace;
  7322. bool ok;
  7323. UPB_UNUSED(hd);
  7324. UPB_UNUSED(handle);
  7325. php_namespace = upb_gstrndup(buf, n);
  7326. ok = upb_filedef_setphpnamespace(r->file, php_namespace, NULL);
  7327. upb_gfree(php_namespace);
  7328. UPB_ASSERT(ok);
  7329. return n;
  7330. }
  7331. static size_t file_onphpprefix(void *closure, const void *hd, const char *buf,
  7332. size_t n, const upb_bufhandle *handle) {
  7333. upb_descreader *r = closure;
  7334. char *prefix;
  7335. bool ok;
  7336. UPB_UNUSED(hd);
  7337. UPB_UNUSED(handle);
  7338. prefix = upb_gstrndup(buf, n);
  7339. ok = upb_filedef_setphpprefix(r->file, prefix, NULL);
  7340. upb_gfree(prefix);
  7341. UPB_ASSERT(ok);
  7342. return n;
  7343. }
  7344. static size_t file_onsyntax(void *closure, const void *hd, const char *buf,
  7345. size_t n, const upb_bufhandle *handle) {
  7346. upb_descreader *r = closure;
  7347. bool ok;
  7348. UPB_UNUSED(hd);
  7349. UPB_UNUSED(handle);
  7350. /* XXX: see comment at the top of the file. */
  7351. if (upb_streq("proto2", buf, n)) {
  7352. ok = upb_filedef_setsyntax(r->file, UPB_SYNTAX_PROTO2, NULL);
  7353. } else if (upb_streq("proto3", buf, n)) {
  7354. ok = upb_filedef_setsyntax(r->file, UPB_SYNTAX_PROTO3, NULL);
  7355. } else {
  7356. ok = false;
  7357. }
  7358. UPB_ASSERT(ok);
  7359. return n;
  7360. }
  7361. static void *file_startmsg(void *closure, const void *hd) {
  7362. upb_descreader *r = closure;
  7363. upb_msgdef *m = upb_msgdef_new(&m);
  7364. bool ok = upb_filedef_addmsg(r->file, m, &m, NULL);
  7365. UPB_UNUSED(hd);
  7366. UPB_ASSERT(ok);
  7367. return r;
  7368. }
  7369. static void *file_startenum(void *closure, const void *hd) {
  7370. upb_descreader *r = closure;
  7371. upb_enumdef *e = upb_enumdef_new(&e);
  7372. bool ok = upb_filedef_addenum(r->file, e, &e, NULL);
  7373. UPB_UNUSED(hd);
  7374. UPB_ASSERT(ok);
  7375. return r;
  7376. }
  7377. static void *file_startext(void *closure, const void *hd) {
  7378. upb_descreader *r = closure;
  7379. bool ok;
  7380. r->f = upb_fielddef_new(r);
  7381. ok = upb_filedef_addext(r->file, r->f, r, NULL);
  7382. UPB_UNUSED(hd);
  7383. UPB_ASSERT(ok);
  7384. return r;
  7385. }
  7386. static size_t file_ondep(void *closure, const void *hd, const char *buf,
  7387. size_t n, const upb_bufhandle *handle) {
  7388. upb_descreader *r = closure;
  7389. upb_value val;
  7390. if (upb_strtable_lookup2(&r->files_by_name, buf, n, &val)) {
  7391. upb_filedef_adddep(r->file, upb_value_getptr(val));
  7392. }
  7393. UPB_UNUSED(hd);
  7394. UPB_UNUSED(handle);
  7395. return n;
  7396. }
  7397. /** Handlers for google.protobuf.EnumValueDescriptorProto. *********************/
  7398. static bool enumval_startmsg(void *closure, const void *hd) {
  7399. upb_descreader *r = closure;
  7400. UPB_UNUSED(hd);
  7401. r->saw_number = false;
  7402. r->saw_name = false;
  7403. return true;
  7404. }
  7405. static size_t enumval_onname(void *closure, const void *hd, const char *buf,
  7406. size_t n, const upb_bufhandle *handle) {
  7407. upb_descreader *r = closure;
  7408. UPB_UNUSED(hd);
  7409. UPB_UNUSED(handle);
  7410. /* XXX: see comment at the top of the file. */
  7411. upb_gfree(r->name);
  7412. r->name = upb_gstrndup(buf, n);
  7413. r->saw_name = true;
  7414. return n;
  7415. }
  7416. static bool enumval_onnumber(void *closure, const void *hd, int32_t val) {
  7417. upb_descreader *r = closure;
  7418. UPB_UNUSED(hd);
  7419. r->number = val;
  7420. r->saw_number = true;
  7421. return true;
  7422. }
  7423. static bool enumval_endmsg(void *closure, const void *hd, upb_status *status) {
  7424. upb_descreader *r = closure;
  7425. upb_enumdef *e;
  7426. UPB_UNUSED(hd);
  7427. if(!r->saw_number || !r->saw_name) {
  7428. upb_status_seterrmsg(status, "Enum value missing name or number.");
  7429. return false;
  7430. }
  7431. e = upb_downcast_enumdef_mutable(upb_descreader_last(r));
  7432. upb_enumdef_addval(e, r->name, r->number, status);
  7433. upb_gfree(r->name);
  7434. r->name = NULL;
  7435. return true;
  7436. }
  7437. /** Handlers for google.protobuf.EnumDescriptorProto. *************************/
  7438. static bool enum_endmsg(void *closure, const void *hd, upb_status *status) {
  7439. upb_descreader *r = closure;
  7440. upb_enumdef *e;
  7441. UPB_UNUSED(hd);
  7442. e = upb_downcast_enumdef_mutable(upb_descreader_last(r));
  7443. if (upb_def_fullname(upb_descreader_last(r)) == NULL) {
  7444. upb_status_seterrmsg(status, "Enum had no name.");
  7445. return false;
  7446. }
  7447. if (upb_enumdef_numvals(e) == 0) {
  7448. upb_status_seterrmsg(status, "Enum had no values.");
  7449. return false;
  7450. }
  7451. return true;
  7452. }
  7453. static size_t enum_onname(void *closure, const void *hd, const char *buf,
  7454. size_t n, const upb_bufhandle *handle) {
  7455. upb_descreader *r = closure;
  7456. char *fullname = upb_gstrndup(buf, n);
  7457. UPB_UNUSED(hd);
  7458. UPB_UNUSED(handle);
  7459. /* XXX: see comment at the top of the file. */
  7460. upb_def_setfullname(upb_descreader_last(r), fullname, NULL);
  7461. upb_gfree(fullname);
  7462. return n;
  7463. }
  7464. /** Handlers for google.protobuf.FieldDescriptorProto *************************/
  7465. static bool field_startmsg(void *closure, const void *hd) {
  7466. upb_descreader *r = closure;
  7467. UPB_UNUSED(hd);
  7468. UPB_ASSERT(r->f);
  7469. upb_gfree(r->default_string);
  7470. r->default_string = NULL;
  7471. /* fielddefs default to packed, but descriptors default to non-packed. */
  7472. upb_fielddef_setpacked(r->f, false);
  7473. return true;
  7474. }
  7475. /* Converts the default value in string "str" into "d". Passes a ref on str.
  7476. * Returns true on success. */
  7477. static bool parse_default(char *str, upb_fielddef *f) {
  7478. bool success = true;
  7479. char *end;
  7480. switch (upb_fielddef_type(f)) {
  7481. case UPB_TYPE_INT32: {
  7482. long val = strtol(str, &end, 0);
  7483. if (val > INT32_MAX || val < INT32_MIN || errno == ERANGE || *end)
  7484. success = false;
  7485. else
  7486. upb_fielddef_setdefaultint32(f, val);
  7487. break;
  7488. }
  7489. case UPB_TYPE_INT64: {
  7490. /* XXX: Need to write our own strtoll, since it's not available in c89. */
  7491. long long val = strtol(str, &end, 0);
  7492. if (val > INT64_MAX || val < INT64_MIN || errno == ERANGE || *end)
  7493. success = false;
  7494. else
  7495. upb_fielddef_setdefaultint64(f, val);
  7496. break;
  7497. }
  7498. case UPB_TYPE_UINT32: {
  7499. unsigned long val = strtoul(str, &end, 0);
  7500. if (val > UINT32_MAX || errno == ERANGE || *end)
  7501. success = false;
  7502. else
  7503. upb_fielddef_setdefaultuint32(f, val);
  7504. break;
  7505. }
  7506. case UPB_TYPE_UINT64: {
  7507. /* XXX: Need to write our own strtoull, since it's not available in c89. */
  7508. unsigned long long val = strtoul(str, &end, 0);
  7509. if (val > UINT64_MAX || errno == ERANGE || *end)
  7510. success = false;
  7511. else
  7512. upb_fielddef_setdefaultuint64(f, val);
  7513. break;
  7514. }
  7515. case UPB_TYPE_DOUBLE: {
  7516. double val = strtod(str, &end);
  7517. if (errno == ERANGE || *end)
  7518. success = false;
  7519. else
  7520. upb_fielddef_setdefaultdouble(f, val);
  7521. break;
  7522. }
  7523. case UPB_TYPE_FLOAT: {
  7524. /* XXX: Need to write our own strtof, since it's not available in c89. */
  7525. float val = strtod(str, &end);
  7526. if (errno == ERANGE || *end)
  7527. success = false;
  7528. else
  7529. upb_fielddef_setdefaultfloat(f, val);
  7530. break;
  7531. }
  7532. case UPB_TYPE_BOOL: {
  7533. if (strcmp(str, "false") == 0)
  7534. upb_fielddef_setdefaultbool(f, false);
  7535. else if (strcmp(str, "true") == 0)
  7536. upb_fielddef_setdefaultbool(f, true);
  7537. else
  7538. success = false;
  7539. break;
  7540. }
  7541. default: abort();
  7542. }
  7543. return success;
  7544. }
  7545. static bool field_endmsg(void *closure, const void *hd, upb_status *status) {
  7546. upb_descreader *r = closure;
  7547. upb_fielddef *f = r->f;
  7548. UPB_UNUSED(hd);
  7549. /* TODO: verify that all required fields were present. */
  7550. UPB_ASSERT(upb_fielddef_number(f) != 0);
  7551. UPB_ASSERT(upb_fielddef_name(f) != NULL);
  7552. UPB_ASSERT((upb_fielddef_subdefname(f) != NULL) == upb_fielddef_hassubdef(f));
  7553. if (r->default_string) {
  7554. if (upb_fielddef_issubmsg(f)) {
  7555. upb_status_seterrmsg(status, "Submessages cannot have defaults.");
  7556. return false;
  7557. }
  7558. if (upb_fielddef_isstring(f) || upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  7559. upb_fielddef_setdefaultcstr(f, r->default_string, NULL);
  7560. } else {
  7561. if (r->default_string && !parse_default(r->default_string, f)) {
  7562. /* We don't worry too much about giving a great error message since the
  7563. * compiler should have ensured this was correct. */
  7564. upb_status_seterrmsg(status, "Error converting default value.");
  7565. return false;
  7566. }
  7567. }
  7568. }
  7569. return true;
  7570. }
  7571. static bool field_onlazy(void *closure, const void *hd, bool val) {
  7572. upb_descreader *r = closure;
  7573. UPB_UNUSED(hd);
  7574. upb_fielddef_setlazy(r->f, val);
  7575. return true;
  7576. }
  7577. static bool field_onpacked(void *closure, const void *hd, bool val) {
  7578. upb_descreader *r = closure;
  7579. UPB_UNUSED(hd);
  7580. upb_fielddef_setpacked(r->f, val);
  7581. return true;
  7582. }
  7583. static bool field_ontype(void *closure, const void *hd, int32_t val) {
  7584. upb_descreader *r = closure;
  7585. UPB_UNUSED(hd);
  7586. upb_fielddef_setdescriptortype(r->f, val);
  7587. return true;
  7588. }
  7589. static bool field_onlabel(void *closure, const void *hd, int32_t val) {
  7590. upb_descreader *r = closure;
  7591. UPB_UNUSED(hd);
  7592. upb_fielddef_setlabel(r->f, val);
  7593. return true;
  7594. }
  7595. static bool field_onnumber(void *closure, const void *hd, int32_t val) {
  7596. upb_descreader *r = closure;
  7597. bool ok;
  7598. UPB_UNUSED(hd);
  7599. ok = upb_fielddef_setnumber(r->f, val, NULL);
  7600. UPB_ASSERT(ok);
  7601. return true;
  7602. }
  7603. static size_t field_onname(void *closure, const void *hd, const char *buf,
  7604. size_t n, const upb_bufhandle *handle) {
  7605. upb_descreader *r = closure;
  7606. char *name = upb_gstrndup(buf, n);
  7607. UPB_UNUSED(hd);
  7608. UPB_UNUSED(handle);
  7609. /* XXX: see comment at the top of the file. */
  7610. upb_fielddef_setname(r->f, name, NULL);
  7611. upb_gfree(name);
  7612. return n;
  7613. }
  7614. static size_t field_ontypename(void *closure, const void *hd, const char *buf,
  7615. size_t n, const upb_bufhandle *handle) {
  7616. upb_descreader *r = closure;
  7617. char *name = upb_gstrndup(buf, n);
  7618. UPB_UNUSED(hd);
  7619. UPB_UNUSED(handle);
  7620. /* XXX: see comment at the top of the file. */
  7621. upb_fielddef_setsubdefname(r->f, name, NULL);
  7622. upb_gfree(name);
  7623. return n;
  7624. }
  7625. static size_t field_onextendee(void *closure, const void *hd, const char *buf,
  7626. size_t n, const upb_bufhandle *handle) {
  7627. upb_descreader *r = closure;
  7628. char *name = upb_gstrndup(buf, n);
  7629. UPB_UNUSED(hd);
  7630. UPB_UNUSED(handle);
  7631. /* XXX: see comment at the top of the file. */
  7632. upb_fielddef_setcontainingtypename(r->f, name, NULL);
  7633. upb_gfree(name);
  7634. return n;
  7635. }
  7636. static size_t field_ondefaultval(void *closure, const void *hd, const char *buf,
  7637. size_t n, const upb_bufhandle *handle) {
  7638. upb_descreader *r = closure;
  7639. UPB_UNUSED(hd);
  7640. UPB_UNUSED(handle);
  7641. /* Have to convert from string to the correct type, but we might not know the
  7642. * type yet, so we save it as a string until the end of the field.
  7643. * XXX: see comment at the top of the file. */
  7644. upb_gfree(r->default_string);
  7645. r->default_string = upb_gstrndup(buf, n);
  7646. return n;
  7647. }
  7648. static bool field_ononeofindex(void *closure, const void *hd, int32_t index) {
  7649. upb_descreader *r = closure;
  7650. upb_oneofdef *o = upb_descreader_getoneof(r, index);
  7651. bool ok = upb_oneofdef_addfield(o, r->f, &r->f, NULL);
  7652. UPB_UNUSED(hd);
  7653. UPB_ASSERT(ok);
  7654. return true;
  7655. }
  7656. /** Handlers for google.protobuf.OneofDescriptorProto. ************************/
  7657. static size_t oneof_name(void *closure, const void *hd, const char *buf,
  7658. size_t n, const upb_bufhandle *handle) {
  7659. upb_descreader *r = closure;
  7660. upb_descreader_frame *f = &r->stack[r->stack_len-1];
  7661. upb_oneofdef *o = upb_descreader_getoneof(r, f->oneof_index++);
  7662. char *name_null_terminated = upb_gstrndup(buf, n);
  7663. bool ok = upb_oneofdef_setname(o, name_null_terminated, NULL);
  7664. UPB_UNUSED(hd);
  7665. UPB_UNUSED(handle);
  7666. UPB_ASSERT(ok);
  7667. free(name_null_terminated);
  7668. return n;
  7669. }
  7670. /** Handlers for google.protobuf.DescriptorProto ******************************/
  7671. static bool msg_start(void *closure, const void *hd) {
  7672. upb_descreader *r = closure;
  7673. UPB_UNUSED(hd);
  7674. upb_descreader_startcontainer(r);
  7675. return true;
  7676. }
  7677. static bool msg_end(void *closure, const void *hd, upb_status *status) {
  7678. upb_descreader *r = closure;
  7679. upb_msgdef *m = upb_descreader_top(r);
  7680. UPB_UNUSED(hd);
  7681. if(!upb_def_fullname(upb_msgdef_upcast_mutable(m))) {
  7682. upb_status_seterrmsg(status, "Encountered message with no name.");
  7683. return false;
  7684. }
  7685. return upb_descreader_endcontainer(r);
  7686. }
  7687. static size_t msg_name(void *closure, const void *hd, const char *buf,
  7688. size_t n, const upb_bufhandle *handle) {
  7689. upb_descreader *r = closure;
  7690. upb_msgdef *m = upb_descreader_top(r);
  7691. /* XXX: see comment at the top of the file. */
  7692. char *name = upb_gstrndup(buf, n);
  7693. UPB_UNUSED(hd);
  7694. UPB_UNUSED(handle);
  7695. upb_def_setfullname(upb_msgdef_upcast_mutable(m), name, NULL);
  7696. upb_descreader_setscopename(r, name); /* Passes ownership of name. */
  7697. return n;
  7698. }
  7699. static void *msg_startmsg(void *closure, const void *hd) {
  7700. upb_descreader *r = closure;
  7701. upb_msgdef *m = upb_msgdef_new(&m);
  7702. bool ok = upb_filedef_addmsg(r->file, m, &m, NULL);
  7703. UPB_UNUSED(hd);
  7704. UPB_ASSERT(ok);
  7705. return r;
  7706. }
  7707. static void *msg_startext(void *closure, const void *hd) {
  7708. upb_descreader *r = closure;
  7709. upb_fielddef *f = upb_fielddef_new(&f);
  7710. bool ok = upb_filedef_addext(r->file, f, &f, NULL);
  7711. UPB_UNUSED(hd);
  7712. UPB_ASSERT(ok);
  7713. return r;
  7714. }
  7715. static void *msg_startfield(void *closure, const void *hd) {
  7716. upb_descreader *r = closure;
  7717. r->f = upb_fielddef_new(&r->f);
  7718. /* We can't add the new field to the message until its name/number are
  7719. * filled in. */
  7720. UPB_UNUSED(hd);
  7721. return r;
  7722. }
  7723. static bool msg_endfield(void *closure, const void *hd) {
  7724. upb_descreader *r = closure;
  7725. upb_msgdef *m = upb_descreader_top(r);
  7726. bool ok;
  7727. UPB_UNUSED(hd);
  7728. /* Oneof fields are added to the msgdef through their oneof, so don't need to
  7729. * be added here. */
  7730. if (upb_fielddef_containingoneof(r->f) == NULL) {
  7731. ok = upb_msgdef_addfield(m, r->f, &r->f, NULL);
  7732. UPB_ASSERT(ok);
  7733. }
  7734. r->f = NULL;
  7735. return true;
  7736. }
  7737. static bool msg_onmapentry(void *closure, const void *hd, bool mapentry) {
  7738. upb_descreader *r = closure;
  7739. upb_msgdef *m = upb_descreader_top(r);
  7740. UPB_UNUSED(hd);
  7741. upb_msgdef_setmapentry(m, mapentry);
  7742. r->f = NULL;
  7743. return true;
  7744. }
  7745. /** Code to register handlers *************************************************/
  7746. #define F(msg, field) upbdefs_google_protobuf_ ## msg ## _f_ ## field(m)
  7747. static void reghandlers(const void *closure, upb_handlers *h) {
  7748. const upb_msgdef *m = upb_handlers_msgdef(h);
  7749. UPB_UNUSED(closure);
  7750. if (upbdefs_google_protobuf_FileDescriptorSet_is(m)) {
  7751. upb_handlers_setstartsubmsg(h, F(FileDescriptorSet, file),
  7752. &fileset_startfile, NULL);
  7753. } else if (upbdefs_google_protobuf_DescriptorProto_is(m)) {
  7754. upb_handlers_setstartmsg(h, &msg_start, NULL);
  7755. upb_handlers_setendmsg(h, &msg_end, NULL);
  7756. upb_handlers_setstring(h, F(DescriptorProto, name), &msg_name, NULL);
  7757. upb_handlers_setstartsubmsg(h, F(DescriptorProto, extension), &msg_startext,
  7758. NULL);
  7759. upb_handlers_setstartsubmsg(h, F(DescriptorProto, nested_type),
  7760. &msg_startmsg, NULL);
  7761. upb_handlers_setstartsubmsg(h, F(DescriptorProto, field),
  7762. &msg_startfield, NULL);
  7763. upb_handlers_setendsubmsg(h, F(DescriptorProto, field),
  7764. &msg_endfield, NULL);
  7765. upb_handlers_setstartsubmsg(h, F(DescriptorProto, enum_type),
  7766. &file_startenum, NULL);
  7767. } else if (upbdefs_google_protobuf_FileDescriptorProto_is(m)) {
  7768. upb_handlers_setstartmsg(h, &file_start, NULL);
  7769. upb_handlers_setendmsg(h, &file_end, NULL);
  7770. upb_handlers_setstring(h, F(FileDescriptorProto, name), &file_onname,
  7771. NULL);
  7772. upb_handlers_setstring(h, F(FileDescriptorProto, package), &file_onpackage,
  7773. NULL);
  7774. upb_handlers_setstring(h, F(FileDescriptorProto, syntax), &file_onsyntax,
  7775. NULL);
  7776. upb_handlers_setstartsubmsg(h, F(FileDescriptorProto, message_type),
  7777. &file_startmsg, NULL);
  7778. upb_handlers_setstartsubmsg(h, F(FileDescriptorProto, enum_type),
  7779. &file_startenum, NULL);
  7780. upb_handlers_setstartsubmsg(h, F(FileDescriptorProto, extension),
  7781. &file_startext, NULL);
  7782. upb_handlers_setstring(h, F(FileDescriptorProto, dependency),
  7783. &file_ondep, NULL);
  7784. } else if (upbdefs_google_protobuf_EnumValueDescriptorProto_is(m)) {
  7785. upb_handlers_setstartmsg(h, &enumval_startmsg, NULL);
  7786. upb_handlers_setendmsg(h, &enumval_endmsg, NULL);
  7787. upb_handlers_setstring(h, F(EnumValueDescriptorProto, name), &enumval_onname, NULL);
  7788. upb_handlers_setint32(h, F(EnumValueDescriptorProto, number), &enumval_onnumber,
  7789. NULL);
  7790. } else if (upbdefs_google_protobuf_EnumDescriptorProto_is(m)) {
  7791. upb_handlers_setendmsg(h, &enum_endmsg, NULL);
  7792. upb_handlers_setstring(h, F(EnumDescriptorProto, name), &enum_onname, NULL);
  7793. } else if (upbdefs_google_protobuf_FieldDescriptorProto_is(m)) {
  7794. upb_handlers_setstartmsg(h, &field_startmsg, NULL);
  7795. upb_handlers_setendmsg(h, &field_endmsg, NULL);
  7796. upb_handlers_setint32(h, F(FieldDescriptorProto, type), &field_ontype,
  7797. NULL);
  7798. upb_handlers_setint32(h, F(FieldDescriptorProto, label), &field_onlabel,
  7799. NULL);
  7800. upb_handlers_setint32(h, F(FieldDescriptorProto, number), &field_onnumber,
  7801. NULL);
  7802. upb_handlers_setstring(h, F(FieldDescriptorProto, name), &field_onname,
  7803. NULL);
  7804. upb_handlers_setstring(h, F(FieldDescriptorProto, type_name),
  7805. &field_ontypename, NULL);
  7806. upb_handlers_setstring(h, F(FieldDescriptorProto, extendee),
  7807. &field_onextendee, NULL);
  7808. upb_handlers_setstring(h, F(FieldDescriptorProto, default_value),
  7809. &field_ondefaultval, NULL);
  7810. upb_handlers_setint32(h, F(FieldDescriptorProto, oneof_index),
  7811. &field_ononeofindex, NULL);
  7812. } else if (upbdefs_google_protobuf_OneofDescriptorProto_is(m)) {
  7813. upb_handlers_setstring(h, F(OneofDescriptorProto, name), &oneof_name, NULL);
  7814. } else if (upbdefs_google_protobuf_FieldOptions_is(m)) {
  7815. upb_handlers_setbool(h, F(FieldOptions, lazy), &field_onlazy, NULL);
  7816. upb_handlers_setbool(h, F(FieldOptions, packed), &field_onpacked, NULL);
  7817. } else if (upbdefs_google_protobuf_MessageOptions_is(m)) {
  7818. upb_handlers_setbool(h, F(MessageOptions, map_entry), &msg_onmapentry, NULL);
  7819. } else if (upbdefs_google_protobuf_FileOptions_is(m)) {
  7820. upb_handlers_setstring(h, F(FileOptions, php_class_prefix),
  7821. &file_onphpprefix, NULL);
  7822. upb_handlers_setstartstr(h, F(FileOptions, php_namespace),
  7823. &file_startphpnamespace, NULL);
  7824. upb_handlers_setstring(h, F(FileOptions, php_namespace),
  7825. &file_onphpnamespace, NULL);
  7826. }
  7827. UPB_ASSERT(upb_ok(upb_handlers_status(h)));
  7828. }
  7829. #undef F
  7830. void descreader_cleanup(void *_r) {
  7831. upb_descreader *r = _r;
  7832. size_t i;
  7833. for (i = 0; i < upb_descreader_filecount(r); i++) {
  7834. upb_filedef_unref(upb_descreader_file(r, i), &r->files);
  7835. }
  7836. upb_gfree(r->name);
  7837. upb_inttable_uninit(&r->files);
  7838. upb_strtable_uninit(&r->files_by_name);
  7839. upb_inttable_uninit(&r->oneofs);
  7840. upb_gfree(r->default_string);
  7841. while (r->stack_len > 0) {
  7842. upb_descreader_frame *f = &r->stack[--r->stack_len];
  7843. upb_gfree(f->name);
  7844. }
  7845. }
  7846. /* Public API ****************************************************************/
  7847. upb_descreader *upb_descreader_create(upb_env *e, const upb_handlers *h) {
  7848. upb_descreader *r = upb_env_malloc(e, sizeof(upb_descreader));
  7849. if (!r || !upb_env_addcleanup(e, descreader_cleanup, r)) {
  7850. return NULL;
  7851. }
  7852. upb_inttable_init(&r->files, UPB_CTYPE_PTR);
  7853. upb_strtable_init(&r->files_by_name, UPB_CTYPE_PTR);
  7854. upb_inttable_init(&r->oneofs, UPB_CTYPE_PTR);
  7855. upb_sink_reset(upb_descreader_input(r), h, r);
  7856. r->stack_len = 0;
  7857. r->name = NULL;
  7858. r->default_string = NULL;
  7859. return r;
  7860. }
  7861. size_t upb_descreader_filecount(const upb_descreader *r) {
  7862. return upb_inttable_count(&r->files);
  7863. }
  7864. upb_filedef *upb_descreader_file(const upb_descreader *r, size_t i) {
  7865. upb_value v;
  7866. if (upb_inttable_lookup(&r->files, i, &v)) {
  7867. return upb_value_getptr(v);
  7868. } else {
  7869. return NULL;
  7870. }
  7871. }
  7872. upb_sink *upb_descreader_input(upb_descreader *r) {
  7873. return &r->sink;
  7874. }
  7875. const upb_handlers *upb_descreader_newhandlers(const void *owner) {
  7876. const upb_msgdef *m = upbdefs_google_protobuf_FileDescriptorSet_get(&m);
  7877. const upb_handlers *h = upb_handlers_newfrozen(m, owner, reghandlers, NULL);
  7878. upb_msgdef_unref(m, &m);
  7879. return h;
  7880. }
  7881. /*
  7882. ** protobuf decoder bytecode compiler
  7883. **
  7884. ** Code to compile a upb::Handlers into bytecode for decoding a protobuf
  7885. ** according to that specific schema and destination handlers.
  7886. **
  7887. ** Compiling to bytecode is always the first step. If we are using the
  7888. ** interpreted decoder we leave it as bytecode and interpret that. If we are
  7889. ** using a JIT decoder we use a code generator to turn the bytecode into native
  7890. ** code, LLVM IR, etc.
  7891. **
  7892. ** Bytecode definition is in decoder.int.h.
  7893. */
  7894. #include <stdarg.h>
  7895. #ifdef UPB_DUMP_BYTECODE
  7896. #include <stdio.h>
  7897. #endif
  7898. #define MAXLABEL 5
  7899. #define EMPTYLABEL -1
  7900. /* mgroup *********************************************************************/
  7901. static void freegroup(upb_refcounted *r) {
  7902. mgroup *g = (mgroup*)r;
  7903. upb_inttable_uninit(&g->methods);
  7904. #ifdef UPB_USE_JIT_X64
  7905. upb_pbdecoder_freejit(g);
  7906. #endif
  7907. upb_gfree(g->bytecode);
  7908. upb_gfree(g);
  7909. }
  7910. static void visitgroup(const upb_refcounted *r, upb_refcounted_visit *visit,
  7911. void *closure) {
  7912. const mgroup *g = (const mgroup*)r;
  7913. upb_inttable_iter i;
  7914. upb_inttable_begin(&i, &g->methods);
  7915. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  7916. upb_pbdecodermethod *method = upb_value_getptr(upb_inttable_iter_value(&i));
  7917. visit(r, upb_pbdecodermethod_upcast(method), closure);
  7918. }
  7919. }
  7920. mgroup *newgroup(const void *owner) {
  7921. mgroup *g = upb_gmalloc(sizeof(*g));
  7922. static const struct upb_refcounted_vtbl vtbl = {visitgroup, freegroup};
  7923. upb_refcounted_init(mgroup_upcast_mutable(g), &vtbl, owner);
  7924. upb_inttable_init(&g->methods, UPB_CTYPE_PTR);
  7925. g->bytecode = NULL;
  7926. g->bytecode_end = NULL;
  7927. return g;
  7928. }
  7929. /* upb_pbdecodermethod ********************************************************/
  7930. static void freemethod(upb_refcounted *r) {
  7931. upb_pbdecodermethod *method = (upb_pbdecodermethod*)r;
  7932. if (method->dest_handlers_) {
  7933. upb_handlers_unref(method->dest_handlers_, method);
  7934. }
  7935. upb_inttable_uninit(&method->dispatch);
  7936. upb_gfree(method);
  7937. }
  7938. static void visitmethod(const upb_refcounted *r, upb_refcounted_visit *visit,
  7939. void *closure) {
  7940. const upb_pbdecodermethod *m = (const upb_pbdecodermethod*)r;
  7941. visit(r, m->group, closure);
  7942. }
  7943. static upb_pbdecodermethod *newmethod(const upb_handlers *dest_handlers,
  7944. mgroup *group) {
  7945. static const struct upb_refcounted_vtbl vtbl = {visitmethod, freemethod};
  7946. upb_pbdecodermethod *ret = upb_gmalloc(sizeof(*ret));
  7947. upb_refcounted_init(upb_pbdecodermethod_upcast_mutable(ret), &vtbl, &ret);
  7948. upb_byteshandler_init(&ret->input_handler_);
  7949. /* The method references the group and vice-versa, in a circular reference. */
  7950. upb_ref2(ret, group);
  7951. upb_ref2(group, ret);
  7952. upb_inttable_insertptr(&group->methods, dest_handlers, upb_value_ptr(ret));
  7953. upb_pbdecodermethod_unref(ret, &ret);
  7954. ret->group = mgroup_upcast_mutable(group);
  7955. ret->dest_handlers_ = dest_handlers;
  7956. ret->is_native_ = false; /* If we JIT, it will update this later. */
  7957. upb_inttable_init(&ret->dispatch, UPB_CTYPE_UINT64);
  7958. if (ret->dest_handlers_) {
  7959. upb_handlers_ref(ret->dest_handlers_, ret);
  7960. }
  7961. return ret;
  7962. }
  7963. const upb_handlers *upb_pbdecodermethod_desthandlers(
  7964. const upb_pbdecodermethod *m) {
  7965. return m->dest_handlers_;
  7966. }
  7967. const upb_byteshandler *upb_pbdecodermethod_inputhandler(
  7968. const upb_pbdecodermethod *m) {
  7969. return &m->input_handler_;
  7970. }
  7971. bool upb_pbdecodermethod_isnative(const upb_pbdecodermethod *m) {
  7972. return m->is_native_;
  7973. }
  7974. const upb_pbdecodermethod *upb_pbdecodermethod_new(
  7975. const upb_pbdecodermethodopts *opts, const void *owner) {
  7976. const upb_pbdecodermethod *ret;
  7977. upb_pbcodecache cache;
  7978. upb_pbcodecache_init(&cache);
  7979. ret = upb_pbcodecache_getdecodermethod(&cache, opts);
  7980. upb_pbdecodermethod_ref(ret, owner);
  7981. upb_pbcodecache_uninit(&cache);
  7982. return ret;
  7983. }
  7984. /* bytecode compiler **********************************************************/
  7985. /* Data used only at compilation time. */
  7986. typedef struct {
  7987. mgroup *group;
  7988. uint32_t *pc;
  7989. int fwd_labels[MAXLABEL];
  7990. int back_labels[MAXLABEL];
  7991. /* For fields marked "lazy", parse them lazily or eagerly? */
  7992. bool lazy;
  7993. } compiler;
  7994. static compiler *newcompiler(mgroup *group, bool lazy) {
  7995. compiler *ret = upb_gmalloc(sizeof(*ret));
  7996. int i;
  7997. ret->group = group;
  7998. ret->lazy = lazy;
  7999. for (i = 0; i < MAXLABEL; i++) {
  8000. ret->fwd_labels[i] = EMPTYLABEL;
  8001. ret->back_labels[i] = EMPTYLABEL;
  8002. }
  8003. return ret;
  8004. }
  8005. static void freecompiler(compiler *c) {
  8006. upb_gfree(c);
  8007. }
  8008. const size_t ptr_words = sizeof(void*) / sizeof(uint32_t);
  8009. /* How many words an instruction is. */
  8010. static int instruction_len(uint32_t instr) {
  8011. switch (getop(instr)) {
  8012. case OP_SETDISPATCH: return 1 + ptr_words;
  8013. case OP_TAGN: return 3;
  8014. case OP_SETBIGGROUPNUM: return 2;
  8015. default: return 1;
  8016. }
  8017. }
  8018. bool op_has_longofs(int32_t instruction) {
  8019. switch (getop(instruction)) {
  8020. case OP_CALL:
  8021. case OP_BRANCH:
  8022. case OP_CHECKDELIM:
  8023. return true;
  8024. /* The "tag" instructions only have 8 bytes available for the jump target,
  8025. * but that is ok because these opcodes only require short jumps. */
  8026. case OP_TAG1:
  8027. case OP_TAG2:
  8028. case OP_TAGN:
  8029. return false;
  8030. default:
  8031. UPB_ASSERT(false);
  8032. return false;
  8033. }
  8034. }
  8035. static int32_t getofs(uint32_t instruction) {
  8036. if (op_has_longofs(instruction)) {
  8037. return (int32_t)instruction >> 8;
  8038. } else {
  8039. return (int8_t)(instruction >> 8);
  8040. }
  8041. }
  8042. static void setofs(uint32_t *instruction, int32_t ofs) {
  8043. if (op_has_longofs(*instruction)) {
  8044. *instruction = getop(*instruction) | ofs << 8;
  8045. } else {
  8046. *instruction = (*instruction & ~0xff00) | ((ofs & 0xff) << 8);
  8047. }
  8048. UPB_ASSERT(getofs(*instruction) == ofs); /* Would fail in cases of overflow. */
  8049. }
  8050. static uint32_t pcofs(compiler *c) { return c->pc - c->group->bytecode; }
  8051. /* Defines a local label at the current PC location. All previous forward
  8052. * references are updated to point to this location. The location is noted
  8053. * for any future backward references. */
  8054. static void label(compiler *c, unsigned int label) {
  8055. int val;
  8056. uint32_t *codep;
  8057. UPB_ASSERT(label < MAXLABEL);
  8058. val = c->fwd_labels[label];
  8059. codep = (val == EMPTYLABEL) ? NULL : c->group->bytecode + val;
  8060. while (codep) {
  8061. int ofs = getofs(*codep);
  8062. setofs(codep, c->pc - codep - instruction_len(*codep));
  8063. codep = ofs ? codep + ofs : NULL;
  8064. }
  8065. c->fwd_labels[label] = EMPTYLABEL;
  8066. c->back_labels[label] = pcofs(c);
  8067. }
  8068. /* Creates a reference to a numbered label; either a forward reference
  8069. * (positive arg) or backward reference (negative arg). For forward references
  8070. * the value returned now is actually a "next" pointer into a linked list of all
  8071. * instructions that use this label and will be patched later when the label is
  8072. * defined with label().
  8073. *
  8074. * The returned value is the offset that should be written into the instruction.
  8075. */
  8076. static int32_t labelref(compiler *c, int label) {
  8077. UPB_ASSERT(label < MAXLABEL);
  8078. if (label == LABEL_DISPATCH) {
  8079. /* No resolving required. */
  8080. return 0;
  8081. } else if (label < 0) {
  8082. /* Backward local label. Relative to the next instruction. */
  8083. uint32_t from = (c->pc + 1) - c->group->bytecode;
  8084. return c->back_labels[-label] - from;
  8085. } else {
  8086. /* Forward local label: prepend to (possibly-empty) linked list. */
  8087. int *lptr = &c->fwd_labels[label];
  8088. int32_t ret = (*lptr == EMPTYLABEL) ? 0 : *lptr - pcofs(c);
  8089. *lptr = pcofs(c);
  8090. return ret;
  8091. }
  8092. }
  8093. static void put32(compiler *c, uint32_t v) {
  8094. mgroup *g = c->group;
  8095. if (c->pc == g->bytecode_end) {
  8096. int ofs = pcofs(c);
  8097. size_t oldsize = g->bytecode_end - g->bytecode;
  8098. size_t newsize = UPB_MAX(oldsize * 2, 64);
  8099. /* TODO(haberman): handle OOM. */
  8100. g->bytecode = upb_grealloc(g->bytecode, oldsize * sizeof(uint32_t),
  8101. newsize * sizeof(uint32_t));
  8102. g->bytecode_end = g->bytecode + newsize;
  8103. c->pc = g->bytecode + ofs;
  8104. }
  8105. *c->pc++ = v;
  8106. }
  8107. static void putop(compiler *c, int op, ...) {
  8108. va_list ap;
  8109. va_start(ap, op);
  8110. switch (op) {
  8111. case OP_SETDISPATCH: {
  8112. uintptr_t ptr = (uintptr_t)va_arg(ap, void*);
  8113. put32(c, OP_SETDISPATCH);
  8114. put32(c, ptr);
  8115. if (sizeof(uintptr_t) > sizeof(uint32_t))
  8116. put32(c, (uint64_t)ptr >> 32);
  8117. break;
  8118. }
  8119. case OP_STARTMSG:
  8120. case OP_ENDMSG:
  8121. case OP_PUSHLENDELIM:
  8122. case OP_POP:
  8123. case OP_SETDELIM:
  8124. case OP_HALT:
  8125. case OP_RET:
  8126. case OP_DISPATCH:
  8127. put32(c, op);
  8128. break;
  8129. case OP_PARSE_DOUBLE:
  8130. case OP_PARSE_FLOAT:
  8131. case OP_PARSE_INT64:
  8132. case OP_PARSE_UINT64:
  8133. case OP_PARSE_INT32:
  8134. case OP_PARSE_FIXED64:
  8135. case OP_PARSE_FIXED32:
  8136. case OP_PARSE_BOOL:
  8137. case OP_PARSE_UINT32:
  8138. case OP_PARSE_SFIXED32:
  8139. case OP_PARSE_SFIXED64:
  8140. case OP_PARSE_SINT32:
  8141. case OP_PARSE_SINT64:
  8142. case OP_STARTSEQ:
  8143. case OP_ENDSEQ:
  8144. case OP_STARTSUBMSG:
  8145. case OP_ENDSUBMSG:
  8146. case OP_STARTSTR:
  8147. case OP_STRING:
  8148. case OP_ENDSTR:
  8149. case OP_PUSHTAGDELIM:
  8150. put32(c, op | va_arg(ap, upb_selector_t) << 8);
  8151. break;
  8152. case OP_SETBIGGROUPNUM:
  8153. put32(c, op);
  8154. put32(c, va_arg(ap, int));
  8155. break;
  8156. case OP_CALL: {
  8157. const upb_pbdecodermethod *method = va_arg(ap, upb_pbdecodermethod *);
  8158. put32(c, op | (method->code_base.ofs - (pcofs(c) + 1)) << 8);
  8159. break;
  8160. }
  8161. case OP_CHECKDELIM:
  8162. case OP_BRANCH: {
  8163. uint32_t instruction = op;
  8164. int label = va_arg(ap, int);
  8165. setofs(&instruction, labelref(c, label));
  8166. put32(c, instruction);
  8167. break;
  8168. }
  8169. case OP_TAG1:
  8170. case OP_TAG2: {
  8171. int label = va_arg(ap, int);
  8172. uint64_t tag = va_arg(ap, uint64_t);
  8173. uint32_t instruction = op | (tag << 16);
  8174. UPB_ASSERT(tag <= 0xffff);
  8175. setofs(&instruction, labelref(c, label));
  8176. put32(c, instruction);
  8177. break;
  8178. }
  8179. case OP_TAGN: {
  8180. int label = va_arg(ap, int);
  8181. uint64_t tag = va_arg(ap, uint64_t);
  8182. uint32_t instruction = op | (upb_value_size(tag) << 16);
  8183. setofs(&instruction, labelref(c, label));
  8184. put32(c, instruction);
  8185. put32(c, tag);
  8186. put32(c, tag >> 32);
  8187. break;
  8188. }
  8189. }
  8190. va_end(ap);
  8191. }
  8192. #if defined(UPB_USE_JIT_X64) || defined(UPB_DUMP_BYTECODE)
  8193. const char *upb_pbdecoder_getopname(unsigned int op) {
  8194. #define QUOTE(x) #x
  8195. #define EXPAND_AND_QUOTE(x) QUOTE(x)
  8196. #define OPNAME(x) OP_##x
  8197. #define OP(x) case OPNAME(x): return EXPAND_AND_QUOTE(OPNAME(x));
  8198. #define T(x) OP(PARSE_##x)
  8199. /* Keep in sync with list in decoder.int.h. */
  8200. switch ((opcode)op) {
  8201. T(DOUBLE) T(FLOAT) T(INT64) T(UINT64) T(INT32) T(FIXED64) T(FIXED32)
  8202. T(BOOL) T(UINT32) T(SFIXED32) T(SFIXED64) T(SINT32) T(SINT64)
  8203. OP(STARTMSG) OP(ENDMSG) OP(STARTSEQ) OP(ENDSEQ) OP(STARTSUBMSG)
  8204. OP(ENDSUBMSG) OP(STARTSTR) OP(STRING) OP(ENDSTR) OP(CALL) OP(RET)
  8205. OP(PUSHLENDELIM) OP(PUSHTAGDELIM) OP(SETDELIM) OP(CHECKDELIM)
  8206. OP(BRANCH) OP(TAG1) OP(TAG2) OP(TAGN) OP(SETDISPATCH) OP(POP)
  8207. OP(SETBIGGROUPNUM) OP(DISPATCH) OP(HALT)
  8208. }
  8209. return "<unknown op>";
  8210. #undef OP
  8211. #undef T
  8212. }
  8213. #endif
  8214. #ifdef UPB_DUMP_BYTECODE
  8215. static void dumpbc(uint32_t *p, uint32_t *end, FILE *f) {
  8216. uint32_t *begin = p;
  8217. while (p < end) {
  8218. fprintf(f, "%p %8tx", p, p - begin);
  8219. uint32_t instr = *p++;
  8220. uint8_t op = getop(instr);
  8221. fprintf(f, " %s", upb_pbdecoder_getopname(op));
  8222. switch ((opcode)op) {
  8223. case OP_SETDISPATCH: {
  8224. const upb_inttable *dispatch;
  8225. memcpy(&dispatch, p, sizeof(void*));
  8226. p += ptr_words;
  8227. const upb_pbdecodermethod *method =
  8228. (void *)((char *)dispatch -
  8229. offsetof(upb_pbdecodermethod, dispatch));
  8230. fprintf(f, " %s", upb_msgdef_fullname(
  8231. upb_handlers_msgdef(method->dest_handlers_)));
  8232. break;
  8233. }
  8234. case OP_DISPATCH:
  8235. case OP_STARTMSG:
  8236. case OP_ENDMSG:
  8237. case OP_PUSHLENDELIM:
  8238. case OP_POP:
  8239. case OP_SETDELIM:
  8240. case OP_HALT:
  8241. case OP_RET:
  8242. break;
  8243. case OP_PARSE_DOUBLE:
  8244. case OP_PARSE_FLOAT:
  8245. case OP_PARSE_INT64:
  8246. case OP_PARSE_UINT64:
  8247. case OP_PARSE_INT32:
  8248. case OP_PARSE_FIXED64:
  8249. case OP_PARSE_FIXED32:
  8250. case OP_PARSE_BOOL:
  8251. case OP_PARSE_UINT32:
  8252. case OP_PARSE_SFIXED32:
  8253. case OP_PARSE_SFIXED64:
  8254. case OP_PARSE_SINT32:
  8255. case OP_PARSE_SINT64:
  8256. case OP_STARTSEQ:
  8257. case OP_ENDSEQ:
  8258. case OP_STARTSUBMSG:
  8259. case OP_ENDSUBMSG:
  8260. case OP_STARTSTR:
  8261. case OP_STRING:
  8262. case OP_ENDSTR:
  8263. case OP_PUSHTAGDELIM:
  8264. fprintf(f, " %d", instr >> 8);
  8265. break;
  8266. case OP_SETBIGGROUPNUM:
  8267. fprintf(f, " %d", *p++);
  8268. break;
  8269. case OP_CHECKDELIM:
  8270. case OP_CALL:
  8271. case OP_BRANCH:
  8272. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  8273. break;
  8274. case OP_TAG1:
  8275. case OP_TAG2: {
  8276. fprintf(f, " tag:0x%x", instr >> 16);
  8277. if (getofs(instr)) {
  8278. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  8279. }
  8280. break;
  8281. }
  8282. case OP_TAGN: {
  8283. uint64_t tag = *p++;
  8284. tag |= (uint64_t)*p++ << 32;
  8285. fprintf(f, " tag:0x%llx", (long long)tag);
  8286. fprintf(f, " n:%d", instr >> 16);
  8287. if (getofs(instr)) {
  8288. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  8289. }
  8290. break;
  8291. }
  8292. }
  8293. fputs("\n", f);
  8294. }
  8295. }
  8296. #endif
  8297. static uint64_t get_encoded_tag(const upb_fielddef *f, int wire_type) {
  8298. uint32_t tag = (upb_fielddef_number(f) << 3) | wire_type;
  8299. uint64_t encoded_tag = upb_vencode32(tag);
  8300. /* No tag should be greater than 5 bytes. */
  8301. UPB_ASSERT(encoded_tag <= 0xffffffffff);
  8302. return encoded_tag;
  8303. }
  8304. static void putchecktag(compiler *c, const upb_fielddef *f,
  8305. int wire_type, int dest) {
  8306. uint64_t tag = get_encoded_tag(f, wire_type);
  8307. switch (upb_value_size(tag)) {
  8308. case 1:
  8309. putop(c, OP_TAG1, dest, tag);
  8310. break;
  8311. case 2:
  8312. putop(c, OP_TAG2, dest, tag);
  8313. break;
  8314. default:
  8315. putop(c, OP_TAGN, dest, tag);
  8316. break;
  8317. }
  8318. }
  8319. static upb_selector_t getsel(const upb_fielddef *f, upb_handlertype_t type) {
  8320. upb_selector_t selector;
  8321. bool ok = upb_handlers_getselector(f, type, &selector);
  8322. UPB_ASSERT(ok);
  8323. return selector;
  8324. }
  8325. /* Takes an existing, primary dispatch table entry and repacks it with a
  8326. * different alternate wire type. Called when we are inserting a secondary
  8327. * dispatch table entry for an alternate wire type. */
  8328. static uint64_t repack(uint64_t dispatch, int new_wt2) {
  8329. uint64_t ofs;
  8330. uint8_t wt1;
  8331. uint8_t old_wt2;
  8332. upb_pbdecoder_unpackdispatch(dispatch, &ofs, &wt1, &old_wt2);
  8333. UPB_ASSERT(old_wt2 == NO_WIRE_TYPE); /* wt2 should not be set yet. */
  8334. return upb_pbdecoder_packdispatch(ofs, wt1, new_wt2);
  8335. }
  8336. /* Marks the current bytecode position as the dispatch target for this message,
  8337. * field, and wire type. */
  8338. static void dispatchtarget(compiler *c, upb_pbdecodermethod *method,
  8339. const upb_fielddef *f, int wire_type) {
  8340. /* Offset is relative to msg base. */
  8341. uint64_t ofs = pcofs(c) - method->code_base.ofs;
  8342. uint32_t fn = upb_fielddef_number(f);
  8343. upb_inttable *d = &method->dispatch;
  8344. upb_value v;
  8345. if (upb_inttable_remove(d, fn, &v)) {
  8346. /* TODO: prioritize based on packed setting in .proto file. */
  8347. uint64_t repacked = repack(upb_value_getuint64(v), wire_type);
  8348. upb_inttable_insert(d, fn, upb_value_uint64(repacked));
  8349. upb_inttable_insert(d, fn + UPB_MAX_FIELDNUMBER, upb_value_uint64(ofs));
  8350. } else {
  8351. uint64_t val = upb_pbdecoder_packdispatch(ofs, wire_type, NO_WIRE_TYPE);
  8352. upb_inttable_insert(d, fn, upb_value_uint64(val));
  8353. }
  8354. }
  8355. static void putpush(compiler *c, const upb_fielddef *f) {
  8356. if (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE) {
  8357. putop(c, OP_PUSHLENDELIM);
  8358. } else {
  8359. uint32_t fn = upb_fielddef_number(f);
  8360. if (fn >= 1 << 24) {
  8361. putop(c, OP_PUSHTAGDELIM, 0);
  8362. putop(c, OP_SETBIGGROUPNUM, fn);
  8363. } else {
  8364. putop(c, OP_PUSHTAGDELIM, fn);
  8365. }
  8366. }
  8367. }
  8368. static upb_pbdecodermethod *find_submethod(const compiler *c,
  8369. const upb_pbdecodermethod *method,
  8370. const upb_fielddef *f) {
  8371. const upb_handlers *sub =
  8372. upb_handlers_getsubhandlers(method->dest_handlers_, f);
  8373. upb_value v;
  8374. return upb_inttable_lookupptr(&c->group->methods, sub, &v)
  8375. ? upb_value_getptr(v)
  8376. : NULL;
  8377. }
  8378. static void putsel(compiler *c, opcode op, upb_selector_t sel,
  8379. const upb_handlers *h) {
  8380. if (upb_handlers_gethandler(h, sel)) {
  8381. putop(c, op, sel);
  8382. }
  8383. }
  8384. /* Puts an opcode to call a callback, but only if a callback actually exists for
  8385. * this field and handler type. */
  8386. static void maybeput(compiler *c, opcode op, const upb_handlers *h,
  8387. const upb_fielddef *f, upb_handlertype_t type) {
  8388. putsel(c, op, getsel(f, type), h);
  8389. }
  8390. static bool haslazyhandlers(const upb_handlers *h, const upb_fielddef *f) {
  8391. if (!upb_fielddef_lazy(f))
  8392. return false;
  8393. return upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STARTSTR)) ||
  8394. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STRING)) ||
  8395. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_ENDSTR));
  8396. }
  8397. /* bytecode compiler code generation ******************************************/
  8398. /* Symbolic names for our local labels. */
  8399. #define LABEL_LOOPSTART 1 /* Top of a repeated field loop. */
  8400. #define LABEL_LOOPBREAK 2 /* To jump out of a repeated loop */
  8401. #define LABEL_FIELD 3 /* Jump backward to find the most recent field. */
  8402. #define LABEL_ENDMSG 4 /* To reach the OP_ENDMSG instr for this msg. */
  8403. /* Generates bytecode to parse a single non-lazy message field. */
  8404. static void generate_msgfield(compiler *c, const upb_fielddef *f,
  8405. upb_pbdecodermethod *method) {
  8406. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  8407. const upb_pbdecodermethod *sub_m = find_submethod(c, method, f);
  8408. int wire_type;
  8409. if (!sub_m) {
  8410. /* Don't emit any code for this field at all; it will be parsed as an
  8411. * unknown field.
  8412. *
  8413. * TODO(haberman): we should change this to parse it as a string field
  8414. * instead. It will probably be faster, but more importantly, once we
  8415. * start vending unknown fields, a field shouldn't be treated as unknown
  8416. * just because it doesn't have subhandlers registered. */
  8417. return;
  8418. }
  8419. label(c, LABEL_FIELD);
  8420. wire_type =
  8421. (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE)
  8422. ? UPB_WIRE_TYPE_DELIMITED
  8423. : UPB_WIRE_TYPE_START_GROUP;
  8424. if (upb_fielddef_isseq(f)) {
  8425. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  8426. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  8427. dispatchtarget(c, method, f, wire_type);
  8428. putop(c, OP_PUSHTAGDELIM, 0);
  8429. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  8430. label(c, LABEL_LOOPSTART);
  8431. putpush(c, f);
  8432. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  8433. putop(c, OP_CALL, sub_m);
  8434. putop(c, OP_POP);
  8435. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  8436. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  8437. putop(c, OP_SETDELIM);
  8438. }
  8439. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  8440. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  8441. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  8442. label(c, LABEL_LOOPBREAK);
  8443. putop(c, OP_POP);
  8444. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  8445. } else {
  8446. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  8447. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  8448. dispatchtarget(c, method, f, wire_type);
  8449. putpush(c, f);
  8450. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  8451. putop(c, OP_CALL, sub_m);
  8452. putop(c, OP_POP);
  8453. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  8454. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  8455. putop(c, OP_SETDELIM);
  8456. }
  8457. }
  8458. }
  8459. /* Generates bytecode to parse a single string or lazy submessage field. */
  8460. static void generate_delimfield(compiler *c, const upb_fielddef *f,
  8461. upb_pbdecodermethod *method) {
  8462. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  8463. label(c, LABEL_FIELD);
  8464. if (upb_fielddef_isseq(f)) {
  8465. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  8466. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  8467. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  8468. putop(c, OP_PUSHTAGDELIM, 0);
  8469. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  8470. label(c, LABEL_LOOPSTART);
  8471. putop(c, OP_PUSHLENDELIM);
  8472. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  8473. /* Need to emit even if no handler to skip past the string. */
  8474. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  8475. putop(c, OP_POP);
  8476. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  8477. putop(c, OP_SETDELIM);
  8478. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  8479. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_LOOPBREAK);
  8480. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  8481. label(c, LABEL_LOOPBREAK);
  8482. putop(c, OP_POP);
  8483. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  8484. } else {
  8485. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  8486. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  8487. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  8488. putop(c, OP_PUSHLENDELIM);
  8489. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  8490. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  8491. putop(c, OP_POP);
  8492. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  8493. putop(c, OP_SETDELIM);
  8494. }
  8495. }
  8496. /* Generates bytecode to parse a single primitive field. */
  8497. static void generate_primitivefield(compiler *c, const upb_fielddef *f,
  8498. upb_pbdecodermethod *method) {
  8499. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  8500. upb_descriptortype_t descriptor_type = upb_fielddef_descriptortype(f);
  8501. opcode parse_type;
  8502. upb_selector_t sel;
  8503. int wire_type;
  8504. label(c, LABEL_FIELD);
  8505. /* From a decoding perspective, ENUM is the same as INT32. */
  8506. if (descriptor_type == UPB_DESCRIPTOR_TYPE_ENUM)
  8507. descriptor_type = UPB_DESCRIPTOR_TYPE_INT32;
  8508. parse_type = (opcode)descriptor_type;
  8509. /* TODO(haberman): generate packed or non-packed first depending on "packed"
  8510. * setting in the fielddef. This will favor (in speed) whichever was
  8511. * specified. */
  8512. UPB_ASSERT((int)parse_type >= 0 && parse_type <= OP_MAX);
  8513. sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  8514. wire_type = upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  8515. if (upb_fielddef_isseq(f)) {
  8516. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  8517. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  8518. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  8519. putop(c, OP_PUSHLENDELIM);
  8520. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); /* Packed */
  8521. label(c, LABEL_LOOPSTART);
  8522. putop(c, parse_type, sel);
  8523. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  8524. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  8525. dispatchtarget(c, method, f, wire_type);
  8526. putop(c, OP_PUSHTAGDELIM, 0);
  8527. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); /* Non-packed */
  8528. label(c, LABEL_LOOPSTART);
  8529. putop(c, parse_type, sel);
  8530. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  8531. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  8532. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  8533. label(c, LABEL_LOOPBREAK);
  8534. putop(c, OP_POP); /* Packed and non-packed join. */
  8535. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  8536. putop(c, OP_SETDELIM); /* Could remove for non-packed by dup ENDSEQ. */
  8537. } else {
  8538. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  8539. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  8540. dispatchtarget(c, method, f, wire_type);
  8541. putop(c, parse_type, sel);
  8542. }
  8543. }
  8544. /* Adds bytecode for parsing the given message to the given decoderplan,
  8545. * while adding all dispatch targets to this message's dispatch table. */
  8546. static void compile_method(compiler *c, upb_pbdecodermethod *method) {
  8547. const upb_handlers *h;
  8548. const upb_msgdef *md;
  8549. uint32_t* start_pc;
  8550. upb_msg_field_iter i;
  8551. upb_value val;
  8552. UPB_ASSERT(method);
  8553. /* Clear all entries in the dispatch table. */
  8554. upb_inttable_uninit(&method->dispatch);
  8555. upb_inttable_init(&method->dispatch, UPB_CTYPE_UINT64);
  8556. h = upb_pbdecodermethod_desthandlers(method);
  8557. md = upb_handlers_msgdef(h);
  8558. method->code_base.ofs = pcofs(c);
  8559. putop(c, OP_SETDISPATCH, &method->dispatch);
  8560. putsel(c, OP_STARTMSG, UPB_STARTMSG_SELECTOR, h);
  8561. label(c, LABEL_FIELD);
  8562. start_pc = c->pc;
  8563. for(upb_msg_field_begin(&i, md);
  8564. !upb_msg_field_done(&i);
  8565. upb_msg_field_next(&i)) {
  8566. const upb_fielddef *f = upb_msg_iter_field(&i);
  8567. upb_fieldtype_t type = upb_fielddef_type(f);
  8568. if (type == UPB_TYPE_MESSAGE && !(haslazyhandlers(h, f) && c->lazy)) {
  8569. generate_msgfield(c, f, method);
  8570. } else if (type == UPB_TYPE_STRING || type == UPB_TYPE_BYTES ||
  8571. type == UPB_TYPE_MESSAGE) {
  8572. generate_delimfield(c, f, method);
  8573. } else {
  8574. generate_primitivefield(c, f, method);
  8575. }
  8576. }
  8577. /* If there were no fields, or if no handlers were defined, we need to
  8578. * generate a non-empty loop body so that we can at least dispatch for unknown
  8579. * fields and check for the end of the message. */
  8580. if (c->pc == start_pc) {
  8581. /* Check for end-of-message. */
  8582. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  8583. /* Unconditionally dispatch. */
  8584. putop(c, OP_DISPATCH, 0);
  8585. }
  8586. /* For now we just loop back to the last field of the message (or if none,
  8587. * the DISPATCH opcode for the message). */
  8588. putop(c, OP_BRANCH, -LABEL_FIELD);
  8589. /* Insert both a label and a dispatch table entry for this end-of-msg. */
  8590. label(c, LABEL_ENDMSG);
  8591. val = upb_value_uint64(pcofs(c) - method->code_base.ofs);
  8592. upb_inttable_insert(&method->dispatch, DISPATCH_ENDMSG, val);
  8593. putsel(c, OP_ENDMSG, UPB_ENDMSG_SELECTOR, h);
  8594. putop(c, OP_RET);
  8595. upb_inttable_compact(&method->dispatch);
  8596. }
  8597. /* Populate "methods" with new upb_pbdecodermethod objects reachable from "h".
  8598. * Returns the method for these handlers.
  8599. *
  8600. * Generates a new method for every destination handlers reachable from "h". */
  8601. static void find_methods(compiler *c, const upb_handlers *h) {
  8602. upb_value v;
  8603. upb_msg_field_iter i;
  8604. const upb_msgdef *md;
  8605. if (upb_inttable_lookupptr(&c->group->methods, h, &v))
  8606. return;
  8607. newmethod(h, c->group);
  8608. /* Find submethods. */
  8609. md = upb_handlers_msgdef(h);
  8610. for(upb_msg_field_begin(&i, md);
  8611. !upb_msg_field_done(&i);
  8612. upb_msg_field_next(&i)) {
  8613. const upb_fielddef *f = upb_msg_iter_field(&i);
  8614. const upb_handlers *sub_h;
  8615. if (upb_fielddef_type(f) == UPB_TYPE_MESSAGE &&
  8616. (sub_h = upb_handlers_getsubhandlers(h, f)) != NULL) {
  8617. /* We only generate a decoder method for submessages with handlers.
  8618. * Others will be parsed as unknown fields. */
  8619. find_methods(c, sub_h);
  8620. }
  8621. }
  8622. }
  8623. /* (Re-)compile bytecode for all messages in "msgs."
  8624. * Overwrites any existing bytecode in "c". */
  8625. static void compile_methods(compiler *c) {
  8626. upb_inttable_iter i;
  8627. /* Start over at the beginning of the bytecode. */
  8628. c->pc = c->group->bytecode;
  8629. upb_inttable_begin(&i, &c->group->methods);
  8630. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  8631. upb_pbdecodermethod *method = upb_value_getptr(upb_inttable_iter_value(&i));
  8632. compile_method(c, method);
  8633. }
  8634. }
  8635. static void set_bytecode_handlers(mgroup *g) {
  8636. upb_inttable_iter i;
  8637. upb_inttable_begin(&i, &g->methods);
  8638. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  8639. upb_pbdecodermethod *m = upb_value_getptr(upb_inttable_iter_value(&i));
  8640. upb_byteshandler *h = &m->input_handler_;
  8641. m->code_base.ptr = g->bytecode + m->code_base.ofs;
  8642. upb_byteshandler_setstartstr(h, upb_pbdecoder_startbc, m->code_base.ptr);
  8643. upb_byteshandler_setstring(h, upb_pbdecoder_decode, g);
  8644. upb_byteshandler_setendstr(h, upb_pbdecoder_end, m);
  8645. }
  8646. }
  8647. /* JIT setup. *****************************************************************/
  8648. #ifdef UPB_USE_JIT_X64
  8649. static void sethandlers(mgroup *g, bool allowjit) {
  8650. g->jit_code = NULL;
  8651. if (allowjit) {
  8652. /* Compile byte-code into machine code, create handlers. */
  8653. upb_pbdecoder_jit(g);
  8654. } else {
  8655. set_bytecode_handlers(g);
  8656. }
  8657. }
  8658. #else /* UPB_USE_JIT_X64 */
  8659. static void sethandlers(mgroup *g, bool allowjit) {
  8660. /* No JIT compiled in; use bytecode handlers unconditionally. */
  8661. UPB_UNUSED(allowjit);
  8662. set_bytecode_handlers(g);
  8663. }
  8664. #endif /* UPB_USE_JIT_X64 */
  8665. /* TODO(haberman): allow this to be constructed for an arbitrary set of dest
  8666. * handlers and other mgroups (but verify we have a transitive closure). */
  8667. const mgroup *mgroup_new(const upb_handlers *dest, bool allowjit, bool lazy,
  8668. const void *owner) {
  8669. mgroup *g;
  8670. compiler *c;
  8671. UPB_UNUSED(allowjit);
  8672. UPB_ASSERT(upb_handlers_isfrozen(dest));
  8673. g = newgroup(owner);
  8674. c = newcompiler(g, lazy);
  8675. find_methods(c, dest);
  8676. /* We compile in two passes:
  8677. * 1. all messages are assigned relative offsets from the beginning of the
  8678. * bytecode (saved in method->code_base).
  8679. * 2. forwards OP_CALL instructions can be correctly linked since message
  8680. * offsets have been previously assigned.
  8681. *
  8682. * Could avoid the second pass by linking OP_CALL instructions somehow. */
  8683. compile_methods(c);
  8684. compile_methods(c);
  8685. g->bytecode_end = c->pc;
  8686. freecompiler(c);
  8687. #ifdef UPB_DUMP_BYTECODE
  8688. {
  8689. FILE *f = fopen("/tmp/upb-bytecode", "w");
  8690. UPB_ASSERT(f);
  8691. dumpbc(g->bytecode, g->bytecode_end, stderr);
  8692. dumpbc(g->bytecode, g->bytecode_end, f);
  8693. fclose(f);
  8694. f = fopen("/tmp/upb-bytecode.bin", "wb");
  8695. UPB_ASSERT(f);
  8696. fwrite(g->bytecode, 1, g->bytecode_end - g->bytecode, f);
  8697. fclose(f);
  8698. }
  8699. #endif
  8700. sethandlers(g, allowjit);
  8701. return g;
  8702. }
  8703. /* upb_pbcodecache ************************************************************/
  8704. void upb_pbcodecache_init(upb_pbcodecache *c) {
  8705. upb_inttable_init(&c->groups, UPB_CTYPE_CONSTPTR);
  8706. c->allow_jit_ = true;
  8707. }
  8708. void upb_pbcodecache_uninit(upb_pbcodecache *c) {
  8709. upb_inttable_iter i;
  8710. upb_inttable_begin(&i, &c->groups);
  8711. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  8712. const mgroup *group = upb_value_getconstptr(upb_inttable_iter_value(&i));
  8713. mgroup_unref(group, c);
  8714. }
  8715. upb_inttable_uninit(&c->groups);
  8716. }
  8717. bool upb_pbcodecache_allowjit(const upb_pbcodecache *c) {
  8718. return c->allow_jit_;
  8719. }
  8720. bool upb_pbcodecache_setallowjit(upb_pbcodecache *c, bool allow) {
  8721. if (upb_inttable_count(&c->groups) > 0)
  8722. return false;
  8723. c->allow_jit_ = allow;
  8724. return true;
  8725. }
  8726. const upb_pbdecodermethod *upb_pbcodecache_getdecodermethod(
  8727. upb_pbcodecache *c, const upb_pbdecodermethodopts *opts) {
  8728. upb_value v;
  8729. bool ok;
  8730. /* Right now we build a new DecoderMethod every time.
  8731. * TODO(haberman): properly cache methods by their true key. */
  8732. const mgroup *g = mgroup_new(opts->handlers, c->allow_jit_, opts->lazy, c);
  8733. upb_inttable_push(&c->groups, upb_value_constptr(g));
  8734. ok = upb_inttable_lookupptr(&g->methods, opts->handlers, &v);
  8735. UPB_ASSERT(ok);
  8736. return upb_value_getptr(v);
  8737. }
  8738. /* upb_pbdecodermethodopts ****************************************************/
  8739. void upb_pbdecodermethodopts_init(upb_pbdecodermethodopts *opts,
  8740. const upb_handlers *h) {
  8741. opts->handlers = h;
  8742. opts->lazy = false;
  8743. }
  8744. void upb_pbdecodermethodopts_setlazy(upb_pbdecodermethodopts *opts, bool lazy) {
  8745. opts->lazy = lazy;
  8746. }
  8747. /*
  8748. ** upb::Decoder (Bytecode Decoder VM)
  8749. **
  8750. ** Bytecode must previously have been generated using the bytecode compiler in
  8751. ** compile_decoder.c. This decoder then walks through the bytecode op-by-op to
  8752. ** parse the input.
  8753. **
  8754. ** Decoding is fully resumable; we just keep a pointer to the current bytecode
  8755. ** instruction and resume from there. A fair amount of the logic here is to
  8756. ** handle the fact that values can span buffer seams and we have to be able to
  8757. ** be capable of suspending/resuming from any byte in the stream. This
  8758. ** sometimes requires keeping a few trailing bytes from the last buffer around
  8759. ** in the "residual" buffer.
  8760. */
  8761. #include <inttypes.h>
  8762. #include <stddef.h>
  8763. #ifdef UPB_DUMP_BYTECODE
  8764. #include <stdio.h>
  8765. #endif
  8766. #define CHECK_SUSPEND(x) if (!(x)) return upb_pbdecoder_suspend(d);
  8767. /* Error messages that are shared between the bytecode and JIT decoders. */
  8768. const char *kPbDecoderStackOverflow = "Nesting too deep.";
  8769. const char *kPbDecoderSubmessageTooLong =
  8770. "Submessage end extends past enclosing submessage.";
  8771. /* Error messages shared within this file. */
  8772. static const char *kUnterminatedVarint = "Unterminated varint.";
  8773. /* upb_pbdecoder **************************************************************/
  8774. static opcode halt = OP_HALT;
  8775. /* A dummy character we can point to when the user passes us a NULL buffer.
  8776. * We need this because in C (NULL + 0) and (NULL - NULL) are undefined
  8777. * behavior, which would invalidate functions like curbufleft(). */
  8778. static const char dummy_char;
  8779. /* Whether an op consumes any of the input buffer. */
  8780. static bool consumes_input(opcode op) {
  8781. switch (op) {
  8782. case OP_SETDISPATCH:
  8783. case OP_STARTMSG:
  8784. case OP_ENDMSG:
  8785. case OP_STARTSEQ:
  8786. case OP_ENDSEQ:
  8787. case OP_STARTSUBMSG:
  8788. case OP_ENDSUBMSG:
  8789. case OP_STARTSTR:
  8790. case OP_ENDSTR:
  8791. case OP_PUSHTAGDELIM:
  8792. case OP_POP:
  8793. case OP_SETDELIM:
  8794. case OP_SETBIGGROUPNUM:
  8795. case OP_CHECKDELIM:
  8796. case OP_CALL:
  8797. case OP_RET:
  8798. case OP_BRANCH:
  8799. return false;
  8800. default:
  8801. return true;
  8802. }
  8803. }
  8804. static size_t stacksize(upb_pbdecoder *d, size_t entries) {
  8805. UPB_UNUSED(d);
  8806. return entries * sizeof(upb_pbdecoder_frame);
  8807. }
  8808. static size_t callstacksize(upb_pbdecoder *d, size_t entries) {
  8809. UPB_UNUSED(d);
  8810. #ifdef UPB_USE_JIT_X64
  8811. if (d->method_->is_native_) {
  8812. /* Each native stack frame needs two pointers, plus we need a few frames for
  8813. * the enter/exit trampolines. */
  8814. size_t ret = entries * sizeof(void*) * 2;
  8815. ret += sizeof(void*) * 10;
  8816. return ret;
  8817. }
  8818. #endif
  8819. return entries * sizeof(uint32_t*);
  8820. }
  8821. static bool in_residual_buf(const upb_pbdecoder *d, const char *p);
  8822. /* It's unfortunate that we have to micro-manage the compiler with
  8823. * UPB_FORCEINLINE and UPB_NOINLINE, especially since this tuning is necessarily
  8824. * specific to one hardware configuration. But empirically on a Core i7,
  8825. * performance increases 30-50% with these annotations. Every instance where
  8826. * these appear, gcc 4.2.1 made the wrong decision and degraded performance in
  8827. * benchmarks. */
  8828. static void seterr(upb_pbdecoder *d, const char *msg) {
  8829. upb_status status = UPB_STATUS_INIT;
  8830. upb_status_seterrmsg(&status, msg);
  8831. upb_env_reporterror(d->env, &status);
  8832. }
  8833. void upb_pbdecoder_seterr(upb_pbdecoder *d, const char *msg) {
  8834. seterr(d, msg);
  8835. }
  8836. /* Buffering ******************************************************************/
  8837. /* We operate on one buffer at a time, which is either the user's buffer passed
  8838. * to our "decode" callback or some residual bytes from the previous buffer. */
  8839. /* How many bytes can be safely read from d->ptr without reading past end-of-buf
  8840. * or past the current delimited end. */
  8841. static size_t curbufleft(const upb_pbdecoder *d) {
  8842. UPB_ASSERT(d->data_end >= d->ptr);
  8843. return d->data_end - d->ptr;
  8844. }
  8845. /* How many bytes are available before end-of-buffer. */
  8846. static size_t bufleft(const upb_pbdecoder *d) {
  8847. return d->end - d->ptr;
  8848. }
  8849. /* Overall stream offset of d->ptr. */
  8850. uint64_t offset(const upb_pbdecoder *d) {
  8851. return d->bufstart_ofs + (d->ptr - d->buf);
  8852. }
  8853. /* How many bytes are available before the end of this delimited region. */
  8854. size_t delim_remaining(const upb_pbdecoder *d) {
  8855. return d->top->end_ofs - offset(d);
  8856. }
  8857. /* Advances d->ptr. */
  8858. static void advance(upb_pbdecoder *d, size_t len) {
  8859. UPB_ASSERT(curbufleft(d) >= len);
  8860. d->ptr += len;
  8861. }
  8862. static bool in_buf(const char *p, const char *buf, const char *end) {
  8863. return p >= buf && p <= end;
  8864. }
  8865. static bool in_residual_buf(const upb_pbdecoder *d, const char *p) {
  8866. return in_buf(p, d->residual, d->residual_end);
  8867. }
  8868. /* Calculates the delim_end value, which is affected by both the current buffer
  8869. * and the parsing stack, so must be called whenever either is updated. */
  8870. static void set_delim_end(upb_pbdecoder *d) {
  8871. size_t delim_ofs = d->top->end_ofs - d->bufstart_ofs;
  8872. if (delim_ofs <= (size_t)(d->end - d->buf)) {
  8873. d->delim_end = d->buf + delim_ofs;
  8874. d->data_end = d->delim_end;
  8875. } else {
  8876. d->data_end = d->end;
  8877. d->delim_end = NULL;
  8878. }
  8879. }
  8880. static void switchtobuf(upb_pbdecoder *d, const char *buf, const char *end) {
  8881. d->ptr = buf;
  8882. d->buf = buf;
  8883. d->end = end;
  8884. set_delim_end(d);
  8885. }
  8886. static void advancetobuf(upb_pbdecoder *d, const char *buf, size_t len) {
  8887. UPB_ASSERT(curbufleft(d) == 0);
  8888. d->bufstart_ofs += (d->end - d->buf);
  8889. switchtobuf(d, buf, buf + len);
  8890. }
  8891. static void checkpoint(upb_pbdecoder *d) {
  8892. /* The assertion here is in the interests of efficiency, not correctness.
  8893. * We are trying to ensure that we don't checkpoint() more often than
  8894. * necessary. */
  8895. UPB_ASSERT(d->checkpoint != d->ptr);
  8896. d->checkpoint = d->ptr;
  8897. }
  8898. /* Skips "bytes" bytes in the stream, which may be more than available. If we
  8899. * skip more bytes than are available, we return a long read count to the caller
  8900. * indicating how many bytes can be skipped over before passing actual data
  8901. * again. Skipped bytes can pass a NULL buffer and the decoder guarantees they
  8902. * won't actually be read.
  8903. */
  8904. static int32_t skip(upb_pbdecoder *d, size_t bytes) {
  8905. UPB_ASSERT(!in_residual_buf(d, d->ptr) || d->size_param == 0);
  8906. UPB_ASSERT(d->skip == 0);
  8907. if (bytes > delim_remaining(d)) {
  8908. seterr(d, "Skipped value extended beyond enclosing submessage.");
  8909. return upb_pbdecoder_suspend(d);
  8910. } else if (bufleft(d) >= bytes) {
  8911. /* Skipped data is all in current buffer, and more is still available. */
  8912. advance(d, bytes);
  8913. d->skip = 0;
  8914. return DECODE_OK;
  8915. } else {
  8916. /* Skipped data extends beyond currently available buffers. */
  8917. d->pc = d->last;
  8918. d->skip = bytes - curbufleft(d);
  8919. d->bufstart_ofs += (d->end - d->buf);
  8920. d->residual_end = d->residual;
  8921. switchtobuf(d, d->residual, d->residual_end);
  8922. return d->size_param + d->skip;
  8923. }
  8924. }
  8925. /* Resumes the decoder from an initial state or from a previous suspend. */
  8926. int32_t upb_pbdecoder_resume(upb_pbdecoder *d, void *p, const char *buf,
  8927. size_t size, const upb_bufhandle *handle) {
  8928. UPB_UNUSED(p); /* Useless; just for the benefit of the JIT. */
  8929. /* d->skip and d->residual_end could probably elegantly be represented
  8930. * as a single variable, to more easily represent this invariant. */
  8931. UPB_ASSERT(!(d->skip && d->residual_end > d->residual));
  8932. /* We need to remember the original size_param, so that the value we return
  8933. * is relative to it, even if we do some skipping first. */
  8934. d->size_param = size;
  8935. d->handle = handle;
  8936. /* Have to handle this case specially (ie. not with skip()) because the user
  8937. * is allowed to pass a NULL buffer here, which won't allow us to safely
  8938. * calculate a d->end or use our normal functions like curbufleft(). */
  8939. if (d->skip && d->skip >= size) {
  8940. d->skip -= size;
  8941. d->bufstart_ofs += size;
  8942. buf = &dummy_char;
  8943. size = 0;
  8944. /* We can't just return now, because we might need to execute some ops
  8945. * like CHECKDELIM, which could call some callbacks and pop the stack. */
  8946. }
  8947. /* We need to pretend that this was the actual buffer param, since some of the
  8948. * calculations assume that d->ptr/d->buf is relative to this. */
  8949. d->buf_param = buf;
  8950. if (!buf) {
  8951. /* NULL buf is ok if its entire span is covered by the "skip" above, but
  8952. * by this point we know that "skip" doesn't cover the buffer. */
  8953. seterr(d, "Passed NULL buffer over non-skippable region.");
  8954. return upb_pbdecoder_suspend(d);
  8955. }
  8956. if (d->residual_end > d->residual) {
  8957. /* We have residual bytes from the last buffer. */
  8958. UPB_ASSERT(d->ptr == d->residual);
  8959. } else {
  8960. switchtobuf(d, buf, buf + size);
  8961. }
  8962. d->checkpoint = d->ptr;
  8963. /* Handle skips that don't cover the whole buffer (as above). */
  8964. if (d->skip) {
  8965. size_t skip_bytes = d->skip;
  8966. d->skip = 0;
  8967. CHECK_RETURN(skip(d, skip_bytes));
  8968. checkpoint(d);
  8969. }
  8970. /* If we're inside an unknown group, continue to parse unknown values. */
  8971. if (d->top->groupnum < 0) {
  8972. CHECK_RETURN(upb_pbdecoder_skipunknown(d, -1, 0));
  8973. checkpoint(d);
  8974. }
  8975. return DECODE_OK;
  8976. }
  8977. /* Suspends the decoder at the last checkpoint, without saving any residual
  8978. * bytes. If there are any unconsumed bytes, returns a short byte count. */
  8979. size_t upb_pbdecoder_suspend(upb_pbdecoder *d) {
  8980. d->pc = d->last;
  8981. if (d->checkpoint == d->residual) {
  8982. /* Checkpoint was in residual buf; no user bytes were consumed. */
  8983. d->ptr = d->residual;
  8984. return 0;
  8985. } else {
  8986. size_t ret = d->size_param - (d->end - d->checkpoint);
  8987. UPB_ASSERT(!in_residual_buf(d, d->checkpoint));
  8988. UPB_ASSERT(d->buf == d->buf_param || d->buf == &dummy_char);
  8989. d->bufstart_ofs += (d->checkpoint - d->buf);
  8990. d->residual_end = d->residual;
  8991. switchtobuf(d, d->residual, d->residual_end);
  8992. return ret;
  8993. }
  8994. }
  8995. /* Suspends the decoder at the last checkpoint, and saves any unconsumed
  8996. * bytes in our residual buffer. This is necessary if we need more user
  8997. * bytes to form a complete value, which might not be contiguous in the
  8998. * user's buffers. Always consumes all user bytes. */
  8999. static size_t suspend_save(upb_pbdecoder *d) {
  9000. /* We hit end-of-buffer before we could parse a full value.
  9001. * Save any unconsumed bytes (if any) to the residual buffer. */
  9002. d->pc = d->last;
  9003. if (d->checkpoint == d->residual) {
  9004. /* Checkpoint was in residual buf; append user byte(s) to residual buf. */
  9005. UPB_ASSERT((d->residual_end - d->residual) + d->size_param <=
  9006. sizeof(d->residual));
  9007. if (!in_residual_buf(d, d->ptr)) {
  9008. d->bufstart_ofs -= (d->residual_end - d->residual);
  9009. }
  9010. memcpy(d->residual_end, d->buf_param, d->size_param);
  9011. d->residual_end += d->size_param;
  9012. } else {
  9013. /* Checkpoint was in user buf; old residual bytes not needed. */
  9014. size_t save;
  9015. UPB_ASSERT(!in_residual_buf(d, d->checkpoint));
  9016. d->ptr = d->checkpoint;
  9017. save = curbufleft(d);
  9018. UPB_ASSERT(save <= sizeof(d->residual));
  9019. memcpy(d->residual, d->ptr, save);
  9020. d->residual_end = d->residual + save;
  9021. d->bufstart_ofs = offset(d);
  9022. }
  9023. switchtobuf(d, d->residual, d->residual_end);
  9024. return d->size_param;
  9025. }
  9026. /* Copies the next "bytes" bytes into "buf" and advances the stream.
  9027. * Requires that this many bytes are available in the current buffer. */
  9028. UPB_FORCEINLINE static void consumebytes(upb_pbdecoder *d, void *buf,
  9029. size_t bytes) {
  9030. UPB_ASSERT(bytes <= curbufleft(d));
  9031. memcpy(buf, d->ptr, bytes);
  9032. advance(d, bytes);
  9033. }
  9034. /* Slow path for getting the next "bytes" bytes, regardless of whether they are
  9035. * available in the current buffer or not. Returns a status code as described
  9036. * in decoder.int.h. */
  9037. UPB_NOINLINE static int32_t getbytes_slow(upb_pbdecoder *d, void *buf,
  9038. size_t bytes) {
  9039. const size_t avail = curbufleft(d);
  9040. consumebytes(d, buf, avail);
  9041. bytes -= avail;
  9042. UPB_ASSERT(bytes > 0);
  9043. if (in_residual_buf(d, d->ptr)) {
  9044. advancetobuf(d, d->buf_param, d->size_param);
  9045. }
  9046. if (curbufleft(d) >= bytes) {
  9047. consumebytes(d, (char *)buf + avail, bytes);
  9048. return DECODE_OK;
  9049. } else if (d->data_end == d->delim_end) {
  9050. seterr(d, "Submessage ended in the middle of a value or group");
  9051. return upb_pbdecoder_suspend(d);
  9052. } else {
  9053. return suspend_save(d);
  9054. }
  9055. }
  9056. /* Gets the next "bytes" bytes, regardless of whether they are available in the
  9057. * current buffer or not. Returns a status code as described in decoder.int.h.
  9058. */
  9059. UPB_FORCEINLINE static int32_t getbytes(upb_pbdecoder *d, void *buf,
  9060. size_t bytes) {
  9061. if (curbufleft(d) >= bytes) {
  9062. /* Buffer has enough data to satisfy. */
  9063. consumebytes(d, buf, bytes);
  9064. return DECODE_OK;
  9065. } else {
  9066. return getbytes_slow(d, buf, bytes);
  9067. }
  9068. }
  9069. UPB_NOINLINE static size_t peekbytes_slow(upb_pbdecoder *d, void *buf,
  9070. size_t bytes) {
  9071. size_t ret = curbufleft(d);
  9072. memcpy(buf, d->ptr, ret);
  9073. if (in_residual_buf(d, d->ptr)) {
  9074. size_t copy = UPB_MIN(bytes - ret, d->size_param);
  9075. memcpy((char *)buf + ret, d->buf_param, copy);
  9076. ret += copy;
  9077. }
  9078. return ret;
  9079. }
  9080. UPB_FORCEINLINE static size_t peekbytes(upb_pbdecoder *d, void *buf,
  9081. size_t bytes) {
  9082. if (curbufleft(d) >= bytes) {
  9083. memcpy(buf, d->ptr, bytes);
  9084. return bytes;
  9085. } else {
  9086. return peekbytes_slow(d, buf, bytes);
  9087. }
  9088. }
  9089. /* Decoding of wire types *****************************************************/
  9090. /* Slow path for decoding a varint from the current buffer position.
  9091. * Returns a status code as described in decoder.int.h. */
  9092. UPB_NOINLINE int32_t upb_pbdecoder_decode_varint_slow(upb_pbdecoder *d,
  9093. uint64_t *u64) {
  9094. uint8_t byte = 0x80;
  9095. int bitpos;
  9096. *u64 = 0;
  9097. for(bitpos = 0; bitpos < 70 && (byte & 0x80); bitpos += 7) {
  9098. CHECK_RETURN(getbytes(d, &byte, 1));
  9099. *u64 |= (uint64_t)(byte & 0x7F) << bitpos;
  9100. }
  9101. if(bitpos == 70 && (byte & 0x80)) {
  9102. seterr(d, kUnterminatedVarint);
  9103. return upb_pbdecoder_suspend(d);
  9104. }
  9105. return DECODE_OK;
  9106. }
  9107. /* Decodes a varint from the current buffer position.
  9108. * Returns a status code as described in decoder.int.h. */
  9109. UPB_FORCEINLINE static int32_t decode_varint(upb_pbdecoder *d, uint64_t *u64) {
  9110. if (curbufleft(d) > 0 && !(*d->ptr & 0x80)) {
  9111. *u64 = *d->ptr;
  9112. advance(d, 1);
  9113. return DECODE_OK;
  9114. } else if (curbufleft(d) >= 10) {
  9115. /* Fast case. */
  9116. upb_decoderet r = upb_vdecode_fast(d->ptr);
  9117. if (r.p == NULL) {
  9118. seterr(d, kUnterminatedVarint);
  9119. return upb_pbdecoder_suspend(d);
  9120. }
  9121. advance(d, r.p - d->ptr);
  9122. *u64 = r.val;
  9123. return DECODE_OK;
  9124. } else {
  9125. /* Slow case -- varint spans buffer seam. */
  9126. return upb_pbdecoder_decode_varint_slow(d, u64);
  9127. }
  9128. }
  9129. /* Decodes a 32-bit varint from the current buffer position.
  9130. * Returns a status code as described in decoder.int.h. */
  9131. UPB_FORCEINLINE static int32_t decode_v32(upb_pbdecoder *d, uint32_t *u32) {
  9132. uint64_t u64;
  9133. int32_t ret = decode_varint(d, &u64);
  9134. if (ret >= 0) return ret;
  9135. if (u64 > UINT32_MAX) {
  9136. seterr(d, "Unterminated 32-bit varint");
  9137. /* TODO(haberman) guarantee that this function return is >= 0 somehow,
  9138. * so we know this path will always be treated as error by our caller.
  9139. * Right now the size_t -> int32_t can overflow and produce negative values.
  9140. */
  9141. *u32 = 0;
  9142. return upb_pbdecoder_suspend(d);
  9143. }
  9144. *u32 = u64;
  9145. return DECODE_OK;
  9146. }
  9147. /* Decodes a fixed32 from the current buffer position.
  9148. * Returns a status code as described in decoder.int.h.
  9149. * TODO: proper byte swapping for big-endian machines. */
  9150. UPB_FORCEINLINE static int32_t decode_fixed32(upb_pbdecoder *d, uint32_t *u32) {
  9151. return getbytes(d, u32, 4);
  9152. }
  9153. /* Decodes a fixed64 from the current buffer position.
  9154. * Returns a status code as described in decoder.int.h.
  9155. * TODO: proper byte swapping for big-endian machines. */
  9156. UPB_FORCEINLINE static int32_t decode_fixed64(upb_pbdecoder *d, uint64_t *u64) {
  9157. return getbytes(d, u64, 8);
  9158. }
  9159. /* Non-static versions of the above functions.
  9160. * These are called by the JIT for fallback paths. */
  9161. int32_t upb_pbdecoder_decode_f32(upb_pbdecoder *d, uint32_t *u32) {
  9162. return decode_fixed32(d, u32);
  9163. }
  9164. int32_t upb_pbdecoder_decode_f64(upb_pbdecoder *d, uint64_t *u64) {
  9165. return decode_fixed64(d, u64);
  9166. }
  9167. static double as_double(uint64_t n) { double d; memcpy(&d, &n, 8); return d; }
  9168. static float as_float(uint32_t n) { float f; memcpy(&f, &n, 4); return f; }
  9169. /* Pushes a frame onto the decoder stack. */
  9170. static bool decoder_push(upb_pbdecoder *d, uint64_t end) {
  9171. upb_pbdecoder_frame *fr = d->top;
  9172. if (end > fr->end_ofs) {
  9173. seterr(d, kPbDecoderSubmessageTooLong);
  9174. return false;
  9175. } else if (fr == d->limit) {
  9176. seterr(d, kPbDecoderStackOverflow);
  9177. return false;
  9178. }
  9179. fr++;
  9180. fr->end_ofs = end;
  9181. fr->dispatch = NULL;
  9182. fr->groupnum = 0;
  9183. d->top = fr;
  9184. return true;
  9185. }
  9186. static bool pushtagdelim(upb_pbdecoder *d, uint32_t arg) {
  9187. /* While we expect to see an "end" tag (either ENDGROUP or a non-sequence
  9188. * field number) prior to hitting any enclosing submessage end, pushing our
  9189. * existing delim end prevents us from continuing to parse values from a
  9190. * corrupt proto that doesn't give us an END tag in time. */
  9191. if (!decoder_push(d, d->top->end_ofs))
  9192. return false;
  9193. d->top->groupnum = arg;
  9194. return true;
  9195. }
  9196. /* Pops a frame from the decoder stack. */
  9197. static void decoder_pop(upb_pbdecoder *d) { d->top--; }
  9198. UPB_NOINLINE int32_t upb_pbdecoder_checktag_slow(upb_pbdecoder *d,
  9199. uint64_t expected) {
  9200. uint64_t data = 0;
  9201. size_t bytes = upb_value_size(expected);
  9202. size_t read = peekbytes(d, &data, bytes);
  9203. if (read == bytes && data == expected) {
  9204. /* Advance past matched bytes. */
  9205. int32_t ok = getbytes(d, &data, read);
  9206. UPB_ASSERT(ok < 0);
  9207. return DECODE_OK;
  9208. } else if (read < bytes && memcmp(&data, &expected, read) == 0) {
  9209. return suspend_save(d);
  9210. } else {
  9211. return DECODE_MISMATCH;
  9212. }
  9213. }
  9214. int32_t upb_pbdecoder_skipunknown(upb_pbdecoder *d, int32_t fieldnum,
  9215. uint8_t wire_type) {
  9216. if (fieldnum >= 0)
  9217. goto have_tag;
  9218. while (true) {
  9219. uint32_t tag;
  9220. CHECK_RETURN(decode_v32(d, &tag));
  9221. wire_type = tag & 0x7;
  9222. fieldnum = tag >> 3;
  9223. have_tag:
  9224. if (fieldnum == 0) {
  9225. seterr(d, "Saw invalid field number (0)");
  9226. return upb_pbdecoder_suspend(d);
  9227. }
  9228. switch (wire_type) {
  9229. case UPB_WIRE_TYPE_32BIT:
  9230. CHECK_RETURN(skip(d, 4));
  9231. break;
  9232. case UPB_WIRE_TYPE_64BIT:
  9233. CHECK_RETURN(skip(d, 8));
  9234. break;
  9235. case UPB_WIRE_TYPE_VARINT: {
  9236. uint64_t u64;
  9237. CHECK_RETURN(decode_varint(d, &u64));
  9238. break;
  9239. }
  9240. case UPB_WIRE_TYPE_DELIMITED: {
  9241. uint32_t len;
  9242. CHECK_RETURN(decode_v32(d, &len));
  9243. CHECK_RETURN(skip(d, len));
  9244. break;
  9245. }
  9246. case UPB_WIRE_TYPE_START_GROUP:
  9247. CHECK_SUSPEND(pushtagdelim(d, -fieldnum));
  9248. break;
  9249. case UPB_WIRE_TYPE_END_GROUP:
  9250. if (fieldnum == -d->top->groupnum) {
  9251. decoder_pop(d);
  9252. } else if (fieldnum == d->top->groupnum) {
  9253. return DECODE_ENDGROUP;
  9254. } else {
  9255. seterr(d, "Unmatched ENDGROUP tag.");
  9256. return upb_pbdecoder_suspend(d);
  9257. }
  9258. break;
  9259. default:
  9260. seterr(d, "Invalid wire type");
  9261. return upb_pbdecoder_suspend(d);
  9262. }
  9263. if (d->top->groupnum >= 0) {
  9264. /* TODO: More code needed for handling unknown groups. */
  9265. upb_sink_putunknown(&d->top->sink, d->checkpoint, d->ptr - d->checkpoint);
  9266. return DECODE_OK;
  9267. }
  9268. /* Unknown group -- continue looping over unknown fields. */
  9269. checkpoint(d);
  9270. }
  9271. }
  9272. static void goto_endmsg(upb_pbdecoder *d) {
  9273. upb_value v;
  9274. bool found = upb_inttable_lookup32(d->top->dispatch, DISPATCH_ENDMSG, &v);
  9275. UPB_ASSERT(found);
  9276. d->pc = d->top->base + upb_value_getuint64(v);
  9277. }
  9278. /* Parses a tag and jumps to the corresponding bytecode instruction for this
  9279. * field.
  9280. *
  9281. * If the tag is unknown (or the wire type doesn't match), parses the field as
  9282. * unknown. If the tag is a valid ENDGROUP tag, jumps to the bytecode
  9283. * instruction for the end of message. */
  9284. static int32_t dispatch(upb_pbdecoder *d) {
  9285. upb_inttable *dispatch = d->top->dispatch;
  9286. uint32_t tag;
  9287. uint8_t wire_type;
  9288. uint32_t fieldnum;
  9289. upb_value val;
  9290. int32_t retval;
  9291. /* Decode tag. */
  9292. CHECK_RETURN(decode_v32(d, &tag));
  9293. wire_type = tag & 0x7;
  9294. fieldnum = tag >> 3;
  9295. /* Lookup tag. Because of packed/non-packed compatibility, we have to
  9296. * check the wire type against two possibilities. */
  9297. if (fieldnum != DISPATCH_ENDMSG &&
  9298. upb_inttable_lookup32(dispatch, fieldnum, &val)) {
  9299. uint64_t v = upb_value_getuint64(val);
  9300. if (wire_type == (v & 0xff)) {
  9301. d->pc = d->top->base + (v >> 16);
  9302. return DECODE_OK;
  9303. } else if (wire_type == ((v >> 8) & 0xff)) {
  9304. bool found =
  9305. upb_inttable_lookup(dispatch, fieldnum + UPB_MAX_FIELDNUMBER, &val);
  9306. UPB_ASSERT(found);
  9307. d->pc = d->top->base + upb_value_getuint64(val);
  9308. return DECODE_OK;
  9309. }
  9310. }
  9311. /* We have some unknown fields (or ENDGROUP) to parse. The DISPATCH or TAG
  9312. * bytecode that triggered this is preceded by a CHECKDELIM bytecode which
  9313. * we need to back up to, so that when we're done skipping unknown data we
  9314. * can re-check the delimited end. */
  9315. d->last--; /* Necessary if we get suspended */
  9316. d->pc = d->last;
  9317. UPB_ASSERT(getop(*d->last) == OP_CHECKDELIM);
  9318. /* Unknown field or ENDGROUP. */
  9319. retval = upb_pbdecoder_skipunknown(d, fieldnum, wire_type);
  9320. CHECK_RETURN(retval);
  9321. if (retval == DECODE_ENDGROUP) {
  9322. goto_endmsg(d);
  9323. return DECODE_OK;
  9324. }
  9325. return DECODE_OK;
  9326. }
  9327. /* Callers know that the stack is more than one deep because the opcodes that
  9328. * call this only occur after PUSH operations. */
  9329. upb_pbdecoder_frame *outer_frame(upb_pbdecoder *d) {
  9330. UPB_ASSERT(d->top != d->stack);
  9331. return d->top - 1;
  9332. }
  9333. /* The main decoding loop *****************************************************/
  9334. /* The main decoder VM function. Uses traditional bytecode dispatch loop with a
  9335. * switch() statement. */
  9336. size_t run_decoder_vm(upb_pbdecoder *d, const mgroup *group,
  9337. const upb_bufhandle* handle) {
  9338. #define VMCASE(op, code) \
  9339. case op: { code; if (consumes_input(op)) checkpoint(d); break; }
  9340. #define PRIMITIVE_OP(type, wt, name, convfunc, ctype) \
  9341. VMCASE(OP_PARSE_ ## type, { \
  9342. ctype val; \
  9343. CHECK_RETURN(decode_ ## wt(d, &val)); \
  9344. upb_sink_put ## name(&d->top->sink, arg, (convfunc)(val)); \
  9345. })
  9346. while(1) {
  9347. int32_t instruction;
  9348. opcode op;
  9349. uint32_t arg;
  9350. int32_t longofs;
  9351. d->last = d->pc;
  9352. instruction = *d->pc++;
  9353. op = getop(instruction);
  9354. arg = instruction >> 8;
  9355. longofs = arg;
  9356. UPB_ASSERT(d->ptr != d->residual_end);
  9357. UPB_UNUSED(group);
  9358. #ifdef UPB_DUMP_BYTECODE
  9359. fprintf(stderr, "s_ofs=%d buf_ofs=%d data_rem=%d buf_rem=%d delim_rem=%d "
  9360. "%x %s (%d)\n",
  9361. (int)offset(d),
  9362. (int)(d->ptr - d->buf),
  9363. (int)(d->data_end - d->ptr),
  9364. (int)(d->end - d->ptr),
  9365. (int)((d->top->end_ofs - d->bufstart_ofs) - (d->ptr - d->buf)),
  9366. (int)(d->pc - 1 - group->bytecode),
  9367. upb_pbdecoder_getopname(op),
  9368. arg);
  9369. #endif
  9370. switch (op) {
  9371. /* Technically, we are losing data if we see a 32-bit varint that is not
  9372. * properly sign-extended. We could detect this and error about the data
  9373. * loss, but proto2 does not do this, so we pass. */
  9374. PRIMITIVE_OP(INT32, varint, int32, int32_t, uint64_t)
  9375. PRIMITIVE_OP(INT64, varint, int64, int64_t, uint64_t)
  9376. PRIMITIVE_OP(UINT32, varint, uint32, uint32_t, uint64_t)
  9377. PRIMITIVE_OP(UINT64, varint, uint64, uint64_t, uint64_t)
  9378. PRIMITIVE_OP(FIXED32, fixed32, uint32, uint32_t, uint32_t)
  9379. PRIMITIVE_OP(FIXED64, fixed64, uint64, uint64_t, uint64_t)
  9380. PRIMITIVE_OP(SFIXED32, fixed32, int32, int32_t, uint32_t)
  9381. PRIMITIVE_OP(SFIXED64, fixed64, int64, int64_t, uint64_t)
  9382. PRIMITIVE_OP(BOOL, varint, bool, bool, uint64_t)
  9383. PRIMITIVE_OP(DOUBLE, fixed64, double, as_double, uint64_t)
  9384. PRIMITIVE_OP(FLOAT, fixed32, float, as_float, uint32_t)
  9385. PRIMITIVE_OP(SINT32, varint, int32, upb_zzdec_32, uint64_t)
  9386. PRIMITIVE_OP(SINT64, varint, int64, upb_zzdec_64, uint64_t)
  9387. VMCASE(OP_SETDISPATCH,
  9388. d->top->base = d->pc - 1;
  9389. memcpy(&d->top->dispatch, d->pc, sizeof(void*));
  9390. d->pc += sizeof(void*) / sizeof(uint32_t);
  9391. )
  9392. VMCASE(OP_STARTMSG,
  9393. CHECK_SUSPEND(upb_sink_startmsg(&d->top->sink));
  9394. )
  9395. VMCASE(OP_ENDMSG,
  9396. CHECK_SUSPEND(upb_sink_endmsg(&d->top->sink, d->status));
  9397. )
  9398. VMCASE(OP_STARTSEQ,
  9399. upb_pbdecoder_frame *outer = outer_frame(d);
  9400. CHECK_SUSPEND(upb_sink_startseq(&outer->sink, arg, &d->top->sink));
  9401. )
  9402. VMCASE(OP_ENDSEQ,
  9403. CHECK_SUSPEND(upb_sink_endseq(&d->top->sink, arg));
  9404. )
  9405. VMCASE(OP_STARTSUBMSG,
  9406. upb_pbdecoder_frame *outer = outer_frame(d);
  9407. CHECK_SUSPEND(upb_sink_startsubmsg(&outer->sink, arg, &d->top->sink));
  9408. )
  9409. VMCASE(OP_ENDSUBMSG,
  9410. CHECK_SUSPEND(upb_sink_endsubmsg(&d->top->sink, arg));
  9411. )
  9412. VMCASE(OP_STARTSTR,
  9413. uint32_t len = delim_remaining(d);
  9414. upb_pbdecoder_frame *outer = outer_frame(d);
  9415. CHECK_SUSPEND(upb_sink_startstr(&outer->sink, arg, len, &d->top->sink));
  9416. if (len == 0) {
  9417. d->pc++; /* Skip OP_STRING. */
  9418. }
  9419. )
  9420. VMCASE(OP_STRING,
  9421. uint32_t len = curbufleft(d);
  9422. size_t n = upb_sink_putstring(&d->top->sink, arg, d->ptr, len, handle);
  9423. if (n > len) {
  9424. if (n > delim_remaining(d)) {
  9425. seterr(d, "Tried to skip past end of string.");
  9426. return upb_pbdecoder_suspend(d);
  9427. } else {
  9428. int32_t ret = skip(d, n);
  9429. /* This shouldn't return DECODE_OK, because n > len. */
  9430. UPB_ASSERT(ret >= 0);
  9431. return ret;
  9432. }
  9433. }
  9434. advance(d, n);
  9435. if (n < len || d->delim_end == NULL) {
  9436. /* We aren't finished with this string yet. */
  9437. d->pc--; /* Repeat OP_STRING. */
  9438. if (n > 0) checkpoint(d);
  9439. return upb_pbdecoder_suspend(d);
  9440. }
  9441. )
  9442. VMCASE(OP_ENDSTR,
  9443. CHECK_SUSPEND(upb_sink_endstr(&d->top->sink, arg));
  9444. )
  9445. VMCASE(OP_PUSHTAGDELIM,
  9446. CHECK_SUSPEND(pushtagdelim(d, arg));
  9447. )
  9448. VMCASE(OP_SETBIGGROUPNUM,
  9449. d->top->groupnum = *d->pc++;
  9450. )
  9451. VMCASE(OP_POP,
  9452. UPB_ASSERT(d->top > d->stack);
  9453. decoder_pop(d);
  9454. )
  9455. VMCASE(OP_PUSHLENDELIM,
  9456. uint32_t len;
  9457. CHECK_RETURN(decode_v32(d, &len));
  9458. CHECK_SUSPEND(decoder_push(d, offset(d) + len));
  9459. set_delim_end(d);
  9460. )
  9461. VMCASE(OP_SETDELIM,
  9462. set_delim_end(d);
  9463. )
  9464. VMCASE(OP_CHECKDELIM,
  9465. /* We are guaranteed of this assert because we never allow ourselves to
  9466. * consume bytes beyond data_end, which covers delim_end when non-NULL.
  9467. */
  9468. UPB_ASSERT(!(d->delim_end && d->ptr > d->delim_end));
  9469. if (d->ptr == d->delim_end)
  9470. d->pc += longofs;
  9471. )
  9472. VMCASE(OP_CALL,
  9473. d->callstack[d->call_len++] = d->pc;
  9474. d->pc += longofs;
  9475. )
  9476. VMCASE(OP_RET,
  9477. UPB_ASSERT(d->call_len > 0);
  9478. d->pc = d->callstack[--d->call_len];
  9479. )
  9480. VMCASE(OP_BRANCH,
  9481. d->pc += longofs;
  9482. )
  9483. VMCASE(OP_TAG1,
  9484. uint8_t expected;
  9485. CHECK_SUSPEND(curbufleft(d) > 0);
  9486. expected = (arg >> 8) & 0xff;
  9487. if (*d->ptr == expected) {
  9488. advance(d, 1);
  9489. } else {
  9490. int8_t shortofs;
  9491. badtag:
  9492. shortofs = arg;
  9493. if (shortofs == LABEL_DISPATCH) {
  9494. CHECK_RETURN(dispatch(d));
  9495. } else {
  9496. d->pc += shortofs;
  9497. break; /* Avoid checkpoint(). */
  9498. }
  9499. }
  9500. )
  9501. VMCASE(OP_TAG2,
  9502. uint16_t expected;
  9503. CHECK_SUSPEND(curbufleft(d) > 0);
  9504. expected = (arg >> 8) & 0xffff;
  9505. if (curbufleft(d) >= 2) {
  9506. uint16_t actual;
  9507. memcpy(&actual, d->ptr, 2);
  9508. if (expected == actual) {
  9509. advance(d, 2);
  9510. } else {
  9511. goto badtag;
  9512. }
  9513. } else {
  9514. int32_t result = upb_pbdecoder_checktag_slow(d, expected);
  9515. if (result == DECODE_MISMATCH) goto badtag;
  9516. if (result >= 0) return result;
  9517. }
  9518. )
  9519. VMCASE(OP_TAGN, {
  9520. uint64_t expected;
  9521. int32_t result;
  9522. memcpy(&expected, d->pc, 8);
  9523. d->pc += 2;
  9524. result = upb_pbdecoder_checktag_slow(d, expected);
  9525. if (result == DECODE_MISMATCH) goto badtag;
  9526. if (result >= 0) return result;
  9527. })
  9528. VMCASE(OP_DISPATCH, {
  9529. CHECK_RETURN(dispatch(d));
  9530. })
  9531. VMCASE(OP_HALT, {
  9532. return d->size_param;
  9533. })
  9534. }
  9535. }
  9536. }
  9537. /* BytesHandler handlers ******************************************************/
  9538. void *upb_pbdecoder_startbc(void *closure, const void *pc, size_t size_hint) {
  9539. upb_pbdecoder *d = closure;
  9540. UPB_UNUSED(size_hint);
  9541. d->top->end_ofs = UINT64_MAX;
  9542. d->bufstart_ofs = 0;
  9543. d->call_len = 1;
  9544. d->callstack[0] = &halt;
  9545. d->pc = pc;
  9546. d->skip = 0;
  9547. return d;
  9548. }
  9549. void *upb_pbdecoder_startjit(void *closure, const void *hd, size_t size_hint) {
  9550. upb_pbdecoder *d = closure;
  9551. UPB_UNUSED(hd);
  9552. UPB_UNUSED(size_hint);
  9553. d->top->end_ofs = UINT64_MAX;
  9554. d->bufstart_ofs = 0;
  9555. d->call_len = 0;
  9556. d->skip = 0;
  9557. return d;
  9558. }
  9559. bool upb_pbdecoder_end(void *closure, const void *handler_data) {
  9560. upb_pbdecoder *d = closure;
  9561. const upb_pbdecodermethod *method = handler_data;
  9562. uint64_t end;
  9563. char dummy;
  9564. if (d->residual_end > d->residual) {
  9565. seterr(d, "Unexpected EOF: decoder still has buffered unparsed data");
  9566. return false;
  9567. }
  9568. if (d->skip) {
  9569. seterr(d, "Unexpected EOF inside skipped data");
  9570. return false;
  9571. }
  9572. if (d->top->end_ofs != UINT64_MAX) {
  9573. seterr(d, "Unexpected EOF inside delimited string");
  9574. return false;
  9575. }
  9576. /* The user's end() call indicates that the message ends here. */
  9577. end = offset(d);
  9578. d->top->end_ofs = end;
  9579. #ifdef UPB_USE_JIT_X64
  9580. if (method->is_native_) {
  9581. const mgroup *group = (const mgroup*)method->group;
  9582. if (d->top != d->stack)
  9583. d->stack->end_ofs = 0;
  9584. group->jit_code(closure, method->code_base.ptr, &dummy, 0, NULL);
  9585. } else
  9586. #endif
  9587. {
  9588. const uint32_t *p = d->pc;
  9589. d->stack->end_ofs = end;
  9590. /* Check the previous bytecode, but guard against beginning. */
  9591. if (p != method->code_base.ptr) p--;
  9592. if (getop(*p) == OP_CHECKDELIM) {
  9593. /* Rewind from OP_TAG* to OP_CHECKDELIM. */
  9594. UPB_ASSERT(getop(*d->pc) == OP_TAG1 ||
  9595. getop(*d->pc) == OP_TAG2 ||
  9596. getop(*d->pc) == OP_TAGN ||
  9597. getop(*d->pc) == OP_DISPATCH);
  9598. d->pc = p;
  9599. }
  9600. upb_pbdecoder_decode(closure, handler_data, &dummy, 0, NULL);
  9601. }
  9602. if (d->call_len != 0) {
  9603. seterr(d, "Unexpected EOF inside submessage or group");
  9604. return false;
  9605. }
  9606. return true;
  9607. }
  9608. size_t upb_pbdecoder_decode(void *decoder, const void *group, const char *buf,
  9609. size_t size, const upb_bufhandle *handle) {
  9610. int32_t result = upb_pbdecoder_resume(decoder, NULL, buf, size, handle);
  9611. if (result == DECODE_ENDGROUP) goto_endmsg(decoder);
  9612. CHECK_RETURN(result);
  9613. return run_decoder_vm(decoder, group, handle);
  9614. }
  9615. /* Public API *****************************************************************/
  9616. void upb_pbdecoder_reset(upb_pbdecoder *d) {
  9617. d->top = d->stack;
  9618. d->top->groupnum = 0;
  9619. d->ptr = d->residual;
  9620. d->buf = d->residual;
  9621. d->end = d->residual;
  9622. d->residual_end = d->residual;
  9623. }
  9624. upb_pbdecoder *upb_pbdecoder_create(upb_env *e, const upb_pbdecodermethod *m,
  9625. upb_sink *sink) {
  9626. const size_t default_max_nesting = 64;
  9627. #ifndef NDEBUG
  9628. size_t size_before = upb_env_bytesallocated(e);
  9629. #endif
  9630. upb_pbdecoder *d = upb_env_malloc(e, sizeof(upb_pbdecoder));
  9631. if (!d) return NULL;
  9632. d->method_ = m;
  9633. d->callstack = upb_env_malloc(e, callstacksize(d, default_max_nesting));
  9634. d->stack = upb_env_malloc(e, stacksize(d, default_max_nesting));
  9635. if (!d->stack || !d->callstack) {
  9636. return NULL;
  9637. }
  9638. d->env = e;
  9639. d->limit = d->stack + default_max_nesting - 1;
  9640. d->stack_size = default_max_nesting;
  9641. d->status = NULL;
  9642. upb_pbdecoder_reset(d);
  9643. upb_bytessink_reset(&d->input_, &m->input_handler_, d);
  9644. UPB_ASSERT(sink);
  9645. if (d->method_->dest_handlers_) {
  9646. if (sink->handlers != d->method_->dest_handlers_)
  9647. return NULL;
  9648. }
  9649. upb_sink_reset(&d->top->sink, sink->handlers, sink->closure);
  9650. /* If this fails, increase the value in decoder.h. */
  9651. UPB_ASSERT_DEBUGVAR(upb_env_bytesallocated(e) - size_before <=
  9652. UPB_PB_DECODER_SIZE);
  9653. return d;
  9654. }
  9655. uint64_t upb_pbdecoder_bytesparsed(const upb_pbdecoder *d) {
  9656. return offset(d);
  9657. }
  9658. const upb_pbdecodermethod *upb_pbdecoder_method(const upb_pbdecoder *d) {
  9659. return d->method_;
  9660. }
  9661. upb_bytessink *upb_pbdecoder_input(upb_pbdecoder *d) {
  9662. return &d->input_;
  9663. }
  9664. size_t upb_pbdecoder_maxnesting(const upb_pbdecoder *d) {
  9665. return d->stack_size;
  9666. }
  9667. bool upb_pbdecoder_setmaxnesting(upb_pbdecoder *d, size_t max) {
  9668. UPB_ASSERT(d->top >= d->stack);
  9669. if (max < (size_t)(d->top - d->stack)) {
  9670. /* Can't set a limit smaller than what we are currently at. */
  9671. return false;
  9672. }
  9673. if (max > d->stack_size) {
  9674. /* Need to reallocate stack and callstack to accommodate. */
  9675. size_t old_size = stacksize(d, d->stack_size);
  9676. size_t new_size = stacksize(d, max);
  9677. void *p = upb_env_realloc(d->env, d->stack, old_size, new_size);
  9678. if (!p) {
  9679. return false;
  9680. }
  9681. d->stack = p;
  9682. old_size = callstacksize(d, d->stack_size);
  9683. new_size = callstacksize(d, max);
  9684. p = upb_env_realloc(d->env, d->callstack, old_size, new_size);
  9685. if (!p) {
  9686. return false;
  9687. }
  9688. d->callstack = p;
  9689. d->stack_size = max;
  9690. }
  9691. d->limit = d->stack + max - 1;
  9692. return true;
  9693. }
  9694. /*
  9695. ** upb::Encoder
  9696. **
  9697. ** Since we are implementing pure handlers (ie. without any out-of-band access
  9698. ** to pre-computed lengths), we have to buffer all submessages before we can
  9699. ** emit even their first byte.
  9700. **
  9701. ** Not knowing the size of submessages also means we can't write a perfect
  9702. ** zero-copy implementation, even with buffering. Lengths are stored as
  9703. ** varints, which means that we don't know how many bytes to reserve for the
  9704. ** length until we know what the length is.
  9705. **
  9706. ** This leaves us with three main choices:
  9707. **
  9708. ** 1. buffer all submessage data in a temporary buffer, then copy it exactly
  9709. ** once into the output buffer.
  9710. **
  9711. ** 2. attempt to buffer data directly into the output buffer, estimating how
  9712. ** many bytes each length will take. When our guesses are wrong, use
  9713. ** memmove() to grow or shrink the allotted space.
  9714. **
  9715. ** 3. buffer directly into the output buffer, allocating a max length
  9716. ** ahead-of-time for each submessage length. If we overallocated, we waste
  9717. ** space, but no memcpy() or memmove() is required. This approach requires
  9718. ** defining a maximum size for submessages and rejecting submessages that
  9719. ** exceed that size.
  9720. **
  9721. ** (2) and (3) have the potential to have better performance, but they are more
  9722. ** complicated and subtle to implement:
  9723. **
  9724. ** (3) requires making an arbitrary choice of the maximum message size; it
  9725. ** wastes space when submessages are shorter than this and fails
  9726. ** completely when they are longer. This makes it more finicky and
  9727. ** requires configuration based on the input. It also makes it impossible
  9728. ** to perfectly match the output of reference encoders that always use the
  9729. ** optimal amount of space for each length.
  9730. **
  9731. ** (2) requires guessing the the size upfront, and if multiple lengths are
  9732. ** guessed wrong the minimum required number of memmove() operations may
  9733. ** be complicated to compute correctly. Implemented properly, it may have
  9734. ** a useful amortized or average cost, but more investigation is required
  9735. ** to determine this and what the optimal algorithm is to achieve it.
  9736. **
  9737. ** (1) makes you always pay for exactly one copy, but its implementation is
  9738. ** the simplest and its performance is predictable.
  9739. **
  9740. ** So for now, we implement (1) only. If we wish to optimize later, we should
  9741. ** be able to do it without affecting users.
  9742. **
  9743. ** The strategy is to buffer the segments of data that do *not* depend on
  9744. ** unknown lengths in one buffer, and keep a separate buffer of segment pointers
  9745. ** and lengths. When the top-level submessage ends, we can go beginning to end,
  9746. ** alternating the writing of lengths with memcpy() of the rest of the data.
  9747. ** At the top level though, no buffering is required.
  9748. */
  9749. /* The output buffer is divided into segments; a segment is a string of data
  9750. * that is "ready to go" -- it does not need any varint lengths inserted into
  9751. * the middle. The seams between segments are where varints will be inserted
  9752. * once they are known.
  9753. *
  9754. * We also use the concept of a "run", which is a range of encoded bytes that
  9755. * occur at a single submessage level. Every segment contains one or more runs.
  9756. *
  9757. * A segment can span messages. Consider:
  9758. *
  9759. * .--Submessage lengths---------.
  9760. * | | |
  9761. * | V V
  9762. * V | |--------------- | |-----------------
  9763. * Submessages: | |-----------------------------------------------
  9764. * Top-level msg: ------------------------------------------------------------
  9765. *
  9766. * Segments: ----- ------------------- -----------------
  9767. * Runs: *---- *--------------*--- *----------------
  9768. * (* marks the start)
  9769. *
  9770. * Note that the top-level menssage is not in any segment because it does not
  9771. * have any length preceding it.
  9772. *
  9773. * A segment is only interrupted when another length needs to be inserted. So
  9774. * observe how the second segment spans both the inner submessage and part of
  9775. * the next enclosing message. */
  9776. typedef struct {
  9777. uint32_t msglen; /* The length to varint-encode before this segment. */
  9778. uint32_t seglen; /* Length of the segment. */
  9779. } upb_pb_encoder_segment;
  9780. struct upb_pb_encoder {
  9781. upb_env *env;
  9782. /* Our input and output. */
  9783. upb_sink input_;
  9784. upb_bytessink *output_;
  9785. /* The "subclosure" -- used as the inner closure as part of the bytessink
  9786. * protocol. */
  9787. void *subc;
  9788. /* The output buffer and limit, and our current write position. "buf"
  9789. * initially points to "initbuf", but is dynamically allocated if we need to
  9790. * grow beyond the initial size. */
  9791. char *buf, *ptr, *limit;
  9792. /* The beginning of the current run, or undefined if we are at the top
  9793. * level. */
  9794. char *runbegin;
  9795. /* The list of segments we are accumulating. */
  9796. upb_pb_encoder_segment *segbuf, *segptr, *seglimit;
  9797. /* The stack of enclosing submessages. Each entry in the stack points to the
  9798. * segment where this submessage's length is being accumulated. */
  9799. int *stack, *top, *stacklimit;
  9800. /* Depth of startmsg/endmsg calls. */
  9801. int depth;
  9802. };
  9803. /* low-level buffering ********************************************************/
  9804. /* Low-level functions for interacting with the output buffer. */
  9805. /* TODO(haberman): handle pushback */
  9806. static void putbuf(upb_pb_encoder *e, const char *buf, size_t len) {
  9807. size_t n = upb_bytessink_putbuf(e->output_, e->subc, buf, len, NULL);
  9808. UPB_ASSERT(n == len);
  9809. }
  9810. static upb_pb_encoder_segment *top(upb_pb_encoder *e) {
  9811. return &e->segbuf[*e->top];
  9812. }
  9813. /* Call to ensure that at least "bytes" bytes are available for writing at
  9814. * e->ptr. Returns false if the bytes could not be allocated. */
  9815. static bool reserve(upb_pb_encoder *e, size_t bytes) {
  9816. if ((size_t)(e->limit - e->ptr) < bytes) {
  9817. /* Grow buffer. */
  9818. char *new_buf;
  9819. size_t needed = bytes + (e->ptr - e->buf);
  9820. size_t old_size = e->limit - e->buf;
  9821. size_t new_size = old_size;
  9822. while (new_size < needed) {
  9823. new_size *= 2;
  9824. }
  9825. new_buf = upb_env_realloc(e->env, e->buf, old_size, new_size);
  9826. if (new_buf == NULL) {
  9827. return false;
  9828. }
  9829. e->ptr = new_buf + (e->ptr - e->buf);
  9830. e->runbegin = new_buf + (e->runbegin - e->buf);
  9831. e->limit = new_buf + new_size;
  9832. e->buf = new_buf;
  9833. }
  9834. return true;
  9835. }
  9836. /* Call when "bytes" bytes have been writte at e->ptr. The caller *must* have
  9837. * previously called reserve() with at least this many bytes. */
  9838. static void encoder_advance(upb_pb_encoder *e, size_t bytes) {
  9839. UPB_ASSERT((size_t)(e->limit - e->ptr) >= bytes);
  9840. e->ptr += bytes;
  9841. }
  9842. /* Call when all of the bytes for a handler have been written. Flushes the
  9843. * bytes if possible and necessary, returning false if this failed. */
  9844. static bool commit(upb_pb_encoder *e) {
  9845. if (!e->top) {
  9846. /* We aren't inside a delimited region. Flush our accumulated bytes to
  9847. * the output.
  9848. *
  9849. * TODO(haberman): in the future we may want to delay flushing for
  9850. * efficiency reasons. */
  9851. putbuf(e, e->buf, e->ptr - e->buf);
  9852. e->ptr = e->buf;
  9853. }
  9854. return true;
  9855. }
  9856. /* Writes the given bytes to the buffer, handling reserve/advance. */
  9857. static bool encode_bytes(upb_pb_encoder *e, const void *data, size_t len) {
  9858. if (!reserve(e, len)) {
  9859. return false;
  9860. }
  9861. memcpy(e->ptr, data, len);
  9862. encoder_advance(e, len);
  9863. return true;
  9864. }
  9865. /* Finish the current run by adding the run totals to the segment and message
  9866. * length. */
  9867. static void accumulate(upb_pb_encoder *e) {
  9868. size_t run_len;
  9869. UPB_ASSERT(e->ptr >= e->runbegin);
  9870. run_len = e->ptr - e->runbegin;
  9871. e->segptr->seglen += run_len;
  9872. top(e)->msglen += run_len;
  9873. e->runbegin = e->ptr;
  9874. }
  9875. /* Call to indicate the start of delimited region for which the full length is
  9876. * not yet known. All data will be buffered until the length is known.
  9877. * Delimited regions may be nested; their lengths will all be tracked properly. */
  9878. static bool start_delim(upb_pb_encoder *e) {
  9879. if (e->top) {
  9880. /* We are already buffering, advance to the next segment and push it on the
  9881. * stack. */
  9882. accumulate(e);
  9883. if (++e->top == e->stacklimit) {
  9884. /* TODO(haberman): grow stack? */
  9885. return false;
  9886. }
  9887. if (++e->segptr == e->seglimit) {
  9888. /* Grow segment buffer. */
  9889. size_t old_size =
  9890. (e->seglimit - e->segbuf) * sizeof(upb_pb_encoder_segment);
  9891. size_t new_size = old_size * 2;
  9892. upb_pb_encoder_segment *new_buf =
  9893. upb_env_realloc(e->env, e->segbuf, old_size, new_size);
  9894. if (new_buf == NULL) {
  9895. return false;
  9896. }
  9897. e->segptr = new_buf + (e->segptr - e->segbuf);
  9898. e->seglimit = new_buf + (new_size / sizeof(upb_pb_encoder_segment));
  9899. e->segbuf = new_buf;
  9900. }
  9901. } else {
  9902. /* We were previously at the top level, start buffering. */
  9903. e->segptr = e->segbuf;
  9904. e->top = e->stack;
  9905. e->runbegin = e->ptr;
  9906. }
  9907. *e->top = e->segptr - e->segbuf;
  9908. e->segptr->seglen = 0;
  9909. e->segptr->msglen = 0;
  9910. return true;
  9911. }
  9912. /* Call to indicate the end of a delimited region. We now know the length of
  9913. * the delimited region. If we are not nested inside any other delimited
  9914. * regions, we can now emit all of the buffered data we accumulated. */
  9915. static bool end_delim(upb_pb_encoder *e) {
  9916. size_t msglen;
  9917. accumulate(e);
  9918. msglen = top(e)->msglen;
  9919. if (e->top == e->stack) {
  9920. /* All lengths are now available, emit all buffered data. */
  9921. char buf[UPB_PB_VARINT_MAX_LEN];
  9922. upb_pb_encoder_segment *s;
  9923. const char *ptr = e->buf;
  9924. for (s = e->segbuf; s <= e->segptr; s++) {
  9925. size_t lenbytes = upb_vencode64(s->msglen, buf);
  9926. putbuf(e, buf, lenbytes);
  9927. putbuf(e, ptr, s->seglen);
  9928. ptr += s->seglen;
  9929. }
  9930. e->ptr = e->buf;
  9931. e->top = NULL;
  9932. } else {
  9933. /* Need to keep buffering; propagate length info into enclosing
  9934. * submessages. */
  9935. --e->top;
  9936. top(e)->msglen += msglen + upb_varint_size(msglen);
  9937. }
  9938. return true;
  9939. }
  9940. /* tag_t **********************************************************************/
  9941. /* A precomputed (pre-encoded) tag and length. */
  9942. typedef struct {
  9943. uint8_t bytes;
  9944. char tag[7];
  9945. } tag_t;
  9946. /* Allocates a new tag for this field, and sets it in these handlerattr. */
  9947. static void new_tag(upb_handlers *h, const upb_fielddef *f, upb_wiretype_t wt,
  9948. upb_handlerattr *attr) {
  9949. uint32_t n = upb_fielddef_number(f);
  9950. tag_t *tag = upb_gmalloc(sizeof(tag_t));
  9951. tag->bytes = upb_vencode64((n << 3) | wt, tag->tag);
  9952. upb_handlerattr_init(attr);
  9953. upb_handlerattr_sethandlerdata(attr, tag);
  9954. upb_handlers_addcleanup(h, tag, upb_gfree);
  9955. }
  9956. static bool encode_tag(upb_pb_encoder *e, const tag_t *tag) {
  9957. return encode_bytes(e, tag->tag, tag->bytes);
  9958. }
  9959. /* encoding of wire types *****************************************************/
  9960. static bool encode_fixed64(upb_pb_encoder *e, uint64_t val) {
  9961. /* TODO(haberman): byte-swap for big endian. */
  9962. return encode_bytes(e, &val, sizeof(uint64_t));
  9963. }
  9964. static bool encode_fixed32(upb_pb_encoder *e, uint32_t val) {
  9965. /* TODO(haberman): byte-swap for big endian. */
  9966. return encode_bytes(e, &val, sizeof(uint32_t));
  9967. }
  9968. static bool encode_varint(upb_pb_encoder *e, uint64_t val) {
  9969. if (!reserve(e, UPB_PB_VARINT_MAX_LEN)) {
  9970. return false;
  9971. }
  9972. encoder_advance(e, upb_vencode64(val, e->ptr));
  9973. return true;
  9974. }
  9975. static uint64_t dbl2uint64(double d) {
  9976. uint64_t ret;
  9977. memcpy(&ret, &d, sizeof(uint64_t));
  9978. return ret;
  9979. }
  9980. static uint32_t flt2uint32(float d) {
  9981. uint32_t ret;
  9982. memcpy(&ret, &d, sizeof(uint32_t));
  9983. return ret;
  9984. }
  9985. /* encoding of proto types ****************************************************/
  9986. static bool startmsg(void *c, const void *hd) {
  9987. upb_pb_encoder *e = c;
  9988. UPB_UNUSED(hd);
  9989. if (e->depth++ == 0) {
  9990. upb_bytessink_start(e->output_, 0, &e->subc);
  9991. }
  9992. return true;
  9993. }
  9994. static bool endmsg(void *c, const void *hd, upb_status *status) {
  9995. upb_pb_encoder *e = c;
  9996. UPB_UNUSED(hd);
  9997. UPB_UNUSED(status);
  9998. if (--e->depth == 0) {
  9999. upb_bytessink_end(e->output_);
  10000. }
  10001. return true;
  10002. }
  10003. static void *encode_startdelimfield(void *c, const void *hd) {
  10004. bool ok = encode_tag(c, hd) && commit(c) && start_delim(c);
  10005. return ok ? c : UPB_BREAK;
  10006. }
  10007. static bool encode_unknown(void *c, const void *hd, const char *buf,
  10008. size_t len) {
  10009. UPB_UNUSED(hd);
  10010. return encode_bytes(c, buf, len) && commit(c);
  10011. }
  10012. static bool encode_enddelimfield(void *c, const void *hd) {
  10013. UPB_UNUSED(hd);
  10014. return end_delim(c);
  10015. }
  10016. static void *encode_startgroup(void *c, const void *hd) {
  10017. return (encode_tag(c, hd) && commit(c)) ? c : UPB_BREAK;
  10018. }
  10019. static bool encode_endgroup(void *c, const void *hd) {
  10020. return encode_tag(c, hd) && commit(c);
  10021. }
  10022. static void *encode_startstr(void *c, const void *hd, size_t size_hint) {
  10023. UPB_UNUSED(size_hint);
  10024. return encode_startdelimfield(c, hd);
  10025. }
  10026. static size_t encode_strbuf(void *c, const void *hd, const char *buf,
  10027. size_t len, const upb_bufhandle *h) {
  10028. UPB_UNUSED(hd);
  10029. UPB_UNUSED(h);
  10030. return encode_bytes(c, buf, len) ? len : 0;
  10031. }
  10032. #define T(type, ctype, convert, encode) \
  10033. static bool encode_scalar_##type(void *e, const void *hd, ctype val) { \
  10034. return encode_tag(e, hd) && encode(e, (convert)(val)) && commit(e); \
  10035. } \
  10036. static bool encode_packed_##type(void *e, const void *hd, ctype val) { \
  10037. UPB_UNUSED(hd); \
  10038. return encode(e, (convert)(val)); \
  10039. }
  10040. T(double, double, dbl2uint64, encode_fixed64)
  10041. T(float, float, flt2uint32, encode_fixed32)
  10042. T(int64, int64_t, uint64_t, encode_varint)
  10043. T(int32, int32_t, int64_t, encode_varint)
  10044. T(fixed64, uint64_t, uint64_t, encode_fixed64)
  10045. T(fixed32, uint32_t, uint32_t, encode_fixed32)
  10046. T(bool, bool, bool, encode_varint)
  10047. T(uint32, uint32_t, uint32_t, encode_varint)
  10048. T(uint64, uint64_t, uint64_t, encode_varint)
  10049. T(enum, int32_t, uint32_t, encode_varint)
  10050. T(sfixed32, int32_t, uint32_t, encode_fixed32)
  10051. T(sfixed64, int64_t, uint64_t, encode_fixed64)
  10052. T(sint32, int32_t, upb_zzenc_32, encode_varint)
  10053. T(sint64, int64_t, upb_zzenc_64, encode_varint)
  10054. #undef T
  10055. /* code to build the handlers *************************************************/
  10056. static void newhandlers_callback(const void *closure, upb_handlers *h) {
  10057. const upb_msgdef *m;
  10058. upb_msg_field_iter i;
  10059. UPB_UNUSED(closure);
  10060. upb_handlers_setstartmsg(h, startmsg, NULL);
  10061. upb_handlers_setendmsg(h, endmsg, NULL);
  10062. upb_handlers_setunknown(h, encode_unknown, NULL);
  10063. m = upb_handlers_msgdef(h);
  10064. for(upb_msg_field_begin(&i, m);
  10065. !upb_msg_field_done(&i);
  10066. upb_msg_field_next(&i)) {
  10067. const upb_fielddef *f = upb_msg_iter_field(&i);
  10068. bool packed = upb_fielddef_isseq(f) && upb_fielddef_isprimitive(f) &&
  10069. upb_fielddef_packed(f);
  10070. upb_handlerattr attr;
  10071. upb_wiretype_t wt =
  10072. packed ? UPB_WIRE_TYPE_DELIMITED
  10073. : upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  10074. /* Pre-encode the tag for this field. */
  10075. new_tag(h, f, wt, &attr);
  10076. if (packed) {
  10077. upb_handlers_setstartseq(h, f, encode_startdelimfield, &attr);
  10078. upb_handlers_setendseq(h, f, encode_enddelimfield, &attr);
  10079. }
  10080. #define T(upper, lower, upbtype) \
  10081. case UPB_DESCRIPTOR_TYPE_##upper: \
  10082. if (packed) { \
  10083. upb_handlers_set##upbtype(h, f, encode_packed_##lower, &attr); \
  10084. } else { \
  10085. upb_handlers_set##upbtype(h, f, encode_scalar_##lower, &attr); \
  10086. } \
  10087. break;
  10088. switch (upb_fielddef_descriptortype(f)) {
  10089. T(DOUBLE, double, double);
  10090. T(FLOAT, float, float);
  10091. T(INT64, int64, int64);
  10092. T(INT32, int32, int32);
  10093. T(FIXED64, fixed64, uint64);
  10094. T(FIXED32, fixed32, uint32);
  10095. T(BOOL, bool, bool);
  10096. T(UINT32, uint32, uint32);
  10097. T(UINT64, uint64, uint64);
  10098. T(ENUM, enum, int32);
  10099. T(SFIXED32, sfixed32, int32);
  10100. T(SFIXED64, sfixed64, int64);
  10101. T(SINT32, sint32, int32);
  10102. T(SINT64, sint64, int64);
  10103. case UPB_DESCRIPTOR_TYPE_STRING:
  10104. case UPB_DESCRIPTOR_TYPE_BYTES:
  10105. upb_handlers_setstartstr(h, f, encode_startstr, &attr);
  10106. upb_handlers_setendstr(h, f, encode_enddelimfield, &attr);
  10107. upb_handlers_setstring(h, f, encode_strbuf, &attr);
  10108. break;
  10109. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  10110. upb_handlers_setstartsubmsg(h, f, encode_startdelimfield, &attr);
  10111. upb_handlers_setendsubmsg(h, f, encode_enddelimfield, &attr);
  10112. break;
  10113. case UPB_DESCRIPTOR_TYPE_GROUP: {
  10114. /* Endgroup takes a different tag (wire_type = END_GROUP). */
  10115. upb_handlerattr attr2;
  10116. new_tag(h, f, UPB_WIRE_TYPE_END_GROUP, &attr2);
  10117. upb_handlers_setstartsubmsg(h, f, encode_startgroup, &attr);
  10118. upb_handlers_setendsubmsg(h, f, encode_endgroup, &attr2);
  10119. upb_handlerattr_uninit(&attr2);
  10120. break;
  10121. }
  10122. }
  10123. #undef T
  10124. upb_handlerattr_uninit(&attr);
  10125. }
  10126. }
  10127. void upb_pb_encoder_reset(upb_pb_encoder *e) {
  10128. e->segptr = NULL;
  10129. e->top = NULL;
  10130. e->depth = 0;
  10131. }
  10132. /* public API *****************************************************************/
  10133. const upb_handlers *upb_pb_encoder_newhandlers(const upb_msgdef *m,
  10134. const void *owner) {
  10135. return upb_handlers_newfrozen(m, owner, newhandlers_callback, NULL);
  10136. }
  10137. upb_pb_encoder *upb_pb_encoder_create(upb_env *env, const upb_handlers *h,
  10138. upb_bytessink *output) {
  10139. const size_t initial_bufsize = 256;
  10140. const size_t initial_segbufsize = 16;
  10141. /* TODO(haberman): make this configurable. */
  10142. const size_t stack_size = 64;
  10143. #ifndef NDEBUG
  10144. const size_t size_before = upb_env_bytesallocated(env);
  10145. #endif
  10146. upb_pb_encoder *e = upb_env_malloc(env, sizeof(upb_pb_encoder));
  10147. if (!e) return NULL;
  10148. e->buf = upb_env_malloc(env, initial_bufsize);
  10149. e->segbuf = upb_env_malloc(env, initial_segbufsize * sizeof(*e->segbuf));
  10150. e->stack = upb_env_malloc(env, stack_size * sizeof(*e->stack));
  10151. if (!e->buf || !e->segbuf || !e->stack) {
  10152. return NULL;
  10153. }
  10154. e->limit = e->buf + initial_bufsize;
  10155. e->seglimit = e->segbuf + initial_segbufsize;
  10156. e->stacklimit = e->stack + stack_size;
  10157. upb_pb_encoder_reset(e);
  10158. upb_sink_reset(&e->input_, h, e);
  10159. e->env = env;
  10160. e->output_ = output;
  10161. e->subc = output->closure;
  10162. e->ptr = e->buf;
  10163. /* If this fails, increase the value in encoder.h. */
  10164. UPB_ASSERT_DEBUGVAR(upb_env_bytesallocated(env) - size_before <=
  10165. UPB_PB_ENCODER_SIZE);
  10166. return e;
  10167. }
  10168. upb_sink *upb_pb_encoder_input(upb_pb_encoder *e) { return &e->input_; }
  10169. upb_filedef **upb_loaddescriptor(const char *buf, size_t n, const void *owner,
  10170. upb_status *status) {
  10171. /* Create handlers. */
  10172. const upb_pbdecodermethod *decoder_m;
  10173. const upb_handlers *reader_h = upb_descreader_newhandlers(&reader_h);
  10174. upb_env env;
  10175. upb_pbdecodermethodopts opts;
  10176. upb_pbdecoder *decoder;
  10177. upb_descreader *reader;
  10178. bool ok;
  10179. size_t i;
  10180. upb_filedef **ret = NULL;
  10181. upb_pbdecodermethodopts_init(&opts, reader_h);
  10182. decoder_m = upb_pbdecodermethod_new(&opts, &decoder_m);
  10183. upb_env_init(&env);
  10184. upb_env_reporterrorsto(&env, status);
  10185. reader = upb_descreader_create(&env, reader_h);
  10186. decoder = upb_pbdecoder_create(&env, decoder_m, upb_descreader_input(reader));
  10187. /* Push input data. */
  10188. ok = upb_bufsrc_putbuf(buf, n, upb_pbdecoder_input(decoder));
  10189. if (!ok) {
  10190. goto cleanup;
  10191. }
  10192. ret = upb_gmalloc(sizeof (*ret) * (upb_descreader_filecount(reader) + 1));
  10193. if (!ret) {
  10194. goto cleanup;
  10195. }
  10196. for (i = 0; i < upb_descreader_filecount(reader); i++) {
  10197. ret[i] = upb_descreader_file(reader, i);
  10198. upb_filedef_ref(ret[i], owner);
  10199. }
  10200. ret[i] = NULL;
  10201. cleanup:
  10202. upb_env_uninit(&env);
  10203. upb_handlers_unref(reader_h, &reader_h);
  10204. upb_pbdecodermethod_unref(decoder_m, &decoder_m);
  10205. return ret;
  10206. }
  10207. /*
  10208. * upb::pb::TextPrinter
  10209. *
  10210. * OPT: This is not optimized at all. It uses printf() which parses the format
  10211. * string every time, and it allocates memory for every put.
  10212. */
  10213. #include <ctype.h>
  10214. #include <float.h>
  10215. #include <inttypes.h>
  10216. #include <stdarg.h>
  10217. #include <stdio.h>
  10218. #include <string.h>
  10219. struct upb_textprinter {
  10220. upb_sink input_;
  10221. upb_bytessink *output_;
  10222. int indent_depth_;
  10223. bool single_line_;
  10224. void *subc;
  10225. };
  10226. #define CHECK(x) if ((x) < 0) goto err;
  10227. static const char *shortname(const char *longname) {
  10228. const char *last = strrchr(longname, '.');
  10229. return last ? last + 1 : longname;
  10230. }
  10231. static int indent(upb_textprinter *p) {
  10232. int i;
  10233. if (!p->single_line_)
  10234. for (i = 0; i < p->indent_depth_; i++)
  10235. upb_bytessink_putbuf(p->output_, p->subc, " ", 2, NULL);
  10236. return 0;
  10237. }
  10238. static int endfield(upb_textprinter *p) {
  10239. const char ch = (p->single_line_ ? ' ' : '\n');
  10240. upb_bytessink_putbuf(p->output_, p->subc, &ch, 1, NULL);
  10241. return 0;
  10242. }
  10243. static int putescaped(upb_textprinter *p, const char *buf, size_t len,
  10244. bool preserve_utf8) {
  10245. /* Based on CEscapeInternal() from Google's protobuf release. */
  10246. char dstbuf[4096], *dst = dstbuf, *dstend = dstbuf + sizeof(dstbuf);
  10247. const char *end = buf + len;
  10248. /* I think hex is prettier and more useful, but proto2 uses octal; should
  10249. * investigate whether it can parse hex also. */
  10250. const bool use_hex = false;
  10251. bool last_hex_escape = false; /* true if last output char was \xNN */
  10252. for (; buf < end; buf++) {
  10253. bool is_hex_escape;
  10254. if (dstend - dst < 4) {
  10255. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  10256. dst = dstbuf;
  10257. }
  10258. is_hex_escape = false;
  10259. switch (*buf) {
  10260. case '\n': *(dst++) = '\\'; *(dst++) = 'n'; break;
  10261. case '\r': *(dst++) = '\\'; *(dst++) = 'r'; break;
  10262. case '\t': *(dst++) = '\\'; *(dst++) = 't'; break;
  10263. case '\"': *(dst++) = '\\'; *(dst++) = '\"'; break;
  10264. case '\'': *(dst++) = '\\'; *(dst++) = '\''; break;
  10265. case '\\': *(dst++) = '\\'; *(dst++) = '\\'; break;
  10266. default:
  10267. /* Note that if we emit \xNN and the buf character after that is a hex
  10268. * digit then that digit must be escaped too to prevent it being
  10269. * interpreted as part of the character code by C. */
  10270. if ((!preserve_utf8 || (uint8_t)*buf < 0x80) &&
  10271. (!isprint(*buf) || (last_hex_escape && isxdigit(*buf)))) {
  10272. sprintf(dst, (use_hex ? "\\x%02x" : "\\%03o"), (uint8_t)*buf);
  10273. is_hex_escape = use_hex;
  10274. dst += 4;
  10275. } else {
  10276. *(dst++) = *buf; break;
  10277. }
  10278. }
  10279. last_hex_escape = is_hex_escape;
  10280. }
  10281. /* Flush remaining data. */
  10282. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  10283. return 0;
  10284. }
  10285. bool putf(upb_textprinter *p, const char *fmt, ...) {
  10286. va_list args;
  10287. va_list args_copy;
  10288. char *str;
  10289. int written;
  10290. int len;
  10291. bool ok;
  10292. va_start(args, fmt);
  10293. /* Run once to get the length of the string. */
  10294. _upb_va_copy(args_copy, args);
  10295. len = _upb_vsnprintf(NULL, 0, fmt, args_copy);
  10296. va_end(args_copy);
  10297. /* + 1 for NULL terminator (vsprintf() requires it even if we don't). */
  10298. str = upb_gmalloc(len + 1);
  10299. if (!str) return false;
  10300. written = vsprintf(str, fmt, args);
  10301. va_end(args);
  10302. UPB_ASSERT(written == len);
  10303. ok = upb_bytessink_putbuf(p->output_, p->subc, str, len, NULL);
  10304. upb_gfree(str);
  10305. return ok;
  10306. }
  10307. /* handlers *******************************************************************/
  10308. static bool textprinter_startmsg(void *c, const void *hd) {
  10309. upb_textprinter *p = c;
  10310. UPB_UNUSED(hd);
  10311. if (p->indent_depth_ == 0) {
  10312. upb_bytessink_start(p->output_, 0, &p->subc);
  10313. }
  10314. return true;
  10315. }
  10316. static bool textprinter_endmsg(void *c, const void *hd, upb_status *s) {
  10317. upb_textprinter *p = c;
  10318. UPB_UNUSED(hd);
  10319. UPB_UNUSED(s);
  10320. if (p->indent_depth_ == 0) {
  10321. upb_bytessink_end(p->output_);
  10322. }
  10323. return true;
  10324. }
  10325. #define TYPE(name, ctype, fmt) \
  10326. static bool textprinter_put ## name(void *closure, const void *handler_data, \
  10327. ctype val) { \
  10328. upb_textprinter *p = closure; \
  10329. const upb_fielddef *f = handler_data; \
  10330. CHECK(indent(p)); \
  10331. putf(p, "%s: " fmt, upb_fielddef_name(f), val); \
  10332. CHECK(endfield(p)); \
  10333. return true; \
  10334. err: \
  10335. return false; \
  10336. }
  10337. static bool textprinter_putbool(void *closure, const void *handler_data,
  10338. bool val) {
  10339. upb_textprinter *p = closure;
  10340. const upb_fielddef *f = handler_data;
  10341. CHECK(indent(p));
  10342. putf(p, "%s: %s", upb_fielddef_name(f), val ? "true" : "false");
  10343. CHECK(endfield(p));
  10344. return true;
  10345. err:
  10346. return false;
  10347. }
  10348. #define STRINGIFY_HELPER(x) #x
  10349. #define STRINGIFY_MACROVAL(x) STRINGIFY_HELPER(x)
  10350. TYPE(int32, int32_t, "%" PRId32)
  10351. TYPE(int64, int64_t, "%" PRId64)
  10352. TYPE(uint32, uint32_t, "%" PRIu32)
  10353. TYPE(uint64, uint64_t, "%" PRIu64)
  10354. TYPE(float, float, "%." STRINGIFY_MACROVAL(FLT_DIG) "g")
  10355. TYPE(double, double, "%." STRINGIFY_MACROVAL(DBL_DIG) "g")
  10356. #undef TYPE
  10357. /* Output a symbolic value from the enum if found, else just print as int32. */
  10358. static bool textprinter_putenum(void *closure, const void *handler_data,
  10359. int32_t val) {
  10360. upb_textprinter *p = closure;
  10361. const upb_fielddef *f = handler_data;
  10362. const upb_enumdef *enum_def = upb_downcast_enumdef(upb_fielddef_subdef(f));
  10363. const char *label = upb_enumdef_iton(enum_def, val);
  10364. if (label) {
  10365. indent(p);
  10366. putf(p, "%s: %s", upb_fielddef_name(f), label);
  10367. endfield(p);
  10368. } else {
  10369. if (!textprinter_putint32(closure, handler_data, val))
  10370. return false;
  10371. }
  10372. return true;
  10373. }
  10374. static void *textprinter_startstr(void *closure, const void *handler_data,
  10375. size_t size_hint) {
  10376. upb_textprinter *p = closure;
  10377. const upb_fielddef *f = handler_data;
  10378. UPB_UNUSED(size_hint);
  10379. indent(p);
  10380. putf(p, "%s: \"", upb_fielddef_name(f));
  10381. return p;
  10382. }
  10383. static bool textprinter_endstr(void *closure, const void *handler_data) {
  10384. upb_textprinter *p = closure;
  10385. UPB_UNUSED(handler_data);
  10386. putf(p, "\"");
  10387. endfield(p);
  10388. return true;
  10389. }
  10390. static size_t textprinter_putstr(void *closure, const void *hd, const char *buf,
  10391. size_t len, const upb_bufhandle *handle) {
  10392. upb_textprinter *p = closure;
  10393. const upb_fielddef *f = hd;
  10394. UPB_UNUSED(handle);
  10395. CHECK(putescaped(p, buf, len, upb_fielddef_type(f) == UPB_TYPE_STRING));
  10396. return len;
  10397. err:
  10398. return 0;
  10399. }
  10400. static void *textprinter_startsubmsg(void *closure, const void *handler_data) {
  10401. upb_textprinter *p = closure;
  10402. const char *name = handler_data;
  10403. CHECK(indent(p));
  10404. putf(p, "%s {%c", name, p->single_line_ ? ' ' : '\n');
  10405. p->indent_depth_++;
  10406. return p;
  10407. err:
  10408. return UPB_BREAK;
  10409. }
  10410. static bool textprinter_endsubmsg(void *closure, const void *handler_data) {
  10411. upb_textprinter *p = closure;
  10412. UPB_UNUSED(handler_data);
  10413. p->indent_depth_--;
  10414. CHECK(indent(p));
  10415. upb_bytessink_putbuf(p->output_, p->subc, "}", 1, NULL);
  10416. CHECK(endfield(p));
  10417. return true;
  10418. err:
  10419. return false;
  10420. }
  10421. static void onmreg(const void *c, upb_handlers *h) {
  10422. const upb_msgdef *m = upb_handlers_msgdef(h);
  10423. upb_msg_field_iter i;
  10424. UPB_UNUSED(c);
  10425. upb_handlers_setstartmsg(h, textprinter_startmsg, NULL);
  10426. upb_handlers_setendmsg(h, textprinter_endmsg, NULL);
  10427. for(upb_msg_field_begin(&i, m);
  10428. !upb_msg_field_done(&i);
  10429. upb_msg_field_next(&i)) {
  10430. upb_fielddef *f = upb_msg_iter_field(&i);
  10431. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  10432. upb_handlerattr_sethandlerdata(&attr, f);
  10433. switch (upb_fielddef_type(f)) {
  10434. case UPB_TYPE_INT32:
  10435. upb_handlers_setint32(h, f, textprinter_putint32, &attr);
  10436. break;
  10437. case UPB_TYPE_INT64:
  10438. upb_handlers_setint64(h, f, textprinter_putint64, &attr);
  10439. break;
  10440. case UPB_TYPE_UINT32:
  10441. upb_handlers_setuint32(h, f, textprinter_putuint32, &attr);
  10442. break;
  10443. case UPB_TYPE_UINT64:
  10444. upb_handlers_setuint64(h, f, textprinter_putuint64, &attr);
  10445. break;
  10446. case UPB_TYPE_FLOAT:
  10447. upb_handlers_setfloat(h, f, textprinter_putfloat, &attr);
  10448. break;
  10449. case UPB_TYPE_DOUBLE:
  10450. upb_handlers_setdouble(h, f, textprinter_putdouble, &attr);
  10451. break;
  10452. case UPB_TYPE_BOOL:
  10453. upb_handlers_setbool(h, f, textprinter_putbool, &attr);
  10454. break;
  10455. case UPB_TYPE_STRING:
  10456. case UPB_TYPE_BYTES:
  10457. upb_handlers_setstartstr(h, f, textprinter_startstr, &attr);
  10458. upb_handlers_setstring(h, f, textprinter_putstr, &attr);
  10459. upb_handlers_setendstr(h, f, textprinter_endstr, &attr);
  10460. break;
  10461. case UPB_TYPE_MESSAGE: {
  10462. const char *name =
  10463. upb_fielddef_istagdelim(f)
  10464. ? shortname(upb_msgdef_fullname(upb_fielddef_msgsubdef(f)))
  10465. : upb_fielddef_name(f);
  10466. upb_handlerattr_sethandlerdata(&attr, name);
  10467. upb_handlers_setstartsubmsg(h, f, textprinter_startsubmsg, &attr);
  10468. upb_handlers_setendsubmsg(h, f, textprinter_endsubmsg, &attr);
  10469. break;
  10470. }
  10471. case UPB_TYPE_ENUM:
  10472. upb_handlers_setint32(h, f, textprinter_putenum, &attr);
  10473. break;
  10474. }
  10475. }
  10476. }
  10477. static void textprinter_reset(upb_textprinter *p, bool single_line) {
  10478. p->single_line_ = single_line;
  10479. p->indent_depth_ = 0;
  10480. }
  10481. /* Public API *****************************************************************/
  10482. upb_textprinter *upb_textprinter_create(upb_env *env, const upb_handlers *h,
  10483. upb_bytessink *output) {
  10484. upb_textprinter *p = upb_env_malloc(env, sizeof(upb_textprinter));
  10485. if (!p) return NULL;
  10486. p->output_ = output;
  10487. upb_sink_reset(&p->input_, h, p);
  10488. textprinter_reset(p, false);
  10489. return p;
  10490. }
  10491. const upb_handlers *upb_textprinter_newhandlers(const upb_msgdef *m,
  10492. const void *owner) {
  10493. return upb_handlers_newfrozen(m, owner, &onmreg, NULL);
  10494. }
  10495. upb_sink *upb_textprinter_input(upb_textprinter *p) { return &p->input_; }
  10496. void upb_textprinter_setsingleline(upb_textprinter *p, bool single_line) {
  10497. p->single_line_ = single_line;
  10498. }
  10499. /* Index is descriptor type. */
  10500. const uint8_t upb_pb_native_wire_types[] = {
  10501. UPB_WIRE_TYPE_END_GROUP, /* ENDGROUP */
  10502. UPB_WIRE_TYPE_64BIT, /* DOUBLE */
  10503. UPB_WIRE_TYPE_32BIT, /* FLOAT */
  10504. UPB_WIRE_TYPE_VARINT, /* INT64 */
  10505. UPB_WIRE_TYPE_VARINT, /* UINT64 */
  10506. UPB_WIRE_TYPE_VARINT, /* INT32 */
  10507. UPB_WIRE_TYPE_64BIT, /* FIXED64 */
  10508. UPB_WIRE_TYPE_32BIT, /* FIXED32 */
  10509. UPB_WIRE_TYPE_VARINT, /* BOOL */
  10510. UPB_WIRE_TYPE_DELIMITED, /* STRING */
  10511. UPB_WIRE_TYPE_START_GROUP, /* GROUP */
  10512. UPB_WIRE_TYPE_DELIMITED, /* MESSAGE */
  10513. UPB_WIRE_TYPE_DELIMITED, /* BYTES */
  10514. UPB_WIRE_TYPE_VARINT, /* UINT32 */
  10515. UPB_WIRE_TYPE_VARINT, /* ENUM */
  10516. UPB_WIRE_TYPE_32BIT, /* SFIXED32 */
  10517. UPB_WIRE_TYPE_64BIT, /* SFIXED64 */
  10518. UPB_WIRE_TYPE_VARINT, /* SINT32 */
  10519. UPB_WIRE_TYPE_VARINT, /* SINT64 */
  10520. };
  10521. /* A basic branch-based decoder, uses 32-bit values to get good performance
  10522. * on 32-bit architectures (but performs well on 64-bits also).
  10523. * This scheme comes from the original Google Protobuf implementation
  10524. * (proto2). */
  10525. upb_decoderet upb_vdecode_max8_branch32(upb_decoderet r) {
  10526. upb_decoderet err = {NULL, 0};
  10527. const char *p = r.p;
  10528. uint32_t low = (uint32_t)r.val;
  10529. uint32_t high = 0;
  10530. uint32_t b;
  10531. b = *(p++); low |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  10532. b = *(p++); low |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  10533. b = *(p++); low |= (b & 0x7fU) << 28;
  10534. high = (b & 0x7fU) >> 4; if (!(b & 0x80)) goto done;
  10535. b = *(p++); high |= (b & 0x7fU) << 3; if (!(b & 0x80)) goto done;
  10536. b = *(p++); high |= (b & 0x7fU) << 10; if (!(b & 0x80)) goto done;
  10537. b = *(p++); high |= (b & 0x7fU) << 17; if (!(b & 0x80)) goto done;
  10538. b = *(p++); high |= (b & 0x7fU) << 24; if (!(b & 0x80)) goto done;
  10539. b = *(p++); high |= (b & 0x7fU) << 31; if (!(b & 0x80)) goto done;
  10540. return err;
  10541. done:
  10542. r.val = ((uint64_t)high << 32) | low;
  10543. r.p = p;
  10544. return r;
  10545. }
  10546. /* Like the previous, but uses 64-bit values. */
  10547. upb_decoderet upb_vdecode_max8_branch64(upb_decoderet r) {
  10548. const char *p = r.p;
  10549. uint64_t val = r.val;
  10550. uint64_t b;
  10551. upb_decoderet err = {NULL, 0};
  10552. b = *(p++); val |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  10553. b = *(p++); val |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  10554. b = *(p++); val |= (b & 0x7fU) << 28; if (!(b & 0x80)) goto done;
  10555. b = *(p++); val |= (b & 0x7fU) << 35; if (!(b & 0x80)) goto done;
  10556. b = *(p++); val |= (b & 0x7fU) << 42; if (!(b & 0x80)) goto done;
  10557. b = *(p++); val |= (b & 0x7fU) << 49; if (!(b & 0x80)) goto done;
  10558. b = *(p++); val |= (b & 0x7fU) << 56; if (!(b & 0x80)) goto done;
  10559. b = *(p++); val |= (b & 0x7fU) << 63; if (!(b & 0x80)) goto done;
  10560. return err;
  10561. done:
  10562. r.val = val;
  10563. r.p = p;
  10564. return r;
  10565. }
  10566. #line 1 "upb/json/parser.rl"
  10567. /*
  10568. ** upb::json::Parser (upb_json_parser)
  10569. **
  10570. ** A parser that uses the Ragel State Machine Compiler to generate
  10571. ** the finite automata.
  10572. **
  10573. ** Ragel only natively handles regular languages, but we can manually
  10574. ** program it a bit to handle context-free languages like JSON, by using
  10575. ** the "fcall" and "fret" constructs.
  10576. **
  10577. ** This parser can handle the basics, but needs several things to be fleshed
  10578. ** out:
  10579. **
  10580. ** - handling of unicode escape sequences (including high surrogate pairs).
  10581. ** - properly check and report errors for unknown fields, stack overflow,
  10582. ** improper array nesting (or lack of nesting).
  10583. ** - handling of base64 sequences with padding characters.
  10584. ** - handling of push-back (non-success returns from sink functions).
  10585. ** - handling of keys/escape-sequences/etc that span input buffers.
  10586. */
  10587. #include <errno.h>
  10588. #include <float.h>
  10589. #include <math.h>
  10590. #include <stdint.h>
  10591. #include <stdlib.h>
  10592. #include <string.h>
  10593. #define UPB_JSON_MAX_DEPTH 64
  10594. typedef struct {
  10595. upb_sink sink;
  10596. /* The current message in which we're parsing, and the field whose value we're
  10597. * expecting next. */
  10598. const upb_msgdef *m;
  10599. const upb_fielddef *f;
  10600. /* The table mapping json name to fielddef for this message. */
  10601. upb_strtable *name_table;
  10602. /* We are in a repeated-field context, ready to emit mapentries as
  10603. * submessages. This flag alters the start-of-object (open-brace) behavior to
  10604. * begin a sequence of mapentry messages rather than a single submessage. */
  10605. bool is_map;
  10606. /* We are in a map-entry message context. This flag is set when parsing the
  10607. * value field of a single map entry and indicates to all value-field parsers
  10608. * (subobjects, strings, numbers, and bools) that the map-entry submessage
  10609. * should end as soon as the value is parsed. */
  10610. bool is_mapentry;
  10611. /* If |is_map| or |is_mapentry| is true, |mapfield| refers to the parent
  10612. * message's map field that we're currently parsing. This differs from |f|
  10613. * because |f| is the field in the *current* message (i.e., the map-entry
  10614. * message itself), not the parent's field that leads to this map. */
  10615. const upb_fielddef *mapfield;
  10616. } upb_jsonparser_frame;
  10617. struct upb_json_parser {
  10618. upb_env *env;
  10619. const upb_json_parsermethod *method;
  10620. upb_bytessink input_;
  10621. /* Stack to track the JSON scopes we are in. */
  10622. upb_jsonparser_frame stack[UPB_JSON_MAX_DEPTH];
  10623. upb_jsonparser_frame *top;
  10624. upb_jsonparser_frame *limit;
  10625. upb_status status;
  10626. /* Ragel's internal parsing stack for the parsing state machine. */
  10627. int current_state;
  10628. int parser_stack[UPB_JSON_MAX_DEPTH];
  10629. int parser_top;
  10630. /* The handle for the current buffer. */
  10631. const upb_bufhandle *handle;
  10632. /* Accumulate buffer. See details in parser.rl. */
  10633. const char *accumulated;
  10634. size_t accumulated_len;
  10635. char *accumulate_buf;
  10636. size_t accumulate_buf_size;
  10637. /* Multi-part text data. See details in parser.rl. */
  10638. int multipart_state;
  10639. upb_selector_t string_selector;
  10640. /* Input capture. See details in parser.rl. */
  10641. const char *capture;
  10642. /* Intermediate result of parsing a unicode escape sequence. */
  10643. uint32_t digit;
  10644. };
  10645. struct upb_json_parsermethod {
  10646. upb_refcounted base;
  10647. upb_byteshandler input_handler_;
  10648. /* Mainly for the purposes of refcounting, so all the fielddefs we point
  10649. * to stay alive. */
  10650. const upb_msgdef *msg;
  10651. /* Keys are upb_msgdef*, values are upb_strtable (json_name -> fielddef) */
  10652. upb_inttable name_tables;
  10653. };
  10654. #define PARSER_CHECK_RETURN(x) if (!(x)) return false
  10655. /* Used to signal that a capture has been suspended. */
  10656. static char suspend_capture;
  10657. static upb_selector_t getsel_for_handlertype(upb_json_parser *p,
  10658. upb_handlertype_t type) {
  10659. upb_selector_t sel;
  10660. bool ok = upb_handlers_getselector(p->top->f, type, &sel);
  10661. UPB_ASSERT(ok);
  10662. return sel;
  10663. }
  10664. static upb_selector_t parser_getsel(upb_json_parser *p) {
  10665. return getsel_for_handlertype(
  10666. p, upb_handlers_getprimitivehandlertype(p->top->f));
  10667. }
  10668. static bool check_stack(upb_json_parser *p) {
  10669. if ((p->top + 1) == p->limit) {
  10670. upb_status_seterrmsg(&p->status, "Nesting too deep");
  10671. upb_env_reporterror(p->env, &p->status);
  10672. return false;
  10673. }
  10674. return true;
  10675. }
  10676. static void set_name_table(upb_json_parser *p, upb_jsonparser_frame *frame) {
  10677. upb_value v;
  10678. bool ok = upb_inttable_lookupptr(&p->method->name_tables, frame->m, &v);
  10679. UPB_ASSERT(ok);
  10680. frame->name_table = upb_value_getptr(v);
  10681. }
  10682. /* There are GCC/Clang built-ins for overflow checking which we could start
  10683. * using if there was any performance benefit to it. */
  10684. static bool checked_add(size_t a, size_t b, size_t *c) {
  10685. if (SIZE_MAX - a < b) return false;
  10686. *c = a + b;
  10687. return true;
  10688. }
  10689. static size_t saturating_multiply(size_t a, size_t b) {
  10690. /* size_t is unsigned, so this is defined behavior even on overflow. */
  10691. size_t ret = a * b;
  10692. if (b != 0 && ret / b != a) {
  10693. ret = SIZE_MAX;
  10694. }
  10695. return ret;
  10696. }
  10697. /* Base64 decoding ************************************************************/
  10698. /* TODO(haberman): make this streaming. */
  10699. static const signed char b64table[] = {
  10700. -1, -1, -1, -1, -1, -1, -1, -1,
  10701. -1, -1, -1, -1, -1, -1, -1, -1,
  10702. -1, -1, -1, -1, -1, -1, -1, -1,
  10703. -1, -1, -1, -1, -1, -1, -1, -1,
  10704. -1, -1, -1, -1, -1, -1, -1, -1,
  10705. -1, -1, -1, 62/*+*/, -1, -1, -1, 63/*/ */,
  10706. 52/*0*/, 53/*1*/, 54/*2*/, 55/*3*/, 56/*4*/, 57/*5*/, 58/*6*/, 59/*7*/,
  10707. 60/*8*/, 61/*9*/, -1, -1, -1, -1, -1, -1,
  10708. -1, 0/*A*/, 1/*B*/, 2/*C*/, 3/*D*/, 4/*E*/, 5/*F*/, 6/*G*/,
  10709. 07/*H*/, 8/*I*/, 9/*J*/, 10/*K*/, 11/*L*/, 12/*M*/, 13/*N*/, 14/*O*/,
  10710. 15/*P*/, 16/*Q*/, 17/*R*/, 18/*S*/, 19/*T*/, 20/*U*/, 21/*V*/, 22/*W*/,
  10711. 23/*X*/, 24/*Y*/, 25/*Z*/, -1, -1, -1, -1, -1,
  10712. -1, 26/*a*/, 27/*b*/, 28/*c*/, 29/*d*/, 30/*e*/, 31/*f*/, 32/*g*/,
  10713. 33/*h*/, 34/*i*/, 35/*j*/, 36/*k*/, 37/*l*/, 38/*m*/, 39/*n*/, 40/*o*/,
  10714. 41/*p*/, 42/*q*/, 43/*r*/, 44/*s*/, 45/*t*/, 46/*u*/, 47/*v*/, 48/*w*/,
  10715. 49/*x*/, 50/*y*/, 51/*z*/, -1, -1, -1, -1, -1,
  10716. -1, -1, -1, -1, -1, -1, -1, -1,
  10717. -1, -1, -1, -1, -1, -1, -1, -1,
  10718. -1, -1, -1, -1, -1, -1, -1, -1,
  10719. -1, -1, -1, -1, -1, -1, -1, -1,
  10720. -1, -1, -1, -1, -1, -1, -1, -1,
  10721. -1, -1, -1, -1, -1, -1, -1, -1,
  10722. -1, -1, -1, -1, -1, -1, -1, -1,
  10723. -1, -1, -1, -1, -1, -1, -1, -1,
  10724. -1, -1, -1, -1, -1, -1, -1, -1,
  10725. -1, -1, -1, -1, -1, -1, -1, -1,
  10726. -1, -1, -1, -1, -1, -1, -1, -1,
  10727. -1, -1, -1, -1, -1, -1, -1, -1,
  10728. -1, -1, -1, -1, -1, -1, -1, -1,
  10729. -1, -1, -1, -1, -1, -1, -1, -1,
  10730. -1, -1, -1, -1, -1, -1, -1, -1,
  10731. -1, -1, -1, -1, -1, -1, -1, -1
  10732. };
  10733. /* Returns the table value sign-extended to 32 bits. Knowing that the upper
  10734. * bits will be 1 for unrecognized characters makes it easier to check for
  10735. * this error condition later (see below). */
  10736. int32_t b64lookup(unsigned char ch) { return b64table[ch]; }
  10737. /* Returns true if the given character is not a valid base64 character or
  10738. * padding. */
  10739. bool nonbase64(unsigned char ch) { return b64lookup(ch) == -1 && ch != '='; }
  10740. static bool base64_push(upb_json_parser *p, upb_selector_t sel, const char *ptr,
  10741. size_t len) {
  10742. const char *limit = ptr + len;
  10743. for (; ptr < limit; ptr += 4) {
  10744. uint32_t val;
  10745. char output[3];
  10746. if (limit - ptr < 4) {
  10747. upb_status_seterrf(&p->status,
  10748. "Base64 input for bytes field not a multiple of 4: %s",
  10749. upb_fielddef_name(p->top->f));
  10750. upb_env_reporterror(p->env, &p->status);
  10751. return false;
  10752. }
  10753. val = b64lookup(ptr[0]) << 18 |
  10754. b64lookup(ptr[1]) << 12 |
  10755. b64lookup(ptr[2]) << 6 |
  10756. b64lookup(ptr[3]);
  10757. /* Test the upper bit; returns true if any of the characters returned -1. */
  10758. if (val & 0x80000000) {
  10759. goto otherchar;
  10760. }
  10761. output[0] = val >> 16;
  10762. output[1] = (val >> 8) & 0xff;
  10763. output[2] = val & 0xff;
  10764. upb_sink_putstring(&p->top->sink, sel, output, 3, NULL);
  10765. }
  10766. return true;
  10767. otherchar:
  10768. if (nonbase64(ptr[0]) || nonbase64(ptr[1]) || nonbase64(ptr[2]) ||
  10769. nonbase64(ptr[3]) ) {
  10770. upb_status_seterrf(&p->status,
  10771. "Non-base64 characters in bytes field: %s",
  10772. upb_fielddef_name(p->top->f));
  10773. upb_env_reporterror(p->env, &p->status);
  10774. return false;
  10775. } if (ptr[2] == '=') {
  10776. uint32_t val;
  10777. char output;
  10778. /* Last group contains only two input bytes, one output byte. */
  10779. if (ptr[0] == '=' || ptr[1] == '=' || ptr[3] != '=') {
  10780. goto badpadding;
  10781. }
  10782. val = b64lookup(ptr[0]) << 18 |
  10783. b64lookup(ptr[1]) << 12;
  10784. UPB_ASSERT(!(val & 0x80000000));
  10785. output = val >> 16;
  10786. upb_sink_putstring(&p->top->sink, sel, &output, 1, NULL);
  10787. return true;
  10788. } else {
  10789. uint32_t val;
  10790. char output[2];
  10791. /* Last group contains only three input bytes, two output bytes. */
  10792. if (ptr[0] == '=' || ptr[1] == '=' || ptr[2] == '=') {
  10793. goto badpadding;
  10794. }
  10795. val = b64lookup(ptr[0]) << 18 |
  10796. b64lookup(ptr[1]) << 12 |
  10797. b64lookup(ptr[2]) << 6;
  10798. output[0] = val >> 16;
  10799. output[1] = (val >> 8) & 0xff;
  10800. upb_sink_putstring(&p->top->sink, sel, output, 2, NULL);
  10801. return true;
  10802. }
  10803. badpadding:
  10804. upb_status_seterrf(&p->status,
  10805. "Incorrect base64 padding for field: %s (%.*s)",
  10806. upb_fielddef_name(p->top->f),
  10807. 4, ptr);
  10808. upb_env_reporterror(p->env, &p->status);
  10809. return false;
  10810. }
  10811. /* Accumulate buffer **********************************************************/
  10812. /* Functionality for accumulating a buffer.
  10813. *
  10814. * Some parts of the parser need an entire value as a contiguous string. For
  10815. * example, to look up a member name in a hash table, or to turn a string into
  10816. * a number, the relevant library routines need the input string to be in
  10817. * contiguous memory, even if the value spanned two or more buffers in the
  10818. * input. These routines handle that.
  10819. *
  10820. * In the common case we can just point to the input buffer to get this
  10821. * contiguous string and avoid any actual copy. So we optimistically begin
  10822. * this way. But there are a few cases where we must instead copy into a
  10823. * separate buffer:
  10824. *
  10825. * 1. The string was not contiguous in the input (it spanned buffers).
  10826. *
  10827. * 2. The string included escape sequences that need to be interpreted to get
  10828. * the true value in a contiguous buffer. */
  10829. static void assert_accumulate_empty(upb_json_parser *p) {
  10830. UPB_ASSERT(p->accumulated == NULL);
  10831. UPB_ASSERT(p->accumulated_len == 0);
  10832. }
  10833. static void accumulate_clear(upb_json_parser *p) {
  10834. p->accumulated = NULL;
  10835. p->accumulated_len = 0;
  10836. }
  10837. /* Used internally by accumulate_append(). */
  10838. static bool accumulate_realloc(upb_json_parser *p, size_t need) {
  10839. void *mem;
  10840. size_t old_size = p->accumulate_buf_size;
  10841. size_t new_size = UPB_MAX(old_size, 128);
  10842. while (new_size < need) {
  10843. new_size = saturating_multiply(new_size, 2);
  10844. }
  10845. mem = upb_env_realloc(p->env, p->accumulate_buf, old_size, new_size);
  10846. if (!mem) {
  10847. upb_status_seterrmsg(&p->status, "Out of memory allocating buffer.");
  10848. upb_env_reporterror(p->env, &p->status);
  10849. return false;
  10850. }
  10851. p->accumulate_buf = mem;
  10852. p->accumulate_buf_size = new_size;
  10853. return true;
  10854. }
  10855. /* Logically appends the given data to the append buffer.
  10856. * If "can_alias" is true, we will try to avoid actually copying, but the buffer
  10857. * must be valid until the next accumulate_append() call (if any). */
  10858. static bool accumulate_append(upb_json_parser *p, const char *buf, size_t len,
  10859. bool can_alias) {
  10860. size_t need;
  10861. if (!p->accumulated && can_alias) {
  10862. p->accumulated = buf;
  10863. p->accumulated_len = len;
  10864. return true;
  10865. }
  10866. if (!checked_add(p->accumulated_len, len, &need)) {
  10867. upb_status_seterrmsg(&p->status, "Integer overflow.");
  10868. upb_env_reporterror(p->env, &p->status);
  10869. return false;
  10870. }
  10871. if (need > p->accumulate_buf_size && !accumulate_realloc(p, need)) {
  10872. return false;
  10873. }
  10874. if (p->accumulated != p->accumulate_buf) {
  10875. memcpy(p->accumulate_buf, p->accumulated, p->accumulated_len);
  10876. p->accumulated = p->accumulate_buf;
  10877. }
  10878. memcpy(p->accumulate_buf + p->accumulated_len, buf, len);
  10879. p->accumulated_len += len;
  10880. return true;
  10881. }
  10882. /* Returns a pointer to the data accumulated since the last accumulate_clear()
  10883. * call, and writes the length to *len. This with point either to the input
  10884. * buffer or a temporary accumulate buffer. */
  10885. static const char *accumulate_getptr(upb_json_parser *p, size_t *len) {
  10886. UPB_ASSERT(p->accumulated);
  10887. *len = p->accumulated_len;
  10888. return p->accumulated;
  10889. }
  10890. /* Mult-part text data ********************************************************/
  10891. /* When we have text data in the input, it can often come in multiple segments.
  10892. * For example, there may be some raw string data followed by an escape
  10893. * sequence. The two segments are processed with different logic. Also buffer
  10894. * seams in the input can cause multiple segments.
  10895. *
  10896. * As we see segments, there are two main cases for how we want to process them:
  10897. *
  10898. * 1. we want to push the captured input directly to string handlers.
  10899. *
  10900. * 2. we need to accumulate all the parts into a contiguous buffer for further
  10901. * processing (field name lookup, string->number conversion, etc). */
  10902. /* This is the set of states for p->multipart_state. */
  10903. enum {
  10904. /* We are not currently processing multipart data. */
  10905. MULTIPART_INACTIVE = 0,
  10906. /* We are processing multipart data by accumulating it into a contiguous
  10907. * buffer. */
  10908. MULTIPART_ACCUMULATE = 1,
  10909. /* We are processing multipart data by pushing each part directly to the
  10910. * current string handlers. */
  10911. MULTIPART_PUSHEAGERLY = 2
  10912. };
  10913. /* Start a multi-part text value where we accumulate the data for processing at
  10914. * the end. */
  10915. static void multipart_startaccum(upb_json_parser *p) {
  10916. assert_accumulate_empty(p);
  10917. UPB_ASSERT(p->multipart_state == MULTIPART_INACTIVE);
  10918. p->multipart_state = MULTIPART_ACCUMULATE;
  10919. }
  10920. /* Start a multi-part text value where we immediately push text data to a string
  10921. * value with the given selector. */
  10922. static void multipart_start(upb_json_parser *p, upb_selector_t sel) {
  10923. assert_accumulate_empty(p);
  10924. UPB_ASSERT(p->multipart_state == MULTIPART_INACTIVE);
  10925. p->multipart_state = MULTIPART_PUSHEAGERLY;
  10926. p->string_selector = sel;
  10927. }
  10928. static bool multipart_text(upb_json_parser *p, const char *buf, size_t len,
  10929. bool can_alias) {
  10930. switch (p->multipart_state) {
  10931. case MULTIPART_INACTIVE:
  10932. upb_status_seterrmsg(
  10933. &p->status, "Internal error: unexpected state MULTIPART_INACTIVE");
  10934. upb_env_reporterror(p->env, &p->status);
  10935. return false;
  10936. case MULTIPART_ACCUMULATE:
  10937. if (!accumulate_append(p, buf, len, can_alias)) {
  10938. return false;
  10939. }
  10940. break;
  10941. case MULTIPART_PUSHEAGERLY: {
  10942. const upb_bufhandle *handle = can_alias ? p->handle : NULL;
  10943. upb_sink_putstring(&p->top->sink, p->string_selector, buf, len, handle);
  10944. break;
  10945. }
  10946. }
  10947. return true;
  10948. }
  10949. /* Note: this invalidates the accumulate buffer! Call only after reading its
  10950. * contents. */
  10951. static void multipart_end(upb_json_parser *p) {
  10952. UPB_ASSERT(p->multipart_state != MULTIPART_INACTIVE);
  10953. p->multipart_state = MULTIPART_INACTIVE;
  10954. accumulate_clear(p);
  10955. }
  10956. /* Input capture **************************************************************/
  10957. /* Functionality for capturing a region of the input as text. Gracefully
  10958. * handles the case where a buffer seam occurs in the middle of the captured
  10959. * region. */
  10960. static void capture_begin(upb_json_parser *p, const char *ptr) {
  10961. UPB_ASSERT(p->multipart_state != MULTIPART_INACTIVE);
  10962. UPB_ASSERT(p->capture == NULL);
  10963. p->capture = ptr;
  10964. }
  10965. static bool capture_end(upb_json_parser *p, const char *ptr) {
  10966. UPB_ASSERT(p->capture);
  10967. if (multipart_text(p, p->capture, ptr - p->capture, true)) {
  10968. p->capture = NULL;
  10969. return true;
  10970. } else {
  10971. return false;
  10972. }
  10973. }
  10974. /* This is called at the end of each input buffer (ie. when we have hit a
  10975. * buffer seam). If we are in the middle of capturing the input, this
  10976. * processes the unprocessed capture region. */
  10977. static void capture_suspend(upb_json_parser *p, const char **ptr) {
  10978. if (!p->capture) return;
  10979. if (multipart_text(p, p->capture, *ptr - p->capture, false)) {
  10980. /* We use this as a signal that we were in the middle of capturing, and
  10981. * that capturing should resume at the beginning of the next buffer.
  10982. *
  10983. * We can't use *ptr here, because we have no guarantee that this pointer
  10984. * will be valid when we resume (if the underlying memory is freed, then
  10985. * using the pointer at all, even to compare to NULL, is likely undefined
  10986. * behavior). */
  10987. p->capture = &suspend_capture;
  10988. } else {
  10989. /* Need to back up the pointer to the beginning of the capture, since
  10990. * we were not able to actually preserve it. */
  10991. *ptr = p->capture;
  10992. }
  10993. }
  10994. static void capture_resume(upb_json_parser *p, const char *ptr) {
  10995. if (p->capture) {
  10996. UPB_ASSERT(p->capture == &suspend_capture);
  10997. p->capture = ptr;
  10998. }
  10999. }
  11000. /* Callbacks from the parser **************************************************/
  11001. /* These are the functions called directly from the parser itself.
  11002. * We define these in the same order as their declarations in the parser. */
  11003. static char escape_char(char in) {
  11004. switch (in) {
  11005. case 'r': return '\r';
  11006. case 't': return '\t';
  11007. case 'n': return '\n';
  11008. case 'f': return '\f';
  11009. case 'b': return '\b';
  11010. case '/': return '/';
  11011. case '"': return '"';
  11012. case '\\': return '\\';
  11013. default:
  11014. UPB_ASSERT(0);
  11015. return 'x';
  11016. }
  11017. }
  11018. static bool escape(upb_json_parser *p, const char *ptr) {
  11019. char ch = escape_char(*ptr);
  11020. return multipart_text(p, &ch, 1, false);
  11021. }
  11022. static void start_hex(upb_json_parser *p) {
  11023. p->digit = 0;
  11024. }
  11025. static void hexdigit(upb_json_parser *p, const char *ptr) {
  11026. char ch = *ptr;
  11027. p->digit <<= 4;
  11028. if (ch >= '0' && ch <= '9') {
  11029. p->digit += (ch - '0');
  11030. } else if (ch >= 'a' && ch <= 'f') {
  11031. p->digit += ((ch - 'a') + 10);
  11032. } else {
  11033. UPB_ASSERT(ch >= 'A' && ch <= 'F');
  11034. p->digit += ((ch - 'A') + 10);
  11035. }
  11036. }
  11037. static bool end_hex(upb_json_parser *p) {
  11038. uint32_t codepoint = p->digit;
  11039. /* emit the codepoint as UTF-8. */
  11040. char utf8[3]; /* support \u0000 -- \uFFFF -- need only three bytes. */
  11041. int length = 0;
  11042. if (codepoint <= 0x7F) {
  11043. utf8[0] = codepoint;
  11044. length = 1;
  11045. } else if (codepoint <= 0x07FF) {
  11046. utf8[1] = (codepoint & 0x3F) | 0x80;
  11047. codepoint >>= 6;
  11048. utf8[0] = (codepoint & 0x1F) | 0xC0;
  11049. length = 2;
  11050. } else /* codepoint <= 0xFFFF */ {
  11051. utf8[2] = (codepoint & 0x3F) | 0x80;
  11052. codepoint >>= 6;
  11053. utf8[1] = (codepoint & 0x3F) | 0x80;
  11054. codepoint >>= 6;
  11055. utf8[0] = (codepoint & 0x0F) | 0xE0;
  11056. length = 3;
  11057. }
  11058. /* TODO(haberman): Handle high surrogates: if codepoint is a high surrogate
  11059. * we have to wait for the next escape to get the full code point). */
  11060. return multipart_text(p, utf8, length, false);
  11061. }
  11062. static void start_text(upb_json_parser *p, const char *ptr) {
  11063. capture_begin(p, ptr);
  11064. }
  11065. static bool end_text(upb_json_parser *p, const char *ptr) {
  11066. return capture_end(p, ptr);
  11067. }
  11068. static void start_number(upb_json_parser *p, const char *ptr) {
  11069. multipart_startaccum(p);
  11070. capture_begin(p, ptr);
  11071. }
  11072. static bool parse_number(upb_json_parser *p, bool is_quoted);
  11073. static bool end_number(upb_json_parser *p, const char *ptr) {
  11074. if (!capture_end(p, ptr)) {
  11075. return false;
  11076. }
  11077. return parse_number(p, false);
  11078. }
  11079. /* |buf| is NULL-terminated. |buf| itself will never include quotes;
  11080. * |is_quoted| tells us whether this text originally appeared inside quotes. */
  11081. static bool parse_number_from_buffer(upb_json_parser *p, const char *buf,
  11082. bool is_quoted) {
  11083. size_t len = strlen(buf);
  11084. const char *bufend = buf + len;
  11085. char *end;
  11086. upb_fieldtype_t type = upb_fielddef_type(p->top->f);
  11087. double val;
  11088. double dummy;
  11089. double inf = 1.0 / 0.0; /* C89 does not have an INFINITY macro. */
  11090. errno = 0;
  11091. if (len == 0 || buf[0] == ' ') {
  11092. return false;
  11093. }
  11094. /* For integer types, first try parsing with integer-specific routines.
  11095. * If these succeed, they will be more accurate for int64/uint64 than
  11096. * strtod().
  11097. */
  11098. switch (type) {
  11099. case UPB_TYPE_ENUM:
  11100. case UPB_TYPE_INT32: {
  11101. long val = strtol(buf, &end, 0);
  11102. if (errno == ERANGE || end != bufend) {
  11103. break;
  11104. } else if (val > INT32_MAX || val < INT32_MIN) {
  11105. return false;
  11106. } else {
  11107. upb_sink_putint32(&p->top->sink, parser_getsel(p), val);
  11108. return true;
  11109. }
  11110. }
  11111. case UPB_TYPE_UINT32: {
  11112. unsigned long val = strtoul(buf, &end, 0);
  11113. if (end != bufend) {
  11114. break;
  11115. } else if (val > UINT32_MAX || errno == ERANGE) {
  11116. return false;
  11117. } else {
  11118. upb_sink_putuint32(&p->top->sink, parser_getsel(p), val);
  11119. return true;
  11120. }
  11121. }
  11122. /* XXX: We can't handle [u]int64 properly on 32-bit machines because
  11123. * strto[u]ll isn't in C89. */
  11124. case UPB_TYPE_INT64: {
  11125. long val = strtol(buf, &end, 0);
  11126. if (errno == ERANGE || end != bufend) {
  11127. break;
  11128. } else {
  11129. upb_sink_putint64(&p->top->sink, parser_getsel(p), val);
  11130. return true;
  11131. }
  11132. }
  11133. case UPB_TYPE_UINT64: {
  11134. unsigned long val = strtoul(p->accumulated, &end, 0);
  11135. if (end != bufend) {
  11136. break;
  11137. } else if (errno == ERANGE) {
  11138. return false;
  11139. } else {
  11140. upb_sink_putuint64(&p->top->sink, parser_getsel(p), val);
  11141. return true;
  11142. }
  11143. }
  11144. default:
  11145. break;
  11146. }
  11147. if (type != UPB_TYPE_DOUBLE && type != UPB_TYPE_FLOAT && is_quoted) {
  11148. /* Quoted numbers for integer types are not allowed to be in double form. */
  11149. return false;
  11150. }
  11151. if (len == strlen("Infinity") && strcmp(buf, "Infinity") == 0) {
  11152. /* C89 does not have an INFINITY macro. */
  11153. val = inf;
  11154. } else if (len == strlen("-Infinity") && strcmp(buf, "-Infinity") == 0) {
  11155. val = -inf;
  11156. } else {
  11157. val = strtod(buf, &end);
  11158. if (errno == ERANGE || end != bufend) {
  11159. return false;
  11160. }
  11161. }
  11162. switch (type) {
  11163. #define CASE(capitaltype, smalltype, ctype, min, max) \
  11164. case UPB_TYPE_ ## capitaltype: { \
  11165. if (modf(val, &dummy) != 0 || val > max || val < min) { \
  11166. return false; \
  11167. } else { \
  11168. upb_sink_put ## smalltype(&p->top->sink, parser_getsel(p), \
  11169. (ctype)val); \
  11170. return true; \
  11171. } \
  11172. break; \
  11173. }
  11174. case UPB_TYPE_ENUM:
  11175. CASE(INT32, int32, int32_t, INT32_MIN, INT32_MAX);
  11176. CASE(INT64, int64, int64_t, INT64_MIN, INT64_MAX);
  11177. CASE(UINT32, uint32, uint32_t, 0, UINT32_MAX);
  11178. CASE(UINT64, uint64, uint64_t, 0, UINT64_MAX);
  11179. #undef CASE
  11180. case UPB_TYPE_DOUBLE:
  11181. upb_sink_putdouble(&p->top->sink, parser_getsel(p), val);
  11182. return true;
  11183. case UPB_TYPE_FLOAT:
  11184. if ((val > FLT_MAX || val < -FLT_MAX) && val != inf && val != -inf) {
  11185. return false;
  11186. } else {
  11187. upb_sink_putfloat(&p->top->sink, parser_getsel(p), val);
  11188. return true;
  11189. }
  11190. default:
  11191. return false;
  11192. }
  11193. }
  11194. static bool parse_number(upb_json_parser *p, bool is_quoted) {
  11195. size_t len;
  11196. const char *buf;
  11197. /* strtol() and friends unfortunately do not support specifying the length of
  11198. * the input string, so we need to force a copy into a NULL-terminated buffer. */
  11199. if (!multipart_text(p, "\0", 1, false)) {
  11200. return false;
  11201. }
  11202. buf = accumulate_getptr(p, &len);
  11203. if (parse_number_from_buffer(p, buf, is_quoted)) {
  11204. multipart_end(p);
  11205. return true;
  11206. } else {
  11207. upb_status_seterrf(&p->status, "error parsing number: %s", buf);
  11208. upb_env_reporterror(p->env, &p->status);
  11209. multipart_end(p);
  11210. return false;
  11211. }
  11212. }
  11213. static bool parser_putbool(upb_json_parser *p, bool val) {
  11214. bool ok;
  11215. if (upb_fielddef_type(p->top->f) != UPB_TYPE_BOOL) {
  11216. upb_status_seterrf(&p->status,
  11217. "Boolean value specified for non-bool field: %s",
  11218. upb_fielddef_name(p->top->f));
  11219. upb_env_reporterror(p->env, &p->status);
  11220. return false;
  11221. }
  11222. ok = upb_sink_putbool(&p->top->sink, parser_getsel(p), val);
  11223. UPB_ASSERT(ok);
  11224. return true;
  11225. }
  11226. static bool start_stringval(upb_json_parser *p) {
  11227. UPB_ASSERT(p->top->f);
  11228. if (upb_fielddef_isstring(p->top->f)) {
  11229. upb_jsonparser_frame *inner;
  11230. upb_selector_t sel;
  11231. if (!check_stack(p)) return false;
  11232. /* Start a new parser frame: parser frames correspond one-to-one with
  11233. * handler frames, and string events occur in a sub-frame. */
  11234. inner = p->top + 1;
  11235. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  11236. upb_sink_startstr(&p->top->sink, sel, 0, &inner->sink);
  11237. inner->m = p->top->m;
  11238. inner->f = p->top->f;
  11239. inner->name_table = NULL;
  11240. inner->is_map = false;
  11241. inner->is_mapentry = false;
  11242. p->top = inner;
  11243. if (upb_fielddef_type(p->top->f) == UPB_TYPE_STRING) {
  11244. /* For STRING fields we push data directly to the handlers as it is
  11245. * parsed. We don't do this yet for BYTES fields, because our base64
  11246. * decoder is not streaming.
  11247. *
  11248. * TODO(haberman): make base64 decoding streaming also. */
  11249. multipart_start(p, getsel_for_handlertype(p, UPB_HANDLER_STRING));
  11250. return true;
  11251. } else {
  11252. multipart_startaccum(p);
  11253. return true;
  11254. }
  11255. } else if (upb_fielddef_type(p->top->f) != UPB_TYPE_BOOL &&
  11256. upb_fielddef_type(p->top->f) != UPB_TYPE_MESSAGE) {
  11257. /* No need to push a frame -- numeric values in quotes remain in the
  11258. * current parser frame. These values must accmulate so we can convert
  11259. * them all at once at the end. */
  11260. multipart_startaccum(p);
  11261. return true;
  11262. } else {
  11263. upb_status_seterrf(&p->status,
  11264. "String specified for bool or submessage field: %s",
  11265. upb_fielddef_name(p->top->f));
  11266. upb_env_reporterror(p->env, &p->status);
  11267. return false;
  11268. }
  11269. }
  11270. static bool end_stringval(upb_json_parser *p) {
  11271. bool ok = true;
  11272. switch (upb_fielddef_type(p->top->f)) {
  11273. case UPB_TYPE_BYTES:
  11274. if (!base64_push(p, getsel_for_handlertype(p, UPB_HANDLER_STRING),
  11275. p->accumulated, p->accumulated_len)) {
  11276. return false;
  11277. }
  11278. /* Fall through. */
  11279. case UPB_TYPE_STRING: {
  11280. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  11281. p->top--;
  11282. upb_sink_endstr(&p->top->sink, sel);
  11283. break;
  11284. }
  11285. case UPB_TYPE_ENUM: {
  11286. /* Resolve enum symbolic name to integer value. */
  11287. const upb_enumdef *enumdef =
  11288. (const upb_enumdef*)upb_fielddef_subdef(p->top->f);
  11289. size_t len;
  11290. const char *buf = accumulate_getptr(p, &len);
  11291. int32_t int_val = 0;
  11292. ok = upb_enumdef_ntoi(enumdef, buf, len, &int_val);
  11293. if (ok) {
  11294. upb_selector_t sel = parser_getsel(p);
  11295. upb_sink_putint32(&p->top->sink, sel, int_val);
  11296. } else {
  11297. upb_status_seterrf(&p->status, "Enum value unknown: '%.*s'", len, buf);
  11298. upb_env_reporterror(p->env, &p->status);
  11299. }
  11300. break;
  11301. }
  11302. case UPB_TYPE_INT32:
  11303. case UPB_TYPE_INT64:
  11304. case UPB_TYPE_UINT32:
  11305. case UPB_TYPE_UINT64:
  11306. case UPB_TYPE_DOUBLE:
  11307. case UPB_TYPE_FLOAT:
  11308. ok = parse_number(p, true);
  11309. break;
  11310. default:
  11311. UPB_ASSERT(false);
  11312. upb_status_seterrmsg(&p->status, "Internal error in JSON decoder");
  11313. upb_env_reporterror(p->env, &p->status);
  11314. ok = false;
  11315. break;
  11316. }
  11317. multipart_end(p);
  11318. return ok;
  11319. }
  11320. static void start_member(upb_json_parser *p) {
  11321. UPB_ASSERT(!p->top->f);
  11322. multipart_startaccum(p);
  11323. }
  11324. /* Helper: invoked during parse_mapentry() to emit the mapentry message's key
  11325. * field based on the current contents of the accumulate buffer. */
  11326. static bool parse_mapentry_key(upb_json_parser *p) {
  11327. size_t len;
  11328. const char *buf = accumulate_getptr(p, &len);
  11329. /* Emit the key field. We do a bit of ad-hoc parsing here because the
  11330. * parser state machine has already decided that this is a string field
  11331. * name, and we are reinterpreting it as some arbitrary key type. In
  11332. * particular, integer and bool keys are quoted, so we need to parse the
  11333. * quoted string contents here. */
  11334. p->top->f = upb_msgdef_itof(p->top->m, UPB_MAPENTRY_KEY);
  11335. if (p->top->f == NULL) {
  11336. upb_status_seterrmsg(&p->status, "mapentry message has no key");
  11337. upb_env_reporterror(p->env, &p->status);
  11338. return false;
  11339. }
  11340. switch (upb_fielddef_type(p->top->f)) {
  11341. case UPB_TYPE_INT32:
  11342. case UPB_TYPE_INT64:
  11343. case UPB_TYPE_UINT32:
  11344. case UPB_TYPE_UINT64:
  11345. /* Invoke end_number. The accum buffer has the number's text already. */
  11346. if (!parse_number(p, true)) {
  11347. return false;
  11348. }
  11349. break;
  11350. case UPB_TYPE_BOOL:
  11351. if (len == 4 && !strncmp(buf, "true", 4)) {
  11352. if (!parser_putbool(p, true)) {
  11353. return false;
  11354. }
  11355. } else if (len == 5 && !strncmp(buf, "false", 5)) {
  11356. if (!parser_putbool(p, false)) {
  11357. return false;
  11358. }
  11359. } else {
  11360. upb_status_seterrmsg(&p->status,
  11361. "Map bool key not 'true' or 'false'");
  11362. upb_env_reporterror(p->env, &p->status);
  11363. return false;
  11364. }
  11365. multipart_end(p);
  11366. break;
  11367. case UPB_TYPE_STRING:
  11368. case UPB_TYPE_BYTES: {
  11369. upb_sink subsink;
  11370. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  11371. upb_sink_startstr(&p->top->sink, sel, len, &subsink);
  11372. sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
  11373. upb_sink_putstring(&subsink, sel, buf, len, NULL);
  11374. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  11375. upb_sink_endstr(&p->top->sink, sel);
  11376. multipart_end(p);
  11377. break;
  11378. }
  11379. default:
  11380. upb_status_seterrmsg(&p->status, "Invalid field type for map key");
  11381. upb_env_reporterror(p->env, &p->status);
  11382. return false;
  11383. }
  11384. return true;
  11385. }
  11386. /* Helper: emit one map entry (as a submessage in the map field sequence). This
  11387. * is invoked from end_membername(), at the end of the map entry's key string,
  11388. * with the map key in the accumulate buffer. It parses the key from that
  11389. * buffer, emits the handler calls to start the mapentry submessage (setting up
  11390. * its subframe in the process), and sets up state in the subframe so that the
  11391. * value parser (invoked next) will emit the mapentry's value field and then
  11392. * end the mapentry message. */
  11393. static bool handle_mapentry(upb_json_parser *p) {
  11394. const upb_fielddef *mapfield;
  11395. const upb_msgdef *mapentrymsg;
  11396. upb_jsonparser_frame *inner;
  11397. upb_selector_t sel;
  11398. /* Map entry: p->top->sink is the seq frame, so we need to start a frame
  11399. * for the mapentry itself, and then set |f| in that frame so that the map
  11400. * value field is parsed, and also set a flag to end the frame after the
  11401. * map-entry value is parsed. */
  11402. if (!check_stack(p)) return false;
  11403. mapfield = p->top->mapfield;
  11404. mapentrymsg = upb_fielddef_msgsubdef(mapfield);
  11405. inner = p->top + 1;
  11406. p->top->f = mapfield;
  11407. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
  11408. upb_sink_startsubmsg(&p->top->sink, sel, &inner->sink);
  11409. inner->m = mapentrymsg;
  11410. inner->name_table = NULL;
  11411. inner->mapfield = mapfield;
  11412. inner->is_map = false;
  11413. /* Don't set this to true *yet* -- we reuse parsing handlers below to push
  11414. * the key field value to the sink, and these handlers will pop the frame
  11415. * if they see is_mapentry (when invoked by the parser state machine, they
  11416. * would have just seen the map-entry value, not key). */
  11417. inner->is_mapentry = false;
  11418. p->top = inner;
  11419. /* send STARTMSG in submsg frame. */
  11420. upb_sink_startmsg(&p->top->sink);
  11421. parse_mapentry_key(p);
  11422. /* Set up the value field to receive the map-entry value. */
  11423. p->top->f = upb_msgdef_itof(p->top->m, UPB_MAPENTRY_VALUE);
  11424. p->top->is_mapentry = true; /* set up to pop frame after value is parsed. */
  11425. p->top->mapfield = mapfield;
  11426. if (p->top->f == NULL) {
  11427. upb_status_seterrmsg(&p->status, "mapentry message has no value");
  11428. upb_env_reporterror(p->env, &p->status);
  11429. return false;
  11430. }
  11431. return true;
  11432. }
  11433. static bool end_membername(upb_json_parser *p) {
  11434. UPB_ASSERT(!p->top->f);
  11435. if (p->top->is_map) {
  11436. return handle_mapentry(p);
  11437. } else {
  11438. size_t len;
  11439. const char *buf = accumulate_getptr(p, &len);
  11440. upb_value v;
  11441. if (upb_strtable_lookup2(p->top->name_table, buf, len, &v)) {
  11442. p->top->f = upb_value_getconstptr(v);
  11443. multipart_end(p);
  11444. return true;
  11445. } else {
  11446. /* TODO(haberman): Ignore unknown fields if requested/configured to do
  11447. * so. */
  11448. upb_status_seterrf(&p->status, "No such field: %.*s\n", (int)len, buf);
  11449. upb_env_reporterror(p->env, &p->status);
  11450. return false;
  11451. }
  11452. }
  11453. }
  11454. static void end_member(upb_json_parser *p) {
  11455. /* If we just parsed a map-entry value, end that frame too. */
  11456. if (p->top->is_mapentry) {
  11457. upb_status s = UPB_STATUS_INIT;
  11458. upb_selector_t sel;
  11459. bool ok;
  11460. const upb_fielddef *mapfield;
  11461. UPB_ASSERT(p->top > p->stack);
  11462. /* send ENDMSG on submsg. */
  11463. upb_sink_endmsg(&p->top->sink, &s);
  11464. mapfield = p->top->mapfield;
  11465. /* send ENDSUBMSG in repeated-field-of-mapentries frame. */
  11466. p->top--;
  11467. ok = upb_handlers_getselector(mapfield, UPB_HANDLER_ENDSUBMSG, &sel);
  11468. UPB_ASSERT(ok);
  11469. upb_sink_endsubmsg(&p->top->sink, sel);
  11470. }
  11471. p->top->f = NULL;
  11472. }
  11473. static bool start_subobject(upb_json_parser *p) {
  11474. UPB_ASSERT(p->top->f);
  11475. if (upb_fielddef_ismap(p->top->f)) {
  11476. upb_jsonparser_frame *inner;
  11477. upb_selector_t sel;
  11478. /* Beginning of a map. Start a new parser frame in a repeated-field
  11479. * context. */
  11480. if (!check_stack(p)) return false;
  11481. inner = p->top + 1;
  11482. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
  11483. upb_sink_startseq(&p->top->sink, sel, &inner->sink);
  11484. inner->m = upb_fielddef_msgsubdef(p->top->f);
  11485. inner->name_table = NULL;
  11486. inner->mapfield = p->top->f;
  11487. inner->f = NULL;
  11488. inner->is_map = true;
  11489. inner->is_mapentry = false;
  11490. p->top = inner;
  11491. return true;
  11492. } else if (upb_fielddef_issubmsg(p->top->f)) {
  11493. upb_jsonparser_frame *inner;
  11494. upb_selector_t sel;
  11495. /* Beginning of a subobject. Start a new parser frame in the submsg
  11496. * context. */
  11497. if (!check_stack(p)) return false;
  11498. inner = p->top + 1;
  11499. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
  11500. upb_sink_startsubmsg(&p->top->sink, sel, &inner->sink);
  11501. inner->m = upb_fielddef_msgsubdef(p->top->f);
  11502. set_name_table(p, inner);
  11503. inner->f = NULL;
  11504. inner->is_map = false;
  11505. inner->is_mapentry = false;
  11506. p->top = inner;
  11507. return true;
  11508. } else {
  11509. upb_status_seterrf(&p->status,
  11510. "Object specified for non-message/group field: %s",
  11511. upb_fielddef_name(p->top->f));
  11512. upb_env_reporterror(p->env, &p->status);
  11513. return false;
  11514. }
  11515. }
  11516. static void end_subobject(upb_json_parser *p) {
  11517. if (p->top->is_map) {
  11518. upb_selector_t sel;
  11519. p->top--;
  11520. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
  11521. upb_sink_endseq(&p->top->sink, sel);
  11522. } else {
  11523. upb_selector_t sel;
  11524. p->top--;
  11525. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSUBMSG);
  11526. upb_sink_endsubmsg(&p->top->sink, sel);
  11527. }
  11528. }
  11529. static bool start_array(upb_json_parser *p) {
  11530. upb_jsonparser_frame *inner;
  11531. upb_selector_t sel;
  11532. UPB_ASSERT(p->top->f);
  11533. if (!upb_fielddef_isseq(p->top->f)) {
  11534. upb_status_seterrf(&p->status,
  11535. "Array specified for non-repeated field: %s",
  11536. upb_fielddef_name(p->top->f));
  11537. upb_env_reporterror(p->env, &p->status);
  11538. return false;
  11539. }
  11540. if (!check_stack(p)) return false;
  11541. inner = p->top + 1;
  11542. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
  11543. upb_sink_startseq(&p->top->sink, sel, &inner->sink);
  11544. inner->m = p->top->m;
  11545. inner->name_table = NULL;
  11546. inner->f = p->top->f;
  11547. inner->is_map = false;
  11548. inner->is_mapentry = false;
  11549. p->top = inner;
  11550. return true;
  11551. }
  11552. static void end_array(upb_json_parser *p) {
  11553. upb_selector_t sel;
  11554. UPB_ASSERT(p->top > p->stack);
  11555. p->top--;
  11556. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
  11557. upb_sink_endseq(&p->top->sink, sel);
  11558. }
  11559. static void start_object(upb_json_parser *p) {
  11560. if (!p->top->is_map) {
  11561. upb_sink_startmsg(&p->top->sink);
  11562. }
  11563. }
  11564. static void end_object(upb_json_parser *p) {
  11565. if (!p->top->is_map) {
  11566. upb_status status;
  11567. upb_status_clear(&status);
  11568. upb_sink_endmsg(&p->top->sink, &status);
  11569. if (!upb_ok(&status)) {
  11570. upb_env_reporterror(p->env, &status);
  11571. }
  11572. }
  11573. }
  11574. #define CHECK_RETURN_TOP(x) if (!(x)) goto error
  11575. /* The actual parser **********************************************************/
  11576. /* What follows is the Ragel parser itself. The language is specified in Ragel
  11577. * and the actions call our C functions above.
  11578. *
  11579. * Ragel has an extensive set of functionality, and we use only a small part of
  11580. * it. There are many action types but we only use a few:
  11581. *
  11582. * ">" -- transition into a machine
  11583. * "%" -- transition out of a machine
  11584. * "@" -- transition into a final state of a machine.
  11585. *
  11586. * "@" transitions are tricky because a machine can transition into a final
  11587. * state repeatedly. But in some cases we know this can't happen, for example
  11588. * a string which is delimited by a final '"' can only transition into its
  11589. * final state once, when the closing '"' is seen. */
  11590. #line 1310 "upb/json/parser.rl"
  11591. #line 1222 "upb/json/parser.c"
  11592. static const char _json_actions[] = {
  11593. 0, 1, 0, 1, 2, 1, 3, 1,
  11594. 5, 1, 6, 1, 7, 1, 8, 1,
  11595. 10, 1, 12, 1, 13, 1, 14, 1,
  11596. 15, 1, 16, 1, 17, 1, 21, 1,
  11597. 25, 1, 27, 2, 3, 8, 2, 4,
  11598. 5, 2, 6, 2, 2, 6, 8, 2,
  11599. 11, 9, 2, 13, 15, 2, 14, 15,
  11600. 2, 18, 1, 2, 19, 27, 2, 20,
  11601. 9, 2, 22, 27, 2, 23, 27, 2,
  11602. 24, 27, 2, 26, 27, 3, 14, 11,
  11603. 9
  11604. };
  11605. static const unsigned char _json_key_offsets[] = {
  11606. 0, 0, 4, 9, 14, 15, 19, 24,
  11607. 29, 34, 38, 42, 45, 48, 50, 54,
  11608. 58, 60, 62, 67, 69, 71, 80, 86,
  11609. 92, 98, 104, 106, 115, 116, 116, 116,
  11610. 121, 126, 131, 132, 133, 134, 135, 135,
  11611. 136, 137, 138, 138, 139, 140, 141, 141,
  11612. 146, 151, 152, 156, 161, 166, 171, 175,
  11613. 175, 178, 178, 178
  11614. };
  11615. static const char _json_trans_keys[] = {
  11616. 32, 123, 9, 13, 32, 34, 125, 9,
  11617. 13, 32, 34, 125, 9, 13, 34, 32,
  11618. 58, 9, 13, 32, 93, 125, 9, 13,
  11619. 32, 44, 125, 9, 13, 32, 44, 125,
  11620. 9, 13, 32, 34, 9, 13, 45, 48,
  11621. 49, 57, 48, 49, 57, 46, 69, 101,
  11622. 48, 57, 69, 101, 48, 57, 43, 45,
  11623. 48, 57, 48, 57, 48, 57, 46, 69,
  11624. 101, 48, 57, 34, 92, 34, 92, 34,
  11625. 47, 92, 98, 102, 110, 114, 116, 117,
  11626. 48, 57, 65, 70, 97, 102, 48, 57,
  11627. 65, 70, 97, 102, 48, 57, 65, 70,
  11628. 97, 102, 48, 57, 65, 70, 97, 102,
  11629. 34, 92, 34, 45, 91, 102, 110, 116,
  11630. 123, 48, 57, 34, 32, 93, 125, 9,
  11631. 13, 32, 44, 93, 9, 13, 32, 93,
  11632. 125, 9, 13, 97, 108, 115, 101, 117,
  11633. 108, 108, 114, 117, 101, 32, 34, 125,
  11634. 9, 13, 32, 34, 125, 9, 13, 34,
  11635. 32, 58, 9, 13, 32, 93, 125, 9,
  11636. 13, 32, 44, 125, 9, 13, 32, 44,
  11637. 125, 9, 13, 32, 34, 9, 13, 32,
  11638. 9, 13, 0
  11639. };
  11640. static const char _json_single_lengths[] = {
  11641. 0, 2, 3, 3, 1, 2, 3, 3,
  11642. 3, 2, 2, 1, 3, 0, 2, 2,
  11643. 0, 0, 3, 2, 2, 9, 0, 0,
  11644. 0, 0, 2, 7, 1, 0, 0, 3,
  11645. 3, 3, 1, 1, 1, 1, 0, 1,
  11646. 1, 1, 0, 1, 1, 1, 0, 3,
  11647. 3, 1, 2, 3, 3, 3, 2, 0,
  11648. 1, 0, 0, 0
  11649. };
  11650. static const char _json_range_lengths[] = {
  11651. 0, 1, 1, 1, 0, 1, 1, 1,
  11652. 1, 1, 1, 1, 0, 1, 1, 1,
  11653. 1, 1, 1, 0, 0, 0, 3, 3,
  11654. 3, 3, 0, 1, 0, 0, 0, 1,
  11655. 1, 1, 0, 0, 0, 0, 0, 0,
  11656. 0, 0, 0, 0, 0, 0, 0, 1,
  11657. 1, 0, 1, 1, 1, 1, 1, 0,
  11658. 1, 0, 0, 0
  11659. };
  11660. static const short _json_index_offsets[] = {
  11661. 0, 0, 4, 9, 14, 16, 20, 25,
  11662. 30, 35, 39, 43, 46, 50, 52, 56,
  11663. 60, 62, 64, 69, 72, 75, 85, 89,
  11664. 93, 97, 101, 104, 113, 115, 116, 117,
  11665. 122, 127, 132, 134, 136, 138, 140, 141,
  11666. 143, 145, 147, 148, 150, 152, 154, 155,
  11667. 160, 165, 167, 171, 176, 181, 186, 190,
  11668. 191, 194, 195, 196
  11669. };
  11670. static const char _json_indicies[] = {
  11671. 0, 2, 0, 1, 3, 4, 5, 3,
  11672. 1, 6, 7, 8, 6, 1, 9, 1,
  11673. 10, 11, 10, 1, 11, 1, 1, 11,
  11674. 12, 13, 14, 15, 13, 1, 16, 17,
  11675. 8, 16, 1, 17, 7, 17, 1, 18,
  11676. 19, 20, 1, 19, 20, 1, 22, 23,
  11677. 23, 21, 24, 1, 23, 23, 24, 21,
  11678. 25, 25, 26, 1, 26, 1, 26, 21,
  11679. 22, 23, 23, 20, 21, 28, 29, 27,
  11680. 31, 32, 30, 33, 33, 33, 33, 33,
  11681. 33, 33, 33, 34, 1, 35, 35, 35,
  11682. 1, 36, 36, 36, 1, 37, 37, 37,
  11683. 1, 38, 38, 38, 1, 40, 41, 39,
  11684. 42, 43, 44, 45, 46, 47, 48, 43,
  11685. 1, 49, 1, 50, 51, 53, 54, 1,
  11686. 53, 52, 55, 56, 54, 55, 1, 56,
  11687. 1, 1, 56, 52, 57, 1, 58, 1,
  11688. 59, 1, 60, 1, 61, 62, 1, 63,
  11689. 1, 64, 1, 65, 66, 1, 67, 1,
  11690. 68, 1, 69, 70, 71, 72, 70, 1,
  11691. 73, 74, 75, 73, 1, 76, 1, 77,
  11692. 78, 77, 1, 78, 1, 1, 78, 79,
  11693. 80, 81, 82, 80, 1, 83, 84, 75,
  11694. 83, 1, 84, 74, 84, 1, 85, 86,
  11695. 86, 1, 1, 1, 1, 0
  11696. };
  11697. static const char _json_trans_targs[] = {
  11698. 1, 0, 2, 3, 4, 56, 3, 4,
  11699. 56, 5, 5, 6, 7, 8, 9, 56,
  11700. 8, 9, 11, 12, 18, 57, 13, 15,
  11701. 14, 16, 17, 20, 58, 21, 20, 58,
  11702. 21, 19, 22, 23, 24, 25, 26, 20,
  11703. 58, 21, 28, 30, 31, 34, 39, 43,
  11704. 47, 29, 59, 59, 32, 31, 29, 32,
  11705. 33, 35, 36, 37, 38, 59, 40, 41,
  11706. 42, 59, 44, 45, 46, 59, 48, 49,
  11707. 55, 48, 49, 55, 50, 50, 51, 52,
  11708. 53, 54, 55, 53, 54, 59, 56
  11709. };
  11710. static const char _json_trans_actions[] = {
  11711. 0, 0, 0, 21, 77, 53, 0, 47,
  11712. 23, 17, 0, 0, 15, 19, 19, 50,
  11713. 0, 0, 0, 0, 0, 1, 0, 0,
  11714. 0, 0, 0, 3, 13, 0, 0, 35,
  11715. 5, 11, 0, 38, 7, 7, 7, 41,
  11716. 44, 9, 62, 56, 25, 0, 0, 0,
  11717. 31, 29, 33, 59, 15, 0, 27, 0,
  11718. 0, 0, 0, 0, 0, 68, 0, 0,
  11719. 0, 71, 0, 0, 0, 65, 21, 77,
  11720. 53, 0, 47, 23, 17, 0, 0, 15,
  11721. 19, 19, 50, 0, 0, 74, 0
  11722. };
  11723. static const int json_start = 1;
  11724. static const int json_en_number_machine = 10;
  11725. static const int json_en_string_machine = 19;
  11726. static const int json_en_value_machine = 27;
  11727. static const int json_en_main = 1;
  11728. #line 1313 "upb/json/parser.rl"
  11729. size_t parse(void *closure, const void *hd, const char *buf, size_t size,
  11730. const upb_bufhandle *handle) {
  11731. upb_json_parser *parser = closure;
  11732. /* Variables used by Ragel's generated code. */
  11733. int cs = parser->current_state;
  11734. int *stack = parser->parser_stack;
  11735. int top = parser->parser_top;
  11736. const char *p = buf;
  11737. const char *pe = buf + size;
  11738. parser->handle = handle;
  11739. UPB_UNUSED(hd);
  11740. UPB_UNUSED(handle);
  11741. capture_resume(parser, buf);
  11742. #line 1393 "upb/json/parser.c"
  11743. {
  11744. int _klen;
  11745. unsigned int _trans;
  11746. const char *_acts;
  11747. unsigned int _nacts;
  11748. const char *_keys;
  11749. if ( p == pe )
  11750. goto _test_eof;
  11751. if ( cs == 0 )
  11752. goto _out;
  11753. _resume:
  11754. _keys = _json_trans_keys + _json_key_offsets[cs];
  11755. _trans = _json_index_offsets[cs];
  11756. _klen = _json_single_lengths[cs];
  11757. if ( _klen > 0 ) {
  11758. const char *_lower = _keys;
  11759. const char *_mid;
  11760. const char *_upper = _keys + _klen - 1;
  11761. while (1) {
  11762. if ( _upper < _lower )
  11763. break;
  11764. _mid = _lower + ((_upper-_lower) >> 1);
  11765. if ( (*p) < *_mid )
  11766. _upper = _mid - 1;
  11767. else if ( (*p) > *_mid )
  11768. _lower = _mid + 1;
  11769. else {
  11770. _trans += (unsigned int)(_mid - _keys);
  11771. goto _match;
  11772. }
  11773. }
  11774. _keys += _klen;
  11775. _trans += _klen;
  11776. }
  11777. _klen = _json_range_lengths[cs];
  11778. if ( _klen > 0 ) {
  11779. const char *_lower = _keys;
  11780. const char *_mid;
  11781. const char *_upper = _keys + (_klen<<1) - 2;
  11782. while (1) {
  11783. if ( _upper < _lower )
  11784. break;
  11785. _mid = _lower + (((_upper-_lower) >> 1) & ~1);
  11786. if ( (*p) < _mid[0] )
  11787. _upper = _mid - 2;
  11788. else if ( (*p) > _mid[1] )
  11789. _lower = _mid + 2;
  11790. else {
  11791. _trans += (unsigned int)((_mid - _keys)>>1);
  11792. goto _match;
  11793. }
  11794. }
  11795. _trans += _klen;
  11796. }
  11797. _match:
  11798. _trans = _json_indicies[_trans];
  11799. cs = _json_trans_targs[_trans];
  11800. if ( _json_trans_actions[_trans] == 0 )
  11801. goto _again;
  11802. _acts = _json_actions + _json_trans_actions[_trans];
  11803. _nacts = (unsigned int) *_acts++;
  11804. while ( _nacts-- > 0 )
  11805. {
  11806. switch ( *_acts++ )
  11807. {
  11808. case 0:
  11809. #line 1225 "upb/json/parser.rl"
  11810. { p--; {cs = stack[--top]; goto _again;} }
  11811. break;
  11812. case 1:
  11813. #line 1226 "upb/json/parser.rl"
  11814. { p--; {stack[top++] = cs; cs = 10; goto _again;} }
  11815. break;
  11816. case 2:
  11817. #line 1230 "upb/json/parser.rl"
  11818. { start_text(parser, p); }
  11819. break;
  11820. case 3:
  11821. #line 1231 "upb/json/parser.rl"
  11822. { CHECK_RETURN_TOP(end_text(parser, p)); }
  11823. break;
  11824. case 4:
  11825. #line 1237 "upb/json/parser.rl"
  11826. { start_hex(parser); }
  11827. break;
  11828. case 5:
  11829. #line 1238 "upb/json/parser.rl"
  11830. { hexdigit(parser, p); }
  11831. break;
  11832. case 6:
  11833. #line 1239 "upb/json/parser.rl"
  11834. { CHECK_RETURN_TOP(end_hex(parser)); }
  11835. break;
  11836. case 7:
  11837. #line 1245 "upb/json/parser.rl"
  11838. { CHECK_RETURN_TOP(escape(parser, p)); }
  11839. break;
  11840. case 8:
  11841. #line 1251 "upb/json/parser.rl"
  11842. { p--; {cs = stack[--top]; goto _again;} }
  11843. break;
  11844. case 9:
  11845. #line 1254 "upb/json/parser.rl"
  11846. { {stack[top++] = cs; cs = 19; goto _again;} }
  11847. break;
  11848. case 10:
  11849. #line 1256 "upb/json/parser.rl"
  11850. { p--; {stack[top++] = cs; cs = 27; goto _again;} }
  11851. break;
  11852. case 11:
  11853. #line 1261 "upb/json/parser.rl"
  11854. { start_member(parser); }
  11855. break;
  11856. case 12:
  11857. #line 1262 "upb/json/parser.rl"
  11858. { CHECK_RETURN_TOP(end_membername(parser)); }
  11859. break;
  11860. case 13:
  11861. #line 1265 "upb/json/parser.rl"
  11862. { end_member(parser); }
  11863. break;
  11864. case 14:
  11865. #line 1271 "upb/json/parser.rl"
  11866. { start_object(parser); }
  11867. break;
  11868. case 15:
  11869. #line 1274 "upb/json/parser.rl"
  11870. { end_object(parser); }
  11871. break;
  11872. case 16:
  11873. #line 1280 "upb/json/parser.rl"
  11874. { CHECK_RETURN_TOP(start_array(parser)); }
  11875. break;
  11876. case 17:
  11877. #line 1284 "upb/json/parser.rl"
  11878. { end_array(parser); }
  11879. break;
  11880. case 18:
  11881. #line 1289 "upb/json/parser.rl"
  11882. { start_number(parser, p); }
  11883. break;
  11884. case 19:
  11885. #line 1290 "upb/json/parser.rl"
  11886. { CHECK_RETURN_TOP(end_number(parser, p)); }
  11887. break;
  11888. case 20:
  11889. #line 1292 "upb/json/parser.rl"
  11890. { CHECK_RETURN_TOP(start_stringval(parser)); }
  11891. break;
  11892. case 21:
  11893. #line 1293 "upb/json/parser.rl"
  11894. { CHECK_RETURN_TOP(end_stringval(parser)); }
  11895. break;
  11896. case 22:
  11897. #line 1295 "upb/json/parser.rl"
  11898. { CHECK_RETURN_TOP(parser_putbool(parser, true)); }
  11899. break;
  11900. case 23:
  11901. #line 1297 "upb/json/parser.rl"
  11902. { CHECK_RETURN_TOP(parser_putbool(parser, false)); }
  11903. break;
  11904. case 24:
  11905. #line 1299 "upb/json/parser.rl"
  11906. { /* null value */ }
  11907. break;
  11908. case 25:
  11909. #line 1301 "upb/json/parser.rl"
  11910. { CHECK_RETURN_TOP(start_subobject(parser)); }
  11911. break;
  11912. case 26:
  11913. #line 1302 "upb/json/parser.rl"
  11914. { end_subobject(parser); }
  11915. break;
  11916. case 27:
  11917. #line 1307 "upb/json/parser.rl"
  11918. { p--; {cs = stack[--top]; goto _again;} }
  11919. break;
  11920. #line 1579 "upb/json/parser.c"
  11921. }
  11922. }
  11923. _again:
  11924. if ( cs == 0 )
  11925. goto _out;
  11926. if ( ++p != pe )
  11927. goto _resume;
  11928. _test_eof: {}
  11929. _out: {}
  11930. }
  11931. #line 1334 "upb/json/parser.rl"
  11932. if (p != pe) {
  11933. upb_status_seterrf(&parser->status, "Parse error at '%.*s'\n", pe - p, p);
  11934. upb_env_reporterror(parser->env, &parser->status);
  11935. } else {
  11936. capture_suspend(parser, &p);
  11937. }
  11938. error:
  11939. /* Save parsing state back to parser. */
  11940. parser->current_state = cs;
  11941. parser->parser_top = top;
  11942. return p - buf;
  11943. }
  11944. bool end(void *closure, const void *hd) {
  11945. UPB_UNUSED(closure);
  11946. UPB_UNUSED(hd);
  11947. /* Prevent compile warning on unused static constants. */
  11948. UPB_UNUSED(json_start);
  11949. UPB_UNUSED(json_en_number_machine);
  11950. UPB_UNUSED(json_en_string_machine);
  11951. UPB_UNUSED(json_en_value_machine);
  11952. UPB_UNUSED(json_en_main);
  11953. return true;
  11954. }
  11955. static void json_parser_reset(upb_json_parser *p) {
  11956. int cs;
  11957. int top;
  11958. p->top = p->stack;
  11959. p->top->f = NULL;
  11960. p->top->is_map = false;
  11961. p->top->is_mapentry = false;
  11962. /* Emit Ragel initialization of the parser. */
  11963. #line 1633 "upb/json/parser.c"
  11964. {
  11965. cs = json_start;
  11966. top = 0;
  11967. }
  11968. #line 1374 "upb/json/parser.rl"
  11969. p->current_state = cs;
  11970. p->parser_top = top;
  11971. accumulate_clear(p);
  11972. p->multipart_state = MULTIPART_INACTIVE;
  11973. p->capture = NULL;
  11974. p->accumulated = NULL;
  11975. upb_status_clear(&p->status);
  11976. }
  11977. static void visit_json_parsermethod(const upb_refcounted *r,
  11978. upb_refcounted_visit *visit,
  11979. void *closure) {
  11980. const upb_json_parsermethod *method = (upb_json_parsermethod*)r;
  11981. visit(r, upb_msgdef_upcast2(method->msg), closure);
  11982. }
  11983. static void free_json_parsermethod(upb_refcounted *r) {
  11984. upb_json_parsermethod *method = (upb_json_parsermethod*)r;
  11985. upb_inttable_iter i;
  11986. upb_inttable_begin(&i, &method->name_tables);
  11987. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  11988. upb_value val = upb_inttable_iter_value(&i);
  11989. upb_strtable *t = upb_value_getptr(val);
  11990. upb_strtable_uninit(t);
  11991. upb_gfree(t);
  11992. }
  11993. upb_inttable_uninit(&method->name_tables);
  11994. upb_gfree(r);
  11995. }
  11996. static void add_jsonname_table(upb_json_parsermethod *m, const upb_msgdef* md) {
  11997. upb_msg_field_iter i;
  11998. upb_strtable *t;
  11999. /* It would be nice to stack-allocate this, but protobufs do not limit the
  12000. * length of fields to any reasonable limit. */
  12001. char *buf = NULL;
  12002. size_t len = 0;
  12003. if (upb_inttable_lookupptr(&m->name_tables, md, NULL)) {
  12004. return;
  12005. }
  12006. /* TODO(haberman): handle malloc failure. */
  12007. t = upb_gmalloc(sizeof(*t));
  12008. upb_strtable_init(t, UPB_CTYPE_CONSTPTR);
  12009. upb_inttable_insertptr(&m->name_tables, md, upb_value_ptr(t));
  12010. for(upb_msg_field_begin(&i, md);
  12011. !upb_msg_field_done(&i);
  12012. upb_msg_field_next(&i)) {
  12013. const upb_fielddef *f = upb_msg_iter_field(&i);
  12014. /* Add an entry for the JSON name. */
  12015. size_t field_len = upb_fielddef_getjsonname(f, buf, len);
  12016. if (field_len > len) {
  12017. size_t len2;
  12018. buf = upb_grealloc(buf, 0, field_len);
  12019. len = field_len;
  12020. len2 = upb_fielddef_getjsonname(f, buf, len);
  12021. UPB_ASSERT(len == len2);
  12022. }
  12023. upb_strtable_insert(t, buf, upb_value_constptr(f));
  12024. if (strcmp(buf, upb_fielddef_name(f)) != 0) {
  12025. /* Since the JSON name is different from the regular field name, add an
  12026. * entry for the raw name (compliant proto3 JSON parsers must accept
  12027. * both). */
  12028. upb_strtable_insert(t, upb_fielddef_name(f), upb_value_constptr(f));
  12029. }
  12030. if (upb_fielddef_issubmsg(f)) {
  12031. add_jsonname_table(m, upb_fielddef_msgsubdef(f));
  12032. }
  12033. }
  12034. upb_gfree(buf);
  12035. }
  12036. /* Public API *****************************************************************/
  12037. upb_json_parser *upb_json_parser_create(upb_env *env,
  12038. const upb_json_parsermethod *method,
  12039. upb_sink *output) {
  12040. #ifndef NDEBUG
  12041. const size_t size_before = upb_env_bytesallocated(env);
  12042. #endif
  12043. upb_json_parser *p = upb_env_malloc(env, sizeof(upb_json_parser));
  12044. if (!p) return false;
  12045. p->env = env;
  12046. p->method = method;
  12047. p->limit = p->stack + UPB_JSON_MAX_DEPTH;
  12048. p->accumulate_buf = NULL;
  12049. p->accumulate_buf_size = 0;
  12050. upb_bytessink_reset(&p->input_, &method->input_handler_, p);
  12051. json_parser_reset(p);
  12052. upb_sink_reset(&p->top->sink, output->handlers, output->closure);
  12053. p->top->m = upb_handlers_msgdef(output->handlers);
  12054. set_name_table(p, p->top);
  12055. /* If this fails, uncomment and increase the value in parser.h. */
  12056. /* fprintf(stderr, "%zd\n", upb_env_bytesallocated(env) - size_before); */
  12057. UPB_ASSERT_DEBUGVAR(upb_env_bytesallocated(env) - size_before <=
  12058. UPB_JSON_PARSER_SIZE);
  12059. return p;
  12060. }
  12061. upb_bytessink *upb_json_parser_input(upb_json_parser *p) {
  12062. return &p->input_;
  12063. }
  12064. upb_json_parsermethod *upb_json_parsermethod_new(const upb_msgdef* md,
  12065. const void* owner) {
  12066. static const struct upb_refcounted_vtbl vtbl = {visit_json_parsermethod,
  12067. free_json_parsermethod};
  12068. upb_json_parsermethod *ret = upb_gmalloc(sizeof(*ret));
  12069. upb_refcounted_init(upb_json_parsermethod_upcast_mutable(ret), &vtbl, owner);
  12070. ret->msg = md;
  12071. upb_ref2(md, ret);
  12072. upb_byteshandler_init(&ret->input_handler_);
  12073. upb_byteshandler_setstring(&ret->input_handler_, parse, ret);
  12074. upb_byteshandler_setendstr(&ret->input_handler_, end, ret);
  12075. upb_inttable_init(&ret->name_tables, UPB_CTYPE_PTR);
  12076. add_jsonname_table(ret, md);
  12077. return ret;
  12078. }
  12079. const upb_byteshandler *upb_json_parsermethod_inputhandler(
  12080. const upb_json_parsermethod *m) {
  12081. return &m->input_handler_;
  12082. }
  12083. /*
  12084. ** This currently uses snprintf() to format primitives, and could be optimized
  12085. ** further.
  12086. */
  12087. #include <string.h>
  12088. #include <stdint.h>
  12089. struct upb_json_printer {
  12090. upb_sink input_;
  12091. /* BytesSink closure. */
  12092. void *subc_;
  12093. upb_bytessink *output_;
  12094. /* We track the depth so that we know when to emit startstr/endstr on the
  12095. * output. */
  12096. int depth_;
  12097. /* Have we emitted the first element? This state is necessary to emit commas
  12098. * without leaving a trailing comma in arrays/maps. We keep this state per
  12099. * frame depth.
  12100. *
  12101. * Why max_depth * 2? UPB_MAX_HANDLER_DEPTH counts depth as nested messages.
  12102. * We count frames (contexts in which we separate elements by commas) as both
  12103. * repeated fields and messages (maps), and the worst case is a
  12104. * message->repeated field->submessage->repeated field->... nesting. */
  12105. bool first_elem_[UPB_MAX_HANDLER_DEPTH * 2];
  12106. };
  12107. /* StringPiece; a pointer plus a length. */
  12108. typedef struct {
  12109. char *ptr;
  12110. size_t len;
  12111. } strpc;
  12112. void freestrpc(void *ptr) {
  12113. strpc *pc = ptr;
  12114. upb_gfree(pc->ptr);
  12115. upb_gfree(pc);
  12116. }
  12117. /* Convert fielddef name to JSON name and return as a string piece. */
  12118. strpc *newstrpc(upb_handlers *h, const upb_fielddef *f,
  12119. bool preserve_fieldnames) {
  12120. /* TODO(haberman): handle malloc failure. */
  12121. strpc *ret = upb_gmalloc(sizeof(*ret));
  12122. if (preserve_fieldnames) {
  12123. ret->ptr = upb_gstrdup(upb_fielddef_name(f));
  12124. ret->len = strlen(ret->ptr);
  12125. } else {
  12126. size_t len;
  12127. ret->len = upb_fielddef_getjsonname(f, NULL, 0);
  12128. ret->ptr = upb_gmalloc(ret->len);
  12129. len = upb_fielddef_getjsonname(f, ret->ptr, ret->len);
  12130. UPB_ASSERT(len == ret->len);
  12131. ret->len--; /* NULL */
  12132. }
  12133. upb_handlers_addcleanup(h, ret, freestrpc);
  12134. return ret;
  12135. }
  12136. /* ------------ JSON string printing: values, maps, arrays ------------------ */
  12137. static void print_data(
  12138. upb_json_printer *p, const char *buf, unsigned int len) {
  12139. /* TODO: Will need to change if we support pushback from the sink. */
  12140. size_t n = upb_bytessink_putbuf(p->output_, p->subc_, buf, len, NULL);
  12141. UPB_ASSERT(n == len);
  12142. }
  12143. static void print_comma(upb_json_printer *p) {
  12144. if (!p->first_elem_[p->depth_]) {
  12145. print_data(p, ",", 1);
  12146. }
  12147. p->first_elem_[p->depth_] = false;
  12148. }
  12149. /* Helpers that print properly formatted elements to the JSON output stream. */
  12150. /* Used for escaping control chars in strings. */
  12151. static const char kControlCharLimit = 0x20;
  12152. UPB_INLINE bool is_json_escaped(char c) {
  12153. /* See RFC 4627. */
  12154. unsigned char uc = (unsigned char)c;
  12155. return uc < kControlCharLimit || uc == '"' || uc == '\\';
  12156. }
  12157. UPB_INLINE const char* json_nice_escape(char c) {
  12158. switch (c) {
  12159. case '"': return "\\\"";
  12160. case '\\': return "\\\\";
  12161. case '\b': return "\\b";
  12162. case '\f': return "\\f";
  12163. case '\n': return "\\n";
  12164. case '\r': return "\\r";
  12165. case '\t': return "\\t";
  12166. default: return NULL;
  12167. }
  12168. }
  12169. /* Write a properly escaped string chunk. The surrounding quotes are *not*
  12170. * printed; this is so that the caller has the option of emitting the string
  12171. * content in chunks. */
  12172. static void putstring(upb_json_printer *p, const char *buf, unsigned int len) {
  12173. const char* unescaped_run = NULL;
  12174. unsigned int i;
  12175. for (i = 0; i < len; i++) {
  12176. char c = buf[i];
  12177. /* Handle escaping. */
  12178. if (is_json_escaped(c)) {
  12179. /* Use a "nice" escape, like \n, if one exists for this character. */
  12180. const char* escape = json_nice_escape(c);
  12181. /* If we don't have a specific 'nice' escape code, use a \uXXXX-style
  12182. * escape. */
  12183. char escape_buf[8];
  12184. if (!escape) {
  12185. unsigned char byte = (unsigned char)c;
  12186. _upb_snprintf(escape_buf, sizeof(escape_buf), "\\u%04x", (int)byte);
  12187. escape = escape_buf;
  12188. }
  12189. /* N.B. that we assume that the input encoding is equal to the output
  12190. * encoding (both UTF-8 for now), so for chars >= 0x20 and != \, ", we
  12191. * can simply pass the bytes through. */
  12192. /* If there's a current run of unescaped chars, print that run first. */
  12193. if (unescaped_run) {
  12194. print_data(p, unescaped_run, &buf[i] - unescaped_run);
  12195. unescaped_run = NULL;
  12196. }
  12197. /* Then print the escape code. */
  12198. print_data(p, escape, strlen(escape));
  12199. } else {
  12200. /* Add to the current unescaped run of characters. */
  12201. if (unescaped_run == NULL) {
  12202. unescaped_run = &buf[i];
  12203. }
  12204. }
  12205. }
  12206. /* If the string ended in a run of unescaped characters, print that last run. */
  12207. if (unescaped_run) {
  12208. print_data(p, unescaped_run, &buf[len] - unescaped_run);
  12209. }
  12210. }
  12211. #define CHKLENGTH(x) if (!(x)) return -1;
  12212. /* Helpers that format floating point values according to our custom formats.
  12213. * Right now we use %.8g and %.17g for float/double, respectively, to match
  12214. * proto2::util::JsonFormat's defaults. May want to change this later. */
  12215. const char neginf[] = "\"-Infinity\"";
  12216. const char inf[] = "\"Infinity\"";
  12217. static size_t fmt_double(double val, char* buf, size_t length) {
  12218. if (val == (1.0 / 0.0)) {
  12219. CHKLENGTH(length >= strlen(inf));
  12220. strcpy(buf, inf);
  12221. return strlen(inf);
  12222. } else if (val == (-1.0 / 0.0)) {
  12223. CHKLENGTH(length >= strlen(neginf));
  12224. strcpy(buf, neginf);
  12225. return strlen(neginf);
  12226. } else {
  12227. size_t n = _upb_snprintf(buf, length, "%.17g", val);
  12228. CHKLENGTH(n > 0 && n < length);
  12229. return n;
  12230. }
  12231. }
  12232. static size_t fmt_float(float val, char* buf, size_t length) {
  12233. size_t n = _upb_snprintf(buf, length, "%.8g", val);
  12234. CHKLENGTH(n > 0 && n < length);
  12235. return n;
  12236. }
  12237. static size_t fmt_bool(bool val, char* buf, size_t length) {
  12238. size_t n = _upb_snprintf(buf, length, "%s", (val ? "true" : "false"));
  12239. CHKLENGTH(n > 0 && n < length);
  12240. return n;
  12241. }
  12242. static size_t fmt_int64(long val, char* buf, size_t length) {
  12243. size_t n = _upb_snprintf(buf, length, "%ld", val);
  12244. CHKLENGTH(n > 0 && n < length);
  12245. return n;
  12246. }
  12247. static size_t fmt_uint64(unsigned long long val, char* buf, size_t length) {
  12248. size_t n = _upb_snprintf(buf, length, "%llu", val);
  12249. CHKLENGTH(n > 0 && n < length);
  12250. return n;
  12251. }
  12252. /* Print a map key given a field name. Called by scalar field handlers and by
  12253. * startseq for repeated fields. */
  12254. static bool putkey(void *closure, const void *handler_data) {
  12255. upb_json_printer *p = closure;
  12256. const strpc *key = handler_data;
  12257. print_comma(p);
  12258. print_data(p, "\"", 1);
  12259. putstring(p, key->ptr, key->len);
  12260. print_data(p, "\":", 2);
  12261. return true;
  12262. }
  12263. #define CHKFMT(val) if ((val) == (size_t)-1) return false;
  12264. #define CHK(val) if (!(val)) return false;
  12265. #define TYPE_HANDLERS(type, fmt_func) \
  12266. static bool put##type(void *closure, const void *handler_data, type val) { \
  12267. upb_json_printer *p = closure; \
  12268. char data[64]; \
  12269. size_t length = fmt_func(val, data, sizeof(data)); \
  12270. UPB_UNUSED(handler_data); \
  12271. CHKFMT(length); \
  12272. print_data(p, data, length); \
  12273. return true; \
  12274. } \
  12275. static bool scalar_##type(void *closure, const void *handler_data, \
  12276. type val) { \
  12277. CHK(putkey(closure, handler_data)); \
  12278. CHK(put##type(closure, handler_data, val)); \
  12279. return true; \
  12280. } \
  12281. static bool repeated_##type(void *closure, const void *handler_data, \
  12282. type val) { \
  12283. upb_json_printer *p = closure; \
  12284. print_comma(p); \
  12285. CHK(put##type(closure, handler_data, val)); \
  12286. return true; \
  12287. }
  12288. #define TYPE_HANDLERS_MAPKEY(type, fmt_func) \
  12289. static bool putmapkey_##type(void *closure, const void *handler_data, \
  12290. type val) { \
  12291. upb_json_printer *p = closure; \
  12292. print_data(p, "\"", 1); \
  12293. CHK(put##type(closure, handler_data, val)); \
  12294. print_data(p, "\":", 2); \
  12295. return true; \
  12296. }
  12297. TYPE_HANDLERS(double, fmt_double)
  12298. TYPE_HANDLERS(float, fmt_float)
  12299. TYPE_HANDLERS(bool, fmt_bool)
  12300. TYPE_HANDLERS(int32_t, fmt_int64)
  12301. TYPE_HANDLERS(uint32_t, fmt_int64)
  12302. TYPE_HANDLERS(int64_t, fmt_int64)
  12303. TYPE_HANDLERS(uint64_t, fmt_uint64)
  12304. /* double and float are not allowed to be map keys. */
  12305. TYPE_HANDLERS_MAPKEY(bool, fmt_bool)
  12306. TYPE_HANDLERS_MAPKEY(int32_t, fmt_int64)
  12307. TYPE_HANDLERS_MAPKEY(uint32_t, fmt_int64)
  12308. TYPE_HANDLERS_MAPKEY(int64_t, fmt_int64)
  12309. TYPE_HANDLERS_MAPKEY(uint64_t, fmt_uint64)
  12310. #undef TYPE_HANDLERS
  12311. #undef TYPE_HANDLERS_MAPKEY
  12312. typedef struct {
  12313. void *keyname;
  12314. const upb_enumdef *enumdef;
  12315. } EnumHandlerData;
  12316. static bool scalar_enum(void *closure, const void *handler_data,
  12317. int32_t val) {
  12318. const EnumHandlerData *hd = handler_data;
  12319. upb_json_printer *p = closure;
  12320. const char *symbolic_name;
  12321. CHK(putkey(closure, hd->keyname));
  12322. symbolic_name = upb_enumdef_iton(hd->enumdef, val);
  12323. if (symbolic_name) {
  12324. print_data(p, "\"", 1);
  12325. putstring(p, symbolic_name, strlen(symbolic_name));
  12326. print_data(p, "\"", 1);
  12327. } else {
  12328. putint32_t(closure, NULL, val);
  12329. }
  12330. return true;
  12331. }
  12332. static void print_enum_symbolic_name(upb_json_printer *p,
  12333. const upb_enumdef *def,
  12334. int32_t val) {
  12335. const char *symbolic_name = upb_enumdef_iton(def, val);
  12336. if (symbolic_name) {
  12337. print_data(p, "\"", 1);
  12338. putstring(p, symbolic_name, strlen(symbolic_name));
  12339. print_data(p, "\"", 1);
  12340. } else {
  12341. putint32_t(p, NULL, val);
  12342. }
  12343. }
  12344. static bool repeated_enum(void *closure, const void *handler_data,
  12345. int32_t val) {
  12346. const EnumHandlerData *hd = handler_data;
  12347. upb_json_printer *p = closure;
  12348. print_comma(p);
  12349. print_enum_symbolic_name(p, hd->enumdef, val);
  12350. return true;
  12351. }
  12352. static bool mapvalue_enum(void *closure, const void *handler_data,
  12353. int32_t val) {
  12354. const EnumHandlerData *hd = handler_data;
  12355. upb_json_printer *p = closure;
  12356. print_enum_symbolic_name(p, hd->enumdef, val);
  12357. return true;
  12358. }
  12359. static void *scalar_startsubmsg(void *closure, const void *handler_data) {
  12360. return putkey(closure, handler_data) ? closure : UPB_BREAK;
  12361. }
  12362. static void *repeated_startsubmsg(void *closure, const void *handler_data) {
  12363. upb_json_printer *p = closure;
  12364. UPB_UNUSED(handler_data);
  12365. print_comma(p);
  12366. return closure;
  12367. }
  12368. static void start_frame(upb_json_printer *p) {
  12369. p->depth_++;
  12370. p->first_elem_[p->depth_] = true;
  12371. print_data(p, "{", 1);
  12372. }
  12373. static void end_frame(upb_json_printer *p) {
  12374. print_data(p, "}", 1);
  12375. p->depth_--;
  12376. }
  12377. static bool printer_startmsg(void *closure, const void *handler_data) {
  12378. upb_json_printer *p = closure;
  12379. UPB_UNUSED(handler_data);
  12380. if (p->depth_ == 0) {
  12381. upb_bytessink_start(p->output_, 0, &p->subc_);
  12382. }
  12383. start_frame(p);
  12384. return true;
  12385. }
  12386. static bool printer_endmsg(void *closure, const void *handler_data, upb_status *s) {
  12387. upb_json_printer *p = closure;
  12388. UPB_UNUSED(handler_data);
  12389. UPB_UNUSED(s);
  12390. end_frame(p);
  12391. if (p->depth_ == 0) {
  12392. upb_bytessink_end(p->output_);
  12393. }
  12394. return true;
  12395. }
  12396. static void *startseq(void *closure, const void *handler_data) {
  12397. upb_json_printer *p = closure;
  12398. CHK(putkey(closure, handler_data));
  12399. p->depth_++;
  12400. p->first_elem_[p->depth_] = true;
  12401. print_data(p, "[", 1);
  12402. return closure;
  12403. }
  12404. static bool endseq(void *closure, const void *handler_data) {
  12405. upb_json_printer *p = closure;
  12406. UPB_UNUSED(handler_data);
  12407. print_data(p, "]", 1);
  12408. p->depth_--;
  12409. return true;
  12410. }
  12411. static void *startmap(void *closure, const void *handler_data) {
  12412. upb_json_printer *p = closure;
  12413. CHK(putkey(closure, handler_data));
  12414. p->depth_++;
  12415. p->first_elem_[p->depth_] = true;
  12416. print_data(p, "{", 1);
  12417. return closure;
  12418. }
  12419. static bool endmap(void *closure, const void *handler_data) {
  12420. upb_json_printer *p = closure;
  12421. UPB_UNUSED(handler_data);
  12422. print_data(p, "}", 1);
  12423. p->depth_--;
  12424. return true;
  12425. }
  12426. static size_t putstr(void *closure, const void *handler_data, const char *str,
  12427. size_t len, const upb_bufhandle *handle) {
  12428. upb_json_printer *p = closure;
  12429. UPB_UNUSED(handler_data);
  12430. UPB_UNUSED(handle);
  12431. putstring(p, str, len);
  12432. return len;
  12433. }
  12434. /* This has to Base64 encode the bytes, because JSON has no "bytes" type. */
  12435. static size_t putbytes(void *closure, const void *handler_data, const char *str,
  12436. size_t len, const upb_bufhandle *handle) {
  12437. upb_json_printer *p = closure;
  12438. /* This is the regular base64, not the "web-safe" version. */
  12439. static const char base64[] =
  12440. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  12441. /* Base64-encode. */
  12442. char data[16000];
  12443. const char *limit = data + sizeof(data);
  12444. const unsigned char *from = (const unsigned char*)str;
  12445. char *to = data;
  12446. size_t remaining = len;
  12447. size_t bytes;
  12448. UPB_UNUSED(handler_data);
  12449. UPB_UNUSED(handle);
  12450. while (remaining > 2) {
  12451. /* TODO(haberman): handle encoded lengths > sizeof(data) */
  12452. UPB_ASSERT((limit - to) >= 4);
  12453. to[0] = base64[from[0] >> 2];
  12454. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  12455. to[2] = base64[((from[1] & 0xf) << 2) | (from[2] >> 6)];
  12456. to[3] = base64[from[2] & 0x3f];
  12457. remaining -= 3;
  12458. to += 4;
  12459. from += 3;
  12460. }
  12461. switch (remaining) {
  12462. case 2:
  12463. to[0] = base64[from[0] >> 2];
  12464. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  12465. to[2] = base64[(from[1] & 0xf) << 2];
  12466. to[3] = '=';
  12467. to += 4;
  12468. from += 2;
  12469. break;
  12470. case 1:
  12471. to[0] = base64[from[0] >> 2];
  12472. to[1] = base64[((from[0] & 0x3) << 4)];
  12473. to[2] = '=';
  12474. to[3] = '=';
  12475. to += 4;
  12476. from += 1;
  12477. break;
  12478. }
  12479. bytes = to - data;
  12480. print_data(p, "\"", 1);
  12481. putstring(p, data, bytes);
  12482. print_data(p, "\"", 1);
  12483. return len;
  12484. }
  12485. static void *scalar_startstr(void *closure, const void *handler_data,
  12486. size_t size_hint) {
  12487. upb_json_printer *p = closure;
  12488. UPB_UNUSED(handler_data);
  12489. UPB_UNUSED(size_hint);
  12490. CHK(putkey(closure, handler_data));
  12491. print_data(p, "\"", 1);
  12492. return p;
  12493. }
  12494. static size_t scalar_str(void *closure, const void *handler_data,
  12495. const char *str, size_t len,
  12496. const upb_bufhandle *handle) {
  12497. CHK(putstr(closure, handler_data, str, len, handle));
  12498. return len;
  12499. }
  12500. static bool scalar_endstr(void *closure, const void *handler_data) {
  12501. upb_json_printer *p = closure;
  12502. UPB_UNUSED(handler_data);
  12503. print_data(p, "\"", 1);
  12504. return true;
  12505. }
  12506. static void *repeated_startstr(void *closure, const void *handler_data,
  12507. size_t size_hint) {
  12508. upb_json_printer *p = closure;
  12509. UPB_UNUSED(handler_data);
  12510. UPB_UNUSED(size_hint);
  12511. print_comma(p);
  12512. print_data(p, "\"", 1);
  12513. return p;
  12514. }
  12515. static size_t repeated_str(void *closure, const void *handler_data,
  12516. const char *str, size_t len,
  12517. const upb_bufhandle *handle) {
  12518. CHK(putstr(closure, handler_data, str, len, handle));
  12519. return len;
  12520. }
  12521. static bool repeated_endstr(void *closure, const void *handler_data) {
  12522. upb_json_printer *p = closure;
  12523. UPB_UNUSED(handler_data);
  12524. print_data(p, "\"", 1);
  12525. return true;
  12526. }
  12527. static void *mapkeyval_startstr(void *closure, const void *handler_data,
  12528. size_t size_hint) {
  12529. upb_json_printer *p = closure;
  12530. UPB_UNUSED(handler_data);
  12531. UPB_UNUSED(size_hint);
  12532. print_data(p, "\"", 1);
  12533. return p;
  12534. }
  12535. static size_t mapkey_str(void *closure, const void *handler_data,
  12536. const char *str, size_t len,
  12537. const upb_bufhandle *handle) {
  12538. CHK(putstr(closure, handler_data, str, len, handle));
  12539. return len;
  12540. }
  12541. static bool mapkey_endstr(void *closure, const void *handler_data) {
  12542. upb_json_printer *p = closure;
  12543. UPB_UNUSED(handler_data);
  12544. print_data(p, "\":", 2);
  12545. return true;
  12546. }
  12547. static bool mapvalue_endstr(void *closure, const void *handler_data) {
  12548. upb_json_printer *p = closure;
  12549. UPB_UNUSED(handler_data);
  12550. print_data(p, "\"", 1);
  12551. return true;
  12552. }
  12553. static size_t scalar_bytes(void *closure, const void *handler_data,
  12554. const char *str, size_t len,
  12555. const upb_bufhandle *handle) {
  12556. CHK(putkey(closure, handler_data));
  12557. CHK(putbytes(closure, handler_data, str, len, handle));
  12558. return len;
  12559. }
  12560. static size_t repeated_bytes(void *closure, const void *handler_data,
  12561. const char *str, size_t len,
  12562. const upb_bufhandle *handle) {
  12563. upb_json_printer *p = closure;
  12564. print_comma(p);
  12565. CHK(putbytes(closure, handler_data, str, len, handle));
  12566. return len;
  12567. }
  12568. static size_t mapkey_bytes(void *closure, const void *handler_data,
  12569. const char *str, size_t len,
  12570. const upb_bufhandle *handle) {
  12571. upb_json_printer *p = closure;
  12572. CHK(putbytes(closure, handler_data, str, len, handle));
  12573. print_data(p, ":", 1);
  12574. return len;
  12575. }
  12576. static void set_enum_hd(upb_handlers *h,
  12577. const upb_fielddef *f,
  12578. bool preserve_fieldnames,
  12579. upb_handlerattr *attr) {
  12580. EnumHandlerData *hd = upb_gmalloc(sizeof(EnumHandlerData));
  12581. hd->enumdef = (const upb_enumdef *)upb_fielddef_subdef(f);
  12582. hd->keyname = newstrpc(h, f, preserve_fieldnames);
  12583. upb_handlers_addcleanup(h, hd, upb_gfree);
  12584. upb_handlerattr_sethandlerdata(attr, hd);
  12585. }
  12586. /* Set up handlers for a mapentry submessage (i.e., an individual key/value pair
  12587. * in a map).
  12588. *
  12589. * TODO: Handle missing key, missing value, out-of-order key/value, or repeated
  12590. * key or value cases properly. The right way to do this is to allocate a
  12591. * temporary structure at the start of a mapentry submessage, store key and
  12592. * value data in it as key and value handlers are called, and then print the
  12593. * key/value pair once at the end of the submessage. If we don't do this, we
  12594. * should at least detect the case and throw an error. However, so far all of
  12595. * our sources that emit mapentry messages do so canonically (with one key
  12596. * field, and then one value field), so this is not a pressing concern at the
  12597. * moment. */
  12598. void printer_sethandlers_mapentry(const void *closure, bool preserve_fieldnames,
  12599. upb_handlers *h) {
  12600. const upb_msgdef *md = upb_handlers_msgdef(h);
  12601. /* A mapentry message is printed simply as '"key": value'. Rather than
  12602. * special-case key and value for every type below, we just handle both
  12603. * fields explicitly here. */
  12604. const upb_fielddef* key_field = upb_msgdef_itof(md, UPB_MAPENTRY_KEY);
  12605. const upb_fielddef* value_field = upb_msgdef_itof(md, UPB_MAPENTRY_VALUE);
  12606. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  12607. UPB_UNUSED(closure);
  12608. switch (upb_fielddef_type(key_field)) {
  12609. case UPB_TYPE_INT32:
  12610. upb_handlers_setint32(h, key_field, putmapkey_int32_t, &empty_attr);
  12611. break;
  12612. case UPB_TYPE_INT64:
  12613. upb_handlers_setint64(h, key_field, putmapkey_int64_t, &empty_attr);
  12614. break;
  12615. case UPB_TYPE_UINT32:
  12616. upb_handlers_setuint32(h, key_field, putmapkey_uint32_t, &empty_attr);
  12617. break;
  12618. case UPB_TYPE_UINT64:
  12619. upb_handlers_setuint64(h, key_field, putmapkey_uint64_t, &empty_attr);
  12620. break;
  12621. case UPB_TYPE_BOOL:
  12622. upb_handlers_setbool(h, key_field, putmapkey_bool, &empty_attr);
  12623. break;
  12624. case UPB_TYPE_STRING:
  12625. upb_handlers_setstartstr(h, key_field, mapkeyval_startstr, &empty_attr);
  12626. upb_handlers_setstring(h, key_field, mapkey_str, &empty_attr);
  12627. upb_handlers_setendstr(h, key_field, mapkey_endstr, &empty_attr);
  12628. break;
  12629. case UPB_TYPE_BYTES:
  12630. upb_handlers_setstring(h, key_field, mapkey_bytes, &empty_attr);
  12631. break;
  12632. default:
  12633. UPB_ASSERT(false);
  12634. break;
  12635. }
  12636. switch (upb_fielddef_type(value_field)) {
  12637. case UPB_TYPE_INT32:
  12638. upb_handlers_setint32(h, value_field, putint32_t, &empty_attr);
  12639. break;
  12640. case UPB_TYPE_INT64:
  12641. upb_handlers_setint64(h, value_field, putint64_t, &empty_attr);
  12642. break;
  12643. case UPB_TYPE_UINT32:
  12644. upb_handlers_setuint32(h, value_field, putuint32_t, &empty_attr);
  12645. break;
  12646. case UPB_TYPE_UINT64:
  12647. upb_handlers_setuint64(h, value_field, putuint64_t, &empty_attr);
  12648. break;
  12649. case UPB_TYPE_BOOL:
  12650. upb_handlers_setbool(h, value_field, putbool, &empty_attr);
  12651. break;
  12652. case UPB_TYPE_FLOAT:
  12653. upb_handlers_setfloat(h, value_field, putfloat, &empty_attr);
  12654. break;
  12655. case UPB_TYPE_DOUBLE:
  12656. upb_handlers_setdouble(h, value_field, putdouble, &empty_attr);
  12657. break;
  12658. case UPB_TYPE_STRING:
  12659. upb_handlers_setstartstr(h, value_field, mapkeyval_startstr, &empty_attr);
  12660. upb_handlers_setstring(h, value_field, putstr, &empty_attr);
  12661. upb_handlers_setendstr(h, value_field, mapvalue_endstr, &empty_attr);
  12662. break;
  12663. case UPB_TYPE_BYTES:
  12664. upb_handlers_setstring(h, value_field, putbytes, &empty_attr);
  12665. break;
  12666. case UPB_TYPE_ENUM: {
  12667. upb_handlerattr enum_attr = UPB_HANDLERATTR_INITIALIZER;
  12668. set_enum_hd(h, value_field, preserve_fieldnames, &enum_attr);
  12669. upb_handlers_setint32(h, value_field, mapvalue_enum, &enum_attr);
  12670. upb_handlerattr_uninit(&enum_attr);
  12671. break;
  12672. }
  12673. case UPB_TYPE_MESSAGE:
  12674. /* No handler necessary -- the submsg handlers will print the message
  12675. * as appropriate. */
  12676. break;
  12677. }
  12678. upb_handlerattr_uninit(&empty_attr);
  12679. }
  12680. void printer_sethandlers(const void *closure, upb_handlers *h) {
  12681. const upb_msgdef *md = upb_handlers_msgdef(h);
  12682. bool is_mapentry = upb_msgdef_mapentry(md);
  12683. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  12684. upb_msg_field_iter i;
  12685. const bool *preserve_fieldnames_ptr = closure;
  12686. const bool preserve_fieldnames = *preserve_fieldnames_ptr;
  12687. if (is_mapentry) {
  12688. /* mapentry messages are sufficiently different that we handle them
  12689. * separately. */
  12690. printer_sethandlers_mapentry(closure, preserve_fieldnames, h);
  12691. return;
  12692. }
  12693. upb_handlers_setstartmsg(h, printer_startmsg, &empty_attr);
  12694. upb_handlers_setendmsg(h, printer_endmsg, &empty_attr);
  12695. #define TYPE(type, name, ctype) \
  12696. case type: \
  12697. if (upb_fielddef_isseq(f)) { \
  12698. upb_handlers_set##name(h, f, repeated_##ctype, &empty_attr); \
  12699. } else { \
  12700. upb_handlers_set##name(h, f, scalar_##ctype, &name_attr); \
  12701. } \
  12702. break;
  12703. upb_msg_field_begin(&i, md);
  12704. for(; !upb_msg_field_done(&i); upb_msg_field_next(&i)) {
  12705. const upb_fielddef *f = upb_msg_iter_field(&i);
  12706. upb_handlerattr name_attr = UPB_HANDLERATTR_INITIALIZER;
  12707. upb_handlerattr_sethandlerdata(&name_attr,
  12708. newstrpc(h, f, preserve_fieldnames));
  12709. if (upb_fielddef_ismap(f)) {
  12710. upb_handlers_setstartseq(h, f, startmap, &name_attr);
  12711. upb_handlers_setendseq(h, f, endmap, &name_attr);
  12712. } else if (upb_fielddef_isseq(f)) {
  12713. upb_handlers_setstartseq(h, f, startseq, &name_attr);
  12714. upb_handlers_setendseq(h, f, endseq, &empty_attr);
  12715. }
  12716. switch (upb_fielddef_type(f)) {
  12717. TYPE(UPB_TYPE_FLOAT, float, float);
  12718. TYPE(UPB_TYPE_DOUBLE, double, double);
  12719. TYPE(UPB_TYPE_BOOL, bool, bool);
  12720. TYPE(UPB_TYPE_INT32, int32, int32_t);
  12721. TYPE(UPB_TYPE_UINT32, uint32, uint32_t);
  12722. TYPE(UPB_TYPE_INT64, int64, int64_t);
  12723. TYPE(UPB_TYPE_UINT64, uint64, uint64_t);
  12724. case UPB_TYPE_ENUM: {
  12725. /* For now, we always emit symbolic names for enums. We may want an
  12726. * option later to control this behavior, but we will wait for a real
  12727. * need first. */
  12728. upb_handlerattr enum_attr = UPB_HANDLERATTR_INITIALIZER;
  12729. set_enum_hd(h, f, preserve_fieldnames, &enum_attr);
  12730. if (upb_fielddef_isseq(f)) {
  12731. upb_handlers_setint32(h, f, repeated_enum, &enum_attr);
  12732. } else {
  12733. upb_handlers_setint32(h, f, scalar_enum, &enum_attr);
  12734. }
  12735. upb_handlerattr_uninit(&enum_attr);
  12736. break;
  12737. }
  12738. case UPB_TYPE_STRING:
  12739. if (upb_fielddef_isseq(f)) {
  12740. upb_handlers_setstartstr(h, f, repeated_startstr, &empty_attr);
  12741. upb_handlers_setstring(h, f, repeated_str, &empty_attr);
  12742. upb_handlers_setendstr(h, f, repeated_endstr, &empty_attr);
  12743. } else {
  12744. upb_handlers_setstartstr(h, f, scalar_startstr, &name_attr);
  12745. upb_handlers_setstring(h, f, scalar_str, &empty_attr);
  12746. upb_handlers_setendstr(h, f, scalar_endstr, &empty_attr);
  12747. }
  12748. break;
  12749. case UPB_TYPE_BYTES:
  12750. /* XXX: this doesn't support strings that span buffers yet. The base64
  12751. * encoder will need to be made resumable for this to work properly. */
  12752. if (upb_fielddef_isseq(f)) {
  12753. upb_handlers_setstring(h, f, repeated_bytes, &empty_attr);
  12754. } else {
  12755. upb_handlers_setstring(h, f, scalar_bytes, &name_attr);
  12756. }
  12757. break;
  12758. case UPB_TYPE_MESSAGE:
  12759. if (upb_fielddef_isseq(f)) {
  12760. upb_handlers_setstartsubmsg(h, f, repeated_startsubmsg, &name_attr);
  12761. } else {
  12762. upb_handlers_setstartsubmsg(h, f, scalar_startsubmsg, &name_attr);
  12763. }
  12764. break;
  12765. }
  12766. upb_handlerattr_uninit(&name_attr);
  12767. }
  12768. upb_handlerattr_uninit(&empty_attr);
  12769. #undef TYPE
  12770. }
  12771. static void json_printer_reset(upb_json_printer *p) {
  12772. p->depth_ = 0;
  12773. }
  12774. /* Public API *****************************************************************/
  12775. upb_json_printer *upb_json_printer_create(upb_env *e, const upb_handlers *h,
  12776. upb_bytessink *output) {
  12777. #ifndef NDEBUG
  12778. size_t size_before = upb_env_bytesallocated(e);
  12779. #endif
  12780. upb_json_printer *p = upb_env_malloc(e, sizeof(upb_json_printer));
  12781. if (!p) return NULL;
  12782. p->output_ = output;
  12783. json_printer_reset(p);
  12784. upb_sink_reset(&p->input_, h, p);
  12785. /* If this fails, increase the value in printer.h. */
  12786. UPB_ASSERT_DEBUGVAR(upb_env_bytesallocated(e) - size_before <=
  12787. UPB_JSON_PRINTER_SIZE);
  12788. return p;
  12789. }
  12790. upb_sink *upb_json_printer_input(upb_json_printer *p) {
  12791. return &p->input_;
  12792. }
  12793. const upb_handlers *upb_json_printer_newhandlers(const upb_msgdef *md,
  12794. bool preserve_fieldnames,
  12795. const void *owner) {
  12796. return upb_handlers_newfrozen(
  12797. md, owner, printer_sethandlers, &preserve_fieldnames);
  12798. }