upb.c 455 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911
  1. // Amalgamated source file
  2. #include "upb.h"
  3. #include <ctype.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. typedef struct {
  7. size_t len;
  8. char str[1]; /* Null-terminated string data follows. */
  9. } str_t;
  10. static str_t *newstr(const char *data, size_t len) {
  11. str_t *ret = upb_gmalloc(sizeof(*ret) + len);
  12. if (!ret) return NULL;
  13. ret->len = len;
  14. memcpy(ret->str, data, len);
  15. ret->str[len] = '\0';
  16. return ret;
  17. }
  18. static void freestr(str_t *s) { upb_gfree(s); }
  19. /* isalpha() etc. from <ctype.h> are locale-dependent, which we don't want. */
  20. static bool upb_isbetween(char c, char low, char high) {
  21. return c >= low && c <= high;
  22. }
  23. static bool upb_isletter(char c) {
  24. return upb_isbetween(c, 'A', 'Z') || upb_isbetween(c, 'a', 'z') || c == '_';
  25. }
  26. static bool upb_isalphanum(char c) {
  27. return upb_isletter(c) || upb_isbetween(c, '0', '9');
  28. }
  29. static bool upb_isident(const char *str, size_t len, bool full, upb_status *s) {
  30. bool start = true;
  31. size_t i;
  32. for (i = 0; i < len; i++) {
  33. char c = str[i];
  34. if (c == '.') {
  35. if (start || !full) {
  36. upb_status_seterrf(s, "invalid name: unexpected '.' (%s)", str);
  37. return false;
  38. }
  39. start = true;
  40. } else if (start) {
  41. if (!upb_isletter(c)) {
  42. upb_status_seterrf(
  43. s, "invalid name: path components must start with a letter (%s)",
  44. str);
  45. return false;
  46. }
  47. start = false;
  48. } else {
  49. if (!upb_isalphanum(c)) {
  50. upb_status_seterrf(s, "invalid name: non-alphanumeric character (%s)",
  51. str);
  52. return false;
  53. }
  54. }
  55. }
  56. return !start;
  57. }
  58. static bool upb_isoneof(const upb_refcounted *def) {
  59. return def->vtbl == &upb_oneofdef_vtbl;
  60. }
  61. static bool upb_isfield(const upb_refcounted *def) {
  62. return def->vtbl == &upb_fielddef_vtbl;
  63. }
  64. static const upb_oneofdef *upb_trygetoneof(const upb_refcounted *def) {
  65. return upb_isoneof(def) ? (const upb_oneofdef*)def : NULL;
  66. }
  67. static const upb_fielddef *upb_trygetfield(const upb_refcounted *def) {
  68. return upb_isfield(def) ? (const upb_fielddef*)def : NULL;
  69. }
  70. /* upb_def ********************************************************************/
  71. upb_deftype_t upb_def_type(const upb_def *d) { return d->type; }
  72. const char *upb_def_fullname(const upb_def *d) { return d->fullname; }
  73. const char *upb_def_name(const upb_def *d) {
  74. const char *p;
  75. if (d->fullname == NULL) {
  76. return NULL;
  77. } else if ((p = strrchr(d->fullname, '.')) == NULL) {
  78. /* No '.' in the name, return the full string. */
  79. return d->fullname;
  80. } else {
  81. /* Return one past the last '.'. */
  82. return p + 1;
  83. }
  84. }
  85. bool upb_def_setfullname(upb_def *def, const char *fullname, upb_status *s) {
  86. UPB_ASSERT(!upb_def_isfrozen(def));
  87. if (!upb_isident(fullname, strlen(fullname), true, s)) {
  88. return false;
  89. }
  90. fullname = upb_gstrdup(fullname);
  91. if (!fullname) {
  92. upb_upberr_setoom(s);
  93. return false;
  94. }
  95. upb_gfree((void*)def->fullname);
  96. def->fullname = fullname;
  97. return true;
  98. }
  99. const upb_filedef *upb_def_file(const upb_def *d) { return d->file; }
  100. static bool upb_def_init(upb_def *def, upb_deftype_t type,
  101. const struct upb_refcounted_vtbl *vtbl,
  102. const void *owner) {
  103. if (!upb_refcounted_init(upb_def_upcast_mutable(def), vtbl, owner)) return false;
  104. def->type = type;
  105. def->fullname = NULL;
  106. def->came_from_user = false;
  107. def->file = NULL;
  108. return true;
  109. }
  110. static void upb_def_uninit(upb_def *def) {
  111. upb_gfree((void*)def->fullname);
  112. }
  113. static const char *msgdef_name(const upb_msgdef *m) {
  114. const char *name = upb_def_fullname(upb_msgdef_upcast(m));
  115. return name ? name : "(anonymous)";
  116. }
  117. static bool upb_validate_field(upb_fielddef *f, upb_status *s) {
  118. if (upb_fielddef_name(f) == NULL || upb_fielddef_number(f) == 0) {
  119. upb_status_seterrmsg(s, "fielddef must have name and number set");
  120. return false;
  121. }
  122. if (!f->type_is_set_) {
  123. upb_status_seterrmsg(s, "fielddef type was not initialized");
  124. return false;
  125. }
  126. if (upb_fielddef_lazy(f) &&
  127. upb_fielddef_descriptortype(f) != UPB_DESCRIPTOR_TYPE_MESSAGE) {
  128. upb_status_seterrmsg(s,
  129. "only length-delimited submessage fields may be lazy");
  130. return false;
  131. }
  132. if (upb_fielddef_hassubdef(f)) {
  133. const upb_def *subdef;
  134. if (f->subdef_is_symbolic) {
  135. upb_status_seterrf(s, "field '%s.%s' has not been resolved",
  136. msgdef_name(f->msg.def), upb_fielddef_name(f));
  137. return false;
  138. }
  139. subdef = upb_fielddef_subdef(f);
  140. if (subdef == NULL) {
  141. upb_status_seterrf(s, "field %s.%s is missing required subdef",
  142. msgdef_name(f->msg.def), upb_fielddef_name(f));
  143. return false;
  144. }
  145. if (!upb_def_isfrozen(subdef) && !subdef->came_from_user) {
  146. upb_status_seterrf(s,
  147. "subdef of field %s.%s is not frozen or being frozen",
  148. msgdef_name(f->msg.def), upb_fielddef_name(f));
  149. return false;
  150. }
  151. }
  152. if (upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  153. bool has_default_name = upb_fielddef_enumhasdefaultstr(f);
  154. bool has_default_number = upb_fielddef_enumhasdefaultint32(f);
  155. /* Previously verified by upb_validate_enumdef(). */
  156. UPB_ASSERT(upb_enumdef_numvals(upb_fielddef_enumsubdef(f)) > 0);
  157. /* We've already validated that we have an associated enumdef and that it
  158. * has at least one member, so at least one of these should be true.
  159. * Because if the user didn't set anything, we'll pick up the enum's
  160. * default, but if the user *did* set something we should at least pick up
  161. * the one they set (int32 or string). */
  162. UPB_ASSERT(has_default_name || has_default_number);
  163. if (!has_default_name) {
  164. upb_status_seterrf(s,
  165. "enum default for field %s.%s (%d) is not in the enum",
  166. msgdef_name(f->msg.def), upb_fielddef_name(f),
  167. upb_fielddef_defaultint32(f));
  168. return false;
  169. }
  170. if (!has_default_number) {
  171. upb_status_seterrf(s,
  172. "enum default for field %s.%s (%s) is not in the enum",
  173. msgdef_name(f->msg.def), upb_fielddef_name(f),
  174. upb_fielddef_defaultstr(f, NULL));
  175. return false;
  176. }
  177. /* Lift the effective numeric default into the field's default slot, in case
  178. * we were only getting it "by reference" from the enumdef. */
  179. upb_fielddef_setdefaultint32(f, upb_fielddef_defaultint32(f));
  180. }
  181. /* Ensure that MapEntry submessages only appear as repeated fields, not
  182. * optional/required (singular) fields. */
  183. if (upb_fielddef_type(f) == UPB_TYPE_MESSAGE &&
  184. upb_fielddef_msgsubdef(f) != NULL) {
  185. const upb_msgdef *subdef = upb_fielddef_msgsubdef(f);
  186. if (upb_msgdef_mapentry(subdef) && !upb_fielddef_isseq(f)) {
  187. upb_status_seterrf(s,
  188. "Field %s refers to mapentry message but is not "
  189. "a repeated field",
  190. upb_fielddef_name(f) ? upb_fielddef_name(f) :
  191. "(unnamed)");
  192. return false;
  193. }
  194. }
  195. return true;
  196. }
  197. static bool upb_validate_enumdef(const upb_enumdef *e, upb_status *s) {
  198. if (upb_enumdef_numvals(e) == 0) {
  199. upb_status_seterrf(s, "enum %s has no members (must have at least one)",
  200. upb_enumdef_fullname(e));
  201. return false;
  202. }
  203. return true;
  204. }
  205. /* All submessage fields are lower than all other fields.
  206. * Secondly, fields are increasing in order. */
  207. uint32_t field_rank(const upb_fielddef *f) {
  208. uint32_t ret = upb_fielddef_number(f);
  209. const uint32_t high_bit = 1 << 30;
  210. UPB_ASSERT(ret < high_bit);
  211. if (!upb_fielddef_issubmsg(f))
  212. ret |= high_bit;
  213. return ret;
  214. }
  215. int cmp_fields(const void *p1, const void *p2) {
  216. const upb_fielddef *f1 = *(upb_fielddef*const*)p1;
  217. const upb_fielddef *f2 = *(upb_fielddef*const*)p2;
  218. return field_rank(f1) - field_rank(f2);
  219. }
  220. static bool assign_msg_indices(upb_msgdef *m, upb_status *s) {
  221. /* Sort fields. upb internally relies on UPB_TYPE_MESSAGE fields having the
  222. * lowest indexes, but we do not publicly guarantee this. */
  223. upb_msg_field_iter j;
  224. upb_msg_oneof_iter k;
  225. int i;
  226. uint32_t selector;
  227. int n = upb_msgdef_numfields(m);
  228. upb_fielddef **fields;
  229. if (n == 0) {
  230. m->selector_count = UPB_STATIC_SELECTOR_COUNT;
  231. m->submsg_field_count = 0;
  232. return true;
  233. }
  234. fields = upb_gmalloc(n * sizeof(*fields));
  235. if (!fields) {
  236. upb_upberr_setoom(s);
  237. return false;
  238. }
  239. m->submsg_field_count = 0;
  240. for(i = 0, upb_msg_field_begin(&j, m);
  241. !upb_msg_field_done(&j);
  242. upb_msg_field_next(&j), i++) {
  243. upb_fielddef *f = upb_msg_iter_field(&j);
  244. UPB_ASSERT(f->msg.def == m);
  245. if (!upb_validate_field(f, s)) {
  246. upb_gfree(fields);
  247. return false;
  248. }
  249. if (upb_fielddef_issubmsg(f)) {
  250. m->submsg_field_count++;
  251. }
  252. fields[i] = f;
  253. }
  254. qsort(fields, n, sizeof(*fields), cmp_fields);
  255. selector = UPB_STATIC_SELECTOR_COUNT + m->submsg_field_count;
  256. for (i = 0; i < n; i++) {
  257. upb_fielddef *f = fields[i];
  258. f->index_ = i;
  259. f->selector_base = selector + upb_handlers_selectorbaseoffset(f);
  260. selector += upb_handlers_selectorcount(f);
  261. }
  262. m->selector_count = selector;
  263. #ifndef NDEBUG
  264. {
  265. /* Verify that all selectors for the message are distinct. */
  266. #define TRY(type) \
  267. if (upb_handlers_getselector(f, type, &sel)) upb_inttable_insert(&t, sel, v);
  268. upb_inttable t;
  269. upb_value v;
  270. upb_selector_t sel;
  271. upb_inttable_init(&t, UPB_CTYPE_BOOL);
  272. v = upb_value_bool(true);
  273. upb_inttable_insert(&t, UPB_STARTMSG_SELECTOR, v);
  274. upb_inttable_insert(&t, UPB_ENDMSG_SELECTOR, v);
  275. for(upb_msg_field_begin(&j, m);
  276. !upb_msg_field_done(&j);
  277. upb_msg_field_next(&j)) {
  278. upb_fielddef *f = upb_msg_iter_field(&j);
  279. /* These calls will assert-fail in upb_table if the value already
  280. * exists. */
  281. TRY(UPB_HANDLER_INT32);
  282. TRY(UPB_HANDLER_INT64)
  283. TRY(UPB_HANDLER_UINT32)
  284. TRY(UPB_HANDLER_UINT64)
  285. TRY(UPB_HANDLER_FLOAT)
  286. TRY(UPB_HANDLER_DOUBLE)
  287. TRY(UPB_HANDLER_BOOL)
  288. TRY(UPB_HANDLER_STARTSTR)
  289. TRY(UPB_HANDLER_STRING)
  290. TRY(UPB_HANDLER_ENDSTR)
  291. TRY(UPB_HANDLER_STARTSUBMSG)
  292. TRY(UPB_HANDLER_ENDSUBMSG)
  293. TRY(UPB_HANDLER_STARTSEQ)
  294. TRY(UPB_HANDLER_ENDSEQ)
  295. }
  296. upb_inttable_uninit(&t);
  297. }
  298. #undef TRY
  299. #endif
  300. for(upb_msg_oneof_begin(&k, m), i = 0;
  301. !upb_msg_oneof_done(&k);
  302. upb_msg_oneof_next(&k), i++) {
  303. upb_oneofdef *o = upb_msg_iter_oneof(&k);
  304. o->index = i;
  305. }
  306. upb_gfree(fields);
  307. return true;
  308. }
  309. bool _upb_def_validate(upb_def *const*defs, size_t n, upb_status *s) {
  310. size_t i;
  311. /* First perform validation, in two passes so we can check that we have a
  312. * transitive closure without needing to search. */
  313. for (i = 0; i < n; i++) {
  314. upb_def *def = defs[i];
  315. if (upb_def_isfrozen(def)) {
  316. /* Could relax this requirement if it's annoying. */
  317. upb_status_seterrmsg(s, "def is already frozen");
  318. goto err;
  319. } else if (def->type == UPB_DEF_FIELD) {
  320. upb_status_seterrmsg(s, "standalone fielddefs can not be frozen");
  321. goto err;
  322. } else {
  323. /* Set now to detect transitive closure in the second pass. */
  324. def->came_from_user = true;
  325. if (def->type == UPB_DEF_ENUM &&
  326. !upb_validate_enumdef(upb_dyncast_enumdef(def), s)) {
  327. goto err;
  328. }
  329. }
  330. }
  331. /* Second pass of validation. Also assign selector bases and indexes, and
  332. * compact tables. */
  333. for (i = 0; i < n; i++) {
  334. upb_def *def = defs[i];
  335. upb_msgdef *m = upb_dyncast_msgdef_mutable(def);
  336. upb_enumdef *e = upb_dyncast_enumdef_mutable(def);
  337. if (m) {
  338. upb_inttable_compact(&m->itof);
  339. if (!assign_msg_indices(m, s)) {
  340. goto err;
  341. }
  342. } else if (e) {
  343. upb_inttable_compact(&e->iton);
  344. }
  345. }
  346. return true;
  347. err:
  348. for (i = 0; i < n; i++) {
  349. upb_def *def = defs[i];
  350. def->came_from_user = false;
  351. }
  352. UPB_ASSERT(!(s && upb_ok(s)));
  353. return false;
  354. }
  355. bool upb_def_freeze(upb_def *const* defs, size_t n, upb_status *s) {
  356. /* Def graph contains FieldDefs between each MessageDef, so double the
  357. * limit. */
  358. const size_t maxdepth = UPB_MAX_MESSAGE_DEPTH * 2;
  359. if (!_upb_def_validate(defs, n, s)) {
  360. return false;
  361. }
  362. /* Validation all passed; freeze the objects. */
  363. return upb_refcounted_freeze((upb_refcounted *const*)defs, n, s, maxdepth);
  364. }
  365. /* upb_enumdef ****************************************************************/
  366. static void visitenum(const upb_refcounted *r, upb_refcounted_visit *visit,
  367. void *closure) {
  368. const upb_enumdef *e = (const upb_enumdef*)r;
  369. const upb_def *def = upb_enumdef_upcast(e);
  370. if (upb_def_file(def)) {
  371. visit(r, upb_filedef_upcast(upb_def_file(def)), closure);
  372. }
  373. }
  374. static void freeenum(upb_refcounted *r) {
  375. upb_enumdef *e = (upb_enumdef*)r;
  376. upb_inttable_iter i;
  377. upb_inttable_begin(&i, &e->iton);
  378. for( ; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  379. /* To clean up the upb_gstrdup() from upb_enumdef_addval(). */
  380. upb_gfree(upb_value_getcstr(upb_inttable_iter_value(&i)));
  381. }
  382. upb_strtable_uninit(&e->ntoi);
  383. upb_inttable_uninit(&e->iton);
  384. upb_def_uninit(upb_enumdef_upcast_mutable(e));
  385. upb_gfree(e);
  386. }
  387. const struct upb_refcounted_vtbl upb_enumdef_vtbl = {&visitenum, &freeenum};
  388. upb_enumdef *upb_enumdef_new(const void *owner) {
  389. upb_enumdef *e = upb_gmalloc(sizeof(*e));
  390. if (!e) return NULL;
  391. if (!upb_def_init(upb_enumdef_upcast_mutable(e), UPB_DEF_ENUM,
  392. &upb_enumdef_vtbl, owner)) {
  393. goto err2;
  394. }
  395. if (!upb_strtable_init(&e->ntoi, UPB_CTYPE_INT32)) goto err2;
  396. if (!upb_inttable_init(&e->iton, UPB_CTYPE_CSTR)) goto err1;
  397. return e;
  398. err1:
  399. upb_strtable_uninit(&e->ntoi);
  400. err2:
  401. upb_gfree(e);
  402. return NULL;
  403. }
  404. bool upb_enumdef_freeze(upb_enumdef *e, upb_status *status) {
  405. upb_def *d = upb_enumdef_upcast_mutable(e);
  406. return upb_def_freeze(&d, 1, status);
  407. }
  408. const char *upb_enumdef_fullname(const upb_enumdef *e) {
  409. return upb_def_fullname(upb_enumdef_upcast(e));
  410. }
  411. const char *upb_enumdef_name(const upb_enumdef *e) {
  412. return upb_def_name(upb_enumdef_upcast(e));
  413. }
  414. bool upb_enumdef_setfullname(upb_enumdef *e, const char *fullname,
  415. upb_status *s) {
  416. return upb_def_setfullname(upb_enumdef_upcast_mutable(e), fullname, s);
  417. }
  418. bool upb_enumdef_addval(upb_enumdef *e, const char *name, int32_t num,
  419. upb_status *status) {
  420. char *name2;
  421. if (!upb_isident(name, strlen(name), false, status)) {
  422. return false;
  423. }
  424. if (upb_enumdef_ntoiz(e, name, NULL)) {
  425. upb_status_seterrf(status, "name '%s' is already defined", name);
  426. return false;
  427. }
  428. if (!upb_strtable_insert(&e->ntoi, name, upb_value_int32(num))) {
  429. upb_status_seterrmsg(status, "out of memory");
  430. return false;
  431. }
  432. if (!upb_inttable_lookup(&e->iton, num, NULL)) {
  433. name2 = upb_gstrdup(name);
  434. if (!name2 || !upb_inttable_insert(&e->iton, num, upb_value_cstr(name2))) {
  435. upb_status_seterrmsg(status, "out of memory");
  436. upb_strtable_remove(&e->ntoi, name, NULL);
  437. return false;
  438. }
  439. }
  440. if (upb_enumdef_numvals(e) == 1) {
  441. bool ok = upb_enumdef_setdefault(e, num, NULL);
  442. UPB_ASSERT(ok);
  443. }
  444. return true;
  445. }
  446. int32_t upb_enumdef_default(const upb_enumdef *e) {
  447. UPB_ASSERT(upb_enumdef_iton(e, e->defaultval));
  448. return e->defaultval;
  449. }
  450. bool upb_enumdef_setdefault(upb_enumdef *e, int32_t val, upb_status *s) {
  451. UPB_ASSERT(!upb_enumdef_isfrozen(e));
  452. if (!upb_enumdef_iton(e, val)) {
  453. upb_status_seterrf(s, "number '%d' is not in the enum.", val);
  454. return false;
  455. }
  456. e->defaultval = val;
  457. return true;
  458. }
  459. int upb_enumdef_numvals(const upb_enumdef *e) {
  460. return upb_strtable_count(&e->ntoi);
  461. }
  462. void upb_enum_begin(upb_enum_iter *i, const upb_enumdef *e) {
  463. /* We iterate over the ntoi table, to account for duplicate numbers. */
  464. upb_strtable_begin(i, &e->ntoi);
  465. }
  466. void upb_enum_next(upb_enum_iter *iter) { upb_strtable_next(iter); }
  467. bool upb_enum_done(upb_enum_iter *iter) { return upb_strtable_done(iter); }
  468. bool upb_enumdef_ntoi(const upb_enumdef *def, const char *name,
  469. size_t len, int32_t *num) {
  470. upb_value v;
  471. if (!upb_strtable_lookup2(&def->ntoi, name, len, &v)) {
  472. return false;
  473. }
  474. if (num) *num = upb_value_getint32(v);
  475. return true;
  476. }
  477. const char *upb_enumdef_iton(const upb_enumdef *def, int32_t num) {
  478. upb_value v;
  479. return upb_inttable_lookup32(&def->iton, num, &v) ?
  480. upb_value_getcstr(v) : NULL;
  481. }
  482. const char *upb_enum_iter_name(upb_enum_iter *iter) {
  483. return upb_strtable_iter_key(iter);
  484. }
  485. int32_t upb_enum_iter_number(upb_enum_iter *iter) {
  486. return upb_value_getint32(upb_strtable_iter_value(iter));
  487. }
  488. /* upb_fielddef ***************************************************************/
  489. static void upb_fielddef_init_default(upb_fielddef *f);
  490. static void upb_fielddef_uninit_default(upb_fielddef *f) {
  491. if (f->type_is_set_ && f->default_is_string && f->defaultval.bytes)
  492. freestr(f->defaultval.bytes);
  493. }
  494. const char *upb_fielddef_fullname(const upb_fielddef *e) {
  495. return upb_def_fullname(upb_fielddef_upcast(e));
  496. }
  497. static void visitfield(const upb_refcounted *r, upb_refcounted_visit *visit,
  498. void *closure) {
  499. const upb_fielddef *f = (const upb_fielddef*)r;
  500. const upb_def *def = upb_fielddef_upcast(f);
  501. if (upb_fielddef_containingtype(f)) {
  502. visit(r, upb_msgdef_upcast2(upb_fielddef_containingtype(f)), closure);
  503. }
  504. if (upb_fielddef_containingoneof(f)) {
  505. visit(r, upb_oneofdef_upcast(upb_fielddef_containingoneof(f)), closure);
  506. }
  507. if (upb_fielddef_subdef(f)) {
  508. visit(r, upb_def_upcast(upb_fielddef_subdef(f)), closure);
  509. }
  510. if (upb_def_file(def)) {
  511. visit(r, upb_filedef_upcast(upb_def_file(def)), closure);
  512. }
  513. }
  514. static void freefield(upb_refcounted *r) {
  515. upb_fielddef *f = (upb_fielddef*)r;
  516. upb_fielddef_uninit_default(f);
  517. if (f->subdef_is_symbolic)
  518. upb_gfree(f->sub.name);
  519. upb_def_uninit(upb_fielddef_upcast_mutable(f));
  520. upb_gfree(f);
  521. }
  522. static const char *enumdefaultstr(const upb_fielddef *f) {
  523. const upb_enumdef *e;
  524. UPB_ASSERT(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  525. e = upb_fielddef_enumsubdef(f);
  526. if (f->default_is_string && f->defaultval.bytes) {
  527. /* Default was explicitly set as a string. */
  528. str_t *s = f->defaultval.bytes;
  529. return s->str;
  530. } else if (e) {
  531. if (!f->default_is_string) {
  532. /* Default was explicitly set as an integer; look it up in enumdef. */
  533. const char *name = upb_enumdef_iton(e, f->defaultval.sint);
  534. if (name) {
  535. return name;
  536. }
  537. } else {
  538. /* Default is completely unset; pull enumdef default. */
  539. if (upb_enumdef_numvals(e) > 0) {
  540. const char *name = upb_enumdef_iton(e, upb_enumdef_default(e));
  541. UPB_ASSERT(name);
  542. return name;
  543. }
  544. }
  545. }
  546. return NULL;
  547. }
  548. static bool enumdefaultint32(const upb_fielddef *f, int32_t *val) {
  549. const upb_enumdef *e;
  550. UPB_ASSERT(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  551. e = upb_fielddef_enumsubdef(f);
  552. if (!f->default_is_string) {
  553. /* Default was explicitly set as an integer. */
  554. *val = f->defaultval.sint;
  555. return true;
  556. } else if (e) {
  557. if (f->defaultval.bytes) {
  558. /* Default was explicitly set as a str; try to lookup corresponding int. */
  559. str_t *s = f->defaultval.bytes;
  560. if (upb_enumdef_ntoiz(e, s->str, val)) {
  561. return true;
  562. }
  563. } else {
  564. /* Default is unset; try to pull in enumdef default. */
  565. if (upb_enumdef_numvals(e) > 0) {
  566. *val = upb_enumdef_default(e);
  567. return true;
  568. }
  569. }
  570. }
  571. return false;
  572. }
  573. const struct upb_refcounted_vtbl upb_fielddef_vtbl = {visitfield, freefield};
  574. upb_fielddef *upb_fielddef_new(const void *o) {
  575. upb_fielddef *f = upb_gmalloc(sizeof(*f));
  576. if (!f) return NULL;
  577. if (!upb_def_init(upb_fielddef_upcast_mutable(f), UPB_DEF_FIELD,
  578. &upb_fielddef_vtbl, o)) {
  579. upb_gfree(f);
  580. return NULL;
  581. }
  582. f->msg.def = NULL;
  583. f->sub.def = NULL;
  584. f->oneof = NULL;
  585. f->subdef_is_symbolic = false;
  586. f->msg_is_symbolic = false;
  587. f->label_ = UPB_LABEL_OPTIONAL;
  588. f->type_ = UPB_TYPE_INT32;
  589. f->number_ = 0;
  590. f->type_is_set_ = false;
  591. f->tagdelim = false;
  592. f->is_extension_ = false;
  593. f->lazy_ = false;
  594. f->packed_ = true;
  595. /* For the moment we default this to UPB_INTFMT_VARIABLE, since it will work
  596. * with all integer types and is in some since more "default" since the most
  597. * normal-looking proto2 types int32/int64/uint32/uint64 use variable.
  598. *
  599. * Other options to consider:
  600. * - there is no default; users must set this manually (like type).
  601. * - default signed integers to UPB_INTFMT_ZIGZAG, since it's more likely to
  602. * be an optimal default for signed integers. */
  603. f->intfmt = UPB_INTFMT_VARIABLE;
  604. return f;
  605. }
  606. bool upb_fielddef_typeisset(const upb_fielddef *f) {
  607. return f->type_is_set_;
  608. }
  609. upb_fieldtype_t upb_fielddef_type(const upb_fielddef *f) {
  610. UPB_ASSERT(f->type_is_set_);
  611. return f->type_;
  612. }
  613. uint32_t upb_fielddef_index(const upb_fielddef *f) {
  614. return f->index_;
  615. }
  616. upb_label_t upb_fielddef_label(const upb_fielddef *f) {
  617. return f->label_;
  618. }
  619. upb_intfmt_t upb_fielddef_intfmt(const upb_fielddef *f) {
  620. return f->intfmt;
  621. }
  622. bool upb_fielddef_istagdelim(const upb_fielddef *f) {
  623. return f->tagdelim;
  624. }
  625. uint32_t upb_fielddef_number(const upb_fielddef *f) {
  626. return f->number_;
  627. }
  628. bool upb_fielddef_isextension(const upb_fielddef *f) {
  629. return f->is_extension_;
  630. }
  631. bool upb_fielddef_lazy(const upb_fielddef *f) {
  632. return f->lazy_;
  633. }
  634. bool upb_fielddef_packed(const upb_fielddef *f) {
  635. return f->packed_;
  636. }
  637. const char *upb_fielddef_name(const upb_fielddef *f) {
  638. return upb_def_fullname(upb_fielddef_upcast(f));
  639. }
  640. size_t upb_fielddef_getjsonname(const upb_fielddef *f, char *buf, size_t len) {
  641. const char *name = upb_fielddef_name(f);
  642. size_t src, dst = 0;
  643. bool ucase_next = false;
  644. #define WRITE(byte) \
  645. ++dst; \
  646. if (dst < len) buf[dst - 1] = byte; \
  647. else if (dst == len) buf[dst - 1] = '\0'
  648. if (!name) {
  649. WRITE('\0');
  650. return 0;
  651. }
  652. /* Implement the transformation as described in the spec:
  653. * 1. upper case all letters after an underscore.
  654. * 2. remove all underscores.
  655. */
  656. for (src = 0; name[src]; src++) {
  657. if (name[src] == '_') {
  658. ucase_next = true;
  659. continue;
  660. }
  661. if (ucase_next) {
  662. WRITE(toupper(name[src]));
  663. ucase_next = false;
  664. } else {
  665. WRITE(name[src]);
  666. }
  667. }
  668. WRITE('\0');
  669. return dst;
  670. #undef WRITE
  671. }
  672. const upb_msgdef *upb_fielddef_containingtype(const upb_fielddef *f) {
  673. return f->msg_is_symbolic ? NULL : f->msg.def;
  674. }
  675. const upb_oneofdef *upb_fielddef_containingoneof(const upb_fielddef *f) {
  676. return f->oneof;
  677. }
  678. upb_msgdef *upb_fielddef_containingtype_mutable(upb_fielddef *f) {
  679. return (upb_msgdef*)upb_fielddef_containingtype(f);
  680. }
  681. const char *upb_fielddef_containingtypename(upb_fielddef *f) {
  682. return f->msg_is_symbolic ? f->msg.name : NULL;
  683. }
  684. static void release_containingtype(upb_fielddef *f) {
  685. if (f->msg_is_symbolic) upb_gfree(f->msg.name);
  686. }
  687. bool upb_fielddef_setcontainingtypename(upb_fielddef *f, const char *name,
  688. upb_status *s) {
  689. char *name_copy;
  690. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  691. if (upb_fielddef_containingtype(f)) {
  692. upb_status_seterrmsg(s, "field has already been added to a message.");
  693. return false;
  694. }
  695. /* TODO: validate name (upb_isident() doesn't quite work atm because this name
  696. * may have a leading "."). */
  697. name_copy = upb_gstrdup(name);
  698. if (!name_copy) {
  699. upb_upberr_setoom(s);
  700. return false;
  701. }
  702. release_containingtype(f);
  703. f->msg.name = name_copy;
  704. f->msg_is_symbolic = true;
  705. return true;
  706. }
  707. bool upb_fielddef_setname(upb_fielddef *f, const char *name, upb_status *s) {
  708. if (upb_fielddef_containingtype(f) || upb_fielddef_containingoneof(f)) {
  709. upb_status_seterrmsg(s, "Already added to message or oneof");
  710. return false;
  711. }
  712. return upb_def_setfullname(upb_fielddef_upcast_mutable(f), name, s);
  713. }
  714. static void chkdefaulttype(const upb_fielddef *f, upb_fieldtype_t type) {
  715. UPB_UNUSED(f);
  716. UPB_UNUSED(type);
  717. UPB_ASSERT(f->type_is_set_ && upb_fielddef_type(f) == type);
  718. }
  719. int64_t upb_fielddef_defaultint64(const upb_fielddef *f) {
  720. chkdefaulttype(f, UPB_TYPE_INT64);
  721. return f->defaultval.sint;
  722. }
  723. int32_t upb_fielddef_defaultint32(const upb_fielddef *f) {
  724. if (f->type_is_set_ && upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  725. int32_t val;
  726. bool ok = enumdefaultint32(f, &val);
  727. UPB_ASSERT(ok);
  728. return val;
  729. } else {
  730. chkdefaulttype(f, UPB_TYPE_INT32);
  731. return f->defaultval.sint;
  732. }
  733. }
  734. uint64_t upb_fielddef_defaultuint64(const upb_fielddef *f) {
  735. chkdefaulttype(f, UPB_TYPE_UINT64);
  736. return f->defaultval.uint;
  737. }
  738. uint32_t upb_fielddef_defaultuint32(const upb_fielddef *f) {
  739. chkdefaulttype(f, UPB_TYPE_UINT32);
  740. return f->defaultval.uint;
  741. }
  742. bool upb_fielddef_defaultbool(const upb_fielddef *f) {
  743. chkdefaulttype(f, UPB_TYPE_BOOL);
  744. return f->defaultval.uint;
  745. }
  746. float upb_fielddef_defaultfloat(const upb_fielddef *f) {
  747. chkdefaulttype(f, UPB_TYPE_FLOAT);
  748. return f->defaultval.flt;
  749. }
  750. double upb_fielddef_defaultdouble(const upb_fielddef *f) {
  751. chkdefaulttype(f, UPB_TYPE_DOUBLE);
  752. return f->defaultval.dbl;
  753. }
  754. const char *upb_fielddef_defaultstr(const upb_fielddef *f, size_t *len) {
  755. UPB_ASSERT(f->type_is_set_);
  756. UPB_ASSERT(upb_fielddef_type(f) == UPB_TYPE_STRING ||
  757. upb_fielddef_type(f) == UPB_TYPE_BYTES ||
  758. upb_fielddef_type(f) == UPB_TYPE_ENUM);
  759. if (upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  760. const char *ret = enumdefaultstr(f);
  761. UPB_ASSERT(ret);
  762. /* Enum defaults can't have embedded NULLs. */
  763. if (len) *len = strlen(ret);
  764. return ret;
  765. }
  766. if (f->default_is_string) {
  767. str_t *str = f->defaultval.bytes;
  768. if (len) *len = str->len;
  769. return str->str;
  770. }
  771. return NULL;
  772. }
  773. static void upb_fielddef_init_default(upb_fielddef *f) {
  774. f->default_is_string = false;
  775. switch (upb_fielddef_type(f)) {
  776. case UPB_TYPE_DOUBLE: f->defaultval.dbl = 0; break;
  777. case UPB_TYPE_FLOAT: f->defaultval.flt = 0; break;
  778. case UPB_TYPE_INT32:
  779. case UPB_TYPE_INT64: f->defaultval.sint = 0; break;
  780. case UPB_TYPE_UINT64:
  781. case UPB_TYPE_UINT32:
  782. case UPB_TYPE_BOOL: f->defaultval.uint = 0; break;
  783. case UPB_TYPE_STRING:
  784. case UPB_TYPE_BYTES:
  785. f->defaultval.bytes = newstr("", 0);
  786. f->default_is_string = true;
  787. break;
  788. case UPB_TYPE_MESSAGE: break;
  789. case UPB_TYPE_ENUM:
  790. /* This is our special sentinel that indicates "not set" for an enum. */
  791. f->default_is_string = true;
  792. f->defaultval.bytes = NULL;
  793. break;
  794. }
  795. }
  796. const upb_def *upb_fielddef_subdef(const upb_fielddef *f) {
  797. return f->subdef_is_symbolic ? NULL : f->sub.def;
  798. }
  799. const upb_msgdef *upb_fielddef_msgsubdef(const upb_fielddef *f) {
  800. const upb_def *def = upb_fielddef_subdef(f);
  801. return def ? upb_dyncast_msgdef(def) : NULL;
  802. }
  803. const upb_enumdef *upb_fielddef_enumsubdef(const upb_fielddef *f) {
  804. const upb_def *def = upb_fielddef_subdef(f);
  805. return def ? upb_dyncast_enumdef(def) : NULL;
  806. }
  807. upb_def *upb_fielddef_subdef_mutable(upb_fielddef *f) {
  808. return (upb_def*)upb_fielddef_subdef(f);
  809. }
  810. const char *upb_fielddef_subdefname(const upb_fielddef *f) {
  811. if (f->subdef_is_symbolic) {
  812. return f->sub.name;
  813. } else if (f->sub.def) {
  814. return upb_def_fullname(f->sub.def);
  815. } else {
  816. return NULL;
  817. }
  818. }
  819. bool upb_fielddef_setnumber(upb_fielddef *f, uint32_t number, upb_status *s) {
  820. if (upb_fielddef_containingtype(f)) {
  821. upb_status_seterrmsg(
  822. s, "cannot change field number after adding to a message");
  823. return false;
  824. }
  825. if (number == 0 || number > UPB_MAX_FIELDNUMBER) {
  826. upb_status_seterrf(s, "invalid field number (%u)", number);
  827. return false;
  828. }
  829. f->number_ = number;
  830. return true;
  831. }
  832. void upb_fielddef_settype(upb_fielddef *f, upb_fieldtype_t type) {
  833. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  834. UPB_ASSERT(upb_fielddef_checktype(type));
  835. upb_fielddef_uninit_default(f);
  836. f->type_ = type;
  837. f->type_is_set_ = true;
  838. upb_fielddef_init_default(f);
  839. }
  840. void upb_fielddef_setdescriptortype(upb_fielddef *f, int type) {
  841. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  842. switch (type) {
  843. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  844. upb_fielddef_settype(f, UPB_TYPE_DOUBLE);
  845. break;
  846. case UPB_DESCRIPTOR_TYPE_FLOAT:
  847. upb_fielddef_settype(f, UPB_TYPE_FLOAT);
  848. break;
  849. case UPB_DESCRIPTOR_TYPE_INT64:
  850. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  851. case UPB_DESCRIPTOR_TYPE_SINT64:
  852. upb_fielddef_settype(f, UPB_TYPE_INT64);
  853. break;
  854. case UPB_DESCRIPTOR_TYPE_UINT64:
  855. case UPB_DESCRIPTOR_TYPE_FIXED64:
  856. upb_fielddef_settype(f, UPB_TYPE_UINT64);
  857. break;
  858. case UPB_DESCRIPTOR_TYPE_INT32:
  859. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  860. case UPB_DESCRIPTOR_TYPE_SINT32:
  861. upb_fielddef_settype(f, UPB_TYPE_INT32);
  862. break;
  863. case UPB_DESCRIPTOR_TYPE_UINT32:
  864. case UPB_DESCRIPTOR_TYPE_FIXED32:
  865. upb_fielddef_settype(f, UPB_TYPE_UINT32);
  866. break;
  867. case UPB_DESCRIPTOR_TYPE_BOOL:
  868. upb_fielddef_settype(f, UPB_TYPE_BOOL);
  869. break;
  870. case UPB_DESCRIPTOR_TYPE_STRING:
  871. upb_fielddef_settype(f, UPB_TYPE_STRING);
  872. break;
  873. case UPB_DESCRIPTOR_TYPE_BYTES:
  874. upb_fielddef_settype(f, UPB_TYPE_BYTES);
  875. break;
  876. case UPB_DESCRIPTOR_TYPE_GROUP:
  877. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  878. upb_fielddef_settype(f, UPB_TYPE_MESSAGE);
  879. break;
  880. case UPB_DESCRIPTOR_TYPE_ENUM:
  881. upb_fielddef_settype(f, UPB_TYPE_ENUM);
  882. break;
  883. default: UPB_ASSERT(false);
  884. }
  885. if (type == UPB_DESCRIPTOR_TYPE_FIXED64 ||
  886. type == UPB_DESCRIPTOR_TYPE_FIXED32 ||
  887. type == UPB_DESCRIPTOR_TYPE_SFIXED64 ||
  888. type == UPB_DESCRIPTOR_TYPE_SFIXED32) {
  889. upb_fielddef_setintfmt(f, UPB_INTFMT_FIXED);
  890. } else if (type == UPB_DESCRIPTOR_TYPE_SINT64 ||
  891. type == UPB_DESCRIPTOR_TYPE_SINT32) {
  892. upb_fielddef_setintfmt(f, UPB_INTFMT_ZIGZAG);
  893. } else {
  894. upb_fielddef_setintfmt(f, UPB_INTFMT_VARIABLE);
  895. }
  896. upb_fielddef_settagdelim(f, type == UPB_DESCRIPTOR_TYPE_GROUP);
  897. }
  898. upb_descriptortype_t upb_fielddef_descriptortype(const upb_fielddef *f) {
  899. switch (upb_fielddef_type(f)) {
  900. case UPB_TYPE_FLOAT: return UPB_DESCRIPTOR_TYPE_FLOAT;
  901. case UPB_TYPE_DOUBLE: return UPB_DESCRIPTOR_TYPE_DOUBLE;
  902. case UPB_TYPE_BOOL: return UPB_DESCRIPTOR_TYPE_BOOL;
  903. case UPB_TYPE_STRING: return UPB_DESCRIPTOR_TYPE_STRING;
  904. case UPB_TYPE_BYTES: return UPB_DESCRIPTOR_TYPE_BYTES;
  905. case UPB_TYPE_ENUM: return UPB_DESCRIPTOR_TYPE_ENUM;
  906. case UPB_TYPE_INT32:
  907. switch (upb_fielddef_intfmt(f)) {
  908. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_INT32;
  909. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_SFIXED32;
  910. case UPB_INTFMT_ZIGZAG: return UPB_DESCRIPTOR_TYPE_SINT32;
  911. }
  912. case UPB_TYPE_INT64:
  913. switch (upb_fielddef_intfmt(f)) {
  914. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_INT64;
  915. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_SFIXED64;
  916. case UPB_INTFMT_ZIGZAG: return UPB_DESCRIPTOR_TYPE_SINT64;
  917. }
  918. case UPB_TYPE_UINT32:
  919. switch (upb_fielddef_intfmt(f)) {
  920. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_UINT32;
  921. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_FIXED32;
  922. case UPB_INTFMT_ZIGZAG: return -1;
  923. }
  924. case UPB_TYPE_UINT64:
  925. switch (upb_fielddef_intfmt(f)) {
  926. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_UINT64;
  927. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_FIXED64;
  928. case UPB_INTFMT_ZIGZAG: return -1;
  929. }
  930. case UPB_TYPE_MESSAGE:
  931. return upb_fielddef_istagdelim(f) ?
  932. UPB_DESCRIPTOR_TYPE_GROUP : UPB_DESCRIPTOR_TYPE_MESSAGE;
  933. }
  934. return 0;
  935. }
  936. void upb_fielddef_setisextension(upb_fielddef *f, bool is_extension) {
  937. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  938. f->is_extension_ = is_extension;
  939. }
  940. void upb_fielddef_setlazy(upb_fielddef *f, bool lazy) {
  941. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  942. f->lazy_ = lazy;
  943. }
  944. void upb_fielddef_setpacked(upb_fielddef *f, bool packed) {
  945. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  946. f->packed_ = packed;
  947. }
  948. void upb_fielddef_setlabel(upb_fielddef *f, upb_label_t label) {
  949. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  950. UPB_ASSERT(upb_fielddef_checklabel(label));
  951. f->label_ = label;
  952. }
  953. void upb_fielddef_setintfmt(upb_fielddef *f, upb_intfmt_t fmt) {
  954. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  955. UPB_ASSERT(upb_fielddef_checkintfmt(fmt));
  956. f->intfmt = fmt;
  957. }
  958. void upb_fielddef_settagdelim(upb_fielddef *f, bool tag_delim) {
  959. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  960. f->tagdelim = tag_delim;
  961. f->tagdelim = tag_delim;
  962. }
  963. static bool checksetdefault(upb_fielddef *f, upb_fieldtype_t type) {
  964. if (!f->type_is_set_ || upb_fielddef_isfrozen(f) ||
  965. upb_fielddef_type(f) != type) {
  966. UPB_ASSERT(false);
  967. return false;
  968. }
  969. if (f->default_is_string) {
  970. str_t *s = f->defaultval.bytes;
  971. UPB_ASSERT(s || type == UPB_TYPE_ENUM);
  972. if (s) freestr(s);
  973. }
  974. f->default_is_string = false;
  975. return true;
  976. }
  977. void upb_fielddef_setdefaultint64(upb_fielddef *f, int64_t value) {
  978. if (checksetdefault(f, UPB_TYPE_INT64))
  979. f->defaultval.sint = value;
  980. }
  981. void upb_fielddef_setdefaultint32(upb_fielddef *f, int32_t value) {
  982. if ((upb_fielddef_type(f) == UPB_TYPE_ENUM &&
  983. checksetdefault(f, UPB_TYPE_ENUM)) ||
  984. checksetdefault(f, UPB_TYPE_INT32)) {
  985. f->defaultval.sint = value;
  986. }
  987. }
  988. void upb_fielddef_setdefaultuint64(upb_fielddef *f, uint64_t value) {
  989. if (checksetdefault(f, UPB_TYPE_UINT64))
  990. f->defaultval.uint = value;
  991. }
  992. void upb_fielddef_setdefaultuint32(upb_fielddef *f, uint32_t value) {
  993. if (checksetdefault(f, UPB_TYPE_UINT32))
  994. f->defaultval.uint = value;
  995. }
  996. void upb_fielddef_setdefaultbool(upb_fielddef *f, bool value) {
  997. if (checksetdefault(f, UPB_TYPE_BOOL))
  998. f->defaultval.uint = value;
  999. }
  1000. void upb_fielddef_setdefaultfloat(upb_fielddef *f, float value) {
  1001. if (checksetdefault(f, UPB_TYPE_FLOAT))
  1002. f->defaultval.flt = value;
  1003. }
  1004. void upb_fielddef_setdefaultdouble(upb_fielddef *f, double value) {
  1005. if (checksetdefault(f, UPB_TYPE_DOUBLE))
  1006. f->defaultval.dbl = value;
  1007. }
  1008. bool upb_fielddef_setdefaultstr(upb_fielddef *f, const void *str, size_t len,
  1009. upb_status *s) {
  1010. str_t *str2;
  1011. UPB_ASSERT(upb_fielddef_isstring(f) || f->type_ == UPB_TYPE_ENUM);
  1012. if (f->type_ == UPB_TYPE_ENUM && !upb_isident(str, len, false, s))
  1013. return false;
  1014. if (f->default_is_string) {
  1015. str_t *s = f->defaultval.bytes;
  1016. UPB_ASSERT(s || f->type_ == UPB_TYPE_ENUM);
  1017. if (s) freestr(s);
  1018. } else {
  1019. UPB_ASSERT(f->type_ == UPB_TYPE_ENUM);
  1020. }
  1021. str2 = newstr(str, len);
  1022. f->defaultval.bytes = str2;
  1023. f->default_is_string = true;
  1024. return true;
  1025. }
  1026. void upb_fielddef_setdefaultcstr(upb_fielddef *f, const char *str,
  1027. upb_status *s) {
  1028. UPB_ASSERT(f->type_is_set_);
  1029. upb_fielddef_setdefaultstr(f, str, str ? strlen(str) : 0, s);
  1030. }
  1031. bool upb_fielddef_enumhasdefaultint32(const upb_fielddef *f) {
  1032. int32_t val;
  1033. UPB_ASSERT(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  1034. return enumdefaultint32(f, &val);
  1035. }
  1036. bool upb_fielddef_enumhasdefaultstr(const upb_fielddef *f) {
  1037. UPB_ASSERT(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  1038. return enumdefaultstr(f) != NULL;
  1039. }
  1040. static bool upb_subdef_typecheck(upb_fielddef *f, const upb_def *subdef,
  1041. upb_status *s) {
  1042. if (f->type_ == UPB_TYPE_MESSAGE) {
  1043. if (upb_dyncast_msgdef(subdef)) return true;
  1044. upb_status_seterrmsg(s, "invalid subdef type for this submessage field");
  1045. return false;
  1046. } else if (f->type_ == UPB_TYPE_ENUM) {
  1047. if (upb_dyncast_enumdef(subdef)) return true;
  1048. upb_status_seterrmsg(s, "invalid subdef type for this enum field");
  1049. return false;
  1050. } else {
  1051. upb_status_seterrmsg(s, "only message and enum fields can have a subdef");
  1052. return false;
  1053. }
  1054. }
  1055. static void release_subdef(upb_fielddef *f) {
  1056. if (f->subdef_is_symbolic) {
  1057. upb_gfree(f->sub.name);
  1058. } else if (f->sub.def) {
  1059. upb_unref2(f->sub.def, f);
  1060. }
  1061. }
  1062. bool upb_fielddef_setsubdef(upb_fielddef *f, const upb_def *subdef,
  1063. upb_status *s) {
  1064. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  1065. UPB_ASSERT(upb_fielddef_hassubdef(f));
  1066. if (subdef && !upb_subdef_typecheck(f, subdef, s)) return false;
  1067. release_subdef(f);
  1068. f->sub.def = subdef;
  1069. f->subdef_is_symbolic = false;
  1070. if (f->sub.def) upb_ref2(f->sub.def, f);
  1071. return true;
  1072. }
  1073. bool upb_fielddef_setmsgsubdef(upb_fielddef *f, const upb_msgdef *subdef,
  1074. upb_status *s) {
  1075. return upb_fielddef_setsubdef(f, upb_msgdef_upcast(subdef), s);
  1076. }
  1077. bool upb_fielddef_setenumsubdef(upb_fielddef *f, const upb_enumdef *subdef,
  1078. upb_status *s) {
  1079. return upb_fielddef_setsubdef(f, upb_enumdef_upcast(subdef), s);
  1080. }
  1081. bool upb_fielddef_setsubdefname(upb_fielddef *f, const char *name,
  1082. upb_status *s) {
  1083. char *name_copy;
  1084. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  1085. if (!upb_fielddef_hassubdef(f)) {
  1086. upb_status_seterrmsg(s, "field type does not accept a subdef");
  1087. return false;
  1088. }
  1089. name_copy = upb_gstrdup(name);
  1090. if (!name_copy) {
  1091. upb_upberr_setoom(s);
  1092. return false;
  1093. }
  1094. /* TODO: validate name (upb_isident() doesn't quite work atm because this name
  1095. * may have a leading "."). */
  1096. release_subdef(f);
  1097. f->sub.name = name_copy;
  1098. f->subdef_is_symbolic = true;
  1099. return true;
  1100. }
  1101. bool upb_fielddef_issubmsg(const upb_fielddef *f) {
  1102. return upb_fielddef_type(f) == UPB_TYPE_MESSAGE;
  1103. }
  1104. bool upb_fielddef_isstring(const upb_fielddef *f) {
  1105. return upb_fielddef_type(f) == UPB_TYPE_STRING ||
  1106. upb_fielddef_type(f) == UPB_TYPE_BYTES;
  1107. }
  1108. bool upb_fielddef_isseq(const upb_fielddef *f) {
  1109. return upb_fielddef_label(f) == UPB_LABEL_REPEATED;
  1110. }
  1111. bool upb_fielddef_isprimitive(const upb_fielddef *f) {
  1112. return !upb_fielddef_isstring(f) && !upb_fielddef_issubmsg(f);
  1113. }
  1114. bool upb_fielddef_ismap(const upb_fielddef *f) {
  1115. return upb_fielddef_isseq(f) && upb_fielddef_issubmsg(f) &&
  1116. upb_msgdef_mapentry(upb_fielddef_msgsubdef(f));
  1117. }
  1118. bool upb_fielddef_haspresence(const upb_fielddef *f) {
  1119. if (upb_fielddef_isseq(f)) return false;
  1120. if (upb_fielddef_issubmsg(f)) return true;
  1121. /* Primitive field: return true unless there is a message that specifies
  1122. * presence should not exist. */
  1123. if (f->msg_is_symbolic || !f->msg.def) return true;
  1124. return f->msg.def->syntax == UPB_SYNTAX_PROTO2;
  1125. }
  1126. bool upb_fielddef_hassubdef(const upb_fielddef *f) {
  1127. return upb_fielddef_issubmsg(f) || upb_fielddef_type(f) == UPB_TYPE_ENUM;
  1128. }
  1129. static bool between(int32_t x, int32_t low, int32_t high) {
  1130. return x >= low && x <= high;
  1131. }
  1132. bool upb_fielddef_checklabel(int32_t label) { return between(label, 1, 3); }
  1133. bool upb_fielddef_checktype(int32_t type) { return between(type, 1, 11); }
  1134. bool upb_fielddef_checkintfmt(int32_t fmt) { return between(fmt, 1, 3); }
  1135. bool upb_fielddef_checkdescriptortype(int32_t type) {
  1136. return between(type, 1, 18);
  1137. }
  1138. /* upb_msgdef *****************************************************************/
  1139. static void visitmsg(const upb_refcounted *r, upb_refcounted_visit *visit,
  1140. void *closure) {
  1141. upb_msg_oneof_iter o;
  1142. const upb_msgdef *m = (const upb_msgdef*)r;
  1143. const upb_def *def = upb_msgdef_upcast(m);
  1144. upb_msg_field_iter i;
  1145. for(upb_msg_field_begin(&i, m);
  1146. !upb_msg_field_done(&i);
  1147. upb_msg_field_next(&i)) {
  1148. upb_fielddef *f = upb_msg_iter_field(&i);
  1149. visit(r, upb_fielddef_upcast2(f), closure);
  1150. }
  1151. for(upb_msg_oneof_begin(&o, m);
  1152. !upb_msg_oneof_done(&o);
  1153. upb_msg_oneof_next(&o)) {
  1154. upb_oneofdef *f = upb_msg_iter_oneof(&o);
  1155. visit(r, upb_oneofdef_upcast(f), closure);
  1156. }
  1157. if (upb_def_file(def)) {
  1158. visit(r, upb_filedef_upcast(upb_def_file(def)), closure);
  1159. }
  1160. }
  1161. static void freemsg(upb_refcounted *r) {
  1162. upb_msgdef *m = (upb_msgdef*)r;
  1163. upb_strtable_uninit(&m->ntof);
  1164. upb_inttable_uninit(&m->itof);
  1165. upb_def_uninit(upb_msgdef_upcast_mutable(m));
  1166. upb_gfree(m);
  1167. }
  1168. const struct upb_refcounted_vtbl upb_msgdef_vtbl = {visitmsg, freemsg};
  1169. upb_msgdef *upb_msgdef_new(const void *owner) {
  1170. upb_msgdef *m = upb_gmalloc(sizeof(*m));
  1171. if (!m) return NULL;
  1172. if (!upb_def_init(upb_msgdef_upcast_mutable(m), UPB_DEF_MSG, &upb_msgdef_vtbl,
  1173. owner)) {
  1174. goto err2;
  1175. }
  1176. if (!upb_inttable_init(&m->itof, UPB_CTYPE_PTR)) goto err2;
  1177. if (!upb_strtable_init(&m->ntof, UPB_CTYPE_PTR)) goto err1;
  1178. m->map_entry = false;
  1179. m->syntax = UPB_SYNTAX_PROTO2;
  1180. return m;
  1181. err1:
  1182. upb_inttable_uninit(&m->itof);
  1183. err2:
  1184. upb_gfree(m);
  1185. return NULL;
  1186. }
  1187. bool upb_msgdef_freeze(upb_msgdef *m, upb_status *status) {
  1188. upb_def *d = upb_msgdef_upcast_mutable(m);
  1189. return upb_def_freeze(&d, 1, status);
  1190. }
  1191. const char *upb_msgdef_fullname(const upb_msgdef *m) {
  1192. return upb_def_fullname(upb_msgdef_upcast(m));
  1193. }
  1194. const char *upb_msgdef_name(const upb_msgdef *m) {
  1195. return upb_def_name(upb_msgdef_upcast(m));
  1196. }
  1197. bool upb_msgdef_setfullname(upb_msgdef *m, const char *fullname,
  1198. upb_status *s) {
  1199. return upb_def_setfullname(upb_msgdef_upcast_mutable(m), fullname, s);
  1200. }
  1201. bool upb_msgdef_setsyntax(upb_msgdef *m, upb_syntax_t syntax) {
  1202. if (syntax != UPB_SYNTAX_PROTO2 && syntax != UPB_SYNTAX_PROTO3) {
  1203. return false;
  1204. }
  1205. m->syntax = syntax;
  1206. return true;
  1207. }
  1208. upb_syntax_t upb_msgdef_syntax(const upb_msgdef *m) {
  1209. return m->syntax;
  1210. }
  1211. /* Helper: check that the field |f| is safe to add to msgdef |m|. Set an error
  1212. * on status |s| and return false if not. */
  1213. static bool check_field_add(const upb_msgdef *m, const upb_fielddef *f,
  1214. upb_status *s) {
  1215. if (upb_fielddef_containingtype(f) != NULL) {
  1216. upb_status_seterrmsg(s, "fielddef already belongs to a message");
  1217. return false;
  1218. } else if (upb_fielddef_name(f) == NULL || upb_fielddef_number(f) == 0) {
  1219. upb_status_seterrmsg(s, "field name or number were not set");
  1220. return false;
  1221. } else if (upb_msgdef_itof(m, upb_fielddef_number(f))) {
  1222. upb_status_seterrmsg(s, "duplicate field number");
  1223. return false;
  1224. } else if (upb_strtable_lookup(&m->ntof, upb_fielddef_name(f), NULL)) {
  1225. upb_status_seterrmsg(s, "name conflicts with existing field or oneof");
  1226. return false;
  1227. }
  1228. return true;
  1229. }
  1230. static void add_field(upb_msgdef *m, upb_fielddef *f, const void *ref_donor) {
  1231. release_containingtype(f);
  1232. f->msg.def = m;
  1233. f->msg_is_symbolic = false;
  1234. upb_inttable_insert(&m->itof, upb_fielddef_number(f), upb_value_ptr(f));
  1235. upb_strtable_insert(&m->ntof, upb_fielddef_name(f), upb_value_ptr(f));
  1236. upb_ref2(f, m);
  1237. upb_ref2(m, f);
  1238. if (ref_donor) upb_fielddef_unref(f, ref_donor);
  1239. }
  1240. bool upb_msgdef_addfield(upb_msgdef *m, upb_fielddef *f, const void *ref_donor,
  1241. upb_status *s) {
  1242. /* TODO: extensions need to have a separate namespace, because proto2 allows a
  1243. * top-level extension (ie. one not in any package) to have the same name as a
  1244. * field from the message.
  1245. *
  1246. * This also implies that there needs to be a separate lookup-by-name method
  1247. * for extensions. It seems desirable for iteration to return both extensions
  1248. * and non-extensions though.
  1249. *
  1250. * We also need to validate that the field number is in an extension range iff
  1251. * it is an extension.
  1252. *
  1253. * This method is idempotent. Check if |f| is already part of this msgdef and
  1254. * return immediately if so. */
  1255. if (upb_fielddef_containingtype(f) == m) {
  1256. if (ref_donor) upb_fielddef_unref(f, ref_donor);
  1257. return true;
  1258. }
  1259. /* Check constraints for all fields before performing any action. */
  1260. if (!check_field_add(m, f, s)) {
  1261. return false;
  1262. } else if (upb_fielddef_containingoneof(f) != NULL) {
  1263. /* Fields in a oneof can only be added by adding the oneof to the msgdef. */
  1264. upb_status_seterrmsg(s, "fielddef is part of a oneof");
  1265. return false;
  1266. }
  1267. /* Constraint checks ok, perform the action. */
  1268. add_field(m, f, ref_donor);
  1269. return true;
  1270. }
  1271. bool upb_msgdef_addoneof(upb_msgdef *m, upb_oneofdef *o, const void *ref_donor,
  1272. upb_status *s) {
  1273. upb_oneof_iter it;
  1274. /* Check various conditions that would prevent this oneof from being added. */
  1275. if (upb_oneofdef_containingtype(o)) {
  1276. upb_status_seterrmsg(s, "oneofdef already belongs to a message");
  1277. return false;
  1278. } else if (upb_oneofdef_name(o) == NULL) {
  1279. upb_status_seterrmsg(s, "oneofdef name was not set");
  1280. return false;
  1281. } else if (upb_strtable_lookup(&m->ntof, upb_oneofdef_name(o), NULL)) {
  1282. upb_status_seterrmsg(s, "name conflicts with existing field or oneof");
  1283. return false;
  1284. }
  1285. /* Check that all of the oneof's fields do not conflict with names or numbers
  1286. * of fields already in the message. */
  1287. for (upb_oneof_begin(&it, o); !upb_oneof_done(&it); upb_oneof_next(&it)) {
  1288. const upb_fielddef *f = upb_oneof_iter_field(&it);
  1289. if (!check_field_add(m, f, s)) {
  1290. return false;
  1291. }
  1292. }
  1293. /* Everything checks out -- commit now. */
  1294. /* Add oneof itself first. */
  1295. o->parent = m;
  1296. upb_strtable_insert(&m->ntof, upb_oneofdef_name(o), upb_value_ptr(o));
  1297. upb_ref2(o, m);
  1298. upb_ref2(m, o);
  1299. /* Add each field of the oneof directly to the msgdef. */
  1300. for (upb_oneof_begin(&it, o); !upb_oneof_done(&it); upb_oneof_next(&it)) {
  1301. upb_fielddef *f = upb_oneof_iter_field(&it);
  1302. add_field(m, f, NULL);
  1303. }
  1304. if (ref_donor) upb_oneofdef_unref(o, ref_donor);
  1305. return true;
  1306. }
  1307. const upb_fielddef *upb_msgdef_itof(const upb_msgdef *m, uint32_t i) {
  1308. upb_value val;
  1309. return upb_inttable_lookup32(&m->itof, i, &val) ?
  1310. upb_value_getptr(val) : NULL;
  1311. }
  1312. const upb_fielddef *upb_msgdef_ntof(const upb_msgdef *m, const char *name,
  1313. size_t len) {
  1314. upb_value val;
  1315. if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
  1316. return NULL;
  1317. }
  1318. return upb_trygetfield(upb_value_getptr(val));
  1319. }
  1320. const upb_oneofdef *upb_msgdef_ntoo(const upb_msgdef *m, const char *name,
  1321. size_t len) {
  1322. upb_value val;
  1323. if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
  1324. return NULL;
  1325. }
  1326. return upb_trygetoneof(upb_value_getptr(val));
  1327. }
  1328. bool upb_msgdef_lookupname(const upb_msgdef *m, const char *name, size_t len,
  1329. const upb_fielddef **f, const upb_oneofdef **o) {
  1330. upb_value val;
  1331. if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
  1332. return false;
  1333. }
  1334. *o = upb_trygetoneof(upb_value_getptr(val));
  1335. *f = upb_trygetfield(upb_value_getptr(val));
  1336. UPB_ASSERT((*o != NULL) ^ (*f != NULL)); /* Exactly one of the two should be set. */
  1337. return true;
  1338. }
  1339. int upb_msgdef_numfields(const upb_msgdef *m) {
  1340. /* The number table contains only fields. */
  1341. return upb_inttable_count(&m->itof);
  1342. }
  1343. int upb_msgdef_numoneofs(const upb_msgdef *m) {
  1344. /* The name table includes oneofs, and the number table does not. */
  1345. return upb_strtable_count(&m->ntof) - upb_inttable_count(&m->itof);
  1346. }
  1347. void upb_msgdef_setmapentry(upb_msgdef *m, bool map_entry) {
  1348. UPB_ASSERT(!upb_msgdef_isfrozen(m));
  1349. m->map_entry = map_entry;
  1350. }
  1351. bool upb_msgdef_mapentry(const upb_msgdef *m) {
  1352. return m->map_entry;
  1353. }
  1354. void upb_msg_field_begin(upb_msg_field_iter *iter, const upb_msgdef *m) {
  1355. upb_inttable_begin(iter, &m->itof);
  1356. }
  1357. void upb_msg_field_next(upb_msg_field_iter *iter) { upb_inttable_next(iter); }
  1358. bool upb_msg_field_done(const upb_msg_field_iter *iter) {
  1359. return upb_inttable_done(iter);
  1360. }
  1361. upb_fielddef *upb_msg_iter_field(const upb_msg_field_iter *iter) {
  1362. return (upb_fielddef*)upb_value_getptr(upb_inttable_iter_value(iter));
  1363. }
  1364. void upb_msg_field_iter_setdone(upb_msg_field_iter *iter) {
  1365. upb_inttable_iter_setdone(iter);
  1366. }
  1367. void upb_msg_oneof_begin(upb_msg_oneof_iter *iter, const upb_msgdef *m) {
  1368. upb_strtable_begin(iter, &m->ntof);
  1369. /* We need to skip past any initial fields. */
  1370. while (!upb_strtable_done(iter) &&
  1371. !upb_isoneof(upb_value_getptr(upb_strtable_iter_value(iter)))) {
  1372. upb_strtable_next(iter);
  1373. }
  1374. }
  1375. void upb_msg_oneof_next(upb_msg_oneof_iter *iter) {
  1376. /* We need to skip past fields to return only oneofs. */
  1377. do {
  1378. upb_strtable_next(iter);
  1379. } while (!upb_strtable_done(iter) &&
  1380. !upb_isoneof(upb_value_getptr(upb_strtable_iter_value(iter))));
  1381. }
  1382. bool upb_msg_oneof_done(const upb_msg_oneof_iter *iter) {
  1383. return upb_strtable_done(iter);
  1384. }
  1385. upb_oneofdef *upb_msg_iter_oneof(const upb_msg_oneof_iter *iter) {
  1386. return (upb_oneofdef*)upb_value_getptr(upb_strtable_iter_value(iter));
  1387. }
  1388. void upb_msg_oneof_iter_setdone(upb_msg_oneof_iter *iter) {
  1389. upb_strtable_iter_setdone(iter);
  1390. }
  1391. /* upb_oneofdef ***************************************************************/
  1392. static void visitoneof(const upb_refcounted *r, upb_refcounted_visit *visit,
  1393. void *closure) {
  1394. const upb_oneofdef *o = (const upb_oneofdef*)r;
  1395. upb_oneof_iter i;
  1396. for (upb_oneof_begin(&i, o); !upb_oneof_done(&i); upb_oneof_next(&i)) {
  1397. const upb_fielddef *f = upb_oneof_iter_field(&i);
  1398. visit(r, upb_fielddef_upcast2(f), closure);
  1399. }
  1400. if (o->parent) {
  1401. visit(r, upb_msgdef_upcast2(o->parent), closure);
  1402. }
  1403. }
  1404. static void freeoneof(upb_refcounted *r) {
  1405. upb_oneofdef *o = (upb_oneofdef*)r;
  1406. upb_strtable_uninit(&o->ntof);
  1407. upb_inttable_uninit(&o->itof);
  1408. upb_gfree((void*)o->name);
  1409. upb_gfree(o);
  1410. }
  1411. const struct upb_refcounted_vtbl upb_oneofdef_vtbl = {visitoneof, freeoneof};
  1412. upb_oneofdef *upb_oneofdef_new(const void *owner) {
  1413. upb_oneofdef *o = upb_gmalloc(sizeof(*o));
  1414. if (!o) {
  1415. return NULL;
  1416. }
  1417. o->parent = NULL;
  1418. o->name = NULL;
  1419. if (!upb_refcounted_init(upb_oneofdef_upcast_mutable(o), &upb_oneofdef_vtbl,
  1420. owner)) {
  1421. goto err2;
  1422. }
  1423. if (!upb_inttable_init(&o->itof, UPB_CTYPE_PTR)) goto err2;
  1424. if (!upb_strtable_init(&o->ntof, UPB_CTYPE_PTR)) goto err1;
  1425. return o;
  1426. err1:
  1427. upb_inttable_uninit(&o->itof);
  1428. err2:
  1429. upb_gfree(o);
  1430. return NULL;
  1431. }
  1432. const char *upb_oneofdef_name(const upb_oneofdef *o) { return o->name; }
  1433. bool upb_oneofdef_setname(upb_oneofdef *o, const char *name, upb_status *s) {
  1434. UPB_ASSERT(!upb_oneofdef_isfrozen(o));
  1435. if (upb_oneofdef_containingtype(o)) {
  1436. upb_status_seterrmsg(s, "oneof already added to a message");
  1437. return false;
  1438. }
  1439. if (!upb_isident(name, strlen(name), true, s)) {
  1440. return false;
  1441. }
  1442. name = upb_gstrdup(name);
  1443. if (!name) {
  1444. upb_status_seterrmsg(s, "One of memory");
  1445. return false;
  1446. }
  1447. upb_gfree((void*)o->name);
  1448. o->name = name;
  1449. return true;
  1450. }
  1451. const upb_msgdef *upb_oneofdef_containingtype(const upb_oneofdef *o) {
  1452. return o->parent;
  1453. }
  1454. int upb_oneofdef_numfields(const upb_oneofdef *o) {
  1455. return upb_strtable_count(&o->ntof);
  1456. }
  1457. uint32_t upb_oneofdef_index(const upb_oneofdef *o) {
  1458. return o->index;
  1459. }
  1460. bool upb_oneofdef_addfield(upb_oneofdef *o, upb_fielddef *f,
  1461. const void *ref_donor,
  1462. upb_status *s) {
  1463. UPB_ASSERT(!upb_oneofdef_isfrozen(o));
  1464. UPB_ASSERT(!o->parent || !upb_msgdef_isfrozen(o->parent));
  1465. /* This method is idempotent. Check if |f| is already part of this oneofdef
  1466. * and return immediately if so. */
  1467. if (upb_fielddef_containingoneof(f) == o) {
  1468. return true;
  1469. }
  1470. /* The field must have an OPTIONAL label. */
  1471. if (upb_fielddef_label(f) != UPB_LABEL_OPTIONAL) {
  1472. upb_status_seterrmsg(s, "fields in oneof must have OPTIONAL label");
  1473. return false;
  1474. }
  1475. /* Check that no field with this name or number exists already in the oneof.
  1476. * Also check that the field is not already part of a oneof. */
  1477. if (upb_fielddef_name(f) == NULL || upb_fielddef_number(f) == 0) {
  1478. upb_status_seterrmsg(s, "field name or number were not set");
  1479. return false;
  1480. } else if (upb_oneofdef_itof(o, upb_fielddef_number(f)) ||
  1481. upb_oneofdef_ntofz(o, upb_fielddef_name(f))) {
  1482. upb_status_seterrmsg(s, "duplicate field name or number");
  1483. return false;
  1484. } else if (upb_fielddef_containingoneof(f) != NULL) {
  1485. upb_status_seterrmsg(s, "fielddef already belongs to a oneof");
  1486. return false;
  1487. }
  1488. /* We allow adding a field to the oneof either if the field is not part of a
  1489. * msgdef, or if it is and we are also part of the same msgdef. */
  1490. if (o->parent == NULL) {
  1491. /* If we're not in a msgdef, the field cannot be either. Otherwise we would
  1492. * need to magically add this oneof to a msgdef to remain consistent, which
  1493. * is surprising behavior. */
  1494. if (upb_fielddef_containingtype(f) != NULL) {
  1495. upb_status_seterrmsg(s, "fielddef already belongs to a message, but "
  1496. "oneof does not");
  1497. return false;
  1498. }
  1499. } else {
  1500. /* If we're in a msgdef, the user can add fields that either aren't in any
  1501. * msgdef (in which case they're added to our msgdef) or already a part of
  1502. * our msgdef. */
  1503. if (upb_fielddef_containingtype(f) != NULL &&
  1504. upb_fielddef_containingtype(f) != o->parent) {
  1505. upb_status_seterrmsg(s, "fielddef belongs to a different message "
  1506. "than oneof");
  1507. return false;
  1508. }
  1509. }
  1510. /* Commit phase. First add the field to our parent msgdef, if any, because
  1511. * that may fail; then add the field to our own tables. */
  1512. if (o->parent != NULL && upb_fielddef_containingtype(f) == NULL) {
  1513. if (!upb_msgdef_addfield((upb_msgdef*)o->parent, f, NULL, s)) {
  1514. return false;
  1515. }
  1516. }
  1517. release_containingtype(f);
  1518. f->oneof = o;
  1519. upb_inttable_insert(&o->itof, upb_fielddef_number(f), upb_value_ptr(f));
  1520. upb_strtable_insert(&o->ntof, upb_fielddef_name(f), upb_value_ptr(f));
  1521. upb_ref2(f, o);
  1522. upb_ref2(o, f);
  1523. if (ref_donor) upb_fielddef_unref(f, ref_donor);
  1524. return true;
  1525. }
  1526. const upb_fielddef *upb_oneofdef_ntof(const upb_oneofdef *o,
  1527. const char *name, size_t length) {
  1528. upb_value val;
  1529. return upb_strtable_lookup2(&o->ntof, name, length, &val) ?
  1530. upb_value_getptr(val) : NULL;
  1531. }
  1532. const upb_fielddef *upb_oneofdef_itof(const upb_oneofdef *o, uint32_t num) {
  1533. upb_value val;
  1534. return upb_inttable_lookup32(&o->itof, num, &val) ?
  1535. upb_value_getptr(val) : NULL;
  1536. }
  1537. void upb_oneof_begin(upb_oneof_iter *iter, const upb_oneofdef *o) {
  1538. upb_inttable_begin(iter, &o->itof);
  1539. }
  1540. void upb_oneof_next(upb_oneof_iter *iter) {
  1541. upb_inttable_next(iter);
  1542. }
  1543. bool upb_oneof_done(upb_oneof_iter *iter) {
  1544. return upb_inttable_done(iter);
  1545. }
  1546. upb_fielddef *upb_oneof_iter_field(const upb_oneof_iter *iter) {
  1547. return (upb_fielddef*)upb_value_getptr(upb_inttable_iter_value(iter));
  1548. }
  1549. void upb_oneof_iter_setdone(upb_oneof_iter *iter) {
  1550. upb_inttable_iter_setdone(iter);
  1551. }
  1552. /* upb_filedef ****************************************************************/
  1553. static void visitfiledef(const upb_refcounted *r, upb_refcounted_visit *visit,
  1554. void *closure) {
  1555. const upb_filedef *f = (const upb_filedef*)r;
  1556. size_t i;
  1557. for(i = 0; i < upb_filedef_defcount(f); i++) {
  1558. visit(r, upb_def_upcast(upb_filedef_def(f, i)), closure);
  1559. }
  1560. }
  1561. static void freefiledef(upb_refcounted *r) {
  1562. upb_filedef *f = (upb_filedef*)r;
  1563. size_t i;
  1564. for(i = 0; i < upb_filedef_depcount(f); i++) {
  1565. upb_filedef_unref(upb_filedef_dep(f, i), f);
  1566. }
  1567. upb_inttable_uninit(&f->defs);
  1568. upb_inttable_uninit(&f->deps);
  1569. upb_gfree((void*)f->name);
  1570. upb_gfree((void*)f->package);
  1571. upb_gfree((void*)f->phpprefix);
  1572. upb_gfree((void*)f->phpnamespace);
  1573. upb_gfree(f);
  1574. }
  1575. const struct upb_refcounted_vtbl upb_filedef_vtbl = {visitfiledef, freefiledef};
  1576. upb_filedef *upb_filedef_new(const void *owner) {
  1577. upb_filedef *f = upb_gmalloc(sizeof(*f));
  1578. if (!f) {
  1579. return NULL;
  1580. }
  1581. f->package = NULL;
  1582. f->name = NULL;
  1583. f->phpprefix = NULL;
  1584. f->phpnamespace = NULL;
  1585. f->syntax = UPB_SYNTAX_PROTO2;
  1586. if (!upb_refcounted_init(upb_filedef_upcast_mutable(f), &upb_filedef_vtbl,
  1587. owner)) {
  1588. goto err;
  1589. }
  1590. if (!upb_inttable_init(&f->defs, UPB_CTYPE_CONSTPTR)) {
  1591. goto err;
  1592. }
  1593. if (!upb_inttable_init(&f->deps, UPB_CTYPE_CONSTPTR)) {
  1594. goto err2;
  1595. }
  1596. return f;
  1597. err2:
  1598. upb_inttable_uninit(&f->defs);
  1599. err:
  1600. upb_gfree(f);
  1601. return NULL;
  1602. }
  1603. const char *upb_filedef_name(const upb_filedef *f) {
  1604. return f->name;
  1605. }
  1606. const char *upb_filedef_package(const upb_filedef *f) {
  1607. return f->package;
  1608. }
  1609. const char *upb_filedef_phpprefix(const upb_filedef *f) {
  1610. return f->phpprefix;
  1611. }
  1612. const char *upb_filedef_phpnamespace(const upb_filedef *f) {
  1613. return f->phpnamespace;
  1614. }
  1615. upb_syntax_t upb_filedef_syntax(const upb_filedef *f) {
  1616. return f->syntax;
  1617. }
  1618. size_t upb_filedef_defcount(const upb_filedef *f) {
  1619. return upb_inttable_count(&f->defs);
  1620. }
  1621. size_t upb_filedef_depcount(const upb_filedef *f) {
  1622. return upb_inttable_count(&f->deps);
  1623. }
  1624. const upb_def *upb_filedef_def(const upb_filedef *f, size_t i) {
  1625. upb_value v;
  1626. if (upb_inttable_lookup32(&f->defs, i, &v)) {
  1627. return upb_value_getconstptr(v);
  1628. } else {
  1629. return NULL;
  1630. }
  1631. }
  1632. const upb_filedef *upb_filedef_dep(const upb_filedef *f, size_t i) {
  1633. upb_value v;
  1634. if (upb_inttable_lookup32(&f->deps, i, &v)) {
  1635. return upb_value_getconstptr(v);
  1636. } else {
  1637. return NULL;
  1638. }
  1639. }
  1640. bool upb_filedef_setname(upb_filedef *f, const char *name, upb_status *s) {
  1641. name = upb_gstrdup(name);
  1642. if (!name) {
  1643. upb_upberr_setoom(s);
  1644. return false;
  1645. }
  1646. upb_gfree((void*)f->name);
  1647. f->name = name;
  1648. return true;
  1649. }
  1650. bool upb_filedef_setpackage(upb_filedef *f, const char *package,
  1651. upb_status *s) {
  1652. if (!upb_isident(package, strlen(package), true, s)) return false;
  1653. package = upb_gstrdup(package);
  1654. if (!package) {
  1655. upb_upberr_setoom(s);
  1656. return false;
  1657. }
  1658. upb_gfree((void*)f->package);
  1659. f->package = package;
  1660. return true;
  1661. }
  1662. bool upb_filedef_setphpprefix(upb_filedef *f, const char *phpprefix,
  1663. upb_status *s) {
  1664. phpprefix = upb_gstrdup(phpprefix);
  1665. if (!phpprefix) {
  1666. upb_upberr_setoom(s);
  1667. return false;
  1668. }
  1669. upb_gfree((void*)f->phpprefix);
  1670. f->phpprefix = phpprefix;
  1671. return true;
  1672. }
  1673. bool upb_filedef_setphpnamespace(upb_filedef *f, const char *phpnamespace,
  1674. upb_status *s) {
  1675. phpnamespace = upb_gstrdup(phpnamespace);
  1676. if (!phpnamespace) {
  1677. upb_upberr_setoom(s);
  1678. return false;
  1679. }
  1680. upb_gfree((void*)f->phpnamespace);
  1681. f->phpnamespace = phpnamespace;
  1682. return true;
  1683. }
  1684. bool upb_filedef_setsyntax(upb_filedef *f, upb_syntax_t syntax,
  1685. upb_status *s) {
  1686. UPB_UNUSED(s);
  1687. if (syntax != UPB_SYNTAX_PROTO2 &&
  1688. syntax != UPB_SYNTAX_PROTO3) {
  1689. upb_status_seterrmsg(s, "Unknown syntax value.");
  1690. return false;
  1691. }
  1692. f->syntax = syntax;
  1693. {
  1694. /* Set all messages in this file to match. */
  1695. size_t i;
  1696. for (i = 0; i < upb_filedef_defcount(f); i++) {
  1697. /* Casting const away is safe since all defs in mutable filedef must
  1698. * also be mutable. */
  1699. upb_def *def = (upb_def*)upb_filedef_def(f, i);
  1700. upb_msgdef *m = upb_dyncast_msgdef_mutable(def);
  1701. if (m) {
  1702. m->syntax = syntax;
  1703. }
  1704. }
  1705. }
  1706. return true;
  1707. }
  1708. bool upb_filedef_adddef(upb_filedef *f, upb_def *def, const void *ref_donor,
  1709. upb_status *s) {
  1710. if (def->file) {
  1711. upb_status_seterrmsg(s, "Def is already part of another filedef.");
  1712. return false;
  1713. }
  1714. if (upb_inttable_push(&f->defs, upb_value_constptr(def))) {
  1715. def->file = f;
  1716. upb_ref2(def, f);
  1717. upb_ref2(f, def);
  1718. if (ref_donor) upb_def_unref(def, ref_donor);
  1719. if (def->type == UPB_DEF_MSG) {
  1720. upb_downcast_msgdef_mutable(def)->syntax = f->syntax;
  1721. }
  1722. return true;
  1723. } else {
  1724. upb_upberr_setoom(s);
  1725. return false;
  1726. }
  1727. }
  1728. bool upb_filedef_adddep(upb_filedef *f, const upb_filedef *dep) {
  1729. if (upb_inttable_push(&f->deps, upb_value_constptr(dep))) {
  1730. /* Regular ref instead of ref2 because files can't form cycles. */
  1731. upb_filedef_ref(dep, f);
  1732. return true;
  1733. } else {
  1734. return false;
  1735. }
  1736. }
  1737. void upb_symtab_free(upb_symtab *s) {
  1738. upb_strtable_iter i;
  1739. upb_strtable_begin(&i, &s->symtab);
  1740. for (; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  1741. const upb_def *def = upb_value_getptr(upb_strtable_iter_value(&i));
  1742. upb_def_unref(def, s);
  1743. }
  1744. upb_strtable_uninit(&s->symtab);
  1745. upb_gfree(s);
  1746. }
  1747. upb_symtab *upb_symtab_new() {
  1748. upb_symtab *s = upb_gmalloc(sizeof(*s));
  1749. if (!s) {
  1750. return NULL;
  1751. }
  1752. upb_strtable_init(&s->symtab, UPB_CTYPE_PTR);
  1753. return s;
  1754. }
  1755. const upb_def *upb_symtab_lookup(const upb_symtab *s, const char *sym) {
  1756. upb_value v;
  1757. upb_def *ret = upb_strtable_lookup(&s->symtab, sym, &v) ?
  1758. upb_value_getptr(v) : NULL;
  1759. return ret;
  1760. }
  1761. const upb_msgdef *upb_symtab_lookupmsg(const upb_symtab *s, const char *sym) {
  1762. upb_value v;
  1763. upb_def *def = upb_strtable_lookup(&s->symtab, sym, &v) ?
  1764. upb_value_getptr(v) : NULL;
  1765. return def ? upb_dyncast_msgdef(def) : NULL;
  1766. }
  1767. const upb_enumdef *upb_symtab_lookupenum(const upb_symtab *s, const char *sym) {
  1768. upb_value v;
  1769. upb_def *def = upb_strtable_lookup(&s->symtab, sym, &v) ?
  1770. upb_value_getptr(v) : NULL;
  1771. return def ? upb_dyncast_enumdef(def) : NULL;
  1772. }
  1773. /* Given a symbol and the base symbol inside which it is defined, find the
  1774. * symbol's definition in t. */
  1775. static upb_def *upb_resolvename(const upb_strtable *t,
  1776. const char *base, const char *sym) {
  1777. if(strlen(sym) == 0) return NULL;
  1778. if(sym[0] == '.') {
  1779. /* Symbols starting with '.' are absolute, so we do a single lookup.
  1780. * Slice to omit the leading '.' */
  1781. upb_value v;
  1782. return upb_strtable_lookup(t, sym + 1, &v) ? upb_value_getptr(v) : NULL;
  1783. } else {
  1784. /* Remove components from base until we find an entry or run out.
  1785. * TODO: This branch is totally broken, but currently not used. */
  1786. (void)base;
  1787. UPB_ASSERT(false);
  1788. return NULL;
  1789. }
  1790. }
  1791. const upb_def *upb_symtab_resolve(const upb_symtab *s, const char *base,
  1792. const char *sym) {
  1793. upb_def *ret = upb_resolvename(&s->symtab, base, sym);
  1794. return ret;
  1795. }
  1796. /* TODO(haberman): we need a lot more testing of error conditions. */
  1797. static bool symtab_add(upb_symtab *s, upb_def *const*defs, size_t n,
  1798. void *ref_donor, upb_refcounted *freeze_also,
  1799. upb_status *status) {
  1800. size_t i;
  1801. size_t add_n;
  1802. size_t freeze_n;
  1803. upb_strtable_iter iter;
  1804. upb_refcounted **add_objs = NULL;
  1805. upb_def **add_defs = NULL;
  1806. size_t add_objs_size;
  1807. upb_strtable addtab;
  1808. if (n == 0 && !freeze_also) {
  1809. return true;
  1810. }
  1811. if (!upb_strtable_init(&addtab, UPB_CTYPE_PTR)) {
  1812. upb_status_seterrmsg(status, "out of memory");
  1813. return false;
  1814. }
  1815. /* Add new defs to our "add" set. */
  1816. for (i = 0; i < n; i++) {
  1817. upb_def *def = defs[i];
  1818. const char *fullname;
  1819. upb_fielddef *f;
  1820. if (upb_def_isfrozen(def)) {
  1821. upb_status_seterrmsg(status, "added defs must be mutable");
  1822. goto err;
  1823. }
  1824. UPB_ASSERT(!upb_def_isfrozen(def));
  1825. fullname = upb_def_fullname(def);
  1826. if (!fullname) {
  1827. upb_status_seterrmsg(
  1828. status, "Anonymous defs cannot be added to a symtab");
  1829. goto err;
  1830. }
  1831. f = upb_dyncast_fielddef_mutable(def);
  1832. if (f) {
  1833. if (!upb_fielddef_containingtypename(f)) {
  1834. upb_status_seterrmsg(status,
  1835. "Standalone fielddefs must have a containing type "
  1836. "(extendee) name set");
  1837. goto err;
  1838. }
  1839. } else {
  1840. if (upb_strtable_lookup(&addtab, fullname, NULL)) {
  1841. upb_status_seterrf(status, "Conflicting defs named '%s'", fullname);
  1842. goto err;
  1843. }
  1844. if (upb_strtable_lookup(&s->symtab, fullname, NULL)) {
  1845. upb_status_seterrf(status, "Symtab already has a def named '%s'",
  1846. fullname);
  1847. goto err;
  1848. }
  1849. if (!upb_strtable_insert(&addtab, fullname, upb_value_ptr(def)))
  1850. goto oom_err;
  1851. upb_def_donateref(def, ref_donor, s);
  1852. }
  1853. if (upb_dyncast_fielddef_mutable(def)) {
  1854. /* TODO(haberman): allow adding extensions attached to files. */
  1855. upb_status_seterrf(status, "Can't add extensions to symtab.\n");
  1856. goto err;
  1857. }
  1858. }
  1859. /* Now using the table, resolve symbolic references for subdefs. */
  1860. upb_strtable_begin(&iter, &addtab);
  1861. for (; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
  1862. const char *base;
  1863. upb_def *def = upb_value_getptr(upb_strtable_iter_value(&iter));
  1864. upb_msgdef *m = upb_dyncast_msgdef_mutable(def);
  1865. upb_msg_field_iter j;
  1866. if (!m) continue;
  1867. /* Type names are resolved relative to the message in which they appear. */
  1868. base = upb_msgdef_fullname(m);
  1869. for(upb_msg_field_begin(&j, m);
  1870. !upb_msg_field_done(&j);
  1871. upb_msg_field_next(&j)) {
  1872. upb_fielddef *f = upb_msg_iter_field(&j);
  1873. const char *name = upb_fielddef_subdefname(f);
  1874. if (name && !upb_fielddef_subdef(f)) {
  1875. /* Try the lookup in the current set of to-be-added defs first. If not
  1876. * there, try existing defs. */
  1877. upb_def *subdef = upb_resolvename(&addtab, base, name);
  1878. if (subdef == NULL) {
  1879. subdef = upb_resolvename(&s->symtab, base, name);
  1880. }
  1881. if (subdef == NULL) {
  1882. upb_status_seterrf(
  1883. status, "couldn't resolve name '%s' in message '%s'", name, base);
  1884. goto err;
  1885. } else if (!upb_fielddef_setsubdef(f, subdef, status)) {
  1886. goto err;
  1887. }
  1888. }
  1889. }
  1890. }
  1891. /* We need an array of the defs in addtab, for passing to
  1892. * upb_refcounted_freeze(). */
  1893. add_objs_size = upb_strtable_count(&addtab);
  1894. if (freeze_also) {
  1895. add_objs_size++;
  1896. }
  1897. add_defs = upb_gmalloc(sizeof(void*) * add_objs_size);
  1898. if (add_defs == NULL) goto oom_err;
  1899. upb_strtable_begin(&iter, &addtab);
  1900. for (add_n = 0; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
  1901. add_defs[add_n++] = upb_value_getptr(upb_strtable_iter_value(&iter));
  1902. }
  1903. /* Validate defs. */
  1904. if (!_upb_def_validate(add_defs, add_n, status)) {
  1905. goto err;
  1906. }
  1907. /* Cheat a little and give the array a new type.
  1908. * This is probably undefined behavior, but this code will be deleted soon. */
  1909. add_objs = (upb_refcounted**)add_defs;
  1910. freeze_n = add_n;
  1911. if (freeze_also) {
  1912. add_objs[freeze_n++] = freeze_also;
  1913. }
  1914. if (!upb_refcounted_freeze(add_objs, freeze_n, status,
  1915. UPB_MAX_MESSAGE_DEPTH * 2)) {
  1916. goto err;
  1917. }
  1918. /* This must be delayed until all errors have been detected, since error
  1919. * recovery code uses this table to cleanup defs. */
  1920. upb_strtable_uninit(&addtab);
  1921. /* TODO(haberman) we don't properly handle errors after this point (like
  1922. * OOM in upb_strtable_insert() below). */
  1923. for (i = 0; i < add_n; i++) {
  1924. upb_def *def = (upb_def*)add_objs[i];
  1925. const char *name = upb_def_fullname(def);
  1926. bool success;
  1927. success = upb_strtable_insert(&s->symtab, name, upb_value_ptr(def));
  1928. UPB_ASSERT(success);
  1929. }
  1930. upb_gfree(add_defs);
  1931. return true;
  1932. oom_err:
  1933. upb_status_seterrmsg(status, "out of memory");
  1934. err: {
  1935. /* We need to donate the refs back. */
  1936. upb_strtable_begin(&iter, &addtab);
  1937. for (; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
  1938. upb_def *def = upb_value_getptr(upb_strtable_iter_value(&iter));
  1939. upb_def_donateref(def, s, ref_donor);
  1940. }
  1941. }
  1942. upb_strtable_uninit(&addtab);
  1943. upb_gfree(add_defs);
  1944. UPB_ASSERT(!upb_ok(status));
  1945. return false;
  1946. }
  1947. bool upb_symtab_add(upb_symtab *s, upb_def *const*defs, size_t n,
  1948. void *ref_donor, upb_status *status) {
  1949. return symtab_add(s, defs, n, ref_donor, NULL, status);
  1950. }
  1951. bool upb_symtab_addfile(upb_symtab *s, upb_filedef *file, upb_status *status) {
  1952. size_t n;
  1953. size_t i;
  1954. upb_def **defs;
  1955. bool ret;
  1956. n = upb_filedef_defcount(file);
  1957. defs = upb_gmalloc(sizeof(*defs) * n);
  1958. if (defs == NULL) {
  1959. upb_status_seterrmsg(status, "Out of memory");
  1960. return false;
  1961. }
  1962. for (i = 0; i < n; i++) {
  1963. defs[i] = upb_filedef_mutabledef(file, i);
  1964. }
  1965. ret = symtab_add(s, defs, n, NULL, upb_filedef_upcast_mutable(file), status);
  1966. upb_gfree(defs);
  1967. return ret;
  1968. }
  1969. /* Iteration. */
  1970. static void advance_to_matching(upb_symtab_iter *iter) {
  1971. if (iter->type == UPB_DEF_ANY)
  1972. return;
  1973. while (!upb_strtable_done(&iter->iter) &&
  1974. iter->type != upb_symtab_iter_def(iter)->type) {
  1975. upb_strtable_next(&iter->iter);
  1976. }
  1977. }
  1978. void upb_symtab_begin(upb_symtab_iter *iter, const upb_symtab *s,
  1979. upb_deftype_t type) {
  1980. upb_strtable_begin(&iter->iter, &s->symtab);
  1981. iter->type = type;
  1982. advance_to_matching(iter);
  1983. }
  1984. void upb_symtab_next(upb_symtab_iter *iter) {
  1985. upb_strtable_next(&iter->iter);
  1986. advance_to_matching(iter);
  1987. }
  1988. bool upb_symtab_done(const upb_symtab_iter *iter) {
  1989. return upb_strtable_done(&iter->iter);
  1990. }
  1991. const upb_def *upb_symtab_iter_def(const upb_symtab_iter *iter) {
  1992. return upb_value_getptr(upb_strtable_iter_value(&iter->iter));
  1993. }
  1994. /*
  1995. ** TODO(haberman): it's unclear whether a lot of the consistency checks should
  1996. ** UPB_ASSERT() or return false.
  1997. */
  1998. #include <string.h>
  1999. static void *upb_calloc(size_t size) {
  2000. void *mem = upb_gmalloc(size);
  2001. if (mem) {
  2002. memset(mem, 0, size);
  2003. }
  2004. return mem;
  2005. }
  2006. /* Defined for the sole purpose of having a unique pointer value for
  2007. * UPB_NO_CLOSURE. */
  2008. char _upb_noclosure;
  2009. static void freehandlers(upb_refcounted *r) {
  2010. upb_handlers *h = (upb_handlers*)r;
  2011. upb_inttable_iter i;
  2012. upb_inttable_begin(&i, &h->cleanup_);
  2013. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  2014. void *val = (void*)upb_inttable_iter_key(&i);
  2015. upb_value func_val = upb_inttable_iter_value(&i);
  2016. upb_handlerfree *func = upb_value_getfptr(func_val);
  2017. func(val);
  2018. }
  2019. upb_inttable_uninit(&h->cleanup_);
  2020. upb_msgdef_unref(h->msg, h);
  2021. upb_gfree(h->sub);
  2022. upb_gfree(h);
  2023. }
  2024. static void visithandlers(const upb_refcounted *r, upb_refcounted_visit *visit,
  2025. void *closure) {
  2026. const upb_handlers *h = (const upb_handlers*)r;
  2027. upb_msg_field_iter i;
  2028. for(upb_msg_field_begin(&i, h->msg);
  2029. !upb_msg_field_done(&i);
  2030. upb_msg_field_next(&i)) {
  2031. upb_fielddef *f = upb_msg_iter_field(&i);
  2032. const upb_handlers *sub;
  2033. if (!upb_fielddef_issubmsg(f)) continue;
  2034. sub = upb_handlers_getsubhandlers(h, f);
  2035. if (sub) visit(r, upb_handlers_upcast(sub), closure);
  2036. }
  2037. }
  2038. static const struct upb_refcounted_vtbl vtbl = {visithandlers, freehandlers};
  2039. typedef struct {
  2040. upb_inttable tab; /* maps upb_msgdef* -> upb_handlers*. */
  2041. upb_handlers_callback *callback;
  2042. const void *closure;
  2043. } dfs_state;
  2044. /* TODO(haberman): discard upb_handlers* objects that do not actually have any
  2045. * handlers set and cannot reach any upb_handlers* object that does. This is
  2046. * slightly tricky to do correctly. */
  2047. static upb_handlers *newformsg(const upb_msgdef *m, const void *owner,
  2048. dfs_state *s) {
  2049. upb_msg_field_iter i;
  2050. upb_handlers *h = upb_handlers_new(m, owner);
  2051. if (!h) return NULL;
  2052. if (!upb_inttable_insertptr(&s->tab, m, upb_value_ptr(h))) goto oom;
  2053. s->callback(s->closure, h);
  2054. /* For each submessage field, get or create a handlers object and set it as
  2055. * the subhandlers. */
  2056. for(upb_msg_field_begin(&i, m);
  2057. !upb_msg_field_done(&i);
  2058. upb_msg_field_next(&i)) {
  2059. upb_fielddef *f = upb_msg_iter_field(&i);
  2060. const upb_msgdef *subdef;
  2061. upb_value subm_ent;
  2062. if (!upb_fielddef_issubmsg(f)) continue;
  2063. subdef = upb_downcast_msgdef(upb_fielddef_subdef(f));
  2064. if (upb_inttable_lookupptr(&s->tab, subdef, &subm_ent)) {
  2065. upb_handlers_setsubhandlers(h, f, upb_value_getptr(subm_ent));
  2066. } else {
  2067. upb_handlers *sub_mh = newformsg(subdef, &sub_mh, s);
  2068. if (!sub_mh) goto oom;
  2069. upb_handlers_setsubhandlers(h, f, sub_mh);
  2070. upb_handlers_unref(sub_mh, &sub_mh);
  2071. }
  2072. }
  2073. return h;
  2074. oom:
  2075. upb_handlers_unref(h, owner);
  2076. return NULL;
  2077. }
  2078. /* Given a selector for a STARTSUBMSG handler, resolves to a pointer to the
  2079. * subhandlers for this submessage field. */
  2080. #define SUBH(h, selector) (h->sub[selector])
  2081. /* The selector for a submessage field is the field index. */
  2082. #define SUBH_F(h, f) SUBH(h, f->index_)
  2083. static int32_t trygetsel(upb_handlers *h, const upb_fielddef *f,
  2084. upb_handlertype_t type) {
  2085. upb_selector_t sel;
  2086. UPB_ASSERT(!upb_handlers_isfrozen(h));
  2087. if (upb_handlers_msgdef(h) != upb_fielddef_containingtype(f)) {
  2088. upb_status_seterrf(
  2089. &h->status_, "type mismatch: field %s does not belong to message %s",
  2090. upb_fielddef_name(f), upb_msgdef_fullname(upb_handlers_msgdef(h)));
  2091. return -1;
  2092. }
  2093. if (!upb_handlers_getselector(f, type, &sel)) {
  2094. upb_status_seterrf(
  2095. &h->status_,
  2096. "type mismatch: cannot register handler type %d for field %s",
  2097. type, upb_fielddef_name(f));
  2098. return -1;
  2099. }
  2100. return sel;
  2101. }
  2102. static upb_selector_t handlers_getsel(upb_handlers *h, const upb_fielddef *f,
  2103. upb_handlertype_t type) {
  2104. int32_t sel = trygetsel(h, f, type);
  2105. UPB_ASSERT(sel >= 0);
  2106. return sel;
  2107. }
  2108. static const void **returntype(upb_handlers *h, const upb_fielddef *f,
  2109. upb_handlertype_t type) {
  2110. return &h->table[handlers_getsel(h, f, type)].attr.return_closure_type_;
  2111. }
  2112. static bool doset(upb_handlers *h, int32_t sel, const upb_fielddef *f,
  2113. upb_handlertype_t type, upb_func *func,
  2114. upb_handlerattr *attr) {
  2115. upb_handlerattr set_attr = UPB_HANDLERATTR_INITIALIZER;
  2116. const void *closure_type;
  2117. const void **context_closure_type;
  2118. UPB_ASSERT(!upb_handlers_isfrozen(h));
  2119. if (sel < 0) {
  2120. upb_status_seterrmsg(&h->status_,
  2121. "incorrect handler type for this field.");
  2122. return false;
  2123. }
  2124. if (h->table[sel].func) {
  2125. upb_status_seterrmsg(&h->status_,
  2126. "cannot change handler once it has been set.");
  2127. return false;
  2128. }
  2129. if (attr) {
  2130. set_attr = *attr;
  2131. }
  2132. /* Check that the given closure type matches the closure type that has been
  2133. * established for this context (if any). */
  2134. closure_type = upb_handlerattr_closuretype(&set_attr);
  2135. if (type == UPB_HANDLER_STRING) {
  2136. context_closure_type = returntype(h, f, UPB_HANDLER_STARTSTR);
  2137. } else if (f && upb_fielddef_isseq(f) &&
  2138. type != UPB_HANDLER_STARTSEQ &&
  2139. type != UPB_HANDLER_ENDSEQ) {
  2140. context_closure_type = returntype(h, f, UPB_HANDLER_STARTSEQ);
  2141. } else {
  2142. context_closure_type = &h->top_closure_type;
  2143. }
  2144. if (closure_type && *context_closure_type &&
  2145. closure_type != *context_closure_type) {
  2146. /* TODO(haberman): better message for debugging. */
  2147. if (f) {
  2148. upb_status_seterrf(&h->status_,
  2149. "closure type does not match for field %s",
  2150. upb_fielddef_name(f));
  2151. } else {
  2152. upb_status_seterrmsg(
  2153. &h->status_, "closure type does not match for message-level handler");
  2154. }
  2155. return false;
  2156. }
  2157. if (closure_type)
  2158. *context_closure_type = closure_type;
  2159. /* If this is a STARTSEQ or STARTSTR handler, check that the returned pointer
  2160. * matches any pre-existing expectations about what type is expected. */
  2161. if (type == UPB_HANDLER_STARTSEQ || type == UPB_HANDLER_STARTSTR) {
  2162. const void *return_type = upb_handlerattr_returnclosuretype(&set_attr);
  2163. const void *table_return_type =
  2164. upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  2165. if (return_type && table_return_type && return_type != table_return_type) {
  2166. upb_status_seterrmsg(&h->status_, "closure return type does not match");
  2167. return false;
  2168. }
  2169. if (table_return_type && !return_type)
  2170. upb_handlerattr_setreturnclosuretype(&set_attr, table_return_type);
  2171. }
  2172. h->table[sel].func = (upb_func*)func;
  2173. h->table[sel].attr = set_attr;
  2174. return true;
  2175. }
  2176. /* Returns the effective closure type for this handler (which will propagate
  2177. * from outer frames if this frame has no START* handler). Not implemented for
  2178. * UPB_HANDLER_STRING at the moment since this is not needed. Returns NULL is
  2179. * the effective closure type is unspecified (either no handler was registered
  2180. * to specify it or the handler that was registered did not specify the closure
  2181. * type). */
  2182. const void *effective_closure_type(upb_handlers *h, const upb_fielddef *f,
  2183. upb_handlertype_t type) {
  2184. const void *ret;
  2185. upb_selector_t sel;
  2186. UPB_ASSERT(type != UPB_HANDLER_STRING);
  2187. ret = h->top_closure_type;
  2188. if (upb_fielddef_isseq(f) &&
  2189. type != UPB_HANDLER_STARTSEQ &&
  2190. type != UPB_HANDLER_ENDSEQ &&
  2191. h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSEQ)].func) {
  2192. ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  2193. }
  2194. if (type == UPB_HANDLER_STRING &&
  2195. h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSTR)].func) {
  2196. ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  2197. }
  2198. /* The effective type of the submessage; not used yet.
  2199. * if (type == SUBMESSAGE &&
  2200. * h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSUBMSG)].func) {
  2201. * ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  2202. * } */
  2203. return ret;
  2204. }
  2205. /* Checks whether the START* handler specified by f & type is missing even
  2206. * though it is required to convert the established type of an outer frame
  2207. * ("closure_type") into the established type of an inner frame (represented in
  2208. * the return closure type of this handler's attr. */
  2209. bool checkstart(upb_handlers *h, const upb_fielddef *f, upb_handlertype_t type,
  2210. upb_status *status) {
  2211. const void *closure_type;
  2212. const upb_handlerattr *attr;
  2213. const void *return_closure_type;
  2214. upb_selector_t sel = handlers_getsel(h, f, type);
  2215. if (h->table[sel].func) return true;
  2216. closure_type = effective_closure_type(h, f, type);
  2217. attr = &h->table[sel].attr;
  2218. return_closure_type = upb_handlerattr_returnclosuretype(attr);
  2219. if (closure_type && return_closure_type &&
  2220. closure_type != return_closure_type) {
  2221. upb_status_seterrf(status,
  2222. "expected start handler to return sub type for field %f",
  2223. upb_fielddef_name(f));
  2224. return false;
  2225. }
  2226. return true;
  2227. }
  2228. /* Public interface ***********************************************************/
  2229. upb_handlers *upb_handlers_new(const upb_msgdef *md, const void *owner) {
  2230. int extra;
  2231. upb_handlers *h;
  2232. UPB_ASSERT(upb_msgdef_isfrozen(md));
  2233. extra = sizeof(upb_handlers_tabent) * (md->selector_count - 1);
  2234. h = upb_calloc(sizeof(*h) + extra);
  2235. if (!h) return NULL;
  2236. h->msg = md;
  2237. upb_msgdef_ref(h->msg, h);
  2238. upb_status_clear(&h->status_);
  2239. if (md->submsg_field_count > 0) {
  2240. h->sub = upb_calloc(md->submsg_field_count * sizeof(*h->sub));
  2241. if (!h->sub) goto oom;
  2242. } else {
  2243. h->sub = 0;
  2244. }
  2245. if (!upb_refcounted_init(upb_handlers_upcast_mutable(h), &vtbl, owner))
  2246. goto oom;
  2247. if (!upb_inttable_init(&h->cleanup_, UPB_CTYPE_FPTR)) goto oom;
  2248. /* calloc() above initialized all handlers to NULL. */
  2249. return h;
  2250. oom:
  2251. freehandlers(upb_handlers_upcast_mutable(h));
  2252. return NULL;
  2253. }
  2254. const upb_handlers *upb_handlers_newfrozen(const upb_msgdef *m,
  2255. const void *owner,
  2256. upb_handlers_callback *callback,
  2257. const void *closure) {
  2258. dfs_state state;
  2259. upb_handlers *ret;
  2260. bool ok;
  2261. upb_refcounted *r;
  2262. state.callback = callback;
  2263. state.closure = closure;
  2264. if (!upb_inttable_init(&state.tab, UPB_CTYPE_PTR)) return NULL;
  2265. ret = newformsg(m, owner, &state);
  2266. upb_inttable_uninit(&state.tab);
  2267. if (!ret) return NULL;
  2268. r = upb_handlers_upcast_mutable(ret);
  2269. ok = upb_refcounted_freeze(&r, 1, NULL, UPB_MAX_HANDLER_DEPTH);
  2270. UPB_ASSERT(ok);
  2271. return ret;
  2272. }
  2273. const upb_status *upb_handlers_status(upb_handlers *h) {
  2274. UPB_ASSERT(!upb_handlers_isfrozen(h));
  2275. return &h->status_;
  2276. }
  2277. void upb_handlers_clearerr(upb_handlers *h) {
  2278. UPB_ASSERT(!upb_handlers_isfrozen(h));
  2279. upb_status_clear(&h->status_);
  2280. }
  2281. #define SETTER(name, handlerctype, handlertype) \
  2282. bool upb_handlers_set ## name(upb_handlers *h, const upb_fielddef *f, \
  2283. handlerctype func, upb_handlerattr *attr) { \
  2284. int32_t sel = trygetsel(h, f, handlertype); \
  2285. return doset(h, sel, f, handlertype, (upb_func*)func, attr); \
  2286. }
  2287. SETTER(int32, upb_int32_handlerfunc*, UPB_HANDLER_INT32)
  2288. SETTER(int64, upb_int64_handlerfunc*, UPB_HANDLER_INT64)
  2289. SETTER(uint32, upb_uint32_handlerfunc*, UPB_HANDLER_UINT32)
  2290. SETTER(uint64, upb_uint64_handlerfunc*, UPB_HANDLER_UINT64)
  2291. SETTER(float, upb_float_handlerfunc*, UPB_HANDLER_FLOAT)
  2292. SETTER(double, upb_double_handlerfunc*, UPB_HANDLER_DOUBLE)
  2293. SETTER(bool, upb_bool_handlerfunc*, UPB_HANDLER_BOOL)
  2294. SETTER(startstr, upb_startstr_handlerfunc*, UPB_HANDLER_STARTSTR)
  2295. SETTER(string, upb_string_handlerfunc*, UPB_HANDLER_STRING)
  2296. SETTER(endstr, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSTR)
  2297. SETTER(startseq, upb_startfield_handlerfunc*, UPB_HANDLER_STARTSEQ)
  2298. SETTER(startsubmsg, upb_startfield_handlerfunc*, UPB_HANDLER_STARTSUBMSG)
  2299. SETTER(endsubmsg, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSUBMSG)
  2300. SETTER(endseq, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSEQ)
  2301. #undef SETTER
  2302. bool upb_handlers_setstartmsg(upb_handlers *h, upb_startmsg_handlerfunc *func,
  2303. upb_handlerattr *attr) {
  2304. return doset(h, UPB_STARTMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
  2305. (upb_func *)func, attr);
  2306. }
  2307. bool upb_handlers_setendmsg(upb_handlers *h, upb_endmsg_handlerfunc *func,
  2308. upb_handlerattr *attr) {
  2309. UPB_ASSERT(!upb_handlers_isfrozen(h));
  2310. return doset(h, UPB_ENDMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
  2311. (upb_func *)func, attr);
  2312. }
  2313. bool upb_handlers_setsubhandlers(upb_handlers *h, const upb_fielddef *f,
  2314. const upb_handlers *sub) {
  2315. UPB_ASSERT(sub);
  2316. UPB_ASSERT(!upb_handlers_isfrozen(h));
  2317. UPB_ASSERT(upb_fielddef_issubmsg(f));
  2318. if (SUBH_F(h, f)) return false; /* Can't reset. */
  2319. if (upb_msgdef_upcast(upb_handlers_msgdef(sub)) != upb_fielddef_subdef(f)) {
  2320. return false;
  2321. }
  2322. SUBH_F(h, f) = sub;
  2323. upb_ref2(sub, h);
  2324. return true;
  2325. }
  2326. const upb_handlers *upb_handlers_getsubhandlers(const upb_handlers *h,
  2327. const upb_fielddef *f) {
  2328. UPB_ASSERT(upb_fielddef_issubmsg(f));
  2329. return SUBH_F(h, f);
  2330. }
  2331. bool upb_handlers_getattr(const upb_handlers *h, upb_selector_t sel,
  2332. upb_handlerattr *attr) {
  2333. if (!upb_handlers_gethandler(h, sel))
  2334. return false;
  2335. *attr = h->table[sel].attr;
  2336. return true;
  2337. }
  2338. const upb_handlers *upb_handlers_getsubhandlers_sel(const upb_handlers *h,
  2339. upb_selector_t sel) {
  2340. /* STARTSUBMSG selector in sel is the field's selector base. */
  2341. return SUBH(h, sel - UPB_STATIC_SELECTOR_COUNT);
  2342. }
  2343. const upb_msgdef *upb_handlers_msgdef(const upb_handlers *h) { return h->msg; }
  2344. bool upb_handlers_addcleanup(upb_handlers *h, void *p, upb_handlerfree *func) {
  2345. bool ok;
  2346. if (upb_inttable_lookupptr(&h->cleanup_, p, NULL)) {
  2347. return false;
  2348. }
  2349. ok = upb_inttable_insertptr(&h->cleanup_, p, upb_value_fptr(func));
  2350. UPB_ASSERT(ok);
  2351. return true;
  2352. }
  2353. /* "Static" methods ***********************************************************/
  2354. bool upb_handlers_freeze(upb_handlers *const*handlers, int n, upb_status *s) {
  2355. /* TODO: verify we have a transitive closure. */
  2356. int i;
  2357. for (i = 0; i < n; i++) {
  2358. upb_msg_field_iter j;
  2359. upb_handlers *h = handlers[i];
  2360. if (!upb_ok(&h->status_)) {
  2361. upb_status_seterrf(s, "handlers for message %s had error status: %s",
  2362. upb_msgdef_fullname(upb_handlers_msgdef(h)),
  2363. upb_status_errmsg(&h->status_));
  2364. return false;
  2365. }
  2366. /* Check that there are no closure mismatches due to missing Start* handlers
  2367. * or subhandlers with different type-level types. */
  2368. for(upb_msg_field_begin(&j, h->msg);
  2369. !upb_msg_field_done(&j);
  2370. upb_msg_field_next(&j)) {
  2371. const upb_fielddef *f = upb_msg_iter_field(&j);
  2372. if (upb_fielddef_isseq(f)) {
  2373. if (!checkstart(h, f, UPB_HANDLER_STARTSEQ, s))
  2374. return false;
  2375. }
  2376. if (upb_fielddef_isstring(f)) {
  2377. if (!checkstart(h, f, UPB_HANDLER_STARTSTR, s))
  2378. return false;
  2379. }
  2380. if (upb_fielddef_issubmsg(f)) {
  2381. bool hashandler = false;
  2382. if (upb_handlers_gethandler(
  2383. h, handlers_getsel(h, f, UPB_HANDLER_STARTSUBMSG)) ||
  2384. upb_handlers_gethandler(
  2385. h, handlers_getsel(h, f, UPB_HANDLER_ENDSUBMSG))) {
  2386. hashandler = true;
  2387. }
  2388. if (upb_fielddef_isseq(f) &&
  2389. (upb_handlers_gethandler(
  2390. h, handlers_getsel(h, f, UPB_HANDLER_STARTSEQ)) ||
  2391. upb_handlers_gethandler(
  2392. h, handlers_getsel(h, f, UPB_HANDLER_ENDSEQ)))) {
  2393. hashandler = true;
  2394. }
  2395. if (hashandler && !upb_handlers_getsubhandlers(h, f)) {
  2396. /* For now we add an empty subhandlers in this case. It makes the
  2397. * decoder code generator simpler, because it only has to handle two
  2398. * cases (submessage has handlers or not) as opposed to three
  2399. * (submessage has handlers in enclosing message but no subhandlers).
  2400. *
  2401. * This makes parsing less efficient in the case that we want to
  2402. * notice a submessage but skip its contents (like if we're testing
  2403. * for submessage presence or counting the number of repeated
  2404. * submessages). In this case we will end up parsing the submessage
  2405. * field by field and throwing away the results for each, instead of
  2406. * skipping the whole delimited thing at once. If this is an issue we
  2407. * can revisit it, but do remember that this only arises when you have
  2408. * handlers (startseq/startsubmsg/endsubmsg/endseq) set for the
  2409. * submessage but no subhandlers. The uses cases for this are
  2410. * limited. */
  2411. upb_handlers *sub = upb_handlers_new(upb_fielddef_msgsubdef(f), &sub);
  2412. upb_handlers_setsubhandlers(h, f, sub);
  2413. upb_handlers_unref(sub, &sub);
  2414. }
  2415. /* TODO(haberman): check type of submessage.
  2416. * This is slightly tricky; also consider whether we should check that
  2417. * they match at setsubhandlers time. */
  2418. }
  2419. }
  2420. }
  2421. if (!upb_refcounted_freeze((upb_refcounted*const*)handlers, n, s,
  2422. UPB_MAX_HANDLER_DEPTH)) {
  2423. return false;
  2424. }
  2425. return true;
  2426. }
  2427. upb_handlertype_t upb_handlers_getprimitivehandlertype(const upb_fielddef *f) {
  2428. switch (upb_fielddef_type(f)) {
  2429. case UPB_TYPE_INT32:
  2430. case UPB_TYPE_ENUM: return UPB_HANDLER_INT32;
  2431. case UPB_TYPE_INT64: return UPB_HANDLER_INT64;
  2432. case UPB_TYPE_UINT32: return UPB_HANDLER_UINT32;
  2433. case UPB_TYPE_UINT64: return UPB_HANDLER_UINT64;
  2434. case UPB_TYPE_FLOAT: return UPB_HANDLER_FLOAT;
  2435. case UPB_TYPE_DOUBLE: return UPB_HANDLER_DOUBLE;
  2436. case UPB_TYPE_BOOL: return UPB_HANDLER_BOOL;
  2437. default: UPB_ASSERT(false); return -1; /* Invalid input. */
  2438. }
  2439. }
  2440. bool upb_handlers_getselector(const upb_fielddef *f, upb_handlertype_t type,
  2441. upb_selector_t *s) {
  2442. switch (type) {
  2443. case UPB_HANDLER_INT32:
  2444. case UPB_HANDLER_INT64:
  2445. case UPB_HANDLER_UINT32:
  2446. case UPB_HANDLER_UINT64:
  2447. case UPB_HANDLER_FLOAT:
  2448. case UPB_HANDLER_DOUBLE:
  2449. case UPB_HANDLER_BOOL:
  2450. if (!upb_fielddef_isprimitive(f) ||
  2451. upb_handlers_getprimitivehandlertype(f) != type)
  2452. return false;
  2453. *s = f->selector_base;
  2454. break;
  2455. case UPB_HANDLER_STRING:
  2456. if (upb_fielddef_isstring(f)) {
  2457. *s = f->selector_base;
  2458. } else if (upb_fielddef_lazy(f)) {
  2459. *s = f->selector_base + 3;
  2460. } else {
  2461. return false;
  2462. }
  2463. break;
  2464. case UPB_HANDLER_STARTSTR:
  2465. if (upb_fielddef_isstring(f) || upb_fielddef_lazy(f)) {
  2466. *s = f->selector_base + 1;
  2467. } else {
  2468. return false;
  2469. }
  2470. break;
  2471. case UPB_HANDLER_ENDSTR:
  2472. if (upb_fielddef_isstring(f) || upb_fielddef_lazy(f)) {
  2473. *s = f->selector_base + 2;
  2474. } else {
  2475. return false;
  2476. }
  2477. break;
  2478. case UPB_HANDLER_STARTSEQ:
  2479. if (!upb_fielddef_isseq(f)) return false;
  2480. *s = f->selector_base - 2;
  2481. break;
  2482. case UPB_HANDLER_ENDSEQ:
  2483. if (!upb_fielddef_isseq(f)) return false;
  2484. *s = f->selector_base - 1;
  2485. break;
  2486. case UPB_HANDLER_STARTSUBMSG:
  2487. if (!upb_fielddef_issubmsg(f)) return false;
  2488. /* Selectors for STARTSUBMSG are at the beginning of the table so that the
  2489. * selector can also be used as an index into the "sub" array of
  2490. * subhandlers. The indexes for the two into these two tables are the
  2491. * same, except that in the handler table the static selectors come first. */
  2492. *s = f->index_ + UPB_STATIC_SELECTOR_COUNT;
  2493. break;
  2494. case UPB_HANDLER_ENDSUBMSG:
  2495. if (!upb_fielddef_issubmsg(f)) return false;
  2496. *s = f->selector_base;
  2497. break;
  2498. }
  2499. UPB_ASSERT((size_t)*s < upb_fielddef_containingtype(f)->selector_count);
  2500. return true;
  2501. }
  2502. uint32_t upb_handlers_selectorbaseoffset(const upb_fielddef *f) {
  2503. return upb_fielddef_isseq(f) ? 2 : 0;
  2504. }
  2505. uint32_t upb_handlers_selectorcount(const upb_fielddef *f) {
  2506. uint32_t ret = 1;
  2507. if (upb_fielddef_isseq(f)) ret += 2; /* STARTSEQ/ENDSEQ */
  2508. if (upb_fielddef_isstring(f)) ret += 2; /* [STRING]/STARTSTR/ENDSTR */
  2509. if (upb_fielddef_issubmsg(f)) {
  2510. /* ENDSUBMSG (STARTSUBMSG is at table beginning) */
  2511. ret += 0;
  2512. if (upb_fielddef_lazy(f)) {
  2513. /* STARTSTR/ENDSTR/STRING (for lazy) */
  2514. ret += 3;
  2515. }
  2516. }
  2517. return ret;
  2518. }
  2519. /* upb_handlerattr ************************************************************/
  2520. void upb_handlerattr_init(upb_handlerattr *attr) {
  2521. upb_handlerattr from = UPB_HANDLERATTR_INITIALIZER;
  2522. memcpy(attr, &from, sizeof(*attr));
  2523. }
  2524. void upb_handlerattr_uninit(upb_handlerattr *attr) {
  2525. UPB_UNUSED(attr);
  2526. }
  2527. bool upb_handlerattr_sethandlerdata(upb_handlerattr *attr, const void *hd) {
  2528. attr->handler_data_ = hd;
  2529. return true;
  2530. }
  2531. bool upb_handlerattr_setclosuretype(upb_handlerattr *attr, const void *type) {
  2532. attr->closure_type_ = type;
  2533. return true;
  2534. }
  2535. const void *upb_handlerattr_closuretype(const upb_handlerattr *attr) {
  2536. return attr->closure_type_;
  2537. }
  2538. bool upb_handlerattr_setreturnclosuretype(upb_handlerattr *attr,
  2539. const void *type) {
  2540. attr->return_closure_type_ = type;
  2541. return true;
  2542. }
  2543. const void *upb_handlerattr_returnclosuretype(const upb_handlerattr *attr) {
  2544. return attr->return_closure_type_;
  2545. }
  2546. bool upb_handlerattr_setalwaysok(upb_handlerattr *attr, bool alwaysok) {
  2547. attr->alwaysok_ = alwaysok;
  2548. return true;
  2549. }
  2550. bool upb_handlerattr_alwaysok(const upb_handlerattr *attr) {
  2551. return attr->alwaysok_;
  2552. }
  2553. /* upb_bufhandle **************************************************************/
  2554. size_t upb_bufhandle_objofs(const upb_bufhandle *h) {
  2555. return h->objofs_;
  2556. }
  2557. /* upb_byteshandler ***********************************************************/
  2558. void upb_byteshandler_init(upb_byteshandler* h) {
  2559. memset(h, 0, sizeof(*h));
  2560. }
  2561. /* For when we support handlerfree callbacks. */
  2562. void upb_byteshandler_uninit(upb_byteshandler* h) {
  2563. UPB_UNUSED(h);
  2564. }
  2565. bool upb_byteshandler_setstartstr(upb_byteshandler *h,
  2566. upb_startstr_handlerfunc *func, void *d) {
  2567. h->table[UPB_STARTSTR_SELECTOR].func = (upb_func*)func;
  2568. h->table[UPB_STARTSTR_SELECTOR].attr.handler_data_ = d;
  2569. return true;
  2570. }
  2571. bool upb_byteshandler_setstring(upb_byteshandler *h,
  2572. upb_string_handlerfunc *func, void *d) {
  2573. h->table[UPB_STRING_SELECTOR].func = (upb_func*)func;
  2574. h->table[UPB_STRING_SELECTOR].attr.handler_data_ = d;
  2575. return true;
  2576. }
  2577. bool upb_byteshandler_setendstr(upb_byteshandler *h,
  2578. upb_endfield_handlerfunc *func, void *d) {
  2579. h->table[UPB_ENDSTR_SELECTOR].func = (upb_func*)func;
  2580. h->table[UPB_ENDSTR_SELECTOR].attr.handler_data_ = d;
  2581. return true;
  2582. }
  2583. static bool is_power_of_two(size_t val) {
  2584. return (val & (val - 1)) == 0;
  2585. }
  2586. /* Align up to the given power of 2. */
  2587. static size_t align_up(size_t val, size_t align) {
  2588. UPB_ASSERT(is_power_of_two(align));
  2589. return (val + align - 1) & ~(align - 1);
  2590. }
  2591. static size_t div_round_up(size_t n, size_t d) {
  2592. return (n + d - 1) / d;
  2593. }
  2594. bool upb_fieldtype_mapkeyok(upb_fieldtype_t type) {
  2595. return type == UPB_TYPE_BOOL || type == UPB_TYPE_INT32 ||
  2596. type == UPB_TYPE_UINT32 || type == UPB_TYPE_INT64 ||
  2597. type == UPB_TYPE_UINT64 || type == UPB_TYPE_STRING;
  2598. }
  2599. void *upb_array_pack(const upb_array *arr, void *p, size_t *ofs, size_t size);
  2600. void *upb_map_pack(const upb_map *map, void *p, size_t *ofs, size_t size);
  2601. #define CHARPTR_AT(msg, ofs) ((char*)msg + ofs)
  2602. #define ENCODE_MAX_NESTING 64
  2603. #define CHECK_TRUE(x) if (!(x)) { return false; }
  2604. /** upb_msgval ****************************************************************/
  2605. #define upb_alignof(t) offsetof(struct { char c; t x; }, x)
  2606. /* These functions will generate real memcpy() calls on ARM sadly, because
  2607. * the compiler assumes they might not be aligned. */
  2608. static upb_msgval upb_msgval_read(const void *p, size_t ofs,
  2609. uint8_t size) {
  2610. upb_msgval val;
  2611. p = (char*)p + ofs;
  2612. memcpy(&val, p, size);
  2613. return val;
  2614. }
  2615. static void upb_msgval_write(void *p, size_t ofs, upb_msgval val,
  2616. uint8_t size) {
  2617. p = (char*)p + ofs;
  2618. memcpy(p, &val, size);
  2619. }
  2620. static size_t upb_msgval_sizeof(upb_fieldtype_t type) {
  2621. switch (type) {
  2622. case UPB_TYPE_DOUBLE:
  2623. case UPB_TYPE_INT64:
  2624. case UPB_TYPE_UINT64:
  2625. return 8;
  2626. case UPB_TYPE_ENUM:
  2627. case UPB_TYPE_INT32:
  2628. case UPB_TYPE_UINT32:
  2629. case UPB_TYPE_FLOAT:
  2630. return 4;
  2631. case UPB_TYPE_BOOL:
  2632. return 1;
  2633. case UPB_TYPE_BYTES:
  2634. case UPB_TYPE_MESSAGE:
  2635. return sizeof(void*);
  2636. case UPB_TYPE_STRING:
  2637. return sizeof(char*) + sizeof(size_t);
  2638. }
  2639. UPB_UNREACHABLE();
  2640. }
  2641. static uint8_t upb_msg_fieldsize(const upb_fielddef *f) {
  2642. if (upb_fielddef_isseq(f)) {
  2643. return sizeof(void*);
  2644. } else {
  2645. return upb_msgval_sizeof(upb_fielddef_type(f));
  2646. }
  2647. }
  2648. /* TODO(haberman): this is broken right now because upb_msgval can contain
  2649. * a char* / size_t pair, which is too big for a upb_value. To fix this
  2650. * we'll probably need to dynamically allocate a upb_msgval and store a
  2651. * pointer to that in the tables for extensions/maps. */
  2652. static upb_value upb_toval(upb_msgval val) {
  2653. upb_value ret;
  2654. UPB_UNUSED(val);
  2655. memset(&ret, 0, sizeof(upb_value)); /* XXX */
  2656. return ret;
  2657. }
  2658. static upb_msgval upb_msgval_fromval(upb_value val) {
  2659. upb_msgval ret;
  2660. UPB_UNUSED(val);
  2661. memset(&ret, 0, sizeof(upb_msgval)); /* XXX */
  2662. return ret;
  2663. }
  2664. static upb_ctype_t upb_fieldtotabtype(upb_fieldtype_t type) {
  2665. switch (type) {
  2666. case UPB_TYPE_FLOAT: return UPB_CTYPE_FLOAT;
  2667. case UPB_TYPE_DOUBLE: return UPB_CTYPE_DOUBLE;
  2668. case UPB_TYPE_BOOL: return UPB_CTYPE_BOOL;
  2669. case UPB_TYPE_BYTES:
  2670. case UPB_TYPE_MESSAGE:
  2671. case UPB_TYPE_STRING: return UPB_CTYPE_CONSTPTR;
  2672. case UPB_TYPE_ENUM:
  2673. case UPB_TYPE_INT32: return UPB_CTYPE_INT32;
  2674. case UPB_TYPE_UINT32: return UPB_CTYPE_UINT32;
  2675. case UPB_TYPE_INT64: return UPB_CTYPE_INT64;
  2676. case UPB_TYPE_UINT64: return UPB_CTYPE_UINT64;
  2677. default: UPB_ASSERT(false); return 0;
  2678. }
  2679. }
  2680. static upb_msgval upb_msgval_fromdefault(const upb_fielddef *f) {
  2681. /* TODO(haberman): improve/optimize this (maybe use upb_msgval in fielddef) */
  2682. switch (upb_fielddef_type(f)) {
  2683. case UPB_TYPE_FLOAT:
  2684. return upb_msgval_float(upb_fielddef_defaultfloat(f));
  2685. case UPB_TYPE_DOUBLE:
  2686. return upb_msgval_double(upb_fielddef_defaultdouble(f));
  2687. case UPB_TYPE_BOOL:
  2688. return upb_msgval_bool(upb_fielddef_defaultbool(f));
  2689. case UPB_TYPE_STRING:
  2690. case UPB_TYPE_BYTES: {
  2691. size_t len;
  2692. const char *ptr = upb_fielddef_defaultstr(f, &len);
  2693. return upb_msgval_str(ptr, len);
  2694. }
  2695. case UPB_TYPE_MESSAGE:
  2696. return upb_msgval_msg(NULL);
  2697. case UPB_TYPE_ENUM:
  2698. case UPB_TYPE_INT32:
  2699. return upb_msgval_int32(upb_fielddef_defaultint32(f));
  2700. case UPB_TYPE_UINT32:
  2701. return upb_msgval_uint32(upb_fielddef_defaultuint32(f));
  2702. case UPB_TYPE_INT64:
  2703. return upb_msgval_int64(upb_fielddef_defaultint64(f));
  2704. case UPB_TYPE_UINT64:
  2705. return upb_msgval_uint64(upb_fielddef_defaultuint64(f));
  2706. default:
  2707. UPB_ASSERT(false);
  2708. return upb_msgval_msg(NULL);
  2709. }
  2710. }
  2711. /** upb_msglayout *************************************************************/
  2712. struct upb_msglayout {
  2713. upb_msgfactory *factory;
  2714. const upb_msgdef *msgdef;
  2715. size_t size;
  2716. size_t extdict_offset;
  2717. void *default_msg;
  2718. uint32_t *field_offsets;
  2719. uint32_t *case_offsets;
  2720. uint32_t *hasbits;
  2721. bool has_extdict;
  2722. uint8_t align;
  2723. };
  2724. static void upb_msg_checkfield(const upb_msglayout *l, const upb_fielddef *f) {
  2725. UPB_ASSERT(l->msgdef == upb_fielddef_containingtype(f));
  2726. }
  2727. static void upb_msglayout_free(upb_msglayout *l) {
  2728. upb_gfree(l->default_msg);
  2729. upb_gfree(l);
  2730. }
  2731. const upb_msgdef *upb_msglayout_msgdef(const upb_msglayout *l) {
  2732. return l->msgdef;
  2733. }
  2734. static size_t upb_msglayout_place(upb_msglayout *l, size_t size) {
  2735. size_t ret;
  2736. l->size = align_up(l->size, size);
  2737. l->align = align_up(l->align, size);
  2738. ret = l->size;
  2739. l->size += size;
  2740. return ret;
  2741. }
  2742. static uint32_t upb_msglayout_offset(const upb_msglayout *l,
  2743. const upb_fielddef *f) {
  2744. return l->field_offsets[upb_fielddef_index(f)];
  2745. }
  2746. static uint32_t upb_msglayout_hasbit(const upb_msglayout *l,
  2747. const upb_fielddef *f) {
  2748. return l->hasbits[upb_fielddef_index(f)];
  2749. }
  2750. static bool upb_msglayout_initdefault(upb_msglayout *l) {
  2751. const upb_msgdef *m = l->msgdef;
  2752. upb_msg_field_iter it;
  2753. if (upb_msgdef_syntax(m) == UPB_SYNTAX_PROTO2 && l->size) {
  2754. /* Allocate default message and set default values in it. */
  2755. l->default_msg = upb_gmalloc(l->size);
  2756. if (!l->default_msg) {
  2757. return false;
  2758. }
  2759. memset(l->default_msg, 0, l->size);
  2760. for (upb_msg_field_begin(&it, m); !upb_msg_field_done(&it);
  2761. upb_msg_field_next(&it)) {
  2762. const upb_fielddef* f = upb_msg_iter_field(&it);
  2763. if (upb_fielddef_containingoneof(f)) {
  2764. continue;
  2765. }
  2766. if (!upb_fielddef_isstring(f) &&
  2767. !upb_fielddef_issubmsg(f) &&
  2768. !upb_fielddef_isseq(f)) {
  2769. upb_msg_set(l->default_msg, f, upb_msgval_fromdefault(f), l);
  2770. }
  2771. }
  2772. }
  2773. return true;
  2774. }
  2775. static upb_msglayout *upb_msglayout_new(const upb_msgdef *m) {
  2776. upb_msg_field_iter it;
  2777. upb_msg_oneof_iter oit;
  2778. upb_msglayout *l;
  2779. size_t hasbit;
  2780. size_t array_size = upb_msgdef_numfields(m) + upb_msgdef_numoneofs(m);
  2781. if (upb_msgdef_syntax(m) == UPB_SYNTAX_PROTO2) {
  2782. array_size += upb_msgdef_numfields(m); /* hasbits. */
  2783. }
  2784. l = upb_gmalloc(sizeof(*l) + (sizeof(uint32_t) * array_size));
  2785. if (!l) return NULL;
  2786. memset(l, 0, sizeof(*l));
  2787. l->msgdef = m;
  2788. l->align = 1;
  2789. l->field_offsets = (uint32_t*)CHARPTR_AT(l, sizeof(*l));
  2790. l->case_offsets = l->field_offsets + upb_msgdef_numfields(m);
  2791. l->hasbits = l->case_offsets + upb_msgdef_numoneofs(m);
  2792. /* Allocate data offsets in three stages:
  2793. *
  2794. * 1. hasbits.
  2795. * 2. regular fields.
  2796. * 3. oneof fields.
  2797. *
  2798. * OPT: There is a lot of room for optimization here to minimize the size.
  2799. */
  2800. /* Allocate hasbits. Start at sizeof(void*) for upb_alloc*. */
  2801. for (upb_msg_field_begin(&it, m), hasbit = sizeof(void*) * 8;
  2802. !upb_msg_field_done(&it);
  2803. upb_msg_field_next(&it)) {
  2804. const upb_fielddef* f = upb_msg_iter_field(&it);
  2805. if (upb_fielddef_haspresence(f) && !upb_fielddef_containingoneof(f)) {
  2806. l->hasbits[upb_fielddef_index(f)] = hasbit++;
  2807. }
  2808. }
  2809. /* Account for space used by hasbits. */
  2810. l->size = div_round_up(hasbit, 8);
  2811. /* Allocate non-oneof fields. */
  2812. for (upb_msg_field_begin(&it, m); !upb_msg_field_done(&it);
  2813. upb_msg_field_next(&it)) {
  2814. const upb_fielddef* f = upb_msg_iter_field(&it);
  2815. size_t field_size = upb_msg_fieldsize(f);
  2816. size_t index = upb_fielddef_index(f);
  2817. if (upb_fielddef_containingoneof(f)) {
  2818. /* Oneofs are handled separately below. */
  2819. continue;
  2820. }
  2821. l->field_offsets[index] = upb_msglayout_place(l, field_size);
  2822. }
  2823. /* Allocate oneof fields. Each oneof field consists of a uint32 for the case
  2824. * and space for the actual data. */
  2825. for (upb_msg_oneof_begin(&oit, m); !upb_msg_oneof_done(&oit);
  2826. upb_msg_oneof_next(&oit)) {
  2827. const upb_oneofdef* oneof = upb_msg_iter_oneof(&oit);
  2828. upb_oneof_iter fit;
  2829. size_t case_size = sizeof(uint32_t); /* Could potentially optimize this. */
  2830. size_t field_size = 0;
  2831. size_t case_offset;
  2832. size_t val_offset;
  2833. /* Calculate field size: the max of all field sizes. */
  2834. for (upb_oneof_begin(&fit, oneof);
  2835. !upb_oneof_done(&fit);
  2836. upb_oneof_next(&fit)) {
  2837. const upb_fielddef* f = upb_oneof_iter_field(&fit);
  2838. field_size = UPB_MAX(field_size, upb_msg_fieldsize(f));
  2839. }
  2840. /* Align and allocate case offset. */
  2841. case_offset = upb_msglayout_place(l, case_size);
  2842. val_offset = upb_msglayout_place(l, field_size);
  2843. l->case_offsets[upb_oneofdef_index(oneof)] = case_offset;
  2844. /* Assign all fields in the oneof this same offset. */
  2845. for (upb_oneof_begin(&fit, oneof); !upb_oneof_done(&fit);
  2846. upb_oneof_next(&fit)) {
  2847. const upb_fielddef* f = upb_oneof_iter_field(&fit);
  2848. l->field_offsets[upb_fielddef_index(f)] = val_offset;
  2849. }
  2850. }
  2851. /* Size of the entire structure should be a multiple of its greatest
  2852. * alignment. */
  2853. l->size = align_up(l->size, l->align);
  2854. if (upb_msglayout_initdefault(l)) {
  2855. return l;
  2856. } else {
  2857. upb_msglayout_free(l);
  2858. return NULL;
  2859. }
  2860. }
  2861. upb_msgfactory *upb_msglayout_factory(const upb_msglayout *layout) {
  2862. return layout->factory;
  2863. }
  2864. /** upb_msgfactory ************************************************************/
  2865. struct upb_msgfactory {
  2866. const upb_symtab *symtab; /* We own a ref. */
  2867. upb_inttable layouts;
  2868. upb_inttable mergehandlers;
  2869. };
  2870. upb_msgfactory *upb_msgfactory_new(const upb_symtab *symtab) {
  2871. upb_msgfactory *ret = upb_gmalloc(sizeof(*ret));
  2872. ret->symtab = symtab;
  2873. upb_inttable_init(&ret->layouts, UPB_CTYPE_PTR);
  2874. upb_inttable_init(&ret->mergehandlers, UPB_CTYPE_CONSTPTR);
  2875. return ret;
  2876. }
  2877. void upb_msgfactory_free(upb_msgfactory *f) {
  2878. upb_inttable_iter i;
  2879. upb_inttable_begin(&i, &f->layouts);
  2880. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  2881. upb_msglayout *l = upb_value_getptr(upb_inttable_iter_value(&i));
  2882. upb_msglayout_free(l);
  2883. }
  2884. upb_inttable_begin(&i, &f->mergehandlers);
  2885. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  2886. const upb_handlers *h = upb_value_getconstptr(upb_inttable_iter_value(&i));
  2887. upb_handlers_unref(h, f);
  2888. }
  2889. upb_inttable_uninit(&f->layouts);
  2890. upb_inttable_uninit(&f->mergehandlers);
  2891. upb_gfree(f);
  2892. }
  2893. const upb_symtab *upb_msgfactory_symtab(const upb_msgfactory *f) {
  2894. return f->symtab;
  2895. }
  2896. const upb_msglayout *upb_msgfactory_getlayout(upb_msgfactory *f,
  2897. const upb_msgdef *m) {
  2898. upb_value v;
  2899. UPB_ASSERT(upb_symtab_lookupmsg(f->symtab, upb_msgdef_fullname(m)) == m);
  2900. UPB_ASSERT(!upb_msgdef_mapentry(m));
  2901. if (upb_inttable_lookupptr(&f->layouts, m, &v)) {
  2902. UPB_ASSERT(upb_value_getptr(v));
  2903. return upb_value_getptr(v);
  2904. } else {
  2905. upb_msgfactory *mutable_f = (void*)f;
  2906. upb_msglayout *l = upb_msglayout_new(m);
  2907. upb_inttable_insertptr(&mutable_f->layouts, m, upb_value_ptr(l));
  2908. UPB_ASSERT(l);
  2909. l->factory = f;
  2910. return l;
  2911. }
  2912. }
  2913. /* Our handlers that we don't expose externally. */
  2914. void *upb_msg_startstr(void *msg, const void *hd, size_t size_hint) {
  2915. uint32_t ofs = (uintptr_t)hd;
  2916. /* We pass NULL here because we know we can get away with it. */
  2917. upb_alloc *alloc = upb_msg_alloc(msg, NULL);
  2918. upb_msgval val;
  2919. UPB_UNUSED(size_hint);
  2920. val = upb_msgval_read(msg, ofs, upb_msgval_sizeof(UPB_TYPE_STRING));
  2921. upb_free(alloc, (void*)val.str.ptr);
  2922. val.str.ptr = NULL;
  2923. val.str.len = 0;
  2924. upb_msgval_write(msg, ofs, val, upb_msgval_sizeof(UPB_TYPE_STRING));
  2925. return msg;
  2926. }
  2927. size_t upb_msg_str(void *msg, const void *hd, const char *ptr, size_t size,
  2928. const upb_bufhandle *handle) {
  2929. uint32_t ofs = (uintptr_t)hd;
  2930. /* We pass NULL here because we know we can get away with it. */
  2931. upb_alloc *alloc = upb_msg_alloc(msg, NULL);
  2932. upb_msgval val;
  2933. size_t newsize;
  2934. UPB_UNUSED(handle);
  2935. val = upb_msgval_read(msg, ofs, upb_msgval_sizeof(UPB_TYPE_STRING));
  2936. newsize = val.str.len + size;
  2937. val.str.ptr = upb_realloc(alloc, (void*)val.str.ptr, val.str.len, newsize);
  2938. if (!val.str.ptr) {
  2939. return false;
  2940. }
  2941. memcpy((char*)val.str.ptr + val.str.len, ptr, size);
  2942. val.str.len = newsize;
  2943. upb_msgval_write(msg, ofs, val, upb_msgval_sizeof(UPB_TYPE_STRING));
  2944. return size;
  2945. }
  2946. static void callback(const void *closure, upb_handlers *h) {
  2947. upb_msgfactory *factory = (upb_msgfactory*)closure;
  2948. const upb_msgdef *md = upb_handlers_msgdef(h);
  2949. const upb_msglayout* layout = upb_msgfactory_getlayout(factory, md);
  2950. upb_msg_field_iter i;
  2951. UPB_UNUSED(factory);
  2952. for(upb_msg_field_begin(&i, md);
  2953. !upb_msg_field_done(&i);
  2954. upb_msg_field_next(&i)) {
  2955. const upb_fielddef *f = upb_msg_iter_field(&i);
  2956. size_t offset = upb_msglayout_offset(layout, f);
  2957. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  2958. upb_handlerattr_sethandlerdata(&attr, (void*)offset);
  2959. if (upb_fielddef_isseq(f)) {
  2960. } else if (upb_fielddef_isstring(f)) {
  2961. upb_handlers_setstartstr(h, f, upb_msg_startstr, &attr);
  2962. upb_handlers_setstring(h, f, upb_msg_str, &attr);
  2963. } else {
  2964. upb_msg_setscalarhandler(
  2965. h, f, offset, upb_msglayout_hasbit(layout, f));
  2966. }
  2967. }
  2968. }
  2969. const upb_handlers *upb_msgfactory_getmergehandlers(upb_msgfactory *f,
  2970. const upb_msgdef *m) {
  2971. upb_msgfactory *mutable_f = (void*)f;
  2972. /* TODO(haberman): properly cache these. */
  2973. const upb_handlers *ret = upb_handlers_newfrozen(m, f, callback, f);
  2974. upb_inttable_push(&mutable_f->mergehandlers, upb_value_constptr(ret));
  2975. return ret;
  2976. }
  2977. const upb_visitorplan *upb_msgfactory_getvisitorplan(upb_msgfactory *f,
  2978. const upb_handlers *h) {
  2979. const upb_msgdef *md = upb_handlers_msgdef(h);
  2980. return (const upb_visitorplan*)upb_msgfactory_getlayout(f, md);
  2981. }
  2982. /** upb_visitor ***************************************************************/
  2983. struct upb_visitor {
  2984. const upb_msglayout *layout;
  2985. upb_sink *sink;
  2986. };
  2987. static upb_selector_t getsel2(const upb_fielddef *f, upb_handlertype_t type) {
  2988. upb_selector_t ret;
  2989. bool ok = upb_handlers_getselector(f, type, &ret);
  2990. UPB_ASSERT(ok);
  2991. return ret;
  2992. }
  2993. static bool upb_visitor_hasfield(const upb_msg *msg, const upb_fielddef *f,
  2994. const upb_msglayout *layout) {
  2995. if (upb_fielddef_isseq(f)) {
  2996. return upb_msgval_getarr(upb_msg_get(msg, f, layout)) != NULL;
  2997. } else if (upb_msgdef_syntax(upb_fielddef_containingtype(f)) ==
  2998. UPB_SYNTAX_PROTO2) {
  2999. return upb_msg_has(msg, f, layout);
  3000. } else {
  3001. upb_msgval val = upb_msg_get(msg, f, layout);
  3002. switch (upb_fielddef_type(f)) {
  3003. case UPB_TYPE_FLOAT:
  3004. return upb_msgval_getfloat(val) != 0;
  3005. case UPB_TYPE_DOUBLE:
  3006. return upb_msgval_getdouble(val) != 0;
  3007. case UPB_TYPE_BOOL:
  3008. return upb_msgval_getbool(val);
  3009. case UPB_TYPE_ENUM:
  3010. case UPB_TYPE_INT32:
  3011. return upb_msgval_getint32(val) != 0;
  3012. case UPB_TYPE_UINT32:
  3013. return upb_msgval_getuint32(val) != 0;
  3014. case UPB_TYPE_INT64:
  3015. return upb_msgval_getint64(val) != 0;
  3016. case UPB_TYPE_UINT64:
  3017. return upb_msgval_getuint64(val) != 0;
  3018. case UPB_TYPE_STRING:
  3019. case UPB_TYPE_BYTES:
  3020. return upb_msgval_getstr(val) && upb_msgval_getstrlen(val) > 0;
  3021. case UPB_TYPE_MESSAGE:
  3022. return upb_msgval_getmsg(val) != NULL;
  3023. }
  3024. UPB_UNREACHABLE();
  3025. }
  3026. }
  3027. static bool upb_visitor_visitmsg2(const upb_msg *msg,
  3028. const upb_msglayout *layout, upb_sink *sink,
  3029. int depth) {
  3030. const upb_msgdef *md = upb_msglayout_msgdef(layout);
  3031. upb_msg_field_iter i;
  3032. upb_status status;
  3033. upb_sink_startmsg(sink);
  3034. /* Protect against cycles (possible because users may freely reassign message
  3035. * and repeated fields) by imposing a maximum recursion depth. */
  3036. if (depth > ENCODE_MAX_NESTING) {
  3037. return false;
  3038. }
  3039. for (upb_msg_field_begin(&i, md);
  3040. !upb_msg_field_done(&i);
  3041. upb_msg_field_next(&i)) {
  3042. upb_fielddef *f = upb_msg_iter_field(&i);
  3043. upb_msgval val;
  3044. if (!upb_visitor_hasfield(msg, f, layout)) {
  3045. continue;
  3046. }
  3047. val = upb_msg_get(msg, f, layout);
  3048. if (upb_fielddef_isseq(f)) {
  3049. const upb_array *arr = upb_msgval_getarr(val);
  3050. UPB_ASSERT(arr);
  3051. /* TODO: putary(ary, f, sink, depth);*/
  3052. } else if (upb_fielddef_issubmsg(f)) {
  3053. const upb_map *map = upb_msgval_getmap(val);
  3054. UPB_ASSERT(map);
  3055. /* TODO: putmap(map, f, sink, depth);*/
  3056. } else if (upb_fielddef_isstring(f)) {
  3057. /* TODO putstr(); */
  3058. } else {
  3059. upb_selector_t sel = getsel2(f, upb_handlers_getprimitivehandlertype(f));
  3060. UPB_ASSERT(upb_fielddef_isprimitive(f));
  3061. switch (upb_fielddef_type(f)) {
  3062. case UPB_TYPE_FLOAT:
  3063. CHECK_TRUE(upb_sink_putfloat(sink, sel, upb_msgval_getfloat(val)));
  3064. break;
  3065. case UPB_TYPE_DOUBLE:
  3066. CHECK_TRUE(upb_sink_putdouble(sink, sel, upb_msgval_getdouble(val)));
  3067. break;
  3068. case UPB_TYPE_BOOL:
  3069. CHECK_TRUE(upb_sink_putbool(sink, sel, upb_msgval_getbool(val)));
  3070. break;
  3071. case UPB_TYPE_ENUM:
  3072. case UPB_TYPE_INT32:
  3073. CHECK_TRUE(upb_sink_putint32(sink, sel, upb_msgval_getint32(val)));
  3074. break;
  3075. case UPB_TYPE_UINT32:
  3076. CHECK_TRUE(upb_sink_putuint32(sink, sel, upb_msgval_getuint32(val)));
  3077. break;
  3078. case UPB_TYPE_INT64:
  3079. CHECK_TRUE(upb_sink_putint64(sink, sel, upb_msgval_getint64(val)));
  3080. break;
  3081. case UPB_TYPE_UINT64:
  3082. CHECK_TRUE(upb_sink_putuint64(sink, sel, upb_msgval_getuint64(val)));
  3083. break;
  3084. case UPB_TYPE_STRING:
  3085. case UPB_TYPE_BYTES:
  3086. case UPB_TYPE_MESSAGE:
  3087. UPB_UNREACHABLE();
  3088. }
  3089. }
  3090. }
  3091. upb_sink_endmsg(sink, &status);
  3092. return true;
  3093. }
  3094. upb_visitor *upb_visitor_create(upb_env *e, const upb_visitorplan *vp,
  3095. upb_sink *output) {
  3096. upb_visitor *visitor = upb_env_malloc(e, sizeof(*visitor));
  3097. visitor->layout = (const upb_msglayout*)vp;
  3098. visitor->sink = output;
  3099. return visitor;
  3100. }
  3101. bool upb_visitor_visitmsg(upb_visitor *visitor, const upb_msg *msg) {
  3102. return upb_visitor_visitmsg2(msg, visitor->layout, visitor->sink, 0);
  3103. }
  3104. /** upb_msg *******************************************************************/
  3105. /* If we always read/write as a consistent type to each address, this shouldn't
  3106. * violate aliasing.
  3107. */
  3108. #define DEREF(msg, ofs, type) *(type*)CHARPTR_AT(msg, ofs)
  3109. static upb_inttable *upb_msg_trygetextdict(const upb_msg *msg,
  3110. const upb_msglayout *l) {
  3111. return l->has_extdict ? DEREF(msg, l->extdict_offset, upb_inttable*) : NULL;
  3112. }
  3113. static upb_inttable *upb_msg_getextdict(upb_msg *msg,
  3114. const upb_msglayout *l,
  3115. upb_alloc *a) {
  3116. upb_inttable *ext_dict;
  3117. UPB_ASSERT(l->has_extdict);
  3118. ext_dict = upb_msg_trygetextdict(msg, l);
  3119. if (!ext_dict) {
  3120. ext_dict = upb_malloc(a, sizeof(upb_inttable));
  3121. if (!ext_dict) {
  3122. return NULL;
  3123. }
  3124. /* Use an 8-byte type to ensure all bytes are copied. */
  3125. if (!upb_inttable_init2(ext_dict, UPB_CTYPE_INT64, a)) {
  3126. upb_free(a, ext_dict);
  3127. return NULL;
  3128. }
  3129. DEREF(msg, l->extdict_offset, upb_inttable*) = ext_dict;
  3130. }
  3131. return ext_dict;
  3132. }
  3133. static uint32_t upb_msg_getoneofint(const upb_msg *msg,
  3134. const upb_oneofdef *o,
  3135. const upb_msglayout *l) {
  3136. size_t oneof_ofs = l->case_offsets[upb_oneofdef_index(o)];
  3137. return DEREF(msg, oneof_ofs, uint8_t);
  3138. }
  3139. static void upb_msg_setoneofcase(const upb_msg *msg,
  3140. const upb_oneofdef *o,
  3141. const upb_msglayout *l,
  3142. uint32_t val) {
  3143. size_t oneof_ofs = l->case_offsets[upb_oneofdef_index(o)];
  3144. DEREF(msg, oneof_ofs, uint8_t) = val;
  3145. }
  3146. static bool upb_msg_oneofis(const upb_msg *msg, const upb_msglayout *l,
  3147. const upb_oneofdef *o, const upb_fielddef *f) {
  3148. return upb_msg_getoneofint(msg, o, l) == upb_fielddef_number(f);
  3149. }
  3150. size_t upb_msg_sizeof(const upb_msglayout *l) { return l->size; }
  3151. void upb_msg_init(upb_msg *msg, const upb_msglayout *l, upb_alloc *a) {
  3152. if (l->default_msg) {
  3153. memcpy(msg, l->default_msg, l->size);
  3154. } else {
  3155. memset(msg, 0, l->size);
  3156. }
  3157. /* Set arena pointer. */
  3158. memcpy(msg, &a, sizeof(a));
  3159. }
  3160. void upb_msg_uninit(upb_msg *msg, const upb_msglayout *l) {
  3161. upb_inttable *ext_dict = upb_msg_trygetextdict(msg, l);
  3162. if (ext_dict) {
  3163. upb_inttable_uninit2(ext_dict, upb_msg_alloc(msg, l));
  3164. }
  3165. }
  3166. upb_msg *upb_msg_new(const upb_msglayout *l, upb_alloc *a) {
  3167. upb_msg *msg = upb_malloc(a, upb_msg_sizeof(l));
  3168. if (msg) {
  3169. upb_msg_init(msg, l, a);
  3170. }
  3171. return msg;
  3172. }
  3173. void upb_msg_free(upb_msg *msg, const upb_msglayout *l) {
  3174. upb_msg_uninit(msg, l);
  3175. upb_free(upb_msg_alloc(msg, l), msg);
  3176. }
  3177. upb_alloc *upb_msg_alloc(const upb_msg *msg, const upb_msglayout *l) {
  3178. upb_alloc *alloc;
  3179. UPB_UNUSED(l);
  3180. memcpy(&alloc, msg, sizeof(alloc));
  3181. return alloc;
  3182. }
  3183. bool upb_msg_has(const upb_msg *msg,
  3184. const upb_fielddef *f,
  3185. const upb_msglayout *l) {
  3186. const upb_oneofdef *o;
  3187. upb_msg_checkfield(l, f);
  3188. UPB_ASSERT(upb_fielddef_haspresence(f));
  3189. if (upb_fielddef_isextension(f)) {
  3190. /* Extensions are set when they are present in the extension dict. */
  3191. upb_inttable *ext_dict = upb_msg_trygetextdict(msg, l);
  3192. upb_value v;
  3193. return ext_dict != NULL &&
  3194. upb_inttable_lookup32(ext_dict, upb_fielddef_number(f), &v);
  3195. } else if ((o = upb_fielddef_containingoneof(f)) != NULL) {
  3196. /* Oneofs are set when the oneof number is set to this field. */
  3197. return upb_msg_getoneofint(msg, o, l) == upb_fielddef_number(f);
  3198. } else {
  3199. /* Other fields are set when their hasbit is set. */
  3200. uint32_t hasbit = l->hasbits[upb_fielddef_index(f)];
  3201. return DEREF(msg, hasbit / 8, char) | (1 << (hasbit % 8));
  3202. }
  3203. }
  3204. upb_msgval upb_msg_get(const upb_msg *msg, const upb_fielddef *f,
  3205. const upb_msglayout *l) {
  3206. upb_msg_checkfield(l, f);
  3207. if (upb_fielddef_isextension(f)) {
  3208. upb_inttable *ext_dict = upb_msg_trygetextdict(msg, l);
  3209. upb_value val;
  3210. if (upb_inttable_lookup32(ext_dict, upb_fielddef_number(f), &val)) {
  3211. return upb_msgval_fromval(val);
  3212. } else {
  3213. return upb_msgval_fromdefault(f);
  3214. }
  3215. } else {
  3216. size_t ofs = l->field_offsets[upb_fielddef_index(f)];
  3217. const upb_oneofdef *o = upb_fielddef_containingoneof(f);
  3218. upb_msgval ret;
  3219. if (o && !upb_msg_oneofis(msg, l, o, f)) {
  3220. /* Oneof defaults can't come from the message because the memory is reused
  3221. * by all types in the oneof. */
  3222. return upb_msgval_fromdefault(f);
  3223. }
  3224. ret = upb_msgval_read(msg, ofs, upb_msg_fieldsize(f));
  3225. return ret;
  3226. }
  3227. }
  3228. bool upb_msg_set(upb_msg *msg,
  3229. const upb_fielddef *f,
  3230. upb_msgval val,
  3231. const upb_msglayout *l) {
  3232. upb_alloc *a = upb_msg_alloc(msg, l);
  3233. upb_msg_checkfield(l, f);
  3234. if (upb_fielddef_isextension(f)) {
  3235. /* TODO(haberman): introduce table API that can do this in one call. */
  3236. upb_inttable *ext = upb_msg_getextdict(msg, l, a);
  3237. upb_value val2 = upb_toval(val);
  3238. if (!upb_inttable_replace(ext, upb_fielddef_number(f), val2) &&
  3239. !upb_inttable_insert2(ext, upb_fielddef_number(f), val2, a)) {
  3240. return false;
  3241. }
  3242. } else {
  3243. size_t ofs = l->field_offsets[upb_fielddef_index(f)];
  3244. const upb_oneofdef *o = upb_fielddef_containingoneof(f);
  3245. if (o) {
  3246. upb_msg_setoneofcase(msg, o, l, upb_fielddef_number(f));
  3247. }
  3248. upb_msgval_write(msg, ofs, val, upb_msg_fieldsize(f));
  3249. }
  3250. return true;
  3251. }
  3252. /** upb_array *****************************************************************/
  3253. struct upb_array {
  3254. upb_fieldtype_t type;
  3255. uint8_t element_size;
  3256. void *data; /* Each element is element_size. */
  3257. size_t len; /* Measured in elements. */
  3258. size_t size; /* Measured in elements. */
  3259. upb_alloc *alloc;
  3260. };
  3261. #define DEREF_ARR(arr, i, type) ((type*)arr->data)[i]
  3262. size_t upb_array_sizeof(upb_fieldtype_t type) {
  3263. UPB_UNUSED(type);
  3264. return sizeof(upb_array);
  3265. }
  3266. void upb_array_init(upb_array *arr, upb_fieldtype_t type, upb_alloc *alloc) {
  3267. arr->type = type;
  3268. arr->data = NULL;
  3269. arr->len = 0;
  3270. arr->size = 0;
  3271. arr->element_size = upb_msgval_sizeof(type);
  3272. arr->alloc = alloc;
  3273. }
  3274. void upb_array_uninit(upb_array *arr) {
  3275. upb_free(arr->alloc, arr->data);
  3276. }
  3277. upb_array *upb_array_new(upb_fieldtype_t type, upb_alloc *a) {
  3278. upb_array *ret = upb_malloc(a, upb_array_sizeof(type));
  3279. if (ret) {
  3280. upb_array_init(ret, type, a);
  3281. }
  3282. return ret;
  3283. }
  3284. void upb_array_free(upb_array *arr) {
  3285. upb_array_uninit(arr);
  3286. upb_free(arr->alloc, arr);
  3287. }
  3288. size_t upb_array_size(const upb_array *arr) {
  3289. return arr->len;
  3290. }
  3291. upb_fieldtype_t upb_array_type(const upb_array *arr) {
  3292. return arr->type;
  3293. }
  3294. upb_msgval upb_array_get(const upb_array *arr, size_t i) {
  3295. UPB_ASSERT(i < arr->len);
  3296. return upb_msgval_read(arr->data, i * arr->element_size, arr->element_size);
  3297. }
  3298. bool upb_array_set(upb_array *arr, size_t i, upb_msgval val) {
  3299. UPB_ASSERT(i <= arr->len);
  3300. if (i == arr->len) {
  3301. /* Extending the array. */
  3302. if (i == arr->size) {
  3303. /* Need to reallocate. */
  3304. size_t new_size = UPB_MAX(arr->size * 2, 8);
  3305. size_t new_bytes = new_size * arr->element_size;
  3306. size_t old_bytes = arr->size * arr->element_size;
  3307. upb_msgval *new_data =
  3308. upb_realloc(arr->alloc, arr->data, old_bytes, new_bytes);
  3309. if (!new_data) {
  3310. return false;
  3311. }
  3312. arr->data = new_data;
  3313. arr->size = new_size;
  3314. }
  3315. arr->len = i + 1;
  3316. }
  3317. upb_msgval_write(arr->data, i * arr->element_size, val, arr->element_size);
  3318. return true;
  3319. }
  3320. /** upb_map *******************************************************************/
  3321. struct upb_map {
  3322. upb_fieldtype_t key_type;
  3323. upb_fieldtype_t val_type;
  3324. /* We may want to optimize this to use inttable where possible, for greater
  3325. * efficiency and lower memory footprint. */
  3326. upb_strtable strtab;
  3327. upb_alloc *alloc;
  3328. };
  3329. static void upb_map_tokey(upb_fieldtype_t type, upb_msgval *key,
  3330. const char **out_key, size_t *out_len) {
  3331. switch (type) {
  3332. case UPB_TYPE_STRING:
  3333. /* Point to string data of the input key. */
  3334. *out_key = key->str.ptr;
  3335. *out_len = key->str.len;
  3336. return;
  3337. case UPB_TYPE_BOOL:
  3338. case UPB_TYPE_INT32:
  3339. case UPB_TYPE_UINT32:
  3340. case UPB_TYPE_INT64:
  3341. case UPB_TYPE_UINT64:
  3342. /* Point to the key itself. XXX: big-endian. */
  3343. *out_key = (const char*)key;
  3344. *out_len = upb_msgval_sizeof(type);
  3345. return;
  3346. case UPB_TYPE_BYTES:
  3347. case UPB_TYPE_DOUBLE:
  3348. case UPB_TYPE_ENUM:
  3349. case UPB_TYPE_FLOAT:
  3350. case UPB_TYPE_MESSAGE:
  3351. break; /* Cannot be a map key. */
  3352. }
  3353. UPB_UNREACHABLE();
  3354. }
  3355. static upb_msgval upb_map_fromkey(upb_fieldtype_t type, const char *key,
  3356. size_t len) {
  3357. switch (type) {
  3358. case UPB_TYPE_STRING:
  3359. return upb_msgval_str(key, len);
  3360. case UPB_TYPE_BOOL:
  3361. case UPB_TYPE_INT32:
  3362. case UPB_TYPE_UINT32:
  3363. case UPB_TYPE_INT64:
  3364. case UPB_TYPE_UINT64:
  3365. return upb_msgval_read(key, 0, upb_msgval_sizeof(type));
  3366. case UPB_TYPE_BYTES:
  3367. case UPB_TYPE_DOUBLE:
  3368. case UPB_TYPE_ENUM:
  3369. case UPB_TYPE_FLOAT:
  3370. case UPB_TYPE_MESSAGE:
  3371. break; /* Cannot be a map key. */
  3372. }
  3373. UPB_UNREACHABLE();
  3374. }
  3375. size_t upb_map_sizeof(upb_fieldtype_t ktype, upb_fieldtype_t vtype) {
  3376. /* Size does not currently depend on key/value type. */
  3377. UPB_UNUSED(ktype);
  3378. UPB_UNUSED(vtype);
  3379. return sizeof(upb_map);
  3380. }
  3381. bool upb_map_init(upb_map *map, upb_fieldtype_t ktype, upb_fieldtype_t vtype,
  3382. upb_alloc *a) {
  3383. upb_ctype_t vtabtype = upb_fieldtotabtype(vtype);
  3384. UPB_ASSERT(upb_fieldtype_mapkeyok(ktype));
  3385. map->key_type = ktype;
  3386. map->val_type = vtype;
  3387. map->alloc = a;
  3388. if (!upb_strtable_init2(&map->strtab, vtabtype, a)) {
  3389. return false;
  3390. }
  3391. return true;
  3392. }
  3393. void upb_map_uninit(upb_map *map) {
  3394. upb_strtable_uninit2(&map->strtab, map->alloc);
  3395. }
  3396. upb_map *upb_map_new(upb_fieldtype_t ktype, upb_fieldtype_t vtype,
  3397. upb_alloc *a) {
  3398. upb_map *map = upb_malloc(a, upb_map_sizeof(ktype, vtype));
  3399. if (!map) {
  3400. return NULL;
  3401. }
  3402. if (!upb_map_init(map, ktype, vtype, a)) {
  3403. return NULL;
  3404. }
  3405. return map;
  3406. }
  3407. void upb_map_free(upb_map *map) {
  3408. upb_map_uninit(map);
  3409. upb_free(map->alloc, map);
  3410. }
  3411. size_t upb_map_size(const upb_map *map) {
  3412. return upb_strtable_count(&map->strtab);
  3413. }
  3414. upb_fieldtype_t upb_map_keytype(const upb_map *map) {
  3415. return map->key_type;
  3416. }
  3417. upb_fieldtype_t upb_map_valuetype(const upb_map *map) {
  3418. return map->val_type;
  3419. }
  3420. bool upb_map_get(const upb_map *map, upb_msgval key, upb_msgval *val) {
  3421. upb_value tabval;
  3422. const char *key_str;
  3423. size_t key_len;
  3424. bool ret;
  3425. upb_map_tokey(map->key_type, &key, &key_str, &key_len);
  3426. ret = upb_strtable_lookup2(&map->strtab, key_str, key_len, &tabval);
  3427. if (ret) {
  3428. memcpy(val, &tabval, sizeof(tabval));
  3429. }
  3430. return ret;
  3431. }
  3432. bool upb_map_set(upb_map *map, upb_msgval key, upb_msgval val,
  3433. upb_msgval *removed) {
  3434. const char *key_str;
  3435. size_t key_len;
  3436. upb_value tabval = upb_toval(val);
  3437. upb_value removedtabval;
  3438. upb_alloc *a = map->alloc;
  3439. upb_map_tokey(map->key_type, &key, &key_str, &key_len);
  3440. /* TODO(haberman): add overwrite operation to minimize number of lookups. */
  3441. if (upb_strtable_lookup2(&map->strtab, key_str, key_len, NULL)) {
  3442. upb_strtable_remove3(&map->strtab, key_str, key_len, &removedtabval, a);
  3443. memcpy(&removed, &removedtabval, sizeof(removed));
  3444. }
  3445. return upb_strtable_insert3(&map->strtab, key_str, key_len, tabval, a);
  3446. }
  3447. bool upb_map_del(upb_map *map, upb_msgval key) {
  3448. const char *key_str;
  3449. size_t key_len;
  3450. upb_alloc *a = map->alloc;
  3451. upb_map_tokey(map->key_type, &key, &key_str, &key_len);
  3452. return upb_strtable_remove3(&map->strtab, key_str, key_len, NULL, a);
  3453. }
  3454. /** upb_mapiter ***************************************************************/
  3455. struct upb_mapiter {
  3456. upb_strtable_iter iter;
  3457. upb_fieldtype_t key_type;
  3458. };
  3459. size_t upb_mapiter_sizeof() {
  3460. return sizeof(upb_mapiter);
  3461. }
  3462. void upb_mapiter_begin(upb_mapiter *i, const upb_map *map) {
  3463. upb_strtable_begin(&i->iter, &map->strtab);
  3464. i->key_type = map->key_type;
  3465. }
  3466. upb_mapiter *upb_mapiter_new(const upb_map *t, upb_alloc *a) {
  3467. upb_mapiter *ret = upb_malloc(a, upb_mapiter_sizeof());
  3468. if (!ret) {
  3469. return NULL;
  3470. }
  3471. upb_mapiter_begin(ret, t);
  3472. return ret;
  3473. }
  3474. void upb_mapiter_free(upb_mapiter *i, upb_alloc *a) {
  3475. upb_free(a, i);
  3476. }
  3477. void upb_mapiter_next(upb_mapiter *i) {
  3478. upb_strtable_next(&i->iter);
  3479. }
  3480. bool upb_mapiter_done(const upb_mapiter *i) {
  3481. return upb_strtable_done(&i->iter);
  3482. }
  3483. upb_msgval upb_mapiter_key(const upb_mapiter *i) {
  3484. return upb_map_fromkey(i->key_type, upb_strtable_iter_key(&i->iter),
  3485. upb_strtable_iter_keylength(&i->iter));
  3486. }
  3487. upb_msgval upb_mapiter_value(const upb_mapiter *i) {
  3488. return upb_msgval_fromval(upb_strtable_iter_value(&i->iter));
  3489. }
  3490. void upb_mapiter_setdone(upb_mapiter *i) {
  3491. upb_strtable_iter_setdone(&i->iter);
  3492. }
  3493. bool upb_mapiter_isequal(const upb_mapiter *i1, const upb_mapiter *i2) {
  3494. return upb_strtable_iter_isequal(&i1->iter, &i2->iter);
  3495. }
  3496. /** Handlers for upb_msg ******************************************************/
  3497. typedef struct {
  3498. size_t offset;
  3499. int32_t hasbit;
  3500. } upb_msg_handlerdata;
  3501. /* Fallback implementation if the handler is not specialized by the producer. */
  3502. #define MSG_WRITER(type, ctype) \
  3503. bool upb_msg_set ## type (void *c, const void *hd, ctype val) { \
  3504. uint8_t *m = c; \
  3505. const upb_msg_handlerdata *d = hd; \
  3506. if (d->hasbit > 0) \
  3507. *(uint8_t*)&m[d->hasbit / 8] |= 1 << (d->hasbit % 8); \
  3508. *(ctype*)&m[d->offset] = val; \
  3509. return true; \
  3510. } \
  3511. MSG_WRITER(double, double)
  3512. MSG_WRITER(float, float)
  3513. MSG_WRITER(int32, int32_t)
  3514. MSG_WRITER(int64, int64_t)
  3515. MSG_WRITER(uint32, uint32_t)
  3516. MSG_WRITER(uint64, uint64_t)
  3517. MSG_WRITER(bool, bool)
  3518. bool upb_msg_setscalarhandler(upb_handlers *h, const upb_fielddef *f,
  3519. size_t offset, int32_t hasbit) {
  3520. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  3521. bool ok;
  3522. upb_msg_handlerdata *d = upb_gmalloc(sizeof(*d));
  3523. if (!d) return false;
  3524. d->offset = offset;
  3525. d->hasbit = hasbit;
  3526. upb_handlerattr_sethandlerdata(&attr, d);
  3527. upb_handlerattr_setalwaysok(&attr, true);
  3528. upb_handlers_addcleanup(h, d, upb_gfree);
  3529. #define TYPE(u, l) \
  3530. case UPB_TYPE_##u: \
  3531. ok = upb_handlers_set##l(h, f, upb_msg_set##l, &attr); break;
  3532. ok = false;
  3533. switch (upb_fielddef_type(f)) {
  3534. TYPE(INT64, int64);
  3535. TYPE(INT32, int32);
  3536. TYPE(ENUM, int32);
  3537. TYPE(UINT64, uint64);
  3538. TYPE(UINT32, uint32);
  3539. TYPE(DOUBLE, double);
  3540. TYPE(FLOAT, float);
  3541. TYPE(BOOL, bool);
  3542. default: UPB_ASSERT(false); break;
  3543. }
  3544. #undef TYPE
  3545. upb_handlerattr_uninit(&attr);
  3546. return ok;
  3547. }
  3548. bool upb_msg_getscalarhandlerdata(const upb_handlers *h,
  3549. upb_selector_t s,
  3550. upb_fieldtype_t *type,
  3551. size_t *offset,
  3552. int32_t *hasbit) {
  3553. const upb_msg_handlerdata *d;
  3554. upb_func *f = upb_handlers_gethandler(h, s);
  3555. if ((upb_int64_handlerfunc*)f == upb_msg_setint64) {
  3556. *type = UPB_TYPE_INT64;
  3557. } else if ((upb_int32_handlerfunc*)f == upb_msg_setint32) {
  3558. *type = UPB_TYPE_INT32;
  3559. } else if ((upb_uint64_handlerfunc*)f == upb_msg_setuint64) {
  3560. *type = UPB_TYPE_UINT64;
  3561. } else if ((upb_uint32_handlerfunc*)f == upb_msg_setuint32) {
  3562. *type = UPB_TYPE_UINT32;
  3563. } else if ((upb_double_handlerfunc*)f == upb_msg_setdouble) {
  3564. *type = UPB_TYPE_DOUBLE;
  3565. } else if ((upb_float_handlerfunc*)f == upb_msg_setfloat) {
  3566. *type = UPB_TYPE_FLOAT;
  3567. } else if ((upb_bool_handlerfunc*)f == upb_msg_setbool) {
  3568. *type = UPB_TYPE_BOOL;
  3569. } else {
  3570. return false;
  3571. }
  3572. d = upb_handlers_gethandlerdata(h, s);
  3573. *offset = d->offset;
  3574. *hasbit = d->hasbit;
  3575. return true;
  3576. }
  3577. /*
  3578. ** upb::RefCounted Implementation
  3579. **
  3580. ** Our key invariants are:
  3581. ** 1. reference cycles never span groups
  3582. ** 2. for ref2(to, from), we increment to's count iff group(from) != group(to)
  3583. **
  3584. ** The previous two are how we avoid leaking cycles. Other important
  3585. ** invariants are:
  3586. ** 3. for mutable objects "from" and "to", if there exists a ref2(to, from)
  3587. ** this implies group(from) == group(to). (In practice, what we implement
  3588. ** is even stronger; "from" and "to" will share a group if there has *ever*
  3589. ** been a ref2(to, from), but all that is necessary for correctness is the
  3590. ** weaker one).
  3591. ** 4. mutable and immutable objects are never in the same group.
  3592. */
  3593. #include <setjmp.h>
  3594. static void freeobj(upb_refcounted *o);
  3595. const char untracked_val;
  3596. const void *UPB_UNTRACKED_REF = &untracked_val;
  3597. /* arch-specific atomic primitives *******************************************/
  3598. #ifdef UPB_THREAD_UNSAFE /*---------------------------------------------------*/
  3599. static void atomic_inc(uint32_t *a) { (*a)++; }
  3600. static bool atomic_dec(uint32_t *a) { return --(*a) == 0; }
  3601. #elif defined(__GNUC__) || defined(__clang__) /*------------------------------*/
  3602. static void atomic_inc(uint32_t *a) { __sync_fetch_and_add(a, 1); }
  3603. static bool atomic_dec(uint32_t *a) { return __sync_sub_and_fetch(a, 1) == 0; }
  3604. #elif defined(WIN32) /*-------------------------------------------------------*/
  3605. #include <Windows.h>
  3606. static void atomic_inc(upb_atomic_t *a) { InterlockedIncrement(&a->val); }
  3607. static bool atomic_dec(upb_atomic_t *a) {
  3608. return InterlockedDecrement(&a->val) == 0;
  3609. }
  3610. #else
  3611. #error Atomic primitives not defined for your platform/CPU. \
  3612. Implement them or compile with UPB_THREAD_UNSAFE.
  3613. #endif
  3614. /* All static objects point to this refcount.
  3615. * It is special-cased in ref/unref below. */
  3616. uint32_t static_refcount = -1;
  3617. /* We can avoid atomic ops for statically-declared objects.
  3618. * This is a minor optimization but nice since we can avoid degrading under
  3619. * contention in this case. */
  3620. static void refgroup(uint32_t *group) {
  3621. if (group != &static_refcount)
  3622. atomic_inc(group);
  3623. }
  3624. static bool unrefgroup(uint32_t *group) {
  3625. if (group == &static_refcount) {
  3626. return false;
  3627. } else {
  3628. return atomic_dec(group);
  3629. }
  3630. }
  3631. /* Reference tracking (debug only) ********************************************/
  3632. #ifdef UPB_DEBUG_REFS
  3633. #ifdef UPB_THREAD_UNSAFE
  3634. static void upb_lock() {}
  3635. static void upb_unlock() {}
  3636. #else
  3637. /* User must define functions that lock/unlock a global mutex and link this
  3638. * file against them. */
  3639. void upb_lock();
  3640. void upb_unlock();
  3641. #endif
  3642. /* UPB_DEBUG_REFS mode counts on being able to malloc() memory in some
  3643. * code-paths that can normally never fail, like upb_refcounted_ref(). Since
  3644. * we have no way to propagage out-of-memory errors back to the user, and since
  3645. * these errors can only occur in UPB_DEBUG_REFS mode, we use an allocator that
  3646. * immediately aborts on failure (avoiding the global allocator, which might
  3647. * inject failures). */
  3648. #include <stdlib.h>
  3649. static void *upb_debugrefs_allocfunc(upb_alloc *alloc, void *ptr,
  3650. size_t oldsize, size_t size) {
  3651. UPB_UNUSED(alloc);
  3652. UPB_UNUSED(oldsize);
  3653. if (size == 0) {
  3654. free(ptr);
  3655. return NULL;
  3656. } else {
  3657. void *ret = realloc(ptr, size);
  3658. if (!ret) {
  3659. abort();
  3660. }
  3661. return ret;
  3662. }
  3663. }
  3664. upb_alloc upb_alloc_debugrefs = {&upb_debugrefs_allocfunc};
  3665. typedef struct {
  3666. int count; /* How many refs there are (duplicates only allowed for ref2). */
  3667. bool is_ref2;
  3668. } trackedref;
  3669. static trackedref *trackedref_new(bool is_ref2) {
  3670. trackedref *ret = upb_malloc(&upb_alloc_debugrefs, sizeof(*ret));
  3671. ret->count = 1;
  3672. ret->is_ref2 = is_ref2;
  3673. return ret;
  3674. }
  3675. static void track(const upb_refcounted *r, const void *owner, bool ref2) {
  3676. upb_value v;
  3677. UPB_ASSERT(owner);
  3678. if (owner == UPB_UNTRACKED_REF) return;
  3679. upb_lock();
  3680. if (upb_inttable_lookupptr(r->refs, owner, &v)) {
  3681. trackedref *ref = upb_value_getptr(v);
  3682. /* Since we allow multiple ref2's for the same to/from pair without
  3683. * allocating separate memory for each one, we lose the fine-grained
  3684. * tracking behavior we get with regular refs. Since ref2s only happen
  3685. * inside upb, we'll accept this limitation until/unless there is a really
  3686. * difficult upb-internal bug that can't be figured out without it. */
  3687. UPB_ASSERT(ref2);
  3688. UPB_ASSERT(ref->is_ref2);
  3689. ref->count++;
  3690. } else {
  3691. trackedref *ref = trackedref_new(ref2);
  3692. upb_inttable_insertptr2(r->refs, owner, upb_value_ptr(ref),
  3693. &upb_alloc_debugrefs);
  3694. if (ref2) {
  3695. /* We know this cast is safe when it is a ref2, because it's coming from
  3696. * another refcounted object. */
  3697. const upb_refcounted *from = owner;
  3698. UPB_ASSERT(!upb_inttable_lookupptr(from->ref2s, r, NULL));
  3699. upb_inttable_insertptr2(from->ref2s, r, upb_value_ptr(NULL),
  3700. &upb_alloc_debugrefs);
  3701. }
  3702. }
  3703. upb_unlock();
  3704. }
  3705. static void untrack(const upb_refcounted *r, const void *owner, bool ref2) {
  3706. upb_value v;
  3707. bool found;
  3708. trackedref *ref;
  3709. UPB_ASSERT(owner);
  3710. if (owner == UPB_UNTRACKED_REF) return;
  3711. upb_lock();
  3712. found = upb_inttable_lookupptr(r->refs, owner, &v);
  3713. /* This assert will fail if an owner attempts to release a ref it didn't have. */
  3714. UPB_ASSERT(found);
  3715. ref = upb_value_getptr(v);
  3716. UPB_ASSERT(ref->is_ref2 == ref2);
  3717. if (--ref->count == 0) {
  3718. free(ref);
  3719. upb_inttable_removeptr(r->refs, owner, NULL);
  3720. if (ref2) {
  3721. /* We know this cast is safe when it is a ref2, because it's coming from
  3722. * another refcounted object. */
  3723. const upb_refcounted *from = owner;
  3724. bool removed = upb_inttable_removeptr(from->ref2s, r, NULL);
  3725. UPB_ASSERT(removed);
  3726. }
  3727. }
  3728. upb_unlock();
  3729. }
  3730. static void checkref(const upb_refcounted *r, const void *owner, bool ref2) {
  3731. upb_value v;
  3732. bool found;
  3733. trackedref *ref;
  3734. upb_lock();
  3735. found = upb_inttable_lookupptr(r->refs, owner, &v);
  3736. UPB_ASSERT(found);
  3737. ref = upb_value_getptr(v);
  3738. UPB_ASSERT(ref->is_ref2 == ref2);
  3739. upb_unlock();
  3740. }
  3741. /* Populates the given UPB_CTYPE_INT32 inttable with counts of ref2's that
  3742. * originate from the given owner. */
  3743. static void getref2s(const upb_refcounted *owner, upb_inttable *tab) {
  3744. upb_inttable_iter i;
  3745. upb_lock();
  3746. upb_inttable_begin(&i, owner->ref2s);
  3747. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  3748. upb_value v;
  3749. upb_value count;
  3750. trackedref *ref;
  3751. bool found;
  3752. upb_refcounted *to = (upb_refcounted*)upb_inttable_iter_key(&i);
  3753. /* To get the count we need to look in the target's table. */
  3754. found = upb_inttable_lookupptr(to->refs, owner, &v);
  3755. UPB_ASSERT(found);
  3756. ref = upb_value_getptr(v);
  3757. count = upb_value_int32(ref->count);
  3758. upb_inttable_insertptr2(tab, to, count, &upb_alloc_debugrefs);
  3759. }
  3760. upb_unlock();
  3761. }
  3762. typedef struct {
  3763. upb_inttable ref2;
  3764. const upb_refcounted *obj;
  3765. } check_state;
  3766. static void visit_check(const upb_refcounted *obj, const upb_refcounted *subobj,
  3767. void *closure) {
  3768. check_state *s = closure;
  3769. upb_inttable *ref2 = &s->ref2;
  3770. upb_value v;
  3771. bool removed;
  3772. int32_t newcount;
  3773. UPB_ASSERT(obj == s->obj);
  3774. UPB_ASSERT(subobj);
  3775. removed = upb_inttable_removeptr(ref2, subobj, &v);
  3776. /* The following assertion will fail if the visit() function visits a subobj
  3777. * that it did not have a ref2 on, or visits the same subobj too many times. */
  3778. UPB_ASSERT(removed);
  3779. newcount = upb_value_getint32(v) - 1;
  3780. if (newcount > 0) {
  3781. upb_inttable_insert2(ref2, (uintptr_t)subobj, upb_value_int32(newcount),
  3782. &upb_alloc_debugrefs);
  3783. }
  3784. }
  3785. static void visit(const upb_refcounted *r, upb_refcounted_visit *v,
  3786. void *closure) {
  3787. /* In DEBUG_REFS mode we know what existing ref2 refs there are, so we know
  3788. * exactly the set of nodes that visit() should visit. So we verify visit()'s
  3789. * correctness here. */
  3790. check_state state;
  3791. state.obj = r;
  3792. upb_inttable_init2(&state.ref2, UPB_CTYPE_INT32, &upb_alloc_debugrefs);
  3793. getref2s(r, &state.ref2);
  3794. /* This should visit any children in the ref2 table. */
  3795. if (r->vtbl->visit) r->vtbl->visit(r, visit_check, &state);
  3796. /* This assertion will fail if the visit() function missed any children. */
  3797. UPB_ASSERT(upb_inttable_count(&state.ref2) == 0);
  3798. upb_inttable_uninit2(&state.ref2, &upb_alloc_debugrefs);
  3799. if (r->vtbl->visit) r->vtbl->visit(r, v, closure);
  3800. }
  3801. static void trackinit(upb_refcounted *r) {
  3802. r->refs = upb_malloc(&upb_alloc_debugrefs, sizeof(*r->refs));
  3803. r->ref2s = upb_malloc(&upb_alloc_debugrefs, sizeof(*r->ref2s));
  3804. upb_inttable_init2(r->refs, UPB_CTYPE_PTR, &upb_alloc_debugrefs);
  3805. upb_inttable_init2(r->ref2s, UPB_CTYPE_PTR, &upb_alloc_debugrefs);
  3806. }
  3807. static void trackfree(const upb_refcounted *r) {
  3808. upb_inttable_uninit2(r->refs, &upb_alloc_debugrefs);
  3809. upb_inttable_uninit2(r->ref2s, &upb_alloc_debugrefs);
  3810. upb_free(&upb_alloc_debugrefs, r->refs);
  3811. upb_free(&upb_alloc_debugrefs, r->ref2s);
  3812. }
  3813. #else
  3814. static void track(const upb_refcounted *r, const void *owner, bool ref2) {
  3815. UPB_UNUSED(r);
  3816. UPB_UNUSED(owner);
  3817. UPB_UNUSED(ref2);
  3818. }
  3819. static void untrack(const upb_refcounted *r, const void *owner, bool ref2) {
  3820. UPB_UNUSED(r);
  3821. UPB_UNUSED(owner);
  3822. UPB_UNUSED(ref2);
  3823. }
  3824. static void checkref(const upb_refcounted *r, const void *owner, bool ref2) {
  3825. UPB_UNUSED(r);
  3826. UPB_UNUSED(owner);
  3827. UPB_UNUSED(ref2);
  3828. }
  3829. static void trackinit(upb_refcounted *r) {
  3830. UPB_UNUSED(r);
  3831. }
  3832. static void trackfree(const upb_refcounted *r) {
  3833. UPB_UNUSED(r);
  3834. }
  3835. static void visit(const upb_refcounted *r, upb_refcounted_visit *v,
  3836. void *closure) {
  3837. if (r->vtbl->visit) r->vtbl->visit(r, v, closure);
  3838. }
  3839. #endif /* UPB_DEBUG_REFS */
  3840. /* freeze() *******************************************************************/
  3841. /* The freeze() operation is by far the most complicated part of this scheme.
  3842. * We compute strongly-connected components and then mutate the graph such that
  3843. * we preserve the invariants documented at the top of this file. And we must
  3844. * handle out-of-memory errors gracefully (without leaving the graph
  3845. * inconsistent), which adds to the fun. */
  3846. /* The state used by the freeze operation (shared across many functions). */
  3847. typedef struct {
  3848. int depth;
  3849. int maxdepth;
  3850. uint64_t index;
  3851. /* Maps upb_refcounted* -> attributes (color, etc). attr layout varies by
  3852. * color. */
  3853. upb_inttable objattr;
  3854. upb_inttable stack; /* stack of upb_refcounted* for Tarjan's algorithm. */
  3855. upb_inttable groups; /* array of uint32_t*, malloc'd refcounts for new groups */
  3856. upb_status *status;
  3857. jmp_buf err;
  3858. } tarjan;
  3859. static void release_ref2(const upb_refcounted *obj,
  3860. const upb_refcounted *subobj,
  3861. void *closure);
  3862. /* Node attributes -----------------------------------------------------------*/
  3863. /* After our analysis phase all nodes will be either GRAY or WHITE. */
  3864. typedef enum {
  3865. BLACK = 0, /* Object has not been seen. */
  3866. GRAY, /* Object has been found via a refgroup but may not be reachable. */
  3867. GREEN, /* Object is reachable and is currently on the Tarjan stack. */
  3868. WHITE /* Object is reachable and has been assigned a group (SCC). */
  3869. } color_t;
  3870. UPB_NORETURN static void err(tarjan *t) { longjmp(t->err, 1); }
  3871. UPB_NORETURN static void oom(tarjan *t) {
  3872. upb_status_seterrmsg(t->status, "out of memory");
  3873. err(t);
  3874. }
  3875. static uint64_t trygetattr(const tarjan *t, const upb_refcounted *r) {
  3876. upb_value v;
  3877. return upb_inttable_lookupptr(&t->objattr, r, &v) ?
  3878. upb_value_getuint64(v) : 0;
  3879. }
  3880. static uint64_t getattr(const tarjan *t, const upb_refcounted *r) {
  3881. upb_value v;
  3882. bool found = upb_inttable_lookupptr(&t->objattr, r, &v);
  3883. UPB_ASSERT(found);
  3884. return upb_value_getuint64(v);
  3885. }
  3886. static void setattr(tarjan *t, const upb_refcounted *r, uint64_t attr) {
  3887. upb_inttable_removeptr(&t->objattr, r, NULL);
  3888. upb_inttable_insertptr(&t->objattr, r, upb_value_uint64(attr));
  3889. }
  3890. static color_t color(tarjan *t, const upb_refcounted *r) {
  3891. return trygetattr(t, r) & 0x3; /* Color is always stored in the low 2 bits. */
  3892. }
  3893. static void set_gray(tarjan *t, const upb_refcounted *r) {
  3894. UPB_ASSERT(color(t, r) == BLACK);
  3895. setattr(t, r, GRAY);
  3896. }
  3897. /* Pushes an obj onto the Tarjan stack and sets it to GREEN. */
  3898. static void push(tarjan *t, const upb_refcounted *r) {
  3899. UPB_ASSERT(color(t, r) == BLACK || color(t, r) == GRAY);
  3900. /* This defines the attr layout for the GREEN state. "index" and "lowlink"
  3901. * get 31 bits, which is plenty (limit of 2B objects frozen at a time). */
  3902. setattr(t, r, GREEN | (t->index << 2) | (t->index << 33));
  3903. if (++t->index == 0x80000000) {
  3904. upb_status_seterrmsg(t->status, "too many objects to freeze");
  3905. err(t);
  3906. }
  3907. upb_inttable_push(&t->stack, upb_value_ptr((void*)r));
  3908. }
  3909. /* Pops an obj from the Tarjan stack and sets it to WHITE, with a ptr to its
  3910. * SCC group. */
  3911. static upb_refcounted *pop(tarjan *t) {
  3912. upb_refcounted *r = upb_value_getptr(upb_inttable_pop(&t->stack));
  3913. UPB_ASSERT(color(t, r) == GREEN);
  3914. /* This defines the attr layout for nodes in the WHITE state.
  3915. * Top of group stack is [group, NULL]; we point at group. */
  3916. setattr(t, r, WHITE | (upb_inttable_count(&t->groups) - 2) << 8);
  3917. return r;
  3918. }
  3919. static void tarjan_newgroup(tarjan *t) {
  3920. uint32_t *group = upb_gmalloc(sizeof(*group));
  3921. if (!group) oom(t);
  3922. /* Push group and empty group leader (we'll fill in leader later). */
  3923. if (!upb_inttable_push(&t->groups, upb_value_ptr(group)) ||
  3924. !upb_inttable_push(&t->groups, upb_value_ptr(NULL))) {
  3925. upb_gfree(group);
  3926. oom(t);
  3927. }
  3928. *group = 0;
  3929. }
  3930. static uint32_t idx(tarjan *t, const upb_refcounted *r) {
  3931. UPB_ASSERT(color(t, r) == GREEN);
  3932. return (getattr(t, r) >> 2) & 0x7FFFFFFF;
  3933. }
  3934. static uint32_t lowlink(tarjan *t, const upb_refcounted *r) {
  3935. if (color(t, r) == GREEN) {
  3936. return getattr(t, r) >> 33;
  3937. } else {
  3938. return UINT32_MAX;
  3939. }
  3940. }
  3941. static void set_lowlink(tarjan *t, const upb_refcounted *r, uint32_t lowlink) {
  3942. UPB_ASSERT(color(t, r) == GREEN);
  3943. setattr(t, r, ((uint64_t)lowlink << 33) | (getattr(t, r) & 0x1FFFFFFFF));
  3944. }
  3945. static uint32_t *group(tarjan *t, upb_refcounted *r) {
  3946. uint64_t groupnum;
  3947. upb_value v;
  3948. bool found;
  3949. UPB_ASSERT(color(t, r) == WHITE);
  3950. groupnum = getattr(t, r) >> 8;
  3951. found = upb_inttable_lookup(&t->groups, groupnum, &v);
  3952. UPB_ASSERT(found);
  3953. return upb_value_getptr(v);
  3954. }
  3955. /* If the group leader for this object's group has not previously been set,
  3956. * the given object is assigned to be its leader. */
  3957. static upb_refcounted *groupleader(tarjan *t, upb_refcounted *r) {
  3958. uint64_t leader_slot;
  3959. upb_value v;
  3960. bool found;
  3961. UPB_ASSERT(color(t, r) == WHITE);
  3962. leader_slot = (getattr(t, r) >> 8) + 1;
  3963. found = upb_inttable_lookup(&t->groups, leader_slot, &v);
  3964. UPB_ASSERT(found);
  3965. if (upb_value_getptr(v)) {
  3966. return upb_value_getptr(v);
  3967. } else {
  3968. upb_inttable_remove(&t->groups, leader_slot, NULL);
  3969. upb_inttable_insert(&t->groups, leader_slot, upb_value_ptr(r));
  3970. return r;
  3971. }
  3972. }
  3973. /* Tarjan's algorithm --------------------------------------------------------*/
  3974. /* See:
  3975. * http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm */
  3976. static void do_tarjan(const upb_refcounted *obj, tarjan *t);
  3977. static void tarjan_visit(const upb_refcounted *obj,
  3978. const upb_refcounted *subobj,
  3979. void *closure) {
  3980. tarjan *t = closure;
  3981. if (++t->depth > t->maxdepth) {
  3982. upb_status_seterrf(t->status, "graph too deep to freeze (%d)", t->maxdepth);
  3983. err(t);
  3984. } else if (subobj->is_frozen || color(t, subobj) == WHITE) {
  3985. /* Do nothing: we don't want to visit or color already-frozen nodes,
  3986. * and WHITE nodes have already been assigned a SCC. */
  3987. } else if (color(t, subobj) < GREEN) {
  3988. /* Subdef has not yet been visited; recurse on it. */
  3989. do_tarjan(subobj, t);
  3990. set_lowlink(t, obj, UPB_MIN(lowlink(t, obj), lowlink(t, subobj)));
  3991. } else if (color(t, subobj) == GREEN) {
  3992. /* Subdef is in the stack and hence in the current SCC. */
  3993. set_lowlink(t, obj, UPB_MIN(lowlink(t, obj), idx(t, subobj)));
  3994. }
  3995. --t->depth;
  3996. }
  3997. static void do_tarjan(const upb_refcounted *obj, tarjan *t) {
  3998. if (color(t, obj) == BLACK) {
  3999. /* We haven't seen this object's group; mark the whole group GRAY. */
  4000. const upb_refcounted *o = obj;
  4001. do { set_gray(t, o); } while ((o = o->next) != obj);
  4002. }
  4003. push(t, obj);
  4004. visit(obj, tarjan_visit, t);
  4005. if (lowlink(t, obj) == idx(t, obj)) {
  4006. tarjan_newgroup(t);
  4007. while (pop(t) != obj)
  4008. ;
  4009. }
  4010. }
  4011. /* freeze() ------------------------------------------------------------------*/
  4012. static void crossref(const upb_refcounted *r, const upb_refcounted *subobj,
  4013. void *_t) {
  4014. tarjan *t = _t;
  4015. UPB_ASSERT(color(t, r) > BLACK);
  4016. if (color(t, subobj) > BLACK && r->group != subobj->group) {
  4017. /* Previously this ref was not reflected in subobj->group because they
  4018. * were in the same group; now that they are split a ref must be taken. */
  4019. refgroup(subobj->group);
  4020. }
  4021. }
  4022. static bool freeze(upb_refcounted *const*roots, int n, upb_status *s,
  4023. int maxdepth) {
  4024. volatile bool ret = false;
  4025. int i;
  4026. upb_inttable_iter iter;
  4027. /* We run in two passes so that we can allocate all memory before performing
  4028. * any mutation of the input -- this allows us to leave the input unchanged
  4029. * in the case of memory allocation failure. */
  4030. tarjan t;
  4031. t.index = 0;
  4032. t.depth = 0;
  4033. t.maxdepth = maxdepth;
  4034. t.status = s;
  4035. if (!upb_inttable_init(&t.objattr, UPB_CTYPE_UINT64)) goto err1;
  4036. if (!upb_inttable_init(&t.stack, UPB_CTYPE_PTR)) goto err2;
  4037. if (!upb_inttable_init(&t.groups, UPB_CTYPE_PTR)) goto err3;
  4038. if (setjmp(t.err) != 0) goto err4;
  4039. for (i = 0; i < n; i++) {
  4040. if (color(&t, roots[i]) < GREEN) {
  4041. do_tarjan(roots[i], &t);
  4042. }
  4043. }
  4044. /* If we've made it this far, no further errors are possible so it's safe to
  4045. * mutate the objects without risk of leaving them in an inconsistent state. */
  4046. ret = true;
  4047. /* The transformation that follows requires care. The preconditions are:
  4048. * - all objects in attr map are WHITE or GRAY, and are in mutable groups
  4049. * (groups of all mutable objs)
  4050. * - no ref2(to, from) refs have incremented count(to) if both "to" and
  4051. * "from" are in our attr map (this follows from invariants (2) and (3)) */
  4052. /* Pass 1: we remove WHITE objects from their mutable groups, and add them to
  4053. * new groups according to the SCC's we computed. These new groups will
  4054. * consist of only frozen objects. None will be immediately collectible,
  4055. * because WHITE objects are by definition reachable from one of "roots",
  4056. * which the caller must own refs on. */
  4057. upb_inttable_begin(&iter, &t.objattr);
  4058. for(; !upb_inttable_done(&iter); upb_inttable_next(&iter)) {
  4059. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&iter);
  4060. /* Since removal from a singly-linked list requires access to the object's
  4061. * predecessor, we consider obj->next instead of obj for moving. With the
  4062. * while() loop we guarantee that we will visit every node's predecessor.
  4063. * Proof:
  4064. * 1. every node's predecessor is in our attr map.
  4065. * 2. though the loop body may change a node's predecessor, it will only
  4066. * change it to be the node we are currently operating on, so with a
  4067. * while() loop we guarantee ourselves the chance to remove each node. */
  4068. while (color(&t, obj->next) == WHITE &&
  4069. group(&t, obj->next) != obj->next->group) {
  4070. upb_refcounted *leader;
  4071. /* Remove from old group. */
  4072. upb_refcounted *move = obj->next;
  4073. if (obj == move) {
  4074. /* Removing the last object from a group. */
  4075. UPB_ASSERT(*obj->group == obj->individual_count);
  4076. upb_gfree(obj->group);
  4077. } else {
  4078. obj->next = move->next;
  4079. /* This may decrease to zero; we'll collect GRAY objects (if any) that
  4080. * remain in the group in the third pass. */
  4081. UPB_ASSERT(*move->group >= move->individual_count);
  4082. *move->group -= move->individual_count;
  4083. }
  4084. /* Add to new group. */
  4085. leader = groupleader(&t, move);
  4086. if (move == leader) {
  4087. /* First object added to new group is its leader. */
  4088. move->group = group(&t, move);
  4089. move->next = move;
  4090. *move->group = move->individual_count;
  4091. } else {
  4092. /* Group already has at least one object in it. */
  4093. UPB_ASSERT(leader->group == group(&t, move));
  4094. move->group = group(&t, move);
  4095. move->next = leader->next;
  4096. leader->next = move;
  4097. *move->group += move->individual_count;
  4098. }
  4099. move->is_frozen = true;
  4100. }
  4101. }
  4102. /* Pass 2: GRAY and WHITE objects "obj" with ref2(to, obj) references must
  4103. * increment count(to) if group(obj) != group(to) (which could now be the
  4104. * case if "to" was just frozen). */
  4105. upb_inttable_begin(&iter, &t.objattr);
  4106. for(; !upb_inttable_done(&iter); upb_inttable_next(&iter)) {
  4107. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&iter);
  4108. visit(obj, crossref, &t);
  4109. }
  4110. /* Pass 3: GRAY objects are collected if their group's refcount dropped to
  4111. * zero when we removed its white nodes. This can happen if they had only
  4112. * been kept alive by virtue of sharing a group with an object that was just
  4113. * frozen.
  4114. *
  4115. * It is important that we do this last, since the GRAY object's free()
  4116. * function could call unref2() on just-frozen objects, which will decrement
  4117. * refs that were added in pass 2. */
  4118. upb_inttable_begin(&iter, &t.objattr);
  4119. for(; !upb_inttable_done(&iter); upb_inttable_next(&iter)) {
  4120. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&iter);
  4121. if (obj->group == NULL || *obj->group == 0) {
  4122. if (obj->group) {
  4123. upb_refcounted *o;
  4124. /* We eagerly free() the group's count (since we can't easily determine
  4125. * the group's remaining size it's the easiest way to ensure it gets
  4126. * done). */
  4127. upb_gfree(obj->group);
  4128. /* Visit to release ref2's (done in a separate pass since release_ref2
  4129. * depends on o->group being unmodified so it can test merged()). */
  4130. o = obj;
  4131. do { visit(o, release_ref2, NULL); } while ((o = o->next) != obj);
  4132. /* Mark "group" fields as NULL so we know to free the objects later in
  4133. * this loop, but also don't try to delete the group twice. */
  4134. o = obj;
  4135. do { o->group = NULL; } while ((o = o->next) != obj);
  4136. }
  4137. freeobj(obj);
  4138. }
  4139. }
  4140. err4:
  4141. if (!ret) {
  4142. upb_inttable_begin(&iter, &t.groups);
  4143. for(; !upb_inttable_done(&iter); upb_inttable_next(&iter))
  4144. upb_gfree(upb_value_getptr(upb_inttable_iter_value(&iter)));
  4145. }
  4146. upb_inttable_uninit(&t.groups);
  4147. err3:
  4148. upb_inttable_uninit(&t.stack);
  4149. err2:
  4150. upb_inttable_uninit(&t.objattr);
  4151. err1:
  4152. return ret;
  4153. }
  4154. /* Misc internal functions ***************************************************/
  4155. static bool merged(const upb_refcounted *r, const upb_refcounted *r2) {
  4156. return r->group == r2->group;
  4157. }
  4158. static void merge(upb_refcounted *r, upb_refcounted *from) {
  4159. upb_refcounted *base;
  4160. upb_refcounted *tmp;
  4161. if (merged(r, from)) return;
  4162. *r->group += *from->group;
  4163. upb_gfree(from->group);
  4164. base = from;
  4165. /* Set all refcount pointers in the "from" chain to the merged refcount.
  4166. *
  4167. * TODO(haberman): this linear algorithm can result in an overall O(n^2) bound
  4168. * if the user continuously extends a group by one object. Prevent this by
  4169. * using one of the techniques in this paper:
  4170. * http://bioinfo.ict.ac.cn/~dbu/AlgorithmCourses/Lectures/Union-Find-Tarjan.pdf */
  4171. do { from->group = r->group; } while ((from = from->next) != base);
  4172. /* Merge the two circularly linked lists by swapping their next pointers. */
  4173. tmp = r->next;
  4174. r->next = base->next;
  4175. base->next = tmp;
  4176. }
  4177. static void unref(const upb_refcounted *r);
  4178. static void release_ref2(const upb_refcounted *obj,
  4179. const upb_refcounted *subobj,
  4180. void *closure) {
  4181. UPB_UNUSED(closure);
  4182. untrack(subobj, obj, true);
  4183. if (!merged(obj, subobj)) {
  4184. UPB_ASSERT(subobj->is_frozen);
  4185. unref(subobj);
  4186. }
  4187. }
  4188. static void unref(const upb_refcounted *r) {
  4189. if (unrefgroup(r->group)) {
  4190. const upb_refcounted *o;
  4191. upb_gfree(r->group);
  4192. /* In two passes, since release_ref2 needs a guarantee that any subobjs
  4193. * are alive. */
  4194. o = r;
  4195. do { visit(o, release_ref2, NULL); } while((o = o->next) != r);
  4196. o = r;
  4197. do {
  4198. const upb_refcounted *next = o->next;
  4199. UPB_ASSERT(o->is_frozen || o->individual_count == 0);
  4200. freeobj((upb_refcounted*)o);
  4201. o = next;
  4202. } while(o != r);
  4203. }
  4204. }
  4205. static void freeobj(upb_refcounted *o) {
  4206. trackfree(o);
  4207. o->vtbl->free((upb_refcounted*)o);
  4208. }
  4209. /* Public interface ***********************************************************/
  4210. bool upb_refcounted_init(upb_refcounted *r,
  4211. const struct upb_refcounted_vtbl *vtbl,
  4212. const void *owner) {
  4213. #ifndef NDEBUG
  4214. /* Endianness check. This is unrelated to upb_refcounted, it's just a
  4215. * convenient place to put the check that we can be assured will run for
  4216. * basically every program using upb. */
  4217. const int x = 1;
  4218. #ifdef UPB_BIG_ENDIAN
  4219. UPB_ASSERT(*(char*)&x != 1);
  4220. #else
  4221. UPB_ASSERT(*(char*)&x == 1);
  4222. #endif
  4223. #endif
  4224. r->next = r;
  4225. r->vtbl = vtbl;
  4226. r->individual_count = 0;
  4227. r->is_frozen = false;
  4228. r->group = upb_gmalloc(sizeof(*r->group));
  4229. if (!r->group) return false;
  4230. *r->group = 0;
  4231. trackinit(r);
  4232. upb_refcounted_ref(r, owner);
  4233. return true;
  4234. }
  4235. bool upb_refcounted_isfrozen(const upb_refcounted *r) {
  4236. return r->is_frozen;
  4237. }
  4238. void upb_refcounted_ref(const upb_refcounted *r, const void *owner) {
  4239. track(r, owner, false);
  4240. if (!r->is_frozen)
  4241. ((upb_refcounted*)r)->individual_count++;
  4242. refgroup(r->group);
  4243. }
  4244. void upb_refcounted_unref(const upb_refcounted *r, const void *owner) {
  4245. untrack(r, owner, false);
  4246. if (!r->is_frozen)
  4247. ((upb_refcounted*)r)->individual_count--;
  4248. unref(r);
  4249. }
  4250. void upb_refcounted_ref2(const upb_refcounted *r, upb_refcounted *from) {
  4251. UPB_ASSERT(!from->is_frozen); /* Non-const pointer implies this. */
  4252. track(r, from, true);
  4253. if (r->is_frozen) {
  4254. refgroup(r->group);
  4255. } else {
  4256. merge((upb_refcounted*)r, from);
  4257. }
  4258. }
  4259. void upb_refcounted_unref2(const upb_refcounted *r, upb_refcounted *from) {
  4260. UPB_ASSERT(!from->is_frozen); /* Non-const pointer implies this. */
  4261. untrack(r, from, true);
  4262. if (r->is_frozen) {
  4263. unref(r);
  4264. } else {
  4265. UPB_ASSERT(merged(r, from));
  4266. }
  4267. }
  4268. void upb_refcounted_donateref(
  4269. const upb_refcounted *r, const void *from, const void *to) {
  4270. UPB_ASSERT(from != to);
  4271. if (to != NULL)
  4272. upb_refcounted_ref(r, to);
  4273. if (from != NULL)
  4274. upb_refcounted_unref(r, from);
  4275. }
  4276. void upb_refcounted_checkref(const upb_refcounted *r, const void *owner) {
  4277. checkref(r, owner, false);
  4278. }
  4279. bool upb_refcounted_freeze(upb_refcounted *const*roots, int n, upb_status *s,
  4280. int maxdepth) {
  4281. int i;
  4282. bool ret;
  4283. for (i = 0; i < n; i++) {
  4284. UPB_ASSERT(!roots[i]->is_frozen);
  4285. }
  4286. ret = freeze(roots, n, s, maxdepth);
  4287. UPB_ASSERT(!s || ret == upb_ok(s));
  4288. return ret;
  4289. }
  4290. bool upb_bufsrc_putbuf(const char *buf, size_t len, upb_bytessink *sink) {
  4291. void *subc;
  4292. bool ret;
  4293. upb_bufhandle handle;
  4294. upb_bufhandle_init(&handle);
  4295. upb_bufhandle_setbuf(&handle, buf, 0);
  4296. ret = upb_bytessink_start(sink, len, &subc);
  4297. if (ret && len != 0) {
  4298. ret = (upb_bytessink_putbuf(sink, subc, buf, len, &handle) >= len);
  4299. }
  4300. if (ret) {
  4301. ret = upb_bytessink_end(sink);
  4302. }
  4303. upb_bufhandle_uninit(&handle);
  4304. return ret;
  4305. }
  4306. struct upb_bufsink {
  4307. upb_byteshandler handler;
  4308. upb_bytessink sink;
  4309. upb_env *env;
  4310. char *ptr;
  4311. size_t len, size;
  4312. };
  4313. static void *upb_bufsink_start(void *_sink, const void *hd, size_t size_hint) {
  4314. upb_bufsink *sink = _sink;
  4315. UPB_UNUSED(hd);
  4316. UPB_UNUSED(size_hint);
  4317. sink->len = 0;
  4318. return sink;
  4319. }
  4320. static size_t upb_bufsink_string(void *_sink, const void *hd, const char *ptr,
  4321. size_t len, const upb_bufhandle *handle) {
  4322. upb_bufsink *sink = _sink;
  4323. size_t new_size = sink->size;
  4324. UPB_ASSERT(new_size > 0);
  4325. UPB_UNUSED(hd);
  4326. UPB_UNUSED(handle);
  4327. while (sink->len + len > new_size) {
  4328. new_size *= 2;
  4329. }
  4330. if (new_size != sink->size) {
  4331. sink->ptr = upb_env_realloc(sink->env, sink->ptr, sink->size, new_size);
  4332. sink->size = new_size;
  4333. }
  4334. memcpy(sink->ptr + sink->len, ptr, len);
  4335. sink->len += len;
  4336. return len;
  4337. }
  4338. upb_bufsink *upb_bufsink_new(upb_env *env) {
  4339. upb_bufsink *sink = upb_env_malloc(env, sizeof(upb_bufsink));
  4340. upb_byteshandler_init(&sink->handler);
  4341. upb_byteshandler_setstartstr(&sink->handler, upb_bufsink_start, NULL);
  4342. upb_byteshandler_setstring(&sink->handler, upb_bufsink_string, NULL);
  4343. upb_bytessink_reset(&sink->sink, &sink->handler, sink);
  4344. sink->env = env;
  4345. sink->size = 32;
  4346. sink->ptr = upb_env_malloc(env, sink->size);
  4347. sink->len = 0;
  4348. return sink;
  4349. }
  4350. void upb_bufsink_free(upb_bufsink *sink) {
  4351. upb_env_free(sink->env, sink->ptr);
  4352. upb_env_free(sink->env, sink);
  4353. }
  4354. upb_bytessink *upb_bufsink_sink(upb_bufsink *sink) {
  4355. return &sink->sink;
  4356. }
  4357. const char *upb_bufsink_getdata(const upb_bufsink *sink, size_t *len) {
  4358. *len = sink->len;
  4359. return sink->ptr;
  4360. }
  4361. /*
  4362. ** upb_table Implementation
  4363. **
  4364. ** Implementation is heavily inspired by Lua's ltable.c.
  4365. */
  4366. #include <string.h>
  4367. #define UPB_MAXARRSIZE 16 /* 64k. */
  4368. /* From Chromium. */
  4369. #define ARRAY_SIZE(x) \
  4370. ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x])))))
  4371. static void upb_check_alloc(upb_table *t, upb_alloc *a) {
  4372. UPB_UNUSED(t);
  4373. UPB_UNUSED(a);
  4374. UPB_ASSERT_DEBUGVAR(t->alloc == a);
  4375. }
  4376. static const double MAX_LOAD = 0.85;
  4377. /* The minimum utilization of the array part of a mixed hash/array table. This
  4378. * is a speed/memory-usage tradeoff (though it's not straightforward because of
  4379. * cache effects). The lower this is, the more memory we'll use. */
  4380. static const double MIN_DENSITY = 0.1;
  4381. bool is_pow2(uint64_t v) { return v == 0 || (v & (v - 1)) == 0; }
  4382. int log2ceil(uint64_t v) {
  4383. int ret = 0;
  4384. bool pow2 = is_pow2(v);
  4385. while (v >>= 1) ret++;
  4386. ret = pow2 ? ret : ret + 1; /* Ceiling. */
  4387. return UPB_MIN(UPB_MAXARRSIZE, ret);
  4388. }
  4389. char *upb_strdup(const char *s, upb_alloc *a) {
  4390. return upb_strdup2(s, strlen(s), a);
  4391. }
  4392. char *upb_strdup2(const char *s, size_t len, upb_alloc *a) {
  4393. size_t n;
  4394. char *p;
  4395. /* Prevent overflow errors. */
  4396. if (len == SIZE_MAX) return NULL;
  4397. /* Always null-terminate, even if binary data; but don't rely on the input to
  4398. * have a null-terminating byte since it may be a raw binary buffer. */
  4399. n = len + 1;
  4400. p = upb_malloc(a, n);
  4401. if (p) {
  4402. memcpy(p, s, len);
  4403. p[len] = 0;
  4404. }
  4405. return p;
  4406. }
  4407. /* A type to represent the lookup key of either a strtable or an inttable. */
  4408. typedef union {
  4409. uintptr_t num;
  4410. struct {
  4411. const char *str;
  4412. size_t len;
  4413. } str;
  4414. } lookupkey_t;
  4415. static lookupkey_t strkey2(const char *str, size_t len) {
  4416. lookupkey_t k;
  4417. k.str.str = str;
  4418. k.str.len = len;
  4419. return k;
  4420. }
  4421. static lookupkey_t intkey(uintptr_t key) {
  4422. lookupkey_t k;
  4423. k.num = key;
  4424. return k;
  4425. }
  4426. typedef uint32_t hashfunc_t(upb_tabkey key);
  4427. typedef bool eqlfunc_t(upb_tabkey k1, lookupkey_t k2);
  4428. /* Base table (shared code) ***************************************************/
  4429. /* For when we need to cast away const. */
  4430. static upb_tabent *mutable_entries(upb_table *t) {
  4431. return (upb_tabent*)t->entries;
  4432. }
  4433. static bool isfull(upb_table *t) {
  4434. if (upb_table_size(t) == 0) {
  4435. return true;
  4436. } else {
  4437. return ((double)(t->count + 1) / upb_table_size(t)) > MAX_LOAD;
  4438. }
  4439. }
  4440. static bool init(upb_table *t, upb_ctype_t ctype, uint8_t size_lg2,
  4441. upb_alloc *a) {
  4442. size_t bytes;
  4443. t->count = 0;
  4444. t->ctype = ctype;
  4445. t->size_lg2 = size_lg2;
  4446. t->mask = upb_table_size(t) ? upb_table_size(t) - 1 : 0;
  4447. #ifndef NDEBUG
  4448. t->alloc = a;
  4449. #endif
  4450. bytes = upb_table_size(t) * sizeof(upb_tabent);
  4451. if (bytes > 0) {
  4452. t->entries = upb_malloc(a, bytes);
  4453. if (!t->entries) return false;
  4454. memset(mutable_entries(t), 0, bytes);
  4455. } else {
  4456. t->entries = NULL;
  4457. }
  4458. return true;
  4459. }
  4460. static void uninit(upb_table *t, upb_alloc *a) {
  4461. upb_check_alloc(t, a);
  4462. upb_free(a, mutable_entries(t));
  4463. }
  4464. static upb_tabent *emptyent(upb_table *t) {
  4465. upb_tabent *e = mutable_entries(t) + upb_table_size(t);
  4466. while (1) { if (upb_tabent_isempty(--e)) return e; UPB_ASSERT(e > t->entries); }
  4467. }
  4468. static upb_tabent *getentry_mutable(upb_table *t, uint32_t hash) {
  4469. return (upb_tabent*)upb_getentry(t, hash);
  4470. }
  4471. static const upb_tabent *findentry(const upb_table *t, lookupkey_t key,
  4472. uint32_t hash, eqlfunc_t *eql) {
  4473. const upb_tabent *e;
  4474. if (t->size_lg2 == 0) return NULL;
  4475. e = upb_getentry(t, hash);
  4476. if (upb_tabent_isempty(e)) return NULL;
  4477. while (1) {
  4478. if (eql(e->key, key)) return e;
  4479. if ((e = e->next) == NULL) return NULL;
  4480. }
  4481. }
  4482. static upb_tabent *findentry_mutable(upb_table *t, lookupkey_t key,
  4483. uint32_t hash, eqlfunc_t *eql) {
  4484. return (upb_tabent*)findentry(t, key, hash, eql);
  4485. }
  4486. static bool lookup(const upb_table *t, lookupkey_t key, upb_value *v,
  4487. uint32_t hash, eqlfunc_t *eql) {
  4488. const upb_tabent *e = findentry(t, key, hash, eql);
  4489. if (e) {
  4490. if (v) {
  4491. _upb_value_setval(v, e->val.val, t->ctype);
  4492. }
  4493. return true;
  4494. } else {
  4495. return false;
  4496. }
  4497. }
  4498. /* The given key must not already exist in the table. */
  4499. static void insert(upb_table *t, lookupkey_t key, upb_tabkey tabkey,
  4500. upb_value val, uint32_t hash,
  4501. hashfunc_t *hashfunc, eqlfunc_t *eql) {
  4502. upb_tabent *mainpos_e;
  4503. upb_tabent *our_e;
  4504. UPB_ASSERT(findentry(t, key, hash, eql) == NULL);
  4505. UPB_ASSERT_DEBUGVAR(val.ctype == t->ctype);
  4506. t->count++;
  4507. mainpos_e = getentry_mutable(t, hash);
  4508. our_e = mainpos_e;
  4509. if (upb_tabent_isempty(mainpos_e)) {
  4510. /* Our main position is empty; use it. */
  4511. our_e->next = NULL;
  4512. } else {
  4513. /* Collision. */
  4514. upb_tabent *new_e = emptyent(t);
  4515. /* Head of collider's chain. */
  4516. upb_tabent *chain = getentry_mutable(t, hashfunc(mainpos_e->key));
  4517. if (chain == mainpos_e) {
  4518. /* Existing ent is in its main posisiton (it has the same hash as us, and
  4519. * is the head of our chain). Insert to new ent and append to this chain. */
  4520. new_e->next = mainpos_e->next;
  4521. mainpos_e->next = new_e;
  4522. our_e = new_e;
  4523. } else {
  4524. /* Existing ent is not in its main position (it is a node in some other
  4525. * chain). This implies that no existing ent in the table has our hash.
  4526. * Evict it (updating its chain) and use its ent for head of our chain. */
  4527. *new_e = *mainpos_e; /* copies next. */
  4528. while (chain->next != mainpos_e) {
  4529. chain = (upb_tabent*)chain->next;
  4530. UPB_ASSERT(chain);
  4531. }
  4532. chain->next = new_e;
  4533. our_e = mainpos_e;
  4534. our_e->next = NULL;
  4535. }
  4536. }
  4537. our_e->key = tabkey;
  4538. our_e->val.val = val.val;
  4539. UPB_ASSERT(findentry(t, key, hash, eql) == our_e);
  4540. }
  4541. static bool rm(upb_table *t, lookupkey_t key, upb_value *val,
  4542. upb_tabkey *removed, uint32_t hash, eqlfunc_t *eql) {
  4543. upb_tabent *chain = getentry_mutable(t, hash);
  4544. if (upb_tabent_isempty(chain)) return false;
  4545. if (eql(chain->key, key)) {
  4546. /* Element to remove is at the head of its chain. */
  4547. t->count--;
  4548. if (val) _upb_value_setval(val, chain->val.val, t->ctype);
  4549. if (removed) *removed = chain->key;
  4550. if (chain->next) {
  4551. upb_tabent *move = (upb_tabent*)chain->next;
  4552. *chain = *move;
  4553. move->key = 0; /* Make the slot empty. */
  4554. } else {
  4555. chain->key = 0; /* Make the slot empty. */
  4556. }
  4557. return true;
  4558. } else {
  4559. /* Element to remove is either in a non-head position or not in the
  4560. * table. */
  4561. while (chain->next && !eql(chain->next->key, key)) {
  4562. chain = (upb_tabent*)chain->next;
  4563. }
  4564. if (chain->next) {
  4565. /* Found element to remove. */
  4566. upb_tabent *rm = (upb_tabent*)chain->next;
  4567. t->count--;
  4568. if (val) _upb_value_setval(val, chain->next->val.val, t->ctype);
  4569. if (removed) *removed = rm->key;
  4570. rm->key = 0; /* Make the slot empty. */
  4571. chain->next = rm->next;
  4572. return true;
  4573. } else {
  4574. /* Element to remove is not in the table. */
  4575. return false;
  4576. }
  4577. }
  4578. }
  4579. static size_t next(const upb_table *t, size_t i) {
  4580. do {
  4581. if (++i >= upb_table_size(t))
  4582. return SIZE_MAX;
  4583. } while(upb_tabent_isempty(&t->entries[i]));
  4584. return i;
  4585. }
  4586. static size_t begin(const upb_table *t) {
  4587. return next(t, -1);
  4588. }
  4589. /* upb_strtable ***************************************************************/
  4590. /* A simple "subclass" of upb_table that only adds a hash function for strings. */
  4591. static upb_tabkey strcopy(lookupkey_t k2, upb_alloc *a) {
  4592. char *str = upb_malloc(a, k2.str.len + sizeof(uint32_t) + 1);
  4593. if (str == NULL) return 0;
  4594. memcpy(str, &k2.str.len, sizeof(uint32_t));
  4595. memcpy(str + sizeof(uint32_t), k2.str.str, k2.str.len + 1);
  4596. return (uintptr_t)str;
  4597. }
  4598. static uint32_t strhash(upb_tabkey key) {
  4599. uint32_t len;
  4600. char *str = upb_tabstr(key, &len);
  4601. return MurmurHash2(str, len, 0);
  4602. }
  4603. static bool streql(upb_tabkey k1, lookupkey_t k2) {
  4604. uint32_t len;
  4605. char *str = upb_tabstr(k1, &len);
  4606. return len == k2.str.len && memcmp(str, k2.str.str, len) == 0;
  4607. }
  4608. bool upb_strtable_init2(upb_strtable *t, upb_ctype_t ctype, upb_alloc *a) {
  4609. return init(&t->t, ctype, 2, a);
  4610. }
  4611. void upb_strtable_uninit2(upb_strtable *t, upb_alloc *a) {
  4612. size_t i;
  4613. for (i = 0; i < upb_table_size(&t->t); i++)
  4614. upb_free(a, (void*)t->t.entries[i].key);
  4615. uninit(&t->t, a);
  4616. }
  4617. bool upb_strtable_resize(upb_strtable *t, size_t size_lg2, upb_alloc *a) {
  4618. upb_strtable new_table;
  4619. upb_strtable_iter i;
  4620. upb_check_alloc(&t->t, a);
  4621. if (!init(&new_table.t, t->t.ctype, size_lg2, a))
  4622. return false;
  4623. upb_strtable_begin(&i, t);
  4624. for ( ; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  4625. upb_strtable_insert3(
  4626. &new_table,
  4627. upb_strtable_iter_key(&i),
  4628. upb_strtable_iter_keylength(&i),
  4629. upb_strtable_iter_value(&i),
  4630. a);
  4631. }
  4632. upb_strtable_uninit2(t, a);
  4633. *t = new_table;
  4634. return true;
  4635. }
  4636. bool upb_strtable_insert3(upb_strtable *t, const char *k, size_t len,
  4637. upb_value v, upb_alloc *a) {
  4638. lookupkey_t key;
  4639. upb_tabkey tabkey;
  4640. uint32_t hash;
  4641. upb_check_alloc(&t->t, a);
  4642. if (isfull(&t->t)) {
  4643. /* Need to resize. New table of double the size, add old elements to it. */
  4644. if (!upb_strtable_resize(t, t->t.size_lg2 + 1, a)) {
  4645. return false;
  4646. }
  4647. }
  4648. key = strkey2(k, len);
  4649. tabkey = strcopy(key, a);
  4650. if (tabkey == 0) return false;
  4651. hash = MurmurHash2(key.str.str, key.str.len, 0);
  4652. insert(&t->t, key, tabkey, v, hash, &strhash, &streql);
  4653. return true;
  4654. }
  4655. bool upb_strtable_lookup2(const upb_strtable *t, const char *key, size_t len,
  4656. upb_value *v) {
  4657. uint32_t hash = MurmurHash2(key, len, 0);
  4658. return lookup(&t->t, strkey2(key, len), v, hash, &streql);
  4659. }
  4660. bool upb_strtable_remove3(upb_strtable *t, const char *key, size_t len,
  4661. upb_value *val, upb_alloc *alloc) {
  4662. uint32_t hash = MurmurHash2(key, len, 0);
  4663. upb_tabkey tabkey;
  4664. if (rm(&t->t, strkey2(key, len), val, &tabkey, hash, &streql)) {
  4665. upb_free(alloc, (void*)tabkey);
  4666. return true;
  4667. } else {
  4668. return false;
  4669. }
  4670. }
  4671. /* Iteration */
  4672. static const upb_tabent *str_tabent(const upb_strtable_iter *i) {
  4673. return &i->t->t.entries[i->index];
  4674. }
  4675. void upb_strtable_begin(upb_strtable_iter *i, const upb_strtable *t) {
  4676. i->t = t;
  4677. i->index = begin(&t->t);
  4678. }
  4679. void upb_strtable_next(upb_strtable_iter *i) {
  4680. i->index = next(&i->t->t, i->index);
  4681. }
  4682. bool upb_strtable_done(const upb_strtable_iter *i) {
  4683. return i->index >= upb_table_size(&i->t->t) ||
  4684. upb_tabent_isempty(str_tabent(i));
  4685. }
  4686. const char *upb_strtable_iter_key(const upb_strtable_iter *i) {
  4687. UPB_ASSERT(!upb_strtable_done(i));
  4688. return upb_tabstr(str_tabent(i)->key, NULL);
  4689. }
  4690. size_t upb_strtable_iter_keylength(const upb_strtable_iter *i) {
  4691. uint32_t len;
  4692. UPB_ASSERT(!upb_strtable_done(i));
  4693. upb_tabstr(str_tabent(i)->key, &len);
  4694. return len;
  4695. }
  4696. upb_value upb_strtable_iter_value(const upb_strtable_iter *i) {
  4697. UPB_ASSERT(!upb_strtable_done(i));
  4698. return _upb_value_val(str_tabent(i)->val.val, i->t->t.ctype);
  4699. }
  4700. void upb_strtable_iter_setdone(upb_strtable_iter *i) {
  4701. i->index = SIZE_MAX;
  4702. }
  4703. bool upb_strtable_iter_isequal(const upb_strtable_iter *i1,
  4704. const upb_strtable_iter *i2) {
  4705. if (upb_strtable_done(i1) && upb_strtable_done(i2))
  4706. return true;
  4707. return i1->t == i2->t && i1->index == i2->index;
  4708. }
  4709. /* upb_inttable ***************************************************************/
  4710. /* For inttables we use a hybrid structure where small keys are kept in an
  4711. * array and large keys are put in the hash table. */
  4712. static uint32_t inthash(upb_tabkey key) { return upb_inthash(key); }
  4713. static bool inteql(upb_tabkey k1, lookupkey_t k2) {
  4714. return k1 == k2.num;
  4715. }
  4716. static upb_tabval *mutable_array(upb_inttable *t) {
  4717. return (upb_tabval*)t->array;
  4718. }
  4719. static upb_tabval *inttable_val(upb_inttable *t, uintptr_t key) {
  4720. if (key < t->array_size) {
  4721. return upb_arrhas(t->array[key]) ? &(mutable_array(t)[key]) : NULL;
  4722. } else {
  4723. upb_tabent *e =
  4724. findentry_mutable(&t->t, intkey(key), upb_inthash(key), &inteql);
  4725. return e ? &e->val : NULL;
  4726. }
  4727. }
  4728. static const upb_tabval *inttable_val_const(const upb_inttable *t,
  4729. uintptr_t key) {
  4730. return inttable_val((upb_inttable*)t, key);
  4731. }
  4732. size_t upb_inttable_count(const upb_inttable *t) {
  4733. return t->t.count + t->array_count;
  4734. }
  4735. static void check(upb_inttable *t) {
  4736. UPB_UNUSED(t);
  4737. #if defined(UPB_DEBUG_TABLE) && !defined(NDEBUG)
  4738. {
  4739. /* This check is very expensive (makes inserts/deletes O(N)). */
  4740. size_t count = 0;
  4741. upb_inttable_iter i;
  4742. upb_inttable_begin(&i, t);
  4743. for(; !upb_inttable_done(&i); upb_inttable_next(&i), count++) {
  4744. UPB_ASSERT(upb_inttable_lookup(t, upb_inttable_iter_key(&i), NULL));
  4745. }
  4746. UPB_ASSERT(count == upb_inttable_count(t));
  4747. }
  4748. #endif
  4749. }
  4750. bool upb_inttable_sizedinit(upb_inttable *t, upb_ctype_t ctype,
  4751. size_t asize, int hsize_lg2, upb_alloc *a) {
  4752. size_t array_bytes;
  4753. if (!init(&t->t, ctype, hsize_lg2, a)) return false;
  4754. /* Always make the array part at least 1 long, so that we know key 0
  4755. * won't be in the hash part, which simplifies things. */
  4756. t->array_size = UPB_MAX(1, asize);
  4757. t->array_count = 0;
  4758. array_bytes = t->array_size * sizeof(upb_value);
  4759. t->array = upb_malloc(a, array_bytes);
  4760. if (!t->array) {
  4761. uninit(&t->t, a);
  4762. return false;
  4763. }
  4764. memset(mutable_array(t), 0xff, array_bytes);
  4765. check(t);
  4766. return true;
  4767. }
  4768. bool upb_inttable_init2(upb_inttable *t, upb_ctype_t ctype, upb_alloc *a) {
  4769. return upb_inttable_sizedinit(t, ctype, 0, 4, a);
  4770. }
  4771. void upb_inttable_uninit2(upb_inttable *t, upb_alloc *a) {
  4772. uninit(&t->t, a);
  4773. upb_free(a, mutable_array(t));
  4774. }
  4775. bool upb_inttable_insert2(upb_inttable *t, uintptr_t key, upb_value val,
  4776. upb_alloc *a) {
  4777. upb_tabval tabval;
  4778. tabval.val = val.val;
  4779. UPB_ASSERT(upb_arrhas(tabval)); /* This will reject (uint64_t)-1. Fix this. */
  4780. upb_check_alloc(&t->t, a);
  4781. if (key < t->array_size) {
  4782. UPB_ASSERT(!upb_arrhas(t->array[key]));
  4783. t->array_count++;
  4784. mutable_array(t)[key].val = val.val;
  4785. } else {
  4786. if (isfull(&t->t)) {
  4787. /* Need to resize the hash part, but we re-use the array part. */
  4788. size_t i;
  4789. upb_table new_table;
  4790. if (!init(&new_table, t->t.ctype, t->t.size_lg2 + 1, a)) {
  4791. return false;
  4792. }
  4793. for (i = begin(&t->t); i < upb_table_size(&t->t); i = next(&t->t, i)) {
  4794. const upb_tabent *e = &t->t.entries[i];
  4795. uint32_t hash;
  4796. upb_value v;
  4797. _upb_value_setval(&v, e->val.val, t->t.ctype);
  4798. hash = upb_inthash(e->key);
  4799. insert(&new_table, intkey(e->key), e->key, v, hash, &inthash, &inteql);
  4800. }
  4801. UPB_ASSERT(t->t.count == new_table.count);
  4802. uninit(&t->t, a);
  4803. t->t = new_table;
  4804. }
  4805. insert(&t->t, intkey(key), key, val, upb_inthash(key), &inthash, &inteql);
  4806. }
  4807. check(t);
  4808. return true;
  4809. }
  4810. bool upb_inttable_lookup(const upb_inttable *t, uintptr_t key, upb_value *v) {
  4811. const upb_tabval *table_v = inttable_val_const(t, key);
  4812. if (!table_v) return false;
  4813. if (v) _upb_value_setval(v, table_v->val, t->t.ctype);
  4814. return true;
  4815. }
  4816. bool upb_inttable_replace(upb_inttable *t, uintptr_t key, upb_value val) {
  4817. upb_tabval *table_v = inttable_val(t, key);
  4818. if (!table_v) return false;
  4819. table_v->val = val.val;
  4820. return true;
  4821. }
  4822. bool upb_inttable_remove(upb_inttable *t, uintptr_t key, upb_value *val) {
  4823. bool success;
  4824. if (key < t->array_size) {
  4825. if (upb_arrhas(t->array[key])) {
  4826. upb_tabval empty = UPB_TABVALUE_EMPTY_INIT;
  4827. t->array_count--;
  4828. if (val) {
  4829. _upb_value_setval(val, t->array[key].val, t->t.ctype);
  4830. }
  4831. mutable_array(t)[key] = empty;
  4832. success = true;
  4833. } else {
  4834. success = false;
  4835. }
  4836. } else {
  4837. success = rm(&t->t, intkey(key), val, NULL, upb_inthash(key), &inteql);
  4838. }
  4839. check(t);
  4840. return success;
  4841. }
  4842. bool upb_inttable_push2(upb_inttable *t, upb_value val, upb_alloc *a) {
  4843. upb_check_alloc(&t->t, a);
  4844. return upb_inttable_insert2(t, upb_inttable_count(t), val, a);
  4845. }
  4846. upb_value upb_inttable_pop(upb_inttable *t) {
  4847. upb_value val;
  4848. bool ok = upb_inttable_remove(t, upb_inttable_count(t) - 1, &val);
  4849. UPB_ASSERT(ok);
  4850. return val;
  4851. }
  4852. bool upb_inttable_insertptr2(upb_inttable *t, const void *key, upb_value val,
  4853. upb_alloc *a) {
  4854. upb_check_alloc(&t->t, a);
  4855. return upb_inttable_insert2(t, (uintptr_t)key, val, a);
  4856. }
  4857. bool upb_inttable_lookupptr(const upb_inttable *t, const void *key,
  4858. upb_value *v) {
  4859. return upb_inttable_lookup(t, (uintptr_t)key, v);
  4860. }
  4861. bool upb_inttable_removeptr(upb_inttable *t, const void *key, upb_value *val) {
  4862. return upb_inttable_remove(t, (uintptr_t)key, val);
  4863. }
  4864. void upb_inttable_compact2(upb_inttable *t, upb_alloc *a) {
  4865. /* A power-of-two histogram of the table keys. */
  4866. size_t counts[UPB_MAXARRSIZE + 1] = {0};
  4867. /* The max key in each bucket. */
  4868. uintptr_t max[UPB_MAXARRSIZE + 1] = {0};
  4869. upb_inttable_iter i;
  4870. size_t arr_count;
  4871. int size_lg2;
  4872. upb_inttable new_t;
  4873. upb_check_alloc(&t->t, a);
  4874. upb_inttable_begin(&i, t);
  4875. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  4876. uintptr_t key = upb_inttable_iter_key(&i);
  4877. int bucket = log2ceil(key);
  4878. max[bucket] = UPB_MAX(max[bucket], key);
  4879. counts[bucket]++;
  4880. }
  4881. /* Find the largest power of two that satisfies the MIN_DENSITY
  4882. * definition (while actually having some keys). */
  4883. arr_count = upb_inttable_count(t);
  4884. for (size_lg2 = ARRAY_SIZE(counts) - 1; size_lg2 > 0; size_lg2--) {
  4885. if (counts[size_lg2] == 0) {
  4886. /* We can halve again without losing any entries. */
  4887. continue;
  4888. } else if (arr_count >= (1 << size_lg2) * MIN_DENSITY) {
  4889. break;
  4890. }
  4891. arr_count -= counts[size_lg2];
  4892. }
  4893. UPB_ASSERT(arr_count <= upb_inttable_count(t));
  4894. {
  4895. /* Insert all elements into new, perfectly-sized table. */
  4896. size_t arr_size = max[size_lg2] + 1; /* +1 so arr[max] will fit. */
  4897. size_t hash_count = upb_inttable_count(t) - arr_count;
  4898. size_t hash_size = hash_count ? (hash_count / MAX_LOAD) + 1 : 0;
  4899. size_t hashsize_lg2 = log2ceil(hash_size);
  4900. upb_inttable_sizedinit(&new_t, t->t.ctype, arr_size, hashsize_lg2, a);
  4901. upb_inttable_begin(&i, t);
  4902. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  4903. uintptr_t k = upb_inttable_iter_key(&i);
  4904. upb_inttable_insert2(&new_t, k, upb_inttable_iter_value(&i), a);
  4905. }
  4906. UPB_ASSERT(new_t.array_size == arr_size);
  4907. UPB_ASSERT(new_t.t.size_lg2 == hashsize_lg2);
  4908. }
  4909. upb_inttable_uninit2(t, a);
  4910. *t = new_t;
  4911. }
  4912. /* Iteration. */
  4913. static const upb_tabent *int_tabent(const upb_inttable_iter *i) {
  4914. UPB_ASSERT(!i->array_part);
  4915. return &i->t->t.entries[i->index];
  4916. }
  4917. static upb_tabval int_arrent(const upb_inttable_iter *i) {
  4918. UPB_ASSERT(i->array_part);
  4919. return i->t->array[i->index];
  4920. }
  4921. void upb_inttable_begin(upb_inttable_iter *i, const upb_inttable *t) {
  4922. i->t = t;
  4923. i->index = -1;
  4924. i->array_part = true;
  4925. upb_inttable_next(i);
  4926. }
  4927. void upb_inttable_next(upb_inttable_iter *iter) {
  4928. const upb_inttable *t = iter->t;
  4929. if (iter->array_part) {
  4930. while (++iter->index < t->array_size) {
  4931. if (upb_arrhas(int_arrent(iter))) {
  4932. return;
  4933. }
  4934. }
  4935. iter->array_part = false;
  4936. iter->index = begin(&t->t);
  4937. } else {
  4938. iter->index = next(&t->t, iter->index);
  4939. }
  4940. }
  4941. bool upb_inttable_done(const upb_inttable_iter *i) {
  4942. if (i->array_part) {
  4943. return i->index >= i->t->array_size ||
  4944. !upb_arrhas(int_arrent(i));
  4945. } else {
  4946. return i->index >= upb_table_size(&i->t->t) ||
  4947. upb_tabent_isempty(int_tabent(i));
  4948. }
  4949. }
  4950. uintptr_t upb_inttable_iter_key(const upb_inttable_iter *i) {
  4951. UPB_ASSERT(!upb_inttable_done(i));
  4952. return i->array_part ? i->index : int_tabent(i)->key;
  4953. }
  4954. upb_value upb_inttable_iter_value(const upb_inttable_iter *i) {
  4955. UPB_ASSERT(!upb_inttable_done(i));
  4956. return _upb_value_val(
  4957. i->array_part ? i->t->array[i->index].val : int_tabent(i)->val.val,
  4958. i->t->t.ctype);
  4959. }
  4960. void upb_inttable_iter_setdone(upb_inttable_iter *i) {
  4961. i->index = SIZE_MAX;
  4962. i->array_part = false;
  4963. }
  4964. bool upb_inttable_iter_isequal(const upb_inttable_iter *i1,
  4965. const upb_inttable_iter *i2) {
  4966. if (upb_inttable_done(i1) && upb_inttable_done(i2))
  4967. return true;
  4968. return i1->t == i2->t && i1->index == i2->index &&
  4969. i1->array_part == i2->array_part;
  4970. }
  4971. #ifdef UPB_UNALIGNED_READS_OK
  4972. /* -----------------------------------------------------------------------------
  4973. * MurmurHash2, by Austin Appleby (released as public domain).
  4974. * Reformatted and C99-ified by Joshua Haberman.
  4975. * Note - This code makes a few assumptions about how your machine behaves -
  4976. * 1. We can read a 4-byte value from any address without crashing
  4977. * 2. sizeof(int) == 4 (in upb this limitation is removed by using uint32_t
  4978. * And it has a few limitations -
  4979. * 1. It will not work incrementally.
  4980. * 2. It will not produce the same results on little-endian and big-endian
  4981. * machines. */
  4982. uint32_t MurmurHash2(const void *key, size_t len, uint32_t seed) {
  4983. /* 'm' and 'r' are mixing constants generated offline.
  4984. * They're not really 'magic', they just happen to work well. */
  4985. const uint32_t m = 0x5bd1e995;
  4986. const int32_t r = 24;
  4987. /* Initialize the hash to a 'random' value */
  4988. uint32_t h = seed ^ len;
  4989. /* Mix 4 bytes at a time into the hash */
  4990. const uint8_t * data = (const uint8_t *)key;
  4991. while(len >= 4) {
  4992. uint32_t k = *(uint32_t *)data;
  4993. k *= m;
  4994. k ^= k >> r;
  4995. k *= m;
  4996. h *= m;
  4997. h ^= k;
  4998. data += 4;
  4999. len -= 4;
  5000. }
  5001. /* Handle the last few bytes of the input array */
  5002. switch(len) {
  5003. case 3: h ^= data[2] << 16;
  5004. case 2: h ^= data[1] << 8;
  5005. case 1: h ^= data[0]; h *= m;
  5006. };
  5007. /* Do a few final mixes of the hash to ensure the last few
  5008. * bytes are well-incorporated. */
  5009. h ^= h >> 13;
  5010. h *= m;
  5011. h ^= h >> 15;
  5012. return h;
  5013. }
  5014. #else /* !UPB_UNALIGNED_READS_OK */
  5015. /* -----------------------------------------------------------------------------
  5016. * MurmurHashAligned2, by Austin Appleby
  5017. * Same algorithm as MurmurHash2, but only does aligned reads - should be safer
  5018. * on certain platforms.
  5019. * Performance will be lower than MurmurHash2 */
  5020. #define MIX(h,k,m) { k *= m; k ^= k >> r; k *= m; h *= m; h ^= k; }
  5021. uint32_t MurmurHash2(const void * key, size_t len, uint32_t seed) {
  5022. const uint32_t m = 0x5bd1e995;
  5023. const int32_t r = 24;
  5024. const uint8_t * data = (const uint8_t *)key;
  5025. uint32_t h = seed ^ len;
  5026. uint8_t align = (uintptr_t)data & 3;
  5027. if(align && (len >= 4)) {
  5028. /* Pre-load the temp registers */
  5029. uint32_t t = 0, d = 0;
  5030. int32_t sl;
  5031. int32_t sr;
  5032. switch(align) {
  5033. case 1: t |= data[2] << 16;
  5034. case 2: t |= data[1] << 8;
  5035. case 3: t |= data[0];
  5036. }
  5037. t <<= (8 * align);
  5038. data += 4-align;
  5039. len -= 4-align;
  5040. sl = 8 * (4-align);
  5041. sr = 8 * align;
  5042. /* Mix */
  5043. while(len >= 4) {
  5044. uint32_t k;
  5045. d = *(uint32_t *)data;
  5046. t = (t >> sr) | (d << sl);
  5047. k = t;
  5048. MIX(h,k,m);
  5049. t = d;
  5050. data += 4;
  5051. len -= 4;
  5052. }
  5053. /* Handle leftover data in temp registers */
  5054. d = 0;
  5055. if(len >= align) {
  5056. uint32_t k;
  5057. switch(align) {
  5058. case 3: d |= data[2] << 16;
  5059. case 2: d |= data[1] << 8;
  5060. case 1: d |= data[0];
  5061. }
  5062. k = (t >> sr) | (d << sl);
  5063. MIX(h,k,m);
  5064. data += align;
  5065. len -= align;
  5066. /* ----------
  5067. * Handle tail bytes */
  5068. switch(len) {
  5069. case 3: h ^= data[2] << 16;
  5070. case 2: h ^= data[1] << 8;
  5071. case 1: h ^= data[0]; h *= m;
  5072. };
  5073. } else {
  5074. switch(len) {
  5075. case 3: d |= data[2] << 16;
  5076. case 2: d |= data[1] << 8;
  5077. case 1: d |= data[0];
  5078. case 0: h ^= (t >> sr) | (d << sl); h *= m;
  5079. }
  5080. }
  5081. h ^= h >> 13;
  5082. h *= m;
  5083. h ^= h >> 15;
  5084. return h;
  5085. } else {
  5086. while(len >= 4) {
  5087. uint32_t k = *(uint32_t *)data;
  5088. MIX(h,k,m);
  5089. data += 4;
  5090. len -= 4;
  5091. }
  5092. /* ----------
  5093. * Handle tail bytes */
  5094. switch(len) {
  5095. case 3: h ^= data[2] << 16;
  5096. case 2: h ^= data[1] << 8;
  5097. case 1: h ^= data[0]; h *= m;
  5098. };
  5099. h ^= h >> 13;
  5100. h *= m;
  5101. h ^= h >> 15;
  5102. return h;
  5103. }
  5104. }
  5105. #undef MIX
  5106. #endif /* UPB_UNALIGNED_READS_OK */
  5107. #include <errno.h>
  5108. #include <stdarg.h>
  5109. #include <stddef.h>
  5110. #include <stdint.h>
  5111. #include <stdio.h>
  5112. #include <stdlib.h>
  5113. #include <string.h>
  5114. bool upb_dumptostderr(void *closure, const upb_status* status) {
  5115. UPB_UNUSED(closure);
  5116. fprintf(stderr, "%s\n", upb_status_errmsg(status));
  5117. return false;
  5118. }
  5119. /* Guarantee null-termination and provide ellipsis truncation.
  5120. * It may be tempting to "optimize" this by initializing these final
  5121. * four bytes up-front and then being careful never to overwrite them,
  5122. * this is safer and simpler. */
  5123. static void nullz(upb_status *status) {
  5124. const char *ellipsis = "...";
  5125. size_t len = strlen(ellipsis);
  5126. UPB_ASSERT(sizeof(status->msg) > len);
  5127. memcpy(status->msg + sizeof(status->msg) - len, ellipsis, len);
  5128. }
  5129. /* upb_upberr *****************************************************************/
  5130. upb_errorspace upb_upberr = {"upb error"};
  5131. void upb_upberr_setoom(upb_status *status) {
  5132. status->error_space_ = &upb_upberr;
  5133. upb_status_seterrmsg(status, "Out of memory");
  5134. }
  5135. /* upb_status *****************************************************************/
  5136. void upb_status_clear(upb_status *status) {
  5137. if (!status) return;
  5138. status->ok_ = true;
  5139. status->code_ = 0;
  5140. status->msg[0] = '\0';
  5141. }
  5142. bool upb_ok(const upb_status *status) { return status->ok_; }
  5143. upb_errorspace *upb_status_errspace(const upb_status *status) {
  5144. return status->error_space_;
  5145. }
  5146. int upb_status_errcode(const upb_status *status) { return status->code_; }
  5147. const char *upb_status_errmsg(const upb_status *status) { return status->msg; }
  5148. void upb_status_seterrmsg(upb_status *status, const char *msg) {
  5149. if (!status) return;
  5150. status->ok_ = false;
  5151. strncpy(status->msg, msg, sizeof(status->msg));
  5152. nullz(status);
  5153. }
  5154. void upb_status_seterrf(upb_status *status, const char *fmt, ...) {
  5155. va_list args;
  5156. va_start(args, fmt);
  5157. upb_status_vseterrf(status, fmt, args);
  5158. va_end(args);
  5159. }
  5160. void upb_status_vseterrf(upb_status *status, const char *fmt, va_list args) {
  5161. if (!status) return;
  5162. status->ok_ = false;
  5163. _upb_vsnprintf(status->msg, sizeof(status->msg), fmt, args);
  5164. nullz(status);
  5165. }
  5166. void upb_status_copy(upb_status *to, const upb_status *from) {
  5167. if (!to) return;
  5168. *to = *from;
  5169. }
  5170. /* upb_alloc ******************************************************************/
  5171. static void *upb_global_allocfunc(upb_alloc *alloc, void *ptr, size_t oldsize,
  5172. size_t size) {
  5173. UPB_UNUSED(alloc);
  5174. UPB_UNUSED(oldsize);
  5175. if (size == 0) {
  5176. free(ptr);
  5177. return NULL;
  5178. } else {
  5179. return realloc(ptr, size);
  5180. }
  5181. }
  5182. upb_alloc upb_alloc_global = {&upb_global_allocfunc};
  5183. /* upb_arena ******************************************************************/
  5184. /* Be conservative and choose 16 in case anyone is using SSE. */
  5185. static const size_t maxalign = 16;
  5186. static size_t align_up_max(size_t size) {
  5187. return ((size + maxalign - 1) / maxalign) * maxalign;
  5188. }
  5189. typedef struct mem_block {
  5190. struct mem_block *next;
  5191. size_t size;
  5192. size_t used;
  5193. bool owned;
  5194. /* Data follows. */
  5195. } mem_block;
  5196. typedef struct cleanup_ent {
  5197. struct cleanup_ent *next;
  5198. upb_cleanup_func *cleanup;
  5199. void *ud;
  5200. } cleanup_ent;
  5201. static void upb_arena_addblock(upb_arena *a, void *ptr, size_t size,
  5202. bool owned) {
  5203. mem_block *block = ptr;
  5204. block->next = a->block_head;
  5205. block->size = size;
  5206. block->used = align_up_max(sizeof(mem_block));
  5207. block->owned = owned;
  5208. a->block_head = block;
  5209. /* TODO(haberman): ASAN poison. */
  5210. }
  5211. static mem_block *upb_arena_allocblock(upb_arena *a, size_t size) {
  5212. size_t block_size = UPB_MAX(size, a->next_block_size) + sizeof(mem_block);
  5213. mem_block *block = upb_malloc(a->block_alloc, block_size);
  5214. if (!block) {
  5215. return NULL;
  5216. }
  5217. upb_arena_addblock(a, block, block_size, true);
  5218. a->next_block_size = UPB_MIN(block_size * 2, a->max_block_size);
  5219. return block;
  5220. }
  5221. static void *upb_arena_doalloc(upb_alloc *alloc, void *ptr, size_t oldsize,
  5222. size_t size) {
  5223. upb_arena *a = (upb_arena*)alloc; /* upb_alloc is initial member. */
  5224. mem_block *block = a->block_head;
  5225. void *ret;
  5226. if (size == 0) {
  5227. return NULL; /* We are an arena, don't need individual frees. */
  5228. }
  5229. size = align_up_max(size);
  5230. /* TODO(haberman): special-case if this is a realloc of the last alloc? */
  5231. if (!block || block->size - block->used < size) {
  5232. /* Slow path: have to allocate a new block. */
  5233. block = upb_arena_allocblock(a, size);
  5234. if (!block) {
  5235. return NULL; /* Out of memory. */
  5236. }
  5237. }
  5238. ret = (char*)block + block->used;
  5239. block->used += size;
  5240. if (oldsize > 0) {
  5241. memcpy(ret, ptr, oldsize); /* Preserve existing data. */
  5242. }
  5243. /* TODO(haberman): ASAN unpoison. */
  5244. a->bytes_allocated += size;
  5245. return ret;
  5246. }
  5247. /* Public Arena API ***********************************************************/
  5248. void upb_arena_init(upb_arena *a) {
  5249. a->alloc.func = &upb_arena_doalloc;
  5250. a->block_alloc = &upb_alloc_global;
  5251. a->bytes_allocated = 0;
  5252. a->next_block_size = 256;
  5253. a->max_block_size = 16384;
  5254. a->cleanup_head = NULL;
  5255. a->block_head = NULL;
  5256. }
  5257. void upb_arena_init2(upb_arena *a, void *mem, size_t size, upb_alloc *alloc) {
  5258. upb_arena_init(a);
  5259. if (size > sizeof(mem_block)) {
  5260. upb_arena_addblock(a, mem, size, false);
  5261. }
  5262. if (alloc) {
  5263. a->block_alloc = alloc;
  5264. }
  5265. }
  5266. void upb_arena_uninit(upb_arena *a) {
  5267. cleanup_ent *ent = a->cleanup_head;
  5268. mem_block *block = a->block_head;
  5269. while (ent) {
  5270. ent->cleanup(ent->ud);
  5271. ent = ent->next;
  5272. }
  5273. /* Must do this after running cleanup functions, because this will delete
  5274. * the memory we store our cleanup entries in! */
  5275. while (block) {
  5276. mem_block *next = block->next;
  5277. if (block->owned) {
  5278. upb_free(a->block_alloc, block);
  5279. }
  5280. block = next;
  5281. }
  5282. /* Protect against multiple-uninit. */
  5283. a->cleanup_head = NULL;
  5284. a->block_head = NULL;
  5285. }
  5286. bool upb_arena_addcleanup(upb_arena *a, upb_cleanup_func *func, void *ud) {
  5287. cleanup_ent *ent = upb_malloc(&a->alloc, sizeof(cleanup_ent));
  5288. if (!ent) {
  5289. return false; /* Out of memory. */
  5290. }
  5291. ent->cleanup = func;
  5292. ent->ud = ud;
  5293. ent->next = a->cleanup_head;
  5294. a->cleanup_head = ent;
  5295. return true;
  5296. }
  5297. size_t upb_arena_bytesallocated(const upb_arena *a) {
  5298. return a->bytes_allocated;
  5299. }
  5300. /* Standard error functions ***************************************************/
  5301. static bool default_err(void *ud, const upb_status *status) {
  5302. UPB_UNUSED(ud);
  5303. UPB_UNUSED(status);
  5304. return false;
  5305. }
  5306. static bool write_err_to(void *ud, const upb_status *status) {
  5307. upb_status *copy_to = ud;
  5308. upb_status_copy(copy_to, status);
  5309. return false;
  5310. }
  5311. /* upb_env ********************************************************************/
  5312. void upb_env_initonly(upb_env *e) {
  5313. e->ok_ = true;
  5314. e->error_func_ = &default_err;
  5315. e->error_ud_ = NULL;
  5316. }
  5317. void upb_env_init(upb_env *e) {
  5318. upb_arena_init(&e->arena_);
  5319. upb_env_initonly(e);
  5320. }
  5321. void upb_env_init2(upb_env *e, void *mem, size_t n, upb_alloc *alloc) {
  5322. upb_arena_init2(&e->arena_, mem, n, alloc);
  5323. upb_env_initonly(e);
  5324. }
  5325. void upb_env_uninit(upb_env *e) {
  5326. upb_arena_uninit(&e->arena_);
  5327. }
  5328. void upb_env_seterrorfunc(upb_env *e, upb_error_func *func, void *ud) {
  5329. e->error_func_ = func;
  5330. e->error_ud_ = ud;
  5331. }
  5332. void upb_env_reporterrorsto(upb_env *e, upb_status *s) {
  5333. e->error_func_ = &write_err_to;
  5334. e->error_ud_ = s;
  5335. }
  5336. bool upb_env_reporterror(upb_env *e, const upb_status *status) {
  5337. e->ok_ = false;
  5338. return e->error_func_(e->error_ud_, status);
  5339. }
  5340. void *upb_env_malloc(upb_env *e, size_t size) {
  5341. return upb_malloc(&e->arena_.alloc, size);
  5342. }
  5343. void *upb_env_realloc(upb_env *e, void *ptr, size_t oldsize, size_t size) {
  5344. return upb_realloc(&e->arena_.alloc, ptr, oldsize, size);
  5345. }
  5346. void upb_env_free(upb_env *e, void *ptr) {
  5347. upb_free(&e->arena_.alloc, ptr);
  5348. }
  5349. bool upb_env_addcleanup(upb_env *e, upb_cleanup_func *func, void *ud) {
  5350. return upb_arena_addcleanup(&e->arena_, func, ud);
  5351. }
  5352. size_t upb_env_bytesallocated(const upb_env *e) {
  5353. return upb_arena_bytesallocated(&e->arena_);
  5354. }
  5355. /* This file was generated by upbc (the upb compiler) from the input
  5356. * file:
  5357. *
  5358. * upb/descriptor/descriptor.proto
  5359. *
  5360. * Do not edit -- your changes will be discarded when the file is
  5361. * regenerated. */
  5362. static const upb_msgdef msgs[22];
  5363. static const upb_fielddef fields[107];
  5364. static const upb_enumdef enums[5];
  5365. static const upb_tabent strentries[236];
  5366. static const upb_tabent intentries[18];
  5367. static const upb_tabval arrays[187];
  5368. #ifdef UPB_DEBUG_REFS
  5369. static upb_inttable reftables[268];
  5370. #endif
  5371. static const upb_msgdef msgs[22] = {
  5372. UPB_MSGDEF_INIT("google.protobuf.DescriptorProto", 40, 8, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[0], 11, 10), UPB_STRTABLE_INIT(10, 15, UPB_CTYPE_PTR, 4, &strentries[0]), false, UPB_SYNTAX_PROTO2, &reftables[0], &reftables[1]),
  5373. UPB_MSGDEF_INIT("google.protobuf.DescriptorProto.ExtensionRange", 4, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[11], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[16]), false, UPB_SYNTAX_PROTO2, &reftables[2], &reftables[3]),
  5374. UPB_MSGDEF_INIT("google.protobuf.DescriptorProto.ReservedRange", 4, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[14], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[20]), false, UPB_SYNTAX_PROTO2, &reftables[4], &reftables[5]),
  5375. UPB_MSGDEF_INIT("google.protobuf.EnumDescriptorProto", 11, 2, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[17], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[24]), false, UPB_SYNTAX_PROTO2, &reftables[6], &reftables[7]),
  5376. UPB_MSGDEF_INIT("google.protobuf.EnumOptions", 8, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[0], &arrays[21], 4, 2), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[28]), false, UPB_SYNTAX_PROTO2, &reftables[8], &reftables[9]),
  5377. UPB_MSGDEF_INIT("google.protobuf.EnumValueDescriptorProto", 8, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[25], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[32]), false, UPB_SYNTAX_PROTO2, &reftables[10], &reftables[11]),
  5378. UPB_MSGDEF_INIT("google.protobuf.EnumValueOptions", 7, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[2], &arrays[29], 2, 1), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[36]), false, UPB_SYNTAX_PROTO2, &reftables[12], &reftables[13]),
  5379. UPB_MSGDEF_INIT("google.protobuf.FieldDescriptorProto", 23, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[31], 11, 10), UPB_STRTABLE_INIT(10, 15, UPB_CTYPE_PTR, 4, &strentries[40]), false, UPB_SYNTAX_PROTO2, &reftables[14], &reftables[15]),
  5380. UPB_MSGDEF_INIT("google.protobuf.FieldOptions", 12, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[4], &arrays[42], 11, 6), UPB_STRTABLE_INIT(7, 15, UPB_CTYPE_PTR, 4, &strentries[56]), false, UPB_SYNTAX_PROTO2, &reftables[16], &reftables[17]),
  5381. UPB_MSGDEF_INIT("google.protobuf.FileDescriptorProto", 42, 6, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[53], 13, 12), UPB_STRTABLE_INIT(12, 15, UPB_CTYPE_PTR, 4, &strentries[72]), false, UPB_SYNTAX_PROTO2, &reftables[18], &reftables[19]),
  5382. UPB_MSGDEF_INIT("google.protobuf.FileDescriptorSet", 6, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[66], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[88]), false, UPB_SYNTAX_PROTO2, &reftables[20], &reftables[21]),
  5383. UPB_MSGDEF_INIT("google.protobuf.FileOptions", 37, 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]),
  5384. UPB_MSGDEF_INIT("google.protobuf.MessageOptions", 10, 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]),
  5385. UPB_MSGDEF_INIT("google.protobuf.MethodDescriptorProto", 15, 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]),
  5386. UPB_MSGDEF_INIT("google.protobuf.MethodOptions", 7, 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]),
  5387. UPB_MSGDEF_INIT("google.protobuf.OneofDescriptorProto", 5, 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]),
  5388. UPB_MSGDEF_INIT("google.protobuf.ServiceDescriptorProto", 11, 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]),
  5389. UPB_MSGDEF_INIT("google.protobuf.ServiceOptions", 7, 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]),
  5390. UPB_MSGDEF_INIT("google.protobuf.SourceCodeInfo", 6, 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]),
  5391. UPB_MSGDEF_INIT("google.protobuf.SourceCodeInfo.Location", 19, 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]),
  5392. UPB_MSGDEF_INIT("google.protobuf.UninterpretedOption", 18, 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]),
  5393. UPB_MSGDEF_INIT("google.protobuf.UninterpretedOption.NamePart", 6, 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]),
  5394. };
  5395. static const upb_fielddef fields[107] = {
  5396. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "aggregate_value", 8, &msgs[20], NULL, 15, 6, {0},&reftables[44], &reftables[45]),
  5397. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "allow_alias", 2, &msgs[4], NULL, 6, 1, {0},&reftables[46], &reftables[47]),
  5398. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "cc_enable_arenas", 31, &msgs[11], NULL, 23, 12, {0},&reftables[48], &reftables[49]),
  5399. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "cc_generic_services", 16, &msgs[11], NULL, 17, 6, {0},&reftables[50], &reftables[51]),
  5400. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "client_streaming", 5, &msgs[13], NULL, 13, 4, {0},&reftables[52], &reftables[53]),
  5401. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "csharp_namespace", 37, &msgs[11], NULL, 27, 14, {0},&reftables[54], &reftables[55]),
  5402. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "ctype", 1, &msgs[8], (const upb_def*)(&enums[2]), 6, 1, {0},&reftables[56], &reftables[57]),
  5403. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "default_value", 7, &msgs[7], NULL, 16, 7, {0},&reftables[58], &reftables[59]),
  5404. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_STRING, 0, false, false, false, false, "dependency", 3, &msgs[9], NULL, 30, 8, {0},&reftables[60], &reftables[61]),
  5405. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[8], NULL, 8, 3, {0},&reftables[62], &reftables[63]),
  5406. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 33, &msgs[14], NULL, 6, 1, {0},&reftables[64], &reftables[65]),
  5407. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[12], NULL, 8, 3, {0},&reftables[66], &reftables[67]),
  5408. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 23, &msgs[11], NULL, 21, 10, {0},&reftables[68], &reftables[69]),
  5409. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 1, &msgs[6], NULL, 6, 1, {0},&reftables[70], &reftables[71]),
  5410. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[4], NULL, 7, 2, {0},&reftables[72], &reftables[73]),
  5411. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 33, &msgs[17], NULL, 6, 1, {0},&reftables[74], &reftables[75]),
  5412. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_DOUBLE, 0, false, false, false, false, "double_value", 6, &msgs[20], NULL, 11, 4, {0},&reftables[76], &reftables[77]),
  5413. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "end", 2, &msgs[2], NULL, 3, 1, {0},&reftables[78], &reftables[79]),
  5414. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "end", 2, &msgs[1], NULL, 3, 1, {0},&reftables[80], &reftables[81]),
  5415. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "enum_type", 5, &msgs[9], (const upb_def*)(&msgs[3]), 13, 1, {0},&reftables[82], &reftables[83]),
  5416. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "enum_type", 4, &msgs[0], (const upb_def*)(&msgs[3]), 18, 2, {0},&reftables[84], &reftables[85]),
  5417. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "extendee", 2, &msgs[7], NULL, 7, 2, {0},&reftables[86], &reftables[87]),
  5418. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension", 6, &msgs[0], (const upb_def*)(&msgs[7]), 24, 4, {0},&reftables[88], &reftables[89]),
  5419. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension", 7, &msgs[9], (const upb_def*)(&msgs[7]), 19, 3, {0},&reftables[90], &reftables[91]),
  5420. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension_range", 5, &msgs[0], (const upb_def*)(&msgs[1]), 21, 3, {0},&reftables[92], &reftables[93]),
  5421. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "field", 2, &msgs[0], (const upb_def*)(&msgs[7]), 12, 0, {0},&reftables[94], &reftables[95]),
  5422. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "file", 1, &msgs[10], (const upb_def*)(&msgs[9]), 5, 0, {0},&reftables[96], &reftables[97]),
  5423. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "go_package", 11, &msgs[11], NULL, 14, 5, {0},&reftables[98], &reftables[99]),
  5424. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "identifier_value", 3, &msgs[20], NULL, 6, 1, {0},&reftables[100], &reftables[101]),
  5425. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "input_type", 2, &msgs[13], NULL, 7, 2, {0},&reftables[102], &reftables[103]),
  5426. UPB_FIELDDEF_INIT(UPB_LABEL_REQUIRED, UPB_TYPE_BOOL, 0, false, false, false, false, "is_extension", 2, &msgs[21], NULL, 5, 1, {0},&reftables[104], &reftables[105]),
  5427. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_generate_equals_and_hash", 20, &msgs[11], NULL, 20, 9, {0},&reftables[106], &reftables[107]),
  5428. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_generic_services", 17, &msgs[11], NULL, 18, 7, {0},&reftables[108], &reftables[109]),
  5429. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_multiple_files", 10, &msgs[11], NULL, 13, 4, {0},&reftables[110], &reftables[111]),
  5430. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "java_outer_classname", 8, &msgs[11], NULL, 9, 2, {0},&reftables[112], &reftables[113]),
  5431. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "java_package", 1, &msgs[11], NULL, 6, 1, {0},&reftables[114], &reftables[115]),
  5432. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_string_check_utf8", 27, &msgs[11], NULL, 22, 11, {0},&reftables[116], &reftables[117]),
  5433. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "javanano_use_deprecated_package", 38, &msgs[11], NULL, 30, 15, {0},&reftables[118], &reftables[119]),
  5434. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "json_name", 10, &msgs[7], NULL, 20, 9, {0},&reftables[120], &reftables[121]),
  5435. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "jstype", 6, &msgs[8], (const upb_def*)(&enums[3]), 10, 5, {0},&reftables[122], &reftables[123]),
  5436. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "label", 4, &msgs[7], (const upb_def*)(&enums[0]), 11, 4, {0},&reftables[124], &reftables[125]),
  5437. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "lazy", 5, &msgs[8], NULL, 9, 4, {0},&reftables[126], &reftables[127]),
  5438. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "leading_comments", 3, &msgs[19], NULL, 8, 2, {0},&reftables[128], &reftables[129]),
  5439. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_STRING, 0, false, false, false, false, "leading_detached_comments", 6, &msgs[19], NULL, 16, 4, {0},&reftables[130], &reftables[131]),
  5440. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "location", 1, &msgs[18], (const upb_def*)(&msgs[19]), 5, 0, {0},&reftables[132], &reftables[133]),
  5441. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "map_entry", 7, &msgs[12], NULL, 9, 4, {0},&reftables[134], &reftables[135]),
  5442. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "message_set_wire_format", 1, &msgs[12], NULL, 6, 1, {0},&reftables[136], &reftables[137]),
  5443. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "message_type", 4, &msgs[9], (const upb_def*)(&msgs[0]), 10, 0, {0},&reftables[138], &reftables[139]),
  5444. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "method", 2, &msgs[16], (const upb_def*)(&msgs[13]), 6, 0, {0},&reftables[140], &reftables[141]),
  5445. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "name", 2, &msgs[20], (const upb_def*)(&msgs[21]), 5, 0, {0},&reftables[142], &reftables[143]),
  5446. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[5], NULL, 4, 1, {0},&reftables[144], &reftables[145]),
  5447. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[9], NULL, 22, 6, {0},&reftables[146], &reftables[147]),
  5448. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[3], NULL, 8, 2, {0},&reftables[148], &reftables[149]),
  5449. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[16], NULL, 8, 2, {0},&reftables[150], &reftables[151]),
  5450. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[15], NULL, 2, 0, {0},&reftables[152], &reftables[153]),
  5451. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[13], NULL, 4, 1, {0},&reftables[154], &reftables[155]),
  5452. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[7], NULL, 4, 1, {0},&reftables[156], &reftables[157]),
  5453. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[0], NULL, 32, 8, {0},&reftables[158], &reftables[159]),
  5454. UPB_FIELDDEF_INIT(UPB_LABEL_REQUIRED, UPB_TYPE_STRING, 0, false, false, false, false, "name_part", 1, &msgs[21], NULL, 2, 0, {0},&reftables[160], &reftables[161]),
  5455. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT64, UPB_INTFMT_VARIABLE, false, false, false, false, "negative_int_value", 5, &msgs[20], NULL, 10, 3, {0},&reftables[162], &reftables[163]),
  5456. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "nested_type", 3, &msgs[0], (const upb_def*)(&msgs[0]), 15, 1, {0},&reftables[164], &reftables[165]),
  5457. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "no_standard_descriptor_accessor", 2, &msgs[12], NULL, 7, 2, {0},&reftables[166], &reftables[167]),
  5458. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "number", 3, &msgs[7], NULL, 10, 3, {0},&reftables[168], &reftables[169]),
  5459. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "number", 2, &msgs[5], NULL, 7, 2, {0},&reftables[170], &reftables[171]),
  5460. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "objc_class_prefix", 36, &msgs[11], NULL, 24, 13, {0},&reftables[172], &reftables[173]),
  5461. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "oneof_decl", 8, &msgs[0], (const upb_def*)(&msgs[15]), 28, 6, {0},&reftables[174], &reftables[175]),
  5462. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "oneof_index", 9, &msgs[7], NULL, 19, 8, {0},&reftables[176], &reftables[177]),
  5463. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "optimize_for", 9, &msgs[11], (const upb_def*)(&enums[4]), 12, 3, {0},&reftables[178], &reftables[179]),
  5464. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 7, &msgs[0], (const upb_def*)(&msgs[12]), 25, 5, {0},&reftables[180], &reftables[181]),
  5465. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 8, &msgs[9], (const upb_def*)(&msgs[11]), 20, 4, {0},&reftables[182], &reftables[183]),
  5466. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 8, &msgs[7], (const upb_def*)(&msgs[8]), 3, 0, {0},&reftables[184], &reftables[185]),
  5467. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 4, &msgs[13], (const upb_def*)(&msgs[14]), 3, 0, {0},&reftables[186], &reftables[187]),
  5468. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[16], (const upb_def*)(&msgs[17]), 7, 1, {0},&reftables[188], &reftables[189]),
  5469. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[3], (const upb_def*)(&msgs[4]), 7, 1, {0},&reftables[190], &reftables[191]),
  5470. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[5], (const upb_def*)(&msgs[6]), 3, 0, {0},&reftables[192], &reftables[193]),
  5471. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "output_type", 3, &msgs[13], NULL, 10, 3, {0},&reftables[194], &reftables[195]),
  5472. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "package", 2, &msgs[9], NULL, 25, 7, {0},&reftables[196], &reftables[197]),
  5473. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "packed", 2, &msgs[8], NULL, 7, 2, {0},&reftables[198], &reftables[199]),
  5474. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, true, "path", 1, &msgs[19], NULL, 4, 0, {0},&reftables[200], &reftables[201]),
  5475. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "php_class_prefix", 40, &msgs[11], NULL, 31, 16, {0},&reftables[202], &reftables[203]),
  5476. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "php_namespace", 41, &msgs[11], NULL, 34, 17, {0},&reftables[204], &reftables[205]),
  5477. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_UINT64, UPB_INTFMT_VARIABLE, false, false, false, false, "positive_int_value", 4, &msgs[20], NULL, 9, 2, {0},&reftables[206], &reftables[207]),
  5478. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "public_dependency", 10, &msgs[9], NULL, 35, 9, {0},&reftables[208], &reftables[209]),
  5479. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "py_generic_services", 18, &msgs[11], NULL, 19, 8, {0},&reftables[210], &reftables[211]),
  5480. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_STRING, 0, false, false, false, false, "reserved_name", 10, &msgs[0], NULL, 37, 9, {0},&reftables[212], &reftables[213]),
  5481. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "reserved_range", 9, &msgs[0], (const upb_def*)(&msgs[2]), 31, 7, {0},&reftables[214], &reftables[215]),
  5482. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "server_streaming", 6, &msgs[13], NULL, 14, 5, {0},&reftables[216], &reftables[217]),
  5483. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "service", 6, &msgs[9], (const upb_def*)(&msgs[16]), 16, 2, {0},&reftables[218], &reftables[219]),
  5484. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "source_code_info", 9, &msgs[9], (const upb_def*)(&msgs[18]), 21, 5, {0},&reftables[220], &reftables[221]),
  5485. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, true, "span", 2, &msgs[19], NULL, 7, 1, {0},&reftables[222], &reftables[223]),
  5486. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "start", 1, &msgs[2], NULL, 2, 0, {0},&reftables[224], &reftables[225]),
  5487. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "start", 1, &msgs[1], NULL, 2, 0, {0},&reftables[226], &reftables[227]),
  5488. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BYTES, 0, false, false, false, false, "string_value", 7, &msgs[20], NULL, 12, 5, {0},&reftables[228], &reftables[229]),
  5489. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "syntax", 12, &msgs[9], NULL, 39, 11, {0},&reftables[230], &reftables[231]),
  5490. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "trailing_comments", 4, &msgs[19], NULL, 11, 3, {0},&reftables[232], &reftables[233]),
  5491. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "type", 5, &msgs[7], (const upb_def*)(&enums[1]), 12, 5, {0},&reftables[234], &reftables[235]),
  5492. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "type_name", 6, &msgs[7], NULL, 13, 6, {0},&reftables[236], &reftables[237]),
  5493. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[12], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[238], &reftables[239]),
  5494. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[17], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[240], &reftables[241]),
  5495. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[11], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[242], &reftables[243]),
  5496. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[14], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[244], &reftables[245]),
  5497. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[8], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[246], &reftables[247]),
  5498. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[6], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[248], &reftables[249]),
  5499. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[4], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[250], &reftables[251]),
  5500. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "value", 2, &msgs[3], (const upb_def*)(&msgs[5]), 6, 0, {0},&reftables[252], &reftables[253]),
  5501. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "weak", 10, &msgs[8], NULL, 11, 6, {0},&reftables[254], &reftables[255]),
  5502. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "weak_dependency", 11, &msgs[9], NULL, 38, 10, {0},&reftables[256], &reftables[257]),
  5503. };
  5504. static const upb_enumdef enums[5] = {
  5505. 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]),
  5506. 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]),
  5507. 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]),
  5508. 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]),
  5509. 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]),
  5510. };
  5511. static const upb_tabent strentries[236] = {
  5512. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "extension"), UPB_TABVALUE_PTR_INIT(&fields[22]), NULL},
  5513. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5514. {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "reserved_name"), UPB_TABVALUE_PTR_INIT(&fields[84]), NULL},
  5515. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[57]), NULL},
  5516. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5517. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5518. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5519. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "field"), UPB_TABVALUE_PTR_INIT(&fields[25]), &strentries[12]},
  5520. {UPB_TABKEY_STR("\017", "\000", "\000", "\000", "extension_range"), UPB_TABVALUE_PTR_INIT(&fields[24]), &strentries[14]},
  5521. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5522. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "nested_type"), UPB_TABVALUE_PTR_INIT(&fields[60]), NULL},
  5523. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5524. {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "reserved_range"), UPB_TABVALUE_PTR_INIT(&fields[85]), NULL},
  5525. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[68]), NULL},
  5526. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "oneof_decl"), UPB_TABVALUE_PTR_INIT(&fields[65]), NULL},
  5527. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "enum_type"), UPB_TABVALUE_PTR_INIT(&fields[20]), &strentries[13]},
  5528. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "start"), UPB_TABVALUE_PTR_INIT(&fields[91]), NULL},
  5529. {UPB_TABKEY_STR("\003", "\000", "\000", "\000", "end"), UPB_TABVALUE_PTR_INIT(&fields[18]), NULL},
  5530. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5531. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5532. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "start"), UPB_TABVALUE_PTR_INIT(&fields[90]), NULL},
  5533. {UPB_TABKEY_STR("\003", "\000", "\000", "\000", "end"), UPB_TABVALUE_PTR_INIT(&fields[17]), NULL},
  5534. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5535. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5536. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5537. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "value"), UPB_TABVALUE_PTR_INIT(&fields[104]), NULL},
  5538. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[73]), NULL},
  5539. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[52]), &strentries[26]},
  5540. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[103]), NULL},
  5541. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[14]), NULL},
  5542. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "allow_alias"), UPB_TABVALUE_PTR_INIT(&fields[1]), NULL},
  5543. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5544. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "number"), UPB_TABVALUE_PTR_INIT(&fields[63]), NULL},
  5545. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5546. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[74]), NULL},
  5547. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[50]), &strentries[34]},
  5548. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[102]), NULL},
  5549. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[13]), NULL},
  5550. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5551. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5552. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "oneof_index"), UPB_TABVALUE_PTR_INIT(&fields[66]), NULL},
  5553. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "label"), UPB_TABVALUE_PTR_INIT(&fields[40]), NULL},
  5554. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5555. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[56]), NULL},
  5556. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5557. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5558. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5559. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5560. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "number"), UPB_TABVALUE_PTR_INIT(&fields[62]), &strentries[53]},
  5561. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5562. {UPB_TABKEY_STR("\010", "\000", "\000", "\000", "extendee"), UPB_TABVALUE_PTR_INIT(&fields[21]), NULL},
  5563. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "type_name"), UPB_TABVALUE_PTR_INIT(&fields[96]), NULL},
  5564. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "json_name"), UPB_TABVALUE_PTR_INIT(&fields[38]), NULL},
  5565. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "type"), UPB_TABVALUE_PTR_INIT(&fields[95]), &strentries[50]},
  5566. {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "default_value"), UPB_TABVALUE_PTR_INIT(&fields[7]), NULL},
  5567. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[70]), NULL},
  5568. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[101]), NULL},
  5569. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5570. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "weak"), UPB_TABVALUE_PTR_INIT(&fields[105]), NULL},
  5571. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5572. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5573. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5574. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5575. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "packed"), UPB_TABVALUE_PTR_INIT(&fields[77]), NULL},
  5576. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "lazy"), UPB_TABVALUE_PTR_INIT(&fields[41]), NULL},
  5577. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5578. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "ctype"), UPB_TABVALUE_PTR_INIT(&fields[6]), NULL},
  5579. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5580. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "jstype"), UPB_TABVALUE_PTR_INIT(&fields[39]), NULL},
  5581. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[9]), NULL},
  5582. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5583. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5584. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "extension"), UPB_TABVALUE_PTR_INIT(&fields[23]), NULL},
  5585. {UPB_TABKEY_STR("\017", "\000", "\000", "\000", "weak_dependency"), UPB_TABVALUE_PTR_INIT(&fields[106]), NULL},
  5586. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5587. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[51]), NULL},
  5588. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "service"), UPB_TABVALUE_PTR_INIT(&fields[87]), NULL},
  5589. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5590. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "source_code_info"), UPB_TABVALUE_PTR_INIT(&fields[88]), NULL},
  5591. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5592. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5593. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "syntax"), UPB_TABVALUE_PTR_INIT(&fields[93]), NULL},
  5594. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "dependency"), UPB_TABVALUE_PTR_INIT(&fields[8]), NULL},
  5595. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "message_type"), UPB_TABVALUE_PTR_INIT(&fields[47]), NULL},
  5596. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "package"), UPB_TABVALUE_PTR_INIT(&fields[76]), NULL},
  5597. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[69]), &strentries[86]},
  5598. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "enum_type"), UPB_TABVALUE_PTR_INIT(&fields[19]), NULL},
  5599. {UPB_TABKEY_STR("\021", "\000", "\000", "\000", "public_dependency"), UPB_TABVALUE_PTR_INIT(&fields[82]), &strentries[85]},
  5600. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5601. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "file"), UPB_TABVALUE_PTR_INIT(&fields[26]), NULL},
  5602. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5603. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5604. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5605. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5606. {UPB_TABKEY_STR("\023", "\000", "\000", "\000", "cc_generic_services"), UPB_TABVALUE_PTR_INIT(&fields[3]), NULL},
  5607. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "csharp_namespace"), UPB_TABVALUE_PTR_INIT(&fields[5]), &strentries[116]},
  5608. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5609. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5610. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5611. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5612. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5613. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5614. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5615. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "go_package"), UPB_TABVALUE_PTR_INIT(&fields[27]), NULL},
  5616. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "java_package"), UPB_TABVALUE_PTR_INIT(&fields[35]), &strentries[120]},
  5617. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5618. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5619. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "java_outer_classname"), UPB_TABVALUE_PTR_INIT(&fields[34]), NULL},
  5620. {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "php_namespace"), UPB_TABVALUE_PTR_INIT(&fields[80]), &strentries[113]},
  5621. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5622. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5623. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5624. {UPB_TABKEY_STR("\023", "\000", "\000", "\000", "java_multiple_files"), UPB_TABVALUE_PTR_INIT(&fields[33]), &strentries[117]},
  5625. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[99]), NULL},
  5626. {UPB_TABKEY_STR("\025", "\000", "\000", "\000", "java_generic_services"), UPB_TABVALUE_PTR_INIT(&fields[32]), &strentries[118]},
  5627. {UPB_TABKEY_STR("\035", "\000", "\000", "\000", "java_generate_equals_and_hash"), UPB_TABVALUE_PTR_INIT(&fields[31]), NULL},
  5628. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "php_class_prefix"), UPB_TABVALUE_PTR_INIT(&fields[79]), NULL},
  5629. {UPB_TABKEY_STR("\037", "\000", "\000", "\000", "javanano_use_deprecated_package"), UPB_TABVALUE_PTR_INIT(&fields[37]), &strentries[123]},
  5630. {UPB_TABKEY_STR("\023", "\000", "\000", "\000", "py_generic_services"), UPB_TABVALUE_PTR_INIT(&fields[83]), NULL},
  5631. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "optimize_for"), UPB_TABVALUE_PTR_INIT(&fields[67]), NULL},
  5632. {UPB_TABKEY_STR("\026", "\000", "\000", "\000", "java_string_check_utf8"), UPB_TABVALUE_PTR_INIT(&fields[36]), NULL},
  5633. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[12]), &strentries[119]},
  5634. {UPB_TABKEY_STR("\021", "\000", "\000", "\000", "objc_class_prefix"), UPB_TABVALUE_PTR_INIT(&fields[64]), NULL},
  5635. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "cc_enable_arenas"), UPB_TABVALUE_PTR_INIT(&fields[2]), NULL},
  5636. {UPB_TABKEY_STR("\027", "\000", "\000", "\000", "message_set_wire_format"), UPB_TABVALUE_PTR_INIT(&fields[46]), &strentries[128]},
  5637. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5638. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5639. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5640. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[97]), NULL},
  5641. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[11]), NULL},
  5642. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "map_entry"), UPB_TABVALUE_PTR_INIT(&fields[45]), NULL},
  5643. {UPB_TABKEY_STR("\037", "\000", "\000", "\000", "no_standard_descriptor_accessor"), UPB_TABVALUE_PTR_INIT(&fields[61]), NULL},
  5644. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5645. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "client_streaming"), UPB_TABVALUE_PTR_INIT(&fields[4]), NULL},
  5646. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "server_streaming"), UPB_TABVALUE_PTR_INIT(&fields[86]), NULL},
  5647. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[55]), NULL},
  5648. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "input_type"), UPB_TABVALUE_PTR_INIT(&fields[29]), NULL},
  5649. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5650. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "output_type"), UPB_TABVALUE_PTR_INIT(&fields[75]), NULL},
  5651. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[71]), NULL},
  5652. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[100]), NULL},
  5653. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[10]), NULL},
  5654. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5655. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5656. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5657. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5658. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5659. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[54]), NULL},
  5660. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5661. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[72]), &strentries[150]},
  5662. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "method"), UPB_TABVALUE_PTR_INIT(&fields[48]), NULL},
  5663. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[53]), &strentries[149]},
  5664. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[98]), NULL},
  5665. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[15]), NULL},
  5666. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5667. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5668. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5669. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5670. {UPB_TABKEY_STR("\010", "\000", "\000", "\000", "location"), UPB_TABVALUE_PTR_INIT(&fields[44]), NULL},
  5671. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5672. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5673. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5674. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5675. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "span"), UPB_TABVALUE_PTR_INIT(&fields[89]), &strentries[167]},
  5676. {UPB_TABKEY_STR("\031", "\000", "\000", "\000", "leading_detached_comments"), UPB_TABVALUE_PTR_INIT(&fields[43]), &strentries[165]},
  5677. {UPB_TABKEY_STR("\021", "\000", "\000", "\000", "trailing_comments"), UPB_TABVALUE_PTR_INIT(&fields[94]), NULL},
  5678. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "leading_comments"), UPB_TABVALUE_PTR_INIT(&fields[42]), &strentries[164]},
  5679. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "path"), UPB_TABVALUE_PTR_INIT(&fields[78]), NULL},
  5680. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "double_value"), UPB_TABVALUE_PTR_INIT(&fields[16]), NULL},
  5681. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5682. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5683. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[49]), NULL},
  5684. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5685. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5686. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5687. {UPB_TABKEY_STR("\022", "\000", "\000", "\000", "negative_int_value"), UPB_TABVALUE_PTR_INIT(&fields[59]), NULL},
  5688. {UPB_TABKEY_STR("\017", "\000", "\000", "\000", "aggregate_value"), UPB_TABVALUE_PTR_INIT(&fields[0]), NULL},
  5689. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5690. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5691. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5692. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5693. {UPB_TABKEY_STR("\022", "\000", "\000", "\000", "positive_int_value"), UPB_TABVALUE_PTR_INIT(&fields[81]), NULL},
  5694. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "identifier_value"), UPB_TABVALUE_PTR_INIT(&fields[28]), NULL},
  5695. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "string_value"), UPB_TABVALUE_PTR_INIT(&fields[92]), &strentries[182]},
  5696. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5697. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5698. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "is_extension"), UPB_TABVALUE_PTR_INIT(&fields[30]), NULL},
  5699. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "name_part"), UPB_TABVALUE_PTR_INIT(&fields[58]), NULL},
  5700. {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "LABEL_REQUIRED"), UPB_TABVALUE_INT_INIT(2), &strentries[190]},
  5701. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5702. {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "LABEL_REPEATED"), UPB_TABVALUE_INT_INIT(3), NULL},
  5703. {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "LABEL_OPTIONAL"), UPB_TABVALUE_INT_INIT(1), NULL},
  5704. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "TYPE_FIXED64"), UPB_TABVALUE_INT_INIT(6), NULL},
  5705. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5706. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5707. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5708. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5709. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_STRING"), UPB_TABVALUE_INT_INIT(9), NULL},
  5710. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_FLOAT"), UPB_TABVALUE_INT_INIT(2), &strentries[221]},
  5711. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_DOUBLE"), UPB_TABVALUE_INT_INIT(1), NULL},
  5712. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5713. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_INT32"), UPB_TABVALUE_INT_INIT(5), NULL},
  5714. {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "TYPE_SFIXED32"), UPB_TABVALUE_INT_INIT(15), NULL},
  5715. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "TYPE_FIXED32"), UPB_TABVALUE_INT_INIT(7), NULL},
  5716. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5717. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "TYPE_MESSAGE"), UPB_TABVALUE_INT_INIT(11), &strentries[222]},
  5718. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5719. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5720. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_INT64"), UPB_TABVALUE_INT_INIT(3), &strentries[219]},
  5721. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5722. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5723. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5724. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5725. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "TYPE_ENUM"), UPB_TABVALUE_INT_INIT(14), NULL},
  5726. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_UINT32"), UPB_TABVALUE_INT_INIT(13), NULL},
  5727. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5728. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_UINT64"), UPB_TABVALUE_INT_INIT(4), &strentries[218]},
  5729. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5730. {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "TYPE_SFIXED64"), UPB_TABVALUE_INT_INIT(16), NULL},
  5731. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_BYTES"), UPB_TABVALUE_INT_INIT(12), NULL},
  5732. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_SINT64"), UPB_TABVALUE_INT_INIT(18), NULL},
  5733. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "TYPE_BOOL"), UPB_TABVALUE_INT_INIT(8), NULL},
  5734. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_GROUP"), UPB_TABVALUE_INT_INIT(10), NULL},
  5735. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_SINT32"), UPB_TABVALUE_INT_INIT(17), NULL},
  5736. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5737. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "CORD"), UPB_TABVALUE_INT_INIT(1), NULL},
  5738. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "STRING"), UPB_TABVALUE_INT_INIT(0), &strentries[225]},
  5739. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "STRING_PIECE"), UPB_TABVALUE_INT_INIT(2), NULL},
  5740. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5741. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "JS_NORMAL"), UPB_TABVALUE_INT_INIT(0), NULL},
  5742. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "JS_NUMBER"), UPB_TABVALUE_INT_INIT(2), NULL},
  5743. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "JS_STRING"), UPB_TABVALUE_INT_INIT(1), NULL},
  5744. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "CODE_SIZE"), UPB_TABVALUE_INT_INIT(2), NULL},
  5745. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "SPEED"), UPB_TABVALUE_INT_INIT(1), &strentries[235]},
  5746. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5747. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "LITE_RUNTIME"), UPB_TABVALUE_INT_INIT(3), NULL},
  5748. };
  5749. static const upb_tabent intentries[18] = {
  5750. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5751. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[103]), NULL},
  5752. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5753. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[102]), NULL},
  5754. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5755. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[101]), NULL},
  5756. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5757. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[99]), NULL},
  5758. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5759. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[97]), NULL},
  5760. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5761. {UPB_TABKEY_NUM(33), UPB_TABVALUE_PTR_INIT(&fields[10]), NULL},
  5762. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5763. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[100]), NULL},
  5764. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5765. {UPB_TABKEY_NUM(33), UPB_TABVALUE_PTR_INIT(&fields[15]), NULL},
  5766. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5767. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[98]), NULL},
  5768. };
  5769. static const upb_tabval arrays[187] = {
  5770. UPB_TABVALUE_EMPTY_INIT,
  5771. UPB_TABVALUE_PTR_INIT(&fields[57]),
  5772. UPB_TABVALUE_PTR_INIT(&fields[25]),
  5773. UPB_TABVALUE_PTR_INIT(&fields[60]),
  5774. UPB_TABVALUE_PTR_INIT(&fields[20]),
  5775. UPB_TABVALUE_PTR_INIT(&fields[24]),
  5776. UPB_TABVALUE_PTR_INIT(&fields[22]),
  5777. UPB_TABVALUE_PTR_INIT(&fields[68]),
  5778. UPB_TABVALUE_PTR_INIT(&fields[65]),
  5779. UPB_TABVALUE_PTR_INIT(&fields[85]),
  5780. UPB_TABVALUE_PTR_INIT(&fields[84]),
  5781. UPB_TABVALUE_EMPTY_INIT,
  5782. UPB_TABVALUE_PTR_INIT(&fields[91]),
  5783. UPB_TABVALUE_PTR_INIT(&fields[18]),
  5784. UPB_TABVALUE_EMPTY_INIT,
  5785. UPB_TABVALUE_PTR_INIT(&fields[90]),
  5786. UPB_TABVALUE_PTR_INIT(&fields[17]),
  5787. UPB_TABVALUE_EMPTY_INIT,
  5788. UPB_TABVALUE_PTR_INIT(&fields[52]),
  5789. UPB_TABVALUE_PTR_INIT(&fields[104]),
  5790. UPB_TABVALUE_PTR_INIT(&fields[73]),
  5791. UPB_TABVALUE_EMPTY_INIT,
  5792. UPB_TABVALUE_EMPTY_INIT,
  5793. UPB_TABVALUE_PTR_INIT(&fields[1]),
  5794. UPB_TABVALUE_PTR_INIT(&fields[14]),
  5795. UPB_TABVALUE_EMPTY_INIT,
  5796. UPB_TABVALUE_PTR_INIT(&fields[50]),
  5797. UPB_TABVALUE_PTR_INIT(&fields[63]),
  5798. UPB_TABVALUE_PTR_INIT(&fields[74]),
  5799. UPB_TABVALUE_EMPTY_INIT,
  5800. UPB_TABVALUE_PTR_INIT(&fields[13]),
  5801. UPB_TABVALUE_EMPTY_INIT,
  5802. UPB_TABVALUE_PTR_INIT(&fields[56]),
  5803. UPB_TABVALUE_PTR_INIT(&fields[21]),
  5804. UPB_TABVALUE_PTR_INIT(&fields[62]),
  5805. UPB_TABVALUE_PTR_INIT(&fields[40]),
  5806. UPB_TABVALUE_PTR_INIT(&fields[95]),
  5807. UPB_TABVALUE_PTR_INIT(&fields[96]),
  5808. UPB_TABVALUE_PTR_INIT(&fields[7]),
  5809. UPB_TABVALUE_PTR_INIT(&fields[70]),
  5810. UPB_TABVALUE_PTR_INIT(&fields[66]),
  5811. UPB_TABVALUE_PTR_INIT(&fields[38]),
  5812. UPB_TABVALUE_EMPTY_INIT,
  5813. UPB_TABVALUE_PTR_INIT(&fields[6]),
  5814. UPB_TABVALUE_PTR_INIT(&fields[77]),
  5815. UPB_TABVALUE_PTR_INIT(&fields[9]),
  5816. UPB_TABVALUE_EMPTY_INIT,
  5817. UPB_TABVALUE_PTR_INIT(&fields[41]),
  5818. UPB_TABVALUE_PTR_INIT(&fields[39]),
  5819. UPB_TABVALUE_EMPTY_INIT,
  5820. UPB_TABVALUE_EMPTY_INIT,
  5821. UPB_TABVALUE_EMPTY_INIT,
  5822. UPB_TABVALUE_PTR_INIT(&fields[105]),
  5823. UPB_TABVALUE_EMPTY_INIT,
  5824. UPB_TABVALUE_PTR_INIT(&fields[51]),
  5825. UPB_TABVALUE_PTR_INIT(&fields[76]),
  5826. UPB_TABVALUE_PTR_INIT(&fields[8]),
  5827. UPB_TABVALUE_PTR_INIT(&fields[47]),
  5828. UPB_TABVALUE_PTR_INIT(&fields[19]),
  5829. UPB_TABVALUE_PTR_INIT(&fields[87]),
  5830. UPB_TABVALUE_PTR_INIT(&fields[23]),
  5831. UPB_TABVALUE_PTR_INIT(&fields[69]),
  5832. UPB_TABVALUE_PTR_INIT(&fields[88]),
  5833. UPB_TABVALUE_PTR_INIT(&fields[82]),
  5834. UPB_TABVALUE_PTR_INIT(&fields[106]),
  5835. UPB_TABVALUE_PTR_INIT(&fields[93]),
  5836. UPB_TABVALUE_EMPTY_INIT,
  5837. UPB_TABVALUE_PTR_INIT(&fields[26]),
  5838. UPB_TABVALUE_EMPTY_INIT,
  5839. UPB_TABVALUE_PTR_INIT(&fields[35]),
  5840. UPB_TABVALUE_EMPTY_INIT,
  5841. UPB_TABVALUE_EMPTY_INIT,
  5842. UPB_TABVALUE_EMPTY_INIT,
  5843. UPB_TABVALUE_EMPTY_INIT,
  5844. UPB_TABVALUE_EMPTY_INIT,
  5845. UPB_TABVALUE_EMPTY_INIT,
  5846. UPB_TABVALUE_PTR_INIT(&fields[34]),
  5847. UPB_TABVALUE_PTR_INIT(&fields[67]),
  5848. UPB_TABVALUE_PTR_INIT(&fields[33]),
  5849. UPB_TABVALUE_PTR_INIT(&fields[27]),
  5850. UPB_TABVALUE_EMPTY_INIT,
  5851. UPB_TABVALUE_EMPTY_INIT,
  5852. UPB_TABVALUE_EMPTY_INIT,
  5853. UPB_TABVALUE_EMPTY_INIT,
  5854. UPB_TABVALUE_PTR_INIT(&fields[3]),
  5855. UPB_TABVALUE_PTR_INIT(&fields[32]),
  5856. UPB_TABVALUE_PTR_INIT(&fields[83]),
  5857. UPB_TABVALUE_EMPTY_INIT,
  5858. UPB_TABVALUE_PTR_INIT(&fields[31]),
  5859. UPB_TABVALUE_EMPTY_INIT,
  5860. UPB_TABVALUE_EMPTY_INIT,
  5861. UPB_TABVALUE_PTR_INIT(&fields[12]),
  5862. UPB_TABVALUE_EMPTY_INIT,
  5863. UPB_TABVALUE_EMPTY_INIT,
  5864. UPB_TABVALUE_EMPTY_INIT,
  5865. UPB_TABVALUE_PTR_INIT(&fields[36]),
  5866. UPB_TABVALUE_EMPTY_INIT,
  5867. UPB_TABVALUE_EMPTY_INIT,
  5868. UPB_TABVALUE_EMPTY_INIT,
  5869. UPB_TABVALUE_PTR_INIT(&fields[2]),
  5870. UPB_TABVALUE_EMPTY_INIT,
  5871. UPB_TABVALUE_EMPTY_INIT,
  5872. UPB_TABVALUE_EMPTY_INIT,
  5873. UPB_TABVALUE_EMPTY_INIT,
  5874. UPB_TABVALUE_PTR_INIT(&fields[64]),
  5875. UPB_TABVALUE_PTR_INIT(&fields[5]),
  5876. UPB_TABVALUE_PTR_INIT(&fields[37]),
  5877. UPB_TABVALUE_EMPTY_INIT,
  5878. UPB_TABVALUE_PTR_INIT(&fields[79]),
  5879. UPB_TABVALUE_PTR_INIT(&fields[80]),
  5880. UPB_TABVALUE_EMPTY_INIT,
  5881. UPB_TABVALUE_PTR_INIT(&fields[46]),
  5882. UPB_TABVALUE_PTR_INIT(&fields[61]),
  5883. UPB_TABVALUE_PTR_INIT(&fields[11]),
  5884. UPB_TABVALUE_EMPTY_INIT,
  5885. UPB_TABVALUE_EMPTY_INIT,
  5886. UPB_TABVALUE_EMPTY_INIT,
  5887. UPB_TABVALUE_PTR_INIT(&fields[45]),
  5888. UPB_TABVALUE_EMPTY_INIT,
  5889. UPB_TABVALUE_PTR_INIT(&fields[55]),
  5890. UPB_TABVALUE_PTR_INIT(&fields[29]),
  5891. UPB_TABVALUE_PTR_INIT(&fields[75]),
  5892. UPB_TABVALUE_PTR_INIT(&fields[71]),
  5893. UPB_TABVALUE_PTR_INIT(&fields[4]),
  5894. UPB_TABVALUE_PTR_INIT(&fields[86]),
  5895. UPB_TABVALUE_EMPTY_INIT,
  5896. UPB_TABVALUE_EMPTY_INIT,
  5897. UPB_TABVALUE_PTR_INIT(&fields[54]),
  5898. UPB_TABVALUE_EMPTY_INIT,
  5899. UPB_TABVALUE_PTR_INIT(&fields[53]),
  5900. UPB_TABVALUE_PTR_INIT(&fields[48]),
  5901. UPB_TABVALUE_PTR_INIT(&fields[72]),
  5902. UPB_TABVALUE_EMPTY_INIT,
  5903. UPB_TABVALUE_EMPTY_INIT,
  5904. UPB_TABVALUE_PTR_INIT(&fields[44]),
  5905. UPB_TABVALUE_EMPTY_INIT,
  5906. UPB_TABVALUE_PTR_INIT(&fields[78]),
  5907. UPB_TABVALUE_PTR_INIT(&fields[89]),
  5908. UPB_TABVALUE_PTR_INIT(&fields[42]),
  5909. UPB_TABVALUE_PTR_INIT(&fields[94]),
  5910. UPB_TABVALUE_EMPTY_INIT,
  5911. UPB_TABVALUE_PTR_INIT(&fields[43]),
  5912. UPB_TABVALUE_EMPTY_INIT,
  5913. UPB_TABVALUE_EMPTY_INIT,
  5914. UPB_TABVALUE_PTR_INIT(&fields[49]),
  5915. UPB_TABVALUE_PTR_INIT(&fields[28]),
  5916. UPB_TABVALUE_PTR_INIT(&fields[81]),
  5917. UPB_TABVALUE_PTR_INIT(&fields[59]),
  5918. UPB_TABVALUE_PTR_INIT(&fields[16]),
  5919. UPB_TABVALUE_PTR_INIT(&fields[92]),
  5920. UPB_TABVALUE_PTR_INIT(&fields[0]),
  5921. UPB_TABVALUE_EMPTY_INIT,
  5922. UPB_TABVALUE_PTR_INIT(&fields[58]),
  5923. UPB_TABVALUE_PTR_INIT(&fields[30]),
  5924. UPB_TABVALUE_EMPTY_INIT,
  5925. UPB_TABVALUE_PTR_INIT("LABEL_OPTIONAL"),
  5926. UPB_TABVALUE_PTR_INIT("LABEL_REQUIRED"),
  5927. UPB_TABVALUE_PTR_INIT("LABEL_REPEATED"),
  5928. UPB_TABVALUE_EMPTY_INIT,
  5929. UPB_TABVALUE_PTR_INIT("TYPE_DOUBLE"),
  5930. UPB_TABVALUE_PTR_INIT("TYPE_FLOAT"),
  5931. UPB_TABVALUE_PTR_INIT("TYPE_INT64"),
  5932. UPB_TABVALUE_PTR_INIT("TYPE_UINT64"),
  5933. UPB_TABVALUE_PTR_INIT("TYPE_INT32"),
  5934. UPB_TABVALUE_PTR_INIT("TYPE_FIXED64"),
  5935. UPB_TABVALUE_PTR_INIT("TYPE_FIXED32"),
  5936. UPB_TABVALUE_PTR_INIT("TYPE_BOOL"),
  5937. UPB_TABVALUE_PTR_INIT("TYPE_STRING"),
  5938. UPB_TABVALUE_PTR_INIT("TYPE_GROUP"),
  5939. UPB_TABVALUE_PTR_INIT("TYPE_MESSAGE"),
  5940. UPB_TABVALUE_PTR_INIT("TYPE_BYTES"),
  5941. UPB_TABVALUE_PTR_INIT("TYPE_UINT32"),
  5942. UPB_TABVALUE_PTR_INIT("TYPE_ENUM"),
  5943. UPB_TABVALUE_PTR_INIT("TYPE_SFIXED32"),
  5944. UPB_TABVALUE_PTR_INIT("TYPE_SFIXED64"),
  5945. UPB_TABVALUE_PTR_INIT("TYPE_SINT32"),
  5946. UPB_TABVALUE_PTR_INIT("TYPE_SINT64"),
  5947. UPB_TABVALUE_PTR_INIT("STRING"),
  5948. UPB_TABVALUE_PTR_INIT("CORD"),
  5949. UPB_TABVALUE_PTR_INIT("STRING_PIECE"),
  5950. UPB_TABVALUE_PTR_INIT("JS_NORMAL"),
  5951. UPB_TABVALUE_PTR_INIT("JS_STRING"),
  5952. UPB_TABVALUE_PTR_INIT("JS_NUMBER"),
  5953. UPB_TABVALUE_EMPTY_INIT,
  5954. UPB_TABVALUE_PTR_INIT("SPEED"),
  5955. UPB_TABVALUE_PTR_INIT("CODE_SIZE"),
  5956. UPB_TABVALUE_PTR_INIT("LITE_RUNTIME"),
  5957. };
  5958. #ifdef UPB_DEBUG_REFS
  5959. static upb_inttable reftables[268] = {
  5960. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5961. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5962. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5963. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5964. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5965. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5966. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5967. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5968. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5969. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5970. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5971. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5972. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5973. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5974. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5975. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5976. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5977. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5978. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5979. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5980. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5981. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5982. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5983. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5984. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5985. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5986. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5987. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5988. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5989. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5990. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5991. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5992. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5993. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5994. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5995. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5996. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5997. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5998. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5999. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6000. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6001. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6002. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6003. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6004. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6005. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6006. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6007. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6008. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6009. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6010. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6011. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6012. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6013. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6014. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6015. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6016. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6017. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6018. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6019. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6020. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6021. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6022. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6023. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6024. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6025. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6026. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6027. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6028. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6029. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6030. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6031. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6032. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6033. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6034. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6035. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6036. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6037. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6038. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6039. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6040. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6041. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6042. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6043. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6044. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6045. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6046. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6047. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6048. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6049. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6050. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6051. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6052. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6053. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6054. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6055. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6056. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6057. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6058. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6059. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6060. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6061. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6062. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6063. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6064. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6065. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6066. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6067. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6068. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6069. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6070. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6071. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6072. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6073. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6074. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6075. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6076. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6077. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6078. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6079. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6080. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6081. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6082. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6083. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6084. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6085. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6086. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6087. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6088. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6089. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6090. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6091. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6092. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6093. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6094. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6095. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6096. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6097. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6098. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6099. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6100. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6101. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6102. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6103. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6104. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6105. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6106. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6107. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6108. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6109. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6110. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6111. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6112. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6113. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6114. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6115. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6116. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6117. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6118. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6119. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6120. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6121. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6122. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6123. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6124. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6125. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6126. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6127. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6128. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6129. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6130. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6131. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6132. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6133. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6134. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6135. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6136. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6137. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6138. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6139. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6140. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6141. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6142. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6143. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6144. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6145. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6146. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6147. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6148. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6149. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6150. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6151. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6152. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6153. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6154. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6155. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6156. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6157. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6158. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6159. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6160. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6161. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6162. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6163. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6164. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6165. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6166. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6167. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6168. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6169. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6170. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6171. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6172. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6173. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6174. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6175. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6176. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6177. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6178. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6179. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6180. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6181. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6182. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6183. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6184. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6185. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6186. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6187. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6188. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6189. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6190. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6191. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6192. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6193. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6194. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6195. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6196. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6197. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6198. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6199. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6200. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6201. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6202. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6203. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6204. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6205. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6206. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6207. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6208. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6209. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6210. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6211. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6212. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6213. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6214. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6215. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6216. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6217. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6218. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6219. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6220. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6221. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6222. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6223. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6224. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6225. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6226. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6227. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  6228. };
  6229. #endif
  6230. static const upb_msgdef *refm(const upb_msgdef *m, const void *owner) {
  6231. upb_msgdef_ref(m, owner);
  6232. return m;
  6233. }
  6234. static const upb_enumdef *refe(const upb_enumdef *e, const void *owner) {
  6235. upb_enumdef_ref(e, owner);
  6236. return e;
  6237. }
  6238. /* Public API. */
  6239. const upb_msgdef *upbdefs_google_protobuf_DescriptorProto_get(const void *owner) { return refm(&msgs[0], owner); }
  6240. const upb_msgdef *upbdefs_google_protobuf_DescriptorProto_ExtensionRange_get(const void *owner) { return refm(&msgs[1], owner); }
  6241. const upb_msgdef *upbdefs_google_protobuf_DescriptorProto_ReservedRange_get(const void *owner) { return refm(&msgs[2], owner); }
  6242. const upb_msgdef *upbdefs_google_protobuf_EnumDescriptorProto_get(const void *owner) { return refm(&msgs[3], owner); }
  6243. const upb_msgdef *upbdefs_google_protobuf_EnumOptions_get(const void *owner) { return refm(&msgs[4], owner); }
  6244. const upb_msgdef *upbdefs_google_protobuf_EnumValueDescriptorProto_get(const void *owner) { return refm(&msgs[5], owner); }
  6245. const upb_msgdef *upbdefs_google_protobuf_EnumValueOptions_get(const void *owner) { return refm(&msgs[6], owner); }
  6246. const upb_msgdef *upbdefs_google_protobuf_FieldDescriptorProto_get(const void *owner) { return refm(&msgs[7], owner); }
  6247. const upb_msgdef *upbdefs_google_protobuf_FieldOptions_get(const void *owner) { return refm(&msgs[8], owner); }
  6248. const upb_msgdef *upbdefs_google_protobuf_FileDescriptorProto_get(const void *owner) { return refm(&msgs[9], owner); }
  6249. const upb_msgdef *upbdefs_google_protobuf_FileDescriptorSet_get(const void *owner) { return refm(&msgs[10], owner); }
  6250. const upb_msgdef *upbdefs_google_protobuf_FileOptions_get(const void *owner) { return refm(&msgs[11], owner); }
  6251. const upb_msgdef *upbdefs_google_protobuf_MessageOptions_get(const void *owner) { return refm(&msgs[12], owner); }
  6252. const upb_msgdef *upbdefs_google_protobuf_MethodDescriptorProto_get(const void *owner) { return refm(&msgs[13], owner); }
  6253. const upb_msgdef *upbdefs_google_protobuf_MethodOptions_get(const void *owner) { return refm(&msgs[14], owner); }
  6254. const upb_msgdef *upbdefs_google_protobuf_OneofDescriptorProto_get(const void *owner) { return refm(&msgs[15], owner); }
  6255. const upb_msgdef *upbdefs_google_protobuf_ServiceDescriptorProto_get(const void *owner) { return refm(&msgs[16], owner); }
  6256. const upb_msgdef *upbdefs_google_protobuf_ServiceOptions_get(const void *owner) { return refm(&msgs[17], owner); }
  6257. const upb_msgdef *upbdefs_google_protobuf_SourceCodeInfo_get(const void *owner) { return refm(&msgs[18], owner); }
  6258. const upb_msgdef *upbdefs_google_protobuf_SourceCodeInfo_Location_get(const void *owner) { return refm(&msgs[19], owner); }
  6259. const upb_msgdef *upbdefs_google_protobuf_UninterpretedOption_get(const void *owner) { return refm(&msgs[20], owner); }
  6260. const upb_msgdef *upbdefs_google_protobuf_UninterpretedOption_NamePart_get(const void *owner) { return refm(&msgs[21], owner); }
  6261. const upb_enumdef *upbdefs_google_protobuf_FieldDescriptorProto_Label_get(const void *owner) { return refe(&enums[0], owner); }
  6262. const upb_enumdef *upbdefs_google_protobuf_FieldDescriptorProto_Type_get(const void *owner) { return refe(&enums[1], owner); }
  6263. const upb_enumdef *upbdefs_google_protobuf_FieldOptions_CType_get(const void *owner) { return refe(&enums[2], owner); }
  6264. const upb_enumdef *upbdefs_google_protobuf_FieldOptions_JSType_get(const void *owner) { return refe(&enums[3], owner); }
  6265. const upb_enumdef *upbdefs_google_protobuf_FileOptions_OptimizeMode_get(const void *owner) { return refe(&enums[4], owner); }
  6266. /*
  6267. ** XXX: The routines in this file that consume a string do not currently
  6268. ** support having the string span buffers. In the future, as upb_sink and
  6269. ** its buffering/sharing functionality evolve there should be an easy and
  6270. ** idiomatic way of correctly handling this case. For now, we accept this
  6271. ** limitation since we currently only parse descriptors from single strings.
  6272. */
  6273. #include <errno.h>
  6274. #include <stdlib.h>
  6275. #include <string.h>
  6276. /* Compares a NULL-terminated string with a non-NULL-terminated string. */
  6277. static bool upb_streq(const char *str, const char *buf, size_t n) {
  6278. return strlen(str) == n && memcmp(str, buf, n) == 0;
  6279. }
  6280. /* We keep a stack of all the messages scopes we are currently in, as well as
  6281. * the top-level file scope. This is necessary to correctly qualify the
  6282. * definitions that are contained inside. "name" tracks the name of the
  6283. * message or package (a bare name -- not qualified by any enclosing scopes). */
  6284. typedef struct {
  6285. char *name;
  6286. /* Index of the first def that is under this scope. For msgdefs, the
  6287. * msgdef itself is at start-1. */
  6288. int start;
  6289. uint32_t oneof_start;
  6290. uint32_t oneof_index;
  6291. } upb_descreader_frame;
  6292. /* The maximum number of nested declarations that are allowed, ie.
  6293. * message Foo {
  6294. * message Bar {
  6295. * message Baz {
  6296. * }
  6297. * }
  6298. * }
  6299. *
  6300. * This is a resource limit that affects how big our runtime stack can grow.
  6301. * TODO: make this a runtime-settable property of the Reader instance. */
  6302. #define UPB_MAX_MESSAGE_NESTING 64
  6303. struct upb_descreader {
  6304. upb_sink sink;
  6305. upb_inttable files;
  6306. upb_filedef *file; /* The last file in files. */
  6307. upb_descreader_frame stack[UPB_MAX_MESSAGE_NESTING];
  6308. int stack_len;
  6309. upb_inttable oneofs;
  6310. uint32_t number;
  6311. char *name;
  6312. bool saw_number;
  6313. bool saw_name;
  6314. char *default_string;
  6315. upb_fielddef *f;
  6316. };
  6317. static char *upb_gstrndup(const char *buf, size_t n) {
  6318. char *ret = upb_gmalloc(n + 1);
  6319. if (!ret) return NULL;
  6320. memcpy(ret, buf, n);
  6321. ret[n] = '\0';
  6322. return ret;
  6323. }
  6324. /* Returns a newly allocated string that joins input strings together, for
  6325. * example:
  6326. * join("Foo.Bar", "Baz") -> "Foo.Bar.Baz"
  6327. * join("", "Baz") -> "Baz"
  6328. * Caller owns a ref on the returned string. */
  6329. static char *upb_join(const char *base, const char *name) {
  6330. if (!base || strlen(base) == 0) {
  6331. return upb_gstrdup(name);
  6332. } else {
  6333. char *ret = upb_gmalloc(strlen(base) + strlen(name) + 2);
  6334. if (!ret) {
  6335. return NULL;
  6336. }
  6337. ret[0] = '\0';
  6338. strcat(ret, base);
  6339. strcat(ret, ".");
  6340. strcat(ret, name);
  6341. return ret;
  6342. }
  6343. }
  6344. /* Qualify the defname for all defs starting with offset "start" with "str". */
  6345. static bool upb_descreader_qualify(upb_filedef *f, char *str, int32_t start) {
  6346. size_t i;
  6347. for (i = start; i < upb_filedef_defcount(f); i++) {
  6348. upb_def *def = upb_filedef_mutabledef(f, i);
  6349. char *name = upb_join(str, upb_def_fullname(def));
  6350. if (!name) {
  6351. /* Need better logic here; at this point we've qualified some names but
  6352. * not others. */
  6353. return false;
  6354. }
  6355. upb_def_setfullname(def, name, NULL);
  6356. upb_gfree(name);
  6357. }
  6358. return true;
  6359. }
  6360. /* upb_descreader ************************************************************/
  6361. static upb_msgdef *upb_descreader_top(upb_descreader *r) {
  6362. int index;
  6363. UPB_ASSERT(r->stack_len > 1);
  6364. index = r->stack[r->stack_len-1].start - 1;
  6365. UPB_ASSERT(index >= 0);
  6366. return upb_downcast_msgdef_mutable(upb_filedef_mutabledef(r->file, index));
  6367. }
  6368. static upb_def *upb_descreader_last(upb_descreader *r) {
  6369. return upb_filedef_mutabledef(r->file, upb_filedef_defcount(r->file) - 1);
  6370. }
  6371. /* Start/end handlers for FileDescriptorProto and DescriptorProto (the two
  6372. * entities that have names and can contain sub-definitions. */
  6373. void upb_descreader_startcontainer(upb_descreader *r) {
  6374. upb_descreader_frame *f = &r->stack[r->stack_len++];
  6375. f->start = upb_filedef_defcount(r->file);
  6376. f->oneof_start = upb_inttable_count(&r->oneofs);
  6377. f->oneof_index = 0;
  6378. f->name = NULL;
  6379. }
  6380. bool upb_descreader_endcontainer(upb_descreader *r) {
  6381. upb_descreader_frame *f = &r->stack[r->stack_len - 1];
  6382. while (upb_inttable_count(&r->oneofs) > f->oneof_start) {
  6383. upb_oneofdef *o = upb_value_getptr(upb_inttable_pop(&r->oneofs));
  6384. bool ok = upb_msgdef_addoneof(upb_descreader_top(r), o, &r->oneofs, NULL);
  6385. UPB_ASSERT(ok);
  6386. }
  6387. if (!upb_descreader_qualify(r->file, f->name, f->start)) {
  6388. return false;
  6389. }
  6390. upb_gfree(f->name);
  6391. f->name = NULL;
  6392. r->stack_len--;
  6393. return true;
  6394. }
  6395. void upb_descreader_setscopename(upb_descreader *r, char *str) {
  6396. upb_descreader_frame *f = &r->stack[r->stack_len-1];
  6397. upb_gfree(f->name);
  6398. f->name = str;
  6399. }
  6400. static upb_oneofdef *upb_descreader_getoneof(upb_descreader *r,
  6401. uint32_t index) {
  6402. bool found;
  6403. upb_value val;
  6404. upb_descreader_frame *f = &r->stack[r->stack_len-1];
  6405. /* DescriptorProto messages can be nested, so we will see the nested messages
  6406. * between when we see the FieldDescriptorProto and the OneofDescriptorProto.
  6407. * We need to preserve the oneofs in between these two things. */
  6408. index += f->oneof_start;
  6409. while (upb_inttable_count(&r->oneofs) <= index) {
  6410. upb_inttable_push(&r->oneofs, upb_value_ptr(upb_oneofdef_new(&r->oneofs)));
  6411. }
  6412. found = upb_inttable_lookup(&r->oneofs, index, &val);
  6413. UPB_ASSERT(found);
  6414. return upb_value_getptr(val);
  6415. }
  6416. /** Handlers for google.protobuf.FileDescriptorSet. ***************************/
  6417. static void *fileset_startfile(void *closure, const void *hd) {
  6418. upb_descreader *r = closure;
  6419. UPB_UNUSED(hd);
  6420. r->file = upb_filedef_new(&r->files);
  6421. upb_inttable_push(&r->files, upb_value_ptr(r->file));
  6422. return r;
  6423. }
  6424. /** Handlers for google.protobuf.FileDescriptorProto. *************************/
  6425. static bool file_start(void *closure, const void *hd) {
  6426. upb_descreader *r = closure;
  6427. UPB_UNUSED(hd);
  6428. upb_descreader_startcontainer(r);
  6429. return true;
  6430. }
  6431. static bool file_end(void *closure, const void *hd, upb_status *status) {
  6432. upb_descreader *r = closure;
  6433. UPB_UNUSED(hd);
  6434. UPB_UNUSED(status);
  6435. return upb_descreader_endcontainer(r);
  6436. }
  6437. static size_t file_onname(void *closure, const void *hd, const char *buf,
  6438. size_t n, const upb_bufhandle *handle) {
  6439. upb_descreader *r = closure;
  6440. char *name;
  6441. bool ok;
  6442. UPB_UNUSED(hd);
  6443. UPB_UNUSED(handle);
  6444. name = upb_gstrndup(buf, n);
  6445. /* XXX: see comment at the top of the file. */
  6446. ok = upb_filedef_setname(r->file, name, NULL);
  6447. upb_gfree(name);
  6448. UPB_ASSERT(ok);
  6449. return n;
  6450. }
  6451. static size_t file_onpackage(void *closure, const void *hd, const char *buf,
  6452. size_t n, const upb_bufhandle *handle) {
  6453. upb_descreader *r = closure;
  6454. char *package;
  6455. bool ok;
  6456. UPB_UNUSED(hd);
  6457. UPB_UNUSED(handle);
  6458. package = upb_gstrndup(buf, n);
  6459. /* XXX: see comment at the top of the file. */
  6460. upb_descreader_setscopename(r, package);
  6461. ok = upb_filedef_setpackage(r->file, package, NULL);
  6462. UPB_ASSERT(ok);
  6463. return n;
  6464. }
  6465. static size_t file_onphpnamespace(void *closure, const void *hd,
  6466. const char *buf, size_t n,
  6467. const upb_bufhandle *handle) {
  6468. upb_descreader *r = closure;
  6469. char *php_namespace;
  6470. bool ok;
  6471. UPB_UNUSED(hd);
  6472. UPB_UNUSED(handle);
  6473. php_namespace = upb_gstrndup(buf, n);
  6474. ok = upb_filedef_setphpnamespace(r->file, php_namespace, NULL);
  6475. upb_gfree(php_namespace);
  6476. UPB_ASSERT(ok);
  6477. return n;
  6478. }
  6479. static size_t file_onphpprefix(void *closure, const void *hd, const char *buf,
  6480. size_t n, const upb_bufhandle *handle) {
  6481. upb_descreader *r = closure;
  6482. char *prefix;
  6483. bool ok;
  6484. UPB_UNUSED(hd);
  6485. UPB_UNUSED(handle);
  6486. prefix = upb_gstrndup(buf, n);
  6487. ok = upb_filedef_setphpprefix(r->file, prefix, NULL);
  6488. upb_gfree(prefix);
  6489. UPB_ASSERT(ok);
  6490. return n;
  6491. }
  6492. static size_t file_onsyntax(void *closure, const void *hd, const char *buf,
  6493. size_t n, const upb_bufhandle *handle) {
  6494. upb_descreader *r = closure;
  6495. bool ok;
  6496. UPB_UNUSED(hd);
  6497. UPB_UNUSED(handle);
  6498. /* XXX: see comment at the top of the file. */
  6499. if (upb_streq("proto2", buf, n)) {
  6500. ok = upb_filedef_setsyntax(r->file, UPB_SYNTAX_PROTO2, NULL);
  6501. } else if (upb_streq("proto3", buf, n)) {
  6502. ok = upb_filedef_setsyntax(r->file, UPB_SYNTAX_PROTO3, NULL);
  6503. } else {
  6504. ok = false;
  6505. }
  6506. UPB_ASSERT(ok);
  6507. return n;
  6508. }
  6509. static void *file_startmsg(void *closure, const void *hd) {
  6510. upb_descreader *r = closure;
  6511. upb_msgdef *m = upb_msgdef_new(&m);
  6512. bool ok = upb_filedef_addmsg(r->file, m, &m, NULL);
  6513. UPB_UNUSED(hd);
  6514. UPB_ASSERT(ok);
  6515. return r;
  6516. }
  6517. static void *file_startenum(void *closure, const void *hd) {
  6518. upb_descreader *r = closure;
  6519. upb_enumdef *e = upb_enumdef_new(&e);
  6520. bool ok = upb_filedef_addenum(r->file, e, &e, NULL);
  6521. UPB_UNUSED(hd);
  6522. UPB_ASSERT(ok);
  6523. return r;
  6524. }
  6525. static void *file_startext(void *closure, const void *hd) {
  6526. upb_descreader *r = closure;
  6527. bool ok;
  6528. r->f = upb_fielddef_new(r);
  6529. ok = upb_filedef_addext(r->file, r->f, r, NULL);
  6530. UPB_UNUSED(hd);
  6531. UPB_ASSERT(ok);
  6532. return r;
  6533. }
  6534. /** Handlers for google.protobuf.EnumValueDescriptorProto. *********************/
  6535. static bool enumval_startmsg(void *closure, const void *hd) {
  6536. upb_descreader *r = closure;
  6537. UPB_UNUSED(hd);
  6538. r->saw_number = false;
  6539. r->saw_name = false;
  6540. return true;
  6541. }
  6542. static size_t enumval_onname(void *closure, const void *hd, const char *buf,
  6543. size_t n, const upb_bufhandle *handle) {
  6544. upb_descreader *r = closure;
  6545. UPB_UNUSED(hd);
  6546. UPB_UNUSED(handle);
  6547. /* XXX: see comment at the top of the file. */
  6548. upb_gfree(r->name);
  6549. r->name = upb_gstrndup(buf, n);
  6550. r->saw_name = true;
  6551. return n;
  6552. }
  6553. static bool enumval_onnumber(void *closure, const void *hd, int32_t val) {
  6554. upb_descreader *r = closure;
  6555. UPB_UNUSED(hd);
  6556. r->number = val;
  6557. r->saw_number = true;
  6558. return true;
  6559. }
  6560. static bool enumval_endmsg(void *closure, const void *hd, upb_status *status) {
  6561. upb_descreader *r = closure;
  6562. upb_enumdef *e;
  6563. UPB_UNUSED(hd);
  6564. if(!r->saw_number || !r->saw_name) {
  6565. upb_status_seterrmsg(status, "Enum value missing name or number.");
  6566. return false;
  6567. }
  6568. e = upb_downcast_enumdef_mutable(upb_descreader_last(r));
  6569. upb_enumdef_addval(e, r->name, r->number, status);
  6570. upb_gfree(r->name);
  6571. r->name = NULL;
  6572. return true;
  6573. }
  6574. /** Handlers for google.protobuf.EnumDescriptorProto. *************************/
  6575. static bool enum_endmsg(void *closure, const void *hd, upb_status *status) {
  6576. upb_descreader *r = closure;
  6577. upb_enumdef *e;
  6578. UPB_UNUSED(hd);
  6579. e = upb_downcast_enumdef_mutable(upb_descreader_last(r));
  6580. if (upb_def_fullname(upb_descreader_last(r)) == NULL) {
  6581. upb_status_seterrmsg(status, "Enum had no name.");
  6582. return false;
  6583. }
  6584. if (upb_enumdef_numvals(e) == 0) {
  6585. upb_status_seterrmsg(status, "Enum had no values.");
  6586. return false;
  6587. }
  6588. return true;
  6589. }
  6590. static size_t enum_onname(void *closure, const void *hd, const char *buf,
  6591. size_t n, const upb_bufhandle *handle) {
  6592. upb_descreader *r = closure;
  6593. char *fullname = upb_gstrndup(buf, n);
  6594. UPB_UNUSED(hd);
  6595. UPB_UNUSED(handle);
  6596. /* XXX: see comment at the top of the file. */
  6597. upb_def_setfullname(upb_descreader_last(r), fullname, NULL);
  6598. upb_gfree(fullname);
  6599. return n;
  6600. }
  6601. /** Handlers for google.protobuf.FieldDescriptorProto *************************/
  6602. static bool field_startmsg(void *closure, const void *hd) {
  6603. upb_descreader *r = closure;
  6604. UPB_UNUSED(hd);
  6605. UPB_ASSERT(r->f);
  6606. upb_gfree(r->default_string);
  6607. r->default_string = NULL;
  6608. /* fielddefs default to packed, but descriptors default to non-packed. */
  6609. upb_fielddef_setpacked(r->f, false);
  6610. return true;
  6611. }
  6612. /* Converts the default value in string "str" into "d". Passes a ref on str.
  6613. * Returns true on success. */
  6614. static bool parse_default(char *str, upb_fielddef *f) {
  6615. bool success = true;
  6616. char *end;
  6617. switch (upb_fielddef_type(f)) {
  6618. case UPB_TYPE_INT32: {
  6619. long val = strtol(str, &end, 0);
  6620. if (val > INT32_MAX || val < INT32_MIN || errno == ERANGE || *end)
  6621. success = false;
  6622. else
  6623. upb_fielddef_setdefaultint32(f, val);
  6624. break;
  6625. }
  6626. case UPB_TYPE_INT64: {
  6627. /* XXX: Need to write our own strtoll, since it's not available in c89. */
  6628. long long val = strtol(str, &end, 0);
  6629. if (val > INT64_MAX || val < INT64_MIN || errno == ERANGE || *end)
  6630. success = false;
  6631. else
  6632. upb_fielddef_setdefaultint64(f, val);
  6633. break;
  6634. }
  6635. case UPB_TYPE_UINT32: {
  6636. unsigned long val = strtoul(str, &end, 0);
  6637. if (val > UINT32_MAX || errno == ERANGE || *end)
  6638. success = false;
  6639. else
  6640. upb_fielddef_setdefaultuint32(f, val);
  6641. break;
  6642. }
  6643. case UPB_TYPE_UINT64: {
  6644. /* XXX: Need to write our own strtoull, since it's not available in c89. */
  6645. unsigned long long val = strtoul(str, &end, 0);
  6646. if (val > UINT64_MAX || errno == ERANGE || *end)
  6647. success = false;
  6648. else
  6649. upb_fielddef_setdefaultuint64(f, val);
  6650. break;
  6651. }
  6652. case UPB_TYPE_DOUBLE: {
  6653. double val = strtod(str, &end);
  6654. if (errno == ERANGE || *end)
  6655. success = false;
  6656. else
  6657. upb_fielddef_setdefaultdouble(f, val);
  6658. break;
  6659. }
  6660. case UPB_TYPE_FLOAT: {
  6661. /* XXX: Need to write our own strtof, since it's not available in c89. */
  6662. float val = strtod(str, &end);
  6663. if (errno == ERANGE || *end)
  6664. success = false;
  6665. else
  6666. upb_fielddef_setdefaultfloat(f, val);
  6667. break;
  6668. }
  6669. case UPB_TYPE_BOOL: {
  6670. if (strcmp(str, "false") == 0)
  6671. upb_fielddef_setdefaultbool(f, false);
  6672. else if (strcmp(str, "true") == 0)
  6673. upb_fielddef_setdefaultbool(f, true);
  6674. else
  6675. success = false;
  6676. break;
  6677. }
  6678. default: abort();
  6679. }
  6680. return success;
  6681. }
  6682. static bool field_endmsg(void *closure, const void *hd, upb_status *status) {
  6683. upb_descreader *r = closure;
  6684. upb_fielddef *f = r->f;
  6685. UPB_UNUSED(hd);
  6686. /* TODO: verify that all required fields were present. */
  6687. UPB_ASSERT(upb_fielddef_number(f) != 0);
  6688. UPB_ASSERT(upb_fielddef_name(f) != NULL);
  6689. UPB_ASSERT((upb_fielddef_subdefname(f) != NULL) == upb_fielddef_hassubdef(f));
  6690. if (r->default_string) {
  6691. if (upb_fielddef_issubmsg(f)) {
  6692. upb_status_seterrmsg(status, "Submessages cannot have defaults.");
  6693. return false;
  6694. }
  6695. if (upb_fielddef_isstring(f) || upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  6696. upb_fielddef_setdefaultcstr(f, r->default_string, NULL);
  6697. } else {
  6698. if (r->default_string && !parse_default(r->default_string, f)) {
  6699. /* We don't worry too much about giving a great error message since the
  6700. * compiler should have ensured this was correct. */
  6701. upb_status_seterrmsg(status, "Error converting default value.");
  6702. return false;
  6703. }
  6704. }
  6705. }
  6706. return true;
  6707. }
  6708. static bool field_onlazy(void *closure, const void *hd, bool val) {
  6709. upb_descreader *r = closure;
  6710. UPB_UNUSED(hd);
  6711. upb_fielddef_setlazy(r->f, val);
  6712. return true;
  6713. }
  6714. static bool field_onpacked(void *closure, const void *hd, bool val) {
  6715. upb_descreader *r = closure;
  6716. UPB_UNUSED(hd);
  6717. upb_fielddef_setpacked(r->f, val);
  6718. return true;
  6719. }
  6720. static bool field_ontype(void *closure, const void *hd, int32_t val) {
  6721. upb_descreader *r = closure;
  6722. UPB_UNUSED(hd);
  6723. upb_fielddef_setdescriptortype(r->f, val);
  6724. return true;
  6725. }
  6726. static bool field_onlabel(void *closure, const void *hd, int32_t val) {
  6727. upb_descreader *r = closure;
  6728. UPB_UNUSED(hd);
  6729. upb_fielddef_setlabel(r->f, val);
  6730. return true;
  6731. }
  6732. static bool field_onnumber(void *closure, const void *hd, int32_t val) {
  6733. upb_descreader *r = closure;
  6734. bool ok;
  6735. UPB_UNUSED(hd);
  6736. ok = upb_fielddef_setnumber(r->f, val, NULL);
  6737. UPB_ASSERT(ok);
  6738. return true;
  6739. }
  6740. static size_t field_onname(void *closure, const void *hd, const char *buf,
  6741. size_t n, const upb_bufhandle *handle) {
  6742. upb_descreader *r = closure;
  6743. char *name = upb_gstrndup(buf, n);
  6744. UPB_UNUSED(hd);
  6745. UPB_UNUSED(handle);
  6746. /* XXX: see comment at the top of the file. */
  6747. upb_fielddef_setname(r->f, name, NULL);
  6748. upb_gfree(name);
  6749. return n;
  6750. }
  6751. static size_t field_ontypename(void *closure, const void *hd, const char *buf,
  6752. size_t n, const upb_bufhandle *handle) {
  6753. upb_descreader *r = closure;
  6754. char *name = upb_gstrndup(buf, n);
  6755. UPB_UNUSED(hd);
  6756. UPB_UNUSED(handle);
  6757. /* XXX: see comment at the top of the file. */
  6758. upb_fielddef_setsubdefname(r->f, name, NULL);
  6759. upb_gfree(name);
  6760. return n;
  6761. }
  6762. static size_t field_onextendee(void *closure, const void *hd, const char *buf,
  6763. size_t n, const upb_bufhandle *handle) {
  6764. upb_descreader *r = closure;
  6765. char *name = upb_gstrndup(buf, n);
  6766. UPB_UNUSED(hd);
  6767. UPB_UNUSED(handle);
  6768. /* XXX: see comment at the top of the file. */
  6769. upb_fielddef_setcontainingtypename(r->f, name, NULL);
  6770. upb_gfree(name);
  6771. return n;
  6772. }
  6773. static size_t field_ondefaultval(void *closure, const void *hd, const char *buf,
  6774. size_t n, const upb_bufhandle *handle) {
  6775. upb_descreader *r = closure;
  6776. UPB_UNUSED(hd);
  6777. UPB_UNUSED(handle);
  6778. /* Have to convert from string to the correct type, but we might not know the
  6779. * type yet, so we save it as a string until the end of the field.
  6780. * XXX: see comment at the top of the file. */
  6781. upb_gfree(r->default_string);
  6782. r->default_string = upb_gstrndup(buf, n);
  6783. return n;
  6784. }
  6785. static bool field_ononeofindex(void *closure, const void *hd, int32_t index) {
  6786. upb_descreader *r = closure;
  6787. upb_oneofdef *o = upb_descreader_getoneof(r, index);
  6788. bool ok = upb_oneofdef_addfield(o, r->f, &r->f, NULL);
  6789. UPB_UNUSED(hd);
  6790. UPB_ASSERT(ok);
  6791. return true;
  6792. }
  6793. /** Handlers for google.protobuf.OneofDescriptorProto. ************************/
  6794. static size_t oneof_name(void *closure, const void *hd, const char *buf,
  6795. size_t n, const upb_bufhandle *handle) {
  6796. upb_descreader *r = closure;
  6797. upb_descreader_frame *f = &r->stack[r->stack_len-1];
  6798. upb_oneofdef *o = upb_descreader_getoneof(r, f->oneof_index++);
  6799. char *name_null_terminated = upb_gstrndup(buf, n);
  6800. bool ok = upb_oneofdef_setname(o, name_null_terminated, NULL);
  6801. UPB_UNUSED(hd);
  6802. UPB_UNUSED(handle);
  6803. UPB_ASSERT(ok);
  6804. free(name_null_terminated);
  6805. return n;
  6806. }
  6807. /** Handlers for google.protobuf.DescriptorProto ******************************/
  6808. static bool msg_start(void *closure, const void *hd) {
  6809. upb_descreader *r = closure;
  6810. UPB_UNUSED(hd);
  6811. upb_descreader_startcontainer(r);
  6812. return true;
  6813. }
  6814. static bool msg_end(void *closure, const void *hd, upb_status *status) {
  6815. upb_descreader *r = closure;
  6816. upb_msgdef *m = upb_descreader_top(r);
  6817. UPB_UNUSED(hd);
  6818. if(!upb_def_fullname(upb_msgdef_upcast_mutable(m))) {
  6819. upb_status_seterrmsg(status, "Encountered message with no name.");
  6820. return false;
  6821. }
  6822. return upb_descreader_endcontainer(r);
  6823. }
  6824. static size_t msg_name(void *closure, const void *hd, const char *buf,
  6825. size_t n, const upb_bufhandle *handle) {
  6826. upb_descreader *r = closure;
  6827. upb_msgdef *m = upb_descreader_top(r);
  6828. /* XXX: see comment at the top of the file. */
  6829. char *name = upb_gstrndup(buf, n);
  6830. UPB_UNUSED(hd);
  6831. UPB_UNUSED(handle);
  6832. upb_def_setfullname(upb_msgdef_upcast_mutable(m), name, NULL);
  6833. upb_descreader_setscopename(r, name); /* Passes ownership of name. */
  6834. return n;
  6835. }
  6836. static void *msg_startmsg(void *closure, const void *hd) {
  6837. upb_descreader *r = closure;
  6838. upb_msgdef *m = upb_msgdef_new(&m);
  6839. bool ok = upb_filedef_addmsg(r->file, m, &m, NULL);
  6840. UPB_UNUSED(hd);
  6841. UPB_ASSERT(ok);
  6842. return r;
  6843. }
  6844. static void *msg_startext(void *closure, const void *hd) {
  6845. upb_descreader *r = closure;
  6846. upb_fielddef *f = upb_fielddef_new(&f);
  6847. bool ok = upb_filedef_addext(r->file, f, &f, NULL);
  6848. UPB_UNUSED(hd);
  6849. UPB_ASSERT(ok);
  6850. return r;
  6851. }
  6852. static void *msg_startfield(void *closure, const void *hd) {
  6853. upb_descreader *r = closure;
  6854. r->f = upb_fielddef_new(&r->f);
  6855. /* We can't add the new field to the message until its name/number are
  6856. * filled in. */
  6857. UPB_UNUSED(hd);
  6858. return r;
  6859. }
  6860. static bool msg_endfield(void *closure, const void *hd) {
  6861. upb_descreader *r = closure;
  6862. upb_msgdef *m = upb_descreader_top(r);
  6863. bool ok;
  6864. UPB_UNUSED(hd);
  6865. /* Oneof fields are added to the msgdef through their oneof, so don't need to
  6866. * be added here. */
  6867. if (upb_fielddef_containingoneof(r->f) == NULL) {
  6868. ok = upb_msgdef_addfield(m, r->f, &r->f, NULL);
  6869. UPB_ASSERT(ok);
  6870. }
  6871. r->f = NULL;
  6872. return true;
  6873. }
  6874. static bool msg_onmapentry(void *closure, const void *hd, bool mapentry) {
  6875. upb_descreader *r = closure;
  6876. upb_msgdef *m = upb_descreader_top(r);
  6877. UPB_UNUSED(hd);
  6878. upb_msgdef_setmapentry(m, mapentry);
  6879. r->f = NULL;
  6880. return true;
  6881. }
  6882. /** Code to register handlers *************************************************/
  6883. #define F(msg, field) upbdefs_google_protobuf_ ## msg ## _f_ ## field(m)
  6884. static void reghandlers(const void *closure, upb_handlers *h) {
  6885. const upb_msgdef *m = upb_handlers_msgdef(h);
  6886. UPB_UNUSED(closure);
  6887. if (upbdefs_google_protobuf_FileDescriptorSet_is(m)) {
  6888. upb_handlers_setstartsubmsg(h, F(FileDescriptorSet, file),
  6889. &fileset_startfile, NULL);
  6890. } else if (upbdefs_google_protobuf_DescriptorProto_is(m)) {
  6891. upb_handlers_setstartmsg(h, &msg_start, NULL);
  6892. upb_handlers_setendmsg(h, &msg_end, NULL);
  6893. upb_handlers_setstring(h, F(DescriptorProto, name), &msg_name, NULL);
  6894. upb_handlers_setstartsubmsg(h, F(DescriptorProto, extension), &msg_startext,
  6895. NULL);
  6896. upb_handlers_setstartsubmsg(h, F(DescriptorProto, nested_type),
  6897. &msg_startmsg, NULL);
  6898. upb_handlers_setstartsubmsg(h, F(DescriptorProto, field),
  6899. &msg_startfield, NULL);
  6900. upb_handlers_setendsubmsg(h, F(DescriptorProto, field),
  6901. &msg_endfield, NULL);
  6902. upb_handlers_setstartsubmsg(h, F(DescriptorProto, enum_type),
  6903. &file_startenum, NULL);
  6904. } else if (upbdefs_google_protobuf_FileDescriptorProto_is(m)) {
  6905. upb_handlers_setstartmsg(h, &file_start, NULL);
  6906. upb_handlers_setendmsg(h, &file_end, NULL);
  6907. upb_handlers_setstring(h, F(FileDescriptorProto, name), &file_onname,
  6908. NULL);
  6909. upb_handlers_setstring(h, F(FileDescriptorProto, package), &file_onpackage,
  6910. NULL);
  6911. upb_handlers_setstring(h, F(FileDescriptorProto, syntax), &file_onsyntax,
  6912. NULL);
  6913. upb_handlers_setstartsubmsg(h, F(FileDescriptorProto, message_type),
  6914. &file_startmsg, NULL);
  6915. upb_handlers_setstartsubmsg(h, F(FileDescriptorProto, enum_type),
  6916. &file_startenum, NULL);
  6917. upb_handlers_setstartsubmsg(h, F(FileDescriptorProto, extension),
  6918. &file_startext, NULL);
  6919. } else if (upbdefs_google_protobuf_EnumValueDescriptorProto_is(m)) {
  6920. upb_handlers_setstartmsg(h, &enumval_startmsg, NULL);
  6921. upb_handlers_setendmsg(h, &enumval_endmsg, NULL);
  6922. upb_handlers_setstring(h, F(EnumValueDescriptorProto, name), &enumval_onname, NULL);
  6923. upb_handlers_setint32(h, F(EnumValueDescriptorProto, number), &enumval_onnumber,
  6924. NULL);
  6925. } else if (upbdefs_google_protobuf_EnumDescriptorProto_is(m)) {
  6926. upb_handlers_setendmsg(h, &enum_endmsg, NULL);
  6927. upb_handlers_setstring(h, F(EnumDescriptorProto, name), &enum_onname, NULL);
  6928. } else if (upbdefs_google_protobuf_FieldDescriptorProto_is(m)) {
  6929. upb_handlers_setstartmsg(h, &field_startmsg, NULL);
  6930. upb_handlers_setendmsg(h, &field_endmsg, NULL);
  6931. upb_handlers_setint32(h, F(FieldDescriptorProto, type), &field_ontype,
  6932. NULL);
  6933. upb_handlers_setint32(h, F(FieldDescriptorProto, label), &field_onlabel,
  6934. NULL);
  6935. upb_handlers_setint32(h, F(FieldDescriptorProto, number), &field_onnumber,
  6936. NULL);
  6937. upb_handlers_setstring(h, F(FieldDescriptorProto, name), &field_onname,
  6938. NULL);
  6939. upb_handlers_setstring(h, F(FieldDescriptorProto, type_name),
  6940. &field_ontypename, NULL);
  6941. upb_handlers_setstring(h, F(FieldDescriptorProto, extendee),
  6942. &field_onextendee, NULL);
  6943. upb_handlers_setstring(h, F(FieldDescriptorProto, default_value),
  6944. &field_ondefaultval, NULL);
  6945. upb_handlers_setint32(h, F(FieldDescriptorProto, oneof_index),
  6946. &field_ononeofindex, NULL);
  6947. } else if (upbdefs_google_protobuf_OneofDescriptorProto_is(m)) {
  6948. upb_handlers_setstring(h, F(OneofDescriptorProto, name), &oneof_name, NULL);
  6949. } else if (upbdefs_google_protobuf_FieldOptions_is(m)) {
  6950. upb_handlers_setbool(h, F(FieldOptions, lazy), &field_onlazy, NULL);
  6951. upb_handlers_setbool(h, F(FieldOptions, packed), &field_onpacked, NULL);
  6952. } else if (upbdefs_google_protobuf_MessageOptions_is(m)) {
  6953. upb_handlers_setbool(h, F(MessageOptions, map_entry), &msg_onmapentry, NULL);
  6954. } else if (upbdefs_google_protobuf_FileOptions_is(m)) {
  6955. upb_handlers_setstring(h, F(FileOptions, php_class_prefix),
  6956. &file_onphpprefix, NULL);
  6957. upb_handlers_setstring(h, F(FileOptions, php_namespace),
  6958. &file_onphpnamespace, NULL);
  6959. }
  6960. UPB_ASSERT(upb_ok(upb_handlers_status(h)));
  6961. }
  6962. #undef F
  6963. void descreader_cleanup(void *_r) {
  6964. upb_descreader *r = _r;
  6965. size_t i;
  6966. for (i = 0; i < upb_descreader_filecount(r); i++) {
  6967. upb_filedef_unref(upb_descreader_file(r, i), &r->files);
  6968. }
  6969. upb_gfree(r->name);
  6970. upb_inttable_uninit(&r->files);
  6971. upb_inttable_uninit(&r->oneofs);
  6972. upb_gfree(r->default_string);
  6973. while (r->stack_len > 0) {
  6974. upb_descreader_frame *f = &r->stack[--r->stack_len];
  6975. upb_gfree(f->name);
  6976. }
  6977. }
  6978. /* Public API ****************************************************************/
  6979. upb_descreader *upb_descreader_create(upb_env *e, const upb_handlers *h) {
  6980. upb_descreader *r = upb_env_malloc(e, sizeof(upb_descreader));
  6981. if (!r || !upb_env_addcleanup(e, descreader_cleanup, r)) {
  6982. return NULL;
  6983. }
  6984. upb_inttable_init(&r->files, UPB_CTYPE_PTR);
  6985. upb_inttable_init(&r->oneofs, UPB_CTYPE_PTR);
  6986. upb_sink_reset(upb_descreader_input(r), h, r);
  6987. r->stack_len = 0;
  6988. r->name = NULL;
  6989. r->default_string = NULL;
  6990. return r;
  6991. }
  6992. size_t upb_descreader_filecount(const upb_descreader *r) {
  6993. return upb_inttable_count(&r->files);
  6994. }
  6995. upb_filedef *upb_descreader_file(const upb_descreader *r, size_t i) {
  6996. upb_value v;
  6997. if (upb_inttable_lookup(&r->files, i, &v)) {
  6998. return upb_value_getptr(v);
  6999. } else {
  7000. return NULL;
  7001. }
  7002. }
  7003. upb_sink *upb_descreader_input(upb_descreader *r) {
  7004. return &r->sink;
  7005. }
  7006. const upb_handlers *upb_descreader_newhandlers(const void *owner) {
  7007. const upb_msgdef *m = upbdefs_google_protobuf_FileDescriptorSet_get(&m);
  7008. const upb_handlers *h = upb_handlers_newfrozen(m, owner, reghandlers, NULL);
  7009. upb_msgdef_unref(m, &m);
  7010. return h;
  7011. }
  7012. /*
  7013. ** protobuf decoder bytecode compiler
  7014. **
  7015. ** Code to compile a upb::Handlers into bytecode for decoding a protobuf
  7016. ** according to that specific schema and destination handlers.
  7017. **
  7018. ** Compiling to bytecode is always the first step. If we are using the
  7019. ** interpreted decoder we leave it as bytecode and interpret that. If we are
  7020. ** using a JIT decoder we use a code generator to turn the bytecode into native
  7021. ** code, LLVM IR, etc.
  7022. **
  7023. ** Bytecode definition is in decoder.int.h.
  7024. */
  7025. #include <stdarg.h>
  7026. #ifdef UPB_DUMP_BYTECODE
  7027. #include <stdio.h>
  7028. #endif
  7029. #define MAXLABEL 5
  7030. #define EMPTYLABEL -1
  7031. /* mgroup *********************************************************************/
  7032. static void freegroup(upb_refcounted *r) {
  7033. mgroup *g = (mgroup*)r;
  7034. upb_inttable_uninit(&g->methods);
  7035. #ifdef UPB_USE_JIT_X64
  7036. upb_pbdecoder_freejit(g);
  7037. #endif
  7038. upb_gfree(g->bytecode);
  7039. upb_gfree(g);
  7040. }
  7041. static void visitgroup(const upb_refcounted *r, upb_refcounted_visit *visit,
  7042. void *closure) {
  7043. const mgroup *g = (const mgroup*)r;
  7044. upb_inttable_iter i;
  7045. upb_inttable_begin(&i, &g->methods);
  7046. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  7047. upb_pbdecodermethod *method = upb_value_getptr(upb_inttable_iter_value(&i));
  7048. visit(r, upb_pbdecodermethod_upcast(method), closure);
  7049. }
  7050. }
  7051. mgroup *newgroup(const void *owner) {
  7052. mgroup *g = upb_gmalloc(sizeof(*g));
  7053. static const struct upb_refcounted_vtbl vtbl = {visitgroup, freegroup};
  7054. upb_refcounted_init(mgroup_upcast_mutable(g), &vtbl, owner);
  7055. upb_inttable_init(&g->methods, UPB_CTYPE_PTR);
  7056. g->bytecode = NULL;
  7057. g->bytecode_end = NULL;
  7058. return g;
  7059. }
  7060. /* upb_pbdecodermethod ********************************************************/
  7061. static void freemethod(upb_refcounted *r) {
  7062. upb_pbdecodermethod *method = (upb_pbdecodermethod*)r;
  7063. if (method->dest_handlers_) {
  7064. upb_handlers_unref(method->dest_handlers_, method);
  7065. }
  7066. upb_inttable_uninit(&method->dispatch);
  7067. upb_gfree(method);
  7068. }
  7069. static void visitmethod(const upb_refcounted *r, upb_refcounted_visit *visit,
  7070. void *closure) {
  7071. const upb_pbdecodermethod *m = (const upb_pbdecodermethod*)r;
  7072. visit(r, m->group, closure);
  7073. }
  7074. static upb_pbdecodermethod *newmethod(const upb_handlers *dest_handlers,
  7075. mgroup *group) {
  7076. static const struct upb_refcounted_vtbl vtbl = {visitmethod, freemethod};
  7077. upb_pbdecodermethod *ret = upb_gmalloc(sizeof(*ret));
  7078. upb_refcounted_init(upb_pbdecodermethod_upcast_mutable(ret), &vtbl, &ret);
  7079. upb_byteshandler_init(&ret->input_handler_);
  7080. /* The method references the group and vice-versa, in a circular reference. */
  7081. upb_ref2(ret, group);
  7082. upb_ref2(group, ret);
  7083. upb_inttable_insertptr(&group->methods, dest_handlers, upb_value_ptr(ret));
  7084. upb_pbdecodermethod_unref(ret, &ret);
  7085. ret->group = mgroup_upcast_mutable(group);
  7086. ret->dest_handlers_ = dest_handlers;
  7087. ret->is_native_ = false; /* If we JIT, it will update this later. */
  7088. upb_inttable_init(&ret->dispatch, UPB_CTYPE_UINT64);
  7089. if (ret->dest_handlers_) {
  7090. upb_handlers_ref(ret->dest_handlers_, ret);
  7091. }
  7092. return ret;
  7093. }
  7094. const upb_handlers *upb_pbdecodermethod_desthandlers(
  7095. const upb_pbdecodermethod *m) {
  7096. return m->dest_handlers_;
  7097. }
  7098. const upb_byteshandler *upb_pbdecodermethod_inputhandler(
  7099. const upb_pbdecodermethod *m) {
  7100. return &m->input_handler_;
  7101. }
  7102. bool upb_pbdecodermethod_isnative(const upb_pbdecodermethod *m) {
  7103. return m->is_native_;
  7104. }
  7105. const upb_pbdecodermethod *upb_pbdecodermethod_new(
  7106. const upb_pbdecodermethodopts *opts, const void *owner) {
  7107. const upb_pbdecodermethod *ret;
  7108. upb_pbcodecache cache;
  7109. upb_pbcodecache_init(&cache);
  7110. ret = upb_pbcodecache_getdecodermethod(&cache, opts);
  7111. upb_pbdecodermethod_ref(ret, owner);
  7112. upb_pbcodecache_uninit(&cache);
  7113. return ret;
  7114. }
  7115. /* bytecode compiler **********************************************************/
  7116. /* Data used only at compilation time. */
  7117. typedef struct {
  7118. mgroup *group;
  7119. uint32_t *pc;
  7120. int fwd_labels[MAXLABEL];
  7121. int back_labels[MAXLABEL];
  7122. /* For fields marked "lazy", parse them lazily or eagerly? */
  7123. bool lazy;
  7124. } compiler;
  7125. static compiler *newcompiler(mgroup *group, bool lazy) {
  7126. compiler *ret = upb_gmalloc(sizeof(*ret));
  7127. int i;
  7128. ret->group = group;
  7129. ret->lazy = lazy;
  7130. for (i = 0; i < MAXLABEL; i++) {
  7131. ret->fwd_labels[i] = EMPTYLABEL;
  7132. ret->back_labels[i] = EMPTYLABEL;
  7133. }
  7134. return ret;
  7135. }
  7136. static void freecompiler(compiler *c) {
  7137. upb_gfree(c);
  7138. }
  7139. const size_t ptr_words = sizeof(void*) / sizeof(uint32_t);
  7140. /* How many words an instruction is. */
  7141. static int instruction_len(uint32_t instr) {
  7142. switch (getop(instr)) {
  7143. case OP_SETDISPATCH: return 1 + ptr_words;
  7144. case OP_TAGN: return 3;
  7145. case OP_SETBIGGROUPNUM: return 2;
  7146. default: return 1;
  7147. }
  7148. }
  7149. bool op_has_longofs(int32_t instruction) {
  7150. switch (getop(instruction)) {
  7151. case OP_CALL:
  7152. case OP_BRANCH:
  7153. case OP_CHECKDELIM:
  7154. return true;
  7155. /* The "tag" instructions only have 8 bytes available for the jump target,
  7156. * but that is ok because these opcodes only require short jumps. */
  7157. case OP_TAG1:
  7158. case OP_TAG2:
  7159. case OP_TAGN:
  7160. return false;
  7161. default:
  7162. UPB_ASSERT(false);
  7163. return false;
  7164. }
  7165. }
  7166. static int32_t getofs(uint32_t instruction) {
  7167. if (op_has_longofs(instruction)) {
  7168. return (int32_t)instruction >> 8;
  7169. } else {
  7170. return (int8_t)(instruction >> 8);
  7171. }
  7172. }
  7173. static void setofs(uint32_t *instruction, int32_t ofs) {
  7174. if (op_has_longofs(*instruction)) {
  7175. *instruction = getop(*instruction) | ofs << 8;
  7176. } else {
  7177. *instruction = (*instruction & ~0xff00) | ((ofs & 0xff) << 8);
  7178. }
  7179. UPB_ASSERT(getofs(*instruction) == ofs); /* Would fail in cases of overflow. */
  7180. }
  7181. static uint32_t pcofs(compiler *c) { return c->pc - c->group->bytecode; }
  7182. /* Defines a local label at the current PC location. All previous forward
  7183. * references are updated to point to this location. The location is noted
  7184. * for any future backward references. */
  7185. static void label(compiler *c, unsigned int label) {
  7186. int val;
  7187. uint32_t *codep;
  7188. UPB_ASSERT(label < MAXLABEL);
  7189. val = c->fwd_labels[label];
  7190. codep = (val == EMPTYLABEL) ? NULL : c->group->bytecode + val;
  7191. while (codep) {
  7192. int ofs = getofs(*codep);
  7193. setofs(codep, c->pc - codep - instruction_len(*codep));
  7194. codep = ofs ? codep + ofs : NULL;
  7195. }
  7196. c->fwd_labels[label] = EMPTYLABEL;
  7197. c->back_labels[label] = pcofs(c);
  7198. }
  7199. /* Creates a reference to a numbered label; either a forward reference
  7200. * (positive arg) or backward reference (negative arg). For forward references
  7201. * the value returned now is actually a "next" pointer into a linked list of all
  7202. * instructions that use this label and will be patched later when the label is
  7203. * defined with label().
  7204. *
  7205. * The returned value is the offset that should be written into the instruction.
  7206. */
  7207. static int32_t labelref(compiler *c, int label) {
  7208. UPB_ASSERT(label < MAXLABEL);
  7209. if (label == LABEL_DISPATCH) {
  7210. /* No resolving required. */
  7211. return 0;
  7212. } else if (label < 0) {
  7213. /* Backward local label. Relative to the next instruction. */
  7214. uint32_t from = (c->pc + 1) - c->group->bytecode;
  7215. return c->back_labels[-label] - from;
  7216. } else {
  7217. /* Forward local label: prepend to (possibly-empty) linked list. */
  7218. int *lptr = &c->fwd_labels[label];
  7219. int32_t ret = (*lptr == EMPTYLABEL) ? 0 : *lptr - pcofs(c);
  7220. *lptr = pcofs(c);
  7221. return ret;
  7222. }
  7223. }
  7224. static void put32(compiler *c, uint32_t v) {
  7225. mgroup *g = c->group;
  7226. if (c->pc == g->bytecode_end) {
  7227. int ofs = pcofs(c);
  7228. size_t oldsize = g->bytecode_end - g->bytecode;
  7229. size_t newsize = UPB_MAX(oldsize * 2, 64);
  7230. /* TODO(haberman): handle OOM. */
  7231. g->bytecode = upb_grealloc(g->bytecode, oldsize * sizeof(uint32_t),
  7232. newsize * sizeof(uint32_t));
  7233. g->bytecode_end = g->bytecode + newsize;
  7234. c->pc = g->bytecode + ofs;
  7235. }
  7236. *c->pc++ = v;
  7237. }
  7238. static void putop(compiler *c, opcode op, ...) {
  7239. va_list ap;
  7240. va_start(ap, op);
  7241. switch (op) {
  7242. case OP_SETDISPATCH: {
  7243. uintptr_t ptr = (uintptr_t)va_arg(ap, void*);
  7244. put32(c, OP_SETDISPATCH);
  7245. put32(c, ptr);
  7246. if (sizeof(uintptr_t) > sizeof(uint32_t))
  7247. put32(c, (uint64_t)ptr >> 32);
  7248. break;
  7249. }
  7250. case OP_STARTMSG:
  7251. case OP_ENDMSG:
  7252. case OP_PUSHLENDELIM:
  7253. case OP_POP:
  7254. case OP_SETDELIM:
  7255. case OP_HALT:
  7256. case OP_RET:
  7257. case OP_DISPATCH:
  7258. put32(c, op);
  7259. break;
  7260. case OP_PARSE_DOUBLE:
  7261. case OP_PARSE_FLOAT:
  7262. case OP_PARSE_INT64:
  7263. case OP_PARSE_UINT64:
  7264. case OP_PARSE_INT32:
  7265. case OP_PARSE_FIXED64:
  7266. case OP_PARSE_FIXED32:
  7267. case OP_PARSE_BOOL:
  7268. case OP_PARSE_UINT32:
  7269. case OP_PARSE_SFIXED32:
  7270. case OP_PARSE_SFIXED64:
  7271. case OP_PARSE_SINT32:
  7272. case OP_PARSE_SINT64:
  7273. case OP_STARTSEQ:
  7274. case OP_ENDSEQ:
  7275. case OP_STARTSUBMSG:
  7276. case OP_ENDSUBMSG:
  7277. case OP_STARTSTR:
  7278. case OP_STRING:
  7279. case OP_ENDSTR:
  7280. case OP_PUSHTAGDELIM:
  7281. put32(c, op | va_arg(ap, upb_selector_t) << 8);
  7282. break;
  7283. case OP_SETBIGGROUPNUM:
  7284. put32(c, op);
  7285. put32(c, va_arg(ap, int));
  7286. break;
  7287. case OP_CALL: {
  7288. const upb_pbdecodermethod *method = va_arg(ap, upb_pbdecodermethod *);
  7289. put32(c, op | (method->code_base.ofs - (pcofs(c) + 1)) << 8);
  7290. break;
  7291. }
  7292. case OP_CHECKDELIM:
  7293. case OP_BRANCH: {
  7294. uint32_t instruction = op;
  7295. int label = va_arg(ap, int);
  7296. setofs(&instruction, labelref(c, label));
  7297. put32(c, instruction);
  7298. break;
  7299. }
  7300. case OP_TAG1:
  7301. case OP_TAG2: {
  7302. int label = va_arg(ap, int);
  7303. uint64_t tag = va_arg(ap, uint64_t);
  7304. uint32_t instruction = op | (tag << 16);
  7305. UPB_ASSERT(tag <= 0xffff);
  7306. setofs(&instruction, labelref(c, label));
  7307. put32(c, instruction);
  7308. break;
  7309. }
  7310. case OP_TAGN: {
  7311. int label = va_arg(ap, int);
  7312. uint64_t tag = va_arg(ap, uint64_t);
  7313. uint32_t instruction = op | (upb_value_size(tag) << 16);
  7314. setofs(&instruction, labelref(c, label));
  7315. put32(c, instruction);
  7316. put32(c, tag);
  7317. put32(c, tag >> 32);
  7318. break;
  7319. }
  7320. }
  7321. va_end(ap);
  7322. }
  7323. #if defined(UPB_USE_JIT_X64) || defined(UPB_DUMP_BYTECODE)
  7324. const char *upb_pbdecoder_getopname(unsigned int op) {
  7325. #define QUOTE(x) #x
  7326. #define EXPAND_AND_QUOTE(x) QUOTE(x)
  7327. #define OPNAME(x) OP_##x
  7328. #define OP(x) case OPNAME(x): return EXPAND_AND_QUOTE(OPNAME(x));
  7329. #define T(x) OP(PARSE_##x)
  7330. /* Keep in sync with list in decoder.int.h. */
  7331. switch ((opcode)op) {
  7332. T(DOUBLE) T(FLOAT) T(INT64) T(UINT64) T(INT32) T(FIXED64) T(FIXED32)
  7333. T(BOOL) T(UINT32) T(SFIXED32) T(SFIXED64) T(SINT32) T(SINT64)
  7334. OP(STARTMSG) OP(ENDMSG) OP(STARTSEQ) OP(ENDSEQ) OP(STARTSUBMSG)
  7335. OP(ENDSUBMSG) OP(STARTSTR) OP(STRING) OP(ENDSTR) OP(CALL) OP(RET)
  7336. OP(PUSHLENDELIM) OP(PUSHTAGDELIM) OP(SETDELIM) OP(CHECKDELIM)
  7337. OP(BRANCH) OP(TAG1) OP(TAG2) OP(TAGN) OP(SETDISPATCH) OP(POP)
  7338. OP(SETBIGGROUPNUM) OP(DISPATCH) OP(HALT)
  7339. }
  7340. return "<unknown op>";
  7341. #undef OP
  7342. #undef T
  7343. }
  7344. #endif
  7345. #ifdef UPB_DUMP_BYTECODE
  7346. static void dumpbc(uint32_t *p, uint32_t *end, FILE *f) {
  7347. uint32_t *begin = p;
  7348. while (p < end) {
  7349. fprintf(f, "%p %8tx", p, p - begin);
  7350. uint32_t instr = *p++;
  7351. uint8_t op = getop(instr);
  7352. fprintf(f, " %s", upb_pbdecoder_getopname(op));
  7353. switch ((opcode)op) {
  7354. case OP_SETDISPATCH: {
  7355. const upb_inttable *dispatch;
  7356. memcpy(&dispatch, p, sizeof(void*));
  7357. p += ptr_words;
  7358. const upb_pbdecodermethod *method =
  7359. (void *)((char *)dispatch -
  7360. offsetof(upb_pbdecodermethod, dispatch));
  7361. fprintf(f, " %s", upb_msgdef_fullname(
  7362. upb_handlers_msgdef(method->dest_handlers_)));
  7363. break;
  7364. }
  7365. case OP_DISPATCH:
  7366. case OP_STARTMSG:
  7367. case OP_ENDMSG:
  7368. case OP_PUSHLENDELIM:
  7369. case OP_POP:
  7370. case OP_SETDELIM:
  7371. case OP_HALT:
  7372. case OP_RET:
  7373. break;
  7374. case OP_PARSE_DOUBLE:
  7375. case OP_PARSE_FLOAT:
  7376. case OP_PARSE_INT64:
  7377. case OP_PARSE_UINT64:
  7378. case OP_PARSE_INT32:
  7379. case OP_PARSE_FIXED64:
  7380. case OP_PARSE_FIXED32:
  7381. case OP_PARSE_BOOL:
  7382. case OP_PARSE_UINT32:
  7383. case OP_PARSE_SFIXED32:
  7384. case OP_PARSE_SFIXED64:
  7385. case OP_PARSE_SINT32:
  7386. case OP_PARSE_SINT64:
  7387. case OP_STARTSEQ:
  7388. case OP_ENDSEQ:
  7389. case OP_STARTSUBMSG:
  7390. case OP_ENDSUBMSG:
  7391. case OP_STARTSTR:
  7392. case OP_STRING:
  7393. case OP_ENDSTR:
  7394. case OP_PUSHTAGDELIM:
  7395. fprintf(f, " %d", instr >> 8);
  7396. break;
  7397. case OP_SETBIGGROUPNUM:
  7398. fprintf(f, " %d", *p++);
  7399. break;
  7400. case OP_CHECKDELIM:
  7401. case OP_CALL:
  7402. case OP_BRANCH:
  7403. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  7404. break;
  7405. case OP_TAG1:
  7406. case OP_TAG2: {
  7407. fprintf(f, " tag:0x%x", instr >> 16);
  7408. if (getofs(instr)) {
  7409. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  7410. }
  7411. break;
  7412. }
  7413. case OP_TAGN: {
  7414. uint64_t tag = *p++;
  7415. tag |= (uint64_t)*p++ << 32;
  7416. fprintf(f, " tag:0x%llx", (long long)tag);
  7417. fprintf(f, " n:%d", instr >> 16);
  7418. if (getofs(instr)) {
  7419. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  7420. }
  7421. break;
  7422. }
  7423. }
  7424. fputs("\n", f);
  7425. }
  7426. }
  7427. #endif
  7428. static uint64_t get_encoded_tag(const upb_fielddef *f, int wire_type) {
  7429. uint32_t tag = (upb_fielddef_number(f) << 3) | wire_type;
  7430. uint64_t encoded_tag = upb_vencode32(tag);
  7431. /* No tag should be greater than 5 bytes. */
  7432. UPB_ASSERT(encoded_tag <= 0xffffffffff);
  7433. return encoded_tag;
  7434. }
  7435. static void putchecktag(compiler *c, const upb_fielddef *f,
  7436. int wire_type, int dest) {
  7437. uint64_t tag = get_encoded_tag(f, wire_type);
  7438. switch (upb_value_size(tag)) {
  7439. case 1:
  7440. putop(c, OP_TAG1, dest, tag);
  7441. break;
  7442. case 2:
  7443. putop(c, OP_TAG2, dest, tag);
  7444. break;
  7445. default:
  7446. putop(c, OP_TAGN, dest, tag);
  7447. break;
  7448. }
  7449. }
  7450. static upb_selector_t getsel(const upb_fielddef *f, upb_handlertype_t type) {
  7451. upb_selector_t selector;
  7452. bool ok = upb_handlers_getselector(f, type, &selector);
  7453. UPB_ASSERT(ok);
  7454. return selector;
  7455. }
  7456. /* Takes an existing, primary dispatch table entry and repacks it with a
  7457. * different alternate wire type. Called when we are inserting a secondary
  7458. * dispatch table entry for an alternate wire type. */
  7459. static uint64_t repack(uint64_t dispatch, int new_wt2) {
  7460. uint64_t ofs;
  7461. uint8_t wt1;
  7462. uint8_t old_wt2;
  7463. upb_pbdecoder_unpackdispatch(dispatch, &ofs, &wt1, &old_wt2);
  7464. UPB_ASSERT(old_wt2 == NO_WIRE_TYPE); /* wt2 should not be set yet. */
  7465. return upb_pbdecoder_packdispatch(ofs, wt1, new_wt2);
  7466. }
  7467. /* Marks the current bytecode position as the dispatch target for this message,
  7468. * field, and wire type. */
  7469. static void dispatchtarget(compiler *c, upb_pbdecodermethod *method,
  7470. const upb_fielddef *f, int wire_type) {
  7471. /* Offset is relative to msg base. */
  7472. uint64_t ofs = pcofs(c) - method->code_base.ofs;
  7473. uint32_t fn = upb_fielddef_number(f);
  7474. upb_inttable *d = &method->dispatch;
  7475. upb_value v;
  7476. if (upb_inttable_remove(d, fn, &v)) {
  7477. /* TODO: prioritize based on packed setting in .proto file. */
  7478. uint64_t repacked = repack(upb_value_getuint64(v), wire_type);
  7479. upb_inttable_insert(d, fn, upb_value_uint64(repacked));
  7480. upb_inttable_insert(d, fn + UPB_MAX_FIELDNUMBER, upb_value_uint64(ofs));
  7481. } else {
  7482. uint64_t val = upb_pbdecoder_packdispatch(ofs, wire_type, NO_WIRE_TYPE);
  7483. upb_inttable_insert(d, fn, upb_value_uint64(val));
  7484. }
  7485. }
  7486. static void putpush(compiler *c, const upb_fielddef *f) {
  7487. if (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE) {
  7488. putop(c, OP_PUSHLENDELIM);
  7489. } else {
  7490. uint32_t fn = upb_fielddef_number(f);
  7491. if (fn >= 1 << 24) {
  7492. putop(c, OP_PUSHTAGDELIM, 0);
  7493. putop(c, OP_SETBIGGROUPNUM, fn);
  7494. } else {
  7495. putop(c, OP_PUSHTAGDELIM, fn);
  7496. }
  7497. }
  7498. }
  7499. static upb_pbdecodermethod *find_submethod(const compiler *c,
  7500. const upb_pbdecodermethod *method,
  7501. const upb_fielddef *f) {
  7502. const upb_handlers *sub =
  7503. upb_handlers_getsubhandlers(method->dest_handlers_, f);
  7504. upb_value v;
  7505. return upb_inttable_lookupptr(&c->group->methods, sub, &v)
  7506. ? upb_value_getptr(v)
  7507. : NULL;
  7508. }
  7509. static void putsel(compiler *c, opcode op, upb_selector_t sel,
  7510. const upb_handlers *h) {
  7511. if (upb_handlers_gethandler(h, sel)) {
  7512. putop(c, op, sel);
  7513. }
  7514. }
  7515. /* Puts an opcode to call a callback, but only if a callback actually exists for
  7516. * this field and handler type. */
  7517. static void maybeput(compiler *c, opcode op, const upb_handlers *h,
  7518. const upb_fielddef *f, upb_handlertype_t type) {
  7519. putsel(c, op, getsel(f, type), h);
  7520. }
  7521. static bool haslazyhandlers(const upb_handlers *h, const upb_fielddef *f) {
  7522. if (!upb_fielddef_lazy(f))
  7523. return false;
  7524. return upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STARTSTR)) ||
  7525. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STRING)) ||
  7526. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_ENDSTR));
  7527. }
  7528. /* bytecode compiler code generation ******************************************/
  7529. /* Symbolic names for our local labels. */
  7530. #define LABEL_LOOPSTART 1 /* Top of a repeated field loop. */
  7531. #define LABEL_LOOPBREAK 2 /* To jump out of a repeated loop */
  7532. #define LABEL_FIELD 3 /* Jump backward to find the most recent field. */
  7533. #define LABEL_ENDMSG 4 /* To reach the OP_ENDMSG instr for this msg. */
  7534. /* Generates bytecode to parse a single non-lazy message field. */
  7535. static void generate_msgfield(compiler *c, const upb_fielddef *f,
  7536. upb_pbdecodermethod *method) {
  7537. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  7538. const upb_pbdecodermethod *sub_m = find_submethod(c, method, f);
  7539. int wire_type;
  7540. if (!sub_m) {
  7541. /* Don't emit any code for this field at all; it will be parsed as an
  7542. * unknown field.
  7543. *
  7544. * TODO(haberman): we should change this to parse it as a string field
  7545. * instead. It will probably be faster, but more importantly, once we
  7546. * start vending unknown fields, a field shouldn't be treated as unknown
  7547. * just because it doesn't have subhandlers registered. */
  7548. return;
  7549. }
  7550. label(c, LABEL_FIELD);
  7551. wire_type =
  7552. (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE)
  7553. ? UPB_WIRE_TYPE_DELIMITED
  7554. : UPB_WIRE_TYPE_START_GROUP;
  7555. if (upb_fielddef_isseq(f)) {
  7556. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  7557. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  7558. dispatchtarget(c, method, f, wire_type);
  7559. putop(c, OP_PUSHTAGDELIM, 0);
  7560. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  7561. label(c, LABEL_LOOPSTART);
  7562. putpush(c, f);
  7563. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  7564. putop(c, OP_CALL, sub_m);
  7565. putop(c, OP_POP);
  7566. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  7567. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  7568. putop(c, OP_SETDELIM);
  7569. }
  7570. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  7571. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  7572. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  7573. label(c, LABEL_LOOPBREAK);
  7574. putop(c, OP_POP);
  7575. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  7576. } else {
  7577. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  7578. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  7579. dispatchtarget(c, method, f, wire_type);
  7580. putpush(c, f);
  7581. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  7582. putop(c, OP_CALL, sub_m);
  7583. putop(c, OP_POP);
  7584. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  7585. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  7586. putop(c, OP_SETDELIM);
  7587. }
  7588. }
  7589. }
  7590. /* Generates bytecode to parse a single string or lazy submessage field. */
  7591. static void generate_delimfield(compiler *c, const upb_fielddef *f,
  7592. upb_pbdecodermethod *method) {
  7593. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  7594. label(c, LABEL_FIELD);
  7595. if (upb_fielddef_isseq(f)) {
  7596. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  7597. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  7598. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  7599. putop(c, OP_PUSHTAGDELIM, 0);
  7600. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  7601. label(c, LABEL_LOOPSTART);
  7602. putop(c, OP_PUSHLENDELIM);
  7603. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  7604. /* Need to emit even if no handler to skip past the string. */
  7605. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  7606. putop(c, OP_POP);
  7607. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  7608. putop(c, OP_SETDELIM);
  7609. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  7610. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_LOOPBREAK);
  7611. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  7612. label(c, LABEL_LOOPBREAK);
  7613. putop(c, OP_POP);
  7614. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  7615. } else {
  7616. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  7617. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  7618. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  7619. putop(c, OP_PUSHLENDELIM);
  7620. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  7621. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  7622. putop(c, OP_POP);
  7623. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  7624. putop(c, OP_SETDELIM);
  7625. }
  7626. }
  7627. /* Generates bytecode to parse a single primitive field. */
  7628. static void generate_primitivefield(compiler *c, const upb_fielddef *f,
  7629. upb_pbdecodermethod *method) {
  7630. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  7631. upb_descriptortype_t descriptor_type = upb_fielddef_descriptortype(f);
  7632. opcode parse_type;
  7633. upb_selector_t sel;
  7634. int wire_type;
  7635. label(c, LABEL_FIELD);
  7636. /* From a decoding perspective, ENUM is the same as INT32. */
  7637. if (descriptor_type == UPB_DESCRIPTOR_TYPE_ENUM)
  7638. descriptor_type = UPB_DESCRIPTOR_TYPE_INT32;
  7639. parse_type = (opcode)descriptor_type;
  7640. /* TODO(haberman): generate packed or non-packed first depending on "packed"
  7641. * setting in the fielddef. This will favor (in speed) whichever was
  7642. * specified. */
  7643. UPB_ASSERT((int)parse_type >= 0 && parse_type <= OP_MAX);
  7644. sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  7645. wire_type = upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  7646. if (upb_fielddef_isseq(f)) {
  7647. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  7648. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  7649. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  7650. putop(c, OP_PUSHLENDELIM);
  7651. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); /* Packed */
  7652. label(c, LABEL_LOOPSTART);
  7653. putop(c, parse_type, sel);
  7654. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  7655. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  7656. dispatchtarget(c, method, f, wire_type);
  7657. putop(c, OP_PUSHTAGDELIM, 0);
  7658. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); /* Non-packed */
  7659. label(c, LABEL_LOOPSTART);
  7660. putop(c, parse_type, sel);
  7661. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  7662. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  7663. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  7664. label(c, LABEL_LOOPBREAK);
  7665. putop(c, OP_POP); /* Packed and non-packed join. */
  7666. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  7667. putop(c, OP_SETDELIM); /* Could remove for non-packed by dup ENDSEQ. */
  7668. } else {
  7669. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  7670. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  7671. dispatchtarget(c, method, f, wire_type);
  7672. putop(c, parse_type, sel);
  7673. }
  7674. }
  7675. /* Adds bytecode for parsing the given message to the given decoderplan,
  7676. * while adding all dispatch targets to this message's dispatch table. */
  7677. static void compile_method(compiler *c, upb_pbdecodermethod *method) {
  7678. const upb_handlers *h;
  7679. const upb_msgdef *md;
  7680. uint32_t* start_pc;
  7681. upb_msg_field_iter i;
  7682. upb_value val;
  7683. UPB_ASSERT(method);
  7684. /* Clear all entries in the dispatch table. */
  7685. upb_inttable_uninit(&method->dispatch);
  7686. upb_inttable_init(&method->dispatch, UPB_CTYPE_UINT64);
  7687. h = upb_pbdecodermethod_desthandlers(method);
  7688. md = upb_handlers_msgdef(h);
  7689. method->code_base.ofs = pcofs(c);
  7690. putop(c, OP_SETDISPATCH, &method->dispatch);
  7691. putsel(c, OP_STARTMSG, UPB_STARTMSG_SELECTOR, h);
  7692. label(c, LABEL_FIELD);
  7693. start_pc = c->pc;
  7694. for(upb_msg_field_begin(&i, md);
  7695. !upb_msg_field_done(&i);
  7696. upb_msg_field_next(&i)) {
  7697. const upb_fielddef *f = upb_msg_iter_field(&i);
  7698. upb_fieldtype_t type = upb_fielddef_type(f);
  7699. if (type == UPB_TYPE_MESSAGE && !(haslazyhandlers(h, f) && c->lazy)) {
  7700. generate_msgfield(c, f, method);
  7701. } else if (type == UPB_TYPE_STRING || type == UPB_TYPE_BYTES ||
  7702. type == UPB_TYPE_MESSAGE) {
  7703. generate_delimfield(c, f, method);
  7704. } else {
  7705. generate_primitivefield(c, f, method);
  7706. }
  7707. }
  7708. /* If there were no fields, or if no handlers were defined, we need to
  7709. * generate a non-empty loop body so that we can at least dispatch for unknown
  7710. * fields and check for the end of the message. */
  7711. if (c->pc == start_pc) {
  7712. /* Check for end-of-message. */
  7713. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  7714. /* Unconditionally dispatch. */
  7715. putop(c, OP_DISPATCH, 0);
  7716. }
  7717. /* For now we just loop back to the last field of the message (or if none,
  7718. * the DISPATCH opcode for the message). */
  7719. putop(c, OP_BRANCH, -LABEL_FIELD);
  7720. /* Insert both a label and a dispatch table entry for this end-of-msg. */
  7721. label(c, LABEL_ENDMSG);
  7722. val = upb_value_uint64(pcofs(c) - method->code_base.ofs);
  7723. upb_inttable_insert(&method->dispatch, DISPATCH_ENDMSG, val);
  7724. putsel(c, OP_ENDMSG, UPB_ENDMSG_SELECTOR, h);
  7725. putop(c, OP_RET);
  7726. upb_inttable_compact(&method->dispatch);
  7727. }
  7728. /* Populate "methods" with new upb_pbdecodermethod objects reachable from "h".
  7729. * Returns the method for these handlers.
  7730. *
  7731. * Generates a new method for every destination handlers reachable from "h". */
  7732. static void find_methods(compiler *c, const upb_handlers *h) {
  7733. upb_value v;
  7734. upb_msg_field_iter i;
  7735. const upb_msgdef *md;
  7736. if (upb_inttable_lookupptr(&c->group->methods, h, &v))
  7737. return;
  7738. newmethod(h, c->group);
  7739. /* Find submethods. */
  7740. md = upb_handlers_msgdef(h);
  7741. for(upb_msg_field_begin(&i, md);
  7742. !upb_msg_field_done(&i);
  7743. upb_msg_field_next(&i)) {
  7744. const upb_fielddef *f = upb_msg_iter_field(&i);
  7745. const upb_handlers *sub_h;
  7746. if (upb_fielddef_type(f) == UPB_TYPE_MESSAGE &&
  7747. (sub_h = upb_handlers_getsubhandlers(h, f)) != NULL) {
  7748. /* We only generate a decoder method for submessages with handlers.
  7749. * Others will be parsed as unknown fields. */
  7750. find_methods(c, sub_h);
  7751. }
  7752. }
  7753. }
  7754. /* (Re-)compile bytecode for all messages in "msgs."
  7755. * Overwrites any existing bytecode in "c". */
  7756. static void compile_methods(compiler *c) {
  7757. upb_inttable_iter i;
  7758. /* Start over at the beginning of the bytecode. */
  7759. c->pc = c->group->bytecode;
  7760. upb_inttable_begin(&i, &c->group->methods);
  7761. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  7762. upb_pbdecodermethod *method = upb_value_getptr(upb_inttable_iter_value(&i));
  7763. compile_method(c, method);
  7764. }
  7765. }
  7766. static void set_bytecode_handlers(mgroup *g) {
  7767. upb_inttable_iter i;
  7768. upb_inttable_begin(&i, &g->methods);
  7769. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  7770. upb_pbdecodermethod *m = upb_value_getptr(upb_inttable_iter_value(&i));
  7771. upb_byteshandler *h = &m->input_handler_;
  7772. m->code_base.ptr = g->bytecode + m->code_base.ofs;
  7773. upb_byteshandler_setstartstr(h, upb_pbdecoder_startbc, m->code_base.ptr);
  7774. upb_byteshandler_setstring(h, upb_pbdecoder_decode, g);
  7775. upb_byteshandler_setendstr(h, upb_pbdecoder_end, m);
  7776. }
  7777. }
  7778. /* JIT setup. *****************************************************************/
  7779. #ifdef UPB_USE_JIT_X64
  7780. static void sethandlers(mgroup *g, bool allowjit) {
  7781. g->jit_code = NULL;
  7782. if (allowjit) {
  7783. /* Compile byte-code into machine code, create handlers. */
  7784. upb_pbdecoder_jit(g);
  7785. } else {
  7786. set_bytecode_handlers(g);
  7787. }
  7788. }
  7789. #else /* UPB_USE_JIT_X64 */
  7790. static void sethandlers(mgroup *g, bool allowjit) {
  7791. /* No JIT compiled in; use bytecode handlers unconditionally. */
  7792. UPB_UNUSED(allowjit);
  7793. set_bytecode_handlers(g);
  7794. }
  7795. #endif /* UPB_USE_JIT_X64 */
  7796. /* TODO(haberman): allow this to be constructed for an arbitrary set of dest
  7797. * handlers and other mgroups (but verify we have a transitive closure). */
  7798. const mgroup *mgroup_new(const upb_handlers *dest, bool allowjit, bool lazy,
  7799. const void *owner) {
  7800. mgroup *g;
  7801. compiler *c;
  7802. UPB_UNUSED(allowjit);
  7803. UPB_ASSERT(upb_handlers_isfrozen(dest));
  7804. g = newgroup(owner);
  7805. c = newcompiler(g, lazy);
  7806. find_methods(c, dest);
  7807. /* We compile in two passes:
  7808. * 1. all messages are assigned relative offsets from the beginning of the
  7809. * bytecode (saved in method->code_base).
  7810. * 2. forwards OP_CALL instructions can be correctly linked since message
  7811. * offsets have been previously assigned.
  7812. *
  7813. * Could avoid the second pass by linking OP_CALL instructions somehow. */
  7814. compile_methods(c);
  7815. compile_methods(c);
  7816. g->bytecode_end = c->pc;
  7817. freecompiler(c);
  7818. #ifdef UPB_DUMP_BYTECODE
  7819. {
  7820. FILE *f = fopen("/tmp/upb-bytecode", "w");
  7821. UPB_ASSERT(f);
  7822. dumpbc(g->bytecode, g->bytecode_end, stderr);
  7823. dumpbc(g->bytecode, g->bytecode_end, f);
  7824. fclose(f);
  7825. f = fopen("/tmp/upb-bytecode.bin", "wb");
  7826. UPB_ASSERT(f);
  7827. fwrite(g->bytecode, 1, g->bytecode_end - g->bytecode, f);
  7828. fclose(f);
  7829. }
  7830. #endif
  7831. sethandlers(g, allowjit);
  7832. return g;
  7833. }
  7834. /* upb_pbcodecache ************************************************************/
  7835. void upb_pbcodecache_init(upb_pbcodecache *c) {
  7836. upb_inttable_init(&c->groups, UPB_CTYPE_CONSTPTR);
  7837. c->allow_jit_ = true;
  7838. }
  7839. void upb_pbcodecache_uninit(upb_pbcodecache *c) {
  7840. upb_inttable_iter i;
  7841. upb_inttable_begin(&i, &c->groups);
  7842. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  7843. const mgroup *group = upb_value_getconstptr(upb_inttable_iter_value(&i));
  7844. mgroup_unref(group, c);
  7845. }
  7846. upb_inttable_uninit(&c->groups);
  7847. }
  7848. bool upb_pbcodecache_allowjit(const upb_pbcodecache *c) {
  7849. return c->allow_jit_;
  7850. }
  7851. bool upb_pbcodecache_setallowjit(upb_pbcodecache *c, bool allow) {
  7852. if (upb_inttable_count(&c->groups) > 0)
  7853. return false;
  7854. c->allow_jit_ = allow;
  7855. return true;
  7856. }
  7857. const upb_pbdecodermethod *upb_pbcodecache_getdecodermethod(
  7858. upb_pbcodecache *c, const upb_pbdecodermethodopts *opts) {
  7859. upb_value v;
  7860. bool ok;
  7861. /* Right now we build a new DecoderMethod every time.
  7862. * TODO(haberman): properly cache methods by their true key. */
  7863. const mgroup *g = mgroup_new(opts->handlers, c->allow_jit_, opts->lazy, c);
  7864. upb_inttable_push(&c->groups, upb_value_constptr(g));
  7865. ok = upb_inttable_lookupptr(&g->methods, opts->handlers, &v);
  7866. UPB_ASSERT(ok);
  7867. return upb_value_getptr(v);
  7868. }
  7869. /* upb_pbdecodermethodopts ****************************************************/
  7870. void upb_pbdecodermethodopts_init(upb_pbdecodermethodopts *opts,
  7871. const upb_handlers *h) {
  7872. opts->handlers = h;
  7873. opts->lazy = false;
  7874. }
  7875. void upb_pbdecodermethodopts_setlazy(upb_pbdecodermethodopts *opts, bool lazy) {
  7876. opts->lazy = lazy;
  7877. }
  7878. /*
  7879. ** upb::Decoder (Bytecode Decoder VM)
  7880. **
  7881. ** Bytecode must previously have been generated using the bytecode compiler in
  7882. ** compile_decoder.c. This decoder then walks through the bytecode op-by-op to
  7883. ** parse the input.
  7884. **
  7885. ** Decoding is fully resumable; we just keep a pointer to the current bytecode
  7886. ** instruction and resume from there. A fair amount of the logic here is to
  7887. ** handle the fact that values can span buffer seams and we have to be able to
  7888. ** be capable of suspending/resuming from any byte in the stream. This
  7889. ** sometimes requires keeping a few trailing bytes from the last buffer around
  7890. ** in the "residual" buffer.
  7891. */
  7892. #include <inttypes.h>
  7893. #include <stddef.h>
  7894. #ifdef UPB_DUMP_BYTECODE
  7895. #include <stdio.h>
  7896. #endif
  7897. #define CHECK_SUSPEND(x) if (!(x)) return upb_pbdecoder_suspend(d);
  7898. /* Error messages that are shared between the bytecode and JIT decoders. */
  7899. const char *kPbDecoderStackOverflow = "Nesting too deep.";
  7900. const char *kPbDecoderSubmessageTooLong =
  7901. "Submessage end extends past enclosing submessage.";
  7902. /* Error messages shared within this file. */
  7903. static const char *kUnterminatedVarint = "Unterminated varint.";
  7904. /* upb_pbdecoder **************************************************************/
  7905. static opcode halt = OP_HALT;
  7906. /* A dummy character we can point to when the user passes us a NULL buffer.
  7907. * We need this because in C (NULL + 0) and (NULL - NULL) are undefined
  7908. * behavior, which would invalidate functions like curbufleft(). */
  7909. static const char dummy_char;
  7910. /* Whether an op consumes any of the input buffer. */
  7911. static bool consumes_input(opcode op) {
  7912. switch (op) {
  7913. case OP_SETDISPATCH:
  7914. case OP_STARTMSG:
  7915. case OP_ENDMSG:
  7916. case OP_STARTSEQ:
  7917. case OP_ENDSEQ:
  7918. case OP_STARTSUBMSG:
  7919. case OP_ENDSUBMSG:
  7920. case OP_STARTSTR:
  7921. case OP_ENDSTR:
  7922. case OP_PUSHTAGDELIM:
  7923. case OP_POP:
  7924. case OP_SETDELIM:
  7925. case OP_SETBIGGROUPNUM:
  7926. case OP_CHECKDELIM:
  7927. case OP_CALL:
  7928. case OP_RET:
  7929. case OP_BRANCH:
  7930. return false;
  7931. default:
  7932. return true;
  7933. }
  7934. }
  7935. static size_t stacksize(upb_pbdecoder *d, size_t entries) {
  7936. UPB_UNUSED(d);
  7937. return entries * sizeof(upb_pbdecoder_frame);
  7938. }
  7939. static size_t callstacksize(upb_pbdecoder *d, size_t entries) {
  7940. UPB_UNUSED(d);
  7941. #ifdef UPB_USE_JIT_X64
  7942. if (d->method_->is_native_) {
  7943. /* Each native stack frame needs two pointers, plus we need a few frames for
  7944. * the enter/exit trampolines. */
  7945. size_t ret = entries * sizeof(void*) * 2;
  7946. ret += sizeof(void*) * 10;
  7947. return ret;
  7948. }
  7949. #endif
  7950. return entries * sizeof(uint32_t*);
  7951. }
  7952. static bool in_residual_buf(const upb_pbdecoder *d, const char *p);
  7953. /* It's unfortunate that we have to micro-manage the compiler with
  7954. * UPB_FORCEINLINE and UPB_NOINLINE, especially since this tuning is necessarily
  7955. * specific to one hardware configuration. But empirically on a Core i7,
  7956. * performance increases 30-50% with these annotations. Every instance where
  7957. * these appear, gcc 4.2.1 made the wrong decision and degraded performance in
  7958. * benchmarks. */
  7959. static void seterr(upb_pbdecoder *d, const char *msg) {
  7960. upb_status status = UPB_STATUS_INIT;
  7961. upb_status_seterrmsg(&status, msg);
  7962. upb_env_reporterror(d->env, &status);
  7963. }
  7964. void upb_pbdecoder_seterr(upb_pbdecoder *d, const char *msg) {
  7965. seterr(d, msg);
  7966. }
  7967. /* Buffering ******************************************************************/
  7968. /* We operate on one buffer at a time, which is either the user's buffer passed
  7969. * to our "decode" callback or some residual bytes from the previous buffer. */
  7970. /* How many bytes can be safely read from d->ptr without reading past end-of-buf
  7971. * or past the current delimited end. */
  7972. static size_t curbufleft(const upb_pbdecoder *d) {
  7973. UPB_ASSERT(d->data_end >= d->ptr);
  7974. return d->data_end - d->ptr;
  7975. }
  7976. /* How many bytes are available before end-of-buffer. */
  7977. static size_t bufleft(const upb_pbdecoder *d) {
  7978. return d->end - d->ptr;
  7979. }
  7980. /* Overall stream offset of d->ptr. */
  7981. uint64_t offset(const upb_pbdecoder *d) {
  7982. return d->bufstart_ofs + (d->ptr - d->buf);
  7983. }
  7984. /* How many bytes are available before the end of this delimited region. */
  7985. size_t delim_remaining(const upb_pbdecoder *d) {
  7986. return d->top->end_ofs - offset(d);
  7987. }
  7988. /* Advances d->ptr. */
  7989. static void advance(upb_pbdecoder *d, size_t len) {
  7990. UPB_ASSERT(curbufleft(d) >= len);
  7991. d->ptr += len;
  7992. }
  7993. static bool in_buf(const char *p, const char *buf, const char *end) {
  7994. return p >= buf && p <= end;
  7995. }
  7996. static bool in_residual_buf(const upb_pbdecoder *d, const char *p) {
  7997. return in_buf(p, d->residual, d->residual_end);
  7998. }
  7999. /* Calculates the delim_end value, which is affected by both the current buffer
  8000. * and the parsing stack, so must be called whenever either is updated. */
  8001. static void set_delim_end(upb_pbdecoder *d) {
  8002. size_t delim_ofs = d->top->end_ofs - d->bufstart_ofs;
  8003. if (delim_ofs <= (size_t)(d->end - d->buf)) {
  8004. d->delim_end = d->buf + delim_ofs;
  8005. d->data_end = d->delim_end;
  8006. } else {
  8007. d->data_end = d->end;
  8008. d->delim_end = NULL;
  8009. }
  8010. }
  8011. static void switchtobuf(upb_pbdecoder *d, const char *buf, const char *end) {
  8012. d->ptr = buf;
  8013. d->buf = buf;
  8014. d->end = end;
  8015. set_delim_end(d);
  8016. }
  8017. static void advancetobuf(upb_pbdecoder *d, const char *buf, size_t len) {
  8018. UPB_ASSERT(curbufleft(d) == 0);
  8019. d->bufstart_ofs += (d->end - d->buf);
  8020. switchtobuf(d, buf, buf + len);
  8021. }
  8022. static void checkpoint(upb_pbdecoder *d) {
  8023. /* The assertion here is in the interests of efficiency, not correctness.
  8024. * We are trying to ensure that we don't checkpoint() more often than
  8025. * necessary. */
  8026. UPB_ASSERT(d->checkpoint != d->ptr);
  8027. d->checkpoint = d->ptr;
  8028. }
  8029. /* Skips "bytes" bytes in the stream, which may be more than available. If we
  8030. * skip more bytes than are available, we return a long read count to the caller
  8031. * indicating how many bytes can be skipped over before passing actual data
  8032. * again. Skipped bytes can pass a NULL buffer and the decoder guarantees they
  8033. * won't actually be read.
  8034. */
  8035. static int32_t skip(upb_pbdecoder *d, size_t bytes) {
  8036. UPB_ASSERT(!in_residual_buf(d, d->ptr) || d->size_param == 0);
  8037. UPB_ASSERT(d->skip == 0);
  8038. if (bytes > delim_remaining(d)) {
  8039. seterr(d, "Skipped value extended beyond enclosing submessage.");
  8040. return upb_pbdecoder_suspend(d);
  8041. } else if (bufleft(d) >= bytes) {
  8042. /* Skipped data is all in current buffer, and more is still available. */
  8043. advance(d, bytes);
  8044. d->skip = 0;
  8045. return DECODE_OK;
  8046. } else {
  8047. /* Skipped data extends beyond currently available buffers. */
  8048. d->pc = d->last;
  8049. d->skip = bytes - curbufleft(d);
  8050. d->bufstart_ofs += (d->end - d->buf);
  8051. d->residual_end = d->residual;
  8052. switchtobuf(d, d->residual, d->residual_end);
  8053. return d->size_param + d->skip;
  8054. }
  8055. }
  8056. /* Resumes the decoder from an initial state or from a previous suspend. */
  8057. int32_t upb_pbdecoder_resume(upb_pbdecoder *d, void *p, const char *buf,
  8058. size_t size, const upb_bufhandle *handle) {
  8059. UPB_UNUSED(p); /* Useless; just for the benefit of the JIT. */
  8060. /* d->skip and d->residual_end could probably elegantly be represented
  8061. * as a single variable, to more easily represent this invariant. */
  8062. UPB_ASSERT(!(d->skip && d->residual_end > d->residual));
  8063. /* We need to remember the original size_param, so that the value we return
  8064. * is relative to it, even if we do some skipping first. */
  8065. d->size_param = size;
  8066. d->handle = handle;
  8067. /* Have to handle this case specially (ie. not with skip()) because the user
  8068. * is allowed to pass a NULL buffer here, which won't allow us to safely
  8069. * calculate a d->end or use our normal functions like curbufleft(). */
  8070. if (d->skip && d->skip >= size) {
  8071. d->skip -= size;
  8072. d->bufstart_ofs += size;
  8073. buf = &dummy_char;
  8074. size = 0;
  8075. /* We can't just return now, because we might need to execute some ops
  8076. * like CHECKDELIM, which could call some callbacks and pop the stack. */
  8077. }
  8078. /* We need to pretend that this was the actual buffer param, since some of the
  8079. * calculations assume that d->ptr/d->buf is relative to this. */
  8080. d->buf_param = buf;
  8081. if (!buf) {
  8082. /* NULL buf is ok if its entire span is covered by the "skip" above, but
  8083. * by this point we know that "skip" doesn't cover the buffer. */
  8084. seterr(d, "Passed NULL buffer over non-skippable region.");
  8085. return upb_pbdecoder_suspend(d);
  8086. }
  8087. if (d->residual_end > d->residual) {
  8088. /* We have residual bytes from the last buffer. */
  8089. UPB_ASSERT(d->ptr == d->residual);
  8090. } else {
  8091. switchtobuf(d, buf, buf + size);
  8092. }
  8093. d->checkpoint = d->ptr;
  8094. /* Handle skips that don't cover the whole buffer (as above). */
  8095. if (d->skip) {
  8096. size_t skip_bytes = d->skip;
  8097. d->skip = 0;
  8098. CHECK_RETURN(skip(d, skip_bytes));
  8099. checkpoint(d);
  8100. }
  8101. /* If we're inside an unknown group, continue to parse unknown values. */
  8102. if (d->top->groupnum < 0) {
  8103. CHECK_RETURN(upb_pbdecoder_skipunknown(d, -1, 0));
  8104. checkpoint(d);
  8105. }
  8106. return DECODE_OK;
  8107. }
  8108. /* Suspends the decoder at the last checkpoint, without saving any residual
  8109. * bytes. If there are any unconsumed bytes, returns a short byte count. */
  8110. size_t upb_pbdecoder_suspend(upb_pbdecoder *d) {
  8111. d->pc = d->last;
  8112. if (d->checkpoint == d->residual) {
  8113. /* Checkpoint was in residual buf; no user bytes were consumed. */
  8114. d->ptr = d->residual;
  8115. return 0;
  8116. } else {
  8117. size_t ret = d->size_param - (d->end - d->checkpoint);
  8118. UPB_ASSERT(!in_residual_buf(d, d->checkpoint));
  8119. UPB_ASSERT(d->buf == d->buf_param || d->buf == &dummy_char);
  8120. d->bufstart_ofs += (d->checkpoint - d->buf);
  8121. d->residual_end = d->residual;
  8122. switchtobuf(d, d->residual, d->residual_end);
  8123. return ret;
  8124. }
  8125. }
  8126. /* Suspends the decoder at the last checkpoint, and saves any unconsumed
  8127. * bytes in our residual buffer. This is necessary if we need more user
  8128. * bytes to form a complete value, which might not be contiguous in the
  8129. * user's buffers. Always consumes all user bytes. */
  8130. static size_t suspend_save(upb_pbdecoder *d) {
  8131. /* We hit end-of-buffer before we could parse a full value.
  8132. * Save any unconsumed bytes (if any) to the residual buffer. */
  8133. d->pc = d->last;
  8134. if (d->checkpoint == d->residual) {
  8135. /* Checkpoint was in residual buf; append user byte(s) to residual buf. */
  8136. UPB_ASSERT((d->residual_end - d->residual) + d->size_param <=
  8137. sizeof(d->residual));
  8138. if (!in_residual_buf(d, d->ptr)) {
  8139. d->bufstart_ofs -= (d->residual_end - d->residual);
  8140. }
  8141. memcpy(d->residual_end, d->buf_param, d->size_param);
  8142. d->residual_end += d->size_param;
  8143. } else {
  8144. /* Checkpoint was in user buf; old residual bytes not needed. */
  8145. size_t save;
  8146. UPB_ASSERT(!in_residual_buf(d, d->checkpoint));
  8147. d->ptr = d->checkpoint;
  8148. save = curbufleft(d);
  8149. UPB_ASSERT(save <= sizeof(d->residual));
  8150. memcpy(d->residual, d->ptr, save);
  8151. d->residual_end = d->residual + save;
  8152. d->bufstart_ofs = offset(d);
  8153. }
  8154. switchtobuf(d, d->residual, d->residual_end);
  8155. return d->size_param;
  8156. }
  8157. /* Copies the next "bytes" bytes into "buf" and advances the stream.
  8158. * Requires that this many bytes are available in the current buffer. */
  8159. UPB_FORCEINLINE static void consumebytes(upb_pbdecoder *d, void *buf,
  8160. size_t bytes) {
  8161. UPB_ASSERT(bytes <= curbufleft(d));
  8162. memcpy(buf, d->ptr, bytes);
  8163. advance(d, bytes);
  8164. }
  8165. /* Slow path for getting the next "bytes" bytes, regardless of whether they are
  8166. * available in the current buffer or not. Returns a status code as described
  8167. * in decoder.int.h. */
  8168. UPB_NOINLINE static int32_t getbytes_slow(upb_pbdecoder *d, void *buf,
  8169. size_t bytes) {
  8170. const size_t avail = curbufleft(d);
  8171. consumebytes(d, buf, avail);
  8172. bytes -= avail;
  8173. UPB_ASSERT(bytes > 0);
  8174. if (in_residual_buf(d, d->ptr)) {
  8175. advancetobuf(d, d->buf_param, d->size_param);
  8176. }
  8177. if (curbufleft(d) >= bytes) {
  8178. consumebytes(d, (char *)buf + avail, bytes);
  8179. return DECODE_OK;
  8180. } else if (d->data_end == d->delim_end) {
  8181. seterr(d, "Submessage ended in the middle of a value or group");
  8182. return upb_pbdecoder_suspend(d);
  8183. } else {
  8184. return suspend_save(d);
  8185. }
  8186. }
  8187. /* Gets the next "bytes" bytes, regardless of whether they are available in the
  8188. * current buffer or not. Returns a status code as described in decoder.int.h.
  8189. */
  8190. UPB_FORCEINLINE static int32_t getbytes(upb_pbdecoder *d, void *buf,
  8191. size_t bytes) {
  8192. if (curbufleft(d) >= bytes) {
  8193. /* Buffer has enough data to satisfy. */
  8194. consumebytes(d, buf, bytes);
  8195. return DECODE_OK;
  8196. } else {
  8197. return getbytes_slow(d, buf, bytes);
  8198. }
  8199. }
  8200. UPB_NOINLINE static size_t peekbytes_slow(upb_pbdecoder *d, void *buf,
  8201. size_t bytes) {
  8202. size_t ret = curbufleft(d);
  8203. memcpy(buf, d->ptr, ret);
  8204. if (in_residual_buf(d, d->ptr)) {
  8205. size_t copy = UPB_MIN(bytes - ret, d->size_param);
  8206. memcpy((char *)buf + ret, d->buf_param, copy);
  8207. ret += copy;
  8208. }
  8209. return ret;
  8210. }
  8211. UPB_FORCEINLINE static size_t peekbytes(upb_pbdecoder *d, void *buf,
  8212. size_t bytes) {
  8213. if (curbufleft(d) >= bytes) {
  8214. memcpy(buf, d->ptr, bytes);
  8215. return bytes;
  8216. } else {
  8217. return peekbytes_slow(d, buf, bytes);
  8218. }
  8219. }
  8220. /* Decoding of wire types *****************************************************/
  8221. /* Slow path for decoding a varint from the current buffer position.
  8222. * Returns a status code as described in decoder.int.h. */
  8223. UPB_NOINLINE int32_t upb_pbdecoder_decode_varint_slow(upb_pbdecoder *d,
  8224. uint64_t *u64) {
  8225. uint8_t byte = 0x80;
  8226. int bitpos;
  8227. *u64 = 0;
  8228. for(bitpos = 0; bitpos < 70 && (byte & 0x80); bitpos += 7) {
  8229. CHECK_RETURN(getbytes(d, &byte, 1));
  8230. *u64 |= (uint64_t)(byte & 0x7F) << bitpos;
  8231. }
  8232. if(bitpos == 70 && (byte & 0x80)) {
  8233. seterr(d, kUnterminatedVarint);
  8234. return upb_pbdecoder_suspend(d);
  8235. }
  8236. return DECODE_OK;
  8237. }
  8238. /* Decodes a varint from the current buffer position.
  8239. * Returns a status code as described in decoder.int.h. */
  8240. UPB_FORCEINLINE static int32_t decode_varint(upb_pbdecoder *d, uint64_t *u64) {
  8241. if (curbufleft(d) > 0 && !(*d->ptr & 0x80)) {
  8242. *u64 = *d->ptr;
  8243. advance(d, 1);
  8244. return DECODE_OK;
  8245. } else if (curbufleft(d) >= 10) {
  8246. /* Fast case. */
  8247. upb_decoderet r = upb_vdecode_fast(d->ptr);
  8248. if (r.p == NULL) {
  8249. seterr(d, kUnterminatedVarint);
  8250. return upb_pbdecoder_suspend(d);
  8251. }
  8252. advance(d, r.p - d->ptr);
  8253. *u64 = r.val;
  8254. return DECODE_OK;
  8255. } else {
  8256. /* Slow case -- varint spans buffer seam. */
  8257. return upb_pbdecoder_decode_varint_slow(d, u64);
  8258. }
  8259. }
  8260. /* Decodes a 32-bit varint from the current buffer position.
  8261. * Returns a status code as described in decoder.int.h. */
  8262. UPB_FORCEINLINE static int32_t decode_v32(upb_pbdecoder *d, uint32_t *u32) {
  8263. uint64_t u64;
  8264. int32_t ret = decode_varint(d, &u64);
  8265. if (ret >= 0) return ret;
  8266. if (u64 > UINT32_MAX) {
  8267. seterr(d, "Unterminated 32-bit varint");
  8268. /* TODO(haberman) guarantee that this function return is >= 0 somehow,
  8269. * so we know this path will always be treated as error by our caller.
  8270. * Right now the size_t -> int32_t can overflow and produce negative values.
  8271. */
  8272. *u32 = 0;
  8273. return upb_pbdecoder_suspend(d);
  8274. }
  8275. *u32 = u64;
  8276. return DECODE_OK;
  8277. }
  8278. /* Decodes a fixed32 from the current buffer position.
  8279. * Returns a status code as described in decoder.int.h.
  8280. * TODO: proper byte swapping for big-endian machines. */
  8281. UPB_FORCEINLINE static int32_t decode_fixed32(upb_pbdecoder *d, uint32_t *u32) {
  8282. return getbytes(d, u32, 4);
  8283. }
  8284. /* Decodes a fixed64 from the current buffer position.
  8285. * Returns a status code as described in decoder.int.h.
  8286. * TODO: proper byte swapping for big-endian machines. */
  8287. UPB_FORCEINLINE static int32_t decode_fixed64(upb_pbdecoder *d, uint64_t *u64) {
  8288. return getbytes(d, u64, 8);
  8289. }
  8290. /* Non-static versions of the above functions.
  8291. * These are called by the JIT for fallback paths. */
  8292. int32_t upb_pbdecoder_decode_f32(upb_pbdecoder *d, uint32_t *u32) {
  8293. return decode_fixed32(d, u32);
  8294. }
  8295. int32_t upb_pbdecoder_decode_f64(upb_pbdecoder *d, uint64_t *u64) {
  8296. return decode_fixed64(d, u64);
  8297. }
  8298. static double as_double(uint64_t n) { double d; memcpy(&d, &n, 8); return d; }
  8299. static float as_float(uint32_t n) { float f; memcpy(&f, &n, 4); return f; }
  8300. /* Pushes a frame onto the decoder stack. */
  8301. static bool decoder_push(upb_pbdecoder *d, uint64_t end) {
  8302. upb_pbdecoder_frame *fr = d->top;
  8303. if (end > fr->end_ofs) {
  8304. seterr(d, kPbDecoderSubmessageTooLong);
  8305. return false;
  8306. } else if (fr == d->limit) {
  8307. seterr(d, kPbDecoderStackOverflow);
  8308. return false;
  8309. }
  8310. fr++;
  8311. fr->end_ofs = end;
  8312. fr->dispatch = NULL;
  8313. fr->groupnum = 0;
  8314. d->top = fr;
  8315. return true;
  8316. }
  8317. static bool pushtagdelim(upb_pbdecoder *d, uint32_t arg) {
  8318. /* While we expect to see an "end" tag (either ENDGROUP or a non-sequence
  8319. * field number) prior to hitting any enclosing submessage end, pushing our
  8320. * existing delim end prevents us from continuing to parse values from a
  8321. * corrupt proto that doesn't give us an END tag in time. */
  8322. if (!decoder_push(d, d->top->end_ofs))
  8323. return false;
  8324. d->top->groupnum = arg;
  8325. return true;
  8326. }
  8327. /* Pops a frame from the decoder stack. */
  8328. static void decoder_pop(upb_pbdecoder *d) { d->top--; }
  8329. UPB_NOINLINE int32_t upb_pbdecoder_checktag_slow(upb_pbdecoder *d,
  8330. uint64_t expected) {
  8331. uint64_t data = 0;
  8332. size_t bytes = upb_value_size(expected);
  8333. size_t read = peekbytes(d, &data, bytes);
  8334. if (read == bytes && data == expected) {
  8335. /* Advance past matched bytes. */
  8336. int32_t ok = getbytes(d, &data, read);
  8337. UPB_ASSERT(ok < 0);
  8338. return DECODE_OK;
  8339. } else if (read < bytes && memcmp(&data, &expected, read) == 0) {
  8340. return suspend_save(d);
  8341. } else {
  8342. return DECODE_MISMATCH;
  8343. }
  8344. }
  8345. int32_t upb_pbdecoder_skipunknown(upb_pbdecoder *d, int32_t fieldnum,
  8346. uint8_t wire_type) {
  8347. if (fieldnum >= 0)
  8348. goto have_tag;
  8349. while (true) {
  8350. uint32_t tag;
  8351. CHECK_RETURN(decode_v32(d, &tag));
  8352. wire_type = tag & 0x7;
  8353. fieldnum = tag >> 3;
  8354. have_tag:
  8355. if (fieldnum == 0) {
  8356. seterr(d, "Saw invalid field number (0)");
  8357. return upb_pbdecoder_suspend(d);
  8358. }
  8359. /* TODO: deliver to unknown field callback. */
  8360. switch (wire_type) {
  8361. case UPB_WIRE_TYPE_32BIT:
  8362. CHECK_RETURN(skip(d, 4));
  8363. break;
  8364. case UPB_WIRE_TYPE_64BIT:
  8365. CHECK_RETURN(skip(d, 8));
  8366. break;
  8367. case UPB_WIRE_TYPE_VARINT: {
  8368. uint64_t u64;
  8369. CHECK_RETURN(decode_varint(d, &u64));
  8370. break;
  8371. }
  8372. case UPB_WIRE_TYPE_DELIMITED: {
  8373. uint32_t len;
  8374. CHECK_RETURN(decode_v32(d, &len));
  8375. CHECK_RETURN(skip(d, len));
  8376. break;
  8377. }
  8378. case UPB_WIRE_TYPE_START_GROUP:
  8379. CHECK_SUSPEND(pushtagdelim(d, -fieldnum));
  8380. break;
  8381. case UPB_WIRE_TYPE_END_GROUP:
  8382. if (fieldnum == -d->top->groupnum) {
  8383. decoder_pop(d);
  8384. } else if (fieldnum == d->top->groupnum) {
  8385. return DECODE_ENDGROUP;
  8386. } else {
  8387. seterr(d, "Unmatched ENDGROUP tag.");
  8388. return upb_pbdecoder_suspend(d);
  8389. }
  8390. break;
  8391. default:
  8392. seterr(d, "Invalid wire type");
  8393. return upb_pbdecoder_suspend(d);
  8394. }
  8395. if (d->top->groupnum >= 0) {
  8396. return DECODE_OK;
  8397. }
  8398. /* Unknown group -- continue looping over unknown fields. */
  8399. checkpoint(d);
  8400. }
  8401. }
  8402. static void goto_endmsg(upb_pbdecoder *d) {
  8403. upb_value v;
  8404. bool found = upb_inttable_lookup32(d->top->dispatch, DISPATCH_ENDMSG, &v);
  8405. UPB_ASSERT(found);
  8406. d->pc = d->top->base + upb_value_getuint64(v);
  8407. }
  8408. /* Parses a tag and jumps to the corresponding bytecode instruction for this
  8409. * field.
  8410. *
  8411. * If the tag is unknown (or the wire type doesn't match), parses the field as
  8412. * unknown. If the tag is a valid ENDGROUP tag, jumps to the bytecode
  8413. * instruction for the end of message. */
  8414. static int32_t dispatch(upb_pbdecoder *d) {
  8415. upb_inttable *dispatch = d->top->dispatch;
  8416. uint32_t tag;
  8417. uint8_t wire_type;
  8418. uint32_t fieldnum;
  8419. upb_value val;
  8420. int32_t retval;
  8421. /* Decode tag. */
  8422. CHECK_RETURN(decode_v32(d, &tag));
  8423. wire_type = tag & 0x7;
  8424. fieldnum = tag >> 3;
  8425. /* Lookup tag. Because of packed/non-packed compatibility, we have to
  8426. * check the wire type against two possibilities. */
  8427. if (fieldnum != DISPATCH_ENDMSG &&
  8428. upb_inttable_lookup32(dispatch, fieldnum, &val)) {
  8429. uint64_t v = upb_value_getuint64(val);
  8430. if (wire_type == (v & 0xff)) {
  8431. d->pc = d->top->base + (v >> 16);
  8432. return DECODE_OK;
  8433. } else if (wire_type == ((v >> 8) & 0xff)) {
  8434. bool found =
  8435. upb_inttable_lookup(dispatch, fieldnum + UPB_MAX_FIELDNUMBER, &val);
  8436. UPB_ASSERT(found);
  8437. d->pc = d->top->base + upb_value_getuint64(val);
  8438. return DECODE_OK;
  8439. }
  8440. }
  8441. /* We have some unknown fields (or ENDGROUP) to parse. The DISPATCH or TAG
  8442. * bytecode that triggered this is preceded by a CHECKDELIM bytecode which
  8443. * we need to back up to, so that when we're done skipping unknown data we
  8444. * can re-check the delimited end. */
  8445. d->last--; /* Necessary if we get suspended */
  8446. d->pc = d->last;
  8447. UPB_ASSERT(getop(*d->last) == OP_CHECKDELIM);
  8448. /* Unknown field or ENDGROUP. */
  8449. retval = upb_pbdecoder_skipunknown(d, fieldnum, wire_type);
  8450. CHECK_RETURN(retval);
  8451. if (retval == DECODE_ENDGROUP) {
  8452. goto_endmsg(d);
  8453. return DECODE_OK;
  8454. }
  8455. return DECODE_OK;
  8456. }
  8457. /* Callers know that the stack is more than one deep because the opcodes that
  8458. * call this only occur after PUSH operations. */
  8459. upb_pbdecoder_frame *outer_frame(upb_pbdecoder *d) {
  8460. UPB_ASSERT(d->top != d->stack);
  8461. return d->top - 1;
  8462. }
  8463. /* The main decoding loop *****************************************************/
  8464. /* The main decoder VM function. Uses traditional bytecode dispatch loop with a
  8465. * switch() statement. */
  8466. size_t run_decoder_vm(upb_pbdecoder *d, const mgroup *group,
  8467. const upb_bufhandle* handle) {
  8468. #define VMCASE(op, code) \
  8469. case op: { code; if (consumes_input(op)) checkpoint(d); break; }
  8470. #define PRIMITIVE_OP(type, wt, name, convfunc, ctype) \
  8471. VMCASE(OP_PARSE_ ## type, { \
  8472. ctype val; \
  8473. CHECK_RETURN(decode_ ## wt(d, &val)); \
  8474. upb_sink_put ## name(&d->top->sink, arg, (convfunc)(val)); \
  8475. })
  8476. while(1) {
  8477. int32_t instruction;
  8478. opcode op;
  8479. uint32_t arg;
  8480. int32_t longofs;
  8481. d->last = d->pc;
  8482. instruction = *d->pc++;
  8483. op = getop(instruction);
  8484. arg = instruction >> 8;
  8485. longofs = arg;
  8486. UPB_ASSERT(d->ptr != d->residual_end);
  8487. UPB_UNUSED(group);
  8488. #ifdef UPB_DUMP_BYTECODE
  8489. fprintf(stderr, "s_ofs=%d buf_ofs=%d data_rem=%d buf_rem=%d delim_rem=%d "
  8490. "%x %s (%d)\n",
  8491. (int)offset(d),
  8492. (int)(d->ptr - d->buf),
  8493. (int)(d->data_end - d->ptr),
  8494. (int)(d->end - d->ptr),
  8495. (int)((d->top->end_ofs - d->bufstart_ofs) - (d->ptr - d->buf)),
  8496. (int)(d->pc - 1 - group->bytecode),
  8497. upb_pbdecoder_getopname(op),
  8498. arg);
  8499. #endif
  8500. switch (op) {
  8501. /* Technically, we are losing data if we see a 32-bit varint that is not
  8502. * properly sign-extended. We could detect this and error about the data
  8503. * loss, but proto2 does not do this, so we pass. */
  8504. PRIMITIVE_OP(INT32, varint, int32, int32_t, uint64_t)
  8505. PRIMITIVE_OP(INT64, varint, int64, int64_t, uint64_t)
  8506. PRIMITIVE_OP(UINT32, varint, uint32, uint32_t, uint64_t)
  8507. PRIMITIVE_OP(UINT64, varint, uint64, uint64_t, uint64_t)
  8508. PRIMITIVE_OP(FIXED32, fixed32, uint32, uint32_t, uint32_t)
  8509. PRIMITIVE_OP(FIXED64, fixed64, uint64, uint64_t, uint64_t)
  8510. PRIMITIVE_OP(SFIXED32, fixed32, int32, int32_t, uint32_t)
  8511. PRIMITIVE_OP(SFIXED64, fixed64, int64, int64_t, uint64_t)
  8512. PRIMITIVE_OP(BOOL, varint, bool, bool, uint64_t)
  8513. PRIMITIVE_OP(DOUBLE, fixed64, double, as_double, uint64_t)
  8514. PRIMITIVE_OP(FLOAT, fixed32, float, as_float, uint32_t)
  8515. PRIMITIVE_OP(SINT32, varint, int32, upb_zzdec_32, uint64_t)
  8516. PRIMITIVE_OP(SINT64, varint, int64, upb_zzdec_64, uint64_t)
  8517. VMCASE(OP_SETDISPATCH,
  8518. d->top->base = d->pc - 1;
  8519. memcpy(&d->top->dispatch, d->pc, sizeof(void*));
  8520. d->pc += sizeof(void*) / sizeof(uint32_t);
  8521. )
  8522. VMCASE(OP_STARTMSG,
  8523. CHECK_SUSPEND(upb_sink_startmsg(&d->top->sink));
  8524. )
  8525. VMCASE(OP_ENDMSG,
  8526. CHECK_SUSPEND(upb_sink_endmsg(&d->top->sink, d->status));
  8527. )
  8528. VMCASE(OP_STARTSEQ,
  8529. upb_pbdecoder_frame *outer = outer_frame(d);
  8530. CHECK_SUSPEND(upb_sink_startseq(&outer->sink, arg, &d->top->sink));
  8531. )
  8532. VMCASE(OP_ENDSEQ,
  8533. CHECK_SUSPEND(upb_sink_endseq(&d->top->sink, arg));
  8534. )
  8535. VMCASE(OP_STARTSUBMSG,
  8536. upb_pbdecoder_frame *outer = outer_frame(d);
  8537. CHECK_SUSPEND(upb_sink_startsubmsg(&outer->sink, arg, &d->top->sink));
  8538. )
  8539. VMCASE(OP_ENDSUBMSG,
  8540. CHECK_SUSPEND(upb_sink_endsubmsg(&d->top->sink, arg));
  8541. )
  8542. VMCASE(OP_STARTSTR,
  8543. uint32_t len = delim_remaining(d);
  8544. upb_pbdecoder_frame *outer = outer_frame(d);
  8545. CHECK_SUSPEND(upb_sink_startstr(&outer->sink, arg, len, &d->top->sink));
  8546. if (len == 0) {
  8547. d->pc++; /* Skip OP_STRING. */
  8548. }
  8549. )
  8550. VMCASE(OP_STRING,
  8551. uint32_t len = curbufleft(d);
  8552. size_t n = upb_sink_putstring(&d->top->sink, arg, d->ptr, len, handle);
  8553. if (n > len) {
  8554. if (n > delim_remaining(d)) {
  8555. seterr(d, "Tried to skip past end of string.");
  8556. return upb_pbdecoder_suspend(d);
  8557. } else {
  8558. int32_t ret = skip(d, n);
  8559. /* This shouldn't return DECODE_OK, because n > len. */
  8560. UPB_ASSERT(ret >= 0);
  8561. return ret;
  8562. }
  8563. }
  8564. advance(d, n);
  8565. if (n < len || d->delim_end == NULL) {
  8566. /* We aren't finished with this string yet. */
  8567. d->pc--; /* Repeat OP_STRING. */
  8568. if (n > 0) checkpoint(d);
  8569. return upb_pbdecoder_suspend(d);
  8570. }
  8571. )
  8572. VMCASE(OP_ENDSTR,
  8573. CHECK_SUSPEND(upb_sink_endstr(&d->top->sink, arg));
  8574. )
  8575. VMCASE(OP_PUSHTAGDELIM,
  8576. CHECK_SUSPEND(pushtagdelim(d, arg));
  8577. )
  8578. VMCASE(OP_SETBIGGROUPNUM,
  8579. d->top->groupnum = *d->pc++;
  8580. )
  8581. VMCASE(OP_POP,
  8582. UPB_ASSERT(d->top > d->stack);
  8583. decoder_pop(d);
  8584. )
  8585. VMCASE(OP_PUSHLENDELIM,
  8586. uint32_t len;
  8587. CHECK_RETURN(decode_v32(d, &len));
  8588. CHECK_SUSPEND(decoder_push(d, offset(d) + len));
  8589. set_delim_end(d);
  8590. )
  8591. VMCASE(OP_SETDELIM,
  8592. set_delim_end(d);
  8593. )
  8594. VMCASE(OP_CHECKDELIM,
  8595. /* We are guaranteed of this assert because we never allow ourselves to
  8596. * consume bytes beyond data_end, which covers delim_end when non-NULL.
  8597. */
  8598. UPB_ASSERT(!(d->delim_end && d->ptr > d->delim_end));
  8599. if (d->ptr == d->delim_end)
  8600. d->pc += longofs;
  8601. )
  8602. VMCASE(OP_CALL,
  8603. d->callstack[d->call_len++] = d->pc;
  8604. d->pc += longofs;
  8605. )
  8606. VMCASE(OP_RET,
  8607. UPB_ASSERT(d->call_len > 0);
  8608. d->pc = d->callstack[--d->call_len];
  8609. )
  8610. VMCASE(OP_BRANCH,
  8611. d->pc += longofs;
  8612. )
  8613. VMCASE(OP_TAG1,
  8614. uint8_t expected;
  8615. CHECK_SUSPEND(curbufleft(d) > 0);
  8616. expected = (arg >> 8) & 0xff;
  8617. if (*d->ptr == expected) {
  8618. advance(d, 1);
  8619. } else {
  8620. int8_t shortofs;
  8621. badtag:
  8622. shortofs = arg;
  8623. if (shortofs == LABEL_DISPATCH) {
  8624. CHECK_RETURN(dispatch(d));
  8625. } else {
  8626. d->pc += shortofs;
  8627. break; /* Avoid checkpoint(). */
  8628. }
  8629. }
  8630. )
  8631. VMCASE(OP_TAG2,
  8632. uint16_t expected;
  8633. CHECK_SUSPEND(curbufleft(d) > 0);
  8634. expected = (arg >> 8) & 0xffff;
  8635. if (curbufleft(d) >= 2) {
  8636. uint16_t actual;
  8637. memcpy(&actual, d->ptr, 2);
  8638. if (expected == actual) {
  8639. advance(d, 2);
  8640. } else {
  8641. goto badtag;
  8642. }
  8643. } else {
  8644. int32_t result = upb_pbdecoder_checktag_slow(d, expected);
  8645. if (result == DECODE_MISMATCH) goto badtag;
  8646. if (result >= 0) return result;
  8647. }
  8648. )
  8649. VMCASE(OP_TAGN, {
  8650. uint64_t expected;
  8651. int32_t result;
  8652. memcpy(&expected, d->pc, 8);
  8653. d->pc += 2;
  8654. result = upb_pbdecoder_checktag_slow(d, expected);
  8655. if (result == DECODE_MISMATCH) goto badtag;
  8656. if (result >= 0) return result;
  8657. })
  8658. VMCASE(OP_DISPATCH, {
  8659. CHECK_RETURN(dispatch(d));
  8660. })
  8661. VMCASE(OP_HALT, {
  8662. return d->size_param;
  8663. })
  8664. }
  8665. }
  8666. }
  8667. /* BytesHandler handlers ******************************************************/
  8668. void *upb_pbdecoder_startbc(void *closure, const void *pc, size_t size_hint) {
  8669. upb_pbdecoder *d = closure;
  8670. UPB_UNUSED(size_hint);
  8671. d->top->end_ofs = UINT64_MAX;
  8672. d->bufstart_ofs = 0;
  8673. d->call_len = 1;
  8674. d->callstack[0] = &halt;
  8675. d->pc = pc;
  8676. d->skip = 0;
  8677. return d;
  8678. }
  8679. void *upb_pbdecoder_startjit(void *closure, const void *hd, size_t size_hint) {
  8680. upb_pbdecoder *d = closure;
  8681. UPB_UNUSED(hd);
  8682. UPB_UNUSED(size_hint);
  8683. d->top->end_ofs = UINT64_MAX;
  8684. d->bufstart_ofs = 0;
  8685. d->call_len = 0;
  8686. d->skip = 0;
  8687. return d;
  8688. }
  8689. bool upb_pbdecoder_end(void *closure, const void *handler_data) {
  8690. upb_pbdecoder *d = closure;
  8691. const upb_pbdecodermethod *method = handler_data;
  8692. uint64_t end;
  8693. char dummy;
  8694. if (d->residual_end > d->residual) {
  8695. seterr(d, "Unexpected EOF: decoder still has buffered unparsed data");
  8696. return false;
  8697. }
  8698. if (d->skip) {
  8699. seterr(d, "Unexpected EOF inside skipped data");
  8700. return false;
  8701. }
  8702. if (d->top->end_ofs != UINT64_MAX) {
  8703. seterr(d, "Unexpected EOF inside delimited string");
  8704. return false;
  8705. }
  8706. /* The user's end() call indicates that the message ends here. */
  8707. end = offset(d);
  8708. d->top->end_ofs = end;
  8709. #ifdef UPB_USE_JIT_X64
  8710. if (method->is_native_) {
  8711. const mgroup *group = (const mgroup*)method->group;
  8712. if (d->top != d->stack)
  8713. d->stack->end_ofs = 0;
  8714. group->jit_code(closure, method->code_base.ptr, &dummy, 0, NULL);
  8715. } else
  8716. #endif
  8717. {
  8718. const uint32_t *p = d->pc;
  8719. d->stack->end_ofs = end;
  8720. /* Check the previous bytecode, but guard against beginning. */
  8721. if (p != method->code_base.ptr) p--;
  8722. if (getop(*p) == OP_CHECKDELIM) {
  8723. /* Rewind from OP_TAG* to OP_CHECKDELIM. */
  8724. UPB_ASSERT(getop(*d->pc) == OP_TAG1 ||
  8725. getop(*d->pc) == OP_TAG2 ||
  8726. getop(*d->pc) == OP_TAGN ||
  8727. getop(*d->pc) == OP_DISPATCH);
  8728. d->pc = p;
  8729. }
  8730. upb_pbdecoder_decode(closure, handler_data, &dummy, 0, NULL);
  8731. }
  8732. if (d->call_len != 0) {
  8733. seterr(d, "Unexpected EOF inside submessage or group");
  8734. return false;
  8735. }
  8736. return true;
  8737. }
  8738. size_t upb_pbdecoder_decode(void *decoder, const void *group, const char *buf,
  8739. size_t size, const upb_bufhandle *handle) {
  8740. int32_t result = upb_pbdecoder_resume(decoder, NULL, buf, size, handle);
  8741. if (result == DECODE_ENDGROUP) goto_endmsg(decoder);
  8742. CHECK_RETURN(result);
  8743. return run_decoder_vm(decoder, group, handle);
  8744. }
  8745. /* Public API *****************************************************************/
  8746. void upb_pbdecoder_reset(upb_pbdecoder *d) {
  8747. d->top = d->stack;
  8748. d->top->groupnum = 0;
  8749. d->ptr = d->residual;
  8750. d->buf = d->residual;
  8751. d->end = d->residual;
  8752. d->residual_end = d->residual;
  8753. }
  8754. upb_pbdecoder *upb_pbdecoder_create(upb_env *e, const upb_pbdecodermethod *m,
  8755. upb_sink *sink) {
  8756. const size_t default_max_nesting = 64;
  8757. #ifndef NDEBUG
  8758. size_t size_before = upb_env_bytesallocated(e);
  8759. #endif
  8760. upb_pbdecoder *d = upb_env_malloc(e, sizeof(upb_pbdecoder));
  8761. if (!d) return NULL;
  8762. d->method_ = m;
  8763. d->callstack = upb_env_malloc(e, callstacksize(d, default_max_nesting));
  8764. d->stack = upb_env_malloc(e, stacksize(d, default_max_nesting));
  8765. if (!d->stack || !d->callstack) {
  8766. return NULL;
  8767. }
  8768. d->env = e;
  8769. d->limit = d->stack + default_max_nesting - 1;
  8770. d->stack_size = default_max_nesting;
  8771. d->status = NULL;
  8772. upb_pbdecoder_reset(d);
  8773. upb_bytessink_reset(&d->input_, &m->input_handler_, d);
  8774. UPB_ASSERT(sink);
  8775. if (d->method_->dest_handlers_) {
  8776. if (sink->handlers != d->method_->dest_handlers_)
  8777. return NULL;
  8778. }
  8779. upb_sink_reset(&d->top->sink, sink->handlers, sink->closure);
  8780. /* If this fails, increase the value in decoder.h. */
  8781. UPB_ASSERT_DEBUGVAR(upb_env_bytesallocated(e) - size_before <=
  8782. UPB_PB_DECODER_SIZE);
  8783. return d;
  8784. }
  8785. uint64_t upb_pbdecoder_bytesparsed(const upb_pbdecoder *d) {
  8786. return offset(d);
  8787. }
  8788. const upb_pbdecodermethod *upb_pbdecoder_method(const upb_pbdecoder *d) {
  8789. return d->method_;
  8790. }
  8791. upb_bytessink *upb_pbdecoder_input(upb_pbdecoder *d) {
  8792. return &d->input_;
  8793. }
  8794. size_t upb_pbdecoder_maxnesting(const upb_pbdecoder *d) {
  8795. return d->stack_size;
  8796. }
  8797. bool upb_pbdecoder_setmaxnesting(upb_pbdecoder *d, size_t max) {
  8798. UPB_ASSERT(d->top >= d->stack);
  8799. if (max < (size_t)(d->top - d->stack)) {
  8800. /* Can't set a limit smaller than what we are currently at. */
  8801. return false;
  8802. }
  8803. if (max > d->stack_size) {
  8804. /* Need to reallocate stack and callstack to accommodate. */
  8805. size_t old_size = stacksize(d, d->stack_size);
  8806. size_t new_size = stacksize(d, max);
  8807. void *p = upb_env_realloc(d->env, d->stack, old_size, new_size);
  8808. if (!p) {
  8809. return false;
  8810. }
  8811. d->stack = p;
  8812. old_size = callstacksize(d, d->stack_size);
  8813. new_size = callstacksize(d, max);
  8814. p = upb_env_realloc(d->env, d->callstack, old_size, new_size);
  8815. if (!p) {
  8816. return false;
  8817. }
  8818. d->callstack = p;
  8819. d->stack_size = max;
  8820. }
  8821. d->limit = d->stack + max - 1;
  8822. return true;
  8823. }
  8824. /*
  8825. ** upb::Encoder
  8826. **
  8827. ** Since we are implementing pure handlers (ie. without any out-of-band access
  8828. ** to pre-computed lengths), we have to buffer all submessages before we can
  8829. ** emit even their first byte.
  8830. **
  8831. ** Not knowing the size of submessages also means we can't write a perfect
  8832. ** zero-copy implementation, even with buffering. Lengths are stored as
  8833. ** varints, which means that we don't know how many bytes to reserve for the
  8834. ** length until we know what the length is.
  8835. **
  8836. ** This leaves us with three main choices:
  8837. **
  8838. ** 1. buffer all submessage data in a temporary buffer, then copy it exactly
  8839. ** once into the output buffer.
  8840. **
  8841. ** 2. attempt to buffer data directly into the output buffer, estimating how
  8842. ** many bytes each length will take. When our guesses are wrong, use
  8843. ** memmove() to grow or shrink the allotted space.
  8844. **
  8845. ** 3. buffer directly into the output buffer, allocating a max length
  8846. ** ahead-of-time for each submessage length. If we overallocated, we waste
  8847. ** space, but no memcpy() or memmove() is required. This approach requires
  8848. ** defining a maximum size for submessages and rejecting submessages that
  8849. ** exceed that size.
  8850. **
  8851. ** (2) and (3) have the potential to have better performance, but they are more
  8852. ** complicated and subtle to implement:
  8853. **
  8854. ** (3) requires making an arbitrary choice of the maximum message size; it
  8855. ** wastes space when submessages are shorter than this and fails
  8856. ** completely when they are longer. This makes it more finicky and
  8857. ** requires configuration based on the input. It also makes it impossible
  8858. ** to perfectly match the output of reference encoders that always use the
  8859. ** optimal amount of space for each length.
  8860. **
  8861. ** (2) requires guessing the the size upfront, and if multiple lengths are
  8862. ** guessed wrong the minimum required number of memmove() operations may
  8863. ** be complicated to compute correctly. Implemented properly, it may have
  8864. ** a useful amortized or average cost, but more investigation is required
  8865. ** to determine this and what the optimal algorithm is to achieve it.
  8866. **
  8867. ** (1) makes you always pay for exactly one copy, but its implementation is
  8868. ** the simplest and its performance is predictable.
  8869. **
  8870. ** So for now, we implement (1) only. If we wish to optimize later, we should
  8871. ** be able to do it without affecting users.
  8872. **
  8873. ** The strategy is to buffer the segments of data that do *not* depend on
  8874. ** unknown lengths in one buffer, and keep a separate buffer of segment pointers
  8875. ** and lengths. When the top-level submessage ends, we can go beginning to end,
  8876. ** alternating the writing of lengths with memcpy() of the rest of the data.
  8877. ** At the top level though, no buffering is required.
  8878. */
  8879. /* The output buffer is divided into segments; a segment is a string of data
  8880. * that is "ready to go" -- it does not need any varint lengths inserted into
  8881. * the middle. The seams between segments are where varints will be inserted
  8882. * once they are known.
  8883. *
  8884. * We also use the concept of a "run", which is a range of encoded bytes that
  8885. * occur at a single submessage level. Every segment contains one or more runs.
  8886. *
  8887. * A segment can span messages. Consider:
  8888. *
  8889. * .--Submessage lengths---------.
  8890. * | | |
  8891. * | V V
  8892. * V | |--------------- | |-----------------
  8893. * Submessages: | |-----------------------------------------------
  8894. * Top-level msg: ------------------------------------------------------------
  8895. *
  8896. * Segments: ----- ------------------- -----------------
  8897. * Runs: *---- *--------------*--- *----------------
  8898. * (* marks the start)
  8899. *
  8900. * Note that the top-level menssage is not in any segment because it does not
  8901. * have any length preceding it.
  8902. *
  8903. * A segment is only interrupted when another length needs to be inserted. So
  8904. * observe how the second segment spans both the inner submessage and part of
  8905. * the next enclosing message. */
  8906. typedef struct {
  8907. uint32_t msglen; /* The length to varint-encode before this segment. */
  8908. uint32_t seglen; /* Length of the segment. */
  8909. } upb_pb_encoder_segment;
  8910. struct upb_pb_encoder {
  8911. upb_env *env;
  8912. /* Our input and output. */
  8913. upb_sink input_;
  8914. upb_bytessink *output_;
  8915. /* The "subclosure" -- used as the inner closure as part of the bytessink
  8916. * protocol. */
  8917. void *subc;
  8918. /* The output buffer and limit, and our current write position. "buf"
  8919. * initially points to "initbuf", but is dynamically allocated if we need to
  8920. * grow beyond the initial size. */
  8921. char *buf, *ptr, *limit;
  8922. /* The beginning of the current run, or undefined if we are at the top
  8923. * level. */
  8924. char *runbegin;
  8925. /* The list of segments we are accumulating. */
  8926. upb_pb_encoder_segment *segbuf, *segptr, *seglimit;
  8927. /* The stack of enclosing submessages. Each entry in the stack points to the
  8928. * segment where this submessage's length is being accumulated. */
  8929. int *stack, *top, *stacklimit;
  8930. /* Depth of startmsg/endmsg calls. */
  8931. int depth;
  8932. };
  8933. /* low-level buffering ********************************************************/
  8934. /* Low-level functions for interacting with the output buffer. */
  8935. /* TODO(haberman): handle pushback */
  8936. static void putbuf(upb_pb_encoder *e, const char *buf, size_t len) {
  8937. size_t n = upb_bytessink_putbuf(e->output_, e->subc, buf, len, NULL);
  8938. UPB_ASSERT(n == len);
  8939. }
  8940. static upb_pb_encoder_segment *top(upb_pb_encoder *e) {
  8941. return &e->segbuf[*e->top];
  8942. }
  8943. /* Call to ensure that at least "bytes" bytes are available for writing at
  8944. * e->ptr. Returns false if the bytes could not be allocated. */
  8945. static bool reserve(upb_pb_encoder *e, size_t bytes) {
  8946. if ((size_t)(e->limit - e->ptr) < bytes) {
  8947. /* Grow buffer. */
  8948. char *new_buf;
  8949. size_t needed = bytes + (e->ptr - e->buf);
  8950. size_t old_size = e->limit - e->buf;
  8951. size_t new_size = old_size;
  8952. while (new_size < needed) {
  8953. new_size *= 2;
  8954. }
  8955. new_buf = upb_env_realloc(e->env, e->buf, old_size, new_size);
  8956. if (new_buf == NULL) {
  8957. return false;
  8958. }
  8959. e->ptr = new_buf + (e->ptr - e->buf);
  8960. e->runbegin = new_buf + (e->runbegin - e->buf);
  8961. e->limit = new_buf + new_size;
  8962. e->buf = new_buf;
  8963. }
  8964. return true;
  8965. }
  8966. /* Call when "bytes" bytes have been writte at e->ptr. The caller *must* have
  8967. * previously called reserve() with at least this many bytes. */
  8968. static void encoder_advance(upb_pb_encoder *e, size_t bytes) {
  8969. UPB_ASSERT((size_t)(e->limit - e->ptr) >= bytes);
  8970. e->ptr += bytes;
  8971. }
  8972. /* Call when all of the bytes for a handler have been written. Flushes the
  8973. * bytes if possible and necessary, returning false if this failed. */
  8974. static bool commit(upb_pb_encoder *e) {
  8975. if (!e->top) {
  8976. /* We aren't inside a delimited region. Flush our accumulated bytes to
  8977. * the output.
  8978. *
  8979. * TODO(haberman): in the future we may want to delay flushing for
  8980. * efficiency reasons. */
  8981. putbuf(e, e->buf, e->ptr - e->buf);
  8982. e->ptr = e->buf;
  8983. }
  8984. return true;
  8985. }
  8986. /* Writes the given bytes to the buffer, handling reserve/advance. */
  8987. static bool encode_bytes(upb_pb_encoder *e, const void *data, size_t len) {
  8988. if (!reserve(e, len)) {
  8989. return false;
  8990. }
  8991. memcpy(e->ptr, data, len);
  8992. encoder_advance(e, len);
  8993. return true;
  8994. }
  8995. /* Finish the current run by adding the run totals to the segment and message
  8996. * length. */
  8997. static void accumulate(upb_pb_encoder *e) {
  8998. size_t run_len;
  8999. UPB_ASSERT(e->ptr >= e->runbegin);
  9000. run_len = e->ptr - e->runbegin;
  9001. e->segptr->seglen += run_len;
  9002. top(e)->msglen += run_len;
  9003. e->runbegin = e->ptr;
  9004. }
  9005. /* Call to indicate the start of delimited region for which the full length is
  9006. * not yet known. All data will be buffered until the length is known.
  9007. * Delimited regions may be nested; their lengths will all be tracked properly. */
  9008. static bool start_delim(upb_pb_encoder *e) {
  9009. if (e->top) {
  9010. /* We are already buffering, advance to the next segment and push it on the
  9011. * stack. */
  9012. accumulate(e);
  9013. if (++e->top == e->stacklimit) {
  9014. /* TODO(haberman): grow stack? */
  9015. return false;
  9016. }
  9017. if (++e->segptr == e->seglimit) {
  9018. /* Grow segment buffer. */
  9019. size_t old_size =
  9020. (e->seglimit - e->segbuf) * sizeof(upb_pb_encoder_segment);
  9021. size_t new_size = old_size * 2;
  9022. upb_pb_encoder_segment *new_buf =
  9023. upb_env_realloc(e->env, e->segbuf, old_size, new_size);
  9024. if (new_buf == NULL) {
  9025. return false;
  9026. }
  9027. e->segptr = new_buf + (e->segptr - e->segbuf);
  9028. e->seglimit = new_buf + (new_size / sizeof(upb_pb_encoder_segment));
  9029. e->segbuf = new_buf;
  9030. }
  9031. } else {
  9032. /* We were previously at the top level, start buffering. */
  9033. e->segptr = e->segbuf;
  9034. e->top = e->stack;
  9035. e->runbegin = e->ptr;
  9036. }
  9037. *e->top = e->segptr - e->segbuf;
  9038. e->segptr->seglen = 0;
  9039. e->segptr->msglen = 0;
  9040. return true;
  9041. }
  9042. /* Call to indicate the end of a delimited region. We now know the length of
  9043. * the delimited region. If we are not nested inside any other delimited
  9044. * regions, we can now emit all of the buffered data we accumulated. */
  9045. static bool end_delim(upb_pb_encoder *e) {
  9046. size_t msglen;
  9047. accumulate(e);
  9048. msglen = top(e)->msglen;
  9049. if (e->top == e->stack) {
  9050. /* All lengths are now available, emit all buffered data. */
  9051. char buf[UPB_PB_VARINT_MAX_LEN];
  9052. upb_pb_encoder_segment *s;
  9053. const char *ptr = e->buf;
  9054. for (s = e->segbuf; s <= e->segptr; s++) {
  9055. size_t lenbytes = upb_vencode64(s->msglen, buf);
  9056. putbuf(e, buf, lenbytes);
  9057. putbuf(e, ptr, s->seglen);
  9058. ptr += s->seglen;
  9059. }
  9060. e->ptr = e->buf;
  9061. e->top = NULL;
  9062. } else {
  9063. /* Need to keep buffering; propagate length info into enclosing
  9064. * submessages. */
  9065. --e->top;
  9066. top(e)->msglen += msglen + upb_varint_size(msglen);
  9067. }
  9068. return true;
  9069. }
  9070. /* tag_t **********************************************************************/
  9071. /* A precomputed (pre-encoded) tag and length. */
  9072. typedef struct {
  9073. uint8_t bytes;
  9074. char tag[7];
  9075. } tag_t;
  9076. /* Allocates a new tag for this field, and sets it in these handlerattr. */
  9077. static void new_tag(upb_handlers *h, const upb_fielddef *f, upb_wiretype_t wt,
  9078. upb_handlerattr *attr) {
  9079. uint32_t n = upb_fielddef_number(f);
  9080. tag_t *tag = upb_gmalloc(sizeof(tag_t));
  9081. tag->bytes = upb_vencode64((n << 3) | wt, tag->tag);
  9082. upb_handlerattr_init(attr);
  9083. upb_handlerattr_sethandlerdata(attr, tag);
  9084. upb_handlers_addcleanup(h, tag, upb_gfree);
  9085. }
  9086. static bool encode_tag(upb_pb_encoder *e, const tag_t *tag) {
  9087. return encode_bytes(e, tag->tag, tag->bytes);
  9088. }
  9089. /* encoding of wire types *****************************************************/
  9090. static bool encode_fixed64(upb_pb_encoder *e, uint64_t val) {
  9091. /* TODO(haberman): byte-swap for big endian. */
  9092. return encode_bytes(e, &val, sizeof(uint64_t));
  9093. }
  9094. static bool encode_fixed32(upb_pb_encoder *e, uint32_t val) {
  9095. /* TODO(haberman): byte-swap for big endian. */
  9096. return encode_bytes(e, &val, sizeof(uint32_t));
  9097. }
  9098. static bool encode_varint(upb_pb_encoder *e, uint64_t val) {
  9099. if (!reserve(e, UPB_PB_VARINT_MAX_LEN)) {
  9100. return false;
  9101. }
  9102. encoder_advance(e, upb_vencode64(val, e->ptr));
  9103. return true;
  9104. }
  9105. static uint64_t dbl2uint64(double d) {
  9106. uint64_t ret;
  9107. memcpy(&ret, &d, sizeof(uint64_t));
  9108. return ret;
  9109. }
  9110. static uint32_t flt2uint32(float d) {
  9111. uint32_t ret;
  9112. memcpy(&ret, &d, sizeof(uint32_t));
  9113. return ret;
  9114. }
  9115. /* encoding of proto types ****************************************************/
  9116. static bool startmsg(void *c, const void *hd) {
  9117. upb_pb_encoder *e = c;
  9118. UPB_UNUSED(hd);
  9119. if (e->depth++ == 0) {
  9120. upb_bytessink_start(e->output_, 0, &e->subc);
  9121. }
  9122. return true;
  9123. }
  9124. static bool endmsg(void *c, const void *hd, upb_status *status) {
  9125. upb_pb_encoder *e = c;
  9126. UPB_UNUSED(hd);
  9127. UPB_UNUSED(status);
  9128. if (--e->depth == 0) {
  9129. upb_bytessink_end(e->output_);
  9130. }
  9131. return true;
  9132. }
  9133. static void *encode_startdelimfield(void *c, const void *hd) {
  9134. bool ok = encode_tag(c, hd) && commit(c) && start_delim(c);
  9135. return ok ? c : UPB_BREAK;
  9136. }
  9137. static bool encode_enddelimfield(void *c, const void *hd) {
  9138. UPB_UNUSED(hd);
  9139. return end_delim(c);
  9140. }
  9141. static void *encode_startgroup(void *c, const void *hd) {
  9142. return (encode_tag(c, hd) && commit(c)) ? c : UPB_BREAK;
  9143. }
  9144. static bool encode_endgroup(void *c, const void *hd) {
  9145. return encode_tag(c, hd) && commit(c);
  9146. }
  9147. static void *encode_startstr(void *c, const void *hd, size_t size_hint) {
  9148. UPB_UNUSED(size_hint);
  9149. return encode_startdelimfield(c, hd);
  9150. }
  9151. static size_t encode_strbuf(void *c, const void *hd, const char *buf,
  9152. size_t len, const upb_bufhandle *h) {
  9153. UPB_UNUSED(hd);
  9154. UPB_UNUSED(h);
  9155. return encode_bytes(c, buf, len) ? len : 0;
  9156. }
  9157. #define T(type, ctype, convert, encode) \
  9158. static bool encode_scalar_##type(void *e, const void *hd, ctype val) { \
  9159. return encode_tag(e, hd) && encode(e, (convert)(val)) && commit(e); \
  9160. } \
  9161. static bool encode_packed_##type(void *e, const void *hd, ctype val) { \
  9162. UPB_UNUSED(hd); \
  9163. return encode(e, (convert)(val)); \
  9164. }
  9165. T(double, double, dbl2uint64, encode_fixed64)
  9166. T(float, float, flt2uint32, encode_fixed32)
  9167. T(int64, int64_t, uint64_t, encode_varint)
  9168. T(int32, int32_t, int64_t, encode_varint)
  9169. T(fixed64, uint64_t, uint64_t, encode_fixed64)
  9170. T(fixed32, uint32_t, uint32_t, encode_fixed32)
  9171. T(bool, bool, bool, encode_varint)
  9172. T(uint32, uint32_t, uint32_t, encode_varint)
  9173. T(uint64, uint64_t, uint64_t, encode_varint)
  9174. T(enum, int32_t, uint32_t, encode_varint)
  9175. T(sfixed32, int32_t, uint32_t, encode_fixed32)
  9176. T(sfixed64, int64_t, uint64_t, encode_fixed64)
  9177. T(sint32, int32_t, upb_zzenc_32, encode_varint)
  9178. T(sint64, int64_t, upb_zzenc_64, encode_varint)
  9179. #undef T
  9180. /* code to build the handlers *************************************************/
  9181. static void newhandlers_callback(const void *closure, upb_handlers *h) {
  9182. const upb_msgdef *m;
  9183. upb_msg_field_iter i;
  9184. UPB_UNUSED(closure);
  9185. upb_handlers_setstartmsg(h, startmsg, NULL);
  9186. upb_handlers_setendmsg(h, endmsg, NULL);
  9187. m = upb_handlers_msgdef(h);
  9188. for(upb_msg_field_begin(&i, m);
  9189. !upb_msg_field_done(&i);
  9190. upb_msg_field_next(&i)) {
  9191. const upb_fielddef *f = upb_msg_iter_field(&i);
  9192. bool packed = upb_fielddef_isseq(f) && upb_fielddef_isprimitive(f) &&
  9193. upb_fielddef_packed(f);
  9194. upb_handlerattr attr;
  9195. upb_wiretype_t wt =
  9196. packed ? UPB_WIRE_TYPE_DELIMITED
  9197. : upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  9198. /* Pre-encode the tag for this field. */
  9199. new_tag(h, f, wt, &attr);
  9200. if (packed) {
  9201. upb_handlers_setstartseq(h, f, encode_startdelimfield, &attr);
  9202. upb_handlers_setendseq(h, f, encode_enddelimfield, &attr);
  9203. }
  9204. #define T(upper, lower, upbtype) \
  9205. case UPB_DESCRIPTOR_TYPE_##upper: \
  9206. if (packed) { \
  9207. upb_handlers_set##upbtype(h, f, encode_packed_##lower, &attr); \
  9208. } else { \
  9209. upb_handlers_set##upbtype(h, f, encode_scalar_##lower, &attr); \
  9210. } \
  9211. break;
  9212. switch (upb_fielddef_descriptortype(f)) {
  9213. T(DOUBLE, double, double);
  9214. T(FLOAT, float, float);
  9215. T(INT64, int64, int64);
  9216. T(INT32, int32, int32);
  9217. T(FIXED64, fixed64, uint64);
  9218. T(FIXED32, fixed32, uint32);
  9219. T(BOOL, bool, bool);
  9220. T(UINT32, uint32, uint32);
  9221. T(UINT64, uint64, uint64);
  9222. T(ENUM, enum, int32);
  9223. T(SFIXED32, sfixed32, int32);
  9224. T(SFIXED64, sfixed64, int64);
  9225. T(SINT32, sint32, int32);
  9226. T(SINT64, sint64, int64);
  9227. case UPB_DESCRIPTOR_TYPE_STRING:
  9228. case UPB_DESCRIPTOR_TYPE_BYTES:
  9229. upb_handlers_setstartstr(h, f, encode_startstr, &attr);
  9230. upb_handlers_setendstr(h, f, encode_enddelimfield, &attr);
  9231. upb_handlers_setstring(h, f, encode_strbuf, &attr);
  9232. break;
  9233. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  9234. upb_handlers_setstartsubmsg(h, f, encode_startdelimfield, &attr);
  9235. upb_handlers_setendsubmsg(h, f, encode_enddelimfield, &attr);
  9236. break;
  9237. case UPB_DESCRIPTOR_TYPE_GROUP: {
  9238. /* Endgroup takes a different tag (wire_type = END_GROUP). */
  9239. upb_handlerattr attr2;
  9240. new_tag(h, f, UPB_WIRE_TYPE_END_GROUP, &attr2);
  9241. upb_handlers_setstartsubmsg(h, f, encode_startgroup, &attr);
  9242. upb_handlers_setendsubmsg(h, f, encode_endgroup, &attr2);
  9243. upb_handlerattr_uninit(&attr2);
  9244. break;
  9245. }
  9246. }
  9247. #undef T
  9248. upb_handlerattr_uninit(&attr);
  9249. }
  9250. }
  9251. void upb_pb_encoder_reset(upb_pb_encoder *e) {
  9252. e->segptr = NULL;
  9253. e->top = NULL;
  9254. e->depth = 0;
  9255. }
  9256. /* public API *****************************************************************/
  9257. const upb_handlers *upb_pb_encoder_newhandlers(const upb_msgdef *m,
  9258. const void *owner) {
  9259. return upb_handlers_newfrozen(m, owner, newhandlers_callback, NULL);
  9260. }
  9261. upb_pb_encoder *upb_pb_encoder_create(upb_env *env, const upb_handlers *h,
  9262. upb_bytessink *output) {
  9263. const size_t initial_bufsize = 256;
  9264. const size_t initial_segbufsize = 16;
  9265. /* TODO(haberman): make this configurable. */
  9266. const size_t stack_size = 64;
  9267. #ifndef NDEBUG
  9268. const size_t size_before = upb_env_bytesallocated(env);
  9269. #endif
  9270. upb_pb_encoder *e = upb_env_malloc(env, sizeof(upb_pb_encoder));
  9271. if (!e) return NULL;
  9272. e->buf = upb_env_malloc(env, initial_bufsize);
  9273. e->segbuf = upb_env_malloc(env, initial_segbufsize * sizeof(*e->segbuf));
  9274. e->stack = upb_env_malloc(env, stack_size * sizeof(*e->stack));
  9275. if (!e->buf || !e->segbuf || !e->stack) {
  9276. return NULL;
  9277. }
  9278. e->limit = e->buf + initial_bufsize;
  9279. e->seglimit = e->segbuf + initial_segbufsize;
  9280. e->stacklimit = e->stack + stack_size;
  9281. upb_pb_encoder_reset(e);
  9282. upb_sink_reset(&e->input_, h, e);
  9283. e->env = env;
  9284. e->output_ = output;
  9285. e->subc = output->closure;
  9286. e->ptr = e->buf;
  9287. /* If this fails, increase the value in encoder.h. */
  9288. UPB_ASSERT_DEBUGVAR(upb_env_bytesallocated(env) - size_before <=
  9289. UPB_PB_ENCODER_SIZE);
  9290. return e;
  9291. }
  9292. upb_sink *upb_pb_encoder_input(upb_pb_encoder *e) { return &e->input_; }
  9293. upb_filedef **upb_loaddescriptor(const char *buf, size_t n, const void *owner,
  9294. upb_status *status) {
  9295. /* Create handlers. */
  9296. const upb_pbdecodermethod *decoder_m;
  9297. const upb_handlers *reader_h = upb_descreader_newhandlers(&reader_h);
  9298. upb_env env;
  9299. upb_pbdecodermethodopts opts;
  9300. upb_pbdecoder *decoder;
  9301. upb_descreader *reader;
  9302. bool ok;
  9303. size_t i;
  9304. upb_filedef **ret = NULL;
  9305. upb_pbdecodermethodopts_init(&opts, reader_h);
  9306. decoder_m = upb_pbdecodermethod_new(&opts, &decoder_m);
  9307. upb_env_init(&env);
  9308. upb_env_reporterrorsto(&env, status);
  9309. reader = upb_descreader_create(&env, reader_h);
  9310. decoder = upb_pbdecoder_create(&env, decoder_m, upb_descreader_input(reader));
  9311. /* Push input data. */
  9312. ok = upb_bufsrc_putbuf(buf, n, upb_pbdecoder_input(decoder));
  9313. if (!ok) {
  9314. goto cleanup;
  9315. }
  9316. ret = upb_gmalloc(sizeof (*ret) * (upb_descreader_filecount(reader) + 1));
  9317. if (!ret) {
  9318. goto cleanup;
  9319. }
  9320. for (i = 0; i < upb_descreader_filecount(reader); i++) {
  9321. ret[i] = upb_descreader_file(reader, i);
  9322. upb_filedef_ref(ret[i], owner);
  9323. }
  9324. ret[i] = NULL;
  9325. cleanup:
  9326. upb_env_uninit(&env);
  9327. upb_handlers_unref(reader_h, &reader_h);
  9328. upb_pbdecodermethod_unref(decoder_m, &decoder_m);
  9329. return ret;
  9330. }
  9331. /*
  9332. * upb::pb::TextPrinter
  9333. *
  9334. * OPT: This is not optimized at all. It uses printf() which parses the format
  9335. * string every time, and it allocates memory for every put.
  9336. */
  9337. #include <ctype.h>
  9338. #include <float.h>
  9339. #include <inttypes.h>
  9340. #include <stdarg.h>
  9341. #include <stdio.h>
  9342. #include <string.h>
  9343. struct upb_textprinter {
  9344. upb_sink input_;
  9345. upb_bytessink *output_;
  9346. int indent_depth_;
  9347. bool single_line_;
  9348. void *subc;
  9349. };
  9350. #define CHECK(x) if ((x) < 0) goto err;
  9351. static const char *shortname(const char *longname) {
  9352. const char *last = strrchr(longname, '.');
  9353. return last ? last + 1 : longname;
  9354. }
  9355. static int indent(upb_textprinter *p) {
  9356. int i;
  9357. if (!p->single_line_)
  9358. for (i = 0; i < p->indent_depth_; i++)
  9359. upb_bytessink_putbuf(p->output_, p->subc, " ", 2, NULL);
  9360. return 0;
  9361. }
  9362. static int endfield(upb_textprinter *p) {
  9363. const char ch = (p->single_line_ ? ' ' : '\n');
  9364. upb_bytessink_putbuf(p->output_, p->subc, &ch, 1, NULL);
  9365. return 0;
  9366. }
  9367. static int putescaped(upb_textprinter *p, const char *buf, size_t len,
  9368. bool preserve_utf8) {
  9369. /* Based on CEscapeInternal() from Google's protobuf release. */
  9370. char dstbuf[4096], *dst = dstbuf, *dstend = dstbuf + sizeof(dstbuf);
  9371. const char *end = buf + len;
  9372. /* I think hex is prettier and more useful, but proto2 uses octal; should
  9373. * investigate whether it can parse hex also. */
  9374. const bool use_hex = false;
  9375. bool last_hex_escape = false; /* true if last output char was \xNN */
  9376. for (; buf < end; buf++) {
  9377. bool is_hex_escape;
  9378. if (dstend - dst < 4) {
  9379. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  9380. dst = dstbuf;
  9381. }
  9382. is_hex_escape = false;
  9383. switch (*buf) {
  9384. case '\n': *(dst++) = '\\'; *(dst++) = 'n'; break;
  9385. case '\r': *(dst++) = '\\'; *(dst++) = 'r'; break;
  9386. case '\t': *(dst++) = '\\'; *(dst++) = 't'; break;
  9387. case '\"': *(dst++) = '\\'; *(dst++) = '\"'; break;
  9388. case '\'': *(dst++) = '\\'; *(dst++) = '\''; break;
  9389. case '\\': *(dst++) = '\\'; *(dst++) = '\\'; break;
  9390. default:
  9391. /* Note that if we emit \xNN and the buf character after that is a hex
  9392. * digit then that digit must be escaped too to prevent it being
  9393. * interpreted as part of the character code by C. */
  9394. if ((!preserve_utf8 || (uint8_t)*buf < 0x80) &&
  9395. (!isprint(*buf) || (last_hex_escape && isxdigit(*buf)))) {
  9396. sprintf(dst, (use_hex ? "\\x%02x" : "\\%03o"), (uint8_t)*buf);
  9397. is_hex_escape = use_hex;
  9398. dst += 4;
  9399. } else {
  9400. *(dst++) = *buf; break;
  9401. }
  9402. }
  9403. last_hex_escape = is_hex_escape;
  9404. }
  9405. /* Flush remaining data. */
  9406. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  9407. return 0;
  9408. }
  9409. bool putf(upb_textprinter *p, const char *fmt, ...) {
  9410. va_list args;
  9411. va_list args_copy;
  9412. char *str;
  9413. int written;
  9414. int len;
  9415. bool ok;
  9416. va_start(args, fmt);
  9417. /* Run once to get the length of the string. */
  9418. _upb_va_copy(args_copy, args);
  9419. len = _upb_vsnprintf(NULL, 0, fmt, args_copy);
  9420. va_end(args_copy);
  9421. /* + 1 for NULL terminator (vsprintf() requires it even if we don't). */
  9422. str = upb_gmalloc(len + 1);
  9423. if (!str) return false;
  9424. written = vsprintf(str, fmt, args);
  9425. va_end(args);
  9426. UPB_ASSERT(written == len);
  9427. ok = upb_bytessink_putbuf(p->output_, p->subc, str, len, NULL);
  9428. upb_gfree(str);
  9429. return ok;
  9430. }
  9431. /* handlers *******************************************************************/
  9432. static bool textprinter_startmsg(void *c, const void *hd) {
  9433. upb_textprinter *p = c;
  9434. UPB_UNUSED(hd);
  9435. if (p->indent_depth_ == 0) {
  9436. upb_bytessink_start(p->output_, 0, &p->subc);
  9437. }
  9438. return true;
  9439. }
  9440. static bool textprinter_endmsg(void *c, const void *hd, upb_status *s) {
  9441. upb_textprinter *p = c;
  9442. UPB_UNUSED(hd);
  9443. UPB_UNUSED(s);
  9444. if (p->indent_depth_ == 0) {
  9445. upb_bytessink_end(p->output_);
  9446. }
  9447. return true;
  9448. }
  9449. #define TYPE(name, ctype, fmt) \
  9450. static bool textprinter_put ## name(void *closure, const void *handler_data, \
  9451. ctype val) { \
  9452. upb_textprinter *p = closure; \
  9453. const upb_fielddef *f = handler_data; \
  9454. CHECK(indent(p)); \
  9455. putf(p, "%s: " fmt, upb_fielddef_name(f), val); \
  9456. CHECK(endfield(p)); \
  9457. return true; \
  9458. err: \
  9459. return false; \
  9460. }
  9461. static bool textprinter_putbool(void *closure, const void *handler_data,
  9462. bool val) {
  9463. upb_textprinter *p = closure;
  9464. const upb_fielddef *f = handler_data;
  9465. CHECK(indent(p));
  9466. putf(p, "%s: %s", upb_fielddef_name(f), val ? "true" : "false");
  9467. CHECK(endfield(p));
  9468. return true;
  9469. err:
  9470. return false;
  9471. }
  9472. #define STRINGIFY_HELPER(x) #x
  9473. #define STRINGIFY_MACROVAL(x) STRINGIFY_HELPER(x)
  9474. TYPE(int32, int32_t, "%" PRId32)
  9475. TYPE(int64, int64_t, "%" PRId64)
  9476. TYPE(uint32, uint32_t, "%" PRIu32)
  9477. TYPE(uint64, uint64_t, "%" PRIu64)
  9478. TYPE(float, float, "%." STRINGIFY_MACROVAL(FLT_DIG) "g")
  9479. TYPE(double, double, "%." STRINGIFY_MACROVAL(DBL_DIG) "g")
  9480. #undef TYPE
  9481. /* Output a symbolic value from the enum if found, else just print as int32. */
  9482. static bool textprinter_putenum(void *closure, const void *handler_data,
  9483. int32_t val) {
  9484. upb_textprinter *p = closure;
  9485. const upb_fielddef *f = handler_data;
  9486. const upb_enumdef *enum_def = upb_downcast_enumdef(upb_fielddef_subdef(f));
  9487. const char *label = upb_enumdef_iton(enum_def, val);
  9488. if (label) {
  9489. indent(p);
  9490. putf(p, "%s: %s", upb_fielddef_name(f), label);
  9491. endfield(p);
  9492. } else {
  9493. if (!textprinter_putint32(closure, handler_data, val))
  9494. return false;
  9495. }
  9496. return true;
  9497. }
  9498. static void *textprinter_startstr(void *closure, const void *handler_data,
  9499. size_t size_hint) {
  9500. upb_textprinter *p = closure;
  9501. const upb_fielddef *f = handler_data;
  9502. UPB_UNUSED(size_hint);
  9503. indent(p);
  9504. putf(p, "%s: \"", upb_fielddef_name(f));
  9505. return p;
  9506. }
  9507. static bool textprinter_endstr(void *closure, const void *handler_data) {
  9508. upb_textprinter *p = closure;
  9509. UPB_UNUSED(handler_data);
  9510. putf(p, "\"");
  9511. endfield(p);
  9512. return true;
  9513. }
  9514. static size_t textprinter_putstr(void *closure, const void *hd, const char *buf,
  9515. size_t len, const upb_bufhandle *handle) {
  9516. upb_textprinter *p = closure;
  9517. const upb_fielddef *f = hd;
  9518. UPB_UNUSED(handle);
  9519. CHECK(putescaped(p, buf, len, upb_fielddef_type(f) == UPB_TYPE_STRING));
  9520. return len;
  9521. err:
  9522. return 0;
  9523. }
  9524. static void *textprinter_startsubmsg(void *closure, const void *handler_data) {
  9525. upb_textprinter *p = closure;
  9526. const char *name = handler_data;
  9527. CHECK(indent(p));
  9528. putf(p, "%s {%c", name, p->single_line_ ? ' ' : '\n');
  9529. p->indent_depth_++;
  9530. return p;
  9531. err:
  9532. return UPB_BREAK;
  9533. }
  9534. static bool textprinter_endsubmsg(void *closure, const void *handler_data) {
  9535. upb_textprinter *p = closure;
  9536. UPB_UNUSED(handler_data);
  9537. p->indent_depth_--;
  9538. CHECK(indent(p));
  9539. upb_bytessink_putbuf(p->output_, p->subc, "}", 1, NULL);
  9540. CHECK(endfield(p));
  9541. return true;
  9542. err:
  9543. return false;
  9544. }
  9545. static void onmreg(const void *c, upb_handlers *h) {
  9546. const upb_msgdef *m = upb_handlers_msgdef(h);
  9547. upb_msg_field_iter i;
  9548. UPB_UNUSED(c);
  9549. upb_handlers_setstartmsg(h, textprinter_startmsg, NULL);
  9550. upb_handlers_setendmsg(h, textprinter_endmsg, NULL);
  9551. for(upb_msg_field_begin(&i, m);
  9552. !upb_msg_field_done(&i);
  9553. upb_msg_field_next(&i)) {
  9554. upb_fielddef *f = upb_msg_iter_field(&i);
  9555. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  9556. upb_handlerattr_sethandlerdata(&attr, f);
  9557. switch (upb_fielddef_type(f)) {
  9558. case UPB_TYPE_INT32:
  9559. upb_handlers_setint32(h, f, textprinter_putint32, &attr);
  9560. break;
  9561. case UPB_TYPE_INT64:
  9562. upb_handlers_setint64(h, f, textprinter_putint64, &attr);
  9563. break;
  9564. case UPB_TYPE_UINT32:
  9565. upb_handlers_setuint32(h, f, textprinter_putuint32, &attr);
  9566. break;
  9567. case UPB_TYPE_UINT64:
  9568. upb_handlers_setuint64(h, f, textprinter_putuint64, &attr);
  9569. break;
  9570. case UPB_TYPE_FLOAT:
  9571. upb_handlers_setfloat(h, f, textprinter_putfloat, &attr);
  9572. break;
  9573. case UPB_TYPE_DOUBLE:
  9574. upb_handlers_setdouble(h, f, textprinter_putdouble, &attr);
  9575. break;
  9576. case UPB_TYPE_BOOL:
  9577. upb_handlers_setbool(h, f, textprinter_putbool, &attr);
  9578. break;
  9579. case UPB_TYPE_STRING:
  9580. case UPB_TYPE_BYTES:
  9581. upb_handlers_setstartstr(h, f, textprinter_startstr, &attr);
  9582. upb_handlers_setstring(h, f, textprinter_putstr, &attr);
  9583. upb_handlers_setendstr(h, f, textprinter_endstr, &attr);
  9584. break;
  9585. case UPB_TYPE_MESSAGE: {
  9586. const char *name =
  9587. upb_fielddef_istagdelim(f)
  9588. ? shortname(upb_msgdef_fullname(upb_fielddef_msgsubdef(f)))
  9589. : upb_fielddef_name(f);
  9590. upb_handlerattr_sethandlerdata(&attr, name);
  9591. upb_handlers_setstartsubmsg(h, f, textprinter_startsubmsg, &attr);
  9592. upb_handlers_setendsubmsg(h, f, textprinter_endsubmsg, &attr);
  9593. break;
  9594. }
  9595. case UPB_TYPE_ENUM:
  9596. upb_handlers_setint32(h, f, textprinter_putenum, &attr);
  9597. break;
  9598. }
  9599. }
  9600. }
  9601. static void textprinter_reset(upb_textprinter *p, bool single_line) {
  9602. p->single_line_ = single_line;
  9603. p->indent_depth_ = 0;
  9604. }
  9605. /* Public API *****************************************************************/
  9606. upb_textprinter *upb_textprinter_create(upb_env *env, const upb_handlers *h,
  9607. upb_bytessink *output) {
  9608. upb_textprinter *p = upb_env_malloc(env, sizeof(upb_textprinter));
  9609. if (!p) return NULL;
  9610. p->output_ = output;
  9611. upb_sink_reset(&p->input_, h, p);
  9612. textprinter_reset(p, false);
  9613. return p;
  9614. }
  9615. const upb_handlers *upb_textprinter_newhandlers(const upb_msgdef *m,
  9616. const void *owner) {
  9617. return upb_handlers_newfrozen(m, owner, &onmreg, NULL);
  9618. }
  9619. upb_sink *upb_textprinter_input(upb_textprinter *p) { return &p->input_; }
  9620. void upb_textprinter_setsingleline(upb_textprinter *p, bool single_line) {
  9621. p->single_line_ = single_line;
  9622. }
  9623. /* Index is descriptor type. */
  9624. const uint8_t upb_pb_native_wire_types[] = {
  9625. UPB_WIRE_TYPE_END_GROUP, /* ENDGROUP */
  9626. UPB_WIRE_TYPE_64BIT, /* DOUBLE */
  9627. UPB_WIRE_TYPE_32BIT, /* FLOAT */
  9628. UPB_WIRE_TYPE_VARINT, /* INT64 */
  9629. UPB_WIRE_TYPE_VARINT, /* UINT64 */
  9630. UPB_WIRE_TYPE_VARINT, /* INT32 */
  9631. UPB_WIRE_TYPE_64BIT, /* FIXED64 */
  9632. UPB_WIRE_TYPE_32BIT, /* FIXED32 */
  9633. UPB_WIRE_TYPE_VARINT, /* BOOL */
  9634. UPB_WIRE_TYPE_DELIMITED, /* STRING */
  9635. UPB_WIRE_TYPE_START_GROUP, /* GROUP */
  9636. UPB_WIRE_TYPE_DELIMITED, /* MESSAGE */
  9637. UPB_WIRE_TYPE_DELIMITED, /* BYTES */
  9638. UPB_WIRE_TYPE_VARINT, /* UINT32 */
  9639. UPB_WIRE_TYPE_VARINT, /* ENUM */
  9640. UPB_WIRE_TYPE_32BIT, /* SFIXED32 */
  9641. UPB_WIRE_TYPE_64BIT, /* SFIXED64 */
  9642. UPB_WIRE_TYPE_VARINT, /* SINT32 */
  9643. UPB_WIRE_TYPE_VARINT, /* SINT64 */
  9644. };
  9645. /* A basic branch-based decoder, uses 32-bit values to get good performance
  9646. * on 32-bit architectures (but performs well on 64-bits also).
  9647. * This scheme comes from the original Google Protobuf implementation
  9648. * (proto2). */
  9649. upb_decoderet upb_vdecode_max8_branch32(upb_decoderet r) {
  9650. upb_decoderet err = {NULL, 0};
  9651. const char *p = r.p;
  9652. uint32_t low = (uint32_t)r.val;
  9653. uint32_t high = 0;
  9654. uint32_t b;
  9655. b = *(p++); low |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  9656. b = *(p++); low |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  9657. b = *(p++); low |= (b & 0x7fU) << 28;
  9658. high = (b & 0x7fU) >> 4; if (!(b & 0x80)) goto done;
  9659. b = *(p++); high |= (b & 0x7fU) << 3; if (!(b & 0x80)) goto done;
  9660. b = *(p++); high |= (b & 0x7fU) << 10; if (!(b & 0x80)) goto done;
  9661. b = *(p++); high |= (b & 0x7fU) << 17; if (!(b & 0x80)) goto done;
  9662. b = *(p++); high |= (b & 0x7fU) << 24; if (!(b & 0x80)) goto done;
  9663. b = *(p++); high |= (b & 0x7fU) << 31; if (!(b & 0x80)) goto done;
  9664. return err;
  9665. done:
  9666. r.val = ((uint64_t)high << 32) | low;
  9667. r.p = p;
  9668. return r;
  9669. }
  9670. /* Like the previous, but uses 64-bit values. */
  9671. upb_decoderet upb_vdecode_max8_branch64(upb_decoderet r) {
  9672. const char *p = r.p;
  9673. uint64_t val = r.val;
  9674. uint64_t b;
  9675. upb_decoderet err = {NULL, 0};
  9676. b = *(p++); val |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  9677. b = *(p++); val |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  9678. b = *(p++); val |= (b & 0x7fU) << 28; if (!(b & 0x80)) goto done;
  9679. b = *(p++); val |= (b & 0x7fU) << 35; if (!(b & 0x80)) goto done;
  9680. b = *(p++); val |= (b & 0x7fU) << 42; if (!(b & 0x80)) goto done;
  9681. b = *(p++); val |= (b & 0x7fU) << 49; if (!(b & 0x80)) goto done;
  9682. b = *(p++); val |= (b & 0x7fU) << 56; if (!(b & 0x80)) goto done;
  9683. b = *(p++); val |= (b & 0x7fU) << 63; if (!(b & 0x80)) goto done;
  9684. return err;
  9685. done:
  9686. r.val = val;
  9687. r.p = p;
  9688. return r;
  9689. }
  9690. #line 1 "upb/json/parser.rl"
  9691. /*
  9692. ** upb::json::Parser (upb_json_parser)
  9693. **
  9694. ** A parser that uses the Ragel State Machine Compiler to generate
  9695. ** the finite automata.
  9696. **
  9697. ** Ragel only natively handles regular languages, but we can manually
  9698. ** program it a bit to handle context-free languages like JSON, by using
  9699. ** the "fcall" and "fret" constructs.
  9700. **
  9701. ** This parser can handle the basics, but needs several things to be fleshed
  9702. ** out:
  9703. **
  9704. ** - handling of unicode escape sequences (including high surrogate pairs).
  9705. ** - properly check and report errors for unknown fields, stack overflow,
  9706. ** improper array nesting (or lack of nesting).
  9707. ** - handling of base64 sequences with padding characters.
  9708. ** - handling of push-back (non-success returns from sink functions).
  9709. ** - handling of keys/escape-sequences/etc that span input buffers.
  9710. */
  9711. #include <errno.h>
  9712. #include <float.h>
  9713. #include <math.h>
  9714. #include <stdint.h>
  9715. #include <stdlib.h>
  9716. #include <string.h>
  9717. #define UPB_JSON_MAX_DEPTH 64
  9718. typedef struct {
  9719. upb_sink sink;
  9720. /* The current message in which we're parsing, and the field whose value we're
  9721. * expecting next. */
  9722. const upb_msgdef *m;
  9723. const upb_fielddef *f;
  9724. /* The table mapping json name to fielddef for this message. */
  9725. upb_strtable *name_table;
  9726. /* We are in a repeated-field context, ready to emit mapentries as
  9727. * submessages. This flag alters the start-of-object (open-brace) behavior to
  9728. * begin a sequence of mapentry messages rather than a single submessage. */
  9729. bool is_map;
  9730. /* We are in a map-entry message context. This flag is set when parsing the
  9731. * value field of a single map entry and indicates to all value-field parsers
  9732. * (subobjects, strings, numbers, and bools) that the map-entry submessage
  9733. * should end as soon as the value is parsed. */
  9734. bool is_mapentry;
  9735. /* If |is_map| or |is_mapentry| is true, |mapfield| refers to the parent
  9736. * message's map field that we're currently parsing. This differs from |f|
  9737. * because |f| is the field in the *current* message (i.e., the map-entry
  9738. * message itself), not the parent's field that leads to this map. */
  9739. const upb_fielddef *mapfield;
  9740. } upb_jsonparser_frame;
  9741. struct upb_json_parser {
  9742. upb_env *env;
  9743. const upb_json_parsermethod *method;
  9744. upb_bytessink input_;
  9745. /* Stack to track the JSON scopes we are in. */
  9746. upb_jsonparser_frame stack[UPB_JSON_MAX_DEPTH];
  9747. upb_jsonparser_frame *top;
  9748. upb_jsonparser_frame *limit;
  9749. upb_status status;
  9750. /* Ragel's internal parsing stack for the parsing state machine. */
  9751. int current_state;
  9752. int parser_stack[UPB_JSON_MAX_DEPTH];
  9753. int parser_top;
  9754. /* The handle for the current buffer. */
  9755. const upb_bufhandle *handle;
  9756. /* Accumulate buffer. See details in parser.rl. */
  9757. const char *accumulated;
  9758. size_t accumulated_len;
  9759. char *accumulate_buf;
  9760. size_t accumulate_buf_size;
  9761. /* Multi-part text data. See details in parser.rl. */
  9762. int multipart_state;
  9763. upb_selector_t string_selector;
  9764. /* Input capture. See details in parser.rl. */
  9765. const char *capture;
  9766. /* Intermediate result of parsing a unicode escape sequence. */
  9767. uint32_t digit;
  9768. };
  9769. struct upb_json_parsermethod {
  9770. upb_refcounted base;
  9771. upb_byteshandler input_handler_;
  9772. /* Mainly for the purposes of refcounting, so all the fielddefs we point
  9773. * to stay alive. */
  9774. const upb_msgdef *msg;
  9775. /* Keys are upb_msgdef*, values are upb_strtable (json_name -> fielddef) */
  9776. upb_inttable name_tables;
  9777. };
  9778. #define PARSER_CHECK_RETURN(x) if (!(x)) return false
  9779. /* Used to signal that a capture has been suspended. */
  9780. static char suspend_capture;
  9781. static upb_selector_t getsel_for_handlertype(upb_json_parser *p,
  9782. upb_handlertype_t type) {
  9783. upb_selector_t sel;
  9784. bool ok = upb_handlers_getselector(p->top->f, type, &sel);
  9785. UPB_ASSERT(ok);
  9786. return sel;
  9787. }
  9788. static upb_selector_t parser_getsel(upb_json_parser *p) {
  9789. return getsel_for_handlertype(
  9790. p, upb_handlers_getprimitivehandlertype(p->top->f));
  9791. }
  9792. static bool check_stack(upb_json_parser *p) {
  9793. if ((p->top + 1) == p->limit) {
  9794. upb_status_seterrmsg(&p->status, "Nesting too deep");
  9795. upb_env_reporterror(p->env, &p->status);
  9796. return false;
  9797. }
  9798. return true;
  9799. }
  9800. static void set_name_table(upb_json_parser *p, upb_jsonparser_frame *frame) {
  9801. upb_value v;
  9802. bool ok = upb_inttable_lookupptr(&p->method->name_tables, frame->m, &v);
  9803. UPB_ASSERT(ok);
  9804. frame->name_table = upb_value_getptr(v);
  9805. }
  9806. /* There are GCC/Clang built-ins for overflow checking which we could start
  9807. * using if there was any performance benefit to it. */
  9808. static bool checked_add(size_t a, size_t b, size_t *c) {
  9809. if (SIZE_MAX - a < b) return false;
  9810. *c = a + b;
  9811. return true;
  9812. }
  9813. static size_t saturating_multiply(size_t a, size_t b) {
  9814. /* size_t is unsigned, so this is defined behavior even on overflow. */
  9815. size_t ret = a * b;
  9816. if (b != 0 && ret / b != a) {
  9817. ret = SIZE_MAX;
  9818. }
  9819. return ret;
  9820. }
  9821. /* Base64 decoding ************************************************************/
  9822. /* TODO(haberman): make this streaming. */
  9823. static const signed char b64table[] = {
  9824. -1, -1, -1, -1, -1, -1, -1, -1,
  9825. -1, -1, -1, -1, -1, -1, -1, -1,
  9826. -1, -1, -1, -1, -1, -1, -1, -1,
  9827. -1, -1, -1, -1, -1, -1, -1, -1,
  9828. -1, -1, -1, -1, -1, -1, -1, -1,
  9829. -1, -1, -1, 62/*+*/, -1, -1, -1, 63/*/ */,
  9830. 52/*0*/, 53/*1*/, 54/*2*/, 55/*3*/, 56/*4*/, 57/*5*/, 58/*6*/, 59/*7*/,
  9831. 60/*8*/, 61/*9*/, -1, -1, -1, -1, -1, -1,
  9832. -1, 0/*A*/, 1/*B*/, 2/*C*/, 3/*D*/, 4/*E*/, 5/*F*/, 6/*G*/,
  9833. 07/*H*/, 8/*I*/, 9/*J*/, 10/*K*/, 11/*L*/, 12/*M*/, 13/*N*/, 14/*O*/,
  9834. 15/*P*/, 16/*Q*/, 17/*R*/, 18/*S*/, 19/*T*/, 20/*U*/, 21/*V*/, 22/*W*/,
  9835. 23/*X*/, 24/*Y*/, 25/*Z*/, -1, -1, -1, -1, -1,
  9836. -1, 26/*a*/, 27/*b*/, 28/*c*/, 29/*d*/, 30/*e*/, 31/*f*/, 32/*g*/,
  9837. 33/*h*/, 34/*i*/, 35/*j*/, 36/*k*/, 37/*l*/, 38/*m*/, 39/*n*/, 40/*o*/,
  9838. 41/*p*/, 42/*q*/, 43/*r*/, 44/*s*/, 45/*t*/, 46/*u*/, 47/*v*/, 48/*w*/,
  9839. 49/*x*/, 50/*y*/, 51/*z*/, -1, -1, -1, -1, -1,
  9840. -1, -1, -1, -1, -1, -1, -1, -1,
  9841. -1, -1, -1, -1, -1, -1, -1, -1,
  9842. -1, -1, -1, -1, -1, -1, -1, -1,
  9843. -1, -1, -1, -1, -1, -1, -1, -1,
  9844. -1, -1, -1, -1, -1, -1, -1, -1,
  9845. -1, -1, -1, -1, -1, -1, -1, -1,
  9846. -1, -1, -1, -1, -1, -1, -1, -1,
  9847. -1, -1, -1, -1, -1, -1, -1, -1,
  9848. -1, -1, -1, -1, -1, -1, -1, -1,
  9849. -1, -1, -1, -1, -1, -1, -1, -1,
  9850. -1, -1, -1, -1, -1, -1, -1, -1,
  9851. -1, -1, -1, -1, -1, -1, -1, -1,
  9852. -1, -1, -1, -1, -1, -1, -1, -1,
  9853. -1, -1, -1, -1, -1, -1, -1, -1,
  9854. -1, -1, -1, -1, -1, -1, -1, -1,
  9855. -1, -1, -1, -1, -1, -1, -1, -1
  9856. };
  9857. /* Returns the table value sign-extended to 32 bits. Knowing that the upper
  9858. * bits will be 1 for unrecognized characters makes it easier to check for
  9859. * this error condition later (see below). */
  9860. int32_t b64lookup(unsigned char ch) { return b64table[ch]; }
  9861. /* Returns true if the given character is not a valid base64 character or
  9862. * padding. */
  9863. bool nonbase64(unsigned char ch) { return b64lookup(ch) == -1 && ch != '='; }
  9864. static bool base64_push(upb_json_parser *p, upb_selector_t sel, const char *ptr,
  9865. size_t len) {
  9866. const char *limit = ptr + len;
  9867. for (; ptr < limit; ptr += 4) {
  9868. uint32_t val;
  9869. char output[3];
  9870. if (limit - ptr < 4) {
  9871. upb_status_seterrf(&p->status,
  9872. "Base64 input for bytes field not a multiple of 4: %s",
  9873. upb_fielddef_name(p->top->f));
  9874. upb_env_reporterror(p->env, &p->status);
  9875. return false;
  9876. }
  9877. val = b64lookup(ptr[0]) << 18 |
  9878. b64lookup(ptr[1]) << 12 |
  9879. b64lookup(ptr[2]) << 6 |
  9880. b64lookup(ptr[3]);
  9881. /* Test the upper bit; returns true if any of the characters returned -1. */
  9882. if (val & 0x80000000) {
  9883. goto otherchar;
  9884. }
  9885. output[0] = val >> 16;
  9886. output[1] = (val >> 8) & 0xff;
  9887. output[2] = val & 0xff;
  9888. upb_sink_putstring(&p->top->sink, sel, output, 3, NULL);
  9889. }
  9890. return true;
  9891. otherchar:
  9892. if (nonbase64(ptr[0]) || nonbase64(ptr[1]) || nonbase64(ptr[2]) ||
  9893. nonbase64(ptr[3]) ) {
  9894. upb_status_seterrf(&p->status,
  9895. "Non-base64 characters in bytes field: %s",
  9896. upb_fielddef_name(p->top->f));
  9897. upb_env_reporterror(p->env, &p->status);
  9898. return false;
  9899. } if (ptr[2] == '=') {
  9900. uint32_t val;
  9901. char output;
  9902. /* Last group contains only two input bytes, one output byte. */
  9903. if (ptr[0] == '=' || ptr[1] == '=' || ptr[3] != '=') {
  9904. goto badpadding;
  9905. }
  9906. val = b64lookup(ptr[0]) << 18 |
  9907. b64lookup(ptr[1]) << 12;
  9908. UPB_ASSERT(!(val & 0x80000000));
  9909. output = val >> 16;
  9910. upb_sink_putstring(&p->top->sink, sel, &output, 1, NULL);
  9911. return true;
  9912. } else {
  9913. uint32_t val;
  9914. char output[2];
  9915. /* Last group contains only three input bytes, two output bytes. */
  9916. if (ptr[0] == '=' || ptr[1] == '=' || ptr[2] == '=') {
  9917. goto badpadding;
  9918. }
  9919. val = b64lookup(ptr[0]) << 18 |
  9920. b64lookup(ptr[1]) << 12 |
  9921. b64lookup(ptr[2]) << 6;
  9922. output[0] = val >> 16;
  9923. output[1] = (val >> 8) & 0xff;
  9924. upb_sink_putstring(&p->top->sink, sel, output, 2, NULL);
  9925. return true;
  9926. }
  9927. badpadding:
  9928. upb_status_seterrf(&p->status,
  9929. "Incorrect base64 padding for field: %s (%.*s)",
  9930. upb_fielddef_name(p->top->f),
  9931. 4, ptr);
  9932. upb_env_reporterror(p->env, &p->status);
  9933. return false;
  9934. }
  9935. /* Accumulate buffer **********************************************************/
  9936. /* Functionality for accumulating a buffer.
  9937. *
  9938. * Some parts of the parser need an entire value as a contiguous string. For
  9939. * example, to look up a member name in a hash table, or to turn a string into
  9940. * a number, the relevant library routines need the input string to be in
  9941. * contiguous memory, even if the value spanned two or more buffers in the
  9942. * input. These routines handle that.
  9943. *
  9944. * In the common case we can just point to the input buffer to get this
  9945. * contiguous string and avoid any actual copy. So we optimistically begin
  9946. * this way. But there are a few cases where we must instead copy into a
  9947. * separate buffer:
  9948. *
  9949. * 1. The string was not contiguous in the input (it spanned buffers).
  9950. *
  9951. * 2. The string included escape sequences that need to be interpreted to get
  9952. * the true value in a contiguous buffer. */
  9953. static void assert_accumulate_empty(upb_json_parser *p) {
  9954. UPB_ASSERT(p->accumulated == NULL);
  9955. UPB_ASSERT(p->accumulated_len == 0);
  9956. }
  9957. static void accumulate_clear(upb_json_parser *p) {
  9958. p->accumulated = NULL;
  9959. p->accumulated_len = 0;
  9960. }
  9961. /* Used internally by accumulate_append(). */
  9962. static bool accumulate_realloc(upb_json_parser *p, size_t need) {
  9963. void *mem;
  9964. size_t old_size = p->accumulate_buf_size;
  9965. size_t new_size = UPB_MAX(old_size, 128);
  9966. while (new_size < need) {
  9967. new_size = saturating_multiply(new_size, 2);
  9968. }
  9969. mem = upb_env_realloc(p->env, p->accumulate_buf, old_size, new_size);
  9970. if (!mem) {
  9971. upb_status_seterrmsg(&p->status, "Out of memory allocating buffer.");
  9972. upb_env_reporterror(p->env, &p->status);
  9973. return false;
  9974. }
  9975. p->accumulate_buf = mem;
  9976. p->accumulate_buf_size = new_size;
  9977. return true;
  9978. }
  9979. /* Logically appends the given data to the append buffer.
  9980. * If "can_alias" is true, we will try to avoid actually copying, but the buffer
  9981. * must be valid until the next accumulate_append() call (if any). */
  9982. static bool accumulate_append(upb_json_parser *p, const char *buf, size_t len,
  9983. bool can_alias) {
  9984. size_t need;
  9985. if (!p->accumulated && can_alias) {
  9986. p->accumulated = buf;
  9987. p->accumulated_len = len;
  9988. return true;
  9989. }
  9990. if (!checked_add(p->accumulated_len, len, &need)) {
  9991. upb_status_seterrmsg(&p->status, "Integer overflow.");
  9992. upb_env_reporterror(p->env, &p->status);
  9993. return false;
  9994. }
  9995. if (need > p->accumulate_buf_size && !accumulate_realloc(p, need)) {
  9996. return false;
  9997. }
  9998. if (p->accumulated != p->accumulate_buf) {
  9999. memcpy(p->accumulate_buf, p->accumulated, p->accumulated_len);
  10000. p->accumulated = p->accumulate_buf;
  10001. }
  10002. memcpy(p->accumulate_buf + p->accumulated_len, buf, len);
  10003. p->accumulated_len += len;
  10004. return true;
  10005. }
  10006. /* Returns a pointer to the data accumulated since the last accumulate_clear()
  10007. * call, and writes the length to *len. This with point either to the input
  10008. * buffer or a temporary accumulate buffer. */
  10009. static const char *accumulate_getptr(upb_json_parser *p, size_t *len) {
  10010. UPB_ASSERT(p->accumulated);
  10011. *len = p->accumulated_len;
  10012. return p->accumulated;
  10013. }
  10014. /* Mult-part text data ********************************************************/
  10015. /* When we have text data in the input, it can often come in multiple segments.
  10016. * For example, there may be some raw string data followed by an escape
  10017. * sequence. The two segments are processed with different logic. Also buffer
  10018. * seams in the input can cause multiple segments.
  10019. *
  10020. * As we see segments, there are two main cases for how we want to process them:
  10021. *
  10022. * 1. we want to push the captured input directly to string handlers.
  10023. *
  10024. * 2. we need to accumulate all the parts into a contiguous buffer for further
  10025. * processing (field name lookup, string->number conversion, etc). */
  10026. /* This is the set of states for p->multipart_state. */
  10027. enum {
  10028. /* We are not currently processing multipart data. */
  10029. MULTIPART_INACTIVE = 0,
  10030. /* We are processing multipart data by accumulating it into a contiguous
  10031. * buffer. */
  10032. MULTIPART_ACCUMULATE = 1,
  10033. /* We are processing multipart data by pushing each part directly to the
  10034. * current string handlers. */
  10035. MULTIPART_PUSHEAGERLY = 2
  10036. };
  10037. /* Start a multi-part text value where we accumulate the data for processing at
  10038. * the end. */
  10039. static void multipart_startaccum(upb_json_parser *p) {
  10040. assert_accumulate_empty(p);
  10041. UPB_ASSERT(p->multipart_state == MULTIPART_INACTIVE);
  10042. p->multipart_state = MULTIPART_ACCUMULATE;
  10043. }
  10044. /* Start a multi-part text value where we immediately push text data to a string
  10045. * value with the given selector. */
  10046. static void multipart_start(upb_json_parser *p, upb_selector_t sel) {
  10047. assert_accumulate_empty(p);
  10048. UPB_ASSERT(p->multipart_state == MULTIPART_INACTIVE);
  10049. p->multipart_state = MULTIPART_PUSHEAGERLY;
  10050. p->string_selector = sel;
  10051. }
  10052. static bool multipart_text(upb_json_parser *p, const char *buf, size_t len,
  10053. bool can_alias) {
  10054. switch (p->multipart_state) {
  10055. case MULTIPART_INACTIVE:
  10056. upb_status_seterrmsg(
  10057. &p->status, "Internal error: unexpected state MULTIPART_INACTIVE");
  10058. upb_env_reporterror(p->env, &p->status);
  10059. return false;
  10060. case MULTIPART_ACCUMULATE:
  10061. if (!accumulate_append(p, buf, len, can_alias)) {
  10062. return false;
  10063. }
  10064. break;
  10065. case MULTIPART_PUSHEAGERLY: {
  10066. const upb_bufhandle *handle = can_alias ? p->handle : NULL;
  10067. upb_sink_putstring(&p->top->sink, p->string_selector, buf, len, handle);
  10068. break;
  10069. }
  10070. }
  10071. return true;
  10072. }
  10073. /* Note: this invalidates the accumulate buffer! Call only after reading its
  10074. * contents. */
  10075. static void multipart_end(upb_json_parser *p) {
  10076. UPB_ASSERT(p->multipart_state != MULTIPART_INACTIVE);
  10077. p->multipart_state = MULTIPART_INACTIVE;
  10078. accumulate_clear(p);
  10079. }
  10080. /* Input capture **************************************************************/
  10081. /* Functionality for capturing a region of the input as text. Gracefully
  10082. * handles the case where a buffer seam occurs in the middle of the captured
  10083. * region. */
  10084. static void capture_begin(upb_json_parser *p, const char *ptr) {
  10085. UPB_ASSERT(p->multipart_state != MULTIPART_INACTIVE);
  10086. UPB_ASSERT(p->capture == NULL);
  10087. p->capture = ptr;
  10088. }
  10089. static bool capture_end(upb_json_parser *p, const char *ptr) {
  10090. UPB_ASSERT(p->capture);
  10091. if (multipart_text(p, p->capture, ptr - p->capture, true)) {
  10092. p->capture = NULL;
  10093. return true;
  10094. } else {
  10095. return false;
  10096. }
  10097. }
  10098. /* This is called at the end of each input buffer (ie. when we have hit a
  10099. * buffer seam). If we are in the middle of capturing the input, this
  10100. * processes the unprocessed capture region. */
  10101. static void capture_suspend(upb_json_parser *p, const char **ptr) {
  10102. if (!p->capture) return;
  10103. if (multipart_text(p, p->capture, *ptr - p->capture, false)) {
  10104. /* We use this as a signal that we were in the middle of capturing, and
  10105. * that capturing should resume at the beginning of the next buffer.
  10106. *
  10107. * We can't use *ptr here, because we have no guarantee that this pointer
  10108. * will be valid when we resume (if the underlying memory is freed, then
  10109. * using the pointer at all, even to compare to NULL, is likely undefined
  10110. * behavior). */
  10111. p->capture = &suspend_capture;
  10112. } else {
  10113. /* Need to back up the pointer to the beginning of the capture, since
  10114. * we were not able to actually preserve it. */
  10115. *ptr = p->capture;
  10116. }
  10117. }
  10118. static void capture_resume(upb_json_parser *p, const char *ptr) {
  10119. if (p->capture) {
  10120. UPB_ASSERT(p->capture == &suspend_capture);
  10121. p->capture = ptr;
  10122. }
  10123. }
  10124. /* Callbacks from the parser **************************************************/
  10125. /* These are the functions called directly from the parser itself.
  10126. * We define these in the same order as their declarations in the parser. */
  10127. static char escape_char(char in) {
  10128. switch (in) {
  10129. case 'r': return '\r';
  10130. case 't': return '\t';
  10131. case 'n': return '\n';
  10132. case 'f': return '\f';
  10133. case 'b': return '\b';
  10134. case '/': return '/';
  10135. case '"': return '"';
  10136. case '\\': return '\\';
  10137. default:
  10138. UPB_ASSERT(0);
  10139. return 'x';
  10140. }
  10141. }
  10142. static bool escape(upb_json_parser *p, const char *ptr) {
  10143. char ch = escape_char(*ptr);
  10144. return multipart_text(p, &ch, 1, false);
  10145. }
  10146. static void start_hex(upb_json_parser *p) {
  10147. p->digit = 0;
  10148. }
  10149. static void hexdigit(upb_json_parser *p, const char *ptr) {
  10150. char ch = *ptr;
  10151. p->digit <<= 4;
  10152. if (ch >= '0' && ch <= '9') {
  10153. p->digit += (ch - '0');
  10154. } else if (ch >= 'a' && ch <= 'f') {
  10155. p->digit += ((ch - 'a') + 10);
  10156. } else {
  10157. UPB_ASSERT(ch >= 'A' && ch <= 'F');
  10158. p->digit += ((ch - 'A') + 10);
  10159. }
  10160. }
  10161. static bool end_hex(upb_json_parser *p) {
  10162. uint32_t codepoint = p->digit;
  10163. /* emit the codepoint as UTF-8. */
  10164. char utf8[3]; /* support \u0000 -- \uFFFF -- need only three bytes. */
  10165. int length = 0;
  10166. if (codepoint <= 0x7F) {
  10167. utf8[0] = codepoint;
  10168. length = 1;
  10169. } else if (codepoint <= 0x07FF) {
  10170. utf8[1] = (codepoint & 0x3F) | 0x80;
  10171. codepoint >>= 6;
  10172. utf8[0] = (codepoint & 0x1F) | 0xC0;
  10173. length = 2;
  10174. } else /* codepoint <= 0xFFFF */ {
  10175. utf8[2] = (codepoint & 0x3F) | 0x80;
  10176. codepoint >>= 6;
  10177. utf8[1] = (codepoint & 0x3F) | 0x80;
  10178. codepoint >>= 6;
  10179. utf8[0] = (codepoint & 0x0F) | 0xE0;
  10180. length = 3;
  10181. }
  10182. /* TODO(haberman): Handle high surrogates: if codepoint is a high surrogate
  10183. * we have to wait for the next escape to get the full code point). */
  10184. return multipart_text(p, utf8, length, false);
  10185. }
  10186. static void start_text(upb_json_parser *p, const char *ptr) {
  10187. capture_begin(p, ptr);
  10188. }
  10189. static bool end_text(upb_json_parser *p, const char *ptr) {
  10190. return capture_end(p, ptr);
  10191. }
  10192. static void start_number(upb_json_parser *p, const char *ptr) {
  10193. multipart_startaccum(p);
  10194. capture_begin(p, ptr);
  10195. }
  10196. static bool parse_number(upb_json_parser *p, bool is_quoted);
  10197. static bool end_number(upb_json_parser *p, const char *ptr) {
  10198. if (!capture_end(p, ptr)) {
  10199. return false;
  10200. }
  10201. return parse_number(p, false);
  10202. }
  10203. static bool parse_number_from_buffer(upb_json_parser *p, const char *buf,
  10204. const char *bufend, bool is_quoted) {
  10205. size_t len = bufend - buf;
  10206. char *end;
  10207. upb_fieldtype_t type = upb_fielddef_type(p->top->f);
  10208. double val;
  10209. double dummy;
  10210. if (buf[0] == ' ') {
  10211. return false;
  10212. }
  10213. /* For integer types, first try parsing with integer-specific routines.
  10214. * If these succeed, they will be more accurate for int64/uint64 than
  10215. * strtod().
  10216. */
  10217. switch (type) {
  10218. case UPB_TYPE_ENUM:
  10219. case UPB_TYPE_INT32: {
  10220. long val = strtol(buf, &end, 0);
  10221. if (errno == ERANGE || end != bufend) {
  10222. break;
  10223. } else if (val > INT32_MAX || val < INT32_MIN) {
  10224. return false;
  10225. } else {
  10226. upb_sink_putint32(&p->top->sink, parser_getsel(p), val);
  10227. return true;
  10228. }
  10229. }
  10230. case UPB_TYPE_UINT32: {
  10231. unsigned long val = strtoul(buf, &end, 0);
  10232. if (end != bufend) {
  10233. break;
  10234. } else if (val > UINT32_MAX || errno == ERANGE) {
  10235. return false;
  10236. } else {
  10237. upb_sink_putuint32(&p->top->sink, parser_getsel(p), val);
  10238. return true;
  10239. }
  10240. }
  10241. /* XXX: We can't handle [u]int64 properly on 32-bit machines because
  10242. * strto[u]ll isn't in C89. */
  10243. case UPB_TYPE_INT64: {
  10244. long val = strtol(buf, &end, 0);
  10245. if (errno == ERANGE || end != bufend) {
  10246. break;
  10247. } else {
  10248. upb_sink_putint64(&p->top->sink, parser_getsel(p), val);
  10249. return true;
  10250. }
  10251. }
  10252. case UPB_TYPE_UINT64: {
  10253. unsigned long val = strtoul(p->accumulated, &end, 0);
  10254. if (end != bufend) {
  10255. break;
  10256. } else if (errno == ERANGE) {
  10257. return false;
  10258. } else {
  10259. upb_sink_putuint64(&p->top->sink, parser_getsel(p), val);
  10260. return true;
  10261. }
  10262. }
  10263. default:
  10264. break;
  10265. }
  10266. if (type != UPB_TYPE_DOUBLE && type != UPB_TYPE_FLOAT && is_quoted) {
  10267. /* Quoted numbers shouldn't support double forms for integer types. */
  10268. return false;
  10269. }
  10270. if (len == strlen("Infinity") && strcmp(buf, "Infinity") == 0) {
  10271. /* C89 does not have an INFINITY macro. */
  10272. val = 1.0 / 0.0;
  10273. } else if (len == strlen("-Infinity") && strcmp(buf, "-Infinity") == 0) {
  10274. val = -1.0 / 0.0;
  10275. } else {
  10276. val = strtod(buf, &end);
  10277. if (errno == ERANGE || end != bufend) {
  10278. return false;
  10279. }
  10280. }
  10281. switch (type) {
  10282. #define CASE(capitaltype, smalltype, min, max) \
  10283. case UPB_TYPE_ ## capitaltype: { \
  10284. if (modf(val, &dummy) != 0 || val > max || val < min) { \
  10285. return false; \
  10286. } else { \
  10287. upb_sink_put ## smalltype(&p->top->sink, parser_getsel(p), val); \
  10288. return true; \
  10289. } \
  10290. break; \
  10291. }
  10292. case UPB_TYPE_ENUM:
  10293. CASE(INT32, int32, INT32_MIN, INT32_MAX);
  10294. CASE(INT64, int64, INT64_MIN, INT64_MAX);
  10295. CASE(UINT32, uint32, 0, UINT32_MAX);
  10296. CASE(UINT64, uint64, 0, UINT64_MAX);
  10297. #undef CASE
  10298. case UPB_TYPE_DOUBLE:
  10299. upb_sink_putdouble(&p->top->sink, parser_getsel(p), val);
  10300. return true;
  10301. case UPB_TYPE_FLOAT:
  10302. if (false /*val > FLT_MAX || val < -FLT_MAX*/) {
  10303. return false;
  10304. } else {
  10305. upb_sink_putfloat(&p->top->sink, parser_getsel(p), val);
  10306. return true;
  10307. }
  10308. default:
  10309. return false;
  10310. }
  10311. }
  10312. static bool parse_number(upb_json_parser *p, bool is_quoted) {
  10313. size_t len;
  10314. const char *buf;
  10315. const char *bufend;
  10316. /* strtol() and friends unfortunately do not support specifying the length of
  10317. * the input string, so we need to force a copy into a NULL-terminated buffer. */
  10318. if (!multipart_text(p, "\0", 1, false)) {
  10319. return false;
  10320. }
  10321. buf = accumulate_getptr(p, &len);
  10322. bufend = buf + len - 1; /* One for NULL. */
  10323. errno = 0;
  10324. if (parse_number_from_buffer(p, buf, bufend, is_quoted)) {
  10325. multipart_end(p);
  10326. return true;
  10327. } else {
  10328. upb_status_seterrf(&p->status, "error parsing number: %s", buf);
  10329. upb_env_reporterror(p->env, &p->status);
  10330. multipart_end(p);
  10331. return false;
  10332. }
  10333. }
  10334. static bool parser_putbool(upb_json_parser *p, bool val) {
  10335. bool ok;
  10336. if (upb_fielddef_type(p->top->f) != UPB_TYPE_BOOL) {
  10337. upb_status_seterrf(&p->status,
  10338. "Boolean value specified for non-bool field: %s",
  10339. upb_fielddef_name(p->top->f));
  10340. upb_env_reporterror(p->env, &p->status);
  10341. return false;
  10342. }
  10343. ok = upb_sink_putbool(&p->top->sink, parser_getsel(p), val);
  10344. UPB_ASSERT(ok);
  10345. return true;
  10346. }
  10347. static bool start_stringval(upb_json_parser *p) {
  10348. UPB_ASSERT(p->top->f);
  10349. if (upb_fielddef_isstring(p->top->f)) {
  10350. upb_jsonparser_frame *inner;
  10351. upb_selector_t sel;
  10352. if (!check_stack(p)) return false;
  10353. /* Start a new parser frame: parser frames correspond one-to-one with
  10354. * handler frames, and string events occur in a sub-frame. */
  10355. inner = p->top + 1;
  10356. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  10357. upb_sink_startstr(&p->top->sink, sel, 0, &inner->sink);
  10358. inner->m = p->top->m;
  10359. inner->f = p->top->f;
  10360. inner->name_table = NULL;
  10361. inner->is_map = false;
  10362. inner->is_mapentry = false;
  10363. p->top = inner;
  10364. if (upb_fielddef_type(p->top->f) == UPB_TYPE_STRING) {
  10365. /* For STRING fields we push data directly to the handlers as it is
  10366. * parsed. We don't do this yet for BYTES fields, because our base64
  10367. * decoder is not streaming.
  10368. *
  10369. * TODO(haberman): make base64 decoding streaming also. */
  10370. multipart_start(p, getsel_for_handlertype(p, UPB_HANDLER_STRING));
  10371. return true;
  10372. } else {
  10373. multipart_startaccum(p);
  10374. return true;
  10375. }
  10376. } else if (upb_fielddef_type(p->top->f) != UPB_TYPE_BOOL &&
  10377. upb_fielddef_type(p->top->f) != UPB_TYPE_MESSAGE) {
  10378. /* No need to push a frame -- numeric values in quotes remain in the
  10379. * current parser frame. These values must accmulate so we can convert
  10380. * them all at once at the end. */
  10381. multipart_startaccum(p);
  10382. return true;
  10383. } else {
  10384. upb_status_seterrf(&p->status,
  10385. "String specified for bool or submessage field: %s",
  10386. upb_fielddef_name(p->top->f));
  10387. upb_env_reporterror(p->env, &p->status);
  10388. return false;
  10389. }
  10390. }
  10391. static bool end_stringval(upb_json_parser *p) {
  10392. bool ok = true;
  10393. switch (upb_fielddef_type(p->top->f)) {
  10394. case UPB_TYPE_BYTES:
  10395. if (!base64_push(p, getsel_for_handlertype(p, UPB_HANDLER_STRING),
  10396. p->accumulated, p->accumulated_len)) {
  10397. return false;
  10398. }
  10399. /* Fall through. */
  10400. case UPB_TYPE_STRING: {
  10401. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  10402. p->top--;
  10403. upb_sink_endstr(&p->top->sink, sel);
  10404. break;
  10405. }
  10406. case UPB_TYPE_ENUM: {
  10407. /* Resolve enum symbolic name to integer value. */
  10408. const upb_enumdef *enumdef =
  10409. (const upb_enumdef*)upb_fielddef_subdef(p->top->f);
  10410. size_t len;
  10411. const char *buf = accumulate_getptr(p, &len);
  10412. int32_t int_val = 0;
  10413. ok = upb_enumdef_ntoi(enumdef, buf, len, &int_val);
  10414. if (ok) {
  10415. upb_selector_t sel = parser_getsel(p);
  10416. upb_sink_putint32(&p->top->sink, sel, int_val);
  10417. } else {
  10418. upb_status_seterrf(&p->status, "Enum value unknown: '%.*s'", len, buf);
  10419. upb_env_reporterror(p->env, &p->status);
  10420. }
  10421. break;
  10422. }
  10423. case UPB_TYPE_INT32:
  10424. case UPB_TYPE_INT64:
  10425. case UPB_TYPE_UINT32:
  10426. case UPB_TYPE_UINT64:
  10427. case UPB_TYPE_DOUBLE:
  10428. case UPB_TYPE_FLOAT:
  10429. ok = parse_number(p, true);
  10430. break;
  10431. default:
  10432. UPB_ASSERT(false);
  10433. upb_status_seterrmsg(&p->status, "Internal error in JSON decoder");
  10434. upb_env_reporterror(p->env, &p->status);
  10435. ok = false;
  10436. break;
  10437. }
  10438. multipart_end(p);
  10439. return ok;
  10440. }
  10441. static void start_member(upb_json_parser *p) {
  10442. UPB_ASSERT(!p->top->f);
  10443. multipart_startaccum(p);
  10444. }
  10445. /* Helper: invoked during parse_mapentry() to emit the mapentry message's key
  10446. * field based on the current contents of the accumulate buffer. */
  10447. static bool parse_mapentry_key(upb_json_parser *p) {
  10448. size_t len;
  10449. const char *buf = accumulate_getptr(p, &len);
  10450. /* Emit the key field. We do a bit of ad-hoc parsing here because the
  10451. * parser state machine has already decided that this is a string field
  10452. * name, and we are reinterpreting it as some arbitrary key type. In
  10453. * particular, integer and bool keys are quoted, so we need to parse the
  10454. * quoted string contents here. */
  10455. p->top->f = upb_msgdef_itof(p->top->m, UPB_MAPENTRY_KEY);
  10456. if (p->top->f == NULL) {
  10457. upb_status_seterrmsg(&p->status, "mapentry message has no key");
  10458. upb_env_reporterror(p->env, &p->status);
  10459. return false;
  10460. }
  10461. switch (upb_fielddef_type(p->top->f)) {
  10462. case UPB_TYPE_INT32:
  10463. case UPB_TYPE_INT64:
  10464. case UPB_TYPE_UINT32:
  10465. case UPB_TYPE_UINT64:
  10466. /* Invoke end_number. The accum buffer has the number's text already. */
  10467. if (!parse_number(p, true)) {
  10468. return false;
  10469. }
  10470. break;
  10471. case UPB_TYPE_BOOL:
  10472. if (len == 4 && !strncmp(buf, "true", 4)) {
  10473. if (!parser_putbool(p, true)) {
  10474. return false;
  10475. }
  10476. } else if (len == 5 && !strncmp(buf, "false", 5)) {
  10477. if (!parser_putbool(p, false)) {
  10478. return false;
  10479. }
  10480. } else {
  10481. upb_status_seterrmsg(&p->status,
  10482. "Map bool key not 'true' or 'false'");
  10483. upb_env_reporterror(p->env, &p->status);
  10484. return false;
  10485. }
  10486. multipart_end(p);
  10487. break;
  10488. case UPB_TYPE_STRING:
  10489. case UPB_TYPE_BYTES: {
  10490. upb_sink subsink;
  10491. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  10492. upb_sink_startstr(&p->top->sink, sel, len, &subsink);
  10493. sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
  10494. upb_sink_putstring(&subsink, sel, buf, len, NULL);
  10495. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  10496. upb_sink_endstr(&p->top->sink, sel);
  10497. multipart_end(p);
  10498. break;
  10499. }
  10500. default:
  10501. upb_status_seterrmsg(&p->status, "Invalid field type for map key");
  10502. upb_env_reporterror(p->env, &p->status);
  10503. return false;
  10504. }
  10505. return true;
  10506. }
  10507. /* Helper: emit one map entry (as a submessage in the map field sequence). This
  10508. * is invoked from end_membername(), at the end of the map entry's key string,
  10509. * with the map key in the accumulate buffer. It parses the key from that
  10510. * buffer, emits the handler calls to start the mapentry submessage (setting up
  10511. * its subframe in the process), and sets up state in the subframe so that the
  10512. * value parser (invoked next) will emit the mapentry's value field and then
  10513. * end the mapentry message. */
  10514. static bool handle_mapentry(upb_json_parser *p) {
  10515. const upb_fielddef *mapfield;
  10516. const upb_msgdef *mapentrymsg;
  10517. upb_jsonparser_frame *inner;
  10518. upb_selector_t sel;
  10519. /* Map entry: p->top->sink is the seq frame, so we need to start a frame
  10520. * for the mapentry itself, and then set |f| in that frame so that the map
  10521. * value field is parsed, and also set a flag to end the frame after the
  10522. * map-entry value is parsed. */
  10523. if (!check_stack(p)) return false;
  10524. mapfield = p->top->mapfield;
  10525. mapentrymsg = upb_fielddef_msgsubdef(mapfield);
  10526. inner = p->top + 1;
  10527. p->top->f = mapfield;
  10528. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
  10529. upb_sink_startsubmsg(&p->top->sink, sel, &inner->sink);
  10530. inner->m = mapentrymsg;
  10531. inner->name_table = NULL;
  10532. inner->mapfield = mapfield;
  10533. inner->is_map = false;
  10534. /* Don't set this to true *yet* -- we reuse parsing handlers below to push
  10535. * the key field value to the sink, and these handlers will pop the frame
  10536. * if they see is_mapentry (when invoked by the parser state machine, they
  10537. * would have just seen the map-entry value, not key). */
  10538. inner->is_mapentry = false;
  10539. p->top = inner;
  10540. /* send STARTMSG in submsg frame. */
  10541. upb_sink_startmsg(&p->top->sink);
  10542. parse_mapentry_key(p);
  10543. /* Set up the value field to receive the map-entry value. */
  10544. p->top->f = upb_msgdef_itof(p->top->m, UPB_MAPENTRY_VALUE);
  10545. p->top->is_mapentry = true; /* set up to pop frame after value is parsed. */
  10546. p->top->mapfield = mapfield;
  10547. if (p->top->f == NULL) {
  10548. upb_status_seterrmsg(&p->status, "mapentry message has no value");
  10549. upb_env_reporterror(p->env, &p->status);
  10550. return false;
  10551. }
  10552. return true;
  10553. }
  10554. static bool end_membername(upb_json_parser *p) {
  10555. UPB_ASSERT(!p->top->f);
  10556. if (p->top->is_map) {
  10557. return handle_mapentry(p);
  10558. } else {
  10559. size_t len;
  10560. const char *buf = accumulate_getptr(p, &len);
  10561. upb_value v;
  10562. if (upb_strtable_lookup2(p->top->name_table, buf, len, &v)) {
  10563. p->top->f = upb_value_getconstptr(v);
  10564. multipart_end(p);
  10565. return true;
  10566. } else {
  10567. /* TODO(haberman): Ignore unknown fields if requested/configured to do
  10568. * so. */
  10569. upb_status_seterrf(&p->status, "No such field: %.*s\n", (int)len, buf);
  10570. upb_env_reporterror(p->env, &p->status);
  10571. return false;
  10572. }
  10573. }
  10574. }
  10575. static void end_member(upb_json_parser *p) {
  10576. /* If we just parsed a map-entry value, end that frame too. */
  10577. if (p->top->is_mapentry) {
  10578. upb_status s = UPB_STATUS_INIT;
  10579. upb_selector_t sel;
  10580. bool ok;
  10581. const upb_fielddef *mapfield;
  10582. UPB_ASSERT(p->top > p->stack);
  10583. /* send ENDMSG on submsg. */
  10584. upb_sink_endmsg(&p->top->sink, &s);
  10585. mapfield = p->top->mapfield;
  10586. /* send ENDSUBMSG in repeated-field-of-mapentries frame. */
  10587. p->top--;
  10588. ok = upb_handlers_getselector(mapfield, UPB_HANDLER_ENDSUBMSG, &sel);
  10589. UPB_ASSERT(ok);
  10590. upb_sink_endsubmsg(&p->top->sink, sel);
  10591. }
  10592. p->top->f = NULL;
  10593. }
  10594. static bool start_subobject(upb_json_parser *p) {
  10595. UPB_ASSERT(p->top->f);
  10596. if (upb_fielddef_ismap(p->top->f)) {
  10597. upb_jsonparser_frame *inner;
  10598. upb_selector_t sel;
  10599. /* Beginning of a map. Start a new parser frame in a repeated-field
  10600. * context. */
  10601. if (!check_stack(p)) return false;
  10602. inner = p->top + 1;
  10603. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
  10604. upb_sink_startseq(&p->top->sink, sel, &inner->sink);
  10605. inner->m = upb_fielddef_msgsubdef(p->top->f);
  10606. inner->name_table = NULL;
  10607. inner->mapfield = p->top->f;
  10608. inner->f = NULL;
  10609. inner->is_map = true;
  10610. inner->is_mapentry = false;
  10611. p->top = inner;
  10612. return true;
  10613. } else if (upb_fielddef_issubmsg(p->top->f)) {
  10614. upb_jsonparser_frame *inner;
  10615. upb_selector_t sel;
  10616. /* Beginning of a subobject. Start a new parser frame in the submsg
  10617. * context. */
  10618. if (!check_stack(p)) return false;
  10619. inner = p->top + 1;
  10620. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
  10621. upb_sink_startsubmsg(&p->top->sink, sel, &inner->sink);
  10622. inner->m = upb_fielddef_msgsubdef(p->top->f);
  10623. set_name_table(p, inner);
  10624. inner->f = NULL;
  10625. inner->is_map = false;
  10626. inner->is_mapentry = false;
  10627. p->top = inner;
  10628. return true;
  10629. } else {
  10630. upb_status_seterrf(&p->status,
  10631. "Object specified for non-message/group field: %s",
  10632. upb_fielddef_name(p->top->f));
  10633. upb_env_reporterror(p->env, &p->status);
  10634. return false;
  10635. }
  10636. }
  10637. static void end_subobject(upb_json_parser *p) {
  10638. if (p->top->is_map) {
  10639. upb_selector_t sel;
  10640. p->top--;
  10641. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
  10642. upb_sink_endseq(&p->top->sink, sel);
  10643. } else {
  10644. upb_selector_t sel;
  10645. p->top--;
  10646. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSUBMSG);
  10647. upb_sink_endsubmsg(&p->top->sink, sel);
  10648. }
  10649. }
  10650. static bool start_array(upb_json_parser *p) {
  10651. upb_jsonparser_frame *inner;
  10652. upb_selector_t sel;
  10653. UPB_ASSERT(p->top->f);
  10654. if (!upb_fielddef_isseq(p->top->f)) {
  10655. upb_status_seterrf(&p->status,
  10656. "Array specified for non-repeated field: %s",
  10657. upb_fielddef_name(p->top->f));
  10658. upb_env_reporterror(p->env, &p->status);
  10659. return false;
  10660. }
  10661. if (!check_stack(p)) return false;
  10662. inner = p->top + 1;
  10663. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
  10664. upb_sink_startseq(&p->top->sink, sel, &inner->sink);
  10665. inner->m = p->top->m;
  10666. inner->name_table = NULL;
  10667. inner->f = p->top->f;
  10668. inner->is_map = false;
  10669. inner->is_mapentry = false;
  10670. p->top = inner;
  10671. return true;
  10672. }
  10673. static void end_array(upb_json_parser *p) {
  10674. upb_selector_t sel;
  10675. UPB_ASSERT(p->top > p->stack);
  10676. p->top--;
  10677. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
  10678. upb_sink_endseq(&p->top->sink, sel);
  10679. }
  10680. static void start_object(upb_json_parser *p) {
  10681. if (!p->top->is_map) {
  10682. upb_sink_startmsg(&p->top->sink);
  10683. }
  10684. }
  10685. static void end_object(upb_json_parser *p) {
  10686. if (!p->top->is_map) {
  10687. upb_status status;
  10688. upb_status_clear(&status);
  10689. upb_sink_endmsg(&p->top->sink, &status);
  10690. if (!upb_ok(&status)) {
  10691. upb_env_reporterror(p->env, &status);
  10692. }
  10693. }
  10694. }
  10695. #define CHECK_RETURN_TOP(x) if (!(x)) goto error
  10696. /* The actual parser **********************************************************/
  10697. /* What follows is the Ragel parser itself. The language is specified in Ragel
  10698. * and the actions call our C functions above.
  10699. *
  10700. * Ragel has an extensive set of functionality, and we use only a small part of
  10701. * it. There are many action types but we only use a few:
  10702. *
  10703. * ">" -- transition into a machine
  10704. * "%" -- transition out of a machine
  10705. * "@" -- transition into a final state of a machine.
  10706. *
  10707. * "@" transitions are tricky because a machine can transition into a final
  10708. * state repeatedly. But in some cases we know this can't happen, for example
  10709. * a string which is delimited by a final '"' can only transition into its
  10710. * final state once, when the closing '"' is seen. */
  10711. #line 1306 "upb/json/parser.rl"
  10712. #line 1218 "upb/json/parser.c"
  10713. static const char _json_actions[] = {
  10714. 0, 1, 0, 1, 2, 1, 3, 1,
  10715. 5, 1, 6, 1, 7, 1, 8, 1,
  10716. 10, 1, 12, 1, 13, 1, 14, 1,
  10717. 15, 1, 16, 1, 17, 1, 21, 1,
  10718. 25, 1, 27, 2, 3, 8, 2, 4,
  10719. 5, 2, 6, 2, 2, 6, 8, 2,
  10720. 11, 9, 2, 13, 15, 2, 14, 15,
  10721. 2, 18, 1, 2, 19, 27, 2, 20,
  10722. 9, 2, 22, 27, 2, 23, 27, 2,
  10723. 24, 27, 2, 26, 27, 3, 14, 11,
  10724. 9
  10725. };
  10726. static const unsigned char _json_key_offsets[] = {
  10727. 0, 0, 4, 9, 14, 15, 19, 24,
  10728. 29, 34, 38, 42, 45, 48, 50, 54,
  10729. 58, 60, 62, 67, 69, 71, 80, 86,
  10730. 92, 98, 104, 106, 115, 116, 116, 116,
  10731. 121, 126, 131, 132, 133, 134, 135, 135,
  10732. 136, 137, 138, 138, 139, 140, 141, 141,
  10733. 146, 151, 152, 156, 161, 166, 171, 175,
  10734. 175, 178, 178, 178
  10735. };
  10736. static const char _json_trans_keys[] = {
  10737. 32, 123, 9, 13, 32, 34, 125, 9,
  10738. 13, 32, 34, 125, 9, 13, 34, 32,
  10739. 58, 9, 13, 32, 93, 125, 9, 13,
  10740. 32, 44, 125, 9, 13, 32, 44, 125,
  10741. 9, 13, 32, 34, 9, 13, 45, 48,
  10742. 49, 57, 48, 49, 57, 46, 69, 101,
  10743. 48, 57, 69, 101, 48, 57, 43, 45,
  10744. 48, 57, 48, 57, 48, 57, 46, 69,
  10745. 101, 48, 57, 34, 92, 34, 92, 34,
  10746. 47, 92, 98, 102, 110, 114, 116, 117,
  10747. 48, 57, 65, 70, 97, 102, 48, 57,
  10748. 65, 70, 97, 102, 48, 57, 65, 70,
  10749. 97, 102, 48, 57, 65, 70, 97, 102,
  10750. 34, 92, 34, 45, 91, 102, 110, 116,
  10751. 123, 48, 57, 34, 32, 93, 125, 9,
  10752. 13, 32, 44, 93, 9, 13, 32, 93,
  10753. 125, 9, 13, 97, 108, 115, 101, 117,
  10754. 108, 108, 114, 117, 101, 32, 34, 125,
  10755. 9, 13, 32, 34, 125, 9, 13, 34,
  10756. 32, 58, 9, 13, 32, 93, 125, 9,
  10757. 13, 32, 44, 125, 9, 13, 32, 44,
  10758. 125, 9, 13, 32, 34, 9, 13, 32,
  10759. 9, 13, 0
  10760. };
  10761. static const char _json_single_lengths[] = {
  10762. 0, 2, 3, 3, 1, 2, 3, 3,
  10763. 3, 2, 2, 1, 3, 0, 2, 2,
  10764. 0, 0, 3, 2, 2, 9, 0, 0,
  10765. 0, 0, 2, 7, 1, 0, 0, 3,
  10766. 3, 3, 1, 1, 1, 1, 0, 1,
  10767. 1, 1, 0, 1, 1, 1, 0, 3,
  10768. 3, 1, 2, 3, 3, 3, 2, 0,
  10769. 1, 0, 0, 0
  10770. };
  10771. static const char _json_range_lengths[] = {
  10772. 0, 1, 1, 1, 0, 1, 1, 1,
  10773. 1, 1, 1, 1, 0, 1, 1, 1,
  10774. 1, 1, 1, 0, 0, 0, 3, 3,
  10775. 3, 3, 0, 1, 0, 0, 0, 1,
  10776. 1, 1, 0, 0, 0, 0, 0, 0,
  10777. 0, 0, 0, 0, 0, 0, 0, 1,
  10778. 1, 0, 1, 1, 1, 1, 1, 0,
  10779. 1, 0, 0, 0
  10780. };
  10781. static const short _json_index_offsets[] = {
  10782. 0, 0, 4, 9, 14, 16, 20, 25,
  10783. 30, 35, 39, 43, 46, 50, 52, 56,
  10784. 60, 62, 64, 69, 72, 75, 85, 89,
  10785. 93, 97, 101, 104, 113, 115, 116, 117,
  10786. 122, 127, 132, 134, 136, 138, 140, 141,
  10787. 143, 145, 147, 148, 150, 152, 154, 155,
  10788. 160, 165, 167, 171, 176, 181, 186, 190,
  10789. 191, 194, 195, 196
  10790. };
  10791. static const char _json_indicies[] = {
  10792. 0, 2, 0, 1, 3, 4, 5, 3,
  10793. 1, 6, 7, 8, 6, 1, 9, 1,
  10794. 10, 11, 10, 1, 11, 1, 1, 11,
  10795. 12, 13, 14, 15, 13, 1, 16, 17,
  10796. 8, 16, 1, 17, 7, 17, 1, 18,
  10797. 19, 20, 1, 19, 20, 1, 22, 23,
  10798. 23, 21, 24, 1, 23, 23, 24, 21,
  10799. 25, 25, 26, 1, 26, 1, 26, 21,
  10800. 22, 23, 23, 20, 21, 28, 29, 27,
  10801. 31, 32, 30, 33, 33, 33, 33, 33,
  10802. 33, 33, 33, 34, 1, 35, 35, 35,
  10803. 1, 36, 36, 36, 1, 37, 37, 37,
  10804. 1, 38, 38, 38, 1, 40, 41, 39,
  10805. 42, 43, 44, 45, 46, 47, 48, 43,
  10806. 1, 49, 1, 50, 51, 53, 54, 1,
  10807. 53, 52, 55, 56, 54, 55, 1, 56,
  10808. 1, 1, 56, 52, 57, 1, 58, 1,
  10809. 59, 1, 60, 1, 61, 62, 1, 63,
  10810. 1, 64, 1, 65, 66, 1, 67, 1,
  10811. 68, 1, 69, 70, 71, 72, 70, 1,
  10812. 73, 74, 75, 73, 1, 76, 1, 77,
  10813. 78, 77, 1, 78, 1, 1, 78, 79,
  10814. 80, 81, 82, 80, 1, 83, 84, 75,
  10815. 83, 1, 84, 74, 84, 1, 85, 86,
  10816. 86, 1, 1, 1, 1, 0
  10817. };
  10818. static const char _json_trans_targs[] = {
  10819. 1, 0, 2, 3, 4, 56, 3, 4,
  10820. 56, 5, 5, 6, 7, 8, 9, 56,
  10821. 8, 9, 11, 12, 18, 57, 13, 15,
  10822. 14, 16, 17, 20, 58, 21, 20, 58,
  10823. 21, 19, 22, 23, 24, 25, 26, 20,
  10824. 58, 21, 28, 30, 31, 34, 39, 43,
  10825. 47, 29, 59, 59, 32, 31, 29, 32,
  10826. 33, 35, 36, 37, 38, 59, 40, 41,
  10827. 42, 59, 44, 45, 46, 59, 48, 49,
  10828. 55, 48, 49, 55, 50, 50, 51, 52,
  10829. 53, 54, 55, 53, 54, 59, 56
  10830. };
  10831. static const char _json_trans_actions[] = {
  10832. 0, 0, 0, 21, 77, 53, 0, 47,
  10833. 23, 17, 0, 0, 15, 19, 19, 50,
  10834. 0, 0, 0, 0, 0, 1, 0, 0,
  10835. 0, 0, 0, 3, 13, 0, 0, 35,
  10836. 5, 11, 0, 38, 7, 7, 7, 41,
  10837. 44, 9, 62, 56, 25, 0, 0, 0,
  10838. 31, 29, 33, 59, 15, 0, 27, 0,
  10839. 0, 0, 0, 0, 0, 68, 0, 0,
  10840. 0, 71, 0, 0, 0, 65, 21, 77,
  10841. 53, 0, 47, 23, 17, 0, 0, 15,
  10842. 19, 19, 50, 0, 0, 74, 0
  10843. };
  10844. static const int json_start = 1;
  10845. static const int json_en_number_machine = 10;
  10846. static const int json_en_string_machine = 19;
  10847. static const int json_en_value_machine = 27;
  10848. static const int json_en_main = 1;
  10849. #line 1309 "upb/json/parser.rl"
  10850. size_t parse(void *closure, const void *hd, const char *buf, size_t size,
  10851. const upb_bufhandle *handle) {
  10852. upb_json_parser *parser = closure;
  10853. /* Variables used by Ragel's generated code. */
  10854. int cs = parser->current_state;
  10855. int *stack = parser->parser_stack;
  10856. int top = parser->parser_top;
  10857. const char *p = buf;
  10858. const char *pe = buf + size;
  10859. parser->handle = handle;
  10860. UPB_UNUSED(hd);
  10861. UPB_UNUSED(handle);
  10862. capture_resume(parser, buf);
  10863. #line 1389 "upb/json/parser.c"
  10864. {
  10865. int _klen;
  10866. unsigned int _trans;
  10867. const char *_acts;
  10868. unsigned int _nacts;
  10869. const char *_keys;
  10870. if ( p == pe )
  10871. goto _test_eof;
  10872. if ( cs == 0 )
  10873. goto _out;
  10874. _resume:
  10875. _keys = _json_trans_keys + _json_key_offsets[cs];
  10876. _trans = _json_index_offsets[cs];
  10877. _klen = _json_single_lengths[cs];
  10878. if ( _klen > 0 ) {
  10879. const char *_lower = _keys;
  10880. const char *_mid;
  10881. const char *_upper = _keys + _klen - 1;
  10882. while (1) {
  10883. if ( _upper < _lower )
  10884. break;
  10885. _mid = _lower + ((_upper-_lower) >> 1);
  10886. if ( (*p) < *_mid )
  10887. _upper = _mid - 1;
  10888. else if ( (*p) > *_mid )
  10889. _lower = _mid + 1;
  10890. else {
  10891. _trans += (unsigned int)(_mid - _keys);
  10892. goto _match;
  10893. }
  10894. }
  10895. _keys += _klen;
  10896. _trans += _klen;
  10897. }
  10898. _klen = _json_range_lengths[cs];
  10899. if ( _klen > 0 ) {
  10900. const char *_lower = _keys;
  10901. const char *_mid;
  10902. const char *_upper = _keys + (_klen<<1) - 2;
  10903. while (1) {
  10904. if ( _upper < _lower )
  10905. break;
  10906. _mid = _lower + (((_upper-_lower) >> 1) & ~1);
  10907. if ( (*p) < _mid[0] )
  10908. _upper = _mid - 2;
  10909. else if ( (*p) > _mid[1] )
  10910. _lower = _mid + 2;
  10911. else {
  10912. _trans += (unsigned int)((_mid - _keys)>>1);
  10913. goto _match;
  10914. }
  10915. }
  10916. _trans += _klen;
  10917. }
  10918. _match:
  10919. _trans = _json_indicies[_trans];
  10920. cs = _json_trans_targs[_trans];
  10921. if ( _json_trans_actions[_trans] == 0 )
  10922. goto _again;
  10923. _acts = _json_actions + _json_trans_actions[_trans];
  10924. _nacts = (unsigned int) *_acts++;
  10925. while ( _nacts-- > 0 )
  10926. {
  10927. switch ( *_acts++ )
  10928. {
  10929. case 0:
  10930. #line 1221 "upb/json/parser.rl"
  10931. { p--; {cs = stack[--top]; goto _again;} }
  10932. break;
  10933. case 1:
  10934. #line 1222 "upb/json/parser.rl"
  10935. { p--; {stack[top++] = cs; cs = 10; goto _again;} }
  10936. break;
  10937. case 2:
  10938. #line 1226 "upb/json/parser.rl"
  10939. { start_text(parser, p); }
  10940. break;
  10941. case 3:
  10942. #line 1227 "upb/json/parser.rl"
  10943. { CHECK_RETURN_TOP(end_text(parser, p)); }
  10944. break;
  10945. case 4:
  10946. #line 1233 "upb/json/parser.rl"
  10947. { start_hex(parser); }
  10948. break;
  10949. case 5:
  10950. #line 1234 "upb/json/parser.rl"
  10951. { hexdigit(parser, p); }
  10952. break;
  10953. case 6:
  10954. #line 1235 "upb/json/parser.rl"
  10955. { CHECK_RETURN_TOP(end_hex(parser)); }
  10956. break;
  10957. case 7:
  10958. #line 1241 "upb/json/parser.rl"
  10959. { CHECK_RETURN_TOP(escape(parser, p)); }
  10960. break;
  10961. case 8:
  10962. #line 1247 "upb/json/parser.rl"
  10963. { p--; {cs = stack[--top]; goto _again;} }
  10964. break;
  10965. case 9:
  10966. #line 1250 "upb/json/parser.rl"
  10967. { {stack[top++] = cs; cs = 19; goto _again;} }
  10968. break;
  10969. case 10:
  10970. #line 1252 "upb/json/parser.rl"
  10971. { p--; {stack[top++] = cs; cs = 27; goto _again;} }
  10972. break;
  10973. case 11:
  10974. #line 1257 "upb/json/parser.rl"
  10975. { start_member(parser); }
  10976. break;
  10977. case 12:
  10978. #line 1258 "upb/json/parser.rl"
  10979. { CHECK_RETURN_TOP(end_membername(parser)); }
  10980. break;
  10981. case 13:
  10982. #line 1261 "upb/json/parser.rl"
  10983. { end_member(parser); }
  10984. break;
  10985. case 14:
  10986. #line 1267 "upb/json/parser.rl"
  10987. { start_object(parser); }
  10988. break;
  10989. case 15:
  10990. #line 1270 "upb/json/parser.rl"
  10991. { end_object(parser); }
  10992. break;
  10993. case 16:
  10994. #line 1276 "upb/json/parser.rl"
  10995. { CHECK_RETURN_TOP(start_array(parser)); }
  10996. break;
  10997. case 17:
  10998. #line 1280 "upb/json/parser.rl"
  10999. { end_array(parser); }
  11000. break;
  11001. case 18:
  11002. #line 1285 "upb/json/parser.rl"
  11003. { start_number(parser, p); }
  11004. break;
  11005. case 19:
  11006. #line 1286 "upb/json/parser.rl"
  11007. { CHECK_RETURN_TOP(end_number(parser, p)); }
  11008. break;
  11009. case 20:
  11010. #line 1288 "upb/json/parser.rl"
  11011. { CHECK_RETURN_TOP(start_stringval(parser)); }
  11012. break;
  11013. case 21:
  11014. #line 1289 "upb/json/parser.rl"
  11015. { CHECK_RETURN_TOP(end_stringval(parser)); }
  11016. break;
  11017. case 22:
  11018. #line 1291 "upb/json/parser.rl"
  11019. { CHECK_RETURN_TOP(parser_putbool(parser, true)); }
  11020. break;
  11021. case 23:
  11022. #line 1293 "upb/json/parser.rl"
  11023. { CHECK_RETURN_TOP(parser_putbool(parser, false)); }
  11024. break;
  11025. case 24:
  11026. #line 1295 "upb/json/parser.rl"
  11027. { /* null value */ }
  11028. break;
  11029. case 25:
  11030. #line 1297 "upb/json/parser.rl"
  11031. { CHECK_RETURN_TOP(start_subobject(parser)); }
  11032. break;
  11033. case 26:
  11034. #line 1298 "upb/json/parser.rl"
  11035. { end_subobject(parser); }
  11036. break;
  11037. case 27:
  11038. #line 1303 "upb/json/parser.rl"
  11039. { p--; {cs = stack[--top]; goto _again;} }
  11040. break;
  11041. #line 1575 "upb/json/parser.c"
  11042. }
  11043. }
  11044. _again:
  11045. if ( cs == 0 )
  11046. goto _out;
  11047. if ( ++p != pe )
  11048. goto _resume;
  11049. _test_eof: {}
  11050. _out: {}
  11051. }
  11052. #line 1330 "upb/json/parser.rl"
  11053. if (p != pe) {
  11054. upb_status_seterrf(&parser->status, "Parse error at '%.*s'\n", pe - p, p);
  11055. upb_env_reporterror(parser->env, &parser->status);
  11056. } else {
  11057. capture_suspend(parser, &p);
  11058. }
  11059. error:
  11060. /* Save parsing state back to parser. */
  11061. parser->current_state = cs;
  11062. parser->parser_top = top;
  11063. return p - buf;
  11064. }
  11065. bool end(void *closure, const void *hd) {
  11066. UPB_UNUSED(closure);
  11067. UPB_UNUSED(hd);
  11068. /* Prevent compile warning on unused static constants. */
  11069. UPB_UNUSED(json_start);
  11070. UPB_UNUSED(json_en_number_machine);
  11071. UPB_UNUSED(json_en_string_machine);
  11072. UPB_UNUSED(json_en_value_machine);
  11073. UPB_UNUSED(json_en_main);
  11074. return true;
  11075. }
  11076. static void json_parser_reset(upb_json_parser *p) {
  11077. int cs;
  11078. int top;
  11079. p->top = p->stack;
  11080. p->top->f = NULL;
  11081. p->top->is_map = false;
  11082. p->top->is_mapentry = false;
  11083. /* Emit Ragel initialization of the parser. */
  11084. #line 1629 "upb/json/parser.c"
  11085. {
  11086. cs = json_start;
  11087. top = 0;
  11088. }
  11089. #line 1370 "upb/json/parser.rl"
  11090. p->current_state = cs;
  11091. p->parser_top = top;
  11092. accumulate_clear(p);
  11093. p->multipart_state = MULTIPART_INACTIVE;
  11094. p->capture = NULL;
  11095. p->accumulated = NULL;
  11096. upb_status_clear(&p->status);
  11097. }
  11098. static void visit_json_parsermethod(const upb_refcounted *r,
  11099. upb_refcounted_visit *visit,
  11100. void *closure) {
  11101. const upb_json_parsermethod *method = (upb_json_parsermethod*)r;
  11102. visit(r, upb_msgdef_upcast2(method->msg), closure);
  11103. }
  11104. static void free_json_parsermethod(upb_refcounted *r) {
  11105. upb_json_parsermethod *method = (upb_json_parsermethod*)r;
  11106. upb_inttable_iter i;
  11107. upb_inttable_begin(&i, &method->name_tables);
  11108. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  11109. upb_value val = upb_inttable_iter_value(&i);
  11110. upb_strtable *t = upb_value_getptr(val);
  11111. upb_strtable_uninit(t);
  11112. upb_gfree(t);
  11113. }
  11114. upb_inttable_uninit(&method->name_tables);
  11115. upb_gfree(r);
  11116. }
  11117. static void add_jsonname_table(upb_json_parsermethod *m, const upb_msgdef* md) {
  11118. upb_msg_field_iter i;
  11119. upb_strtable *t;
  11120. /* It would be nice to stack-allocate this, but protobufs do not limit the
  11121. * length of fields to any reasonable limit. */
  11122. char *buf = NULL;
  11123. size_t len = 0;
  11124. if (upb_inttable_lookupptr(&m->name_tables, md, NULL)) {
  11125. return;
  11126. }
  11127. /* TODO(haberman): handle malloc failure. */
  11128. t = upb_gmalloc(sizeof(*t));
  11129. upb_strtable_init(t, UPB_CTYPE_CONSTPTR);
  11130. upb_inttable_insertptr(&m->name_tables, md, upb_value_ptr(t));
  11131. for(upb_msg_field_begin(&i, md);
  11132. !upb_msg_field_done(&i);
  11133. upb_msg_field_next(&i)) {
  11134. const upb_fielddef *f = upb_msg_iter_field(&i);
  11135. /* Add an entry for the JSON name. */
  11136. size_t field_len = upb_fielddef_getjsonname(f, buf, len);
  11137. if (field_len > len) {
  11138. size_t len2;
  11139. buf = upb_grealloc(buf, 0, field_len);
  11140. len = field_len;
  11141. len2 = upb_fielddef_getjsonname(f, buf, len);
  11142. UPB_ASSERT(len == len2);
  11143. }
  11144. upb_strtable_insert(t, buf, upb_value_constptr(f));
  11145. if (strcmp(buf, upb_fielddef_name(f)) != 0) {
  11146. /* Since the JSON name is different from the regular field name, add an
  11147. * entry for the raw name (compliant proto3 JSON parsers must accept
  11148. * both). */
  11149. upb_strtable_insert(t, upb_fielddef_name(f), upb_value_constptr(f));
  11150. }
  11151. if (upb_fielddef_issubmsg(f)) {
  11152. add_jsonname_table(m, upb_fielddef_msgsubdef(f));
  11153. }
  11154. }
  11155. upb_gfree(buf);
  11156. }
  11157. /* Public API *****************************************************************/
  11158. upb_json_parser *upb_json_parser_create(upb_env *env,
  11159. const upb_json_parsermethod *method,
  11160. upb_sink *output) {
  11161. #ifndef NDEBUG
  11162. const size_t size_before = upb_env_bytesallocated(env);
  11163. #endif
  11164. upb_json_parser *p = upb_env_malloc(env, sizeof(upb_json_parser));
  11165. if (!p) return false;
  11166. p->env = env;
  11167. p->method = method;
  11168. p->limit = p->stack + UPB_JSON_MAX_DEPTH;
  11169. p->accumulate_buf = NULL;
  11170. p->accumulate_buf_size = 0;
  11171. upb_bytessink_reset(&p->input_, &method->input_handler_, p);
  11172. json_parser_reset(p);
  11173. upb_sink_reset(&p->top->sink, output->handlers, output->closure);
  11174. p->top->m = upb_handlers_msgdef(output->handlers);
  11175. set_name_table(p, p->top);
  11176. /* If this fails, uncomment and increase the value in parser.h. */
  11177. /* fprintf(stderr, "%zd\n", upb_env_bytesallocated(env) - size_before); */
  11178. UPB_ASSERT_DEBUGVAR(upb_env_bytesallocated(env) - size_before <=
  11179. UPB_JSON_PARSER_SIZE);
  11180. return p;
  11181. }
  11182. upb_bytessink *upb_json_parser_input(upb_json_parser *p) {
  11183. return &p->input_;
  11184. }
  11185. upb_json_parsermethod *upb_json_parsermethod_new(const upb_msgdef* md,
  11186. const void* owner) {
  11187. static const struct upb_refcounted_vtbl vtbl = {visit_json_parsermethod,
  11188. free_json_parsermethod};
  11189. upb_json_parsermethod *ret = upb_gmalloc(sizeof(*ret));
  11190. upb_refcounted_init(upb_json_parsermethod_upcast_mutable(ret), &vtbl, owner);
  11191. ret->msg = md;
  11192. upb_ref2(md, ret);
  11193. upb_byteshandler_init(&ret->input_handler_);
  11194. upb_byteshandler_setstring(&ret->input_handler_, parse, ret);
  11195. upb_byteshandler_setendstr(&ret->input_handler_, end, ret);
  11196. upb_inttable_init(&ret->name_tables, UPB_CTYPE_PTR);
  11197. add_jsonname_table(ret, md);
  11198. return ret;
  11199. }
  11200. const upb_byteshandler *upb_json_parsermethod_inputhandler(
  11201. const upb_json_parsermethod *m) {
  11202. return &m->input_handler_;
  11203. }
  11204. /*
  11205. ** This currently uses snprintf() to format primitives, and could be optimized
  11206. ** further.
  11207. */
  11208. #include <string.h>
  11209. #include <stdint.h>
  11210. struct upb_json_printer {
  11211. upb_sink input_;
  11212. /* BytesSink closure. */
  11213. void *subc_;
  11214. upb_bytessink *output_;
  11215. /* We track the depth so that we know when to emit startstr/endstr on the
  11216. * output. */
  11217. int depth_;
  11218. /* Have we emitted the first element? This state is necessary to emit commas
  11219. * without leaving a trailing comma in arrays/maps. We keep this state per
  11220. * frame depth.
  11221. *
  11222. * Why max_depth * 2? UPB_MAX_HANDLER_DEPTH counts depth as nested messages.
  11223. * We count frames (contexts in which we separate elements by commas) as both
  11224. * repeated fields and messages (maps), and the worst case is a
  11225. * message->repeated field->submessage->repeated field->... nesting. */
  11226. bool first_elem_[UPB_MAX_HANDLER_DEPTH * 2];
  11227. };
  11228. /* StringPiece; a pointer plus a length. */
  11229. typedef struct {
  11230. char *ptr;
  11231. size_t len;
  11232. } strpc;
  11233. void freestrpc(void *ptr) {
  11234. strpc *pc = ptr;
  11235. upb_gfree(pc->ptr);
  11236. upb_gfree(pc);
  11237. }
  11238. /* Convert fielddef name to JSON name and return as a string piece. */
  11239. strpc *newstrpc(upb_handlers *h, const upb_fielddef *f,
  11240. bool preserve_fieldnames) {
  11241. /* TODO(haberman): handle malloc failure. */
  11242. strpc *ret = upb_gmalloc(sizeof(*ret));
  11243. if (preserve_fieldnames) {
  11244. ret->ptr = upb_gstrdup(upb_fielddef_name(f));
  11245. ret->len = strlen(ret->ptr);
  11246. } else {
  11247. size_t len;
  11248. ret->len = upb_fielddef_getjsonname(f, NULL, 0);
  11249. ret->ptr = upb_gmalloc(ret->len);
  11250. len = upb_fielddef_getjsonname(f, ret->ptr, ret->len);
  11251. UPB_ASSERT(len == ret->len);
  11252. ret->len--; /* NULL */
  11253. }
  11254. upb_handlers_addcleanup(h, ret, freestrpc);
  11255. return ret;
  11256. }
  11257. /* ------------ JSON string printing: values, maps, arrays ------------------ */
  11258. static void print_data(
  11259. upb_json_printer *p, const char *buf, unsigned int len) {
  11260. /* TODO: Will need to change if we support pushback from the sink. */
  11261. size_t n = upb_bytessink_putbuf(p->output_, p->subc_, buf, len, NULL);
  11262. UPB_ASSERT(n == len);
  11263. }
  11264. static void print_comma(upb_json_printer *p) {
  11265. if (!p->first_elem_[p->depth_]) {
  11266. print_data(p, ",", 1);
  11267. }
  11268. p->first_elem_[p->depth_] = false;
  11269. }
  11270. /* Helpers that print properly formatted elements to the JSON output stream. */
  11271. /* Used for escaping control chars in strings. */
  11272. static const char kControlCharLimit = 0x20;
  11273. UPB_INLINE bool is_json_escaped(char c) {
  11274. /* See RFC 4627. */
  11275. unsigned char uc = (unsigned char)c;
  11276. return uc < kControlCharLimit || uc == '"' || uc == '\\';
  11277. }
  11278. UPB_INLINE const char* json_nice_escape(char c) {
  11279. switch (c) {
  11280. case '"': return "\\\"";
  11281. case '\\': return "\\\\";
  11282. case '\b': return "\\b";
  11283. case '\f': return "\\f";
  11284. case '\n': return "\\n";
  11285. case '\r': return "\\r";
  11286. case '\t': return "\\t";
  11287. default: return NULL;
  11288. }
  11289. }
  11290. /* Write a properly escaped string chunk. The surrounding quotes are *not*
  11291. * printed; this is so that the caller has the option of emitting the string
  11292. * content in chunks. */
  11293. static void putstring(upb_json_printer *p, const char *buf, unsigned int len) {
  11294. const char* unescaped_run = NULL;
  11295. unsigned int i;
  11296. for (i = 0; i < len; i++) {
  11297. char c = buf[i];
  11298. /* Handle escaping. */
  11299. if (is_json_escaped(c)) {
  11300. /* Use a "nice" escape, like \n, if one exists for this character. */
  11301. const char* escape = json_nice_escape(c);
  11302. /* If we don't have a specific 'nice' escape code, use a \uXXXX-style
  11303. * escape. */
  11304. char escape_buf[8];
  11305. if (!escape) {
  11306. unsigned char byte = (unsigned char)c;
  11307. _upb_snprintf(escape_buf, sizeof(escape_buf), "\\u%04x", (int)byte);
  11308. escape = escape_buf;
  11309. }
  11310. /* N.B. that we assume that the input encoding is equal to the output
  11311. * encoding (both UTF-8 for now), so for chars >= 0x20 and != \, ", we
  11312. * can simply pass the bytes through. */
  11313. /* If there's a current run of unescaped chars, print that run first. */
  11314. if (unescaped_run) {
  11315. print_data(p, unescaped_run, &buf[i] - unescaped_run);
  11316. unescaped_run = NULL;
  11317. }
  11318. /* Then print the escape code. */
  11319. print_data(p, escape, strlen(escape));
  11320. } else {
  11321. /* Add to the current unescaped run of characters. */
  11322. if (unescaped_run == NULL) {
  11323. unescaped_run = &buf[i];
  11324. }
  11325. }
  11326. }
  11327. /* If the string ended in a run of unescaped characters, print that last run. */
  11328. if (unescaped_run) {
  11329. print_data(p, unescaped_run, &buf[len] - unescaped_run);
  11330. }
  11331. }
  11332. #define CHKLENGTH(x) if (!(x)) return -1;
  11333. /* Helpers that format floating point values according to our custom formats.
  11334. * Right now we use %.8g and %.17g for float/double, respectively, to match
  11335. * proto2::util::JsonFormat's defaults. May want to change this later. */
  11336. const char neginf[] = "\"-Infinity\"";
  11337. const char inf[] = "\"Infinity\"";
  11338. static size_t fmt_double(double val, char* buf, size_t length) {
  11339. if (val == (1.0 / 0.0)) {
  11340. CHKLENGTH(length >= strlen(inf));
  11341. strcpy(buf, inf);
  11342. return strlen(inf);
  11343. } else if (val == (-1.0 / 0.0)) {
  11344. CHKLENGTH(length >= strlen(neginf));
  11345. strcpy(buf, neginf);
  11346. return strlen(neginf);
  11347. } else {
  11348. size_t n = _upb_snprintf(buf, length, "%.17g", val);
  11349. CHKLENGTH(n > 0 && n < length);
  11350. return n;
  11351. }
  11352. }
  11353. static size_t fmt_float(float val, char* buf, size_t length) {
  11354. size_t n = _upb_snprintf(buf, length, "%.8g", val);
  11355. CHKLENGTH(n > 0 && n < length);
  11356. return n;
  11357. }
  11358. static size_t fmt_bool(bool val, char* buf, size_t length) {
  11359. size_t n = _upb_snprintf(buf, length, "%s", (val ? "true" : "false"));
  11360. CHKLENGTH(n > 0 && n < length);
  11361. return n;
  11362. }
  11363. static size_t fmt_int64(long val, char* buf, size_t length) {
  11364. size_t n = _upb_snprintf(buf, length, "%ld", val);
  11365. CHKLENGTH(n > 0 && n < length);
  11366. return n;
  11367. }
  11368. static size_t fmt_uint64(unsigned long long val, char* buf, size_t length) {
  11369. size_t n = _upb_snprintf(buf, length, "%llu", val);
  11370. CHKLENGTH(n > 0 && n < length);
  11371. return n;
  11372. }
  11373. /* Print a map key given a field name. Called by scalar field handlers and by
  11374. * startseq for repeated fields. */
  11375. static bool putkey(void *closure, const void *handler_data) {
  11376. upb_json_printer *p = closure;
  11377. const strpc *key = handler_data;
  11378. print_comma(p);
  11379. print_data(p, "\"", 1);
  11380. putstring(p, key->ptr, key->len);
  11381. print_data(p, "\":", 2);
  11382. return true;
  11383. }
  11384. #define CHKFMT(val) if ((val) == (size_t)-1) return false;
  11385. #define CHK(val) if (!(val)) return false;
  11386. #define TYPE_HANDLERS(type, fmt_func) \
  11387. static bool put##type(void *closure, const void *handler_data, type val) { \
  11388. upb_json_printer *p = closure; \
  11389. char data[64]; \
  11390. size_t length = fmt_func(val, data, sizeof(data)); \
  11391. UPB_UNUSED(handler_data); \
  11392. CHKFMT(length); \
  11393. print_data(p, data, length); \
  11394. return true; \
  11395. } \
  11396. static bool scalar_##type(void *closure, const void *handler_data, \
  11397. type val) { \
  11398. CHK(putkey(closure, handler_data)); \
  11399. CHK(put##type(closure, handler_data, val)); \
  11400. return true; \
  11401. } \
  11402. static bool repeated_##type(void *closure, const void *handler_data, \
  11403. type val) { \
  11404. upb_json_printer *p = closure; \
  11405. print_comma(p); \
  11406. CHK(put##type(closure, handler_data, val)); \
  11407. return true; \
  11408. }
  11409. #define TYPE_HANDLERS_MAPKEY(type, fmt_func) \
  11410. static bool putmapkey_##type(void *closure, const void *handler_data, \
  11411. type val) { \
  11412. upb_json_printer *p = closure; \
  11413. print_data(p, "\"", 1); \
  11414. CHK(put##type(closure, handler_data, val)); \
  11415. print_data(p, "\":", 2); \
  11416. return true; \
  11417. }
  11418. TYPE_HANDLERS(double, fmt_double)
  11419. TYPE_HANDLERS(float, fmt_float)
  11420. TYPE_HANDLERS(bool, fmt_bool)
  11421. TYPE_HANDLERS(int32_t, fmt_int64)
  11422. TYPE_HANDLERS(uint32_t, fmt_int64)
  11423. TYPE_HANDLERS(int64_t, fmt_int64)
  11424. TYPE_HANDLERS(uint64_t, fmt_uint64)
  11425. /* double and float are not allowed to be map keys. */
  11426. TYPE_HANDLERS_MAPKEY(bool, fmt_bool)
  11427. TYPE_HANDLERS_MAPKEY(int32_t, fmt_int64)
  11428. TYPE_HANDLERS_MAPKEY(uint32_t, fmt_int64)
  11429. TYPE_HANDLERS_MAPKEY(int64_t, fmt_int64)
  11430. TYPE_HANDLERS_MAPKEY(uint64_t, fmt_uint64)
  11431. #undef TYPE_HANDLERS
  11432. #undef TYPE_HANDLERS_MAPKEY
  11433. typedef struct {
  11434. void *keyname;
  11435. const upb_enumdef *enumdef;
  11436. } EnumHandlerData;
  11437. static bool scalar_enum(void *closure, const void *handler_data,
  11438. int32_t val) {
  11439. const EnumHandlerData *hd = handler_data;
  11440. upb_json_printer *p = closure;
  11441. const char *symbolic_name;
  11442. CHK(putkey(closure, hd->keyname));
  11443. symbolic_name = upb_enumdef_iton(hd->enumdef, val);
  11444. if (symbolic_name) {
  11445. print_data(p, "\"", 1);
  11446. putstring(p, symbolic_name, strlen(symbolic_name));
  11447. print_data(p, "\"", 1);
  11448. } else {
  11449. putint32_t(closure, NULL, val);
  11450. }
  11451. return true;
  11452. }
  11453. static void print_enum_symbolic_name(upb_json_printer *p,
  11454. const upb_enumdef *def,
  11455. int32_t val) {
  11456. const char *symbolic_name = upb_enumdef_iton(def, val);
  11457. if (symbolic_name) {
  11458. print_data(p, "\"", 1);
  11459. putstring(p, symbolic_name, strlen(symbolic_name));
  11460. print_data(p, "\"", 1);
  11461. } else {
  11462. putint32_t(p, NULL, val);
  11463. }
  11464. }
  11465. static bool repeated_enum(void *closure, const void *handler_data,
  11466. int32_t val) {
  11467. const EnumHandlerData *hd = handler_data;
  11468. upb_json_printer *p = closure;
  11469. print_comma(p);
  11470. print_enum_symbolic_name(p, hd->enumdef, val);
  11471. return true;
  11472. }
  11473. static bool mapvalue_enum(void *closure, const void *handler_data,
  11474. int32_t val) {
  11475. const EnumHandlerData *hd = handler_data;
  11476. upb_json_printer *p = closure;
  11477. print_enum_symbolic_name(p, hd->enumdef, val);
  11478. return true;
  11479. }
  11480. static void *scalar_startsubmsg(void *closure, const void *handler_data) {
  11481. return putkey(closure, handler_data) ? closure : UPB_BREAK;
  11482. }
  11483. static void *repeated_startsubmsg(void *closure, const void *handler_data) {
  11484. upb_json_printer *p = closure;
  11485. UPB_UNUSED(handler_data);
  11486. print_comma(p);
  11487. return closure;
  11488. }
  11489. static void start_frame(upb_json_printer *p) {
  11490. p->depth_++;
  11491. p->first_elem_[p->depth_] = true;
  11492. print_data(p, "{", 1);
  11493. }
  11494. static void end_frame(upb_json_printer *p) {
  11495. print_data(p, "}", 1);
  11496. p->depth_--;
  11497. }
  11498. static bool printer_startmsg(void *closure, const void *handler_data) {
  11499. upb_json_printer *p = closure;
  11500. UPB_UNUSED(handler_data);
  11501. if (p->depth_ == 0) {
  11502. upb_bytessink_start(p->output_, 0, &p->subc_);
  11503. }
  11504. start_frame(p);
  11505. return true;
  11506. }
  11507. static bool printer_endmsg(void *closure, const void *handler_data, upb_status *s) {
  11508. upb_json_printer *p = closure;
  11509. UPB_UNUSED(handler_data);
  11510. UPB_UNUSED(s);
  11511. end_frame(p);
  11512. if (p->depth_ == 0) {
  11513. upb_bytessink_end(p->output_);
  11514. }
  11515. return true;
  11516. }
  11517. static void *startseq(void *closure, const void *handler_data) {
  11518. upb_json_printer *p = closure;
  11519. CHK(putkey(closure, handler_data));
  11520. p->depth_++;
  11521. p->first_elem_[p->depth_] = true;
  11522. print_data(p, "[", 1);
  11523. return closure;
  11524. }
  11525. static bool endseq(void *closure, const void *handler_data) {
  11526. upb_json_printer *p = closure;
  11527. UPB_UNUSED(handler_data);
  11528. print_data(p, "]", 1);
  11529. p->depth_--;
  11530. return true;
  11531. }
  11532. static void *startmap(void *closure, const void *handler_data) {
  11533. upb_json_printer *p = closure;
  11534. CHK(putkey(closure, handler_data));
  11535. p->depth_++;
  11536. p->first_elem_[p->depth_] = true;
  11537. print_data(p, "{", 1);
  11538. return closure;
  11539. }
  11540. static bool endmap(void *closure, const void *handler_data) {
  11541. upb_json_printer *p = closure;
  11542. UPB_UNUSED(handler_data);
  11543. print_data(p, "}", 1);
  11544. p->depth_--;
  11545. return true;
  11546. }
  11547. static size_t putstr(void *closure, const void *handler_data, const char *str,
  11548. size_t len, const upb_bufhandle *handle) {
  11549. upb_json_printer *p = closure;
  11550. UPB_UNUSED(handler_data);
  11551. UPB_UNUSED(handle);
  11552. putstring(p, str, len);
  11553. return len;
  11554. }
  11555. /* This has to Base64 encode the bytes, because JSON has no "bytes" type. */
  11556. static size_t putbytes(void *closure, const void *handler_data, const char *str,
  11557. size_t len, const upb_bufhandle *handle) {
  11558. upb_json_printer *p = closure;
  11559. /* This is the regular base64, not the "web-safe" version. */
  11560. static const char base64[] =
  11561. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  11562. /* Base64-encode. */
  11563. char data[16000];
  11564. const char *limit = data + sizeof(data);
  11565. const unsigned char *from = (const unsigned char*)str;
  11566. char *to = data;
  11567. size_t remaining = len;
  11568. size_t bytes;
  11569. UPB_UNUSED(handler_data);
  11570. UPB_UNUSED(handle);
  11571. while (remaining > 2) {
  11572. /* TODO(haberman): handle encoded lengths > sizeof(data) */
  11573. UPB_ASSERT((limit - to) >= 4);
  11574. to[0] = base64[from[0] >> 2];
  11575. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  11576. to[2] = base64[((from[1] & 0xf) << 2) | (from[2] >> 6)];
  11577. to[3] = base64[from[2] & 0x3f];
  11578. remaining -= 3;
  11579. to += 4;
  11580. from += 3;
  11581. }
  11582. switch (remaining) {
  11583. case 2:
  11584. to[0] = base64[from[0] >> 2];
  11585. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  11586. to[2] = base64[(from[1] & 0xf) << 2];
  11587. to[3] = '=';
  11588. to += 4;
  11589. from += 2;
  11590. break;
  11591. case 1:
  11592. to[0] = base64[from[0] >> 2];
  11593. to[1] = base64[((from[0] & 0x3) << 4)];
  11594. to[2] = '=';
  11595. to[3] = '=';
  11596. to += 4;
  11597. from += 1;
  11598. break;
  11599. }
  11600. bytes = to - data;
  11601. print_data(p, "\"", 1);
  11602. putstring(p, data, bytes);
  11603. print_data(p, "\"", 1);
  11604. return len;
  11605. }
  11606. static void *scalar_startstr(void *closure, const void *handler_data,
  11607. size_t size_hint) {
  11608. upb_json_printer *p = closure;
  11609. UPB_UNUSED(handler_data);
  11610. UPB_UNUSED(size_hint);
  11611. CHK(putkey(closure, handler_data));
  11612. print_data(p, "\"", 1);
  11613. return p;
  11614. }
  11615. static size_t scalar_str(void *closure, const void *handler_data,
  11616. const char *str, size_t len,
  11617. const upb_bufhandle *handle) {
  11618. CHK(putstr(closure, handler_data, str, len, handle));
  11619. return len;
  11620. }
  11621. static bool scalar_endstr(void *closure, const void *handler_data) {
  11622. upb_json_printer *p = closure;
  11623. UPB_UNUSED(handler_data);
  11624. print_data(p, "\"", 1);
  11625. return true;
  11626. }
  11627. static void *repeated_startstr(void *closure, const void *handler_data,
  11628. size_t size_hint) {
  11629. upb_json_printer *p = closure;
  11630. UPB_UNUSED(handler_data);
  11631. UPB_UNUSED(size_hint);
  11632. print_comma(p);
  11633. print_data(p, "\"", 1);
  11634. return p;
  11635. }
  11636. static size_t repeated_str(void *closure, const void *handler_data,
  11637. const char *str, size_t len,
  11638. const upb_bufhandle *handle) {
  11639. CHK(putstr(closure, handler_data, str, len, handle));
  11640. return len;
  11641. }
  11642. static bool repeated_endstr(void *closure, const void *handler_data) {
  11643. upb_json_printer *p = closure;
  11644. UPB_UNUSED(handler_data);
  11645. print_data(p, "\"", 1);
  11646. return true;
  11647. }
  11648. static void *mapkeyval_startstr(void *closure, const void *handler_data,
  11649. size_t size_hint) {
  11650. upb_json_printer *p = closure;
  11651. UPB_UNUSED(handler_data);
  11652. UPB_UNUSED(size_hint);
  11653. print_data(p, "\"", 1);
  11654. return p;
  11655. }
  11656. static size_t mapkey_str(void *closure, const void *handler_data,
  11657. const char *str, size_t len,
  11658. const upb_bufhandle *handle) {
  11659. CHK(putstr(closure, handler_data, str, len, handle));
  11660. return len;
  11661. }
  11662. static bool mapkey_endstr(void *closure, const void *handler_data) {
  11663. upb_json_printer *p = closure;
  11664. UPB_UNUSED(handler_data);
  11665. print_data(p, "\":", 2);
  11666. return true;
  11667. }
  11668. static bool mapvalue_endstr(void *closure, const void *handler_data) {
  11669. upb_json_printer *p = closure;
  11670. UPB_UNUSED(handler_data);
  11671. print_data(p, "\"", 1);
  11672. return true;
  11673. }
  11674. static size_t scalar_bytes(void *closure, const void *handler_data,
  11675. const char *str, size_t len,
  11676. const upb_bufhandle *handle) {
  11677. CHK(putkey(closure, handler_data));
  11678. CHK(putbytes(closure, handler_data, str, len, handle));
  11679. return len;
  11680. }
  11681. static size_t repeated_bytes(void *closure, const void *handler_data,
  11682. const char *str, size_t len,
  11683. const upb_bufhandle *handle) {
  11684. upb_json_printer *p = closure;
  11685. print_comma(p);
  11686. CHK(putbytes(closure, handler_data, str, len, handle));
  11687. return len;
  11688. }
  11689. static size_t mapkey_bytes(void *closure, const void *handler_data,
  11690. const char *str, size_t len,
  11691. const upb_bufhandle *handle) {
  11692. upb_json_printer *p = closure;
  11693. CHK(putbytes(closure, handler_data, str, len, handle));
  11694. print_data(p, ":", 1);
  11695. return len;
  11696. }
  11697. static void set_enum_hd(upb_handlers *h,
  11698. const upb_fielddef *f,
  11699. bool preserve_fieldnames,
  11700. upb_handlerattr *attr) {
  11701. EnumHandlerData *hd = upb_gmalloc(sizeof(EnumHandlerData));
  11702. hd->enumdef = (const upb_enumdef *)upb_fielddef_subdef(f);
  11703. hd->keyname = newstrpc(h, f, preserve_fieldnames);
  11704. upb_handlers_addcleanup(h, hd, upb_gfree);
  11705. upb_handlerattr_sethandlerdata(attr, hd);
  11706. }
  11707. /* Set up handlers for a mapentry submessage (i.e., an individual key/value pair
  11708. * in a map).
  11709. *
  11710. * TODO: Handle missing key, missing value, out-of-order key/value, or repeated
  11711. * key or value cases properly. The right way to do this is to allocate a
  11712. * temporary structure at the start of a mapentry submessage, store key and
  11713. * value data in it as key and value handlers are called, and then print the
  11714. * key/value pair once at the end of the submessage. If we don't do this, we
  11715. * should at least detect the case and throw an error. However, so far all of
  11716. * our sources that emit mapentry messages do so canonically (with one key
  11717. * field, and then one value field), so this is not a pressing concern at the
  11718. * moment. */
  11719. void printer_sethandlers_mapentry(const void *closure, bool preserve_fieldnames,
  11720. upb_handlers *h) {
  11721. const upb_msgdef *md = upb_handlers_msgdef(h);
  11722. /* A mapentry message is printed simply as '"key": value'. Rather than
  11723. * special-case key and value for every type below, we just handle both
  11724. * fields explicitly here. */
  11725. const upb_fielddef* key_field = upb_msgdef_itof(md, UPB_MAPENTRY_KEY);
  11726. const upb_fielddef* value_field = upb_msgdef_itof(md, UPB_MAPENTRY_VALUE);
  11727. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  11728. UPB_UNUSED(closure);
  11729. switch (upb_fielddef_type(key_field)) {
  11730. case UPB_TYPE_INT32:
  11731. upb_handlers_setint32(h, key_field, putmapkey_int32_t, &empty_attr);
  11732. break;
  11733. case UPB_TYPE_INT64:
  11734. upb_handlers_setint64(h, key_field, putmapkey_int64_t, &empty_attr);
  11735. break;
  11736. case UPB_TYPE_UINT32:
  11737. upb_handlers_setuint32(h, key_field, putmapkey_uint32_t, &empty_attr);
  11738. break;
  11739. case UPB_TYPE_UINT64:
  11740. upb_handlers_setuint64(h, key_field, putmapkey_uint64_t, &empty_attr);
  11741. break;
  11742. case UPB_TYPE_BOOL:
  11743. upb_handlers_setbool(h, key_field, putmapkey_bool, &empty_attr);
  11744. break;
  11745. case UPB_TYPE_STRING:
  11746. upb_handlers_setstartstr(h, key_field, mapkeyval_startstr, &empty_attr);
  11747. upb_handlers_setstring(h, key_field, mapkey_str, &empty_attr);
  11748. upb_handlers_setendstr(h, key_field, mapkey_endstr, &empty_attr);
  11749. break;
  11750. case UPB_TYPE_BYTES:
  11751. upb_handlers_setstring(h, key_field, mapkey_bytes, &empty_attr);
  11752. break;
  11753. default:
  11754. UPB_ASSERT(false);
  11755. break;
  11756. }
  11757. switch (upb_fielddef_type(value_field)) {
  11758. case UPB_TYPE_INT32:
  11759. upb_handlers_setint32(h, value_field, putint32_t, &empty_attr);
  11760. break;
  11761. case UPB_TYPE_INT64:
  11762. upb_handlers_setint64(h, value_field, putint64_t, &empty_attr);
  11763. break;
  11764. case UPB_TYPE_UINT32:
  11765. upb_handlers_setuint32(h, value_field, putuint32_t, &empty_attr);
  11766. break;
  11767. case UPB_TYPE_UINT64:
  11768. upb_handlers_setuint64(h, value_field, putuint64_t, &empty_attr);
  11769. break;
  11770. case UPB_TYPE_BOOL:
  11771. upb_handlers_setbool(h, value_field, putbool, &empty_attr);
  11772. break;
  11773. case UPB_TYPE_FLOAT:
  11774. upb_handlers_setfloat(h, value_field, putfloat, &empty_attr);
  11775. break;
  11776. case UPB_TYPE_DOUBLE:
  11777. upb_handlers_setdouble(h, value_field, putdouble, &empty_attr);
  11778. break;
  11779. case UPB_TYPE_STRING:
  11780. upb_handlers_setstartstr(h, value_field, mapkeyval_startstr, &empty_attr);
  11781. upb_handlers_setstring(h, value_field, putstr, &empty_attr);
  11782. upb_handlers_setendstr(h, value_field, mapvalue_endstr, &empty_attr);
  11783. break;
  11784. case UPB_TYPE_BYTES:
  11785. upb_handlers_setstring(h, value_field, putbytes, &empty_attr);
  11786. break;
  11787. case UPB_TYPE_ENUM: {
  11788. upb_handlerattr enum_attr = UPB_HANDLERATTR_INITIALIZER;
  11789. set_enum_hd(h, value_field, preserve_fieldnames, &enum_attr);
  11790. upb_handlers_setint32(h, value_field, mapvalue_enum, &enum_attr);
  11791. upb_handlerattr_uninit(&enum_attr);
  11792. break;
  11793. }
  11794. case UPB_TYPE_MESSAGE:
  11795. /* No handler necessary -- the submsg handlers will print the message
  11796. * as appropriate. */
  11797. break;
  11798. }
  11799. upb_handlerattr_uninit(&empty_attr);
  11800. }
  11801. void printer_sethandlers(const void *closure, upb_handlers *h) {
  11802. const upb_msgdef *md = upb_handlers_msgdef(h);
  11803. bool is_mapentry = upb_msgdef_mapentry(md);
  11804. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  11805. upb_msg_field_iter i;
  11806. const bool *preserve_fieldnames_ptr = closure;
  11807. const bool preserve_fieldnames = *preserve_fieldnames_ptr;
  11808. if (is_mapentry) {
  11809. /* mapentry messages are sufficiently different that we handle them
  11810. * separately. */
  11811. printer_sethandlers_mapentry(closure, preserve_fieldnames, h);
  11812. return;
  11813. }
  11814. upb_handlers_setstartmsg(h, printer_startmsg, &empty_attr);
  11815. upb_handlers_setendmsg(h, printer_endmsg, &empty_attr);
  11816. #define TYPE(type, name, ctype) \
  11817. case type: \
  11818. if (upb_fielddef_isseq(f)) { \
  11819. upb_handlers_set##name(h, f, repeated_##ctype, &empty_attr); \
  11820. } else { \
  11821. upb_handlers_set##name(h, f, scalar_##ctype, &name_attr); \
  11822. } \
  11823. break;
  11824. upb_msg_field_begin(&i, md);
  11825. for(; !upb_msg_field_done(&i); upb_msg_field_next(&i)) {
  11826. const upb_fielddef *f = upb_msg_iter_field(&i);
  11827. upb_handlerattr name_attr = UPB_HANDLERATTR_INITIALIZER;
  11828. upb_handlerattr_sethandlerdata(&name_attr,
  11829. newstrpc(h, f, preserve_fieldnames));
  11830. if (upb_fielddef_ismap(f)) {
  11831. upb_handlers_setstartseq(h, f, startmap, &name_attr);
  11832. upb_handlers_setendseq(h, f, endmap, &name_attr);
  11833. } else if (upb_fielddef_isseq(f)) {
  11834. upb_handlers_setstartseq(h, f, startseq, &name_attr);
  11835. upb_handlers_setendseq(h, f, endseq, &empty_attr);
  11836. }
  11837. switch (upb_fielddef_type(f)) {
  11838. TYPE(UPB_TYPE_FLOAT, float, float);
  11839. TYPE(UPB_TYPE_DOUBLE, double, double);
  11840. TYPE(UPB_TYPE_BOOL, bool, bool);
  11841. TYPE(UPB_TYPE_INT32, int32, int32_t);
  11842. TYPE(UPB_TYPE_UINT32, uint32, uint32_t);
  11843. TYPE(UPB_TYPE_INT64, int64, int64_t);
  11844. TYPE(UPB_TYPE_UINT64, uint64, uint64_t);
  11845. case UPB_TYPE_ENUM: {
  11846. /* For now, we always emit symbolic names for enums. We may want an
  11847. * option later to control this behavior, but we will wait for a real
  11848. * need first. */
  11849. upb_handlerattr enum_attr = UPB_HANDLERATTR_INITIALIZER;
  11850. set_enum_hd(h, f, preserve_fieldnames, &enum_attr);
  11851. if (upb_fielddef_isseq(f)) {
  11852. upb_handlers_setint32(h, f, repeated_enum, &enum_attr);
  11853. } else {
  11854. upb_handlers_setint32(h, f, scalar_enum, &enum_attr);
  11855. }
  11856. upb_handlerattr_uninit(&enum_attr);
  11857. break;
  11858. }
  11859. case UPB_TYPE_STRING:
  11860. if (upb_fielddef_isseq(f)) {
  11861. upb_handlers_setstartstr(h, f, repeated_startstr, &empty_attr);
  11862. upb_handlers_setstring(h, f, repeated_str, &empty_attr);
  11863. upb_handlers_setendstr(h, f, repeated_endstr, &empty_attr);
  11864. } else {
  11865. upb_handlers_setstartstr(h, f, scalar_startstr, &name_attr);
  11866. upb_handlers_setstring(h, f, scalar_str, &empty_attr);
  11867. upb_handlers_setendstr(h, f, scalar_endstr, &empty_attr);
  11868. }
  11869. break;
  11870. case UPB_TYPE_BYTES:
  11871. /* XXX: this doesn't support strings that span buffers yet. The base64
  11872. * encoder will need to be made resumable for this to work properly. */
  11873. if (upb_fielddef_isseq(f)) {
  11874. upb_handlers_setstring(h, f, repeated_bytes, &empty_attr);
  11875. } else {
  11876. upb_handlers_setstring(h, f, scalar_bytes, &name_attr);
  11877. }
  11878. break;
  11879. case UPB_TYPE_MESSAGE:
  11880. if (upb_fielddef_isseq(f)) {
  11881. upb_handlers_setstartsubmsg(h, f, repeated_startsubmsg, &name_attr);
  11882. } else {
  11883. upb_handlers_setstartsubmsg(h, f, scalar_startsubmsg, &name_attr);
  11884. }
  11885. break;
  11886. }
  11887. upb_handlerattr_uninit(&name_attr);
  11888. }
  11889. upb_handlerattr_uninit(&empty_attr);
  11890. #undef TYPE
  11891. }
  11892. static void json_printer_reset(upb_json_printer *p) {
  11893. p->depth_ = 0;
  11894. }
  11895. /* Public API *****************************************************************/
  11896. upb_json_printer *upb_json_printer_create(upb_env *e, const upb_handlers *h,
  11897. upb_bytessink *output) {
  11898. #ifndef NDEBUG
  11899. size_t size_before = upb_env_bytesallocated(e);
  11900. #endif
  11901. upb_json_printer *p = upb_env_malloc(e, sizeof(upb_json_printer));
  11902. if (!p) return NULL;
  11903. p->output_ = output;
  11904. json_printer_reset(p);
  11905. upb_sink_reset(&p->input_, h, p);
  11906. /* If this fails, increase the value in printer.h. */
  11907. UPB_ASSERT_DEBUGVAR(upb_env_bytesallocated(e) - size_before <=
  11908. UPB_JSON_PRINTER_SIZE);
  11909. return p;
  11910. }
  11911. upb_sink *upb_json_printer_input(upb_json_printer *p) {
  11912. return &p->input_;
  11913. }
  11914. const upb_handlers *upb_json_printer_newhandlers(const upb_msgdef *md,
  11915. bool preserve_fieldnames,
  11916. const void *owner) {
  11917. return upb_handlers_newfrozen(
  11918. md, owner, printer_sethandlers, &preserve_fieldnames);
  11919. }