upb.c 398 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575
  1. /* Amalgamated source file */
  2. #include "upb.h"
  3. #ifndef UINTPTR_MAX
  4. #error must include stdint.h first
  5. #endif
  6. #if UINTPTR_MAX == 0xffffffff
  7. #define UPB_SIZE(size32, size64) size32
  8. #else
  9. #define UPB_SIZE(size32, size64) size64
  10. #endif
  11. #define UPB_FIELD_AT(msg, fieldtype, offset) \
  12. *(fieldtype*)((const char*)(msg) + offset)
  13. #define UPB_READ_ONEOF(msg, fieldtype, offset, case_offset, case_val, default) \
  14. UPB_FIELD_AT(msg, int, case_offset) == case_val \
  15. ? UPB_FIELD_AT(msg, fieldtype, offset) \
  16. : default
  17. #define UPB_WRITE_ONEOF(msg, fieldtype, offset, value, case_offset, case_val) \
  18. UPB_FIELD_AT(msg, int, case_offset) = case_val; \
  19. UPB_FIELD_AT(msg, fieldtype, offset) = value;
  20. /* This file was generated by upbc (the upb compiler) from the input
  21. * file:
  22. *
  23. * google/protobuf/descriptor.proto
  24. *
  25. * Do not edit -- your changes will be discarded when the file is
  26. * regenerated. */
  27. #include <stddef.h>
  28. static const upb_msglayout *const google_protobuf_FileDescriptorSet_submsgs[1] = {
  29. &google_protobuf_FileDescriptorProto_msginit,
  30. };
  31. static const upb_msglayout_field google_protobuf_FileDescriptorSet__fields[1] = {
  32. {1, UPB_SIZE(0, 0), 0, 0, 11, 3},
  33. };
  34. const upb_msglayout google_protobuf_FileDescriptorSet_msginit = {
  35. &google_protobuf_FileDescriptorSet_submsgs[0],
  36. &google_protobuf_FileDescriptorSet__fields[0],
  37. UPB_SIZE(4, 8), 1, false,
  38. };
  39. static const upb_msglayout *const google_protobuf_FileDescriptorProto_submsgs[6] = {
  40. &google_protobuf_DescriptorProto_msginit,
  41. &google_protobuf_EnumDescriptorProto_msginit,
  42. &google_protobuf_FieldDescriptorProto_msginit,
  43. &google_protobuf_FileOptions_msginit,
  44. &google_protobuf_ServiceDescriptorProto_msginit,
  45. &google_protobuf_SourceCodeInfo_msginit,
  46. };
  47. static const upb_msglayout_field google_protobuf_FileDescriptorProto__fields[12] = {
  48. {1, UPB_SIZE(4, 8), 1, 0, 9, 1},
  49. {2, UPB_SIZE(12, 24), 2, 0, 9, 1},
  50. {3, UPB_SIZE(36, 72), 0, 0, 9, 3},
  51. {4, UPB_SIZE(40, 80), 0, 0, 11, 3},
  52. {5, UPB_SIZE(44, 88), 0, 1, 11, 3},
  53. {6, UPB_SIZE(48, 96), 0, 4, 11, 3},
  54. {7, UPB_SIZE(52, 104), 0, 2, 11, 3},
  55. {8, UPB_SIZE(28, 56), 4, 3, 11, 1},
  56. {9, UPB_SIZE(32, 64), 5, 5, 11, 1},
  57. {10, UPB_SIZE(56, 112), 0, 0, 5, 3},
  58. {11, UPB_SIZE(60, 120), 0, 0, 5, 3},
  59. {12, UPB_SIZE(20, 40), 3, 0, 9, 1},
  60. };
  61. const upb_msglayout google_protobuf_FileDescriptorProto_msginit = {
  62. &google_protobuf_FileDescriptorProto_submsgs[0],
  63. &google_protobuf_FileDescriptorProto__fields[0],
  64. UPB_SIZE(64, 128), 12, false,
  65. };
  66. static const upb_msglayout *const google_protobuf_DescriptorProto_submsgs[8] = {
  67. &google_protobuf_DescriptorProto_msginit,
  68. &google_protobuf_DescriptorProto_ExtensionRange_msginit,
  69. &google_protobuf_DescriptorProto_ReservedRange_msginit,
  70. &google_protobuf_EnumDescriptorProto_msginit,
  71. &google_protobuf_FieldDescriptorProto_msginit,
  72. &google_protobuf_MessageOptions_msginit,
  73. &google_protobuf_OneofDescriptorProto_msginit,
  74. };
  75. static const upb_msglayout_field google_protobuf_DescriptorProto__fields[10] = {
  76. {1, UPB_SIZE(4, 8), 1, 0, 9, 1},
  77. {2, UPB_SIZE(16, 32), 0, 4, 11, 3},
  78. {3, UPB_SIZE(20, 40), 0, 0, 11, 3},
  79. {4, UPB_SIZE(24, 48), 0, 3, 11, 3},
  80. {5, UPB_SIZE(28, 56), 0, 1, 11, 3},
  81. {6, UPB_SIZE(32, 64), 0, 4, 11, 3},
  82. {7, UPB_SIZE(12, 24), 2, 5, 11, 1},
  83. {8, UPB_SIZE(36, 72), 0, 6, 11, 3},
  84. {9, UPB_SIZE(40, 80), 0, 2, 11, 3},
  85. {10, UPB_SIZE(44, 88), 0, 0, 9, 3},
  86. };
  87. const upb_msglayout google_protobuf_DescriptorProto_msginit = {
  88. &google_protobuf_DescriptorProto_submsgs[0],
  89. &google_protobuf_DescriptorProto__fields[0],
  90. UPB_SIZE(48, 96), 10, false,
  91. };
  92. static const upb_msglayout *const google_protobuf_DescriptorProto_ExtensionRange_submsgs[1] = {
  93. &google_protobuf_ExtensionRangeOptions_msginit,
  94. };
  95. static const upb_msglayout_field google_protobuf_DescriptorProto_ExtensionRange__fields[3] = {
  96. {1, UPB_SIZE(4, 4), 1, 0, 5, 1},
  97. {2, UPB_SIZE(8, 8), 2, 0, 5, 1},
  98. {3, UPB_SIZE(12, 16), 3, 0, 11, 1},
  99. };
  100. const upb_msglayout google_protobuf_DescriptorProto_ExtensionRange_msginit = {
  101. &google_protobuf_DescriptorProto_ExtensionRange_submsgs[0],
  102. &google_protobuf_DescriptorProto_ExtensionRange__fields[0],
  103. UPB_SIZE(16, 24), 3, false,
  104. };
  105. static const upb_msglayout_field google_protobuf_DescriptorProto_ReservedRange__fields[2] = {
  106. {1, UPB_SIZE(4, 4), 1, 0, 5, 1},
  107. {2, UPB_SIZE(8, 8), 2, 0, 5, 1},
  108. };
  109. const upb_msglayout google_protobuf_DescriptorProto_ReservedRange_msginit = {
  110. NULL,
  111. &google_protobuf_DescriptorProto_ReservedRange__fields[0],
  112. UPB_SIZE(12, 12), 2, false,
  113. };
  114. static const upb_msglayout *const google_protobuf_ExtensionRangeOptions_submsgs[1] = {
  115. &google_protobuf_UninterpretedOption_msginit,
  116. };
  117. static const upb_msglayout_field google_protobuf_ExtensionRangeOptions__fields[1] = {
  118. {999, UPB_SIZE(0, 0), 0, 0, 11, 3},
  119. };
  120. const upb_msglayout google_protobuf_ExtensionRangeOptions_msginit = {
  121. &google_protobuf_ExtensionRangeOptions_submsgs[0],
  122. &google_protobuf_ExtensionRangeOptions__fields[0],
  123. UPB_SIZE(4, 8), 1, false,
  124. };
  125. static const upb_msglayout *const google_protobuf_FieldDescriptorProto_submsgs[1] = {
  126. &google_protobuf_FieldOptions_msginit,
  127. };
  128. static const upb_msglayout_field google_protobuf_FieldDescriptorProto__fields[10] = {
  129. {1, UPB_SIZE(32, 32), 5, 0, 9, 1},
  130. {2, UPB_SIZE(40, 48), 6, 0, 9, 1},
  131. {3, UPB_SIZE(24, 24), 3, 0, 5, 1},
  132. {4, UPB_SIZE(8, 8), 1, 0, 14, 1},
  133. {5, UPB_SIZE(16, 16), 2, 0, 14, 1},
  134. {6, UPB_SIZE(48, 64), 7, 0, 9, 1},
  135. {7, UPB_SIZE(56, 80), 8, 0, 9, 1},
  136. {8, UPB_SIZE(72, 112), 10, 0, 11, 1},
  137. {9, UPB_SIZE(28, 28), 4, 0, 5, 1},
  138. {10, UPB_SIZE(64, 96), 9, 0, 9, 1},
  139. };
  140. const upb_msglayout google_protobuf_FieldDescriptorProto_msginit = {
  141. &google_protobuf_FieldDescriptorProto_submsgs[0],
  142. &google_protobuf_FieldDescriptorProto__fields[0],
  143. UPB_SIZE(80, 128), 10, false,
  144. };
  145. static const upb_msglayout *const google_protobuf_OneofDescriptorProto_submsgs[1] = {
  146. &google_protobuf_OneofOptions_msginit,
  147. };
  148. static const upb_msglayout_field google_protobuf_OneofDescriptorProto__fields[2] = {
  149. {1, UPB_SIZE(4, 8), 1, 0, 9, 1},
  150. {2, UPB_SIZE(12, 24), 2, 0, 11, 1},
  151. };
  152. const upb_msglayout google_protobuf_OneofDescriptorProto_msginit = {
  153. &google_protobuf_OneofDescriptorProto_submsgs[0],
  154. &google_protobuf_OneofDescriptorProto__fields[0],
  155. UPB_SIZE(16, 32), 2, false,
  156. };
  157. static const upb_msglayout *const google_protobuf_EnumDescriptorProto_submsgs[3] = {
  158. &google_protobuf_EnumDescriptorProto_EnumReservedRange_msginit,
  159. &google_protobuf_EnumOptions_msginit,
  160. &google_protobuf_EnumValueDescriptorProto_msginit,
  161. };
  162. static const upb_msglayout_field google_protobuf_EnumDescriptorProto__fields[5] = {
  163. {1, UPB_SIZE(4, 8), 1, 0, 9, 1},
  164. {2, UPB_SIZE(16, 32), 0, 2, 11, 3},
  165. {3, UPB_SIZE(12, 24), 2, 1, 11, 1},
  166. {4, UPB_SIZE(20, 40), 0, 0, 11, 3},
  167. {5, UPB_SIZE(24, 48), 0, 0, 9, 3},
  168. };
  169. const upb_msglayout google_protobuf_EnumDescriptorProto_msginit = {
  170. &google_protobuf_EnumDescriptorProto_submsgs[0],
  171. &google_protobuf_EnumDescriptorProto__fields[0],
  172. UPB_SIZE(32, 64), 5, false,
  173. };
  174. static const upb_msglayout_field google_protobuf_EnumDescriptorProto_EnumReservedRange__fields[2] = {
  175. {1, UPB_SIZE(4, 4), 1, 0, 5, 1},
  176. {2, UPB_SIZE(8, 8), 2, 0, 5, 1},
  177. };
  178. const upb_msglayout google_protobuf_EnumDescriptorProto_EnumReservedRange_msginit = {
  179. NULL,
  180. &google_protobuf_EnumDescriptorProto_EnumReservedRange__fields[0],
  181. UPB_SIZE(12, 12), 2, false,
  182. };
  183. static const upb_msglayout *const google_protobuf_EnumValueDescriptorProto_submsgs[1] = {
  184. &google_protobuf_EnumValueOptions_msginit,
  185. };
  186. static const upb_msglayout_field google_protobuf_EnumValueDescriptorProto__fields[3] = {
  187. {1, UPB_SIZE(8, 8), 2, 0, 9, 1},
  188. {2, UPB_SIZE(4, 4), 1, 0, 5, 1},
  189. {3, UPB_SIZE(16, 24), 3, 0, 11, 1},
  190. };
  191. const upb_msglayout google_protobuf_EnumValueDescriptorProto_msginit = {
  192. &google_protobuf_EnumValueDescriptorProto_submsgs[0],
  193. &google_protobuf_EnumValueDescriptorProto__fields[0],
  194. UPB_SIZE(24, 32), 3, false,
  195. };
  196. static const upb_msglayout *const google_protobuf_ServiceDescriptorProto_submsgs[2] = {
  197. &google_protobuf_MethodDescriptorProto_msginit,
  198. &google_protobuf_ServiceOptions_msginit,
  199. };
  200. static const upb_msglayout_field google_protobuf_ServiceDescriptorProto__fields[3] = {
  201. {1, UPB_SIZE(4, 8), 1, 0, 9, 1},
  202. {2, UPB_SIZE(16, 32), 0, 0, 11, 3},
  203. {3, UPB_SIZE(12, 24), 2, 1, 11, 1},
  204. };
  205. const upb_msglayout google_protobuf_ServiceDescriptorProto_msginit = {
  206. &google_protobuf_ServiceDescriptorProto_submsgs[0],
  207. &google_protobuf_ServiceDescriptorProto__fields[0],
  208. UPB_SIZE(24, 48), 3, false,
  209. };
  210. static const upb_msglayout *const google_protobuf_MethodDescriptorProto_submsgs[1] = {
  211. &google_protobuf_MethodOptions_msginit,
  212. };
  213. static const upb_msglayout_field google_protobuf_MethodDescriptorProto__fields[6] = {
  214. {1, UPB_SIZE(4, 8), 3, 0, 9, 1},
  215. {2, UPB_SIZE(12, 24), 4, 0, 9, 1},
  216. {3, UPB_SIZE(20, 40), 5, 0, 9, 1},
  217. {4, UPB_SIZE(28, 56), 6, 0, 11, 1},
  218. {5, UPB_SIZE(1, 1), 1, 0, 8, 1},
  219. {6, UPB_SIZE(2, 2), 2, 0, 8, 1},
  220. };
  221. const upb_msglayout google_protobuf_MethodDescriptorProto_msginit = {
  222. &google_protobuf_MethodDescriptorProto_submsgs[0],
  223. &google_protobuf_MethodDescriptorProto__fields[0],
  224. UPB_SIZE(32, 64), 6, false,
  225. };
  226. static const upb_msglayout *const google_protobuf_FileOptions_submsgs[1] = {
  227. &google_protobuf_UninterpretedOption_msginit,
  228. };
  229. static const upb_msglayout_field google_protobuf_FileOptions__fields[19] = {
  230. {1, UPB_SIZE(28, 32), 11, 0, 9, 1},
  231. {8, UPB_SIZE(36, 48), 12, 0, 9, 1},
  232. {9, UPB_SIZE(8, 8), 1, 0, 14, 1},
  233. {10, UPB_SIZE(16, 16), 2, 0, 8, 1},
  234. {11, UPB_SIZE(44, 64), 13, 0, 9, 1},
  235. {16, UPB_SIZE(17, 17), 3, 0, 8, 1},
  236. {17, UPB_SIZE(18, 18), 4, 0, 8, 1},
  237. {18, UPB_SIZE(19, 19), 5, 0, 8, 1},
  238. {20, UPB_SIZE(20, 20), 6, 0, 8, 1},
  239. {23, UPB_SIZE(21, 21), 7, 0, 8, 1},
  240. {27, UPB_SIZE(22, 22), 8, 0, 8, 1},
  241. {31, UPB_SIZE(23, 23), 9, 0, 8, 1},
  242. {36, UPB_SIZE(52, 80), 14, 0, 9, 1},
  243. {37, UPB_SIZE(60, 96), 15, 0, 9, 1},
  244. {39, UPB_SIZE(68, 112), 16, 0, 9, 1},
  245. {40, UPB_SIZE(76, 128), 17, 0, 9, 1},
  246. {41, UPB_SIZE(84, 144), 18, 0, 9, 1},
  247. {42, UPB_SIZE(24, 24), 10, 0, 8, 1},
  248. {999, UPB_SIZE(92, 160), 0, 0, 11, 3},
  249. };
  250. const upb_msglayout google_protobuf_FileOptions_msginit = {
  251. &google_protobuf_FileOptions_submsgs[0],
  252. &google_protobuf_FileOptions__fields[0],
  253. UPB_SIZE(96, 176), 19, false,
  254. };
  255. static const upb_msglayout *const google_protobuf_MessageOptions_submsgs[1] = {
  256. &google_protobuf_UninterpretedOption_msginit,
  257. };
  258. static const upb_msglayout_field google_protobuf_MessageOptions__fields[5] = {
  259. {1, UPB_SIZE(1, 1), 1, 0, 8, 1},
  260. {2, UPB_SIZE(2, 2), 2, 0, 8, 1},
  261. {3, UPB_SIZE(3, 3), 3, 0, 8, 1},
  262. {7, UPB_SIZE(4, 4), 4, 0, 8, 1},
  263. {999, UPB_SIZE(8, 8), 0, 0, 11, 3},
  264. };
  265. const upb_msglayout google_protobuf_MessageOptions_msginit = {
  266. &google_protobuf_MessageOptions_submsgs[0],
  267. &google_protobuf_MessageOptions__fields[0],
  268. UPB_SIZE(12, 16), 5, false,
  269. };
  270. static const upb_msglayout *const google_protobuf_FieldOptions_submsgs[1] = {
  271. &google_protobuf_UninterpretedOption_msginit,
  272. };
  273. static const upb_msglayout_field google_protobuf_FieldOptions__fields[7] = {
  274. {1, UPB_SIZE(8, 8), 1, 0, 14, 1},
  275. {2, UPB_SIZE(24, 24), 3, 0, 8, 1},
  276. {3, UPB_SIZE(25, 25), 4, 0, 8, 1},
  277. {5, UPB_SIZE(26, 26), 5, 0, 8, 1},
  278. {6, UPB_SIZE(16, 16), 2, 0, 14, 1},
  279. {10, UPB_SIZE(27, 27), 6, 0, 8, 1},
  280. {999, UPB_SIZE(28, 32), 0, 0, 11, 3},
  281. };
  282. const upb_msglayout google_protobuf_FieldOptions_msginit = {
  283. &google_protobuf_FieldOptions_submsgs[0],
  284. &google_protobuf_FieldOptions__fields[0],
  285. UPB_SIZE(32, 40), 7, false,
  286. };
  287. static const upb_msglayout *const google_protobuf_OneofOptions_submsgs[1] = {
  288. &google_protobuf_UninterpretedOption_msginit,
  289. };
  290. static const upb_msglayout_field google_protobuf_OneofOptions__fields[1] = {
  291. {999, UPB_SIZE(0, 0), 0, 0, 11, 3},
  292. };
  293. const upb_msglayout google_protobuf_OneofOptions_msginit = {
  294. &google_protobuf_OneofOptions_submsgs[0],
  295. &google_protobuf_OneofOptions__fields[0],
  296. UPB_SIZE(4, 8), 1, false,
  297. };
  298. static const upb_msglayout *const google_protobuf_EnumOptions_submsgs[1] = {
  299. &google_protobuf_UninterpretedOption_msginit,
  300. };
  301. static const upb_msglayout_field google_protobuf_EnumOptions__fields[3] = {
  302. {2, UPB_SIZE(1, 1), 1, 0, 8, 1},
  303. {3, UPB_SIZE(2, 2), 2, 0, 8, 1},
  304. {999, UPB_SIZE(4, 8), 0, 0, 11, 3},
  305. };
  306. const upb_msglayout google_protobuf_EnumOptions_msginit = {
  307. &google_protobuf_EnumOptions_submsgs[0],
  308. &google_protobuf_EnumOptions__fields[0],
  309. UPB_SIZE(8, 16), 3, false,
  310. };
  311. static const upb_msglayout *const google_protobuf_EnumValueOptions_submsgs[1] = {
  312. &google_protobuf_UninterpretedOption_msginit,
  313. };
  314. static const upb_msglayout_field google_protobuf_EnumValueOptions__fields[2] = {
  315. {1, UPB_SIZE(1, 1), 1, 0, 8, 1},
  316. {999, UPB_SIZE(4, 8), 0, 0, 11, 3},
  317. };
  318. const upb_msglayout google_protobuf_EnumValueOptions_msginit = {
  319. &google_protobuf_EnumValueOptions_submsgs[0],
  320. &google_protobuf_EnumValueOptions__fields[0],
  321. UPB_SIZE(8, 16), 2, false,
  322. };
  323. static const upb_msglayout *const google_protobuf_ServiceOptions_submsgs[1] = {
  324. &google_protobuf_UninterpretedOption_msginit,
  325. };
  326. static const upb_msglayout_field google_protobuf_ServiceOptions__fields[2] = {
  327. {33, UPB_SIZE(1, 1), 1, 0, 8, 1},
  328. {999, UPB_SIZE(4, 8), 0, 0, 11, 3},
  329. };
  330. const upb_msglayout google_protobuf_ServiceOptions_msginit = {
  331. &google_protobuf_ServiceOptions_submsgs[0],
  332. &google_protobuf_ServiceOptions__fields[0],
  333. UPB_SIZE(8, 16), 2, false,
  334. };
  335. static const upb_msglayout *const google_protobuf_MethodOptions_submsgs[1] = {
  336. &google_protobuf_UninterpretedOption_msginit,
  337. };
  338. static const upb_msglayout_field google_protobuf_MethodOptions__fields[3] = {
  339. {33, UPB_SIZE(16, 16), 2, 0, 8, 1},
  340. {34, UPB_SIZE(8, 8), 1, 0, 14, 1},
  341. {999, UPB_SIZE(20, 24), 0, 0, 11, 3},
  342. };
  343. const upb_msglayout google_protobuf_MethodOptions_msginit = {
  344. &google_protobuf_MethodOptions_submsgs[0],
  345. &google_protobuf_MethodOptions__fields[0],
  346. UPB_SIZE(24, 32), 3, false,
  347. };
  348. static const upb_msglayout *const google_protobuf_UninterpretedOption_submsgs[1] = {
  349. &google_protobuf_UninterpretedOption_NamePart_msginit,
  350. };
  351. static const upb_msglayout_field google_protobuf_UninterpretedOption__fields[7] = {
  352. {2, UPB_SIZE(56, 80), 0, 0, 11, 3},
  353. {3, UPB_SIZE(32, 32), 4, 0, 9, 1},
  354. {4, UPB_SIZE(8, 8), 1, 0, 4, 1},
  355. {5, UPB_SIZE(16, 16), 2, 0, 3, 1},
  356. {6, UPB_SIZE(24, 24), 3, 0, 1, 1},
  357. {7, UPB_SIZE(40, 48), 5, 0, 12, 1},
  358. {8, UPB_SIZE(48, 64), 6, 0, 9, 1},
  359. };
  360. const upb_msglayout google_protobuf_UninterpretedOption_msginit = {
  361. &google_protobuf_UninterpretedOption_submsgs[0],
  362. &google_protobuf_UninterpretedOption__fields[0],
  363. UPB_SIZE(64, 96), 7, false,
  364. };
  365. static const upb_msglayout_field google_protobuf_UninterpretedOption_NamePart__fields[2] = {
  366. {1, UPB_SIZE(4, 8), 2, 0, 9, 2},
  367. {2, UPB_SIZE(1, 1), 1, 0, 8, 2},
  368. };
  369. const upb_msglayout google_protobuf_UninterpretedOption_NamePart_msginit = {
  370. NULL,
  371. &google_protobuf_UninterpretedOption_NamePart__fields[0],
  372. UPB_SIZE(16, 32), 2, false,
  373. };
  374. static const upb_msglayout *const google_protobuf_SourceCodeInfo_submsgs[1] = {
  375. &google_protobuf_SourceCodeInfo_Location_msginit,
  376. };
  377. static const upb_msglayout_field google_protobuf_SourceCodeInfo__fields[1] = {
  378. {1, UPB_SIZE(0, 0), 0, 0, 11, 3},
  379. };
  380. const upb_msglayout google_protobuf_SourceCodeInfo_msginit = {
  381. &google_protobuf_SourceCodeInfo_submsgs[0],
  382. &google_protobuf_SourceCodeInfo__fields[0],
  383. UPB_SIZE(4, 8), 1, false,
  384. };
  385. static const upb_msglayout_field google_protobuf_SourceCodeInfo_Location__fields[5] = {
  386. {1, UPB_SIZE(20, 40), 0, 0, 5, 3},
  387. {2, UPB_SIZE(24, 48), 0, 0, 5, 3},
  388. {3, UPB_SIZE(4, 8), 1, 0, 9, 1},
  389. {4, UPB_SIZE(12, 24), 2, 0, 9, 1},
  390. {6, UPB_SIZE(28, 56), 0, 0, 9, 3},
  391. };
  392. const upb_msglayout google_protobuf_SourceCodeInfo_Location_msginit = {
  393. NULL,
  394. &google_protobuf_SourceCodeInfo_Location__fields[0],
  395. UPB_SIZE(32, 64), 5, false,
  396. };
  397. static const upb_msglayout *const google_protobuf_GeneratedCodeInfo_submsgs[1] = {
  398. &google_protobuf_GeneratedCodeInfo_Annotation_msginit,
  399. };
  400. static const upb_msglayout_field google_protobuf_GeneratedCodeInfo__fields[1] = {
  401. {1, UPB_SIZE(0, 0), 0, 0, 11, 3},
  402. };
  403. const upb_msglayout google_protobuf_GeneratedCodeInfo_msginit = {
  404. &google_protobuf_GeneratedCodeInfo_submsgs[0],
  405. &google_protobuf_GeneratedCodeInfo__fields[0],
  406. UPB_SIZE(4, 8), 1, false,
  407. };
  408. static const upb_msglayout_field google_protobuf_GeneratedCodeInfo_Annotation__fields[4] = {
  409. {1, UPB_SIZE(20, 32), 0, 0, 5, 3},
  410. {2, UPB_SIZE(12, 16), 3, 0, 9, 1},
  411. {3, UPB_SIZE(4, 4), 1, 0, 5, 1},
  412. {4, UPB_SIZE(8, 8), 2, 0, 5, 1},
  413. };
  414. const upb_msglayout google_protobuf_GeneratedCodeInfo_Annotation_msginit = {
  415. NULL,
  416. &google_protobuf_GeneratedCodeInfo_Annotation__fields[0],
  417. UPB_SIZE(24, 48), 4, false,
  418. };
  419. #include <string.h>
  420. /* Maps descriptor type -> upb field type. */
  421. const uint8_t upb_desctype_to_fieldtype[] = {
  422. UPB_WIRE_TYPE_END_GROUP, /* ENDGROUP */
  423. UPB_TYPE_DOUBLE, /* DOUBLE */
  424. UPB_TYPE_FLOAT, /* FLOAT */
  425. UPB_TYPE_INT64, /* INT64 */
  426. UPB_TYPE_UINT64, /* UINT64 */
  427. UPB_TYPE_INT32, /* INT32 */
  428. UPB_TYPE_UINT64, /* FIXED64 */
  429. UPB_TYPE_UINT32, /* FIXED32 */
  430. UPB_TYPE_BOOL, /* BOOL */
  431. UPB_TYPE_STRING, /* STRING */
  432. UPB_TYPE_MESSAGE, /* GROUP */
  433. UPB_TYPE_MESSAGE, /* MESSAGE */
  434. UPB_TYPE_BYTES, /* BYTES */
  435. UPB_TYPE_UINT32, /* UINT32 */
  436. UPB_TYPE_ENUM, /* ENUM */
  437. UPB_TYPE_INT32, /* SFIXED32 */
  438. UPB_TYPE_INT64, /* SFIXED64 */
  439. UPB_TYPE_INT32, /* SINT32 */
  440. UPB_TYPE_INT64, /* SINT64 */
  441. };
  442. /* Data pertaining to the parse. */
  443. typedef struct {
  444. /* Current decoding pointer. Points to the beginning of a field until we
  445. * have finished decoding the whole field. */
  446. const char *ptr;
  447. } upb_decstate;
  448. /* Data pertaining to a single message frame. */
  449. typedef struct {
  450. const char *limit;
  451. int32_t group_number; /* 0 if we are not parsing a group. */
  452. /* These members are unset for an unknown group frame. */
  453. char *msg;
  454. const upb_msglayout *m;
  455. } upb_decframe;
  456. #define CHK(x) if (!(x)) { return false; }
  457. static bool upb_skip_unknowngroup(upb_decstate *d, int field_number,
  458. const char *limit);
  459. static bool upb_decode_message(upb_decstate *d, const char *limit,
  460. int group_number, char *msg,
  461. const upb_msglayout *l);
  462. static bool upb_decode_varint(const char **ptr, const char *limit,
  463. uint64_t *val) {
  464. uint8_t byte;
  465. int bitpos = 0;
  466. const char *p = *ptr;
  467. *val = 0;
  468. do {
  469. CHK(bitpos < 70 && p < limit);
  470. byte = *p;
  471. *val |= (uint64_t)(byte & 0x7F) << bitpos;
  472. p++;
  473. bitpos += 7;
  474. } while (byte & 0x80);
  475. *ptr = p;
  476. return true;
  477. }
  478. static bool upb_decode_varint32(const char **ptr, const char *limit,
  479. uint32_t *val) {
  480. uint64_t u64;
  481. CHK(upb_decode_varint(ptr, limit, &u64) && u64 <= UINT32_MAX);
  482. *val = u64;
  483. return true;
  484. }
  485. static bool upb_decode_64bit(const char **ptr, const char *limit,
  486. uint64_t *val) {
  487. CHK(limit - *ptr >= 8);
  488. memcpy(val, *ptr, 8);
  489. *ptr += 8;
  490. return true;
  491. }
  492. static bool upb_decode_32bit(const char **ptr, const char *limit,
  493. uint32_t *val) {
  494. CHK(limit - *ptr >= 4);
  495. memcpy(val, *ptr, 4);
  496. *ptr += 4;
  497. return true;
  498. }
  499. static bool upb_decode_tag(const char **ptr, const char *limit,
  500. int *field_number, int *wire_type) {
  501. uint32_t tag = 0;
  502. CHK(upb_decode_varint32(ptr, limit, &tag));
  503. *field_number = tag >> 3;
  504. *wire_type = tag & 7;
  505. return true;
  506. }
  507. static int32_t upb_zzdecode_32(uint32_t n) {
  508. return (n >> 1) ^ -(int32_t)(n & 1);
  509. }
  510. static int64_t upb_zzdecode_64(uint64_t n) {
  511. return (n >> 1) ^ -(int64_t)(n & 1);
  512. }
  513. static bool upb_decode_string(const char **ptr, const char *limit,
  514. upb_strview *val) {
  515. uint32_t len;
  516. CHK(upb_decode_varint32(ptr, limit, &len) &&
  517. len < INT32_MAX &&
  518. limit - *ptr >= (int32_t)len);
  519. *val = upb_strview_make(*ptr, len);
  520. *ptr += len;
  521. return true;
  522. }
  523. static void upb_set32(void *msg, size_t ofs, uint32_t val) {
  524. memcpy((char*)msg + ofs, &val, sizeof(val));
  525. }
  526. static bool upb_append_unknown(upb_decstate *d, upb_decframe *frame,
  527. const char *start) {
  528. upb_msg_addunknown(frame->msg, start, d->ptr - start);
  529. return true;
  530. }
  531. static bool upb_skip_unknownfielddata(upb_decstate *d, upb_decframe *frame,
  532. int field_number, int wire_type) {
  533. switch (wire_type) {
  534. case UPB_WIRE_TYPE_VARINT: {
  535. uint64_t val;
  536. return upb_decode_varint(&d->ptr, frame->limit, &val);
  537. }
  538. case UPB_WIRE_TYPE_32BIT: {
  539. uint32_t val;
  540. return upb_decode_32bit(&d->ptr, frame->limit, &val);
  541. }
  542. case UPB_WIRE_TYPE_64BIT: {
  543. uint64_t val;
  544. return upb_decode_64bit(&d->ptr, frame->limit, &val);
  545. }
  546. case UPB_WIRE_TYPE_DELIMITED: {
  547. upb_strview val;
  548. return upb_decode_string(&d->ptr, frame->limit, &val);
  549. }
  550. case UPB_WIRE_TYPE_START_GROUP:
  551. return upb_skip_unknowngroup(d, field_number, frame->limit);
  552. case UPB_WIRE_TYPE_END_GROUP:
  553. CHK(field_number == frame->group_number);
  554. frame->limit = d->ptr;
  555. return true;
  556. }
  557. return false;
  558. }
  559. static bool upb_array_grow(upb_array *arr, size_t elements) {
  560. size_t needed = arr->len + elements;
  561. size_t new_size = UPB_MAX(arr->size, 8);
  562. size_t new_bytes;
  563. size_t old_bytes;
  564. void *new_data;
  565. upb_alloc *alloc = upb_arena_alloc(arr->arena);
  566. while (new_size < needed) {
  567. new_size *= 2;
  568. }
  569. old_bytes = arr->len * arr->element_size;
  570. new_bytes = new_size * arr->element_size;
  571. new_data = upb_realloc(alloc, arr->data, old_bytes, new_bytes);
  572. CHK(new_data);
  573. arr->data = new_data;
  574. arr->size = new_size;
  575. return true;
  576. }
  577. static void *upb_array_reserve(upb_array *arr, size_t elements) {
  578. if (arr->size - arr->len < elements) {
  579. CHK(upb_array_grow(arr, elements));
  580. }
  581. return (char*)arr->data + (arr->len * arr->element_size);
  582. }
  583. static void *upb_array_add(upb_array *arr, size_t elements) {
  584. void *ret = upb_array_reserve(arr, elements);
  585. arr->len += elements;
  586. return ret;
  587. }
  588. static upb_array *upb_getarr(upb_decframe *frame,
  589. const upb_msglayout_field *field) {
  590. UPB_ASSERT(field->label == UPB_LABEL_REPEATED);
  591. return *(upb_array**)&frame->msg[field->offset];
  592. }
  593. static upb_array *upb_getorcreatearr(upb_decframe *frame,
  594. const upb_msglayout_field *field) {
  595. upb_array *arr = upb_getarr(frame, field);
  596. if (!arr) {
  597. upb_fieldtype_t type = upb_desctype_to_fieldtype[field->descriptortype];
  598. arr = upb_array_new(type, upb_msg_arena(frame->msg));
  599. if (!arr) {
  600. return NULL;
  601. }
  602. *(upb_array**)&frame->msg[field->offset] = arr;
  603. }
  604. return arr;
  605. }
  606. static void upb_sethasbit(upb_decframe *frame,
  607. const upb_msglayout_field *field) {
  608. int32_t hasbit = field->presence;
  609. UPB_ASSERT(field->presence > 0);
  610. frame->msg[hasbit / 8] |= (1 << (hasbit % 8));
  611. }
  612. static void upb_setoneofcase(upb_decframe *frame,
  613. const upb_msglayout_field *field) {
  614. UPB_ASSERT(field->presence < 0);
  615. upb_set32(frame->msg, ~field->presence, field->number);
  616. }
  617. static char *upb_decode_prepareslot(upb_decframe *frame,
  618. const upb_msglayout_field *field) {
  619. char *field_mem = frame->msg + field->offset;
  620. upb_array *arr;
  621. if (field->label == UPB_LABEL_REPEATED) {
  622. arr = upb_getorcreatearr(frame, field);
  623. field_mem = upb_array_reserve(arr, 1);
  624. }
  625. return field_mem;
  626. }
  627. static void upb_decode_setpresent(upb_decframe *frame,
  628. const upb_msglayout_field *field) {
  629. if (field->label == UPB_LABEL_REPEATED) {
  630. upb_array *arr = upb_getarr(frame, field);
  631. UPB_ASSERT(arr->len < arr->size);
  632. arr->len++;
  633. } else if (field->presence < 0) {
  634. upb_setoneofcase(frame, field);
  635. } else if (field->presence > 0) {
  636. upb_sethasbit(frame, field);
  637. }
  638. }
  639. static bool upb_decode_submsg(upb_decstate *d, upb_decframe *frame,
  640. const char *limit,
  641. const upb_msglayout_field *field,
  642. int group_number) {
  643. char *submsg_slot = upb_decode_prepareslot(frame, field);
  644. char *submsg = *(void **)submsg_slot;
  645. const upb_msglayout *subm;
  646. subm = frame->m->submsgs[field->submsg_index];
  647. UPB_ASSERT(subm);
  648. if (!submsg) {
  649. submsg = upb_msg_new(subm, upb_msg_arena(frame->msg));
  650. CHK(submsg);
  651. *(void**)submsg_slot = submsg;
  652. }
  653. upb_decode_message(d, limit, group_number, submsg, subm);
  654. return true;
  655. }
  656. static bool upb_decode_varintfield(upb_decstate *d, upb_decframe *frame,
  657. const char *field_start,
  658. const upb_msglayout_field *field) {
  659. uint64_t val;
  660. void *field_mem;
  661. field_mem = upb_decode_prepareslot(frame, field);
  662. CHK(field_mem);
  663. CHK(upb_decode_varint(&d->ptr, frame->limit, &val));
  664. switch ((upb_descriptortype_t)field->descriptortype) {
  665. case UPB_DESCRIPTOR_TYPE_INT64:
  666. case UPB_DESCRIPTOR_TYPE_UINT64:
  667. memcpy(field_mem, &val, sizeof(val));
  668. break;
  669. case UPB_DESCRIPTOR_TYPE_INT32:
  670. case UPB_DESCRIPTOR_TYPE_UINT32:
  671. case UPB_DESCRIPTOR_TYPE_ENUM: {
  672. uint32_t val32 = val;
  673. memcpy(field_mem, &val32, sizeof(val32));
  674. break;
  675. }
  676. case UPB_DESCRIPTOR_TYPE_BOOL: {
  677. bool valbool = val != 0;
  678. memcpy(field_mem, &valbool, sizeof(valbool));
  679. break;
  680. }
  681. case UPB_DESCRIPTOR_TYPE_SINT32: {
  682. int32_t decoded = upb_zzdecode_32(val);
  683. memcpy(field_mem, &decoded, sizeof(decoded));
  684. break;
  685. }
  686. case UPB_DESCRIPTOR_TYPE_SINT64: {
  687. int64_t decoded = upb_zzdecode_64(val);
  688. memcpy(field_mem, &decoded, sizeof(decoded));
  689. break;
  690. }
  691. default:
  692. return upb_append_unknown(d, frame, field_start);
  693. }
  694. upb_decode_setpresent(frame, field);
  695. return true;
  696. }
  697. static bool upb_decode_64bitfield(upb_decstate *d, upb_decframe *frame,
  698. const char *field_start,
  699. const upb_msglayout_field *field) {
  700. void *field_mem;
  701. uint64_t val;
  702. field_mem = upb_decode_prepareslot(frame, field);
  703. CHK(field_mem);
  704. CHK(upb_decode_64bit(&d->ptr, frame->limit, &val));
  705. switch ((upb_descriptortype_t)field->descriptortype) {
  706. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  707. case UPB_DESCRIPTOR_TYPE_FIXED64:
  708. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  709. memcpy(field_mem, &val, sizeof(val));
  710. break;
  711. default:
  712. return upb_append_unknown(d, frame, field_start);
  713. }
  714. upb_decode_setpresent(frame, field);
  715. return true;
  716. }
  717. static bool upb_decode_32bitfield(upb_decstate *d, upb_decframe *frame,
  718. const char *field_start,
  719. const upb_msglayout_field *field) {
  720. void *field_mem;
  721. uint32_t val;
  722. field_mem = upb_decode_prepareslot(frame, field);
  723. CHK(field_mem);
  724. CHK(upb_decode_32bit(&d->ptr, frame->limit, &val));
  725. switch ((upb_descriptortype_t)field->descriptortype) {
  726. case UPB_DESCRIPTOR_TYPE_FLOAT:
  727. case UPB_DESCRIPTOR_TYPE_FIXED32:
  728. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  729. memcpy(field_mem, &val, sizeof(val));
  730. break;
  731. default:
  732. return upb_append_unknown(d, frame, field_start);
  733. }
  734. upb_decode_setpresent(frame, field);
  735. return true;
  736. }
  737. static bool upb_decode_fixedpacked(upb_array *arr, upb_strview data,
  738. int elem_size) {
  739. int elements = data.size / elem_size;
  740. void *field_mem;
  741. CHK((size_t)(elements * elem_size) == data.size);
  742. field_mem = upb_array_add(arr, elements);
  743. CHK(field_mem);
  744. memcpy(field_mem, data.data, data.size);
  745. return true;
  746. }
  747. static bool upb_decode_toarray(upb_decstate *d, upb_decframe *frame,
  748. const char *field_start,
  749. const upb_msglayout_field *field,
  750. upb_strview val) {
  751. upb_array *arr = upb_getorcreatearr(frame, field);
  752. #define VARINT_CASE(ctype, decode) { \
  753. const char *ptr = val.data; \
  754. const char *limit = ptr + val.size; \
  755. while (ptr < limit) { \
  756. uint64_t val; \
  757. void *field_mem; \
  758. ctype decoded; \
  759. CHK(upb_decode_varint(&ptr, limit, &val)); \
  760. decoded = (decode)(val); \
  761. field_mem = upb_array_add(arr, 1); \
  762. CHK(field_mem); \
  763. memcpy(field_mem, &decoded, sizeof(ctype)); \
  764. } \
  765. return true; \
  766. }
  767. switch ((upb_descriptortype_t)field->descriptortype) {
  768. case UPB_DESCRIPTOR_TYPE_STRING:
  769. case UPB_DESCRIPTOR_TYPE_BYTES: {
  770. void *field_mem = upb_array_add(arr, 1);
  771. CHK(field_mem);
  772. memcpy(field_mem, &val, sizeof(val));
  773. return true;
  774. }
  775. case UPB_DESCRIPTOR_TYPE_FLOAT:
  776. case UPB_DESCRIPTOR_TYPE_FIXED32:
  777. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  778. return upb_decode_fixedpacked(arr, val, sizeof(int32_t));
  779. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  780. case UPB_DESCRIPTOR_TYPE_FIXED64:
  781. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  782. return upb_decode_fixedpacked(arr, val, sizeof(int64_t));
  783. case UPB_DESCRIPTOR_TYPE_INT32:
  784. case UPB_DESCRIPTOR_TYPE_UINT32:
  785. case UPB_DESCRIPTOR_TYPE_ENUM:
  786. /* TODO: proto2 enum field that isn't in the enum. */
  787. VARINT_CASE(uint32_t, uint32_t);
  788. case UPB_DESCRIPTOR_TYPE_INT64:
  789. case UPB_DESCRIPTOR_TYPE_UINT64:
  790. VARINT_CASE(uint64_t, uint64_t);
  791. case UPB_DESCRIPTOR_TYPE_BOOL:
  792. VARINT_CASE(bool, bool);
  793. case UPB_DESCRIPTOR_TYPE_SINT32:
  794. VARINT_CASE(int32_t, upb_zzdecode_32);
  795. case UPB_DESCRIPTOR_TYPE_SINT64:
  796. VARINT_CASE(int64_t, upb_zzdecode_64);
  797. case UPB_DESCRIPTOR_TYPE_MESSAGE: {
  798. const upb_msglayout *subm;
  799. char *submsg;
  800. void *field_mem;
  801. CHK(val.size <= (size_t)(frame->limit - val.data));
  802. d->ptr -= val.size;
  803. /* Create elemente message. */
  804. subm = frame->m->submsgs[field->submsg_index];
  805. UPB_ASSERT(subm);
  806. submsg = upb_msg_new(subm, upb_msg_arena(frame->msg));
  807. CHK(submsg);
  808. field_mem = upb_array_add(arr, 1);
  809. CHK(field_mem);
  810. *(void**)field_mem = submsg;
  811. return upb_decode_message(
  812. d, val.data + val.size, frame->group_number, submsg, subm);
  813. }
  814. case UPB_DESCRIPTOR_TYPE_GROUP:
  815. return upb_append_unknown(d, frame, field_start);
  816. }
  817. #undef VARINT_CASE
  818. UPB_UNREACHABLE();
  819. }
  820. static bool upb_decode_delimitedfield(upb_decstate *d, upb_decframe *frame,
  821. const char *field_start,
  822. const upb_msglayout_field *field) {
  823. upb_strview val;
  824. CHK(upb_decode_string(&d->ptr, frame->limit, &val));
  825. if (field->label == UPB_LABEL_REPEATED) {
  826. return upb_decode_toarray(d, frame, field_start, field, val);
  827. } else {
  828. switch ((upb_descriptortype_t)field->descriptortype) {
  829. case UPB_DESCRIPTOR_TYPE_STRING:
  830. case UPB_DESCRIPTOR_TYPE_BYTES: {
  831. void *field_mem = upb_decode_prepareslot(frame, field);
  832. CHK(field_mem);
  833. memcpy(field_mem, &val, sizeof(val));
  834. break;
  835. }
  836. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  837. CHK(val.size <= (size_t)(frame->limit - val.data));
  838. d->ptr -= val.size;
  839. CHK(upb_decode_submsg(d, frame, val.data + val.size, field, 0));
  840. break;
  841. default:
  842. /* TODO(haberman): should we accept the last element of a packed? */
  843. return upb_append_unknown(d, frame, field_start);
  844. }
  845. upb_decode_setpresent(frame, field);
  846. return true;
  847. }
  848. }
  849. static const upb_msglayout_field *upb_find_field(const upb_msglayout *l,
  850. uint32_t field_number) {
  851. /* Lots of optimization opportunities here. */
  852. int i;
  853. for (i = 0; i < l->field_count; i++) {
  854. if (l->fields[i].number == field_number) {
  855. return &l->fields[i];
  856. }
  857. }
  858. return NULL; /* Unknown field. */
  859. }
  860. static bool upb_decode_field(upb_decstate *d, upb_decframe *frame) {
  861. int field_number;
  862. int wire_type;
  863. const char *field_start = d->ptr;
  864. const upb_msglayout_field *field;
  865. CHK(upb_decode_tag(&d->ptr, frame->limit, &field_number, &wire_type));
  866. field = upb_find_field(frame->m, field_number);
  867. if (field) {
  868. switch (wire_type) {
  869. case UPB_WIRE_TYPE_VARINT:
  870. return upb_decode_varintfield(d, frame, field_start, field);
  871. case UPB_WIRE_TYPE_32BIT:
  872. return upb_decode_32bitfield(d, frame, field_start, field);
  873. case UPB_WIRE_TYPE_64BIT:
  874. return upb_decode_64bitfield(d, frame, field_start, field);
  875. case UPB_WIRE_TYPE_DELIMITED:
  876. return upb_decode_delimitedfield(d, frame, field_start, field);
  877. case UPB_WIRE_TYPE_START_GROUP:
  878. CHK(field->descriptortype == UPB_DESCRIPTOR_TYPE_GROUP);
  879. return upb_decode_submsg(d, frame, frame->limit, field, field_number);
  880. case UPB_WIRE_TYPE_END_GROUP:
  881. CHK(frame->group_number == field_number)
  882. frame->limit = d->ptr;
  883. return true;
  884. default:
  885. return false;
  886. }
  887. } else {
  888. CHK(field_number != 0);
  889. CHK(upb_skip_unknownfielddata(d, frame, field_number, wire_type));
  890. CHK(upb_append_unknown(d, frame, field_start));
  891. return true;
  892. }
  893. }
  894. static bool upb_skip_unknowngroup(upb_decstate *d, int field_number,
  895. const char *limit) {
  896. upb_decframe frame;
  897. frame.msg = NULL;
  898. frame.m = NULL;
  899. frame.group_number = field_number;
  900. frame.limit = limit;
  901. while (d->ptr < frame.limit) {
  902. int wire_type;
  903. int field_number;
  904. CHK(upb_decode_tag(&d->ptr, frame.limit, &field_number, &wire_type));
  905. CHK(upb_skip_unknownfielddata(d, &frame, field_number, wire_type));
  906. }
  907. return true;
  908. }
  909. static bool upb_decode_message(upb_decstate *d, const char *limit,
  910. int group_number, char *msg,
  911. const upb_msglayout *l) {
  912. upb_decframe frame;
  913. frame.group_number = group_number;
  914. frame.limit = limit;
  915. frame.msg = msg;
  916. frame.m = l;
  917. while (d->ptr < frame.limit) {
  918. CHK(upb_decode_field(d, &frame));
  919. }
  920. return true;
  921. }
  922. bool upb_decode(const char *buf, size_t size, void *msg,
  923. const upb_msglayout *l) {
  924. upb_decstate state;
  925. state.ptr = buf;
  926. return upb_decode_message(&state, buf + size, 0, msg, l);
  927. }
  928. #undef CHK
  929. #include <ctype.h>
  930. #include <errno.h>
  931. #include <stdlib.h>
  932. #include <string.h>
  933. typedef struct {
  934. size_t len;
  935. char str[1]; /* Null-terminated string data follows. */
  936. } str_t;
  937. static str_t *newstr(upb_alloc *alloc, const char *data, size_t len) {
  938. str_t *ret = upb_malloc(alloc, sizeof(*ret) + len);
  939. if (!ret) return NULL;
  940. ret->len = len;
  941. memcpy(ret->str, data, len);
  942. ret->str[len] = '\0';
  943. return ret;
  944. }
  945. struct upb_fielddef {
  946. const upb_filedef *file;
  947. const upb_msgdef *msgdef;
  948. const char *full_name;
  949. union {
  950. int64_t sint;
  951. uint64_t uint;
  952. double dbl;
  953. float flt;
  954. bool boolean;
  955. str_t *str;
  956. } defaultval;
  957. const upb_oneofdef *oneof;
  958. union {
  959. const upb_msgdef *msgdef;
  960. const upb_enumdef *enumdef;
  961. const google_protobuf_FieldDescriptorProto *unresolved;
  962. } sub;
  963. uint32_t number_;
  964. uint32_t index_;
  965. uint32_t selector_base; /* Used to index into a upb::Handlers table. */
  966. bool is_extension_;
  967. bool lazy_;
  968. bool packed_;
  969. upb_descriptortype_t type_;
  970. upb_label_t label_;
  971. };
  972. struct upb_msgdef {
  973. const upb_filedef *file;
  974. const char *full_name;
  975. uint32_t selector_count;
  976. uint32_t submsg_field_count;
  977. /* Tables for looking up fields by number and name. */
  978. upb_inttable itof;
  979. upb_strtable ntof;
  980. const upb_fielddef *fields;
  981. const upb_oneofdef *oneofs;
  982. int field_count;
  983. int oneof_count;
  984. /* Is this a map-entry message? */
  985. bool map_entry;
  986. upb_wellknowntype_t well_known_type;
  987. /* TODO(haberman): proper extension ranges (there can be multiple). */
  988. };
  989. struct upb_enumdef {
  990. const upb_filedef *file;
  991. const char *full_name;
  992. upb_strtable ntoi;
  993. upb_inttable iton;
  994. int32_t defaultval;
  995. };
  996. struct upb_oneofdef {
  997. const upb_msgdef *parent;
  998. const char *full_name;
  999. uint32_t index;
  1000. upb_strtable ntof;
  1001. upb_inttable itof;
  1002. };
  1003. struct upb_filedef {
  1004. const char *name;
  1005. const char *package;
  1006. const char *phpprefix;
  1007. const char *phpnamespace;
  1008. upb_syntax_t syntax;
  1009. const upb_filedef **deps;
  1010. const upb_msgdef *msgs;
  1011. const upb_enumdef *enums;
  1012. const upb_fielddef *exts;
  1013. int dep_count;
  1014. int msg_count;
  1015. int enum_count;
  1016. int ext_count;
  1017. };
  1018. struct upb_symtab {
  1019. upb_arena *arena;
  1020. upb_strtable syms; /* full_name -> packed def ptr */
  1021. upb_strtable files; /* file_name -> upb_filedef* */
  1022. };
  1023. /* Inside a symtab we store tagged pointers to specific def types. */
  1024. typedef enum {
  1025. UPB_DEFTYPE_MSG = 0,
  1026. UPB_DEFTYPE_ENUM = 1,
  1027. UPB_DEFTYPE_FIELD = 2,
  1028. UPB_DEFTYPE_ONEOF = 3
  1029. } upb_deftype_t;
  1030. static const void *unpack_def(upb_value v, upb_deftype_t type) {
  1031. uintptr_t num = (uintptr_t)upb_value_getconstptr(v);
  1032. return (num & 3) == type ? (const void*)(num & ~3) : NULL;
  1033. }
  1034. static upb_value pack_def(const void *ptr, upb_deftype_t type) {
  1035. uintptr_t num = (uintptr_t)ptr | type;
  1036. return upb_value_constptr((const void*)num);
  1037. }
  1038. /* isalpha() etc. from <ctype.h> are locale-dependent, which we don't want. */
  1039. static bool upb_isbetween(char c, char low, char high) {
  1040. return c >= low && c <= high;
  1041. }
  1042. static bool upb_isletter(char c) {
  1043. return upb_isbetween(c, 'A', 'Z') || upb_isbetween(c, 'a', 'z') || c == '_';
  1044. }
  1045. static bool upb_isalphanum(char c) {
  1046. return upb_isletter(c) || upb_isbetween(c, '0', '9');
  1047. }
  1048. static bool upb_isident(upb_strview name, bool full, upb_status *s) {
  1049. const char *str = name.data;
  1050. size_t len = name.size;
  1051. bool start = true;
  1052. size_t i;
  1053. for (i = 0; i < len; i++) {
  1054. char c = str[i];
  1055. if (c == '.') {
  1056. if (start || !full) {
  1057. upb_status_seterrf(s, "invalid name: unexpected '.' (%s)", str);
  1058. return false;
  1059. }
  1060. start = true;
  1061. } else if (start) {
  1062. if (!upb_isletter(c)) {
  1063. upb_status_seterrf(
  1064. s, "invalid name: path components must start with a letter (%s)",
  1065. str);
  1066. return false;
  1067. }
  1068. start = false;
  1069. } else {
  1070. if (!upb_isalphanum(c)) {
  1071. upb_status_seterrf(s, "invalid name: non-alphanumeric character (%s)",
  1072. str);
  1073. return false;
  1074. }
  1075. }
  1076. }
  1077. return !start;
  1078. }
  1079. static const char *shortdefname(const char *fullname) {
  1080. const char *p;
  1081. if (fullname == NULL) {
  1082. return NULL;
  1083. } else if ((p = strrchr(fullname, '.')) == NULL) {
  1084. /* No '.' in the name, return the full string. */
  1085. return fullname;
  1086. } else {
  1087. /* Return one past the last '.'. */
  1088. return p + 1;
  1089. }
  1090. }
  1091. /* All submessage fields are lower than all other fields.
  1092. * Secondly, fields are increasing in order. */
  1093. uint32_t field_rank(const upb_fielddef *f) {
  1094. uint32_t ret = upb_fielddef_number(f);
  1095. const uint32_t high_bit = 1 << 30;
  1096. UPB_ASSERT(ret < high_bit);
  1097. if (!upb_fielddef_issubmsg(f))
  1098. ret |= high_bit;
  1099. return ret;
  1100. }
  1101. int cmp_fields(const void *p1, const void *p2) {
  1102. const upb_fielddef *f1 = *(upb_fielddef*const*)p1;
  1103. const upb_fielddef *f2 = *(upb_fielddef*const*)p2;
  1104. return field_rank(f1) - field_rank(f2);
  1105. }
  1106. static bool assign_msg_indices(upb_msgdef *m, upb_status *s) {
  1107. /* Sort fields. upb internally relies on UPB_TYPE_MESSAGE fields having the
  1108. * lowest indexes, but we do not publicly guarantee this. */
  1109. upb_msg_field_iter j;
  1110. upb_msg_oneof_iter k;
  1111. int i;
  1112. uint32_t selector;
  1113. int n = upb_msgdef_numfields(m);
  1114. upb_fielddef **fields;
  1115. if (n == 0) {
  1116. m->selector_count = UPB_STATIC_SELECTOR_COUNT;
  1117. m->submsg_field_count = 0;
  1118. return true;
  1119. }
  1120. fields = upb_gmalloc(n * sizeof(*fields));
  1121. if (!fields) {
  1122. upb_status_setoom(s);
  1123. return false;
  1124. }
  1125. m->submsg_field_count = 0;
  1126. for(i = 0, upb_msg_field_begin(&j, m);
  1127. !upb_msg_field_done(&j);
  1128. upb_msg_field_next(&j), i++) {
  1129. upb_fielddef *f = upb_msg_iter_field(&j);
  1130. UPB_ASSERT(f->msgdef == m);
  1131. if (upb_fielddef_issubmsg(f)) {
  1132. m->submsg_field_count++;
  1133. }
  1134. fields[i] = f;
  1135. }
  1136. qsort(fields, n, sizeof(*fields), cmp_fields);
  1137. selector = UPB_STATIC_SELECTOR_COUNT + m->submsg_field_count;
  1138. for (i = 0; i < n; i++) {
  1139. upb_fielddef *f = fields[i];
  1140. f->index_ = i;
  1141. f->selector_base = selector + upb_handlers_selectorbaseoffset(f);
  1142. selector += upb_handlers_selectorcount(f);
  1143. }
  1144. m->selector_count = selector;
  1145. #ifndef NDEBUG
  1146. {
  1147. /* Verify that all selectors for the message are distinct. */
  1148. #define TRY(type) \
  1149. if (upb_handlers_getselector(f, type, &sel)) { upb_inttable_insert(&t, sel, v); }
  1150. upb_inttable t;
  1151. upb_value v;
  1152. upb_selector_t sel;
  1153. upb_inttable_init(&t, UPB_CTYPE_BOOL);
  1154. v = upb_value_bool(true);
  1155. upb_inttable_insert(&t, UPB_STARTMSG_SELECTOR, v);
  1156. upb_inttable_insert(&t, UPB_ENDMSG_SELECTOR, v);
  1157. upb_inttable_insert(&t, UPB_UNKNOWN_SELECTOR, v);
  1158. for(upb_msg_field_begin(&j, m);
  1159. !upb_msg_field_done(&j);
  1160. upb_msg_field_next(&j)) {
  1161. upb_fielddef *f = upb_msg_iter_field(&j);
  1162. /* These calls will assert-fail in upb_table if the value already
  1163. * exists. */
  1164. TRY(UPB_HANDLER_INT32);
  1165. TRY(UPB_HANDLER_INT64)
  1166. TRY(UPB_HANDLER_UINT32)
  1167. TRY(UPB_HANDLER_UINT64)
  1168. TRY(UPB_HANDLER_FLOAT)
  1169. TRY(UPB_HANDLER_DOUBLE)
  1170. TRY(UPB_HANDLER_BOOL)
  1171. TRY(UPB_HANDLER_STARTSTR)
  1172. TRY(UPB_HANDLER_STRING)
  1173. TRY(UPB_HANDLER_ENDSTR)
  1174. TRY(UPB_HANDLER_STARTSUBMSG)
  1175. TRY(UPB_HANDLER_ENDSUBMSG)
  1176. TRY(UPB_HANDLER_STARTSEQ)
  1177. TRY(UPB_HANDLER_ENDSEQ)
  1178. }
  1179. upb_inttable_uninit(&t);
  1180. }
  1181. #undef TRY
  1182. #endif
  1183. for(upb_msg_oneof_begin(&k, m), i = 0;
  1184. !upb_msg_oneof_done(&k);
  1185. upb_msg_oneof_next(&k), i++) {
  1186. upb_oneofdef *o = (upb_oneofdef*)upb_msg_iter_oneof(&k);
  1187. o->index = i;
  1188. }
  1189. upb_gfree(fields);
  1190. return true;
  1191. }
  1192. static void assign_msg_wellknowntype(upb_msgdef *m) {
  1193. const char *name = upb_msgdef_fullname(m);
  1194. if (name == NULL) {
  1195. m->well_known_type = UPB_WELLKNOWN_UNSPECIFIED;
  1196. return;
  1197. }
  1198. if (!strcmp(name, "google.protobuf.Any")) {
  1199. m->well_known_type = UPB_WELLKNOWN_ANY;
  1200. } else if (!strcmp(name, "google.protobuf.FieldMask")) {
  1201. m->well_known_type = UPB_WELLKNOWN_FIELDMASK;
  1202. } else if (!strcmp(name, "google.protobuf.Duration")) {
  1203. m->well_known_type = UPB_WELLKNOWN_DURATION;
  1204. } else if (!strcmp(name, "google.protobuf.Timestamp")) {
  1205. m->well_known_type = UPB_WELLKNOWN_TIMESTAMP;
  1206. } else if (!strcmp(name, "google.protobuf.DoubleValue")) {
  1207. m->well_known_type = UPB_WELLKNOWN_DOUBLEVALUE;
  1208. } else if (!strcmp(name, "google.protobuf.FloatValue")) {
  1209. m->well_known_type = UPB_WELLKNOWN_FLOATVALUE;
  1210. } else if (!strcmp(name, "google.protobuf.Int64Value")) {
  1211. m->well_known_type = UPB_WELLKNOWN_INT64VALUE;
  1212. } else if (!strcmp(name, "google.protobuf.UInt64Value")) {
  1213. m->well_known_type = UPB_WELLKNOWN_UINT64VALUE;
  1214. } else if (!strcmp(name, "google.protobuf.Int32Value")) {
  1215. m->well_known_type = UPB_WELLKNOWN_INT32VALUE;
  1216. } else if (!strcmp(name, "google.protobuf.UInt32Value")) {
  1217. m->well_known_type = UPB_WELLKNOWN_UINT32VALUE;
  1218. } else if (!strcmp(name, "google.protobuf.BoolValue")) {
  1219. m->well_known_type = UPB_WELLKNOWN_BOOLVALUE;
  1220. } else if (!strcmp(name, "google.protobuf.StringValue")) {
  1221. m->well_known_type = UPB_WELLKNOWN_STRINGVALUE;
  1222. } else if (!strcmp(name, "google.protobuf.BytesValue")) {
  1223. m->well_known_type = UPB_WELLKNOWN_BYTESVALUE;
  1224. } else if (!strcmp(name, "google.protobuf.Value")) {
  1225. m->well_known_type = UPB_WELLKNOWN_VALUE;
  1226. } else if (!strcmp(name, "google.protobuf.ListValue")) {
  1227. m->well_known_type = UPB_WELLKNOWN_LISTVALUE;
  1228. } else if (!strcmp(name, "google.protobuf.Struct")) {
  1229. m->well_known_type = UPB_WELLKNOWN_STRUCT;
  1230. } else {
  1231. m->well_known_type = UPB_WELLKNOWN_UNSPECIFIED;
  1232. }
  1233. }
  1234. /* upb_enumdef ****************************************************************/
  1235. const char *upb_enumdef_fullname(const upb_enumdef *e) {
  1236. return e->full_name;
  1237. }
  1238. const char *upb_enumdef_name(const upb_enumdef *e) {
  1239. return shortdefname(e->full_name);
  1240. }
  1241. const upb_filedef *upb_enumdef_file(const upb_enumdef *e) {
  1242. return e->file;
  1243. }
  1244. int32_t upb_enumdef_default(const upb_enumdef *e) {
  1245. UPB_ASSERT(upb_enumdef_iton(e, e->defaultval));
  1246. return e->defaultval;
  1247. }
  1248. int upb_enumdef_numvals(const upb_enumdef *e) {
  1249. return upb_strtable_count(&e->ntoi);
  1250. }
  1251. void upb_enum_begin(upb_enum_iter *i, const upb_enumdef *e) {
  1252. /* We iterate over the ntoi table, to account for duplicate numbers. */
  1253. upb_strtable_begin(i, &e->ntoi);
  1254. }
  1255. void upb_enum_next(upb_enum_iter *iter) { upb_strtable_next(iter); }
  1256. bool upb_enum_done(upb_enum_iter *iter) { return upb_strtable_done(iter); }
  1257. bool upb_enumdef_ntoi(const upb_enumdef *def, const char *name,
  1258. size_t len, int32_t *num) {
  1259. upb_value v;
  1260. if (!upb_strtable_lookup2(&def->ntoi, name, len, &v)) {
  1261. return false;
  1262. }
  1263. if (num) *num = upb_value_getint32(v);
  1264. return true;
  1265. }
  1266. const char *upb_enumdef_iton(const upb_enumdef *def, int32_t num) {
  1267. upb_value v;
  1268. return upb_inttable_lookup32(&def->iton, num, &v) ?
  1269. upb_value_getcstr(v) : NULL;
  1270. }
  1271. const char *upb_enum_iter_name(upb_enum_iter *iter) {
  1272. return upb_strtable_iter_key(iter);
  1273. }
  1274. int32_t upb_enum_iter_number(upb_enum_iter *iter) {
  1275. return upb_value_getint32(upb_strtable_iter_value(iter));
  1276. }
  1277. /* upb_fielddef ***************************************************************/
  1278. const char *upb_fielddef_fullname(const upb_fielddef *f) {
  1279. return f->full_name;
  1280. }
  1281. upb_fieldtype_t upb_fielddef_type(const upb_fielddef *f) {
  1282. switch (f->type_) {
  1283. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  1284. return UPB_TYPE_DOUBLE;
  1285. case UPB_DESCRIPTOR_TYPE_FLOAT:
  1286. return UPB_TYPE_FLOAT;
  1287. case UPB_DESCRIPTOR_TYPE_INT64:
  1288. case UPB_DESCRIPTOR_TYPE_SINT64:
  1289. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  1290. return UPB_TYPE_INT64;
  1291. case UPB_DESCRIPTOR_TYPE_INT32:
  1292. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  1293. case UPB_DESCRIPTOR_TYPE_SINT32:
  1294. return UPB_TYPE_INT32;
  1295. case UPB_DESCRIPTOR_TYPE_UINT64:
  1296. case UPB_DESCRIPTOR_TYPE_FIXED64:
  1297. return UPB_TYPE_UINT64;
  1298. case UPB_DESCRIPTOR_TYPE_UINT32:
  1299. case UPB_DESCRIPTOR_TYPE_FIXED32:
  1300. return UPB_TYPE_UINT32;
  1301. case UPB_DESCRIPTOR_TYPE_ENUM:
  1302. return UPB_TYPE_ENUM;
  1303. case UPB_DESCRIPTOR_TYPE_BOOL:
  1304. return UPB_TYPE_BOOL;
  1305. case UPB_DESCRIPTOR_TYPE_STRING:
  1306. return UPB_TYPE_STRING;
  1307. case UPB_DESCRIPTOR_TYPE_BYTES:
  1308. return UPB_TYPE_BYTES;
  1309. case UPB_DESCRIPTOR_TYPE_GROUP:
  1310. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  1311. return UPB_TYPE_MESSAGE;
  1312. }
  1313. UPB_UNREACHABLE();
  1314. }
  1315. upb_descriptortype_t upb_fielddef_descriptortype(const upb_fielddef *f) {
  1316. return f->type_;
  1317. }
  1318. uint32_t upb_fielddef_index(const upb_fielddef *f) {
  1319. return f->index_;
  1320. }
  1321. upb_label_t upb_fielddef_label(const upb_fielddef *f) {
  1322. return f->label_;
  1323. }
  1324. uint32_t upb_fielddef_number(const upb_fielddef *f) {
  1325. return f->number_;
  1326. }
  1327. bool upb_fielddef_isextension(const upb_fielddef *f) {
  1328. return f->is_extension_;
  1329. }
  1330. bool upb_fielddef_lazy(const upb_fielddef *f) {
  1331. return f->lazy_;
  1332. }
  1333. bool upb_fielddef_packed(const upb_fielddef *f) {
  1334. return f->packed_;
  1335. }
  1336. const char *upb_fielddef_name(const upb_fielddef *f) {
  1337. return shortdefname(f->full_name);
  1338. }
  1339. uint32_t upb_fielddef_selectorbase(const upb_fielddef *f) {
  1340. return f->selector_base;
  1341. }
  1342. size_t upb_fielddef_getjsonname(const upb_fielddef *f, char *buf, size_t len) {
  1343. const char *name = upb_fielddef_name(f);
  1344. size_t src, dst = 0;
  1345. bool ucase_next = false;
  1346. #define WRITE(byte) \
  1347. ++dst; \
  1348. if (dst < len) buf[dst - 1] = byte; \
  1349. else if (dst == len) buf[dst - 1] = '\0'
  1350. if (!name) {
  1351. WRITE('\0');
  1352. return 0;
  1353. }
  1354. /* Implement the transformation as described in the spec:
  1355. * 1. upper case all letters after an underscore.
  1356. * 2. remove all underscores.
  1357. */
  1358. for (src = 0; name[src]; src++) {
  1359. if (name[src] == '_') {
  1360. ucase_next = true;
  1361. continue;
  1362. }
  1363. if (ucase_next) {
  1364. WRITE(toupper(name[src]));
  1365. ucase_next = false;
  1366. } else {
  1367. WRITE(name[src]);
  1368. }
  1369. }
  1370. WRITE('\0');
  1371. return dst;
  1372. #undef WRITE
  1373. }
  1374. const upb_msgdef *upb_fielddef_containingtype(const upb_fielddef *f) {
  1375. return f->msgdef;
  1376. }
  1377. const upb_oneofdef *upb_fielddef_containingoneof(const upb_fielddef *f) {
  1378. return f->oneof;
  1379. }
  1380. static void chkdefaulttype(const upb_fielddef *f, int ctype) {
  1381. UPB_UNUSED(f);
  1382. UPB_UNUSED(ctype);
  1383. }
  1384. int64_t upb_fielddef_defaultint64(const upb_fielddef *f) {
  1385. chkdefaulttype(f, UPB_TYPE_INT64);
  1386. return f->defaultval.sint;
  1387. }
  1388. int32_t upb_fielddef_defaultint32(const upb_fielddef *f) {
  1389. chkdefaulttype(f, UPB_TYPE_INT32);
  1390. return f->defaultval.sint;
  1391. }
  1392. uint64_t upb_fielddef_defaultuint64(const upb_fielddef *f) {
  1393. chkdefaulttype(f, UPB_TYPE_UINT64);
  1394. return f->defaultval.uint;
  1395. }
  1396. uint32_t upb_fielddef_defaultuint32(const upb_fielddef *f) {
  1397. chkdefaulttype(f, UPB_TYPE_UINT32);
  1398. return f->defaultval.uint;
  1399. }
  1400. bool upb_fielddef_defaultbool(const upb_fielddef *f) {
  1401. chkdefaulttype(f, UPB_TYPE_BOOL);
  1402. return f->defaultval.boolean;
  1403. }
  1404. float upb_fielddef_defaultfloat(const upb_fielddef *f) {
  1405. chkdefaulttype(f, UPB_TYPE_FLOAT);
  1406. return f->defaultval.flt;
  1407. }
  1408. double upb_fielddef_defaultdouble(const upb_fielddef *f) {
  1409. chkdefaulttype(f, UPB_TYPE_DOUBLE);
  1410. return f->defaultval.dbl;
  1411. }
  1412. const char *upb_fielddef_defaultstr(const upb_fielddef *f, size_t *len) {
  1413. str_t *str = f->defaultval.str;
  1414. UPB_ASSERT(upb_fielddef_type(f) == UPB_TYPE_STRING ||
  1415. upb_fielddef_type(f) == UPB_TYPE_BYTES ||
  1416. upb_fielddef_type(f) == UPB_TYPE_ENUM);
  1417. if (str) {
  1418. if (len) *len = str->len;
  1419. return str->str;
  1420. } else {
  1421. if (len) *len = 0;
  1422. return NULL;
  1423. }
  1424. }
  1425. const upb_msgdef *upb_fielddef_msgsubdef(const upb_fielddef *f) {
  1426. UPB_ASSERT(upb_fielddef_type(f) == UPB_TYPE_MESSAGE);
  1427. return f->sub.msgdef;
  1428. }
  1429. const upb_enumdef *upb_fielddef_enumsubdef(const upb_fielddef *f) {
  1430. UPB_ASSERT(upb_fielddef_type(f) == UPB_TYPE_ENUM);
  1431. return f->sub.enumdef;
  1432. }
  1433. bool upb_fielddef_issubmsg(const upb_fielddef *f) {
  1434. return upb_fielddef_type(f) == UPB_TYPE_MESSAGE;
  1435. }
  1436. bool upb_fielddef_isstring(const upb_fielddef *f) {
  1437. return upb_fielddef_type(f) == UPB_TYPE_STRING ||
  1438. upb_fielddef_type(f) == UPB_TYPE_BYTES;
  1439. }
  1440. bool upb_fielddef_isseq(const upb_fielddef *f) {
  1441. return upb_fielddef_label(f) == UPB_LABEL_REPEATED;
  1442. }
  1443. bool upb_fielddef_isprimitive(const upb_fielddef *f) {
  1444. return !upb_fielddef_isstring(f) && !upb_fielddef_issubmsg(f);
  1445. }
  1446. bool upb_fielddef_ismap(const upb_fielddef *f) {
  1447. return upb_fielddef_isseq(f) && upb_fielddef_issubmsg(f) &&
  1448. upb_msgdef_mapentry(upb_fielddef_msgsubdef(f));
  1449. }
  1450. bool upb_fielddef_hassubdef(const upb_fielddef *f) {
  1451. return upb_fielddef_issubmsg(f) || upb_fielddef_type(f) == UPB_TYPE_ENUM;
  1452. }
  1453. bool upb_fielddef_haspresence(const upb_fielddef *f) {
  1454. if (upb_fielddef_isseq(f)) return false;
  1455. if (upb_fielddef_issubmsg(f)) return true;
  1456. return f->file->syntax == UPB_SYNTAX_PROTO2;
  1457. }
  1458. static bool between(int32_t x, int32_t low, int32_t high) {
  1459. return x >= low && x <= high;
  1460. }
  1461. bool upb_fielddef_checklabel(int32_t label) { return between(label, 1, 3); }
  1462. bool upb_fielddef_checktype(int32_t type) { return between(type, 1, 11); }
  1463. bool upb_fielddef_checkintfmt(int32_t fmt) { return between(fmt, 1, 3); }
  1464. bool upb_fielddef_checkdescriptortype(int32_t type) {
  1465. return between(type, 1, 18);
  1466. }
  1467. /* upb_msgdef *****************************************************************/
  1468. const char *upb_msgdef_fullname(const upb_msgdef *m) {
  1469. return m->full_name;
  1470. }
  1471. const upb_filedef *upb_msgdef_file(const upb_msgdef *m) {
  1472. return m->file;
  1473. }
  1474. const char *upb_msgdef_name(const upb_msgdef *m) {
  1475. return shortdefname(m->full_name);
  1476. }
  1477. upb_syntax_t upb_msgdef_syntax(const upb_msgdef *m) {
  1478. return m->file->syntax;
  1479. }
  1480. size_t upb_msgdef_selectorcount(const upb_msgdef *m) {
  1481. return m->selector_count;
  1482. }
  1483. uint32_t upb_msgdef_submsgfieldcount(const upb_msgdef *m) {
  1484. return m->submsg_field_count;
  1485. }
  1486. const upb_fielddef *upb_msgdef_itof(const upb_msgdef *m, uint32_t i) {
  1487. upb_value val;
  1488. return upb_inttable_lookup32(&m->itof, i, &val) ?
  1489. upb_value_getconstptr(val) : NULL;
  1490. }
  1491. const upb_fielddef *upb_msgdef_ntof(const upb_msgdef *m, const char *name,
  1492. size_t len) {
  1493. upb_value val;
  1494. if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
  1495. return NULL;
  1496. }
  1497. return unpack_def(val, UPB_DEFTYPE_FIELD);
  1498. }
  1499. const upb_oneofdef *upb_msgdef_ntoo(const upb_msgdef *m, const char *name,
  1500. size_t len) {
  1501. upb_value val;
  1502. if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
  1503. return NULL;
  1504. }
  1505. return unpack_def(val, UPB_DEFTYPE_ONEOF);
  1506. }
  1507. bool upb_msgdef_lookupname(const upb_msgdef *m, const char *name, size_t len,
  1508. const upb_fielddef **f, const upb_oneofdef **o) {
  1509. upb_value val;
  1510. if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
  1511. return false;
  1512. }
  1513. *o = unpack_def(val, UPB_DEFTYPE_ONEOF);
  1514. *f = unpack_def(val, UPB_DEFTYPE_FIELD);
  1515. UPB_ASSERT((*o != NULL) ^ (*f != NULL)); /* Exactly one of the two should be set. */
  1516. return true;
  1517. }
  1518. int upb_msgdef_numfields(const upb_msgdef *m) {
  1519. /* The number table contains only fields. */
  1520. return upb_inttable_count(&m->itof);
  1521. }
  1522. int upb_msgdef_numoneofs(const upb_msgdef *m) {
  1523. /* The name table includes oneofs, and the number table does not. */
  1524. return upb_strtable_count(&m->ntof) - upb_inttable_count(&m->itof);
  1525. }
  1526. bool upb_msgdef_mapentry(const upb_msgdef *m) {
  1527. return m->map_entry;
  1528. }
  1529. upb_wellknowntype_t upb_msgdef_wellknowntype(const upb_msgdef *m) {
  1530. return m->well_known_type;
  1531. }
  1532. bool upb_msgdef_isnumberwrapper(const upb_msgdef *m) {
  1533. upb_wellknowntype_t type = upb_msgdef_wellknowntype(m);
  1534. return type >= UPB_WELLKNOWN_DOUBLEVALUE &&
  1535. type <= UPB_WELLKNOWN_UINT32VALUE;
  1536. }
  1537. void upb_msg_field_begin(upb_msg_field_iter *iter, const upb_msgdef *m) {
  1538. upb_inttable_begin(iter, &m->itof);
  1539. }
  1540. void upb_msg_field_next(upb_msg_field_iter *iter) { upb_inttable_next(iter); }
  1541. bool upb_msg_field_done(const upb_msg_field_iter *iter) {
  1542. return upb_inttable_done(iter);
  1543. }
  1544. upb_fielddef *upb_msg_iter_field(const upb_msg_field_iter *iter) {
  1545. return (upb_fielddef *)upb_value_getconstptr(upb_inttable_iter_value(iter));
  1546. }
  1547. void upb_msg_field_iter_setdone(upb_msg_field_iter *iter) {
  1548. upb_inttable_iter_setdone(iter);
  1549. }
  1550. bool upb_msg_field_iter_isequal(const upb_msg_field_iter * iter1,
  1551. const upb_msg_field_iter * iter2) {
  1552. return upb_inttable_iter_isequal(iter1, iter2);
  1553. }
  1554. void upb_msg_oneof_begin(upb_msg_oneof_iter *iter, const upb_msgdef *m) {
  1555. upb_strtable_begin(iter, &m->ntof);
  1556. /* We need to skip past any initial fields. */
  1557. while (!upb_strtable_done(iter) &&
  1558. !unpack_def(upb_strtable_iter_value(iter), UPB_DEFTYPE_ONEOF)) {
  1559. upb_strtable_next(iter);
  1560. }
  1561. }
  1562. void upb_msg_oneof_next(upb_msg_oneof_iter *iter) {
  1563. /* We need to skip past fields to return only oneofs. */
  1564. do {
  1565. upb_strtable_next(iter);
  1566. } while (!upb_strtable_done(iter) &&
  1567. !unpack_def(upb_strtable_iter_value(iter), UPB_DEFTYPE_ONEOF));
  1568. }
  1569. bool upb_msg_oneof_done(const upb_msg_oneof_iter *iter) {
  1570. return upb_strtable_done(iter);
  1571. }
  1572. const upb_oneofdef *upb_msg_iter_oneof(const upb_msg_oneof_iter *iter) {
  1573. return unpack_def(upb_strtable_iter_value(iter), UPB_DEFTYPE_ONEOF);
  1574. }
  1575. void upb_msg_oneof_iter_setdone(upb_msg_oneof_iter *iter) {
  1576. upb_strtable_iter_setdone(iter);
  1577. }
  1578. bool upb_msg_oneof_iter_isequal(const upb_msg_oneof_iter *iter1,
  1579. const upb_msg_oneof_iter *iter2) {
  1580. return upb_strtable_iter_isequal(iter1, iter2);
  1581. }
  1582. /* upb_oneofdef ***************************************************************/
  1583. const char *upb_oneofdef_name(const upb_oneofdef *o) {
  1584. return shortdefname(o->full_name);
  1585. }
  1586. const upb_msgdef *upb_oneofdef_containingtype(const upb_oneofdef *o) {
  1587. return o->parent;
  1588. }
  1589. int upb_oneofdef_numfields(const upb_oneofdef *o) {
  1590. return upb_strtable_count(&o->ntof);
  1591. }
  1592. uint32_t upb_oneofdef_index(const upb_oneofdef *o) {
  1593. return o->index;
  1594. }
  1595. const upb_fielddef *upb_oneofdef_ntof(const upb_oneofdef *o,
  1596. const char *name, size_t length) {
  1597. upb_value val;
  1598. return upb_strtable_lookup2(&o->ntof, name, length, &val) ?
  1599. upb_value_getptr(val) : NULL;
  1600. }
  1601. const upb_fielddef *upb_oneofdef_itof(const upb_oneofdef *o, uint32_t num) {
  1602. upb_value val;
  1603. return upb_inttable_lookup32(&o->itof, num, &val) ?
  1604. upb_value_getptr(val) : NULL;
  1605. }
  1606. void upb_oneof_begin(upb_oneof_iter *iter, const upb_oneofdef *o) {
  1607. upb_inttable_begin(iter, &o->itof);
  1608. }
  1609. void upb_oneof_next(upb_oneof_iter *iter) {
  1610. upb_inttable_next(iter);
  1611. }
  1612. bool upb_oneof_done(upb_oneof_iter *iter) {
  1613. return upb_inttable_done(iter);
  1614. }
  1615. upb_fielddef *upb_oneof_iter_field(const upb_oneof_iter *iter) {
  1616. return (upb_fielddef *)upb_value_getconstptr(upb_inttable_iter_value(iter));
  1617. }
  1618. void upb_oneof_iter_setdone(upb_oneof_iter *iter) {
  1619. upb_inttable_iter_setdone(iter);
  1620. }
  1621. /* Code to build defs from descriptor protos. *********************************/
  1622. /* There is a question of how much validation to do here. It will be difficult
  1623. * to perfectly match the amount of validation performed by proto2. But since
  1624. * this code is used to directly build defs from Ruby (for example) we do need
  1625. * to validate important constraints like uniqueness of names and numbers. */
  1626. #define CHK(x) if (!(x)) { return false; }
  1627. #define CHK_OOM(x) if (!(x)) { upb_status_setoom(ctx->status); return false; }
  1628. typedef struct {
  1629. const upb_symtab *symtab;
  1630. upb_filedef *file; /* File we are building. */
  1631. upb_alloc *alloc; /* Allocate defs here. */
  1632. upb_alloc *tmp; /* Alloc for addtab and any other tmp data. */
  1633. upb_strtable *addtab; /* full_name -> packed def ptr for new defs. */
  1634. upb_status *status; /* Record errors here. */
  1635. } symtab_addctx;
  1636. static char* strviewdup(const symtab_addctx *ctx, upb_strview view) {
  1637. return upb_strdup2(view.data, view.size, ctx->alloc);
  1638. }
  1639. static bool streql2(const char *a, size_t n, const char *b) {
  1640. return n == strlen(b) && memcmp(a, b, n) == 0;
  1641. }
  1642. static bool streql_view(upb_strview view, const char *b) {
  1643. return streql2(view.data, view.size, b);
  1644. }
  1645. static const char *makefullname(const symtab_addctx *ctx, const char *prefix,
  1646. upb_strview name) {
  1647. if (prefix) {
  1648. /* ret = prefix + '.' + name; */
  1649. size_t n = strlen(prefix);
  1650. char *ret = upb_malloc(ctx->alloc, n + name.size + 2);
  1651. CHK_OOM(ret);
  1652. strcpy(ret, prefix);
  1653. ret[n] = '.';
  1654. memcpy(&ret[n + 1], name.data, name.size);
  1655. ret[n + 1 + name.size] = '\0';
  1656. return ret;
  1657. } else {
  1658. return strviewdup(ctx, name);
  1659. }
  1660. }
  1661. static bool symtab_add(const symtab_addctx *ctx, const char *name,
  1662. upb_value v) {
  1663. upb_value tmp;
  1664. if (upb_strtable_lookup(ctx->addtab, name, &tmp) ||
  1665. upb_strtable_lookup(&ctx->symtab->syms, name, &tmp)) {
  1666. upb_status_seterrf(ctx->status, "duplicate symbol '%s'", name);
  1667. return false;
  1668. }
  1669. CHK_OOM(upb_strtable_insert3(ctx->addtab, name, strlen(name), v, ctx->tmp));
  1670. return true;
  1671. }
  1672. /* Given a symbol and the base symbol inside which it is defined, find the
  1673. * symbol's definition in t. */
  1674. static bool resolvename(const upb_strtable *t, const upb_fielddef *f,
  1675. const char *base, upb_strview sym,
  1676. upb_deftype_t type, upb_status *status,
  1677. const void **def) {
  1678. if(sym.size == 0) return NULL;
  1679. if(sym.data[0] == '.') {
  1680. /* Symbols starting with '.' are absolute, so we do a single lookup.
  1681. * Slice to omit the leading '.' */
  1682. upb_value v;
  1683. if (!upb_strtable_lookup2(t, sym.data + 1, sym.size - 1, &v)) {
  1684. return false;
  1685. }
  1686. *def = unpack_def(v, type);
  1687. if (!*def) {
  1688. upb_status_seterrf(status,
  1689. "type mismatch when resolving field %s, name %s",
  1690. f->full_name, sym.data);
  1691. return false;
  1692. }
  1693. return true;
  1694. } else {
  1695. /* Remove components from base until we find an entry or run out.
  1696. * TODO: This branch is totally broken, but currently not used. */
  1697. (void)base;
  1698. UPB_ASSERT(false);
  1699. return false;
  1700. }
  1701. }
  1702. const void *symtab_resolve(const symtab_addctx *ctx, const upb_fielddef *f,
  1703. const char *base, upb_strview sym,
  1704. upb_deftype_t type) {
  1705. const void *ret;
  1706. if (!resolvename(ctx->addtab, f, base, sym, type, ctx->status, &ret) &&
  1707. !resolvename(&ctx->symtab->syms, f, base, sym, type, ctx->status, &ret)) {
  1708. if (upb_ok(ctx->status)) {
  1709. upb_status_seterrf(ctx->status, "couldn't resolve name '%s'", sym.data);
  1710. }
  1711. return false;
  1712. }
  1713. return ret;
  1714. }
  1715. static bool create_oneofdef(
  1716. const symtab_addctx *ctx, upb_msgdef *m,
  1717. const google_protobuf_OneofDescriptorProto *oneof_proto) {
  1718. upb_oneofdef *o;
  1719. upb_strview name = google_protobuf_OneofDescriptorProto_name(oneof_proto);
  1720. upb_value v;
  1721. o = (upb_oneofdef*)&m->oneofs[m->oneof_count++];
  1722. o->parent = m;
  1723. o->full_name = makefullname(ctx, m->full_name, name);
  1724. v = pack_def(o, UPB_DEFTYPE_ONEOF);
  1725. CHK_OOM(symtab_add(ctx, o->full_name, v));
  1726. CHK_OOM(upb_strtable_insert3(&m->ntof, name.data, name.size, v, ctx->alloc));
  1727. CHK_OOM(upb_inttable_init2(&o->itof, UPB_CTYPE_CONSTPTR, ctx->alloc));
  1728. CHK_OOM(upb_strtable_init2(&o->ntof, UPB_CTYPE_CONSTPTR, ctx->alloc));
  1729. return true;
  1730. }
  1731. static bool parse_default(const symtab_addctx *ctx, const char *str, size_t len,
  1732. upb_fielddef *f) {
  1733. char *end;
  1734. char nullz[64];
  1735. errno = 0;
  1736. switch (upb_fielddef_type(f)) {
  1737. case UPB_TYPE_INT32:
  1738. case UPB_TYPE_INT64:
  1739. case UPB_TYPE_UINT32:
  1740. case UPB_TYPE_UINT64:
  1741. case UPB_TYPE_DOUBLE:
  1742. case UPB_TYPE_FLOAT:
  1743. /* Standard C number parsing functions expect null-terminated strings. */
  1744. if (len >= sizeof(nullz) - 1) {
  1745. return false;
  1746. }
  1747. memcpy(nullz, str, len);
  1748. nullz[len] = '\0';
  1749. str = nullz;
  1750. break;
  1751. default:
  1752. break;
  1753. }
  1754. switch (upb_fielddef_type(f)) {
  1755. case UPB_TYPE_INT32: {
  1756. long val = strtol(str, &end, 0);
  1757. CHK(val <= INT32_MAX && val >= INT32_MIN && errno != ERANGE && !*end);
  1758. f->defaultval.sint = val;
  1759. break;
  1760. }
  1761. case UPB_TYPE_ENUM: {
  1762. const upb_enumdef *e = f->sub.enumdef;
  1763. int32_t val;
  1764. CHK(upb_enumdef_ntoi(e, str, len, &val));
  1765. f->defaultval.sint = val;
  1766. break;
  1767. }
  1768. case UPB_TYPE_INT64: {
  1769. /* XXX: Need to write our own strtoll, since it's not available in c89. */
  1770. long long val = strtol(str, &end, 0);
  1771. CHK(val <= INT64_MAX && val >= INT64_MIN && errno != ERANGE && !*end);
  1772. f->defaultval.sint = val;
  1773. break;
  1774. }
  1775. case UPB_TYPE_UINT32: {
  1776. unsigned long val = strtoul(str, &end, 0);
  1777. CHK(val <= UINT32_MAX && errno != ERANGE && !*end);
  1778. f->defaultval.uint = val;
  1779. break;
  1780. }
  1781. case UPB_TYPE_UINT64: {
  1782. /* XXX: Need to write our own strtoull, since it's not available in c89. */
  1783. unsigned long long val = strtoul(str, &end, 0);
  1784. CHK(val <= UINT64_MAX && errno != ERANGE && !*end);
  1785. f->defaultval.uint = val;
  1786. break;
  1787. }
  1788. case UPB_TYPE_DOUBLE: {
  1789. double val = strtod(str, &end);
  1790. CHK(errno != ERANGE && !*end);
  1791. f->defaultval.dbl = val;
  1792. break;
  1793. }
  1794. case UPB_TYPE_FLOAT: {
  1795. /* XXX: Need to write our own strtof, since it's not available in c89. */
  1796. float val = strtod(str, &end);
  1797. CHK(errno != ERANGE && !*end);
  1798. f->defaultval.flt = val;
  1799. break;
  1800. }
  1801. case UPB_TYPE_BOOL: {
  1802. if (streql2(str, len, "false")) {
  1803. f->defaultval.boolean = false;
  1804. } else if (streql2(str, len, "true")) {
  1805. f->defaultval.boolean = true;
  1806. } else {
  1807. return false;
  1808. }
  1809. }
  1810. case UPB_TYPE_STRING:
  1811. f->defaultval.str = newstr(ctx->alloc, str, len);
  1812. break;
  1813. case UPB_TYPE_BYTES:
  1814. /* XXX: need to interpret the C-escaped value. */
  1815. f->defaultval.str = newstr(ctx->alloc, str, len);
  1816. break;
  1817. case UPB_TYPE_MESSAGE:
  1818. /* Should not have a default value. */
  1819. return false;
  1820. }
  1821. return true;
  1822. }
  1823. static void set_default_default(const symtab_addctx *ctx, upb_fielddef *f) {
  1824. switch (upb_fielddef_type(f)) {
  1825. case UPB_TYPE_INT32:
  1826. case UPB_TYPE_INT64:
  1827. case UPB_TYPE_ENUM:
  1828. f->defaultval.sint = 0;
  1829. break;
  1830. case UPB_TYPE_UINT64:
  1831. case UPB_TYPE_UINT32:
  1832. f->defaultval.uint = 0;
  1833. break;
  1834. case UPB_TYPE_DOUBLE:
  1835. case UPB_TYPE_FLOAT:
  1836. f->defaultval.dbl = 0;
  1837. break;
  1838. case UPB_TYPE_STRING:
  1839. case UPB_TYPE_BYTES:
  1840. f->defaultval.str = newstr(ctx->alloc, NULL, 0);
  1841. break;
  1842. case UPB_TYPE_BOOL:
  1843. f->defaultval.boolean = false;
  1844. break;
  1845. case UPB_TYPE_MESSAGE:
  1846. break;
  1847. }
  1848. }
  1849. static bool create_fielddef(
  1850. const symtab_addctx *ctx, const char *prefix, upb_msgdef *m,
  1851. const google_protobuf_FieldDescriptorProto *field_proto) {
  1852. upb_alloc *alloc = ctx->alloc;
  1853. upb_fielddef *f;
  1854. const google_protobuf_FieldOptions *options;
  1855. upb_strview name;
  1856. const char *full_name;
  1857. const char *shortname;
  1858. uint32_t field_number;
  1859. if (!google_protobuf_FieldDescriptorProto_has_name(field_proto)) {
  1860. upb_status_seterrmsg(ctx->status, "field has no name");
  1861. return false;
  1862. }
  1863. name = google_protobuf_FieldDescriptorProto_name(field_proto);
  1864. CHK(upb_isident(name, false, ctx->status));
  1865. full_name = makefullname(ctx, prefix, name);
  1866. shortname = shortdefname(full_name);
  1867. field_number = google_protobuf_FieldDescriptorProto_number(field_proto);
  1868. if (field_number == 0 || field_number > UPB_MAX_FIELDNUMBER) {
  1869. upb_status_seterrf(ctx->status, "invalid field number (%u)", field_number);
  1870. return false;
  1871. }
  1872. if (m) {
  1873. /* direct message field. */
  1874. upb_value v, packed_v;
  1875. f = (upb_fielddef*)&m->fields[m->field_count++];
  1876. f->msgdef = m;
  1877. f->is_extension_ = false;
  1878. packed_v = pack_def(f, UPB_DEFTYPE_FIELD);
  1879. v = upb_value_constptr(f);
  1880. if (!upb_strtable_insert3(&m->ntof, name.data, name.size, packed_v, alloc)) {
  1881. upb_status_seterrf(ctx->status, "duplicate field name (%s)", shortname);
  1882. return false;
  1883. }
  1884. if (!upb_inttable_insert2(&m->itof, field_number, v, alloc)) {
  1885. upb_status_seterrf(ctx->status, "duplicate field number (%u)",
  1886. field_number);
  1887. return false;
  1888. }
  1889. } else {
  1890. /* extension field. */
  1891. f = (upb_fielddef*)&ctx->file->exts[ctx->file->ext_count];
  1892. f->is_extension_ = true;
  1893. CHK_OOM(symtab_add(ctx, full_name, pack_def(f, UPB_DEFTYPE_FIELD)));
  1894. }
  1895. f->full_name = full_name;
  1896. f->file = ctx->file;
  1897. f->type_ = (int)google_protobuf_FieldDescriptorProto_type(field_proto);
  1898. f->label_ = (int)google_protobuf_FieldDescriptorProto_label(field_proto);
  1899. f->number_ = field_number;
  1900. f->oneof = NULL;
  1901. /* We can't resolve the subdef or (in the case of extensions) the containing
  1902. * message yet, because it may not have been defined yet. We stash a pointer
  1903. * to the field_proto until later when we can properly resolve it. */
  1904. f->sub.unresolved = field_proto;
  1905. if (f->label_ == UPB_LABEL_REQUIRED && f->file->syntax == UPB_SYNTAX_PROTO3) {
  1906. upb_status_seterrf(ctx->status, "proto3 fields cannot be required (%s)",
  1907. f->full_name);
  1908. return false;
  1909. }
  1910. if (google_protobuf_FieldDescriptorProto_has_oneof_index(field_proto)) {
  1911. int oneof_index =
  1912. google_protobuf_FieldDescriptorProto_oneof_index(field_proto);
  1913. upb_oneofdef *oneof;
  1914. upb_value v = upb_value_constptr(f);
  1915. if (upb_fielddef_label(f) != UPB_LABEL_OPTIONAL) {
  1916. upb_status_seterrf(ctx->status,
  1917. "fields in oneof must have OPTIONAL label (%s)",
  1918. f->full_name);
  1919. return false;
  1920. }
  1921. if (!m) {
  1922. upb_status_seterrf(ctx->status,
  1923. "oneof_index provided for extension field (%s)",
  1924. f->full_name);
  1925. return false;
  1926. }
  1927. if (oneof_index >= m->oneof_count) {
  1928. upb_status_seterrf(ctx->status, "oneof_index out of range (%s)",
  1929. f->full_name);
  1930. return false;
  1931. }
  1932. oneof = (upb_oneofdef*)&m->oneofs[oneof_index];
  1933. f->oneof = oneof;
  1934. CHK(upb_inttable_insert2(&oneof->itof, f->number_, v, alloc));
  1935. CHK(upb_strtable_insert3(&oneof->ntof, name.data, name.size, v, alloc));
  1936. } else {
  1937. f->oneof = NULL;
  1938. }
  1939. if (google_protobuf_FieldDescriptorProto_has_options(field_proto)) {
  1940. options = google_protobuf_FieldDescriptorProto_options(field_proto);
  1941. f->lazy_ = google_protobuf_FieldOptions_lazy(options);
  1942. f->packed_ = google_protobuf_FieldOptions_packed(options);
  1943. } else {
  1944. f->lazy_ = false;
  1945. f->packed_ = false;
  1946. }
  1947. return true;
  1948. }
  1949. static bool create_enumdef(
  1950. const symtab_addctx *ctx, const char *prefix,
  1951. const google_protobuf_EnumDescriptorProto *enum_proto) {
  1952. upb_enumdef *e;
  1953. const google_protobuf_EnumValueDescriptorProto *const *values;
  1954. upb_strview name;
  1955. size_t i, n;
  1956. name = google_protobuf_EnumDescriptorProto_name(enum_proto);
  1957. CHK(upb_isident(name, false, ctx->status));
  1958. e = (upb_enumdef*)&ctx->file->enums[ctx->file->enum_count++];
  1959. e->full_name = makefullname(ctx, prefix, name);
  1960. CHK_OOM(symtab_add(ctx, e->full_name, pack_def(e, UPB_DEFTYPE_ENUM)));
  1961. CHK_OOM(upb_strtable_init2(&e->ntoi, UPB_CTYPE_INT32, ctx->alloc));
  1962. CHK_OOM(upb_inttable_init2(&e->iton, UPB_CTYPE_CSTR, ctx->alloc));
  1963. e->file = ctx->file;
  1964. e->defaultval = 0;
  1965. values = google_protobuf_EnumDescriptorProto_value(enum_proto, &n);
  1966. if (n == 0) {
  1967. upb_status_seterrf(ctx->status,
  1968. "enums must contain at least one value (%s)",
  1969. e->full_name);
  1970. return false;
  1971. }
  1972. for (i = 0; i < n; i++) {
  1973. const google_protobuf_EnumValueDescriptorProto *value = values[i];
  1974. upb_strview name = google_protobuf_EnumValueDescriptorProto_name(value);
  1975. char *name2 = strviewdup(ctx, name);
  1976. int32_t num = google_protobuf_EnumValueDescriptorProto_number(value);
  1977. upb_value v = upb_value_int32(num);
  1978. if (i == 0 && e->file->syntax == UPB_SYNTAX_PROTO3 && num != 0) {
  1979. upb_status_seterrf(ctx->status,
  1980. "for proto3, the first enum value must be zero (%s)",
  1981. e->full_name);
  1982. return false;
  1983. }
  1984. if (upb_strtable_lookup(&e->ntoi, name2, NULL)) {
  1985. upb_status_seterrf(ctx->status, "duplicate enum label '%s'", name2);
  1986. return false;
  1987. }
  1988. CHK_OOM(name2)
  1989. CHK_OOM(
  1990. upb_strtable_insert3(&e->ntoi, name2, strlen(name2), v, ctx->alloc));
  1991. if (!upb_inttable_lookup(&e->iton, num, NULL)) {
  1992. upb_value v = upb_value_cstr(name2);
  1993. CHK_OOM(upb_inttable_insert2(&e->iton, num, v, ctx->alloc));
  1994. }
  1995. }
  1996. upb_inttable_compact2(&e->iton, ctx->alloc);
  1997. return true;
  1998. }
  1999. static bool create_msgdef(const symtab_addctx *ctx, const char *prefix,
  2000. const google_protobuf_DescriptorProto *msg_proto) {
  2001. upb_msgdef *m;
  2002. const google_protobuf_MessageOptions *options;
  2003. const google_protobuf_OneofDescriptorProto *const *oneofs;
  2004. const google_protobuf_FieldDescriptorProto *const *fields;
  2005. const google_protobuf_EnumDescriptorProto *const *enums;
  2006. const google_protobuf_DescriptorProto *const *msgs;
  2007. size_t i, n;
  2008. upb_strview name;
  2009. name = google_protobuf_DescriptorProto_name(msg_proto);
  2010. CHK(upb_isident(name, false, ctx->status));
  2011. m = (upb_msgdef*)&ctx->file->msgs[ctx->file->msg_count++];
  2012. m->full_name = makefullname(ctx, prefix, name);
  2013. CHK_OOM(symtab_add(ctx, m->full_name, pack_def(m, UPB_DEFTYPE_MSG)));
  2014. CHK_OOM(upb_inttable_init2(&m->itof, UPB_CTYPE_CONSTPTR, ctx->alloc));
  2015. CHK_OOM(upb_strtable_init2(&m->ntof, UPB_CTYPE_CONSTPTR, ctx->alloc));
  2016. m->file = ctx->file;
  2017. m->map_entry = false;
  2018. options = google_protobuf_DescriptorProto_options(msg_proto);
  2019. if (options) {
  2020. m->map_entry = google_protobuf_MessageOptions_map_entry(options);
  2021. }
  2022. oneofs = google_protobuf_DescriptorProto_oneof_decl(msg_proto, &n);
  2023. m->oneof_count = 0;
  2024. m->oneofs = upb_malloc(ctx->alloc, sizeof(*m->oneofs) * n);
  2025. for (i = 0; i < n; i++) {
  2026. CHK(create_oneofdef(ctx, m, oneofs[i]));
  2027. }
  2028. fields = google_protobuf_DescriptorProto_field(msg_proto, &n);
  2029. m->field_count = 0;
  2030. m->fields = upb_malloc(ctx->alloc, sizeof(*m->fields) * n);
  2031. for (i = 0; i < n; i++) {
  2032. CHK(create_fielddef(ctx, m->full_name, m, fields[i]));
  2033. }
  2034. CHK(assign_msg_indices(m, ctx->status));
  2035. assign_msg_wellknowntype(m);
  2036. upb_inttable_compact2(&m->itof, ctx->alloc);
  2037. /* This message is built. Now build nested messages and enums. */
  2038. enums = google_protobuf_DescriptorProto_enum_type(msg_proto, &n);
  2039. for (i = 0; i < n; i++) {
  2040. CHK(create_enumdef(ctx, m->full_name, enums[i]));
  2041. }
  2042. msgs = google_protobuf_DescriptorProto_nested_type(msg_proto, &n);
  2043. for (i = 0; i < n; i++) {
  2044. CHK(create_msgdef(ctx, m->full_name, msgs[i]));
  2045. }
  2046. return true;
  2047. }
  2048. typedef struct {
  2049. int msg_count;
  2050. int enum_count;
  2051. int ext_count;
  2052. } decl_counts;
  2053. static void count_types_in_msg(const google_protobuf_DescriptorProto *msg_proto,
  2054. decl_counts *counts) {
  2055. const google_protobuf_DescriptorProto *const *msgs;
  2056. size_t i, n;
  2057. counts->msg_count++;
  2058. msgs = google_protobuf_DescriptorProto_nested_type(msg_proto, &n);
  2059. for (i = 0; i < n; i++) {
  2060. count_types_in_msg(msgs[i], counts);
  2061. }
  2062. google_protobuf_DescriptorProto_enum_type(msg_proto, &n);
  2063. counts->enum_count += n;
  2064. google_protobuf_DescriptorProto_extension(msg_proto, &n);
  2065. counts->ext_count += n;
  2066. }
  2067. static void count_types_in_file(
  2068. const google_protobuf_FileDescriptorProto *file_proto,
  2069. decl_counts *counts) {
  2070. const google_protobuf_DescriptorProto *const *msgs;
  2071. size_t i, n;
  2072. msgs = google_protobuf_FileDescriptorProto_message_type(file_proto, &n);
  2073. for (i = 0; i < n; i++) {
  2074. count_types_in_msg(msgs[i], counts);
  2075. }
  2076. google_protobuf_FileDescriptorProto_enum_type(file_proto, &n);
  2077. counts->enum_count += n;
  2078. google_protobuf_FileDescriptorProto_extension(file_proto, &n);
  2079. counts->ext_count += n;
  2080. }
  2081. static bool resolve_fielddef(const symtab_addctx *ctx, const char *prefix,
  2082. upb_fielddef *f) {
  2083. upb_strview name;
  2084. const google_protobuf_FieldDescriptorProto *field_proto = f->sub.unresolved;
  2085. if (f->is_extension_) {
  2086. if (!google_protobuf_FieldDescriptorProto_has_extendee(field_proto)) {
  2087. upb_status_seterrf(ctx->status,
  2088. "extension for field '%s' had no extendee",
  2089. f->full_name);
  2090. return false;
  2091. }
  2092. name = google_protobuf_FieldDescriptorProto_extendee(field_proto);
  2093. f->msgdef = symtab_resolve(ctx, f, prefix, name, UPB_DEFTYPE_MSG);
  2094. CHK(f->msgdef);
  2095. }
  2096. if ((upb_fielddef_issubmsg(f) || f->type_ == UPB_DESCRIPTOR_TYPE_ENUM) &&
  2097. !google_protobuf_FieldDescriptorProto_has_type_name(field_proto)) {
  2098. upb_status_seterrf(ctx->status, "field '%s' is missing type name",
  2099. f->full_name);
  2100. return false;
  2101. }
  2102. name = google_protobuf_FieldDescriptorProto_type_name(field_proto);
  2103. if (upb_fielddef_issubmsg(f)) {
  2104. f->sub.msgdef = symtab_resolve(ctx, f, prefix, name, UPB_DEFTYPE_MSG);
  2105. CHK(f->sub.msgdef);
  2106. } else if (f->type_ == UPB_DESCRIPTOR_TYPE_ENUM) {
  2107. f->sub.enumdef = symtab_resolve(ctx, f, prefix, name, UPB_DEFTYPE_ENUM);
  2108. CHK(f->sub.enumdef);
  2109. }
  2110. /* Have to delay resolving of the default value until now because of the enum
  2111. * case, since enum defaults are specified with a label. */
  2112. if (google_protobuf_FieldDescriptorProto_has_default_value(field_proto)) {
  2113. upb_strview defaultval =
  2114. google_protobuf_FieldDescriptorProto_default_value(field_proto);
  2115. if (f->file->syntax == UPB_SYNTAX_PROTO3) {
  2116. upb_status_seterrf(ctx->status,
  2117. "proto3 fields cannot have explicit defaults (%s)",
  2118. f->full_name);
  2119. return false;
  2120. }
  2121. if (upb_fielddef_issubmsg(f)) {
  2122. upb_status_seterrf(ctx->status,
  2123. "message fields cannot have explicit defaults (%s)",
  2124. f->full_name);
  2125. return false;
  2126. }
  2127. if (!parse_default(ctx, defaultval.data, defaultval.size, f)) {
  2128. upb_status_seterrf(ctx->status,
  2129. "couldn't parse default '" UPB_STRVIEW_FORMAT
  2130. "' for field (%s)",
  2131. UPB_STRVIEW_ARGS(defaultval), f->full_name);
  2132. return false;
  2133. }
  2134. } else {
  2135. set_default_default(ctx, f);
  2136. }
  2137. return true;
  2138. }
  2139. static bool build_filedef(
  2140. const symtab_addctx *ctx, upb_filedef *file,
  2141. const google_protobuf_FileDescriptorProto *file_proto) {
  2142. upb_alloc *alloc = ctx->alloc;
  2143. const google_protobuf_FileOptions *file_options_proto;
  2144. const google_protobuf_DescriptorProto *const *msgs;
  2145. const google_protobuf_EnumDescriptorProto *const *enums;
  2146. const google_protobuf_FieldDescriptorProto *const *exts;
  2147. const upb_strview* strs;
  2148. size_t i, n;
  2149. decl_counts counts = {0};
  2150. count_types_in_file(file_proto, &counts);
  2151. file->msgs = upb_malloc(alloc, sizeof(*file->msgs) * counts.msg_count);
  2152. file->enums = upb_malloc(alloc, sizeof(*file->enums) * counts.enum_count);
  2153. file->exts = upb_malloc(alloc, sizeof(*file->exts) * counts.ext_count);
  2154. CHK_OOM(counts.msg_count == 0 || file->msgs);
  2155. CHK_OOM(counts.enum_count == 0 || file->enums);
  2156. CHK_OOM(counts.ext_count == 0 || file->exts);
  2157. /* We increment these as defs are added. */
  2158. file->msg_count = 0;
  2159. file->enum_count = 0;
  2160. file->ext_count = 0;
  2161. if (!google_protobuf_FileDescriptorProto_has_name(file_proto)) {
  2162. upb_status_seterrmsg(ctx->status, "File has no name");
  2163. return false;
  2164. }
  2165. file->name =
  2166. strviewdup(ctx, google_protobuf_FileDescriptorProto_name(file_proto));
  2167. file->phpprefix = NULL;
  2168. file->phpnamespace = NULL;
  2169. if (google_protobuf_FileDescriptorProto_has_package(file_proto)) {
  2170. upb_strview package =
  2171. google_protobuf_FileDescriptorProto_package(file_proto);
  2172. CHK(upb_isident(package, true, ctx->status));
  2173. file->package = strviewdup(ctx, package);
  2174. } else {
  2175. file->package = NULL;
  2176. }
  2177. if (google_protobuf_FileDescriptorProto_has_syntax(file_proto)) {
  2178. upb_strview syntax =
  2179. google_protobuf_FileDescriptorProto_syntax(file_proto);
  2180. if (streql_view(syntax, "proto2")) {
  2181. file->syntax = UPB_SYNTAX_PROTO2;
  2182. } else if (streql_view(syntax, "proto3")) {
  2183. file->syntax = UPB_SYNTAX_PROTO3;
  2184. } else {
  2185. upb_status_seterrf(ctx->status, "Invalid syntax '%s'", syntax);
  2186. return false;
  2187. }
  2188. } else {
  2189. file->syntax = UPB_SYNTAX_PROTO2;
  2190. }
  2191. /* Read options. */
  2192. file_options_proto = google_protobuf_FileDescriptorProto_options(file_proto);
  2193. if (file_options_proto) {
  2194. if (google_protobuf_FileOptions_has_php_class_prefix(file_options_proto)) {
  2195. file->phpprefix = strviewdup(
  2196. ctx,
  2197. google_protobuf_FileOptions_php_class_prefix(file_options_proto));
  2198. }
  2199. if (google_protobuf_FileOptions_has_php_namespace(file_options_proto)) {
  2200. file->phpnamespace = strviewdup(
  2201. ctx, google_protobuf_FileOptions_php_namespace(file_options_proto));
  2202. }
  2203. }
  2204. /* Verify dependencies. */
  2205. strs = google_protobuf_FileDescriptorProto_dependency(file_proto, &n);
  2206. file->deps = upb_malloc(alloc, sizeof(*file->deps) * n) ;
  2207. CHK_OOM(n == 0 || file->deps);
  2208. for (i = 0; i < n; i++) {
  2209. upb_strview dep_name = strs[i];
  2210. upb_value v;
  2211. if (!upb_strtable_lookup2(&ctx->symtab->files, dep_name.data,
  2212. dep_name.size, &v)) {
  2213. upb_status_seterrf(ctx->status,
  2214. "Depends on file '" UPB_STRVIEW_FORMAT
  2215. "', but it has not been loaded",
  2216. UPB_STRVIEW_ARGS(dep_name));
  2217. return false;
  2218. }
  2219. file->deps[i] = upb_value_getconstptr(v);
  2220. }
  2221. /* Create messages. */
  2222. msgs = google_protobuf_FileDescriptorProto_message_type(file_proto, &n);
  2223. for (i = 0; i < n; i++) {
  2224. CHK(create_msgdef(ctx, file->package, msgs[i]));
  2225. }
  2226. /* Create enums. */
  2227. enums = google_protobuf_FileDescriptorProto_enum_type(file_proto, &n);
  2228. for (i = 0; i < n; i++) {
  2229. CHK(create_enumdef(ctx, file->package, enums[i]));
  2230. }
  2231. /* Create extensions. */
  2232. exts = google_protobuf_FileDescriptorProto_extension(file_proto, &n);
  2233. file->exts = upb_malloc(alloc, sizeof(*file->exts) * n);
  2234. CHK_OOM(n == 0 || file->exts);
  2235. for (i = 0; i < n; i++) {
  2236. CHK(create_fielddef(ctx, file->package, NULL, exts[i]));
  2237. }
  2238. /* Now that all names are in the table, resolve references. */
  2239. for (i = 0; i < file->ext_count; i++) {
  2240. CHK(resolve_fielddef(ctx, file->package, (upb_fielddef*)&file->exts[i]));
  2241. }
  2242. for (i = 0; i < file->msg_count; i++) {
  2243. const upb_msgdef *m = &file->msgs[i];
  2244. int j;
  2245. for (j = 0; j < m->field_count; j++) {
  2246. CHK(resolve_fielddef(ctx, m->full_name, (upb_fielddef*)&m->fields[j]));
  2247. }
  2248. }
  2249. return true;
  2250. }
  2251. static bool upb_symtab_addtotabs(upb_symtab *s, symtab_addctx *ctx,
  2252. upb_status *status) {
  2253. const upb_filedef *file = ctx->file;
  2254. upb_alloc *alloc = upb_arena_alloc(s->arena);
  2255. upb_strtable_iter iter;
  2256. CHK_OOM(upb_strtable_insert3(&s->files, file->name, strlen(file->name),
  2257. upb_value_constptr(file), alloc));
  2258. upb_strtable_begin(&iter, ctx->addtab);
  2259. for (; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
  2260. const char *key = upb_strtable_iter_key(&iter);
  2261. size_t keylen = upb_strtable_iter_keylength(&iter);
  2262. upb_value value = upb_strtable_iter_value(&iter);
  2263. CHK_OOM(upb_strtable_insert3(&s->syms, key, keylen, value, alloc));
  2264. }
  2265. return true;
  2266. }
  2267. /* upb_filedef ****************************************************************/
  2268. const char *upb_filedef_name(const upb_filedef *f) {
  2269. return f->name;
  2270. }
  2271. const char *upb_filedef_package(const upb_filedef *f) {
  2272. return f->package;
  2273. }
  2274. const char *upb_filedef_phpprefix(const upb_filedef *f) {
  2275. return f->phpprefix;
  2276. }
  2277. const char *upb_filedef_phpnamespace(const upb_filedef *f) {
  2278. return f->phpnamespace;
  2279. }
  2280. upb_syntax_t upb_filedef_syntax(const upb_filedef *f) {
  2281. return f->syntax;
  2282. }
  2283. int upb_filedef_msgcount(const upb_filedef *f) {
  2284. return f->msg_count;
  2285. }
  2286. int upb_filedef_depcount(const upb_filedef *f) {
  2287. return f->dep_count;
  2288. }
  2289. int upb_filedef_enumcount(const upb_filedef *f) {
  2290. return f->enum_count;
  2291. }
  2292. const upb_filedef *upb_filedef_dep(const upb_filedef *f, int i) {
  2293. return i < 0 || i >= f->dep_count ? NULL : f->deps[i];
  2294. }
  2295. const upb_msgdef *upb_filedef_msg(const upb_filedef *f, int i) {
  2296. return i < 0 || i >= f->msg_count ? NULL : &f->msgs[i];
  2297. }
  2298. const upb_enumdef *upb_filedef_enum(const upb_filedef *f, int i) {
  2299. return i < 0 || i >= f->enum_count ? NULL : &f->enums[i];
  2300. }
  2301. void upb_symtab_free(upb_symtab *s) {
  2302. upb_arena_free(s->arena);
  2303. upb_gfree(s);
  2304. }
  2305. upb_symtab *upb_symtab_new() {
  2306. upb_symtab *s = upb_gmalloc(sizeof(*s));
  2307. upb_alloc *alloc;
  2308. if (!s) {
  2309. return NULL;
  2310. }
  2311. s->arena = upb_arena_new();
  2312. alloc = upb_arena_alloc(s->arena);
  2313. if (!upb_strtable_init2(&s->syms, UPB_CTYPE_CONSTPTR, alloc) ||
  2314. !upb_strtable_init2(&s->files, UPB_CTYPE_CONSTPTR, alloc)) {
  2315. upb_arena_free(s->arena);
  2316. upb_gfree(s);
  2317. s = NULL;
  2318. }
  2319. return s;
  2320. }
  2321. const upb_msgdef *upb_symtab_lookupmsg(const upb_symtab *s, const char *sym) {
  2322. upb_value v;
  2323. return upb_strtable_lookup(&s->syms, sym, &v) ?
  2324. unpack_def(v, UPB_DEFTYPE_MSG) : NULL;
  2325. }
  2326. const upb_msgdef *upb_symtab_lookupmsg2(const upb_symtab *s, const char *sym,
  2327. size_t len) {
  2328. upb_value v;
  2329. return upb_strtable_lookup2(&s->syms, sym, len, &v) ?
  2330. unpack_def(v, UPB_DEFTYPE_MSG) : NULL;
  2331. }
  2332. const upb_enumdef *upb_symtab_lookupenum(const upb_symtab *s, const char *sym) {
  2333. upb_value v;
  2334. return upb_strtable_lookup(&s->syms, sym, &v) ?
  2335. unpack_def(v, UPB_DEFTYPE_ENUM) : NULL;
  2336. }
  2337. const upb_filedef *upb_symtab_lookupfile(const upb_symtab *s, const char *name) {
  2338. upb_value v;
  2339. return upb_strtable_lookup(&s->files, name, &v) ? upb_value_getconstptr(v)
  2340. : NULL;
  2341. }
  2342. const upb_filedef *upb_symtab_addfile(
  2343. upb_symtab *s, const google_protobuf_FileDescriptorProto *file_proto,
  2344. upb_status *status) {
  2345. upb_arena *tmparena = upb_arena_new();
  2346. upb_strtable addtab;
  2347. upb_alloc *alloc = upb_arena_alloc(s->arena);
  2348. upb_filedef *file = upb_malloc(alloc, sizeof(*file));
  2349. bool ok;
  2350. symtab_addctx ctx;
  2351. ctx.file = file;
  2352. ctx.symtab = s;
  2353. ctx.alloc = alloc;
  2354. ctx.tmp = upb_arena_alloc(tmparena);
  2355. ctx.addtab = &addtab;
  2356. ctx.status = status;
  2357. ok = file &&
  2358. upb_strtable_init2(&addtab, UPB_CTYPE_CONSTPTR, ctx.tmp) &&
  2359. build_filedef(&ctx, file, file_proto) &&
  2360. upb_symtab_addtotabs(s, &ctx, status);
  2361. upb_arena_free(tmparena);
  2362. return ok ? file : NULL;
  2363. }
  2364. /* Include here since we want most of this file to be stdio-free. */
  2365. #include <stdio.h>
  2366. bool _upb_symtab_loaddefinit(upb_symtab *s, const upb_def_init *init) {
  2367. /* Since this function should never fail (it would indicate a bug in upb) we
  2368. * print errors to stderr instead of returning error status to the user. */
  2369. upb_def_init **deps = init->deps;
  2370. google_protobuf_FileDescriptorProto *file;
  2371. upb_arena *arena;
  2372. upb_status status;
  2373. upb_status_clear(&status);
  2374. if (upb_strtable_lookup(&s->files, init->filename, NULL)) {
  2375. return true;
  2376. }
  2377. arena = upb_arena_new();
  2378. for (; *deps; deps++) {
  2379. if (!_upb_symtab_loaddefinit(s, *deps)) goto err;
  2380. }
  2381. file = google_protobuf_FileDescriptorProto_parse(
  2382. init->descriptor.data, init->descriptor.size, arena);
  2383. if (!file) {
  2384. upb_status_seterrf(
  2385. &status,
  2386. "Failed to parse compiled-in descriptor for file '%s'. This should "
  2387. "never happen.",
  2388. init->filename);
  2389. goto err;
  2390. }
  2391. if (!upb_symtab_addfile(s, file, &status)) goto err;
  2392. upb_arena_free(arena);
  2393. return true;
  2394. err:
  2395. fprintf(stderr, "Error loading compiled-in descriptor: %s\n",
  2396. upb_status_errmsg(&status));
  2397. upb_arena_free(arena);
  2398. return false;
  2399. }
  2400. #undef CHK
  2401. #undef CHK_OOM
  2402. /* We encode backwards, to avoid pre-computing lengths (one-pass encode). */
  2403. #include <string.h>
  2404. #define UPB_PB_VARINT_MAX_LEN 10
  2405. #define CHK(x) do { if (!(x)) { return false; } } while(0)
  2406. /* Maps descriptor type -> upb field type. */
  2407. static const uint8_t upb_desctype_to_fieldtype2[] = {
  2408. UPB_WIRE_TYPE_END_GROUP, /* ENDGROUP */
  2409. UPB_TYPE_DOUBLE, /* DOUBLE */
  2410. UPB_TYPE_FLOAT, /* FLOAT */
  2411. UPB_TYPE_INT64, /* INT64 */
  2412. UPB_TYPE_UINT64, /* UINT64 */
  2413. UPB_TYPE_INT32, /* INT32 */
  2414. UPB_TYPE_UINT64, /* FIXED64 */
  2415. UPB_TYPE_UINT32, /* FIXED32 */
  2416. UPB_TYPE_BOOL, /* BOOL */
  2417. UPB_TYPE_STRING, /* STRING */
  2418. UPB_TYPE_MESSAGE, /* GROUP */
  2419. UPB_TYPE_MESSAGE, /* MESSAGE */
  2420. UPB_TYPE_BYTES, /* BYTES */
  2421. UPB_TYPE_UINT32, /* UINT32 */
  2422. UPB_TYPE_ENUM, /* ENUM */
  2423. UPB_TYPE_INT32, /* SFIXED32 */
  2424. UPB_TYPE_INT64, /* SFIXED64 */
  2425. UPB_TYPE_INT32, /* SINT32 */
  2426. UPB_TYPE_INT64, /* SINT64 */
  2427. };
  2428. static size_t upb_encode_varint(uint64_t val, char *buf) {
  2429. size_t i;
  2430. if (val < 128) { buf[0] = val; return 1; }
  2431. i = 0;
  2432. while (val) {
  2433. uint8_t byte = val & 0x7fU;
  2434. val >>= 7;
  2435. if (val) byte |= 0x80U;
  2436. buf[i++] = byte;
  2437. }
  2438. return i;
  2439. }
  2440. static uint32_t upb_zzencode_32(int32_t n) { return (n << 1) ^ (n >> 31); }
  2441. static uint64_t upb_zzencode_64(int64_t n) { return (n << 1) ^ (n >> 63); }
  2442. typedef struct {
  2443. upb_alloc *alloc;
  2444. char *buf, *ptr, *limit;
  2445. } upb_encstate;
  2446. static size_t upb_roundup_pow2(size_t bytes) {
  2447. size_t ret = 128;
  2448. while (ret < bytes) {
  2449. ret *= 2;
  2450. }
  2451. return ret;
  2452. }
  2453. static bool upb_encode_growbuffer(upb_encstate *e, size_t bytes) {
  2454. size_t old_size = e->limit - e->buf;
  2455. size_t new_size = upb_roundup_pow2(bytes + (e->limit - e->ptr));
  2456. char *new_buf = upb_realloc(e->alloc, e->buf, old_size, new_size);
  2457. CHK(new_buf);
  2458. /* We want previous data at the end, realloc() put it at the beginning. */
  2459. memmove(new_buf + new_size - old_size, e->buf, old_size);
  2460. e->ptr = new_buf + new_size - (e->limit - e->ptr);
  2461. e->limit = new_buf + new_size;
  2462. e->buf = new_buf;
  2463. return true;
  2464. }
  2465. /* Call to ensure that at least "bytes" bytes are available for writing at
  2466. * e->ptr. Returns false if the bytes could not be allocated. */
  2467. static bool upb_encode_reserve(upb_encstate *e, size_t bytes) {
  2468. CHK(UPB_LIKELY((size_t)(e->ptr - e->buf) >= bytes) ||
  2469. upb_encode_growbuffer(e, bytes));
  2470. e->ptr -= bytes;
  2471. return true;
  2472. }
  2473. /* Writes the given bytes to the buffer, handling reserve/advance. */
  2474. static bool upb_put_bytes(upb_encstate *e, const void *data, size_t len) {
  2475. CHK(upb_encode_reserve(e, len));
  2476. memcpy(e->ptr, data, len);
  2477. return true;
  2478. }
  2479. static bool upb_put_fixed64(upb_encstate *e, uint64_t val) {
  2480. /* TODO(haberman): byte-swap for big endian. */
  2481. return upb_put_bytes(e, &val, sizeof(uint64_t));
  2482. }
  2483. static bool upb_put_fixed32(upb_encstate *e, uint32_t val) {
  2484. /* TODO(haberman): byte-swap for big endian. */
  2485. return upb_put_bytes(e, &val, sizeof(uint32_t));
  2486. }
  2487. static bool upb_put_varint(upb_encstate *e, uint64_t val) {
  2488. size_t len;
  2489. char *start;
  2490. CHK(upb_encode_reserve(e, UPB_PB_VARINT_MAX_LEN));
  2491. len = upb_encode_varint(val, e->ptr);
  2492. start = e->ptr + UPB_PB_VARINT_MAX_LEN - len;
  2493. memmove(start, e->ptr, len);
  2494. e->ptr = start;
  2495. return true;
  2496. }
  2497. static bool upb_put_double(upb_encstate *e, double d) {
  2498. uint64_t u64;
  2499. UPB_ASSERT(sizeof(double) == sizeof(uint64_t));
  2500. memcpy(&u64, &d, sizeof(uint64_t));
  2501. return upb_put_fixed64(e, u64);
  2502. }
  2503. static bool upb_put_float(upb_encstate *e, float d) {
  2504. uint32_t u32;
  2505. UPB_ASSERT(sizeof(float) == sizeof(uint32_t));
  2506. memcpy(&u32, &d, sizeof(uint32_t));
  2507. return upb_put_fixed32(e, u32);
  2508. }
  2509. static uint32_t upb_readcase(const char *msg, const upb_msglayout_field *f) {
  2510. uint32_t ret;
  2511. uint32_t offset = ~f->presence;
  2512. memcpy(&ret, msg + offset, sizeof(ret));
  2513. return ret;
  2514. }
  2515. static bool upb_readhasbit(const char *msg, const upb_msglayout_field *f) {
  2516. uint32_t hasbit = f->presence;
  2517. UPB_ASSERT(f->presence > 0);
  2518. return msg[hasbit / 8] & (1 << (hasbit % 8));
  2519. }
  2520. static bool upb_put_tag(upb_encstate *e, int field_number, int wire_type) {
  2521. return upb_put_varint(e, (field_number << 3) | wire_type);
  2522. }
  2523. static bool upb_put_fixedarray(upb_encstate *e, const upb_array *arr,
  2524. size_t size) {
  2525. size_t bytes = arr->len * size;
  2526. return upb_put_bytes(e, arr->data, bytes) && upb_put_varint(e, bytes);
  2527. }
  2528. bool upb_encode_message(upb_encstate *e, const char *msg,
  2529. const upb_msglayout *m, size_t *size);
  2530. static bool upb_encode_array(upb_encstate *e, const char *field_mem,
  2531. const upb_msglayout *m,
  2532. const upb_msglayout_field *f) {
  2533. const upb_array *arr = *(const upb_array**)field_mem;
  2534. if (arr == NULL || arr->len == 0) {
  2535. return true;
  2536. }
  2537. UPB_ASSERT(arr->type == upb_desctype_to_fieldtype2[f->descriptortype]);
  2538. #define VARINT_CASE(ctype, encode) { \
  2539. ctype *start = arr->data; \
  2540. ctype *ptr = start + arr->len; \
  2541. size_t pre_len = e->limit - e->ptr; \
  2542. do { \
  2543. ptr--; \
  2544. CHK(upb_put_varint(e, encode)); \
  2545. } while (ptr != start); \
  2546. CHK(upb_put_varint(e, e->limit - e->ptr - pre_len)); \
  2547. } \
  2548. break; \
  2549. do { ; } while(0)
  2550. switch (f->descriptortype) {
  2551. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  2552. CHK(upb_put_fixedarray(e, arr, sizeof(double)));
  2553. break;
  2554. case UPB_DESCRIPTOR_TYPE_FLOAT:
  2555. CHK(upb_put_fixedarray(e, arr, sizeof(float)));
  2556. break;
  2557. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  2558. case UPB_DESCRIPTOR_TYPE_FIXED64:
  2559. CHK(upb_put_fixedarray(e, arr, sizeof(uint64_t)));
  2560. break;
  2561. case UPB_DESCRIPTOR_TYPE_FIXED32:
  2562. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  2563. CHK(upb_put_fixedarray(e, arr, sizeof(uint32_t)));
  2564. break;
  2565. case UPB_DESCRIPTOR_TYPE_INT64:
  2566. case UPB_DESCRIPTOR_TYPE_UINT64:
  2567. VARINT_CASE(uint64_t, *ptr);
  2568. case UPB_DESCRIPTOR_TYPE_UINT32:
  2569. VARINT_CASE(uint32_t, *ptr);
  2570. case UPB_DESCRIPTOR_TYPE_INT32:
  2571. case UPB_DESCRIPTOR_TYPE_ENUM:
  2572. VARINT_CASE(int32_t, (int64_t)*ptr);
  2573. case UPB_DESCRIPTOR_TYPE_BOOL:
  2574. VARINT_CASE(bool, *ptr);
  2575. case UPB_DESCRIPTOR_TYPE_SINT32:
  2576. VARINT_CASE(int32_t, upb_zzencode_32(*ptr));
  2577. case UPB_DESCRIPTOR_TYPE_SINT64:
  2578. VARINT_CASE(int64_t, upb_zzencode_64(*ptr));
  2579. case UPB_DESCRIPTOR_TYPE_STRING:
  2580. case UPB_DESCRIPTOR_TYPE_BYTES: {
  2581. upb_strview *start = arr->data;
  2582. upb_strview *ptr = start + arr->len;
  2583. do {
  2584. ptr--;
  2585. CHK(upb_put_bytes(e, ptr->data, ptr->size) &&
  2586. upb_put_varint(e, ptr->size) &&
  2587. upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
  2588. } while (ptr != start);
  2589. return true;
  2590. }
  2591. case UPB_DESCRIPTOR_TYPE_GROUP: {
  2592. void **start = arr->data;
  2593. void **ptr = start + arr->len;
  2594. const upb_msglayout *subm = m->submsgs[f->submsg_index];
  2595. do {
  2596. size_t size;
  2597. ptr--;
  2598. CHK(upb_put_tag(e, f->number, UPB_WIRE_TYPE_END_GROUP) &&
  2599. upb_encode_message(e, *ptr, subm, &size) &&
  2600. upb_put_tag(e, f->number, UPB_WIRE_TYPE_START_GROUP));
  2601. } while (ptr != start);
  2602. return true;
  2603. }
  2604. case UPB_DESCRIPTOR_TYPE_MESSAGE: {
  2605. void **start = arr->data;
  2606. void **ptr = start + arr->len;
  2607. const upb_msglayout *subm = m->submsgs[f->submsg_index];
  2608. do {
  2609. size_t size;
  2610. ptr--;
  2611. CHK(upb_encode_message(e, *ptr, subm, &size) &&
  2612. upb_put_varint(e, size) &&
  2613. upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
  2614. } while (ptr != start);
  2615. return true;
  2616. }
  2617. }
  2618. #undef VARINT_CASE
  2619. /* We encode all primitive arrays as packed, regardless of what was specified
  2620. * in the .proto file. Could special case 1-sized arrays. */
  2621. CHK(upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
  2622. return true;
  2623. }
  2624. static bool upb_encode_scalarfield(upb_encstate *e, const char *field_mem,
  2625. const upb_msglayout *m,
  2626. const upb_msglayout_field *f,
  2627. bool skip_zero_value) {
  2628. #define CASE(ctype, type, wire_type, encodeval) do { \
  2629. ctype val = *(ctype*)field_mem; \
  2630. if (skip_zero_value && val == 0) { \
  2631. return true; \
  2632. } \
  2633. return upb_put_ ## type(e, encodeval) && \
  2634. upb_put_tag(e, f->number, wire_type); \
  2635. } while(0)
  2636. switch (f->descriptortype) {
  2637. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  2638. CASE(double, double, UPB_WIRE_TYPE_64BIT, val);
  2639. case UPB_DESCRIPTOR_TYPE_FLOAT:
  2640. CASE(float, float, UPB_WIRE_TYPE_32BIT, val);
  2641. case UPB_DESCRIPTOR_TYPE_INT64:
  2642. case UPB_DESCRIPTOR_TYPE_UINT64:
  2643. CASE(uint64_t, varint, UPB_WIRE_TYPE_VARINT, val);
  2644. case UPB_DESCRIPTOR_TYPE_UINT32:
  2645. CASE(uint32_t, varint, UPB_WIRE_TYPE_VARINT, val);
  2646. case UPB_DESCRIPTOR_TYPE_INT32:
  2647. case UPB_DESCRIPTOR_TYPE_ENUM:
  2648. CASE(int32_t, varint, UPB_WIRE_TYPE_VARINT, (int64_t)val);
  2649. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  2650. case UPB_DESCRIPTOR_TYPE_FIXED64:
  2651. CASE(uint64_t, fixed64, UPB_WIRE_TYPE_64BIT, val);
  2652. case UPB_DESCRIPTOR_TYPE_FIXED32:
  2653. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  2654. CASE(uint32_t, fixed32, UPB_WIRE_TYPE_32BIT, val);
  2655. case UPB_DESCRIPTOR_TYPE_BOOL:
  2656. CASE(bool, varint, UPB_WIRE_TYPE_VARINT, val);
  2657. case UPB_DESCRIPTOR_TYPE_SINT32:
  2658. CASE(int32_t, varint, UPB_WIRE_TYPE_VARINT, upb_zzencode_32(val));
  2659. case UPB_DESCRIPTOR_TYPE_SINT64:
  2660. CASE(int64_t, varint, UPB_WIRE_TYPE_VARINT, upb_zzencode_64(val));
  2661. case UPB_DESCRIPTOR_TYPE_STRING:
  2662. case UPB_DESCRIPTOR_TYPE_BYTES: {
  2663. upb_strview view = *(upb_strview*)field_mem;
  2664. if (skip_zero_value && view.size == 0) {
  2665. return true;
  2666. }
  2667. return upb_put_bytes(e, view.data, view.size) &&
  2668. upb_put_varint(e, view.size) &&
  2669. upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED);
  2670. }
  2671. case UPB_DESCRIPTOR_TYPE_GROUP: {
  2672. size_t size;
  2673. void *submsg = *(void **)field_mem;
  2674. const upb_msglayout *subm = m->submsgs[f->submsg_index];
  2675. if (submsg == NULL) {
  2676. return true;
  2677. }
  2678. return upb_put_tag(e, f->number, UPB_WIRE_TYPE_END_GROUP) &&
  2679. upb_encode_message(e, submsg, subm, &size) &&
  2680. upb_put_tag(e, f->number, UPB_WIRE_TYPE_START_GROUP);
  2681. }
  2682. case UPB_DESCRIPTOR_TYPE_MESSAGE: {
  2683. size_t size;
  2684. void *submsg = *(void **)field_mem;
  2685. const upb_msglayout *subm = m->submsgs[f->submsg_index];
  2686. if (submsg == NULL) {
  2687. return true;
  2688. }
  2689. return upb_encode_message(e, submsg, subm, &size) &&
  2690. upb_put_varint(e, size) &&
  2691. upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED);
  2692. }
  2693. }
  2694. #undef CASE
  2695. UPB_UNREACHABLE();
  2696. }
  2697. bool upb_encode_message(upb_encstate *e, const char *msg,
  2698. const upb_msglayout *m, size_t *size) {
  2699. int i;
  2700. size_t pre_len = e->limit - e->ptr;
  2701. const char *unknown;
  2702. size_t unknown_size;
  2703. for (i = m->field_count - 1; i >= 0; i--) {
  2704. const upb_msglayout_field *f = &m->fields[i];
  2705. if (f->label == UPB_LABEL_REPEATED) {
  2706. CHK(upb_encode_array(e, msg + f->offset, m, f));
  2707. } else {
  2708. bool skip_empty = false;
  2709. if (f->presence == 0) {
  2710. /* Proto3 presence. */
  2711. skip_empty = true;
  2712. } else if (f->presence > 0) {
  2713. /* Proto2 presence: hasbit. */
  2714. if (!upb_readhasbit(msg, f)) {
  2715. continue;
  2716. }
  2717. } else {
  2718. /* Field is in a oneof. */
  2719. if (upb_readcase(msg, f) != f->number) {
  2720. continue;
  2721. }
  2722. }
  2723. CHK(upb_encode_scalarfield(e, msg + f->offset, m, f, skip_empty));
  2724. }
  2725. }
  2726. unknown = upb_msg_getunknown(msg, &unknown_size);
  2727. if (unknown) {
  2728. upb_put_bytes(e, unknown, unknown_size);
  2729. }
  2730. *size = (e->limit - e->ptr) - pre_len;
  2731. return true;
  2732. }
  2733. char *upb_encode(const void *msg, const upb_msglayout *m, upb_arena *arena,
  2734. size_t *size) {
  2735. upb_encstate e;
  2736. e.alloc = upb_arena_alloc(arena);
  2737. e.buf = NULL;
  2738. e.limit = NULL;
  2739. e.ptr = NULL;
  2740. if (!upb_encode_message(&e, msg, m, size)) {
  2741. *size = 0;
  2742. return NULL;
  2743. }
  2744. *size = e.limit - e.ptr;
  2745. if (*size == 0) {
  2746. static char ch;
  2747. return &ch;
  2748. } else {
  2749. UPB_ASSERT(e.ptr);
  2750. return e.ptr;
  2751. }
  2752. }
  2753. #undef CHK
  2754. /*
  2755. ** TODO(haberman): it's unclear whether a lot of the consistency checks should
  2756. ** UPB_ASSERT() or return false.
  2757. */
  2758. #include <string.h>
  2759. struct upb_handlers {
  2760. upb_handlercache *cache;
  2761. const upb_msgdef *msg;
  2762. const upb_handlers **sub;
  2763. const void *top_closure_type;
  2764. upb_handlers_tabent table[1]; /* Dynamically-sized field handler array. */
  2765. };
  2766. static void *upb_calloc(upb_arena *arena, size_t size) {
  2767. void *mem = upb_malloc(upb_arena_alloc(arena), size);
  2768. if (mem) {
  2769. memset(mem, 0, size);
  2770. }
  2771. return mem;
  2772. }
  2773. /* Defined for the sole purpose of having a unique pointer value for
  2774. * UPB_NO_CLOSURE. */
  2775. char _upb_noclosure;
  2776. /* Given a selector for a STARTSUBMSG handler, resolves to a pointer to the
  2777. * subhandlers for this submessage field. */
  2778. #define SUBH(h, selector) (h->sub[selector])
  2779. /* The selector for a submessage field is the field index. */
  2780. #define SUBH_F(h, f) SUBH(h, upb_fielddef_index(f))
  2781. static int32_t trygetsel(upb_handlers *h, const upb_fielddef *f,
  2782. upb_handlertype_t type) {
  2783. upb_selector_t sel;
  2784. bool ok;
  2785. ok = upb_handlers_getselector(f, type, &sel);
  2786. UPB_ASSERT(upb_handlers_msgdef(h) == upb_fielddef_containingtype(f));
  2787. UPB_ASSERT(ok);
  2788. return sel;
  2789. }
  2790. static upb_selector_t handlers_getsel(upb_handlers *h, const upb_fielddef *f,
  2791. upb_handlertype_t type) {
  2792. int32_t sel = trygetsel(h, f, type);
  2793. UPB_ASSERT(sel >= 0);
  2794. return sel;
  2795. }
  2796. static const void **returntype(upb_handlers *h, const upb_fielddef *f,
  2797. upb_handlertype_t type) {
  2798. return &h->table[handlers_getsel(h, f, type)].attr.return_closure_type;
  2799. }
  2800. static bool doset(upb_handlers *h, int32_t sel, const upb_fielddef *f,
  2801. upb_handlertype_t type, upb_func *func,
  2802. const upb_handlerattr *attr) {
  2803. upb_handlerattr set_attr = UPB_HANDLERATTR_INIT;
  2804. const void *closure_type;
  2805. const void **context_closure_type;
  2806. UPB_ASSERT(!h->table[sel].func);
  2807. if (attr) {
  2808. set_attr = *attr;
  2809. }
  2810. /* Check that the given closure type matches the closure type that has been
  2811. * established for this context (if any). */
  2812. closure_type = set_attr.closure_type;
  2813. if (type == UPB_HANDLER_STRING) {
  2814. context_closure_type = returntype(h, f, UPB_HANDLER_STARTSTR);
  2815. } else if (f && upb_fielddef_isseq(f) &&
  2816. type != UPB_HANDLER_STARTSEQ &&
  2817. type != UPB_HANDLER_ENDSEQ) {
  2818. context_closure_type = returntype(h, f, UPB_HANDLER_STARTSEQ);
  2819. } else {
  2820. context_closure_type = &h->top_closure_type;
  2821. }
  2822. if (closure_type && *context_closure_type &&
  2823. closure_type != *context_closure_type) {
  2824. return false;
  2825. }
  2826. if (closure_type)
  2827. *context_closure_type = closure_type;
  2828. /* If this is a STARTSEQ or STARTSTR handler, check that the returned pointer
  2829. * matches any pre-existing expectations about what type is expected. */
  2830. if (type == UPB_HANDLER_STARTSEQ || type == UPB_HANDLER_STARTSTR) {
  2831. const void *return_type = set_attr.return_closure_type;
  2832. const void *table_return_type = h->table[sel].attr.return_closure_type;
  2833. if (return_type && table_return_type && return_type != table_return_type) {
  2834. return false;
  2835. }
  2836. if (table_return_type && !return_type) {
  2837. set_attr.return_closure_type = table_return_type;
  2838. }
  2839. }
  2840. h->table[sel].func = (upb_func*)func;
  2841. h->table[sel].attr = set_attr;
  2842. return true;
  2843. }
  2844. /* Returns the effective closure type for this handler (which will propagate
  2845. * from outer frames if this frame has no START* handler). Not implemented for
  2846. * UPB_HANDLER_STRING at the moment since this is not needed. Returns NULL is
  2847. * the effective closure type is unspecified (either no handler was registered
  2848. * to specify it or the handler that was registered did not specify the closure
  2849. * type). */
  2850. const void *effective_closure_type(upb_handlers *h, const upb_fielddef *f,
  2851. upb_handlertype_t type) {
  2852. const void *ret;
  2853. upb_selector_t sel;
  2854. UPB_ASSERT(type != UPB_HANDLER_STRING);
  2855. ret = h->top_closure_type;
  2856. if (upb_fielddef_isseq(f) &&
  2857. type != UPB_HANDLER_STARTSEQ &&
  2858. type != UPB_HANDLER_ENDSEQ &&
  2859. h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSEQ)].func) {
  2860. ret = h->table[sel].attr.return_closure_type;
  2861. }
  2862. if (type == UPB_HANDLER_STRING &&
  2863. h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSTR)].func) {
  2864. ret = h->table[sel].attr.return_closure_type;
  2865. }
  2866. /* The effective type of the submessage; not used yet.
  2867. * if (type == SUBMESSAGE &&
  2868. * h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSUBMSG)].func) {
  2869. * ret = h->table[sel].attr.return_closure_type;
  2870. * } */
  2871. return ret;
  2872. }
  2873. /* Checks whether the START* handler specified by f & type is missing even
  2874. * though it is required to convert the established type of an outer frame
  2875. * ("closure_type") into the established type of an inner frame (represented in
  2876. * the return closure type of this handler's attr. */
  2877. bool checkstart(upb_handlers *h, const upb_fielddef *f, upb_handlertype_t type,
  2878. upb_status *status) {
  2879. const void *closure_type;
  2880. const upb_handlerattr *attr;
  2881. const void *return_closure_type;
  2882. upb_selector_t sel = handlers_getsel(h, f, type);
  2883. if (h->table[sel].func) return true;
  2884. closure_type = effective_closure_type(h, f, type);
  2885. attr = &h->table[sel].attr;
  2886. return_closure_type = attr->return_closure_type;
  2887. if (closure_type && return_closure_type &&
  2888. closure_type != return_closure_type) {
  2889. return false;
  2890. }
  2891. return true;
  2892. }
  2893. static upb_handlers *upb_handlers_new(const upb_msgdef *md,
  2894. upb_handlercache *cache,
  2895. upb_arena *arena) {
  2896. int extra;
  2897. upb_handlers *h;
  2898. extra = sizeof(upb_handlers_tabent) * (upb_msgdef_selectorcount(md) - 1);
  2899. h = upb_calloc(arena, sizeof(*h) + extra);
  2900. if (!h) return NULL;
  2901. h->cache = cache;
  2902. h->msg = md;
  2903. if (upb_msgdef_submsgfieldcount(md) > 0) {
  2904. size_t bytes = upb_msgdef_submsgfieldcount(md) * sizeof(*h->sub);
  2905. h->sub = upb_calloc(arena, bytes);
  2906. if (!h->sub) return NULL;
  2907. } else {
  2908. h->sub = 0;
  2909. }
  2910. /* calloc() above initialized all handlers to NULL. */
  2911. return h;
  2912. }
  2913. /* Public interface ***********************************************************/
  2914. #define SETTER(name, handlerctype, handlertype) \
  2915. bool upb_handlers_set##name(upb_handlers *h, const upb_fielddef *f, \
  2916. handlerctype func, \
  2917. const upb_handlerattr *attr) { \
  2918. int32_t sel = trygetsel(h, f, handlertype); \
  2919. return doset(h, sel, f, handlertype, (upb_func *)func, attr); \
  2920. }
  2921. SETTER(int32, upb_int32_handlerfunc*, UPB_HANDLER_INT32)
  2922. SETTER(int64, upb_int64_handlerfunc*, UPB_HANDLER_INT64)
  2923. SETTER(uint32, upb_uint32_handlerfunc*, UPB_HANDLER_UINT32)
  2924. SETTER(uint64, upb_uint64_handlerfunc*, UPB_HANDLER_UINT64)
  2925. SETTER(float, upb_float_handlerfunc*, UPB_HANDLER_FLOAT)
  2926. SETTER(double, upb_double_handlerfunc*, UPB_HANDLER_DOUBLE)
  2927. SETTER(bool, upb_bool_handlerfunc*, UPB_HANDLER_BOOL)
  2928. SETTER(startstr, upb_startstr_handlerfunc*, UPB_HANDLER_STARTSTR)
  2929. SETTER(string, upb_string_handlerfunc*, UPB_HANDLER_STRING)
  2930. SETTER(endstr, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSTR)
  2931. SETTER(startseq, upb_startfield_handlerfunc*, UPB_HANDLER_STARTSEQ)
  2932. SETTER(startsubmsg, upb_startfield_handlerfunc*, UPB_HANDLER_STARTSUBMSG)
  2933. SETTER(endsubmsg, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSUBMSG)
  2934. SETTER(endseq, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSEQ)
  2935. #undef SETTER
  2936. bool upb_handlers_setunknown(upb_handlers *h, upb_unknown_handlerfunc *func,
  2937. const upb_handlerattr *attr) {
  2938. return doset(h, UPB_UNKNOWN_SELECTOR, NULL, UPB_HANDLER_INT32,
  2939. (upb_func *)func, attr);
  2940. }
  2941. bool upb_handlers_setstartmsg(upb_handlers *h, upb_startmsg_handlerfunc *func,
  2942. const upb_handlerattr *attr) {
  2943. return doset(h, UPB_STARTMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
  2944. (upb_func *)func, attr);
  2945. }
  2946. bool upb_handlers_setendmsg(upb_handlers *h, upb_endmsg_handlerfunc *func,
  2947. const upb_handlerattr *attr) {
  2948. return doset(h, UPB_ENDMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
  2949. (upb_func *)func, attr);
  2950. }
  2951. bool upb_handlers_setsubhandlers(upb_handlers *h, const upb_fielddef *f,
  2952. const upb_handlers *sub) {
  2953. UPB_ASSERT(sub);
  2954. UPB_ASSERT(upb_fielddef_issubmsg(f));
  2955. if (SUBH_F(h, f)) return false; /* Can't reset. */
  2956. if (upb_handlers_msgdef(sub) != upb_fielddef_msgsubdef(f)) {
  2957. return false;
  2958. }
  2959. SUBH_F(h, f) = sub;
  2960. return true;
  2961. }
  2962. const upb_handlers *upb_handlers_getsubhandlers(const upb_handlers *h,
  2963. const upb_fielddef *f) {
  2964. UPB_ASSERT(upb_fielddef_issubmsg(f));
  2965. return SUBH_F(h, f);
  2966. }
  2967. upb_func *upb_handlers_gethandler(const upb_handlers *h, upb_selector_t s,
  2968. const void **handler_data) {
  2969. upb_func *ret = (upb_func *)h->table[s].func;
  2970. if (ret && handler_data) {
  2971. *handler_data = h->table[s].attr.handler_data;
  2972. }
  2973. return ret;
  2974. }
  2975. bool upb_handlers_getattr(const upb_handlers *h, upb_selector_t sel,
  2976. upb_handlerattr *attr) {
  2977. if (!upb_handlers_gethandler(h, sel, NULL))
  2978. return false;
  2979. *attr = h->table[sel].attr;
  2980. return true;
  2981. }
  2982. const upb_handlers *upb_handlers_getsubhandlers_sel(const upb_handlers *h,
  2983. upb_selector_t sel) {
  2984. /* STARTSUBMSG selector in sel is the field's selector base. */
  2985. return SUBH(h, sel - UPB_STATIC_SELECTOR_COUNT);
  2986. }
  2987. const upb_msgdef *upb_handlers_msgdef(const upb_handlers *h) { return h->msg; }
  2988. bool upb_handlers_addcleanup(upb_handlers *h, void *p, upb_handlerfree *func) {
  2989. return upb_handlercache_addcleanup(h->cache, p, func);
  2990. }
  2991. upb_handlertype_t upb_handlers_getprimitivehandlertype(const upb_fielddef *f) {
  2992. switch (upb_fielddef_type(f)) {
  2993. case UPB_TYPE_INT32:
  2994. case UPB_TYPE_ENUM: return UPB_HANDLER_INT32;
  2995. case UPB_TYPE_INT64: return UPB_HANDLER_INT64;
  2996. case UPB_TYPE_UINT32: return UPB_HANDLER_UINT32;
  2997. case UPB_TYPE_UINT64: return UPB_HANDLER_UINT64;
  2998. case UPB_TYPE_FLOAT: return UPB_HANDLER_FLOAT;
  2999. case UPB_TYPE_DOUBLE: return UPB_HANDLER_DOUBLE;
  3000. case UPB_TYPE_BOOL: return UPB_HANDLER_BOOL;
  3001. default: UPB_ASSERT(false); return -1; /* Invalid input. */
  3002. }
  3003. }
  3004. bool upb_handlers_getselector(const upb_fielddef *f, upb_handlertype_t type,
  3005. upb_selector_t *s) {
  3006. uint32_t selector_base = upb_fielddef_selectorbase(f);
  3007. switch (type) {
  3008. case UPB_HANDLER_INT32:
  3009. case UPB_HANDLER_INT64:
  3010. case UPB_HANDLER_UINT32:
  3011. case UPB_HANDLER_UINT64:
  3012. case UPB_HANDLER_FLOAT:
  3013. case UPB_HANDLER_DOUBLE:
  3014. case UPB_HANDLER_BOOL:
  3015. if (!upb_fielddef_isprimitive(f) ||
  3016. upb_handlers_getprimitivehandlertype(f) != type)
  3017. return false;
  3018. *s = selector_base;
  3019. break;
  3020. case UPB_HANDLER_STRING:
  3021. if (upb_fielddef_isstring(f)) {
  3022. *s = selector_base;
  3023. } else if (upb_fielddef_lazy(f)) {
  3024. *s = selector_base + 3;
  3025. } else {
  3026. return false;
  3027. }
  3028. break;
  3029. case UPB_HANDLER_STARTSTR:
  3030. if (upb_fielddef_isstring(f) || upb_fielddef_lazy(f)) {
  3031. *s = selector_base + 1;
  3032. } else {
  3033. return false;
  3034. }
  3035. break;
  3036. case UPB_HANDLER_ENDSTR:
  3037. if (upb_fielddef_isstring(f) || upb_fielddef_lazy(f)) {
  3038. *s = selector_base + 2;
  3039. } else {
  3040. return false;
  3041. }
  3042. break;
  3043. case UPB_HANDLER_STARTSEQ:
  3044. if (!upb_fielddef_isseq(f)) return false;
  3045. *s = selector_base - 2;
  3046. break;
  3047. case UPB_HANDLER_ENDSEQ:
  3048. if (!upb_fielddef_isseq(f)) return false;
  3049. *s = selector_base - 1;
  3050. break;
  3051. case UPB_HANDLER_STARTSUBMSG:
  3052. if (!upb_fielddef_issubmsg(f)) return false;
  3053. /* Selectors for STARTSUBMSG are at the beginning of the table so that the
  3054. * selector can also be used as an index into the "sub" array of
  3055. * subhandlers. The indexes for the two into these two tables are the
  3056. * same, except that in the handler table the static selectors come first. */
  3057. *s = upb_fielddef_index(f) + UPB_STATIC_SELECTOR_COUNT;
  3058. break;
  3059. case UPB_HANDLER_ENDSUBMSG:
  3060. if (!upb_fielddef_issubmsg(f)) return false;
  3061. *s = selector_base;
  3062. break;
  3063. }
  3064. UPB_ASSERT((size_t)*s < upb_msgdef_selectorcount(upb_fielddef_containingtype(f)));
  3065. return true;
  3066. }
  3067. uint32_t upb_handlers_selectorbaseoffset(const upb_fielddef *f) {
  3068. return upb_fielddef_isseq(f) ? 2 : 0;
  3069. }
  3070. uint32_t upb_handlers_selectorcount(const upb_fielddef *f) {
  3071. uint32_t ret = 1;
  3072. if (upb_fielddef_isseq(f)) ret += 2; /* STARTSEQ/ENDSEQ */
  3073. if (upb_fielddef_isstring(f)) ret += 2; /* [STRING]/STARTSTR/ENDSTR */
  3074. if (upb_fielddef_issubmsg(f)) {
  3075. /* ENDSUBMSG (STARTSUBMSG is at table beginning) */
  3076. ret += 0;
  3077. if (upb_fielddef_lazy(f)) {
  3078. /* STARTSTR/ENDSTR/STRING (for lazy) */
  3079. ret += 3;
  3080. }
  3081. }
  3082. return ret;
  3083. }
  3084. /* upb_handlercache ***********************************************************/
  3085. struct upb_handlercache {
  3086. upb_arena *arena;
  3087. upb_inttable tab; /* maps upb_msgdef* -> upb_handlers*. */
  3088. upb_handlers_callback *callback;
  3089. const void *closure;
  3090. };
  3091. const upb_handlers *upb_handlercache_get(upb_handlercache *c,
  3092. const upb_msgdef *md) {
  3093. upb_msg_field_iter i;
  3094. upb_value v;
  3095. upb_handlers *h;
  3096. if (upb_inttable_lookupptr(&c->tab, md, &v)) {
  3097. return upb_value_getptr(v);
  3098. }
  3099. h = upb_handlers_new(md, c, c->arena);
  3100. v = upb_value_ptr(h);
  3101. if (!h) return NULL;
  3102. if (!upb_inttable_insertptr(&c->tab, md, v)) return NULL;
  3103. c->callback(c->closure, h);
  3104. /* For each submessage field, get or create a handlers object and set it as
  3105. * the subhandlers. */
  3106. for(upb_msg_field_begin(&i, md);
  3107. !upb_msg_field_done(&i);
  3108. upb_msg_field_next(&i)) {
  3109. upb_fielddef *f = upb_msg_iter_field(&i);
  3110. if (upb_fielddef_issubmsg(f)) {
  3111. const upb_msgdef *subdef = upb_fielddef_msgsubdef(f);
  3112. const upb_handlers *sub_mh = upb_handlercache_get(c, subdef);
  3113. if (!sub_mh) return NULL;
  3114. upb_handlers_setsubhandlers(h, f, sub_mh);
  3115. }
  3116. }
  3117. return h;
  3118. }
  3119. upb_handlercache *upb_handlercache_new(upb_handlers_callback *callback,
  3120. const void *closure) {
  3121. upb_handlercache *cache = upb_gmalloc(sizeof(*cache));
  3122. if (!cache) return NULL;
  3123. cache->arena = upb_arena_new();
  3124. cache->callback = callback;
  3125. cache->closure = closure;
  3126. if (!upb_inttable_init(&cache->tab, UPB_CTYPE_PTR)) goto oom;
  3127. return cache;
  3128. oom:
  3129. upb_gfree(cache);
  3130. return NULL;
  3131. }
  3132. void upb_handlercache_free(upb_handlercache *cache) {
  3133. upb_inttable_uninit(&cache->tab);
  3134. upb_arena_free(cache->arena);
  3135. upb_gfree(cache);
  3136. }
  3137. bool upb_handlercache_addcleanup(upb_handlercache *c, void *p,
  3138. upb_handlerfree *func) {
  3139. return upb_arena_addcleanup(c->arena, p, func);
  3140. }
  3141. /* upb_byteshandler ***********************************************************/
  3142. bool upb_byteshandler_setstartstr(upb_byteshandler *h,
  3143. upb_startstr_handlerfunc *func, void *d) {
  3144. h->table[UPB_STARTSTR_SELECTOR].func = (upb_func*)func;
  3145. h->table[UPB_STARTSTR_SELECTOR].attr.handler_data = d;
  3146. return true;
  3147. }
  3148. bool upb_byteshandler_setstring(upb_byteshandler *h,
  3149. upb_string_handlerfunc *func, void *d) {
  3150. h->table[UPB_STRING_SELECTOR].func = (upb_func*)func;
  3151. h->table[UPB_STRING_SELECTOR].attr.handler_data = d;
  3152. return true;
  3153. }
  3154. bool upb_byteshandler_setendstr(upb_byteshandler *h,
  3155. upb_endfield_handlerfunc *func, void *d) {
  3156. h->table[UPB_ENDSTR_SELECTOR].func = (upb_func*)func;
  3157. h->table[UPB_ENDSTR_SELECTOR].attr.handler_data = d;
  3158. return true;
  3159. }
  3160. /** Handlers for upb_msg ******************************************************/
  3161. typedef struct {
  3162. size_t offset;
  3163. int32_t hasbit;
  3164. } upb_msg_handlerdata;
  3165. /* Fallback implementation if the handler is not specialized by the producer. */
  3166. #define MSG_WRITER(type, ctype) \
  3167. bool upb_msg_set ## type (void *c, const void *hd, ctype val) { \
  3168. uint8_t *m = c; \
  3169. const upb_msg_handlerdata *d = hd; \
  3170. if (d->hasbit > 0) \
  3171. *(uint8_t*)&m[d->hasbit / 8] |= 1 << (d->hasbit % 8); \
  3172. *(ctype*)&m[d->offset] = val; \
  3173. return true; \
  3174. } \
  3175. MSG_WRITER(double, double)
  3176. MSG_WRITER(float, float)
  3177. MSG_WRITER(int32, int32_t)
  3178. MSG_WRITER(int64, int64_t)
  3179. MSG_WRITER(uint32, uint32_t)
  3180. MSG_WRITER(uint64, uint64_t)
  3181. MSG_WRITER(bool, bool)
  3182. bool upb_msg_setscalarhandler(upb_handlers *h, const upb_fielddef *f,
  3183. size_t offset, int32_t hasbit) {
  3184. upb_handlerattr attr = UPB_HANDLERATTR_INIT;
  3185. bool ok;
  3186. upb_msg_handlerdata *d = upb_gmalloc(sizeof(*d));
  3187. if (!d) return false;
  3188. d->offset = offset;
  3189. d->hasbit = hasbit;
  3190. attr.handler_data = d;
  3191. attr.alwaysok = true;
  3192. upb_handlers_addcleanup(h, d, upb_gfree);
  3193. #define TYPE(u, l) \
  3194. case UPB_TYPE_##u: \
  3195. ok = upb_handlers_set##l(h, f, upb_msg_set##l, &attr); break;
  3196. ok = false;
  3197. switch (upb_fielddef_type(f)) {
  3198. TYPE(INT64, int64);
  3199. TYPE(INT32, int32);
  3200. TYPE(ENUM, int32);
  3201. TYPE(UINT64, uint64);
  3202. TYPE(UINT32, uint32);
  3203. TYPE(DOUBLE, double);
  3204. TYPE(FLOAT, float);
  3205. TYPE(BOOL, bool);
  3206. default: UPB_ASSERT(false); break;
  3207. }
  3208. #undef TYPE
  3209. return ok;
  3210. }
  3211. bool upb_msg_getscalarhandlerdata(const upb_handlers *h,
  3212. upb_selector_t s,
  3213. upb_fieldtype_t *type,
  3214. size_t *offset,
  3215. int32_t *hasbit) {
  3216. const upb_msg_handlerdata *d;
  3217. const void *p;
  3218. upb_func *f = upb_handlers_gethandler(h, s, &p);
  3219. if ((upb_int64_handlerfunc*)f == upb_msg_setint64) {
  3220. *type = UPB_TYPE_INT64;
  3221. } else if ((upb_int32_handlerfunc*)f == upb_msg_setint32) {
  3222. *type = UPB_TYPE_INT32;
  3223. } else if ((upb_uint64_handlerfunc*)f == upb_msg_setuint64) {
  3224. *type = UPB_TYPE_UINT64;
  3225. } else if ((upb_uint32_handlerfunc*)f == upb_msg_setuint32) {
  3226. *type = UPB_TYPE_UINT32;
  3227. } else if ((upb_double_handlerfunc*)f == upb_msg_setdouble) {
  3228. *type = UPB_TYPE_DOUBLE;
  3229. } else if ((upb_float_handlerfunc*)f == upb_msg_setfloat) {
  3230. *type = UPB_TYPE_FLOAT;
  3231. } else if ((upb_bool_handlerfunc*)f == upb_msg_setbool) {
  3232. *type = UPB_TYPE_BOOL;
  3233. } else {
  3234. return false;
  3235. }
  3236. d = p;
  3237. *offset = d->offset;
  3238. *hasbit = d->hasbit;
  3239. return true;
  3240. }
  3241. #include <string.h>
  3242. bool upb_fieldtype_mapkeyok(upb_fieldtype_t type) {
  3243. return type == UPB_TYPE_BOOL || type == UPB_TYPE_INT32 ||
  3244. type == UPB_TYPE_UINT32 || type == UPB_TYPE_INT64 ||
  3245. type == UPB_TYPE_UINT64 || type == UPB_TYPE_STRING;
  3246. }
  3247. #define PTR_AT(msg, ofs, type) (type*)((char*)msg + ofs)
  3248. #define VOIDPTR_AT(msg, ofs) PTR_AT(msg, ofs, void)
  3249. #define ENCODE_MAX_NESTING 64
  3250. #define CHECK_TRUE(x) if (!(x)) { return false; }
  3251. /** upb_msgval ****************************************************************/
  3252. /* These functions will generate real memcpy() calls on ARM sadly, because
  3253. * the compiler assumes they might not be aligned. */
  3254. static upb_msgval upb_msgval_read(const void *p, size_t ofs,
  3255. uint8_t size) {
  3256. upb_msgval val;
  3257. p = (char*)p + ofs;
  3258. memcpy(&val, p, size);
  3259. return val;
  3260. }
  3261. static void upb_msgval_write(void *p, size_t ofs, upb_msgval val,
  3262. uint8_t size) {
  3263. p = (char*)p + ofs;
  3264. memcpy(p, &val, size);
  3265. }
  3266. static size_t upb_msgval_sizeof(upb_fieldtype_t type) {
  3267. switch (type) {
  3268. case UPB_TYPE_DOUBLE:
  3269. case UPB_TYPE_INT64:
  3270. case UPB_TYPE_UINT64:
  3271. return 8;
  3272. case UPB_TYPE_ENUM:
  3273. case UPB_TYPE_INT32:
  3274. case UPB_TYPE_UINT32:
  3275. case UPB_TYPE_FLOAT:
  3276. return 4;
  3277. case UPB_TYPE_BOOL:
  3278. return 1;
  3279. case UPB_TYPE_MESSAGE:
  3280. return sizeof(void*);
  3281. case UPB_TYPE_BYTES:
  3282. case UPB_TYPE_STRING:
  3283. return sizeof(upb_strview);
  3284. }
  3285. UPB_UNREACHABLE();
  3286. }
  3287. static uint8_t upb_msg_fieldsize(const upb_msglayout_field *field) {
  3288. if (field->label == UPB_LABEL_REPEATED) {
  3289. return sizeof(void*);
  3290. } else {
  3291. return upb_msgval_sizeof(upb_desctype_to_fieldtype[field->descriptortype]);
  3292. }
  3293. }
  3294. /* TODO(haberman): this is broken right now because upb_msgval can contain
  3295. * a char* / size_t pair, which is too big for a upb_value. To fix this
  3296. * we'll probably need to dynamically allocate a upb_msgval and store a
  3297. * pointer to that in the tables for extensions/maps. */
  3298. static upb_value upb_toval(upb_msgval val) {
  3299. upb_value ret;
  3300. UPB_UNUSED(val);
  3301. memset(&ret, 0, sizeof(upb_value)); /* XXX */
  3302. return ret;
  3303. }
  3304. static upb_msgval upb_msgval_fromval(upb_value val) {
  3305. upb_msgval ret;
  3306. UPB_UNUSED(val);
  3307. memset(&ret, 0, sizeof(upb_msgval)); /* XXX */
  3308. return ret;
  3309. }
  3310. static upb_ctype_t upb_fieldtotabtype(upb_fieldtype_t type) {
  3311. switch (type) {
  3312. case UPB_TYPE_FLOAT: return UPB_CTYPE_FLOAT;
  3313. case UPB_TYPE_DOUBLE: return UPB_CTYPE_DOUBLE;
  3314. case UPB_TYPE_BOOL: return UPB_CTYPE_BOOL;
  3315. case UPB_TYPE_BYTES:
  3316. case UPB_TYPE_MESSAGE:
  3317. case UPB_TYPE_STRING: return UPB_CTYPE_CONSTPTR;
  3318. case UPB_TYPE_ENUM:
  3319. case UPB_TYPE_INT32: return UPB_CTYPE_INT32;
  3320. case UPB_TYPE_UINT32: return UPB_CTYPE_UINT32;
  3321. case UPB_TYPE_INT64: return UPB_CTYPE_INT64;
  3322. case UPB_TYPE_UINT64: return UPB_CTYPE_UINT64;
  3323. default: UPB_ASSERT(false); return 0;
  3324. }
  3325. }
  3326. /** upb_msg *******************************************************************/
  3327. /* If we always read/write as a consistent type to each address, this shouldn't
  3328. * violate aliasing.
  3329. */
  3330. #define DEREF(msg, ofs, type) *PTR_AT(msg, ofs, type)
  3331. /* Internal members of a upb_msg. We can change this without breaking binary
  3332. * compatibility. We put these before the user's data. The user's upb_msg*
  3333. * points after the upb_msg_internal. */
  3334. /* Used when a message is not extendable. */
  3335. typedef struct {
  3336. /* TODO(haberman): use pointer tagging so we we are slim when known unknown
  3337. * fields are not present. */
  3338. upb_arena *arena;
  3339. char *unknown;
  3340. size_t unknown_len;
  3341. size_t unknown_size;
  3342. } upb_msg_internal;
  3343. /* Used when a message is extendable. */
  3344. typedef struct {
  3345. upb_inttable *extdict;
  3346. upb_msg_internal base;
  3347. } upb_msg_internal_withext;
  3348. static int upb_msg_internalsize(const upb_msglayout *l) {
  3349. return sizeof(upb_msg_internal) - l->extendable * sizeof(void *);
  3350. }
  3351. static upb_msg_internal *upb_msg_getinternal(upb_msg *msg) {
  3352. return VOIDPTR_AT(msg, -sizeof(upb_msg_internal));
  3353. }
  3354. static const upb_msg_internal *upb_msg_getinternal_const(const upb_msg *msg) {
  3355. return VOIDPTR_AT(msg, -sizeof(upb_msg_internal));
  3356. }
  3357. static upb_msg_internal_withext *upb_msg_getinternalwithext(
  3358. upb_msg *msg, const upb_msglayout *l) {
  3359. UPB_ASSERT(l->extendable);
  3360. return VOIDPTR_AT(msg, -sizeof(upb_msg_internal_withext));
  3361. }
  3362. void upb_msg_addunknown(upb_msg *msg, const char *data, size_t len) {
  3363. upb_msg_internal* in = upb_msg_getinternal(msg);
  3364. if (len > in->unknown_size - in->unknown_len) {
  3365. upb_alloc *alloc = upb_arena_alloc(in->arena);
  3366. size_t need = in->unknown_size + len;
  3367. size_t newsize = UPB_MAX(in->unknown_size * 2, need);
  3368. in->unknown = upb_realloc(alloc, in->unknown, in->unknown_size, newsize);
  3369. in->unknown_size = newsize;
  3370. }
  3371. memcpy(in->unknown + in->unknown_len, data, len);
  3372. in->unknown_len += len;
  3373. }
  3374. const char *upb_msg_getunknown(const upb_msg *msg, size_t *len) {
  3375. const upb_msg_internal* in = upb_msg_getinternal_const(msg);
  3376. *len = in->unknown_len;
  3377. return in->unknown;
  3378. }
  3379. static const upb_msglayout_field *upb_msg_checkfield(int field_index,
  3380. const upb_msglayout *l) {
  3381. UPB_ASSERT(field_index >= 0 && field_index < l->field_count);
  3382. return &l->fields[field_index];
  3383. }
  3384. static bool upb_msg_inoneof(const upb_msglayout_field *field) {
  3385. return field->presence < 0;
  3386. }
  3387. static uint32_t *upb_msg_oneofcase(const upb_msg *msg, int field_index,
  3388. const upb_msglayout *l) {
  3389. const upb_msglayout_field *field = upb_msg_checkfield(field_index, l);
  3390. UPB_ASSERT(upb_msg_inoneof(field));
  3391. return PTR_AT(msg, ~field->presence, uint32_t);
  3392. }
  3393. static size_t upb_msg_sizeof(const upb_msglayout *l) {
  3394. return l->size + upb_msg_internalsize(l);
  3395. }
  3396. upb_msg *upb_msg_new(const upb_msglayout *l, upb_arena *a) {
  3397. upb_alloc *alloc = upb_arena_alloc(a);
  3398. void *mem = upb_malloc(alloc, upb_msg_sizeof(l));
  3399. upb_msg_internal *in;
  3400. upb_msg *msg;
  3401. if (!mem) {
  3402. return NULL;
  3403. }
  3404. msg = VOIDPTR_AT(mem, upb_msg_internalsize(l));
  3405. /* Initialize normal members. */
  3406. memset(msg, 0, l->size);
  3407. /* Initialize internal members. */
  3408. in = upb_msg_getinternal(msg);
  3409. in->arena = a;
  3410. in->unknown = NULL;
  3411. in->unknown_len = 0;
  3412. in->unknown_size = 0;
  3413. if (l->extendable) {
  3414. upb_msg_getinternalwithext(msg, l)->extdict = NULL;
  3415. }
  3416. return msg;
  3417. }
  3418. upb_arena *upb_msg_arena(const upb_msg *msg) {
  3419. return upb_msg_getinternal_const(msg)->arena;
  3420. }
  3421. bool upb_msg_has(const upb_msg *msg,
  3422. int field_index,
  3423. const upb_msglayout *l) {
  3424. const upb_msglayout_field *field = upb_msg_checkfield(field_index, l);
  3425. UPB_ASSERT(field->presence);
  3426. if (upb_msg_inoneof(field)) {
  3427. /* Oneofs are set when the oneof number is set to this field. */
  3428. return *upb_msg_oneofcase(msg, field_index, l) == field->number;
  3429. } else {
  3430. /* Other fields are set when their hasbit is set. */
  3431. uint32_t hasbit = field->presence;
  3432. return DEREF(msg, hasbit / 8, char) | (1 << (hasbit % 8));
  3433. }
  3434. }
  3435. upb_msgval upb_msg_get(const upb_msg *msg, int field_index,
  3436. const upb_msglayout *l) {
  3437. const upb_msglayout_field *field = upb_msg_checkfield(field_index, l);
  3438. int size = upb_msg_fieldsize(field);
  3439. return upb_msgval_read(msg, field->offset, size);
  3440. }
  3441. void upb_msg_set(upb_msg *msg, int field_index, upb_msgval val,
  3442. const upb_msglayout *l) {
  3443. const upb_msglayout_field *field = upb_msg_checkfield(field_index, l);
  3444. int size = upb_msg_fieldsize(field);
  3445. upb_msgval_write(msg, field->offset, val, size);
  3446. }
  3447. /** upb_array *****************************************************************/
  3448. #define DEREF_ARR(arr, i, type) ((type*)arr->data)[i]
  3449. upb_array *upb_array_new(upb_fieldtype_t type, upb_arena *a) {
  3450. upb_alloc *alloc = upb_arena_alloc(a);
  3451. upb_array *ret = upb_malloc(alloc, sizeof(upb_array));
  3452. if (!ret) {
  3453. return NULL;
  3454. }
  3455. ret->type = type;
  3456. ret->data = NULL;
  3457. ret->len = 0;
  3458. ret->size = 0;
  3459. ret->element_size = upb_msgval_sizeof(type);
  3460. ret->arena = a;
  3461. return ret;
  3462. }
  3463. size_t upb_array_size(const upb_array *arr) {
  3464. return arr->len;
  3465. }
  3466. upb_fieldtype_t upb_array_type(const upb_array *arr) {
  3467. return arr->type;
  3468. }
  3469. upb_msgval upb_array_get(const upb_array *arr, size_t i) {
  3470. UPB_ASSERT(i < arr->len);
  3471. return upb_msgval_read(arr->data, i * arr->element_size, arr->element_size);
  3472. }
  3473. bool upb_array_set(upb_array *arr, size_t i, upb_msgval val) {
  3474. UPB_ASSERT(i <= arr->len);
  3475. if (i == arr->len) {
  3476. /* Extending the array. */
  3477. if (i == arr->size) {
  3478. /* Need to reallocate. */
  3479. size_t new_size = UPB_MAX(arr->size * 2, 8);
  3480. size_t new_bytes = new_size * arr->element_size;
  3481. size_t old_bytes = arr->size * arr->element_size;
  3482. upb_alloc *alloc = upb_arena_alloc(arr->arena);
  3483. upb_msgval *new_data =
  3484. upb_realloc(alloc, arr->data, old_bytes, new_bytes);
  3485. if (!new_data) {
  3486. return false;
  3487. }
  3488. arr->data = new_data;
  3489. arr->size = new_size;
  3490. }
  3491. arr->len = i + 1;
  3492. }
  3493. upb_msgval_write(arr->data, i * arr->element_size, val, arr->element_size);
  3494. return true;
  3495. }
  3496. /** upb_map *******************************************************************/
  3497. struct upb_map {
  3498. upb_fieldtype_t key_type;
  3499. upb_fieldtype_t val_type;
  3500. /* We may want to optimize this to use inttable where possible, for greater
  3501. * efficiency and lower memory footprint. */
  3502. upb_strtable strtab;
  3503. upb_arena *arena;
  3504. };
  3505. static void upb_map_tokey(upb_fieldtype_t type, upb_msgval *key,
  3506. const char **out_key, size_t *out_len) {
  3507. switch (type) {
  3508. case UPB_TYPE_STRING:
  3509. /* Point to string data of the input key. */
  3510. *out_key = key->str.data;
  3511. *out_len = key->str.size;
  3512. return;
  3513. case UPB_TYPE_BOOL:
  3514. case UPB_TYPE_INT32:
  3515. case UPB_TYPE_UINT32:
  3516. case UPB_TYPE_INT64:
  3517. case UPB_TYPE_UINT64:
  3518. /* Point to the key itself. XXX: big-endian. */
  3519. *out_key = (const char*)key;
  3520. *out_len = upb_msgval_sizeof(type);
  3521. return;
  3522. case UPB_TYPE_BYTES:
  3523. case UPB_TYPE_DOUBLE:
  3524. case UPB_TYPE_ENUM:
  3525. case UPB_TYPE_FLOAT:
  3526. case UPB_TYPE_MESSAGE:
  3527. break; /* Cannot be a map key. */
  3528. }
  3529. UPB_UNREACHABLE();
  3530. }
  3531. static upb_msgval upb_map_fromkey(upb_fieldtype_t type, const char *key,
  3532. size_t len) {
  3533. switch (type) {
  3534. case UPB_TYPE_STRING:
  3535. return upb_msgval_makestr(key, len);
  3536. case UPB_TYPE_BOOL:
  3537. case UPB_TYPE_INT32:
  3538. case UPB_TYPE_UINT32:
  3539. case UPB_TYPE_INT64:
  3540. case UPB_TYPE_UINT64:
  3541. return upb_msgval_read(key, 0, upb_msgval_sizeof(type));
  3542. case UPB_TYPE_BYTES:
  3543. case UPB_TYPE_DOUBLE:
  3544. case UPB_TYPE_ENUM:
  3545. case UPB_TYPE_FLOAT:
  3546. case UPB_TYPE_MESSAGE:
  3547. break; /* Cannot be a map key. */
  3548. }
  3549. UPB_UNREACHABLE();
  3550. }
  3551. upb_map *upb_map_new(upb_fieldtype_t ktype, upb_fieldtype_t vtype,
  3552. upb_arena *a) {
  3553. upb_ctype_t vtabtype = upb_fieldtotabtype(vtype);
  3554. upb_alloc *alloc = upb_arena_alloc(a);
  3555. upb_map *map = upb_malloc(alloc, sizeof(upb_map));
  3556. if (!map) {
  3557. return NULL;
  3558. }
  3559. UPB_ASSERT(upb_fieldtype_mapkeyok(ktype));
  3560. map->key_type = ktype;
  3561. map->val_type = vtype;
  3562. map->arena = a;
  3563. if (!upb_strtable_init2(&map->strtab, vtabtype, alloc)) {
  3564. return NULL;
  3565. }
  3566. return map;
  3567. }
  3568. size_t upb_map_size(const upb_map *map) {
  3569. return upb_strtable_count(&map->strtab);
  3570. }
  3571. upb_fieldtype_t upb_map_keytype(const upb_map *map) {
  3572. return map->key_type;
  3573. }
  3574. upb_fieldtype_t upb_map_valuetype(const upb_map *map) {
  3575. return map->val_type;
  3576. }
  3577. bool upb_map_get(const upb_map *map, upb_msgval key, upb_msgval *val) {
  3578. upb_value tabval;
  3579. const char *key_str;
  3580. size_t key_len;
  3581. bool ret;
  3582. upb_map_tokey(map->key_type, &key, &key_str, &key_len);
  3583. ret = upb_strtable_lookup2(&map->strtab, key_str, key_len, &tabval);
  3584. if (ret) {
  3585. memcpy(val, &tabval, sizeof(tabval));
  3586. }
  3587. return ret;
  3588. }
  3589. bool upb_map_set(upb_map *map, upb_msgval key, upb_msgval val,
  3590. upb_msgval *removed) {
  3591. const char *key_str;
  3592. size_t key_len;
  3593. upb_value tabval = upb_toval(val);
  3594. upb_value removedtabval;
  3595. upb_alloc *a = upb_arena_alloc(map->arena);
  3596. upb_map_tokey(map->key_type, &key, &key_str, &key_len);
  3597. /* TODO(haberman): add overwrite operation to minimize number of lookups. */
  3598. if (upb_strtable_lookup2(&map->strtab, key_str, key_len, NULL)) {
  3599. upb_strtable_remove3(&map->strtab, key_str, key_len, &removedtabval, a);
  3600. memcpy(&removed, &removedtabval, sizeof(removed));
  3601. }
  3602. return upb_strtable_insert3(&map->strtab, key_str, key_len, tabval, a);
  3603. }
  3604. bool upb_map_del(upb_map *map, upb_msgval key) {
  3605. const char *key_str;
  3606. size_t key_len;
  3607. upb_alloc *a = upb_arena_alloc(map->arena);
  3608. upb_map_tokey(map->key_type, &key, &key_str, &key_len);
  3609. return upb_strtable_remove3(&map->strtab, key_str, key_len, NULL, a);
  3610. }
  3611. /** upb_mapiter ***************************************************************/
  3612. struct upb_mapiter {
  3613. upb_strtable_iter iter;
  3614. upb_fieldtype_t key_type;
  3615. };
  3616. size_t upb_mapiter_sizeof() {
  3617. return sizeof(upb_mapiter);
  3618. }
  3619. void upb_mapiter_begin(upb_mapiter *i, const upb_map *map) {
  3620. upb_strtable_begin(&i->iter, &map->strtab);
  3621. i->key_type = map->key_type;
  3622. }
  3623. upb_mapiter *upb_mapiter_new(const upb_map *t, upb_alloc *a) {
  3624. upb_mapiter *ret = upb_malloc(a, upb_mapiter_sizeof());
  3625. if (!ret) {
  3626. return NULL;
  3627. }
  3628. upb_mapiter_begin(ret, t);
  3629. return ret;
  3630. }
  3631. void upb_mapiter_free(upb_mapiter *i, upb_alloc *a) {
  3632. upb_free(a, i);
  3633. }
  3634. void upb_mapiter_next(upb_mapiter *i) {
  3635. upb_strtable_next(&i->iter);
  3636. }
  3637. bool upb_mapiter_done(const upb_mapiter *i) {
  3638. return upb_strtable_done(&i->iter);
  3639. }
  3640. upb_msgval upb_mapiter_key(const upb_mapiter *i) {
  3641. return upb_map_fromkey(i->key_type, upb_strtable_iter_key(&i->iter),
  3642. upb_strtable_iter_keylength(&i->iter));
  3643. }
  3644. upb_msgval upb_mapiter_value(const upb_mapiter *i) {
  3645. return upb_msgval_fromval(upb_strtable_iter_value(&i->iter));
  3646. }
  3647. void upb_mapiter_setdone(upb_mapiter *i) {
  3648. upb_strtable_iter_setdone(&i->iter);
  3649. }
  3650. bool upb_mapiter_isequal(const upb_mapiter *i1, const upb_mapiter *i2) {
  3651. return upb_strtable_iter_isequal(&i1->iter, &i2->iter);
  3652. }
  3653. static bool is_power_of_two(size_t val) {
  3654. return (val & (val - 1)) == 0;
  3655. }
  3656. /* Align up to the given power of 2. */
  3657. static size_t align_up(size_t val, size_t align) {
  3658. UPB_ASSERT(is_power_of_two(align));
  3659. return (val + align - 1) & ~(align - 1);
  3660. }
  3661. static size_t div_round_up(size_t n, size_t d) {
  3662. return (n + d - 1) / d;
  3663. }
  3664. static size_t upb_msgval_sizeof2(upb_fieldtype_t type) {
  3665. switch (type) {
  3666. case UPB_TYPE_DOUBLE:
  3667. case UPB_TYPE_INT64:
  3668. case UPB_TYPE_UINT64:
  3669. return 8;
  3670. case UPB_TYPE_ENUM:
  3671. case UPB_TYPE_INT32:
  3672. case UPB_TYPE_UINT32:
  3673. case UPB_TYPE_FLOAT:
  3674. return 4;
  3675. case UPB_TYPE_BOOL:
  3676. return 1;
  3677. case UPB_TYPE_MESSAGE:
  3678. return sizeof(void*);
  3679. case UPB_TYPE_BYTES:
  3680. case UPB_TYPE_STRING:
  3681. return sizeof(upb_strview);
  3682. }
  3683. UPB_UNREACHABLE();
  3684. }
  3685. static uint8_t upb_msg_fielddefsize(const upb_fielddef *f) {
  3686. if (upb_fielddef_isseq(f)) {
  3687. return sizeof(void*);
  3688. } else {
  3689. return upb_msgval_sizeof2(upb_fielddef_type(f));
  3690. }
  3691. }
  3692. /** upb_msglayout *************************************************************/
  3693. static void upb_msglayout_free(upb_msglayout *l) {
  3694. upb_gfree(l);
  3695. }
  3696. static size_t upb_msglayout_place(upb_msglayout *l, size_t size) {
  3697. size_t ret;
  3698. l->size = align_up(l->size, size);
  3699. ret = l->size;
  3700. l->size += size;
  3701. return ret;
  3702. }
  3703. static bool upb_msglayout_init(const upb_msgdef *m,
  3704. upb_msglayout *l,
  3705. upb_msgfactory *factory) {
  3706. upb_msg_field_iter it;
  3707. upb_msg_oneof_iter oit;
  3708. size_t hasbit;
  3709. size_t submsg_count = 0;
  3710. const upb_msglayout **submsgs;
  3711. upb_msglayout_field *fields;
  3712. for (upb_msg_field_begin(&it, m);
  3713. !upb_msg_field_done(&it);
  3714. upb_msg_field_next(&it)) {
  3715. const upb_fielddef* f = upb_msg_iter_field(&it);
  3716. if (upb_fielddef_issubmsg(f)) {
  3717. submsg_count++;
  3718. }
  3719. }
  3720. memset(l, 0, sizeof(*l));
  3721. fields = upb_gmalloc(upb_msgdef_numfields(m) * sizeof(*fields));
  3722. submsgs = upb_gmalloc(submsg_count * sizeof(*submsgs));
  3723. if ((!fields && upb_msgdef_numfields(m)) ||
  3724. (!submsgs && submsg_count)) {
  3725. /* OOM. */
  3726. upb_gfree(fields);
  3727. upb_gfree(submsgs);
  3728. return false;
  3729. }
  3730. l->field_count = upb_msgdef_numfields(m);
  3731. l->fields = fields;
  3732. l->submsgs = submsgs;
  3733. /* Allocate data offsets in three stages:
  3734. *
  3735. * 1. hasbits.
  3736. * 2. regular fields.
  3737. * 3. oneof fields.
  3738. *
  3739. * OPT: There is a lot of room for optimization here to minimize the size.
  3740. */
  3741. /* Allocate hasbits and set basic field attributes. */
  3742. submsg_count = 0;
  3743. for (upb_msg_field_begin(&it, m), hasbit = 0;
  3744. !upb_msg_field_done(&it);
  3745. upb_msg_field_next(&it)) {
  3746. const upb_fielddef* f = upb_msg_iter_field(&it);
  3747. upb_msglayout_field *field = &fields[upb_fielddef_index(f)];
  3748. field->number = upb_fielddef_number(f);
  3749. field->descriptortype = upb_fielddef_descriptortype(f);
  3750. field->label = upb_fielddef_label(f);
  3751. if (upb_fielddef_issubmsg(f)) {
  3752. const upb_msglayout *sub_layout =
  3753. upb_msgfactory_getlayout(factory, upb_fielddef_msgsubdef(f));
  3754. field->submsg_index = submsg_count++;
  3755. submsgs[field->submsg_index] = sub_layout;
  3756. }
  3757. if (upb_fielddef_haspresence(f) && !upb_fielddef_containingoneof(f)) {
  3758. field->presence = (hasbit++);
  3759. } else {
  3760. field->presence = 0;
  3761. }
  3762. }
  3763. /* Account for space used by hasbits. */
  3764. l->size = div_round_up(hasbit, 8);
  3765. /* Allocate non-oneof fields. */
  3766. for (upb_msg_field_begin(&it, m); !upb_msg_field_done(&it);
  3767. upb_msg_field_next(&it)) {
  3768. const upb_fielddef* f = upb_msg_iter_field(&it);
  3769. size_t field_size = upb_msg_fielddefsize(f);
  3770. size_t index = upb_fielddef_index(f);
  3771. if (upb_fielddef_containingoneof(f)) {
  3772. /* Oneofs are handled separately below. */
  3773. continue;
  3774. }
  3775. fields[index].offset = upb_msglayout_place(l, field_size);
  3776. }
  3777. /* Allocate oneof fields. Each oneof field consists of a uint32 for the case
  3778. * and space for the actual data. */
  3779. for (upb_msg_oneof_begin(&oit, m); !upb_msg_oneof_done(&oit);
  3780. upb_msg_oneof_next(&oit)) {
  3781. const upb_oneofdef* o = upb_msg_iter_oneof(&oit);
  3782. upb_oneof_iter fit;
  3783. size_t case_size = sizeof(uint32_t); /* Could potentially optimize this. */
  3784. size_t field_size = 0;
  3785. uint32_t case_offset;
  3786. uint32_t data_offset;
  3787. /* Calculate field size: the max of all field sizes. */
  3788. for (upb_oneof_begin(&fit, o);
  3789. !upb_oneof_done(&fit);
  3790. upb_oneof_next(&fit)) {
  3791. const upb_fielddef* f = upb_oneof_iter_field(&fit);
  3792. field_size = UPB_MAX(field_size, upb_msg_fielddefsize(f));
  3793. }
  3794. /* Align and allocate case offset. */
  3795. case_offset = upb_msglayout_place(l, case_size);
  3796. data_offset = upb_msglayout_place(l, field_size);
  3797. for (upb_oneof_begin(&fit, o);
  3798. !upb_oneof_done(&fit);
  3799. upb_oneof_next(&fit)) {
  3800. const upb_fielddef* f = upb_oneof_iter_field(&fit);
  3801. fields[upb_fielddef_index(f)].offset = data_offset;
  3802. fields[upb_fielddef_index(f)].presence = ~case_offset;
  3803. }
  3804. }
  3805. /* Size of the entire structure should be a multiple of its greatest
  3806. * alignment. TODO: track overall alignment for real? */
  3807. l->size = align_up(l->size, 8);
  3808. return true;
  3809. }
  3810. /** upb_msgfactory ************************************************************/
  3811. struct upb_msgfactory {
  3812. const upb_symtab *symtab; /* We own a ref. */
  3813. upb_inttable layouts;
  3814. };
  3815. upb_msgfactory *upb_msgfactory_new(const upb_symtab *symtab) {
  3816. upb_msgfactory *ret = upb_gmalloc(sizeof(*ret));
  3817. ret->symtab = symtab;
  3818. upb_inttable_init(&ret->layouts, UPB_CTYPE_PTR);
  3819. return ret;
  3820. }
  3821. void upb_msgfactory_free(upb_msgfactory *f) {
  3822. upb_inttable_iter i;
  3823. upb_inttable_begin(&i, &f->layouts);
  3824. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  3825. upb_msglayout *l = upb_value_getptr(upb_inttable_iter_value(&i));
  3826. upb_msglayout_free(l);
  3827. }
  3828. upb_inttable_uninit(&f->layouts);
  3829. upb_gfree(f);
  3830. }
  3831. const upb_symtab *upb_msgfactory_symtab(const upb_msgfactory *f) {
  3832. return f->symtab;
  3833. }
  3834. const upb_msglayout *upb_msgfactory_getlayout(upb_msgfactory *f,
  3835. const upb_msgdef *m) {
  3836. upb_value v;
  3837. UPB_ASSERT(upb_symtab_lookupmsg(f->symtab, upb_msgdef_fullname(m)) == m);
  3838. UPB_ASSERT(!upb_msgdef_mapentry(m));
  3839. if (upb_inttable_lookupptr(&f->layouts, m, &v)) {
  3840. UPB_ASSERT(upb_value_getptr(v));
  3841. return upb_value_getptr(v);
  3842. } else {
  3843. /* In case of circular dependency, layout has to be inserted first. */
  3844. upb_msglayout *l = upb_gmalloc(sizeof(*l));
  3845. upb_msgfactory *mutable_f = (void*)f;
  3846. upb_inttable_insertptr(&mutable_f->layouts, m, upb_value_ptr(l));
  3847. UPB_ASSERT(l);
  3848. if (!upb_msglayout_init(m, l, f)) {
  3849. upb_msglayout_free(l);
  3850. }
  3851. return l;
  3852. }
  3853. }
  3854. #ifndef UINTPTR_MAX
  3855. #error must include stdint.h first
  3856. #endif
  3857. #if UINTPTR_MAX == 0xffffffff
  3858. #define UPB_SIZE(size32, size64) size32
  3859. #else
  3860. #define UPB_SIZE(size32, size64) size64
  3861. #endif
  3862. #define UPB_FIELD_AT(msg, fieldtype, offset) \
  3863. *(fieldtype*)((const char*)(msg) + offset)
  3864. #define UPB_READ_ONEOF(msg, fieldtype, offset, case_offset, case_val, default) \
  3865. UPB_FIELD_AT(msg, int, case_offset) == case_val \
  3866. ? UPB_FIELD_AT(msg, fieldtype, offset) \
  3867. : default
  3868. #define UPB_WRITE_ONEOF(msg, fieldtype, offset, value, case_offset, case_val) \
  3869. UPB_FIELD_AT(msg, int, case_offset) = case_val; \
  3870. UPB_FIELD_AT(msg, fieldtype, offset) = value;
  3871. #undef UPB_SIZE
  3872. #undef UPB_FIELD_AT
  3873. #undef UPB_READ_ONEOF
  3874. #undef UPB_WRITE_ONEOF
  3875. bool upb_bufsrc_putbuf(const char *buf, size_t len, upb_bytessink sink) {
  3876. void *subc;
  3877. bool ret;
  3878. upb_bufhandle handle = UPB_BUFHANDLE_INIT;
  3879. handle.buf = buf;
  3880. ret = upb_bytessink_start(sink, len, &subc);
  3881. if (ret && len != 0) {
  3882. ret = (upb_bytessink_putbuf(sink, subc, buf, len, &handle) >= len);
  3883. }
  3884. if (ret) {
  3885. ret = upb_bytessink_end(sink);
  3886. }
  3887. return ret;
  3888. }
  3889. /*
  3890. ** upb_table Implementation
  3891. **
  3892. ** Implementation is heavily inspired by Lua's ltable.c.
  3893. */
  3894. #include <string.h>
  3895. #define UPB_MAXARRSIZE 16 /* 64k. */
  3896. /* From Chromium. */
  3897. #define ARRAY_SIZE(x) \
  3898. ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x])))))
  3899. static void upb_check_alloc(upb_table *t, upb_alloc *a) {
  3900. UPB_UNUSED(t);
  3901. UPB_UNUSED(a);
  3902. UPB_ASSERT_DEBUGVAR(t->alloc == a);
  3903. }
  3904. static const double MAX_LOAD = 0.85;
  3905. /* The minimum utilization of the array part of a mixed hash/array table. This
  3906. * is a speed/memory-usage tradeoff (though it's not straightforward because of
  3907. * cache effects). The lower this is, the more memory we'll use. */
  3908. static const double MIN_DENSITY = 0.1;
  3909. bool is_pow2(uint64_t v) { return v == 0 || (v & (v - 1)) == 0; }
  3910. int log2ceil(uint64_t v) {
  3911. int ret = 0;
  3912. bool pow2 = is_pow2(v);
  3913. while (v >>= 1) ret++;
  3914. ret = pow2 ? ret : ret + 1; /* Ceiling. */
  3915. return UPB_MIN(UPB_MAXARRSIZE, ret);
  3916. }
  3917. char *upb_strdup(const char *s, upb_alloc *a) {
  3918. return upb_strdup2(s, strlen(s), a);
  3919. }
  3920. char *upb_strdup2(const char *s, size_t len, upb_alloc *a) {
  3921. size_t n;
  3922. char *p;
  3923. /* Prevent overflow errors. */
  3924. if (len == SIZE_MAX) return NULL;
  3925. /* Always null-terminate, even if binary data; but don't rely on the input to
  3926. * have a null-terminating byte since it may be a raw binary buffer. */
  3927. n = len + 1;
  3928. p = upb_malloc(a, n);
  3929. if (p) {
  3930. memcpy(p, s, len);
  3931. p[len] = 0;
  3932. }
  3933. return p;
  3934. }
  3935. /* A type to represent the lookup key of either a strtable or an inttable. */
  3936. typedef union {
  3937. uintptr_t num;
  3938. struct {
  3939. const char *str;
  3940. size_t len;
  3941. } str;
  3942. } lookupkey_t;
  3943. static lookupkey_t strkey2(const char *str, size_t len) {
  3944. lookupkey_t k;
  3945. k.str.str = str;
  3946. k.str.len = len;
  3947. return k;
  3948. }
  3949. static lookupkey_t intkey(uintptr_t key) {
  3950. lookupkey_t k;
  3951. k.num = key;
  3952. return k;
  3953. }
  3954. typedef uint32_t hashfunc_t(upb_tabkey key);
  3955. typedef bool eqlfunc_t(upb_tabkey k1, lookupkey_t k2);
  3956. /* Base table (shared code) ***************************************************/
  3957. /* For when we need to cast away const. */
  3958. static upb_tabent *mutable_entries(upb_table *t) {
  3959. return (upb_tabent*)t->entries;
  3960. }
  3961. static bool isfull(upb_table *t) {
  3962. if (upb_table_size(t) == 0) {
  3963. return true;
  3964. } else {
  3965. return ((double)(t->count + 1) / upb_table_size(t)) > MAX_LOAD;
  3966. }
  3967. }
  3968. static bool init(upb_table *t, upb_ctype_t ctype, uint8_t size_lg2,
  3969. upb_alloc *a) {
  3970. size_t bytes;
  3971. t->count = 0;
  3972. t->ctype = ctype;
  3973. t->size_lg2 = size_lg2;
  3974. t->mask = upb_table_size(t) ? upb_table_size(t) - 1 : 0;
  3975. #ifndef NDEBUG
  3976. t->alloc = a;
  3977. #endif
  3978. bytes = upb_table_size(t) * sizeof(upb_tabent);
  3979. if (bytes > 0) {
  3980. t->entries = upb_malloc(a, bytes);
  3981. if (!t->entries) return false;
  3982. memset(mutable_entries(t), 0, bytes);
  3983. } else {
  3984. t->entries = NULL;
  3985. }
  3986. return true;
  3987. }
  3988. static void uninit(upb_table *t, upb_alloc *a) {
  3989. upb_check_alloc(t, a);
  3990. upb_free(a, mutable_entries(t));
  3991. }
  3992. static upb_tabent *emptyent(upb_table *t) {
  3993. upb_tabent *e = mutable_entries(t) + upb_table_size(t);
  3994. while (1) { if (upb_tabent_isempty(--e)) return e; UPB_ASSERT(e > t->entries); }
  3995. }
  3996. static upb_tabent *getentry_mutable(upb_table *t, uint32_t hash) {
  3997. return (upb_tabent*)upb_getentry(t, hash);
  3998. }
  3999. static const upb_tabent *findentry(const upb_table *t, lookupkey_t key,
  4000. uint32_t hash, eqlfunc_t *eql) {
  4001. const upb_tabent *e;
  4002. if (t->size_lg2 == 0) return NULL;
  4003. e = upb_getentry(t, hash);
  4004. if (upb_tabent_isempty(e)) return NULL;
  4005. while (1) {
  4006. if (eql(e->key, key)) return e;
  4007. if ((e = e->next) == NULL) return NULL;
  4008. }
  4009. }
  4010. static upb_tabent *findentry_mutable(upb_table *t, lookupkey_t key,
  4011. uint32_t hash, eqlfunc_t *eql) {
  4012. return (upb_tabent*)findentry(t, key, hash, eql);
  4013. }
  4014. static bool lookup(const upb_table *t, lookupkey_t key, upb_value *v,
  4015. uint32_t hash, eqlfunc_t *eql) {
  4016. const upb_tabent *e = findentry(t, key, hash, eql);
  4017. if (e) {
  4018. if (v) {
  4019. _upb_value_setval(v, e->val.val, t->ctype);
  4020. }
  4021. return true;
  4022. } else {
  4023. return false;
  4024. }
  4025. }
  4026. /* The given key must not already exist in the table. */
  4027. static void insert(upb_table *t, lookupkey_t key, upb_tabkey tabkey,
  4028. upb_value val, uint32_t hash,
  4029. hashfunc_t *hashfunc, eqlfunc_t *eql) {
  4030. upb_tabent *mainpos_e;
  4031. upb_tabent *our_e;
  4032. UPB_ASSERT(findentry(t, key, hash, eql) == NULL);
  4033. UPB_ASSERT_DEBUGVAR(val.ctype == t->ctype);
  4034. t->count++;
  4035. mainpos_e = getentry_mutable(t, hash);
  4036. our_e = mainpos_e;
  4037. if (upb_tabent_isempty(mainpos_e)) {
  4038. /* Our main position is empty; use it. */
  4039. our_e->next = NULL;
  4040. } else {
  4041. /* Collision. */
  4042. upb_tabent *new_e = emptyent(t);
  4043. /* Head of collider's chain. */
  4044. upb_tabent *chain = getentry_mutable(t, hashfunc(mainpos_e->key));
  4045. if (chain == mainpos_e) {
  4046. /* Existing ent is in its main posisiton (it has the same hash as us, and
  4047. * is the head of our chain). Insert to new ent and append to this chain. */
  4048. new_e->next = mainpos_e->next;
  4049. mainpos_e->next = new_e;
  4050. our_e = new_e;
  4051. } else {
  4052. /* Existing ent is not in its main position (it is a node in some other
  4053. * chain). This implies that no existing ent in the table has our hash.
  4054. * Evict it (updating its chain) and use its ent for head of our chain. */
  4055. *new_e = *mainpos_e; /* copies next. */
  4056. while (chain->next != mainpos_e) {
  4057. chain = (upb_tabent*)chain->next;
  4058. UPB_ASSERT(chain);
  4059. }
  4060. chain->next = new_e;
  4061. our_e = mainpos_e;
  4062. our_e->next = NULL;
  4063. }
  4064. }
  4065. our_e->key = tabkey;
  4066. our_e->val.val = val.val;
  4067. UPB_ASSERT(findentry(t, key, hash, eql) == our_e);
  4068. }
  4069. static bool rm(upb_table *t, lookupkey_t key, upb_value *val,
  4070. upb_tabkey *removed, uint32_t hash, eqlfunc_t *eql) {
  4071. upb_tabent *chain = getentry_mutable(t, hash);
  4072. if (upb_tabent_isempty(chain)) return false;
  4073. if (eql(chain->key, key)) {
  4074. /* Element to remove is at the head of its chain. */
  4075. t->count--;
  4076. if (val) _upb_value_setval(val, chain->val.val, t->ctype);
  4077. if (removed) *removed = chain->key;
  4078. if (chain->next) {
  4079. upb_tabent *move = (upb_tabent*)chain->next;
  4080. *chain = *move;
  4081. move->key = 0; /* Make the slot empty. */
  4082. } else {
  4083. chain->key = 0; /* Make the slot empty. */
  4084. }
  4085. return true;
  4086. } else {
  4087. /* Element to remove is either in a non-head position or not in the
  4088. * table. */
  4089. while (chain->next && !eql(chain->next->key, key)) {
  4090. chain = (upb_tabent*)chain->next;
  4091. }
  4092. if (chain->next) {
  4093. /* Found element to remove. */
  4094. upb_tabent *rm = (upb_tabent*)chain->next;
  4095. t->count--;
  4096. if (val) _upb_value_setval(val, chain->next->val.val, t->ctype);
  4097. if (removed) *removed = rm->key;
  4098. rm->key = 0; /* Make the slot empty. */
  4099. chain->next = rm->next;
  4100. return true;
  4101. } else {
  4102. /* Element to remove is not in the table. */
  4103. return false;
  4104. }
  4105. }
  4106. }
  4107. static size_t next(const upb_table *t, size_t i) {
  4108. do {
  4109. if (++i >= upb_table_size(t))
  4110. return SIZE_MAX;
  4111. } while(upb_tabent_isempty(&t->entries[i]));
  4112. return i;
  4113. }
  4114. static size_t begin(const upb_table *t) {
  4115. return next(t, -1);
  4116. }
  4117. /* upb_strtable ***************************************************************/
  4118. /* A simple "subclass" of upb_table that only adds a hash function for strings. */
  4119. static upb_tabkey strcopy(lookupkey_t k2, upb_alloc *a) {
  4120. uint32_t len = (uint32_t) k2.str.len;
  4121. char *str = upb_malloc(a, k2.str.len + sizeof(uint32_t) + 1);
  4122. if (str == NULL) return 0;
  4123. memcpy(str, &len, sizeof(uint32_t));
  4124. memcpy(str + sizeof(uint32_t), k2.str.str, k2.str.len + 1);
  4125. return (uintptr_t)str;
  4126. }
  4127. static uint32_t strhash(upb_tabkey key) {
  4128. uint32_t len;
  4129. char *str = upb_tabstr(key, &len);
  4130. return MurmurHash2(str, len, 0);
  4131. }
  4132. static bool streql(upb_tabkey k1, lookupkey_t k2) {
  4133. uint32_t len;
  4134. char *str = upb_tabstr(k1, &len);
  4135. return len == k2.str.len && memcmp(str, k2.str.str, len) == 0;
  4136. }
  4137. bool upb_strtable_init2(upb_strtable *t, upb_ctype_t ctype, upb_alloc *a) {
  4138. return init(&t->t, ctype, 2, a);
  4139. }
  4140. void upb_strtable_uninit2(upb_strtable *t, upb_alloc *a) {
  4141. size_t i;
  4142. for (i = 0; i < upb_table_size(&t->t); i++)
  4143. upb_free(a, (void*)t->t.entries[i].key);
  4144. uninit(&t->t, a);
  4145. }
  4146. bool upb_strtable_resize(upb_strtable *t, size_t size_lg2, upb_alloc *a) {
  4147. upb_strtable new_table;
  4148. upb_strtable_iter i;
  4149. upb_check_alloc(&t->t, a);
  4150. if (!init(&new_table.t, t->t.ctype, size_lg2, a))
  4151. return false;
  4152. upb_strtable_begin(&i, t);
  4153. for ( ; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  4154. upb_strtable_insert3(
  4155. &new_table,
  4156. upb_strtable_iter_key(&i),
  4157. upb_strtable_iter_keylength(&i),
  4158. upb_strtable_iter_value(&i),
  4159. a);
  4160. }
  4161. upb_strtable_uninit2(t, a);
  4162. *t = new_table;
  4163. return true;
  4164. }
  4165. bool upb_strtable_insert3(upb_strtable *t, const char *k, size_t len,
  4166. upb_value v, upb_alloc *a) {
  4167. lookupkey_t key;
  4168. upb_tabkey tabkey;
  4169. uint32_t hash;
  4170. upb_check_alloc(&t->t, a);
  4171. if (isfull(&t->t)) {
  4172. /* Need to resize. New table of double the size, add old elements to it. */
  4173. if (!upb_strtable_resize(t, t->t.size_lg2 + 1, a)) {
  4174. return false;
  4175. }
  4176. }
  4177. key = strkey2(k, len);
  4178. tabkey = strcopy(key, a);
  4179. if (tabkey == 0) return false;
  4180. hash = MurmurHash2(key.str.str, key.str.len, 0);
  4181. insert(&t->t, key, tabkey, v, hash, &strhash, &streql);
  4182. return true;
  4183. }
  4184. bool upb_strtable_lookup2(const upb_strtable *t, const char *key, size_t len,
  4185. upb_value *v) {
  4186. uint32_t hash = MurmurHash2(key, len, 0);
  4187. return lookup(&t->t, strkey2(key, len), v, hash, &streql);
  4188. }
  4189. bool upb_strtable_remove3(upb_strtable *t, const char *key, size_t len,
  4190. upb_value *val, upb_alloc *alloc) {
  4191. uint32_t hash = MurmurHash2(key, len, 0);
  4192. upb_tabkey tabkey;
  4193. if (rm(&t->t, strkey2(key, len), val, &tabkey, hash, &streql)) {
  4194. upb_free(alloc, (void*)tabkey);
  4195. return true;
  4196. } else {
  4197. return false;
  4198. }
  4199. }
  4200. /* Iteration */
  4201. static const upb_tabent *str_tabent(const upb_strtable_iter *i) {
  4202. return &i->t->t.entries[i->index];
  4203. }
  4204. void upb_strtable_begin(upb_strtable_iter *i, const upb_strtable *t) {
  4205. i->t = t;
  4206. i->index = begin(&t->t);
  4207. }
  4208. void upb_strtable_next(upb_strtable_iter *i) {
  4209. i->index = next(&i->t->t, i->index);
  4210. }
  4211. bool upb_strtable_done(const upb_strtable_iter *i) {
  4212. if (!i->t) return true;
  4213. return i->index >= upb_table_size(&i->t->t) ||
  4214. upb_tabent_isempty(str_tabent(i));
  4215. }
  4216. const char *upb_strtable_iter_key(const upb_strtable_iter *i) {
  4217. UPB_ASSERT(!upb_strtable_done(i));
  4218. return upb_tabstr(str_tabent(i)->key, NULL);
  4219. }
  4220. size_t upb_strtable_iter_keylength(const upb_strtable_iter *i) {
  4221. uint32_t len;
  4222. UPB_ASSERT(!upb_strtable_done(i));
  4223. upb_tabstr(str_tabent(i)->key, &len);
  4224. return len;
  4225. }
  4226. upb_value upb_strtable_iter_value(const upb_strtable_iter *i) {
  4227. UPB_ASSERT(!upb_strtable_done(i));
  4228. return _upb_value_val(str_tabent(i)->val.val, i->t->t.ctype);
  4229. }
  4230. void upb_strtable_iter_setdone(upb_strtable_iter *i) {
  4231. i->t = NULL;
  4232. i->index = SIZE_MAX;
  4233. }
  4234. bool upb_strtable_iter_isequal(const upb_strtable_iter *i1,
  4235. const upb_strtable_iter *i2) {
  4236. if (upb_strtable_done(i1) && upb_strtable_done(i2))
  4237. return true;
  4238. return i1->t == i2->t && i1->index == i2->index;
  4239. }
  4240. /* upb_inttable ***************************************************************/
  4241. /* For inttables we use a hybrid structure where small keys are kept in an
  4242. * array and large keys are put in the hash table. */
  4243. static uint32_t inthash(upb_tabkey key) { return upb_inthash(key); }
  4244. static bool inteql(upb_tabkey k1, lookupkey_t k2) {
  4245. return k1 == k2.num;
  4246. }
  4247. static upb_tabval *mutable_array(upb_inttable *t) {
  4248. return (upb_tabval*)t->array;
  4249. }
  4250. static upb_tabval *inttable_val(upb_inttable *t, uintptr_t key) {
  4251. if (key < t->array_size) {
  4252. return upb_arrhas(t->array[key]) ? &(mutable_array(t)[key]) : NULL;
  4253. } else {
  4254. upb_tabent *e =
  4255. findentry_mutable(&t->t, intkey(key), upb_inthash(key), &inteql);
  4256. return e ? &e->val : NULL;
  4257. }
  4258. }
  4259. static const upb_tabval *inttable_val_const(const upb_inttable *t,
  4260. uintptr_t key) {
  4261. return inttable_val((upb_inttable*)t, key);
  4262. }
  4263. size_t upb_inttable_count(const upb_inttable *t) {
  4264. return t->t.count + t->array_count;
  4265. }
  4266. static void check(upb_inttable *t) {
  4267. UPB_UNUSED(t);
  4268. #if defined(UPB_DEBUG_TABLE) && !defined(NDEBUG)
  4269. {
  4270. /* This check is very expensive (makes inserts/deletes O(N)). */
  4271. size_t count = 0;
  4272. upb_inttable_iter i;
  4273. upb_inttable_begin(&i, t);
  4274. for(; !upb_inttable_done(&i); upb_inttable_next(&i), count++) {
  4275. UPB_ASSERT(upb_inttable_lookup(t, upb_inttable_iter_key(&i), NULL));
  4276. }
  4277. UPB_ASSERT(count == upb_inttable_count(t));
  4278. }
  4279. #endif
  4280. }
  4281. bool upb_inttable_sizedinit(upb_inttable *t, upb_ctype_t ctype,
  4282. size_t asize, int hsize_lg2, upb_alloc *a) {
  4283. size_t array_bytes;
  4284. if (!init(&t->t, ctype, hsize_lg2, a)) return false;
  4285. /* Always make the array part at least 1 long, so that we know key 0
  4286. * won't be in the hash part, which simplifies things. */
  4287. t->array_size = UPB_MAX(1, asize);
  4288. t->array_count = 0;
  4289. array_bytes = t->array_size * sizeof(upb_value);
  4290. t->array = upb_malloc(a, array_bytes);
  4291. if (!t->array) {
  4292. uninit(&t->t, a);
  4293. return false;
  4294. }
  4295. memset(mutable_array(t), 0xff, array_bytes);
  4296. check(t);
  4297. return true;
  4298. }
  4299. bool upb_inttable_init2(upb_inttable *t, upb_ctype_t ctype, upb_alloc *a) {
  4300. return upb_inttable_sizedinit(t, ctype, 0, 4, a);
  4301. }
  4302. void upb_inttable_uninit2(upb_inttable *t, upb_alloc *a) {
  4303. uninit(&t->t, a);
  4304. upb_free(a, mutable_array(t));
  4305. }
  4306. bool upb_inttable_insert2(upb_inttable *t, uintptr_t key, upb_value val,
  4307. upb_alloc *a) {
  4308. upb_tabval tabval;
  4309. tabval.val = val.val;
  4310. UPB_ASSERT(upb_arrhas(tabval)); /* This will reject (uint64_t)-1. Fix this. */
  4311. upb_check_alloc(&t->t, a);
  4312. if (key < t->array_size) {
  4313. UPB_ASSERT(!upb_arrhas(t->array[key]));
  4314. t->array_count++;
  4315. mutable_array(t)[key].val = val.val;
  4316. } else {
  4317. if (isfull(&t->t)) {
  4318. /* Need to resize the hash part, but we re-use the array part. */
  4319. size_t i;
  4320. upb_table new_table;
  4321. if (!init(&new_table, t->t.ctype, t->t.size_lg2 + 1, a)) {
  4322. return false;
  4323. }
  4324. for (i = begin(&t->t); i < upb_table_size(&t->t); i = next(&t->t, i)) {
  4325. const upb_tabent *e = &t->t.entries[i];
  4326. uint32_t hash;
  4327. upb_value v;
  4328. _upb_value_setval(&v, e->val.val, t->t.ctype);
  4329. hash = upb_inthash(e->key);
  4330. insert(&new_table, intkey(e->key), e->key, v, hash, &inthash, &inteql);
  4331. }
  4332. UPB_ASSERT(t->t.count == new_table.count);
  4333. uninit(&t->t, a);
  4334. t->t = new_table;
  4335. }
  4336. insert(&t->t, intkey(key), key, val, upb_inthash(key), &inthash, &inteql);
  4337. }
  4338. check(t);
  4339. return true;
  4340. }
  4341. bool upb_inttable_lookup(const upb_inttable *t, uintptr_t key, upb_value *v) {
  4342. const upb_tabval *table_v = inttable_val_const(t, key);
  4343. if (!table_v) return false;
  4344. if (v) _upb_value_setval(v, table_v->val, t->t.ctype);
  4345. return true;
  4346. }
  4347. bool upb_inttable_replace(upb_inttable *t, uintptr_t key, upb_value val) {
  4348. upb_tabval *table_v = inttable_val(t, key);
  4349. if (!table_v) return false;
  4350. table_v->val = val.val;
  4351. return true;
  4352. }
  4353. bool upb_inttable_remove(upb_inttable *t, uintptr_t key, upb_value *val) {
  4354. bool success;
  4355. if (key < t->array_size) {
  4356. if (upb_arrhas(t->array[key])) {
  4357. upb_tabval empty = UPB_TABVALUE_EMPTY_INIT;
  4358. t->array_count--;
  4359. if (val) {
  4360. _upb_value_setval(val, t->array[key].val, t->t.ctype);
  4361. }
  4362. mutable_array(t)[key] = empty;
  4363. success = true;
  4364. } else {
  4365. success = false;
  4366. }
  4367. } else {
  4368. success = rm(&t->t, intkey(key), val, NULL, upb_inthash(key), &inteql);
  4369. }
  4370. check(t);
  4371. return success;
  4372. }
  4373. bool upb_inttable_push2(upb_inttable *t, upb_value val, upb_alloc *a) {
  4374. upb_check_alloc(&t->t, a);
  4375. return upb_inttable_insert2(t, upb_inttable_count(t), val, a);
  4376. }
  4377. upb_value upb_inttable_pop(upb_inttable *t) {
  4378. upb_value val;
  4379. bool ok = upb_inttable_remove(t, upb_inttable_count(t) - 1, &val);
  4380. UPB_ASSERT(ok);
  4381. return val;
  4382. }
  4383. bool upb_inttable_insertptr2(upb_inttable *t, const void *key, upb_value val,
  4384. upb_alloc *a) {
  4385. upb_check_alloc(&t->t, a);
  4386. return upb_inttable_insert2(t, (uintptr_t)key, val, a);
  4387. }
  4388. bool upb_inttable_lookupptr(const upb_inttable *t, const void *key,
  4389. upb_value *v) {
  4390. return upb_inttable_lookup(t, (uintptr_t)key, v);
  4391. }
  4392. bool upb_inttable_removeptr(upb_inttable *t, const void *key, upb_value *val) {
  4393. return upb_inttable_remove(t, (uintptr_t)key, val);
  4394. }
  4395. void upb_inttable_compact2(upb_inttable *t, upb_alloc *a) {
  4396. /* A power-of-two histogram of the table keys. */
  4397. size_t counts[UPB_MAXARRSIZE + 1] = {0};
  4398. /* The max key in each bucket. */
  4399. uintptr_t max[UPB_MAXARRSIZE + 1] = {0};
  4400. upb_inttable_iter i;
  4401. size_t arr_count;
  4402. int size_lg2;
  4403. upb_inttable new_t;
  4404. upb_check_alloc(&t->t, a);
  4405. upb_inttable_begin(&i, t);
  4406. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  4407. uintptr_t key = upb_inttable_iter_key(&i);
  4408. int bucket = log2ceil(key);
  4409. max[bucket] = UPB_MAX(max[bucket], key);
  4410. counts[bucket]++;
  4411. }
  4412. /* Find the largest power of two that satisfies the MIN_DENSITY
  4413. * definition (while actually having some keys). */
  4414. arr_count = upb_inttable_count(t);
  4415. for (size_lg2 = ARRAY_SIZE(counts) - 1; size_lg2 > 0; size_lg2--) {
  4416. if (counts[size_lg2] == 0) {
  4417. /* We can halve again without losing any entries. */
  4418. continue;
  4419. } else if (arr_count >= (1 << size_lg2) * MIN_DENSITY) {
  4420. break;
  4421. }
  4422. arr_count -= counts[size_lg2];
  4423. }
  4424. UPB_ASSERT(arr_count <= upb_inttable_count(t));
  4425. {
  4426. /* Insert all elements into new, perfectly-sized table. */
  4427. size_t arr_size = max[size_lg2] + 1; /* +1 so arr[max] will fit. */
  4428. size_t hash_count = upb_inttable_count(t) - arr_count;
  4429. size_t hash_size = hash_count ? (hash_count / MAX_LOAD) + 1 : 0;
  4430. size_t hashsize_lg2 = log2ceil(hash_size);
  4431. upb_inttable_sizedinit(&new_t, t->t.ctype, arr_size, hashsize_lg2, a);
  4432. upb_inttable_begin(&i, t);
  4433. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  4434. uintptr_t k = upb_inttable_iter_key(&i);
  4435. upb_inttable_insert2(&new_t, k, upb_inttable_iter_value(&i), a);
  4436. }
  4437. UPB_ASSERT(new_t.array_size == arr_size);
  4438. UPB_ASSERT(new_t.t.size_lg2 == hashsize_lg2);
  4439. }
  4440. upb_inttable_uninit2(t, a);
  4441. *t = new_t;
  4442. }
  4443. /* Iteration. */
  4444. static const upb_tabent *int_tabent(const upb_inttable_iter *i) {
  4445. UPB_ASSERT(!i->array_part);
  4446. return &i->t->t.entries[i->index];
  4447. }
  4448. static upb_tabval int_arrent(const upb_inttable_iter *i) {
  4449. UPB_ASSERT(i->array_part);
  4450. return i->t->array[i->index];
  4451. }
  4452. void upb_inttable_begin(upb_inttable_iter *i, const upb_inttable *t) {
  4453. i->t = t;
  4454. i->index = -1;
  4455. i->array_part = true;
  4456. upb_inttable_next(i);
  4457. }
  4458. void upb_inttable_next(upb_inttable_iter *iter) {
  4459. const upb_inttable *t = iter->t;
  4460. if (iter->array_part) {
  4461. while (++iter->index < t->array_size) {
  4462. if (upb_arrhas(int_arrent(iter))) {
  4463. return;
  4464. }
  4465. }
  4466. iter->array_part = false;
  4467. iter->index = begin(&t->t);
  4468. } else {
  4469. iter->index = next(&t->t, iter->index);
  4470. }
  4471. }
  4472. bool upb_inttable_done(const upb_inttable_iter *i) {
  4473. if (!i->t) return true;
  4474. if (i->array_part) {
  4475. return i->index >= i->t->array_size ||
  4476. !upb_arrhas(int_arrent(i));
  4477. } else {
  4478. return i->index >= upb_table_size(&i->t->t) ||
  4479. upb_tabent_isempty(int_tabent(i));
  4480. }
  4481. }
  4482. uintptr_t upb_inttable_iter_key(const upb_inttable_iter *i) {
  4483. UPB_ASSERT(!upb_inttable_done(i));
  4484. return i->array_part ? i->index : int_tabent(i)->key;
  4485. }
  4486. upb_value upb_inttable_iter_value(const upb_inttable_iter *i) {
  4487. UPB_ASSERT(!upb_inttable_done(i));
  4488. return _upb_value_val(
  4489. i->array_part ? i->t->array[i->index].val : int_tabent(i)->val.val,
  4490. i->t->t.ctype);
  4491. }
  4492. void upb_inttable_iter_setdone(upb_inttable_iter *i) {
  4493. i->t = NULL;
  4494. i->index = SIZE_MAX;
  4495. i->array_part = false;
  4496. }
  4497. bool upb_inttable_iter_isequal(const upb_inttable_iter *i1,
  4498. const upb_inttable_iter *i2) {
  4499. if (upb_inttable_done(i1) && upb_inttable_done(i2))
  4500. return true;
  4501. return i1->t == i2->t && i1->index == i2->index &&
  4502. i1->array_part == i2->array_part;
  4503. }
  4504. #if defined(UPB_UNALIGNED_READS_OK) || defined(__s390x__)
  4505. /* -----------------------------------------------------------------------------
  4506. * MurmurHash2, by Austin Appleby (released as public domain).
  4507. * Reformatted and C99-ified by Joshua Haberman.
  4508. * Note - This code makes a few assumptions about how your machine behaves -
  4509. * 1. We can read a 4-byte value from any address without crashing
  4510. * 2. sizeof(int) == 4 (in upb this limitation is removed by using uint32_t
  4511. * And it has a few limitations -
  4512. * 1. It will not work incrementally.
  4513. * 2. It will not produce the same results on little-endian and big-endian
  4514. * machines. */
  4515. uint32_t MurmurHash2(const void *key, size_t len, uint32_t seed) {
  4516. /* 'm' and 'r' are mixing constants generated offline.
  4517. * They're not really 'magic', they just happen to work well. */
  4518. const uint32_t m = 0x5bd1e995;
  4519. const int32_t r = 24;
  4520. /* Initialize the hash to a 'random' value */
  4521. uint32_t h = seed ^ len;
  4522. /* Mix 4 bytes at a time into the hash */
  4523. const uint8_t * data = (const uint8_t *)key;
  4524. while(len >= 4) {
  4525. uint32_t k = *(uint32_t *)data;
  4526. k *= m;
  4527. k ^= k >> r;
  4528. k *= m;
  4529. h *= m;
  4530. h ^= k;
  4531. data += 4;
  4532. len -= 4;
  4533. }
  4534. /* Handle the last few bytes of the input array */
  4535. switch(len) {
  4536. case 3: h ^= data[2] << 16;
  4537. case 2: h ^= data[1] << 8;
  4538. case 1: h ^= data[0]; h *= m;
  4539. };
  4540. /* Do a few final mixes of the hash to ensure the last few
  4541. * bytes are well-incorporated. */
  4542. h ^= h >> 13;
  4543. h *= m;
  4544. h ^= h >> 15;
  4545. return h;
  4546. }
  4547. #else /* !UPB_UNALIGNED_READS_OK */
  4548. /* -----------------------------------------------------------------------------
  4549. * MurmurHashAligned2, by Austin Appleby
  4550. * Same algorithm as MurmurHash2, but only does aligned reads - should be safer
  4551. * on certain platforms.
  4552. * Performance will be lower than MurmurHash2 */
  4553. #define MIX(h,k,m) { k *= m; k ^= k >> r; k *= m; h *= m; h ^= k; }
  4554. uint32_t MurmurHash2(const void * key, size_t len, uint32_t seed) {
  4555. const uint32_t m = 0x5bd1e995;
  4556. const int32_t r = 24;
  4557. const uint8_t * data = (const uint8_t *)key;
  4558. uint32_t h = seed ^ len;
  4559. uint8_t align = (uintptr_t)data & 3;
  4560. if(align && (len >= 4)) {
  4561. /* Pre-load the temp registers */
  4562. uint32_t t = 0, d = 0;
  4563. int32_t sl;
  4564. int32_t sr;
  4565. switch(align) {
  4566. case 1: t |= data[2] << 16;
  4567. case 2: t |= data[1] << 8;
  4568. case 3: t |= data[0];
  4569. }
  4570. t <<= (8 * align);
  4571. data += 4-align;
  4572. len -= 4-align;
  4573. sl = 8 * (4-align);
  4574. sr = 8 * align;
  4575. /* Mix */
  4576. while(len >= 4) {
  4577. uint32_t k;
  4578. d = *(uint32_t *)data;
  4579. t = (t >> sr) | (d << sl);
  4580. k = t;
  4581. MIX(h,k,m);
  4582. t = d;
  4583. data += 4;
  4584. len -= 4;
  4585. }
  4586. /* Handle leftover data in temp registers */
  4587. d = 0;
  4588. if(len >= align) {
  4589. uint32_t k;
  4590. switch(align) {
  4591. case 3: d |= data[2] << 16;
  4592. case 2: d |= data[1] << 8;
  4593. case 1: d |= data[0];
  4594. }
  4595. k = (t >> sr) | (d << sl);
  4596. MIX(h,k,m);
  4597. data += align;
  4598. len -= align;
  4599. /* ----------
  4600. * Handle tail bytes */
  4601. switch(len) {
  4602. case 3: h ^= data[2] << 16;
  4603. case 2: h ^= data[1] << 8;
  4604. case 1: h ^= data[0]; h *= m;
  4605. };
  4606. } else {
  4607. switch(len) {
  4608. case 3: d |= data[2] << 16;
  4609. case 2: d |= data[1] << 8;
  4610. case 1: d |= data[0];
  4611. case 0: h ^= (t >> sr) | (d << sl); h *= m;
  4612. }
  4613. }
  4614. h ^= h >> 13;
  4615. h *= m;
  4616. h ^= h >> 15;
  4617. return h;
  4618. } else {
  4619. while(len >= 4) {
  4620. uint32_t k = *(uint32_t *)data;
  4621. MIX(h,k,m);
  4622. data += 4;
  4623. len -= 4;
  4624. }
  4625. /* ----------
  4626. * Handle tail bytes */
  4627. switch(len) {
  4628. case 3: h ^= data[2] << 16;
  4629. case 2: h ^= data[1] << 8;
  4630. case 1: h ^= data[0]; h *= m;
  4631. };
  4632. h ^= h >> 13;
  4633. h *= m;
  4634. h ^= h >> 15;
  4635. return h;
  4636. }
  4637. }
  4638. #undef MIX
  4639. #endif /* UPB_UNALIGNED_READS_OK */
  4640. #include <errno.h>
  4641. #include <stdarg.h>
  4642. #include <stddef.h>
  4643. #include <stdint.h>
  4644. #include <stdio.h>
  4645. #include <stdlib.h>
  4646. #include <string.h>
  4647. /* Guarantee null-termination and provide ellipsis truncation.
  4648. * It may be tempting to "optimize" this by initializing these final
  4649. * four bytes up-front and then being careful never to overwrite them,
  4650. * this is safer and simpler. */
  4651. static void nullz(upb_status *status) {
  4652. const char *ellipsis = "...";
  4653. size_t len = strlen(ellipsis);
  4654. UPB_ASSERT(sizeof(status->msg) > len);
  4655. memcpy(status->msg + sizeof(status->msg) - len, ellipsis, len);
  4656. }
  4657. /* upb_status *****************************************************************/
  4658. void upb_status_clear(upb_status *status) {
  4659. if (!status) return;
  4660. status->ok = true;
  4661. status->msg[0] = '\0';
  4662. }
  4663. bool upb_ok(const upb_status *status) { return status->ok; }
  4664. const char *upb_status_errmsg(const upb_status *status) { return status->msg; }
  4665. void upb_status_seterrmsg(upb_status *status, const char *msg) {
  4666. if (!status) return;
  4667. status->ok = false;
  4668. strncpy(status->msg, msg, sizeof(status->msg));
  4669. nullz(status);
  4670. }
  4671. void upb_status_seterrf(upb_status *status, const char *fmt, ...) {
  4672. va_list args;
  4673. va_start(args, fmt);
  4674. upb_status_vseterrf(status, fmt, args);
  4675. va_end(args);
  4676. }
  4677. void upb_status_vseterrf(upb_status *status, const char *fmt, va_list args) {
  4678. if (!status) return;
  4679. status->ok = false;
  4680. _upb_vsnprintf(status->msg, sizeof(status->msg), fmt, args);
  4681. nullz(status);
  4682. }
  4683. /* upb_alloc ******************************************************************/
  4684. static void *upb_global_allocfunc(upb_alloc *alloc, void *ptr, size_t oldsize,
  4685. size_t size) {
  4686. UPB_UNUSED(alloc);
  4687. UPB_UNUSED(oldsize);
  4688. if (size == 0) {
  4689. free(ptr);
  4690. return NULL;
  4691. } else {
  4692. return realloc(ptr, size);
  4693. }
  4694. }
  4695. upb_alloc upb_alloc_global = {&upb_global_allocfunc};
  4696. /* upb_arena ******************************************************************/
  4697. /* Be conservative and choose 16 in case anyone is using SSE. */
  4698. static const size_t maxalign = 16;
  4699. static size_t align_up_max(size_t size) {
  4700. return ((size + maxalign - 1) / maxalign) * maxalign;
  4701. }
  4702. struct upb_arena {
  4703. /* We implement the allocator interface.
  4704. * This must be the first member of upb_arena! */
  4705. upb_alloc alloc;
  4706. /* Allocator to allocate arena blocks. We are responsible for freeing these
  4707. * when we are destroyed. */
  4708. upb_alloc *block_alloc;
  4709. size_t bytes_allocated;
  4710. size_t next_block_size;
  4711. size_t max_block_size;
  4712. /* Linked list of blocks. Points to an arena_block, defined in env.c */
  4713. void *block_head;
  4714. /* Cleanup entries. Pointer to a cleanup_ent, defined in env.c */
  4715. void *cleanup_head;
  4716. };
  4717. typedef struct mem_block {
  4718. struct mem_block *next;
  4719. size_t size;
  4720. size_t used;
  4721. bool owned;
  4722. /* Data follows. */
  4723. } mem_block;
  4724. typedef struct cleanup_ent {
  4725. struct cleanup_ent *next;
  4726. upb_cleanup_func *cleanup;
  4727. void *ud;
  4728. } cleanup_ent;
  4729. static void upb_arena_addblock(upb_arena *a, void *ptr, size_t size,
  4730. bool owned) {
  4731. mem_block *block = ptr;
  4732. block->next = a->block_head;
  4733. block->size = size;
  4734. block->used = align_up_max(sizeof(mem_block));
  4735. block->owned = owned;
  4736. a->block_head = block;
  4737. /* TODO(haberman): ASAN poison. */
  4738. }
  4739. static mem_block *upb_arena_allocblock(upb_arena *a, size_t size) {
  4740. size_t block_size = UPB_MAX(size, a->next_block_size) + sizeof(mem_block);
  4741. mem_block *block = upb_malloc(a->block_alloc, block_size);
  4742. if (!block) {
  4743. return NULL;
  4744. }
  4745. upb_arena_addblock(a, block, block_size, true);
  4746. a->next_block_size = UPB_MIN(block_size * 2, a->max_block_size);
  4747. return block;
  4748. }
  4749. static void *upb_arena_doalloc(upb_alloc *alloc, void *ptr, size_t oldsize,
  4750. size_t size) {
  4751. upb_arena *a = (upb_arena*)alloc; /* upb_alloc is initial member. */
  4752. mem_block *block = a->block_head;
  4753. void *ret;
  4754. if (size == 0) {
  4755. return NULL; /* We are an arena, don't need individual frees. */
  4756. }
  4757. size = align_up_max(size);
  4758. /* TODO(haberman): special-case if this is a realloc of the last alloc? */
  4759. if (!block || block->size - block->used < size) {
  4760. /* Slow path: have to allocate a new block. */
  4761. block = upb_arena_allocblock(a, size);
  4762. if (!block) {
  4763. return NULL; /* Out of memory. */
  4764. }
  4765. }
  4766. ret = (char*)block + block->used;
  4767. block->used += size;
  4768. if (oldsize > 0) {
  4769. memcpy(ret, ptr, oldsize); /* Preserve existing data. */
  4770. }
  4771. /* TODO(haberman): ASAN unpoison. */
  4772. a->bytes_allocated += size;
  4773. return ret;
  4774. }
  4775. /* Public Arena API ***********************************************************/
  4776. #define upb_alignof(type) offsetof (struct { char c; type member; }, member)
  4777. upb_arena *upb_arena_init(void *mem, size_t n, upb_alloc *alloc) {
  4778. const size_t first_block_overhead = sizeof(upb_arena) + sizeof(mem_block);
  4779. upb_arena *a;
  4780. bool owned = false;
  4781. /* Round block size down to alignof(*a) since we will allocate the arena
  4782. * itself at the end. */
  4783. n &= ~(upb_alignof(upb_arena) - 1);
  4784. if (n < first_block_overhead) {
  4785. /* We need to malloc the initial block. */
  4786. n = first_block_overhead + 256;
  4787. owned = true;
  4788. if (!alloc || !(mem = upb_malloc(alloc, n))) {
  4789. return NULL;
  4790. }
  4791. }
  4792. a = (void*)((char*)mem + n - sizeof(*a));
  4793. n -= sizeof(*a);
  4794. a->alloc.func = &upb_arena_doalloc;
  4795. a->block_alloc = &upb_alloc_global;
  4796. a->bytes_allocated = 0;
  4797. a->next_block_size = 256;
  4798. a->max_block_size = 16384;
  4799. a->cleanup_head = NULL;
  4800. a->block_head = NULL;
  4801. a->block_alloc = alloc;
  4802. upb_arena_addblock(a, mem, n, owned);
  4803. return a;
  4804. }
  4805. #undef upb_alignof
  4806. void upb_arena_free(upb_arena *a) {
  4807. cleanup_ent *ent = a->cleanup_head;
  4808. mem_block *block = a->block_head;
  4809. while (ent) {
  4810. ent->cleanup(ent->ud);
  4811. ent = ent->next;
  4812. }
  4813. /* Must do this after running cleanup functions, because this will delete
  4814. * the memory we store our cleanup entries in! */
  4815. while (block) {
  4816. /* Load first since we are deleting block. */
  4817. mem_block *next = block->next;
  4818. if (block->owned) {
  4819. upb_free(a->block_alloc, block);
  4820. }
  4821. block = next;
  4822. }
  4823. }
  4824. bool upb_arena_addcleanup(upb_arena *a, void *ud, upb_cleanup_func *func) {
  4825. cleanup_ent *ent = upb_malloc(&a->alloc, sizeof(cleanup_ent));
  4826. if (!ent) {
  4827. return false; /* Out of memory. */
  4828. }
  4829. ent->cleanup = func;
  4830. ent->ud = ud;
  4831. ent->next = a->cleanup_head;
  4832. a->cleanup_head = ent;
  4833. return true;
  4834. }
  4835. size_t upb_arena_bytesallocated(const upb_arena *a) {
  4836. return a->bytes_allocated;
  4837. }
  4838. /*
  4839. ** protobuf decoder bytecode compiler
  4840. **
  4841. ** Code to compile a upb::Handlers into bytecode for decoding a protobuf
  4842. ** according to that specific schema and destination handlers.
  4843. **
  4844. ** Bytecode definition is in decoder.int.h.
  4845. */
  4846. #include <stdarg.h>
  4847. #ifdef UPB_DUMP_BYTECODE
  4848. #include <stdio.h>
  4849. #endif
  4850. #define MAXLABEL 5
  4851. #define EMPTYLABEL -1
  4852. /* upb_pbdecodermethod ********************************************************/
  4853. static void freemethod(upb_pbdecodermethod *method) {
  4854. upb_inttable_uninit(&method->dispatch);
  4855. upb_gfree(method);
  4856. }
  4857. static upb_pbdecodermethod *newmethod(const upb_handlers *dest_handlers,
  4858. mgroup *group) {
  4859. upb_pbdecodermethod *ret = upb_gmalloc(sizeof(*ret));
  4860. upb_byteshandler_init(&ret->input_handler_);
  4861. ret->group = group;
  4862. ret->dest_handlers_ = dest_handlers;
  4863. upb_inttable_init(&ret->dispatch, UPB_CTYPE_UINT64);
  4864. return ret;
  4865. }
  4866. const upb_handlers *upb_pbdecodermethod_desthandlers(
  4867. const upb_pbdecodermethod *m) {
  4868. return m->dest_handlers_;
  4869. }
  4870. const upb_byteshandler *upb_pbdecodermethod_inputhandler(
  4871. const upb_pbdecodermethod *m) {
  4872. return &m->input_handler_;
  4873. }
  4874. bool upb_pbdecodermethod_isnative(const upb_pbdecodermethod *m) {
  4875. return m->is_native_;
  4876. }
  4877. /* mgroup *********************************************************************/
  4878. static void freegroup(mgroup *g) {
  4879. upb_inttable_iter i;
  4880. upb_inttable_begin(&i, &g->methods);
  4881. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  4882. freemethod(upb_value_getptr(upb_inttable_iter_value(&i)));
  4883. }
  4884. upb_inttable_uninit(&g->methods);
  4885. upb_gfree(g->bytecode);
  4886. upb_gfree(g);
  4887. }
  4888. mgroup *newgroup() {
  4889. mgroup *g = upb_gmalloc(sizeof(*g));
  4890. upb_inttable_init(&g->methods, UPB_CTYPE_PTR);
  4891. g->bytecode = NULL;
  4892. g->bytecode_end = NULL;
  4893. return g;
  4894. }
  4895. /* bytecode compiler **********************************************************/
  4896. /* Data used only at compilation time. */
  4897. typedef struct {
  4898. mgroup *group;
  4899. uint32_t *pc;
  4900. int fwd_labels[MAXLABEL];
  4901. int back_labels[MAXLABEL];
  4902. /* For fields marked "lazy", parse them lazily or eagerly? */
  4903. bool lazy;
  4904. } compiler;
  4905. static compiler *newcompiler(mgroup *group, bool lazy) {
  4906. compiler *ret = upb_gmalloc(sizeof(*ret));
  4907. int i;
  4908. ret->group = group;
  4909. ret->lazy = lazy;
  4910. for (i = 0; i < MAXLABEL; i++) {
  4911. ret->fwd_labels[i] = EMPTYLABEL;
  4912. ret->back_labels[i] = EMPTYLABEL;
  4913. }
  4914. return ret;
  4915. }
  4916. static void freecompiler(compiler *c) {
  4917. upb_gfree(c);
  4918. }
  4919. const size_t ptr_words = sizeof(void*) / sizeof(uint32_t);
  4920. /* How many words an instruction is. */
  4921. static int instruction_len(uint32_t instr) {
  4922. switch (getop(instr)) {
  4923. case OP_SETDISPATCH: return 1 + ptr_words;
  4924. case OP_TAGN: return 3;
  4925. case OP_SETBIGGROUPNUM: return 2;
  4926. default: return 1;
  4927. }
  4928. }
  4929. bool op_has_longofs(int32_t instruction) {
  4930. switch (getop(instruction)) {
  4931. case OP_CALL:
  4932. case OP_BRANCH:
  4933. case OP_CHECKDELIM:
  4934. return true;
  4935. /* The "tag" instructions only have 8 bytes available for the jump target,
  4936. * but that is ok because these opcodes only require short jumps. */
  4937. case OP_TAG1:
  4938. case OP_TAG2:
  4939. case OP_TAGN:
  4940. return false;
  4941. default:
  4942. UPB_ASSERT(false);
  4943. return false;
  4944. }
  4945. }
  4946. static int32_t getofs(uint32_t instruction) {
  4947. if (op_has_longofs(instruction)) {
  4948. return (int32_t)instruction >> 8;
  4949. } else {
  4950. return (int8_t)(instruction >> 8);
  4951. }
  4952. }
  4953. static void setofs(uint32_t *instruction, int32_t ofs) {
  4954. if (op_has_longofs(*instruction)) {
  4955. *instruction = getop(*instruction) | ofs << 8;
  4956. } else {
  4957. *instruction = (*instruction & ~0xff00) | ((ofs & 0xff) << 8);
  4958. }
  4959. UPB_ASSERT(getofs(*instruction) == ofs); /* Would fail in cases of overflow. */
  4960. }
  4961. static uint32_t pcofs(compiler *c) { return c->pc - c->group->bytecode; }
  4962. /* Defines a local label at the current PC location. All previous forward
  4963. * references are updated to point to this location. The location is noted
  4964. * for any future backward references. */
  4965. static void label(compiler *c, unsigned int label) {
  4966. int val;
  4967. uint32_t *codep;
  4968. UPB_ASSERT(label < MAXLABEL);
  4969. val = c->fwd_labels[label];
  4970. codep = (val == EMPTYLABEL) ? NULL : c->group->bytecode + val;
  4971. while (codep) {
  4972. int ofs = getofs(*codep);
  4973. setofs(codep, c->pc - codep - instruction_len(*codep));
  4974. codep = ofs ? codep + ofs : NULL;
  4975. }
  4976. c->fwd_labels[label] = EMPTYLABEL;
  4977. c->back_labels[label] = pcofs(c);
  4978. }
  4979. /* Creates a reference to a numbered label; either a forward reference
  4980. * (positive arg) or backward reference (negative arg). For forward references
  4981. * the value returned now is actually a "next" pointer into a linked list of all
  4982. * instructions that use this label and will be patched later when the label is
  4983. * defined with label().
  4984. *
  4985. * The returned value is the offset that should be written into the instruction.
  4986. */
  4987. static int32_t labelref(compiler *c, int label) {
  4988. UPB_ASSERT(label < MAXLABEL);
  4989. if (label == LABEL_DISPATCH) {
  4990. /* No resolving required. */
  4991. return 0;
  4992. } else if (label < 0) {
  4993. /* Backward local label. Relative to the next instruction. */
  4994. uint32_t from = (c->pc + 1) - c->group->bytecode;
  4995. return c->back_labels[-label] - from;
  4996. } else {
  4997. /* Forward local label: prepend to (possibly-empty) linked list. */
  4998. int *lptr = &c->fwd_labels[label];
  4999. int32_t ret = (*lptr == EMPTYLABEL) ? 0 : *lptr - pcofs(c);
  5000. *lptr = pcofs(c);
  5001. return ret;
  5002. }
  5003. }
  5004. static void put32(compiler *c, uint32_t v) {
  5005. mgroup *g = c->group;
  5006. if (c->pc == g->bytecode_end) {
  5007. int ofs = pcofs(c);
  5008. size_t oldsize = g->bytecode_end - g->bytecode;
  5009. size_t newsize = UPB_MAX(oldsize * 2, 64);
  5010. /* TODO(haberman): handle OOM. */
  5011. g->bytecode = upb_grealloc(g->bytecode, oldsize * sizeof(uint32_t),
  5012. newsize * sizeof(uint32_t));
  5013. g->bytecode_end = g->bytecode + newsize;
  5014. c->pc = g->bytecode + ofs;
  5015. }
  5016. *c->pc++ = v;
  5017. }
  5018. static void putop(compiler *c, int op, ...) {
  5019. va_list ap;
  5020. va_start(ap, op);
  5021. switch (op) {
  5022. case OP_SETDISPATCH: {
  5023. uintptr_t ptr = (uintptr_t)va_arg(ap, void*);
  5024. put32(c, OP_SETDISPATCH);
  5025. put32(c, ptr);
  5026. if (sizeof(uintptr_t) > sizeof(uint32_t))
  5027. put32(c, (uint64_t)ptr >> 32);
  5028. break;
  5029. }
  5030. case OP_STARTMSG:
  5031. case OP_ENDMSG:
  5032. case OP_PUSHLENDELIM:
  5033. case OP_POP:
  5034. case OP_SETDELIM:
  5035. case OP_HALT:
  5036. case OP_RET:
  5037. case OP_DISPATCH:
  5038. put32(c, op);
  5039. break;
  5040. case OP_PARSE_DOUBLE:
  5041. case OP_PARSE_FLOAT:
  5042. case OP_PARSE_INT64:
  5043. case OP_PARSE_UINT64:
  5044. case OP_PARSE_INT32:
  5045. case OP_PARSE_FIXED64:
  5046. case OP_PARSE_FIXED32:
  5047. case OP_PARSE_BOOL:
  5048. case OP_PARSE_UINT32:
  5049. case OP_PARSE_SFIXED32:
  5050. case OP_PARSE_SFIXED64:
  5051. case OP_PARSE_SINT32:
  5052. case OP_PARSE_SINT64:
  5053. case OP_STARTSEQ:
  5054. case OP_ENDSEQ:
  5055. case OP_STARTSUBMSG:
  5056. case OP_ENDSUBMSG:
  5057. case OP_STARTSTR:
  5058. case OP_STRING:
  5059. case OP_ENDSTR:
  5060. case OP_PUSHTAGDELIM:
  5061. put32(c, op | va_arg(ap, upb_selector_t) << 8);
  5062. break;
  5063. case OP_SETBIGGROUPNUM:
  5064. put32(c, op);
  5065. put32(c, va_arg(ap, int));
  5066. break;
  5067. case OP_CALL: {
  5068. const upb_pbdecodermethod *method = va_arg(ap, upb_pbdecodermethod *);
  5069. put32(c, op | (method->code_base.ofs - (pcofs(c) + 1)) << 8);
  5070. break;
  5071. }
  5072. case OP_CHECKDELIM:
  5073. case OP_BRANCH: {
  5074. uint32_t instruction = op;
  5075. int label = va_arg(ap, int);
  5076. setofs(&instruction, labelref(c, label));
  5077. put32(c, instruction);
  5078. break;
  5079. }
  5080. case OP_TAG1:
  5081. case OP_TAG2: {
  5082. int label = va_arg(ap, int);
  5083. uint64_t tag = va_arg(ap, uint64_t);
  5084. uint32_t instruction = op | (tag << 16);
  5085. UPB_ASSERT(tag <= 0xffff);
  5086. setofs(&instruction, labelref(c, label));
  5087. put32(c, instruction);
  5088. break;
  5089. }
  5090. case OP_TAGN: {
  5091. int label = va_arg(ap, int);
  5092. uint64_t tag = va_arg(ap, uint64_t);
  5093. uint32_t instruction = op | (upb_value_size(tag) << 16);
  5094. setofs(&instruction, labelref(c, label));
  5095. put32(c, instruction);
  5096. put32(c, tag);
  5097. put32(c, tag >> 32);
  5098. break;
  5099. }
  5100. }
  5101. va_end(ap);
  5102. }
  5103. #if defined(UPB_DUMP_BYTECODE)
  5104. const char *upb_pbdecoder_getopname(unsigned int op) {
  5105. #define QUOTE(x) #x
  5106. #define EXPAND_AND_QUOTE(x) QUOTE(x)
  5107. #define OPNAME(x) OP_##x
  5108. #define OP(x) case OPNAME(x): return EXPAND_AND_QUOTE(OPNAME(x));
  5109. #define T(x) OP(PARSE_##x)
  5110. /* Keep in sync with list in decoder.int.h. */
  5111. switch ((opcode)op) {
  5112. T(DOUBLE) T(FLOAT) T(INT64) T(UINT64) T(INT32) T(FIXED64) T(FIXED32)
  5113. T(BOOL) T(UINT32) T(SFIXED32) T(SFIXED64) T(SINT32) T(SINT64)
  5114. OP(STARTMSG) OP(ENDMSG) OP(STARTSEQ) OP(ENDSEQ) OP(STARTSUBMSG)
  5115. OP(ENDSUBMSG) OP(STARTSTR) OP(STRING) OP(ENDSTR) OP(CALL) OP(RET)
  5116. OP(PUSHLENDELIM) OP(PUSHTAGDELIM) OP(SETDELIM) OP(CHECKDELIM)
  5117. OP(BRANCH) OP(TAG1) OP(TAG2) OP(TAGN) OP(SETDISPATCH) OP(POP)
  5118. OP(SETBIGGROUPNUM) OP(DISPATCH) OP(HALT)
  5119. }
  5120. return "<unknown op>";
  5121. #undef OP
  5122. #undef T
  5123. }
  5124. #endif
  5125. #ifdef UPB_DUMP_BYTECODE
  5126. static void dumpbc(uint32_t *p, uint32_t *end, FILE *f) {
  5127. uint32_t *begin = p;
  5128. while (p < end) {
  5129. fprintf(f, "%p %8tx", p, p - begin);
  5130. uint32_t instr = *p++;
  5131. uint8_t op = getop(instr);
  5132. fprintf(f, " %s", upb_pbdecoder_getopname(op));
  5133. switch ((opcode)op) {
  5134. case OP_SETDISPATCH: {
  5135. const upb_inttable *dispatch;
  5136. memcpy(&dispatch, p, sizeof(void*));
  5137. p += ptr_words;
  5138. const upb_pbdecodermethod *method =
  5139. (void *)((char *)dispatch -
  5140. offsetof(upb_pbdecodermethod, dispatch));
  5141. fprintf(f, " %s", upb_msgdef_fullname(
  5142. upb_handlers_msgdef(method->dest_handlers_)));
  5143. break;
  5144. }
  5145. case OP_DISPATCH:
  5146. case OP_STARTMSG:
  5147. case OP_ENDMSG:
  5148. case OP_PUSHLENDELIM:
  5149. case OP_POP:
  5150. case OP_SETDELIM:
  5151. case OP_HALT:
  5152. case OP_RET:
  5153. break;
  5154. case OP_PARSE_DOUBLE:
  5155. case OP_PARSE_FLOAT:
  5156. case OP_PARSE_INT64:
  5157. case OP_PARSE_UINT64:
  5158. case OP_PARSE_INT32:
  5159. case OP_PARSE_FIXED64:
  5160. case OP_PARSE_FIXED32:
  5161. case OP_PARSE_BOOL:
  5162. case OP_PARSE_UINT32:
  5163. case OP_PARSE_SFIXED32:
  5164. case OP_PARSE_SFIXED64:
  5165. case OP_PARSE_SINT32:
  5166. case OP_PARSE_SINT64:
  5167. case OP_STARTSEQ:
  5168. case OP_ENDSEQ:
  5169. case OP_STARTSUBMSG:
  5170. case OP_ENDSUBMSG:
  5171. case OP_STARTSTR:
  5172. case OP_STRING:
  5173. case OP_ENDSTR:
  5174. case OP_PUSHTAGDELIM:
  5175. fprintf(f, " %d", instr >> 8);
  5176. break;
  5177. case OP_SETBIGGROUPNUM:
  5178. fprintf(f, " %d", *p++);
  5179. break;
  5180. case OP_CHECKDELIM:
  5181. case OP_CALL:
  5182. case OP_BRANCH:
  5183. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  5184. break;
  5185. case OP_TAG1:
  5186. case OP_TAG2: {
  5187. fprintf(f, " tag:0x%x", instr >> 16);
  5188. if (getofs(instr)) {
  5189. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  5190. }
  5191. break;
  5192. }
  5193. case OP_TAGN: {
  5194. uint64_t tag = *p++;
  5195. tag |= (uint64_t)*p++ << 32;
  5196. fprintf(f, " tag:0x%llx", (long long)tag);
  5197. fprintf(f, " n:%d", instr >> 16);
  5198. if (getofs(instr)) {
  5199. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  5200. }
  5201. break;
  5202. }
  5203. }
  5204. fputs("\n", f);
  5205. }
  5206. }
  5207. #endif
  5208. static uint64_t get_encoded_tag(const upb_fielddef *f, int wire_type) {
  5209. uint32_t tag = (upb_fielddef_number(f) << 3) | wire_type;
  5210. uint64_t encoded_tag = upb_vencode32(tag);
  5211. /* No tag should be greater than 5 bytes. */
  5212. UPB_ASSERT(encoded_tag <= 0xffffffffff);
  5213. return encoded_tag;
  5214. }
  5215. static void putchecktag(compiler *c, const upb_fielddef *f,
  5216. int wire_type, int dest) {
  5217. uint64_t tag = get_encoded_tag(f, wire_type);
  5218. switch (upb_value_size(tag)) {
  5219. case 1:
  5220. putop(c, OP_TAG1, dest, tag);
  5221. break;
  5222. case 2:
  5223. putop(c, OP_TAG2, dest, tag);
  5224. break;
  5225. default:
  5226. putop(c, OP_TAGN, dest, tag);
  5227. break;
  5228. }
  5229. }
  5230. static upb_selector_t getsel(const upb_fielddef *f, upb_handlertype_t type) {
  5231. upb_selector_t selector;
  5232. bool ok = upb_handlers_getselector(f, type, &selector);
  5233. UPB_ASSERT(ok);
  5234. return selector;
  5235. }
  5236. /* Takes an existing, primary dispatch table entry and repacks it with a
  5237. * different alternate wire type. Called when we are inserting a secondary
  5238. * dispatch table entry for an alternate wire type. */
  5239. static uint64_t repack(uint64_t dispatch, int new_wt2) {
  5240. uint64_t ofs;
  5241. uint8_t wt1;
  5242. uint8_t old_wt2;
  5243. upb_pbdecoder_unpackdispatch(dispatch, &ofs, &wt1, &old_wt2);
  5244. UPB_ASSERT(old_wt2 == NO_WIRE_TYPE); /* wt2 should not be set yet. */
  5245. return upb_pbdecoder_packdispatch(ofs, wt1, new_wt2);
  5246. }
  5247. /* Marks the current bytecode position as the dispatch target for this message,
  5248. * field, and wire type. */
  5249. static void dispatchtarget(compiler *c, upb_pbdecodermethod *method,
  5250. const upb_fielddef *f, int wire_type) {
  5251. /* Offset is relative to msg base. */
  5252. uint64_t ofs = pcofs(c) - method->code_base.ofs;
  5253. uint32_t fn = upb_fielddef_number(f);
  5254. upb_inttable *d = &method->dispatch;
  5255. upb_value v;
  5256. if (upb_inttable_remove(d, fn, &v)) {
  5257. /* TODO: prioritize based on packed setting in .proto file. */
  5258. uint64_t repacked = repack(upb_value_getuint64(v), wire_type);
  5259. upb_inttable_insert(d, fn, upb_value_uint64(repacked));
  5260. upb_inttable_insert(d, fn + UPB_MAX_FIELDNUMBER, upb_value_uint64(ofs));
  5261. } else {
  5262. uint64_t val = upb_pbdecoder_packdispatch(ofs, wire_type, NO_WIRE_TYPE);
  5263. upb_inttable_insert(d, fn, upb_value_uint64(val));
  5264. }
  5265. }
  5266. static void putpush(compiler *c, const upb_fielddef *f) {
  5267. if (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE) {
  5268. putop(c, OP_PUSHLENDELIM);
  5269. } else {
  5270. uint32_t fn = upb_fielddef_number(f);
  5271. if (fn >= 1 << 24) {
  5272. putop(c, OP_PUSHTAGDELIM, 0);
  5273. putop(c, OP_SETBIGGROUPNUM, fn);
  5274. } else {
  5275. putop(c, OP_PUSHTAGDELIM, fn);
  5276. }
  5277. }
  5278. }
  5279. static upb_pbdecodermethod *find_submethod(const compiler *c,
  5280. const upb_pbdecodermethod *method,
  5281. const upb_fielddef *f) {
  5282. const upb_handlers *sub =
  5283. upb_handlers_getsubhandlers(method->dest_handlers_, f);
  5284. upb_value v;
  5285. return upb_inttable_lookupptr(&c->group->methods, sub, &v)
  5286. ? upb_value_getptr(v)
  5287. : NULL;
  5288. }
  5289. static void putsel(compiler *c, opcode op, upb_selector_t sel,
  5290. const upb_handlers *h) {
  5291. if (upb_handlers_gethandler(h, sel, NULL)) {
  5292. putop(c, op, sel);
  5293. }
  5294. }
  5295. /* Puts an opcode to call a callback, but only if a callback actually exists for
  5296. * this field and handler type. */
  5297. static void maybeput(compiler *c, opcode op, const upb_handlers *h,
  5298. const upb_fielddef *f, upb_handlertype_t type) {
  5299. putsel(c, op, getsel(f, type), h);
  5300. }
  5301. static bool haslazyhandlers(const upb_handlers *h, const upb_fielddef *f) {
  5302. if (!upb_fielddef_lazy(f))
  5303. return false;
  5304. return upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STARTSTR), NULL) ||
  5305. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STRING), NULL) ||
  5306. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_ENDSTR), NULL);
  5307. }
  5308. /* bytecode compiler code generation ******************************************/
  5309. /* Symbolic names for our local labels. */
  5310. #define LABEL_LOOPSTART 1 /* Top of a repeated field loop. */
  5311. #define LABEL_LOOPBREAK 2 /* To jump out of a repeated loop */
  5312. #define LABEL_FIELD 3 /* Jump backward to find the most recent field. */
  5313. #define LABEL_ENDMSG 4 /* To reach the OP_ENDMSG instr for this msg. */
  5314. /* Generates bytecode to parse a single non-lazy message field. */
  5315. static void generate_msgfield(compiler *c, const upb_fielddef *f,
  5316. upb_pbdecodermethod *method) {
  5317. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  5318. const upb_pbdecodermethod *sub_m = find_submethod(c, method, f);
  5319. int wire_type;
  5320. if (!sub_m) {
  5321. /* Don't emit any code for this field at all; it will be parsed as an
  5322. * unknown field.
  5323. *
  5324. * TODO(haberman): we should change this to parse it as a string field
  5325. * instead. It will probably be faster, but more importantly, once we
  5326. * start vending unknown fields, a field shouldn't be treated as unknown
  5327. * just because it doesn't have subhandlers registered. */
  5328. return;
  5329. }
  5330. label(c, LABEL_FIELD);
  5331. wire_type =
  5332. (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE)
  5333. ? UPB_WIRE_TYPE_DELIMITED
  5334. : UPB_WIRE_TYPE_START_GROUP;
  5335. if (upb_fielddef_isseq(f)) {
  5336. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5337. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  5338. dispatchtarget(c, method, f, wire_type);
  5339. putop(c, OP_PUSHTAGDELIM, 0);
  5340. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  5341. label(c, LABEL_LOOPSTART);
  5342. putpush(c, f);
  5343. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  5344. putop(c, OP_CALL, sub_m);
  5345. putop(c, OP_POP);
  5346. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  5347. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  5348. putop(c, OP_SETDELIM);
  5349. }
  5350. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5351. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  5352. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5353. label(c, LABEL_LOOPBREAK);
  5354. putop(c, OP_POP);
  5355. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  5356. } else {
  5357. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5358. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  5359. dispatchtarget(c, method, f, wire_type);
  5360. putpush(c, f);
  5361. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  5362. putop(c, OP_CALL, sub_m);
  5363. putop(c, OP_POP);
  5364. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  5365. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  5366. putop(c, OP_SETDELIM);
  5367. }
  5368. }
  5369. }
  5370. /* Generates bytecode to parse a single string or lazy submessage field. */
  5371. static void generate_delimfield(compiler *c, const upb_fielddef *f,
  5372. upb_pbdecodermethod *method) {
  5373. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  5374. label(c, LABEL_FIELD);
  5375. if (upb_fielddef_isseq(f)) {
  5376. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5377. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  5378. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  5379. putop(c, OP_PUSHTAGDELIM, 0);
  5380. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  5381. label(c, LABEL_LOOPSTART);
  5382. putop(c, OP_PUSHLENDELIM);
  5383. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  5384. /* Need to emit even if no handler to skip past the string. */
  5385. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  5386. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  5387. putop(c, OP_POP);
  5388. putop(c, OP_SETDELIM);
  5389. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5390. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_LOOPBREAK);
  5391. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5392. label(c, LABEL_LOOPBREAK);
  5393. putop(c, OP_POP);
  5394. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  5395. } else {
  5396. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5397. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  5398. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  5399. putop(c, OP_PUSHLENDELIM);
  5400. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  5401. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  5402. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  5403. putop(c, OP_POP);
  5404. putop(c, OP_SETDELIM);
  5405. }
  5406. }
  5407. /* Generates bytecode to parse a single primitive field. */
  5408. static void generate_primitivefield(compiler *c, const upb_fielddef *f,
  5409. upb_pbdecodermethod *method) {
  5410. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  5411. upb_descriptortype_t descriptor_type = upb_fielddef_descriptortype(f);
  5412. opcode parse_type;
  5413. upb_selector_t sel;
  5414. int wire_type;
  5415. label(c, LABEL_FIELD);
  5416. /* From a decoding perspective, ENUM is the same as INT32. */
  5417. if (descriptor_type == UPB_DESCRIPTOR_TYPE_ENUM)
  5418. descriptor_type = UPB_DESCRIPTOR_TYPE_INT32;
  5419. parse_type = (opcode)descriptor_type;
  5420. /* TODO(haberman): generate packed or non-packed first depending on "packed"
  5421. * setting in the fielddef. This will favor (in speed) whichever was
  5422. * specified. */
  5423. UPB_ASSERT((int)parse_type >= 0 && parse_type <= OP_MAX);
  5424. sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  5425. wire_type = upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  5426. if (upb_fielddef_isseq(f)) {
  5427. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5428. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  5429. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  5430. putop(c, OP_PUSHLENDELIM);
  5431. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); /* Packed */
  5432. label(c, LABEL_LOOPSTART);
  5433. putop(c, parse_type, sel);
  5434. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5435. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5436. dispatchtarget(c, method, f, wire_type);
  5437. putop(c, OP_PUSHTAGDELIM, 0);
  5438. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); /* Non-packed */
  5439. label(c, LABEL_LOOPSTART);
  5440. putop(c, parse_type, sel);
  5441. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5442. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  5443. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5444. label(c, LABEL_LOOPBREAK);
  5445. putop(c, OP_POP); /* Packed and non-packed join. */
  5446. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  5447. putop(c, OP_SETDELIM); /* Could remove for non-packed by dup ENDSEQ. */
  5448. } else {
  5449. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5450. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  5451. dispatchtarget(c, method, f, wire_type);
  5452. putop(c, parse_type, sel);
  5453. }
  5454. }
  5455. /* Adds bytecode for parsing the given message to the given decoderplan,
  5456. * while adding all dispatch targets to this message's dispatch table. */
  5457. static void compile_method(compiler *c, upb_pbdecodermethod *method) {
  5458. const upb_handlers *h;
  5459. const upb_msgdef *md;
  5460. uint32_t* start_pc;
  5461. upb_msg_field_iter i;
  5462. upb_value val;
  5463. UPB_ASSERT(method);
  5464. /* Clear all entries in the dispatch table. */
  5465. upb_inttable_uninit(&method->dispatch);
  5466. upb_inttable_init(&method->dispatch, UPB_CTYPE_UINT64);
  5467. h = upb_pbdecodermethod_desthandlers(method);
  5468. md = upb_handlers_msgdef(h);
  5469. method->code_base.ofs = pcofs(c);
  5470. putop(c, OP_SETDISPATCH, &method->dispatch);
  5471. putsel(c, OP_STARTMSG, UPB_STARTMSG_SELECTOR, h);
  5472. label(c, LABEL_FIELD);
  5473. start_pc = c->pc;
  5474. for(upb_msg_field_begin(&i, md);
  5475. !upb_msg_field_done(&i);
  5476. upb_msg_field_next(&i)) {
  5477. const upb_fielddef *f = upb_msg_iter_field(&i);
  5478. upb_fieldtype_t type = upb_fielddef_type(f);
  5479. if (type == UPB_TYPE_MESSAGE && !(haslazyhandlers(h, f) && c->lazy)) {
  5480. generate_msgfield(c, f, method);
  5481. } else if (type == UPB_TYPE_STRING || type == UPB_TYPE_BYTES ||
  5482. type == UPB_TYPE_MESSAGE) {
  5483. generate_delimfield(c, f, method);
  5484. } else {
  5485. generate_primitivefield(c, f, method);
  5486. }
  5487. }
  5488. /* If there were no fields, or if no handlers were defined, we need to
  5489. * generate a non-empty loop body so that we can at least dispatch for unknown
  5490. * fields and check for the end of the message. */
  5491. if (c->pc == start_pc) {
  5492. /* Check for end-of-message. */
  5493. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5494. /* Unconditionally dispatch. */
  5495. putop(c, OP_DISPATCH, 0);
  5496. }
  5497. /* For now we just loop back to the last field of the message (or if none,
  5498. * the DISPATCH opcode for the message). */
  5499. putop(c, OP_BRANCH, -LABEL_FIELD);
  5500. /* Insert both a label and a dispatch table entry for this end-of-msg. */
  5501. label(c, LABEL_ENDMSG);
  5502. val = upb_value_uint64(pcofs(c) - method->code_base.ofs);
  5503. upb_inttable_insert(&method->dispatch, DISPATCH_ENDMSG, val);
  5504. putsel(c, OP_ENDMSG, UPB_ENDMSG_SELECTOR, h);
  5505. putop(c, OP_RET);
  5506. upb_inttable_compact(&method->dispatch);
  5507. }
  5508. /* Populate "methods" with new upb_pbdecodermethod objects reachable from "h".
  5509. * Returns the method for these handlers.
  5510. *
  5511. * Generates a new method for every destination handlers reachable from "h". */
  5512. static void find_methods(compiler *c, const upb_handlers *h) {
  5513. upb_value v;
  5514. upb_msg_field_iter i;
  5515. const upb_msgdef *md;
  5516. upb_pbdecodermethod *method;
  5517. if (upb_inttable_lookupptr(&c->group->methods, h, &v))
  5518. return;
  5519. method = newmethod(h, c->group);
  5520. upb_inttable_insertptr(&c->group->methods, h, upb_value_ptr(method));
  5521. /* Find submethods. */
  5522. md = upb_handlers_msgdef(h);
  5523. for(upb_msg_field_begin(&i, md);
  5524. !upb_msg_field_done(&i);
  5525. upb_msg_field_next(&i)) {
  5526. const upb_fielddef *f = upb_msg_iter_field(&i);
  5527. const upb_handlers *sub_h;
  5528. if (upb_fielddef_type(f) == UPB_TYPE_MESSAGE &&
  5529. (sub_h = upb_handlers_getsubhandlers(h, f)) != NULL) {
  5530. /* We only generate a decoder method for submessages with handlers.
  5531. * Others will be parsed as unknown fields. */
  5532. find_methods(c, sub_h);
  5533. }
  5534. }
  5535. }
  5536. /* (Re-)compile bytecode for all messages in "msgs."
  5537. * Overwrites any existing bytecode in "c". */
  5538. static void compile_methods(compiler *c) {
  5539. upb_inttable_iter i;
  5540. /* Start over at the beginning of the bytecode. */
  5541. c->pc = c->group->bytecode;
  5542. upb_inttable_begin(&i, &c->group->methods);
  5543. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5544. upb_pbdecodermethod *method = upb_value_getptr(upb_inttable_iter_value(&i));
  5545. compile_method(c, method);
  5546. }
  5547. }
  5548. static void set_bytecode_handlers(mgroup *g) {
  5549. upb_inttable_iter i;
  5550. upb_inttable_begin(&i, &g->methods);
  5551. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5552. upb_pbdecodermethod *m = upb_value_getptr(upb_inttable_iter_value(&i));
  5553. upb_byteshandler *h = &m->input_handler_;
  5554. m->code_base.ptr = g->bytecode + m->code_base.ofs;
  5555. upb_byteshandler_setstartstr(h, upb_pbdecoder_startbc, m->code_base.ptr);
  5556. upb_byteshandler_setstring(h, upb_pbdecoder_decode, g);
  5557. upb_byteshandler_setendstr(h, upb_pbdecoder_end, m);
  5558. }
  5559. }
  5560. /* TODO(haberman): allow this to be constructed for an arbitrary set of dest
  5561. * handlers and other mgroups (but verify we have a transitive closure). */
  5562. const mgroup *mgroup_new(const upb_handlers *dest, bool allowjit, bool lazy) {
  5563. mgroup *g;
  5564. compiler *c;
  5565. UPB_UNUSED(allowjit);
  5566. g = newgroup();
  5567. c = newcompiler(g, lazy);
  5568. find_methods(c, dest);
  5569. /* We compile in two passes:
  5570. * 1. all messages are assigned relative offsets from the beginning of the
  5571. * bytecode (saved in method->code_base).
  5572. * 2. forwards OP_CALL instructions can be correctly linked since message
  5573. * offsets have been previously assigned.
  5574. *
  5575. * Could avoid the second pass by linking OP_CALL instructions somehow. */
  5576. compile_methods(c);
  5577. compile_methods(c);
  5578. g->bytecode_end = c->pc;
  5579. freecompiler(c);
  5580. #ifdef UPB_DUMP_BYTECODE
  5581. {
  5582. FILE *f = fopen("/tmp/upb-bytecode", "w");
  5583. UPB_ASSERT(f);
  5584. dumpbc(g->bytecode, g->bytecode_end, stderr);
  5585. dumpbc(g->bytecode, g->bytecode_end, f);
  5586. fclose(f);
  5587. f = fopen("/tmp/upb-bytecode.bin", "wb");
  5588. UPB_ASSERT(f);
  5589. fwrite(g->bytecode, 1, g->bytecode_end - g->bytecode, f);
  5590. fclose(f);
  5591. }
  5592. #endif
  5593. set_bytecode_handlers(g);
  5594. return g;
  5595. }
  5596. /* upb_pbcodecache ************************************************************/
  5597. upb_pbcodecache *upb_pbcodecache_new(upb_handlercache *dest) {
  5598. upb_pbcodecache *c = upb_gmalloc(sizeof(*c));
  5599. if (!c) return NULL;
  5600. c->dest = dest;
  5601. c->allow_jit = true;
  5602. c->lazy = false;
  5603. c->arena = upb_arena_new();
  5604. if (!upb_inttable_init(&c->groups, UPB_CTYPE_CONSTPTR)) return NULL;
  5605. return c;
  5606. }
  5607. void upb_pbcodecache_free(upb_pbcodecache *c) {
  5608. size_t i;
  5609. for (i = 0; i < upb_inttable_count(&c->groups); i++) {
  5610. upb_value v;
  5611. bool ok = upb_inttable_lookup(&c->groups, i, &v);
  5612. UPB_ASSERT(ok);
  5613. freegroup((void*)upb_value_getconstptr(v));
  5614. }
  5615. upb_inttable_uninit(&c->groups);
  5616. upb_arena_free(c->arena);
  5617. upb_gfree(c);
  5618. }
  5619. bool upb_pbcodecache_allowjit(const upb_pbcodecache *c) {
  5620. return c->allow_jit;
  5621. }
  5622. void upb_pbcodecache_setallowjit(upb_pbcodecache *c, bool allow) {
  5623. UPB_ASSERT(upb_inttable_count(&c->groups) == 0);
  5624. c->allow_jit = allow;
  5625. }
  5626. void upb_pbdecodermethodopts_setlazy(upb_pbcodecache *c, bool lazy) {
  5627. UPB_ASSERT(upb_inttable_count(&c->groups) == 0);
  5628. c->lazy = lazy;
  5629. }
  5630. const upb_pbdecodermethod *upb_pbcodecache_get(upb_pbcodecache *c,
  5631. const upb_msgdef *md) {
  5632. upb_value v;
  5633. bool ok;
  5634. const upb_handlers *h;
  5635. const mgroup *g;
  5636. /* Right now we build a new DecoderMethod every time.
  5637. * TODO(haberman): properly cache methods by their true key. */
  5638. h = upb_handlercache_get(c->dest, md);
  5639. g = mgroup_new(h, c->allow_jit, c->lazy);
  5640. upb_inttable_push(&c->groups, upb_value_constptr(g));
  5641. ok = upb_inttable_lookupptr(&g->methods, h, &v);
  5642. UPB_ASSERT(ok);
  5643. return upb_value_getptr(v);
  5644. }
  5645. /*
  5646. ** upb::Decoder (Bytecode Decoder VM)
  5647. **
  5648. ** Bytecode must previously have been generated using the bytecode compiler in
  5649. ** compile_decoder.c. This decoder then walks through the bytecode op-by-op to
  5650. ** parse the input.
  5651. **
  5652. ** Decoding is fully resumable; we just keep a pointer to the current bytecode
  5653. ** instruction and resume from there. A fair amount of the logic here is to
  5654. ** handle the fact that values can span buffer seams and we have to be able to
  5655. ** be capable of suspending/resuming from any byte in the stream. This
  5656. ** sometimes requires keeping a few trailing bytes from the last buffer around
  5657. ** in the "residual" buffer.
  5658. */
  5659. #include <inttypes.h>
  5660. #include <stddef.h>
  5661. #ifdef UPB_DUMP_BYTECODE
  5662. #include <stdio.h>
  5663. #endif
  5664. #define CHECK_SUSPEND(x) if (!(x)) return upb_pbdecoder_suspend(d);
  5665. /* Error messages that are shared between the bytecode and JIT decoders. */
  5666. const char *kPbDecoderStackOverflow = "Nesting too deep.";
  5667. const char *kPbDecoderSubmessageTooLong =
  5668. "Submessage end extends past enclosing submessage.";
  5669. /* Error messages shared within this file. */
  5670. static const char *kUnterminatedVarint = "Unterminated varint.";
  5671. /* upb_pbdecoder **************************************************************/
  5672. static opcode halt = OP_HALT;
  5673. /* A dummy character we can point to when the user passes us a NULL buffer.
  5674. * We need this because in C (NULL + 0) and (NULL - NULL) are undefined
  5675. * behavior, which would invalidate functions like curbufleft(). */
  5676. static const char dummy_char;
  5677. /* Whether an op consumes any of the input buffer. */
  5678. static bool consumes_input(opcode op) {
  5679. switch (op) {
  5680. case OP_SETDISPATCH:
  5681. case OP_STARTMSG:
  5682. case OP_ENDMSG:
  5683. case OP_STARTSEQ:
  5684. case OP_ENDSEQ:
  5685. case OP_STARTSUBMSG:
  5686. case OP_ENDSUBMSG:
  5687. case OP_STARTSTR:
  5688. case OP_ENDSTR:
  5689. case OP_PUSHTAGDELIM:
  5690. case OP_POP:
  5691. case OP_SETDELIM:
  5692. case OP_SETBIGGROUPNUM:
  5693. case OP_CHECKDELIM:
  5694. case OP_CALL:
  5695. case OP_RET:
  5696. case OP_BRANCH:
  5697. return false;
  5698. default:
  5699. return true;
  5700. }
  5701. }
  5702. static size_t stacksize(upb_pbdecoder *d, size_t entries) {
  5703. UPB_UNUSED(d);
  5704. return entries * sizeof(upb_pbdecoder_frame);
  5705. }
  5706. static size_t callstacksize(upb_pbdecoder *d, size_t entries) {
  5707. UPB_UNUSED(d);
  5708. #ifdef UPB_USE_JIT_X64
  5709. if (d->method_->is_native_) {
  5710. /* Each native stack frame needs two pointers, plus we need a few frames for
  5711. * the enter/exit trampolines. */
  5712. size_t ret = entries * sizeof(void*) * 2;
  5713. ret += sizeof(void*) * 10;
  5714. return ret;
  5715. }
  5716. #endif
  5717. return entries * sizeof(uint32_t*);
  5718. }
  5719. static bool in_residual_buf(const upb_pbdecoder *d, const char *p);
  5720. /* It's unfortunate that we have to micro-manage the compiler with
  5721. * UPB_FORCEINLINE and UPB_NOINLINE, especially since this tuning is necessarily
  5722. * specific to one hardware configuration. But empirically on a Core i7,
  5723. * performance increases 30-50% with these annotations. Every instance where
  5724. * these appear, gcc 4.2.1 made the wrong decision and degraded performance in
  5725. * benchmarks. */
  5726. static void seterr(upb_pbdecoder *d, const char *msg) {
  5727. upb_status_seterrmsg(d->status, msg);
  5728. }
  5729. void upb_pbdecoder_seterr(upb_pbdecoder *d, const char *msg) {
  5730. seterr(d, msg);
  5731. }
  5732. /* Buffering ******************************************************************/
  5733. /* We operate on one buffer at a time, which is either the user's buffer passed
  5734. * to our "decode" callback or some residual bytes from the previous buffer. */
  5735. /* How many bytes can be safely read from d->ptr without reading past end-of-buf
  5736. * or past the current delimited end. */
  5737. static size_t curbufleft(const upb_pbdecoder *d) {
  5738. UPB_ASSERT(d->data_end >= d->ptr);
  5739. return d->data_end - d->ptr;
  5740. }
  5741. /* How many bytes are available before end-of-buffer. */
  5742. static size_t bufleft(const upb_pbdecoder *d) {
  5743. return d->end - d->ptr;
  5744. }
  5745. /* Overall stream offset of d->ptr. */
  5746. uint64_t offset(const upb_pbdecoder *d) {
  5747. return d->bufstart_ofs + (d->ptr - d->buf);
  5748. }
  5749. /* How many bytes are available before the end of this delimited region. */
  5750. size_t delim_remaining(const upb_pbdecoder *d) {
  5751. return d->top->end_ofs - offset(d);
  5752. }
  5753. /* Advances d->ptr. */
  5754. static void advance(upb_pbdecoder *d, size_t len) {
  5755. UPB_ASSERT(curbufleft(d) >= len);
  5756. d->ptr += len;
  5757. }
  5758. static bool in_buf(const char *p, const char *buf, const char *end) {
  5759. return p >= buf && p <= end;
  5760. }
  5761. static bool in_residual_buf(const upb_pbdecoder *d, const char *p) {
  5762. return in_buf(p, d->residual, d->residual_end);
  5763. }
  5764. /* Calculates the delim_end value, which is affected by both the current buffer
  5765. * and the parsing stack, so must be called whenever either is updated. */
  5766. static void set_delim_end(upb_pbdecoder *d) {
  5767. size_t delim_ofs = d->top->end_ofs - d->bufstart_ofs;
  5768. if (delim_ofs <= (size_t)(d->end - d->buf)) {
  5769. d->delim_end = d->buf + delim_ofs;
  5770. d->data_end = d->delim_end;
  5771. } else {
  5772. d->data_end = d->end;
  5773. d->delim_end = NULL;
  5774. }
  5775. }
  5776. static void switchtobuf(upb_pbdecoder *d, const char *buf, const char *end) {
  5777. d->ptr = buf;
  5778. d->buf = buf;
  5779. d->end = end;
  5780. set_delim_end(d);
  5781. }
  5782. static void advancetobuf(upb_pbdecoder *d, const char *buf, size_t len) {
  5783. UPB_ASSERT(curbufleft(d) == 0);
  5784. d->bufstart_ofs += (d->end - d->buf);
  5785. switchtobuf(d, buf, buf + len);
  5786. }
  5787. static void checkpoint(upb_pbdecoder *d) {
  5788. /* The assertion here is in the interests of efficiency, not correctness.
  5789. * We are trying to ensure that we don't checkpoint() more often than
  5790. * necessary. */
  5791. UPB_ASSERT(d->checkpoint != d->ptr);
  5792. d->checkpoint = d->ptr;
  5793. }
  5794. /* Skips "bytes" bytes in the stream, which may be more than available. If we
  5795. * skip more bytes than are available, we return a long read count to the caller
  5796. * indicating how many bytes can be skipped over before passing actual data
  5797. * again. Skipped bytes can pass a NULL buffer and the decoder guarantees they
  5798. * won't actually be read.
  5799. */
  5800. static int32_t skip(upb_pbdecoder *d, size_t bytes) {
  5801. UPB_ASSERT(!in_residual_buf(d, d->ptr) || d->size_param == 0);
  5802. UPB_ASSERT(d->skip == 0);
  5803. if (bytes > delim_remaining(d)) {
  5804. seterr(d, "Skipped value extended beyond enclosing submessage.");
  5805. return upb_pbdecoder_suspend(d);
  5806. } else if (bufleft(d) >= bytes) {
  5807. /* Skipped data is all in current buffer, and more is still available. */
  5808. advance(d, bytes);
  5809. d->skip = 0;
  5810. return DECODE_OK;
  5811. } else {
  5812. /* Skipped data extends beyond currently available buffers. */
  5813. d->pc = d->last;
  5814. d->skip = bytes - curbufleft(d);
  5815. d->bufstart_ofs += (d->end - d->buf);
  5816. d->residual_end = d->residual;
  5817. switchtobuf(d, d->residual, d->residual_end);
  5818. return d->size_param + d->skip;
  5819. }
  5820. }
  5821. /* Resumes the decoder from an initial state or from a previous suspend. */
  5822. int32_t upb_pbdecoder_resume(upb_pbdecoder *d, void *p, const char *buf,
  5823. size_t size, const upb_bufhandle *handle) {
  5824. UPB_UNUSED(p); /* Useless; just for the benefit of the JIT. */
  5825. /* d->skip and d->residual_end could probably elegantly be represented
  5826. * as a single variable, to more easily represent this invariant. */
  5827. UPB_ASSERT(!(d->skip && d->residual_end > d->residual));
  5828. /* We need to remember the original size_param, so that the value we return
  5829. * is relative to it, even if we do some skipping first. */
  5830. d->size_param = size;
  5831. d->handle = handle;
  5832. /* Have to handle this case specially (ie. not with skip()) because the user
  5833. * is allowed to pass a NULL buffer here, which won't allow us to safely
  5834. * calculate a d->end or use our normal functions like curbufleft(). */
  5835. if (d->skip && d->skip >= size) {
  5836. d->skip -= size;
  5837. d->bufstart_ofs += size;
  5838. buf = &dummy_char;
  5839. size = 0;
  5840. /* We can't just return now, because we might need to execute some ops
  5841. * like CHECKDELIM, which could call some callbacks and pop the stack. */
  5842. }
  5843. /* We need to pretend that this was the actual buffer param, since some of the
  5844. * calculations assume that d->ptr/d->buf is relative to this. */
  5845. d->buf_param = buf;
  5846. if (!buf) {
  5847. /* NULL buf is ok if its entire span is covered by the "skip" above, but
  5848. * by this point we know that "skip" doesn't cover the buffer. */
  5849. seterr(d, "Passed NULL buffer over non-skippable region.");
  5850. return upb_pbdecoder_suspend(d);
  5851. }
  5852. if (d->residual_end > d->residual) {
  5853. /* We have residual bytes from the last buffer. */
  5854. UPB_ASSERT(d->ptr == d->residual);
  5855. } else {
  5856. switchtobuf(d, buf, buf + size);
  5857. }
  5858. d->checkpoint = d->ptr;
  5859. /* Handle skips that don't cover the whole buffer (as above). */
  5860. if (d->skip) {
  5861. size_t skip_bytes = d->skip;
  5862. d->skip = 0;
  5863. CHECK_RETURN(skip(d, skip_bytes));
  5864. checkpoint(d);
  5865. }
  5866. /* If we're inside an unknown group, continue to parse unknown values. */
  5867. if (d->top->groupnum < 0) {
  5868. CHECK_RETURN(upb_pbdecoder_skipunknown(d, -1, 0));
  5869. checkpoint(d);
  5870. }
  5871. return DECODE_OK;
  5872. }
  5873. /* Suspends the decoder at the last checkpoint, without saving any residual
  5874. * bytes. If there are any unconsumed bytes, returns a short byte count. */
  5875. size_t upb_pbdecoder_suspend(upb_pbdecoder *d) {
  5876. d->pc = d->last;
  5877. if (d->checkpoint == d->residual) {
  5878. /* Checkpoint was in residual buf; no user bytes were consumed. */
  5879. d->ptr = d->residual;
  5880. return 0;
  5881. } else {
  5882. size_t ret = d->size_param - (d->end - d->checkpoint);
  5883. UPB_ASSERT(!in_residual_buf(d, d->checkpoint));
  5884. UPB_ASSERT(d->buf == d->buf_param || d->buf == &dummy_char);
  5885. d->bufstart_ofs += (d->checkpoint - d->buf);
  5886. d->residual_end = d->residual;
  5887. switchtobuf(d, d->residual, d->residual_end);
  5888. return ret;
  5889. }
  5890. }
  5891. /* Suspends the decoder at the last checkpoint, and saves any unconsumed
  5892. * bytes in our residual buffer. This is necessary if we need more user
  5893. * bytes to form a complete value, which might not be contiguous in the
  5894. * user's buffers. Always consumes all user bytes. */
  5895. static size_t suspend_save(upb_pbdecoder *d) {
  5896. /* We hit end-of-buffer before we could parse a full value.
  5897. * Save any unconsumed bytes (if any) to the residual buffer. */
  5898. d->pc = d->last;
  5899. if (d->checkpoint == d->residual) {
  5900. /* Checkpoint was in residual buf; append user byte(s) to residual buf. */
  5901. UPB_ASSERT((d->residual_end - d->residual) + d->size_param <=
  5902. sizeof(d->residual));
  5903. if (!in_residual_buf(d, d->ptr)) {
  5904. d->bufstart_ofs -= (d->residual_end - d->residual);
  5905. }
  5906. memcpy(d->residual_end, d->buf_param, d->size_param);
  5907. d->residual_end += d->size_param;
  5908. } else {
  5909. /* Checkpoint was in user buf; old residual bytes not needed. */
  5910. size_t save;
  5911. UPB_ASSERT(!in_residual_buf(d, d->checkpoint));
  5912. d->ptr = d->checkpoint;
  5913. save = curbufleft(d);
  5914. UPB_ASSERT(save <= sizeof(d->residual));
  5915. memcpy(d->residual, d->ptr, save);
  5916. d->residual_end = d->residual + save;
  5917. d->bufstart_ofs = offset(d);
  5918. }
  5919. switchtobuf(d, d->residual, d->residual_end);
  5920. return d->size_param;
  5921. }
  5922. /* Copies the next "bytes" bytes into "buf" and advances the stream.
  5923. * Requires that this many bytes are available in the current buffer. */
  5924. UPB_FORCEINLINE static void consumebytes(upb_pbdecoder *d, void *buf,
  5925. size_t bytes) {
  5926. UPB_ASSERT(bytes <= curbufleft(d));
  5927. memcpy(buf, d->ptr, bytes);
  5928. advance(d, bytes);
  5929. }
  5930. /* Slow path for getting the next "bytes" bytes, regardless of whether they are
  5931. * available in the current buffer or not. Returns a status code as described
  5932. * in decoder.int.h. */
  5933. UPB_NOINLINE static int32_t getbytes_slow(upb_pbdecoder *d, void *buf,
  5934. size_t bytes) {
  5935. const size_t avail = curbufleft(d);
  5936. consumebytes(d, buf, avail);
  5937. bytes -= avail;
  5938. UPB_ASSERT(bytes > 0);
  5939. if (in_residual_buf(d, d->ptr)) {
  5940. advancetobuf(d, d->buf_param, d->size_param);
  5941. }
  5942. if (curbufleft(d) >= bytes) {
  5943. consumebytes(d, (char *)buf + avail, bytes);
  5944. return DECODE_OK;
  5945. } else if (d->data_end == d->delim_end) {
  5946. seterr(d, "Submessage ended in the middle of a value or group");
  5947. return upb_pbdecoder_suspend(d);
  5948. } else {
  5949. return suspend_save(d);
  5950. }
  5951. }
  5952. /* Gets the next "bytes" bytes, regardless of whether they are available in the
  5953. * current buffer or not. Returns a status code as described in decoder.int.h.
  5954. */
  5955. UPB_FORCEINLINE static int32_t getbytes(upb_pbdecoder *d, void *buf,
  5956. size_t bytes) {
  5957. if (curbufleft(d) >= bytes) {
  5958. /* Buffer has enough data to satisfy. */
  5959. consumebytes(d, buf, bytes);
  5960. return DECODE_OK;
  5961. } else {
  5962. return getbytes_slow(d, buf, bytes);
  5963. }
  5964. }
  5965. UPB_NOINLINE static size_t peekbytes_slow(upb_pbdecoder *d, void *buf,
  5966. size_t bytes) {
  5967. size_t ret = curbufleft(d);
  5968. memcpy(buf, d->ptr, ret);
  5969. if (in_residual_buf(d, d->ptr)) {
  5970. size_t copy = UPB_MIN(bytes - ret, d->size_param);
  5971. memcpy((char *)buf + ret, d->buf_param, copy);
  5972. ret += copy;
  5973. }
  5974. return ret;
  5975. }
  5976. UPB_FORCEINLINE static size_t peekbytes(upb_pbdecoder *d, void *buf,
  5977. size_t bytes) {
  5978. if (curbufleft(d) >= bytes) {
  5979. memcpy(buf, d->ptr, bytes);
  5980. return bytes;
  5981. } else {
  5982. return peekbytes_slow(d, buf, bytes);
  5983. }
  5984. }
  5985. /* Decoding of wire types *****************************************************/
  5986. /* Slow path for decoding a varint from the current buffer position.
  5987. * Returns a status code as described in decoder.int.h. */
  5988. UPB_NOINLINE int32_t upb_pbdecoder_decode_varint_slow(upb_pbdecoder *d,
  5989. uint64_t *u64) {
  5990. uint8_t byte = 0x80;
  5991. int bitpos;
  5992. *u64 = 0;
  5993. for(bitpos = 0; bitpos < 70 && (byte & 0x80); bitpos += 7) {
  5994. CHECK_RETURN(getbytes(d, &byte, 1));
  5995. *u64 |= (uint64_t)(byte & 0x7F) << bitpos;
  5996. }
  5997. if(bitpos == 70 && (byte & 0x80)) {
  5998. seterr(d, kUnterminatedVarint);
  5999. return upb_pbdecoder_suspend(d);
  6000. }
  6001. return DECODE_OK;
  6002. }
  6003. /* Decodes a varint from the current buffer position.
  6004. * Returns a status code as described in decoder.int.h. */
  6005. UPB_FORCEINLINE static int32_t decode_varint(upb_pbdecoder *d, uint64_t *u64) {
  6006. if (curbufleft(d) > 0 && !(*d->ptr & 0x80)) {
  6007. *u64 = *d->ptr;
  6008. advance(d, 1);
  6009. return DECODE_OK;
  6010. } else if (curbufleft(d) >= 10) {
  6011. /* Fast case. */
  6012. upb_decoderet r = upb_vdecode_fast(d->ptr);
  6013. if (r.p == NULL) {
  6014. seterr(d, kUnterminatedVarint);
  6015. return upb_pbdecoder_suspend(d);
  6016. }
  6017. advance(d, r.p - d->ptr);
  6018. *u64 = r.val;
  6019. return DECODE_OK;
  6020. } else {
  6021. /* Slow case -- varint spans buffer seam. */
  6022. return upb_pbdecoder_decode_varint_slow(d, u64);
  6023. }
  6024. }
  6025. /* Decodes a 32-bit varint from the current buffer position.
  6026. * Returns a status code as described in decoder.int.h. */
  6027. UPB_FORCEINLINE static int32_t decode_v32(upb_pbdecoder *d, uint32_t *u32) {
  6028. uint64_t u64;
  6029. int32_t ret = decode_varint(d, &u64);
  6030. if (ret >= 0) return ret;
  6031. if (u64 > UINT32_MAX) {
  6032. seterr(d, "Unterminated 32-bit varint");
  6033. /* TODO(haberman) guarantee that this function return is >= 0 somehow,
  6034. * so we know this path will always be treated as error by our caller.
  6035. * Right now the size_t -> int32_t can overflow and produce negative values.
  6036. */
  6037. *u32 = 0;
  6038. return upb_pbdecoder_suspend(d);
  6039. }
  6040. *u32 = u64;
  6041. return DECODE_OK;
  6042. }
  6043. /* Decodes a fixed32 from the current buffer position.
  6044. * Returns a status code as described in decoder.int.h.
  6045. * TODO: proper byte swapping for big-endian machines. */
  6046. UPB_FORCEINLINE static int32_t decode_fixed32(upb_pbdecoder *d, uint32_t *u32) {
  6047. return getbytes(d, u32, 4);
  6048. }
  6049. /* Decodes a fixed64 from the current buffer position.
  6050. * Returns a status code as described in decoder.int.h.
  6051. * TODO: proper byte swapping for big-endian machines. */
  6052. UPB_FORCEINLINE static int32_t decode_fixed64(upb_pbdecoder *d, uint64_t *u64) {
  6053. return getbytes(d, u64, 8);
  6054. }
  6055. /* Non-static versions of the above functions.
  6056. * These are called by the JIT for fallback paths. */
  6057. int32_t upb_pbdecoder_decode_f32(upb_pbdecoder *d, uint32_t *u32) {
  6058. return decode_fixed32(d, u32);
  6059. }
  6060. int32_t upb_pbdecoder_decode_f64(upb_pbdecoder *d, uint64_t *u64) {
  6061. return decode_fixed64(d, u64);
  6062. }
  6063. static double as_double(uint64_t n) { double d; memcpy(&d, &n, 8); return d; }
  6064. static float as_float(uint32_t n) { float f; memcpy(&f, &n, 4); return f; }
  6065. /* Pushes a frame onto the decoder stack. */
  6066. static bool decoder_push(upb_pbdecoder *d, uint64_t end) {
  6067. upb_pbdecoder_frame *fr = d->top;
  6068. if (end > fr->end_ofs) {
  6069. seterr(d, kPbDecoderSubmessageTooLong);
  6070. return false;
  6071. } else if (fr == d->limit) {
  6072. seterr(d, kPbDecoderStackOverflow);
  6073. return false;
  6074. }
  6075. fr++;
  6076. fr->end_ofs = end;
  6077. fr->dispatch = NULL;
  6078. fr->groupnum = 0;
  6079. d->top = fr;
  6080. return true;
  6081. }
  6082. static bool pushtagdelim(upb_pbdecoder *d, uint32_t arg) {
  6083. /* While we expect to see an "end" tag (either ENDGROUP or a non-sequence
  6084. * field number) prior to hitting any enclosing submessage end, pushing our
  6085. * existing delim end prevents us from continuing to parse values from a
  6086. * corrupt proto that doesn't give us an END tag in time. */
  6087. if (!decoder_push(d, d->top->end_ofs))
  6088. return false;
  6089. d->top->groupnum = arg;
  6090. return true;
  6091. }
  6092. /* Pops a frame from the decoder stack. */
  6093. static void decoder_pop(upb_pbdecoder *d) { d->top--; }
  6094. UPB_NOINLINE int32_t upb_pbdecoder_checktag_slow(upb_pbdecoder *d,
  6095. uint64_t expected) {
  6096. uint64_t data = 0;
  6097. size_t bytes = upb_value_size(expected);
  6098. size_t read = peekbytes(d, &data, bytes);
  6099. if (read == bytes && data == expected) {
  6100. /* Advance past matched bytes. */
  6101. int32_t ok = getbytes(d, &data, read);
  6102. UPB_ASSERT(ok < 0);
  6103. return DECODE_OK;
  6104. } else if (read < bytes && memcmp(&data, &expected, read) == 0) {
  6105. return suspend_save(d);
  6106. } else {
  6107. return DECODE_MISMATCH;
  6108. }
  6109. }
  6110. int32_t upb_pbdecoder_skipunknown(upb_pbdecoder *d, int32_t fieldnum,
  6111. uint8_t wire_type) {
  6112. if (fieldnum >= 0)
  6113. goto have_tag;
  6114. while (true) {
  6115. uint32_t tag;
  6116. CHECK_RETURN(decode_v32(d, &tag));
  6117. wire_type = tag & 0x7;
  6118. fieldnum = tag >> 3;
  6119. have_tag:
  6120. if (fieldnum == 0) {
  6121. seterr(d, "Saw invalid field number (0)");
  6122. return upb_pbdecoder_suspend(d);
  6123. }
  6124. switch (wire_type) {
  6125. case UPB_WIRE_TYPE_32BIT:
  6126. CHECK_RETURN(skip(d, 4));
  6127. break;
  6128. case UPB_WIRE_TYPE_64BIT:
  6129. CHECK_RETURN(skip(d, 8));
  6130. break;
  6131. case UPB_WIRE_TYPE_VARINT: {
  6132. uint64_t u64;
  6133. CHECK_RETURN(decode_varint(d, &u64));
  6134. break;
  6135. }
  6136. case UPB_WIRE_TYPE_DELIMITED: {
  6137. uint32_t len;
  6138. CHECK_RETURN(decode_v32(d, &len));
  6139. CHECK_RETURN(skip(d, len));
  6140. break;
  6141. }
  6142. case UPB_WIRE_TYPE_START_GROUP:
  6143. CHECK_SUSPEND(pushtagdelim(d, -fieldnum));
  6144. break;
  6145. case UPB_WIRE_TYPE_END_GROUP:
  6146. if (fieldnum == -d->top->groupnum) {
  6147. decoder_pop(d);
  6148. } else if (fieldnum == d->top->groupnum) {
  6149. return DECODE_ENDGROUP;
  6150. } else {
  6151. seterr(d, "Unmatched ENDGROUP tag.");
  6152. return upb_pbdecoder_suspend(d);
  6153. }
  6154. break;
  6155. default:
  6156. seterr(d, "Invalid wire type");
  6157. return upb_pbdecoder_suspend(d);
  6158. }
  6159. if (d->top->groupnum >= 0) {
  6160. /* TODO: More code needed for handling unknown groups. */
  6161. upb_sink_putunknown(d->top->sink, d->checkpoint, d->ptr - d->checkpoint);
  6162. return DECODE_OK;
  6163. }
  6164. /* Unknown group -- continue looping over unknown fields. */
  6165. checkpoint(d);
  6166. }
  6167. }
  6168. static void goto_endmsg(upb_pbdecoder *d) {
  6169. upb_value v;
  6170. bool found = upb_inttable_lookup32(d->top->dispatch, DISPATCH_ENDMSG, &v);
  6171. UPB_ASSERT(found);
  6172. d->pc = d->top->base + upb_value_getuint64(v);
  6173. }
  6174. /* Parses a tag and jumps to the corresponding bytecode instruction for this
  6175. * field.
  6176. *
  6177. * If the tag is unknown (or the wire type doesn't match), parses the field as
  6178. * unknown. If the tag is a valid ENDGROUP tag, jumps to the bytecode
  6179. * instruction for the end of message. */
  6180. static int32_t dispatch(upb_pbdecoder *d) {
  6181. upb_inttable *dispatch = d->top->dispatch;
  6182. uint32_t tag;
  6183. uint8_t wire_type;
  6184. uint32_t fieldnum;
  6185. upb_value val;
  6186. int32_t retval;
  6187. /* Decode tag. */
  6188. CHECK_RETURN(decode_v32(d, &tag));
  6189. wire_type = tag & 0x7;
  6190. fieldnum = tag >> 3;
  6191. /* Lookup tag. Because of packed/non-packed compatibility, we have to
  6192. * check the wire type against two possibilities. */
  6193. if (fieldnum != DISPATCH_ENDMSG &&
  6194. upb_inttable_lookup32(dispatch, fieldnum, &val)) {
  6195. uint64_t v = upb_value_getuint64(val);
  6196. if (wire_type == (v & 0xff)) {
  6197. d->pc = d->top->base + (v >> 16);
  6198. return DECODE_OK;
  6199. } else if (wire_type == ((v >> 8) & 0xff)) {
  6200. bool found =
  6201. upb_inttable_lookup(dispatch, fieldnum + UPB_MAX_FIELDNUMBER, &val);
  6202. UPB_ASSERT(found);
  6203. d->pc = d->top->base + upb_value_getuint64(val);
  6204. return DECODE_OK;
  6205. }
  6206. }
  6207. /* We have some unknown fields (or ENDGROUP) to parse. The DISPATCH or TAG
  6208. * bytecode that triggered this is preceded by a CHECKDELIM bytecode which
  6209. * we need to back up to, so that when we're done skipping unknown data we
  6210. * can re-check the delimited end. */
  6211. d->last--; /* Necessary if we get suspended */
  6212. d->pc = d->last;
  6213. UPB_ASSERT(getop(*d->last) == OP_CHECKDELIM);
  6214. /* Unknown field or ENDGROUP. */
  6215. retval = upb_pbdecoder_skipunknown(d, fieldnum, wire_type);
  6216. CHECK_RETURN(retval);
  6217. if (retval == DECODE_ENDGROUP) {
  6218. goto_endmsg(d);
  6219. return DECODE_OK;
  6220. }
  6221. return DECODE_OK;
  6222. }
  6223. /* Callers know that the stack is more than one deep because the opcodes that
  6224. * call this only occur after PUSH operations. */
  6225. upb_pbdecoder_frame *outer_frame(upb_pbdecoder *d) {
  6226. UPB_ASSERT(d->top != d->stack);
  6227. return d->top - 1;
  6228. }
  6229. /* The main decoding loop *****************************************************/
  6230. /* The main decoder VM function. Uses traditional bytecode dispatch loop with a
  6231. * switch() statement. */
  6232. size_t run_decoder_vm(upb_pbdecoder *d, const mgroup *group,
  6233. const upb_bufhandle* handle) {
  6234. #define VMCASE(op, code) \
  6235. case op: { code; if (consumes_input(op)) checkpoint(d); break; }
  6236. #define PRIMITIVE_OP(type, wt, name, convfunc, ctype) \
  6237. VMCASE(OP_PARSE_ ## type, { \
  6238. ctype val; \
  6239. CHECK_RETURN(decode_ ## wt(d, &val)); \
  6240. upb_sink_put ## name(d->top->sink, arg, (convfunc)(val)); \
  6241. })
  6242. while(1) {
  6243. int32_t instruction;
  6244. opcode op;
  6245. uint32_t arg;
  6246. int32_t longofs;
  6247. d->last = d->pc;
  6248. instruction = *d->pc++;
  6249. op = getop(instruction);
  6250. arg = instruction >> 8;
  6251. longofs = arg;
  6252. UPB_ASSERT(d->ptr != d->residual_end);
  6253. UPB_UNUSED(group);
  6254. #ifdef UPB_DUMP_BYTECODE
  6255. fprintf(stderr, "s_ofs=%d buf_ofs=%d data_rem=%d buf_rem=%d delim_rem=%d "
  6256. "%x %s (%d)\n",
  6257. (int)offset(d),
  6258. (int)(d->ptr - d->buf),
  6259. (int)(d->data_end - d->ptr),
  6260. (int)(d->end - d->ptr),
  6261. (int)((d->top->end_ofs - d->bufstart_ofs) - (d->ptr - d->buf)),
  6262. (int)(d->pc - 1 - group->bytecode),
  6263. upb_pbdecoder_getopname(op),
  6264. arg);
  6265. #endif
  6266. switch (op) {
  6267. /* Technically, we are losing data if we see a 32-bit varint that is not
  6268. * properly sign-extended. We could detect this and error about the data
  6269. * loss, but proto2 does not do this, so we pass. */
  6270. PRIMITIVE_OP(INT32, varint, int32, int32_t, uint64_t)
  6271. PRIMITIVE_OP(INT64, varint, int64, int64_t, uint64_t)
  6272. PRIMITIVE_OP(UINT32, varint, uint32, uint32_t, uint64_t)
  6273. PRIMITIVE_OP(UINT64, varint, uint64, uint64_t, uint64_t)
  6274. PRIMITIVE_OP(FIXED32, fixed32, uint32, uint32_t, uint32_t)
  6275. PRIMITIVE_OP(FIXED64, fixed64, uint64, uint64_t, uint64_t)
  6276. PRIMITIVE_OP(SFIXED32, fixed32, int32, int32_t, uint32_t)
  6277. PRIMITIVE_OP(SFIXED64, fixed64, int64, int64_t, uint64_t)
  6278. PRIMITIVE_OP(BOOL, varint, bool, bool, uint64_t)
  6279. PRIMITIVE_OP(DOUBLE, fixed64, double, as_double, uint64_t)
  6280. PRIMITIVE_OP(FLOAT, fixed32, float, as_float, uint32_t)
  6281. PRIMITIVE_OP(SINT32, varint, int32, upb_zzdec_32, uint64_t)
  6282. PRIMITIVE_OP(SINT64, varint, int64, upb_zzdec_64, uint64_t)
  6283. VMCASE(OP_SETDISPATCH,
  6284. d->top->base = d->pc - 1;
  6285. memcpy(&d->top->dispatch, d->pc, sizeof(void*));
  6286. d->pc += sizeof(void*) / sizeof(uint32_t);
  6287. )
  6288. VMCASE(OP_STARTMSG,
  6289. CHECK_SUSPEND(upb_sink_startmsg(d->top->sink));
  6290. )
  6291. VMCASE(OP_ENDMSG,
  6292. CHECK_SUSPEND(upb_sink_endmsg(d->top->sink, d->status));
  6293. )
  6294. VMCASE(OP_STARTSEQ,
  6295. upb_pbdecoder_frame *outer = outer_frame(d);
  6296. CHECK_SUSPEND(upb_sink_startseq(outer->sink, arg, &d->top->sink));
  6297. )
  6298. VMCASE(OP_ENDSEQ,
  6299. CHECK_SUSPEND(upb_sink_endseq(d->top->sink, arg));
  6300. )
  6301. VMCASE(OP_STARTSUBMSG,
  6302. upb_pbdecoder_frame *outer = outer_frame(d);
  6303. CHECK_SUSPEND(upb_sink_startsubmsg(outer->sink, arg, &d->top->sink));
  6304. )
  6305. VMCASE(OP_ENDSUBMSG,
  6306. CHECK_SUSPEND(upb_sink_endsubmsg(d->top->sink, arg));
  6307. )
  6308. VMCASE(OP_STARTSTR,
  6309. uint32_t len = delim_remaining(d);
  6310. upb_pbdecoder_frame *outer = outer_frame(d);
  6311. CHECK_SUSPEND(upb_sink_startstr(outer->sink, arg, len, &d->top->sink));
  6312. if (len == 0) {
  6313. d->pc++; /* Skip OP_STRING. */
  6314. }
  6315. )
  6316. VMCASE(OP_STRING,
  6317. uint32_t len = curbufleft(d);
  6318. size_t n = upb_sink_putstring(d->top->sink, arg, d->ptr, len, handle);
  6319. if (n > len) {
  6320. if (n > delim_remaining(d)) {
  6321. seterr(d, "Tried to skip past end of string.");
  6322. return upb_pbdecoder_suspend(d);
  6323. } else {
  6324. int32_t ret = skip(d, n);
  6325. /* This shouldn't return DECODE_OK, because n > len. */
  6326. UPB_ASSERT(ret >= 0);
  6327. return ret;
  6328. }
  6329. }
  6330. advance(d, n);
  6331. if (n < len || d->delim_end == NULL) {
  6332. /* We aren't finished with this string yet. */
  6333. d->pc--; /* Repeat OP_STRING. */
  6334. if (n > 0) checkpoint(d);
  6335. return upb_pbdecoder_suspend(d);
  6336. }
  6337. )
  6338. VMCASE(OP_ENDSTR,
  6339. CHECK_SUSPEND(upb_sink_endstr(d->top->sink, arg));
  6340. )
  6341. VMCASE(OP_PUSHTAGDELIM,
  6342. CHECK_SUSPEND(pushtagdelim(d, arg));
  6343. )
  6344. VMCASE(OP_SETBIGGROUPNUM,
  6345. d->top->groupnum = *d->pc++;
  6346. )
  6347. VMCASE(OP_POP,
  6348. UPB_ASSERT(d->top > d->stack);
  6349. decoder_pop(d);
  6350. )
  6351. VMCASE(OP_PUSHLENDELIM,
  6352. uint32_t len;
  6353. CHECK_RETURN(decode_v32(d, &len));
  6354. CHECK_SUSPEND(decoder_push(d, offset(d) + len));
  6355. set_delim_end(d);
  6356. )
  6357. VMCASE(OP_SETDELIM,
  6358. set_delim_end(d);
  6359. )
  6360. VMCASE(OP_CHECKDELIM,
  6361. /* We are guaranteed of this assert because we never allow ourselves to
  6362. * consume bytes beyond data_end, which covers delim_end when non-NULL.
  6363. */
  6364. UPB_ASSERT(!(d->delim_end && d->ptr > d->delim_end));
  6365. if (d->ptr == d->delim_end)
  6366. d->pc += longofs;
  6367. )
  6368. VMCASE(OP_CALL,
  6369. d->callstack[d->call_len++] = d->pc;
  6370. d->pc += longofs;
  6371. )
  6372. VMCASE(OP_RET,
  6373. UPB_ASSERT(d->call_len > 0);
  6374. d->pc = d->callstack[--d->call_len];
  6375. )
  6376. VMCASE(OP_BRANCH,
  6377. d->pc += longofs;
  6378. )
  6379. VMCASE(OP_TAG1,
  6380. uint8_t expected;
  6381. CHECK_SUSPEND(curbufleft(d) > 0);
  6382. expected = (arg >> 8) & 0xff;
  6383. if (*d->ptr == expected) {
  6384. advance(d, 1);
  6385. } else {
  6386. int8_t shortofs;
  6387. badtag:
  6388. shortofs = arg;
  6389. if (shortofs == LABEL_DISPATCH) {
  6390. CHECK_RETURN(dispatch(d));
  6391. } else {
  6392. d->pc += shortofs;
  6393. break; /* Avoid checkpoint(). */
  6394. }
  6395. }
  6396. )
  6397. VMCASE(OP_TAG2,
  6398. uint16_t expected;
  6399. CHECK_SUSPEND(curbufleft(d) > 0);
  6400. expected = (arg >> 8) & 0xffff;
  6401. if (curbufleft(d) >= 2) {
  6402. uint16_t actual;
  6403. memcpy(&actual, d->ptr, 2);
  6404. if (expected == actual) {
  6405. advance(d, 2);
  6406. } else {
  6407. goto badtag;
  6408. }
  6409. } else {
  6410. int32_t result = upb_pbdecoder_checktag_slow(d, expected);
  6411. if (result == DECODE_MISMATCH) goto badtag;
  6412. if (result >= 0) return result;
  6413. }
  6414. )
  6415. VMCASE(OP_TAGN, {
  6416. uint64_t expected;
  6417. int32_t result;
  6418. memcpy(&expected, d->pc, 8);
  6419. d->pc += 2;
  6420. result = upb_pbdecoder_checktag_slow(d, expected);
  6421. if (result == DECODE_MISMATCH) goto badtag;
  6422. if (result >= 0) return result;
  6423. })
  6424. VMCASE(OP_DISPATCH, {
  6425. CHECK_RETURN(dispatch(d));
  6426. })
  6427. VMCASE(OP_HALT, {
  6428. return d->size_param;
  6429. })
  6430. }
  6431. }
  6432. }
  6433. /* BytesHandler handlers ******************************************************/
  6434. void *upb_pbdecoder_startbc(void *closure, const void *pc, size_t size_hint) {
  6435. upb_pbdecoder *d = closure;
  6436. UPB_UNUSED(size_hint);
  6437. d->top->end_ofs = UINT64_MAX;
  6438. d->bufstart_ofs = 0;
  6439. d->call_len = 1;
  6440. d->callstack[0] = &halt;
  6441. d->pc = pc;
  6442. d->skip = 0;
  6443. return d;
  6444. }
  6445. void *upb_pbdecoder_startjit(void *closure, const void *hd, size_t size_hint) {
  6446. upb_pbdecoder *d = closure;
  6447. UPB_UNUSED(hd);
  6448. UPB_UNUSED(size_hint);
  6449. d->top->end_ofs = UINT64_MAX;
  6450. d->bufstart_ofs = 0;
  6451. d->call_len = 0;
  6452. d->skip = 0;
  6453. return d;
  6454. }
  6455. bool upb_pbdecoder_end(void *closure, const void *handler_data) {
  6456. upb_pbdecoder *d = closure;
  6457. const upb_pbdecodermethod *method = handler_data;
  6458. uint64_t end;
  6459. char dummy;
  6460. if (d->residual_end > d->residual) {
  6461. seterr(d, "Unexpected EOF: decoder still has buffered unparsed data");
  6462. return false;
  6463. }
  6464. if (d->skip) {
  6465. seterr(d, "Unexpected EOF inside skipped data");
  6466. return false;
  6467. }
  6468. if (d->top->end_ofs != UINT64_MAX) {
  6469. seterr(d, "Unexpected EOF inside delimited string");
  6470. return false;
  6471. }
  6472. /* The user's end() call indicates that the message ends here. */
  6473. end = offset(d);
  6474. d->top->end_ofs = end;
  6475. #ifdef UPB_USE_JIT_X64
  6476. if (method->is_native_) {
  6477. const mgroup *group = (const mgroup*)method->group;
  6478. if (d->top != d->stack)
  6479. d->stack->end_ofs = 0;
  6480. group->jit_code(closure, method->code_base.ptr, &dummy, 0, NULL);
  6481. } else
  6482. #endif
  6483. {
  6484. const uint32_t *p = d->pc;
  6485. d->stack->end_ofs = end;
  6486. /* Check the previous bytecode, but guard against beginning. */
  6487. if (p != method->code_base.ptr) p--;
  6488. if (getop(*p) == OP_CHECKDELIM) {
  6489. /* Rewind from OP_TAG* to OP_CHECKDELIM. */
  6490. UPB_ASSERT(getop(*d->pc) == OP_TAG1 ||
  6491. getop(*d->pc) == OP_TAG2 ||
  6492. getop(*d->pc) == OP_TAGN ||
  6493. getop(*d->pc) == OP_DISPATCH);
  6494. d->pc = p;
  6495. }
  6496. upb_pbdecoder_decode(closure, handler_data, &dummy, 0, NULL);
  6497. }
  6498. if (d->call_len != 0) {
  6499. seterr(d, "Unexpected EOF inside submessage or group");
  6500. return false;
  6501. }
  6502. return true;
  6503. }
  6504. size_t upb_pbdecoder_decode(void *decoder, const void *group, const char *buf,
  6505. size_t size, const upb_bufhandle *handle) {
  6506. int32_t result = upb_pbdecoder_resume(decoder, NULL, buf, size, handle);
  6507. if (result == DECODE_ENDGROUP) goto_endmsg(decoder);
  6508. CHECK_RETURN(result);
  6509. return run_decoder_vm(decoder, group, handle);
  6510. }
  6511. /* Public API *****************************************************************/
  6512. void upb_pbdecoder_reset(upb_pbdecoder *d) {
  6513. d->top = d->stack;
  6514. d->top->groupnum = 0;
  6515. d->ptr = d->residual;
  6516. d->buf = d->residual;
  6517. d->end = d->residual;
  6518. d->residual_end = d->residual;
  6519. }
  6520. upb_pbdecoder *upb_pbdecoder_create(upb_arena *a, const upb_pbdecodermethod *m,
  6521. upb_sink sink, upb_status *status) {
  6522. const size_t default_max_nesting = 64;
  6523. #ifndef NDEBUG
  6524. size_t size_before = upb_arena_bytesallocated(a);
  6525. #endif
  6526. upb_pbdecoder *d = upb_arena_malloc(a, sizeof(upb_pbdecoder));
  6527. if (!d) return NULL;
  6528. d->method_ = m;
  6529. d->callstack = upb_arena_malloc(a, callstacksize(d, default_max_nesting));
  6530. d->stack = upb_arena_malloc(a, stacksize(d, default_max_nesting));
  6531. if (!d->stack || !d->callstack) {
  6532. return NULL;
  6533. }
  6534. d->arena = a;
  6535. d->limit = d->stack + default_max_nesting - 1;
  6536. d->stack_size = default_max_nesting;
  6537. d->status = status;
  6538. upb_pbdecoder_reset(d);
  6539. upb_bytessink_reset(&d->input_, &m->input_handler_, d);
  6540. if (d->method_->dest_handlers_) {
  6541. if (sink.handlers != d->method_->dest_handlers_)
  6542. return NULL;
  6543. }
  6544. d->top->sink = sink;
  6545. /* If this fails, increase the value in decoder.h. */
  6546. UPB_ASSERT_DEBUGVAR(upb_arena_bytesallocated(a) - size_before <=
  6547. UPB_PB_DECODER_SIZE);
  6548. return d;
  6549. }
  6550. uint64_t upb_pbdecoder_bytesparsed(const upb_pbdecoder *d) {
  6551. return offset(d);
  6552. }
  6553. const upb_pbdecodermethod *upb_pbdecoder_method(const upb_pbdecoder *d) {
  6554. return d->method_;
  6555. }
  6556. upb_bytessink upb_pbdecoder_input(upb_pbdecoder *d) {
  6557. return d->input_;
  6558. }
  6559. size_t upb_pbdecoder_maxnesting(const upb_pbdecoder *d) {
  6560. return d->stack_size;
  6561. }
  6562. bool upb_pbdecoder_setmaxnesting(upb_pbdecoder *d, size_t max) {
  6563. UPB_ASSERT(d->top >= d->stack);
  6564. if (max < (size_t)(d->top - d->stack)) {
  6565. /* Can't set a limit smaller than what we are currently at. */
  6566. return false;
  6567. }
  6568. if (max > d->stack_size) {
  6569. /* Need to reallocate stack and callstack to accommodate. */
  6570. size_t old_size = stacksize(d, d->stack_size);
  6571. size_t new_size = stacksize(d, max);
  6572. void *p = upb_arena_realloc(d->arena, d->stack, old_size, new_size);
  6573. if (!p) {
  6574. return false;
  6575. }
  6576. d->stack = p;
  6577. old_size = callstacksize(d, d->stack_size);
  6578. new_size = callstacksize(d, max);
  6579. p = upb_arena_realloc(d->arena, d->callstack, old_size, new_size);
  6580. if (!p) {
  6581. return false;
  6582. }
  6583. d->callstack = p;
  6584. d->stack_size = max;
  6585. }
  6586. d->limit = d->stack + max - 1;
  6587. return true;
  6588. }
  6589. /*
  6590. ** upb::Encoder
  6591. **
  6592. ** Since we are implementing pure handlers (ie. without any out-of-band access
  6593. ** to pre-computed lengths), we have to buffer all submessages before we can
  6594. ** emit even their first byte.
  6595. **
  6596. ** Not knowing the size of submessages also means we can't write a perfect
  6597. ** zero-copy implementation, even with buffering. Lengths are stored as
  6598. ** varints, which means that we don't know how many bytes to reserve for the
  6599. ** length until we know what the length is.
  6600. **
  6601. ** This leaves us with three main choices:
  6602. **
  6603. ** 1. buffer all submessage data in a temporary buffer, then copy it exactly
  6604. ** once into the output buffer.
  6605. **
  6606. ** 2. attempt to buffer data directly into the output buffer, estimating how
  6607. ** many bytes each length will take. When our guesses are wrong, use
  6608. ** memmove() to grow or shrink the allotted space.
  6609. **
  6610. ** 3. buffer directly into the output buffer, allocating a max length
  6611. ** ahead-of-time for each submessage length. If we overallocated, we waste
  6612. ** space, but no memcpy() or memmove() is required. This approach requires
  6613. ** defining a maximum size for submessages and rejecting submessages that
  6614. ** exceed that size.
  6615. **
  6616. ** (2) and (3) have the potential to have better performance, but they are more
  6617. ** complicated and subtle to implement:
  6618. **
  6619. ** (3) requires making an arbitrary choice of the maximum message size; it
  6620. ** wastes space when submessages are shorter than this and fails
  6621. ** completely when they are longer. This makes it more finicky and
  6622. ** requires configuration based on the input. It also makes it impossible
  6623. ** to perfectly match the output of reference encoders that always use the
  6624. ** optimal amount of space for each length.
  6625. **
  6626. ** (2) requires guessing the the size upfront, and if multiple lengths are
  6627. ** guessed wrong the minimum required number of memmove() operations may
  6628. ** be complicated to compute correctly. Implemented properly, it may have
  6629. ** a useful amortized or average cost, but more investigation is required
  6630. ** to determine this and what the optimal algorithm is to achieve it.
  6631. **
  6632. ** (1) makes you always pay for exactly one copy, but its implementation is
  6633. ** the simplest and its performance is predictable.
  6634. **
  6635. ** So for now, we implement (1) only. If we wish to optimize later, we should
  6636. ** be able to do it without affecting users.
  6637. **
  6638. ** The strategy is to buffer the segments of data that do *not* depend on
  6639. ** unknown lengths in one buffer, and keep a separate buffer of segment pointers
  6640. ** and lengths. When the top-level submessage ends, we can go beginning to end,
  6641. ** alternating the writing of lengths with memcpy() of the rest of the data.
  6642. ** At the top level though, no buffering is required.
  6643. */
  6644. /* The output buffer is divided into segments; a segment is a string of data
  6645. * that is "ready to go" -- it does not need any varint lengths inserted into
  6646. * the middle. The seams between segments are where varints will be inserted
  6647. * once they are known.
  6648. *
  6649. * We also use the concept of a "run", which is a range of encoded bytes that
  6650. * occur at a single submessage level. Every segment contains one or more runs.
  6651. *
  6652. * A segment can span messages. Consider:
  6653. *
  6654. * .--Submessage lengths---------.
  6655. * | | |
  6656. * | V V
  6657. * V | |--------------- | |-----------------
  6658. * Submessages: | |-----------------------------------------------
  6659. * Top-level msg: ------------------------------------------------------------
  6660. *
  6661. * Segments: ----- ------------------- -----------------
  6662. * Runs: *---- *--------------*--- *----------------
  6663. * (* marks the start)
  6664. *
  6665. * Note that the top-level menssage is not in any segment because it does not
  6666. * have any length preceding it.
  6667. *
  6668. * A segment is only interrupted when another length needs to be inserted. So
  6669. * observe how the second segment spans both the inner submessage and part of
  6670. * the next enclosing message. */
  6671. typedef struct {
  6672. uint32_t msglen; /* The length to varint-encode before this segment. */
  6673. uint32_t seglen; /* Length of the segment. */
  6674. } upb_pb_encoder_segment;
  6675. struct upb_pb_encoder {
  6676. upb_arena *arena;
  6677. /* Our input and output. */
  6678. upb_sink input_;
  6679. upb_bytessink output_;
  6680. /* The "subclosure" -- used as the inner closure as part of the bytessink
  6681. * protocol. */
  6682. void *subc;
  6683. /* The output buffer and limit, and our current write position. "buf"
  6684. * initially points to "initbuf", but is dynamically allocated if we need to
  6685. * grow beyond the initial size. */
  6686. char *buf, *ptr, *limit;
  6687. /* The beginning of the current run, or undefined if we are at the top
  6688. * level. */
  6689. char *runbegin;
  6690. /* The list of segments we are accumulating. */
  6691. upb_pb_encoder_segment *segbuf, *segptr, *seglimit;
  6692. /* The stack of enclosing submessages. Each entry in the stack points to the
  6693. * segment where this submessage's length is being accumulated. */
  6694. int *stack, *top, *stacklimit;
  6695. /* Depth of startmsg/endmsg calls. */
  6696. int depth;
  6697. };
  6698. /* low-level buffering ********************************************************/
  6699. /* Low-level functions for interacting with the output buffer. */
  6700. /* TODO(haberman): handle pushback */
  6701. static void putbuf(upb_pb_encoder *e, const char *buf, size_t len) {
  6702. size_t n = upb_bytessink_putbuf(e->output_, e->subc, buf, len, NULL);
  6703. UPB_ASSERT(n == len);
  6704. }
  6705. static upb_pb_encoder_segment *top(upb_pb_encoder *e) {
  6706. return &e->segbuf[*e->top];
  6707. }
  6708. /* Call to ensure that at least "bytes" bytes are available for writing at
  6709. * e->ptr. Returns false if the bytes could not be allocated. */
  6710. static bool reserve(upb_pb_encoder *e, size_t bytes) {
  6711. if ((size_t)(e->limit - e->ptr) < bytes) {
  6712. /* Grow buffer. */
  6713. char *new_buf;
  6714. size_t needed = bytes + (e->ptr - e->buf);
  6715. size_t old_size = e->limit - e->buf;
  6716. size_t new_size = old_size;
  6717. while (new_size < needed) {
  6718. new_size *= 2;
  6719. }
  6720. new_buf = upb_arena_realloc(e->arena, e->buf, old_size, new_size);
  6721. if (new_buf == NULL) {
  6722. return false;
  6723. }
  6724. e->ptr = new_buf + (e->ptr - e->buf);
  6725. e->runbegin = new_buf + (e->runbegin - e->buf);
  6726. e->limit = new_buf + new_size;
  6727. e->buf = new_buf;
  6728. }
  6729. return true;
  6730. }
  6731. /* Call when "bytes" bytes have been writte at e->ptr. The caller *must* have
  6732. * previously called reserve() with at least this many bytes. */
  6733. static void encoder_advance(upb_pb_encoder *e, size_t bytes) {
  6734. UPB_ASSERT((size_t)(e->limit - e->ptr) >= bytes);
  6735. e->ptr += bytes;
  6736. }
  6737. /* Call when all of the bytes for a handler have been written. Flushes the
  6738. * bytes if possible and necessary, returning false if this failed. */
  6739. static bool commit(upb_pb_encoder *e) {
  6740. if (!e->top) {
  6741. /* We aren't inside a delimited region. Flush our accumulated bytes to
  6742. * the output.
  6743. *
  6744. * TODO(haberman): in the future we may want to delay flushing for
  6745. * efficiency reasons. */
  6746. putbuf(e, e->buf, e->ptr - e->buf);
  6747. e->ptr = e->buf;
  6748. }
  6749. return true;
  6750. }
  6751. /* Writes the given bytes to the buffer, handling reserve/advance. */
  6752. static bool encode_bytes(upb_pb_encoder *e, const void *data, size_t len) {
  6753. if (!reserve(e, len)) {
  6754. return false;
  6755. }
  6756. memcpy(e->ptr, data, len);
  6757. encoder_advance(e, len);
  6758. return true;
  6759. }
  6760. /* Finish the current run by adding the run totals to the segment and message
  6761. * length. */
  6762. static void accumulate(upb_pb_encoder *e) {
  6763. size_t run_len;
  6764. UPB_ASSERT(e->ptr >= e->runbegin);
  6765. run_len = e->ptr - e->runbegin;
  6766. e->segptr->seglen += run_len;
  6767. top(e)->msglen += run_len;
  6768. e->runbegin = e->ptr;
  6769. }
  6770. /* Call to indicate the start of delimited region for which the full length is
  6771. * not yet known. All data will be buffered until the length is known.
  6772. * Delimited regions may be nested; their lengths will all be tracked properly. */
  6773. static bool start_delim(upb_pb_encoder *e) {
  6774. if (e->top) {
  6775. /* We are already buffering, advance to the next segment and push it on the
  6776. * stack. */
  6777. accumulate(e);
  6778. if (++e->top == e->stacklimit) {
  6779. /* TODO(haberman): grow stack? */
  6780. return false;
  6781. }
  6782. if (++e->segptr == e->seglimit) {
  6783. /* Grow segment buffer. */
  6784. size_t old_size =
  6785. (e->seglimit - e->segbuf) * sizeof(upb_pb_encoder_segment);
  6786. size_t new_size = old_size * 2;
  6787. upb_pb_encoder_segment *new_buf =
  6788. upb_arena_realloc(e->arena, e->segbuf, old_size, new_size);
  6789. if (new_buf == NULL) {
  6790. return false;
  6791. }
  6792. e->segptr = new_buf + (e->segptr - e->segbuf);
  6793. e->seglimit = new_buf + (new_size / sizeof(upb_pb_encoder_segment));
  6794. e->segbuf = new_buf;
  6795. }
  6796. } else {
  6797. /* We were previously at the top level, start buffering. */
  6798. e->segptr = e->segbuf;
  6799. e->top = e->stack;
  6800. e->runbegin = e->ptr;
  6801. }
  6802. *e->top = e->segptr - e->segbuf;
  6803. e->segptr->seglen = 0;
  6804. e->segptr->msglen = 0;
  6805. return true;
  6806. }
  6807. /* Call to indicate the end of a delimited region. We now know the length of
  6808. * the delimited region. If we are not nested inside any other delimited
  6809. * regions, we can now emit all of the buffered data we accumulated. */
  6810. static bool end_delim(upb_pb_encoder *e) {
  6811. size_t msglen;
  6812. accumulate(e);
  6813. msglen = top(e)->msglen;
  6814. if (e->top == e->stack) {
  6815. /* All lengths are now available, emit all buffered data. */
  6816. char buf[UPB_PB_VARINT_MAX_LEN];
  6817. upb_pb_encoder_segment *s;
  6818. const char *ptr = e->buf;
  6819. for (s = e->segbuf; s <= e->segptr; s++) {
  6820. size_t lenbytes = upb_vencode64(s->msglen, buf);
  6821. putbuf(e, buf, lenbytes);
  6822. putbuf(e, ptr, s->seglen);
  6823. ptr += s->seglen;
  6824. }
  6825. e->ptr = e->buf;
  6826. e->top = NULL;
  6827. } else {
  6828. /* Need to keep buffering; propagate length info into enclosing
  6829. * submessages. */
  6830. --e->top;
  6831. top(e)->msglen += msglen + upb_varint_size(msglen);
  6832. }
  6833. return true;
  6834. }
  6835. /* tag_t **********************************************************************/
  6836. /* A precomputed (pre-encoded) tag and length. */
  6837. typedef struct {
  6838. uint8_t bytes;
  6839. char tag[7];
  6840. } tag_t;
  6841. /* Allocates a new tag for this field, and sets it in these handlerattr. */
  6842. static void new_tag(upb_handlers *h, const upb_fielddef *f, upb_wiretype_t wt,
  6843. upb_handlerattr *attr) {
  6844. uint32_t n = upb_fielddef_number(f);
  6845. tag_t *tag = upb_gmalloc(sizeof(tag_t));
  6846. tag->bytes = upb_vencode64((n << 3) | wt, tag->tag);
  6847. attr->handler_data = tag;
  6848. upb_handlers_addcleanup(h, tag, upb_gfree);
  6849. }
  6850. static bool encode_tag(upb_pb_encoder *e, const tag_t *tag) {
  6851. return encode_bytes(e, tag->tag, tag->bytes);
  6852. }
  6853. /* encoding of wire types *****************************************************/
  6854. static bool encode_fixed64(upb_pb_encoder *e, uint64_t val) {
  6855. /* TODO(haberman): byte-swap for big endian. */
  6856. return encode_bytes(e, &val, sizeof(uint64_t));
  6857. }
  6858. static bool encode_fixed32(upb_pb_encoder *e, uint32_t val) {
  6859. /* TODO(haberman): byte-swap for big endian. */
  6860. return encode_bytes(e, &val, sizeof(uint32_t));
  6861. }
  6862. static bool encode_varint(upb_pb_encoder *e, uint64_t val) {
  6863. if (!reserve(e, UPB_PB_VARINT_MAX_LEN)) {
  6864. return false;
  6865. }
  6866. encoder_advance(e, upb_vencode64(val, e->ptr));
  6867. return true;
  6868. }
  6869. static uint64_t dbl2uint64(double d) {
  6870. uint64_t ret;
  6871. memcpy(&ret, &d, sizeof(uint64_t));
  6872. return ret;
  6873. }
  6874. static uint32_t flt2uint32(float d) {
  6875. uint32_t ret;
  6876. memcpy(&ret, &d, sizeof(uint32_t));
  6877. return ret;
  6878. }
  6879. /* encoding of proto types ****************************************************/
  6880. static bool startmsg(void *c, const void *hd) {
  6881. upb_pb_encoder *e = c;
  6882. UPB_UNUSED(hd);
  6883. if (e->depth++ == 0) {
  6884. upb_bytessink_start(e->output_, 0, &e->subc);
  6885. }
  6886. return true;
  6887. }
  6888. static bool endmsg(void *c, const void *hd, upb_status *status) {
  6889. upb_pb_encoder *e = c;
  6890. UPB_UNUSED(hd);
  6891. UPB_UNUSED(status);
  6892. if (--e->depth == 0) {
  6893. upb_bytessink_end(e->output_);
  6894. }
  6895. return true;
  6896. }
  6897. static void *encode_startdelimfield(void *c, const void *hd) {
  6898. bool ok = encode_tag(c, hd) && commit(c) && start_delim(c);
  6899. return ok ? c : UPB_BREAK;
  6900. }
  6901. static bool encode_unknown(void *c, const void *hd, const char *buf,
  6902. size_t len) {
  6903. UPB_UNUSED(hd);
  6904. return encode_bytes(c, buf, len) && commit(c);
  6905. }
  6906. static bool encode_enddelimfield(void *c, const void *hd) {
  6907. UPB_UNUSED(hd);
  6908. return end_delim(c);
  6909. }
  6910. static void *encode_startgroup(void *c, const void *hd) {
  6911. return (encode_tag(c, hd) && commit(c)) ? c : UPB_BREAK;
  6912. }
  6913. static bool encode_endgroup(void *c, const void *hd) {
  6914. return encode_tag(c, hd) && commit(c);
  6915. }
  6916. static void *encode_startstr(void *c, const void *hd, size_t size_hint) {
  6917. UPB_UNUSED(size_hint);
  6918. return encode_startdelimfield(c, hd);
  6919. }
  6920. static size_t encode_strbuf(void *c, const void *hd, const char *buf,
  6921. size_t len, const upb_bufhandle *h) {
  6922. UPB_UNUSED(hd);
  6923. UPB_UNUSED(h);
  6924. return encode_bytes(c, buf, len) ? len : 0;
  6925. }
  6926. #define T(type, ctype, convert, encode) \
  6927. static bool encode_scalar_##type(void *e, const void *hd, ctype val) { \
  6928. return encode_tag(e, hd) && encode(e, (convert)(val)) && commit(e); \
  6929. } \
  6930. static bool encode_packed_##type(void *e, const void *hd, ctype val) { \
  6931. UPB_UNUSED(hd); \
  6932. return encode(e, (convert)(val)); \
  6933. }
  6934. T(double, double, dbl2uint64, encode_fixed64)
  6935. T(float, float, flt2uint32, encode_fixed32)
  6936. T(int64, int64_t, uint64_t, encode_varint)
  6937. T(int32, int32_t, int64_t, encode_varint)
  6938. T(fixed64, uint64_t, uint64_t, encode_fixed64)
  6939. T(fixed32, uint32_t, uint32_t, encode_fixed32)
  6940. T(bool, bool, bool, encode_varint)
  6941. T(uint32, uint32_t, uint32_t, encode_varint)
  6942. T(uint64, uint64_t, uint64_t, encode_varint)
  6943. T(enum, int32_t, uint32_t, encode_varint)
  6944. T(sfixed32, int32_t, uint32_t, encode_fixed32)
  6945. T(sfixed64, int64_t, uint64_t, encode_fixed64)
  6946. T(sint32, int32_t, upb_zzenc_32, encode_varint)
  6947. T(sint64, int64_t, upb_zzenc_64, encode_varint)
  6948. #undef T
  6949. /* code to build the handlers *************************************************/
  6950. #include <stdio.h>
  6951. static void newhandlers_callback(const void *closure, upb_handlers *h) {
  6952. const upb_msgdef *m;
  6953. upb_msg_field_iter i;
  6954. UPB_UNUSED(closure);
  6955. upb_handlers_setstartmsg(h, startmsg, NULL);
  6956. upb_handlers_setendmsg(h, endmsg, NULL);
  6957. upb_handlers_setunknown(h, encode_unknown, NULL);
  6958. m = upb_handlers_msgdef(h);
  6959. for(upb_msg_field_begin(&i, m);
  6960. !upb_msg_field_done(&i);
  6961. upb_msg_field_next(&i)) {
  6962. const upb_fielddef *f = upb_msg_iter_field(&i);
  6963. bool packed = upb_fielddef_isseq(f) && upb_fielddef_isprimitive(f) &&
  6964. upb_fielddef_packed(f);
  6965. upb_handlerattr attr = UPB_HANDLERATTR_INIT;
  6966. upb_wiretype_t wt =
  6967. packed ? UPB_WIRE_TYPE_DELIMITED
  6968. : upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  6969. /* Pre-encode the tag for this field. */
  6970. new_tag(h, f, wt, &attr);
  6971. if (packed) {
  6972. upb_handlers_setstartseq(h, f, encode_startdelimfield, &attr);
  6973. upb_handlers_setendseq(h, f, encode_enddelimfield, &attr);
  6974. }
  6975. #define T(upper, lower, upbtype) \
  6976. case UPB_DESCRIPTOR_TYPE_##upper: \
  6977. if (packed) { \
  6978. upb_handlers_set##upbtype(h, f, encode_packed_##lower, &attr); \
  6979. } else { \
  6980. upb_handlers_set##upbtype(h, f, encode_scalar_##lower, &attr); \
  6981. } \
  6982. break;
  6983. switch (upb_fielddef_descriptortype(f)) {
  6984. T(DOUBLE, double, double);
  6985. T(FLOAT, float, float);
  6986. T(INT64, int64, int64);
  6987. T(INT32, int32, int32);
  6988. T(FIXED64, fixed64, uint64);
  6989. T(FIXED32, fixed32, uint32);
  6990. T(BOOL, bool, bool);
  6991. T(UINT32, uint32, uint32);
  6992. T(UINT64, uint64, uint64);
  6993. T(ENUM, enum, int32);
  6994. T(SFIXED32, sfixed32, int32);
  6995. T(SFIXED64, sfixed64, int64);
  6996. T(SINT32, sint32, int32);
  6997. T(SINT64, sint64, int64);
  6998. case UPB_DESCRIPTOR_TYPE_STRING:
  6999. case UPB_DESCRIPTOR_TYPE_BYTES:
  7000. upb_handlers_setstartstr(h, f, encode_startstr, &attr);
  7001. upb_handlers_setendstr(h, f, encode_enddelimfield, &attr);
  7002. upb_handlers_setstring(h, f, encode_strbuf, &attr);
  7003. break;
  7004. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  7005. upb_handlers_setstartsubmsg(h, f, encode_startdelimfield, &attr);
  7006. upb_handlers_setendsubmsg(h, f, encode_enddelimfield, &attr);
  7007. break;
  7008. case UPB_DESCRIPTOR_TYPE_GROUP: {
  7009. /* Endgroup takes a different tag (wire_type = END_GROUP). */
  7010. upb_handlerattr attr2 = UPB_HANDLERATTR_INIT;
  7011. new_tag(h, f, UPB_WIRE_TYPE_END_GROUP, &attr2);
  7012. upb_handlers_setstartsubmsg(h, f, encode_startgroup, &attr);
  7013. upb_handlers_setendsubmsg(h, f, encode_endgroup, &attr2);
  7014. break;
  7015. }
  7016. }
  7017. #undef T
  7018. }
  7019. }
  7020. void upb_pb_encoder_reset(upb_pb_encoder *e) {
  7021. e->segptr = NULL;
  7022. e->top = NULL;
  7023. e->depth = 0;
  7024. }
  7025. /* public API *****************************************************************/
  7026. upb_handlercache *upb_pb_encoder_newcache() {
  7027. return upb_handlercache_new(newhandlers_callback, NULL);
  7028. }
  7029. upb_pb_encoder *upb_pb_encoder_create(upb_arena *arena, const upb_handlers *h,
  7030. upb_bytessink output) {
  7031. const size_t initial_bufsize = 256;
  7032. const size_t initial_segbufsize = 16;
  7033. /* TODO(haberman): make this configurable. */
  7034. const size_t stack_size = 64;
  7035. #ifndef NDEBUG
  7036. const size_t size_before = upb_arena_bytesallocated(arena);
  7037. #endif
  7038. upb_pb_encoder *e = upb_arena_malloc(arena, sizeof(upb_pb_encoder));
  7039. if (!e) return NULL;
  7040. e->buf = upb_arena_malloc(arena, initial_bufsize);
  7041. e->segbuf = upb_arena_malloc(arena, initial_segbufsize * sizeof(*e->segbuf));
  7042. e->stack = upb_arena_malloc(arena, stack_size * sizeof(*e->stack));
  7043. if (!e->buf || !e->segbuf || !e->stack) {
  7044. return NULL;
  7045. }
  7046. e->limit = e->buf + initial_bufsize;
  7047. e->seglimit = e->segbuf + initial_segbufsize;
  7048. e->stacklimit = e->stack + stack_size;
  7049. upb_pb_encoder_reset(e);
  7050. upb_sink_reset(&e->input_, h, e);
  7051. e->arena = arena;
  7052. e->output_ = output;
  7053. e->subc = output.closure;
  7054. e->ptr = e->buf;
  7055. /* If this fails, increase the value in encoder.h. */
  7056. UPB_ASSERT_DEBUGVAR(upb_arena_bytesallocated(arena) - size_before <=
  7057. UPB_PB_ENCODER_SIZE);
  7058. return e;
  7059. }
  7060. upb_sink upb_pb_encoder_input(upb_pb_encoder *e) { return e->input_; }
  7061. /*
  7062. * upb::pb::TextPrinter
  7063. *
  7064. * OPT: This is not optimized at all. It uses printf() which parses the format
  7065. * string every time, and it allocates memory for every put.
  7066. */
  7067. #include <ctype.h>
  7068. #include <float.h>
  7069. #include <inttypes.h>
  7070. #include <stdarg.h>
  7071. #include <stdio.h>
  7072. #include <string.h>
  7073. struct upb_textprinter {
  7074. upb_sink input_;
  7075. upb_bytessink output_;
  7076. int indent_depth_;
  7077. bool single_line_;
  7078. void *subc;
  7079. };
  7080. #define CHECK(x) if ((x) < 0) goto err;
  7081. static const char *shortname(const char *longname) {
  7082. const char *last = strrchr(longname, '.');
  7083. return last ? last + 1 : longname;
  7084. }
  7085. static int indent(upb_textprinter *p) {
  7086. int i;
  7087. if (!p->single_line_)
  7088. for (i = 0; i < p->indent_depth_; i++)
  7089. upb_bytessink_putbuf(p->output_, p->subc, " ", 2, NULL);
  7090. return 0;
  7091. }
  7092. static int endfield(upb_textprinter *p) {
  7093. const char ch = (p->single_line_ ? ' ' : '\n');
  7094. upb_bytessink_putbuf(p->output_, p->subc, &ch, 1, NULL);
  7095. return 0;
  7096. }
  7097. static int putescaped(upb_textprinter *p, const char *buf, size_t len,
  7098. bool preserve_utf8) {
  7099. /* Based on CEscapeInternal() from Google's protobuf release. */
  7100. char dstbuf[4096], *dst = dstbuf, *dstend = dstbuf + sizeof(dstbuf);
  7101. const char *end = buf + len;
  7102. /* I think hex is prettier and more useful, but proto2 uses octal; should
  7103. * investigate whether it can parse hex also. */
  7104. const bool use_hex = false;
  7105. bool last_hex_escape = false; /* true if last output char was \xNN */
  7106. for (; buf < end; buf++) {
  7107. bool is_hex_escape;
  7108. if (dstend - dst < 4) {
  7109. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  7110. dst = dstbuf;
  7111. }
  7112. is_hex_escape = false;
  7113. switch (*buf) {
  7114. case '\n': *(dst++) = '\\'; *(dst++) = 'n'; break;
  7115. case '\r': *(dst++) = '\\'; *(dst++) = 'r'; break;
  7116. case '\t': *(dst++) = '\\'; *(dst++) = 't'; break;
  7117. case '\"': *(dst++) = '\\'; *(dst++) = '\"'; break;
  7118. case '\'': *(dst++) = '\\'; *(dst++) = '\''; break;
  7119. case '\\': *(dst++) = '\\'; *(dst++) = '\\'; break;
  7120. default:
  7121. /* Note that if we emit \xNN and the buf character after that is a hex
  7122. * digit then that digit must be escaped too to prevent it being
  7123. * interpreted as part of the character code by C. */
  7124. if ((!preserve_utf8 || (uint8_t)*buf < 0x80) &&
  7125. (!isprint(*buf) || (last_hex_escape && isxdigit(*buf)))) {
  7126. sprintf(dst, (use_hex ? "\\x%02x" : "\\%03o"), (uint8_t)*buf);
  7127. is_hex_escape = use_hex;
  7128. dst += 4;
  7129. } else {
  7130. *(dst++) = *buf; break;
  7131. }
  7132. }
  7133. last_hex_escape = is_hex_escape;
  7134. }
  7135. /* Flush remaining data. */
  7136. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  7137. return 0;
  7138. }
  7139. bool putf(upb_textprinter *p, const char *fmt, ...) {
  7140. va_list args;
  7141. va_list args_copy;
  7142. char *str;
  7143. int written;
  7144. int len;
  7145. bool ok;
  7146. va_start(args, fmt);
  7147. /* Run once to get the length of the string. */
  7148. _upb_va_copy(args_copy, args);
  7149. len = _upb_vsnprintf(NULL, 0, fmt, args_copy);
  7150. va_end(args_copy);
  7151. /* + 1 for NULL terminator (vsprintf() requires it even if we don't). */
  7152. str = upb_gmalloc(len + 1);
  7153. if (!str) return false;
  7154. written = vsprintf(str, fmt, args);
  7155. va_end(args);
  7156. UPB_ASSERT(written == len);
  7157. ok = upb_bytessink_putbuf(p->output_, p->subc, str, len, NULL);
  7158. upb_gfree(str);
  7159. return ok;
  7160. }
  7161. /* handlers *******************************************************************/
  7162. static bool textprinter_startmsg(void *c, const void *hd) {
  7163. upb_textprinter *p = c;
  7164. UPB_UNUSED(hd);
  7165. if (p->indent_depth_ == 0) {
  7166. upb_bytessink_start(p->output_, 0, &p->subc);
  7167. }
  7168. return true;
  7169. }
  7170. static bool textprinter_endmsg(void *c, const void *hd, upb_status *s) {
  7171. upb_textprinter *p = c;
  7172. UPB_UNUSED(hd);
  7173. UPB_UNUSED(s);
  7174. if (p->indent_depth_ == 0) {
  7175. upb_bytessink_end(p->output_);
  7176. }
  7177. return true;
  7178. }
  7179. #define TYPE(name, ctype, fmt) \
  7180. static bool textprinter_put ## name(void *closure, const void *handler_data, \
  7181. ctype val) { \
  7182. upb_textprinter *p = closure; \
  7183. const upb_fielddef *f = handler_data; \
  7184. CHECK(indent(p)); \
  7185. putf(p, "%s: " fmt, upb_fielddef_name(f), val); \
  7186. CHECK(endfield(p)); \
  7187. return true; \
  7188. err: \
  7189. return false; \
  7190. }
  7191. static bool textprinter_putbool(void *closure, const void *handler_data,
  7192. bool val) {
  7193. upb_textprinter *p = closure;
  7194. const upb_fielddef *f = handler_data;
  7195. CHECK(indent(p));
  7196. putf(p, "%s: %s", upb_fielddef_name(f), val ? "true" : "false");
  7197. CHECK(endfield(p));
  7198. return true;
  7199. err:
  7200. return false;
  7201. }
  7202. #define STRINGIFY_HELPER(x) #x
  7203. #define STRINGIFY_MACROVAL(x) STRINGIFY_HELPER(x)
  7204. TYPE(int32, int32_t, "%" PRId32)
  7205. TYPE(int64, int64_t, "%" PRId64)
  7206. TYPE(uint32, uint32_t, "%" PRIu32)
  7207. TYPE(uint64, uint64_t, "%" PRIu64)
  7208. TYPE(float, float, "%." STRINGIFY_MACROVAL(FLT_DIG) "g")
  7209. TYPE(double, double, "%." STRINGIFY_MACROVAL(DBL_DIG) "g")
  7210. #undef TYPE
  7211. /* Output a symbolic value from the enum if found, else just print as int32. */
  7212. static bool textprinter_putenum(void *closure, const void *handler_data,
  7213. int32_t val) {
  7214. upb_textprinter *p = closure;
  7215. const upb_fielddef *f = handler_data;
  7216. const upb_enumdef *enum_def = upb_fielddef_enumsubdef(f);
  7217. const char *label = upb_enumdef_iton(enum_def, val);
  7218. if (label) {
  7219. indent(p);
  7220. putf(p, "%s: %s", upb_fielddef_name(f), label);
  7221. endfield(p);
  7222. } else {
  7223. if (!textprinter_putint32(closure, handler_data, val))
  7224. return false;
  7225. }
  7226. return true;
  7227. }
  7228. static void *textprinter_startstr(void *closure, const void *handler_data,
  7229. size_t size_hint) {
  7230. upb_textprinter *p = closure;
  7231. const upb_fielddef *f = handler_data;
  7232. UPB_UNUSED(size_hint);
  7233. indent(p);
  7234. putf(p, "%s: \"", upb_fielddef_name(f));
  7235. return p;
  7236. }
  7237. static bool textprinter_endstr(void *closure, const void *handler_data) {
  7238. upb_textprinter *p = closure;
  7239. UPB_UNUSED(handler_data);
  7240. putf(p, "\"");
  7241. endfield(p);
  7242. return true;
  7243. }
  7244. static size_t textprinter_putstr(void *closure, const void *hd, const char *buf,
  7245. size_t len, const upb_bufhandle *handle) {
  7246. upb_textprinter *p = closure;
  7247. const upb_fielddef *f = hd;
  7248. UPB_UNUSED(handle);
  7249. CHECK(putescaped(p, buf, len, upb_fielddef_type(f) == UPB_TYPE_STRING));
  7250. return len;
  7251. err:
  7252. return 0;
  7253. }
  7254. static void *textprinter_startsubmsg(void *closure, const void *handler_data) {
  7255. upb_textprinter *p = closure;
  7256. const char *name = handler_data;
  7257. CHECK(indent(p));
  7258. putf(p, "%s {%c", name, p->single_line_ ? ' ' : '\n');
  7259. p->indent_depth_++;
  7260. return p;
  7261. err:
  7262. return UPB_BREAK;
  7263. }
  7264. static bool textprinter_endsubmsg(void *closure, const void *handler_data) {
  7265. upb_textprinter *p = closure;
  7266. UPB_UNUSED(handler_data);
  7267. p->indent_depth_--;
  7268. CHECK(indent(p));
  7269. upb_bytessink_putbuf(p->output_, p->subc, "}", 1, NULL);
  7270. CHECK(endfield(p));
  7271. return true;
  7272. err:
  7273. return false;
  7274. }
  7275. static void onmreg(const void *c, upb_handlers *h) {
  7276. const upb_msgdef *m = upb_handlers_msgdef(h);
  7277. upb_msg_field_iter i;
  7278. UPB_UNUSED(c);
  7279. upb_handlers_setstartmsg(h, textprinter_startmsg, NULL);
  7280. upb_handlers_setendmsg(h, textprinter_endmsg, NULL);
  7281. for(upb_msg_field_begin(&i, m);
  7282. !upb_msg_field_done(&i);
  7283. upb_msg_field_next(&i)) {
  7284. upb_fielddef *f = upb_msg_iter_field(&i);
  7285. upb_handlerattr attr = UPB_HANDLERATTR_INIT;
  7286. attr.handler_data = f;
  7287. switch (upb_fielddef_type(f)) {
  7288. case UPB_TYPE_INT32:
  7289. upb_handlers_setint32(h, f, textprinter_putint32, &attr);
  7290. break;
  7291. case UPB_TYPE_INT64:
  7292. upb_handlers_setint64(h, f, textprinter_putint64, &attr);
  7293. break;
  7294. case UPB_TYPE_UINT32:
  7295. upb_handlers_setuint32(h, f, textprinter_putuint32, &attr);
  7296. break;
  7297. case UPB_TYPE_UINT64:
  7298. upb_handlers_setuint64(h, f, textprinter_putuint64, &attr);
  7299. break;
  7300. case UPB_TYPE_FLOAT:
  7301. upb_handlers_setfloat(h, f, textprinter_putfloat, &attr);
  7302. break;
  7303. case UPB_TYPE_DOUBLE:
  7304. upb_handlers_setdouble(h, f, textprinter_putdouble, &attr);
  7305. break;
  7306. case UPB_TYPE_BOOL:
  7307. upb_handlers_setbool(h, f, textprinter_putbool, &attr);
  7308. break;
  7309. case UPB_TYPE_STRING:
  7310. case UPB_TYPE_BYTES:
  7311. upb_handlers_setstartstr(h, f, textprinter_startstr, &attr);
  7312. upb_handlers_setstring(h, f, textprinter_putstr, &attr);
  7313. upb_handlers_setendstr(h, f, textprinter_endstr, &attr);
  7314. break;
  7315. case UPB_TYPE_MESSAGE: {
  7316. const char *name =
  7317. upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_GROUP
  7318. ? shortname(upb_msgdef_fullname(upb_fielddef_msgsubdef(f)))
  7319. : upb_fielddef_name(f);
  7320. attr.handler_data = name;
  7321. upb_handlers_setstartsubmsg(h, f, textprinter_startsubmsg, &attr);
  7322. upb_handlers_setendsubmsg(h, f, textprinter_endsubmsg, &attr);
  7323. break;
  7324. }
  7325. case UPB_TYPE_ENUM:
  7326. upb_handlers_setint32(h, f, textprinter_putenum, &attr);
  7327. break;
  7328. }
  7329. }
  7330. }
  7331. static void textprinter_reset(upb_textprinter *p, bool single_line) {
  7332. p->single_line_ = single_line;
  7333. p->indent_depth_ = 0;
  7334. }
  7335. /* Public API *****************************************************************/
  7336. upb_textprinter *upb_textprinter_create(upb_arena *arena, const upb_handlers *h,
  7337. upb_bytessink output) {
  7338. upb_textprinter *p = upb_arena_malloc(arena, sizeof(upb_textprinter));
  7339. if (!p) return NULL;
  7340. p->output_ = output;
  7341. upb_sink_reset(&p->input_, h, p);
  7342. textprinter_reset(p, false);
  7343. return p;
  7344. }
  7345. upb_handlercache *upb_textprinter_newcache() {
  7346. return upb_handlercache_new(&onmreg, NULL);
  7347. }
  7348. upb_sink upb_textprinter_input(upb_textprinter *p) { return p->input_; }
  7349. void upb_textprinter_setsingleline(upb_textprinter *p, bool single_line) {
  7350. p->single_line_ = single_line;
  7351. }
  7352. /* Index is descriptor type. */
  7353. const uint8_t upb_pb_native_wire_types[] = {
  7354. UPB_WIRE_TYPE_END_GROUP, /* ENDGROUP */
  7355. UPB_WIRE_TYPE_64BIT, /* DOUBLE */
  7356. UPB_WIRE_TYPE_32BIT, /* FLOAT */
  7357. UPB_WIRE_TYPE_VARINT, /* INT64 */
  7358. UPB_WIRE_TYPE_VARINT, /* UINT64 */
  7359. UPB_WIRE_TYPE_VARINT, /* INT32 */
  7360. UPB_WIRE_TYPE_64BIT, /* FIXED64 */
  7361. UPB_WIRE_TYPE_32BIT, /* FIXED32 */
  7362. UPB_WIRE_TYPE_VARINT, /* BOOL */
  7363. UPB_WIRE_TYPE_DELIMITED, /* STRING */
  7364. UPB_WIRE_TYPE_START_GROUP, /* GROUP */
  7365. UPB_WIRE_TYPE_DELIMITED, /* MESSAGE */
  7366. UPB_WIRE_TYPE_DELIMITED, /* BYTES */
  7367. UPB_WIRE_TYPE_VARINT, /* UINT32 */
  7368. UPB_WIRE_TYPE_VARINT, /* ENUM */
  7369. UPB_WIRE_TYPE_32BIT, /* SFIXED32 */
  7370. UPB_WIRE_TYPE_64BIT, /* SFIXED64 */
  7371. UPB_WIRE_TYPE_VARINT, /* SINT32 */
  7372. UPB_WIRE_TYPE_VARINT, /* SINT64 */
  7373. };
  7374. /* A basic branch-based decoder, uses 32-bit values to get good performance
  7375. * on 32-bit architectures (but performs well on 64-bits also).
  7376. * This scheme comes from the original Google Protobuf implementation
  7377. * (proto2). */
  7378. upb_decoderet upb_vdecode_max8_branch32(upb_decoderet r) {
  7379. upb_decoderet err = {NULL, 0};
  7380. const char *p = r.p;
  7381. uint32_t low = (uint32_t)r.val;
  7382. uint32_t high = 0;
  7383. uint32_t b;
  7384. b = *(p++); low |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  7385. b = *(p++); low |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  7386. b = *(p++); low |= (b & 0x7fU) << 28;
  7387. high = (b & 0x7fU) >> 4; if (!(b & 0x80)) goto done;
  7388. b = *(p++); high |= (b & 0x7fU) << 3; if (!(b & 0x80)) goto done;
  7389. b = *(p++); high |= (b & 0x7fU) << 10; if (!(b & 0x80)) goto done;
  7390. b = *(p++); high |= (b & 0x7fU) << 17; if (!(b & 0x80)) goto done;
  7391. b = *(p++); high |= (b & 0x7fU) << 24; if (!(b & 0x80)) goto done;
  7392. b = *(p++); high |= (b & 0x7fU) << 31; if (!(b & 0x80)) goto done;
  7393. return err;
  7394. done:
  7395. r.val = ((uint64_t)high << 32) | low;
  7396. r.p = p;
  7397. return r;
  7398. }
  7399. /* Like the previous, but uses 64-bit values. */
  7400. upb_decoderet upb_vdecode_max8_branch64(upb_decoderet r) {
  7401. const char *p = r.p;
  7402. uint64_t val = r.val;
  7403. uint64_t b;
  7404. upb_decoderet err = {NULL, 0};
  7405. b = *(p++); val |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  7406. b = *(p++); val |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  7407. b = *(p++); val |= (b & 0x7fU) << 28; if (!(b & 0x80)) goto done;
  7408. b = *(p++); val |= (b & 0x7fU) << 35; if (!(b & 0x80)) goto done;
  7409. b = *(p++); val |= (b & 0x7fU) << 42; if (!(b & 0x80)) goto done;
  7410. b = *(p++); val |= (b & 0x7fU) << 49; if (!(b & 0x80)) goto done;
  7411. b = *(p++); val |= (b & 0x7fU) << 56; if (!(b & 0x80)) goto done;
  7412. b = *(p++); val |= (b & 0x7fU) << 63; if (!(b & 0x80)) goto done;
  7413. return err;
  7414. done:
  7415. r.val = val;
  7416. r.p = p;
  7417. return r;
  7418. }
  7419. #line 1 "upb/json/parser.rl"
  7420. /*
  7421. ** upb::json::Parser (upb_json_parser)
  7422. **
  7423. ** A parser that uses the Ragel State Machine Compiler to generate
  7424. ** the finite automata.
  7425. **
  7426. ** Ragel only natively handles regular languages, but we can manually
  7427. ** program it a bit to handle context-free languages like JSON, by using
  7428. ** the "fcall" and "fret" constructs.
  7429. **
  7430. ** This parser can handle the basics, but needs several things to be fleshed
  7431. ** out:
  7432. **
  7433. ** - handling of unicode escape sequences (including high surrogate pairs).
  7434. ** - properly check and report errors for unknown fields, stack overflow,
  7435. ** improper array nesting (or lack of nesting).
  7436. ** - handling of base64 sequences with padding characters.
  7437. ** - handling of push-back (non-success returns from sink functions).
  7438. ** - handling of keys/escape-sequences/etc that span input buffers.
  7439. */
  7440. #include <ctype.h>
  7441. #include <errno.h>
  7442. #include <float.h>
  7443. #include <math.h>
  7444. #include <stdint.h>
  7445. #include <stdio.h>
  7446. #include <stdlib.h>
  7447. #include <string.h>
  7448. #include <time.h>
  7449. #define UPB_JSON_MAX_DEPTH 64
  7450. /* Type of value message */
  7451. enum {
  7452. VALUE_NULLVALUE = 0,
  7453. VALUE_NUMBERVALUE = 1,
  7454. VALUE_STRINGVALUE = 2,
  7455. VALUE_BOOLVALUE = 3,
  7456. VALUE_STRUCTVALUE = 4,
  7457. VALUE_LISTVALUE = 5
  7458. };
  7459. /* Forward declare */
  7460. static bool is_top_level(upb_json_parser *p);
  7461. static bool is_wellknown_msg(upb_json_parser *p, upb_wellknowntype_t type);
  7462. static bool is_wellknown_field(upb_json_parser *p, upb_wellknowntype_t type);
  7463. static bool is_number_wrapper_object(upb_json_parser *p);
  7464. static bool does_number_wrapper_start(upb_json_parser *p);
  7465. static bool does_number_wrapper_end(upb_json_parser *p);
  7466. static bool is_string_wrapper_object(upb_json_parser *p);
  7467. static bool does_string_wrapper_start(upb_json_parser *p);
  7468. static bool does_string_wrapper_end(upb_json_parser *p);
  7469. static bool does_fieldmask_start(upb_json_parser *p);
  7470. static bool does_fieldmask_end(upb_json_parser *p);
  7471. static void start_fieldmask_object(upb_json_parser *p);
  7472. static void end_fieldmask_object(upb_json_parser *p);
  7473. static void start_wrapper_object(upb_json_parser *p);
  7474. static void end_wrapper_object(upb_json_parser *p);
  7475. static void start_value_object(upb_json_parser *p, int value_type);
  7476. static void end_value_object(upb_json_parser *p);
  7477. static void start_listvalue_object(upb_json_parser *p);
  7478. static void end_listvalue_object(upb_json_parser *p);
  7479. static void start_structvalue_object(upb_json_parser *p);
  7480. static void end_structvalue_object(upb_json_parser *p);
  7481. static void start_object(upb_json_parser *p);
  7482. static void end_object(upb_json_parser *p);
  7483. static void start_any_object(upb_json_parser *p, const char *ptr);
  7484. static bool end_any_object(upb_json_parser *p, const char *ptr);
  7485. static bool start_subobject(upb_json_parser *p);
  7486. static void end_subobject(upb_json_parser *p);
  7487. static void start_member(upb_json_parser *p);
  7488. static void end_member(upb_json_parser *p);
  7489. static bool end_membername(upb_json_parser *p);
  7490. static void start_any_member(upb_json_parser *p, const char *ptr);
  7491. static void end_any_member(upb_json_parser *p, const char *ptr);
  7492. static bool end_any_membername(upb_json_parser *p);
  7493. size_t parse(void *closure, const void *hd, const char *buf, size_t size,
  7494. const upb_bufhandle *handle);
  7495. static bool end(void *closure, const void *hd);
  7496. static const char eof_ch = 'e';
  7497. /* stringsink */
  7498. typedef struct {
  7499. upb_byteshandler handler;
  7500. upb_bytessink sink;
  7501. char *ptr;
  7502. size_t len, size;
  7503. } upb_stringsink;
  7504. static void *stringsink_start(void *_sink, const void *hd, size_t size_hint) {
  7505. upb_stringsink *sink = _sink;
  7506. sink->len = 0;
  7507. UPB_UNUSED(hd);
  7508. UPB_UNUSED(size_hint);
  7509. return sink;
  7510. }
  7511. static size_t stringsink_string(void *_sink, const void *hd, const char *ptr,
  7512. size_t len, const upb_bufhandle *handle) {
  7513. upb_stringsink *sink = _sink;
  7514. size_t new_size = sink->size;
  7515. UPB_UNUSED(hd);
  7516. UPB_UNUSED(handle);
  7517. while (sink->len + len > new_size) {
  7518. new_size *= 2;
  7519. }
  7520. if (new_size != sink->size) {
  7521. sink->ptr = realloc(sink->ptr, new_size);
  7522. sink->size = new_size;
  7523. }
  7524. memcpy(sink->ptr + sink->len, ptr, len);
  7525. sink->len += len;
  7526. return len;
  7527. }
  7528. void upb_stringsink_init(upb_stringsink *sink) {
  7529. upb_byteshandler_init(&sink->handler);
  7530. upb_byteshandler_setstartstr(&sink->handler, stringsink_start, NULL);
  7531. upb_byteshandler_setstring(&sink->handler, stringsink_string, NULL);
  7532. upb_bytessink_reset(&sink->sink, &sink->handler, sink);
  7533. sink->size = 32;
  7534. sink->ptr = malloc(sink->size);
  7535. sink->len = 0;
  7536. }
  7537. void upb_stringsink_uninit(upb_stringsink *sink) { free(sink->ptr); }
  7538. typedef struct {
  7539. /* For encoding Any value field in binary format. */
  7540. upb_handlercache *encoder_handlercache;
  7541. upb_stringsink stringsink;
  7542. /* For decoding Any value field in json format. */
  7543. upb_json_codecache *parser_codecache;
  7544. upb_sink sink;
  7545. upb_json_parser *parser;
  7546. /* Mark the range of uninterpreted values in json input before type url. */
  7547. const char *before_type_url_start;
  7548. const char *before_type_url_end;
  7549. /* Mark the range of uninterpreted values in json input after type url. */
  7550. const char *after_type_url_start;
  7551. } upb_jsonparser_any_frame;
  7552. typedef struct {
  7553. upb_sink sink;
  7554. /* The current message in which we're parsing, and the field whose value we're
  7555. * expecting next. */
  7556. const upb_msgdef *m;
  7557. const upb_fielddef *f;
  7558. /* The table mapping json name to fielddef for this message. */
  7559. const upb_strtable *name_table;
  7560. /* We are in a repeated-field context. We need this flag to decide whether to
  7561. * handle the array as a normal repeated field or a
  7562. * google.protobuf.ListValue/google.protobuf.Value. */
  7563. bool is_repeated;
  7564. /* We are in a repeated-field context, ready to emit mapentries as
  7565. * submessages. This flag alters the start-of-object (open-brace) behavior to
  7566. * begin a sequence of mapentry messages rather than a single submessage. */
  7567. bool is_map;
  7568. /* We are in a map-entry message context. This flag is set when parsing the
  7569. * value field of a single map entry and indicates to all value-field parsers
  7570. * (subobjects, strings, numbers, and bools) that the map-entry submessage
  7571. * should end as soon as the value is parsed. */
  7572. bool is_mapentry;
  7573. /* If |is_map| or |is_mapentry| is true, |mapfield| refers to the parent
  7574. * message's map field that we're currently parsing. This differs from |f|
  7575. * because |f| is the field in the *current* message (i.e., the map-entry
  7576. * message itself), not the parent's field that leads to this map. */
  7577. const upb_fielddef *mapfield;
  7578. /* We are in an Any message context. This flag is set when parsing the Any
  7579. * message and indicates to all field parsers (subobjects, strings, numbers,
  7580. * and bools) that the parsed field should be serialized as binary data or
  7581. * cached (type url not found yet). */
  7582. bool is_any;
  7583. /* The type of packed message in Any. */
  7584. upb_jsonparser_any_frame *any_frame;
  7585. /* True if the field to be parsed is unknown. */
  7586. bool is_unknown_field;
  7587. } upb_jsonparser_frame;
  7588. static void init_frame(upb_jsonparser_frame* frame) {
  7589. frame->m = NULL;
  7590. frame->f = NULL;
  7591. frame->name_table = NULL;
  7592. frame->is_repeated = false;
  7593. frame->is_map = false;
  7594. frame->is_mapentry = false;
  7595. frame->mapfield = NULL;
  7596. frame->is_any = false;
  7597. frame->any_frame = NULL;
  7598. frame->is_unknown_field = false;
  7599. }
  7600. struct upb_json_parser {
  7601. upb_arena *arena;
  7602. const upb_json_parsermethod *method;
  7603. upb_bytessink input_;
  7604. /* Stack to track the JSON scopes we are in. */
  7605. upb_jsonparser_frame stack[UPB_JSON_MAX_DEPTH];
  7606. upb_jsonparser_frame *top;
  7607. upb_jsonparser_frame *limit;
  7608. upb_status *status;
  7609. /* Ragel's internal parsing stack for the parsing state machine. */
  7610. int current_state;
  7611. int parser_stack[UPB_JSON_MAX_DEPTH];
  7612. int parser_top;
  7613. /* The handle for the current buffer. */
  7614. const upb_bufhandle *handle;
  7615. /* Accumulate buffer. See details in parser.rl. */
  7616. const char *accumulated;
  7617. size_t accumulated_len;
  7618. char *accumulate_buf;
  7619. size_t accumulate_buf_size;
  7620. /* Multi-part text data. See details in parser.rl. */
  7621. int multipart_state;
  7622. upb_selector_t string_selector;
  7623. /* Input capture. See details in parser.rl. */
  7624. const char *capture;
  7625. /* Intermediate result of parsing a unicode escape sequence. */
  7626. uint32_t digit;
  7627. /* For resolve type url in Any. */
  7628. const upb_symtab *symtab;
  7629. /* Whether to proceed if unknown field is met. */
  7630. bool ignore_json_unknown;
  7631. /* Cache for parsing timestamp due to base and zone are handled in different
  7632. * handlers. */
  7633. struct tm tm;
  7634. };
  7635. static upb_jsonparser_frame* start_jsonparser_frame(upb_json_parser *p) {
  7636. upb_jsonparser_frame *inner;
  7637. inner = p->top + 1;
  7638. init_frame(inner);
  7639. return inner;
  7640. }
  7641. struct upb_json_codecache {
  7642. upb_arena *arena;
  7643. upb_inttable methods; /* upb_msgdef* -> upb_json_parsermethod* */
  7644. };
  7645. struct upb_json_parsermethod {
  7646. const upb_json_codecache *cache;
  7647. upb_byteshandler input_handler_;
  7648. /* Maps json_name -> fielddef */
  7649. upb_strtable name_table;
  7650. };
  7651. #define PARSER_CHECK_RETURN(x) if (!(x)) return false
  7652. static upb_jsonparser_any_frame *json_parser_any_frame_new(
  7653. upb_json_parser *p) {
  7654. upb_jsonparser_any_frame *frame;
  7655. frame = upb_arena_malloc(p->arena, sizeof(upb_jsonparser_any_frame));
  7656. frame->encoder_handlercache = upb_pb_encoder_newcache();
  7657. frame->parser_codecache = upb_json_codecache_new();
  7658. frame->parser = NULL;
  7659. frame->before_type_url_start = NULL;
  7660. frame->before_type_url_end = NULL;
  7661. frame->after_type_url_start = NULL;
  7662. upb_stringsink_init(&frame->stringsink);
  7663. return frame;
  7664. }
  7665. static void json_parser_any_frame_set_payload_type(
  7666. upb_json_parser *p,
  7667. upb_jsonparser_any_frame *frame,
  7668. const upb_msgdef *payload_type) {
  7669. const upb_handlers *h;
  7670. const upb_json_parsermethod *parser_method;
  7671. upb_pb_encoder *encoder;
  7672. /* Initialize encoder. */
  7673. h = upb_handlercache_get(frame->encoder_handlercache, payload_type);
  7674. encoder = upb_pb_encoder_create(p->arena, h, frame->stringsink.sink);
  7675. /* Initialize parser. */
  7676. parser_method = upb_json_codecache_get(frame->parser_codecache, payload_type);
  7677. upb_sink_reset(&frame->sink, h, encoder);
  7678. frame->parser =
  7679. upb_json_parser_create(p->arena, parser_method, p->symtab, frame->sink,
  7680. p->status, p->ignore_json_unknown);
  7681. }
  7682. static void json_parser_any_frame_free(upb_jsonparser_any_frame *frame) {
  7683. upb_handlercache_free(frame->encoder_handlercache);
  7684. upb_json_codecache_free(frame->parser_codecache);
  7685. upb_stringsink_uninit(&frame->stringsink);
  7686. }
  7687. static bool json_parser_any_frame_has_type_url(
  7688. upb_jsonparser_any_frame *frame) {
  7689. return frame->parser != NULL;
  7690. }
  7691. static bool json_parser_any_frame_has_value_before_type_url(
  7692. upb_jsonparser_any_frame *frame) {
  7693. return frame->before_type_url_start != frame->before_type_url_end;
  7694. }
  7695. static bool json_parser_any_frame_has_value_after_type_url(
  7696. upb_jsonparser_any_frame *frame) {
  7697. return frame->after_type_url_start != NULL;
  7698. }
  7699. static bool json_parser_any_frame_has_value(
  7700. upb_jsonparser_any_frame *frame) {
  7701. return json_parser_any_frame_has_value_before_type_url(frame) ||
  7702. json_parser_any_frame_has_value_after_type_url(frame);
  7703. }
  7704. static void json_parser_any_frame_set_before_type_url_end(
  7705. upb_jsonparser_any_frame *frame,
  7706. const char *ptr) {
  7707. if (frame->parser == NULL) {
  7708. frame->before_type_url_end = ptr;
  7709. }
  7710. }
  7711. static void json_parser_any_frame_set_after_type_url_start_once(
  7712. upb_jsonparser_any_frame *frame,
  7713. const char *ptr) {
  7714. if (json_parser_any_frame_has_type_url(frame) &&
  7715. frame->after_type_url_start == NULL) {
  7716. frame->after_type_url_start = ptr;
  7717. }
  7718. }
  7719. /* Used to signal that a capture has been suspended. */
  7720. static char suspend_capture;
  7721. static upb_selector_t getsel_for_handlertype(upb_json_parser *p,
  7722. upb_handlertype_t type) {
  7723. upb_selector_t sel;
  7724. bool ok = upb_handlers_getselector(p->top->f, type, &sel);
  7725. UPB_ASSERT(ok);
  7726. return sel;
  7727. }
  7728. static upb_selector_t parser_getsel(upb_json_parser *p) {
  7729. return getsel_for_handlertype(
  7730. p, upb_handlers_getprimitivehandlertype(p->top->f));
  7731. }
  7732. static bool check_stack(upb_json_parser *p) {
  7733. if ((p->top + 1) == p->limit) {
  7734. upb_status_seterrmsg(p->status, "Nesting too deep");
  7735. return false;
  7736. }
  7737. return true;
  7738. }
  7739. static void set_name_table(upb_json_parser *p, upb_jsonparser_frame *frame) {
  7740. upb_value v;
  7741. const upb_json_codecache *cache = p->method->cache;
  7742. bool ok;
  7743. const upb_json_parsermethod *method;
  7744. ok = upb_inttable_lookupptr(&cache->methods, frame->m, &v);
  7745. UPB_ASSERT(ok);
  7746. method = upb_value_getconstptr(v);
  7747. frame->name_table = &method->name_table;
  7748. }
  7749. /* There are GCC/Clang built-ins for overflow checking which we could start
  7750. * using if there was any performance benefit to it. */
  7751. static bool checked_add(size_t a, size_t b, size_t *c) {
  7752. if (SIZE_MAX - a < b) return false;
  7753. *c = a + b;
  7754. return true;
  7755. }
  7756. static size_t saturating_multiply(size_t a, size_t b) {
  7757. /* size_t is unsigned, so this is defined behavior even on overflow. */
  7758. size_t ret = a * b;
  7759. if (b != 0 && ret / b != a) {
  7760. ret = SIZE_MAX;
  7761. }
  7762. return ret;
  7763. }
  7764. /* Base64 decoding ************************************************************/
  7765. /* TODO(haberman): make this streaming. */
  7766. static const signed char b64table[] = {
  7767. -1, -1, -1, -1, -1, -1, -1, -1,
  7768. -1, -1, -1, -1, -1, -1, -1, -1,
  7769. -1, -1, -1, -1, -1, -1, -1, -1,
  7770. -1, -1, -1, -1, -1, -1, -1, -1,
  7771. -1, -1, -1, -1, -1, -1, -1, -1,
  7772. -1, -1, -1, 62/*+*/, -1, -1, -1, 63/*/ */,
  7773. 52/*0*/, 53/*1*/, 54/*2*/, 55/*3*/, 56/*4*/, 57/*5*/, 58/*6*/, 59/*7*/,
  7774. 60/*8*/, 61/*9*/, -1, -1, -1, -1, -1, -1,
  7775. -1, 0/*A*/, 1/*B*/, 2/*C*/, 3/*D*/, 4/*E*/, 5/*F*/, 6/*G*/,
  7776. 07/*H*/, 8/*I*/, 9/*J*/, 10/*K*/, 11/*L*/, 12/*M*/, 13/*N*/, 14/*O*/,
  7777. 15/*P*/, 16/*Q*/, 17/*R*/, 18/*S*/, 19/*T*/, 20/*U*/, 21/*V*/, 22/*W*/,
  7778. 23/*X*/, 24/*Y*/, 25/*Z*/, -1, -1, -1, -1, -1,
  7779. -1, 26/*a*/, 27/*b*/, 28/*c*/, 29/*d*/, 30/*e*/, 31/*f*/, 32/*g*/,
  7780. 33/*h*/, 34/*i*/, 35/*j*/, 36/*k*/, 37/*l*/, 38/*m*/, 39/*n*/, 40/*o*/,
  7781. 41/*p*/, 42/*q*/, 43/*r*/, 44/*s*/, 45/*t*/, 46/*u*/, 47/*v*/, 48/*w*/,
  7782. 49/*x*/, 50/*y*/, 51/*z*/, -1, -1, -1, -1, -1,
  7783. -1, -1, -1, -1, -1, -1, -1, -1,
  7784. -1, -1, -1, -1, -1, -1, -1, -1,
  7785. -1, -1, -1, -1, -1, -1, -1, -1,
  7786. -1, -1, -1, -1, -1, -1, -1, -1,
  7787. -1, -1, -1, -1, -1, -1, -1, -1,
  7788. -1, -1, -1, -1, -1, -1, -1, -1,
  7789. -1, -1, -1, -1, -1, -1, -1, -1,
  7790. -1, -1, -1, -1, -1, -1, -1, -1,
  7791. -1, -1, -1, -1, -1, -1, -1, -1,
  7792. -1, -1, -1, -1, -1, -1, -1, -1,
  7793. -1, -1, -1, -1, -1, -1, -1, -1,
  7794. -1, -1, -1, -1, -1, -1, -1, -1,
  7795. -1, -1, -1, -1, -1, -1, -1, -1,
  7796. -1, -1, -1, -1, -1, -1, -1, -1,
  7797. -1, -1, -1, -1, -1, -1, -1, -1,
  7798. -1, -1, -1, -1, -1, -1, -1, -1
  7799. };
  7800. /* Returns the table value sign-extended to 32 bits. Knowing that the upper
  7801. * bits will be 1 for unrecognized characters makes it easier to check for
  7802. * this error condition later (see below). */
  7803. int32_t b64lookup(unsigned char ch) { return b64table[ch]; }
  7804. /* Returns true if the given character is not a valid base64 character or
  7805. * padding. */
  7806. bool nonbase64(unsigned char ch) { return b64lookup(ch) == -1 && ch != '='; }
  7807. static bool base64_push(upb_json_parser *p, upb_selector_t sel, const char *ptr,
  7808. size_t len) {
  7809. const char *limit = ptr + len;
  7810. for (; ptr < limit; ptr += 4) {
  7811. uint32_t val;
  7812. char output[3];
  7813. if (limit - ptr < 4) {
  7814. upb_status_seterrf(p->status,
  7815. "Base64 input for bytes field not a multiple of 4: %s",
  7816. upb_fielddef_name(p->top->f));
  7817. return false;
  7818. }
  7819. val = b64lookup(ptr[0]) << 18 |
  7820. b64lookup(ptr[1]) << 12 |
  7821. b64lookup(ptr[2]) << 6 |
  7822. b64lookup(ptr[3]);
  7823. /* Test the upper bit; returns true if any of the characters returned -1. */
  7824. if (val & 0x80000000) {
  7825. goto otherchar;
  7826. }
  7827. output[0] = val >> 16;
  7828. output[1] = (val >> 8) & 0xff;
  7829. output[2] = val & 0xff;
  7830. upb_sink_putstring(p->top->sink, sel, output, 3, NULL);
  7831. }
  7832. return true;
  7833. otherchar:
  7834. if (nonbase64(ptr[0]) || nonbase64(ptr[1]) || nonbase64(ptr[2]) ||
  7835. nonbase64(ptr[3]) ) {
  7836. upb_status_seterrf(p->status,
  7837. "Non-base64 characters in bytes field: %s",
  7838. upb_fielddef_name(p->top->f));
  7839. return false;
  7840. } if (ptr[2] == '=') {
  7841. uint32_t val;
  7842. char output;
  7843. /* Last group contains only two input bytes, one output byte. */
  7844. if (ptr[0] == '=' || ptr[1] == '=' || ptr[3] != '=') {
  7845. goto badpadding;
  7846. }
  7847. val = b64lookup(ptr[0]) << 18 |
  7848. b64lookup(ptr[1]) << 12;
  7849. UPB_ASSERT(!(val & 0x80000000));
  7850. output = val >> 16;
  7851. upb_sink_putstring(p->top->sink, sel, &output, 1, NULL);
  7852. return true;
  7853. } else {
  7854. uint32_t val;
  7855. char output[2];
  7856. /* Last group contains only three input bytes, two output bytes. */
  7857. if (ptr[0] == '=' || ptr[1] == '=' || ptr[2] == '=') {
  7858. goto badpadding;
  7859. }
  7860. val = b64lookup(ptr[0]) << 18 |
  7861. b64lookup(ptr[1]) << 12 |
  7862. b64lookup(ptr[2]) << 6;
  7863. output[0] = val >> 16;
  7864. output[1] = (val >> 8) & 0xff;
  7865. upb_sink_putstring(p->top->sink, sel, output, 2, NULL);
  7866. return true;
  7867. }
  7868. badpadding:
  7869. upb_status_seterrf(p->status,
  7870. "Incorrect base64 padding for field: %s (%.*s)",
  7871. upb_fielddef_name(p->top->f),
  7872. 4, ptr);
  7873. return false;
  7874. }
  7875. /* Accumulate buffer **********************************************************/
  7876. /* Functionality for accumulating a buffer.
  7877. *
  7878. * Some parts of the parser need an entire value as a contiguous string. For
  7879. * example, to look up a member name in a hash table, or to turn a string into
  7880. * a number, the relevant library routines need the input string to be in
  7881. * contiguous memory, even if the value spanned two or more buffers in the
  7882. * input. These routines handle that.
  7883. *
  7884. * In the common case we can just point to the input buffer to get this
  7885. * contiguous string and avoid any actual copy. So we optimistically begin
  7886. * this way. But there are a few cases where we must instead copy into a
  7887. * separate buffer:
  7888. *
  7889. * 1. The string was not contiguous in the input (it spanned buffers).
  7890. *
  7891. * 2. The string included escape sequences that need to be interpreted to get
  7892. * the true value in a contiguous buffer. */
  7893. static void assert_accumulate_empty(upb_json_parser *p) {
  7894. UPB_ASSERT(p->accumulated == NULL);
  7895. UPB_ASSERT(p->accumulated_len == 0);
  7896. }
  7897. static void accumulate_clear(upb_json_parser *p) {
  7898. p->accumulated = NULL;
  7899. p->accumulated_len = 0;
  7900. }
  7901. /* Used internally by accumulate_append(). */
  7902. static bool accumulate_realloc(upb_json_parser *p, size_t need) {
  7903. void *mem;
  7904. size_t old_size = p->accumulate_buf_size;
  7905. size_t new_size = UPB_MAX(old_size, 128);
  7906. while (new_size < need) {
  7907. new_size = saturating_multiply(new_size, 2);
  7908. }
  7909. mem = upb_arena_realloc(p->arena, p->accumulate_buf, old_size, new_size);
  7910. if (!mem) {
  7911. upb_status_seterrmsg(p->status, "Out of memory allocating buffer.");
  7912. return false;
  7913. }
  7914. p->accumulate_buf = mem;
  7915. p->accumulate_buf_size = new_size;
  7916. return true;
  7917. }
  7918. /* Logically appends the given data to the append buffer.
  7919. * If "can_alias" is true, we will try to avoid actually copying, but the buffer
  7920. * must be valid until the next accumulate_append() call (if any). */
  7921. static bool accumulate_append(upb_json_parser *p, const char *buf, size_t len,
  7922. bool can_alias) {
  7923. size_t need;
  7924. if (!p->accumulated && can_alias) {
  7925. p->accumulated = buf;
  7926. p->accumulated_len = len;
  7927. return true;
  7928. }
  7929. if (!checked_add(p->accumulated_len, len, &need)) {
  7930. upb_status_seterrmsg(p->status, "Integer overflow.");
  7931. return false;
  7932. }
  7933. if (need > p->accumulate_buf_size && !accumulate_realloc(p, need)) {
  7934. return false;
  7935. }
  7936. if (p->accumulated != p->accumulate_buf) {
  7937. memcpy(p->accumulate_buf, p->accumulated, p->accumulated_len);
  7938. p->accumulated = p->accumulate_buf;
  7939. }
  7940. memcpy(p->accumulate_buf + p->accumulated_len, buf, len);
  7941. p->accumulated_len += len;
  7942. return true;
  7943. }
  7944. /* Returns a pointer to the data accumulated since the last accumulate_clear()
  7945. * call, and writes the length to *len. This with point either to the input
  7946. * buffer or a temporary accumulate buffer. */
  7947. static const char *accumulate_getptr(upb_json_parser *p, size_t *len) {
  7948. UPB_ASSERT(p->accumulated);
  7949. *len = p->accumulated_len;
  7950. return p->accumulated;
  7951. }
  7952. /* Mult-part text data ********************************************************/
  7953. /* When we have text data in the input, it can often come in multiple segments.
  7954. * For example, there may be some raw string data followed by an escape
  7955. * sequence. The two segments are processed with different logic. Also buffer
  7956. * seams in the input can cause multiple segments.
  7957. *
  7958. * As we see segments, there are two main cases for how we want to process them:
  7959. *
  7960. * 1. we want to push the captured input directly to string handlers.
  7961. *
  7962. * 2. we need to accumulate all the parts into a contiguous buffer for further
  7963. * processing (field name lookup, string->number conversion, etc). */
  7964. /* This is the set of states for p->multipart_state. */
  7965. enum {
  7966. /* We are not currently processing multipart data. */
  7967. MULTIPART_INACTIVE = 0,
  7968. /* We are processing multipart data by accumulating it into a contiguous
  7969. * buffer. */
  7970. MULTIPART_ACCUMULATE = 1,
  7971. /* We are processing multipart data by pushing each part directly to the
  7972. * current string handlers. */
  7973. MULTIPART_PUSHEAGERLY = 2
  7974. };
  7975. /* Start a multi-part text value where we accumulate the data for processing at
  7976. * the end. */
  7977. static void multipart_startaccum(upb_json_parser *p) {
  7978. assert_accumulate_empty(p);
  7979. UPB_ASSERT(p->multipart_state == MULTIPART_INACTIVE);
  7980. p->multipart_state = MULTIPART_ACCUMULATE;
  7981. }
  7982. /* Start a multi-part text value where we immediately push text data to a string
  7983. * value with the given selector. */
  7984. static void multipart_start(upb_json_parser *p, upb_selector_t sel) {
  7985. assert_accumulate_empty(p);
  7986. UPB_ASSERT(p->multipart_state == MULTIPART_INACTIVE);
  7987. p->multipart_state = MULTIPART_PUSHEAGERLY;
  7988. p->string_selector = sel;
  7989. }
  7990. static bool multipart_text(upb_json_parser *p, const char *buf, size_t len,
  7991. bool can_alias) {
  7992. switch (p->multipart_state) {
  7993. case MULTIPART_INACTIVE:
  7994. upb_status_seterrmsg(
  7995. p->status, "Internal error: unexpected state MULTIPART_INACTIVE");
  7996. return false;
  7997. case MULTIPART_ACCUMULATE:
  7998. if (!accumulate_append(p, buf, len, can_alias)) {
  7999. return false;
  8000. }
  8001. break;
  8002. case MULTIPART_PUSHEAGERLY: {
  8003. const upb_bufhandle *handle = can_alias ? p->handle : NULL;
  8004. upb_sink_putstring(p->top->sink, p->string_selector, buf, len, handle);
  8005. break;
  8006. }
  8007. }
  8008. return true;
  8009. }
  8010. /* Note: this invalidates the accumulate buffer! Call only after reading its
  8011. * contents. */
  8012. static void multipart_end(upb_json_parser *p) {
  8013. UPB_ASSERT(p->multipart_state != MULTIPART_INACTIVE);
  8014. p->multipart_state = MULTIPART_INACTIVE;
  8015. accumulate_clear(p);
  8016. }
  8017. /* Input capture **************************************************************/
  8018. /* Functionality for capturing a region of the input as text. Gracefully
  8019. * handles the case where a buffer seam occurs in the middle of the captured
  8020. * region. */
  8021. static void capture_begin(upb_json_parser *p, const char *ptr) {
  8022. UPB_ASSERT(p->multipart_state != MULTIPART_INACTIVE);
  8023. UPB_ASSERT(p->capture == NULL);
  8024. p->capture = ptr;
  8025. }
  8026. static bool capture_end(upb_json_parser *p, const char *ptr) {
  8027. UPB_ASSERT(p->capture);
  8028. if (multipart_text(p, p->capture, ptr - p->capture, true)) {
  8029. p->capture = NULL;
  8030. return true;
  8031. } else {
  8032. return false;
  8033. }
  8034. }
  8035. /* This is called at the end of each input buffer (ie. when we have hit a
  8036. * buffer seam). If we are in the middle of capturing the input, this
  8037. * processes the unprocessed capture region. */
  8038. static void capture_suspend(upb_json_parser *p, const char **ptr) {
  8039. if (!p->capture) return;
  8040. if (multipart_text(p, p->capture, *ptr - p->capture, false)) {
  8041. /* We use this as a signal that we were in the middle of capturing, and
  8042. * that capturing should resume at the beginning of the next buffer.
  8043. *
  8044. * We can't use *ptr here, because we have no guarantee that this pointer
  8045. * will be valid when we resume (if the underlying memory is freed, then
  8046. * using the pointer at all, even to compare to NULL, is likely undefined
  8047. * behavior). */
  8048. p->capture = &suspend_capture;
  8049. } else {
  8050. /* Need to back up the pointer to the beginning of the capture, since
  8051. * we were not able to actually preserve it. */
  8052. *ptr = p->capture;
  8053. }
  8054. }
  8055. static void capture_resume(upb_json_parser *p, const char *ptr) {
  8056. if (p->capture) {
  8057. UPB_ASSERT(p->capture == &suspend_capture);
  8058. p->capture = ptr;
  8059. }
  8060. }
  8061. /* Callbacks from the parser **************************************************/
  8062. /* These are the functions called directly from the parser itself.
  8063. * We define these in the same order as their declarations in the parser. */
  8064. static char escape_char(char in) {
  8065. switch (in) {
  8066. case 'r': return '\r';
  8067. case 't': return '\t';
  8068. case 'n': return '\n';
  8069. case 'f': return '\f';
  8070. case 'b': return '\b';
  8071. case '/': return '/';
  8072. case '"': return '"';
  8073. case '\\': return '\\';
  8074. default:
  8075. UPB_ASSERT(0);
  8076. return 'x';
  8077. }
  8078. }
  8079. static bool escape(upb_json_parser *p, const char *ptr) {
  8080. char ch = escape_char(*ptr);
  8081. return multipart_text(p, &ch, 1, false);
  8082. }
  8083. static void start_hex(upb_json_parser *p) {
  8084. p->digit = 0;
  8085. }
  8086. static void hexdigit(upb_json_parser *p, const char *ptr) {
  8087. char ch = *ptr;
  8088. p->digit <<= 4;
  8089. if (ch >= '0' && ch <= '9') {
  8090. p->digit += (ch - '0');
  8091. } else if (ch >= 'a' && ch <= 'f') {
  8092. p->digit += ((ch - 'a') + 10);
  8093. } else {
  8094. UPB_ASSERT(ch >= 'A' && ch <= 'F');
  8095. p->digit += ((ch - 'A') + 10);
  8096. }
  8097. }
  8098. static bool end_hex(upb_json_parser *p) {
  8099. uint32_t codepoint = p->digit;
  8100. /* emit the codepoint as UTF-8. */
  8101. char utf8[3]; /* support \u0000 -- \uFFFF -- need only three bytes. */
  8102. int length = 0;
  8103. if (codepoint <= 0x7F) {
  8104. utf8[0] = codepoint;
  8105. length = 1;
  8106. } else if (codepoint <= 0x07FF) {
  8107. utf8[1] = (codepoint & 0x3F) | 0x80;
  8108. codepoint >>= 6;
  8109. utf8[0] = (codepoint & 0x1F) | 0xC0;
  8110. length = 2;
  8111. } else /* codepoint <= 0xFFFF */ {
  8112. utf8[2] = (codepoint & 0x3F) | 0x80;
  8113. codepoint >>= 6;
  8114. utf8[1] = (codepoint & 0x3F) | 0x80;
  8115. codepoint >>= 6;
  8116. utf8[0] = (codepoint & 0x0F) | 0xE0;
  8117. length = 3;
  8118. }
  8119. /* TODO(haberman): Handle high surrogates: if codepoint is a high surrogate
  8120. * we have to wait for the next escape to get the full code point). */
  8121. return multipart_text(p, utf8, length, false);
  8122. }
  8123. static void start_text(upb_json_parser *p, const char *ptr) {
  8124. capture_begin(p, ptr);
  8125. }
  8126. static bool end_text(upb_json_parser *p, const char *ptr) {
  8127. return capture_end(p, ptr);
  8128. }
  8129. static bool start_number(upb_json_parser *p, const char *ptr) {
  8130. if (is_top_level(p)) {
  8131. if (is_number_wrapper_object(p)) {
  8132. start_wrapper_object(p);
  8133. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8134. start_value_object(p, VALUE_NUMBERVALUE);
  8135. } else {
  8136. return false;
  8137. }
  8138. } else if (does_number_wrapper_start(p)) {
  8139. if (!start_subobject(p)) {
  8140. return false;
  8141. }
  8142. start_wrapper_object(p);
  8143. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  8144. if (!start_subobject(p)) {
  8145. return false;
  8146. }
  8147. start_value_object(p, VALUE_NUMBERVALUE);
  8148. }
  8149. multipart_startaccum(p);
  8150. capture_begin(p, ptr);
  8151. return true;
  8152. }
  8153. static bool parse_number(upb_json_parser *p, bool is_quoted);
  8154. static bool end_number_nontop(upb_json_parser *p, const char *ptr) {
  8155. if (!capture_end(p, ptr)) {
  8156. return false;
  8157. }
  8158. if (p->top->f == NULL) {
  8159. multipart_end(p);
  8160. return true;
  8161. }
  8162. return parse_number(p, false);
  8163. }
  8164. static bool end_number(upb_json_parser *p, const char *ptr) {
  8165. if (!end_number_nontop(p, ptr)) {
  8166. return false;
  8167. }
  8168. if (does_number_wrapper_end(p)) {
  8169. end_wrapper_object(p);
  8170. if (!is_top_level(p)) {
  8171. end_subobject(p);
  8172. }
  8173. return true;
  8174. }
  8175. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8176. end_value_object(p);
  8177. if (!is_top_level(p)) {
  8178. end_subobject(p);
  8179. }
  8180. return true;
  8181. }
  8182. return true;
  8183. }
  8184. /* |buf| is NULL-terminated. |buf| itself will never include quotes;
  8185. * |is_quoted| tells us whether this text originally appeared inside quotes. */
  8186. static bool parse_number_from_buffer(upb_json_parser *p, const char *buf,
  8187. bool is_quoted) {
  8188. size_t len = strlen(buf);
  8189. const char *bufend = buf + len;
  8190. char *end;
  8191. upb_fieldtype_t type = upb_fielddef_type(p->top->f);
  8192. double val;
  8193. double dummy;
  8194. double inf = 1.0 / 0.0; /* C89 does not have an INFINITY macro. */
  8195. errno = 0;
  8196. if (len == 0 || buf[0] == ' ') {
  8197. return false;
  8198. }
  8199. /* For integer types, first try parsing with integer-specific routines.
  8200. * If these succeed, they will be more accurate for int64/uint64 than
  8201. * strtod().
  8202. */
  8203. switch (type) {
  8204. case UPB_TYPE_ENUM:
  8205. case UPB_TYPE_INT32: {
  8206. long val = strtol(buf, &end, 0);
  8207. if (errno == ERANGE || end != bufend) {
  8208. break;
  8209. } else if (val > INT32_MAX || val < INT32_MIN) {
  8210. return false;
  8211. } else {
  8212. upb_sink_putint32(p->top->sink, parser_getsel(p), val);
  8213. return true;
  8214. }
  8215. }
  8216. case UPB_TYPE_UINT32: {
  8217. unsigned long val = strtoul(buf, &end, 0);
  8218. if (end != bufend) {
  8219. break;
  8220. } else if (val > UINT32_MAX || errno == ERANGE) {
  8221. return false;
  8222. } else {
  8223. upb_sink_putuint32(p->top->sink, parser_getsel(p), val);
  8224. return true;
  8225. }
  8226. }
  8227. /* XXX: We can't handle [u]int64 properly on 32-bit machines because
  8228. * strto[u]ll isn't in C89. */
  8229. case UPB_TYPE_INT64: {
  8230. long val = strtol(buf, &end, 0);
  8231. if (errno == ERANGE || end != bufend) {
  8232. break;
  8233. } else {
  8234. upb_sink_putint64(p->top->sink, parser_getsel(p), val);
  8235. return true;
  8236. }
  8237. }
  8238. case UPB_TYPE_UINT64: {
  8239. unsigned long val = strtoul(p->accumulated, &end, 0);
  8240. if (end != bufend) {
  8241. break;
  8242. } else if (errno == ERANGE) {
  8243. return false;
  8244. } else {
  8245. upb_sink_putuint64(p->top->sink, parser_getsel(p), val);
  8246. return true;
  8247. }
  8248. }
  8249. default:
  8250. break;
  8251. }
  8252. if (type != UPB_TYPE_DOUBLE && type != UPB_TYPE_FLOAT && is_quoted) {
  8253. /* Quoted numbers for integer types are not allowed to be in double form. */
  8254. return false;
  8255. }
  8256. if (len == strlen("Infinity") && strcmp(buf, "Infinity") == 0) {
  8257. /* C89 does not have an INFINITY macro. */
  8258. val = inf;
  8259. } else if (len == strlen("-Infinity") && strcmp(buf, "-Infinity") == 0) {
  8260. val = -inf;
  8261. } else {
  8262. val = strtod(buf, &end);
  8263. if (errno == ERANGE || end != bufend) {
  8264. return false;
  8265. }
  8266. }
  8267. switch (type) {
  8268. #define CASE(capitaltype, smalltype, ctype, min, max) \
  8269. case UPB_TYPE_ ## capitaltype: { \
  8270. if (modf(val, &dummy) != 0 || val > max || val < min) { \
  8271. return false; \
  8272. } else { \
  8273. upb_sink_put ## smalltype(p->top->sink, parser_getsel(p), \
  8274. (ctype)val); \
  8275. return true; \
  8276. } \
  8277. break; \
  8278. }
  8279. case UPB_TYPE_ENUM:
  8280. CASE(INT32, int32, int32_t, INT32_MIN, INT32_MAX);
  8281. CASE(INT64, int64, int64_t, INT64_MIN, INT64_MAX);
  8282. CASE(UINT32, uint32, uint32_t, 0, UINT32_MAX);
  8283. CASE(UINT64, uint64, uint64_t, 0, UINT64_MAX);
  8284. #undef CASE
  8285. case UPB_TYPE_DOUBLE:
  8286. upb_sink_putdouble(p->top->sink, parser_getsel(p), val);
  8287. return true;
  8288. case UPB_TYPE_FLOAT:
  8289. if ((val > FLT_MAX || val < -FLT_MAX) && val != inf && val != -inf) {
  8290. return false;
  8291. } else {
  8292. upb_sink_putfloat(p->top->sink, parser_getsel(p), val);
  8293. return true;
  8294. }
  8295. default:
  8296. return false;
  8297. }
  8298. }
  8299. static bool parse_number(upb_json_parser *p, bool is_quoted) {
  8300. size_t len;
  8301. const char *buf;
  8302. /* strtol() and friends unfortunately do not support specifying the length of
  8303. * the input string, so we need to force a copy into a NULL-terminated buffer. */
  8304. if (!multipart_text(p, "\0", 1, false)) {
  8305. return false;
  8306. }
  8307. buf = accumulate_getptr(p, &len);
  8308. if (parse_number_from_buffer(p, buf, is_quoted)) {
  8309. multipart_end(p);
  8310. return true;
  8311. } else {
  8312. upb_status_seterrf(p->status, "error parsing number: %s", buf);
  8313. multipart_end(p);
  8314. return false;
  8315. }
  8316. }
  8317. static bool parser_putbool(upb_json_parser *p, bool val) {
  8318. bool ok;
  8319. if (p->top->f == NULL) {
  8320. return true;
  8321. }
  8322. if (upb_fielddef_type(p->top->f) != UPB_TYPE_BOOL) {
  8323. upb_status_seterrf(p->status,
  8324. "Boolean value specified for non-bool field: %s",
  8325. upb_fielddef_name(p->top->f));
  8326. return false;
  8327. }
  8328. ok = upb_sink_putbool(p->top->sink, parser_getsel(p), val);
  8329. UPB_ASSERT(ok);
  8330. return true;
  8331. }
  8332. static bool end_bool(upb_json_parser *p, bool val) {
  8333. if (is_top_level(p)) {
  8334. if (is_wellknown_msg(p, UPB_WELLKNOWN_BOOLVALUE)) {
  8335. start_wrapper_object(p);
  8336. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8337. start_value_object(p, VALUE_BOOLVALUE);
  8338. } else {
  8339. return false;
  8340. }
  8341. } else if (is_wellknown_field(p, UPB_WELLKNOWN_BOOLVALUE)) {
  8342. if (!start_subobject(p)) {
  8343. return false;
  8344. }
  8345. start_wrapper_object(p);
  8346. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  8347. if (!start_subobject(p)) {
  8348. return false;
  8349. }
  8350. start_value_object(p, VALUE_BOOLVALUE);
  8351. }
  8352. if (p->top->is_unknown_field) {
  8353. return true;
  8354. }
  8355. if (!parser_putbool(p, val)) {
  8356. return false;
  8357. }
  8358. if (is_wellknown_msg(p, UPB_WELLKNOWN_BOOLVALUE)) {
  8359. end_wrapper_object(p);
  8360. if (!is_top_level(p)) {
  8361. end_subobject(p);
  8362. }
  8363. return true;
  8364. }
  8365. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8366. end_value_object(p);
  8367. if (!is_top_level(p)) {
  8368. end_subobject(p);
  8369. }
  8370. return true;
  8371. }
  8372. return true;
  8373. }
  8374. static bool end_null(upb_json_parser *p) {
  8375. const char *zero_ptr = "0";
  8376. if (is_top_level(p)) {
  8377. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8378. start_value_object(p, VALUE_NULLVALUE);
  8379. } else {
  8380. return true;
  8381. }
  8382. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  8383. if (!start_subobject(p)) {
  8384. return false;
  8385. }
  8386. start_value_object(p, VALUE_NULLVALUE);
  8387. } else {
  8388. return true;
  8389. }
  8390. /* Fill null_value field. */
  8391. multipart_startaccum(p);
  8392. capture_begin(p, zero_ptr);
  8393. capture_end(p, zero_ptr + 1);
  8394. parse_number(p, false);
  8395. end_value_object(p);
  8396. if (!is_top_level(p)) {
  8397. end_subobject(p);
  8398. }
  8399. return true;
  8400. }
  8401. static bool start_any_stringval(upb_json_parser *p) {
  8402. multipart_startaccum(p);
  8403. return true;
  8404. }
  8405. static bool start_stringval(upb_json_parser *p) {
  8406. if (is_top_level(p)) {
  8407. if (is_string_wrapper_object(p)) {
  8408. start_wrapper_object(p);
  8409. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_FIELDMASK)) {
  8410. start_fieldmask_object(p);
  8411. return true;
  8412. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_TIMESTAMP) ||
  8413. is_wellknown_msg(p, UPB_WELLKNOWN_DURATION)) {
  8414. start_object(p);
  8415. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8416. start_value_object(p, VALUE_STRINGVALUE);
  8417. } else {
  8418. return false;
  8419. }
  8420. } else if (does_string_wrapper_start(p)) {
  8421. if (!start_subobject(p)) {
  8422. return false;
  8423. }
  8424. start_wrapper_object(p);
  8425. } else if (does_fieldmask_start(p)) {
  8426. if (!start_subobject(p)) {
  8427. return false;
  8428. }
  8429. start_fieldmask_object(p);
  8430. return true;
  8431. } else if (is_wellknown_field(p, UPB_WELLKNOWN_TIMESTAMP) ||
  8432. is_wellknown_field(p, UPB_WELLKNOWN_DURATION)) {
  8433. if (!start_subobject(p)) {
  8434. return false;
  8435. }
  8436. start_object(p);
  8437. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  8438. if (!start_subobject(p)) {
  8439. return false;
  8440. }
  8441. start_value_object(p, VALUE_STRINGVALUE);
  8442. }
  8443. if (p->top->f == NULL) {
  8444. multipart_startaccum(p);
  8445. return true;
  8446. }
  8447. if (p->top->is_any) {
  8448. return start_any_stringval(p);
  8449. }
  8450. if (upb_fielddef_isstring(p->top->f)) {
  8451. upb_jsonparser_frame *inner;
  8452. upb_selector_t sel;
  8453. if (!check_stack(p)) return false;
  8454. /* Start a new parser frame: parser frames correspond one-to-one with
  8455. * handler frames, and string events occur in a sub-frame. */
  8456. inner = start_jsonparser_frame(p);
  8457. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  8458. upb_sink_startstr(p->top->sink, sel, 0, &inner->sink);
  8459. inner->m = p->top->m;
  8460. inner->f = p->top->f;
  8461. p->top = inner;
  8462. if (upb_fielddef_type(p->top->f) == UPB_TYPE_STRING) {
  8463. /* For STRING fields we push data directly to the handlers as it is
  8464. * parsed. We don't do this yet for BYTES fields, because our base64
  8465. * decoder is not streaming.
  8466. *
  8467. * TODO(haberman): make base64 decoding streaming also. */
  8468. multipart_start(p, getsel_for_handlertype(p, UPB_HANDLER_STRING));
  8469. return true;
  8470. } else {
  8471. multipart_startaccum(p);
  8472. return true;
  8473. }
  8474. } else if (upb_fielddef_type(p->top->f) != UPB_TYPE_BOOL &&
  8475. upb_fielddef_type(p->top->f) != UPB_TYPE_MESSAGE) {
  8476. /* No need to push a frame -- numeric values in quotes remain in the
  8477. * current parser frame. These values must accmulate so we can convert
  8478. * them all at once at the end. */
  8479. multipart_startaccum(p);
  8480. return true;
  8481. } else {
  8482. upb_status_seterrf(p->status,
  8483. "String specified for bool or submessage field: %s",
  8484. upb_fielddef_name(p->top->f));
  8485. return false;
  8486. }
  8487. }
  8488. static bool end_any_stringval(upb_json_parser *p) {
  8489. size_t len;
  8490. const char *buf = accumulate_getptr(p, &len);
  8491. /* Set type_url */
  8492. upb_selector_t sel;
  8493. upb_jsonparser_frame *inner;
  8494. if (!check_stack(p)) return false;
  8495. inner = p->top + 1;
  8496. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  8497. upb_sink_startstr(p->top->sink, sel, 0, &inner->sink);
  8498. sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
  8499. upb_sink_putstring(inner->sink, sel, buf, len, NULL);
  8500. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  8501. upb_sink_endstr(inner->sink, sel);
  8502. multipart_end(p);
  8503. /* Resolve type url */
  8504. if (strncmp(buf, "type.googleapis.com/", 20) == 0 && len > 20) {
  8505. const upb_msgdef *payload_type = NULL;
  8506. buf += 20;
  8507. len -= 20;
  8508. payload_type = upb_symtab_lookupmsg2(p->symtab, buf, len);
  8509. if (payload_type == NULL) {
  8510. upb_status_seterrf(
  8511. p->status, "Cannot find packed type: %.*s\n", (int)len, buf);
  8512. return false;
  8513. }
  8514. json_parser_any_frame_set_payload_type(p, p->top->any_frame, payload_type);
  8515. return true;
  8516. } else {
  8517. upb_status_seterrf(
  8518. p->status, "Invalid type url: %.*s\n", (int)len, buf);
  8519. return false;
  8520. }
  8521. }
  8522. static bool end_stringval_nontop(upb_json_parser *p) {
  8523. bool ok = true;
  8524. if (is_wellknown_msg(p, UPB_WELLKNOWN_TIMESTAMP) ||
  8525. is_wellknown_msg(p, UPB_WELLKNOWN_DURATION)) {
  8526. multipart_end(p);
  8527. return true;
  8528. }
  8529. if (p->top->f == NULL) {
  8530. multipart_end(p);
  8531. return true;
  8532. }
  8533. if (p->top->is_any) {
  8534. return end_any_stringval(p);
  8535. }
  8536. switch (upb_fielddef_type(p->top->f)) {
  8537. case UPB_TYPE_BYTES:
  8538. if (!base64_push(p, getsel_for_handlertype(p, UPB_HANDLER_STRING),
  8539. p->accumulated, p->accumulated_len)) {
  8540. return false;
  8541. }
  8542. /* Fall through. */
  8543. case UPB_TYPE_STRING: {
  8544. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  8545. upb_sink_endstr(p->top->sink, sel);
  8546. p->top--;
  8547. break;
  8548. }
  8549. case UPB_TYPE_ENUM: {
  8550. /* Resolve enum symbolic name to integer value. */
  8551. const upb_enumdef *enumdef = upb_fielddef_enumsubdef(p->top->f);
  8552. size_t len;
  8553. const char *buf = accumulate_getptr(p, &len);
  8554. int32_t int_val = 0;
  8555. ok = upb_enumdef_ntoi(enumdef, buf, len, &int_val);
  8556. if (ok) {
  8557. upb_selector_t sel = parser_getsel(p);
  8558. upb_sink_putint32(p->top->sink, sel, int_val);
  8559. } else {
  8560. upb_status_seterrf(p->status, "Enum value unknown: '%.*s'", len, buf);
  8561. }
  8562. break;
  8563. }
  8564. case UPB_TYPE_INT32:
  8565. case UPB_TYPE_INT64:
  8566. case UPB_TYPE_UINT32:
  8567. case UPB_TYPE_UINT64:
  8568. case UPB_TYPE_DOUBLE:
  8569. case UPB_TYPE_FLOAT:
  8570. ok = parse_number(p, true);
  8571. break;
  8572. default:
  8573. UPB_ASSERT(false);
  8574. upb_status_seterrmsg(p->status, "Internal error in JSON decoder");
  8575. ok = false;
  8576. break;
  8577. }
  8578. multipart_end(p);
  8579. return ok;
  8580. }
  8581. static bool end_stringval(upb_json_parser *p) {
  8582. /* FieldMask's stringvals have been ended when handling them. Only need to
  8583. * close FieldMask here.*/
  8584. if (does_fieldmask_end(p)) {
  8585. end_fieldmask_object(p);
  8586. if (!is_top_level(p)) {
  8587. end_subobject(p);
  8588. }
  8589. return true;
  8590. }
  8591. if (!end_stringval_nontop(p)) {
  8592. return false;
  8593. }
  8594. if (does_string_wrapper_end(p)) {
  8595. end_wrapper_object(p);
  8596. if (!is_top_level(p)) {
  8597. end_subobject(p);
  8598. }
  8599. return true;
  8600. }
  8601. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8602. end_value_object(p);
  8603. if (!is_top_level(p)) {
  8604. end_subobject(p);
  8605. }
  8606. return true;
  8607. }
  8608. if (is_wellknown_msg(p, UPB_WELLKNOWN_TIMESTAMP) ||
  8609. is_wellknown_msg(p, UPB_WELLKNOWN_DURATION) ||
  8610. is_wellknown_msg(p, UPB_WELLKNOWN_FIELDMASK)) {
  8611. end_object(p);
  8612. if (!is_top_level(p)) {
  8613. end_subobject(p);
  8614. }
  8615. return true;
  8616. }
  8617. return true;
  8618. }
  8619. static void start_duration_base(upb_json_parser *p, const char *ptr) {
  8620. capture_begin(p, ptr);
  8621. }
  8622. static bool end_duration_base(upb_json_parser *p, const char *ptr) {
  8623. size_t len;
  8624. const char *buf;
  8625. char seconds_buf[14];
  8626. char nanos_buf[12];
  8627. char *end;
  8628. int64_t seconds = 0;
  8629. int32_t nanos = 0;
  8630. double val = 0.0;
  8631. const char *seconds_membername = "seconds";
  8632. const char *nanos_membername = "nanos";
  8633. size_t fraction_start;
  8634. if (!capture_end(p, ptr)) {
  8635. return false;
  8636. }
  8637. buf = accumulate_getptr(p, &len);
  8638. memset(seconds_buf, 0, 14);
  8639. memset(nanos_buf, 0, 12);
  8640. /* Find out base end. The maximus duration is 315576000000, which cannot be
  8641. * represented by double without losing precision. Thus, we need to handle
  8642. * fraction and base separately. */
  8643. for (fraction_start = 0; fraction_start < len && buf[fraction_start] != '.';
  8644. fraction_start++);
  8645. /* Parse base */
  8646. memcpy(seconds_buf, buf, fraction_start);
  8647. seconds = strtol(seconds_buf, &end, 10);
  8648. if (errno == ERANGE || end != seconds_buf + fraction_start) {
  8649. upb_status_seterrf(p->status, "error parsing duration: %s",
  8650. seconds_buf);
  8651. return false;
  8652. }
  8653. if (seconds > 315576000000) {
  8654. upb_status_seterrf(p->status, "error parsing duration: "
  8655. "maximum acceptable value is "
  8656. "315576000000");
  8657. return false;
  8658. }
  8659. if (seconds < -315576000000) {
  8660. upb_status_seterrf(p->status, "error parsing duration: "
  8661. "minimum acceptable value is "
  8662. "-315576000000");
  8663. return false;
  8664. }
  8665. /* Parse fraction */
  8666. nanos_buf[0] = '0';
  8667. memcpy(nanos_buf + 1, buf + fraction_start, len - fraction_start);
  8668. val = strtod(nanos_buf, &end);
  8669. if (errno == ERANGE || end != nanos_buf + len - fraction_start + 1) {
  8670. upb_status_seterrf(p->status, "error parsing duration: %s",
  8671. nanos_buf);
  8672. return false;
  8673. }
  8674. nanos = val * 1000000000;
  8675. if (seconds < 0) nanos = -nanos;
  8676. /* Clean up buffer */
  8677. multipart_end(p);
  8678. /* Set seconds */
  8679. start_member(p);
  8680. capture_begin(p, seconds_membername);
  8681. capture_end(p, seconds_membername + 7);
  8682. end_membername(p);
  8683. upb_sink_putint64(p->top->sink, parser_getsel(p), seconds);
  8684. end_member(p);
  8685. /* Set nanos */
  8686. start_member(p);
  8687. capture_begin(p, nanos_membername);
  8688. capture_end(p, nanos_membername + 5);
  8689. end_membername(p);
  8690. upb_sink_putint32(p->top->sink, parser_getsel(p), nanos);
  8691. end_member(p);
  8692. /* Continue previous arena */
  8693. multipart_startaccum(p);
  8694. return true;
  8695. }
  8696. static int parse_timestamp_number(upb_json_parser *p) {
  8697. size_t len;
  8698. const char *buf;
  8699. char *end;
  8700. int val;
  8701. /* atoi() and friends unfortunately do not support specifying the length of
  8702. * the input string, so we need to force a copy into a NULL-terminated buffer. */
  8703. multipart_text(p, "\0", 1, false);
  8704. buf = accumulate_getptr(p, &len);
  8705. val = atoi(buf);
  8706. multipart_end(p);
  8707. multipart_startaccum(p);
  8708. return val;
  8709. }
  8710. static void start_year(upb_json_parser *p, const char *ptr) {
  8711. capture_begin(p, ptr);
  8712. }
  8713. static bool end_year(upb_json_parser *p, const char *ptr) {
  8714. if (!capture_end(p, ptr)) {
  8715. return false;
  8716. }
  8717. p->tm.tm_year = parse_timestamp_number(p) - 1900;
  8718. return true;
  8719. }
  8720. static void start_month(upb_json_parser *p, const char *ptr) {
  8721. capture_begin(p, ptr);
  8722. }
  8723. static bool end_month(upb_json_parser *p, const char *ptr) {
  8724. if (!capture_end(p, ptr)) {
  8725. return false;
  8726. }
  8727. p->tm.tm_mon = parse_timestamp_number(p) - 1;
  8728. return true;
  8729. }
  8730. static void start_day(upb_json_parser *p, const char *ptr) {
  8731. capture_begin(p, ptr);
  8732. }
  8733. static bool end_day(upb_json_parser *p, const char *ptr) {
  8734. if (!capture_end(p, ptr)) {
  8735. return false;
  8736. }
  8737. p->tm.tm_mday = parse_timestamp_number(p);
  8738. return true;
  8739. }
  8740. static void start_hour(upb_json_parser *p, const char *ptr) {
  8741. capture_begin(p, ptr);
  8742. }
  8743. static bool end_hour(upb_json_parser *p, const char *ptr) {
  8744. if (!capture_end(p, ptr)) {
  8745. return false;
  8746. }
  8747. p->tm.tm_hour = parse_timestamp_number(p);
  8748. return true;
  8749. }
  8750. static void start_minute(upb_json_parser *p, const char *ptr) {
  8751. capture_begin(p, ptr);
  8752. }
  8753. static bool end_minute(upb_json_parser *p, const char *ptr) {
  8754. if (!capture_end(p, ptr)) {
  8755. return false;
  8756. }
  8757. p->tm.tm_min = parse_timestamp_number(p);
  8758. return true;
  8759. }
  8760. static void start_second(upb_json_parser *p, const char *ptr) {
  8761. capture_begin(p, ptr);
  8762. }
  8763. static bool end_second(upb_json_parser *p, const char *ptr) {
  8764. if (!capture_end(p, ptr)) {
  8765. return false;
  8766. }
  8767. p->tm.tm_sec = parse_timestamp_number(p);
  8768. return true;
  8769. }
  8770. static void start_timestamp_base(upb_json_parser *p) {
  8771. memset(&p->tm, 0, sizeof(struct tm));
  8772. }
  8773. static void start_timestamp_fraction(upb_json_parser *p, const char *ptr) {
  8774. capture_begin(p, ptr);
  8775. }
  8776. static bool end_timestamp_fraction(upb_json_parser *p, const char *ptr) {
  8777. size_t len;
  8778. const char *buf;
  8779. char nanos_buf[12];
  8780. char *end;
  8781. double val = 0.0;
  8782. int32_t nanos;
  8783. const char *nanos_membername = "nanos";
  8784. memset(nanos_buf, 0, 12);
  8785. if (!capture_end(p, ptr)) {
  8786. return false;
  8787. }
  8788. buf = accumulate_getptr(p, &len);
  8789. if (len > 10) {
  8790. upb_status_seterrf(p->status,
  8791. "error parsing timestamp: at most 9-digit fraction.");
  8792. return false;
  8793. }
  8794. /* Parse nanos */
  8795. nanos_buf[0] = '0';
  8796. memcpy(nanos_buf + 1, buf, len);
  8797. val = strtod(nanos_buf, &end);
  8798. if (errno == ERANGE || end != nanos_buf + len + 1) {
  8799. upb_status_seterrf(p->status, "error parsing timestamp nanos: %s",
  8800. nanos_buf);
  8801. return false;
  8802. }
  8803. nanos = val * 1000000000;
  8804. /* Clean up previous environment */
  8805. multipart_end(p);
  8806. /* Set nanos */
  8807. start_member(p);
  8808. capture_begin(p, nanos_membername);
  8809. capture_end(p, nanos_membername + 5);
  8810. end_membername(p);
  8811. upb_sink_putint32(p->top->sink, parser_getsel(p), nanos);
  8812. end_member(p);
  8813. /* Continue previous environment */
  8814. multipart_startaccum(p);
  8815. return true;
  8816. }
  8817. static void start_timestamp_zone(upb_json_parser *p, const char *ptr) {
  8818. capture_begin(p, ptr);
  8819. }
  8820. static bool end_timestamp_zone(upb_json_parser *p, const char *ptr) {
  8821. size_t len;
  8822. const char *buf;
  8823. int hours;
  8824. int64_t seconds;
  8825. const char *seconds_membername = "seconds";
  8826. if (!capture_end(p, ptr)) {
  8827. return false;
  8828. }
  8829. buf = accumulate_getptr(p, &len);
  8830. if (buf[0] != 'Z') {
  8831. if (sscanf(buf + 1, "%2d:00", &hours) != 1) {
  8832. upb_status_seterrf(p->status, "error parsing timestamp offset");
  8833. return false;
  8834. }
  8835. if (buf[0] == '+') {
  8836. hours = -hours;
  8837. }
  8838. p->tm.tm_hour += hours;
  8839. }
  8840. /* Normalize tm */
  8841. seconds = mktime(&p->tm);
  8842. /* Check timestamp boundary */
  8843. if (seconds < -62135596800) {
  8844. upb_status_seterrf(p->status, "error parsing timestamp: "
  8845. "minimum acceptable value is "
  8846. "0001-01-01T00:00:00Z");
  8847. return false;
  8848. }
  8849. /* Clean up previous environment */
  8850. multipart_end(p);
  8851. /* Set seconds */
  8852. start_member(p);
  8853. capture_begin(p, seconds_membername);
  8854. capture_end(p, seconds_membername + 7);
  8855. end_membername(p);
  8856. upb_sink_putint64(p->top->sink, parser_getsel(p), seconds);
  8857. end_member(p);
  8858. /* Continue previous environment */
  8859. multipart_startaccum(p);
  8860. return true;
  8861. }
  8862. static void start_fieldmask_path_text(upb_json_parser *p, const char *ptr) {
  8863. capture_begin(p, ptr);
  8864. }
  8865. static bool end_fieldmask_path_text(upb_json_parser *p, const char *ptr) {
  8866. return capture_end(p, ptr);
  8867. }
  8868. static bool start_fieldmask_path(upb_json_parser *p) {
  8869. upb_jsonparser_frame *inner;
  8870. upb_selector_t sel;
  8871. if (!check_stack(p)) return false;
  8872. /* Start a new parser frame: parser frames correspond one-to-one with
  8873. * handler frames, and string events occur in a sub-frame. */
  8874. inner = start_jsonparser_frame(p);
  8875. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  8876. upb_sink_startstr(p->top->sink, sel, 0, &inner->sink);
  8877. inner->m = p->top->m;
  8878. inner->f = p->top->f;
  8879. p->top = inner;
  8880. multipart_startaccum(p);
  8881. return true;
  8882. }
  8883. static bool lower_camel_push(
  8884. upb_json_parser *p, upb_selector_t sel, const char *ptr, size_t len) {
  8885. const char *limit = ptr + len;
  8886. bool first = true;
  8887. for (;ptr < limit; ptr++) {
  8888. if (*ptr >= 'A' && *ptr <= 'Z' && !first) {
  8889. char lower = tolower(*ptr);
  8890. upb_sink_putstring(p->top->sink, sel, "_", 1, NULL);
  8891. upb_sink_putstring(p->top->sink, sel, &lower, 1, NULL);
  8892. } else {
  8893. upb_sink_putstring(p->top->sink, sel, ptr, 1, NULL);
  8894. }
  8895. first = false;
  8896. }
  8897. return true;
  8898. }
  8899. static bool end_fieldmask_path(upb_json_parser *p) {
  8900. upb_selector_t sel;
  8901. if (!lower_camel_push(
  8902. p, getsel_for_handlertype(p, UPB_HANDLER_STRING),
  8903. p->accumulated, p->accumulated_len)) {
  8904. return false;
  8905. }
  8906. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  8907. upb_sink_endstr(p->top->sink, sel);
  8908. p->top--;
  8909. multipart_end(p);
  8910. return true;
  8911. }
  8912. static void start_member(upb_json_parser *p) {
  8913. UPB_ASSERT(!p->top->f);
  8914. multipart_startaccum(p);
  8915. }
  8916. /* Helper: invoked during parse_mapentry() to emit the mapentry message's key
  8917. * field based on the current contents of the accumulate buffer. */
  8918. static bool parse_mapentry_key(upb_json_parser *p) {
  8919. size_t len;
  8920. const char *buf = accumulate_getptr(p, &len);
  8921. /* Emit the key field. We do a bit of ad-hoc parsing here because the
  8922. * parser state machine has already decided that this is a string field
  8923. * name, and we are reinterpreting it as some arbitrary key type. In
  8924. * particular, integer and bool keys are quoted, so we need to parse the
  8925. * quoted string contents here. */
  8926. p->top->f = upb_msgdef_itof(p->top->m, UPB_MAPENTRY_KEY);
  8927. if (p->top->f == NULL) {
  8928. upb_status_seterrmsg(p->status, "mapentry message has no key");
  8929. return false;
  8930. }
  8931. switch (upb_fielddef_type(p->top->f)) {
  8932. case UPB_TYPE_INT32:
  8933. case UPB_TYPE_INT64:
  8934. case UPB_TYPE_UINT32:
  8935. case UPB_TYPE_UINT64:
  8936. /* Invoke end_number. The accum buffer has the number's text already. */
  8937. if (!parse_number(p, true)) {
  8938. return false;
  8939. }
  8940. break;
  8941. case UPB_TYPE_BOOL:
  8942. if (len == 4 && !strncmp(buf, "true", 4)) {
  8943. if (!parser_putbool(p, true)) {
  8944. return false;
  8945. }
  8946. } else if (len == 5 && !strncmp(buf, "false", 5)) {
  8947. if (!parser_putbool(p, false)) {
  8948. return false;
  8949. }
  8950. } else {
  8951. upb_status_seterrmsg(p->status,
  8952. "Map bool key not 'true' or 'false'");
  8953. return false;
  8954. }
  8955. multipart_end(p);
  8956. break;
  8957. case UPB_TYPE_STRING:
  8958. case UPB_TYPE_BYTES: {
  8959. upb_sink subsink;
  8960. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  8961. upb_sink_startstr(p->top->sink, sel, len, &subsink);
  8962. sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
  8963. upb_sink_putstring(subsink, sel, buf, len, NULL);
  8964. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  8965. upb_sink_endstr(subsink, sel);
  8966. multipart_end(p);
  8967. break;
  8968. }
  8969. default:
  8970. upb_status_seterrmsg(p->status, "Invalid field type for map key");
  8971. return false;
  8972. }
  8973. return true;
  8974. }
  8975. /* Helper: emit one map entry (as a submessage in the map field sequence). This
  8976. * is invoked from end_membername(), at the end of the map entry's key string,
  8977. * with the map key in the accumulate buffer. It parses the key from that
  8978. * buffer, emits the handler calls to start the mapentry submessage (setting up
  8979. * its subframe in the process), and sets up state in the subframe so that the
  8980. * value parser (invoked next) will emit the mapentry's value field and then
  8981. * end the mapentry message. */
  8982. static bool handle_mapentry(upb_json_parser *p) {
  8983. const upb_fielddef *mapfield;
  8984. const upb_msgdef *mapentrymsg;
  8985. upb_jsonparser_frame *inner;
  8986. upb_selector_t sel;
  8987. /* Map entry: p->top->sink is the seq frame, so we need to start a frame
  8988. * for the mapentry itself, and then set |f| in that frame so that the map
  8989. * value field is parsed, and also set a flag to end the frame after the
  8990. * map-entry value is parsed. */
  8991. if (!check_stack(p)) return false;
  8992. mapfield = p->top->mapfield;
  8993. mapentrymsg = upb_fielddef_msgsubdef(mapfield);
  8994. inner = start_jsonparser_frame(p);
  8995. p->top->f = mapfield;
  8996. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
  8997. upb_sink_startsubmsg(p->top->sink, sel, &inner->sink);
  8998. inner->m = mapentrymsg;
  8999. inner->mapfield = mapfield;
  9000. /* Don't set this to true *yet* -- we reuse parsing handlers below to push
  9001. * the key field value to the sink, and these handlers will pop the frame
  9002. * if they see is_mapentry (when invoked by the parser state machine, they
  9003. * would have just seen the map-entry value, not key). */
  9004. inner->is_mapentry = false;
  9005. p->top = inner;
  9006. /* send STARTMSG in submsg frame. */
  9007. upb_sink_startmsg(p->top->sink);
  9008. parse_mapentry_key(p);
  9009. /* Set up the value field to receive the map-entry value. */
  9010. p->top->f = upb_msgdef_itof(p->top->m, UPB_MAPENTRY_VALUE);
  9011. p->top->is_mapentry = true; /* set up to pop frame after value is parsed. */
  9012. p->top->mapfield = mapfield;
  9013. if (p->top->f == NULL) {
  9014. upb_status_seterrmsg(p->status, "mapentry message has no value");
  9015. return false;
  9016. }
  9017. return true;
  9018. }
  9019. static bool end_membername(upb_json_parser *p) {
  9020. UPB_ASSERT(!p->top->f);
  9021. if (!p->top->m) {
  9022. p->top->is_unknown_field = true;
  9023. multipart_end(p);
  9024. return true;
  9025. }
  9026. if (p->top->is_any) {
  9027. return end_any_membername(p);
  9028. } else if (p->top->is_map) {
  9029. return handle_mapentry(p);
  9030. } else {
  9031. size_t len;
  9032. const char *buf = accumulate_getptr(p, &len);
  9033. upb_value v;
  9034. if (upb_strtable_lookup2(p->top->name_table, buf, len, &v)) {
  9035. p->top->f = upb_value_getconstptr(v);
  9036. multipart_end(p);
  9037. return true;
  9038. } else if (p->ignore_json_unknown) {
  9039. p->top->is_unknown_field = true;
  9040. multipart_end(p);
  9041. return true;
  9042. } else {
  9043. upb_status_seterrf(p->status, "No such field: %.*s\n", (int)len, buf);
  9044. return false;
  9045. }
  9046. }
  9047. }
  9048. static bool end_any_membername(upb_json_parser *p) {
  9049. size_t len;
  9050. const char *buf = accumulate_getptr(p, &len);
  9051. upb_value v;
  9052. if (len == 5 && strncmp(buf, "@type", len) == 0) {
  9053. upb_strtable_lookup2(p->top->name_table, "type_url", 8, &v);
  9054. p->top->f = upb_value_getconstptr(v);
  9055. multipart_end(p);
  9056. return true;
  9057. } else {
  9058. p->top->is_unknown_field = true;
  9059. multipart_end(p);
  9060. return true;
  9061. }
  9062. }
  9063. static void end_member(upb_json_parser *p) {
  9064. /* If we just parsed a map-entry value, end that frame too. */
  9065. if (p->top->is_mapentry) {
  9066. upb_selector_t sel;
  9067. bool ok;
  9068. const upb_fielddef *mapfield;
  9069. UPB_ASSERT(p->top > p->stack);
  9070. /* send ENDMSG on submsg. */
  9071. upb_sink_endmsg(p->top->sink, p->status);
  9072. mapfield = p->top->mapfield;
  9073. /* send ENDSUBMSG in repeated-field-of-mapentries frame. */
  9074. p->top--;
  9075. ok = upb_handlers_getselector(mapfield, UPB_HANDLER_ENDSUBMSG, &sel);
  9076. UPB_ASSERT(ok);
  9077. upb_sink_endsubmsg(p->top->sink, sel);
  9078. }
  9079. p->top->f = NULL;
  9080. p->top->is_unknown_field = false;
  9081. }
  9082. static void start_any_member(upb_json_parser *p, const char *ptr) {
  9083. start_member(p);
  9084. json_parser_any_frame_set_after_type_url_start_once(p->top->any_frame, ptr);
  9085. }
  9086. static void end_any_member(upb_json_parser *p, const char *ptr) {
  9087. json_parser_any_frame_set_before_type_url_end(p->top->any_frame, ptr);
  9088. end_member(p);
  9089. }
  9090. static bool start_subobject(upb_json_parser *p) {
  9091. if (p->top->is_unknown_field) {
  9092. upb_jsonparser_frame *inner;
  9093. if (!check_stack(p)) return false;
  9094. p->top = start_jsonparser_frame(p);
  9095. return true;
  9096. }
  9097. if (upb_fielddef_ismap(p->top->f)) {
  9098. upb_jsonparser_frame *inner;
  9099. upb_selector_t sel;
  9100. /* Beginning of a map. Start a new parser frame in a repeated-field
  9101. * context. */
  9102. if (!check_stack(p)) return false;
  9103. inner = start_jsonparser_frame(p);
  9104. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
  9105. upb_sink_startseq(p->top->sink, sel, &inner->sink);
  9106. inner->m = upb_fielddef_msgsubdef(p->top->f);
  9107. inner->mapfield = p->top->f;
  9108. inner->is_map = true;
  9109. p->top = inner;
  9110. return true;
  9111. } else if (upb_fielddef_issubmsg(p->top->f)) {
  9112. upb_jsonparser_frame *inner;
  9113. upb_selector_t sel;
  9114. /* Beginning of a subobject. Start a new parser frame in the submsg
  9115. * context. */
  9116. if (!check_stack(p)) return false;
  9117. inner = start_jsonparser_frame(p);
  9118. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
  9119. upb_sink_startsubmsg(p->top->sink, sel, &inner->sink);
  9120. inner->m = upb_fielddef_msgsubdef(p->top->f);
  9121. set_name_table(p, inner);
  9122. p->top = inner;
  9123. if (is_wellknown_msg(p, UPB_WELLKNOWN_ANY)) {
  9124. p->top->is_any = true;
  9125. p->top->any_frame = json_parser_any_frame_new(p);
  9126. } else {
  9127. p->top->is_any = false;
  9128. p->top->any_frame = NULL;
  9129. }
  9130. return true;
  9131. } else {
  9132. upb_status_seterrf(p->status,
  9133. "Object specified for non-message/group field: %s",
  9134. upb_fielddef_name(p->top->f));
  9135. return false;
  9136. }
  9137. }
  9138. static bool start_subobject_full(upb_json_parser *p) {
  9139. if (is_top_level(p)) {
  9140. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  9141. start_value_object(p, VALUE_STRUCTVALUE);
  9142. if (!start_subobject(p)) return false;
  9143. start_structvalue_object(p);
  9144. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_STRUCT)) {
  9145. start_structvalue_object(p);
  9146. } else {
  9147. return true;
  9148. }
  9149. } else if (is_wellknown_field(p, UPB_WELLKNOWN_STRUCT)) {
  9150. if (!start_subobject(p)) return false;
  9151. start_structvalue_object(p);
  9152. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  9153. if (!start_subobject(p)) return false;
  9154. start_value_object(p, VALUE_STRUCTVALUE);
  9155. if (!start_subobject(p)) return false;
  9156. start_structvalue_object(p);
  9157. }
  9158. return start_subobject(p);
  9159. }
  9160. static void end_subobject(upb_json_parser *p) {
  9161. if (is_top_level(p)) {
  9162. return;
  9163. }
  9164. if (p->top->is_map) {
  9165. upb_selector_t sel;
  9166. p->top--;
  9167. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
  9168. upb_sink_endseq(p->top->sink, sel);
  9169. } else {
  9170. upb_selector_t sel;
  9171. bool is_unknown = p->top->m == NULL;
  9172. p->top--;
  9173. if (!is_unknown) {
  9174. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSUBMSG);
  9175. upb_sink_endsubmsg(p->top->sink, sel);
  9176. }
  9177. }
  9178. }
  9179. static void end_subobject_full(upb_json_parser *p) {
  9180. end_subobject(p);
  9181. if (is_wellknown_msg(p, UPB_WELLKNOWN_STRUCT)) {
  9182. end_structvalue_object(p);
  9183. if (!is_top_level(p)) {
  9184. end_subobject(p);
  9185. }
  9186. }
  9187. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  9188. end_value_object(p);
  9189. if (!is_top_level(p)) {
  9190. end_subobject(p);
  9191. }
  9192. }
  9193. }
  9194. static bool start_array(upb_json_parser *p) {
  9195. upb_jsonparser_frame *inner;
  9196. upb_selector_t sel;
  9197. if (is_top_level(p)) {
  9198. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  9199. start_value_object(p, VALUE_LISTVALUE);
  9200. if (!start_subobject(p)) return false;
  9201. start_listvalue_object(p);
  9202. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_LISTVALUE)) {
  9203. start_listvalue_object(p);
  9204. } else {
  9205. return false;
  9206. }
  9207. } else if (is_wellknown_field(p, UPB_WELLKNOWN_LISTVALUE) &&
  9208. (!upb_fielddef_isseq(p->top->f) ||
  9209. p->top->is_repeated)) {
  9210. if (!start_subobject(p)) return false;
  9211. start_listvalue_object(p);
  9212. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE) &&
  9213. (!upb_fielddef_isseq(p->top->f) ||
  9214. p->top->is_repeated)) {
  9215. if (!start_subobject(p)) return false;
  9216. start_value_object(p, VALUE_LISTVALUE);
  9217. if (!start_subobject(p)) return false;
  9218. start_listvalue_object(p);
  9219. }
  9220. if (p->top->is_unknown_field) {
  9221. inner = start_jsonparser_frame(p);
  9222. inner->is_unknown_field = true;
  9223. p->top = inner;
  9224. return true;
  9225. }
  9226. if (!upb_fielddef_isseq(p->top->f)) {
  9227. upb_status_seterrf(p->status,
  9228. "Array specified for non-repeated field: %s",
  9229. upb_fielddef_name(p->top->f));
  9230. return false;
  9231. }
  9232. if (!check_stack(p)) return false;
  9233. inner = start_jsonparser_frame(p);
  9234. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
  9235. upb_sink_startseq(p->top->sink, sel, &inner->sink);
  9236. inner->m = p->top->m;
  9237. inner->f = p->top->f;
  9238. inner->is_repeated = true;
  9239. p->top = inner;
  9240. return true;
  9241. }
  9242. static void end_array(upb_json_parser *p) {
  9243. upb_selector_t sel;
  9244. UPB_ASSERT(p->top > p->stack);
  9245. p->top--;
  9246. if (p->top->is_unknown_field) {
  9247. return;
  9248. }
  9249. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
  9250. upb_sink_endseq(p->top->sink, sel);
  9251. if (is_wellknown_msg(p, UPB_WELLKNOWN_LISTVALUE)) {
  9252. end_listvalue_object(p);
  9253. if (!is_top_level(p)) {
  9254. end_subobject(p);
  9255. }
  9256. }
  9257. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  9258. end_value_object(p);
  9259. if (!is_top_level(p)) {
  9260. end_subobject(p);
  9261. }
  9262. }
  9263. }
  9264. static void start_object(upb_json_parser *p) {
  9265. if (!p->top->is_map && p->top->m != NULL) {
  9266. upb_sink_startmsg(p->top->sink);
  9267. }
  9268. }
  9269. static void end_object(upb_json_parser *p) {
  9270. if (!p->top->is_map && p->top->m != NULL) {
  9271. upb_sink_endmsg(p->top->sink, p->status);
  9272. }
  9273. }
  9274. static void start_any_object(upb_json_parser *p, const char *ptr) {
  9275. start_object(p);
  9276. p->top->any_frame->before_type_url_start = ptr;
  9277. p->top->any_frame->before_type_url_end = ptr;
  9278. }
  9279. static bool end_any_object(upb_json_parser *p, const char *ptr) {
  9280. const char *value_membername = "value";
  9281. bool is_well_known_packed = false;
  9282. const char *packed_end = ptr + 1;
  9283. upb_selector_t sel;
  9284. upb_jsonparser_frame *inner;
  9285. if (json_parser_any_frame_has_value(p->top->any_frame) &&
  9286. !json_parser_any_frame_has_type_url(p->top->any_frame)) {
  9287. upb_status_seterrmsg(p->status, "No valid type url");
  9288. return false;
  9289. }
  9290. /* Well known types data is represented as value field. */
  9291. if (upb_msgdef_wellknowntype(p->top->any_frame->parser->top->m) !=
  9292. UPB_WELLKNOWN_UNSPECIFIED) {
  9293. is_well_known_packed = true;
  9294. if (json_parser_any_frame_has_value_before_type_url(p->top->any_frame)) {
  9295. p->top->any_frame->before_type_url_start =
  9296. memchr(p->top->any_frame->before_type_url_start, ':',
  9297. p->top->any_frame->before_type_url_end -
  9298. p->top->any_frame->before_type_url_start);
  9299. if (p->top->any_frame->before_type_url_start == NULL) {
  9300. upb_status_seterrmsg(p->status, "invalid data for well known type.");
  9301. return false;
  9302. }
  9303. p->top->any_frame->before_type_url_start++;
  9304. }
  9305. if (json_parser_any_frame_has_value_after_type_url(p->top->any_frame)) {
  9306. p->top->any_frame->after_type_url_start =
  9307. memchr(p->top->any_frame->after_type_url_start, ':',
  9308. (ptr + 1) -
  9309. p->top->any_frame->after_type_url_start);
  9310. if (p->top->any_frame->after_type_url_start == NULL) {
  9311. upb_status_seterrmsg(p->status, "Invalid data for well known type.");
  9312. return false;
  9313. }
  9314. p->top->any_frame->after_type_url_start++;
  9315. packed_end = ptr;
  9316. }
  9317. }
  9318. if (json_parser_any_frame_has_value_before_type_url(p->top->any_frame)) {
  9319. if (!parse(p->top->any_frame->parser, NULL,
  9320. p->top->any_frame->before_type_url_start,
  9321. p->top->any_frame->before_type_url_end -
  9322. p->top->any_frame->before_type_url_start, NULL)) {
  9323. return false;
  9324. }
  9325. } else {
  9326. if (!is_well_known_packed) {
  9327. if (!parse(p->top->any_frame->parser, NULL, "{", 1, NULL)) {
  9328. return false;
  9329. }
  9330. }
  9331. }
  9332. if (json_parser_any_frame_has_value_before_type_url(p->top->any_frame) &&
  9333. json_parser_any_frame_has_value_after_type_url(p->top->any_frame)) {
  9334. if (!parse(p->top->any_frame->parser, NULL, ",", 1, NULL)) {
  9335. return false;
  9336. }
  9337. }
  9338. if (json_parser_any_frame_has_value_after_type_url(p->top->any_frame)) {
  9339. if (!parse(p->top->any_frame->parser, NULL,
  9340. p->top->any_frame->after_type_url_start,
  9341. packed_end - p->top->any_frame->after_type_url_start, NULL)) {
  9342. return false;
  9343. }
  9344. } else {
  9345. if (!is_well_known_packed) {
  9346. if (!parse(p->top->any_frame->parser, NULL, "}", 1, NULL)) {
  9347. return false;
  9348. }
  9349. }
  9350. }
  9351. if (!end(p->top->any_frame->parser, NULL)) {
  9352. return false;
  9353. }
  9354. p->top->is_any = false;
  9355. /* Set value */
  9356. start_member(p);
  9357. capture_begin(p, value_membername);
  9358. capture_end(p, value_membername + 5);
  9359. end_membername(p);
  9360. if (!check_stack(p)) return false;
  9361. inner = p->top + 1;
  9362. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  9363. upb_sink_startstr(p->top->sink, sel, 0, &inner->sink);
  9364. sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
  9365. upb_sink_putstring(inner->sink, sel, p->top->any_frame->stringsink.ptr,
  9366. p->top->any_frame->stringsink.len, NULL);
  9367. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  9368. upb_sink_endstr(inner->sink, sel);
  9369. end_member(p);
  9370. end_object(p);
  9371. /* Deallocate any parse frame. */
  9372. json_parser_any_frame_free(p->top->any_frame);
  9373. return true;
  9374. }
  9375. static bool is_string_wrapper(const upb_msgdef *m) {
  9376. upb_wellknowntype_t type = upb_msgdef_wellknowntype(m);
  9377. return type == UPB_WELLKNOWN_STRINGVALUE ||
  9378. type == UPB_WELLKNOWN_BYTESVALUE;
  9379. }
  9380. static bool is_fieldmask(const upb_msgdef *m) {
  9381. upb_wellknowntype_t type = upb_msgdef_wellknowntype(m);
  9382. return type == UPB_WELLKNOWN_FIELDMASK;
  9383. }
  9384. static void start_fieldmask_object(upb_json_parser *p) {
  9385. const char *membername = "paths";
  9386. start_object(p);
  9387. /* Set up context for parsing value */
  9388. start_member(p);
  9389. capture_begin(p, membername);
  9390. capture_end(p, membername + 5);
  9391. end_membername(p);
  9392. start_array(p);
  9393. }
  9394. static void end_fieldmask_object(upb_json_parser *p) {
  9395. end_array(p);
  9396. end_member(p);
  9397. end_object(p);
  9398. }
  9399. static void start_wrapper_object(upb_json_parser *p) {
  9400. const char *membername = "value";
  9401. start_object(p);
  9402. /* Set up context for parsing value */
  9403. start_member(p);
  9404. capture_begin(p, membername);
  9405. capture_end(p, membername + 5);
  9406. end_membername(p);
  9407. }
  9408. static void end_wrapper_object(upb_json_parser *p) {
  9409. end_member(p);
  9410. end_object(p);
  9411. }
  9412. static void start_value_object(upb_json_parser *p, int value_type) {
  9413. const char *nullmember = "null_value";
  9414. const char *numbermember = "number_value";
  9415. const char *stringmember = "string_value";
  9416. const char *boolmember = "bool_value";
  9417. const char *structmember = "struct_value";
  9418. const char *listmember = "list_value";
  9419. const char *membername = "";
  9420. switch (value_type) {
  9421. case VALUE_NULLVALUE:
  9422. membername = nullmember;
  9423. break;
  9424. case VALUE_NUMBERVALUE:
  9425. membername = numbermember;
  9426. break;
  9427. case VALUE_STRINGVALUE:
  9428. membername = stringmember;
  9429. break;
  9430. case VALUE_BOOLVALUE:
  9431. membername = boolmember;
  9432. break;
  9433. case VALUE_STRUCTVALUE:
  9434. membername = structmember;
  9435. break;
  9436. case VALUE_LISTVALUE:
  9437. membername = listmember;
  9438. break;
  9439. }
  9440. start_object(p);
  9441. /* Set up context for parsing value */
  9442. start_member(p);
  9443. capture_begin(p, membername);
  9444. capture_end(p, membername + strlen(membername));
  9445. end_membername(p);
  9446. }
  9447. static void end_value_object(upb_json_parser *p) {
  9448. end_member(p);
  9449. end_object(p);
  9450. }
  9451. static void start_listvalue_object(upb_json_parser *p) {
  9452. const char *membername = "values";
  9453. start_object(p);
  9454. /* Set up context for parsing value */
  9455. start_member(p);
  9456. capture_begin(p, membername);
  9457. capture_end(p, membername + strlen(membername));
  9458. end_membername(p);
  9459. }
  9460. static void end_listvalue_object(upb_json_parser *p) {
  9461. end_member(p);
  9462. end_object(p);
  9463. }
  9464. static void start_structvalue_object(upb_json_parser *p) {
  9465. const char *membername = "fields";
  9466. start_object(p);
  9467. /* Set up context for parsing value */
  9468. start_member(p);
  9469. capture_begin(p, membername);
  9470. capture_end(p, membername + strlen(membername));
  9471. end_membername(p);
  9472. }
  9473. static void end_structvalue_object(upb_json_parser *p) {
  9474. end_member(p);
  9475. end_object(p);
  9476. }
  9477. static bool is_top_level(upb_json_parser *p) {
  9478. return p->top == p->stack && p->top->f == NULL && !p->top->is_unknown_field;
  9479. }
  9480. static bool is_wellknown_msg(upb_json_parser *p, upb_wellknowntype_t type) {
  9481. return p->top->m != NULL && upb_msgdef_wellknowntype(p->top->m) == type;
  9482. }
  9483. static bool is_wellknown_field(upb_json_parser *p, upb_wellknowntype_t type) {
  9484. return p->top->f != NULL &&
  9485. upb_fielddef_issubmsg(p->top->f) &&
  9486. (upb_msgdef_wellknowntype(upb_fielddef_msgsubdef(p->top->f))
  9487. == type);
  9488. }
  9489. static bool does_number_wrapper_start(upb_json_parser *p) {
  9490. return p->top->f != NULL &&
  9491. upb_fielddef_issubmsg(p->top->f) &&
  9492. upb_msgdef_isnumberwrapper(upb_fielddef_msgsubdef(p->top->f));
  9493. }
  9494. static bool does_number_wrapper_end(upb_json_parser *p) {
  9495. return p->top->m != NULL && upb_msgdef_isnumberwrapper(p->top->m);
  9496. }
  9497. static bool is_number_wrapper_object(upb_json_parser *p) {
  9498. return p->top->m != NULL && upb_msgdef_isnumberwrapper(p->top->m);
  9499. }
  9500. static bool does_string_wrapper_start(upb_json_parser *p) {
  9501. return p->top->f != NULL &&
  9502. upb_fielddef_issubmsg(p->top->f) &&
  9503. is_string_wrapper(upb_fielddef_msgsubdef(p->top->f));
  9504. }
  9505. static bool does_string_wrapper_end(upb_json_parser *p) {
  9506. return p->top->m != NULL && is_string_wrapper(p->top->m);
  9507. }
  9508. static bool is_string_wrapper_object(upb_json_parser *p) {
  9509. return p->top->m != NULL && is_string_wrapper(p->top->m);
  9510. }
  9511. static bool does_fieldmask_start(upb_json_parser *p) {
  9512. return p->top->f != NULL &&
  9513. upb_fielddef_issubmsg(p->top->f) &&
  9514. is_fieldmask(upb_fielddef_msgsubdef(p->top->f));
  9515. }
  9516. static bool does_fieldmask_end(upb_json_parser *p) {
  9517. return p->top->m != NULL && is_fieldmask(p->top->m);
  9518. }
  9519. #define CHECK_RETURN_TOP(x) if (!(x)) goto error
  9520. /* The actual parser **********************************************************/
  9521. /* What follows is the Ragel parser itself. The language is specified in Ragel
  9522. * and the actions call our C functions above.
  9523. *
  9524. * Ragel has an extensive set of functionality, and we use only a small part of
  9525. * it. There are many action types but we only use a few:
  9526. *
  9527. * ">" -- transition into a machine
  9528. * "%" -- transition out of a machine
  9529. * "@" -- transition into a final state of a machine.
  9530. *
  9531. * "@" transitions are tricky because a machine can transition into a final
  9532. * state repeatedly. But in some cases we know this can't happen, for example
  9533. * a string which is delimited by a final '"' can only transition into its
  9534. * final state once, when the closing '"' is seen. */
  9535. #line 2749 "upb/json/parser.rl"
  9536. #line 2552 "upb/json/parser.c"
  9537. static const char _json_actions[] = {
  9538. 0, 1, 0, 1, 1, 1, 3, 1,
  9539. 4, 1, 6, 1, 7, 1, 8, 1,
  9540. 9, 1, 11, 1, 12, 1, 13, 1,
  9541. 14, 1, 15, 1, 16, 1, 17, 1,
  9542. 18, 1, 19, 1, 20, 1, 22, 1,
  9543. 23, 1, 24, 1, 35, 1, 37, 1,
  9544. 39, 1, 40, 1, 42, 1, 43, 1,
  9545. 44, 1, 46, 1, 48, 1, 49, 1,
  9546. 50, 1, 51, 1, 53, 1, 54, 2,
  9547. 4, 9, 2, 5, 6, 2, 7, 3,
  9548. 2, 7, 9, 2, 21, 26, 2, 25,
  9549. 10, 2, 27, 28, 2, 29, 30, 2,
  9550. 32, 34, 2, 33, 31, 2, 38, 36,
  9551. 2, 40, 42, 2, 45, 2, 2, 46,
  9552. 54, 2, 47, 36, 2, 49, 54, 2,
  9553. 50, 54, 2, 51, 54, 2, 52, 41,
  9554. 2, 53, 54, 3, 32, 34, 35, 4,
  9555. 21, 26, 27, 28
  9556. };
  9557. static const short _json_key_offsets[] = {
  9558. 0, 0, 12, 13, 18, 23, 28, 29,
  9559. 30, 31, 32, 33, 34, 35, 36, 37,
  9560. 38, 43, 44, 48, 53, 58, 63, 67,
  9561. 71, 74, 77, 79, 83, 87, 89, 91,
  9562. 96, 98, 100, 109, 115, 121, 127, 133,
  9563. 135, 139, 142, 144, 146, 149, 150, 154,
  9564. 156, 158, 160, 162, 163, 165, 167, 168,
  9565. 170, 172, 173, 175, 177, 178, 180, 182,
  9566. 183, 185, 187, 191, 193, 195, 196, 197,
  9567. 198, 199, 201, 206, 208, 210, 212, 221,
  9568. 222, 222, 222, 227, 232, 237, 238, 239,
  9569. 240, 241, 241, 242, 243, 244, 244, 245,
  9570. 246, 247, 247, 252, 253, 257, 262, 267,
  9571. 272, 276, 276, 279, 282, 285, 288, 291,
  9572. 294, 294, 294, 294, 294, 294
  9573. };
  9574. static const char _json_trans_keys[] = {
  9575. 32, 34, 45, 91, 102, 110, 116, 123,
  9576. 9, 13, 48, 57, 34, 32, 93, 125,
  9577. 9, 13, 32, 44, 93, 9, 13, 32,
  9578. 93, 125, 9, 13, 97, 108, 115, 101,
  9579. 117, 108, 108, 114, 117, 101, 32, 34,
  9580. 125, 9, 13, 34, 32, 58, 9, 13,
  9581. 32, 93, 125, 9, 13, 32, 44, 125,
  9582. 9, 13, 32, 44, 125, 9, 13, 32,
  9583. 34, 9, 13, 45, 48, 49, 57, 48,
  9584. 49, 57, 46, 69, 101, 48, 57, 69,
  9585. 101, 48, 57, 43, 45, 48, 57, 48,
  9586. 57, 48, 57, 46, 69, 101, 48, 57,
  9587. 34, 92, 34, 92, 34, 47, 92, 98,
  9588. 102, 110, 114, 116, 117, 48, 57, 65,
  9589. 70, 97, 102, 48, 57, 65, 70, 97,
  9590. 102, 48, 57, 65, 70, 97, 102, 48,
  9591. 57, 65, 70, 97, 102, 34, 92, 45,
  9592. 48, 49, 57, 48, 49, 57, 46, 115,
  9593. 48, 57, 115, 48, 57, 34, 46, 115,
  9594. 48, 57, 48, 57, 48, 57, 48, 57,
  9595. 48, 57, 45, 48, 57, 48, 57, 45,
  9596. 48, 57, 48, 57, 84, 48, 57, 48,
  9597. 57, 58, 48, 57, 48, 57, 58, 48,
  9598. 57, 48, 57, 43, 45, 46, 90, 48,
  9599. 57, 48, 57, 58, 48, 48, 34, 48,
  9600. 57, 43, 45, 90, 48, 57, 34, 44,
  9601. 34, 44, 34, 44, 34, 45, 91, 102,
  9602. 110, 116, 123, 48, 57, 34, 32, 93,
  9603. 125, 9, 13, 32, 44, 93, 9, 13,
  9604. 32, 93, 125, 9, 13, 97, 108, 115,
  9605. 101, 117, 108, 108, 114, 117, 101, 32,
  9606. 34, 125, 9, 13, 34, 32, 58, 9,
  9607. 13, 32, 93, 125, 9, 13, 32, 44,
  9608. 125, 9, 13, 32, 44, 125, 9, 13,
  9609. 32, 34, 9, 13, 32, 9, 13, 32,
  9610. 9, 13, 32, 9, 13, 32, 9, 13,
  9611. 32, 9, 13, 32, 9, 13, 0
  9612. };
  9613. static const char _json_single_lengths[] = {
  9614. 0, 8, 1, 3, 3, 3, 1, 1,
  9615. 1, 1, 1, 1, 1, 1, 1, 1,
  9616. 3, 1, 2, 3, 3, 3, 2, 2,
  9617. 1, 3, 0, 2, 2, 0, 0, 3,
  9618. 2, 2, 9, 0, 0, 0, 0, 2,
  9619. 2, 1, 2, 0, 1, 1, 2, 0,
  9620. 0, 0, 0, 1, 0, 0, 1, 0,
  9621. 0, 1, 0, 0, 1, 0, 0, 1,
  9622. 0, 0, 4, 0, 0, 1, 1, 1,
  9623. 1, 0, 3, 2, 2, 2, 7, 1,
  9624. 0, 0, 3, 3, 3, 1, 1, 1,
  9625. 1, 0, 1, 1, 1, 0, 1, 1,
  9626. 1, 0, 3, 1, 2, 3, 3, 3,
  9627. 2, 0, 1, 1, 1, 1, 1, 1,
  9628. 0, 0, 0, 0, 0, 0
  9629. };
  9630. static const char _json_range_lengths[] = {
  9631. 0, 2, 0, 1, 1, 1, 0, 0,
  9632. 0, 0, 0, 0, 0, 0, 0, 0,
  9633. 1, 0, 1, 1, 1, 1, 1, 1,
  9634. 1, 0, 1, 1, 1, 1, 1, 1,
  9635. 0, 0, 0, 3, 3, 3, 3, 0,
  9636. 1, 1, 0, 1, 1, 0, 1, 1,
  9637. 1, 1, 1, 0, 1, 1, 0, 1,
  9638. 1, 0, 1, 1, 0, 1, 1, 0,
  9639. 1, 1, 0, 1, 1, 0, 0, 0,
  9640. 0, 1, 1, 0, 0, 0, 1, 0,
  9641. 0, 0, 1, 1, 1, 0, 0, 0,
  9642. 0, 0, 0, 0, 0, 0, 0, 0,
  9643. 0, 0, 1, 0, 1, 1, 1, 1,
  9644. 1, 0, 1, 1, 1, 1, 1, 1,
  9645. 0, 0, 0, 0, 0, 0
  9646. };
  9647. static const short _json_index_offsets[] = {
  9648. 0, 0, 11, 13, 18, 23, 28, 30,
  9649. 32, 34, 36, 38, 40, 42, 44, 46,
  9650. 48, 53, 55, 59, 64, 69, 74, 78,
  9651. 82, 85, 89, 91, 95, 99, 101, 103,
  9652. 108, 111, 114, 124, 128, 132, 136, 140,
  9653. 143, 147, 150, 153, 155, 158, 160, 164,
  9654. 166, 168, 170, 172, 174, 176, 178, 180,
  9655. 182, 184, 186, 188, 190, 192, 194, 196,
  9656. 198, 200, 202, 207, 209, 211, 213, 215,
  9657. 217, 219, 221, 226, 229, 232, 235, 244,
  9658. 246, 247, 248, 253, 258, 263, 265, 267,
  9659. 269, 271, 272, 274, 276, 278, 279, 281,
  9660. 283, 285, 286, 291, 293, 297, 302, 307,
  9661. 312, 316, 317, 320, 323, 326, 329, 332,
  9662. 335, 336, 337, 338, 339, 340
  9663. };
  9664. static const unsigned char _json_indicies[] = {
  9665. 0, 2, 3, 4, 5, 6, 7, 8,
  9666. 0, 3, 1, 9, 1, 11, 12, 1,
  9667. 11, 10, 13, 14, 12, 13, 1, 14,
  9668. 1, 1, 14, 10, 15, 1, 16, 1,
  9669. 17, 1, 18, 1, 19, 1, 20, 1,
  9670. 21, 1, 22, 1, 23, 1, 24, 1,
  9671. 25, 26, 27, 25, 1, 28, 1, 29,
  9672. 30, 29, 1, 30, 1, 1, 30, 31,
  9673. 32, 33, 34, 32, 1, 35, 36, 27,
  9674. 35, 1, 36, 26, 36, 1, 37, 38,
  9675. 39, 1, 38, 39, 1, 41, 42, 42,
  9676. 40, 43, 1, 42, 42, 43, 40, 44,
  9677. 44, 45, 1, 45, 1, 45, 40, 41,
  9678. 42, 42, 39, 40, 47, 48, 46, 50,
  9679. 51, 49, 52, 52, 52, 52, 52, 52,
  9680. 52, 52, 53, 1, 54, 54, 54, 1,
  9681. 55, 55, 55, 1, 56, 56, 56, 1,
  9682. 57, 57, 57, 1, 59, 60, 58, 61,
  9683. 62, 63, 1, 64, 65, 1, 66, 67,
  9684. 1, 68, 1, 67, 68, 1, 69, 1,
  9685. 66, 67, 65, 1, 70, 1, 71, 1,
  9686. 72, 1, 73, 1, 74, 1, 75, 1,
  9687. 76, 1, 77, 1, 78, 1, 79, 1,
  9688. 80, 1, 81, 1, 82, 1, 83, 1,
  9689. 84, 1, 85, 1, 86, 1, 87, 1,
  9690. 88, 1, 89, 89, 90, 91, 1, 92,
  9691. 1, 93, 1, 94, 1, 95, 1, 96,
  9692. 1, 97, 1, 98, 1, 99, 99, 100,
  9693. 98, 1, 102, 1, 101, 104, 105, 103,
  9694. 1, 1, 101, 106, 107, 108, 109, 110,
  9695. 111, 112, 107, 1, 113, 1, 114, 115,
  9696. 117, 118, 1, 117, 116, 119, 120, 118,
  9697. 119, 1, 120, 1, 1, 120, 116, 121,
  9698. 1, 122, 1, 123, 1, 124, 1, 125,
  9699. 126, 1, 127, 1, 128, 1, 129, 130,
  9700. 1, 131, 1, 132, 1, 133, 134, 135,
  9701. 136, 134, 1, 137, 1, 138, 139, 138,
  9702. 1, 139, 1, 1, 139, 140, 141, 142,
  9703. 143, 141, 1, 144, 145, 136, 144, 1,
  9704. 145, 135, 145, 1, 146, 147, 147, 1,
  9705. 148, 148, 1, 149, 149, 1, 150, 150,
  9706. 1, 151, 151, 1, 152, 152, 1, 1,
  9707. 1, 1, 1, 1, 1, 0
  9708. };
  9709. static const char _json_trans_targs[] = {
  9710. 1, 0, 2, 107, 3, 6, 10, 13,
  9711. 16, 106, 4, 3, 106, 4, 5, 7,
  9712. 8, 9, 108, 11, 12, 109, 14, 15,
  9713. 110, 16, 17, 111, 18, 18, 19, 20,
  9714. 21, 22, 111, 21, 22, 24, 25, 31,
  9715. 112, 26, 28, 27, 29, 30, 33, 113,
  9716. 34, 33, 113, 34, 32, 35, 36, 37,
  9717. 38, 39, 33, 113, 34, 41, 42, 46,
  9718. 42, 46, 43, 45, 44, 114, 48, 49,
  9719. 50, 51, 52, 53, 54, 55, 56, 57,
  9720. 58, 59, 60, 61, 62, 63, 64, 65,
  9721. 66, 67, 73, 72, 68, 69, 70, 71,
  9722. 72, 115, 74, 67, 72, 76, 116, 76,
  9723. 116, 77, 79, 81, 82, 85, 90, 94,
  9724. 98, 80, 117, 117, 83, 82, 80, 83,
  9725. 84, 86, 87, 88, 89, 117, 91, 92,
  9726. 93, 117, 95, 96, 97, 117, 98, 99,
  9727. 105, 100, 100, 101, 102, 103, 104, 105,
  9728. 103, 104, 117, 106, 106, 106, 106, 106,
  9729. 106
  9730. };
  9731. static const unsigned char _json_trans_actions[] = {
  9732. 0, 0, 113, 107, 53, 0, 0, 0,
  9733. 125, 59, 45, 0, 55, 0, 0, 0,
  9734. 0, 0, 0, 0, 0, 0, 0, 0,
  9735. 0, 0, 101, 51, 47, 0, 0, 45,
  9736. 49, 49, 104, 0, 0, 0, 0, 0,
  9737. 3, 0, 0, 0, 0, 0, 5, 15,
  9738. 0, 0, 71, 7, 13, 0, 74, 9,
  9739. 9, 9, 77, 80, 11, 37, 37, 37,
  9740. 0, 0, 0, 39, 0, 41, 86, 0,
  9741. 0, 0, 17, 19, 0, 21, 23, 0,
  9742. 25, 27, 0, 29, 31, 0, 33, 35,
  9743. 0, 135, 83, 135, 0, 0, 0, 0,
  9744. 0, 92, 0, 89, 89, 98, 43, 0,
  9745. 131, 95, 113, 107, 53, 0, 0, 0,
  9746. 125, 59, 69, 110, 45, 0, 55, 0,
  9747. 0, 0, 0, 0, 0, 119, 0, 0,
  9748. 0, 122, 0, 0, 0, 116, 0, 101,
  9749. 51, 47, 0, 0, 45, 49, 49, 104,
  9750. 0, 0, 128, 0, 57, 63, 65, 61,
  9751. 67
  9752. };
  9753. static const unsigned char _json_eof_actions[] = {
  9754. 0, 0, 0, 0, 0, 0, 0, 0,
  9755. 0, 0, 0, 0, 0, 0, 0, 0,
  9756. 0, 0, 0, 0, 0, 0, 0, 0,
  9757. 0, 1, 0, 1, 0, 0, 1, 1,
  9758. 0, 0, 0, 0, 0, 0, 0, 0,
  9759. 0, 0, 0, 0, 0, 0, 0, 0,
  9760. 0, 0, 0, 0, 0, 0, 0, 0,
  9761. 0, 0, 0, 0, 0, 0, 0, 0,
  9762. 0, 0, 0, 0, 0, 0, 0, 0,
  9763. 0, 0, 0, 0, 0, 0, 0, 0,
  9764. 0, 0, 0, 0, 0, 0, 0, 0,
  9765. 0, 0, 0, 0, 0, 0, 0, 0,
  9766. 0, 0, 0, 0, 0, 0, 0, 0,
  9767. 0, 0, 0, 57, 63, 65, 61, 67,
  9768. 0, 0, 0, 0, 0, 0
  9769. };
  9770. static const int json_start = 1;
  9771. static const int json_en_number_machine = 23;
  9772. static const int json_en_string_machine = 32;
  9773. static const int json_en_duration_machine = 40;
  9774. static const int json_en_timestamp_machine = 47;
  9775. static const int json_en_fieldmask_machine = 75;
  9776. static const int json_en_value_machine = 78;
  9777. static const int json_en_main = 1;
  9778. #line 2752 "upb/json/parser.rl"
  9779. size_t parse(void *closure, const void *hd, const char *buf, size_t size,
  9780. const upb_bufhandle *handle) {
  9781. upb_json_parser *parser = closure;
  9782. /* Variables used by Ragel's generated code. */
  9783. int cs = parser->current_state;
  9784. int *stack = parser->parser_stack;
  9785. int top = parser->parser_top;
  9786. const char *p = buf;
  9787. const char *pe = buf + size;
  9788. const char *eof = &eof_ch;
  9789. parser->handle = handle;
  9790. UPB_UNUSED(hd);
  9791. UPB_UNUSED(handle);
  9792. capture_resume(parser, buf);
  9793. #line 2830 "upb/json/parser.c"
  9794. {
  9795. int _klen;
  9796. unsigned int _trans;
  9797. const char *_acts;
  9798. unsigned int _nacts;
  9799. const char *_keys;
  9800. if ( p == pe )
  9801. goto _test_eof;
  9802. if ( cs == 0 )
  9803. goto _out;
  9804. _resume:
  9805. _keys = _json_trans_keys + _json_key_offsets[cs];
  9806. _trans = _json_index_offsets[cs];
  9807. _klen = _json_single_lengths[cs];
  9808. if ( _klen > 0 ) {
  9809. const char *_lower = _keys;
  9810. const char *_mid;
  9811. const char *_upper = _keys + _klen - 1;
  9812. while (1) {
  9813. if ( _upper < _lower )
  9814. break;
  9815. _mid = _lower + ((_upper-_lower) >> 1);
  9816. if ( (*p) < *_mid )
  9817. _upper = _mid - 1;
  9818. else if ( (*p) > *_mid )
  9819. _lower = _mid + 1;
  9820. else {
  9821. _trans += (unsigned int)(_mid - _keys);
  9822. goto _match;
  9823. }
  9824. }
  9825. _keys += _klen;
  9826. _trans += _klen;
  9827. }
  9828. _klen = _json_range_lengths[cs];
  9829. if ( _klen > 0 ) {
  9830. const char *_lower = _keys;
  9831. const char *_mid;
  9832. const char *_upper = _keys + (_klen<<1) - 2;
  9833. while (1) {
  9834. if ( _upper < _lower )
  9835. break;
  9836. _mid = _lower + (((_upper-_lower) >> 1) & ~1);
  9837. if ( (*p) < _mid[0] )
  9838. _upper = _mid - 2;
  9839. else if ( (*p) > _mid[1] )
  9840. _lower = _mid + 2;
  9841. else {
  9842. _trans += (unsigned int)((_mid - _keys)>>1);
  9843. goto _match;
  9844. }
  9845. }
  9846. _trans += _klen;
  9847. }
  9848. _match:
  9849. _trans = _json_indicies[_trans];
  9850. cs = _json_trans_targs[_trans];
  9851. if ( _json_trans_actions[_trans] == 0 )
  9852. goto _again;
  9853. _acts = _json_actions + _json_trans_actions[_trans];
  9854. _nacts = (unsigned int) *_acts++;
  9855. while ( _nacts-- > 0 )
  9856. {
  9857. switch ( *_acts++ )
  9858. {
  9859. case 1:
  9860. #line 2557 "upb/json/parser.rl"
  9861. { p--; {cs = stack[--top]; goto _again;} }
  9862. break;
  9863. case 2:
  9864. #line 2559 "upb/json/parser.rl"
  9865. { p--; {stack[top++] = cs; cs = 23;goto _again;} }
  9866. break;
  9867. case 3:
  9868. #line 2563 "upb/json/parser.rl"
  9869. { start_text(parser, p); }
  9870. break;
  9871. case 4:
  9872. #line 2564 "upb/json/parser.rl"
  9873. { CHECK_RETURN_TOP(end_text(parser, p)); }
  9874. break;
  9875. case 5:
  9876. #line 2570 "upb/json/parser.rl"
  9877. { start_hex(parser); }
  9878. break;
  9879. case 6:
  9880. #line 2571 "upb/json/parser.rl"
  9881. { hexdigit(parser, p); }
  9882. break;
  9883. case 7:
  9884. #line 2572 "upb/json/parser.rl"
  9885. { CHECK_RETURN_TOP(end_hex(parser)); }
  9886. break;
  9887. case 8:
  9888. #line 2578 "upb/json/parser.rl"
  9889. { CHECK_RETURN_TOP(escape(parser, p)); }
  9890. break;
  9891. case 9:
  9892. #line 2584 "upb/json/parser.rl"
  9893. { p--; {cs = stack[--top]; goto _again;} }
  9894. break;
  9895. case 10:
  9896. #line 2589 "upb/json/parser.rl"
  9897. { start_year(parser, p); }
  9898. break;
  9899. case 11:
  9900. #line 2590 "upb/json/parser.rl"
  9901. { CHECK_RETURN_TOP(end_year(parser, p)); }
  9902. break;
  9903. case 12:
  9904. #line 2594 "upb/json/parser.rl"
  9905. { start_month(parser, p); }
  9906. break;
  9907. case 13:
  9908. #line 2595 "upb/json/parser.rl"
  9909. { CHECK_RETURN_TOP(end_month(parser, p)); }
  9910. break;
  9911. case 14:
  9912. #line 2599 "upb/json/parser.rl"
  9913. { start_day(parser, p); }
  9914. break;
  9915. case 15:
  9916. #line 2600 "upb/json/parser.rl"
  9917. { CHECK_RETURN_TOP(end_day(parser, p)); }
  9918. break;
  9919. case 16:
  9920. #line 2604 "upb/json/parser.rl"
  9921. { start_hour(parser, p); }
  9922. break;
  9923. case 17:
  9924. #line 2605 "upb/json/parser.rl"
  9925. { CHECK_RETURN_TOP(end_hour(parser, p)); }
  9926. break;
  9927. case 18:
  9928. #line 2609 "upb/json/parser.rl"
  9929. { start_minute(parser, p); }
  9930. break;
  9931. case 19:
  9932. #line 2610 "upb/json/parser.rl"
  9933. { CHECK_RETURN_TOP(end_minute(parser, p)); }
  9934. break;
  9935. case 20:
  9936. #line 2614 "upb/json/parser.rl"
  9937. { start_second(parser, p); }
  9938. break;
  9939. case 21:
  9940. #line 2615 "upb/json/parser.rl"
  9941. { CHECK_RETURN_TOP(end_second(parser, p)); }
  9942. break;
  9943. case 22:
  9944. #line 2620 "upb/json/parser.rl"
  9945. { start_duration_base(parser, p); }
  9946. break;
  9947. case 23:
  9948. #line 2621 "upb/json/parser.rl"
  9949. { CHECK_RETURN_TOP(end_duration_base(parser, p)); }
  9950. break;
  9951. case 24:
  9952. #line 2623 "upb/json/parser.rl"
  9953. { p--; {cs = stack[--top]; goto _again;} }
  9954. break;
  9955. case 25:
  9956. #line 2628 "upb/json/parser.rl"
  9957. { start_timestamp_base(parser); }
  9958. break;
  9959. case 26:
  9960. #line 2630 "upb/json/parser.rl"
  9961. { start_timestamp_fraction(parser, p); }
  9962. break;
  9963. case 27:
  9964. #line 2631 "upb/json/parser.rl"
  9965. { CHECK_RETURN_TOP(end_timestamp_fraction(parser, p)); }
  9966. break;
  9967. case 28:
  9968. #line 2633 "upb/json/parser.rl"
  9969. { start_timestamp_zone(parser, p); }
  9970. break;
  9971. case 29:
  9972. #line 2634 "upb/json/parser.rl"
  9973. { CHECK_RETURN_TOP(end_timestamp_zone(parser, p)); }
  9974. break;
  9975. case 30:
  9976. #line 2636 "upb/json/parser.rl"
  9977. { p--; {cs = stack[--top]; goto _again;} }
  9978. break;
  9979. case 31:
  9980. #line 2641 "upb/json/parser.rl"
  9981. { start_fieldmask_path_text(parser, p); }
  9982. break;
  9983. case 32:
  9984. #line 2642 "upb/json/parser.rl"
  9985. { end_fieldmask_path_text(parser, p); }
  9986. break;
  9987. case 33:
  9988. #line 2647 "upb/json/parser.rl"
  9989. { start_fieldmask_path(parser); }
  9990. break;
  9991. case 34:
  9992. #line 2648 "upb/json/parser.rl"
  9993. { end_fieldmask_path(parser); }
  9994. break;
  9995. case 35:
  9996. #line 2654 "upb/json/parser.rl"
  9997. { p--; {cs = stack[--top]; goto _again;} }
  9998. break;
  9999. case 36:
  10000. #line 2659 "upb/json/parser.rl"
  10001. {
  10002. if (is_wellknown_msg(parser, UPB_WELLKNOWN_TIMESTAMP)) {
  10003. {stack[top++] = cs; cs = 47;goto _again;}
  10004. } else if (is_wellknown_msg(parser, UPB_WELLKNOWN_DURATION)) {
  10005. {stack[top++] = cs; cs = 40;goto _again;}
  10006. } else if (is_wellknown_msg(parser, UPB_WELLKNOWN_FIELDMASK)) {
  10007. {stack[top++] = cs; cs = 75;goto _again;}
  10008. } else {
  10009. {stack[top++] = cs; cs = 32;goto _again;}
  10010. }
  10011. }
  10012. break;
  10013. case 37:
  10014. #line 2672 "upb/json/parser.rl"
  10015. { p--; {stack[top++] = cs; cs = 78;goto _again;} }
  10016. break;
  10017. case 38:
  10018. #line 2677 "upb/json/parser.rl"
  10019. {
  10020. if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
  10021. start_any_member(parser, p);
  10022. } else {
  10023. start_member(parser);
  10024. }
  10025. }
  10026. break;
  10027. case 39:
  10028. #line 2684 "upb/json/parser.rl"
  10029. { CHECK_RETURN_TOP(end_membername(parser)); }
  10030. break;
  10031. case 40:
  10032. #line 2687 "upb/json/parser.rl"
  10033. {
  10034. if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
  10035. end_any_member(parser, p);
  10036. } else {
  10037. end_member(parser);
  10038. }
  10039. }
  10040. break;
  10041. case 41:
  10042. #line 2698 "upb/json/parser.rl"
  10043. {
  10044. if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
  10045. start_any_object(parser, p);
  10046. } else {
  10047. start_object(parser);
  10048. }
  10049. }
  10050. break;
  10051. case 42:
  10052. #line 2707 "upb/json/parser.rl"
  10053. {
  10054. if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
  10055. CHECK_RETURN_TOP(end_any_object(parser, p));
  10056. } else {
  10057. end_object(parser);
  10058. }
  10059. }
  10060. break;
  10061. case 43:
  10062. #line 2719 "upb/json/parser.rl"
  10063. { CHECK_RETURN_TOP(start_array(parser)); }
  10064. break;
  10065. case 44:
  10066. #line 2723 "upb/json/parser.rl"
  10067. { end_array(parser); }
  10068. break;
  10069. case 45:
  10070. #line 2728 "upb/json/parser.rl"
  10071. { CHECK_RETURN_TOP(start_number(parser, p)); }
  10072. break;
  10073. case 46:
  10074. #line 2729 "upb/json/parser.rl"
  10075. { CHECK_RETURN_TOP(end_number(parser, p)); }
  10076. break;
  10077. case 47:
  10078. #line 2731 "upb/json/parser.rl"
  10079. { CHECK_RETURN_TOP(start_stringval(parser)); }
  10080. break;
  10081. case 48:
  10082. #line 2732 "upb/json/parser.rl"
  10083. { CHECK_RETURN_TOP(end_stringval(parser)); }
  10084. break;
  10085. case 49:
  10086. #line 2734 "upb/json/parser.rl"
  10087. { CHECK_RETURN_TOP(end_bool(parser, true)); }
  10088. break;
  10089. case 50:
  10090. #line 2736 "upb/json/parser.rl"
  10091. { CHECK_RETURN_TOP(end_bool(parser, false)); }
  10092. break;
  10093. case 51:
  10094. #line 2738 "upb/json/parser.rl"
  10095. { CHECK_RETURN_TOP(end_null(parser)); }
  10096. break;
  10097. case 52:
  10098. #line 2740 "upb/json/parser.rl"
  10099. { CHECK_RETURN_TOP(start_subobject_full(parser)); }
  10100. break;
  10101. case 53:
  10102. #line 2741 "upb/json/parser.rl"
  10103. { end_subobject_full(parser); }
  10104. break;
  10105. case 54:
  10106. #line 2746 "upb/json/parser.rl"
  10107. { p--; {cs = stack[--top]; goto _again;} }
  10108. break;
  10109. #line 3154 "upb/json/parser.c"
  10110. }
  10111. }
  10112. _again:
  10113. if ( cs == 0 )
  10114. goto _out;
  10115. if ( ++p != pe )
  10116. goto _resume;
  10117. _test_eof: {}
  10118. if ( p == eof )
  10119. {
  10120. const char *__acts = _json_actions + _json_eof_actions[cs];
  10121. unsigned int __nacts = (unsigned int) *__acts++;
  10122. while ( __nacts-- > 0 ) {
  10123. switch ( *__acts++ ) {
  10124. case 0:
  10125. #line 2555 "upb/json/parser.rl"
  10126. { p--; {cs = stack[--top]; if ( p == pe )
  10127. goto _test_eof;
  10128. goto _again;} }
  10129. break;
  10130. case 46:
  10131. #line 2729 "upb/json/parser.rl"
  10132. { CHECK_RETURN_TOP(end_number(parser, p)); }
  10133. break;
  10134. case 49:
  10135. #line 2734 "upb/json/parser.rl"
  10136. { CHECK_RETURN_TOP(end_bool(parser, true)); }
  10137. break;
  10138. case 50:
  10139. #line 2736 "upb/json/parser.rl"
  10140. { CHECK_RETURN_TOP(end_bool(parser, false)); }
  10141. break;
  10142. case 51:
  10143. #line 2738 "upb/json/parser.rl"
  10144. { CHECK_RETURN_TOP(end_null(parser)); }
  10145. break;
  10146. case 53:
  10147. #line 2741 "upb/json/parser.rl"
  10148. { end_subobject_full(parser); }
  10149. break;
  10150. #line 3196 "upb/json/parser.c"
  10151. }
  10152. }
  10153. }
  10154. _out: {}
  10155. }
  10156. #line 2774 "upb/json/parser.rl"
  10157. if (p != pe) {
  10158. upb_status_seterrf(parser->status, "Parse error at '%.*s'\n", pe - p, p);
  10159. } else {
  10160. capture_suspend(parser, &p);
  10161. }
  10162. error:
  10163. /* Save parsing state back to parser. */
  10164. parser->current_state = cs;
  10165. parser->parser_top = top;
  10166. return p - buf;
  10167. }
  10168. static bool end(void *closure, const void *hd) {
  10169. upb_json_parser *parser = closure;
  10170. /* Prevent compile warning on unused static constants. */
  10171. UPB_UNUSED(json_start);
  10172. UPB_UNUSED(json_en_duration_machine);
  10173. UPB_UNUSED(json_en_fieldmask_machine);
  10174. UPB_UNUSED(json_en_number_machine);
  10175. UPB_UNUSED(json_en_string_machine);
  10176. UPB_UNUSED(json_en_timestamp_machine);
  10177. UPB_UNUSED(json_en_value_machine);
  10178. UPB_UNUSED(json_en_main);
  10179. parse(parser, hd, &eof_ch, 0, NULL);
  10180. return parser->current_state >= 106;
  10181. }
  10182. static void json_parser_reset(upb_json_parser *p) {
  10183. int cs;
  10184. int top;
  10185. p->top = p->stack;
  10186. init_frame(p->top);
  10187. /* Emit Ragel initialization of the parser. */
  10188. #line 3247 "upb/json/parser.c"
  10189. {
  10190. cs = json_start;
  10191. top = 0;
  10192. }
  10193. #line 2816 "upb/json/parser.rl"
  10194. p->current_state = cs;
  10195. p->parser_top = top;
  10196. accumulate_clear(p);
  10197. p->multipart_state = MULTIPART_INACTIVE;
  10198. p->capture = NULL;
  10199. p->accumulated = NULL;
  10200. }
  10201. static upb_json_parsermethod *parsermethod_new(upb_json_codecache *c,
  10202. const upb_msgdef *md) {
  10203. upb_msg_field_iter i;
  10204. upb_alloc *alloc = upb_arena_alloc(c->arena);
  10205. upb_json_parsermethod *m = upb_malloc(alloc, sizeof(*m));
  10206. m->cache = c;
  10207. upb_byteshandler_init(&m->input_handler_);
  10208. upb_byteshandler_setstring(&m->input_handler_, parse, m);
  10209. upb_byteshandler_setendstr(&m->input_handler_, end, m);
  10210. upb_strtable_init2(&m->name_table, UPB_CTYPE_CONSTPTR, alloc);
  10211. /* Build name_table */
  10212. for(upb_msg_field_begin(&i, md);
  10213. !upb_msg_field_done(&i);
  10214. upb_msg_field_next(&i)) {
  10215. const upb_fielddef *f = upb_msg_iter_field(&i);
  10216. upb_value v = upb_value_constptr(f);
  10217. char *buf;
  10218. /* Add an entry for the JSON name. */
  10219. size_t len = upb_fielddef_getjsonname(f, NULL, 0);
  10220. buf = upb_malloc(alloc, len);
  10221. upb_fielddef_getjsonname(f, buf, len);
  10222. upb_strtable_insert3(&m->name_table, buf, strlen(buf), v, alloc);
  10223. if (strcmp(buf, upb_fielddef_name(f)) != 0) {
  10224. /* Since the JSON name is different from the regular field name, add an
  10225. * entry for the raw name (compliant proto3 JSON parsers must accept
  10226. * both). */
  10227. const char *name = upb_fielddef_name(f);
  10228. upb_strtable_insert3(&m->name_table, name, strlen(name), v, alloc);
  10229. }
  10230. }
  10231. return m;
  10232. }
  10233. /* Public API *****************************************************************/
  10234. upb_json_parser *upb_json_parser_create(upb_arena *arena,
  10235. const upb_json_parsermethod *method,
  10236. const upb_symtab* symtab,
  10237. upb_sink output,
  10238. upb_status *status,
  10239. bool ignore_json_unknown) {
  10240. #ifndef NDEBUG
  10241. const size_t size_before = upb_arena_bytesallocated(arena);
  10242. #endif
  10243. upb_json_parser *p = upb_arena_malloc(arena, sizeof(upb_json_parser));
  10244. if (!p) return false;
  10245. p->arena = arena;
  10246. p->method = method;
  10247. p->status = status;
  10248. p->limit = p->stack + UPB_JSON_MAX_DEPTH;
  10249. p->accumulate_buf = NULL;
  10250. p->accumulate_buf_size = 0;
  10251. upb_bytessink_reset(&p->input_, &method->input_handler_, p);
  10252. json_parser_reset(p);
  10253. p->top->sink = output;
  10254. p->top->m = upb_handlers_msgdef(output.handlers);
  10255. if (is_wellknown_msg(p, UPB_WELLKNOWN_ANY)) {
  10256. p->top->is_any = true;
  10257. p->top->any_frame = json_parser_any_frame_new(p);
  10258. } else {
  10259. p->top->is_any = false;
  10260. p->top->any_frame = NULL;
  10261. }
  10262. set_name_table(p, p->top);
  10263. p->symtab = symtab;
  10264. p->ignore_json_unknown = ignore_json_unknown;
  10265. /* If this fails, uncomment and increase the value in parser.h. */
  10266. /* fprintf(stderr, "%zd\n", upb_arena_bytesallocated(arena) - size_before); */
  10267. UPB_ASSERT_DEBUGVAR(upb_arena_bytesallocated(arena) - size_before <=
  10268. UPB_JSON_PARSER_SIZE);
  10269. return p;
  10270. }
  10271. upb_bytessink upb_json_parser_input(upb_json_parser *p) {
  10272. return p->input_;
  10273. }
  10274. const upb_byteshandler *upb_json_parsermethod_inputhandler(
  10275. const upb_json_parsermethod *m) {
  10276. return &m->input_handler_;
  10277. }
  10278. upb_json_codecache *upb_json_codecache_new() {
  10279. upb_alloc *alloc;
  10280. upb_json_codecache *c;
  10281. c = upb_gmalloc(sizeof(*c));
  10282. c->arena = upb_arena_new();
  10283. alloc = upb_arena_alloc(c->arena);
  10284. upb_inttable_init2(&c->methods, UPB_CTYPE_CONSTPTR, alloc);
  10285. return c;
  10286. }
  10287. void upb_json_codecache_free(upb_json_codecache *c) {
  10288. upb_arena_free(c->arena);
  10289. upb_gfree(c);
  10290. }
  10291. const upb_json_parsermethod *upb_json_codecache_get(upb_json_codecache *c,
  10292. const upb_msgdef *md) {
  10293. upb_json_parsermethod *m;
  10294. upb_value v;
  10295. upb_msg_field_iter i;
  10296. upb_alloc *alloc = upb_arena_alloc(c->arena);
  10297. if (upb_inttable_lookupptr(&c->methods, md, &v)) {
  10298. return upb_value_getconstptr(v);
  10299. }
  10300. m = parsermethod_new(c, md);
  10301. v = upb_value_constptr(m);
  10302. if (!m) return NULL;
  10303. if (!upb_inttable_insertptr2(&c->methods, md, v, alloc)) return NULL;
  10304. /* Populate parser methods for all submessages, so the name tables will
  10305. * be available during parsing. */
  10306. for(upb_msg_field_begin(&i, md);
  10307. !upb_msg_field_done(&i);
  10308. upb_msg_field_next(&i)) {
  10309. upb_fielddef *f = upb_msg_iter_field(&i);
  10310. if (upb_fielddef_issubmsg(f)) {
  10311. const upb_msgdef *subdef = upb_fielddef_msgsubdef(f);
  10312. const upb_json_parsermethod *sub_method =
  10313. upb_json_codecache_get(c, subdef);
  10314. if (!sub_method) return NULL;
  10315. }
  10316. }
  10317. return m;
  10318. }
  10319. /*
  10320. ** This currently uses snprintf() to format primitives, and could be optimized
  10321. ** further.
  10322. */
  10323. #include <ctype.h>
  10324. #include <stdint.h>
  10325. #include <string.h>
  10326. #include <time.h>
  10327. struct upb_json_printer {
  10328. upb_sink input_;
  10329. /* BytesSink closure. */
  10330. void *subc_;
  10331. upb_bytessink output_;
  10332. /* We track the depth so that we know when to emit startstr/endstr on the
  10333. * output. */
  10334. int depth_;
  10335. /* Have we emitted the first element? This state is necessary to emit commas
  10336. * without leaving a trailing comma in arrays/maps. We keep this state per
  10337. * frame depth.
  10338. *
  10339. * Why max_depth * 2? UPB_MAX_HANDLER_DEPTH counts depth as nested messages.
  10340. * We count frames (contexts in which we separate elements by commas) as both
  10341. * repeated fields and messages (maps), and the worst case is a
  10342. * message->repeated field->submessage->repeated field->... nesting. */
  10343. bool first_elem_[UPB_MAX_HANDLER_DEPTH * 2];
  10344. /* To print timestamp, printer needs to cache its seconds and nanos values
  10345. * and convert them when ending timestamp message. See comments of
  10346. * printer_sethandlers_timestamp for more detail. */
  10347. int64_t seconds;
  10348. int32_t nanos;
  10349. };
  10350. /* StringPiece; a pointer plus a length. */
  10351. typedef struct {
  10352. char *ptr;
  10353. size_t len;
  10354. } strpc;
  10355. void freestrpc(void *ptr) {
  10356. strpc *pc = ptr;
  10357. upb_gfree(pc->ptr);
  10358. upb_gfree(pc);
  10359. }
  10360. typedef struct {
  10361. bool preserve_fieldnames;
  10362. } upb_json_printercache;
  10363. /* Convert fielddef name to JSON name and return as a string piece. */
  10364. strpc *newstrpc(upb_handlers *h, const upb_fielddef *f,
  10365. bool preserve_fieldnames) {
  10366. /* TODO(haberman): handle malloc failure. */
  10367. strpc *ret = upb_gmalloc(sizeof(*ret));
  10368. if (preserve_fieldnames) {
  10369. ret->ptr = upb_gstrdup(upb_fielddef_name(f));
  10370. ret->len = strlen(ret->ptr);
  10371. } else {
  10372. size_t len;
  10373. ret->len = upb_fielddef_getjsonname(f, NULL, 0);
  10374. ret->ptr = upb_gmalloc(ret->len);
  10375. len = upb_fielddef_getjsonname(f, ret->ptr, ret->len);
  10376. UPB_ASSERT(len == ret->len);
  10377. ret->len--; /* NULL */
  10378. }
  10379. upb_handlers_addcleanup(h, ret, freestrpc);
  10380. return ret;
  10381. }
  10382. /* Convert a null-terminated const char* to a string piece. */
  10383. strpc *newstrpc_str(upb_handlers *h, const char * str) {
  10384. strpc * ret = upb_gmalloc(sizeof(*ret));
  10385. ret->ptr = upb_gstrdup(str);
  10386. ret->len = strlen(str);
  10387. upb_handlers_addcleanup(h, ret, freestrpc);
  10388. return ret;
  10389. }
  10390. /* ------------ JSON string printing: values, maps, arrays ------------------ */
  10391. static void print_data(
  10392. upb_json_printer *p, const char *buf, unsigned int len) {
  10393. /* TODO: Will need to change if we support pushback from the sink. */
  10394. size_t n = upb_bytessink_putbuf(p->output_, p->subc_, buf, len, NULL);
  10395. UPB_ASSERT(n == len);
  10396. }
  10397. static void print_comma(upb_json_printer *p) {
  10398. if (!p->first_elem_[p->depth_]) {
  10399. print_data(p, ",", 1);
  10400. }
  10401. p->first_elem_[p->depth_] = false;
  10402. }
  10403. /* Helpers that print properly formatted elements to the JSON output stream. */
  10404. /* Used for escaping control chars in strings. */
  10405. static const char kControlCharLimit = 0x20;
  10406. UPB_INLINE bool is_json_escaped(char c) {
  10407. /* See RFC 4627. */
  10408. unsigned char uc = (unsigned char)c;
  10409. return uc < kControlCharLimit || uc == '"' || uc == '\\';
  10410. }
  10411. UPB_INLINE const char* json_nice_escape(char c) {
  10412. switch (c) {
  10413. case '"': return "\\\"";
  10414. case '\\': return "\\\\";
  10415. case '\b': return "\\b";
  10416. case '\f': return "\\f";
  10417. case '\n': return "\\n";
  10418. case '\r': return "\\r";
  10419. case '\t': return "\\t";
  10420. default: return NULL;
  10421. }
  10422. }
  10423. /* Write a properly escaped string chunk. The surrounding quotes are *not*
  10424. * printed; this is so that the caller has the option of emitting the string
  10425. * content in chunks. */
  10426. static void putstring(upb_json_printer *p, const char *buf, unsigned int len) {
  10427. const char* unescaped_run = NULL;
  10428. unsigned int i;
  10429. for (i = 0; i < len; i++) {
  10430. char c = buf[i];
  10431. /* Handle escaping. */
  10432. if (is_json_escaped(c)) {
  10433. /* Use a "nice" escape, like \n, if one exists for this character. */
  10434. const char* escape = json_nice_escape(c);
  10435. /* If we don't have a specific 'nice' escape code, use a \uXXXX-style
  10436. * escape. */
  10437. char escape_buf[8];
  10438. if (!escape) {
  10439. unsigned char byte = (unsigned char)c;
  10440. _upb_snprintf(escape_buf, sizeof(escape_buf), "\\u%04x", (int)byte);
  10441. escape = escape_buf;
  10442. }
  10443. /* N.B. that we assume that the input encoding is equal to the output
  10444. * encoding (both UTF-8 for now), so for chars >= 0x20 and != \, ", we
  10445. * can simply pass the bytes through. */
  10446. /* If there's a current run of unescaped chars, print that run first. */
  10447. if (unescaped_run) {
  10448. print_data(p, unescaped_run, &buf[i] - unescaped_run);
  10449. unescaped_run = NULL;
  10450. }
  10451. /* Then print the escape code. */
  10452. print_data(p, escape, strlen(escape));
  10453. } else {
  10454. /* Add to the current unescaped run of characters. */
  10455. if (unescaped_run == NULL) {
  10456. unescaped_run = &buf[i];
  10457. }
  10458. }
  10459. }
  10460. /* If the string ended in a run of unescaped characters, print that last run. */
  10461. if (unescaped_run) {
  10462. print_data(p, unescaped_run, &buf[len] - unescaped_run);
  10463. }
  10464. }
  10465. #define CHKLENGTH(x) if (!(x)) return -1;
  10466. /* Helpers that format floating point values according to our custom formats.
  10467. * Right now we use %.8g and %.17g for float/double, respectively, to match
  10468. * proto2::util::JsonFormat's defaults. May want to change this later. */
  10469. const char neginf[] = "\"-Infinity\"";
  10470. const char inf[] = "\"Infinity\"";
  10471. static size_t fmt_double(double val, char* buf, size_t length) {
  10472. if (val == (1.0 / 0.0)) {
  10473. CHKLENGTH(length >= strlen(inf));
  10474. strcpy(buf, inf);
  10475. return strlen(inf);
  10476. } else if (val == (-1.0 / 0.0)) {
  10477. CHKLENGTH(length >= strlen(neginf));
  10478. strcpy(buf, neginf);
  10479. return strlen(neginf);
  10480. } else {
  10481. size_t n = _upb_snprintf(buf, length, "%.17g", val);
  10482. CHKLENGTH(n > 0 && n < length);
  10483. return n;
  10484. }
  10485. }
  10486. static size_t fmt_float(float val, char* buf, size_t length) {
  10487. size_t n = _upb_snprintf(buf, length, "%.8g", val);
  10488. CHKLENGTH(n > 0 && n < length);
  10489. return n;
  10490. }
  10491. static size_t fmt_bool(bool val, char* buf, size_t length) {
  10492. size_t n = _upb_snprintf(buf, length, "%s", (val ? "true" : "false"));
  10493. CHKLENGTH(n > 0 && n < length);
  10494. return n;
  10495. }
  10496. static size_t fmt_int64(long val, char* buf, size_t length) {
  10497. size_t n = _upb_snprintf(buf, length, "%ld", val);
  10498. CHKLENGTH(n > 0 && n < length);
  10499. return n;
  10500. }
  10501. static size_t fmt_uint64(unsigned long long val, char* buf, size_t length) {
  10502. size_t n = _upb_snprintf(buf, length, "%llu", val);
  10503. CHKLENGTH(n > 0 && n < length);
  10504. return n;
  10505. }
  10506. /* Print a map key given a field name. Called by scalar field handlers and by
  10507. * startseq for repeated fields. */
  10508. static bool putkey(void *closure, const void *handler_data) {
  10509. upb_json_printer *p = closure;
  10510. const strpc *key = handler_data;
  10511. print_comma(p);
  10512. print_data(p, "\"", 1);
  10513. putstring(p, key->ptr, key->len);
  10514. print_data(p, "\":", 2);
  10515. return true;
  10516. }
  10517. #define CHKFMT(val) if ((val) == (size_t)-1) return false;
  10518. #define CHK(val) if (!(val)) return false;
  10519. #define TYPE_HANDLERS(type, fmt_func) \
  10520. static bool put##type(void *closure, const void *handler_data, type val) { \
  10521. upb_json_printer *p = closure; \
  10522. char data[64]; \
  10523. size_t length = fmt_func(val, data, sizeof(data)); \
  10524. UPB_UNUSED(handler_data); \
  10525. CHKFMT(length); \
  10526. print_data(p, data, length); \
  10527. return true; \
  10528. } \
  10529. static bool scalar_##type(void *closure, const void *handler_data, \
  10530. type val) { \
  10531. CHK(putkey(closure, handler_data)); \
  10532. CHK(put##type(closure, handler_data, val)); \
  10533. return true; \
  10534. } \
  10535. static bool repeated_##type(void *closure, const void *handler_data, \
  10536. type val) { \
  10537. upb_json_printer *p = closure; \
  10538. print_comma(p); \
  10539. CHK(put##type(closure, handler_data, val)); \
  10540. return true; \
  10541. }
  10542. #define TYPE_HANDLERS_MAPKEY(type, fmt_func) \
  10543. static bool putmapkey_##type(void *closure, const void *handler_data, \
  10544. type val) { \
  10545. upb_json_printer *p = closure; \
  10546. print_data(p, "\"", 1); \
  10547. CHK(put##type(closure, handler_data, val)); \
  10548. print_data(p, "\":", 2); \
  10549. return true; \
  10550. }
  10551. TYPE_HANDLERS(double, fmt_double)
  10552. TYPE_HANDLERS(float, fmt_float)
  10553. TYPE_HANDLERS(bool, fmt_bool)
  10554. TYPE_HANDLERS(int32_t, fmt_int64)
  10555. TYPE_HANDLERS(uint32_t, fmt_int64)
  10556. TYPE_HANDLERS(int64_t, fmt_int64)
  10557. TYPE_HANDLERS(uint64_t, fmt_uint64)
  10558. /* double and float are not allowed to be map keys. */
  10559. TYPE_HANDLERS_MAPKEY(bool, fmt_bool)
  10560. TYPE_HANDLERS_MAPKEY(int32_t, fmt_int64)
  10561. TYPE_HANDLERS_MAPKEY(uint32_t, fmt_int64)
  10562. TYPE_HANDLERS_MAPKEY(int64_t, fmt_int64)
  10563. TYPE_HANDLERS_MAPKEY(uint64_t, fmt_uint64)
  10564. #undef TYPE_HANDLERS
  10565. #undef TYPE_HANDLERS_MAPKEY
  10566. typedef struct {
  10567. void *keyname;
  10568. const upb_enumdef *enumdef;
  10569. } EnumHandlerData;
  10570. static bool scalar_enum(void *closure, const void *handler_data,
  10571. int32_t val) {
  10572. const EnumHandlerData *hd = handler_data;
  10573. upb_json_printer *p = closure;
  10574. const char *symbolic_name;
  10575. CHK(putkey(closure, hd->keyname));
  10576. symbolic_name = upb_enumdef_iton(hd->enumdef, val);
  10577. if (symbolic_name) {
  10578. print_data(p, "\"", 1);
  10579. putstring(p, symbolic_name, strlen(symbolic_name));
  10580. print_data(p, "\"", 1);
  10581. } else {
  10582. putint32_t(closure, NULL, val);
  10583. }
  10584. return true;
  10585. }
  10586. static void print_enum_symbolic_name(upb_json_printer *p,
  10587. const upb_enumdef *def,
  10588. int32_t val) {
  10589. const char *symbolic_name = upb_enumdef_iton(def, val);
  10590. if (symbolic_name) {
  10591. print_data(p, "\"", 1);
  10592. putstring(p, symbolic_name, strlen(symbolic_name));
  10593. print_data(p, "\"", 1);
  10594. } else {
  10595. putint32_t(p, NULL, val);
  10596. }
  10597. }
  10598. static bool repeated_enum(void *closure, const void *handler_data,
  10599. int32_t val) {
  10600. const EnumHandlerData *hd = handler_data;
  10601. upb_json_printer *p = closure;
  10602. print_comma(p);
  10603. print_enum_symbolic_name(p, hd->enumdef, val);
  10604. return true;
  10605. }
  10606. static bool mapvalue_enum(void *closure, const void *handler_data,
  10607. int32_t val) {
  10608. const EnumHandlerData *hd = handler_data;
  10609. upb_json_printer *p = closure;
  10610. print_enum_symbolic_name(p, hd->enumdef, val);
  10611. return true;
  10612. }
  10613. static void *scalar_startsubmsg(void *closure, const void *handler_data) {
  10614. return putkey(closure, handler_data) ? closure : UPB_BREAK;
  10615. }
  10616. static void *repeated_startsubmsg(void *closure, const void *handler_data) {
  10617. upb_json_printer *p = closure;
  10618. UPB_UNUSED(handler_data);
  10619. print_comma(p);
  10620. return closure;
  10621. }
  10622. static void start_frame(upb_json_printer *p) {
  10623. p->depth_++;
  10624. p->first_elem_[p->depth_] = true;
  10625. print_data(p, "{", 1);
  10626. }
  10627. static void end_frame(upb_json_printer *p) {
  10628. print_data(p, "}", 1);
  10629. p->depth_--;
  10630. }
  10631. static bool printer_startmsg(void *closure, const void *handler_data) {
  10632. upb_json_printer *p = closure;
  10633. UPB_UNUSED(handler_data);
  10634. if (p->depth_ == 0) {
  10635. upb_bytessink_start(p->output_, 0, &p->subc_);
  10636. }
  10637. start_frame(p);
  10638. return true;
  10639. }
  10640. static bool printer_endmsg(void *closure, const void *handler_data, upb_status *s) {
  10641. upb_json_printer *p = closure;
  10642. UPB_UNUSED(handler_data);
  10643. UPB_UNUSED(s);
  10644. end_frame(p);
  10645. if (p->depth_ == 0) {
  10646. upb_bytessink_end(p->output_);
  10647. }
  10648. return true;
  10649. }
  10650. static void *startseq(void *closure, const void *handler_data) {
  10651. upb_json_printer *p = closure;
  10652. CHK(putkey(closure, handler_data));
  10653. p->depth_++;
  10654. p->first_elem_[p->depth_] = true;
  10655. print_data(p, "[", 1);
  10656. return closure;
  10657. }
  10658. static bool endseq(void *closure, const void *handler_data) {
  10659. upb_json_printer *p = closure;
  10660. UPB_UNUSED(handler_data);
  10661. print_data(p, "]", 1);
  10662. p->depth_--;
  10663. return true;
  10664. }
  10665. static void *startmap(void *closure, const void *handler_data) {
  10666. upb_json_printer *p = closure;
  10667. CHK(putkey(closure, handler_data));
  10668. p->depth_++;
  10669. p->first_elem_[p->depth_] = true;
  10670. print_data(p, "{", 1);
  10671. return closure;
  10672. }
  10673. static bool endmap(void *closure, const void *handler_data) {
  10674. upb_json_printer *p = closure;
  10675. UPB_UNUSED(handler_data);
  10676. print_data(p, "}", 1);
  10677. p->depth_--;
  10678. return true;
  10679. }
  10680. static size_t putstr(void *closure, const void *handler_data, const char *str,
  10681. size_t len, const upb_bufhandle *handle) {
  10682. upb_json_printer *p = closure;
  10683. UPB_UNUSED(handler_data);
  10684. UPB_UNUSED(handle);
  10685. putstring(p, str, len);
  10686. return len;
  10687. }
  10688. /* This has to Base64 encode the bytes, because JSON has no "bytes" type. */
  10689. static size_t putbytes(void *closure, const void *handler_data, const char *str,
  10690. size_t len, const upb_bufhandle *handle) {
  10691. upb_json_printer *p = closure;
  10692. /* This is the regular base64, not the "web-safe" version. */
  10693. static const char base64[] =
  10694. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  10695. /* Base64-encode. */
  10696. char data[16000];
  10697. const char *limit = data + sizeof(data);
  10698. const unsigned char *from = (const unsigned char*)str;
  10699. char *to = data;
  10700. size_t remaining = len;
  10701. size_t bytes;
  10702. UPB_UNUSED(handler_data);
  10703. UPB_UNUSED(handle);
  10704. print_data(p, "\"", 1);
  10705. while (remaining > 2) {
  10706. if (limit - to < 4) {
  10707. bytes = to - data;
  10708. putstring(p, data, bytes);
  10709. to = data;
  10710. }
  10711. to[0] = base64[from[0] >> 2];
  10712. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  10713. to[2] = base64[((from[1] & 0xf) << 2) | (from[2] >> 6)];
  10714. to[3] = base64[from[2] & 0x3f];
  10715. remaining -= 3;
  10716. to += 4;
  10717. from += 3;
  10718. }
  10719. switch (remaining) {
  10720. case 2:
  10721. to[0] = base64[from[0] >> 2];
  10722. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  10723. to[2] = base64[(from[1] & 0xf) << 2];
  10724. to[3] = '=';
  10725. to += 4;
  10726. from += 2;
  10727. break;
  10728. case 1:
  10729. to[0] = base64[from[0] >> 2];
  10730. to[1] = base64[((from[0] & 0x3) << 4)];
  10731. to[2] = '=';
  10732. to[3] = '=';
  10733. to += 4;
  10734. from += 1;
  10735. break;
  10736. }
  10737. bytes = to - data;
  10738. putstring(p, data, bytes);
  10739. print_data(p, "\"", 1);
  10740. return len;
  10741. }
  10742. static void *scalar_startstr(void *closure, const void *handler_data,
  10743. size_t size_hint) {
  10744. upb_json_printer *p = closure;
  10745. UPB_UNUSED(handler_data);
  10746. UPB_UNUSED(size_hint);
  10747. CHK(putkey(closure, handler_data));
  10748. print_data(p, "\"", 1);
  10749. return p;
  10750. }
  10751. static size_t scalar_str(void *closure, const void *handler_data,
  10752. const char *str, size_t len,
  10753. const upb_bufhandle *handle) {
  10754. CHK(putstr(closure, handler_data, str, len, handle));
  10755. return len;
  10756. }
  10757. static bool scalar_endstr(void *closure, const void *handler_data) {
  10758. upb_json_printer *p = closure;
  10759. UPB_UNUSED(handler_data);
  10760. print_data(p, "\"", 1);
  10761. return true;
  10762. }
  10763. static void *repeated_startstr(void *closure, const void *handler_data,
  10764. size_t size_hint) {
  10765. upb_json_printer *p = closure;
  10766. UPB_UNUSED(handler_data);
  10767. UPB_UNUSED(size_hint);
  10768. print_comma(p);
  10769. print_data(p, "\"", 1);
  10770. return p;
  10771. }
  10772. static size_t repeated_str(void *closure, const void *handler_data,
  10773. const char *str, size_t len,
  10774. const upb_bufhandle *handle) {
  10775. CHK(putstr(closure, handler_data, str, len, handle));
  10776. return len;
  10777. }
  10778. static bool repeated_endstr(void *closure, const void *handler_data) {
  10779. upb_json_printer *p = closure;
  10780. UPB_UNUSED(handler_data);
  10781. print_data(p, "\"", 1);
  10782. return true;
  10783. }
  10784. static void *mapkeyval_startstr(void *closure, const void *handler_data,
  10785. size_t size_hint) {
  10786. upb_json_printer *p = closure;
  10787. UPB_UNUSED(handler_data);
  10788. UPB_UNUSED(size_hint);
  10789. print_data(p, "\"", 1);
  10790. return p;
  10791. }
  10792. static size_t mapkey_str(void *closure, const void *handler_data,
  10793. const char *str, size_t len,
  10794. const upb_bufhandle *handle) {
  10795. CHK(putstr(closure, handler_data, str, len, handle));
  10796. return len;
  10797. }
  10798. static bool mapkey_endstr(void *closure, const void *handler_data) {
  10799. upb_json_printer *p = closure;
  10800. UPB_UNUSED(handler_data);
  10801. print_data(p, "\":", 2);
  10802. return true;
  10803. }
  10804. static bool mapvalue_endstr(void *closure, const void *handler_data) {
  10805. upb_json_printer *p = closure;
  10806. UPB_UNUSED(handler_data);
  10807. print_data(p, "\"", 1);
  10808. return true;
  10809. }
  10810. static size_t scalar_bytes(void *closure, const void *handler_data,
  10811. const char *str, size_t len,
  10812. const upb_bufhandle *handle) {
  10813. CHK(putkey(closure, handler_data));
  10814. CHK(putbytes(closure, handler_data, str, len, handle));
  10815. return len;
  10816. }
  10817. static size_t repeated_bytes(void *closure, const void *handler_data,
  10818. const char *str, size_t len,
  10819. const upb_bufhandle *handle) {
  10820. upb_json_printer *p = closure;
  10821. print_comma(p);
  10822. CHK(putbytes(closure, handler_data, str, len, handle));
  10823. return len;
  10824. }
  10825. static size_t mapkey_bytes(void *closure, const void *handler_data,
  10826. const char *str, size_t len,
  10827. const upb_bufhandle *handle) {
  10828. upb_json_printer *p = closure;
  10829. CHK(putbytes(closure, handler_data, str, len, handle));
  10830. print_data(p, ":", 1);
  10831. return len;
  10832. }
  10833. static void set_enum_hd(upb_handlers *h,
  10834. const upb_fielddef *f,
  10835. bool preserve_fieldnames,
  10836. upb_handlerattr *attr) {
  10837. EnumHandlerData *hd = upb_gmalloc(sizeof(EnumHandlerData));
  10838. hd->enumdef = upb_fielddef_enumsubdef(f);
  10839. hd->keyname = newstrpc(h, f, preserve_fieldnames);
  10840. upb_handlers_addcleanup(h, hd, upb_gfree);
  10841. attr->handler_data = hd;
  10842. }
  10843. /* Set up handlers for a mapentry submessage (i.e., an individual key/value pair
  10844. * in a map).
  10845. *
  10846. * TODO: Handle missing key, missing value, out-of-order key/value, or repeated
  10847. * key or value cases properly. The right way to do this is to allocate a
  10848. * temporary structure at the start of a mapentry submessage, store key and
  10849. * value data in it as key and value handlers are called, and then print the
  10850. * key/value pair once at the end of the submessage. If we don't do this, we
  10851. * should at least detect the case and throw an error. However, so far all of
  10852. * our sources that emit mapentry messages do so canonically (with one key
  10853. * field, and then one value field), so this is not a pressing concern at the
  10854. * moment. */
  10855. void printer_sethandlers_mapentry(const void *closure, bool preserve_fieldnames,
  10856. upb_handlers *h) {
  10857. const upb_msgdef *md = upb_handlers_msgdef(h);
  10858. /* A mapentry message is printed simply as '"key": value'. Rather than
  10859. * special-case key and value for every type below, we just handle both
  10860. * fields explicitly here. */
  10861. const upb_fielddef* key_field = upb_msgdef_itof(md, UPB_MAPENTRY_KEY);
  10862. const upb_fielddef* value_field = upb_msgdef_itof(md, UPB_MAPENTRY_VALUE);
  10863. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  10864. UPB_UNUSED(closure);
  10865. switch (upb_fielddef_type(key_field)) {
  10866. case UPB_TYPE_INT32:
  10867. upb_handlers_setint32(h, key_field, putmapkey_int32_t, &empty_attr);
  10868. break;
  10869. case UPB_TYPE_INT64:
  10870. upb_handlers_setint64(h, key_field, putmapkey_int64_t, &empty_attr);
  10871. break;
  10872. case UPB_TYPE_UINT32:
  10873. upb_handlers_setuint32(h, key_field, putmapkey_uint32_t, &empty_attr);
  10874. break;
  10875. case UPB_TYPE_UINT64:
  10876. upb_handlers_setuint64(h, key_field, putmapkey_uint64_t, &empty_attr);
  10877. break;
  10878. case UPB_TYPE_BOOL:
  10879. upb_handlers_setbool(h, key_field, putmapkey_bool, &empty_attr);
  10880. break;
  10881. case UPB_TYPE_STRING:
  10882. upb_handlers_setstartstr(h, key_field, mapkeyval_startstr, &empty_attr);
  10883. upb_handlers_setstring(h, key_field, mapkey_str, &empty_attr);
  10884. upb_handlers_setendstr(h, key_field, mapkey_endstr, &empty_attr);
  10885. break;
  10886. case UPB_TYPE_BYTES:
  10887. upb_handlers_setstring(h, key_field, mapkey_bytes, &empty_attr);
  10888. break;
  10889. default:
  10890. UPB_ASSERT(false);
  10891. break;
  10892. }
  10893. switch (upb_fielddef_type(value_field)) {
  10894. case UPB_TYPE_INT32:
  10895. upb_handlers_setint32(h, value_field, putint32_t, &empty_attr);
  10896. break;
  10897. case UPB_TYPE_INT64:
  10898. upb_handlers_setint64(h, value_field, putint64_t, &empty_attr);
  10899. break;
  10900. case UPB_TYPE_UINT32:
  10901. upb_handlers_setuint32(h, value_field, putuint32_t, &empty_attr);
  10902. break;
  10903. case UPB_TYPE_UINT64:
  10904. upb_handlers_setuint64(h, value_field, putuint64_t, &empty_attr);
  10905. break;
  10906. case UPB_TYPE_BOOL:
  10907. upb_handlers_setbool(h, value_field, putbool, &empty_attr);
  10908. break;
  10909. case UPB_TYPE_FLOAT:
  10910. upb_handlers_setfloat(h, value_field, putfloat, &empty_attr);
  10911. break;
  10912. case UPB_TYPE_DOUBLE:
  10913. upb_handlers_setdouble(h, value_field, putdouble, &empty_attr);
  10914. break;
  10915. case UPB_TYPE_STRING:
  10916. upb_handlers_setstartstr(h, value_field, mapkeyval_startstr, &empty_attr);
  10917. upb_handlers_setstring(h, value_field, putstr, &empty_attr);
  10918. upb_handlers_setendstr(h, value_field, mapvalue_endstr, &empty_attr);
  10919. break;
  10920. case UPB_TYPE_BYTES:
  10921. upb_handlers_setstring(h, value_field, putbytes, &empty_attr);
  10922. break;
  10923. case UPB_TYPE_ENUM: {
  10924. upb_handlerattr enum_attr = UPB_HANDLERATTR_INIT;
  10925. set_enum_hd(h, value_field, preserve_fieldnames, &enum_attr);
  10926. upb_handlers_setint32(h, value_field, mapvalue_enum, &enum_attr);
  10927. break;
  10928. }
  10929. case UPB_TYPE_MESSAGE:
  10930. /* No handler necessary -- the submsg handlers will print the message
  10931. * as appropriate. */
  10932. break;
  10933. }
  10934. }
  10935. static bool putseconds(void *closure, const void *handler_data,
  10936. int64_t seconds) {
  10937. upb_json_printer *p = closure;
  10938. p->seconds = seconds;
  10939. UPB_UNUSED(handler_data);
  10940. return true;
  10941. }
  10942. static bool putnanos(void *closure, const void *handler_data,
  10943. int32_t nanos) {
  10944. upb_json_printer *p = closure;
  10945. p->nanos = nanos;
  10946. UPB_UNUSED(handler_data);
  10947. return true;
  10948. }
  10949. static void *scalar_startstr_nokey(void *closure, const void *handler_data,
  10950. size_t size_hint) {
  10951. upb_json_printer *p = closure;
  10952. UPB_UNUSED(handler_data);
  10953. UPB_UNUSED(size_hint);
  10954. print_data(p, "\"", 1);
  10955. return p;
  10956. }
  10957. static size_t putstr_nokey(void *closure, const void *handler_data,
  10958. const char *str, size_t len,
  10959. const upb_bufhandle *handle) {
  10960. upb_json_printer *p = closure;
  10961. UPB_UNUSED(handler_data);
  10962. UPB_UNUSED(handle);
  10963. print_data(p, "\"", 1);
  10964. putstring(p, str, len);
  10965. print_data(p, "\"", 1);
  10966. return len + 2;
  10967. }
  10968. static void *startseq_nokey(void *closure, const void *handler_data) {
  10969. upb_json_printer *p = closure;
  10970. UPB_UNUSED(handler_data);
  10971. p->depth_++;
  10972. p->first_elem_[p->depth_] = true;
  10973. print_data(p, "[", 1);
  10974. return closure;
  10975. }
  10976. static void *startseq_fieldmask(void *closure, const void *handler_data) {
  10977. upb_json_printer *p = closure;
  10978. UPB_UNUSED(handler_data);
  10979. p->depth_++;
  10980. p->first_elem_[p->depth_] = true;
  10981. return closure;
  10982. }
  10983. static bool endseq_fieldmask(void *closure, const void *handler_data) {
  10984. upb_json_printer *p = closure;
  10985. UPB_UNUSED(handler_data);
  10986. p->depth_--;
  10987. return true;
  10988. }
  10989. static void *repeated_startstr_fieldmask(
  10990. void *closure, const void *handler_data,
  10991. size_t size_hint) {
  10992. upb_json_printer *p = closure;
  10993. UPB_UNUSED(handler_data);
  10994. UPB_UNUSED(size_hint);
  10995. print_comma(p);
  10996. return p;
  10997. }
  10998. static size_t repeated_str_fieldmask(
  10999. void *closure, const void *handler_data,
  11000. const char *str, size_t len,
  11001. const upb_bufhandle *handle) {
  11002. const char* limit = str + len;
  11003. bool upper = false;
  11004. size_t result_len = 0;
  11005. for (; str < limit; str++) {
  11006. if (*str == '_') {
  11007. upper = true;
  11008. continue;
  11009. }
  11010. if (upper && *str >= 'a' && *str <= 'z') {
  11011. char upper_char = toupper(*str);
  11012. CHK(putstr(closure, handler_data, &upper_char, 1, handle));
  11013. } else {
  11014. CHK(putstr(closure, handler_data, str, 1, handle));
  11015. }
  11016. upper = false;
  11017. result_len++;
  11018. }
  11019. return result_len;
  11020. }
  11021. static void *startmap_nokey(void *closure, const void *handler_data) {
  11022. upb_json_printer *p = closure;
  11023. UPB_UNUSED(handler_data);
  11024. p->depth_++;
  11025. p->first_elem_[p->depth_] = true;
  11026. print_data(p, "{", 1);
  11027. return closure;
  11028. }
  11029. static bool putnull(void *closure, const void *handler_data,
  11030. int32_t null) {
  11031. upb_json_printer *p = closure;
  11032. print_data(p, "null", 4);
  11033. UPB_UNUSED(handler_data);
  11034. UPB_UNUSED(null);
  11035. return true;
  11036. }
  11037. static bool printer_startdurationmsg(void *closure, const void *handler_data) {
  11038. upb_json_printer *p = closure;
  11039. UPB_UNUSED(handler_data);
  11040. if (p->depth_ == 0) {
  11041. upb_bytessink_start(p->output_, 0, &p->subc_);
  11042. }
  11043. return true;
  11044. }
  11045. #define UPB_DURATION_MAX_JSON_LEN 23
  11046. #define UPB_DURATION_MAX_NANO_LEN 9
  11047. static bool printer_enddurationmsg(void *closure, const void *handler_data,
  11048. upb_status *s) {
  11049. upb_json_printer *p = closure;
  11050. char buffer[UPB_DURATION_MAX_JSON_LEN];
  11051. size_t base_len;
  11052. size_t curr;
  11053. size_t i;
  11054. memset(buffer, 0, UPB_DURATION_MAX_JSON_LEN);
  11055. if (p->seconds < -315576000000) {
  11056. upb_status_seterrf(s, "error parsing duration: "
  11057. "minimum acceptable value is "
  11058. "-315576000000");
  11059. return false;
  11060. }
  11061. if (p->seconds > 315576000000) {
  11062. upb_status_seterrf(s, "error serializing duration: "
  11063. "maximum acceptable value is "
  11064. "315576000000");
  11065. return false;
  11066. }
  11067. _upb_snprintf(buffer, sizeof(buffer), "%ld", (long)p->seconds);
  11068. base_len = strlen(buffer);
  11069. if (p->nanos != 0) {
  11070. char nanos_buffer[UPB_DURATION_MAX_NANO_LEN + 3];
  11071. _upb_snprintf(nanos_buffer, sizeof(nanos_buffer), "%.9f",
  11072. p->nanos / 1000000000.0);
  11073. /* Remove trailing 0. */
  11074. for (i = UPB_DURATION_MAX_NANO_LEN + 2;
  11075. nanos_buffer[i] == '0'; i--) {
  11076. nanos_buffer[i] = 0;
  11077. }
  11078. strcpy(buffer + base_len, nanos_buffer + 1);
  11079. }
  11080. curr = strlen(buffer);
  11081. strcpy(buffer + curr, "s");
  11082. p->seconds = 0;
  11083. p->nanos = 0;
  11084. print_data(p, "\"", 1);
  11085. print_data(p, buffer, strlen(buffer));
  11086. print_data(p, "\"", 1);
  11087. if (p->depth_ == 0) {
  11088. upb_bytessink_end(p->output_);
  11089. }
  11090. UPB_UNUSED(handler_data);
  11091. return true;
  11092. }
  11093. static bool printer_starttimestampmsg(void *closure, const void *handler_data) {
  11094. upb_json_printer *p = closure;
  11095. UPB_UNUSED(handler_data);
  11096. if (p->depth_ == 0) {
  11097. upb_bytessink_start(p->output_, 0, &p->subc_);
  11098. }
  11099. return true;
  11100. }
  11101. #define UPB_TIMESTAMP_MAX_JSON_LEN 31
  11102. #define UPB_TIMESTAMP_BEFORE_NANO_LEN 19
  11103. #define UPB_TIMESTAMP_MAX_NANO_LEN 9
  11104. static bool printer_endtimestampmsg(void *closure, const void *handler_data,
  11105. upb_status *s) {
  11106. upb_json_printer *p = closure;
  11107. char buffer[UPB_TIMESTAMP_MAX_JSON_LEN];
  11108. time_t time = p->seconds;
  11109. size_t curr;
  11110. size_t i;
  11111. size_t year_length =
  11112. strftime(buffer, UPB_TIMESTAMP_MAX_JSON_LEN, "%Y", gmtime(&time));
  11113. if (p->seconds < -62135596800) {
  11114. upb_status_seterrf(s, "error parsing timestamp: "
  11115. "minimum acceptable value is "
  11116. "0001-01-01T00:00:00Z");
  11117. return false;
  11118. }
  11119. if (p->seconds > 253402300799) {
  11120. upb_status_seterrf(s, "error parsing timestamp: "
  11121. "maximum acceptable value is "
  11122. "9999-12-31T23:59:59Z");
  11123. return false;
  11124. }
  11125. /* strftime doesn't guarantee 4 digits for year. Prepend 0 by ourselves. */
  11126. for (i = 0; i < 4 - year_length; i++) {
  11127. buffer[i] = '0';
  11128. }
  11129. strftime(buffer + (4 - year_length), UPB_TIMESTAMP_MAX_JSON_LEN,
  11130. "%Y-%m-%dT%H:%M:%S", gmtime(&time));
  11131. if (p->nanos != 0) {
  11132. char nanos_buffer[UPB_TIMESTAMP_MAX_NANO_LEN + 3];
  11133. _upb_snprintf(nanos_buffer, sizeof(nanos_buffer), "%.9f",
  11134. p->nanos / 1000000000.0);
  11135. /* Remove trailing 0. */
  11136. for (i = UPB_TIMESTAMP_MAX_NANO_LEN + 2;
  11137. nanos_buffer[i] == '0'; i--) {
  11138. nanos_buffer[i] = 0;
  11139. }
  11140. strcpy(buffer + UPB_TIMESTAMP_BEFORE_NANO_LEN, nanos_buffer + 1);
  11141. }
  11142. curr = strlen(buffer);
  11143. strcpy(buffer + curr, "Z");
  11144. p->seconds = 0;
  11145. p->nanos = 0;
  11146. print_data(p, "\"", 1);
  11147. print_data(p, buffer, strlen(buffer));
  11148. print_data(p, "\"", 1);
  11149. if (p->depth_ == 0) {
  11150. upb_bytessink_end(p->output_);
  11151. }
  11152. UPB_UNUSED(handler_data);
  11153. UPB_UNUSED(s);
  11154. return true;
  11155. }
  11156. static bool printer_startmsg_noframe(void *closure, const void *handler_data) {
  11157. upb_json_printer *p = closure;
  11158. UPB_UNUSED(handler_data);
  11159. if (p->depth_ == 0) {
  11160. upb_bytessink_start(p->output_, 0, &p->subc_);
  11161. }
  11162. return true;
  11163. }
  11164. static bool printer_endmsg_noframe(
  11165. void *closure, const void *handler_data, upb_status *s) {
  11166. upb_json_printer *p = closure;
  11167. UPB_UNUSED(handler_data);
  11168. UPB_UNUSED(s);
  11169. if (p->depth_ == 0) {
  11170. upb_bytessink_end(p->output_);
  11171. }
  11172. return true;
  11173. }
  11174. static bool printer_startmsg_fieldmask(
  11175. void *closure, const void *handler_data) {
  11176. upb_json_printer *p = closure;
  11177. UPB_UNUSED(handler_data);
  11178. if (p->depth_ == 0) {
  11179. upb_bytessink_start(p->output_, 0, &p->subc_);
  11180. }
  11181. print_data(p, "\"", 1);
  11182. return true;
  11183. }
  11184. static bool printer_endmsg_fieldmask(
  11185. void *closure, const void *handler_data, upb_status *s) {
  11186. upb_json_printer *p = closure;
  11187. UPB_UNUSED(handler_data);
  11188. UPB_UNUSED(s);
  11189. print_data(p, "\"", 1);
  11190. if (p->depth_ == 0) {
  11191. upb_bytessink_end(p->output_);
  11192. }
  11193. return true;
  11194. }
  11195. static void *scalar_startstr_onlykey(
  11196. void *closure, const void *handler_data, size_t size_hint) {
  11197. upb_json_printer *p = closure;
  11198. UPB_UNUSED(size_hint);
  11199. CHK(putkey(closure, handler_data));
  11200. return p;
  11201. }
  11202. /* Set up handlers for an Any submessage. */
  11203. void printer_sethandlers_any(const void *closure, upb_handlers *h) {
  11204. const upb_msgdef *md = upb_handlers_msgdef(h);
  11205. const upb_fielddef* type_field = upb_msgdef_itof(md, UPB_ANY_TYPE);
  11206. const upb_fielddef* value_field = upb_msgdef_itof(md, UPB_ANY_VALUE);
  11207. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11208. /* type_url's json name is "@type" */
  11209. upb_handlerattr type_name_attr = UPB_HANDLERATTR_INIT;
  11210. upb_handlerattr value_name_attr = UPB_HANDLERATTR_INIT;
  11211. strpc *type_url_json_name = newstrpc_str(h, "@type");
  11212. strpc *value_json_name = newstrpc_str(h, "value");
  11213. type_name_attr.handler_data = type_url_json_name;
  11214. value_name_attr.handler_data = value_json_name;
  11215. /* Set up handlers. */
  11216. upb_handlers_setstartmsg(h, printer_startmsg, &empty_attr);
  11217. upb_handlers_setendmsg(h, printer_endmsg, &empty_attr);
  11218. upb_handlers_setstartstr(h, type_field, scalar_startstr, &type_name_attr);
  11219. upb_handlers_setstring(h, type_field, scalar_str, &empty_attr);
  11220. upb_handlers_setendstr(h, type_field, scalar_endstr, &empty_attr);
  11221. /* This is not the full and correct JSON encoding for the Any value field. It
  11222. * requires further processing by the wrapper code based on the type URL.
  11223. */
  11224. upb_handlers_setstartstr(h, value_field, scalar_startstr_onlykey,
  11225. &value_name_attr);
  11226. UPB_UNUSED(closure);
  11227. }
  11228. /* Set up handlers for a fieldmask submessage. */
  11229. void printer_sethandlers_fieldmask(const void *closure, upb_handlers *h) {
  11230. const upb_msgdef *md = upb_handlers_msgdef(h);
  11231. const upb_fielddef* f = upb_msgdef_itof(md, 1);
  11232. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11233. upb_handlers_setstartseq(h, f, startseq_fieldmask, &empty_attr);
  11234. upb_handlers_setendseq(h, f, endseq_fieldmask, &empty_attr);
  11235. upb_handlers_setstartmsg(h, printer_startmsg_fieldmask, &empty_attr);
  11236. upb_handlers_setendmsg(h, printer_endmsg_fieldmask, &empty_attr);
  11237. upb_handlers_setstartstr(h, f, repeated_startstr_fieldmask, &empty_attr);
  11238. upb_handlers_setstring(h, f, repeated_str_fieldmask, &empty_attr);
  11239. UPB_UNUSED(closure);
  11240. }
  11241. /* Set up handlers for a duration submessage. */
  11242. void printer_sethandlers_duration(const void *closure, upb_handlers *h) {
  11243. const upb_msgdef *md = upb_handlers_msgdef(h);
  11244. const upb_fielddef* seconds_field =
  11245. upb_msgdef_itof(md, UPB_DURATION_SECONDS);
  11246. const upb_fielddef* nanos_field =
  11247. upb_msgdef_itof(md, UPB_DURATION_NANOS);
  11248. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11249. upb_handlers_setstartmsg(h, printer_startdurationmsg, &empty_attr);
  11250. upb_handlers_setint64(h, seconds_field, putseconds, &empty_attr);
  11251. upb_handlers_setint32(h, nanos_field, putnanos, &empty_attr);
  11252. upb_handlers_setendmsg(h, printer_enddurationmsg, &empty_attr);
  11253. UPB_UNUSED(closure);
  11254. }
  11255. /* Set up handlers for a timestamp submessage. Instead of printing fields
  11256. * separately, the json representation of timestamp follows RFC 3339 */
  11257. void printer_sethandlers_timestamp(const void *closure, upb_handlers *h) {
  11258. const upb_msgdef *md = upb_handlers_msgdef(h);
  11259. const upb_fielddef* seconds_field =
  11260. upb_msgdef_itof(md, UPB_TIMESTAMP_SECONDS);
  11261. const upb_fielddef* nanos_field =
  11262. upb_msgdef_itof(md, UPB_TIMESTAMP_NANOS);
  11263. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11264. upb_handlers_setstartmsg(h, printer_starttimestampmsg, &empty_attr);
  11265. upb_handlers_setint64(h, seconds_field, putseconds, &empty_attr);
  11266. upb_handlers_setint32(h, nanos_field, putnanos, &empty_attr);
  11267. upb_handlers_setendmsg(h, printer_endtimestampmsg, &empty_attr);
  11268. UPB_UNUSED(closure);
  11269. }
  11270. void printer_sethandlers_value(const void *closure, upb_handlers *h) {
  11271. const upb_msgdef *md = upb_handlers_msgdef(h);
  11272. upb_msg_field_iter i;
  11273. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11274. upb_handlers_setstartmsg(h, printer_startmsg_noframe, &empty_attr);
  11275. upb_handlers_setendmsg(h, printer_endmsg_noframe, &empty_attr);
  11276. upb_msg_field_begin(&i, md);
  11277. for(; !upb_msg_field_done(&i); upb_msg_field_next(&i)) {
  11278. const upb_fielddef *f = upb_msg_iter_field(&i);
  11279. switch (upb_fielddef_type(f)) {
  11280. case UPB_TYPE_ENUM:
  11281. upb_handlers_setint32(h, f, putnull, &empty_attr);
  11282. break;
  11283. case UPB_TYPE_DOUBLE:
  11284. upb_handlers_setdouble(h, f, putdouble, &empty_attr);
  11285. break;
  11286. case UPB_TYPE_STRING:
  11287. upb_handlers_setstartstr(h, f, scalar_startstr_nokey, &empty_attr);
  11288. upb_handlers_setstring(h, f, scalar_str, &empty_attr);
  11289. upb_handlers_setendstr(h, f, scalar_endstr, &empty_attr);
  11290. break;
  11291. case UPB_TYPE_BOOL:
  11292. upb_handlers_setbool(h, f, putbool, &empty_attr);
  11293. break;
  11294. case UPB_TYPE_MESSAGE:
  11295. break;
  11296. default:
  11297. UPB_ASSERT(false);
  11298. break;
  11299. }
  11300. }
  11301. UPB_UNUSED(closure);
  11302. }
  11303. #define WRAPPER_SETHANDLERS(wrapper, type, putmethod) \
  11304. void printer_sethandlers_##wrapper(const void *closure, upb_handlers *h) { \
  11305. const upb_msgdef *md = upb_handlers_msgdef(h); \
  11306. const upb_fielddef* f = upb_msgdef_itof(md, 1); \
  11307. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT; \
  11308. upb_handlers_setstartmsg(h, printer_startmsg_noframe, &empty_attr); \
  11309. upb_handlers_setendmsg(h, printer_endmsg_noframe, &empty_attr); \
  11310. upb_handlers_set##type(h, f, putmethod, &empty_attr); \
  11311. UPB_UNUSED(closure); \
  11312. }
  11313. WRAPPER_SETHANDLERS(doublevalue, double, putdouble)
  11314. WRAPPER_SETHANDLERS(floatvalue, float, putfloat)
  11315. WRAPPER_SETHANDLERS(int64value, int64, putint64_t)
  11316. WRAPPER_SETHANDLERS(uint64value, uint64, putuint64_t)
  11317. WRAPPER_SETHANDLERS(int32value, int32, putint32_t)
  11318. WRAPPER_SETHANDLERS(uint32value, uint32, putuint32_t)
  11319. WRAPPER_SETHANDLERS(boolvalue, bool, putbool)
  11320. WRAPPER_SETHANDLERS(stringvalue, string, putstr_nokey)
  11321. WRAPPER_SETHANDLERS(bytesvalue, string, putbytes)
  11322. #undef WRAPPER_SETHANDLERS
  11323. void printer_sethandlers_listvalue(const void *closure, upb_handlers *h) {
  11324. const upb_msgdef *md = upb_handlers_msgdef(h);
  11325. const upb_fielddef* f = upb_msgdef_itof(md, 1);
  11326. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11327. upb_handlers_setstartseq(h, f, startseq_nokey, &empty_attr);
  11328. upb_handlers_setendseq(h, f, endseq, &empty_attr);
  11329. upb_handlers_setstartmsg(h, printer_startmsg_noframe, &empty_attr);
  11330. upb_handlers_setendmsg(h, printer_endmsg_noframe, &empty_attr);
  11331. upb_handlers_setstartsubmsg(h, f, repeated_startsubmsg, &empty_attr);
  11332. UPB_UNUSED(closure);
  11333. }
  11334. void printer_sethandlers_structvalue(const void *closure, upb_handlers *h) {
  11335. const upb_msgdef *md = upb_handlers_msgdef(h);
  11336. const upb_fielddef* f = upb_msgdef_itof(md, 1);
  11337. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11338. upb_handlers_setstartseq(h, f, startmap_nokey, &empty_attr);
  11339. upb_handlers_setendseq(h, f, endmap, &empty_attr);
  11340. upb_handlers_setstartmsg(h, printer_startmsg_noframe, &empty_attr);
  11341. upb_handlers_setendmsg(h, printer_endmsg_noframe, &empty_attr);
  11342. upb_handlers_setstartsubmsg(h, f, repeated_startsubmsg, &empty_attr);
  11343. UPB_UNUSED(closure);
  11344. }
  11345. void printer_sethandlers(const void *closure, upb_handlers *h) {
  11346. const upb_msgdef *md = upb_handlers_msgdef(h);
  11347. bool is_mapentry = upb_msgdef_mapentry(md);
  11348. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11349. upb_msg_field_iter i;
  11350. const upb_json_printercache *cache = closure;
  11351. const bool preserve_fieldnames = cache->preserve_fieldnames;
  11352. if (is_mapentry) {
  11353. /* mapentry messages are sufficiently different that we handle them
  11354. * separately. */
  11355. printer_sethandlers_mapentry(closure, preserve_fieldnames, h);
  11356. return;
  11357. }
  11358. switch (upb_msgdef_wellknowntype(md)) {
  11359. case UPB_WELLKNOWN_UNSPECIFIED:
  11360. break;
  11361. case UPB_WELLKNOWN_ANY:
  11362. printer_sethandlers_any(closure, h);
  11363. return;
  11364. case UPB_WELLKNOWN_FIELDMASK:
  11365. printer_sethandlers_fieldmask(closure, h);
  11366. return;
  11367. case UPB_WELLKNOWN_DURATION:
  11368. printer_sethandlers_duration(closure, h);
  11369. return;
  11370. case UPB_WELLKNOWN_TIMESTAMP:
  11371. printer_sethandlers_timestamp(closure, h);
  11372. return;
  11373. case UPB_WELLKNOWN_VALUE:
  11374. printer_sethandlers_value(closure, h);
  11375. return;
  11376. case UPB_WELLKNOWN_LISTVALUE:
  11377. printer_sethandlers_listvalue(closure, h);
  11378. return;
  11379. case UPB_WELLKNOWN_STRUCT:
  11380. printer_sethandlers_structvalue(closure, h);
  11381. return;
  11382. #define WRAPPER(wellknowntype, name) \
  11383. case wellknowntype: \
  11384. printer_sethandlers_##name(closure, h); \
  11385. return; \
  11386. WRAPPER(UPB_WELLKNOWN_DOUBLEVALUE, doublevalue);
  11387. WRAPPER(UPB_WELLKNOWN_FLOATVALUE, floatvalue);
  11388. WRAPPER(UPB_WELLKNOWN_INT64VALUE, int64value);
  11389. WRAPPER(UPB_WELLKNOWN_UINT64VALUE, uint64value);
  11390. WRAPPER(UPB_WELLKNOWN_INT32VALUE, int32value);
  11391. WRAPPER(UPB_WELLKNOWN_UINT32VALUE, uint32value);
  11392. WRAPPER(UPB_WELLKNOWN_BOOLVALUE, boolvalue);
  11393. WRAPPER(UPB_WELLKNOWN_STRINGVALUE, stringvalue);
  11394. WRAPPER(UPB_WELLKNOWN_BYTESVALUE, bytesvalue);
  11395. #undef WRAPPER
  11396. }
  11397. upb_handlers_setstartmsg(h, printer_startmsg, &empty_attr);
  11398. upb_handlers_setendmsg(h, printer_endmsg, &empty_attr);
  11399. #define TYPE(type, name, ctype) \
  11400. case type: \
  11401. if (upb_fielddef_isseq(f)) { \
  11402. upb_handlers_set##name(h, f, repeated_##ctype, &empty_attr); \
  11403. } else { \
  11404. upb_handlers_set##name(h, f, scalar_##ctype, &name_attr); \
  11405. } \
  11406. break;
  11407. upb_msg_field_begin(&i, md);
  11408. for(; !upb_msg_field_done(&i); upb_msg_field_next(&i)) {
  11409. const upb_fielddef *f = upb_msg_iter_field(&i);
  11410. upb_handlerattr name_attr = UPB_HANDLERATTR_INIT;
  11411. name_attr.handler_data = newstrpc(h, f, preserve_fieldnames);
  11412. if (upb_fielddef_ismap(f)) {
  11413. upb_handlers_setstartseq(h, f, startmap, &name_attr);
  11414. upb_handlers_setendseq(h, f, endmap, &name_attr);
  11415. } else if (upb_fielddef_isseq(f)) {
  11416. upb_handlers_setstartseq(h, f, startseq, &name_attr);
  11417. upb_handlers_setendseq(h, f, endseq, &empty_attr);
  11418. }
  11419. switch (upb_fielddef_type(f)) {
  11420. TYPE(UPB_TYPE_FLOAT, float, float);
  11421. TYPE(UPB_TYPE_DOUBLE, double, double);
  11422. TYPE(UPB_TYPE_BOOL, bool, bool);
  11423. TYPE(UPB_TYPE_INT32, int32, int32_t);
  11424. TYPE(UPB_TYPE_UINT32, uint32, uint32_t);
  11425. TYPE(UPB_TYPE_INT64, int64, int64_t);
  11426. TYPE(UPB_TYPE_UINT64, uint64, uint64_t);
  11427. case UPB_TYPE_ENUM: {
  11428. /* For now, we always emit symbolic names for enums. We may want an
  11429. * option later to control this behavior, but we will wait for a real
  11430. * need first. */
  11431. upb_handlerattr enum_attr = UPB_HANDLERATTR_INIT;
  11432. set_enum_hd(h, f, preserve_fieldnames, &enum_attr);
  11433. if (upb_fielddef_isseq(f)) {
  11434. upb_handlers_setint32(h, f, repeated_enum, &enum_attr);
  11435. } else {
  11436. upb_handlers_setint32(h, f, scalar_enum, &enum_attr);
  11437. }
  11438. break;
  11439. }
  11440. case UPB_TYPE_STRING:
  11441. if (upb_fielddef_isseq(f)) {
  11442. upb_handlers_setstartstr(h, f, repeated_startstr, &empty_attr);
  11443. upb_handlers_setstring(h, f, repeated_str, &empty_attr);
  11444. upb_handlers_setendstr(h, f, repeated_endstr, &empty_attr);
  11445. } else {
  11446. upb_handlers_setstartstr(h, f, scalar_startstr, &name_attr);
  11447. upb_handlers_setstring(h, f, scalar_str, &empty_attr);
  11448. upb_handlers_setendstr(h, f, scalar_endstr, &empty_attr);
  11449. }
  11450. break;
  11451. case UPB_TYPE_BYTES:
  11452. /* XXX: this doesn't support strings that span buffers yet. The base64
  11453. * encoder will need to be made resumable for this to work properly. */
  11454. if (upb_fielddef_isseq(f)) {
  11455. upb_handlers_setstring(h, f, repeated_bytes, &empty_attr);
  11456. } else {
  11457. upb_handlers_setstring(h, f, scalar_bytes, &name_attr);
  11458. }
  11459. break;
  11460. case UPB_TYPE_MESSAGE:
  11461. if (upb_fielddef_isseq(f)) {
  11462. upb_handlers_setstartsubmsg(h, f, repeated_startsubmsg, &name_attr);
  11463. } else {
  11464. upb_handlers_setstartsubmsg(h, f, scalar_startsubmsg, &name_attr);
  11465. }
  11466. break;
  11467. }
  11468. }
  11469. #undef TYPE
  11470. }
  11471. static void json_printer_reset(upb_json_printer *p) {
  11472. p->depth_ = 0;
  11473. }
  11474. /* Public API *****************************************************************/
  11475. upb_json_printer *upb_json_printer_create(upb_arena *a, const upb_handlers *h,
  11476. upb_bytessink output) {
  11477. #ifndef NDEBUG
  11478. size_t size_before = upb_arena_bytesallocated(a);
  11479. #endif
  11480. upb_json_printer *p = upb_arena_malloc(a, sizeof(upb_json_printer));
  11481. if (!p) return NULL;
  11482. p->output_ = output;
  11483. json_printer_reset(p);
  11484. upb_sink_reset(&p->input_, h, p);
  11485. p->seconds = 0;
  11486. p->nanos = 0;
  11487. /* If this fails, increase the value in printer.h. */
  11488. UPB_ASSERT_DEBUGVAR(upb_arena_bytesallocated(a) - size_before <=
  11489. UPB_JSON_PRINTER_SIZE);
  11490. return p;
  11491. }
  11492. upb_sink upb_json_printer_input(upb_json_printer *p) {
  11493. return p->input_;
  11494. }
  11495. upb_handlercache *upb_json_printer_newcache(bool preserve_proto_fieldnames) {
  11496. upb_json_printercache *cache = upb_gmalloc(sizeof(*cache));
  11497. upb_handlercache *ret = upb_handlercache_new(printer_sethandlers, cache);
  11498. cache->preserve_fieldnames = preserve_proto_fieldnames;
  11499. upb_handlercache_addcleanup(ret, cache, upb_gfree);
  11500. return ret;
  11501. }
  11502. #undef UPB_SIZE
  11503. #undef UPB_FIELD_AT
  11504. #undef UPB_READ_ONEOF
  11505. #undef UPB_WRITE_ONEOF