upb.c 392 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341
  1. /* Amalgamated source file */
  2. #include "upb.h"
  3. /*
  4. * This is where we define macros used across upb.
  5. *
  6. * All of these macros are undef'd in port_undef.inc to avoid leaking them to
  7. * users.
  8. *
  9. * The correct usage is:
  10. *
  11. * #include "upb/foobar.h"
  12. * #include "upb/baz.h"
  13. *
  14. * // MUST be last included header.
  15. * #include "upb/port_def.inc"
  16. *
  17. * // Code for this file.
  18. * // <...>
  19. *
  20. * // Can be omitted for .c files, required for .h.
  21. * #include "upb/port_undef.inc"
  22. *
  23. * This file is private and must not be included by users!
  24. */
  25. #ifndef UINTPTR_MAX
  26. #error must include stdint.h first
  27. #endif
  28. #if UINTPTR_MAX == 0xffffffff
  29. #define UPB_SIZE(size32, size64) size32
  30. #else
  31. #define UPB_SIZE(size32, size64) size64
  32. #endif
  33. #define UPB_FIELD_AT(msg, fieldtype, offset) \
  34. *(fieldtype*)((const char*)(msg) + offset)
  35. #define UPB_READ_ONEOF(msg, fieldtype, offset, case_offset, case_val, default) \
  36. UPB_FIELD_AT(msg, int, case_offset) == case_val \
  37. ? UPB_FIELD_AT(msg, fieldtype, offset) \
  38. : default
  39. #define UPB_WRITE_ONEOF(msg, fieldtype, offset, value, case_offset, case_val) \
  40. UPB_FIELD_AT(msg, int, case_offset) = case_val; \
  41. UPB_FIELD_AT(msg, fieldtype, offset) = value;
  42. /* UPB_INLINE: inline if possible, emit standalone code if required. */
  43. #ifdef __cplusplus
  44. #define UPB_INLINE inline
  45. #elif defined (__GNUC__) || defined(__clang__)
  46. #define UPB_INLINE static __inline__
  47. #else
  48. #define UPB_INLINE static
  49. #endif
  50. /* Hints to the compiler about likely/unlikely branches. */
  51. #if defined (__GNUC__) || defined(__clang__)
  52. #define UPB_LIKELY(x) __builtin_expect((x),1)
  53. #define UPB_UNLIKELY(x) __builtin_expect((x),0)
  54. #else
  55. #define UPB_LIKELY(x) (x)
  56. #define UPB_UNLIKELY(x) (x)
  57. #endif
  58. /* Define UPB_BIG_ENDIAN manually if you're on big endian and your compiler
  59. * doesn't provide these preprocessor symbols. */
  60. #if defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)
  61. #define UPB_BIG_ENDIAN
  62. #endif
  63. /* Macros for function attributes on compilers that support them. */
  64. #ifdef __GNUC__
  65. #define UPB_FORCEINLINE __inline__ __attribute__((always_inline))
  66. #define UPB_NOINLINE __attribute__((noinline))
  67. #define UPB_NORETURN __attribute__((__noreturn__))
  68. #else /* !defined(__GNUC__) */
  69. #define UPB_FORCEINLINE
  70. #define UPB_NOINLINE
  71. #define UPB_NORETURN
  72. #endif
  73. #if __STDC_VERSION__ >= 199901L || __cplusplus >= 201103L
  74. /* C99/C++11 versions. */
  75. #include <stdio.h>
  76. #define _upb_snprintf snprintf
  77. #define _upb_vsnprintf vsnprintf
  78. #define _upb_va_copy(a, b) va_copy(a, b)
  79. #elif defined(_MSC_VER)
  80. /* Microsoft C/C++ versions. */
  81. #include <stdarg.h>
  82. #include <stdio.h>
  83. #if _MSC_VER < 1900
  84. int msvc_snprintf(char* s, size_t n, const char* format, ...);
  85. int msvc_vsnprintf(char* s, size_t n, const char* format, va_list arg);
  86. #define UPB_MSVC_VSNPRINTF
  87. #define _upb_snprintf msvc_snprintf
  88. #define _upb_vsnprintf msvc_vsnprintf
  89. #else
  90. #define _upb_snprintf snprintf
  91. #define _upb_vsnprintf vsnprintf
  92. #endif
  93. #define _upb_va_copy(a, b) va_copy(a, b)
  94. #elif defined __GNUC__
  95. /* A few hacky workarounds for functions not in C89.
  96. * For internal use only!
  97. * TODO(haberman): fix these by including our own implementations, or finding
  98. * another workaround.
  99. */
  100. #define _upb_snprintf __builtin_snprintf
  101. #define _upb_vsnprintf __builtin_vsnprintf
  102. #define _upb_va_copy(a, b) __va_copy(a, b)
  103. #else
  104. #error Need implementations of [v]snprintf and va_copy
  105. #endif
  106. #ifdef __cplusplus
  107. #if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__) || \
  108. (defined(_MSC_VER) && _MSC_VER >= 1900)
  109. // C++11 is present
  110. #else
  111. #error upb requires C++11 for C++ support
  112. #endif
  113. #endif
  114. #define UPB_MAX(x, y) ((x) > (y) ? (x) : (y))
  115. #define UPB_MIN(x, y) ((x) < (y) ? (x) : (y))
  116. #define UPB_UNUSED(var) (void)var
  117. /* UPB_ASSERT(): in release mode, we use the expression without letting it be
  118. * evaluated. This prevents "unused variable" warnings. */
  119. #ifdef NDEBUG
  120. #define UPB_ASSERT(expr) do {} while (false && (expr))
  121. #else
  122. #define UPB_ASSERT(expr) assert(expr)
  123. #endif
  124. /* UPB_ASSERT_DEBUGVAR(): assert that uses functions or variables that only
  125. * exist in debug mode. This turns into regular assert. */
  126. #define UPB_ASSERT_DEBUGVAR(expr) assert(expr)
  127. #if defined(__GNUC__) || defined(__clang__)
  128. #define UPB_UNREACHABLE() do { assert(0); __builtin_unreachable(); } while(0)
  129. #else
  130. #define UPB_UNREACHABLE() do { assert(0); } while(0)
  131. #endif
  132. /* UPB_INFINITY representing floating-point positive infinity. */
  133. #include <math.h>
  134. #ifdef INFINITY
  135. #define UPB_INFINITY INFINITY
  136. #else
  137. #define UPB_INFINITY (1.0 / 0.0)
  138. #endif
  139. #include <string.h>
  140. /* Maps descriptor type -> upb field type. */
  141. const uint8_t upb_desctype_to_fieldtype[] = {
  142. UPB_WIRE_TYPE_END_GROUP, /* ENDGROUP */
  143. UPB_TYPE_DOUBLE, /* DOUBLE */
  144. UPB_TYPE_FLOAT, /* FLOAT */
  145. UPB_TYPE_INT64, /* INT64 */
  146. UPB_TYPE_UINT64, /* UINT64 */
  147. UPB_TYPE_INT32, /* INT32 */
  148. UPB_TYPE_UINT64, /* FIXED64 */
  149. UPB_TYPE_UINT32, /* FIXED32 */
  150. UPB_TYPE_BOOL, /* BOOL */
  151. UPB_TYPE_STRING, /* STRING */
  152. UPB_TYPE_MESSAGE, /* GROUP */
  153. UPB_TYPE_MESSAGE, /* MESSAGE */
  154. UPB_TYPE_BYTES, /* BYTES */
  155. UPB_TYPE_UINT32, /* UINT32 */
  156. UPB_TYPE_ENUM, /* ENUM */
  157. UPB_TYPE_INT32, /* SFIXED32 */
  158. UPB_TYPE_INT64, /* SFIXED64 */
  159. UPB_TYPE_INT32, /* SINT32 */
  160. UPB_TYPE_INT64, /* SINT64 */
  161. };
  162. /* Data pertaining to the parse. */
  163. typedef struct {
  164. const char *ptr; /* Current parsing position. */
  165. const char *field_start; /* Start of this field. */
  166. const char *limit; /* End of delimited region or end of buffer. */
  167. upb_arena *arena;
  168. int depth;
  169. uint32_t end_group; /* Set to field number of END_GROUP tag, if any. */
  170. } upb_decstate;
  171. /* Data passed by value to each parsing function. */
  172. typedef struct {
  173. char *msg;
  174. const upb_msglayout *layout;
  175. upb_decstate *state;
  176. } upb_decframe;
  177. #define CHK(x) if (!(x)) { return 0; }
  178. static bool upb_skip_unknowngroup(upb_decstate *d, int field_number);
  179. static bool upb_decode_message(upb_decstate *d, char *msg,
  180. const upb_msglayout *l);
  181. static bool upb_decode_varint(const char **ptr, const char *limit,
  182. uint64_t *val) {
  183. uint8_t byte;
  184. int bitpos = 0;
  185. const char *p = *ptr;
  186. *val = 0;
  187. do {
  188. CHK(bitpos < 70 && p < limit);
  189. byte = *p;
  190. *val |= (uint64_t)(byte & 0x7F) << bitpos;
  191. p++;
  192. bitpos += 7;
  193. } while (byte & 0x80);
  194. *ptr = p;
  195. return true;
  196. }
  197. static bool upb_decode_varint32(const char **ptr, const char *limit,
  198. uint32_t *val) {
  199. uint64_t u64;
  200. CHK(upb_decode_varint(ptr, limit, &u64) && u64 <= UINT32_MAX);
  201. *val = (uint32_t)u64;
  202. return true;
  203. }
  204. static bool upb_decode_64bit(const char **ptr, const char *limit,
  205. uint64_t *val) {
  206. CHK(limit - *ptr >= 8);
  207. memcpy(val, *ptr, 8);
  208. *ptr += 8;
  209. return true;
  210. }
  211. static bool upb_decode_32bit(const char **ptr, const char *limit,
  212. uint32_t *val) {
  213. CHK(limit - *ptr >= 4);
  214. memcpy(val, *ptr, 4);
  215. *ptr += 4;
  216. return true;
  217. }
  218. static int32_t upb_zzdecode_32(uint32_t n) {
  219. return (n >> 1) ^ -(int32_t)(n & 1);
  220. }
  221. static int64_t upb_zzdecode_64(uint64_t n) {
  222. return (n >> 1) ^ -(int64_t)(n & 1);
  223. }
  224. static bool upb_decode_string(const char **ptr, const char *limit,
  225. int *outlen) {
  226. uint32_t len;
  227. CHK(upb_decode_varint32(ptr, limit, &len) &&
  228. len < INT32_MAX &&
  229. limit - *ptr >= (int32_t)len);
  230. *outlen = len;
  231. return true;
  232. }
  233. static void upb_set32(void *msg, size_t ofs, uint32_t val) {
  234. memcpy((char*)msg + ofs, &val, sizeof(val));
  235. }
  236. static bool upb_append_unknown(upb_decstate *d, upb_decframe *frame) {
  237. upb_msg_addunknown(frame->msg, d->field_start, d->ptr - d->field_start,
  238. d->arena);
  239. return true;
  240. }
  241. static bool upb_skip_unknownfielddata(upb_decstate *d, uint32_t tag,
  242. uint32_t group_fieldnum) {
  243. switch (tag & 7) {
  244. case UPB_WIRE_TYPE_VARINT: {
  245. uint64_t val;
  246. return upb_decode_varint(&d->ptr, d->limit, &val);
  247. }
  248. case UPB_WIRE_TYPE_32BIT: {
  249. uint32_t val;
  250. return upb_decode_32bit(&d->ptr, d->limit, &val);
  251. }
  252. case UPB_WIRE_TYPE_64BIT: {
  253. uint64_t val;
  254. return upb_decode_64bit(&d->ptr, d->limit, &val);
  255. }
  256. case UPB_WIRE_TYPE_DELIMITED: {
  257. int len;
  258. CHK(upb_decode_string(&d->ptr, d->limit, &len));
  259. d->ptr += len;
  260. return true;
  261. }
  262. case UPB_WIRE_TYPE_START_GROUP:
  263. return upb_skip_unknowngroup(d, tag >> 3);
  264. case UPB_WIRE_TYPE_END_GROUP:
  265. return (tag >> 3) == group_fieldnum;
  266. }
  267. return false;
  268. }
  269. static bool upb_skip_unknowngroup(upb_decstate *d, int field_number) {
  270. while (d->ptr < d->limit && d->end_group == 0) {
  271. uint32_t tag = 0;
  272. CHK(upb_decode_varint32(&d->ptr, d->limit, &tag));
  273. CHK(upb_skip_unknownfielddata(d, tag, field_number));
  274. }
  275. CHK(d->end_group == field_number);
  276. d->end_group = 0;
  277. return true;
  278. }
  279. static bool upb_array_grow(upb_array *arr, size_t elements, size_t elem_size,
  280. upb_arena *arena) {
  281. size_t needed = arr->len + elements;
  282. size_t new_size = UPB_MAX(arr->size, 8);
  283. size_t new_bytes;
  284. size_t old_bytes;
  285. void *new_data;
  286. upb_alloc *alloc = upb_arena_alloc(arena);
  287. while (new_size < needed) {
  288. new_size *= 2;
  289. }
  290. old_bytes = arr->len * elem_size;
  291. new_bytes = new_size * elem_size;
  292. new_data = upb_realloc(alloc, arr->data, old_bytes, new_bytes);
  293. CHK(new_data);
  294. arr->data = new_data;
  295. arr->size = new_size;
  296. return true;
  297. }
  298. static void *upb_array_reserve(upb_array *arr, size_t elements,
  299. size_t elem_size, upb_arena *arena) {
  300. if (arr->size - arr->len < elements) {
  301. CHK(upb_array_grow(arr, elements, elem_size, arena));
  302. }
  303. return (char*)arr->data + (arr->len * elem_size);
  304. }
  305. bool upb_array_add(upb_array *arr, size_t elements, size_t elem_size,
  306. const void *data, upb_arena *arena) {
  307. void *dest = upb_array_reserve(arr, elements, elem_size, arena);
  308. CHK(dest);
  309. arr->len += elements;
  310. memcpy(dest, data, elements * elem_size);
  311. return true;
  312. }
  313. static upb_array *upb_getarr(upb_decframe *frame,
  314. const upb_msglayout_field *field) {
  315. UPB_ASSERT(field->label == UPB_LABEL_REPEATED);
  316. return *(upb_array**)&frame->msg[field->offset];
  317. }
  318. static upb_array *upb_getorcreatearr(upb_decframe *frame,
  319. const upb_msglayout_field *field) {
  320. upb_array *arr = upb_getarr(frame, field);
  321. if (!arr) {
  322. arr = upb_array_new(frame->state->arena);
  323. CHK(arr);
  324. *(upb_array**)&frame->msg[field->offset] = arr;
  325. }
  326. return arr;
  327. }
  328. static upb_msg *upb_getorcreatemsg(upb_decframe *frame,
  329. const upb_msglayout_field *field,
  330. const upb_msglayout **subm) {
  331. upb_msg **submsg = (void*)(frame->msg + field->offset);
  332. *subm = frame->layout->submsgs[field->submsg_index];
  333. UPB_ASSERT(field->label != UPB_LABEL_REPEATED);
  334. if (!*submsg) {
  335. *submsg = upb_msg_new(*subm, frame->state->arena);
  336. CHK(*submsg);
  337. }
  338. return *submsg;
  339. }
  340. static upb_msg *upb_addmsg(upb_decframe *frame,
  341. const upb_msglayout_field *field,
  342. const upb_msglayout **subm) {
  343. upb_msg *submsg;
  344. upb_array *arr = upb_getorcreatearr(frame, field);
  345. *subm = frame->layout->submsgs[field->submsg_index];
  346. submsg = upb_msg_new(*subm, frame->state->arena);
  347. CHK(submsg);
  348. upb_array_add(arr, 1, sizeof(submsg), &submsg, frame->state->arena);
  349. return submsg;
  350. }
  351. static void upb_sethasbit(upb_decframe *frame,
  352. const upb_msglayout_field *field) {
  353. int32_t hasbit = field->presence;
  354. UPB_ASSERT(field->presence > 0);
  355. frame->msg[hasbit / 8] |= (1 << (hasbit % 8));
  356. }
  357. static void upb_setoneofcase(upb_decframe *frame,
  358. const upb_msglayout_field *field) {
  359. UPB_ASSERT(field->presence < 0);
  360. upb_set32(frame->msg, ~field->presence, field->number);
  361. }
  362. static bool upb_decode_addval(upb_decframe *frame,
  363. const upb_msglayout_field *field, void *val,
  364. size_t size) {
  365. char *field_mem = frame->msg + field->offset;
  366. upb_array *arr;
  367. if (field->label == UPB_LABEL_REPEATED) {
  368. arr = upb_getorcreatearr(frame, field);
  369. CHK(arr);
  370. field_mem = upb_array_reserve(arr, 1, size, frame->state->arena);
  371. CHK(field_mem);
  372. }
  373. memcpy(field_mem, val, size);
  374. return true;
  375. }
  376. static void upb_decode_setpresent(upb_decframe *frame,
  377. const upb_msglayout_field *field) {
  378. if (field->label == UPB_LABEL_REPEATED) {
  379. upb_array *arr = upb_getarr(frame, field);
  380. UPB_ASSERT(arr->len < arr->size);
  381. arr->len++;
  382. } else if (field->presence < 0) {
  383. upb_setoneofcase(frame, field);
  384. } else if (field->presence > 0) {
  385. upb_sethasbit(frame, field);
  386. }
  387. }
  388. static bool upb_decode_msgfield(upb_decstate *d, upb_msg *msg,
  389. const upb_msglayout *layout, int limit) {
  390. const char* saved_limit = d->limit;
  391. d->limit = d->ptr + limit;
  392. CHK(--d->depth >= 0);
  393. upb_decode_message(d, msg, layout);
  394. d->depth++;
  395. d->limit = saved_limit;
  396. CHK(d->end_group == 0);
  397. return true;
  398. }
  399. static bool upb_decode_groupfield(upb_decstate *d, upb_msg *msg,
  400. const upb_msglayout *layout,
  401. int field_number) {
  402. CHK(--d->depth >= 0);
  403. upb_decode_message(d, msg, layout);
  404. d->depth++;
  405. CHK(d->end_group == field_number);
  406. d->end_group = 0;
  407. return true;
  408. }
  409. static bool upb_decode_varintfield(upb_decstate *d, upb_decframe *frame,
  410. const upb_msglayout_field *field) {
  411. uint64_t val;
  412. CHK(upb_decode_varint(&d->ptr, d->limit, &val));
  413. switch (field->descriptortype) {
  414. case UPB_DESCRIPTOR_TYPE_INT64:
  415. case UPB_DESCRIPTOR_TYPE_UINT64:
  416. CHK(upb_decode_addval(frame, field, &val, sizeof(val)));
  417. break;
  418. case UPB_DESCRIPTOR_TYPE_INT32:
  419. case UPB_DESCRIPTOR_TYPE_UINT32:
  420. case UPB_DESCRIPTOR_TYPE_ENUM: {
  421. uint32_t val32 = (uint32_t)val;
  422. CHK(upb_decode_addval(frame, field, &val32, sizeof(val32)));
  423. break;
  424. }
  425. case UPB_DESCRIPTOR_TYPE_BOOL: {
  426. bool valbool = val != 0;
  427. CHK(upb_decode_addval(frame, field, &valbool, sizeof(valbool)));
  428. break;
  429. }
  430. case UPB_DESCRIPTOR_TYPE_SINT32: {
  431. int32_t decoded = upb_zzdecode_32((uint32_t)val);
  432. CHK(upb_decode_addval(frame, field, &decoded, sizeof(decoded)));
  433. break;
  434. }
  435. case UPB_DESCRIPTOR_TYPE_SINT64: {
  436. int64_t decoded = upb_zzdecode_64(val);
  437. CHK(upb_decode_addval(frame, field, &decoded, sizeof(decoded)));
  438. break;
  439. }
  440. default:
  441. return upb_append_unknown(d, frame);
  442. }
  443. upb_decode_setpresent(frame, field);
  444. return true;
  445. }
  446. static bool upb_decode_64bitfield(upb_decstate *d, upb_decframe *frame,
  447. const upb_msglayout_field *field) {
  448. uint64_t val;
  449. CHK(upb_decode_64bit(&d->ptr, d->limit, &val));
  450. switch (field->descriptortype) {
  451. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  452. case UPB_DESCRIPTOR_TYPE_FIXED64:
  453. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  454. CHK(upb_decode_addval(frame, field, &val, sizeof(val)));
  455. break;
  456. default:
  457. return upb_append_unknown(d, frame);
  458. }
  459. upb_decode_setpresent(frame, field);
  460. return true;
  461. }
  462. static bool upb_decode_32bitfield(upb_decstate *d, upb_decframe *frame,
  463. const upb_msglayout_field *field) {
  464. uint32_t val;
  465. CHK(upb_decode_32bit(&d->ptr, d->limit, &val));
  466. switch (field->descriptortype) {
  467. case UPB_DESCRIPTOR_TYPE_FLOAT:
  468. case UPB_DESCRIPTOR_TYPE_FIXED32:
  469. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  470. CHK(upb_decode_addval(frame, field, &val, sizeof(val)));
  471. break;
  472. default:
  473. return upb_append_unknown(d, frame);
  474. }
  475. upb_decode_setpresent(frame, field);
  476. return true;
  477. }
  478. static bool upb_decode_fixedpacked(upb_decstate *d, upb_array *arr,
  479. uint32_t len, int elem_size) {
  480. size_t elements = len / elem_size;
  481. CHK((size_t)(elements * elem_size) == len);
  482. CHK(upb_array_add(arr, elements, elem_size, d->ptr, d->arena));
  483. d->ptr += len;
  484. return true;
  485. }
  486. static upb_strview upb_decode_strfield(upb_decstate *d, uint32_t len) {
  487. upb_strview ret;
  488. ret.data = d->ptr;
  489. ret.size = len;
  490. d->ptr += len;
  491. return ret;
  492. }
  493. static bool upb_decode_toarray(upb_decstate *d, upb_decframe *frame,
  494. const upb_msglayout_field *field, int len) {
  495. upb_array *arr = upb_getorcreatearr(frame, field);
  496. CHK(arr);
  497. #define VARINT_CASE(ctype, decode) \
  498. VARINT_CASE_EX(ctype, decode, decode)
  499. #define VARINT_CASE_EX(ctype, decode, dtype) \
  500. { \
  501. const char *ptr = d->ptr; \
  502. const char *limit = ptr + len; \
  503. while (ptr < limit) { \
  504. uint64_t val; \
  505. ctype decoded; \
  506. CHK(upb_decode_varint(&ptr, limit, &val)); \
  507. decoded = (decode)((dtype)val); \
  508. CHK(upb_array_add(arr, 1, sizeof(decoded), &decoded, d->arena)); \
  509. } \
  510. d->ptr = ptr; \
  511. return true; \
  512. }
  513. switch (field->descriptortype) {
  514. case UPB_DESCRIPTOR_TYPE_STRING:
  515. case UPB_DESCRIPTOR_TYPE_BYTES: {
  516. upb_strview str = upb_decode_strfield(d, len);
  517. return upb_array_add(arr, 1, sizeof(str), &str, d->arena);
  518. }
  519. case UPB_DESCRIPTOR_TYPE_FLOAT:
  520. case UPB_DESCRIPTOR_TYPE_FIXED32:
  521. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  522. return upb_decode_fixedpacked(d, arr, len, sizeof(int32_t));
  523. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  524. case UPB_DESCRIPTOR_TYPE_FIXED64:
  525. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  526. return upb_decode_fixedpacked(d, arr, len, sizeof(int64_t));
  527. case UPB_DESCRIPTOR_TYPE_INT32:
  528. case UPB_DESCRIPTOR_TYPE_UINT32:
  529. case UPB_DESCRIPTOR_TYPE_ENUM:
  530. VARINT_CASE(uint32_t, uint32_t);
  531. case UPB_DESCRIPTOR_TYPE_INT64:
  532. case UPB_DESCRIPTOR_TYPE_UINT64:
  533. VARINT_CASE(uint64_t, uint64_t);
  534. case UPB_DESCRIPTOR_TYPE_BOOL:
  535. VARINT_CASE(bool, bool);
  536. case UPB_DESCRIPTOR_TYPE_SINT32:
  537. VARINT_CASE_EX(int32_t, upb_zzdecode_32, uint32_t);
  538. case UPB_DESCRIPTOR_TYPE_SINT64:
  539. VARINT_CASE_EX(int64_t, upb_zzdecode_64, uint64_t);
  540. case UPB_DESCRIPTOR_TYPE_MESSAGE: {
  541. const upb_msglayout *subm;
  542. upb_msg *submsg = upb_addmsg(frame, field, &subm);
  543. CHK(submsg);
  544. return upb_decode_msgfield(d, submsg, subm, len);
  545. }
  546. case UPB_DESCRIPTOR_TYPE_GROUP:
  547. return upb_append_unknown(d, frame);
  548. }
  549. #undef VARINT_CASE
  550. UPB_UNREACHABLE();
  551. }
  552. static bool upb_decode_delimitedfield(upb_decstate *d, upb_decframe *frame,
  553. const upb_msglayout_field *field) {
  554. int len;
  555. CHK(upb_decode_string(&d->ptr, d->limit, &len));
  556. if (field->label == UPB_LABEL_REPEATED) {
  557. return upb_decode_toarray(d, frame, field, len);
  558. } else {
  559. switch (field->descriptortype) {
  560. case UPB_DESCRIPTOR_TYPE_STRING:
  561. case UPB_DESCRIPTOR_TYPE_BYTES: {
  562. upb_strview str = upb_decode_strfield(d, len);
  563. CHK(upb_decode_addval(frame, field, &str, sizeof(str)));
  564. break;
  565. }
  566. case UPB_DESCRIPTOR_TYPE_MESSAGE: {
  567. const upb_msglayout *subm;
  568. upb_msg *submsg = upb_getorcreatemsg(frame, field, &subm);
  569. CHK(submsg);
  570. CHK(upb_decode_msgfield(d, submsg, subm, len));
  571. break;
  572. }
  573. default:
  574. /* TODO(haberman): should we accept the last element of a packed? */
  575. d->ptr += len;
  576. return upb_append_unknown(d, frame);
  577. }
  578. upb_decode_setpresent(frame, field);
  579. return true;
  580. }
  581. }
  582. static const upb_msglayout_field *upb_find_field(const upb_msglayout *l,
  583. uint32_t field_number) {
  584. /* Lots of optimization opportunities here. */
  585. int i;
  586. for (i = 0; i < l->field_count; i++) {
  587. if (l->fields[i].number == field_number) {
  588. return &l->fields[i];
  589. }
  590. }
  591. return NULL; /* Unknown field. */
  592. }
  593. static bool upb_decode_field(upb_decstate *d, upb_decframe *frame) {
  594. uint32_t tag;
  595. const upb_msglayout_field *field;
  596. int field_number;
  597. d->field_start = d->ptr;
  598. CHK(upb_decode_varint32(&d->ptr, d->limit, &tag));
  599. field_number = tag >> 3;
  600. field = upb_find_field(frame->layout, field_number);
  601. if (field) {
  602. switch (tag & 7) {
  603. case UPB_WIRE_TYPE_VARINT:
  604. return upb_decode_varintfield(d, frame, field);
  605. case UPB_WIRE_TYPE_32BIT:
  606. return upb_decode_32bitfield(d, frame, field);
  607. case UPB_WIRE_TYPE_64BIT:
  608. return upb_decode_64bitfield(d, frame, field);
  609. case UPB_WIRE_TYPE_DELIMITED:
  610. return upb_decode_delimitedfield(d, frame, field);
  611. case UPB_WIRE_TYPE_START_GROUP: {
  612. const upb_msglayout *layout;
  613. upb_msg *group;
  614. if (field->label == UPB_LABEL_REPEATED) {
  615. group = upb_addmsg(frame, field, &layout);
  616. } else {
  617. group = upb_getorcreatemsg(frame, field, &layout);
  618. }
  619. return upb_decode_groupfield(d, group, layout, field_number);
  620. }
  621. case UPB_WIRE_TYPE_END_GROUP:
  622. d->end_group = field_number;
  623. return true;
  624. default:
  625. CHK(false);
  626. }
  627. } else {
  628. CHK(field_number != 0);
  629. CHK(upb_skip_unknownfielddata(d, tag, -1));
  630. CHK(upb_append_unknown(d, frame));
  631. return true;
  632. }
  633. }
  634. static bool upb_decode_message(upb_decstate *d, char *msg, const upb_msglayout *l) {
  635. upb_decframe frame;
  636. frame.msg = msg;
  637. frame.layout = l;
  638. frame.state = d;
  639. while (d->ptr < d->limit) {
  640. CHK(upb_decode_field(d, &frame));
  641. }
  642. return true;
  643. }
  644. bool upb_decode(const char *buf, size_t size, void *msg, const upb_msglayout *l,
  645. upb_arena *arena) {
  646. upb_decstate state;
  647. state.ptr = buf;
  648. state.limit = buf + size;
  649. state.arena = arena;
  650. state.depth = 64;
  651. state.end_group = 0;
  652. CHK(upb_decode_message(&state, msg, l));
  653. return state.end_group == 0;
  654. }
  655. #undef CHK
  656. /* We encode backwards, to avoid pre-computing lengths (one-pass encode). */
  657. #include <string.h>
  658. #define UPB_PB_VARINT_MAX_LEN 10
  659. #define CHK(x) do { if (!(x)) { return false; } } while(0)
  660. static size_t upb_encode_varint(uint64_t val, char *buf) {
  661. size_t i;
  662. if (val < 128) { buf[0] = val; return 1; }
  663. i = 0;
  664. while (val) {
  665. uint8_t byte = val & 0x7fU;
  666. val >>= 7;
  667. if (val) byte |= 0x80U;
  668. buf[i++] = byte;
  669. }
  670. return i;
  671. }
  672. static uint32_t upb_zzencode_32(int32_t n) { return ((uint32_t)n << 1) ^ (n >> 31); }
  673. static uint64_t upb_zzencode_64(int64_t n) { return ((uint64_t)n << 1) ^ (n >> 63); }
  674. typedef struct {
  675. upb_alloc *alloc;
  676. char *buf, *ptr, *limit;
  677. } upb_encstate;
  678. static size_t upb_roundup_pow2(size_t bytes) {
  679. size_t ret = 128;
  680. while (ret < bytes) {
  681. ret *= 2;
  682. }
  683. return ret;
  684. }
  685. static bool upb_encode_growbuffer(upb_encstate *e, size_t bytes) {
  686. size_t old_size = e->limit - e->buf;
  687. size_t new_size = upb_roundup_pow2(bytes + (e->limit - e->ptr));
  688. char *new_buf = upb_realloc(e->alloc, e->buf, old_size, new_size);
  689. CHK(new_buf);
  690. /* We want previous data at the end, realloc() put it at the beginning. */
  691. if (old_size > 0) {
  692. memmove(new_buf + new_size - old_size, e->buf, old_size);
  693. }
  694. e->ptr = new_buf + new_size - (e->limit - e->ptr);
  695. e->limit = new_buf + new_size;
  696. e->buf = new_buf;
  697. return true;
  698. }
  699. /* Call to ensure that at least "bytes" bytes are available for writing at
  700. * e->ptr. Returns false if the bytes could not be allocated. */
  701. static bool upb_encode_reserve(upb_encstate *e, size_t bytes) {
  702. CHK(UPB_LIKELY((size_t)(e->ptr - e->buf) >= bytes) ||
  703. upb_encode_growbuffer(e, bytes));
  704. e->ptr -= bytes;
  705. return true;
  706. }
  707. /* Writes the given bytes to the buffer, handling reserve/advance. */
  708. static bool upb_put_bytes(upb_encstate *e, const void *data, size_t len) {
  709. CHK(upb_encode_reserve(e, len));
  710. memcpy(e->ptr, data, len);
  711. return true;
  712. }
  713. static bool upb_put_fixed64(upb_encstate *e, uint64_t val) {
  714. /* TODO(haberman): byte-swap for big endian. */
  715. return upb_put_bytes(e, &val, sizeof(uint64_t));
  716. }
  717. static bool upb_put_fixed32(upb_encstate *e, uint32_t val) {
  718. /* TODO(haberman): byte-swap for big endian. */
  719. return upb_put_bytes(e, &val, sizeof(uint32_t));
  720. }
  721. static bool upb_put_varint(upb_encstate *e, uint64_t val) {
  722. size_t len;
  723. char *start;
  724. CHK(upb_encode_reserve(e, UPB_PB_VARINT_MAX_LEN));
  725. len = upb_encode_varint(val, e->ptr);
  726. start = e->ptr + UPB_PB_VARINT_MAX_LEN - len;
  727. memmove(start, e->ptr, len);
  728. e->ptr = start;
  729. return true;
  730. }
  731. static bool upb_put_double(upb_encstate *e, double d) {
  732. uint64_t u64;
  733. UPB_ASSERT(sizeof(double) == sizeof(uint64_t));
  734. memcpy(&u64, &d, sizeof(uint64_t));
  735. return upb_put_fixed64(e, u64);
  736. }
  737. static bool upb_put_float(upb_encstate *e, float d) {
  738. uint32_t u32;
  739. UPB_ASSERT(sizeof(float) == sizeof(uint32_t));
  740. memcpy(&u32, &d, sizeof(uint32_t));
  741. return upb_put_fixed32(e, u32);
  742. }
  743. static uint32_t upb_readcase(const char *msg, const upb_msglayout_field *f) {
  744. uint32_t ret;
  745. uint32_t offset = ~f->presence;
  746. memcpy(&ret, msg + offset, sizeof(ret));
  747. return ret;
  748. }
  749. static bool upb_readhasbit(const char *msg, const upb_msglayout_field *f) {
  750. uint32_t hasbit = f->presence;
  751. UPB_ASSERT(f->presence > 0);
  752. return msg[hasbit / 8] & (1 << (hasbit % 8));
  753. }
  754. static bool upb_put_tag(upb_encstate *e, int field_number, int wire_type) {
  755. return upb_put_varint(e, (field_number << 3) | wire_type);
  756. }
  757. static bool upb_put_fixedarray(upb_encstate *e, const upb_array *arr,
  758. size_t size) {
  759. size_t bytes = arr->len * size;
  760. return upb_put_bytes(e, arr->data, bytes) && upb_put_varint(e, bytes);
  761. }
  762. bool upb_encode_message(upb_encstate *e, const char *msg,
  763. const upb_msglayout *m, size_t *size);
  764. static bool upb_encode_array(upb_encstate *e, const char *field_mem,
  765. const upb_msglayout *m,
  766. const upb_msglayout_field *f) {
  767. const upb_array *arr = *(const upb_array**)field_mem;
  768. if (arr == NULL || arr->len == 0) {
  769. return true;
  770. }
  771. #define VARINT_CASE(ctype, encode) { \
  772. ctype *start = arr->data; \
  773. ctype *ptr = start + arr->len; \
  774. size_t pre_len = e->limit - e->ptr; \
  775. do { \
  776. ptr--; \
  777. CHK(upb_put_varint(e, encode)); \
  778. } while (ptr != start); \
  779. CHK(upb_put_varint(e, e->limit - e->ptr - pre_len)); \
  780. } \
  781. break; \
  782. do { ; } while(0)
  783. switch (f->descriptortype) {
  784. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  785. CHK(upb_put_fixedarray(e, arr, sizeof(double)));
  786. break;
  787. case UPB_DESCRIPTOR_TYPE_FLOAT:
  788. CHK(upb_put_fixedarray(e, arr, sizeof(float)));
  789. break;
  790. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  791. case UPB_DESCRIPTOR_TYPE_FIXED64:
  792. CHK(upb_put_fixedarray(e, arr, sizeof(uint64_t)));
  793. break;
  794. case UPB_DESCRIPTOR_TYPE_FIXED32:
  795. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  796. CHK(upb_put_fixedarray(e, arr, sizeof(uint32_t)));
  797. break;
  798. case UPB_DESCRIPTOR_TYPE_INT64:
  799. case UPB_DESCRIPTOR_TYPE_UINT64:
  800. VARINT_CASE(uint64_t, *ptr);
  801. case UPB_DESCRIPTOR_TYPE_UINT32:
  802. VARINT_CASE(uint32_t, *ptr);
  803. case UPB_DESCRIPTOR_TYPE_INT32:
  804. case UPB_DESCRIPTOR_TYPE_ENUM:
  805. VARINT_CASE(int32_t, (int64_t)*ptr);
  806. case UPB_DESCRIPTOR_TYPE_BOOL:
  807. VARINT_CASE(bool, *ptr);
  808. case UPB_DESCRIPTOR_TYPE_SINT32:
  809. VARINT_CASE(int32_t, upb_zzencode_32(*ptr));
  810. case UPB_DESCRIPTOR_TYPE_SINT64:
  811. VARINT_CASE(int64_t, upb_zzencode_64(*ptr));
  812. case UPB_DESCRIPTOR_TYPE_STRING:
  813. case UPB_DESCRIPTOR_TYPE_BYTES: {
  814. upb_strview *start = arr->data;
  815. upb_strview *ptr = start + arr->len;
  816. do {
  817. ptr--;
  818. CHK(upb_put_bytes(e, ptr->data, ptr->size) &&
  819. upb_put_varint(e, ptr->size) &&
  820. upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
  821. } while (ptr != start);
  822. return true;
  823. }
  824. case UPB_DESCRIPTOR_TYPE_GROUP: {
  825. void **start = arr->data;
  826. void **ptr = start + arr->len;
  827. const upb_msglayout *subm = m->submsgs[f->submsg_index];
  828. do {
  829. size_t size;
  830. ptr--;
  831. CHK(upb_put_tag(e, f->number, UPB_WIRE_TYPE_END_GROUP) &&
  832. upb_encode_message(e, *ptr, subm, &size) &&
  833. upb_put_tag(e, f->number, UPB_WIRE_TYPE_START_GROUP));
  834. } while (ptr != start);
  835. return true;
  836. }
  837. case UPB_DESCRIPTOR_TYPE_MESSAGE: {
  838. void **start = arr->data;
  839. void **ptr = start + arr->len;
  840. const upb_msglayout *subm = m->submsgs[f->submsg_index];
  841. do {
  842. size_t size;
  843. ptr--;
  844. CHK(upb_encode_message(e, *ptr, subm, &size) &&
  845. upb_put_varint(e, size) &&
  846. upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
  847. } while (ptr != start);
  848. return true;
  849. }
  850. }
  851. #undef VARINT_CASE
  852. /* We encode all primitive arrays as packed, regardless of what was specified
  853. * in the .proto file. Could special case 1-sized arrays. */
  854. CHK(upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
  855. return true;
  856. }
  857. static bool upb_encode_scalarfield(upb_encstate *e, const char *field_mem,
  858. const upb_msglayout *m,
  859. const upb_msglayout_field *f,
  860. bool skip_zero_value) {
  861. #define CASE(ctype, type, wire_type, encodeval) do { \
  862. ctype val = *(ctype*)field_mem; \
  863. if (skip_zero_value && val == 0) { \
  864. return true; \
  865. } \
  866. return upb_put_ ## type(e, encodeval) && \
  867. upb_put_tag(e, f->number, wire_type); \
  868. } while(0)
  869. switch (f->descriptortype) {
  870. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  871. CASE(double, double, UPB_WIRE_TYPE_64BIT, val);
  872. case UPB_DESCRIPTOR_TYPE_FLOAT:
  873. CASE(float, float, UPB_WIRE_TYPE_32BIT, val);
  874. case UPB_DESCRIPTOR_TYPE_INT64:
  875. case UPB_DESCRIPTOR_TYPE_UINT64:
  876. CASE(uint64_t, varint, UPB_WIRE_TYPE_VARINT, val);
  877. case UPB_DESCRIPTOR_TYPE_UINT32:
  878. CASE(uint32_t, varint, UPB_WIRE_TYPE_VARINT, val);
  879. case UPB_DESCRIPTOR_TYPE_INT32:
  880. case UPB_DESCRIPTOR_TYPE_ENUM:
  881. CASE(int32_t, varint, UPB_WIRE_TYPE_VARINT, (int64_t)val);
  882. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  883. case UPB_DESCRIPTOR_TYPE_FIXED64:
  884. CASE(uint64_t, fixed64, UPB_WIRE_TYPE_64BIT, val);
  885. case UPB_DESCRIPTOR_TYPE_FIXED32:
  886. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  887. CASE(uint32_t, fixed32, UPB_WIRE_TYPE_32BIT, val);
  888. case UPB_DESCRIPTOR_TYPE_BOOL:
  889. CASE(bool, varint, UPB_WIRE_TYPE_VARINT, val);
  890. case UPB_DESCRIPTOR_TYPE_SINT32:
  891. CASE(int32_t, varint, UPB_WIRE_TYPE_VARINT, upb_zzencode_32(val));
  892. case UPB_DESCRIPTOR_TYPE_SINT64:
  893. CASE(int64_t, varint, UPB_WIRE_TYPE_VARINT, upb_zzencode_64(val));
  894. case UPB_DESCRIPTOR_TYPE_STRING:
  895. case UPB_DESCRIPTOR_TYPE_BYTES: {
  896. upb_strview view = *(upb_strview*)field_mem;
  897. if (skip_zero_value && view.size == 0) {
  898. return true;
  899. }
  900. return upb_put_bytes(e, view.data, view.size) &&
  901. upb_put_varint(e, view.size) &&
  902. upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED);
  903. }
  904. case UPB_DESCRIPTOR_TYPE_GROUP: {
  905. size_t size;
  906. void *submsg = *(void **)field_mem;
  907. const upb_msglayout *subm = m->submsgs[f->submsg_index];
  908. if (submsg == NULL) {
  909. return true;
  910. }
  911. return upb_put_tag(e, f->number, UPB_WIRE_TYPE_END_GROUP) &&
  912. upb_encode_message(e, submsg, subm, &size) &&
  913. upb_put_tag(e, f->number, UPB_WIRE_TYPE_START_GROUP);
  914. }
  915. case UPB_DESCRIPTOR_TYPE_MESSAGE: {
  916. size_t size;
  917. void *submsg = *(void **)field_mem;
  918. const upb_msglayout *subm = m->submsgs[f->submsg_index];
  919. if (submsg == NULL) {
  920. return true;
  921. }
  922. return upb_encode_message(e, submsg, subm, &size) &&
  923. upb_put_varint(e, size) &&
  924. upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED);
  925. }
  926. }
  927. #undef CASE
  928. UPB_UNREACHABLE();
  929. }
  930. bool upb_encode_message(upb_encstate *e, const char *msg,
  931. const upb_msglayout *m, size_t *size) {
  932. int i;
  933. size_t pre_len = e->limit - e->ptr;
  934. const char *unknown;
  935. size_t unknown_size;
  936. for (i = m->field_count - 1; i >= 0; i--) {
  937. const upb_msglayout_field *f = &m->fields[i];
  938. if (f->label == UPB_LABEL_REPEATED) {
  939. CHK(upb_encode_array(e, msg + f->offset, m, f));
  940. } else {
  941. bool skip_empty = false;
  942. if (f->presence == 0) {
  943. /* Proto3 presence. */
  944. skip_empty = true;
  945. } else if (f->presence > 0) {
  946. /* Proto2 presence: hasbit. */
  947. if (!upb_readhasbit(msg, f)) {
  948. continue;
  949. }
  950. } else {
  951. /* Field is in a oneof. */
  952. if (upb_readcase(msg, f) != f->number) {
  953. continue;
  954. }
  955. }
  956. CHK(upb_encode_scalarfield(e, msg + f->offset, m, f, skip_empty));
  957. }
  958. }
  959. unknown = upb_msg_getunknown(msg, &unknown_size);
  960. if (unknown) {
  961. upb_put_bytes(e, unknown, unknown_size);
  962. }
  963. *size = (e->limit - e->ptr) - pre_len;
  964. return true;
  965. }
  966. char *upb_encode(const void *msg, const upb_msglayout *m, upb_arena *arena,
  967. size_t *size) {
  968. upb_encstate e;
  969. e.alloc = upb_arena_alloc(arena);
  970. e.buf = NULL;
  971. e.limit = NULL;
  972. e.ptr = NULL;
  973. if (!upb_encode_message(&e, msg, m, size)) {
  974. *size = 0;
  975. return NULL;
  976. }
  977. *size = e.limit - e.ptr;
  978. if (*size == 0) {
  979. static char ch;
  980. return &ch;
  981. } else {
  982. UPB_ASSERT(e.ptr);
  983. return e.ptr;
  984. }
  985. }
  986. #undef CHK
  987. #define VOIDPTR_AT(msg, ofs) (void*)((char*)msg + (int)ofs)
  988. /* Internal members of a upb_msg. We can change this without breaking binary
  989. * compatibility. We put these before the user's data. The user's upb_msg*
  990. * points after the upb_msg_internal. */
  991. /* Used when a message is not extendable. */
  992. typedef struct {
  993. char *unknown;
  994. size_t unknown_len;
  995. size_t unknown_size;
  996. } upb_msg_internal;
  997. /* Used when a message is extendable. */
  998. typedef struct {
  999. upb_inttable *extdict;
  1000. upb_msg_internal base;
  1001. } upb_msg_internal_withext;
  1002. static int upb_msg_internalsize(const upb_msglayout *l) {
  1003. return sizeof(upb_msg_internal) - l->extendable * sizeof(void *);
  1004. }
  1005. static size_t upb_msg_sizeof(const upb_msglayout *l) {
  1006. return l->size + upb_msg_internalsize(l);
  1007. }
  1008. static upb_msg_internal *upb_msg_getinternal(upb_msg *msg) {
  1009. return VOIDPTR_AT(msg, -sizeof(upb_msg_internal));
  1010. }
  1011. static const upb_msg_internal *upb_msg_getinternal_const(const upb_msg *msg) {
  1012. return VOIDPTR_AT(msg, -sizeof(upb_msg_internal));
  1013. }
  1014. static upb_msg_internal_withext *upb_msg_getinternalwithext(
  1015. upb_msg *msg, const upb_msglayout *l) {
  1016. UPB_ASSERT(l->extendable);
  1017. return VOIDPTR_AT(msg, -sizeof(upb_msg_internal_withext));
  1018. }
  1019. upb_msg *upb_msg_new(const upb_msglayout *l, upb_arena *a) {
  1020. upb_alloc *alloc = upb_arena_alloc(a);
  1021. void *mem = upb_malloc(alloc, upb_msg_sizeof(l));
  1022. upb_msg_internal *in;
  1023. upb_msg *msg;
  1024. if (!mem) {
  1025. return NULL;
  1026. }
  1027. msg = VOIDPTR_AT(mem, upb_msg_internalsize(l));
  1028. /* Initialize normal members. */
  1029. memset(msg, 0, l->size);
  1030. /* Initialize internal members. */
  1031. in = upb_msg_getinternal(msg);
  1032. in->unknown = NULL;
  1033. in->unknown_len = 0;
  1034. in->unknown_size = 0;
  1035. if (l->extendable) {
  1036. upb_msg_getinternalwithext(msg, l)->extdict = NULL;
  1037. }
  1038. return msg;
  1039. }
  1040. upb_array *upb_array_new(upb_arena *a) {
  1041. upb_array *ret = upb_arena_malloc(a, sizeof(upb_array));
  1042. if (!ret) {
  1043. return NULL;
  1044. }
  1045. ret->data = NULL;
  1046. ret->len = 0;
  1047. ret->size = 0;
  1048. return ret;
  1049. }
  1050. void upb_msg_addunknown(upb_msg *msg, const char *data, size_t len,
  1051. upb_arena *arena) {
  1052. upb_msg_internal *in = upb_msg_getinternal(msg);
  1053. if (len > in->unknown_size - in->unknown_len) {
  1054. upb_alloc *alloc = upb_arena_alloc(arena);
  1055. size_t need = in->unknown_size + len;
  1056. size_t newsize = UPB_MAX(in->unknown_size * 2, need);
  1057. in->unknown = upb_realloc(alloc, in->unknown, in->unknown_size, newsize);
  1058. in->unknown_size = newsize;
  1059. }
  1060. memcpy(in->unknown + in->unknown_len, data, len);
  1061. in->unknown_len += len;
  1062. }
  1063. const char *upb_msg_getunknown(const upb_msg *msg, size_t *len) {
  1064. const upb_msg_internal* in = upb_msg_getinternal_const(msg);
  1065. *len = in->unknown_len;
  1066. return in->unknown;
  1067. }
  1068. #undef VOIDPTR_AT
  1069. #ifdef UPB_MSVC_VSNPRINTF
  1070. /* Visual C++ earlier than 2015 doesn't have standard C99 snprintf and
  1071. * vsnprintf. To support them, missing functions are manually implemented
  1072. * using the existing secure functions. */
  1073. int msvc_vsnprintf(char* s, size_t n, const char* format, va_list arg) {
  1074. if (!s) {
  1075. return _vscprintf(format, arg);
  1076. }
  1077. int ret = _vsnprintf_s(s, n, _TRUNCATE, format, arg);
  1078. if (ret < 0) {
  1079. ret = _vscprintf(format, arg);
  1080. }
  1081. return ret;
  1082. }
  1083. int msvc_snprintf(char* s, size_t n, const char* format, ...) {
  1084. va_list arg;
  1085. va_start(arg, format);
  1086. int ret = msvc_vsnprintf(s, n, format, arg);
  1087. va_end(arg);
  1088. return ret;
  1089. }
  1090. #endif
  1091. /*
  1092. ** upb_table Implementation
  1093. **
  1094. ** Implementation is heavily inspired by Lua's ltable.c.
  1095. */
  1096. #include <string.h>
  1097. #define UPB_MAXARRSIZE 16 /* 64k. */
  1098. /* From Chromium. */
  1099. #define ARRAY_SIZE(x) \
  1100. ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x])))))
  1101. static void upb_check_alloc(upb_table *t, upb_alloc *a) {
  1102. UPB_UNUSED(t);
  1103. UPB_UNUSED(a);
  1104. UPB_ASSERT_DEBUGVAR(t->alloc == a);
  1105. }
  1106. static const double MAX_LOAD = 0.85;
  1107. /* The minimum utilization of the array part of a mixed hash/array table. This
  1108. * is a speed/memory-usage tradeoff (though it's not straightforward because of
  1109. * cache effects). The lower this is, the more memory we'll use. */
  1110. static const double MIN_DENSITY = 0.1;
  1111. bool is_pow2(uint64_t v) { return v == 0 || (v & (v - 1)) == 0; }
  1112. int log2ceil(uint64_t v) {
  1113. int ret = 0;
  1114. bool pow2 = is_pow2(v);
  1115. while (v >>= 1) ret++;
  1116. ret = pow2 ? ret : ret + 1; /* Ceiling. */
  1117. return UPB_MIN(UPB_MAXARRSIZE, ret);
  1118. }
  1119. char *upb_strdup(const char *s, upb_alloc *a) {
  1120. return upb_strdup2(s, strlen(s), a);
  1121. }
  1122. char *upb_strdup2(const char *s, size_t len, upb_alloc *a) {
  1123. size_t n;
  1124. char *p;
  1125. /* Prevent overflow errors. */
  1126. if (len == SIZE_MAX) return NULL;
  1127. /* Always null-terminate, even if binary data; but don't rely on the input to
  1128. * have a null-terminating byte since it may be a raw binary buffer. */
  1129. n = len + 1;
  1130. p = upb_malloc(a, n);
  1131. if (p) {
  1132. memcpy(p, s, len);
  1133. p[len] = 0;
  1134. }
  1135. return p;
  1136. }
  1137. /* A type to represent the lookup key of either a strtable or an inttable. */
  1138. typedef union {
  1139. uintptr_t num;
  1140. struct {
  1141. const char *str;
  1142. size_t len;
  1143. } str;
  1144. } lookupkey_t;
  1145. static lookupkey_t strkey2(const char *str, size_t len) {
  1146. lookupkey_t k;
  1147. k.str.str = str;
  1148. k.str.len = len;
  1149. return k;
  1150. }
  1151. static lookupkey_t intkey(uintptr_t key) {
  1152. lookupkey_t k;
  1153. k.num = key;
  1154. return k;
  1155. }
  1156. typedef uint32_t hashfunc_t(upb_tabkey key);
  1157. typedef bool eqlfunc_t(upb_tabkey k1, lookupkey_t k2);
  1158. /* Base table (shared code) ***************************************************/
  1159. /* For when we need to cast away const. */
  1160. static upb_tabent *mutable_entries(upb_table *t) {
  1161. return (upb_tabent*)t->entries;
  1162. }
  1163. static bool isfull(upb_table *t) {
  1164. if (upb_table_size(t) == 0) {
  1165. return true;
  1166. } else {
  1167. return ((double)(t->count + 1) / upb_table_size(t)) > MAX_LOAD;
  1168. }
  1169. }
  1170. static bool init(upb_table *t, upb_ctype_t ctype, uint8_t size_lg2,
  1171. upb_alloc *a) {
  1172. size_t bytes;
  1173. t->count = 0;
  1174. t->ctype = ctype;
  1175. t->size_lg2 = size_lg2;
  1176. t->mask = upb_table_size(t) ? upb_table_size(t) - 1 : 0;
  1177. #ifndef NDEBUG
  1178. t->alloc = a;
  1179. #endif
  1180. bytes = upb_table_size(t) * sizeof(upb_tabent);
  1181. if (bytes > 0) {
  1182. t->entries = upb_malloc(a, bytes);
  1183. if (!t->entries) return false;
  1184. memset(mutable_entries(t), 0, bytes);
  1185. } else {
  1186. t->entries = NULL;
  1187. }
  1188. return true;
  1189. }
  1190. static void uninit(upb_table *t, upb_alloc *a) {
  1191. upb_check_alloc(t, a);
  1192. upb_free(a, mutable_entries(t));
  1193. }
  1194. static upb_tabent *emptyent(upb_table *t) {
  1195. upb_tabent *e = mutable_entries(t) + upb_table_size(t);
  1196. while (1) { if (upb_tabent_isempty(--e)) return e; UPB_ASSERT(e > t->entries); }
  1197. }
  1198. static upb_tabent *getentry_mutable(upb_table *t, uint32_t hash) {
  1199. return (upb_tabent*)upb_getentry(t, hash);
  1200. }
  1201. static const upb_tabent *findentry(const upb_table *t, lookupkey_t key,
  1202. uint32_t hash, eqlfunc_t *eql) {
  1203. const upb_tabent *e;
  1204. if (t->size_lg2 == 0) return NULL;
  1205. e = upb_getentry(t, hash);
  1206. if (upb_tabent_isempty(e)) return NULL;
  1207. while (1) {
  1208. if (eql(e->key, key)) return e;
  1209. if ((e = e->next) == NULL) return NULL;
  1210. }
  1211. }
  1212. static upb_tabent *findentry_mutable(upb_table *t, lookupkey_t key,
  1213. uint32_t hash, eqlfunc_t *eql) {
  1214. return (upb_tabent*)findentry(t, key, hash, eql);
  1215. }
  1216. static bool lookup(const upb_table *t, lookupkey_t key, upb_value *v,
  1217. uint32_t hash, eqlfunc_t *eql) {
  1218. const upb_tabent *e = findentry(t, key, hash, eql);
  1219. if (e) {
  1220. if (v) {
  1221. _upb_value_setval(v, e->val.val, t->ctype);
  1222. }
  1223. return true;
  1224. } else {
  1225. return false;
  1226. }
  1227. }
  1228. /* The given key must not already exist in the table. */
  1229. static void insert(upb_table *t, lookupkey_t key, upb_tabkey tabkey,
  1230. upb_value val, uint32_t hash,
  1231. hashfunc_t *hashfunc, eqlfunc_t *eql) {
  1232. upb_tabent *mainpos_e;
  1233. upb_tabent *our_e;
  1234. UPB_ASSERT(findentry(t, key, hash, eql) == NULL);
  1235. UPB_ASSERT_DEBUGVAR(val.ctype == t->ctype);
  1236. t->count++;
  1237. mainpos_e = getentry_mutable(t, hash);
  1238. our_e = mainpos_e;
  1239. if (upb_tabent_isempty(mainpos_e)) {
  1240. /* Our main position is empty; use it. */
  1241. our_e->next = NULL;
  1242. } else {
  1243. /* Collision. */
  1244. upb_tabent *new_e = emptyent(t);
  1245. /* Head of collider's chain. */
  1246. upb_tabent *chain = getentry_mutable(t, hashfunc(mainpos_e->key));
  1247. if (chain == mainpos_e) {
  1248. /* Existing ent is in its main posisiton (it has the same hash as us, and
  1249. * is the head of our chain). Insert to new ent and append to this chain. */
  1250. new_e->next = mainpos_e->next;
  1251. mainpos_e->next = new_e;
  1252. our_e = new_e;
  1253. } else {
  1254. /* Existing ent is not in its main position (it is a node in some other
  1255. * chain). This implies that no existing ent in the table has our hash.
  1256. * Evict it (updating its chain) and use its ent for head of our chain. */
  1257. *new_e = *mainpos_e; /* copies next. */
  1258. while (chain->next != mainpos_e) {
  1259. chain = (upb_tabent*)chain->next;
  1260. UPB_ASSERT(chain);
  1261. }
  1262. chain->next = new_e;
  1263. our_e = mainpos_e;
  1264. our_e->next = NULL;
  1265. }
  1266. }
  1267. our_e->key = tabkey;
  1268. our_e->val.val = val.val;
  1269. UPB_ASSERT(findentry(t, key, hash, eql) == our_e);
  1270. }
  1271. static bool rm(upb_table *t, lookupkey_t key, upb_value *val,
  1272. upb_tabkey *removed, uint32_t hash, eqlfunc_t *eql) {
  1273. upb_tabent *chain = getentry_mutable(t, hash);
  1274. if (upb_tabent_isempty(chain)) return false;
  1275. if (eql(chain->key, key)) {
  1276. /* Element to remove is at the head of its chain. */
  1277. t->count--;
  1278. if (val) _upb_value_setval(val, chain->val.val, t->ctype);
  1279. if (removed) *removed = chain->key;
  1280. if (chain->next) {
  1281. upb_tabent *move = (upb_tabent*)chain->next;
  1282. *chain = *move;
  1283. move->key = 0; /* Make the slot empty. */
  1284. } else {
  1285. chain->key = 0; /* Make the slot empty. */
  1286. }
  1287. return true;
  1288. } else {
  1289. /* Element to remove is either in a non-head position or not in the
  1290. * table. */
  1291. while (chain->next && !eql(chain->next->key, key)) {
  1292. chain = (upb_tabent*)chain->next;
  1293. }
  1294. if (chain->next) {
  1295. /* Found element to remove. */
  1296. upb_tabent *rm = (upb_tabent*)chain->next;
  1297. t->count--;
  1298. if (val) _upb_value_setval(val, chain->next->val.val, t->ctype);
  1299. if (removed) *removed = rm->key;
  1300. rm->key = 0; /* Make the slot empty. */
  1301. chain->next = rm->next;
  1302. return true;
  1303. } else {
  1304. /* Element to remove is not in the table. */
  1305. return false;
  1306. }
  1307. }
  1308. }
  1309. static size_t next(const upb_table *t, size_t i) {
  1310. do {
  1311. if (++i >= upb_table_size(t))
  1312. return SIZE_MAX;
  1313. } while(upb_tabent_isempty(&t->entries[i]));
  1314. return i;
  1315. }
  1316. static size_t begin(const upb_table *t) {
  1317. return next(t, -1);
  1318. }
  1319. /* upb_strtable ***************************************************************/
  1320. /* A simple "subclass" of upb_table that only adds a hash function for strings. */
  1321. static upb_tabkey strcopy(lookupkey_t k2, upb_alloc *a) {
  1322. uint32_t len = (uint32_t) k2.str.len;
  1323. char *str = upb_malloc(a, k2.str.len + sizeof(uint32_t) + 1);
  1324. if (str == NULL) return 0;
  1325. memcpy(str, &len, sizeof(uint32_t));
  1326. memcpy(str + sizeof(uint32_t), k2.str.str, k2.str.len + 1);
  1327. return (uintptr_t)str;
  1328. }
  1329. static uint32_t strhash(upb_tabkey key) {
  1330. uint32_t len;
  1331. char *str = upb_tabstr(key, &len);
  1332. return upb_murmur_hash2(str, len, 0);
  1333. }
  1334. static bool streql(upb_tabkey k1, lookupkey_t k2) {
  1335. uint32_t len;
  1336. char *str = upb_tabstr(k1, &len);
  1337. return len == k2.str.len && memcmp(str, k2.str.str, len) == 0;
  1338. }
  1339. bool upb_strtable_init2(upb_strtable *t, upb_ctype_t ctype, upb_alloc *a) {
  1340. return init(&t->t, ctype, 2, a);
  1341. }
  1342. void upb_strtable_uninit2(upb_strtable *t, upb_alloc *a) {
  1343. size_t i;
  1344. for (i = 0; i < upb_table_size(&t->t); i++)
  1345. upb_free(a, (void*)t->t.entries[i].key);
  1346. uninit(&t->t, a);
  1347. }
  1348. bool upb_strtable_resize(upb_strtable *t, size_t size_lg2, upb_alloc *a) {
  1349. upb_strtable new_table;
  1350. upb_strtable_iter i;
  1351. upb_check_alloc(&t->t, a);
  1352. if (!init(&new_table.t, t->t.ctype, size_lg2, a))
  1353. return false;
  1354. upb_strtable_begin(&i, t);
  1355. for ( ; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  1356. upb_strtable_insert3(
  1357. &new_table,
  1358. upb_strtable_iter_key(&i),
  1359. upb_strtable_iter_keylength(&i),
  1360. upb_strtable_iter_value(&i),
  1361. a);
  1362. }
  1363. upb_strtable_uninit2(t, a);
  1364. *t = new_table;
  1365. return true;
  1366. }
  1367. bool upb_strtable_insert3(upb_strtable *t, const char *k, size_t len,
  1368. upb_value v, upb_alloc *a) {
  1369. lookupkey_t key;
  1370. upb_tabkey tabkey;
  1371. uint32_t hash;
  1372. upb_check_alloc(&t->t, a);
  1373. if (isfull(&t->t)) {
  1374. /* Need to resize. New table of double the size, add old elements to it. */
  1375. if (!upb_strtable_resize(t, t->t.size_lg2 + 1, a)) {
  1376. return false;
  1377. }
  1378. }
  1379. key = strkey2(k, len);
  1380. tabkey = strcopy(key, a);
  1381. if (tabkey == 0) return false;
  1382. hash = upb_murmur_hash2(key.str.str, key.str.len, 0);
  1383. insert(&t->t, key, tabkey, v, hash, &strhash, &streql);
  1384. return true;
  1385. }
  1386. bool upb_strtable_lookup2(const upb_strtable *t, const char *key, size_t len,
  1387. upb_value *v) {
  1388. uint32_t hash = upb_murmur_hash2(key, len, 0);
  1389. return lookup(&t->t, strkey2(key, len), v, hash, &streql);
  1390. }
  1391. bool upb_strtable_remove3(upb_strtable *t, const char *key, size_t len,
  1392. upb_value *val, upb_alloc *alloc) {
  1393. uint32_t hash = upb_murmur_hash2(key, len, 0);
  1394. upb_tabkey tabkey;
  1395. if (rm(&t->t, strkey2(key, len), val, &tabkey, hash, &streql)) {
  1396. upb_free(alloc, (void*)tabkey);
  1397. return true;
  1398. } else {
  1399. return false;
  1400. }
  1401. }
  1402. /* Iteration */
  1403. static const upb_tabent *str_tabent(const upb_strtable_iter *i) {
  1404. return &i->t->t.entries[i->index];
  1405. }
  1406. void upb_strtable_begin(upb_strtable_iter *i, const upb_strtable *t) {
  1407. i->t = t;
  1408. i->index = begin(&t->t);
  1409. }
  1410. void upb_strtable_next(upb_strtable_iter *i) {
  1411. i->index = next(&i->t->t, i->index);
  1412. }
  1413. bool upb_strtable_done(const upb_strtable_iter *i) {
  1414. if (!i->t) return true;
  1415. return i->index >= upb_table_size(&i->t->t) ||
  1416. upb_tabent_isempty(str_tabent(i));
  1417. }
  1418. const char *upb_strtable_iter_key(const upb_strtable_iter *i) {
  1419. UPB_ASSERT(!upb_strtable_done(i));
  1420. return upb_tabstr(str_tabent(i)->key, NULL);
  1421. }
  1422. size_t upb_strtable_iter_keylength(const upb_strtable_iter *i) {
  1423. uint32_t len;
  1424. UPB_ASSERT(!upb_strtable_done(i));
  1425. upb_tabstr(str_tabent(i)->key, &len);
  1426. return len;
  1427. }
  1428. upb_value upb_strtable_iter_value(const upb_strtable_iter *i) {
  1429. UPB_ASSERT(!upb_strtable_done(i));
  1430. return _upb_value_val(str_tabent(i)->val.val, i->t->t.ctype);
  1431. }
  1432. void upb_strtable_iter_setdone(upb_strtable_iter *i) {
  1433. i->t = NULL;
  1434. i->index = SIZE_MAX;
  1435. }
  1436. bool upb_strtable_iter_isequal(const upb_strtable_iter *i1,
  1437. const upb_strtable_iter *i2) {
  1438. if (upb_strtable_done(i1) && upb_strtable_done(i2))
  1439. return true;
  1440. return i1->t == i2->t && i1->index == i2->index;
  1441. }
  1442. /* upb_inttable ***************************************************************/
  1443. /* For inttables we use a hybrid structure where small keys are kept in an
  1444. * array and large keys are put in the hash table. */
  1445. static uint32_t inthash(upb_tabkey key) { return upb_inthash(key); }
  1446. static bool inteql(upb_tabkey k1, lookupkey_t k2) {
  1447. return k1 == k2.num;
  1448. }
  1449. static upb_tabval *mutable_array(upb_inttable *t) {
  1450. return (upb_tabval*)t->array;
  1451. }
  1452. static upb_tabval *inttable_val(upb_inttable *t, uintptr_t key) {
  1453. if (key < t->array_size) {
  1454. return upb_arrhas(t->array[key]) ? &(mutable_array(t)[key]) : NULL;
  1455. } else {
  1456. upb_tabent *e =
  1457. findentry_mutable(&t->t, intkey(key), upb_inthash(key), &inteql);
  1458. return e ? &e->val : NULL;
  1459. }
  1460. }
  1461. static const upb_tabval *inttable_val_const(const upb_inttable *t,
  1462. uintptr_t key) {
  1463. return inttable_val((upb_inttable*)t, key);
  1464. }
  1465. size_t upb_inttable_count(const upb_inttable *t) {
  1466. return t->t.count + t->array_count;
  1467. }
  1468. static void check(upb_inttable *t) {
  1469. UPB_UNUSED(t);
  1470. #if defined(UPB_DEBUG_TABLE) && !defined(NDEBUG)
  1471. {
  1472. /* This check is very expensive (makes inserts/deletes O(N)). */
  1473. size_t count = 0;
  1474. upb_inttable_iter i;
  1475. upb_inttable_begin(&i, t);
  1476. for(; !upb_inttable_done(&i); upb_inttable_next(&i), count++) {
  1477. UPB_ASSERT(upb_inttable_lookup(t, upb_inttable_iter_key(&i), NULL));
  1478. }
  1479. UPB_ASSERT(count == upb_inttable_count(t));
  1480. }
  1481. #endif
  1482. }
  1483. bool upb_inttable_sizedinit(upb_inttable *t, upb_ctype_t ctype,
  1484. size_t asize, int hsize_lg2, upb_alloc *a) {
  1485. size_t array_bytes;
  1486. if (!init(&t->t, ctype, hsize_lg2, a)) return false;
  1487. /* Always make the array part at least 1 long, so that we know key 0
  1488. * won't be in the hash part, which simplifies things. */
  1489. t->array_size = UPB_MAX(1, asize);
  1490. t->array_count = 0;
  1491. array_bytes = t->array_size * sizeof(upb_value);
  1492. t->array = upb_malloc(a, array_bytes);
  1493. if (!t->array) {
  1494. uninit(&t->t, a);
  1495. return false;
  1496. }
  1497. memset(mutable_array(t), 0xff, array_bytes);
  1498. check(t);
  1499. return true;
  1500. }
  1501. bool upb_inttable_init2(upb_inttable *t, upb_ctype_t ctype, upb_alloc *a) {
  1502. return upb_inttable_sizedinit(t, ctype, 0, 4, a);
  1503. }
  1504. void upb_inttable_uninit2(upb_inttable *t, upb_alloc *a) {
  1505. uninit(&t->t, a);
  1506. upb_free(a, mutable_array(t));
  1507. }
  1508. bool upb_inttable_insert2(upb_inttable *t, uintptr_t key, upb_value val,
  1509. upb_alloc *a) {
  1510. upb_tabval tabval;
  1511. tabval.val = val.val;
  1512. UPB_ASSERT(upb_arrhas(tabval)); /* This will reject (uint64_t)-1. Fix this. */
  1513. upb_check_alloc(&t->t, a);
  1514. if (key < t->array_size) {
  1515. UPB_ASSERT(!upb_arrhas(t->array[key]));
  1516. t->array_count++;
  1517. mutable_array(t)[key].val = val.val;
  1518. } else {
  1519. if (isfull(&t->t)) {
  1520. /* Need to resize the hash part, but we re-use the array part. */
  1521. size_t i;
  1522. upb_table new_table;
  1523. if (!init(&new_table, t->t.ctype, t->t.size_lg2 + 1, a)) {
  1524. return false;
  1525. }
  1526. for (i = begin(&t->t); i < upb_table_size(&t->t); i = next(&t->t, i)) {
  1527. const upb_tabent *e = &t->t.entries[i];
  1528. uint32_t hash;
  1529. upb_value v;
  1530. _upb_value_setval(&v, e->val.val, t->t.ctype);
  1531. hash = upb_inthash(e->key);
  1532. insert(&new_table, intkey(e->key), e->key, v, hash, &inthash, &inteql);
  1533. }
  1534. UPB_ASSERT(t->t.count == new_table.count);
  1535. uninit(&t->t, a);
  1536. t->t = new_table;
  1537. }
  1538. insert(&t->t, intkey(key), key, val, upb_inthash(key), &inthash, &inteql);
  1539. }
  1540. check(t);
  1541. return true;
  1542. }
  1543. bool upb_inttable_lookup(const upb_inttable *t, uintptr_t key, upb_value *v) {
  1544. const upb_tabval *table_v = inttable_val_const(t, key);
  1545. if (!table_v) return false;
  1546. if (v) _upb_value_setval(v, table_v->val, t->t.ctype);
  1547. return true;
  1548. }
  1549. bool upb_inttable_replace(upb_inttable *t, uintptr_t key, upb_value val) {
  1550. upb_tabval *table_v = inttable_val(t, key);
  1551. if (!table_v) return false;
  1552. table_v->val = val.val;
  1553. return true;
  1554. }
  1555. bool upb_inttable_remove(upb_inttable *t, uintptr_t key, upb_value *val) {
  1556. bool success;
  1557. if (key < t->array_size) {
  1558. if (upb_arrhas(t->array[key])) {
  1559. upb_tabval empty = UPB_TABVALUE_EMPTY_INIT;
  1560. t->array_count--;
  1561. if (val) {
  1562. _upb_value_setval(val, t->array[key].val, t->t.ctype);
  1563. }
  1564. mutable_array(t)[key] = empty;
  1565. success = true;
  1566. } else {
  1567. success = false;
  1568. }
  1569. } else {
  1570. success = rm(&t->t, intkey(key), val, NULL, upb_inthash(key), &inteql);
  1571. }
  1572. check(t);
  1573. return success;
  1574. }
  1575. bool upb_inttable_push2(upb_inttable *t, upb_value val, upb_alloc *a) {
  1576. upb_check_alloc(&t->t, a);
  1577. return upb_inttable_insert2(t, upb_inttable_count(t), val, a);
  1578. }
  1579. upb_value upb_inttable_pop(upb_inttable *t) {
  1580. upb_value val;
  1581. bool ok = upb_inttable_remove(t, upb_inttable_count(t) - 1, &val);
  1582. UPB_ASSERT(ok);
  1583. return val;
  1584. }
  1585. bool upb_inttable_insertptr2(upb_inttable *t, const void *key, upb_value val,
  1586. upb_alloc *a) {
  1587. upb_check_alloc(&t->t, a);
  1588. return upb_inttable_insert2(t, (uintptr_t)key, val, a);
  1589. }
  1590. bool upb_inttable_lookupptr(const upb_inttable *t, const void *key,
  1591. upb_value *v) {
  1592. return upb_inttable_lookup(t, (uintptr_t)key, v);
  1593. }
  1594. bool upb_inttable_removeptr(upb_inttable *t, const void *key, upb_value *val) {
  1595. return upb_inttable_remove(t, (uintptr_t)key, val);
  1596. }
  1597. void upb_inttable_compact2(upb_inttable *t, upb_alloc *a) {
  1598. /* A power-of-two histogram of the table keys. */
  1599. size_t counts[UPB_MAXARRSIZE + 1] = {0};
  1600. /* The max key in each bucket. */
  1601. uintptr_t max[UPB_MAXARRSIZE + 1] = {0};
  1602. upb_inttable_iter i;
  1603. size_t arr_count;
  1604. int size_lg2;
  1605. upb_inttable new_t;
  1606. upb_check_alloc(&t->t, a);
  1607. upb_inttable_begin(&i, t);
  1608. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  1609. uintptr_t key = upb_inttable_iter_key(&i);
  1610. int bucket = log2ceil(key);
  1611. max[bucket] = UPB_MAX(max[bucket], key);
  1612. counts[bucket]++;
  1613. }
  1614. /* Find the largest power of two that satisfies the MIN_DENSITY
  1615. * definition (while actually having some keys). */
  1616. arr_count = upb_inttable_count(t);
  1617. for (size_lg2 = ARRAY_SIZE(counts) - 1; size_lg2 > 0; size_lg2--) {
  1618. if (counts[size_lg2] == 0) {
  1619. /* We can halve again without losing any entries. */
  1620. continue;
  1621. } else if (arr_count >= (1 << size_lg2) * MIN_DENSITY) {
  1622. break;
  1623. }
  1624. arr_count -= counts[size_lg2];
  1625. }
  1626. UPB_ASSERT(arr_count <= upb_inttable_count(t));
  1627. {
  1628. /* Insert all elements into new, perfectly-sized table. */
  1629. size_t arr_size = max[size_lg2] + 1; /* +1 so arr[max] will fit. */
  1630. size_t hash_count = upb_inttable_count(t) - arr_count;
  1631. size_t hash_size = hash_count ? (hash_count / MAX_LOAD) + 1 : 0;
  1632. int hashsize_lg2 = log2ceil(hash_size);
  1633. upb_inttable_sizedinit(&new_t, t->t.ctype, arr_size, hashsize_lg2, a);
  1634. upb_inttable_begin(&i, t);
  1635. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  1636. uintptr_t k = upb_inttable_iter_key(&i);
  1637. upb_inttable_insert2(&new_t, k, upb_inttable_iter_value(&i), a);
  1638. }
  1639. UPB_ASSERT(new_t.array_size == arr_size);
  1640. UPB_ASSERT(new_t.t.size_lg2 == hashsize_lg2);
  1641. }
  1642. upb_inttable_uninit2(t, a);
  1643. *t = new_t;
  1644. }
  1645. /* Iteration. */
  1646. static const upb_tabent *int_tabent(const upb_inttable_iter *i) {
  1647. UPB_ASSERT(!i->array_part);
  1648. return &i->t->t.entries[i->index];
  1649. }
  1650. static upb_tabval int_arrent(const upb_inttable_iter *i) {
  1651. UPB_ASSERT(i->array_part);
  1652. return i->t->array[i->index];
  1653. }
  1654. void upb_inttable_begin(upb_inttable_iter *i, const upb_inttable *t) {
  1655. i->t = t;
  1656. i->index = -1;
  1657. i->array_part = true;
  1658. upb_inttable_next(i);
  1659. }
  1660. void upb_inttable_next(upb_inttable_iter *iter) {
  1661. const upb_inttable *t = iter->t;
  1662. if (iter->array_part) {
  1663. while (++iter->index < t->array_size) {
  1664. if (upb_arrhas(int_arrent(iter))) {
  1665. return;
  1666. }
  1667. }
  1668. iter->array_part = false;
  1669. iter->index = begin(&t->t);
  1670. } else {
  1671. iter->index = next(&t->t, iter->index);
  1672. }
  1673. }
  1674. bool upb_inttable_done(const upb_inttable_iter *i) {
  1675. if (!i->t) return true;
  1676. if (i->array_part) {
  1677. return i->index >= i->t->array_size ||
  1678. !upb_arrhas(int_arrent(i));
  1679. } else {
  1680. return i->index >= upb_table_size(&i->t->t) ||
  1681. upb_tabent_isempty(int_tabent(i));
  1682. }
  1683. }
  1684. uintptr_t upb_inttable_iter_key(const upb_inttable_iter *i) {
  1685. UPB_ASSERT(!upb_inttable_done(i));
  1686. return i->array_part ? i->index : int_tabent(i)->key;
  1687. }
  1688. upb_value upb_inttable_iter_value(const upb_inttable_iter *i) {
  1689. UPB_ASSERT(!upb_inttable_done(i));
  1690. return _upb_value_val(
  1691. i->array_part ? i->t->array[i->index].val : int_tabent(i)->val.val,
  1692. i->t->t.ctype);
  1693. }
  1694. void upb_inttable_iter_setdone(upb_inttable_iter *i) {
  1695. i->t = NULL;
  1696. i->index = SIZE_MAX;
  1697. i->array_part = false;
  1698. }
  1699. bool upb_inttable_iter_isequal(const upb_inttable_iter *i1,
  1700. const upb_inttable_iter *i2) {
  1701. if (upb_inttable_done(i1) && upb_inttable_done(i2))
  1702. return true;
  1703. return i1->t == i2->t && i1->index == i2->index &&
  1704. i1->array_part == i2->array_part;
  1705. }
  1706. #if defined(UPB_UNALIGNED_READS_OK) || defined(__s390x__)
  1707. /* -----------------------------------------------------------------------------
  1708. * MurmurHash2, by Austin Appleby (released as public domain).
  1709. * Reformatted and C99-ified by Joshua Haberman.
  1710. * Note - This code makes a few assumptions about how your machine behaves -
  1711. * 1. We can read a 4-byte value from any address without crashing
  1712. * 2. sizeof(int) == 4 (in upb this limitation is removed by using uint32_t
  1713. * And it has a few limitations -
  1714. * 1. It will not work incrementally.
  1715. * 2. It will not produce the same results on little-endian and big-endian
  1716. * machines. */
  1717. uint32_t upb_murmur_hash2(const void *key, size_t len, uint32_t seed) {
  1718. /* 'm' and 'r' are mixing constants generated offline.
  1719. * They're not really 'magic', they just happen to work well. */
  1720. const uint32_t m = 0x5bd1e995;
  1721. const int32_t r = 24;
  1722. /* Initialize the hash to a 'random' value */
  1723. uint32_t h = seed ^ len;
  1724. /* Mix 4 bytes at a time into the hash */
  1725. const uint8_t * data = (const uint8_t *)key;
  1726. while(len >= 4) {
  1727. uint32_t k = *(uint32_t *)data;
  1728. k *= m;
  1729. k ^= k >> r;
  1730. k *= m;
  1731. h *= m;
  1732. h ^= k;
  1733. data += 4;
  1734. len -= 4;
  1735. }
  1736. /* Handle the last few bytes of the input array */
  1737. switch(len) {
  1738. case 3: h ^= data[2] << 16;
  1739. case 2: h ^= data[1] << 8;
  1740. case 1: h ^= data[0]; h *= m;
  1741. };
  1742. /* Do a few final mixes of the hash to ensure the last few
  1743. * bytes are well-incorporated. */
  1744. h ^= h >> 13;
  1745. h *= m;
  1746. h ^= h >> 15;
  1747. return h;
  1748. }
  1749. #else /* !UPB_UNALIGNED_READS_OK */
  1750. /* -----------------------------------------------------------------------------
  1751. * MurmurHashAligned2, by Austin Appleby
  1752. * Same algorithm as MurmurHash2, but only does aligned reads - should be safer
  1753. * on certain platforms.
  1754. * Performance will be lower than MurmurHash2 */
  1755. #define MIX(h,k,m) { k *= m; k ^= k >> r; k *= m; h *= m; h ^= k; }
  1756. uint32_t upb_murmur_hash2(const void * key, size_t len, uint32_t seed) {
  1757. const uint32_t m = 0x5bd1e995;
  1758. const int32_t r = 24;
  1759. const uint8_t * data = (const uint8_t *)key;
  1760. uint32_t h = (uint32_t)(seed ^ len);
  1761. uint8_t align = (uintptr_t)data & 3;
  1762. if(align && (len >= 4)) {
  1763. /* Pre-load the temp registers */
  1764. uint32_t t = 0, d = 0;
  1765. int32_t sl;
  1766. int32_t sr;
  1767. switch(align) {
  1768. case 1: t |= data[2] << 16;
  1769. case 2: t |= data[1] << 8;
  1770. case 3: t |= data[0];
  1771. }
  1772. t <<= (8 * align);
  1773. data += 4-align;
  1774. len -= 4-align;
  1775. sl = 8 * (4-align);
  1776. sr = 8 * align;
  1777. /* Mix */
  1778. while(len >= 4) {
  1779. uint32_t k;
  1780. d = *(uint32_t *)data;
  1781. t = (t >> sr) | (d << sl);
  1782. k = t;
  1783. MIX(h,k,m);
  1784. t = d;
  1785. data += 4;
  1786. len -= 4;
  1787. }
  1788. /* Handle leftover data in temp registers */
  1789. d = 0;
  1790. if(len >= align) {
  1791. uint32_t k;
  1792. switch(align) {
  1793. case 3: d |= data[2] << 16;
  1794. case 2: d |= data[1] << 8;
  1795. case 1: d |= data[0];
  1796. }
  1797. k = (t >> sr) | (d << sl);
  1798. MIX(h,k,m);
  1799. data += align;
  1800. len -= align;
  1801. /* ----------
  1802. * Handle tail bytes */
  1803. switch(len) {
  1804. case 3: h ^= data[2] << 16;
  1805. case 2: h ^= data[1] << 8;
  1806. case 1: h ^= data[0]; h *= m;
  1807. };
  1808. } else {
  1809. switch(len) {
  1810. case 3: d |= data[2] << 16;
  1811. case 2: d |= data[1] << 8;
  1812. case 1: d |= data[0];
  1813. case 0: h ^= (t >> sr) | (d << sl); h *= m;
  1814. }
  1815. }
  1816. h ^= h >> 13;
  1817. h *= m;
  1818. h ^= h >> 15;
  1819. return h;
  1820. } else {
  1821. while(len >= 4) {
  1822. uint32_t k = *(uint32_t *)data;
  1823. MIX(h,k,m);
  1824. data += 4;
  1825. len -= 4;
  1826. }
  1827. /* ----------
  1828. * Handle tail bytes */
  1829. switch(len) {
  1830. case 3: h ^= data[2] << 16;
  1831. case 2: h ^= data[1] << 8;
  1832. case 1: h ^= data[0]; h *= m;
  1833. };
  1834. h ^= h >> 13;
  1835. h *= m;
  1836. h ^= h >> 15;
  1837. return h;
  1838. }
  1839. }
  1840. #undef MIX
  1841. #endif /* UPB_UNALIGNED_READS_OK */
  1842. #include <errno.h>
  1843. #include <stdarg.h>
  1844. #include <stddef.h>
  1845. #include <stdint.h>
  1846. #include <stdio.h>
  1847. #include <stdlib.h>
  1848. #include <string.h>
  1849. /* Guarantee null-termination and provide ellipsis truncation.
  1850. * It may be tempting to "optimize" this by initializing these final
  1851. * four bytes up-front and then being careful never to overwrite them,
  1852. * this is safer and simpler. */
  1853. static void nullz(upb_status *status) {
  1854. const char *ellipsis = "...";
  1855. size_t len = strlen(ellipsis);
  1856. UPB_ASSERT(sizeof(status->msg) > len);
  1857. memcpy(status->msg + sizeof(status->msg) - len, ellipsis, len);
  1858. }
  1859. /* upb_status *****************************************************************/
  1860. void upb_status_clear(upb_status *status) {
  1861. if (!status) return;
  1862. status->ok = true;
  1863. status->msg[0] = '\0';
  1864. }
  1865. bool upb_ok(const upb_status *status) { return status->ok; }
  1866. const char *upb_status_errmsg(const upb_status *status) { return status->msg; }
  1867. void upb_status_seterrmsg(upb_status *status, const char *msg) {
  1868. if (!status) return;
  1869. status->ok = false;
  1870. strncpy(status->msg, msg, sizeof(status->msg));
  1871. nullz(status);
  1872. }
  1873. void upb_status_seterrf(upb_status *status, const char *fmt, ...) {
  1874. va_list args;
  1875. va_start(args, fmt);
  1876. upb_status_vseterrf(status, fmt, args);
  1877. va_end(args);
  1878. }
  1879. void upb_status_vseterrf(upb_status *status, const char *fmt, va_list args) {
  1880. if (!status) return;
  1881. status->ok = false;
  1882. _upb_vsnprintf(status->msg, sizeof(status->msg), fmt, args);
  1883. nullz(status);
  1884. }
  1885. /* upb_alloc ******************************************************************/
  1886. static void *upb_global_allocfunc(upb_alloc *alloc, void *ptr, size_t oldsize,
  1887. size_t size) {
  1888. UPB_UNUSED(alloc);
  1889. UPB_UNUSED(oldsize);
  1890. if (size == 0) {
  1891. free(ptr);
  1892. return NULL;
  1893. } else {
  1894. return realloc(ptr, size);
  1895. }
  1896. }
  1897. upb_alloc upb_alloc_global = {&upb_global_allocfunc};
  1898. /* upb_arena ******************************************************************/
  1899. /* Be conservative and choose 16 in case anyone is using SSE. */
  1900. static const size_t maxalign = 16;
  1901. static size_t align_up_max(size_t size) {
  1902. return ((size + maxalign - 1) / maxalign) * maxalign;
  1903. }
  1904. struct upb_arena {
  1905. /* We implement the allocator interface.
  1906. * This must be the first member of upb_arena! */
  1907. upb_alloc alloc;
  1908. /* Allocator to allocate arena blocks. We are responsible for freeing these
  1909. * when we are destroyed. */
  1910. upb_alloc *block_alloc;
  1911. size_t bytes_allocated;
  1912. size_t next_block_size;
  1913. size_t max_block_size;
  1914. /* Linked list of blocks. Points to an arena_block, defined in env.c */
  1915. void *block_head;
  1916. /* Cleanup entries. Pointer to a cleanup_ent, defined in env.c */
  1917. void *cleanup_head;
  1918. };
  1919. typedef struct mem_block {
  1920. struct mem_block *next;
  1921. size_t size;
  1922. size_t used;
  1923. bool owned;
  1924. /* Data follows. */
  1925. } mem_block;
  1926. typedef struct cleanup_ent {
  1927. struct cleanup_ent *next;
  1928. upb_cleanup_func *cleanup;
  1929. void *ud;
  1930. } cleanup_ent;
  1931. static void upb_arena_addblock(upb_arena *a, void *ptr, size_t size,
  1932. bool owned) {
  1933. mem_block *block = ptr;
  1934. block->next = a->block_head;
  1935. block->size = size;
  1936. block->used = align_up_max(sizeof(mem_block));
  1937. block->owned = owned;
  1938. a->block_head = block;
  1939. /* TODO(haberman): ASAN poison. */
  1940. }
  1941. static mem_block *upb_arena_allocblock(upb_arena *a, size_t size) {
  1942. size_t block_size = UPB_MAX(size, a->next_block_size) + sizeof(mem_block);
  1943. mem_block *block = upb_malloc(a->block_alloc, block_size);
  1944. if (!block) {
  1945. return NULL;
  1946. }
  1947. upb_arena_addblock(a, block, block_size, true);
  1948. a->next_block_size = UPB_MIN(block_size * 2, a->max_block_size);
  1949. return block;
  1950. }
  1951. static void *upb_arena_doalloc(upb_alloc *alloc, void *ptr, size_t oldsize,
  1952. size_t size) {
  1953. upb_arena *a = (upb_arena*)alloc; /* upb_alloc is initial member. */
  1954. mem_block *block = a->block_head;
  1955. void *ret;
  1956. if (size == 0) {
  1957. return NULL; /* We are an arena, don't need individual frees. */
  1958. }
  1959. size = align_up_max(size);
  1960. /* TODO(haberman): special-case if this is a realloc of the last alloc? */
  1961. if (!block || block->size - block->used < size) {
  1962. /* Slow path: have to allocate a new block. */
  1963. block = upb_arena_allocblock(a, size);
  1964. if (!block) {
  1965. return NULL; /* Out of memory. */
  1966. }
  1967. }
  1968. ret = (char*)block + block->used;
  1969. block->used += size;
  1970. if (oldsize > 0) {
  1971. memcpy(ret, ptr, oldsize); /* Preserve existing data. */
  1972. }
  1973. /* TODO(haberman): ASAN unpoison. */
  1974. a->bytes_allocated += size;
  1975. return ret;
  1976. }
  1977. /* Public Arena API ***********************************************************/
  1978. #define upb_alignof(type) offsetof (struct { char c; type member; }, member)
  1979. upb_arena *upb_arena_init(void *mem, size_t n, upb_alloc *alloc) {
  1980. const size_t first_block_overhead = sizeof(upb_arena) + sizeof(mem_block);
  1981. upb_arena *a;
  1982. bool owned = false;
  1983. /* Round block size down to alignof(*a) since we will allocate the arena
  1984. * itself at the end. */
  1985. n &= ~(upb_alignof(upb_arena) - 1);
  1986. if (n < first_block_overhead) {
  1987. /* We need to malloc the initial block. */
  1988. n = first_block_overhead + 256;
  1989. owned = true;
  1990. if (!alloc || !(mem = upb_malloc(alloc, n))) {
  1991. return NULL;
  1992. }
  1993. }
  1994. a = (void*)((char*)mem + n - sizeof(*a));
  1995. n -= sizeof(*a);
  1996. a->alloc.func = &upb_arena_doalloc;
  1997. a->block_alloc = &upb_alloc_global;
  1998. a->bytes_allocated = 0;
  1999. a->next_block_size = 256;
  2000. a->max_block_size = 16384;
  2001. a->cleanup_head = NULL;
  2002. a->block_head = NULL;
  2003. a->block_alloc = alloc;
  2004. upb_arena_addblock(a, mem, n, owned);
  2005. return a;
  2006. }
  2007. #undef upb_alignof
  2008. void upb_arena_free(upb_arena *a) {
  2009. cleanup_ent *ent = a->cleanup_head;
  2010. mem_block *block = a->block_head;
  2011. while (ent) {
  2012. ent->cleanup(ent->ud);
  2013. ent = ent->next;
  2014. }
  2015. /* Must do this after running cleanup functions, because this will delete
  2016. * the memory we store our cleanup entries in! */
  2017. while (block) {
  2018. /* Load first since we are deleting block. */
  2019. mem_block *next = block->next;
  2020. if (block->owned) {
  2021. upb_free(a->block_alloc, block);
  2022. }
  2023. block = next;
  2024. }
  2025. }
  2026. bool upb_arena_addcleanup(upb_arena *a, void *ud, upb_cleanup_func *func) {
  2027. cleanup_ent *ent = upb_malloc(&a->alloc, sizeof(cleanup_ent));
  2028. if (!ent) {
  2029. return false; /* Out of memory. */
  2030. }
  2031. ent->cleanup = func;
  2032. ent->ud = ud;
  2033. ent->next = a->cleanup_head;
  2034. a->cleanup_head = ent;
  2035. return true;
  2036. }
  2037. size_t upb_arena_bytesallocated(const upb_arena *a) {
  2038. return a->bytes_allocated;
  2039. }
  2040. /* This file was generated by upbc (the upb compiler) from the input
  2041. * file:
  2042. *
  2043. * google/protobuf/descriptor.proto
  2044. *
  2045. * Do not edit -- your changes will be discarded when the file is
  2046. * regenerated. */
  2047. #include <stddef.h>
  2048. static const upb_msglayout *const google_protobuf_FileDescriptorSet_submsgs[1] = {
  2049. &google_protobuf_FileDescriptorProto_msginit,
  2050. };
  2051. static const upb_msglayout_field google_protobuf_FileDescriptorSet__fields[1] = {
  2052. {1, UPB_SIZE(0, 0), 0, 0, 11, 3},
  2053. };
  2054. const upb_msglayout google_protobuf_FileDescriptorSet_msginit = {
  2055. &google_protobuf_FileDescriptorSet_submsgs[0],
  2056. &google_protobuf_FileDescriptorSet__fields[0],
  2057. UPB_SIZE(4, 8), 1, false,
  2058. };
  2059. static const upb_msglayout *const google_protobuf_FileDescriptorProto_submsgs[6] = {
  2060. &google_protobuf_DescriptorProto_msginit,
  2061. &google_protobuf_EnumDescriptorProto_msginit,
  2062. &google_protobuf_FieldDescriptorProto_msginit,
  2063. &google_protobuf_FileOptions_msginit,
  2064. &google_protobuf_ServiceDescriptorProto_msginit,
  2065. &google_protobuf_SourceCodeInfo_msginit,
  2066. };
  2067. static const upb_msglayout_field google_protobuf_FileDescriptorProto__fields[12] = {
  2068. {1, UPB_SIZE(4, 8), 1, 0, 9, 1},
  2069. {2, UPB_SIZE(12, 24), 2, 0, 9, 1},
  2070. {3, UPB_SIZE(36, 72), 0, 0, 9, 3},
  2071. {4, UPB_SIZE(40, 80), 0, 0, 11, 3},
  2072. {5, UPB_SIZE(44, 88), 0, 1, 11, 3},
  2073. {6, UPB_SIZE(48, 96), 0, 4, 11, 3},
  2074. {7, UPB_SIZE(52, 104), 0, 2, 11, 3},
  2075. {8, UPB_SIZE(28, 56), 4, 3, 11, 1},
  2076. {9, UPB_SIZE(32, 64), 5, 5, 11, 1},
  2077. {10, UPB_SIZE(56, 112), 0, 0, 5, 3},
  2078. {11, UPB_SIZE(60, 120), 0, 0, 5, 3},
  2079. {12, UPB_SIZE(20, 40), 3, 0, 9, 1},
  2080. };
  2081. const upb_msglayout google_protobuf_FileDescriptorProto_msginit = {
  2082. &google_protobuf_FileDescriptorProto_submsgs[0],
  2083. &google_protobuf_FileDescriptorProto__fields[0],
  2084. UPB_SIZE(64, 128), 12, false,
  2085. };
  2086. static const upb_msglayout *const google_protobuf_DescriptorProto_submsgs[8] = {
  2087. &google_protobuf_DescriptorProto_msginit,
  2088. &google_protobuf_DescriptorProto_ExtensionRange_msginit,
  2089. &google_protobuf_DescriptorProto_ReservedRange_msginit,
  2090. &google_protobuf_EnumDescriptorProto_msginit,
  2091. &google_protobuf_FieldDescriptorProto_msginit,
  2092. &google_protobuf_MessageOptions_msginit,
  2093. &google_protobuf_OneofDescriptorProto_msginit,
  2094. };
  2095. static const upb_msglayout_field google_protobuf_DescriptorProto__fields[10] = {
  2096. {1, UPB_SIZE(4, 8), 1, 0, 9, 1},
  2097. {2, UPB_SIZE(16, 32), 0, 4, 11, 3},
  2098. {3, UPB_SIZE(20, 40), 0, 0, 11, 3},
  2099. {4, UPB_SIZE(24, 48), 0, 3, 11, 3},
  2100. {5, UPB_SIZE(28, 56), 0, 1, 11, 3},
  2101. {6, UPB_SIZE(32, 64), 0, 4, 11, 3},
  2102. {7, UPB_SIZE(12, 24), 2, 5, 11, 1},
  2103. {8, UPB_SIZE(36, 72), 0, 6, 11, 3},
  2104. {9, UPB_SIZE(40, 80), 0, 2, 11, 3},
  2105. {10, UPB_SIZE(44, 88), 0, 0, 9, 3},
  2106. };
  2107. const upb_msglayout google_protobuf_DescriptorProto_msginit = {
  2108. &google_protobuf_DescriptorProto_submsgs[0],
  2109. &google_protobuf_DescriptorProto__fields[0],
  2110. UPB_SIZE(48, 96), 10, false,
  2111. };
  2112. static const upb_msglayout *const google_protobuf_DescriptorProto_ExtensionRange_submsgs[1] = {
  2113. &google_protobuf_ExtensionRangeOptions_msginit,
  2114. };
  2115. static const upb_msglayout_field google_protobuf_DescriptorProto_ExtensionRange__fields[3] = {
  2116. {1, UPB_SIZE(4, 4), 1, 0, 5, 1},
  2117. {2, UPB_SIZE(8, 8), 2, 0, 5, 1},
  2118. {3, UPB_SIZE(12, 16), 3, 0, 11, 1},
  2119. };
  2120. const upb_msglayout google_protobuf_DescriptorProto_ExtensionRange_msginit = {
  2121. &google_protobuf_DescriptorProto_ExtensionRange_submsgs[0],
  2122. &google_protobuf_DescriptorProto_ExtensionRange__fields[0],
  2123. UPB_SIZE(16, 24), 3, false,
  2124. };
  2125. static const upb_msglayout_field google_protobuf_DescriptorProto_ReservedRange__fields[2] = {
  2126. {1, UPB_SIZE(4, 4), 1, 0, 5, 1},
  2127. {2, UPB_SIZE(8, 8), 2, 0, 5, 1},
  2128. };
  2129. const upb_msglayout google_protobuf_DescriptorProto_ReservedRange_msginit = {
  2130. NULL,
  2131. &google_protobuf_DescriptorProto_ReservedRange__fields[0],
  2132. UPB_SIZE(12, 12), 2, false,
  2133. };
  2134. static const upb_msglayout *const google_protobuf_ExtensionRangeOptions_submsgs[1] = {
  2135. &google_protobuf_UninterpretedOption_msginit,
  2136. };
  2137. static const upb_msglayout_field google_protobuf_ExtensionRangeOptions__fields[1] = {
  2138. {999, UPB_SIZE(0, 0), 0, 0, 11, 3},
  2139. };
  2140. const upb_msglayout google_protobuf_ExtensionRangeOptions_msginit = {
  2141. &google_protobuf_ExtensionRangeOptions_submsgs[0],
  2142. &google_protobuf_ExtensionRangeOptions__fields[0],
  2143. UPB_SIZE(4, 8), 1, false,
  2144. };
  2145. static const upb_msglayout *const google_protobuf_FieldDescriptorProto_submsgs[1] = {
  2146. &google_protobuf_FieldOptions_msginit,
  2147. };
  2148. static const upb_msglayout_field google_protobuf_FieldDescriptorProto__fields[10] = {
  2149. {1, UPB_SIZE(32, 32), 5, 0, 9, 1},
  2150. {2, UPB_SIZE(40, 48), 6, 0, 9, 1},
  2151. {3, UPB_SIZE(24, 24), 3, 0, 5, 1},
  2152. {4, UPB_SIZE(8, 8), 1, 0, 14, 1},
  2153. {5, UPB_SIZE(16, 16), 2, 0, 14, 1},
  2154. {6, UPB_SIZE(48, 64), 7, 0, 9, 1},
  2155. {7, UPB_SIZE(56, 80), 8, 0, 9, 1},
  2156. {8, UPB_SIZE(72, 112), 10, 0, 11, 1},
  2157. {9, UPB_SIZE(28, 28), 4, 0, 5, 1},
  2158. {10, UPB_SIZE(64, 96), 9, 0, 9, 1},
  2159. };
  2160. const upb_msglayout google_protobuf_FieldDescriptorProto_msginit = {
  2161. &google_protobuf_FieldDescriptorProto_submsgs[0],
  2162. &google_protobuf_FieldDescriptorProto__fields[0],
  2163. UPB_SIZE(80, 128), 10, false,
  2164. };
  2165. static const upb_msglayout *const google_protobuf_OneofDescriptorProto_submsgs[1] = {
  2166. &google_protobuf_OneofOptions_msginit,
  2167. };
  2168. static const upb_msglayout_field google_protobuf_OneofDescriptorProto__fields[2] = {
  2169. {1, UPB_SIZE(4, 8), 1, 0, 9, 1},
  2170. {2, UPB_SIZE(12, 24), 2, 0, 11, 1},
  2171. };
  2172. const upb_msglayout google_protobuf_OneofDescriptorProto_msginit = {
  2173. &google_protobuf_OneofDescriptorProto_submsgs[0],
  2174. &google_protobuf_OneofDescriptorProto__fields[0],
  2175. UPB_SIZE(16, 32), 2, false,
  2176. };
  2177. static const upb_msglayout *const google_protobuf_EnumDescriptorProto_submsgs[3] = {
  2178. &google_protobuf_EnumDescriptorProto_EnumReservedRange_msginit,
  2179. &google_protobuf_EnumOptions_msginit,
  2180. &google_protobuf_EnumValueDescriptorProto_msginit,
  2181. };
  2182. static const upb_msglayout_field google_protobuf_EnumDescriptorProto__fields[5] = {
  2183. {1, UPB_SIZE(4, 8), 1, 0, 9, 1},
  2184. {2, UPB_SIZE(16, 32), 0, 2, 11, 3},
  2185. {3, UPB_SIZE(12, 24), 2, 1, 11, 1},
  2186. {4, UPB_SIZE(20, 40), 0, 0, 11, 3},
  2187. {5, UPB_SIZE(24, 48), 0, 0, 9, 3},
  2188. };
  2189. const upb_msglayout google_protobuf_EnumDescriptorProto_msginit = {
  2190. &google_protobuf_EnumDescriptorProto_submsgs[0],
  2191. &google_protobuf_EnumDescriptorProto__fields[0],
  2192. UPB_SIZE(32, 64), 5, false,
  2193. };
  2194. static const upb_msglayout_field google_protobuf_EnumDescriptorProto_EnumReservedRange__fields[2] = {
  2195. {1, UPB_SIZE(4, 4), 1, 0, 5, 1},
  2196. {2, UPB_SIZE(8, 8), 2, 0, 5, 1},
  2197. };
  2198. const upb_msglayout google_protobuf_EnumDescriptorProto_EnumReservedRange_msginit = {
  2199. NULL,
  2200. &google_protobuf_EnumDescriptorProto_EnumReservedRange__fields[0],
  2201. UPB_SIZE(12, 12), 2, false,
  2202. };
  2203. static const upb_msglayout *const google_protobuf_EnumValueDescriptorProto_submsgs[1] = {
  2204. &google_protobuf_EnumValueOptions_msginit,
  2205. };
  2206. static const upb_msglayout_field google_protobuf_EnumValueDescriptorProto__fields[3] = {
  2207. {1, UPB_SIZE(8, 8), 2, 0, 9, 1},
  2208. {2, UPB_SIZE(4, 4), 1, 0, 5, 1},
  2209. {3, UPB_SIZE(16, 24), 3, 0, 11, 1},
  2210. };
  2211. const upb_msglayout google_protobuf_EnumValueDescriptorProto_msginit = {
  2212. &google_protobuf_EnumValueDescriptorProto_submsgs[0],
  2213. &google_protobuf_EnumValueDescriptorProto__fields[0],
  2214. UPB_SIZE(24, 32), 3, false,
  2215. };
  2216. static const upb_msglayout *const google_protobuf_ServiceDescriptorProto_submsgs[2] = {
  2217. &google_protobuf_MethodDescriptorProto_msginit,
  2218. &google_protobuf_ServiceOptions_msginit,
  2219. };
  2220. static const upb_msglayout_field google_protobuf_ServiceDescriptorProto__fields[3] = {
  2221. {1, UPB_SIZE(4, 8), 1, 0, 9, 1},
  2222. {2, UPB_SIZE(16, 32), 0, 0, 11, 3},
  2223. {3, UPB_SIZE(12, 24), 2, 1, 11, 1},
  2224. };
  2225. const upb_msglayout google_protobuf_ServiceDescriptorProto_msginit = {
  2226. &google_protobuf_ServiceDescriptorProto_submsgs[0],
  2227. &google_protobuf_ServiceDescriptorProto__fields[0],
  2228. UPB_SIZE(24, 48), 3, false,
  2229. };
  2230. static const upb_msglayout *const google_protobuf_MethodDescriptorProto_submsgs[1] = {
  2231. &google_protobuf_MethodOptions_msginit,
  2232. };
  2233. static const upb_msglayout_field google_protobuf_MethodDescriptorProto__fields[6] = {
  2234. {1, UPB_SIZE(4, 8), 3, 0, 9, 1},
  2235. {2, UPB_SIZE(12, 24), 4, 0, 9, 1},
  2236. {3, UPB_SIZE(20, 40), 5, 0, 9, 1},
  2237. {4, UPB_SIZE(28, 56), 6, 0, 11, 1},
  2238. {5, UPB_SIZE(1, 1), 1, 0, 8, 1},
  2239. {6, UPB_SIZE(2, 2), 2, 0, 8, 1},
  2240. };
  2241. const upb_msglayout google_protobuf_MethodDescriptorProto_msginit = {
  2242. &google_protobuf_MethodDescriptorProto_submsgs[0],
  2243. &google_protobuf_MethodDescriptorProto__fields[0],
  2244. UPB_SIZE(32, 64), 6, false,
  2245. };
  2246. static const upb_msglayout *const google_protobuf_FileOptions_submsgs[1] = {
  2247. &google_protobuf_UninterpretedOption_msginit,
  2248. };
  2249. static const upb_msglayout_field google_protobuf_FileOptions__fields[21] = {
  2250. {1, UPB_SIZE(28, 32), 11, 0, 9, 1},
  2251. {8, UPB_SIZE(36, 48), 12, 0, 9, 1},
  2252. {9, UPB_SIZE(8, 8), 1, 0, 14, 1},
  2253. {10, UPB_SIZE(16, 16), 2, 0, 8, 1},
  2254. {11, UPB_SIZE(44, 64), 13, 0, 9, 1},
  2255. {16, UPB_SIZE(17, 17), 3, 0, 8, 1},
  2256. {17, UPB_SIZE(18, 18), 4, 0, 8, 1},
  2257. {18, UPB_SIZE(19, 19), 5, 0, 8, 1},
  2258. {20, UPB_SIZE(20, 20), 6, 0, 8, 1},
  2259. {23, UPB_SIZE(21, 21), 7, 0, 8, 1},
  2260. {27, UPB_SIZE(22, 22), 8, 0, 8, 1},
  2261. {31, UPB_SIZE(23, 23), 9, 0, 8, 1},
  2262. {36, UPB_SIZE(52, 80), 14, 0, 9, 1},
  2263. {37, UPB_SIZE(60, 96), 15, 0, 9, 1},
  2264. {39, UPB_SIZE(68, 112), 16, 0, 9, 1},
  2265. {40, UPB_SIZE(76, 128), 17, 0, 9, 1},
  2266. {41, UPB_SIZE(84, 144), 18, 0, 9, 1},
  2267. {42, UPB_SIZE(24, 24), 10, 0, 8, 1},
  2268. {44, UPB_SIZE(92, 160), 19, 0, 9, 1},
  2269. {45, UPB_SIZE(100, 176), 20, 0, 9, 1},
  2270. {999, UPB_SIZE(108, 192), 0, 0, 11, 3},
  2271. };
  2272. const upb_msglayout google_protobuf_FileOptions_msginit = {
  2273. &google_protobuf_FileOptions_submsgs[0],
  2274. &google_protobuf_FileOptions__fields[0],
  2275. UPB_SIZE(112, 208), 21, false,
  2276. };
  2277. static const upb_msglayout *const google_protobuf_MessageOptions_submsgs[1] = {
  2278. &google_protobuf_UninterpretedOption_msginit,
  2279. };
  2280. static const upb_msglayout_field google_protobuf_MessageOptions__fields[5] = {
  2281. {1, UPB_SIZE(1, 1), 1, 0, 8, 1},
  2282. {2, UPB_SIZE(2, 2), 2, 0, 8, 1},
  2283. {3, UPB_SIZE(3, 3), 3, 0, 8, 1},
  2284. {7, UPB_SIZE(4, 4), 4, 0, 8, 1},
  2285. {999, UPB_SIZE(8, 8), 0, 0, 11, 3},
  2286. };
  2287. const upb_msglayout google_protobuf_MessageOptions_msginit = {
  2288. &google_protobuf_MessageOptions_submsgs[0],
  2289. &google_protobuf_MessageOptions__fields[0],
  2290. UPB_SIZE(12, 16), 5, false,
  2291. };
  2292. static const upb_msglayout *const google_protobuf_FieldOptions_submsgs[1] = {
  2293. &google_protobuf_UninterpretedOption_msginit,
  2294. };
  2295. static const upb_msglayout_field google_protobuf_FieldOptions__fields[7] = {
  2296. {1, UPB_SIZE(8, 8), 1, 0, 14, 1},
  2297. {2, UPB_SIZE(24, 24), 3, 0, 8, 1},
  2298. {3, UPB_SIZE(25, 25), 4, 0, 8, 1},
  2299. {5, UPB_SIZE(26, 26), 5, 0, 8, 1},
  2300. {6, UPB_SIZE(16, 16), 2, 0, 14, 1},
  2301. {10, UPB_SIZE(27, 27), 6, 0, 8, 1},
  2302. {999, UPB_SIZE(28, 32), 0, 0, 11, 3},
  2303. };
  2304. const upb_msglayout google_protobuf_FieldOptions_msginit = {
  2305. &google_protobuf_FieldOptions_submsgs[0],
  2306. &google_protobuf_FieldOptions__fields[0],
  2307. UPB_SIZE(32, 40), 7, false,
  2308. };
  2309. static const upb_msglayout *const google_protobuf_OneofOptions_submsgs[1] = {
  2310. &google_protobuf_UninterpretedOption_msginit,
  2311. };
  2312. static const upb_msglayout_field google_protobuf_OneofOptions__fields[1] = {
  2313. {999, UPB_SIZE(0, 0), 0, 0, 11, 3},
  2314. };
  2315. const upb_msglayout google_protobuf_OneofOptions_msginit = {
  2316. &google_protobuf_OneofOptions_submsgs[0],
  2317. &google_protobuf_OneofOptions__fields[0],
  2318. UPB_SIZE(4, 8), 1, false,
  2319. };
  2320. static const upb_msglayout *const google_protobuf_EnumOptions_submsgs[1] = {
  2321. &google_protobuf_UninterpretedOption_msginit,
  2322. };
  2323. static const upb_msglayout_field google_protobuf_EnumOptions__fields[3] = {
  2324. {2, UPB_SIZE(1, 1), 1, 0, 8, 1},
  2325. {3, UPB_SIZE(2, 2), 2, 0, 8, 1},
  2326. {999, UPB_SIZE(4, 8), 0, 0, 11, 3},
  2327. };
  2328. const upb_msglayout google_protobuf_EnumOptions_msginit = {
  2329. &google_protobuf_EnumOptions_submsgs[0],
  2330. &google_protobuf_EnumOptions__fields[0],
  2331. UPB_SIZE(8, 16), 3, false,
  2332. };
  2333. static const upb_msglayout *const google_protobuf_EnumValueOptions_submsgs[1] = {
  2334. &google_protobuf_UninterpretedOption_msginit,
  2335. };
  2336. static const upb_msglayout_field google_protobuf_EnumValueOptions__fields[2] = {
  2337. {1, UPB_SIZE(1, 1), 1, 0, 8, 1},
  2338. {999, UPB_SIZE(4, 8), 0, 0, 11, 3},
  2339. };
  2340. const upb_msglayout google_protobuf_EnumValueOptions_msginit = {
  2341. &google_protobuf_EnumValueOptions_submsgs[0],
  2342. &google_protobuf_EnumValueOptions__fields[0],
  2343. UPB_SIZE(8, 16), 2, false,
  2344. };
  2345. static const upb_msglayout *const google_protobuf_ServiceOptions_submsgs[1] = {
  2346. &google_protobuf_UninterpretedOption_msginit,
  2347. };
  2348. static const upb_msglayout_field google_protobuf_ServiceOptions__fields[2] = {
  2349. {33, UPB_SIZE(1, 1), 1, 0, 8, 1},
  2350. {999, UPB_SIZE(4, 8), 0, 0, 11, 3},
  2351. };
  2352. const upb_msglayout google_protobuf_ServiceOptions_msginit = {
  2353. &google_protobuf_ServiceOptions_submsgs[0],
  2354. &google_protobuf_ServiceOptions__fields[0],
  2355. UPB_SIZE(8, 16), 2, false,
  2356. };
  2357. static const upb_msglayout *const google_protobuf_MethodOptions_submsgs[1] = {
  2358. &google_protobuf_UninterpretedOption_msginit,
  2359. };
  2360. static const upb_msglayout_field google_protobuf_MethodOptions__fields[3] = {
  2361. {33, UPB_SIZE(16, 16), 2, 0, 8, 1},
  2362. {34, UPB_SIZE(8, 8), 1, 0, 14, 1},
  2363. {999, UPB_SIZE(20, 24), 0, 0, 11, 3},
  2364. };
  2365. const upb_msglayout google_protobuf_MethodOptions_msginit = {
  2366. &google_protobuf_MethodOptions_submsgs[0],
  2367. &google_protobuf_MethodOptions__fields[0],
  2368. UPB_SIZE(24, 32), 3, false,
  2369. };
  2370. static const upb_msglayout *const google_protobuf_UninterpretedOption_submsgs[1] = {
  2371. &google_protobuf_UninterpretedOption_NamePart_msginit,
  2372. };
  2373. static const upb_msglayout_field google_protobuf_UninterpretedOption__fields[7] = {
  2374. {2, UPB_SIZE(56, 80), 0, 0, 11, 3},
  2375. {3, UPB_SIZE(32, 32), 4, 0, 9, 1},
  2376. {4, UPB_SIZE(8, 8), 1, 0, 4, 1},
  2377. {5, UPB_SIZE(16, 16), 2, 0, 3, 1},
  2378. {6, UPB_SIZE(24, 24), 3, 0, 1, 1},
  2379. {7, UPB_SIZE(40, 48), 5, 0, 12, 1},
  2380. {8, UPB_SIZE(48, 64), 6, 0, 9, 1},
  2381. };
  2382. const upb_msglayout google_protobuf_UninterpretedOption_msginit = {
  2383. &google_protobuf_UninterpretedOption_submsgs[0],
  2384. &google_protobuf_UninterpretedOption__fields[0],
  2385. UPB_SIZE(64, 96), 7, false,
  2386. };
  2387. static const upb_msglayout_field google_protobuf_UninterpretedOption_NamePart__fields[2] = {
  2388. {1, UPB_SIZE(4, 8), 2, 0, 9, 2},
  2389. {2, UPB_SIZE(1, 1), 1, 0, 8, 2},
  2390. };
  2391. const upb_msglayout google_protobuf_UninterpretedOption_NamePart_msginit = {
  2392. NULL,
  2393. &google_protobuf_UninterpretedOption_NamePart__fields[0],
  2394. UPB_SIZE(16, 32), 2, false,
  2395. };
  2396. static const upb_msglayout *const google_protobuf_SourceCodeInfo_submsgs[1] = {
  2397. &google_protobuf_SourceCodeInfo_Location_msginit,
  2398. };
  2399. static const upb_msglayout_field google_protobuf_SourceCodeInfo__fields[1] = {
  2400. {1, UPB_SIZE(0, 0), 0, 0, 11, 3},
  2401. };
  2402. const upb_msglayout google_protobuf_SourceCodeInfo_msginit = {
  2403. &google_protobuf_SourceCodeInfo_submsgs[0],
  2404. &google_protobuf_SourceCodeInfo__fields[0],
  2405. UPB_SIZE(4, 8), 1, false,
  2406. };
  2407. static const upb_msglayout_field google_protobuf_SourceCodeInfo_Location__fields[5] = {
  2408. {1, UPB_SIZE(20, 40), 0, 0, 5, 3},
  2409. {2, UPB_SIZE(24, 48), 0, 0, 5, 3},
  2410. {3, UPB_SIZE(4, 8), 1, 0, 9, 1},
  2411. {4, UPB_SIZE(12, 24), 2, 0, 9, 1},
  2412. {6, UPB_SIZE(28, 56), 0, 0, 9, 3},
  2413. };
  2414. const upb_msglayout google_protobuf_SourceCodeInfo_Location_msginit = {
  2415. NULL,
  2416. &google_protobuf_SourceCodeInfo_Location__fields[0],
  2417. UPB_SIZE(32, 64), 5, false,
  2418. };
  2419. static const upb_msglayout *const google_protobuf_GeneratedCodeInfo_submsgs[1] = {
  2420. &google_protobuf_GeneratedCodeInfo_Annotation_msginit,
  2421. };
  2422. static const upb_msglayout_field google_protobuf_GeneratedCodeInfo__fields[1] = {
  2423. {1, UPB_SIZE(0, 0), 0, 0, 11, 3},
  2424. };
  2425. const upb_msglayout google_protobuf_GeneratedCodeInfo_msginit = {
  2426. &google_protobuf_GeneratedCodeInfo_submsgs[0],
  2427. &google_protobuf_GeneratedCodeInfo__fields[0],
  2428. UPB_SIZE(4, 8), 1, false,
  2429. };
  2430. static const upb_msglayout_field google_protobuf_GeneratedCodeInfo_Annotation__fields[4] = {
  2431. {1, UPB_SIZE(20, 32), 0, 0, 5, 3},
  2432. {2, UPB_SIZE(12, 16), 3, 0, 9, 1},
  2433. {3, UPB_SIZE(4, 4), 1, 0, 5, 1},
  2434. {4, UPB_SIZE(8, 8), 2, 0, 5, 1},
  2435. };
  2436. const upb_msglayout google_protobuf_GeneratedCodeInfo_Annotation_msginit = {
  2437. NULL,
  2438. &google_protobuf_GeneratedCodeInfo_Annotation__fields[0],
  2439. UPB_SIZE(24, 48), 4, false,
  2440. };
  2441. #include <ctype.h>
  2442. #include <errno.h>
  2443. #include <stdlib.h>
  2444. #include <string.h>
  2445. typedef struct {
  2446. size_t len;
  2447. char str[1]; /* Null-terminated string data follows. */
  2448. } str_t;
  2449. static str_t *newstr(upb_alloc *alloc, const char *data, size_t len) {
  2450. str_t *ret = upb_malloc(alloc, sizeof(*ret) + len);
  2451. if (!ret) return NULL;
  2452. ret->len = len;
  2453. memcpy(ret->str, data, len);
  2454. ret->str[len] = '\0';
  2455. return ret;
  2456. }
  2457. struct upb_fielddef {
  2458. const upb_filedef *file;
  2459. const upb_msgdef *msgdef;
  2460. const char *full_name;
  2461. union {
  2462. int64_t sint;
  2463. uint64_t uint;
  2464. double dbl;
  2465. float flt;
  2466. bool boolean;
  2467. str_t *str;
  2468. } defaultval;
  2469. const upb_oneofdef *oneof;
  2470. union {
  2471. const upb_msgdef *msgdef;
  2472. const upb_enumdef *enumdef;
  2473. const google_protobuf_FieldDescriptorProto *unresolved;
  2474. } sub;
  2475. uint32_t number_;
  2476. uint32_t index_;
  2477. uint32_t selector_base; /* Used to index into a upb::Handlers table. */
  2478. bool is_extension_;
  2479. bool lazy_;
  2480. bool packed_;
  2481. upb_descriptortype_t type_;
  2482. upb_label_t label_;
  2483. };
  2484. struct upb_msgdef {
  2485. const upb_filedef *file;
  2486. const char *full_name;
  2487. uint32_t selector_count;
  2488. uint32_t submsg_field_count;
  2489. /* Tables for looking up fields by number and name. */
  2490. upb_inttable itof;
  2491. upb_strtable ntof;
  2492. const upb_fielddef *fields;
  2493. const upb_oneofdef *oneofs;
  2494. int field_count;
  2495. int oneof_count;
  2496. /* Is this a map-entry message? */
  2497. bool map_entry;
  2498. upb_wellknowntype_t well_known_type;
  2499. /* TODO(haberman): proper extension ranges (there can be multiple). */
  2500. };
  2501. struct upb_enumdef {
  2502. const upb_filedef *file;
  2503. const char *full_name;
  2504. upb_strtable ntoi;
  2505. upb_inttable iton;
  2506. int32_t defaultval;
  2507. };
  2508. struct upb_oneofdef {
  2509. const upb_msgdef *parent;
  2510. const char *full_name;
  2511. uint32_t index;
  2512. upb_strtable ntof;
  2513. upb_inttable itof;
  2514. };
  2515. struct upb_filedef {
  2516. const char *name;
  2517. const char *package;
  2518. const char *phpprefix;
  2519. const char *phpnamespace;
  2520. upb_syntax_t syntax;
  2521. const upb_filedef **deps;
  2522. const upb_msgdef *msgs;
  2523. const upb_enumdef *enums;
  2524. const upb_fielddef *exts;
  2525. int dep_count;
  2526. int msg_count;
  2527. int enum_count;
  2528. int ext_count;
  2529. };
  2530. struct upb_symtab {
  2531. upb_arena *arena;
  2532. upb_strtable syms; /* full_name -> packed def ptr */
  2533. upb_strtable files; /* file_name -> upb_filedef* */
  2534. };
  2535. /* Inside a symtab we store tagged pointers to specific def types. */
  2536. typedef enum {
  2537. UPB_DEFTYPE_MSG = 0,
  2538. UPB_DEFTYPE_ENUM = 1,
  2539. UPB_DEFTYPE_FIELD = 2,
  2540. UPB_DEFTYPE_ONEOF = 3
  2541. } upb_deftype_t;
  2542. static const void *unpack_def(upb_value v, upb_deftype_t type) {
  2543. uintptr_t num = (uintptr_t)upb_value_getconstptr(v);
  2544. return (num & 3) == type ? (const void*)(num & ~3) : NULL;
  2545. }
  2546. static upb_value pack_def(const void *ptr, upb_deftype_t type) {
  2547. uintptr_t num = (uintptr_t)ptr | type;
  2548. return upb_value_constptr((const void*)num);
  2549. }
  2550. /* isalpha() etc. from <ctype.h> are locale-dependent, which we don't want. */
  2551. static bool upb_isbetween(char c, char low, char high) {
  2552. return c >= low && c <= high;
  2553. }
  2554. static bool upb_isletter(char c) {
  2555. return upb_isbetween(c, 'A', 'Z') || upb_isbetween(c, 'a', 'z') || c == '_';
  2556. }
  2557. static bool upb_isalphanum(char c) {
  2558. return upb_isletter(c) || upb_isbetween(c, '0', '9');
  2559. }
  2560. static bool upb_isident(upb_strview name, bool full, upb_status *s) {
  2561. const char *str = name.data;
  2562. size_t len = name.size;
  2563. bool start = true;
  2564. size_t i;
  2565. for (i = 0; i < len; i++) {
  2566. char c = str[i];
  2567. if (c == '.') {
  2568. if (start || !full) {
  2569. upb_status_seterrf(s, "invalid name: unexpected '.' (%s)", str);
  2570. return false;
  2571. }
  2572. start = true;
  2573. } else if (start) {
  2574. if (!upb_isletter(c)) {
  2575. upb_status_seterrf(
  2576. s, "invalid name: path components must start with a letter (%s)",
  2577. str);
  2578. return false;
  2579. }
  2580. start = false;
  2581. } else {
  2582. if (!upb_isalphanum(c)) {
  2583. upb_status_seterrf(s, "invalid name: non-alphanumeric character (%s)",
  2584. str);
  2585. return false;
  2586. }
  2587. }
  2588. }
  2589. return !start;
  2590. }
  2591. static const char *shortdefname(const char *fullname) {
  2592. const char *p;
  2593. if (fullname == NULL) {
  2594. return NULL;
  2595. } else if ((p = strrchr(fullname, '.')) == NULL) {
  2596. /* No '.' in the name, return the full string. */
  2597. return fullname;
  2598. } else {
  2599. /* Return one past the last '.'. */
  2600. return p + 1;
  2601. }
  2602. }
  2603. /* All submessage fields are lower than all other fields.
  2604. * Secondly, fields are increasing in order. */
  2605. uint32_t field_rank(const upb_fielddef *f) {
  2606. uint32_t ret = upb_fielddef_number(f);
  2607. const uint32_t high_bit = 1 << 30;
  2608. UPB_ASSERT(ret < high_bit);
  2609. if (!upb_fielddef_issubmsg(f))
  2610. ret |= high_bit;
  2611. return ret;
  2612. }
  2613. int cmp_fields(const void *p1, const void *p2) {
  2614. const upb_fielddef *f1 = *(upb_fielddef*const*)p1;
  2615. const upb_fielddef *f2 = *(upb_fielddef*const*)p2;
  2616. return field_rank(f1) - field_rank(f2);
  2617. }
  2618. /* A few implementation details of handlers. We put these here to avoid
  2619. * a def -> handlers dependency. */
  2620. #define UPB_STATIC_SELECTOR_COUNT 3 /* Warning: also in upb/handlers.h. */
  2621. static uint32_t upb_handlers_selectorbaseoffset(const upb_fielddef *f) {
  2622. return upb_fielddef_isseq(f) ? 2 : 0;
  2623. }
  2624. static uint32_t upb_handlers_selectorcount(const upb_fielddef *f) {
  2625. uint32_t ret = 1;
  2626. if (upb_fielddef_isseq(f)) ret += 2; /* STARTSEQ/ENDSEQ */
  2627. if (upb_fielddef_isstring(f)) ret += 2; /* [STRING]/STARTSTR/ENDSTR */
  2628. if (upb_fielddef_issubmsg(f)) {
  2629. /* ENDSUBMSG (STARTSUBMSG is at table beginning) */
  2630. ret += 0;
  2631. if (upb_fielddef_lazy(f)) {
  2632. /* STARTSTR/ENDSTR/STRING (for lazy) */
  2633. ret += 3;
  2634. }
  2635. }
  2636. return ret;
  2637. }
  2638. static bool assign_msg_indices(upb_msgdef *m, upb_status *s) {
  2639. /* Sort fields. upb internally relies on UPB_TYPE_MESSAGE fields having the
  2640. * lowest indexes, but we do not publicly guarantee this. */
  2641. upb_msg_field_iter j;
  2642. upb_msg_oneof_iter k;
  2643. int i;
  2644. uint32_t selector;
  2645. int n = upb_msgdef_numfields(m);
  2646. upb_fielddef **fields;
  2647. if (n == 0) {
  2648. m->selector_count = UPB_STATIC_SELECTOR_COUNT;
  2649. m->submsg_field_count = 0;
  2650. return true;
  2651. }
  2652. fields = upb_gmalloc(n * sizeof(*fields));
  2653. if (!fields) {
  2654. upb_status_setoom(s);
  2655. return false;
  2656. }
  2657. m->submsg_field_count = 0;
  2658. for(i = 0, upb_msg_field_begin(&j, m);
  2659. !upb_msg_field_done(&j);
  2660. upb_msg_field_next(&j), i++) {
  2661. upb_fielddef *f = upb_msg_iter_field(&j);
  2662. UPB_ASSERT(f->msgdef == m);
  2663. if (upb_fielddef_issubmsg(f)) {
  2664. m->submsg_field_count++;
  2665. }
  2666. fields[i] = f;
  2667. }
  2668. qsort(fields, n, sizeof(*fields), cmp_fields);
  2669. selector = UPB_STATIC_SELECTOR_COUNT + m->submsg_field_count;
  2670. for (i = 0; i < n; i++) {
  2671. upb_fielddef *f = fields[i];
  2672. f->index_ = i;
  2673. f->selector_base = selector + upb_handlers_selectorbaseoffset(f);
  2674. selector += upb_handlers_selectorcount(f);
  2675. }
  2676. m->selector_count = selector;
  2677. for(upb_msg_oneof_begin(&k, m), i = 0;
  2678. !upb_msg_oneof_done(&k);
  2679. upb_msg_oneof_next(&k), i++) {
  2680. upb_oneofdef *o = (upb_oneofdef*)upb_msg_iter_oneof(&k);
  2681. o->index = i;
  2682. }
  2683. upb_gfree(fields);
  2684. return true;
  2685. }
  2686. static void assign_msg_wellknowntype(upb_msgdef *m) {
  2687. const char *name = upb_msgdef_fullname(m);
  2688. if (name == NULL) {
  2689. m->well_known_type = UPB_WELLKNOWN_UNSPECIFIED;
  2690. return;
  2691. }
  2692. if (!strcmp(name, "google.protobuf.Any")) {
  2693. m->well_known_type = UPB_WELLKNOWN_ANY;
  2694. } else if (!strcmp(name, "google.protobuf.FieldMask")) {
  2695. m->well_known_type = UPB_WELLKNOWN_FIELDMASK;
  2696. } else if (!strcmp(name, "google.protobuf.Duration")) {
  2697. m->well_known_type = UPB_WELLKNOWN_DURATION;
  2698. } else if (!strcmp(name, "google.protobuf.Timestamp")) {
  2699. m->well_known_type = UPB_WELLKNOWN_TIMESTAMP;
  2700. } else if (!strcmp(name, "google.protobuf.DoubleValue")) {
  2701. m->well_known_type = UPB_WELLKNOWN_DOUBLEVALUE;
  2702. } else if (!strcmp(name, "google.protobuf.FloatValue")) {
  2703. m->well_known_type = UPB_WELLKNOWN_FLOATVALUE;
  2704. } else if (!strcmp(name, "google.protobuf.Int64Value")) {
  2705. m->well_known_type = UPB_WELLKNOWN_INT64VALUE;
  2706. } else if (!strcmp(name, "google.protobuf.UInt64Value")) {
  2707. m->well_known_type = UPB_WELLKNOWN_UINT64VALUE;
  2708. } else if (!strcmp(name, "google.protobuf.Int32Value")) {
  2709. m->well_known_type = UPB_WELLKNOWN_INT32VALUE;
  2710. } else if (!strcmp(name, "google.protobuf.UInt32Value")) {
  2711. m->well_known_type = UPB_WELLKNOWN_UINT32VALUE;
  2712. } else if (!strcmp(name, "google.protobuf.BoolValue")) {
  2713. m->well_known_type = UPB_WELLKNOWN_BOOLVALUE;
  2714. } else if (!strcmp(name, "google.protobuf.StringValue")) {
  2715. m->well_known_type = UPB_WELLKNOWN_STRINGVALUE;
  2716. } else if (!strcmp(name, "google.protobuf.BytesValue")) {
  2717. m->well_known_type = UPB_WELLKNOWN_BYTESVALUE;
  2718. } else if (!strcmp(name, "google.protobuf.Value")) {
  2719. m->well_known_type = UPB_WELLKNOWN_VALUE;
  2720. } else if (!strcmp(name, "google.protobuf.ListValue")) {
  2721. m->well_known_type = UPB_WELLKNOWN_LISTVALUE;
  2722. } else if (!strcmp(name, "google.protobuf.Struct")) {
  2723. m->well_known_type = UPB_WELLKNOWN_STRUCT;
  2724. } else {
  2725. m->well_known_type = UPB_WELLKNOWN_UNSPECIFIED;
  2726. }
  2727. }
  2728. /* upb_enumdef ****************************************************************/
  2729. const char *upb_enumdef_fullname(const upb_enumdef *e) {
  2730. return e->full_name;
  2731. }
  2732. const char *upb_enumdef_name(const upb_enumdef *e) {
  2733. return shortdefname(e->full_name);
  2734. }
  2735. const upb_filedef *upb_enumdef_file(const upb_enumdef *e) {
  2736. return e->file;
  2737. }
  2738. int32_t upb_enumdef_default(const upb_enumdef *e) {
  2739. UPB_ASSERT(upb_enumdef_iton(e, e->defaultval));
  2740. return e->defaultval;
  2741. }
  2742. int upb_enumdef_numvals(const upb_enumdef *e) {
  2743. return upb_strtable_count(&e->ntoi);
  2744. }
  2745. void upb_enum_begin(upb_enum_iter *i, const upb_enumdef *e) {
  2746. /* We iterate over the ntoi table, to account for duplicate numbers. */
  2747. upb_strtable_begin(i, &e->ntoi);
  2748. }
  2749. void upb_enum_next(upb_enum_iter *iter) { upb_strtable_next(iter); }
  2750. bool upb_enum_done(upb_enum_iter *iter) { return upb_strtable_done(iter); }
  2751. bool upb_enumdef_ntoi(const upb_enumdef *def, const char *name,
  2752. size_t len, int32_t *num) {
  2753. upb_value v;
  2754. if (!upb_strtable_lookup2(&def->ntoi, name, len, &v)) {
  2755. return false;
  2756. }
  2757. if (num) *num = upb_value_getint32(v);
  2758. return true;
  2759. }
  2760. const char *upb_enumdef_iton(const upb_enumdef *def, int32_t num) {
  2761. upb_value v;
  2762. return upb_inttable_lookup32(&def->iton, num, &v) ?
  2763. upb_value_getcstr(v) : NULL;
  2764. }
  2765. const char *upb_enum_iter_name(upb_enum_iter *iter) {
  2766. return upb_strtable_iter_key(iter);
  2767. }
  2768. int32_t upb_enum_iter_number(upb_enum_iter *iter) {
  2769. return upb_value_getint32(upb_strtable_iter_value(iter));
  2770. }
  2771. /* upb_fielddef ***************************************************************/
  2772. const char *upb_fielddef_fullname(const upb_fielddef *f) {
  2773. return f->full_name;
  2774. }
  2775. upb_fieldtype_t upb_fielddef_type(const upb_fielddef *f) {
  2776. switch (f->type_) {
  2777. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  2778. return UPB_TYPE_DOUBLE;
  2779. case UPB_DESCRIPTOR_TYPE_FLOAT:
  2780. return UPB_TYPE_FLOAT;
  2781. case UPB_DESCRIPTOR_TYPE_INT64:
  2782. case UPB_DESCRIPTOR_TYPE_SINT64:
  2783. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  2784. return UPB_TYPE_INT64;
  2785. case UPB_DESCRIPTOR_TYPE_INT32:
  2786. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  2787. case UPB_DESCRIPTOR_TYPE_SINT32:
  2788. return UPB_TYPE_INT32;
  2789. case UPB_DESCRIPTOR_TYPE_UINT64:
  2790. case UPB_DESCRIPTOR_TYPE_FIXED64:
  2791. return UPB_TYPE_UINT64;
  2792. case UPB_DESCRIPTOR_TYPE_UINT32:
  2793. case UPB_DESCRIPTOR_TYPE_FIXED32:
  2794. return UPB_TYPE_UINT32;
  2795. case UPB_DESCRIPTOR_TYPE_ENUM:
  2796. return UPB_TYPE_ENUM;
  2797. case UPB_DESCRIPTOR_TYPE_BOOL:
  2798. return UPB_TYPE_BOOL;
  2799. case UPB_DESCRIPTOR_TYPE_STRING:
  2800. return UPB_TYPE_STRING;
  2801. case UPB_DESCRIPTOR_TYPE_BYTES:
  2802. return UPB_TYPE_BYTES;
  2803. case UPB_DESCRIPTOR_TYPE_GROUP:
  2804. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  2805. return UPB_TYPE_MESSAGE;
  2806. }
  2807. UPB_UNREACHABLE();
  2808. }
  2809. upb_descriptortype_t upb_fielddef_descriptortype(const upb_fielddef *f) {
  2810. return f->type_;
  2811. }
  2812. uint32_t upb_fielddef_index(const upb_fielddef *f) {
  2813. return f->index_;
  2814. }
  2815. upb_label_t upb_fielddef_label(const upb_fielddef *f) {
  2816. return f->label_;
  2817. }
  2818. uint32_t upb_fielddef_number(const upb_fielddef *f) {
  2819. return f->number_;
  2820. }
  2821. bool upb_fielddef_isextension(const upb_fielddef *f) {
  2822. return f->is_extension_;
  2823. }
  2824. bool upb_fielddef_lazy(const upb_fielddef *f) {
  2825. return f->lazy_;
  2826. }
  2827. bool upb_fielddef_packed(const upb_fielddef *f) {
  2828. return f->packed_;
  2829. }
  2830. const char *upb_fielddef_name(const upb_fielddef *f) {
  2831. return shortdefname(f->full_name);
  2832. }
  2833. uint32_t upb_fielddef_selectorbase(const upb_fielddef *f) {
  2834. return f->selector_base;
  2835. }
  2836. size_t upb_fielddef_getjsonname(const upb_fielddef *f, char *buf, size_t len) {
  2837. const char *name = upb_fielddef_name(f);
  2838. size_t src, dst = 0;
  2839. bool ucase_next = false;
  2840. #define WRITE(byte) \
  2841. ++dst; \
  2842. if (dst < len) buf[dst - 1] = byte; \
  2843. else if (dst == len) buf[dst - 1] = '\0'
  2844. if (!name) {
  2845. WRITE('\0');
  2846. return 0;
  2847. }
  2848. /* Implement the transformation as described in the spec:
  2849. * 1. upper case all letters after an underscore.
  2850. * 2. remove all underscores.
  2851. */
  2852. for (src = 0; name[src]; src++) {
  2853. if (name[src] == '_') {
  2854. ucase_next = true;
  2855. continue;
  2856. }
  2857. if (ucase_next) {
  2858. WRITE(toupper(name[src]));
  2859. ucase_next = false;
  2860. } else {
  2861. WRITE(name[src]);
  2862. }
  2863. }
  2864. WRITE('\0');
  2865. return dst;
  2866. #undef WRITE
  2867. }
  2868. const upb_msgdef *upb_fielddef_containingtype(const upb_fielddef *f) {
  2869. return f->msgdef;
  2870. }
  2871. const upb_oneofdef *upb_fielddef_containingoneof(const upb_fielddef *f) {
  2872. return f->oneof;
  2873. }
  2874. static void chkdefaulttype(const upb_fielddef *f, int ctype) {
  2875. UPB_UNUSED(f);
  2876. UPB_UNUSED(ctype);
  2877. }
  2878. int64_t upb_fielddef_defaultint64(const upb_fielddef *f) {
  2879. chkdefaulttype(f, UPB_TYPE_INT64);
  2880. return f->defaultval.sint;
  2881. }
  2882. int32_t upb_fielddef_defaultint32(const upb_fielddef *f) {
  2883. chkdefaulttype(f, UPB_TYPE_INT32);
  2884. return f->defaultval.sint;
  2885. }
  2886. uint64_t upb_fielddef_defaultuint64(const upb_fielddef *f) {
  2887. chkdefaulttype(f, UPB_TYPE_UINT64);
  2888. return f->defaultval.uint;
  2889. }
  2890. uint32_t upb_fielddef_defaultuint32(const upb_fielddef *f) {
  2891. chkdefaulttype(f, UPB_TYPE_UINT32);
  2892. return f->defaultval.uint;
  2893. }
  2894. bool upb_fielddef_defaultbool(const upb_fielddef *f) {
  2895. chkdefaulttype(f, UPB_TYPE_BOOL);
  2896. return f->defaultval.boolean;
  2897. }
  2898. float upb_fielddef_defaultfloat(const upb_fielddef *f) {
  2899. chkdefaulttype(f, UPB_TYPE_FLOAT);
  2900. return f->defaultval.flt;
  2901. }
  2902. double upb_fielddef_defaultdouble(const upb_fielddef *f) {
  2903. chkdefaulttype(f, UPB_TYPE_DOUBLE);
  2904. return f->defaultval.dbl;
  2905. }
  2906. const char *upb_fielddef_defaultstr(const upb_fielddef *f, size_t *len) {
  2907. str_t *str = f->defaultval.str;
  2908. UPB_ASSERT(upb_fielddef_type(f) == UPB_TYPE_STRING ||
  2909. upb_fielddef_type(f) == UPB_TYPE_BYTES ||
  2910. upb_fielddef_type(f) == UPB_TYPE_ENUM);
  2911. if (str) {
  2912. if (len) *len = str->len;
  2913. return str->str;
  2914. } else {
  2915. if (len) *len = 0;
  2916. return NULL;
  2917. }
  2918. }
  2919. const upb_msgdef *upb_fielddef_msgsubdef(const upb_fielddef *f) {
  2920. UPB_ASSERT(upb_fielddef_type(f) == UPB_TYPE_MESSAGE);
  2921. return f->sub.msgdef;
  2922. }
  2923. const upb_enumdef *upb_fielddef_enumsubdef(const upb_fielddef *f) {
  2924. UPB_ASSERT(upb_fielddef_type(f) == UPB_TYPE_ENUM);
  2925. return f->sub.enumdef;
  2926. }
  2927. bool upb_fielddef_issubmsg(const upb_fielddef *f) {
  2928. return upb_fielddef_type(f) == UPB_TYPE_MESSAGE;
  2929. }
  2930. bool upb_fielddef_isstring(const upb_fielddef *f) {
  2931. return upb_fielddef_type(f) == UPB_TYPE_STRING ||
  2932. upb_fielddef_type(f) == UPB_TYPE_BYTES;
  2933. }
  2934. bool upb_fielddef_isseq(const upb_fielddef *f) {
  2935. return upb_fielddef_label(f) == UPB_LABEL_REPEATED;
  2936. }
  2937. bool upb_fielddef_isprimitive(const upb_fielddef *f) {
  2938. return !upb_fielddef_isstring(f) && !upb_fielddef_issubmsg(f);
  2939. }
  2940. bool upb_fielddef_ismap(const upb_fielddef *f) {
  2941. return upb_fielddef_isseq(f) && upb_fielddef_issubmsg(f) &&
  2942. upb_msgdef_mapentry(upb_fielddef_msgsubdef(f));
  2943. }
  2944. bool upb_fielddef_hassubdef(const upb_fielddef *f) {
  2945. return upb_fielddef_issubmsg(f) || upb_fielddef_type(f) == UPB_TYPE_ENUM;
  2946. }
  2947. bool upb_fielddef_haspresence(const upb_fielddef *f) {
  2948. if (upb_fielddef_isseq(f)) return false;
  2949. if (upb_fielddef_issubmsg(f)) return true;
  2950. return f->file->syntax == UPB_SYNTAX_PROTO2;
  2951. }
  2952. static bool between(int32_t x, int32_t low, int32_t high) {
  2953. return x >= low && x <= high;
  2954. }
  2955. bool upb_fielddef_checklabel(int32_t label) { return between(label, 1, 3); }
  2956. bool upb_fielddef_checktype(int32_t type) { return between(type, 1, 11); }
  2957. bool upb_fielddef_checkintfmt(int32_t fmt) { return between(fmt, 1, 3); }
  2958. bool upb_fielddef_checkdescriptortype(int32_t type) {
  2959. return between(type, 1, 18);
  2960. }
  2961. /* upb_msgdef *****************************************************************/
  2962. const char *upb_msgdef_fullname(const upb_msgdef *m) {
  2963. return m->full_name;
  2964. }
  2965. const upb_filedef *upb_msgdef_file(const upb_msgdef *m) {
  2966. return m->file;
  2967. }
  2968. const char *upb_msgdef_name(const upb_msgdef *m) {
  2969. return shortdefname(m->full_name);
  2970. }
  2971. upb_syntax_t upb_msgdef_syntax(const upb_msgdef *m) {
  2972. return m->file->syntax;
  2973. }
  2974. size_t upb_msgdef_selectorcount(const upb_msgdef *m) {
  2975. return m->selector_count;
  2976. }
  2977. uint32_t upb_msgdef_submsgfieldcount(const upb_msgdef *m) {
  2978. return m->submsg_field_count;
  2979. }
  2980. const upb_fielddef *upb_msgdef_itof(const upb_msgdef *m, uint32_t i) {
  2981. upb_value val;
  2982. return upb_inttable_lookup32(&m->itof, i, &val) ?
  2983. upb_value_getconstptr(val) : NULL;
  2984. }
  2985. const upb_fielddef *upb_msgdef_ntof(const upb_msgdef *m, const char *name,
  2986. size_t len) {
  2987. upb_value val;
  2988. if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
  2989. return NULL;
  2990. }
  2991. return unpack_def(val, UPB_DEFTYPE_FIELD);
  2992. }
  2993. const upb_oneofdef *upb_msgdef_ntoo(const upb_msgdef *m, const char *name,
  2994. size_t len) {
  2995. upb_value val;
  2996. if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
  2997. return NULL;
  2998. }
  2999. return unpack_def(val, UPB_DEFTYPE_ONEOF);
  3000. }
  3001. bool upb_msgdef_lookupname(const upb_msgdef *m, const char *name, size_t len,
  3002. const upb_fielddef **f, const upb_oneofdef **o) {
  3003. upb_value val;
  3004. if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
  3005. return false;
  3006. }
  3007. *o = unpack_def(val, UPB_DEFTYPE_ONEOF);
  3008. *f = unpack_def(val, UPB_DEFTYPE_FIELD);
  3009. UPB_ASSERT((*o != NULL) ^ (*f != NULL)); /* Exactly one of the two should be set. */
  3010. return true;
  3011. }
  3012. int upb_msgdef_numfields(const upb_msgdef *m) {
  3013. /* The number table contains only fields. */
  3014. return upb_inttable_count(&m->itof);
  3015. }
  3016. int upb_msgdef_numoneofs(const upb_msgdef *m) {
  3017. /* The name table includes oneofs, and the number table does not. */
  3018. return upb_strtable_count(&m->ntof) - upb_inttable_count(&m->itof);
  3019. }
  3020. bool upb_msgdef_mapentry(const upb_msgdef *m) {
  3021. return m->map_entry;
  3022. }
  3023. upb_wellknowntype_t upb_msgdef_wellknowntype(const upb_msgdef *m) {
  3024. return m->well_known_type;
  3025. }
  3026. bool upb_msgdef_isnumberwrapper(const upb_msgdef *m) {
  3027. upb_wellknowntype_t type = upb_msgdef_wellknowntype(m);
  3028. return type >= UPB_WELLKNOWN_DOUBLEVALUE &&
  3029. type <= UPB_WELLKNOWN_UINT32VALUE;
  3030. }
  3031. void upb_msg_field_begin(upb_msg_field_iter *iter, const upb_msgdef *m) {
  3032. upb_inttable_begin(iter, &m->itof);
  3033. }
  3034. void upb_msg_field_next(upb_msg_field_iter *iter) { upb_inttable_next(iter); }
  3035. bool upb_msg_field_done(const upb_msg_field_iter *iter) {
  3036. return upb_inttable_done(iter);
  3037. }
  3038. upb_fielddef *upb_msg_iter_field(const upb_msg_field_iter *iter) {
  3039. return (upb_fielddef *)upb_value_getconstptr(upb_inttable_iter_value(iter));
  3040. }
  3041. void upb_msg_field_iter_setdone(upb_msg_field_iter *iter) {
  3042. upb_inttable_iter_setdone(iter);
  3043. }
  3044. bool upb_msg_field_iter_isequal(const upb_msg_field_iter * iter1,
  3045. const upb_msg_field_iter * iter2) {
  3046. return upb_inttable_iter_isequal(iter1, iter2);
  3047. }
  3048. void upb_msg_oneof_begin(upb_msg_oneof_iter *iter, const upb_msgdef *m) {
  3049. upb_strtable_begin(iter, &m->ntof);
  3050. /* We need to skip past any initial fields. */
  3051. while (!upb_strtable_done(iter) &&
  3052. !unpack_def(upb_strtable_iter_value(iter), UPB_DEFTYPE_ONEOF)) {
  3053. upb_strtable_next(iter);
  3054. }
  3055. }
  3056. void upb_msg_oneof_next(upb_msg_oneof_iter *iter) {
  3057. /* We need to skip past fields to return only oneofs. */
  3058. do {
  3059. upb_strtable_next(iter);
  3060. } while (!upb_strtable_done(iter) &&
  3061. !unpack_def(upb_strtable_iter_value(iter), UPB_DEFTYPE_ONEOF));
  3062. }
  3063. bool upb_msg_oneof_done(const upb_msg_oneof_iter *iter) {
  3064. return upb_strtable_done(iter);
  3065. }
  3066. const upb_oneofdef *upb_msg_iter_oneof(const upb_msg_oneof_iter *iter) {
  3067. return unpack_def(upb_strtable_iter_value(iter), UPB_DEFTYPE_ONEOF);
  3068. }
  3069. void upb_msg_oneof_iter_setdone(upb_msg_oneof_iter *iter) {
  3070. upb_strtable_iter_setdone(iter);
  3071. }
  3072. bool upb_msg_oneof_iter_isequal(const upb_msg_oneof_iter *iter1,
  3073. const upb_msg_oneof_iter *iter2) {
  3074. return upb_strtable_iter_isequal(iter1, iter2);
  3075. }
  3076. /* upb_oneofdef ***************************************************************/
  3077. const char *upb_oneofdef_name(const upb_oneofdef *o) {
  3078. return shortdefname(o->full_name);
  3079. }
  3080. const upb_msgdef *upb_oneofdef_containingtype(const upb_oneofdef *o) {
  3081. return o->parent;
  3082. }
  3083. int upb_oneofdef_numfields(const upb_oneofdef *o) {
  3084. return upb_strtable_count(&o->ntof);
  3085. }
  3086. uint32_t upb_oneofdef_index(const upb_oneofdef *o) {
  3087. return o->index;
  3088. }
  3089. const upb_fielddef *upb_oneofdef_ntof(const upb_oneofdef *o,
  3090. const char *name, size_t length) {
  3091. upb_value val;
  3092. return upb_strtable_lookup2(&o->ntof, name, length, &val) ?
  3093. upb_value_getptr(val) : NULL;
  3094. }
  3095. const upb_fielddef *upb_oneofdef_itof(const upb_oneofdef *o, uint32_t num) {
  3096. upb_value val;
  3097. return upb_inttable_lookup32(&o->itof, num, &val) ?
  3098. upb_value_getptr(val) : NULL;
  3099. }
  3100. void upb_oneof_begin(upb_oneof_iter *iter, const upb_oneofdef *o) {
  3101. upb_inttable_begin(iter, &o->itof);
  3102. }
  3103. void upb_oneof_next(upb_oneof_iter *iter) {
  3104. upb_inttable_next(iter);
  3105. }
  3106. bool upb_oneof_done(upb_oneof_iter *iter) {
  3107. return upb_inttable_done(iter);
  3108. }
  3109. upb_fielddef *upb_oneof_iter_field(const upb_oneof_iter *iter) {
  3110. return (upb_fielddef *)upb_value_getconstptr(upb_inttable_iter_value(iter));
  3111. }
  3112. void upb_oneof_iter_setdone(upb_oneof_iter *iter) {
  3113. upb_inttable_iter_setdone(iter);
  3114. }
  3115. /* Code to build defs from descriptor protos. *********************************/
  3116. /* There is a question of how much validation to do here. It will be difficult
  3117. * to perfectly match the amount of validation performed by proto2. But since
  3118. * this code is used to directly build defs from Ruby (for example) we do need
  3119. * to validate important constraints like uniqueness of names and numbers. */
  3120. #define CHK(x) if (!(x)) { return false; }
  3121. #define CHK_OOM(x) if (!(x)) { upb_status_setoom(ctx->status); return false; }
  3122. typedef struct {
  3123. const upb_symtab *symtab;
  3124. upb_filedef *file; /* File we are building. */
  3125. upb_alloc *alloc; /* Allocate defs here. */
  3126. upb_alloc *tmp; /* Alloc for addtab and any other tmp data. */
  3127. upb_strtable *addtab; /* full_name -> packed def ptr for new defs. */
  3128. upb_status *status; /* Record errors here. */
  3129. } symtab_addctx;
  3130. static char* strviewdup(const symtab_addctx *ctx, upb_strview view) {
  3131. return upb_strdup2(view.data, view.size, ctx->alloc);
  3132. }
  3133. static bool streql2(const char *a, size_t n, const char *b) {
  3134. return n == strlen(b) && memcmp(a, b, n) == 0;
  3135. }
  3136. static bool streql_view(upb_strview view, const char *b) {
  3137. return streql2(view.data, view.size, b);
  3138. }
  3139. static const char *makefullname(const symtab_addctx *ctx, const char *prefix,
  3140. upb_strview name) {
  3141. if (prefix) {
  3142. /* ret = prefix + '.' + name; */
  3143. size_t n = strlen(prefix);
  3144. char *ret = upb_malloc(ctx->alloc, n + name.size + 2);
  3145. CHK_OOM(ret);
  3146. strcpy(ret, prefix);
  3147. ret[n] = '.';
  3148. memcpy(&ret[n + 1], name.data, name.size);
  3149. ret[n + 1 + name.size] = '\0';
  3150. return ret;
  3151. } else {
  3152. return strviewdup(ctx, name);
  3153. }
  3154. }
  3155. static bool symtab_add(const symtab_addctx *ctx, const char *name,
  3156. upb_value v) {
  3157. upb_value tmp;
  3158. if (upb_strtable_lookup(ctx->addtab, name, &tmp) ||
  3159. upb_strtable_lookup(&ctx->symtab->syms, name, &tmp)) {
  3160. upb_status_seterrf(ctx->status, "duplicate symbol '%s'", name);
  3161. return false;
  3162. }
  3163. CHK_OOM(upb_strtable_insert3(ctx->addtab, name, strlen(name), v, ctx->tmp));
  3164. return true;
  3165. }
  3166. /* Given a symbol and the base symbol inside which it is defined, find the
  3167. * symbol's definition in t. */
  3168. static bool resolvename(const upb_strtable *t, const upb_fielddef *f,
  3169. const char *base, upb_strview sym,
  3170. upb_deftype_t type, upb_status *status,
  3171. const void **def) {
  3172. if(sym.size == 0) return NULL;
  3173. if(sym.data[0] == '.') {
  3174. /* Symbols starting with '.' are absolute, so we do a single lookup.
  3175. * Slice to omit the leading '.' */
  3176. upb_value v;
  3177. if (!upb_strtable_lookup2(t, sym.data + 1, sym.size - 1, &v)) {
  3178. return false;
  3179. }
  3180. *def = unpack_def(v, type);
  3181. if (!*def) {
  3182. upb_status_seterrf(status,
  3183. "type mismatch when resolving field %s, name %s",
  3184. f->full_name, sym.data);
  3185. return false;
  3186. }
  3187. return true;
  3188. } else {
  3189. /* Remove components from base until we find an entry or run out.
  3190. * TODO: This branch is totally broken, but currently not used. */
  3191. (void)base;
  3192. UPB_ASSERT(false);
  3193. return false;
  3194. }
  3195. }
  3196. const void *symtab_resolve(const symtab_addctx *ctx, const upb_fielddef *f,
  3197. const char *base, upb_strview sym,
  3198. upb_deftype_t type) {
  3199. const void *ret;
  3200. if (!resolvename(ctx->addtab, f, base, sym, type, ctx->status, &ret) &&
  3201. !resolvename(&ctx->symtab->syms, f, base, sym, type, ctx->status, &ret)) {
  3202. if (upb_ok(ctx->status)) {
  3203. upb_status_seterrf(ctx->status, "couldn't resolve name '%s'", sym.data);
  3204. }
  3205. return false;
  3206. }
  3207. return ret;
  3208. }
  3209. static bool create_oneofdef(
  3210. const symtab_addctx *ctx, upb_msgdef *m,
  3211. const google_protobuf_OneofDescriptorProto *oneof_proto) {
  3212. upb_oneofdef *o;
  3213. upb_strview name = google_protobuf_OneofDescriptorProto_name(oneof_proto);
  3214. upb_value v;
  3215. o = (upb_oneofdef*)&m->oneofs[m->oneof_count++];
  3216. o->parent = m;
  3217. o->full_name = makefullname(ctx, m->full_name, name);
  3218. v = pack_def(o, UPB_DEFTYPE_ONEOF);
  3219. CHK_OOM(symtab_add(ctx, o->full_name, v));
  3220. CHK_OOM(upb_strtable_insert3(&m->ntof, name.data, name.size, v, ctx->alloc));
  3221. CHK_OOM(upb_inttable_init2(&o->itof, UPB_CTYPE_CONSTPTR, ctx->alloc));
  3222. CHK_OOM(upb_strtable_init2(&o->ntof, UPB_CTYPE_CONSTPTR, ctx->alloc));
  3223. return true;
  3224. }
  3225. static bool parse_default(const symtab_addctx *ctx, const char *str, size_t len,
  3226. upb_fielddef *f) {
  3227. char *end;
  3228. char nullz[64];
  3229. errno = 0;
  3230. switch (upb_fielddef_type(f)) {
  3231. case UPB_TYPE_INT32:
  3232. case UPB_TYPE_INT64:
  3233. case UPB_TYPE_UINT32:
  3234. case UPB_TYPE_UINT64:
  3235. case UPB_TYPE_DOUBLE:
  3236. case UPB_TYPE_FLOAT:
  3237. /* Standard C number parsing functions expect null-terminated strings. */
  3238. if (len >= sizeof(nullz) - 1) {
  3239. return false;
  3240. }
  3241. memcpy(nullz, str, len);
  3242. nullz[len] = '\0';
  3243. str = nullz;
  3244. break;
  3245. default:
  3246. break;
  3247. }
  3248. switch (upb_fielddef_type(f)) {
  3249. case UPB_TYPE_INT32: {
  3250. long val = strtol(str, &end, 0);
  3251. CHK(val <= INT32_MAX && val >= INT32_MIN && errno != ERANGE && !*end);
  3252. f->defaultval.sint = val;
  3253. break;
  3254. }
  3255. case UPB_TYPE_ENUM: {
  3256. const upb_enumdef *e = f->sub.enumdef;
  3257. int32_t val;
  3258. CHK(upb_enumdef_ntoi(e, str, len, &val));
  3259. f->defaultval.sint = val;
  3260. break;
  3261. }
  3262. case UPB_TYPE_INT64: {
  3263. /* XXX: Need to write our own strtoll, since it's not available in c89. */
  3264. long long val = strtol(str, &end, 0);
  3265. CHK(val <= INT64_MAX && val >= INT64_MIN && errno != ERANGE && !*end);
  3266. f->defaultval.sint = val;
  3267. break;
  3268. }
  3269. case UPB_TYPE_UINT32: {
  3270. unsigned long val = strtoul(str, &end, 0);
  3271. CHK(val <= UINT32_MAX && errno != ERANGE && !*end);
  3272. f->defaultval.uint = val;
  3273. break;
  3274. }
  3275. case UPB_TYPE_UINT64: {
  3276. /* XXX: Need to write our own strtoull, since it's not available in c89. */
  3277. unsigned long long val = strtoul(str, &end, 0);
  3278. CHK(val <= UINT64_MAX && errno != ERANGE && !*end);
  3279. f->defaultval.uint = val;
  3280. break;
  3281. }
  3282. case UPB_TYPE_DOUBLE: {
  3283. double val = strtod(str, &end);
  3284. CHK(errno != ERANGE && !*end);
  3285. f->defaultval.dbl = val;
  3286. break;
  3287. }
  3288. case UPB_TYPE_FLOAT: {
  3289. /* XXX: Need to write our own strtof, since it's not available in c89. */
  3290. float val = strtod(str, &end);
  3291. CHK(errno != ERANGE && !*end);
  3292. f->defaultval.flt = val;
  3293. break;
  3294. }
  3295. case UPB_TYPE_BOOL: {
  3296. if (streql2(str, len, "false")) {
  3297. f->defaultval.boolean = false;
  3298. } else if (streql2(str, len, "true")) {
  3299. f->defaultval.boolean = true;
  3300. } else {
  3301. return false;
  3302. }
  3303. }
  3304. case UPB_TYPE_STRING:
  3305. f->defaultval.str = newstr(ctx->alloc, str, len);
  3306. break;
  3307. case UPB_TYPE_BYTES:
  3308. /* XXX: need to interpret the C-escaped value. */
  3309. f->defaultval.str = newstr(ctx->alloc, str, len);
  3310. break;
  3311. case UPB_TYPE_MESSAGE:
  3312. /* Should not have a default value. */
  3313. return false;
  3314. }
  3315. return true;
  3316. }
  3317. static void set_default_default(const symtab_addctx *ctx, upb_fielddef *f) {
  3318. switch (upb_fielddef_type(f)) {
  3319. case UPB_TYPE_INT32:
  3320. case UPB_TYPE_INT64:
  3321. case UPB_TYPE_ENUM:
  3322. f->defaultval.sint = 0;
  3323. break;
  3324. case UPB_TYPE_UINT64:
  3325. case UPB_TYPE_UINT32:
  3326. f->defaultval.uint = 0;
  3327. break;
  3328. case UPB_TYPE_DOUBLE:
  3329. case UPB_TYPE_FLOAT:
  3330. f->defaultval.dbl = 0;
  3331. break;
  3332. case UPB_TYPE_STRING:
  3333. case UPB_TYPE_BYTES:
  3334. f->defaultval.str = newstr(ctx->alloc, NULL, 0);
  3335. break;
  3336. case UPB_TYPE_BOOL:
  3337. f->defaultval.boolean = false;
  3338. break;
  3339. case UPB_TYPE_MESSAGE:
  3340. break;
  3341. }
  3342. }
  3343. static bool create_fielddef(
  3344. const symtab_addctx *ctx, const char *prefix, upb_msgdef *m,
  3345. const google_protobuf_FieldDescriptorProto *field_proto) {
  3346. upb_alloc *alloc = ctx->alloc;
  3347. upb_fielddef *f;
  3348. const google_protobuf_FieldOptions *options;
  3349. upb_strview name;
  3350. const char *full_name;
  3351. const char *shortname;
  3352. uint32_t field_number;
  3353. if (!google_protobuf_FieldDescriptorProto_has_name(field_proto)) {
  3354. upb_status_seterrmsg(ctx->status, "field has no name");
  3355. return false;
  3356. }
  3357. name = google_protobuf_FieldDescriptorProto_name(field_proto);
  3358. CHK(upb_isident(name, false, ctx->status));
  3359. full_name = makefullname(ctx, prefix, name);
  3360. shortname = shortdefname(full_name);
  3361. field_number = google_protobuf_FieldDescriptorProto_number(field_proto);
  3362. if (field_number == 0 || field_number > UPB_MAX_FIELDNUMBER) {
  3363. upb_status_seterrf(ctx->status, "invalid field number (%u)", field_number);
  3364. return false;
  3365. }
  3366. if (m) {
  3367. /* direct message field. */
  3368. upb_value v, packed_v;
  3369. f = (upb_fielddef*)&m->fields[m->field_count++];
  3370. f->msgdef = m;
  3371. f->is_extension_ = false;
  3372. packed_v = pack_def(f, UPB_DEFTYPE_FIELD);
  3373. v = upb_value_constptr(f);
  3374. if (!upb_strtable_insert3(&m->ntof, name.data, name.size, packed_v, alloc)) {
  3375. upb_status_seterrf(ctx->status, "duplicate field name (%s)", shortname);
  3376. return false;
  3377. }
  3378. if (!upb_inttable_insert2(&m->itof, field_number, v, alloc)) {
  3379. upb_status_seterrf(ctx->status, "duplicate field number (%u)",
  3380. field_number);
  3381. return false;
  3382. }
  3383. } else {
  3384. /* extension field. */
  3385. f = (upb_fielddef*)&ctx->file->exts[ctx->file->ext_count];
  3386. f->is_extension_ = true;
  3387. CHK_OOM(symtab_add(ctx, full_name, pack_def(f, UPB_DEFTYPE_FIELD)));
  3388. }
  3389. f->full_name = full_name;
  3390. f->file = ctx->file;
  3391. f->type_ = (int)google_protobuf_FieldDescriptorProto_type(field_proto);
  3392. f->label_ = (int)google_protobuf_FieldDescriptorProto_label(field_proto);
  3393. f->number_ = field_number;
  3394. f->oneof = NULL;
  3395. /* We can't resolve the subdef or (in the case of extensions) the containing
  3396. * message yet, because it may not have been defined yet. We stash a pointer
  3397. * to the field_proto until later when we can properly resolve it. */
  3398. f->sub.unresolved = field_proto;
  3399. if (f->label_ == UPB_LABEL_REQUIRED && f->file->syntax == UPB_SYNTAX_PROTO3) {
  3400. upb_status_seterrf(ctx->status, "proto3 fields cannot be required (%s)",
  3401. f->full_name);
  3402. return false;
  3403. }
  3404. if (google_protobuf_FieldDescriptorProto_has_oneof_index(field_proto)) {
  3405. int oneof_index =
  3406. google_protobuf_FieldDescriptorProto_oneof_index(field_proto);
  3407. upb_oneofdef *oneof;
  3408. upb_value v = upb_value_constptr(f);
  3409. if (upb_fielddef_label(f) != UPB_LABEL_OPTIONAL) {
  3410. upb_status_seterrf(ctx->status,
  3411. "fields in oneof must have OPTIONAL label (%s)",
  3412. f->full_name);
  3413. return false;
  3414. }
  3415. if (!m) {
  3416. upb_status_seterrf(ctx->status,
  3417. "oneof_index provided for extension field (%s)",
  3418. f->full_name);
  3419. return false;
  3420. }
  3421. if (oneof_index >= m->oneof_count) {
  3422. upb_status_seterrf(ctx->status, "oneof_index out of range (%s)",
  3423. f->full_name);
  3424. return false;
  3425. }
  3426. oneof = (upb_oneofdef*)&m->oneofs[oneof_index];
  3427. f->oneof = oneof;
  3428. CHK(upb_inttable_insert2(&oneof->itof, f->number_, v, alloc));
  3429. CHK(upb_strtable_insert3(&oneof->ntof, name.data, name.size, v, alloc));
  3430. } else {
  3431. f->oneof = NULL;
  3432. }
  3433. if (google_protobuf_FieldDescriptorProto_has_options(field_proto)) {
  3434. options = google_protobuf_FieldDescriptorProto_options(field_proto);
  3435. f->lazy_ = google_protobuf_FieldOptions_lazy(options);
  3436. f->packed_ = google_protobuf_FieldOptions_packed(options);
  3437. } else {
  3438. f->lazy_ = false;
  3439. f->packed_ = false;
  3440. }
  3441. return true;
  3442. }
  3443. static bool create_enumdef(
  3444. const symtab_addctx *ctx, const char *prefix,
  3445. const google_protobuf_EnumDescriptorProto *enum_proto) {
  3446. upb_enumdef *e;
  3447. const google_protobuf_EnumValueDescriptorProto *const *values;
  3448. upb_strview name;
  3449. size_t i, n;
  3450. name = google_protobuf_EnumDescriptorProto_name(enum_proto);
  3451. CHK(upb_isident(name, false, ctx->status));
  3452. e = (upb_enumdef*)&ctx->file->enums[ctx->file->enum_count++];
  3453. e->full_name = makefullname(ctx, prefix, name);
  3454. CHK_OOM(symtab_add(ctx, e->full_name, pack_def(e, UPB_DEFTYPE_ENUM)));
  3455. CHK_OOM(upb_strtable_init2(&e->ntoi, UPB_CTYPE_INT32, ctx->alloc));
  3456. CHK_OOM(upb_inttable_init2(&e->iton, UPB_CTYPE_CSTR, ctx->alloc));
  3457. e->file = ctx->file;
  3458. e->defaultval = 0;
  3459. values = google_protobuf_EnumDescriptorProto_value(enum_proto, &n);
  3460. if (n == 0) {
  3461. upb_status_seterrf(ctx->status,
  3462. "enums must contain at least one value (%s)",
  3463. e->full_name);
  3464. return false;
  3465. }
  3466. for (i = 0; i < n; i++) {
  3467. const google_protobuf_EnumValueDescriptorProto *value = values[i];
  3468. upb_strview name = google_protobuf_EnumValueDescriptorProto_name(value);
  3469. char *name2 = strviewdup(ctx, name);
  3470. int32_t num = google_protobuf_EnumValueDescriptorProto_number(value);
  3471. upb_value v = upb_value_int32(num);
  3472. if (i == 0 && e->file->syntax == UPB_SYNTAX_PROTO3 && num != 0) {
  3473. upb_status_seterrf(ctx->status,
  3474. "for proto3, the first enum value must be zero (%s)",
  3475. e->full_name);
  3476. return false;
  3477. }
  3478. if (upb_strtable_lookup(&e->ntoi, name2, NULL)) {
  3479. upb_status_seterrf(ctx->status, "duplicate enum label '%s'", name2);
  3480. return false;
  3481. }
  3482. CHK_OOM(name2)
  3483. CHK_OOM(
  3484. upb_strtable_insert3(&e->ntoi, name2, strlen(name2), v, ctx->alloc));
  3485. if (!upb_inttable_lookup(&e->iton, num, NULL)) {
  3486. upb_value v = upb_value_cstr(name2);
  3487. CHK_OOM(upb_inttable_insert2(&e->iton, num, v, ctx->alloc));
  3488. }
  3489. }
  3490. upb_inttable_compact2(&e->iton, ctx->alloc);
  3491. return true;
  3492. }
  3493. static bool create_msgdef(const symtab_addctx *ctx, const char *prefix,
  3494. const google_protobuf_DescriptorProto *msg_proto) {
  3495. upb_msgdef *m;
  3496. const google_protobuf_MessageOptions *options;
  3497. const google_protobuf_OneofDescriptorProto *const *oneofs;
  3498. const google_protobuf_FieldDescriptorProto *const *fields;
  3499. const google_protobuf_EnumDescriptorProto *const *enums;
  3500. const google_protobuf_DescriptorProto *const *msgs;
  3501. size_t i, n;
  3502. upb_strview name;
  3503. name = google_protobuf_DescriptorProto_name(msg_proto);
  3504. CHK(upb_isident(name, false, ctx->status));
  3505. m = (upb_msgdef*)&ctx->file->msgs[ctx->file->msg_count++];
  3506. m->full_name = makefullname(ctx, prefix, name);
  3507. CHK_OOM(symtab_add(ctx, m->full_name, pack_def(m, UPB_DEFTYPE_MSG)));
  3508. CHK_OOM(upb_inttable_init2(&m->itof, UPB_CTYPE_CONSTPTR, ctx->alloc));
  3509. CHK_OOM(upb_strtable_init2(&m->ntof, UPB_CTYPE_CONSTPTR, ctx->alloc));
  3510. m->file = ctx->file;
  3511. m->map_entry = false;
  3512. options = google_protobuf_DescriptorProto_options(msg_proto);
  3513. if (options) {
  3514. m->map_entry = google_protobuf_MessageOptions_map_entry(options);
  3515. }
  3516. oneofs = google_protobuf_DescriptorProto_oneof_decl(msg_proto, &n);
  3517. m->oneof_count = 0;
  3518. m->oneofs = upb_malloc(ctx->alloc, sizeof(*m->oneofs) * n);
  3519. for (i = 0; i < n; i++) {
  3520. CHK(create_oneofdef(ctx, m, oneofs[i]));
  3521. }
  3522. fields = google_protobuf_DescriptorProto_field(msg_proto, &n);
  3523. m->field_count = 0;
  3524. m->fields = upb_malloc(ctx->alloc, sizeof(*m->fields) * n);
  3525. for (i = 0; i < n; i++) {
  3526. CHK(create_fielddef(ctx, m->full_name, m, fields[i]));
  3527. }
  3528. CHK(assign_msg_indices(m, ctx->status));
  3529. assign_msg_wellknowntype(m);
  3530. upb_inttable_compact2(&m->itof, ctx->alloc);
  3531. /* This message is built. Now build nested messages and enums. */
  3532. enums = google_protobuf_DescriptorProto_enum_type(msg_proto, &n);
  3533. for (i = 0; i < n; i++) {
  3534. CHK(create_enumdef(ctx, m->full_name, enums[i]));
  3535. }
  3536. msgs = google_protobuf_DescriptorProto_nested_type(msg_proto, &n);
  3537. for (i = 0; i < n; i++) {
  3538. CHK(create_msgdef(ctx, m->full_name, msgs[i]));
  3539. }
  3540. return true;
  3541. }
  3542. typedef struct {
  3543. int msg_count;
  3544. int enum_count;
  3545. int ext_count;
  3546. } decl_counts;
  3547. static void count_types_in_msg(const google_protobuf_DescriptorProto *msg_proto,
  3548. decl_counts *counts) {
  3549. const google_protobuf_DescriptorProto *const *msgs;
  3550. size_t i, n;
  3551. counts->msg_count++;
  3552. msgs = google_protobuf_DescriptorProto_nested_type(msg_proto, &n);
  3553. for (i = 0; i < n; i++) {
  3554. count_types_in_msg(msgs[i], counts);
  3555. }
  3556. google_protobuf_DescriptorProto_enum_type(msg_proto, &n);
  3557. counts->enum_count += n;
  3558. google_protobuf_DescriptorProto_extension(msg_proto, &n);
  3559. counts->ext_count += n;
  3560. }
  3561. static void count_types_in_file(
  3562. const google_protobuf_FileDescriptorProto *file_proto,
  3563. decl_counts *counts) {
  3564. const google_protobuf_DescriptorProto *const *msgs;
  3565. size_t i, n;
  3566. msgs = google_protobuf_FileDescriptorProto_message_type(file_proto, &n);
  3567. for (i = 0; i < n; i++) {
  3568. count_types_in_msg(msgs[i], counts);
  3569. }
  3570. google_protobuf_FileDescriptorProto_enum_type(file_proto, &n);
  3571. counts->enum_count += n;
  3572. google_protobuf_FileDescriptorProto_extension(file_proto, &n);
  3573. counts->ext_count += n;
  3574. }
  3575. static bool resolve_fielddef(const symtab_addctx *ctx, const char *prefix,
  3576. upb_fielddef *f) {
  3577. upb_strview name;
  3578. const google_protobuf_FieldDescriptorProto *field_proto = f->sub.unresolved;
  3579. if (f->is_extension_) {
  3580. if (!google_protobuf_FieldDescriptorProto_has_extendee(field_proto)) {
  3581. upb_status_seterrf(ctx->status,
  3582. "extension for field '%s' had no extendee",
  3583. f->full_name);
  3584. return false;
  3585. }
  3586. name = google_protobuf_FieldDescriptorProto_extendee(field_proto);
  3587. f->msgdef = symtab_resolve(ctx, f, prefix, name, UPB_DEFTYPE_MSG);
  3588. CHK(f->msgdef);
  3589. }
  3590. if ((upb_fielddef_issubmsg(f) || f->type_ == UPB_DESCRIPTOR_TYPE_ENUM) &&
  3591. !google_protobuf_FieldDescriptorProto_has_type_name(field_proto)) {
  3592. upb_status_seterrf(ctx->status, "field '%s' is missing type name",
  3593. f->full_name);
  3594. return false;
  3595. }
  3596. name = google_protobuf_FieldDescriptorProto_type_name(field_proto);
  3597. if (upb_fielddef_issubmsg(f)) {
  3598. f->sub.msgdef = symtab_resolve(ctx, f, prefix, name, UPB_DEFTYPE_MSG);
  3599. CHK(f->sub.msgdef);
  3600. } else if (f->type_ == UPB_DESCRIPTOR_TYPE_ENUM) {
  3601. f->sub.enumdef = symtab_resolve(ctx, f, prefix, name, UPB_DEFTYPE_ENUM);
  3602. CHK(f->sub.enumdef);
  3603. }
  3604. /* Have to delay resolving of the default value until now because of the enum
  3605. * case, since enum defaults are specified with a label. */
  3606. if (google_protobuf_FieldDescriptorProto_has_default_value(field_proto)) {
  3607. upb_strview defaultval =
  3608. google_protobuf_FieldDescriptorProto_default_value(field_proto);
  3609. if (f->file->syntax == UPB_SYNTAX_PROTO3) {
  3610. upb_status_seterrf(ctx->status,
  3611. "proto3 fields cannot have explicit defaults (%s)",
  3612. f->full_name);
  3613. return false;
  3614. }
  3615. if (upb_fielddef_issubmsg(f)) {
  3616. upb_status_seterrf(ctx->status,
  3617. "message fields cannot have explicit defaults (%s)",
  3618. f->full_name);
  3619. return false;
  3620. }
  3621. if (!parse_default(ctx, defaultval.data, defaultval.size, f)) {
  3622. upb_status_seterrf(ctx->status,
  3623. "couldn't parse default '" UPB_STRVIEW_FORMAT
  3624. "' for field (%s)",
  3625. UPB_STRVIEW_ARGS(defaultval), f->full_name);
  3626. return false;
  3627. }
  3628. } else {
  3629. set_default_default(ctx, f);
  3630. }
  3631. return true;
  3632. }
  3633. static bool build_filedef(
  3634. const symtab_addctx *ctx, upb_filedef *file,
  3635. const google_protobuf_FileDescriptorProto *file_proto) {
  3636. upb_alloc *alloc = ctx->alloc;
  3637. const google_protobuf_FileOptions *file_options_proto;
  3638. const google_protobuf_DescriptorProto *const *msgs;
  3639. const google_protobuf_EnumDescriptorProto *const *enums;
  3640. const google_protobuf_FieldDescriptorProto *const *exts;
  3641. const upb_strview* strs;
  3642. size_t i, n;
  3643. decl_counts counts = {0};
  3644. count_types_in_file(file_proto, &counts);
  3645. file->msgs = upb_malloc(alloc, sizeof(*file->msgs) * counts.msg_count);
  3646. file->enums = upb_malloc(alloc, sizeof(*file->enums) * counts.enum_count);
  3647. file->exts = upb_malloc(alloc, sizeof(*file->exts) * counts.ext_count);
  3648. CHK_OOM(counts.msg_count == 0 || file->msgs);
  3649. CHK_OOM(counts.enum_count == 0 || file->enums);
  3650. CHK_OOM(counts.ext_count == 0 || file->exts);
  3651. /* We increment these as defs are added. */
  3652. file->msg_count = 0;
  3653. file->enum_count = 0;
  3654. file->ext_count = 0;
  3655. if (!google_protobuf_FileDescriptorProto_has_name(file_proto)) {
  3656. upb_status_seterrmsg(ctx->status, "File has no name");
  3657. return false;
  3658. }
  3659. file->name =
  3660. strviewdup(ctx, google_protobuf_FileDescriptorProto_name(file_proto));
  3661. file->phpprefix = NULL;
  3662. file->phpnamespace = NULL;
  3663. if (google_protobuf_FileDescriptorProto_has_package(file_proto)) {
  3664. upb_strview package =
  3665. google_protobuf_FileDescriptorProto_package(file_proto);
  3666. CHK(upb_isident(package, true, ctx->status));
  3667. file->package = strviewdup(ctx, package);
  3668. } else {
  3669. file->package = NULL;
  3670. }
  3671. if (google_protobuf_FileDescriptorProto_has_syntax(file_proto)) {
  3672. upb_strview syntax =
  3673. google_protobuf_FileDescriptorProto_syntax(file_proto);
  3674. if (streql_view(syntax, "proto2")) {
  3675. file->syntax = UPB_SYNTAX_PROTO2;
  3676. } else if (streql_view(syntax, "proto3")) {
  3677. file->syntax = UPB_SYNTAX_PROTO3;
  3678. } else {
  3679. upb_status_seterrf(ctx->status, "Invalid syntax '%s'", syntax);
  3680. return false;
  3681. }
  3682. } else {
  3683. file->syntax = UPB_SYNTAX_PROTO2;
  3684. }
  3685. /* Read options. */
  3686. file_options_proto = google_protobuf_FileDescriptorProto_options(file_proto);
  3687. if (file_options_proto) {
  3688. if (google_protobuf_FileOptions_has_php_class_prefix(file_options_proto)) {
  3689. file->phpprefix = strviewdup(
  3690. ctx,
  3691. google_protobuf_FileOptions_php_class_prefix(file_options_proto));
  3692. }
  3693. if (google_protobuf_FileOptions_has_php_namespace(file_options_proto)) {
  3694. file->phpnamespace = strviewdup(
  3695. ctx, google_protobuf_FileOptions_php_namespace(file_options_proto));
  3696. }
  3697. }
  3698. /* Verify dependencies. */
  3699. strs = google_protobuf_FileDescriptorProto_dependency(file_proto, &n);
  3700. file->deps = upb_malloc(alloc, sizeof(*file->deps) * n) ;
  3701. CHK_OOM(n == 0 || file->deps);
  3702. for (i = 0; i < n; i++) {
  3703. upb_strview dep_name = strs[i];
  3704. upb_value v;
  3705. if (!upb_strtable_lookup2(&ctx->symtab->files, dep_name.data,
  3706. dep_name.size, &v)) {
  3707. upb_status_seterrf(ctx->status,
  3708. "Depends on file '" UPB_STRVIEW_FORMAT
  3709. "', but it has not been loaded",
  3710. UPB_STRVIEW_ARGS(dep_name));
  3711. return false;
  3712. }
  3713. file->deps[i] = upb_value_getconstptr(v);
  3714. }
  3715. /* Create messages. */
  3716. msgs = google_protobuf_FileDescriptorProto_message_type(file_proto, &n);
  3717. for (i = 0; i < n; i++) {
  3718. CHK(create_msgdef(ctx, file->package, msgs[i]));
  3719. }
  3720. /* Create enums. */
  3721. enums = google_protobuf_FileDescriptorProto_enum_type(file_proto, &n);
  3722. for (i = 0; i < n; i++) {
  3723. CHK(create_enumdef(ctx, file->package, enums[i]));
  3724. }
  3725. /* Create extensions. */
  3726. exts = google_protobuf_FileDescriptorProto_extension(file_proto, &n);
  3727. file->exts = upb_malloc(alloc, sizeof(*file->exts) * n);
  3728. CHK_OOM(n == 0 || file->exts);
  3729. for (i = 0; i < n; i++) {
  3730. CHK(create_fielddef(ctx, file->package, NULL, exts[i]));
  3731. }
  3732. /* Now that all names are in the table, resolve references. */
  3733. for (i = 0; i < file->ext_count; i++) {
  3734. CHK(resolve_fielddef(ctx, file->package, (upb_fielddef*)&file->exts[i]));
  3735. }
  3736. for (i = 0; i < file->msg_count; i++) {
  3737. const upb_msgdef *m = &file->msgs[i];
  3738. int j;
  3739. for (j = 0; j < m->field_count; j++) {
  3740. CHK(resolve_fielddef(ctx, m->full_name, (upb_fielddef*)&m->fields[j]));
  3741. }
  3742. }
  3743. return true;
  3744. }
  3745. static bool upb_symtab_addtotabs(upb_symtab *s, symtab_addctx *ctx,
  3746. upb_status *status) {
  3747. const upb_filedef *file = ctx->file;
  3748. upb_alloc *alloc = upb_arena_alloc(s->arena);
  3749. upb_strtable_iter iter;
  3750. CHK_OOM(upb_strtable_insert3(&s->files, file->name, strlen(file->name),
  3751. upb_value_constptr(file), alloc));
  3752. upb_strtable_begin(&iter, ctx->addtab);
  3753. for (; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
  3754. const char *key = upb_strtable_iter_key(&iter);
  3755. size_t keylen = upb_strtable_iter_keylength(&iter);
  3756. upb_value value = upb_strtable_iter_value(&iter);
  3757. CHK_OOM(upb_strtable_insert3(&s->syms, key, keylen, value, alloc));
  3758. }
  3759. return true;
  3760. }
  3761. /* upb_filedef ****************************************************************/
  3762. const char *upb_filedef_name(const upb_filedef *f) {
  3763. return f->name;
  3764. }
  3765. const char *upb_filedef_package(const upb_filedef *f) {
  3766. return f->package;
  3767. }
  3768. const char *upb_filedef_phpprefix(const upb_filedef *f) {
  3769. return f->phpprefix;
  3770. }
  3771. const char *upb_filedef_phpnamespace(const upb_filedef *f) {
  3772. return f->phpnamespace;
  3773. }
  3774. upb_syntax_t upb_filedef_syntax(const upb_filedef *f) {
  3775. return f->syntax;
  3776. }
  3777. int upb_filedef_msgcount(const upb_filedef *f) {
  3778. return f->msg_count;
  3779. }
  3780. int upb_filedef_depcount(const upb_filedef *f) {
  3781. return f->dep_count;
  3782. }
  3783. int upb_filedef_enumcount(const upb_filedef *f) {
  3784. return f->enum_count;
  3785. }
  3786. const upb_filedef *upb_filedef_dep(const upb_filedef *f, int i) {
  3787. return i < 0 || i >= f->dep_count ? NULL : f->deps[i];
  3788. }
  3789. const upb_msgdef *upb_filedef_msg(const upb_filedef *f, int i) {
  3790. return i < 0 || i >= f->msg_count ? NULL : &f->msgs[i];
  3791. }
  3792. const upb_enumdef *upb_filedef_enum(const upb_filedef *f, int i) {
  3793. return i < 0 || i >= f->enum_count ? NULL : &f->enums[i];
  3794. }
  3795. void upb_symtab_free(upb_symtab *s) {
  3796. upb_arena_free(s->arena);
  3797. upb_gfree(s);
  3798. }
  3799. upb_symtab *upb_symtab_new(void) {
  3800. upb_symtab *s = upb_gmalloc(sizeof(*s));
  3801. upb_alloc *alloc;
  3802. if (!s) {
  3803. return NULL;
  3804. }
  3805. s->arena = upb_arena_new();
  3806. alloc = upb_arena_alloc(s->arena);
  3807. if (!upb_strtable_init2(&s->syms, UPB_CTYPE_CONSTPTR, alloc) ||
  3808. !upb_strtable_init2(&s->files, UPB_CTYPE_CONSTPTR, alloc)) {
  3809. upb_arena_free(s->arena);
  3810. upb_gfree(s);
  3811. s = NULL;
  3812. }
  3813. return s;
  3814. }
  3815. const upb_msgdef *upb_symtab_lookupmsg(const upb_symtab *s, const char *sym) {
  3816. upb_value v;
  3817. return upb_strtable_lookup(&s->syms, sym, &v) ?
  3818. unpack_def(v, UPB_DEFTYPE_MSG) : NULL;
  3819. }
  3820. const upb_msgdef *upb_symtab_lookupmsg2(const upb_symtab *s, const char *sym,
  3821. size_t len) {
  3822. upb_value v;
  3823. return upb_strtable_lookup2(&s->syms, sym, len, &v) ?
  3824. unpack_def(v, UPB_DEFTYPE_MSG) : NULL;
  3825. }
  3826. const upb_enumdef *upb_symtab_lookupenum(const upb_symtab *s, const char *sym) {
  3827. upb_value v;
  3828. return upb_strtable_lookup(&s->syms, sym, &v) ?
  3829. unpack_def(v, UPB_DEFTYPE_ENUM) : NULL;
  3830. }
  3831. const upb_filedef *upb_symtab_lookupfile(const upb_symtab *s, const char *name) {
  3832. upb_value v;
  3833. return upb_strtable_lookup(&s->files, name, &v) ? upb_value_getconstptr(v)
  3834. : NULL;
  3835. }
  3836. const upb_filedef *upb_symtab_addfile(
  3837. upb_symtab *s, const google_protobuf_FileDescriptorProto *file_proto,
  3838. upb_status *status) {
  3839. upb_arena *tmparena = upb_arena_new();
  3840. upb_strtable addtab;
  3841. upb_alloc *alloc = upb_arena_alloc(s->arena);
  3842. upb_filedef *file = upb_malloc(alloc, sizeof(*file));
  3843. bool ok;
  3844. symtab_addctx ctx;
  3845. ctx.file = file;
  3846. ctx.symtab = s;
  3847. ctx.alloc = alloc;
  3848. ctx.tmp = upb_arena_alloc(tmparena);
  3849. ctx.addtab = &addtab;
  3850. ctx.status = status;
  3851. ok = file &&
  3852. upb_strtable_init2(&addtab, UPB_CTYPE_CONSTPTR, ctx.tmp) &&
  3853. build_filedef(&ctx, file, file_proto) &&
  3854. upb_symtab_addtotabs(s, &ctx, status);
  3855. upb_arena_free(tmparena);
  3856. return ok ? file : NULL;
  3857. }
  3858. /* Include here since we want most of this file to be stdio-free. */
  3859. #include <stdio.h>
  3860. bool _upb_symtab_loaddefinit(upb_symtab *s, const upb_def_init *init) {
  3861. /* Since this function should never fail (it would indicate a bug in upb) we
  3862. * print errors to stderr instead of returning error status to the user. */
  3863. upb_def_init **deps = init->deps;
  3864. google_protobuf_FileDescriptorProto *file;
  3865. upb_arena *arena;
  3866. upb_status status;
  3867. upb_status_clear(&status);
  3868. if (upb_strtable_lookup(&s->files, init->filename, NULL)) {
  3869. return true;
  3870. }
  3871. arena = upb_arena_new();
  3872. for (; *deps; deps++) {
  3873. if (!_upb_symtab_loaddefinit(s, *deps)) goto err;
  3874. }
  3875. file = google_protobuf_FileDescriptorProto_parse(
  3876. init->descriptor.data, init->descriptor.size, arena);
  3877. if (!file) {
  3878. upb_status_seterrf(
  3879. &status,
  3880. "Failed to parse compiled-in descriptor for file '%s'. This should "
  3881. "never happen.",
  3882. init->filename);
  3883. goto err;
  3884. }
  3885. if (!upb_symtab_addfile(s, file, &status)) goto err;
  3886. upb_arena_free(arena);
  3887. return true;
  3888. err:
  3889. fprintf(stderr, "Error loading compiled-in descriptor: %s\n",
  3890. upb_status_errmsg(&status));
  3891. upb_arena_free(arena);
  3892. return false;
  3893. }
  3894. #undef CHK
  3895. #undef CHK_OOM
  3896. static bool is_power_of_two(size_t val) {
  3897. return (val & (val - 1)) == 0;
  3898. }
  3899. /* Align up to the given power of 2. */
  3900. static size_t align_up(size_t val, size_t align) {
  3901. UPB_ASSERT(is_power_of_two(align));
  3902. return (val + align - 1) & ~(align - 1);
  3903. }
  3904. static size_t div_round_up(size_t n, size_t d) {
  3905. return (n + d - 1) / d;
  3906. }
  3907. static size_t upb_msgval_sizeof2(upb_fieldtype_t type) {
  3908. switch (type) {
  3909. case UPB_TYPE_DOUBLE:
  3910. case UPB_TYPE_INT64:
  3911. case UPB_TYPE_UINT64:
  3912. return 8;
  3913. case UPB_TYPE_ENUM:
  3914. case UPB_TYPE_INT32:
  3915. case UPB_TYPE_UINT32:
  3916. case UPB_TYPE_FLOAT:
  3917. return 4;
  3918. case UPB_TYPE_BOOL:
  3919. return 1;
  3920. case UPB_TYPE_MESSAGE:
  3921. return sizeof(void*);
  3922. case UPB_TYPE_BYTES:
  3923. case UPB_TYPE_STRING:
  3924. return sizeof(upb_strview);
  3925. }
  3926. UPB_UNREACHABLE();
  3927. }
  3928. static uint8_t upb_msg_fielddefsize(const upb_fielddef *f) {
  3929. if (upb_fielddef_isseq(f)) {
  3930. return sizeof(void*);
  3931. } else {
  3932. return upb_msgval_sizeof2(upb_fielddef_type(f));
  3933. }
  3934. }
  3935. /** upb_msglayout *************************************************************/
  3936. static void upb_msglayout_free(upb_msglayout *l) {
  3937. upb_gfree(l);
  3938. }
  3939. static size_t upb_msglayout_place(upb_msglayout *l, size_t size) {
  3940. size_t ret;
  3941. l->size = align_up(l->size, size);
  3942. ret = l->size;
  3943. l->size += size;
  3944. return ret;
  3945. }
  3946. static bool upb_msglayout_init(const upb_msgdef *m,
  3947. upb_msglayout *l,
  3948. upb_msgfactory *factory) {
  3949. upb_msg_field_iter it;
  3950. upb_msg_oneof_iter oit;
  3951. size_t hasbit;
  3952. size_t submsg_count = 0;
  3953. const upb_msglayout **submsgs;
  3954. upb_msglayout_field *fields;
  3955. for (upb_msg_field_begin(&it, m);
  3956. !upb_msg_field_done(&it);
  3957. upb_msg_field_next(&it)) {
  3958. const upb_fielddef* f = upb_msg_iter_field(&it);
  3959. if (upb_fielddef_issubmsg(f)) {
  3960. submsg_count++;
  3961. }
  3962. }
  3963. memset(l, 0, sizeof(*l));
  3964. fields = upb_gmalloc(upb_msgdef_numfields(m) * sizeof(*fields));
  3965. submsgs = upb_gmalloc(submsg_count * sizeof(*submsgs));
  3966. if ((!fields && upb_msgdef_numfields(m)) ||
  3967. (!submsgs && submsg_count)) {
  3968. /* OOM. */
  3969. upb_gfree(fields);
  3970. upb_gfree(submsgs);
  3971. return false;
  3972. }
  3973. l->field_count = upb_msgdef_numfields(m);
  3974. l->fields = fields;
  3975. l->submsgs = submsgs;
  3976. /* Allocate data offsets in three stages:
  3977. *
  3978. * 1. hasbits.
  3979. * 2. regular fields.
  3980. * 3. oneof fields.
  3981. *
  3982. * OPT: There is a lot of room for optimization here to minimize the size.
  3983. */
  3984. /* Allocate hasbits and set basic field attributes. */
  3985. submsg_count = 0;
  3986. for (upb_msg_field_begin(&it, m), hasbit = 0;
  3987. !upb_msg_field_done(&it);
  3988. upb_msg_field_next(&it)) {
  3989. const upb_fielddef* f = upb_msg_iter_field(&it);
  3990. upb_msglayout_field *field = &fields[upb_fielddef_index(f)];
  3991. field->number = upb_fielddef_number(f);
  3992. field->descriptortype = upb_fielddef_descriptortype(f);
  3993. field->label = upb_fielddef_label(f);
  3994. if (upb_fielddef_issubmsg(f)) {
  3995. const upb_msglayout *sub_layout =
  3996. upb_msgfactory_getlayout(factory, upb_fielddef_msgsubdef(f));
  3997. field->submsg_index = submsg_count++;
  3998. submsgs[field->submsg_index] = sub_layout;
  3999. }
  4000. if (upb_fielddef_haspresence(f) && !upb_fielddef_containingoneof(f)) {
  4001. field->presence = (hasbit++);
  4002. } else {
  4003. field->presence = 0;
  4004. }
  4005. }
  4006. /* Account for space used by hasbits. */
  4007. l->size = div_round_up(hasbit, 8);
  4008. /* Allocate non-oneof fields. */
  4009. for (upb_msg_field_begin(&it, m); !upb_msg_field_done(&it);
  4010. upb_msg_field_next(&it)) {
  4011. const upb_fielddef* f = upb_msg_iter_field(&it);
  4012. size_t field_size = upb_msg_fielddefsize(f);
  4013. size_t index = upb_fielddef_index(f);
  4014. if (upb_fielddef_containingoneof(f)) {
  4015. /* Oneofs are handled separately below. */
  4016. continue;
  4017. }
  4018. fields[index].offset = upb_msglayout_place(l, field_size);
  4019. }
  4020. /* Allocate oneof fields. Each oneof field consists of a uint32 for the case
  4021. * and space for the actual data. */
  4022. for (upb_msg_oneof_begin(&oit, m); !upb_msg_oneof_done(&oit);
  4023. upb_msg_oneof_next(&oit)) {
  4024. const upb_oneofdef* o = upb_msg_iter_oneof(&oit);
  4025. upb_oneof_iter fit;
  4026. size_t case_size = sizeof(uint32_t); /* Could potentially optimize this. */
  4027. size_t field_size = 0;
  4028. uint32_t case_offset;
  4029. uint32_t data_offset;
  4030. /* Calculate field size: the max of all field sizes. */
  4031. for (upb_oneof_begin(&fit, o);
  4032. !upb_oneof_done(&fit);
  4033. upb_oneof_next(&fit)) {
  4034. const upb_fielddef* f = upb_oneof_iter_field(&fit);
  4035. field_size = UPB_MAX(field_size, upb_msg_fielddefsize(f));
  4036. }
  4037. /* Align and allocate case offset. */
  4038. case_offset = upb_msglayout_place(l, case_size);
  4039. data_offset = upb_msglayout_place(l, field_size);
  4040. for (upb_oneof_begin(&fit, o);
  4041. !upb_oneof_done(&fit);
  4042. upb_oneof_next(&fit)) {
  4043. const upb_fielddef* f = upb_oneof_iter_field(&fit);
  4044. fields[upb_fielddef_index(f)].offset = data_offset;
  4045. fields[upb_fielddef_index(f)].presence = ~case_offset;
  4046. }
  4047. }
  4048. /* Size of the entire structure should be a multiple of its greatest
  4049. * alignment. TODO: track overall alignment for real? */
  4050. l->size = align_up(l->size, 8);
  4051. return true;
  4052. }
  4053. /** upb_msgfactory ************************************************************/
  4054. struct upb_msgfactory {
  4055. const upb_symtab *symtab; /* We own a ref. */
  4056. upb_inttable layouts;
  4057. };
  4058. upb_msgfactory *upb_msgfactory_new(const upb_symtab *symtab) {
  4059. upb_msgfactory *ret = upb_gmalloc(sizeof(*ret));
  4060. ret->symtab = symtab;
  4061. upb_inttable_init(&ret->layouts, UPB_CTYPE_PTR);
  4062. return ret;
  4063. }
  4064. void upb_msgfactory_free(upb_msgfactory *f) {
  4065. upb_inttable_iter i;
  4066. upb_inttable_begin(&i, &f->layouts);
  4067. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  4068. upb_msglayout *l = upb_value_getptr(upb_inttable_iter_value(&i));
  4069. upb_msglayout_free(l);
  4070. }
  4071. upb_inttable_uninit(&f->layouts);
  4072. upb_gfree(f);
  4073. }
  4074. const upb_symtab *upb_msgfactory_symtab(const upb_msgfactory *f) {
  4075. return f->symtab;
  4076. }
  4077. const upb_msglayout *upb_msgfactory_getlayout(upb_msgfactory *f,
  4078. const upb_msgdef *m) {
  4079. upb_value v;
  4080. UPB_ASSERT(upb_symtab_lookupmsg(f->symtab, upb_msgdef_fullname(m)) == m);
  4081. UPB_ASSERT(!upb_msgdef_mapentry(m));
  4082. if (upb_inttable_lookupptr(&f->layouts, m, &v)) {
  4083. UPB_ASSERT(upb_value_getptr(v));
  4084. return upb_value_getptr(v);
  4085. } else {
  4086. /* In case of circular dependency, layout has to be inserted first. */
  4087. upb_msglayout *l = upb_gmalloc(sizeof(*l));
  4088. upb_msgfactory *mutable_f = (void*)f;
  4089. upb_inttable_insertptr(&mutable_f->layouts, m, upb_value_ptr(l));
  4090. UPB_ASSERT(l);
  4091. if (!upb_msglayout_init(m, l, f)) {
  4092. upb_msglayout_free(l);
  4093. }
  4094. return l;
  4095. }
  4096. }
  4097. /*
  4098. ** TODO(haberman): it's unclear whether a lot of the consistency checks should
  4099. ** UPB_ASSERT() or return false.
  4100. */
  4101. #include <string.h>
  4102. struct upb_handlers {
  4103. upb_handlercache *cache;
  4104. const upb_msgdef *msg;
  4105. const upb_handlers **sub;
  4106. const void *top_closure_type;
  4107. upb_handlers_tabent table[1]; /* Dynamically-sized field handler array. */
  4108. };
  4109. static void *upb_calloc(upb_arena *arena, size_t size) {
  4110. void *mem = upb_malloc(upb_arena_alloc(arena), size);
  4111. if (mem) {
  4112. memset(mem, 0, size);
  4113. }
  4114. return mem;
  4115. }
  4116. /* Defined for the sole purpose of having a unique pointer value for
  4117. * UPB_NO_CLOSURE. */
  4118. char _upb_noclosure;
  4119. /* Given a selector for a STARTSUBMSG handler, resolves to a pointer to the
  4120. * subhandlers for this submessage field. */
  4121. #define SUBH(h, selector) (h->sub[selector])
  4122. /* The selector for a submessage field is the field index. */
  4123. #define SUBH_F(h, f) SUBH(h, upb_fielddef_index(f))
  4124. static int32_t trygetsel(upb_handlers *h, const upb_fielddef *f,
  4125. upb_handlertype_t type) {
  4126. upb_selector_t sel;
  4127. bool ok;
  4128. ok = upb_handlers_getselector(f, type, &sel);
  4129. UPB_ASSERT(upb_handlers_msgdef(h) == upb_fielddef_containingtype(f));
  4130. UPB_ASSERT(ok);
  4131. return sel;
  4132. }
  4133. static upb_selector_t handlers_getsel(upb_handlers *h, const upb_fielddef *f,
  4134. upb_handlertype_t type) {
  4135. int32_t sel = trygetsel(h, f, type);
  4136. UPB_ASSERT(sel >= 0);
  4137. return sel;
  4138. }
  4139. static const void **returntype(upb_handlers *h, const upb_fielddef *f,
  4140. upb_handlertype_t type) {
  4141. return &h->table[handlers_getsel(h, f, type)].attr.return_closure_type;
  4142. }
  4143. static bool doset(upb_handlers *h, int32_t sel, const upb_fielddef *f,
  4144. upb_handlertype_t type, upb_func *func,
  4145. const upb_handlerattr *attr) {
  4146. upb_handlerattr set_attr = UPB_HANDLERATTR_INIT;
  4147. const void *closure_type;
  4148. const void **context_closure_type;
  4149. UPB_ASSERT(!h->table[sel].func);
  4150. if (attr) {
  4151. set_attr = *attr;
  4152. }
  4153. /* Check that the given closure type matches the closure type that has been
  4154. * established for this context (if any). */
  4155. closure_type = set_attr.closure_type;
  4156. if (type == UPB_HANDLER_STRING) {
  4157. context_closure_type = returntype(h, f, UPB_HANDLER_STARTSTR);
  4158. } else if (f && upb_fielddef_isseq(f) &&
  4159. type != UPB_HANDLER_STARTSEQ &&
  4160. type != UPB_HANDLER_ENDSEQ) {
  4161. context_closure_type = returntype(h, f, UPB_HANDLER_STARTSEQ);
  4162. } else {
  4163. context_closure_type = &h->top_closure_type;
  4164. }
  4165. if (closure_type && *context_closure_type &&
  4166. closure_type != *context_closure_type) {
  4167. return false;
  4168. }
  4169. if (closure_type)
  4170. *context_closure_type = closure_type;
  4171. /* If this is a STARTSEQ or STARTSTR handler, check that the returned pointer
  4172. * matches any pre-existing expectations about what type is expected. */
  4173. if (type == UPB_HANDLER_STARTSEQ || type == UPB_HANDLER_STARTSTR) {
  4174. const void *return_type = set_attr.return_closure_type;
  4175. const void *table_return_type = h->table[sel].attr.return_closure_type;
  4176. if (return_type && table_return_type && return_type != table_return_type) {
  4177. return false;
  4178. }
  4179. if (table_return_type && !return_type) {
  4180. set_attr.return_closure_type = table_return_type;
  4181. }
  4182. }
  4183. h->table[sel].func = (upb_func*)func;
  4184. h->table[sel].attr = set_attr;
  4185. return true;
  4186. }
  4187. /* Returns the effective closure type for this handler (which will propagate
  4188. * from outer frames if this frame has no START* handler). Not implemented for
  4189. * UPB_HANDLER_STRING at the moment since this is not needed. Returns NULL is
  4190. * the effective closure type is unspecified (either no handler was registered
  4191. * to specify it or the handler that was registered did not specify the closure
  4192. * type). */
  4193. const void *effective_closure_type(upb_handlers *h, const upb_fielddef *f,
  4194. upb_handlertype_t type) {
  4195. const void *ret;
  4196. upb_selector_t sel;
  4197. UPB_ASSERT(type != UPB_HANDLER_STRING);
  4198. ret = h->top_closure_type;
  4199. if (upb_fielddef_isseq(f) &&
  4200. type != UPB_HANDLER_STARTSEQ &&
  4201. type != UPB_HANDLER_ENDSEQ &&
  4202. h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSEQ)].func) {
  4203. ret = h->table[sel].attr.return_closure_type;
  4204. }
  4205. if (type == UPB_HANDLER_STRING &&
  4206. h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSTR)].func) {
  4207. ret = h->table[sel].attr.return_closure_type;
  4208. }
  4209. /* The effective type of the submessage; not used yet.
  4210. * if (type == SUBMESSAGE &&
  4211. * h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSUBMSG)].func) {
  4212. * ret = h->table[sel].attr.return_closure_type;
  4213. * } */
  4214. return ret;
  4215. }
  4216. /* Checks whether the START* handler specified by f & type is missing even
  4217. * though it is required to convert the established type of an outer frame
  4218. * ("closure_type") into the established type of an inner frame (represented in
  4219. * the return closure type of this handler's attr. */
  4220. bool checkstart(upb_handlers *h, const upb_fielddef *f, upb_handlertype_t type,
  4221. upb_status *status) {
  4222. const void *closure_type;
  4223. const upb_handlerattr *attr;
  4224. const void *return_closure_type;
  4225. upb_selector_t sel = handlers_getsel(h, f, type);
  4226. if (h->table[sel].func) return true;
  4227. closure_type = effective_closure_type(h, f, type);
  4228. attr = &h->table[sel].attr;
  4229. return_closure_type = attr->return_closure_type;
  4230. if (closure_type && return_closure_type &&
  4231. closure_type != return_closure_type) {
  4232. return false;
  4233. }
  4234. return true;
  4235. }
  4236. static upb_handlers *upb_handlers_new(const upb_msgdef *md,
  4237. upb_handlercache *cache,
  4238. upb_arena *arena) {
  4239. int extra;
  4240. upb_handlers *h;
  4241. extra = sizeof(upb_handlers_tabent) * (upb_msgdef_selectorcount(md) - 1);
  4242. h = upb_calloc(arena, sizeof(*h) + extra);
  4243. if (!h) return NULL;
  4244. h->cache = cache;
  4245. h->msg = md;
  4246. if (upb_msgdef_submsgfieldcount(md) > 0) {
  4247. size_t bytes = upb_msgdef_submsgfieldcount(md) * sizeof(*h->sub);
  4248. h->sub = upb_calloc(arena, bytes);
  4249. if (!h->sub) return NULL;
  4250. } else {
  4251. h->sub = 0;
  4252. }
  4253. /* calloc() above initialized all handlers to NULL. */
  4254. return h;
  4255. }
  4256. /* Public interface ***********************************************************/
  4257. #define SETTER(name, handlerctype, handlertype) \
  4258. bool upb_handlers_set##name(upb_handlers *h, const upb_fielddef *f, \
  4259. handlerctype func, \
  4260. const upb_handlerattr *attr) { \
  4261. int32_t sel = trygetsel(h, f, handlertype); \
  4262. return doset(h, sel, f, handlertype, (upb_func *)func, attr); \
  4263. }
  4264. SETTER(int32, upb_int32_handlerfunc*, UPB_HANDLER_INT32)
  4265. SETTER(int64, upb_int64_handlerfunc*, UPB_HANDLER_INT64)
  4266. SETTER(uint32, upb_uint32_handlerfunc*, UPB_HANDLER_UINT32)
  4267. SETTER(uint64, upb_uint64_handlerfunc*, UPB_HANDLER_UINT64)
  4268. SETTER(float, upb_float_handlerfunc*, UPB_HANDLER_FLOAT)
  4269. SETTER(double, upb_double_handlerfunc*, UPB_HANDLER_DOUBLE)
  4270. SETTER(bool, upb_bool_handlerfunc*, UPB_HANDLER_BOOL)
  4271. SETTER(startstr, upb_startstr_handlerfunc*, UPB_HANDLER_STARTSTR)
  4272. SETTER(string, upb_string_handlerfunc*, UPB_HANDLER_STRING)
  4273. SETTER(endstr, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSTR)
  4274. SETTER(startseq, upb_startfield_handlerfunc*, UPB_HANDLER_STARTSEQ)
  4275. SETTER(startsubmsg, upb_startfield_handlerfunc*, UPB_HANDLER_STARTSUBMSG)
  4276. SETTER(endsubmsg, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSUBMSG)
  4277. SETTER(endseq, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSEQ)
  4278. #undef SETTER
  4279. bool upb_handlers_setunknown(upb_handlers *h, upb_unknown_handlerfunc *func,
  4280. const upb_handlerattr *attr) {
  4281. return doset(h, UPB_UNKNOWN_SELECTOR, NULL, UPB_HANDLER_INT32,
  4282. (upb_func *)func, attr);
  4283. }
  4284. bool upb_handlers_setstartmsg(upb_handlers *h, upb_startmsg_handlerfunc *func,
  4285. const upb_handlerattr *attr) {
  4286. return doset(h, UPB_STARTMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
  4287. (upb_func *)func, attr);
  4288. }
  4289. bool upb_handlers_setendmsg(upb_handlers *h, upb_endmsg_handlerfunc *func,
  4290. const upb_handlerattr *attr) {
  4291. return doset(h, UPB_ENDMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
  4292. (upb_func *)func, attr);
  4293. }
  4294. bool upb_handlers_setsubhandlers(upb_handlers *h, const upb_fielddef *f,
  4295. const upb_handlers *sub) {
  4296. UPB_ASSERT(sub);
  4297. UPB_ASSERT(upb_fielddef_issubmsg(f));
  4298. if (SUBH_F(h, f)) return false; /* Can't reset. */
  4299. if (upb_handlers_msgdef(sub) != upb_fielddef_msgsubdef(f)) {
  4300. return false;
  4301. }
  4302. SUBH_F(h, f) = sub;
  4303. return true;
  4304. }
  4305. const upb_handlers *upb_handlers_getsubhandlers(const upb_handlers *h,
  4306. const upb_fielddef *f) {
  4307. UPB_ASSERT(upb_fielddef_issubmsg(f));
  4308. return SUBH_F(h, f);
  4309. }
  4310. upb_func *upb_handlers_gethandler(const upb_handlers *h, upb_selector_t s,
  4311. const void **handler_data) {
  4312. upb_func *ret = (upb_func *)h->table[s].func;
  4313. if (ret && handler_data) {
  4314. *handler_data = h->table[s].attr.handler_data;
  4315. }
  4316. return ret;
  4317. }
  4318. bool upb_handlers_getattr(const upb_handlers *h, upb_selector_t sel,
  4319. upb_handlerattr *attr) {
  4320. if (!upb_handlers_gethandler(h, sel, NULL))
  4321. return false;
  4322. *attr = h->table[sel].attr;
  4323. return true;
  4324. }
  4325. const upb_handlers *upb_handlers_getsubhandlers_sel(const upb_handlers *h,
  4326. upb_selector_t sel) {
  4327. /* STARTSUBMSG selector in sel is the field's selector base. */
  4328. return SUBH(h, sel - UPB_STATIC_SELECTOR_COUNT);
  4329. }
  4330. const upb_msgdef *upb_handlers_msgdef(const upb_handlers *h) { return h->msg; }
  4331. bool upb_handlers_addcleanup(upb_handlers *h, void *p, upb_handlerfree *func) {
  4332. return upb_handlercache_addcleanup(h->cache, p, func);
  4333. }
  4334. upb_handlertype_t upb_handlers_getprimitivehandlertype(const upb_fielddef *f) {
  4335. switch (upb_fielddef_type(f)) {
  4336. case UPB_TYPE_INT32:
  4337. case UPB_TYPE_ENUM: return UPB_HANDLER_INT32;
  4338. case UPB_TYPE_INT64: return UPB_HANDLER_INT64;
  4339. case UPB_TYPE_UINT32: return UPB_HANDLER_UINT32;
  4340. case UPB_TYPE_UINT64: return UPB_HANDLER_UINT64;
  4341. case UPB_TYPE_FLOAT: return UPB_HANDLER_FLOAT;
  4342. case UPB_TYPE_DOUBLE: return UPB_HANDLER_DOUBLE;
  4343. case UPB_TYPE_BOOL: return UPB_HANDLER_BOOL;
  4344. default: UPB_ASSERT(false); return -1; /* Invalid input. */
  4345. }
  4346. }
  4347. bool upb_handlers_getselector(const upb_fielddef *f, upb_handlertype_t type,
  4348. upb_selector_t *s) {
  4349. uint32_t selector_base = upb_fielddef_selectorbase(f);
  4350. switch (type) {
  4351. case UPB_HANDLER_INT32:
  4352. case UPB_HANDLER_INT64:
  4353. case UPB_HANDLER_UINT32:
  4354. case UPB_HANDLER_UINT64:
  4355. case UPB_HANDLER_FLOAT:
  4356. case UPB_HANDLER_DOUBLE:
  4357. case UPB_HANDLER_BOOL:
  4358. if (!upb_fielddef_isprimitive(f) ||
  4359. upb_handlers_getprimitivehandlertype(f) != type)
  4360. return false;
  4361. *s = selector_base;
  4362. break;
  4363. case UPB_HANDLER_STRING:
  4364. if (upb_fielddef_isstring(f)) {
  4365. *s = selector_base;
  4366. } else if (upb_fielddef_lazy(f)) {
  4367. *s = selector_base + 3;
  4368. } else {
  4369. return false;
  4370. }
  4371. break;
  4372. case UPB_HANDLER_STARTSTR:
  4373. if (upb_fielddef_isstring(f) || upb_fielddef_lazy(f)) {
  4374. *s = selector_base + 1;
  4375. } else {
  4376. return false;
  4377. }
  4378. break;
  4379. case UPB_HANDLER_ENDSTR:
  4380. if (upb_fielddef_isstring(f) || upb_fielddef_lazy(f)) {
  4381. *s = selector_base + 2;
  4382. } else {
  4383. return false;
  4384. }
  4385. break;
  4386. case UPB_HANDLER_STARTSEQ:
  4387. if (!upb_fielddef_isseq(f)) return false;
  4388. *s = selector_base - 2;
  4389. break;
  4390. case UPB_HANDLER_ENDSEQ:
  4391. if (!upb_fielddef_isseq(f)) return false;
  4392. *s = selector_base - 1;
  4393. break;
  4394. case UPB_HANDLER_STARTSUBMSG:
  4395. if (!upb_fielddef_issubmsg(f)) return false;
  4396. /* Selectors for STARTSUBMSG are at the beginning of the table so that the
  4397. * selector can also be used as an index into the "sub" array of
  4398. * subhandlers. The indexes for the two into these two tables are the
  4399. * same, except that in the handler table the static selectors come first. */
  4400. *s = upb_fielddef_index(f) + UPB_STATIC_SELECTOR_COUNT;
  4401. break;
  4402. case UPB_HANDLER_ENDSUBMSG:
  4403. if (!upb_fielddef_issubmsg(f)) return false;
  4404. *s = selector_base;
  4405. break;
  4406. }
  4407. UPB_ASSERT((size_t)*s < upb_msgdef_selectorcount(upb_fielddef_containingtype(f)));
  4408. return true;
  4409. }
  4410. /* upb_handlercache ***********************************************************/
  4411. struct upb_handlercache {
  4412. upb_arena *arena;
  4413. upb_inttable tab; /* maps upb_msgdef* -> upb_handlers*. */
  4414. upb_handlers_callback *callback;
  4415. const void *closure;
  4416. };
  4417. const upb_handlers *upb_handlercache_get(upb_handlercache *c,
  4418. const upb_msgdef *md) {
  4419. upb_msg_field_iter i;
  4420. upb_value v;
  4421. upb_handlers *h;
  4422. if (upb_inttable_lookupptr(&c->tab, md, &v)) {
  4423. return upb_value_getptr(v);
  4424. }
  4425. h = upb_handlers_new(md, c, c->arena);
  4426. v = upb_value_ptr(h);
  4427. if (!h) return NULL;
  4428. if (!upb_inttable_insertptr(&c->tab, md, v)) return NULL;
  4429. c->callback(c->closure, h);
  4430. /* For each submessage field, get or create a handlers object and set it as
  4431. * the subhandlers. */
  4432. for(upb_msg_field_begin(&i, md);
  4433. !upb_msg_field_done(&i);
  4434. upb_msg_field_next(&i)) {
  4435. upb_fielddef *f = upb_msg_iter_field(&i);
  4436. if (upb_fielddef_issubmsg(f)) {
  4437. const upb_msgdef *subdef = upb_fielddef_msgsubdef(f);
  4438. const upb_handlers *sub_mh = upb_handlercache_get(c, subdef);
  4439. if (!sub_mh) return NULL;
  4440. upb_handlers_setsubhandlers(h, f, sub_mh);
  4441. }
  4442. }
  4443. return h;
  4444. }
  4445. upb_handlercache *upb_handlercache_new(upb_handlers_callback *callback,
  4446. const void *closure) {
  4447. upb_handlercache *cache = upb_gmalloc(sizeof(*cache));
  4448. if (!cache) return NULL;
  4449. cache->arena = upb_arena_new();
  4450. cache->callback = callback;
  4451. cache->closure = closure;
  4452. if (!upb_inttable_init(&cache->tab, UPB_CTYPE_PTR)) goto oom;
  4453. return cache;
  4454. oom:
  4455. upb_gfree(cache);
  4456. return NULL;
  4457. }
  4458. void upb_handlercache_free(upb_handlercache *cache) {
  4459. upb_inttable_uninit(&cache->tab);
  4460. upb_arena_free(cache->arena);
  4461. upb_gfree(cache);
  4462. }
  4463. bool upb_handlercache_addcleanup(upb_handlercache *c, void *p,
  4464. upb_handlerfree *func) {
  4465. return upb_arena_addcleanup(c->arena, p, func);
  4466. }
  4467. /* upb_byteshandler ***********************************************************/
  4468. bool upb_byteshandler_setstartstr(upb_byteshandler *h,
  4469. upb_startstr_handlerfunc *func, void *d) {
  4470. h->table[UPB_STARTSTR_SELECTOR].func = (upb_func*)func;
  4471. h->table[UPB_STARTSTR_SELECTOR].attr.handler_data = d;
  4472. return true;
  4473. }
  4474. bool upb_byteshandler_setstring(upb_byteshandler *h,
  4475. upb_string_handlerfunc *func, void *d) {
  4476. h->table[UPB_STRING_SELECTOR].func = (upb_func*)func;
  4477. h->table[UPB_STRING_SELECTOR].attr.handler_data = d;
  4478. return true;
  4479. }
  4480. bool upb_byteshandler_setendstr(upb_byteshandler *h,
  4481. upb_endfield_handlerfunc *func, void *d) {
  4482. h->table[UPB_ENDSTR_SELECTOR].func = (upb_func*)func;
  4483. h->table[UPB_ENDSTR_SELECTOR].attr.handler_data = d;
  4484. return true;
  4485. }
  4486. /** Handlers for upb_msg ******************************************************/
  4487. typedef struct {
  4488. size_t offset;
  4489. int32_t hasbit;
  4490. } upb_msg_handlerdata;
  4491. /* Fallback implementation if the handler is not specialized by the producer. */
  4492. #define MSG_WRITER(type, ctype) \
  4493. bool upb_msg_set ## type (void *c, const void *hd, ctype val) { \
  4494. uint8_t *m = c; \
  4495. const upb_msg_handlerdata *d = hd; \
  4496. if (d->hasbit > 0) \
  4497. *(uint8_t*)&m[d->hasbit / 8] |= 1 << (d->hasbit % 8); \
  4498. *(ctype*)&m[d->offset] = val; \
  4499. return true; \
  4500. } \
  4501. MSG_WRITER(double, double)
  4502. MSG_WRITER(float, float)
  4503. MSG_WRITER(int32, int32_t)
  4504. MSG_WRITER(int64, int64_t)
  4505. MSG_WRITER(uint32, uint32_t)
  4506. MSG_WRITER(uint64, uint64_t)
  4507. MSG_WRITER(bool, bool)
  4508. bool upb_msg_setscalarhandler(upb_handlers *h, const upb_fielddef *f,
  4509. size_t offset, int32_t hasbit) {
  4510. upb_handlerattr attr = UPB_HANDLERATTR_INIT;
  4511. bool ok;
  4512. upb_msg_handlerdata *d = upb_gmalloc(sizeof(*d));
  4513. if (!d) return false;
  4514. d->offset = offset;
  4515. d->hasbit = hasbit;
  4516. attr.handler_data = d;
  4517. attr.alwaysok = true;
  4518. upb_handlers_addcleanup(h, d, upb_gfree);
  4519. #define TYPE(u, l) \
  4520. case UPB_TYPE_##u: \
  4521. ok = upb_handlers_set##l(h, f, upb_msg_set##l, &attr); break;
  4522. ok = false;
  4523. switch (upb_fielddef_type(f)) {
  4524. TYPE(INT64, int64);
  4525. TYPE(INT32, int32);
  4526. TYPE(ENUM, int32);
  4527. TYPE(UINT64, uint64);
  4528. TYPE(UINT32, uint32);
  4529. TYPE(DOUBLE, double);
  4530. TYPE(FLOAT, float);
  4531. TYPE(BOOL, bool);
  4532. default: UPB_ASSERT(false); break;
  4533. }
  4534. #undef TYPE
  4535. return ok;
  4536. }
  4537. bool upb_msg_getscalarhandlerdata(const upb_handlers *h,
  4538. upb_selector_t s,
  4539. upb_fieldtype_t *type,
  4540. size_t *offset,
  4541. int32_t *hasbit) {
  4542. const upb_msg_handlerdata *d;
  4543. const void *p;
  4544. upb_func *f = upb_handlers_gethandler(h, s, &p);
  4545. if ((upb_int64_handlerfunc*)f == upb_msg_setint64) {
  4546. *type = UPB_TYPE_INT64;
  4547. } else if ((upb_int32_handlerfunc*)f == upb_msg_setint32) {
  4548. *type = UPB_TYPE_INT32;
  4549. } else if ((upb_uint64_handlerfunc*)f == upb_msg_setuint64) {
  4550. *type = UPB_TYPE_UINT64;
  4551. } else if ((upb_uint32_handlerfunc*)f == upb_msg_setuint32) {
  4552. *type = UPB_TYPE_UINT32;
  4553. } else if ((upb_double_handlerfunc*)f == upb_msg_setdouble) {
  4554. *type = UPB_TYPE_DOUBLE;
  4555. } else if ((upb_float_handlerfunc*)f == upb_msg_setfloat) {
  4556. *type = UPB_TYPE_FLOAT;
  4557. } else if ((upb_bool_handlerfunc*)f == upb_msg_setbool) {
  4558. *type = UPB_TYPE_BOOL;
  4559. } else {
  4560. return false;
  4561. }
  4562. d = p;
  4563. *offset = d->offset;
  4564. *hasbit = d->hasbit;
  4565. return true;
  4566. }
  4567. bool upb_bufsrc_putbuf(const char *buf, size_t len, upb_bytessink sink) {
  4568. void *subc;
  4569. bool ret;
  4570. upb_bufhandle handle = UPB_BUFHANDLE_INIT;
  4571. handle.buf = buf;
  4572. ret = upb_bytessink_start(sink, len, &subc);
  4573. if (ret && len != 0) {
  4574. ret = (upb_bytessink_putbuf(sink, subc, buf, len, &handle) >= len);
  4575. }
  4576. if (ret) {
  4577. ret = upb_bytessink_end(sink);
  4578. }
  4579. return ret;
  4580. }
  4581. /*
  4582. ** protobuf decoder bytecode compiler
  4583. **
  4584. ** Code to compile a upb::Handlers into bytecode for decoding a protobuf
  4585. ** according to that specific schema and destination handlers.
  4586. **
  4587. ** Bytecode definition is in decoder.int.h.
  4588. */
  4589. #include <stdarg.h>
  4590. #ifdef UPB_DUMP_BYTECODE
  4591. #include <stdio.h>
  4592. #endif
  4593. #define MAXLABEL 5
  4594. #define EMPTYLABEL -1
  4595. /* upb_pbdecodermethod ********************************************************/
  4596. static void freemethod(upb_pbdecodermethod *method) {
  4597. upb_inttable_uninit(&method->dispatch);
  4598. upb_gfree(method);
  4599. }
  4600. static upb_pbdecodermethod *newmethod(const upb_handlers *dest_handlers,
  4601. mgroup *group) {
  4602. upb_pbdecodermethod *ret = upb_gmalloc(sizeof(*ret));
  4603. upb_byteshandler_init(&ret->input_handler_);
  4604. ret->group = group;
  4605. ret->dest_handlers_ = dest_handlers;
  4606. upb_inttable_init(&ret->dispatch, UPB_CTYPE_UINT64);
  4607. return ret;
  4608. }
  4609. const upb_handlers *upb_pbdecodermethod_desthandlers(
  4610. const upb_pbdecodermethod *m) {
  4611. return m->dest_handlers_;
  4612. }
  4613. const upb_byteshandler *upb_pbdecodermethod_inputhandler(
  4614. const upb_pbdecodermethod *m) {
  4615. return &m->input_handler_;
  4616. }
  4617. bool upb_pbdecodermethod_isnative(const upb_pbdecodermethod *m) {
  4618. return m->is_native_;
  4619. }
  4620. /* mgroup *********************************************************************/
  4621. static void freegroup(mgroup *g) {
  4622. upb_inttable_iter i;
  4623. upb_inttable_begin(&i, &g->methods);
  4624. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  4625. freemethod(upb_value_getptr(upb_inttable_iter_value(&i)));
  4626. }
  4627. upb_inttable_uninit(&g->methods);
  4628. upb_gfree(g->bytecode);
  4629. upb_gfree(g);
  4630. }
  4631. mgroup *newgroup(void) {
  4632. mgroup *g = upb_gmalloc(sizeof(*g));
  4633. upb_inttable_init(&g->methods, UPB_CTYPE_PTR);
  4634. g->bytecode = NULL;
  4635. g->bytecode_end = NULL;
  4636. return g;
  4637. }
  4638. /* bytecode compiler **********************************************************/
  4639. /* Data used only at compilation time. */
  4640. typedef struct {
  4641. mgroup *group;
  4642. uint32_t *pc;
  4643. int fwd_labels[MAXLABEL];
  4644. int back_labels[MAXLABEL];
  4645. /* For fields marked "lazy", parse them lazily or eagerly? */
  4646. bool lazy;
  4647. } compiler;
  4648. static compiler *newcompiler(mgroup *group, bool lazy) {
  4649. compiler *ret = upb_gmalloc(sizeof(*ret));
  4650. int i;
  4651. ret->group = group;
  4652. ret->lazy = lazy;
  4653. for (i = 0; i < MAXLABEL; i++) {
  4654. ret->fwd_labels[i] = EMPTYLABEL;
  4655. ret->back_labels[i] = EMPTYLABEL;
  4656. }
  4657. return ret;
  4658. }
  4659. static void freecompiler(compiler *c) {
  4660. upb_gfree(c);
  4661. }
  4662. const size_t ptr_words = sizeof(void*) / sizeof(uint32_t);
  4663. /* How many words an instruction is. */
  4664. static int instruction_len(uint32_t instr) {
  4665. switch (getop(instr)) {
  4666. case OP_SETDISPATCH: return 1 + ptr_words;
  4667. case OP_TAGN: return 3;
  4668. case OP_SETBIGGROUPNUM: return 2;
  4669. default: return 1;
  4670. }
  4671. }
  4672. bool op_has_longofs(int32_t instruction) {
  4673. switch (getop(instruction)) {
  4674. case OP_CALL:
  4675. case OP_BRANCH:
  4676. case OP_CHECKDELIM:
  4677. return true;
  4678. /* The "tag" instructions only have 8 bytes available for the jump target,
  4679. * but that is ok because these opcodes only require short jumps. */
  4680. case OP_TAG1:
  4681. case OP_TAG2:
  4682. case OP_TAGN:
  4683. return false;
  4684. default:
  4685. UPB_ASSERT(false);
  4686. return false;
  4687. }
  4688. }
  4689. static int32_t getofs(uint32_t instruction) {
  4690. if (op_has_longofs(instruction)) {
  4691. return (int32_t)instruction >> 8;
  4692. } else {
  4693. return (int8_t)(instruction >> 8);
  4694. }
  4695. }
  4696. static void setofs(uint32_t *instruction, int32_t ofs) {
  4697. if (op_has_longofs(*instruction)) {
  4698. *instruction = getop(*instruction) | (uint32_t)ofs << 8;
  4699. } else {
  4700. *instruction = (*instruction & ~0xff00) | ((ofs & 0xff) << 8);
  4701. }
  4702. UPB_ASSERT(getofs(*instruction) == ofs); /* Would fail in cases of overflow. */
  4703. }
  4704. static uint32_t pcofs(compiler *c) { return c->pc - c->group->bytecode; }
  4705. /* Defines a local label at the current PC location. All previous forward
  4706. * references are updated to point to this location. The location is noted
  4707. * for any future backward references. */
  4708. static void label(compiler *c, unsigned int label) {
  4709. int val;
  4710. uint32_t *codep;
  4711. UPB_ASSERT(label < MAXLABEL);
  4712. val = c->fwd_labels[label];
  4713. codep = (val == EMPTYLABEL) ? NULL : c->group->bytecode + val;
  4714. while (codep) {
  4715. int ofs = getofs(*codep);
  4716. setofs(codep, c->pc - codep - instruction_len(*codep));
  4717. codep = ofs ? codep + ofs : NULL;
  4718. }
  4719. c->fwd_labels[label] = EMPTYLABEL;
  4720. c->back_labels[label] = pcofs(c);
  4721. }
  4722. /* Creates a reference to a numbered label; either a forward reference
  4723. * (positive arg) or backward reference (negative arg). For forward references
  4724. * the value returned now is actually a "next" pointer into a linked list of all
  4725. * instructions that use this label and will be patched later when the label is
  4726. * defined with label().
  4727. *
  4728. * The returned value is the offset that should be written into the instruction.
  4729. */
  4730. static int32_t labelref(compiler *c, int label) {
  4731. UPB_ASSERT(label < MAXLABEL);
  4732. if (label == LABEL_DISPATCH) {
  4733. /* No resolving required. */
  4734. return 0;
  4735. } else if (label < 0) {
  4736. /* Backward local label. Relative to the next instruction. */
  4737. uint32_t from = (c->pc + 1) - c->group->bytecode;
  4738. return c->back_labels[-label] - from;
  4739. } else {
  4740. /* Forward local label: prepend to (possibly-empty) linked list. */
  4741. int *lptr = &c->fwd_labels[label];
  4742. int32_t ret = (*lptr == EMPTYLABEL) ? 0 : *lptr - pcofs(c);
  4743. *lptr = pcofs(c);
  4744. return ret;
  4745. }
  4746. }
  4747. static void put32(compiler *c, uint32_t v) {
  4748. mgroup *g = c->group;
  4749. if (c->pc == g->bytecode_end) {
  4750. int ofs = pcofs(c);
  4751. size_t oldsize = g->bytecode_end - g->bytecode;
  4752. size_t newsize = UPB_MAX(oldsize * 2, 64);
  4753. /* TODO(haberman): handle OOM. */
  4754. g->bytecode = upb_grealloc(g->bytecode, oldsize * sizeof(uint32_t),
  4755. newsize * sizeof(uint32_t));
  4756. g->bytecode_end = g->bytecode + newsize;
  4757. c->pc = g->bytecode + ofs;
  4758. }
  4759. *c->pc++ = v;
  4760. }
  4761. static void putop(compiler *c, int op, ...) {
  4762. va_list ap;
  4763. va_start(ap, op);
  4764. switch (op) {
  4765. case OP_SETDISPATCH: {
  4766. uintptr_t ptr = (uintptr_t)va_arg(ap, void*);
  4767. put32(c, OP_SETDISPATCH);
  4768. put32(c, ptr);
  4769. if (sizeof(uintptr_t) > sizeof(uint32_t))
  4770. put32(c, (uint64_t)ptr >> 32);
  4771. break;
  4772. }
  4773. case OP_STARTMSG:
  4774. case OP_ENDMSG:
  4775. case OP_PUSHLENDELIM:
  4776. case OP_POP:
  4777. case OP_SETDELIM:
  4778. case OP_HALT:
  4779. case OP_RET:
  4780. case OP_DISPATCH:
  4781. put32(c, op);
  4782. break;
  4783. case OP_PARSE_DOUBLE:
  4784. case OP_PARSE_FLOAT:
  4785. case OP_PARSE_INT64:
  4786. case OP_PARSE_UINT64:
  4787. case OP_PARSE_INT32:
  4788. case OP_PARSE_FIXED64:
  4789. case OP_PARSE_FIXED32:
  4790. case OP_PARSE_BOOL:
  4791. case OP_PARSE_UINT32:
  4792. case OP_PARSE_SFIXED32:
  4793. case OP_PARSE_SFIXED64:
  4794. case OP_PARSE_SINT32:
  4795. case OP_PARSE_SINT64:
  4796. case OP_STARTSEQ:
  4797. case OP_ENDSEQ:
  4798. case OP_STARTSUBMSG:
  4799. case OP_ENDSUBMSG:
  4800. case OP_STARTSTR:
  4801. case OP_STRING:
  4802. case OP_ENDSTR:
  4803. case OP_PUSHTAGDELIM:
  4804. put32(c, op | va_arg(ap, upb_selector_t) << 8);
  4805. break;
  4806. case OP_SETBIGGROUPNUM:
  4807. put32(c, op);
  4808. put32(c, va_arg(ap, int));
  4809. break;
  4810. case OP_CALL: {
  4811. const upb_pbdecodermethod *method = va_arg(ap, upb_pbdecodermethod *);
  4812. put32(c, op | (method->code_base.ofs - (pcofs(c) + 1)) << 8);
  4813. break;
  4814. }
  4815. case OP_CHECKDELIM:
  4816. case OP_BRANCH: {
  4817. uint32_t instruction = op;
  4818. int label = va_arg(ap, int);
  4819. setofs(&instruction, labelref(c, label));
  4820. put32(c, instruction);
  4821. break;
  4822. }
  4823. case OP_TAG1:
  4824. case OP_TAG2: {
  4825. int label = va_arg(ap, int);
  4826. uint64_t tag = va_arg(ap, uint64_t);
  4827. uint32_t instruction = op | (tag << 16);
  4828. UPB_ASSERT(tag <= 0xffff);
  4829. setofs(&instruction, labelref(c, label));
  4830. put32(c, instruction);
  4831. break;
  4832. }
  4833. case OP_TAGN: {
  4834. int label = va_arg(ap, int);
  4835. uint64_t tag = va_arg(ap, uint64_t);
  4836. uint32_t instruction = op | (upb_value_size(tag) << 16);
  4837. setofs(&instruction, labelref(c, label));
  4838. put32(c, instruction);
  4839. put32(c, tag);
  4840. put32(c, tag >> 32);
  4841. break;
  4842. }
  4843. }
  4844. va_end(ap);
  4845. }
  4846. #if defined(UPB_DUMP_BYTECODE)
  4847. const char *upb_pbdecoder_getopname(unsigned int op) {
  4848. #define QUOTE(x) #x
  4849. #define EXPAND_AND_QUOTE(x) QUOTE(x)
  4850. #define OPNAME(x) OP_##x
  4851. #define OP(x) case OPNAME(x): return EXPAND_AND_QUOTE(OPNAME(x));
  4852. #define T(x) OP(PARSE_##x)
  4853. /* Keep in sync with list in decoder.int.h. */
  4854. switch ((opcode)op) {
  4855. T(DOUBLE) T(FLOAT) T(INT64) T(UINT64) T(INT32) T(FIXED64) T(FIXED32)
  4856. T(BOOL) T(UINT32) T(SFIXED32) T(SFIXED64) T(SINT32) T(SINT64)
  4857. OP(STARTMSG) OP(ENDMSG) OP(STARTSEQ) OP(ENDSEQ) OP(STARTSUBMSG)
  4858. OP(ENDSUBMSG) OP(STARTSTR) OP(STRING) OP(ENDSTR) OP(CALL) OP(RET)
  4859. OP(PUSHLENDELIM) OP(PUSHTAGDELIM) OP(SETDELIM) OP(CHECKDELIM)
  4860. OP(BRANCH) OP(TAG1) OP(TAG2) OP(TAGN) OP(SETDISPATCH) OP(POP)
  4861. OP(SETBIGGROUPNUM) OP(DISPATCH) OP(HALT)
  4862. }
  4863. return "<unknown op>";
  4864. #undef OP
  4865. #undef T
  4866. }
  4867. #endif
  4868. #ifdef UPB_DUMP_BYTECODE
  4869. static void dumpbc(uint32_t *p, uint32_t *end, FILE *f) {
  4870. uint32_t *begin = p;
  4871. while (p < end) {
  4872. fprintf(f, "%p %8tx", p, p - begin);
  4873. uint32_t instr = *p++;
  4874. uint8_t op = getop(instr);
  4875. fprintf(f, " %s", upb_pbdecoder_getopname(op));
  4876. switch ((opcode)op) {
  4877. case OP_SETDISPATCH: {
  4878. const upb_inttable *dispatch;
  4879. memcpy(&dispatch, p, sizeof(void*));
  4880. p += ptr_words;
  4881. const upb_pbdecodermethod *method =
  4882. (void *)((char *)dispatch -
  4883. offsetof(upb_pbdecodermethod, dispatch));
  4884. fprintf(f, " %s", upb_msgdef_fullname(
  4885. upb_handlers_msgdef(method->dest_handlers_)));
  4886. break;
  4887. }
  4888. case OP_DISPATCH:
  4889. case OP_STARTMSG:
  4890. case OP_ENDMSG:
  4891. case OP_PUSHLENDELIM:
  4892. case OP_POP:
  4893. case OP_SETDELIM:
  4894. case OP_HALT:
  4895. case OP_RET:
  4896. break;
  4897. case OP_PARSE_DOUBLE:
  4898. case OP_PARSE_FLOAT:
  4899. case OP_PARSE_INT64:
  4900. case OP_PARSE_UINT64:
  4901. case OP_PARSE_INT32:
  4902. case OP_PARSE_FIXED64:
  4903. case OP_PARSE_FIXED32:
  4904. case OP_PARSE_BOOL:
  4905. case OP_PARSE_UINT32:
  4906. case OP_PARSE_SFIXED32:
  4907. case OP_PARSE_SFIXED64:
  4908. case OP_PARSE_SINT32:
  4909. case OP_PARSE_SINT64:
  4910. case OP_STARTSEQ:
  4911. case OP_ENDSEQ:
  4912. case OP_STARTSUBMSG:
  4913. case OP_ENDSUBMSG:
  4914. case OP_STARTSTR:
  4915. case OP_STRING:
  4916. case OP_ENDSTR:
  4917. case OP_PUSHTAGDELIM:
  4918. fprintf(f, " %d", instr >> 8);
  4919. break;
  4920. case OP_SETBIGGROUPNUM:
  4921. fprintf(f, " %d", *p++);
  4922. break;
  4923. case OP_CHECKDELIM:
  4924. case OP_CALL:
  4925. case OP_BRANCH:
  4926. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  4927. break;
  4928. case OP_TAG1:
  4929. case OP_TAG2: {
  4930. fprintf(f, " tag:0x%x", instr >> 16);
  4931. if (getofs(instr)) {
  4932. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  4933. }
  4934. break;
  4935. }
  4936. case OP_TAGN: {
  4937. uint64_t tag = *p++;
  4938. tag |= (uint64_t)*p++ << 32;
  4939. fprintf(f, " tag:0x%llx", (long long)tag);
  4940. fprintf(f, " n:%d", instr >> 16);
  4941. if (getofs(instr)) {
  4942. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  4943. }
  4944. break;
  4945. }
  4946. }
  4947. fputs("\n", f);
  4948. }
  4949. }
  4950. #endif
  4951. static uint64_t get_encoded_tag(const upb_fielddef *f, int wire_type) {
  4952. uint32_t tag = (upb_fielddef_number(f) << 3) | wire_type;
  4953. uint64_t encoded_tag = upb_vencode32(tag);
  4954. /* No tag should be greater than 5 bytes. */
  4955. UPB_ASSERT(encoded_tag <= 0xffffffffff);
  4956. return encoded_tag;
  4957. }
  4958. static void putchecktag(compiler *c, const upb_fielddef *f,
  4959. int wire_type, int dest) {
  4960. uint64_t tag = get_encoded_tag(f, wire_type);
  4961. switch (upb_value_size(tag)) {
  4962. case 1:
  4963. putop(c, OP_TAG1, dest, tag);
  4964. break;
  4965. case 2:
  4966. putop(c, OP_TAG2, dest, tag);
  4967. break;
  4968. default:
  4969. putop(c, OP_TAGN, dest, tag);
  4970. break;
  4971. }
  4972. }
  4973. static upb_selector_t getsel(const upb_fielddef *f, upb_handlertype_t type) {
  4974. upb_selector_t selector;
  4975. bool ok = upb_handlers_getselector(f, type, &selector);
  4976. UPB_ASSERT(ok);
  4977. return selector;
  4978. }
  4979. /* Takes an existing, primary dispatch table entry and repacks it with a
  4980. * different alternate wire type. Called when we are inserting a secondary
  4981. * dispatch table entry for an alternate wire type. */
  4982. static uint64_t repack(uint64_t dispatch, int new_wt2) {
  4983. uint64_t ofs;
  4984. uint8_t wt1;
  4985. uint8_t old_wt2;
  4986. upb_pbdecoder_unpackdispatch(dispatch, &ofs, &wt1, &old_wt2);
  4987. UPB_ASSERT(old_wt2 == NO_WIRE_TYPE); /* wt2 should not be set yet. */
  4988. return upb_pbdecoder_packdispatch(ofs, wt1, new_wt2);
  4989. }
  4990. /* Marks the current bytecode position as the dispatch target for this message,
  4991. * field, and wire type. */
  4992. static void dispatchtarget(compiler *c, upb_pbdecodermethod *method,
  4993. const upb_fielddef *f, int wire_type) {
  4994. /* Offset is relative to msg base. */
  4995. uint64_t ofs = pcofs(c) - method->code_base.ofs;
  4996. uint32_t fn = upb_fielddef_number(f);
  4997. upb_inttable *d = &method->dispatch;
  4998. upb_value v;
  4999. if (upb_inttable_remove(d, fn, &v)) {
  5000. /* TODO: prioritize based on packed setting in .proto file. */
  5001. uint64_t repacked = repack(upb_value_getuint64(v), wire_type);
  5002. upb_inttable_insert(d, fn, upb_value_uint64(repacked));
  5003. upb_inttable_insert(d, fn + UPB_MAX_FIELDNUMBER, upb_value_uint64(ofs));
  5004. } else {
  5005. uint64_t val = upb_pbdecoder_packdispatch(ofs, wire_type, NO_WIRE_TYPE);
  5006. upb_inttable_insert(d, fn, upb_value_uint64(val));
  5007. }
  5008. }
  5009. static void putpush(compiler *c, const upb_fielddef *f) {
  5010. if (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE) {
  5011. putop(c, OP_PUSHLENDELIM);
  5012. } else {
  5013. uint32_t fn = upb_fielddef_number(f);
  5014. if (fn >= 1 << 24) {
  5015. putop(c, OP_PUSHTAGDELIM, 0);
  5016. putop(c, OP_SETBIGGROUPNUM, fn);
  5017. } else {
  5018. putop(c, OP_PUSHTAGDELIM, fn);
  5019. }
  5020. }
  5021. }
  5022. static upb_pbdecodermethod *find_submethod(const compiler *c,
  5023. const upb_pbdecodermethod *method,
  5024. const upb_fielddef *f) {
  5025. const upb_handlers *sub =
  5026. upb_handlers_getsubhandlers(method->dest_handlers_, f);
  5027. upb_value v;
  5028. return upb_inttable_lookupptr(&c->group->methods, sub, &v)
  5029. ? upb_value_getptr(v)
  5030. : NULL;
  5031. }
  5032. static void putsel(compiler *c, opcode op, upb_selector_t sel,
  5033. const upb_handlers *h) {
  5034. if (upb_handlers_gethandler(h, sel, NULL)) {
  5035. putop(c, op, sel);
  5036. }
  5037. }
  5038. /* Puts an opcode to call a callback, but only if a callback actually exists for
  5039. * this field and handler type. */
  5040. static void maybeput(compiler *c, opcode op, const upb_handlers *h,
  5041. const upb_fielddef *f, upb_handlertype_t type) {
  5042. putsel(c, op, getsel(f, type), h);
  5043. }
  5044. static bool haslazyhandlers(const upb_handlers *h, const upb_fielddef *f) {
  5045. if (!upb_fielddef_lazy(f))
  5046. return false;
  5047. return upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STARTSTR), NULL) ||
  5048. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STRING), NULL) ||
  5049. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_ENDSTR), NULL);
  5050. }
  5051. /* bytecode compiler code generation ******************************************/
  5052. /* Symbolic names for our local labels. */
  5053. #define LABEL_LOOPSTART 1 /* Top of a repeated field loop. */
  5054. #define LABEL_LOOPBREAK 2 /* To jump out of a repeated loop */
  5055. #define LABEL_FIELD 3 /* Jump backward to find the most recent field. */
  5056. #define LABEL_ENDMSG 4 /* To reach the OP_ENDMSG instr for this msg. */
  5057. /* Generates bytecode to parse a single non-lazy message field. */
  5058. static void generate_msgfield(compiler *c, const upb_fielddef *f,
  5059. upb_pbdecodermethod *method) {
  5060. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  5061. const upb_pbdecodermethod *sub_m = find_submethod(c, method, f);
  5062. int wire_type;
  5063. if (!sub_m) {
  5064. /* Don't emit any code for this field at all; it will be parsed as an
  5065. * unknown field.
  5066. *
  5067. * TODO(haberman): we should change this to parse it as a string field
  5068. * instead. It will probably be faster, but more importantly, once we
  5069. * start vending unknown fields, a field shouldn't be treated as unknown
  5070. * just because it doesn't have subhandlers registered. */
  5071. return;
  5072. }
  5073. label(c, LABEL_FIELD);
  5074. wire_type =
  5075. (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE)
  5076. ? UPB_WIRE_TYPE_DELIMITED
  5077. : UPB_WIRE_TYPE_START_GROUP;
  5078. if (upb_fielddef_isseq(f)) {
  5079. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5080. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  5081. dispatchtarget(c, method, f, wire_type);
  5082. putop(c, OP_PUSHTAGDELIM, 0);
  5083. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  5084. label(c, LABEL_LOOPSTART);
  5085. putpush(c, f);
  5086. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  5087. putop(c, OP_CALL, sub_m);
  5088. putop(c, OP_POP);
  5089. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  5090. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  5091. putop(c, OP_SETDELIM);
  5092. }
  5093. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5094. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  5095. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5096. label(c, LABEL_LOOPBREAK);
  5097. putop(c, OP_POP);
  5098. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  5099. } else {
  5100. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5101. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  5102. dispatchtarget(c, method, f, wire_type);
  5103. putpush(c, f);
  5104. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  5105. putop(c, OP_CALL, sub_m);
  5106. putop(c, OP_POP);
  5107. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  5108. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  5109. putop(c, OP_SETDELIM);
  5110. }
  5111. }
  5112. }
  5113. /* Generates bytecode to parse a single string or lazy submessage field. */
  5114. static void generate_delimfield(compiler *c, const upb_fielddef *f,
  5115. upb_pbdecodermethod *method) {
  5116. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  5117. label(c, LABEL_FIELD);
  5118. if (upb_fielddef_isseq(f)) {
  5119. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5120. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  5121. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  5122. putop(c, OP_PUSHTAGDELIM, 0);
  5123. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  5124. label(c, LABEL_LOOPSTART);
  5125. putop(c, OP_PUSHLENDELIM);
  5126. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  5127. /* Need to emit even if no handler to skip past the string. */
  5128. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  5129. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  5130. putop(c, OP_POP);
  5131. putop(c, OP_SETDELIM);
  5132. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5133. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_LOOPBREAK);
  5134. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5135. label(c, LABEL_LOOPBREAK);
  5136. putop(c, OP_POP);
  5137. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  5138. } else {
  5139. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5140. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  5141. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  5142. putop(c, OP_PUSHLENDELIM);
  5143. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  5144. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  5145. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  5146. putop(c, OP_POP);
  5147. putop(c, OP_SETDELIM);
  5148. }
  5149. }
  5150. /* Generates bytecode to parse a single primitive field. */
  5151. static void generate_primitivefield(compiler *c, const upb_fielddef *f,
  5152. upb_pbdecodermethod *method) {
  5153. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  5154. upb_descriptortype_t descriptor_type = upb_fielddef_descriptortype(f);
  5155. opcode parse_type;
  5156. upb_selector_t sel;
  5157. int wire_type;
  5158. label(c, LABEL_FIELD);
  5159. /* From a decoding perspective, ENUM is the same as INT32. */
  5160. if (descriptor_type == UPB_DESCRIPTOR_TYPE_ENUM)
  5161. descriptor_type = UPB_DESCRIPTOR_TYPE_INT32;
  5162. parse_type = (opcode)descriptor_type;
  5163. /* TODO(haberman): generate packed or non-packed first depending on "packed"
  5164. * setting in the fielddef. This will favor (in speed) whichever was
  5165. * specified. */
  5166. UPB_ASSERT((int)parse_type >= 0 && parse_type <= OP_MAX);
  5167. sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  5168. wire_type = upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  5169. if (upb_fielddef_isseq(f)) {
  5170. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5171. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  5172. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  5173. putop(c, OP_PUSHLENDELIM);
  5174. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); /* Packed */
  5175. label(c, LABEL_LOOPSTART);
  5176. putop(c, parse_type, sel);
  5177. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5178. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5179. dispatchtarget(c, method, f, wire_type);
  5180. putop(c, OP_PUSHTAGDELIM, 0);
  5181. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); /* Non-packed */
  5182. label(c, LABEL_LOOPSTART);
  5183. putop(c, parse_type, sel);
  5184. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5185. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  5186. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5187. label(c, LABEL_LOOPBREAK);
  5188. putop(c, OP_POP); /* Packed and non-packed join. */
  5189. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  5190. putop(c, OP_SETDELIM); /* Could remove for non-packed by dup ENDSEQ. */
  5191. } else {
  5192. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5193. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  5194. dispatchtarget(c, method, f, wire_type);
  5195. putop(c, parse_type, sel);
  5196. }
  5197. }
  5198. /* Adds bytecode for parsing the given message to the given decoderplan,
  5199. * while adding all dispatch targets to this message's dispatch table. */
  5200. static void compile_method(compiler *c, upb_pbdecodermethod *method) {
  5201. const upb_handlers *h;
  5202. const upb_msgdef *md;
  5203. uint32_t* start_pc;
  5204. upb_msg_field_iter i;
  5205. upb_value val;
  5206. UPB_ASSERT(method);
  5207. /* Clear all entries in the dispatch table. */
  5208. upb_inttable_uninit(&method->dispatch);
  5209. upb_inttable_init(&method->dispatch, UPB_CTYPE_UINT64);
  5210. h = upb_pbdecodermethod_desthandlers(method);
  5211. md = upb_handlers_msgdef(h);
  5212. method->code_base.ofs = pcofs(c);
  5213. putop(c, OP_SETDISPATCH, &method->dispatch);
  5214. putsel(c, OP_STARTMSG, UPB_STARTMSG_SELECTOR, h);
  5215. label(c, LABEL_FIELD);
  5216. start_pc = c->pc;
  5217. for(upb_msg_field_begin(&i, md);
  5218. !upb_msg_field_done(&i);
  5219. upb_msg_field_next(&i)) {
  5220. const upb_fielddef *f = upb_msg_iter_field(&i);
  5221. upb_fieldtype_t type = upb_fielddef_type(f);
  5222. if (type == UPB_TYPE_MESSAGE && !(haslazyhandlers(h, f) && c->lazy)) {
  5223. generate_msgfield(c, f, method);
  5224. } else if (type == UPB_TYPE_STRING || type == UPB_TYPE_BYTES ||
  5225. type == UPB_TYPE_MESSAGE) {
  5226. generate_delimfield(c, f, method);
  5227. } else {
  5228. generate_primitivefield(c, f, method);
  5229. }
  5230. }
  5231. /* If there were no fields, or if no handlers were defined, we need to
  5232. * generate a non-empty loop body so that we can at least dispatch for unknown
  5233. * fields and check for the end of the message. */
  5234. if (c->pc == start_pc) {
  5235. /* Check for end-of-message. */
  5236. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5237. /* Unconditionally dispatch. */
  5238. putop(c, OP_DISPATCH, 0);
  5239. }
  5240. /* For now we just loop back to the last field of the message (or if none,
  5241. * the DISPATCH opcode for the message). */
  5242. putop(c, OP_BRANCH, -LABEL_FIELD);
  5243. /* Insert both a label and a dispatch table entry for this end-of-msg. */
  5244. label(c, LABEL_ENDMSG);
  5245. val = upb_value_uint64(pcofs(c) - method->code_base.ofs);
  5246. upb_inttable_insert(&method->dispatch, DISPATCH_ENDMSG, val);
  5247. putsel(c, OP_ENDMSG, UPB_ENDMSG_SELECTOR, h);
  5248. putop(c, OP_RET);
  5249. upb_inttable_compact(&method->dispatch);
  5250. }
  5251. /* Populate "methods" with new upb_pbdecodermethod objects reachable from "h".
  5252. * Returns the method for these handlers.
  5253. *
  5254. * Generates a new method for every destination handlers reachable from "h". */
  5255. static void find_methods(compiler *c, const upb_handlers *h) {
  5256. upb_value v;
  5257. upb_msg_field_iter i;
  5258. const upb_msgdef *md;
  5259. upb_pbdecodermethod *method;
  5260. if (upb_inttable_lookupptr(&c->group->methods, h, &v))
  5261. return;
  5262. method = newmethod(h, c->group);
  5263. upb_inttable_insertptr(&c->group->methods, h, upb_value_ptr(method));
  5264. /* Find submethods. */
  5265. md = upb_handlers_msgdef(h);
  5266. for(upb_msg_field_begin(&i, md);
  5267. !upb_msg_field_done(&i);
  5268. upb_msg_field_next(&i)) {
  5269. const upb_fielddef *f = upb_msg_iter_field(&i);
  5270. const upb_handlers *sub_h;
  5271. if (upb_fielddef_type(f) == UPB_TYPE_MESSAGE &&
  5272. (sub_h = upb_handlers_getsubhandlers(h, f)) != NULL) {
  5273. /* We only generate a decoder method for submessages with handlers.
  5274. * Others will be parsed as unknown fields. */
  5275. find_methods(c, sub_h);
  5276. }
  5277. }
  5278. }
  5279. /* (Re-)compile bytecode for all messages in "msgs."
  5280. * Overwrites any existing bytecode in "c". */
  5281. static void compile_methods(compiler *c) {
  5282. upb_inttable_iter i;
  5283. /* Start over at the beginning of the bytecode. */
  5284. c->pc = c->group->bytecode;
  5285. upb_inttable_begin(&i, &c->group->methods);
  5286. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5287. upb_pbdecodermethod *method = upb_value_getptr(upb_inttable_iter_value(&i));
  5288. compile_method(c, method);
  5289. }
  5290. }
  5291. static void set_bytecode_handlers(mgroup *g) {
  5292. upb_inttable_iter i;
  5293. upb_inttable_begin(&i, &g->methods);
  5294. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5295. upb_pbdecodermethod *m = upb_value_getptr(upb_inttable_iter_value(&i));
  5296. upb_byteshandler *h = &m->input_handler_;
  5297. m->code_base.ptr = g->bytecode + m->code_base.ofs;
  5298. upb_byteshandler_setstartstr(h, upb_pbdecoder_startbc, m->code_base.ptr);
  5299. upb_byteshandler_setstring(h, upb_pbdecoder_decode, g);
  5300. upb_byteshandler_setendstr(h, upb_pbdecoder_end, m);
  5301. }
  5302. }
  5303. /* TODO(haberman): allow this to be constructed for an arbitrary set of dest
  5304. * handlers and other mgroups (but verify we have a transitive closure). */
  5305. const mgroup *mgroup_new(const upb_handlers *dest, bool allowjit, bool lazy) {
  5306. mgroup *g;
  5307. compiler *c;
  5308. UPB_UNUSED(allowjit);
  5309. g = newgroup();
  5310. c = newcompiler(g, lazy);
  5311. find_methods(c, dest);
  5312. /* We compile in two passes:
  5313. * 1. all messages are assigned relative offsets from the beginning of the
  5314. * bytecode (saved in method->code_base).
  5315. * 2. forwards OP_CALL instructions can be correctly linked since message
  5316. * offsets have been previously assigned.
  5317. *
  5318. * Could avoid the second pass by linking OP_CALL instructions somehow. */
  5319. compile_methods(c);
  5320. compile_methods(c);
  5321. g->bytecode_end = c->pc;
  5322. freecompiler(c);
  5323. #ifdef UPB_DUMP_BYTECODE
  5324. {
  5325. FILE *f = fopen("/tmp/upb-bytecode", "w");
  5326. UPB_ASSERT(f);
  5327. dumpbc(g->bytecode, g->bytecode_end, stderr);
  5328. dumpbc(g->bytecode, g->bytecode_end, f);
  5329. fclose(f);
  5330. f = fopen("/tmp/upb-bytecode.bin", "wb");
  5331. UPB_ASSERT(f);
  5332. fwrite(g->bytecode, 1, g->bytecode_end - g->bytecode, f);
  5333. fclose(f);
  5334. }
  5335. #endif
  5336. set_bytecode_handlers(g);
  5337. return g;
  5338. }
  5339. /* upb_pbcodecache ************************************************************/
  5340. upb_pbcodecache *upb_pbcodecache_new(upb_handlercache *dest) {
  5341. upb_pbcodecache *c = upb_gmalloc(sizeof(*c));
  5342. if (!c) return NULL;
  5343. c->dest = dest;
  5344. c->allow_jit = true;
  5345. c->lazy = false;
  5346. c->arena = upb_arena_new();
  5347. if (!upb_inttable_init(&c->groups, UPB_CTYPE_CONSTPTR)) return NULL;
  5348. return c;
  5349. }
  5350. void upb_pbcodecache_free(upb_pbcodecache *c) {
  5351. size_t i;
  5352. for (i = 0; i < upb_inttable_count(&c->groups); i++) {
  5353. upb_value v;
  5354. bool ok = upb_inttable_lookup(&c->groups, i, &v);
  5355. UPB_ASSERT(ok);
  5356. freegroup((void*)upb_value_getconstptr(v));
  5357. }
  5358. upb_inttable_uninit(&c->groups);
  5359. upb_arena_free(c->arena);
  5360. upb_gfree(c);
  5361. }
  5362. bool upb_pbcodecache_allowjit(const upb_pbcodecache *c) {
  5363. return c->allow_jit;
  5364. }
  5365. void upb_pbcodecache_setallowjit(upb_pbcodecache *c, bool allow) {
  5366. UPB_ASSERT(upb_inttable_count(&c->groups) == 0);
  5367. c->allow_jit = allow;
  5368. }
  5369. void upb_pbdecodermethodopts_setlazy(upb_pbcodecache *c, bool lazy) {
  5370. UPB_ASSERT(upb_inttable_count(&c->groups) == 0);
  5371. c->lazy = lazy;
  5372. }
  5373. const upb_pbdecodermethod *upb_pbcodecache_get(upb_pbcodecache *c,
  5374. const upb_msgdef *md) {
  5375. upb_value v;
  5376. bool ok;
  5377. const upb_handlers *h;
  5378. const mgroup *g;
  5379. /* Right now we build a new DecoderMethod every time.
  5380. * TODO(haberman): properly cache methods by their true key. */
  5381. h = upb_handlercache_get(c->dest, md);
  5382. g = mgroup_new(h, c->allow_jit, c->lazy);
  5383. upb_inttable_push(&c->groups, upb_value_constptr(g));
  5384. ok = upb_inttable_lookupptr(&g->methods, h, &v);
  5385. UPB_ASSERT(ok);
  5386. return upb_value_getptr(v);
  5387. }
  5388. /*
  5389. ** upb::Decoder (Bytecode Decoder VM)
  5390. **
  5391. ** Bytecode must previously have been generated using the bytecode compiler in
  5392. ** compile_decoder.c. This decoder then walks through the bytecode op-by-op to
  5393. ** parse the input.
  5394. **
  5395. ** Decoding is fully resumable; we just keep a pointer to the current bytecode
  5396. ** instruction and resume from there. A fair amount of the logic here is to
  5397. ** handle the fact that values can span buffer seams and we have to be able to
  5398. ** be capable of suspending/resuming from any byte in the stream. This
  5399. ** sometimes requires keeping a few trailing bytes from the last buffer around
  5400. ** in the "residual" buffer.
  5401. */
  5402. #include <inttypes.h>
  5403. #include <stddef.h>
  5404. #ifdef UPB_DUMP_BYTECODE
  5405. #include <stdio.h>
  5406. #endif
  5407. #define CHECK_SUSPEND(x) if (!(x)) return upb_pbdecoder_suspend(d);
  5408. /* Error messages that are shared between the bytecode and JIT decoders. */
  5409. const char *kPbDecoderStackOverflow = "Nesting too deep.";
  5410. const char *kPbDecoderSubmessageTooLong =
  5411. "Submessage end extends past enclosing submessage.";
  5412. /* Error messages shared within this file. */
  5413. static const char *kUnterminatedVarint = "Unterminated varint.";
  5414. /* upb_pbdecoder **************************************************************/
  5415. static opcode halt = OP_HALT;
  5416. /* A dummy character we can point to when the user passes us a NULL buffer.
  5417. * We need this because in C (NULL + 0) and (NULL - NULL) are undefined
  5418. * behavior, which would invalidate functions like curbufleft(). */
  5419. static const char dummy_char;
  5420. /* Whether an op consumes any of the input buffer. */
  5421. static bool consumes_input(opcode op) {
  5422. switch (op) {
  5423. case OP_SETDISPATCH:
  5424. case OP_STARTMSG:
  5425. case OP_ENDMSG:
  5426. case OP_STARTSEQ:
  5427. case OP_ENDSEQ:
  5428. case OP_STARTSUBMSG:
  5429. case OP_ENDSUBMSG:
  5430. case OP_STARTSTR:
  5431. case OP_ENDSTR:
  5432. case OP_PUSHTAGDELIM:
  5433. case OP_POP:
  5434. case OP_SETDELIM:
  5435. case OP_SETBIGGROUPNUM:
  5436. case OP_CHECKDELIM:
  5437. case OP_CALL:
  5438. case OP_RET:
  5439. case OP_BRANCH:
  5440. return false;
  5441. default:
  5442. return true;
  5443. }
  5444. }
  5445. static size_t stacksize(upb_pbdecoder *d, size_t entries) {
  5446. UPB_UNUSED(d);
  5447. return entries * sizeof(upb_pbdecoder_frame);
  5448. }
  5449. static size_t callstacksize(upb_pbdecoder *d, size_t entries) {
  5450. UPB_UNUSED(d);
  5451. #ifdef UPB_USE_JIT_X64
  5452. if (d->method_->is_native_) {
  5453. /* Each native stack frame needs two pointers, plus we need a few frames for
  5454. * the enter/exit trampolines. */
  5455. size_t ret = entries * sizeof(void*) * 2;
  5456. ret += sizeof(void*) * 10;
  5457. return ret;
  5458. }
  5459. #endif
  5460. return entries * sizeof(uint32_t*);
  5461. }
  5462. static bool in_residual_buf(const upb_pbdecoder *d, const char *p);
  5463. /* It's unfortunate that we have to micro-manage the compiler with
  5464. * UPB_FORCEINLINE and UPB_NOINLINE, especially since this tuning is necessarily
  5465. * specific to one hardware configuration. But empirically on a Core i7,
  5466. * performance increases 30-50% with these annotations. Every instance where
  5467. * these appear, gcc 4.2.1 made the wrong decision and degraded performance in
  5468. * benchmarks. */
  5469. static void seterr(upb_pbdecoder *d, const char *msg) {
  5470. upb_status_seterrmsg(d->status, msg);
  5471. }
  5472. void upb_pbdecoder_seterr(upb_pbdecoder *d, const char *msg) {
  5473. seterr(d, msg);
  5474. }
  5475. /* Buffering ******************************************************************/
  5476. /* We operate on one buffer at a time, which is either the user's buffer passed
  5477. * to our "decode" callback or some residual bytes from the previous buffer. */
  5478. /* How many bytes can be safely read from d->ptr without reading past end-of-buf
  5479. * or past the current delimited end. */
  5480. static size_t curbufleft(const upb_pbdecoder *d) {
  5481. UPB_ASSERT(d->data_end >= d->ptr);
  5482. return d->data_end - d->ptr;
  5483. }
  5484. /* How many bytes are available before end-of-buffer. */
  5485. static size_t bufleft(const upb_pbdecoder *d) {
  5486. return d->end - d->ptr;
  5487. }
  5488. /* Overall stream offset of d->ptr. */
  5489. uint64_t offset(const upb_pbdecoder *d) {
  5490. return d->bufstart_ofs + (d->ptr - d->buf);
  5491. }
  5492. /* How many bytes are available before the end of this delimited region. */
  5493. size_t delim_remaining(const upb_pbdecoder *d) {
  5494. return d->top->end_ofs - offset(d);
  5495. }
  5496. /* Advances d->ptr. */
  5497. static void advance(upb_pbdecoder *d, size_t len) {
  5498. UPB_ASSERT(curbufleft(d) >= len);
  5499. d->ptr += len;
  5500. }
  5501. static bool in_buf(const char *p, const char *buf, const char *end) {
  5502. return p >= buf && p <= end;
  5503. }
  5504. static bool in_residual_buf(const upb_pbdecoder *d, const char *p) {
  5505. return in_buf(p, d->residual, d->residual_end);
  5506. }
  5507. /* Calculates the delim_end value, which is affected by both the current buffer
  5508. * and the parsing stack, so must be called whenever either is updated. */
  5509. static void set_delim_end(upb_pbdecoder *d) {
  5510. size_t delim_ofs = d->top->end_ofs - d->bufstart_ofs;
  5511. if (delim_ofs <= (size_t)(d->end - d->buf)) {
  5512. d->delim_end = d->buf + delim_ofs;
  5513. d->data_end = d->delim_end;
  5514. } else {
  5515. d->data_end = d->end;
  5516. d->delim_end = NULL;
  5517. }
  5518. }
  5519. static void switchtobuf(upb_pbdecoder *d, const char *buf, const char *end) {
  5520. d->ptr = buf;
  5521. d->buf = buf;
  5522. d->end = end;
  5523. set_delim_end(d);
  5524. }
  5525. static void advancetobuf(upb_pbdecoder *d, const char *buf, size_t len) {
  5526. UPB_ASSERT(curbufleft(d) == 0);
  5527. d->bufstart_ofs += (d->end - d->buf);
  5528. switchtobuf(d, buf, buf + len);
  5529. }
  5530. static void checkpoint(upb_pbdecoder *d) {
  5531. /* The assertion here is in the interests of efficiency, not correctness.
  5532. * We are trying to ensure that we don't checkpoint() more often than
  5533. * necessary. */
  5534. UPB_ASSERT(d->checkpoint != d->ptr);
  5535. d->checkpoint = d->ptr;
  5536. }
  5537. /* Skips "bytes" bytes in the stream, which may be more than available. If we
  5538. * skip more bytes than are available, we return a long read count to the caller
  5539. * indicating how many bytes can be skipped over before passing actual data
  5540. * again. Skipped bytes can pass a NULL buffer and the decoder guarantees they
  5541. * won't actually be read.
  5542. */
  5543. static int32_t skip(upb_pbdecoder *d, size_t bytes) {
  5544. UPB_ASSERT(!in_residual_buf(d, d->ptr) || d->size_param == 0);
  5545. UPB_ASSERT(d->skip == 0);
  5546. if (bytes > delim_remaining(d)) {
  5547. seterr(d, "Skipped value extended beyond enclosing submessage.");
  5548. return upb_pbdecoder_suspend(d);
  5549. } else if (bufleft(d) >= bytes) {
  5550. /* Skipped data is all in current buffer, and more is still available. */
  5551. advance(d, bytes);
  5552. d->skip = 0;
  5553. return DECODE_OK;
  5554. } else {
  5555. /* Skipped data extends beyond currently available buffers. */
  5556. d->pc = d->last;
  5557. d->skip = bytes - curbufleft(d);
  5558. d->bufstart_ofs += (d->end - d->buf);
  5559. d->residual_end = d->residual;
  5560. switchtobuf(d, d->residual, d->residual_end);
  5561. return d->size_param + d->skip;
  5562. }
  5563. }
  5564. /* Resumes the decoder from an initial state or from a previous suspend. */
  5565. int32_t upb_pbdecoder_resume(upb_pbdecoder *d, void *p, const char *buf,
  5566. size_t size, const upb_bufhandle *handle) {
  5567. UPB_UNUSED(p); /* Useless; just for the benefit of the JIT. */
  5568. /* d->skip and d->residual_end could probably elegantly be represented
  5569. * as a single variable, to more easily represent this invariant. */
  5570. UPB_ASSERT(!(d->skip && d->residual_end > d->residual));
  5571. /* We need to remember the original size_param, so that the value we return
  5572. * is relative to it, even if we do some skipping first. */
  5573. d->size_param = size;
  5574. d->handle = handle;
  5575. /* Have to handle this case specially (ie. not with skip()) because the user
  5576. * is allowed to pass a NULL buffer here, which won't allow us to safely
  5577. * calculate a d->end or use our normal functions like curbufleft(). */
  5578. if (d->skip && d->skip >= size) {
  5579. d->skip -= size;
  5580. d->bufstart_ofs += size;
  5581. buf = &dummy_char;
  5582. size = 0;
  5583. /* We can't just return now, because we might need to execute some ops
  5584. * like CHECKDELIM, which could call some callbacks and pop the stack. */
  5585. }
  5586. /* We need to pretend that this was the actual buffer param, since some of the
  5587. * calculations assume that d->ptr/d->buf is relative to this. */
  5588. d->buf_param = buf;
  5589. if (!buf) {
  5590. /* NULL buf is ok if its entire span is covered by the "skip" above, but
  5591. * by this point we know that "skip" doesn't cover the buffer. */
  5592. seterr(d, "Passed NULL buffer over non-skippable region.");
  5593. return upb_pbdecoder_suspend(d);
  5594. }
  5595. if (d->residual_end > d->residual) {
  5596. /* We have residual bytes from the last buffer. */
  5597. UPB_ASSERT(d->ptr == d->residual);
  5598. } else {
  5599. switchtobuf(d, buf, buf + size);
  5600. }
  5601. d->checkpoint = d->ptr;
  5602. /* Handle skips that don't cover the whole buffer (as above). */
  5603. if (d->skip) {
  5604. size_t skip_bytes = d->skip;
  5605. d->skip = 0;
  5606. CHECK_RETURN(skip(d, skip_bytes));
  5607. checkpoint(d);
  5608. }
  5609. /* If we're inside an unknown group, continue to parse unknown values. */
  5610. if (d->top->groupnum < 0) {
  5611. CHECK_RETURN(upb_pbdecoder_skipunknown(d, -1, 0));
  5612. checkpoint(d);
  5613. }
  5614. return DECODE_OK;
  5615. }
  5616. /* Suspends the decoder at the last checkpoint, without saving any residual
  5617. * bytes. If there are any unconsumed bytes, returns a short byte count. */
  5618. size_t upb_pbdecoder_suspend(upb_pbdecoder *d) {
  5619. d->pc = d->last;
  5620. if (d->checkpoint == d->residual) {
  5621. /* Checkpoint was in residual buf; no user bytes were consumed. */
  5622. d->ptr = d->residual;
  5623. return 0;
  5624. } else {
  5625. size_t ret = d->size_param - (d->end - d->checkpoint);
  5626. UPB_ASSERT(!in_residual_buf(d, d->checkpoint));
  5627. UPB_ASSERT(d->buf == d->buf_param || d->buf == &dummy_char);
  5628. d->bufstart_ofs += (d->checkpoint - d->buf);
  5629. d->residual_end = d->residual;
  5630. switchtobuf(d, d->residual, d->residual_end);
  5631. return ret;
  5632. }
  5633. }
  5634. /* Suspends the decoder at the last checkpoint, and saves any unconsumed
  5635. * bytes in our residual buffer. This is necessary if we need more user
  5636. * bytes to form a complete value, which might not be contiguous in the
  5637. * user's buffers. Always consumes all user bytes. */
  5638. static size_t suspend_save(upb_pbdecoder *d) {
  5639. /* We hit end-of-buffer before we could parse a full value.
  5640. * Save any unconsumed bytes (if any) to the residual buffer. */
  5641. d->pc = d->last;
  5642. if (d->checkpoint == d->residual) {
  5643. /* Checkpoint was in residual buf; append user byte(s) to residual buf. */
  5644. UPB_ASSERT((d->residual_end - d->residual) + d->size_param <=
  5645. sizeof(d->residual));
  5646. if (!in_residual_buf(d, d->ptr)) {
  5647. d->bufstart_ofs -= (d->residual_end - d->residual);
  5648. }
  5649. memcpy(d->residual_end, d->buf_param, d->size_param);
  5650. d->residual_end += d->size_param;
  5651. } else {
  5652. /* Checkpoint was in user buf; old residual bytes not needed. */
  5653. size_t save;
  5654. UPB_ASSERT(!in_residual_buf(d, d->checkpoint));
  5655. d->ptr = d->checkpoint;
  5656. save = curbufleft(d);
  5657. UPB_ASSERT(save <= sizeof(d->residual));
  5658. memcpy(d->residual, d->ptr, save);
  5659. d->residual_end = d->residual + save;
  5660. d->bufstart_ofs = offset(d);
  5661. }
  5662. switchtobuf(d, d->residual, d->residual_end);
  5663. return d->size_param;
  5664. }
  5665. /* Copies the next "bytes" bytes into "buf" and advances the stream.
  5666. * Requires that this many bytes are available in the current buffer. */
  5667. UPB_FORCEINLINE static void consumebytes(upb_pbdecoder *d, void *buf,
  5668. size_t bytes) {
  5669. UPB_ASSERT(bytes <= curbufleft(d));
  5670. memcpy(buf, d->ptr, bytes);
  5671. advance(d, bytes);
  5672. }
  5673. /* Slow path for getting the next "bytes" bytes, regardless of whether they are
  5674. * available in the current buffer or not. Returns a status code as described
  5675. * in decoder.int.h. */
  5676. UPB_NOINLINE static int32_t getbytes_slow(upb_pbdecoder *d, void *buf,
  5677. size_t bytes) {
  5678. const size_t avail = curbufleft(d);
  5679. consumebytes(d, buf, avail);
  5680. bytes -= avail;
  5681. UPB_ASSERT(bytes > 0);
  5682. if (in_residual_buf(d, d->ptr)) {
  5683. advancetobuf(d, d->buf_param, d->size_param);
  5684. }
  5685. if (curbufleft(d) >= bytes) {
  5686. consumebytes(d, (char *)buf + avail, bytes);
  5687. return DECODE_OK;
  5688. } else if (d->data_end == d->delim_end) {
  5689. seterr(d, "Submessage ended in the middle of a value or group");
  5690. return upb_pbdecoder_suspend(d);
  5691. } else {
  5692. return suspend_save(d);
  5693. }
  5694. }
  5695. /* Gets the next "bytes" bytes, regardless of whether they are available in the
  5696. * current buffer or not. Returns a status code as described in decoder.int.h.
  5697. */
  5698. UPB_FORCEINLINE static int32_t getbytes(upb_pbdecoder *d, void *buf,
  5699. size_t bytes) {
  5700. if (curbufleft(d) >= bytes) {
  5701. /* Buffer has enough data to satisfy. */
  5702. consumebytes(d, buf, bytes);
  5703. return DECODE_OK;
  5704. } else {
  5705. return getbytes_slow(d, buf, bytes);
  5706. }
  5707. }
  5708. UPB_NOINLINE static size_t peekbytes_slow(upb_pbdecoder *d, void *buf,
  5709. size_t bytes) {
  5710. size_t ret = curbufleft(d);
  5711. memcpy(buf, d->ptr, ret);
  5712. if (in_residual_buf(d, d->ptr)) {
  5713. size_t copy = UPB_MIN(bytes - ret, d->size_param);
  5714. memcpy((char *)buf + ret, d->buf_param, copy);
  5715. ret += copy;
  5716. }
  5717. return ret;
  5718. }
  5719. UPB_FORCEINLINE static size_t peekbytes(upb_pbdecoder *d, void *buf,
  5720. size_t bytes) {
  5721. if (curbufleft(d) >= bytes) {
  5722. memcpy(buf, d->ptr, bytes);
  5723. return bytes;
  5724. } else {
  5725. return peekbytes_slow(d, buf, bytes);
  5726. }
  5727. }
  5728. /* Decoding of wire types *****************************************************/
  5729. /* Slow path for decoding a varint from the current buffer position.
  5730. * Returns a status code as described in decoder.int.h. */
  5731. UPB_NOINLINE int32_t upb_pbdecoder_decode_varint_slow(upb_pbdecoder *d,
  5732. uint64_t *u64) {
  5733. uint8_t byte = 0x80;
  5734. int bitpos;
  5735. *u64 = 0;
  5736. for(bitpos = 0; bitpos < 70 && (byte & 0x80); bitpos += 7) {
  5737. CHECK_RETURN(getbytes(d, &byte, 1));
  5738. *u64 |= (uint64_t)(byte & 0x7F) << bitpos;
  5739. }
  5740. if(bitpos == 70 && (byte & 0x80)) {
  5741. seterr(d, kUnterminatedVarint);
  5742. return upb_pbdecoder_suspend(d);
  5743. }
  5744. return DECODE_OK;
  5745. }
  5746. /* Decodes a varint from the current buffer position.
  5747. * Returns a status code as described in decoder.int.h. */
  5748. UPB_FORCEINLINE static int32_t decode_varint(upb_pbdecoder *d, uint64_t *u64) {
  5749. if (curbufleft(d) > 0 && !(*d->ptr & 0x80)) {
  5750. *u64 = *d->ptr;
  5751. advance(d, 1);
  5752. return DECODE_OK;
  5753. } else if (curbufleft(d) >= 10) {
  5754. /* Fast case. */
  5755. upb_decoderet r = upb_vdecode_fast(d->ptr);
  5756. if (r.p == NULL) {
  5757. seterr(d, kUnterminatedVarint);
  5758. return upb_pbdecoder_suspend(d);
  5759. }
  5760. advance(d, r.p - d->ptr);
  5761. *u64 = r.val;
  5762. return DECODE_OK;
  5763. } else {
  5764. /* Slow case -- varint spans buffer seam. */
  5765. return upb_pbdecoder_decode_varint_slow(d, u64);
  5766. }
  5767. }
  5768. /* Decodes a 32-bit varint from the current buffer position.
  5769. * Returns a status code as described in decoder.int.h. */
  5770. UPB_FORCEINLINE static int32_t decode_v32(upb_pbdecoder *d, uint32_t *u32) {
  5771. uint64_t u64;
  5772. int32_t ret = decode_varint(d, &u64);
  5773. if (ret >= 0) return ret;
  5774. if (u64 > UINT32_MAX) {
  5775. seterr(d, "Unterminated 32-bit varint");
  5776. /* TODO(haberman) guarantee that this function return is >= 0 somehow,
  5777. * so we know this path will always be treated as error by our caller.
  5778. * Right now the size_t -> int32_t can overflow and produce negative values.
  5779. */
  5780. *u32 = 0;
  5781. return upb_pbdecoder_suspend(d);
  5782. }
  5783. *u32 = u64;
  5784. return DECODE_OK;
  5785. }
  5786. /* Decodes a fixed32 from the current buffer position.
  5787. * Returns a status code as described in decoder.int.h.
  5788. * TODO: proper byte swapping for big-endian machines. */
  5789. UPB_FORCEINLINE static int32_t decode_fixed32(upb_pbdecoder *d, uint32_t *u32) {
  5790. return getbytes(d, u32, 4);
  5791. }
  5792. /* Decodes a fixed64 from the current buffer position.
  5793. * Returns a status code as described in decoder.int.h.
  5794. * TODO: proper byte swapping for big-endian machines. */
  5795. UPB_FORCEINLINE static int32_t decode_fixed64(upb_pbdecoder *d, uint64_t *u64) {
  5796. return getbytes(d, u64, 8);
  5797. }
  5798. /* Non-static versions of the above functions.
  5799. * These are called by the JIT for fallback paths. */
  5800. int32_t upb_pbdecoder_decode_f32(upb_pbdecoder *d, uint32_t *u32) {
  5801. return decode_fixed32(d, u32);
  5802. }
  5803. int32_t upb_pbdecoder_decode_f64(upb_pbdecoder *d, uint64_t *u64) {
  5804. return decode_fixed64(d, u64);
  5805. }
  5806. static double as_double(uint64_t n) { double d; memcpy(&d, &n, 8); return d; }
  5807. static float as_float(uint32_t n) { float f; memcpy(&f, &n, 4); return f; }
  5808. /* Pushes a frame onto the decoder stack. */
  5809. static bool decoder_push(upb_pbdecoder *d, uint64_t end) {
  5810. upb_pbdecoder_frame *fr = d->top;
  5811. if (end > fr->end_ofs) {
  5812. seterr(d, kPbDecoderSubmessageTooLong);
  5813. return false;
  5814. } else if (fr == d->limit) {
  5815. seterr(d, kPbDecoderStackOverflow);
  5816. return false;
  5817. }
  5818. fr++;
  5819. fr->end_ofs = end;
  5820. fr->dispatch = NULL;
  5821. fr->groupnum = 0;
  5822. d->top = fr;
  5823. return true;
  5824. }
  5825. static bool pushtagdelim(upb_pbdecoder *d, uint32_t arg) {
  5826. /* While we expect to see an "end" tag (either ENDGROUP or a non-sequence
  5827. * field number) prior to hitting any enclosing submessage end, pushing our
  5828. * existing delim end prevents us from continuing to parse values from a
  5829. * corrupt proto that doesn't give us an END tag in time. */
  5830. if (!decoder_push(d, d->top->end_ofs))
  5831. return false;
  5832. d->top->groupnum = arg;
  5833. return true;
  5834. }
  5835. /* Pops a frame from the decoder stack. */
  5836. static void decoder_pop(upb_pbdecoder *d) { d->top--; }
  5837. UPB_NOINLINE int32_t upb_pbdecoder_checktag_slow(upb_pbdecoder *d,
  5838. uint64_t expected) {
  5839. uint64_t data = 0;
  5840. size_t bytes = upb_value_size(expected);
  5841. size_t read = peekbytes(d, &data, bytes);
  5842. if (read == bytes && data == expected) {
  5843. /* Advance past matched bytes. */
  5844. int32_t ok = getbytes(d, &data, read);
  5845. UPB_ASSERT(ok < 0);
  5846. return DECODE_OK;
  5847. } else if (read < bytes && memcmp(&data, &expected, read) == 0) {
  5848. return suspend_save(d);
  5849. } else {
  5850. return DECODE_MISMATCH;
  5851. }
  5852. }
  5853. int32_t upb_pbdecoder_skipunknown(upb_pbdecoder *d, int32_t fieldnum,
  5854. uint8_t wire_type) {
  5855. if (fieldnum >= 0)
  5856. goto have_tag;
  5857. while (true) {
  5858. uint32_t tag;
  5859. CHECK_RETURN(decode_v32(d, &tag));
  5860. wire_type = tag & 0x7;
  5861. fieldnum = tag >> 3;
  5862. have_tag:
  5863. if (fieldnum == 0) {
  5864. seterr(d, "Saw invalid field number (0)");
  5865. return upb_pbdecoder_suspend(d);
  5866. }
  5867. switch (wire_type) {
  5868. case UPB_WIRE_TYPE_32BIT:
  5869. CHECK_RETURN(skip(d, 4));
  5870. break;
  5871. case UPB_WIRE_TYPE_64BIT:
  5872. CHECK_RETURN(skip(d, 8));
  5873. break;
  5874. case UPB_WIRE_TYPE_VARINT: {
  5875. uint64_t u64;
  5876. CHECK_RETURN(decode_varint(d, &u64));
  5877. break;
  5878. }
  5879. case UPB_WIRE_TYPE_DELIMITED: {
  5880. uint32_t len;
  5881. CHECK_RETURN(decode_v32(d, &len));
  5882. CHECK_RETURN(skip(d, len));
  5883. break;
  5884. }
  5885. case UPB_WIRE_TYPE_START_GROUP:
  5886. CHECK_SUSPEND(pushtagdelim(d, -fieldnum));
  5887. break;
  5888. case UPB_WIRE_TYPE_END_GROUP:
  5889. if (fieldnum == -d->top->groupnum) {
  5890. decoder_pop(d);
  5891. } else if (fieldnum == d->top->groupnum) {
  5892. return DECODE_ENDGROUP;
  5893. } else {
  5894. seterr(d, "Unmatched ENDGROUP tag.");
  5895. return upb_pbdecoder_suspend(d);
  5896. }
  5897. break;
  5898. default:
  5899. seterr(d, "Invalid wire type");
  5900. return upb_pbdecoder_suspend(d);
  5901. }
  5902. if (d->top->groupnum >= 0) {
  5903. /* TODO: More code needed for handling unknown groups. */
  5904. upb_sink_putunknown(d->top->sink, d->checkpoint, d->ptr - d->checkpoint);
  5905. return DECODE_OK;
  5906. }
  5907. /* Unknown group -- continue looping over unknown fields. */
  5908. checkpoint(d);
  5909. }
  5910. }
  5911. static void goto_endmsg(upb_pbdecoder *d) {
  5912. upb_value v;
  5913. bool found = upb_inttable_lookup32(d->top->dispatch, DISPATCH_ENDMSG, &v);
  5914. UPB_ASSERT(found);
  5915. d->pc = d->top->base + upb_value_getuint64(v);
  5916. }
  5917. /* Parses a tag and jumps to the corresponding bytecode instruction for this
  5918. * field.
  5919. *
  5920. * If the tag is unknown (or the wire type doesn't match), parses the field as
  5921. * unknown. If the tag is a valid ENDGROUP tag, jumps to the bytecode
  5922. * instruction for the end of message. */
  5923. static int32_t dispatch(upb_pbdecoder *d) {
  5924. upb_inttable *dispatch = d->top->dispatch;
  5925. uint32_t tag;
  5926. uint8_t wire_type;
  5927. uint32_t fieldnum;
  5928. upb_value val;
  5929. int32_t retval;
  5930. /* Decode tag. */
  5931. CHECK_RETURN(decode_v32(d, &tag));
  5932. wire_type = tag & 0x7;
  5933. fieldnum = tag >> 3;
  5934. /* Lookup tag. Because of packed/non-packed compatibility, we have to
  5935. * check the wire type against two possibilities. */
  5936. if (fieldnum != DISPATCH_ENDMSG &&
  5937. upb_inttable_lookup32(dispatch, fieldnum, &val)) {
  5938. uint64_t v = upb_value_getuint64(val);
  5939. if (wire_type == (v & 0xff)) {
  5940. d->pc = d->top->base + (v >> 16);
  5941. return DECODE_OK;
  5942. } else if (wire_type == ((v >> 8) & 0xff)) {
  5943. bool found =
  5944. upb_inttable_lookup(dispatch, fieldnum + UPB_MAX_FIELDNUMBER, &val);
  5945. UPB_ASSERT(found);
  5946. d->pc = d->top->base + upb_value_getuint64(val);
  5947. return DECODE_OK;
  5948. }
  5949. }
  5950. /* We have some unknown fields (or ENDGROUP) to parse. The DISPATCH or TAG
  5951. * bytecode that triggered this is preceded by a CHECKDELIM bytecode which
  5952. * we need to back up to, so that when we're done skipping unknown data we
  5953. * can re-check the delimited end. */
  5954. d->last--; /* Necessary if we get suspended */
  5955. d->pc = d->last;
  5956. UPB_ASSERT(getop(*d->last) == OP_CHECKDELIM);
  5957. /* Unknown field or ENDGROUP. */
  5958. retval = upb_pbdecoder_skipunknown(d, fieldnum, wire_type);
  5959. CHECK_RETURN(retval);
  5960. if (retval == DECODE_ENDGROUP) {
  5961. goto_endmsg(d);
  5962. return DECODE_OK;
  5963. }
  5964. return DECODE_OK;
  5965. }
  5966. /* Callers know that the stack is more than one deep because the opcodes that
  5967. * call this only occur after PUSH operations. */
  5968. upb_pbdecoder_frame *outer_frame(upb_pbdecoder *d) {
  5969. UPB_ASSERT(d->top != d->stack);
  5970. return d->top - 1;
  5971. }
  5972. /* The main decoding loop *****************************************************/
  5973. /* The main decoder VM function. Uses traditional bytecode dispatch loop with a
  5974. * switch() statement. */
  5975. size_t run_decoder_vm(upb_pbdecoder *d, const mgroup *group,
  5976. const upb_bufhandle* handle) {
  5977. #define VMCASE(op, code) \
  5978. case op: { code; if (consumes_input(op)) checkpoint(d); break; }
  5979. #define PRIMITIVE_OP(type, wt, name, convfunc, ctype) \
  5980. VMCASE(OP_PARSE_ ## type, { \
  5981. ctype val; \
  5982. CHECK_RETURN(decode_ ## wt(d, &val)); \
  5983. upb_sink_put ## name(d->top->sink, arg, (convfunc)(val)); \
  5984. })
  5985. while(1) {
  5986. int32_t instruction;
  5987. opcode op;
  5988. uint32_t arg;
  5989. int32_t longofs;
  5990. d->last = d->pc;
  5991. instruction = *d->pc++;
  5992. op = getop(instruction);
  5993. arg = instruction >> 8;
  5994. longofs = arg;
  5995. UPB_ASSERT(d->ptr != d->residual_end);
  5996. UPB_UNUSED(group);
  5997. #ifdef UPB_DUMP_BYTECODE
  5998. fprintf(stderr, "s_ofs=%d buf_ofs=%d data_rem=%d buf_rem=%d delim_rem=%d "
  5999. "%x %s (%d)\n",
  6000. (int)offset(d),
  6001. (int)(d->ptr - d->buf),
  6002. (int)(d->data_end - d->ptr),
  6003. (int)(d->end - d->ptr),
  6004. (int)((d->top->end_ofs - d->bufstart_ofs) - (d->ptr - d->buf)),
  6005. (int)(d->pc - 1 - group->bytecode),
  6006. upb_pbdecoder_getopname(op),
  6007. arg);
  6008. #endif
  6009. switch (op) {
  6010. /* Technically, we are losing data if we see a 32-bit varint that is not
  6011. * properly sign-extended. We could detect this and error about the data
  6012. * loss, but proto2 does not do this, so we pass. */
  6013. PRIMITIVE_OP(INT32, varint, int32, int32_t, uint64_t)
  6014. PRIMITIVE_OP(INT64, varint, int64, int64_t, uint64_t)
  6015. PRIMITIVE_OP(UINT32, varint, uint32, uint32_t, uint64_t)
  6016. PRIMITIVE_OP(UINT64, varint, uint64, uint64_t, uint64_t)
  6017. PRIMITIVE_OP(FIXED32, fixed32, uint32, uint32_t, uint32_t)
  6018. PRIMITIVE_OP(FIXED64, fixed64, uint64, uint64_t, uint64_t)
  6019. PRIMITIVE_OP(SFIXED32, fixed32, int32, int32_t, uint32_t)
  6020. PRIMITIVE_OP(SFIXED64, fixed64, int64, int64_t, uint64_t)
  6021. PRIMITIVE_OP(BOOL, varint, bool, bool, uint64_t)
  6022. PRIMITIVE_OP(DOUBLE, fixed64, double, as_double, uint64_t)
  6023. PRIMITIVE_OP(FLOAT, fixed32, float, as_float, uint32_t)
  6024. PRIMITIVE_OP(SINT32, varint, int32, upb_zzdec_32, uint64_t)
  6025. PRIMITIVE_OP(SINT64, varint, int64, upb_zzdec_64, uint64_t)
  6026. VMCASE(OP_SETDISPATCH,
  6027. d->top->base = d->pc - 1;
  6028. memcpy(&d->top->dispatch, d->pc, sizeof(void*));
  6029. d->pc += sizeof(void*) / sizeof(uint32_t);
  6030. )
  6031. VMCASE(OP_STARTMSG,
  6032. CHECK_SUSPEND(upb_sink_startmsg(d->top->sink));
  6033. )
  6034. VMCASE(OP_ENDMSG,
  6035. CHECK_SUSPEND(upb_sink_endmsg(d->top->sink, d->status));
  6036. )
  6037. VMCASE(OP_STARTSEQ,
  6038. upb_pbdecoder_frame *outer = outer_frame(d);
  6039. CHECK_SUSPEND(upb_sink_startseq(outer->sink, arg, &d->top->sink));
  6040. )
  6041. VMCASE(OP_ENDSEQ,
  6042. CHECK_SUSPEND(upb_sink_endseq(d->top->sink, arg));
  6043. )
  6044. VMCASE(OP_STARTSUBMSG,
  6045. upb_pbdecoder_frame *outer = outer_frame(d);
  6046. CHECK_SUSPEND(upb_sink_startsubmsg(outer->sink, arg, &d->top->sink));
  6047. )
  6048. VMCASE(OP_ENDSUBMSG,
  6049. CHECK_SUSPEND(upb_sink_endsubmsg(d->top->sink, arg));
  6050. )
  6051. VMCASE(OP_STARTSTR,
  6052. uint32_t len = delim_remaining(d);
  6053. upb_pbdecoder_frame *outer = outer_frame(d);
  6054. CHECK_SUSPEND(upb_sink_startstr(outer->sink, arg, len, &d->top->sink));
  6055. if (len == 0) {
  6056. d->pc++; /* Skip OP_STRING. */
  6057. }
  6058. )
  6059. VMCASE(OP_STRING,
  6060. uint32_t len = curbufleft(d);
  6061. size_t n = upb_sink_putstring(d->top->sink, arg, d->ptr, len, handle);
  6062. if (n > len) {
  6063. if (n > delim_remaining(d)) {
  6064. seterr(d, "Tried to skip past end of string.");
  6065. return upb_pbdecoder_suspend(d);
  6066. } else {
  6067. int32_t ret = skip(d, n);
  6068. /* This shouldn't return DECODE_OK, because n > len. */
  6069. UPB_ASSERT(ret >= 0);
  6070. return ret;
  6071. }
  6072. }
  6073. advance(d, n);
  6074. if (n < len || d->delim_end == NULL) {
  6075. /* We aren't finished with this string yet. */
  6076. d->pc--; /* Repeat OP_STRING. */
  6077. if (n > 0) checkpoint(d);
  6078. return upb_pbdecoder_suspend(d);
  6079. }
  6080. )
  6081. VMCASE(OP_ENDSTR,
  6082. CHECK_SUSPEND(upb_sink_endstr(d->top->sink, arg));
  6083. )
  6084. VMCASE(OP_PUSHTAGDELIM,
  6085. CHECK_SUSPEND(pushtagdelim(d, arg));
  6086. )
  6087. VMCASE(OP_SETBIGGROUPNUM,
  6088. d->top->groupnum = *d->pc++;
  6089. )
  6090. VMCASE(OP_POP,
  6091. UPB_ASSERT(d->top > d->stack);
  6092. decoder_pop(d);
  6093. )
  6094. VMCASE(OP_PUSHLENDELIM,
  6095. uint32_t len;
  6096. CHECK_RETURN(decode_v32(d, &len));
  6097. CHECK_SUSPEND(decoder_push(d, offset(d) + len));
  6098. set_delim_end(d);
  6099. )
  6100. VMCASE(OP_SETDELIM,
  6101. set_delim_end(d);
  6102. )
  6103. VMCASE(OP_CHECKDELIM,
  6104. /* We are guaranteed of this assert because we never allow ourselves to
  6105. * consume bytes beyond data_end, which covers delim_end when non-NULL.
  6106. */
  6107. UPB_ASSERT(!(d->delim_end && d->ptr > d->delim_end));
  6108. if (d->ptr == d->delim_end)
  6109. d->pc += longofs;
  6110. )
  6111. VMCASE(OP_CALL,
  6112. d->callstack[d->call_len++] = d->pc;
  6113. d->pc += longofs;
  6114. )
  6115. VMCASE(OP_RET,
  6116. UPB_ASSERT(d->call_len > 0);
  6117. d->pc = d->callstack[--d->call_len];
  6118. )
  6119. VMCASE(OP_BRANCH,
  6120. d->pc += longofs;
  6121. )
  6122. VMCASE(OP_TAG1,
  6123. uint8_t expected;
  6124. CHECK_SUSPEND(curbufleft(d) > 0);
  6125. expected = (arg >> 8) & 0xff;
  6126. if (*d->ptr == expected) {
  6127. advance(d, 1);
  6128. } else {
  6129. int8_t shortofs;
  6130. badtag:
  6131. shortofs = arg;
  6132. if (shortofs == LABEL_DISPATCH) {
  6133. CHECK_RETURN(dispatch(d));
  6134. } else {
  6135. d->pc += shortofs;
  6136. break; /* Avoid checkpoint(). */
  6137. }
  6138. }
  6139. )
  6140. VMCASE(OP_TAG2,
  6141. uint16_t expected;
  6142. CHECK_SUSPEND(curbufleft(d) > 0);
  6143. expected = (arg >> 8) & 0xffff;
  6144. if (curbufleft(d) >= 2) {
  6145. uint16_t actual;
  6146. memcpy(&actual, d->ptr, 2);
  6147. if (expected == actual) {
  6148. advance(d, 2);
  6149. } else {
  6150. goto badtag;
  6151. }
  6152. } else {
  6153. int32_t result = upb_pbdecoder_checktag_slow(d, expected);
  6154. if (result == DECODE_MISMATCH) goto badtag;
  6155. if (result >= 0) return result;
  6156. }
  6157. )
  6158. VMCASE(OP_TAGN, {
  6159. uint64_t expected;
  6160. int32_t result;
  6161. memcpy(&expected, d->pc, 8);
  6162. d->pc += 2;
  6163. result = upb_pbdecoder_checktag_slow(d, expected);
  6164. if (result == DECODE_MISMATCH) goto badtag;
  6165. if (result >= 0) return result;
  6166. })
  6167. VMCASE(OP_DISPATCH, {
  6168. CHECK_RETURN(dispatch(d));
  6169. })
  6170. VMCASE(OP_HALT, {
  6171. return d->size_param;
  6172. })
  6173. }
  6174. }
  6175. }
  6176. /* BytesHandler handlers ******************************************************/
  6177. void *upb_pbdecoder_startbc(void *closure, const void *pc, size_t size_hint) {
  6178. upb_pbdecoder *d = closure;
  6179. UPB_UNUSED(size_hint);
  6180. d->top->end_ofs = UINT64_MAX;
  6181. d->bufstart_ofs = 0;
  6182. d->call_len = 1;
  6183. d->callstack[0] = &halt;
  6184. d->pc = pc;
  6185. d->skip = 0;
  6186. return d;
  6187. }
  6188. void *upb_pbdecoder_startjit(void *closure, const void *hd, size_t size_hint) {
  6189. upb_pbdecoder *d = closure;
  6190. UPB_UNUSED(hd);
  6191. UPB_UNUSED(size_hint);
  6192. d->top->end_ofs = UINT64_MAX;
  6193. d->bufstart_ofs = 0;
  6194. d->call_len = 0;
  6195. d->skip = 0;
  6196. return d;
  6197. }
  6198. bool upb_pbdecoder_end(void *closure, const void *handler_data) {
  6199. upb_pbdecoder *d = closure;
  6200. const upb_pbdecodermethod *method = handler_data;
  6201. uint64_t end;
  6202. char dummy;
  6203. if (d->residual_end > d->residual) {
  6204. seterr(d, "Unexpected EOF: decoder still has buffered unparsed data");
  6205. return false;
  6206. }
  6207. if (d->skip) {
  6208. seterr(d, "Unexpected EOF inside skipped data");
  6209. return false;
  6210. }
  6211. if (d->top->end_ofs != UINT64_MAX) {
  6212. seterr(d, "Unexpected EOF inside delimited string");
  6213. return false;
  6214. }
  6215. /* The user's end() call indicates that the message ends here. */
  6216. end = offset(d);
  6217. d->top->end_ofs = end;
  6218. #ifdef UPB_USE_JIT_X64
  6219. if (method->is_native_) {
  6220. const mgroup *group = (const mgroup*)method->group;
  6221. if (d->top != d->stack)
  6222. d->stack->end_ofs = 0;
  6223. group->jit_code(closure, method->code_base.ptr, &dummy, 0, NULL);
  6224. } else
  6225. #endif
  6226. {
  6227. const uint32_t *p = d->pc;
  6228. d->stack->end_ofs = end;
  6229. /* Check the previous bytecode, but guard against beginning. */
  6230. if (p != method->code_base.ptr) p--;
  6231. if (getop(*p) == OP_CHECKDELIM) {
  6232. /* Rewind from OP_TAG* to OP_CHECKDELIM. */
  6233. UPB_ASSERT(getop(*d->pc) == OP_TAG1 ||
  6234. getop(*d->pc) == OP_TAG2 ||
  6235. getop(*d->pc) == OP_TAGN ||
  6236. getop(*d->pc) == OP_DISPATCH);
  6237. d->pc = p;
  6238. }
  6239. upb_pbdecoder_decode(closure, handler_data, &dummy, 0, NULL);
  6240. }
  6241. if (d->call_len != 0) {
  6242. seterr(d, "Unexpected EOF inside submessage or group");
  6243. return false;
  6244. }
  6245. return true;
  6246. }
  6247. size_t upb_pbdecoder_decode(void *decoder, const void *group, const char *buf,
  6248. size_t size, const upb_bufhandle *handle) {
  6249. int32_t result = upb_pbdecoder_resume(decoder, NULL, buf, size, handle);
  6250. if (result == DECODE_ENDGROUP) goto_endmsg(decoder);
  6251. CHECK_RETURN(result);
  6252. return run_decoder_vm(decoder, group, handle);
  6253. }
  6254. /* Public API *****************************************************************/
  6255. void upb_pbdecoder_reset(upb_pbdecoder *d) {
  6256. d->top = d->stack;
  6257. d->top->groupnum = 0;
  6258. d->ptr = d->residual;
  6259. d->buf = d->residual;
  6260. d->end = d->residual;
  6261. d->residual_end = d->residual;
  6262. }
  6263. upb_pbdecoder *upb_pbdecoder_create(upb_arena *a, const upb_pbdecodermethod *m,
  6264. upb_sink sink, upb_status *status) {
  6265. const size_t default_max_nesting = 64;
  6266. #ifndef NDEBUG
  6267. size_t size_before = upb_arena_bytesallocated(a);
  6268. #endif
  6269. upb_pbdecoder *d = upb_arena_malloc(a, sizeof(upb_pbdecoder));
  6270. if (!d) return NULL;
  6271. d->method_ = m;
  6272. d->callstack = upb_arena_malloc(a, callstacksize(d, default_max_nesting));
  6273. d->stack = upb_arena_malloc(a, stacksize(d, default_max_nesting));
  6274. if (!d->stack || !d->callstack) {
  6275. return NULL;
  6276. }
  6277. d->arena = a;
  6278. d->limit = d->stack + default_max_nesting - 1;
  6279. d->stack_size = default_max_nesting;
  6280. d->status = status;
  6281. upb_pbdecoder_reset(d);
  6282. upb_bytessink_reset(&d->input_, &m->input_handler_, d);
  6283. if (d->method_->dest_handlers_) {
  6284. if (sink.handlers != d->method_->dest_handlers_)
  6285. return NULL;
  6286. }
  6287. d->top->sink = sink;
  6288. /* If this fails, increase the value in decoder.h. */
  6289. UPB_ASSERT_DEBUGVAR(upb_arena_bytesallocated(a) - size_before <=
  6290. UPB_PB_DECODER_SIZE);
  6291. return d;
  6292. }
  6293. uint64_t upb_pbdecoder_bytesparsed(const upb_pbdecoder *d) {
  6294. return offset(d);
  6295. }
  6296. const upb_pbdecodermethod *upb_pbdecoder_method(const upb_pbdecoder *d) {
  6297. return d->method_;
  6298. }
  6299. upb_bytessink upb_pbdecoder_input(upb_pbdecoder *d) {
  6300. return d->input_;
  6301. }
  6302. size_t upb_pbdecoder_maxnesting(const upb_pbdecoder *d) {
  6303. return d->stack_size;
  6304. }
  6305. bool upb_pbdecoder_setmaxnesting(upb_pbdecoder *d, size_t max) {
  6306. UPB_ASSERT(d->top >= d->stack);
  6307. if (max < (size_t)(d->top - d->stack)) {
  6308. /* Can't set a limit smaller than what we are currently at. */
  6309. return false;
  6310. }
  6311. if (max > d->stack_size) {
  6312. /* Need to reallocate stack and callstack to accommodate. */
  6313. size_t old_size = stacksize(d, d->stack_size);
  6314. size_t new_size = stacksize(d, max);
  6315. void *p = upb_arena_realloc(d->arena, d->stack, old_size, new_size);
  6316. if (!p) {
  6317. return false;
  6318. }
  6319. d->stack = p;
  6320. old_size = callstacksize(d, d->stack_size);
  6321. new_size = callstacksize(d, max);
  6322. p = upb_arena_realloc(d->arena, d->callstack, old_size, new_size);
  6323. if (!p) {
  6324. return false;
  6325. }
  6326. d->callstack = p;
  6327. d->stack_size = max;
  6328. }
  6329. d->limit = d->stack + max - 1;
  6330. return true;
  6331. }
  6332. /*
  6333. ** upb::Encoder
  6334. **
  6335. ** Since we are implementing pure handlers (ie. without any out-of-band access
  6336. ** to pre-computed lengths), we have to buffer all submessages before we can
  6337. ** emit even their first byte.
  6338. **
  6339. ** Not knowing the size of submessages also means we can't write a perfect
  6340. ** zero-copy implementation, even with buffering. Lengths are stored as
  6341. ** varints, which means that we don't know how many bytes to reserve for the
  6342. ** length until we know what the length is.
  6343. **
  6344. ** This leaves us with three main choices:
  6345. **
  6346. ** 1. buffer all submessage data in a temporary buffer, then copy it exactly
  6347. ** once into the output buffer.
  6348. **
  6349. ** 2. attempt to buffer data directly into the output buffer, estimating how
  6350. ** many bytes each length will take. When our guesses are wrong, use
  6351. ** memmove() to grow or shrink the allotted space.
  6352. **
  6353. ** 3. buffer directly into the output buffer, allocating a max length
  6354. ** ahead-of-time for each submessage length. If we overallocated, we waste
  6355. ** space, but no memcpy() or memmove() is required. This approach requires
  6356. ** defining a maximum size for submessages and rejecting submessages that
  6357. ** exceed that size.
  6358. **
  6359. ** (2) and (3) have the potential to have better performance, but they are more
  6360. ** complicated and subtle to implement:
  6361. **
  6362. ** (3) requires making an arbitrary choice of the maximum message size; it
  6363. ** wastes space when submessages are shorter than this and fails
  6364. ** completely when they are longer. This makes it more finicky and
  6365. ** requires configuration based on the input. It also makes it impossible
  6366. ** to perfectly match the output of reference encoders that always use the
  6367. ** optimal amount of space for each length.
  6368. **
  6369. ** (2) requires guessing the the size upfront, and if multiple lengths are
  6370. ** guessed wrong the minimum required number of memmove() operations may
  6371. ** be complicated to compute correctly. Implemented properly, it may have
  6372. ** a useful amortized or average cost, but more investigation is required
  6373. ** to determine this and what the optimal algorithm is to achieve it.
  6374. **
  6375. ** (1) makes you always pay for exactly one copy, but its implementation is
  6376. ** the simplest and its performance is predictable.
  6377. **
  6378. ** So for now, we implement (1) only. If we wish to optimize later, we should
  6379. ** be able to do it without affecting users.
  6380. **
  6381. ** The strategy is to buffer the segments of data that do *not* depend on
  6382. ** unknown lengths in one buffer, and keep a separate buffer of segment pointers
  6383. ** and lengths. When the top-level submessage ends, we can go beginning to end,
  6384. ** alternating the writing of lengths with memcpy() of the rest of the data.
  6385. ** At the top level though, no buffering is required.
  6386. */
  6387. /* The output buffer is divided into segments; a segment is a string of data
  6388. * that is "ready to go" -- it does not need any varint lengths inserted into
  6389. * the middle. The seams between segments are where varints will be inserted
  6390. * once they are known.
  6391. *
  6392. * We also use the concept of a "run", which is a range of encoded bytes that
  6393. * occur at a single submessage level. Every segment contains one or more runs.
  6394. *
  6395. * A segment can span messages. Consider:
  6396. *
  6397. * .--Submessage lengths---------.
  6398. * | | |
  6399. * | V V
  6400. * V | |--------------- | |-----------------
  6401. * Submessages: | |-----------------------------------------------
  6402. * Top-level msg: ------------------------------------------------------------
  6403. *
  6404. * Segments: ----- ------------------- -----------------
  6405. * Runs: *---- *--------------*--- *----------------
  6406. * (* marks the start)
  6407. *
  6408. * Note that the top-level menssage is not in any segment because it does not
  6409. * have any length preceding it.
  6410. *
  6411. * A segment is only interrupted when another length needs to be inserted. So
  6412. * observe how the second segment spans both the inner submessage and part of
  6413. * the next enclosing message. */
  6414. typedef struct {
  6415. uint32_t msglen; /* The length to varint-encode before this segment. */
  6416. uint32_t seglen; /* Length of the segment. */
  6417. } upb_pb_encoder_segment;
  6418. struct upb_pb_encoder {
  6419. upb_arena *arena;
  6420. /* Our input and output. */
  6421. upb_sink input_;
  6422. upb_bytessink output_;
  6423. /* The "subclosure" -- used as the inner closure as part of the bytessink
  6424. * protocol. */
  6425. void *subc;
  6426. /* The output buffer and limit, and our current write position. "buf"
  6427. * initially points to "initbuf", but is dynamically allocated if we need to
  6428. * grow beyond the initial size. */
  6429. char *buf, *ptr, *limit;
  6430. /* The beginning of the current run, or undefined if we are at the top
  6431. * level. */
  6432. char *runbegin;
  6433. /* The list of segments we are accumulating. */
  6434. upb_pb_encoder_segment *segbuf, *segptr, *seglimit;
  6435. /* The stack of enclosing submessages. Each entry in the stack points to the
  6436. * segment where this submessage's length is being accumulated. */
  6437. int *stack, *top, *stacklimit;
  6438. /* Depth of startmsg/endmsg calls. */
  6439. int depth;
  6440. };
  6441. /* low-level buffering ********************************************************/
  6442. /* Low-level functions for interacting with the output buffer. */
  6443. /* TODO(haberman): handle pushback */
  6444. static void putbuf(upb_pb_encoder *e, const char *buf, size_t len) {
  6445. size_t n = upb_bytessink_putbuf(e->output_, e->subc, buf, len, NULL);
  6446. UPB_ASSERT(n == len);
  6447. }
  6448. static upb_pb_encoder_segment *top(upb_pb_encoder *e) {
  6449. return &e->segbuf[*e->top];
  6450. }
  6451. /* Call to ensure that at least "bytes" bytes are available for writing at
  6452. * e->ptr. Returns false if the bytes could not be allocated. */
  6453. static bool reserve(upb_pb_encoder *e, size_t bytes) {
  6454. if ((size_t)(e->limit - e->ptr) < bytes) {
  6455. /* Grow buffer. */
  6456. char *new_buf;
  6457. size_t needed = bytes + (e->ptr - e->buf);
  6458. size_t old_size = e->limit - e->buf;
  6459. size_t new_size = old_size;
  6460. while (new_size < needed) {
  6461. new_size *= 2;
  6462. }
  6463. new_buf = upb_arena_realloc(e->arena, e->buf, old_size, new_size);
  6464. if (new_buf == NULL) {
  6465. return false;
  6466. }
  6467. e->ptr = new_buf + (e->ptr - e->buf);
  6468. e->runbegin = new_buf + (e->runbegin - e->buf);
  6469. e->limit = new_buf + new_size;
  6470. e->buf = new_buf;
  6471. }
  6472. return true;
  6473. }
  6474. /* Call when "bytes" bytes have been writte at e->ptr. The caller *must* have
  6475. * previously called reserve() with at least this many bytes. */
  6476. static void encoder_advance(upb_pb_encoder *e, size_t bytes) {
  6477. UPB_ASSERT((size_t)(e->limit - e->ptr) >= bytes);
  6478. e->ptr += bytes;
  6479. }
  6480. /* Call when all of the bytes for a handler have been written. Flushes the
  6481. * bytes if possible and necessary, returning false if this failed. */
  6482. static bool commit(upb_pb_encoder *e) {
  6483. if (!e->top) {
  6484. /* We aren't inside a delimited region. Flush our accumulated bytes to
  6485. * the output.
  6486. *
  6487. * TODO(haberman): in the future we may want to delay flushing for
  6488. * efficiency reasons. */
  6489. putbuf(e, e->buf, e->ptr - e->buf);
  6490. e->ptr = e->buf;
  6491. }
  6492. return true;
  6493. }
  6494. /* Writes the given bytes to the buffer, handling reserve/advance. */
  6495. static bool encode_bytes(upb_pb_encoder *e, const void *data, size_t len) {
  6496. if (!reserve(e, len)) {
  6497. return false;
  6498. }
  6499. memcpy(e->ptr, data, len);
  6500. encoder_advance(e, len);
  6501. return true;
  6502. }
  6503. /* Finish the current run by adding the run totals to the segment and message
  6504. * length. */
  6505. static void accumulate(upb_pb_encoder *e) {
  6506. size_t run_len;
  6507. UPB_ASSERT(e->ptr >= e->runbegin);
  6508. run_len = e->ptr - e->runbegin;
  6509. e->segptr->seglen += run_len;
  6510. top(e)->msglen += run_len;
  6511. e->runbegin = e->ptr;
  6512. }
  6513. /* Call to indicate the start of delimited region for which the full length is
  6514. * not yet known. All data will be buffered until the length is known.
  6515. * Delimited regions may be nested; their lengths will all be tracked properly. */
  6516. static bool start_delim(upb_pb_encoder *e) {
  6517. if (e->top) {
  6518. /* We are already buffering, advance to the next segment and push it on the
  6519. * stack. */
  6520. accumulate(e);
  6521. if (++e->top == e->stacklimit) {
  6522. /* TODO(haberman): grow stack? */
  6523. return false;
  6524. }
  6525. if (++e->segptr == e->seglimit) {
  6526. /* Grow segment buffer. */
  6527. size_t old_size =
  6528. (e->seglimit - e->segbuf) * sizeof(upb_pb_encoder_segment);
  6529. size_t new_size = old_size * 2;
  6530. upb_pb_encoder_segment *new_buf =
  6531. upb_arena_realloc(e->arena, e->segbuf, old_size, new_size);
  6532. if (new_buf == NULL) {
  6533. return false;
  6534. }
  6535. e->segptr = new_buf + (e->segptr - e->segbuf);
  6536. e->seglimit = new_buf + (new_size / sizeof(upb_pb_encoder_segment));
  6537. e->segbuf = new_buf;
  6538. }
  6539. } else {
  6540. /* We were previously at the top level, start buffering. */
  6541. e->segptr = e->segbuf;
  6542. e->top = e->stack;
  6543. e->runbegin = e->ptr;
  6544. }
  6545. *e->top = e->segptr - e->segbuf;
  6546. e->segptr->seglen = 0;
  6547. e->segptr->msglen = 0;
  6548. return true;
  6549. }
  6550. /* Call to indicate the end of a delimited region. We now know the length of
  6551. * the delimited region. If we are not nested inside any other delimited
  6552. * regions, we can now emit all of the buffered data we accumulated. */
  6553. static bool end_delim(upb_pb_encoder *e) {
  6554. size_t msglen;
  6555. accumulate(e);
  6556. msglen = top(e)->msglen;
  6557. if (e->top == e->stack) {
  6558. /* All lengths are now available, emit all buffered data. */
  6559. char buf[UPB_PB_VARINT_MAX_LEN];
  6560. upb_pb_encoder_segment *s;
  6561. const char *ptr = e->buf;
  6562. for (s = e->segbuf; s <= e->segptr; s++) {
  6563. size_t lenbytes = upb_vencode64(s->msglen, buf);
  6564. putbuf(e, buf, lenbytes);
  6565. putbuf(e, ptr, s->seglen);
  6566. ptr += s->seglen;
  6567. }
  6568. e->ptr = e->buf;
  6569. e->top = NULL;
  6570. } else {
  6571. /* Need to keep buffering; propagate length info into enclosing
  6572. * submessages. */
  6573. --e->top;
  6574. top(e)->msglen += msglen + upb_varint_size(msglen);
  6575. }
  6576. return true;
  6577. }
  6578. /* tag_t **********************************************************************/
  6579. /* A precomputed (pre-encoded) tag and length. */
  6580. typedef struct {
  6581. uint8_t bytes;
  6582. char tag[7];
  6583. } tag_t;
  6584. /* Allocates a new tag for this field, and sets it in these handlerattr. */
  6585. static void new_tag(upb_handlers *h, const upb_fielddef *f, upb_wiretype_t wt,
  6586. upb_handlerattr *attr) {
  6587. uint32_t n = upb_fielddef_number(f);
  6588. tag_t *tag = upb_gmalloc(sizeof(tag_t));
  6589. tag->bytes = upb_vencode64((n << 3) | wt, tag->tag);
  6590. attr->handler_data = tag;
  6591. upb_handlers_addcleanup(h, tag, upb_gfree);
  6592. }
  6593. static bool encode_tag(upb_pb_encoder *e, const tag_t *tag) {
  6594. return encode_bytes(e, tag->tag, tag->bytes);
  6595. }
  6596. /* encoding of wire types *****************************************************/
  6597. static bool encode_fixed64(upb_pb_encoder *e, uint64_t val) {
  6598. /* TODO(haberman): byte-swap for big endian. */
  6599. return encode_bytes(e, &val, sizeof(uint64_t));
  6600. }
  6601. static bool encode_fixed32(upb_pb_encoder *e, uint32_t val) {
  6602. /* TODO(haberman): byte-swap for big endian. */
  6603. return encode_bytes(e, &val, sizeof(uint32_t));
  6604. }
  6605. static bool encode_varint(upb_pb_encoder *e, uint64_t val) {
  6606. if (!reserve(e, UPB_PB_VARINT_MAX_LEN)) {
  6607. return false;
  6608. }
  6609. encoder_advance(e, upb_vencode64(val, e->ptr));
  6610. return true;
  6611. }
  6612. static uint64_t dbl2uint64(double d) {
  6613. uint64_t ret;
  6614. memcpy(&ret, &d, sizeof(uint64_t));
  6615. return ret;
  6616. }
  6617. static uint32_t flt2uint32(float d) {
  6618. uint32_t ret;
  6619. memcpy(&ret, &d, sizeof(uint32_t));
  6620. return ret;
  6621. }
  6622. /* encoding of proto types ****************************************************/
  6623. static bool startmsg(void *c, const void *hd) {
  6624. upb_pb_encoder *e = c;
  6625. UPB_UNUSED(hd);
  6626. if (e->depth++ == 0) {
  6627. upb_bytessink_start(e->output_, 0, &e->subc);
  6628. }
  6629. return true;
  6630. }
  6631. static bool endmsg(void *c, const void *hd, upb_status *status) {
  6632. upb_pb_encoder *e = c;
  6633. UPB_UNUSED(hd);
  6634. UPB_UNUSED(status);
  6635. if (--e->depth == 0) {
  6636. upb_bytessink_end(e->output_);
  6637. }
  6638. return true;
  6639. }
  6640. static void *encode_startdelimfield(void *c, const void *hd) {
  6641. bool ok = encode_tag(c, hd) && commit(c) && start_delim(c);
  6642. return ok ? c : UPB_BREAK;
  6643. }
  6644. static bool encode_unknown(void *c, const void *hd, const char *buf,
  6645. size_t len) {
  6646. UPB_UNUSED(hd);
  6647. return encode_bytes(c, buf, len) && commit(c);
  6648. }
  6649. static bool encode_enddelimfield(void *c, const void *hd) {
  6650. UPB_UNUSED(hd);
  6651. return end_delim(c);
  6652. }
  6653. static void *encode_startgroup(void *c, const void *hd) {
  6654. return (encode_tag(c, hd) && commit(c)) ? c : UPB_BREAK;
  6655. }
  6656. static bool encode_endgroup(void *c, const void *hd) {
  6657. return encode_tag(c, hd) && commit(c);
  6658. }
  6659. static void *encode_startstr(void *c, const void *hd, size_t size_hint) {
  6660. UPB_UNUSED(size_hint);
  6661. return encode_startdelimfield(c, hd);
  6662. }
  6663. static size_t encode_strbuf(void *c, const void *hd, const char *buf,
  6664. size_t len, const upb_bufhandle *h) {
  6665. UPB_UNUSED(hd);
  6666. UPB_UNUSED(h);
  6667. return encode_bytes(c, buf, len) ? len : 0;
  6668. }
  6669. #define T(type, ctype, convert, encode) \
  6670. static bool encode_scalar_##type(void *e, const void *hd, ctype val) { \
  6671. return encode_tag(e, hd) && encode(e, (convert)(val)) && commit(e); \
  6672. } \
  6673. static bool encode_packed_##type(void *e, const void *hd, ctype val) { \
  6674. UPB_UNUSED(hd); \
  6675. return encode(e, (convert)(val)); \
  6676. }
  6677. T(double, double, dbl2uint64, encode_fixed64)
  6678. T(float, float, flt2uint32, encode_fixed32)
  6679. T(int64, int64_t, uint64_t, encode_varint)
  6680. T(int32, int32_t, int64_t, encode_varint)
  6681. T(fixed64, uint64_t, uint64_t, encode_fixed64)
  6682. T(fixed32, uint32_t, uint32_t, encode_fixed32)
  6683. T(bool, bool, bool, encode_varint)
  6684. T(uint32, uint32_t, uint32_t, encode_varint)
  6685. T(uint64, uint64_t, uint64_t, encode_varint)
  6686. T(enum, int32_t, uint32_t, encode_varint)
  6687. T(sfixed32, int32_t, uint32_t, encode_fixed32)
  6688. T(sfixed64, int64_t, uint64_t, encode_fixed64)
  6689. T(sint32, int32_t, upb_zzenc_32, encode_varint)
  6690. T(sint64, int64_t, upb_zzenc_64, encode_varint)
  6691. #undef T
  6692. /* code to build the handlers *************************************************/
  6693. #include <stdio.h>
  6694. static void newhandlers_callback(const void *closure, upb_handlers *h) {
  6695. const upb_msgdef *m;
  6696. upb_msg_field_iter i;
  6697. UPB_UNUSED(closure);
  6698. upb_handlers_setstartmsg(h, startmsg, NULL);
  6699. upb_handlers_setendmsg(h, endmsg, NULL);
  6700. upb_handlers_setunknown(h, encode_unknown, NULL);
  6701. m = upb_handlers_msgdef(h);
  6702. for(upb_msg_field_begin(&i, m);
  6703. !upb_msg_field_done(&i);
  6704. upb_msg_field_next(&i)) {
  6705. const upb_fielddef *f = upb_msg_iter_field(&i);
  6706. bool packed = upb_fielddef_isseq(f) && upb_fielddef_isprimitive(f) &&
  6707. upb_fielddef_packed(f);
  6708. upb_handlerattr attr = UPB_HANDLERATTR_INIT;
  6709. upb_wiretype_t wt =
  6710. packed ? UPB_WIRE_TYPE_DELIMITED
  6711. : upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  6712. /* Pre-encode the tag for this field. */
  6713. new_tag(h, f, wt, &attr);
  6714. if (packed) {
  6715. upb_handlers_setstartseq(h, f, encode_startdelimfield, &attr);
  6716. upb_handlers_setendseq(h, f, encode_enddelimfield, &attr);
  6717. }
  6718. #define T(upper, lower, upbtype) \
  6719. case UPB_DESCRIPTOR_TYPE_##upper: \
  6720. if (packed) { \
  6721. upb_handlers_set##upbtype(h, f, encode_packed_##lower, &attr); \
  6722. } else { \
  6723. upb_handlers_set##upbtype(h, f, encode_scalar_##lower, &attr); \
  6724. } \
  6725. break;
  6726. switch (upb_fielddef_descriptortype(f)) {
  6727. T(DOUBLE, double, double);
  6728. T(FLOAT, float, float);
  6729. T(INT64, int64, int64);
  6730. T(INT32, int32, int32);
  6731. T(FIXED64, fixed64, uint64);
  6732. T(FIXED32, fixed32, uint32);
  6733. T(BOOL, bool, bool);
  6734. T(UINT32, uint32, uint32);
  6735. T(UINT64, uint64, uint64);
  6736. T(ENUM, enum, int32);
  6737. T(SFIXED32, sfixed32, int32);
  6738. T(SFIXED64, sfixed64, int64);
  6739. T(SINT32, sint32, int32);
  6740. T(SINT64, sint64, int64);
  6741. case UPB_DESCRIPTOR_TYPE_STRING:
  6742. case UPB_DESCRIPTOR_TYPE_BYTES:
  6743. upb_handlers_setstartstr(h, f, encode_startstr, &attr);
  6744. upb_handlers_setendstr(h, f, encode_enddelimfield, &attr);
  6745. upb_handlers_setstring(h, f, encode_strbuf, &attr);
  6746. break;
  6747. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  6748. upb_handlers_setstartsubmsg(h, f, encode_startdelimfield, &attr);
  6749. upb_handlers_setendsubmsg(h, f, encode_enddelimfield, &attr);
  6750. break;
  6751. case UPB_DESCRIPTOR_TYPE_GROUP: {
  6752. /* Endgroup takes a different tag (wire_type = END_GROUP). */
  6753. upb_handlerattr attr2 = UPB_HANDLERATTR_INIT;
  6754. new_tag(h, f, UPB_WIRE_TYPE_END_GROUP, &attr2);
  6755. upb_handlers_setstartsubmsg(h, f, encode_startgroup, &attr);
  6756. upb_handlers_setendsubmsg(h, f, encode_endgroup, &attr2);
  6757. break;
  6758. }
  6759. }
  6760. #undef T
  6761. }
  6762. }
  6763. void upb_pb_encoder_reset(upb_pb_encoder *e) {
  6764. e->segptr = NULL;
  6765. e->top = NULL;
  6766. e->depth = 0;
  6767. }
  6768. /* public API *****************************************************************/
  6769. upb_handlercache *upb_pb_encoder_newcache(void) {
  6770. return upb_handlercache_new(newhandlers_callback, NULL);
  6771. }
  6772. upb_pb_encoder *upb_pb_encoder_create(upb_arena *arena, const upb_handlers *h,
  6773. upb_bytessink output) {
  6774. const size_t initial_bufsize = 256;
  6775. const size_t initial_segbufsize = 16;
  6776. /* TODO(haberman): make this configurable. */
  6777. const size_t stack_size = 64;
  6778. #ifndef NDEBUG
  6779. const size_t size_before = upb_arena_bytesallocated(arena);
  6780. #endif
  6781. upb_pb_encoder *e = upb_arena_malloc(arena, sizeof(upb_pb_encoder));
  6782. if (!e) return NULL;
  6783. e->buf = upb_arena_malloc(arena, initial_bufsize);
  6784. e->segbuf = upb_arena_malloc(arena, initial_segbufsize * sizeof(*e->segbuf));
  6785. e->stack = upb_arena_malloc(arena, stack_size * sizeof(*e->stack));
  6786. if (!e->buf || !e->segbuf || !e->stack) {
  6787. return NULL;
  6788. }
  6789. e->limit = e->buf + initial_bufsize;
  6790. e->seglimit = e->segbuf + initial_segbufsize;
  6791. e->stacklimit = e->stack + stack_size;
  6792. upb_pb_encoder_reset(e);
  6793. upb_sink_reset(&e->input_, h, e);
  6794. e->arena = arena;
  6795. e->output_ = output;
  6796. e->subc = output.closure;
  6797. e->ptr = e->buf;
  6798. /* If this fails, increase the value in encoder.h. */
  6799. UPB_ASSERT_DEBUGVAR(upb_arena_bytesallocated(arena) - size_before <=
  6800. UPB_PB_ENCODER_SIZE);
  6801. return e;
  6802. }
  6803. upb_sink upb_pb_encoder_input(upb_pb_encoder *e) { return e->input_; }
  6804. /*
  6805. * upb::pb::TextPrinter
  6806. *
  6807. * OPT: This is not optimized at all. It uses printf() which parses the format
  6808. * string every time, and it allocates memory for every put.
  6809. */
  6810. #include <ctype.h>
  6811. #include <float.h>
  6812. #include <inttypes.h>
  6813. #include <stdarg.h>
  6814. #include <stdio.h>
  6815. #include <string.h>
  6816. struct upb_textprinter {
  6817. upb_sink input_;
  6818. upb_bytessink output_;
  6819. int indent_depth_;
  6820. bool single_line_;
  6821. void *subc;
  6822. };
  6823. #define CHECK(x) if ((x) < 0) goto err;
  6824. static const char *shortname(const char *longname) {
  6825. const char *last = strrchr(longname, '.');
  6826. return last ? last + 1 : longname;
  6827. }
  6828. static int indent(upb_textprinter *p) {
  6829. int i;
  6830. if (!p->single_line_)
  6831. for (i = 0; i < p->indent_depth_; i++)
  6832. upb_bytessink_putbuf(p->output_, p->subc, " ", 2, NULL);
  6833. return 0;
  6834. }
  6835. static int endfield(upb_textprinter *p) {
  6836. const char ch = (p->single_line_ ? ' ' : '\n');
  6837. upb_bytessink_putbuf(p->output_, p->subc, &ch, 1, NULL);
  6838. return 0;
  6839. }
  6840. static int putescaped(upb_textprinter *p, const char *buf, size_t len,
  6841. bool preserve_utf8) {
  6842. /* Based on CEscapeInternal() from Google's protobuf release. */
  6843. char dstbuf[4096], *dst = dstbuf, *dstend = dstbuf + sizeof(dstbuf);
  6844. const char *end = buf + len;
  6845. /* I think hex is prettier and more useful, but proto2 uses octal; should
  6846. * investigate whether it can parse hex also. */
  6847. const bool use_hex = false;
  6848. bool last_hex_escape = false; /* true if last output char was \xNN */
  6849. for (; buf < end; buf++) {
  6850. bool is_hex_escape;
  6851. if (dstend - dst < 4) {
  6852. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  6853. dst = dstbuf;
  6854. }
  6855. is_hex_escape = false;
  6856. switch (*buf) {
  6857. case '\n': *(dst++) = '\\'; *(dst++) = 'n'; break;
  6858. case '\r': *(dst++) = '\\'; *(dst++) = 'r'; break;
  6859. case '\t': *(dst++) = '\\'; *(dst++) = 't'; break;
  6860. case '\"': *(dst++) = '\\'; *(dst++) = '\"'; break;
  6861. case '\'': *(dst++) = '\\'; *(dst++) = '\''; break;
  6862. case '\\': *(dst++) = '\\'; *(dst++) = '\\'; break;
  6863. default:
  6864. /* Note that if we emit \xNN and the buf character after that is a hex
  6865. * digit then that digit must be escaped too to prevent it being
  6866. * interpreted as part of the character code by C. */
  6867. if ((!preserve_utf8 || (uint8_t)*buf < 0x80) &&
  6868. (!isprint(*buf) || (last_hex_escape && isxdigit(*buf)))) {
  6869. sprintf(dst, (use_hex ? "\\x%02x" : "\\%03o"), (uint8_t)*buf);
  6870. is_hex_escape = use_hex;
  6871. dst += 4;
  6872. } else {
  6873. *(dst++) = *buf; break;
  6874. }
  6875. }
  6876. last_hex_escape = is_hex_escape;
  6877. }
  6878. /* Flush remaining data. */
  6879. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  6880. return 0;
  6881. }
  6882. bool putf(upb_textprinter *p, const char *fmt, ...) {
  6883. va_list args;
  6884. va_list args_copy;
  6885. char *str;
  6886. int written;
  6887. int len;
  6888. bool ok;
  6889. va_start(args, fmt);
  6890. /* Run once to get the length of the string. */
  6891. _upb_va_copy(args_copy, args);
  6892. len = _upb_vsnprintf(NULL, 0, fmt, args_copy);
  6893. va_end(args_copy);
  6894. /* + 1 for NULL terminator (vsprintf() requires it even if we don't). */
  6895. str = upb_gmalloc(len + 1);
  6896. if (!str) return false;
  6897. written = vsprintf(str, fmt, args);
  6898. va_end(args);
  6899. UPB_ASSERT(written == len);
  6900. ok = upb_bytessink_putbuf(p->output_, p->subc, str, len, NULL);
  6901. upb_gfree(str);
  6902. return ok;
  6903. }
  6904. /* handlers *******************************************************************/
  6905. static bool textprinter_startmsg(void *c, const void *hd) {
  6906. upb_textprinter *p = c;
  6907. UPB_UNUSED(hd);
  6908. if (p->indent_depth_ == 0) {
  6909. upb_bytessink_start(p->output_, 0, &p->subc);
  6910. }
  6911. return true;
  6912. }
  6913. static bool textprinter_endmsg(void *c, const void *hd, upb_status *s) {
  6914. upb_textprinter *p = c;
  6915. UPB_UNUSED(hd);
  6916. UPB_UNUSED(s);
  6917. if (p->indent_depth_ == 0) {
  6918. upb_bytessink_end(p->output_);
  6919. }
  6920. return true;
  6921. }
  6922. #define TYPE(name, ctype, fmt) \
  6923. static bool textprinter_put ## name(void *closure, const void *handler_data, \
  6924. ctype val) { \
  6925. upb_textprinter *p = closure; \
  6926. const upb_fielddef *f = handler_data; \
  6927. CHECK(indent(p)); \
  6928. putf(p, "%s: " fmt, upb_fielddef_name(f), val); \
  6929. CHECK(endfield(p)); \
  6930. return true; \
  6931. err: \
  6932. return false; \
  6933. }
  6934. static bool textprinter_putbool(void *closure, const void *handler_data,
  6935. bool val) {
  6936. upb_textprinter *p = closure;
  6937. const upb_fielddef *f = handler_data;
  6938. CHECK(indent(p));
  6939. putf(p, "%s: %s", upb_fielddef_name(f), val ? "true" : "false");
  6940. CHECK(endfield(p));
  6941. return true;
  6942. err:
  6943. return false;
  6944. }
  6945. #define STRINGIFY_HELPER(x) #x
  6946. #define STRINGIFY_MACROVAL(x) STRINGIFY_HELPER(x)
  6947. TYPE(int32, int32_t, "%" PRId32)
  6948. TYPE(int64, int64_t, "%" PRId64)
  6949. TYPE(uint32, uint32_t, "%" PRIu32)
  6950. TYPE(uint64, uint64_t, "%" PRIu64)
  6951. TYPE(float, float, "%." STRINGIFY_MACROVAL(FLT_DIG) "g")
  6952. TYPE(double, double, "%." STRINGIFY_MACROVAL(DBL_DIG) "g")
  6953. #undef TYPE
  6954. /* Output a symbolic value from the enum if found, else just print as int32. */
  6955. static bool textprinter_putenum(void *closure, const void *handler_data,
  6956. int32_t val) {
  6957. upb_textprinter *p = closure;
  6958. const upb_fielddef *f = handler_data;
  6959. const upb_enumdef *enum_def = upb_fielddef_enumsubdef(f);
  6960. const char *label = upb_enumdef_iton(enum_def, val);
  6961. if (label) {
  6962. indent(p);
  6963. putf(p, "%s: %s", upb_fielddef_name(f), label);
  6964. endfield(p);
  6965. } else {
  6966. if (!textprinter_putint32(closure, handler_data, val))
  6967. return false;
  6968. }
  6969. return true;
  6970. }
  6971. static void *textprinter_startstr(void *closure, const void *handler_data,
  6972. size_t size_hint) {
  6973. upb_textprinter *p = closure;
  6974. const upb_fielddef *f = handler_data;
  6975. UPB_UNUSED(size_hint);
  6976. indent(p);
  6977. putf(p, "%s: \"", upb_fielddef_name(f));
  6978. return p;
  6979. }
  6980. static bool textprinter_endstr(void *closure, const void *handler_data) {
  6981. upb_textprinter *p = closure;
  6982. UPB_UNUSED(handler_data);
  6983. putf(p, "\"");
  6984. endfield(p);
  6985. return true;
  6986. }
  6987. static size_t textprinter_putstr(void *closure, const void *hd, const char *buf,
  6988. size_t len, const upb_bufhandle *handle) {
  6989. upb_textprinter *p = closure;
  6990. const upb_fielddef *f = hd;
  6991. UPB_UNUSED(handle);
  6992. CHECK(putescaped(p, buf, len, upb_fielddef_type(f) == UPB_TYPE_STRING));
  6993. return len;
  6994. err:
  6995. return 0;
  6996. }
  6997. static void *textprinter_startsubmsg(void *closure, const void *handler_data) {
  6998. upb_textprinter *p = closure;
  6999. const char *name = handler_data;
  7000. CHECK(indent(p));
  7001. putf(p, "%s {%c", name, p->single_line_ ? ' ' : '\n');
  7002. p->indent_depth_++;
  7003. return p;
  7004. err:
  7005. return UPB_BREAK;
  7006. }
  7007. static bool textprinter_endsubmsg(void *closure, const void *handler_data) {
  7008. upb_textprinter *p = closure;
  7009. UPB_UNUSED(handler_data);
  7010. p->indent_depth_--;
  7011. CHECK(indent(p));
  7012. upb_bytessink_putbuf(p->output_, p->subc, "}", 1, NULL);
  7013. CHECK(endfield(p));
  7014. return true;
  7015. err:
  7016. return false;
  7017. }
  7018. static void onmreg(const void *c, upb_handlers *h) {
  7019. const upb_msgdef *m = upb_handlers_msgdef(h);
  7020. upb_msg_field_iter i;
  7021. UPB_UNUSED(c);
  7022. upb_handlers_setstartmsg(h, textprinter_startmsg, NULL);
  7023. upb_handlers_setendmsg(h, textprinter_endmsg, NULL);
  7024. for(upb_msg_field_begin(&i, m);
  7025. !upb_msg_field_done(&i);
  7026. upb_msg_field_next(&i)) {
  7027. upb_fielddef *f = upb_msg_iter_field(&i);
  7028. upb_handlerattr attr = UPB_HANDLERATTR_INIT;
  7029. attr.handler_data = f;
  7030. switch (upb_fielddef_type(f)) {
  7031. case UPB_TYPE_INT32:
  7032. upb_handlers_setint32(h, f, textprinter_putint32, &attr);
  7033. break;
  7034. case UPB_TYPE_INT64:
  7035. upb_handlers_setint64(h, f, textprinter_putint64, &attr);
  7036. break;
  7037. case UPB_TYPE_UINT32:
  7038. upb_handlers_setuint32(h, f, textprinter_putuint32, &attr);
  7039. break;
  7040. case UPB_TYPE_UINT64:
  7041. upb_handlers_setuint64(h, f, textprinter_putuint64, &attr);
  7042. break;
  7043. case UPB_TYPE_FLOAT:
  7044. upb_handlers_setfloat(h, f, textprinter_putfloat, &attr);
  7045. break;
  7046. case UPB_TYPE_DOUBLE:
  7047. upb_handlers_setdouble(h, f, textprinter_putdouble, &attr);
  7048. break;
  7049. case UPB_TYPE_BOOL:
  7050. upb_handlers_setbool(h, f, textprinter_putbool, &attr);
  7051. break;
  7052. case UPB_TYPE_STRING:
  7053. case UPB_TYPE_BYTES:
  7054. upb_handlers_setstartstr(h, f, textprinter_startstr, &attr);
  7055. upb_handlers_setstring(h, f, textprinter_putstr, &attr);
  7056. upb_handlers_setendstr(h, f, textprinter_endstr, &attr);
  7057. break;
  7058. case UPB_TYPE_MESSAGE: {
  7059. const char *name =
  7060. upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_GROUP
  7061. ? shortname(upb_msgdef_fullname(upb_fielddef_msgsubdef(f)))
  7062. : upb_fielddef_name(f);
  7063. attr.handler_data = name;
  7064. upb_handlers_setstartsubmsg(h, f, textprinter_startsubmsg, &attr);
  7065. upb_handlers_setendsubmsg(h, f, textprinter_endsubmsg, &attr);
  7066. break;
  7067. }
  7068. case UPB_TYPE_ENUM:
  7069. upb_handlers_setint32(h, f, textprinter_putenum, &attr);
  7070. break;
  7071. }
  7072. }
  7073. }
  7074. static void textprinter_reset(upb_textprinter *p, bool single_line) {
  7075. p->single_line_ = single_line;
  7076. p->indent_depth_ = 0;
  7077. }
  7078. /* Public API *****************************************************************/
  7079. upb_textprinter *upb_textprinter_create(upb_arena *arena, const upb_handlers *h,
  7080. upb_bytessink output) {
  7081. upb_textprinter *p = upb_arena_malloc(arena, sizeof(upb_textprinter));
  7082. if (!p) return NULL;
  7083. p->output_ = output;
  7084. upb_sink_reset(&p->input_, h, p);
  7085. textprinter_reset(p, false);
  7086. return p;
  7087. }
  7088. upb_handlercache *upb_textprinter_newcache(void) {
  7089. return upb_handlercache_new(&onmreg, NULL);
  7090. }
  7091. upb_sink upb_textprinter_input(upb_textprinter *p) { return p->input_; }
  7092. void upb_textprinter_setsingleline(upb_textprinter *p, bool single_line) {
  7093. p->single_line_ = single_line;
  7094. }
  7095. /* Index is descriptor type. */
  7096. const uint8_t upb_pb_native_wire_types[] = {
  7097. UPB_WIRE_TYPE_END_GROUP, /* ENDGROUP */
  7098. UPB_WIRE_TYPE_64BIT, /* DOUBLE */
  7099. UPB_WIRE_TYPE_32BIT, /* FLOAT */
  7100. UPB_WIRE_TYPE_VARINT, /* INT64 */
  7101. UPB_WIRE_TYPE_VARINT, /* UINT64 */
  7102. UPB_WIRE_TYPE_VARINT, /* INT32 */
  7103. UPB_WIRE_TYPE_64BIT, /* FIXED64 */
  7104. UPB_WIRE_TYPE_32BIT, /* FIXED32 */
  7105. UPB_WIRE_TYPE_VARINT, /* BOOL */
  7106. UPB_WIRE_TYPE_DELIMITED, /* STRING */
  7107. UPB_WIRE_TYPE_START_GROUP, /* GROUP */
  7108. UPB_WIRE_TYPE_DELIMITED, /* MESSAGE */
  7109. UPB_WIRE_TYPE_DELIMITED, /* BYTES */
  7110. UPB_WIRE_TYPE_VARINT, /* UINT32 */
  7111. UPB_WIRE_TYPE_VARINT, /* ENUM */
  7112. UPB_WIRE_TYPE_32BIT, /* SFIXED32 */
  7113. UPB_WIRE_TYPE_64BIT, /* SFIXED64 */
  7114. UPB_WIRE_TYPE_VARINT, /* SINT32 */
  7115. UPB_WIRE_TYPE_VARINT, /* SINT64 */
  7116. };
  7117. /* A basic branch-based decoder, uses 32-bit values to get good performance
  7118. * on 32-bit architectures (but performs well on 64-bits also).
  7119. * This scheme comes from the original Google Protobuf implementation
  7120. * (proto2). */
  7121. upb_decoderet upb_vdecode_max8_branch32(upb_decoderet r) {
  7122. upb_decoderet err = {NULL, 0};
  7123. const char *p = r.p;
  7124. uint32_t low = (uint32_t)r.val;
  7125. uint32_t high = 0;
  7126. uint32_t b;
  7127. b = *(p++); low |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  7128. b = *(p++); low |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  7129. b = *(p++); low |= (b & 0x7fU) << 28;
  7130. high = (b & 0x7fU) >> 4; if (!(b & 0x80)) goto done;
  7131. b = *(p++); high |= (b & 0x7fU) << 3; if (!(b & 0x80)) goto done;
  7132. b = *(p++); high |= (b & 0x7fU) << 10; if (!(b & 0x80)) goto done;
  7133. b = *(p++); high |= (b & 0x7fU) << 17; if (!(b & 0x80)) goto done;
  7134. b = *(p++); high |= (b & 0x7fU) << 24; if (!(b & 0x80)) goto done;
  7135. b = *(p++); high |= (b & 0x7fU) << 31; if (!(b & 0x80)) goto done;
  7136. return err;
  7137. done:
  7138. r.val = ((uint64_t)high << 32) | low;
  7139. r.p = p;
  7140. return r;
  7141. }
  7142. /* Like the previous, but uses 64-bit values. */
  7143. upb_decoderet upb_vdecode_max8_branch64(upb_decoderet r) {
  7144. const char *p = r.p;
  7145. uint64_t val = r.val;
  7146. uint64_t b;
  7147. upb_decoderet err = {NULL, 0};
  7148. b = *(p++); val |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  7149. b = *(p++); val |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  7150. b = *(p++); val |= (b & 0x7fU) << 28; if (!(b & 0x80)) goto done;
  7151. b = *(p++); val |= (b & 0x7fU) << 35; if (!(b & 0x80)) goto done;
  7152. b = *(p++); val |= (b & 0x7fU) << 42; if (!(b & 0x80)) goto done;
  7153. b = *(p++); val |= (b & 0x7fU) << 49; if (!(b & 0x80)) goto done;
  7154. b = *(p++); val |= (b & 0x7fU) << 56; if (!(b & 0x80)) goto done;
  7155. b = *(p++); val |= (b & 0x7fU) << 63; if (!(b & 0x80)) goto done;
  7156. return err;
  7157. done:
  7158. r.val = val;
  7159. r.p = p;
  7160. return r;
  7161. }
  7162. #line 1 "upb/json/parser.rl"
  7163. /*
  7164. ** upb::json::Parser (upb_json_parser)
  7165. **
  7166. ** A parser that uses the Ragel State Machine Compiler to generate
  7167. ** the finite automata.
  7168. **
  7169. ** Ragel only natively handles regular languages, but we can manually
  7170. ** program it a bit to handle context-free languages like JSON, by using
  7171. ** the "fcall" and "fret" constructs.
  7172. **
  7173. ** This parser can handle the basics, but needs several things to be fleshed
  7174. ** out:
  7175. **
  7176. ** - handling of unicode escape sequences (including high surrogate pairs).
  7177. ** - properly check and report errors for unknown fields, stack overflow,
  7178. ** improper array nesting (or lack of nesting).
  7179. ** - handling of base64 sequences with padding characters.
  7180. ** - handling of push-back (non-success returns from sink functions).
  7181. ** - handling of keys/escape-sequences/etc that span input buffers.
  7182. */
  7183. #include <ctype.h>
  7184. #include <errno.h>
  7185. #include <float.h>
  7186. #include <math.h>
  7187. #include <stdint.h>
  7188. #include <stdio.h>
  7189. #include <stdlib.h>
  7190. #include <string.h>
  7191. #include <time.h>
  7192. #define UPB_JSON_MAX_DEPTH 64
  7193. /* Type of value message */
  7194. enum {
  7195. VALUE_NULLVALUE = 0,
  7196. VALUE_NUMBERVALUE = 1,
  7197. VALUE_STRINGVALUE = 2,
  7198. VALUE_BOOLVALUE = 3,
  7199. VALUE_STRUCTVALUE = 4,
  7200. VALUE_LISTVALUE = 5
  7201. };
  7202. /* Forward declare */
  7203. static bool is_top_level(upb_json_parser *p);
  7204. static bool is_wellknown_msg(upb_json_parser *p, upb_wellknowntype_t type);
  7205. static bool is_wellknown_field(upb_json_parser *p, upb_wellknowntype_t type);
  7206. static bool is_number_wrapper_object(upb_json_parser *p);
  7207. static bool does_number_wrapper_start(upb_json_parser *p);
  7208. static bool does_number_wrapper_end(upb_json_parser *p);
  7209. static bool is_string_wrapper_object(upb_json_parser *p);
  7210. static bool does_string_wrapper_start(upb_json_parser *p);
  7211. static bool does_string_wrapper_end(upb_json_parser *p);
  7212. static bool does_fieldmask_start(upb_json_parser *p);
  7213. static bool does_fieldmask_end(upb_json_parser *p);
  7214. static void start_fieldmask_object(upb_json_parser *p);
  7215. static void end_fieldmask_object(upb_json_parser *p);
  7216. static void start_wrapper_object(upb_json_parser *p);
  7217. static void end_wrapper_object(upb_json_parser *p);
  7218. static void start_value_object(upb_json_parser *p, int value_type);
  7219. static void end_value_object(upb_json_parser *p);
  7220. static void start_listvalue_object(upb_json_parser *p);
  7221. static void end_listvalue_object(upb_json_parser *p);
  7222. static void start_structvalue_object(upb_json_parser *p);
  7223. static void end_structvalue_object(upb_json_parser *p);
  7224. static void start_object(upb_json_parser *p);
  7225. static void end_object(upb_json_parser *p);
  7226. static void start_any_object(upb_json_parser *p, const char *ptr);
  7227. static bool end_any_object(upb_json_parser *p, const char *ptr);
  7228. static bool start_subobject(upb_json_parser *p);
  7229. static void end_subobject(upb_json_parser *p);
  7230. static void start_member(upb_json_parser *p);
  7231. static void end_member(upb_json_parser *p);
  7232. static bool end_membername(upb_json_parser *p);
  7233. static void start_any_member(upb_json_parser *p, const char *ptr);
  7234. static void end_any_member(upb_json_parser *p, const char *ptr);
  7235. static bool end_any_membername(upb_json_parser *p);
  7236. size_t parse(void *closure, const void *hd, const char *buf, size_t size,
  7237. const upb_bufhandle *handle);
  7238. static bool end(void *closure, const void *hd);
  7239. static const char eof_ch = 'e';
  7240. /* stringsink */
  7241. typedef struct {
  7242. upb_byteshandler handler;
  7243. upb_bytessink sink;
  7244. char *ptr;
  7245. size_t len, size;
  7246. } upb_stringsink;
  7247. static void *stringsink_start(void *_sink, const void *hd, size_t size_hint) {
  7248. upb_stringsink *sink = _sink;
  7249. sink->len = 0;
  7250. UPB_UNUSED(hd);
  7251. UPB_UNUSED(size_hint);
  7252. return sink;
  7253. }
  7254. static size_t stringsink_string(void *_sink, const void *hd, const char *ptr,
  7255. size_t len, const upb_bufhandle *handle) {
  7256. upb_stringsink *sink = _sink;
  7257. size_t new_size = sink->size;
  7258. UPB_UNUSED(hd);
  7259. UPB_UNUSED(handle);
  7260. while (sink->len + len > new_size) {
  7261. new_size *= 2;
  7262. }
  7263. if (new_size != sink->size) {
  7264. sink->ptr = realloc(sink->ptr, new_size);
  7265. sink->size = new_size;
  7266. }
  7267. memcpy(sink->ptr + sink->len, ptr, len);
  7268. sink->len += len;
  7269. return len;
  7270. }
  7271. void upb_stringsink_init(upb_stringsink *sink) {
  7272. upb_byteshandler_init(&sink->handler);
  7273. upb_byteshandler_setstartstr(&sink->handler, stringsink_start, NULL);
  7274. upb_byteshandler_setstring(&sink->handler, stringsink_string, NULL);
  7275. upb_bytessink_reset(&sink->sink, &sink->handler, sink);
  7276. sink->size = 32;
  7277. sink->ptr = malloc(sink->size);
  7278. sink->len = 0;
  7279. }
  7280. void upb_stringsink_uninit(upb_stringsink *sink) { free(sink->ptr); }
  7281. typedef struct {
  7282. /* For encoding Any value field in binary format. */
  7283. upb_handlercache *encoder_handlercache;
  7284. upb_stringsink stringsink;
  7285. /* For decoding Any value field in json format. */
  7286. upb_json_codecache *parser_codecache;
  7287. upb_sink sink;
  7288. upb_json_parser *parser;
  7289. /* Mark the range of uninterpreted values in json input before type url. */
  7290. const char *before_type_url_start;
  7291. const char *before_type_url_end;
  7292. /* Mark the range of uninterpreted values in json input after type url. */
  7293. const char *after_type_url_start;
  7294. } upb_jsonparser_any_frame;
  7295. typedef struct {
  7296. upb_sink sink;
  7297. /* The current message in which we're parsing, and the field whose value we're
  7298. * expecting next. */
  7299. const upb_msgdef *m;
  7300. const upb_fielddef *f;
  7301. /* The table mapping json name to fielddef for this message. */
  7302. const upb_strtable *name_table;
  7303. /* We are in a repeated-field context. We need this flag to decide whether to
  7304. * handle the array as a normal repeated field or a
  7305. * google.protobuf.ListValue/google.protobuf.Value. */
  7306. bool is_repeated;
  7307. /* We are in a repeated-field context, ready to emit mapentries as
  7308. * submessages. This flag alters the start-of-object (open-brace) behavior to
  7309. * begin a sequence of mapentry messages rather than a single submessage. */
  7310. bool is_map;
  7311. /* We are in a map-entry message context. This flag is set when parsing the
  7312. * value field of a single map entry and indicates to all value-field parsers
  7313. * (subobjects, strings, numbers, and bools) that the map-entry submessage
  7314. * should end as soon as the value is parsed. */
  7315. bool is_mapentry;
  7316. /* If |is_map| or |is_mapentry| is true, |mapfield| refers to the parent
  7317. * message's map field that we're currently parsing. This differs from |f|
  7318. * because |f| is the field in the *current* message (i.e., the map-entry
  7319. * message itself), not the parent's field that leads to this map. */
  7320. const upb_fielddef *mapfield;
  7321. /* We are in an Any message context. This flag is set when parsing the Any
  7322. * message and indicates to all field parsers (subobjects, strings, numbers,
  7323. * and bools) that the parsed field should be serialized as binary data or
  7324. * cached (type url not found yet). */
  7325. bool is_any;
  7326. /* The type of packed message in Any. */
  7327. upb_jsonparser_any_frame *any_frame;
  7328. /* True if the field to be parsed is unknown. */
  7329. bool is_unknown_field;
  7330. } upb_jsonparser_frame;
  7331. static void init_frame(upb_jsonparser_frame* frame) {
  7332. frame->m = NULL;
  7333. frame->f = NULL;
  7334. frame->name_table = NULL;
  7335. frame->is_repeated = false;
  7336. frame->is_map = false;
  7337. frame->is_mapentry = false;
  7338. frame->mapfield = NULL;
  7339. frame->is_any = false;
  7340. frame->any_frame = NULL;
  7341. frame->is_unknown_field = false;
  7342. }
  7343. struct upb_json_parser {
  7344. upb_arena *arena;
  7345. const upb_json_parsermethod *method;
  7346. upb_bytessink input_;
  7347. /* Stack to track the JSON scopes we are in. */
  7348. upb_jsonparser_frame stack[UPB_JSON_MAX_DEPTH];
  7349. upb_jsonparser_frame *top;
  7350. upb_jsonparser_frame *limit;
  7351. upb_status *status;
  7352. /* Ragel's internal parsing stack for the parsing state machine. */
  7353. int current_state;
  7354. int parser_stack[UPB_JSON_MAX_DEPTH];
  7355. int parser_top;
  7356. /* The handle for the current buffer. */
  7357. const upb_bufhandle *handle;
  7358. /* Accumulate buffer. See details in parser.rl. */
  7359. const char *accumulated;
  7360. size_t accumulated_len;
  7361. char *accumulate_buf;
  7362. size_t accumulate_buf_size;
  7363. /* Multi-part text data. See details in parser.rl. */
  7364. int multipart_state;
  7365. upb_selector_t string_selector;
  7366. /* Input capture. See details in parser.rl. */
  7367. const char *capture;
  7368. /* Intermediate result of parsing a unicode escape sequence. */
  7369. uint32_t digit;
  7370. /* For resolve type url in Any. */
  7371. const upb_symtab *symtab;
  7372. /* Whether to proceed if unknown field is met. */
  7373. bool ignore_json_unknown;
  7374. /* Cache for parsing timestamp due to base and zone are handled in different
  7375. * handlers. */
  7376. struct tm tm;
  7377. };
  7378. static upb_jsonparser_frame* start_jsonparser_frame(upb_json_parser *p) {
  7379. upb_jsonparser_frame *inner;
  7380. inner = p->top + 1;
  7381. init_frame(inner);
  7382. return inner;
  7383. }
  7384. struct upb_json_codecache {
  7385. upb_arena *arena;
  7386. upb_inttable methods; /* upb_msgdef* -> upb_json_parsermethod* */
  7387. };
  7388. struct upb_json_parsermethod {
  7389. const upb_json_codecache *cache;
  7390. upb_byteshandler input_handler_;
  7391. /* Maps json_name -> fielddef */
  7392. upb_strtable name_table;
  7393. };
  7394. #define PARSER_CHECK_RETURN(x) if (!(x)) return false
  7395. static upb_jsonparser_any_frame *json_parser_any_frame_new(
  7396. upb_json_parser *p) {
  7397. upb_jsonparser_any_frame *frame;
  7398. frame = upb_arena_malloc(p->arena, sizeof(upb_jsonparser_any_frame));
  7399. frame->encoder_handlercache = upb_pb_encoder_newcache();
  7400. frame->parser_codecache = upb_json_codecache_new();
  7401. frame->parser = NULL;
  7402. frame->before_type_url_start = NULL;
  7403. frame->before_type_url_end = NULL;
  7404. frame->after_type_url_start = NULL;
  7405. upb_stringsink_init(&frame->stringsink);
  7406. return frame;
  7407. }
  7408. static void json_parser_any_frame_set_payload_type(
  7409. upb_json_parser *p,
  7410. upb_jsonparser_any_frame *frame,
  7411. const upb_msgdef *payload_type) {
  7412. const upb_handlers *h;
  7413. const upb_json_parsermethod *parser_method;
  7414. upb_pb_encoder *encoder;
  7415. /* Initialize encoder. */
  7416. h = upb_handlercache_get(frame->encoder_handlercache, payload_type);
  7417. encoder = upb_pb_encoder_create(p->arena, h, frame->stringsink.sink);
  7418. /* Initialize parser. */
  7419. parser_method = upb_json_codecache_get(frame->parser_codecache, payload_type);
  7420. upb_sink_reset(&frame->sink, h, encoder);
  7421. frame->parser =
  7422. upb_json_parser_create(p->arena, parser_method, p->symtab, frame->sink,
  7423. p->status, p->ignore_json_unknown);
  7424. }
  7425. static void json_parser_any_frame_free(upb_jsonparser_any_frame *frame) {
  7426. upb_handlercache_free(frame->encoder_handlercache);
  7427. upb_json_codecache_free(frame->parser_codecache);
  7428. upb_stringsink_uninit(&frame->stringsink);
  7429. }
  7430. static bool json_parser_any_frame_has_type_url(
  7431. upb_jsonparser_any_frame *frame) {
  7432. return frame->parser != NULL;
  7433. }
  7434. static bool json_parser_any_frame_has_value_before_type_url(
  7435. upb_jsonparser_any_frame *frame) {
  7436. return frame->before_type_url_start != frame->before_type_url_end;
  7437. }
  7438. static bool json_parser_any_frame_has_value_after_type_url(
  7439. upb_jsonparser_any_frame *frame) {
  7440. return frame->after_type_url_start != NULL;
  7441. }
  7442. static bool json_parser_any_frame_has_value(
  7443. upb_jsonparser_any_frame *frame) {
  7444. return json_parser_any_frame_has_value_before_type_url(frame) ||
  7445. json_parser_any_frame_has_value_after_type_url(frame);
  7446. }
  7447. static void json_parser_any_frame_set_before_type_url_end(
  7448. upb_jsonparser_any_frame *frame,
  7449. const char *ptr) {
  7450. if (frame->parser == NULL) {
  7451. frame->before_type_url_end = ptr;
  7452. }
  7453. }
  7454. static void json_parser_any_frame_set_after_type_url_start_once(
  7455. upb_jsonparser_any_frame *frame,
  7456. const char *ptr) {
  7457. if (json_parser_any_frame_has_type_url(frame) &&
  7458. frame->after_type_url_start == NULL) {
  7459. frame->after_type_url_start = ptr;
  7460. }
  7461. }
  7462. /* Used to signal that a capture has been suspended. */
  7463. static char suspend_capture;
  7464. static upb_selector_t getsel_for_handlertype(upb_json_parser *p,
  7465. upb_handlertype_t type) {
  7466. upb_selector_t sel;
  7467. bool ok = upb_handlers_getselector(p->top->f, type, &sel);
  7468. UPB_ASSERT(ok);
  7469. return sel;
  7470. }
  7471. static upb_selector_t parser_getsel(upb_json_parser *p) {
  7472. return getsel_for_handlertype(
  7473. p, upb_handlers_getprimitivehandlertype(p->top->f));
  7474. }
  7475. static bool check_stack(upb_json_parser *p) {
  7476. if ((p->top + 1) == p->limit) {
  7477. upb_status_seterrmsg(p->status, "Nesting too deep");
  7478. return false;
  7479. }
  7480. return true;
  7481. }
  7482. static void set_name_table(upb_json_parser *p, upb_jsonparser_frame *frame) {
  7483. upb_value v;
  7484. const upb_json_codecache *cache = p->method->cache;
  7485. bool ok;
  7486. const upb_json_parsermethod *method;
  7487. ok = upb_inttable_lookupptr(&cache->methods, frame->m, &v);
  7488. UPB_ASSERT(ok);
  7489. method = upb_value_getconstptr(v);
  7490. frame->name_table = &method->name_table;
  7491. }
  7492. /* There are GCC/Clang built-ins for overflow checking which we could start
  7493. * using if there was any performance benefit to it. */
  7494. static bool checked_add(size_t a, size_t b, size_t *c) {
  7495. if (SIZE_MAX - a < b) return false;
  7496. *c = a + b;
  7497. return true;
  7498. }
  7499. static size_t saturating_multiply(size_t a, size_t b) {
  7500. /* size_t is unsigned, so this is defined behavior even on overflow. */
  7501. size_t ret = a * b;
  7502. if (b != 0 && ret / b != a) {
  7503. ret = SIZE_MAX;
  7504. }
  7505. return ret;
  7506. }
  7507. /* Base64 decoding ************************************************************/
  7508. /* TODO(haberman): make this streaming. */
  7509. static const signed char b64table[] = {
  7510. -1, -1, -1, -1, -1, -1, -1, -1,
  7511. -1, -1, -1, -1, -1, -1, -1, -1,
  7512. -1, -1, -1, -1, -1, -1, -1, -1,
  7513. -1, -1, -1, -1, -1, -1, -1, -1,
  7514. -1, -1, -1, -1, -1, -1, -1, -1,
  7515. -1, -1, -1, 62/*+*/, -1, -1, -1, 63/*/ */,
  7516. 52/*0*/, 53/*1*/, 54/*2*/, 55/*3*/, 56/*4*/, 57/*5*/, 58/*6*/, 59/*7*/,
  7517. 60/*8*/, 61/*9*/, -1, -1, -1, -1, -1, -1,
  7518. -1, 0/*A*/, 1/*B*/, 2/*C*/, 3/*D*/, 4/*E*/, 5/*F*/, 6/*G*/,
  7519. 07/*H*/, 8/*I*/, 9/*J*/, 10/*K*/, 11/*L*/, 12/*M*/, 13/*N*/, 14/*O*/,
  7520. 15/*P*/, 16/*Q*/, 17/*R*/, 18/*S*/, 19/*T*/, 20/*U*/, 21/*V*/, 22/*W*/,
  7521. 23/*X*/, 24/*Y*/, 25/*Z*/, -1, -1, -1, -1, -1,
  7522. -1, 26/*a*/, 27/*b*/, 28/*c*/, 29/*d*/, 30/*e*/, 31/*f*/, 32/*g*/,
  7523. 33/*h*/, 34/*i*/, 35/*j*/, 36/*k*/, 37/*l*/, 38/*m*/, 39/*n*/, 40/*o*/,
  7524. 41/*p*/, 42/*q*/, 43/*r*/, 44/*s*/, 45/*t*/, 46/*u*/, 47/*v*/, 48/*w*/,
  7525. 49/*x*/, 50/*y*/, 51/*z*/, -1, -1, -1, -1, -1,
  7526. -1, -1, -1, -1, -1, -1, -1, -1,
  7527. -1, -1, -1, -1, -1, -1, -1, -1,
  7528. -1, -1, -1, -1, -1, -1, -1, -1,
  7529. -1, -1, -1, -1, -1, -1, -1, -1,
  7530. -1, -1, -1, -1, -1, -1, -1, -1,
  7531. -1, -1, -1, -1, -1, -1, -1, -1,
  7532. -1, -1, -1, -1, -1, -1, -1, -1,
  7533. -1, -1, -1, -1, -1, -1, -1, -1,
  7534. -1, -1, -1, -1, -1, -1, -1, -1,
  7535. -1, -1, -1, -1, -1, -1, -1, -1,
  7536. -1, -1, -1, -1, -1, -1, -1, -1,
  7537. -1, -1, -1, -1, -1, -1, -1, -1,
  7538. -1, -1, -1, -1, -1, -1, -1, -1,
  7539. -1, -1, -1, -1, -1, -1, -1, -1,
  7540. -1, -1, -1, -1, -1, -1, -1, -1,
  7541. -1, -1, -1, -1, -1, -1, -1, -1
  7542. };
  7543. /* Returns the table value sign-extended to 32 bits. Knowing that the upper
  7544. * bits will be 1 for unrecognized characters makes it easier to check for
  7545. * this error condition later (see below). */
  7546. int32_t b64lookup(unsigned char ch) { return b64table[ch]; }
  7547. /* Returns true if the given character is not a valid base64 character or
  7548. * padding. */
  7549. bool nonbase64(unsigned char ch) { return b64lookup(ch) == -1 && ch != '='; }
  7550. static bool base64_push(upb_json_parser *p, upb_selector_t sel, const char *ptr,
  7551. size_t len) {
  7552. const char *limit = ptr + len;
  7553. for (; ptr < limit; ptr += 4) {
  7554. uint32_t val;
  7555. char output[3];
  7556. if (limit - ptr < 4) {
  7557. upb_status_seterrf(p->status,
  7558. "Base64 input for bytes field not a multiple of 4: %s",
  7559. upb_fielddef_name(p->top->f));
  7560. return false;
  7561. }
  7562. val = b64lookup(ptr[0]) << 18 |
  7563. b64lookup(ptr[1]) << 12 |
  7564. b64lookup(ptr[2]) << 6 |
  7565. b64lookup(ptr[3]);
  7566. /* Test the upper bit; returns true if any of the characters returned -1. */
  7567. if (val & 0x80000000) {
  7568. goto otherchar;
  7569. }
  7570. output[0] = val >> 16;
  7571. output[1] = (val >> 8) & 0xff;
  7572. output[2] = val & 0xff;
  7573. upb_sink_putstring(p->top->sink, sel, output, 3, NULL);
  7574. }
  7575. return true;
  7576. otherchar:
  7577. if (nonbase64(ptr[0]) || nonbase64(ptr[1]) || nonbase64(ptr[2]) ||
  7578. nonbase64(ptr[3]) ) {
  7579. upb_status_seterrf(p->status,
  7580. "Non-base64 characters in bytes field: %s",
  7581. upb_fielddef_name(p->top->f));
  7582. return false;
  7583. } if (ptr[2] == '=') {
  7584. uint32_t val;
  7585. char output;
  7586. /* Last group contains only two input bytes, one output byte. */
  7587. if (ptr[0] == '=' || ptr[1] == '=' || ptr[3] != '=') {
  7588. goto badpadding;
  7589. }
  7590. val = b64lookup(ptr[0]) << 18 |
  7591. b64lookup(ptr[1]) << 12;
  7592. UPB_ASSERT(!(val & 0x80000000));
  7593. output = val >> 16;
  7594. upb_sink_putstring(p->top->sink, sel, &output, 1, NULL);
  7595. return true;
  7596. } else {
  7597. uint32_t val;
  7598. char output[2];
  7599. /* Last group contains only three input bytes, two output bytes. */
  7600. if (ptr[0] == '=' || ptr[1] == '=' || ptr[2] == '=') {
  7601. goto badpadding;
  7602. }
  7603. val = b64lookup(ptr[0]) << 18 |
  7604. b64lookup(ptr[1]) << 12 |
  7605. b64lookup(ptr[2]) << 6;
  7606. output[0] = val >> 16;
  7607. output[1] = (val >> 8) & 0xff;
  7608. upb_sink_putstring(p->top->sink, sel, output, 2, NULL);
  7609. return true;
  7610. }
  7611. badpadding:
  7612. upb_status_seterrf(p->status,
  7613. "Incorrect base64 padding for field: %s (%.*s)",
  7614. upb_fielddef_name(p->top->f),
  7615. 4, ptr);
  7616. return false;
  7617. }
  7618. /* Accumulate buffer **********************************************************/
  7619. /* Functionality for accumulating a buffer.
  7620. *
  7621. * Some parts of the parser need an entire value as a contiguous string. For
  7622. * example, to look up a member name in a hash table, or to turn a string into
  7623. * a number, the relevant library routines need the input string to be in
  7624. * contiguous memory, even if the value spanned two or more buffers in the
  7625. * input. These routines handle that.
  7626. *
  7627. * In the common case we can just point to the input buffer to get this
  7628. * contiguous string and avoid any actual copy. So we optimistically begin
  7629. * this way. But there are a few cases where we must instead copy into a
  7630. * separate buffer:
  7631. *
  7632. * 1. The string was not contiguous in the input (it spanned buffers).
  7633. *
  7634. * 2. The string included escape sequences that need to be interpreted to get
  7635. * the true value in a contiguous buffer. */
  7636. static void assert_accumulate_empty(upb_json_parser *p) {
  7637. UPB_ASSERT(p->accumulated == NULL);
  7638. UPB_ASSERT(p->accumulated_len == 0);
  7639. }
  7640. static void accumulate_clear(upb_json_parser *p) {
  7641. p->accumulated = NULL;
  7642. p->accumulated_len = 0;
  7643. }
  7644. /* Used internally by accumulate_append(). */
  7645. static bool accumulate_realloc(upb_json_parser *p, size_t need) {
  7646. void *mem;
  7647. size_t old_size = p->accumulate_buf_size;
  7648. size_t new_size = UPB_MAX(old_size, 128);
  7649. while (new_size < need) {
  7650. new_size = saturating_multiply(new_size, 2);
  7651. }
  7652. mem = upb_arena_realloc(p->arena, p->accumulate_buf, old_size, new_size);
  7653. if (!mem) {
  7654. upb_status_seterrmsg(p->status, "Out of memory allocating buffer.");
  7655. return false;
  7656. }
  7657. p->accumulate_buf = mem;
  7658. p->accumulate_buf_size = new_size;
  7659. return true;
  7660. }
  7661. /* Logically appends the given data to the append buffer.
  7662. * If "can_alias" is true, we will try to avoid actually copying, but the buffer
  7663. * must be valid until the next accumulate_append() call (if any). */
  7664. static bool accumulate_append(upb_json_parser *p, const char *buf, size_t len,
  7665. bool can_alias) {
  7666. size_t need;
  7667. if (!p->accumulated && can_alias) {
  7668. p->accumulated = buf;
  7669. p->accumulated_len = len;
  7670. return true;
  7671. }
  7672. if (!checked_add(p->accumulated_len, len, &need)) {
  7673. upb_status_seterrmsg(p->status, "Integer overflow.");
  7674. return false;
  7675. }
  7676. if (need > p->accumulate_buf_size && !accumulate_realloc(p, need)) {
  7677. return false;
  7678. }
  7679. if (p->accumulated != p->accumulate_buf) {
  7680. memcpy(p->accumulate_buf, p->accumulated, p->accumulated_len);
  7681. p->accumulated = p->accumulate_buf;
  7682. }
  7683. memcpy(p->accumulate_buf + p->accumulated_len, buf, len);
  7684. p->accumulated_len += len;
  7685. return true;
  7686. }
  7687. /* Returns a pointer to the data accumulated since the last accumulate_clear()
  7688. * call, and writes the length to *len. This with point either to the input
  7689. * buffer or a temporary accumulate buffer. */
  7690. static const char *accumulate_getptr(upb_json_parser *p, size_t *len) {
  7691. UPB_ASSERT(p->accumulated);
  7692. *len = p->accumulated_len;
  7693. return p->accumulated;
  7694. }
  7695. /* Mult-part text data ********************************************************/
  7696. /* When we have text data in the input, it can often come in multiple segments.
  7697. * For example, there may be some raw string data followed by an escape
  7698. * sequence. The two segments are processed with different logic. Also buffer
  7699. * seams in the input can cause multiple segments.
  7700. *
  7701. * As we see segments, there are two main cases for how we want to process them:
  7702. *
  7703. * 1. we want to push the captured input directly to string handlers.
  7704. *
  7705. * 2. we need to accumulate all the parts into a contiguous buffer for further
  7706. * processing (field name lookup, string->number conversion, etc). */
  7707. /* This is the set of states for p->multipart_state. */
  7708. enum {
  7709. /* We are not currently processing multipart data. */
  7710. MULTIPART_INACTIVE = 0,
  7711. /* We are processing multipart data by accumulating it into a contiguous
  7712. * buffer. */
  7713. MULTIPART_ACCUMULATE = 1,
  7714. /* We are processing multipart data by pushing each part directly to the
  7715. * current string handlers. */
  7716. MULTIPART_PUSHEAGERLY = 2
  7717. };
  7718. /* Start a multi-part text value where we accumulate the data for processing at
  7719. * the end. */
  7720. static void multipart_startaccum(upb_json_parser *p) {
  7721. assert_accumulate_empty(p);
  7722. UPB_ASSERT(p->multipart_state == MULTIPART_INACTIVE);
  7723. p->multipart_state = MULTIPART_ACCUMULATE;
  7724. }
  7725. /* Start a multi-part text value where we immediately push text data to a string
  7726. * value with the given selector. */
  7727. static void multipart_start(upb_json_parser *p, upb_selector_t sel) {
  7728. assert_accumulate_empty(p);
  7729. UPB_ASSERT(p->multipart_state == MULTIPART_INACTIVE);
  7730. p->multipart_state = MULTIPART_PUSHEAGERLY;
  7731. p->string_selector = sel;
  7732. }
  7733. static bool multipart_text(upb_json_parser *p, const char *buf, size_t len,
  7734. bool can_alias) {
  7735. switch (p->multipart_state) {
  7736. case MULTIPART_INACTIVE:
  7737. upb_status_seterrmsg(
  7738. p->status, "Internal error: unexpected state MULTIPART_INACTIVE");
  7739. return false;
  7740. case MULTIPART_ACCUMULATE:
  7741. if (!accumulate_append(p, buf, len, can_alias)) {
  7742. return false;
  7743. }
  7744. break;
  7745. case MULTIPART_PUSHEAGERLY: {
  7746. const upb_bufhandle *handle = can_alias ? p->handle : NULL;
  7747. upb_sink_putstring(p->top->sink, p->string_selector, buf, len, handle);
  7748. break;
  7749. }
  7750. }
  7751. return true;
  7752. }
  7753. /* Note: this invalidates the accumulate buffer! Call only after reading its
  7754. * contents. */
  7755. static void multipart_end(upb_json_parser *p) {
  7756. UPB_ASSERT(p->multipart_state != MULTIPART_INACTIVE);
  7757. p->multipart_state = MULTIPART_INACTIVE;
  7758. accumulate_clear(p);
  7759. }
  7760. /* Input capture **************************************************************/
  7761. /* Functionality for capturing a region of the input as text. Gracefully
  7762. * handles the case where a buffer seam occurs in the middle of the captured
  7763. * region. */
  7764. static void capture_begin(upb_json_parser *p, const char *ptr) {
  7765. UPB_ASSERT(p->multipart_state != MULTIPART_INACTIVE);
  7766. UPB_ASSERT(p->capture == NULL);
  7767. p->capture = ptr;
  7768. }
  7769. static bool capture_end(upb_json_parser *p, const char *ptr) {
  7770. UPB_ASSERT(p->capture);
  7771. if (multipart_text(p, p->capture, ptr - p->capture, true)) {
  7772. p->capture = NULL;
  7773. return true;
  7774. } else {
  7775. return false;
  7776. }
  7777. }
  7778. /* This is called at the end of each input buffer (ie. when we have hit a
  7779. * buffer seam). If we are in the middle of capturing the input, this
  7780. * processes the unprocessed capture region. */
  7781. static void capture_suspend(upb_json_parser *p, const char **ptr) {
  7782. if (!p->capture) return;
  7783. if (multipart_text(p, p->capture, *ptr - p->capture, false)) {
  7784. /* We use this as a signal that we were in the middle of capturing, and
  7785. * that capturing should resume at the beginning of the next buffer.
  7786. *
  7787. * We can't use *ptr here, because we have no guarantee that this pointer
  7788. * will be valid when we resume (if the underlying memory is freed, then
  7789. * using the pointer at all, even to compare to NULL, is likely undefined
  7790. * behavior). */
  7791. p->capture = &suspend_capture;
  7792. } else {
  7793. /* Need to back up the pointer to the beginning of the capture, since
  7794. * we were not able to actually preserve it. */
  7795. *ptr = p->capture;
  7796. }
  7797. }
  7798. static void capture_resume(upb_json_parser *p, const char *ptr) {
  7799. if (p->capture) {
  7800. UPB_ASSERT(p->capture == &suspend_capture);
  7801. p->capture = ptr;
  7802. }
  7803. }
  7804. /* Callbacks from the parser **************************************************/
  7805. /* These are the functions called directly from the parser itself.
  7806. * We define these in the same order as their declarations in the parser. */
  7807. static char escape_char(char in) {
  7808. switch (in) {
  7809. case 'r': return '\r';
  7810. case 't': return '\t';
  7811. case 'n': return '\n';
  7812. case 'f': return '\f';
  7813. case 'b': return '\b';
  7814. case '/': return '/';
  7815. case '"': return '"';
  7816. case '\\': return '\\';
  7817. default:
  7818. UPB_ASSERT(0);
  7819. return 'x';
  7820. }
  7821. }
  7822. static bool escape(upb_json_parser *p, const char *ptr) {
  7823. char ch = escape_char(*ptr);
  7824. return multipart_text(p, &ch, 1, false);
  7825. }
  7826. static void start_hex(upb_json_parser *p) {
  7827. p->digit = 0;
  7828. }
  7829. static void hexdigit(upb_json_parser *p, const char *ptr) {
  7830. char ch = *ptr;
  7831. p->digit <<= 4;
  7832. if (ch >= '0' && ch <= '9') {
  7833. p->digit += (ch - '0');
  7834. } else if (ch >= 'a' && ch <= 'f') {
  7835. p->digit += ((ch - 'a') + 10);
  7836. } else {
  7837. UPB_ASSERT(ch >= 'A' && ch <= 'F');
  7838. p->digit += ((ch - 'A') + 10);
  7839. }
  7840. }
  7841. static bool end_hex(upb_json_parser *p) {
  7842. uint32_t codepoint = p->digit;
  7843. /* emit the codepoint as UTF-8. */
  7844. char utf8[3]; /* support \u0000 -- \uFFFF -- need only three bytes. */
  7845. int length = 0;
  7846. if (codepoint <= 0x7F) {
  7847. utf8[0] = codepoint;
  7848. length = 1;
  7849. } else if (codepoint <= 0x07FF) {
  7850. utf8[1] = (codepoint & 0x3F) | 0x80;
  7851. codepoint >>= 6;
  7852. utf8[0] = (codepoint & 0x1F) | 0xC0;
  7853. length = 2;
  7854. } else /* codepoint <= 0xFFFF */ {
  7855. utf8[2] = (codepoint & 0x3F) | 0x80;
  7856. codepoint >>= 6;
  7857. utf8[1] = (codepoint & 0x3F) | 0x80;
  7858. codepoint >>= 6;
  7859. utf8[0] = (codepoint & 0x0F) | 0xE0;
  7860. length = 3;
  7861. }
  7862. /* TODO(haberman): Handle high surrogates: if codepoint is a high surrogate
  7863. * we have to wait for the next escape to get the full code point). */
  7864. return multipart_text(p, utf8, length, false);
  7865. }
  7866. static void start_text(upb_json_parser *p, const char *ptr) {
  7867. capture_begin(p, ptr);
  7868. }
  7869. static bool end_text(upb_json_parser *p, const char *ptr) {
  7870. return capture_end(p, ptr);
  7871. }
  7872. static bool start_number(upb_json_parser *p, const char *ptr) {
  7873. if (is_top_level(p)) {
  7874. if (is_number_wrapper_object(p)) {
  7875. start_wrapper_object(p);
  7876. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  7877. start_value_object(p, VALUE_NUMBERVALUE);
  7878. } else {
  7879. return false;
  7880. }
  7881. } else if (does_number_wrapper_start(p)) {
  7882. if (!start_subobject(p)) {
  7883. return false;
  7884. }
  7885. start_wrapper_object(p);
  7886. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  7887. if (!start_subobject(p)) {
  7888. return false;
  7889. }
  7890. start_value_object(p, VALUE_NUMBERVALUE);
  7891. }
  7892. multipart_startaccum(p);
  7893. capture_begin(p, ptr);
  7894. return true;
  7895. }
  7896. static bool parse_number(upb_json_parser *p, bool is_quoted);
  7897. static bool end_number_nontop(upb_json_parser *p, const char *ptr) {
  7898. if (!capture_end(p, ptr)) {
  7899. return false;
  7900. }
  7901. if (p->top->f == NULL) {
  7902. multipart_end(p);
  7903. return true;
  7904. }
  7905. return parse_number(p, false);
  7906. }
  7907. static bool end_number(upb_json_parser *p, const char *ptr) {
  7908. if (!end_number_nontop(p, ptr)) {
  7909. return false;
  7910. }
  7911. if (does_number_wrapper_end(p)) {
  7912. end_wrapper_object(p);
  7913. if (!is_top_level(p)) {
  7914. end_subobject(p);
  7915. }
  7916. return true;
  7917. }
  7918. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  7919. end_value_object(p);
  7920. if (!is_top_level(p)) {
  7921. end_subobject(p);
  7922. }
  7923. return true;
  7924. }
  7925. return true;
  7926. }
  7927. /* |buf| is NULL-terminated. |buf| itself will never include quotes;
  7928. * |is_quoted| tells us whether this text originally appeared inside quotes. */
  7929. static bool parse_number_from_buffer(upb_json_parser *p, const char *buf,
  7930. bool is_quoted) {
  7931. size_t len = strlen(buf);
  7932. const char *bufend = buf + len;
  7933. char *end;
  7934. upb_fieldtype_t type = upb_fielddef_type(p->top->f);
  7935. double val;
  7936. double dummy;
  7937. double inf = UPB_INFINITY;
  7938. errno = 0;
  7939. if (len == 0 || buf[0] == ' ') {
  7940. return false;
  7941. }
  7942. /* For integer types, first try parsing with integer-specific routines.
  7943. * If these succeed, they will be more accurate for int64/uint64 than
  7944. * strtod().
  7945. */
  7946. switch (type) {
  7947. case UPB_TYPE_ENUM:
  7948. case UPB_TYPE_INT32: {
  7949. long val = strtol(buf, &end, 0);
  7950. if (errno == ERANGE || end != bufend) {
  7951. break;
  7952. } else if (val > INT32_MAX || val < INT32_MIN) {
  7953. return false;
  7954. } else {
  7955. upb_sink_putint32(p->top->sink, parser_getsel(p), val);
  7956. return true;
  7957. }
  7958. }
  7959. case UPB_TYPE_UINT32: {
  7960. unsigned long val = strtoul(buf, &end, 0);
  7961. if (end != bufend) {
  7962. break;
  7963. } else if (val > UINT32_MAX || errno == ERANGE) {
  7964. return false;
  7965. } else {
  7966. upb_sink_putuint32(p->top->sink, parser_getsel(p), val);
  7967. return true;
  7968. }
  7969. }
  7970. /* XXX: We can't handle [u]int64 properly on 32-bit machines because
  7971. * strto[u]ll isn't in C89. */
  7972. case UPB_TYPE_INT64: {
  7973. long val = strtol(buf, &end, 0);
  7974. if (errno == ERANGE || end != bufend) {
  7975. break;
  7976. } else {
  7977. upb_sink_putint64(p->top->sink, parser_getsel(p), val);
  7978. return true;
  7979. }
  7980. }
  7981. case UPB_TYPE_UINT64: {
  7982. unsigned long val = strtoul(p->accumulated, &end, 0);
  7983. if (end != bufend) {
  7984. break;
  7985. } else if (errno == ERANGE) {
  7986. return false;
  7987. } else {
  7988. upb_sink_putuint64(p->top->sink, parser_getsel(p), val);
  7989. return true;
  7990. }
  7991. }
  7992. default:
  7993. break;
  7994. }
  7995. if (type != UPB_TYPE_DOUBLE && type != UPB_TYPE_FLOAT && is_quoted) {
  7996. /* Quoted numbers for integer types are not allowed to be in double form. */
  7997. return false;
  7998. }
  7999. if (len == strlen("Infinity") && strcmp(buf, "Infinity") == 0) {
  8000. /* C89 does not have an INFINITY macro. */
  8001. val = inf;
  8002. } else if (len == strlen("-Infinity") && strcmp(buf, "-Infinity") == 0) {
  8003. val = -inf;
  8004. } else {
  8005. val = strtod(buf, &end);
  8006. if (errno == ERANGE || end != bufend) {
  8007. return false;
  8008. }
  8009. }
  8010. switch (type) {
  8011. #define CASE(capitaltype, smalltype, ctype, min, max) \
  8012. case UPB_TYPE_ ## capitaltype: { \
  8013. if (modf(val, &dummy) != 0 || val > max || val < min) { \
  8014. return false; \
  8015. } else { \
  8016. upb_sink_put ## smalltype(p->top->sink, parser_getsel(p), \
  8017. (ctype)val); \
  8018. return true; \
  8019. } \
  8020. break; \
  8021. }
  8022. case UPB_TYPE_ENUM:
  8023. CASE(INT32, int32, int32_t, INT32_MIN, INT32_MAX);
  8024. CASE(INT64, int64, int64_t, INT64_MIN, INT64_MAX);
  8025. CASE(UINT32, uint32, uint32_t, 0, UINT32_MAX);
  8026. CASE(UINT64, uint64, uint64_t, 0, UINT64_MAX);
  8027. #undef CASE
  8028. case UPB_TYPE_DOUBLE:
  8029. upb_sink_putdouble(p->top->sink, parser_getsel(p), val);
  8030. return true;
  8031. case UPB_TYPE_FLOAT:
  8032. if ((val > FLT_MAX || val < -FLT_MAX) && val != inf && val != -inf) {
  8033. return false;
  8034. } else {
  8035. upb_sink_putfloat(p->top->sink, parser_getsel(p), val);
  8036. return true;
  8037. }
  8038. default:
  8039. return false;
  8040. }
  8041. }
  8042. static bool parse_number(upb_json_parser *p, bool is_quoted) {
  8043. size_t len;
  8044. const char *buf;
  8045. /* strtol() and friends unfortunately do not support specifying the length of
  8046. * the input string, so we need to force a copy into a NULL-terminated buffer. */
  8047. if (!multipart_text(p, "\0", 1, false)) {
  8048. return false;
  8049. }
  8050. buf = accumulate_getptr(p, &len);
  8051. if (parse_number_from_buffer(p, buf, is_quoted)) {
  8052. multipart_end(p);
  8053. return true;
  8054. } else {
  8055. upb_status_seterrf(p->status, "error parsing number: %s", buf);
  8056. multipart_end(p);
  8057. return false;
  8058. }
  8059. }
  8060. static bool parser_putbool(upb_json_parser *p, bool val) {
  8061. bool ok;
  8062. if (p->top->f == NULL) {
  8063. return true;
  8064. }
  8065. if (upb_fielddef_type(p->top->f) != UPB_TYPE_BOOL) {
  8066. upb_status_seterrf(p->status,
  8067. "Boolean value specified for non-bool field: %s",
  8068. upb_fielddef_name(p->top->f));
  8069. return false;
  8070. }
  8071. ok = upb_sink_putbool(p->top->sink, parser_getsel(p), val);
  8072. UPB_ASSERT(ok);
  8073. return true;
  8074. }
  8075. static bool end_bool(upb_json_parser *p, bool val) {
  8076. if (is_top_level(p)) {
  8077. if (is_wellknown_msg(p, UPB_WELLKNOWN_BOOLVALUE)) {
  8078. start_wrapper_object(p);
  8079. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8080. start_value_object(p, VALUE_BOOLVALUE);
  8081. } else {
  8082. return false;
  8083. }
  8084. } else if (is_wellknown_field(p, UPB_WELLKNOWN_BOOLVALUE)) {
  8085. if (!start_subobject(p)) {
  8086. return false;
  8087. }
  8088. start_wrapper_object(p);
  8089. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  8090. if (!start_subobject(p)) {
  8091. return false;
  8092. }
  8093. start_value_object(p, VALUE_BOOLVALUE);
  8094. }
  8095. if (p->top->is_unknown_field) {
  8096. return true;
  8097. }
  8098. if (!parser_putbool(p, val)) {
  8099. return false;
  8100. }
  8101. if (is_wellknown_msg(p, UPB_WELLKNOWN_BOOLVALUE)) {
  8102. end_wrapper_object(p);
  8103. if (!is_top_level(p)) {
  8104. end_subobject(p);
  8105. }
  8106. return true;
  8107. }
  8108. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8109. end_value_object(p);
  8110. if (!is_top_level(p)) {
  8111. end_subobject(p);
  8112. }
  8113. return true;
  8114. }
  8115. return true;
  8116. }
  8117. static bool end_null(upb_json_parser *p) {
  8118. const char *zero_ptr = "0";
  8119. if (is_top_level(p)) {
  8120. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8121. start_value_object(p, VALUE_NULLVALUE);
  8122. } else {
  8123. return true;
  8124. }
  8125. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  8126. if (!start_subobject(p)) {
  8127. return false;
  8128. }
  8129. start_value_object(p, VALUE_NULLVALUE);
  8130. } else {
  8131. return true;
  8132. }
  8133. /* Fill null_value field. */
  8134. multipart_startaccum(p);
  8135. capture_begin(p, zero_ptr);
  8136. capture_end(p, zero_ptr + 1);
  8137. parse_number(p, false);
  8138. end_value_object(p);
  8139. if (!is_top_level(p)) {
  8140. end_subobject(p);
  8141. }
  8142. return true;
  8143. }
  8144. static bool start_any_stringval(upb_json_parser *p) {
  8145. multipart_startaccum(p);
  8146. return true;
  8147. }
  8148. static bool start_stringval(upb_json_parser *p) {
  8149. if (is_top_level(p)) {
  8150. if (is_string_wrapper_object(p)) {
  8151. start_wrapper_object(p);
  8152. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_FIELDMASK)) {
  8153. start_fieldmask_object(p);
  8154. return true;
  8155. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_TIMESTAMP) ||
  8156. is_wellknown_msg(p, UPB_WELLKNOWN_DURATION)) {
  8157. start_object(p);
  8158. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8159. start_value_object(p, VALUE_STRINGVALUE);
  8160. } else {
  8161. return false;
  8162. }
  8163. } else if (does_string_wrapper_start(p)) {
  8164. if (!start_subobject(p)) {
  8165. return false;
  8166. }
  8167. start_wrapper_object(p);
  8168. } else if (does_fieldmask_start(p)) {
  8169. if (!start_subobject(p)) {
  8170. return false;
  8171. }
  8172. start_fieldmask_object(p);
  8173. return true;
  8174. } else if (is_wellknown_field(p, UPB_WELLKNOWN_TIMESTAMP) ||
  8175. is_wellknown_field(p, UPB_WELLKNOWN_DURATION)) {
  8176. if (!start_subobject(p)) {
  8177. return false;
  8178. }
  8179. start_object(p);
  8180. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  8181. if (!start_subobject(p)) {
  8182. return false;
  8183. }
  8184. start_value_object(p, VALUE_STRINGVALUE);
  8185. }
  8186. if (p->top->f == NULL) {
  8187. multipart_startaccum(p);
  8188. return true;
  8189. }
  8190. if (p->top->is_any) {
  8191. return start_any_stringval(p);
  8192. }
  8193. if (upb_fielddef_isstring(p->top->f)) {
  8194. upb_jsonparser_frame *inner;
  8195. upb_selector_t sel;
  8196. if (!check_stack(p)) return false;
  8197. /* Start a new parser frame: parser frames correspond one-to-one with
  8198. * handler frames, and string events occur in a sub-frame. */
  8199. inner = start_jsonparser_frame(p);
  8200. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  8201. upb_sink_startstr(p->top->sink, sel, 0, &inner->sink);
  8202. inner->m = p->top->m;
  8203. inner->f = p->top->f;
  8204. p->top = inner;
  8205. if (upb_fielddef_type(p->top->f) == UPB_TYPE_STRING) {
  8206. /* For STRING fields we push data directly to the handlers as it is
  8207. * parsed. We don't do this yet for BYTES fields, because our base64
  8208. * decoder is not streaming.
  8209. *
  8210. * TODO(haberman): make base64 decoding streaming also. */
  8211. multipart_start(p, getsel_for_handlertype(p, UPB_HANDLER_STRING));
  8212. return true;
  8213. } else {
  8214. multipart_startaccum(p);
  8215. return true;
  8216. }
  8217. } else if (upb_fielddef_type(p->top->f) != UPB_TYPE_BOOL &&
  8218. upb_fielddef_type(p->top->f) != UPB_TYPE_MESSAGE) {
  8219. /* No need to push a frame -- numeric values in quotes remain in the
  8220. * current parser frame. These values must accmulate so we can convert
  8221. * them all at once at the end. */
  8222. multipart_startaccum(p);
  8223. return true;
  8224. } else {
  8225. upb_status_seterrf(p->status,
  8226. "String specified for bool or submessage field: %s",
  8227. upb_fielddef_name(p->top->f));
  8228. return false;
  8229. }
  8230. }
  8231. static bool end_any_stringval(upb_json_parser *p) {
  8232. size_t len;
  8233. const char *buf = accumulate_getptr(p, &len);
  8234. /* Set type_url */
  8235. upb_selector_t sel;
  8236. upb_jsonparser_frame *inner;
  8237. if (!check_stack(p)) return false;
  8238. inner = p->top + 1;
  8239. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  8240. upb_sink_startstr(p->top->sink, sel, 0, &inner->sink);
  8241. sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
  8242. upb_sink_putstring(inner->sink, sel, buf, len, NULL);
  8243. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  8244. upb_sink_endstr(inner->sink, sel);
  8245. multipart_end(p);
  8246. /* Resolve type url */
  8247. if (strncmp(buf, "type.googleapis.com/", 20) == 0 && len > 20) {
  8248. const upb_msgdef *payload_type = NULL;
  8249. buf += 20;
  8250. len -= 20;
  8251. payload_type = upb_symtab_lookupmsg2(p->symtab, buf, len);
  8252. if (payload_type == NULL) {
  8253. upb_status_seterrf(
  8254. p->status, "Cannot find packed type: %.*s\n", (int)len, buf);
  8255. return false;
  8256. }
  8257. json_parser_any_frame_set_payload_type(p, p->top->any_frame, payload_type);
  8258. return true;
  8259. } else {
  8260. upb_status_seterrf(
  8261. p->status, "Invalid type url: %.*s\n", (int)len, buf);
  8262. return false;
  8263. }
  8264. }
  8265. static bool end_stringval_nontop(upb_json_parser *p) {
  8266. bool ok = true;
  8267. if (is_wellknown_msg(p, UPB_WELLKNOWN_TIMESTAMP) ||
  8268. is_wellknown_msg(p, UPB_WELLKNOWN_DURATION)) {
  8269. multipart_end(p);
  8270. return true;
  8271. }
  8272. if (p->top->f == NULL) {
  8273. multipart_end(p);
  8274. return true;
  8275. }
  8276. if (p->top->is_any) {
  8277. return end_any_stringval(p);
  8278. }
  8279. switch (upb_fielddef_type(p->top->f)) {
  8280. case UPB_TYPE_BYTES:
  8281. if (!base64_push(p, getsel_for_handlertype(p, UPB_HANDLER_STRING),
  8282. p->accumulated, p->accumulated_len)) {
  8283. return false;
  8284. }
  8285. /* Fall through. */
  8286. case UPB_TYPE_STRING: {
  8287. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  8288. upb_sink_endstr(p->top->sink, sel);
  8289. p->top--;
  8290. break;
  8291. }
  8292. case UPB_TYPE_ENUM: {
  8293. /* Resolve enum symbolic name to integer value. */
  8294. const upb_enumdef *enumdef = upb_fielddef_enumsubdef(p->top->f);
  8295. size_t len;
  8296. const char *buf = accumulate_getptr(p, &len);
  8297. int32_t int_val = 0;
  8298. ok = upb_enumdef_ntoi(enumdef, buf, len, &int_val);
  8299. if (ok) {
  8300. upb_selector_t sel = parser_getsel(p);
  8301. upb_sink_putint32(p->top->sink, sel, int_val);
  8302. } else {
  8303. upb_status_seterrf(p->status, "Enum value unknown: '%.*s'", len, buf);
  8304. }
  8305. break;
  8306. }
  8307. case UPB_TYPE_INT32:
  8308. case UPB_TYPE_INT64:
  8309. case UPB_TYPE_UINT32:
  8310. case UPB_TYPE_UINT64:
  8311. case UPB_TYPE_DOUBLE:
  8312. case UPB_TYPE_FLOAT:
  8313. ok = parse_number(p, true);
  8314. break;
  8315. default:
  8316. UPB_ASSERT(false);
  8317. upb_status_seterrmsg(p->status, "Internal error in JSON decoder");
  8318. ok = false;
  8319. break;
  8320. }
  8321. multipart_end(p);
  8322. return ok;
  8323. }
  8324. static bool end_stringval(upb_json_parser *p) {
  8325. /* FieldMask's stringvals have been ended when handling them. Only need to
  8326. * close FieldMask here.*/
  8327. if (does_fieldmask_end(p)) {
  8328. end_fieldmask_object(p);
  8329. if (!is_top_level(p)) {
  8330. end_subobject(p);
  8331. }
  8332. return true;
  8333. }
  8334. if (!end_stringval_nontop(p)) {
  8335. return false;
  8336. }
  8337. if (does_string_wrapper_end(p)) {
  8338. end_wrapper_object(p);
  8339. if (!is_top_level(p)) {
  8340. end_subobject(p);
  8341. }
  8342. return true;
  8343. }
  8344. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8345. end_value_object(p);
  8346. if (!is_top_level(p)) {
  8347. end_subobject(p);
  8348. }
  8349. return true;
  8350. }
  8351. if (is_wellknown_msg(p, UPB_WELLKNOWN_TIMESTAMP) ||
  8352. is_wellknown_msg(p, UPB_WELLKNOWN_DURATION) ||
  8353. is_wellknown_msg(p, UPB_WELLKNOWN_FIELDMASK)) {
  8354. end_object(p);
  8355. if (!is_top_level(p)) {
  8356. end_subobject(p);
  8357. }
  8358. return true;
  8359. }
  8360. return true;
  8361. }
  8362. static void start_duration_base(upb_json_parser *p, const char *ptr) {
  8363. capture_begin(p, ptr);
  8364. }
  8365. static bool end_duration_base(upb_json_parser *p, const char *ptr) {
  8366. size_t len;
  8367. const char *buf;
  8368. char seconds_buf[14];
  8369. char nanos_buf[12];
  8370. char *end;
  8371. int64_t seconds = 0;
  8372. int32_t nanos = 0;
  8373. double val = 0.0;
  8374. const char *seconds_membername = "seconds";
  8375. const char *nanos_membername = "nanos";
  8376. size_t fraction_start;
  8377. if (!capture_end(p, ptr)) {
  8378. return false;
  8379. }
  8380. buf = accumulate_getptr(p, &len);
  8381. memset(seconds_buf, 0, 14);
  8382. memset(nanos_buf, 0, 12);
  8383. /* Find out base end. The maximus duration is 315576000000, which cannot be
  8384. * represented by double without losing precision. Thus, we need to handle
  8385. * fraction and base separately. */
  8386. for (fraction_start = 0; fraction_start < len && buf[fraction_start] != '.';
  8387. fraction_start++);
  8388. /* Parse base */
  8389. memcpy(seconds_buf, buf, fraction_start);
  8390. seconds = strtol(seconds_buf, &end, 10);
  8391. if (errno == ERANGE || end != seconds_buf + fraction_start) {
  8392. upb_status_seterrf(p->status, "error parsing duration: %s",
  8393. seconds_buf);
  8394. return false;
  8395. }
  8396. if (seconds > 315576000000) {
  8397. upb_status_seterrf(p->status, "error parsing duration: "
  8398. "maximum acceptable value is "
  8399. "315576000000");
  8400. return false;
  8401. }
  8402. if (seconds < -315576000000) {
  8403. upb_status_seterrf(p->status, "error parsing duration: "
  8404. "minimum acceptable value is "
  8405. "-315576000000");
  8406. return false;
  8407. }
  8408. /* Parse fraction */
  8409. nanos_buf[0] = '0';
  8410. memcpy(nanos_buf + 1, buf + fraction_start, len - fraction_start);
  8411. val = strtod(nanos_buf, &end);
  8412. if (errno == ERANGE || end != nanos_buf + len - fraction_start + 1) {
  8413. upb_status_seterrf(p->status, "error parsing duration: %s",
  8414. nanos_buf);
  8415. return false;
  8416. }
  8417. nanos = val * 1000000000;
  8418. if (seconds < 0) nanos = -nanos;
  8419. /* Clean up buffer */
  8420. multipart_end(p);
  8421. /* Set seconds */
  8422. start_member(p);
  8423. capture_begin(p, seconds_membername);
  8424. capture_end(p, seconds_membername + 7);
  8425. end_membername(p);
  8426. upb_sink_putint64(p->top->sink, parser_getsel(p), seconds);
  8427. end_member(p);
  8428. /* Set nanos */
  8429. start_member(p);
  8430. capture_begin(p, nanos_membername);
  8431. capture_end(p, nanos_membername + 5);
  8432. end_membername(p);
  8433. upb_sink_putint32(p->top->sink, parser_getsel(p), nanos);
  8434. end_member(p);
  8435. /* Continue previous arena */
  8436. multipart_startaccum(p);
  8437. return true;
  8438. }
  8439. static int parse_timestamp_number(upb_json_parser *p) {
  8440. size_t len;
  8441. const char *buf;
  8442. int val;
  8443. /* atoi() and friends unfortunately do not support specifying the length of
  8444. * the input string, so we need to force a copy into a NULL-terminated buffer. */
  8445. multipart_text(p, "\0", 1, false);
  8446. buf = accumulate_getptr(p, &len);
  8447. val = atoi(buf);
  8448. multipart_end(p);
  8449. multipart_startaccum(p);
  8450. return val;
  8451. }
  8452. static void start_year(upb_json_parser *p, const char *ptr) {
  8453. capture_begin(p, ptr);
  8454. }
  8455. static bool end_year(upb_json_parser *p, const char *ptr) {
  8456. if (!capture_end(p, ptr)) {
  8457. return false;
  8458. }
  8459. p->tm.tm_year = parse_timestamp_number(p) - 1900;
  8460. return true;
  8461. }
  8462. static void start_month(upb_json_parser *p, const char *ptr) {
  8463. capture_begin(p, ptr);
  8464. }
  8465. static bool end_month(upb_json_parser *p, const char *ptr) {
  8466. if (!capture_end(p, ptr)) {
  8467. return false;
  8468. }
  8469. p->tm.tm_mon = parse_timestamp_number(p) - 1;
  8470. return true;
  8471. }
  8472. static void start_day(upb_json_parser *p, const char *ptr) {
  8473. capture_begin(p, ptr);
  8474. }
  8475. static bool end_day(upb_json_parser *p, const char *ptr) {
  8476. if (!capture_end(p, ptr)) {
  8477. return false;
  8478. }
  8479. p->tm.tm_mday = parse_timestamp_number(p);
  8480. return true;
  8481. }
  8482. static void start_hour(upb_json_parser *p, const char *ptr) {
  8483. capture_begin(p, ptr);
  8484. }
  8485. static bool end_hour(upb_json_parser *p, const char *ptr) {
  8486. if (!capture_end(p, ptr)) {
  8487. return false;
  8488. }
  8489. p->tm.tm_hour = parse_timestamp_number(p);
  8490. return true;
  8491. }
  8492. static void start_minute(upb_json_parser *p, const char *ptr) {
  8493. capture_begin(p, ptr);
  8494. }
  8495. static bool end_minute(upb_json_parser *p, const char *ptr) {
  8496. if (!capture_end(p, ptr)) {
  8497. return false;
  8498. }
  8499. p->tm.tm_min = parse_timestamp_number(p);
  8500. return true;
  8501. }
  8502. static void start_second(upb_json_parser *p, const char *ptr) {
  8503. capture_begin(p, ptr);
  8504. }
  8505. static bool end_second(upb_json_parser *p, const char *ptr) {
  8506. if (!capture_end(p, ptr)) {
  8507. return false;
  8508. }
  8509. p->tm.tm_sec = parse_timestamp_number(p);
  8510. return true;
  8511. }
  8512. static void start_timestamp_base(upb_json_parser *p) {
  8513. memset(&p->tm, 0, sizeof(struct tm));
  8514. }
  8515. static void start_timestamp_fraction(upb_json_parser *p, const char *ptr) {
  8516. capture_begin(p, ptr);
  8517. }
  8518. static bool end_timestamp_fraction(upb_json_parser *p, const char *ptr) {
  8519. size_t len;
  8520. const char *buf;
  8521. char nanos_buf[12];
  8522. char *end;
  8523. double val = 0.0;
  8524. int32_t nanos;
  8525. const char *nanos_membername = "nanos";
  8526. memset(nanos_buf, 0, 12);
  8527. if (!capture_end(p, ptr)) {
  8528. return false;
  8529. }
  8530. buf = accumulate_getptr(p, &len);
  8531. if (len > 10) {
  8532. upb_status_seterrf(p->status,
  8533. "error parsing timestamp: at most 9-digit fraction.");
  8534. return false;
  8535. }
  8536. /* Parse nanos */
  8537. nanos_buf[0] = '0';
  8538. memcpy(nanos_buf + 1, buf, len);
  8539. val = strtod(nanos_buf, &end);
  8540. if (errno == ERANGE || end != nanos_buf + len + 1) {
  8541. upb_status_seterrf(p->status, "error parsing timestamp nanos: %s",
  8542. nanos_buf);
  8543. return false;
  8544. }
  8545. nanos = val * 1000000000;
  8546. /* Clean up previous environment */
  8547. multipart_end(p);
  8548. /* Set nanos */
  8549. start_member(p);
  8550. capture_begin(p, nanos_membername);
  8551. capture_end(p, nanos_membername + 5);
  8552. end_membername(p);
  8553. upb_sink_putint32(p->top->sink, parser_getsel(p), nanos);
  8554. end_member(p);
  8555. /* Continue previous environment */
  8556. multipart_startaccum(p);
  8557. return true;
  8558. }
  8559. static void start_timestamp_zone(upb_json_parser *p, const char *ptr) {
  8560. capture_begin(p, ptr);
  8561. }
  8562. #define EPOCH_YEAR 1970
  8563. #define TM_YEAR_BASE 1900
  8564. static bool isleap(int year) {
  8565. return (year % 4) == 0 && (year % 100 != 0 || (year % 400) == 0);
  8566. }
  8567. const unsigned short int __mon_yday[2][13] = {
  8568. /* Normal years. */
  8569. { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 },
  8570. /* Leap years. */
  8571. { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }
  8572. };
  8573. int64_t epoch(int year, int yday, int hour, int min, int sec) {
  8574. int64_t years = year - EPOCH_YEAR;
  8575. int64_t leap_days = years / 4 - years / 100 + years / 400;
  8576. int64_t days = years * 365 + yday + leap_days;
  8577. int64_t hours = days * 24 + hour;
  8578. int64_t mins = hours * 60 + min;
  8579. int64_t secs = mins * 60 + sec;
  8580. return secs;
  8581. }
  8582. static int64_t upb_mktime(const struct tm *tp) {
  8583. int sec = tp->tm_sec;
  8584. int min = tp->tm_min;
  8585. int hour = tp->tm_hour;
  8586. int mday = tp->tm_mday;
  8587. int mon = tp->tm_mon;
  8588. int year = tp->tm_year + TM_YEAR_BASE;
  8589. /* Calculate day of year from year, month, and day of month. */
  8590. int mon_yday = ((__mon_yday[isleap(year)][mon]) - 1);
  8591. int yday = mon_yday + mday;
  8592. return epoch(year, yday, hour, min, sec);
  8593. }
  8594. static bool end_timestamp_zone(upb_json_parser *p, const char *ptr) {
  8595. size_t len;
  8596. const char *buf;
  8597. int hours;
  8598. int64_t seconds;
  8599. const char *seconds_membername = "seconds";
  8600. if (!capture_end(p, ptr)) {
  8601. return false;
  8602. }
  8603. buf = accumulate_getptr(p, &len);
  8604. if (buf[0] != 'Z') {
  8605. if (sscanf(buf + 1, "%2d:00", &hours) != 1) {
  8606. upb_status_seterrf(p->status, "error parsing timestamp offset");
  8607. return false;
  8608. }
  8609. if (buf[0] == '+') {
  8610. hours = -hours;
  8611. }
  8612. p->tm.tm_hour += hours;
  8613. }
  8614. /* Normalize tm */
  8615. seconds = upb_mktime(&p->tm);
  8616. /* Check timestamp boundary */
  8617. if (seconds < -62135596800) {
  8618. upb_status_seterrf(p->status, "error parsing timestamp: "
  8619. "minimum acceptable value is "
  8620. "0001-01-01T00:00:00Z");
  8621. return false;
  8622. }
  8623. /* Clean up previous environment */
  8624. multipart_end(p);
  8625. /* Set seconds */
  8626. start_member(p);
  8627. capture_begin(p, seconds_membername);
  8628. capture_end(p, seconds_membername + 7);
  8629. end_membername(p);
  8630. upb_sink_putint64(p->top->sink, parser_getsel(p), seconds);
  8631. end_member(p);
  8632. /* Continue previous environment */
  8633. multipart_startaccum(p);
  8634. return true;
  8635. }
  8636. static void start_fieldmask_path_text(upb_json_parser *p, const char *ptr) {
  8637. capture_begin(p, ptr);
  8638. }
  8639. static bool end_fieldmask_path_text(upb_json_parser *p, const char *ptr) {
  8640. return capture_end(p, ptr);
  8641. }
  8642. static bool start_fieldmask_path(upb_json_parser *p) {
  8643. upb_jsonparser_frame *inner;
  8644. upb_selector_t sel;
  8645. if (!check_stack(p)) return false;
  8646. /* Start a new parser frame: parser frames correspond one-to-one with
  8647. * handler frames, and string events occur in a sub-frame. */
  8648. inner = start_jsonparser_frame(p);
  8649. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  8650. upb_sink_startstr(p->top->sink, sel, 0, &inner->sink);
  8651. inner->m = p->top->m;
  8652. inner->f = p->top->f;
  8653. p->top = inner;
  8654. multipart_startaccum(p);
  8655. return true;
  8656. }
  8657. static bool lower_camel_push(
  8658. upb_json_parser *p, upb_selector_t sel, const char *ptr, size_t len) {
  8659. const char *limit = ptr + len;
  8660. bool first = true;
  8661. for (;ptr < limit; ptr++) {
  8662. if (*ptr >= 'A' && *ptr <= 'Z' && !first) {
  8663. char lower = tolower(*ptr);
  8664. upb_sink_putstring(p->top->sink, sel, "_", 1, NULL);
  8665. upb_sink_putstring(p->top->sink, sel, &lower, 1, NULL);
  8666. } else {
  8667. upb_sink_putstring(p->top->sink, sel, ptr, 1, NULL);
  8668. }
  8669. first = false;
  8670. }
  8671. return true;
  8672. }
  8673. static bool end_fieldmask_path(upb_json_parser *p) {
  8674. upb_selector_t sel;
  8675. if (!lower_camel_push(
  8676. p, getsel_for_handlertype(p, UPB_HANDLER_STRING),
  8677. p->accumulated, p->accumulated_len)) {
  8678. return false;
  8679. }
  8680. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  8681. upb_sink_endstr(p->top->sink, sel);
  8682. p->top--;
  8683. multipart_end(p);
  8684. return true;
  8685. }
  8686. static void start_member(upb_json_parser *p) {
  8687. UPB_ASSERT(!p->top->f);
  8688. multipart_startaccum(p);
  8689. }
  8690. /* Helper: invoked during parse_mapentry() to emit the mapentry message's key
  8691. * field based on the current contents of the accumulate buffer. */
  8692. static bool parse_mapentry_key(upb_json_parser *p) {
  8693. size_t len;
  8694. const char *buf = accumulate_getptr(p, &len);
  8695. /* Emit the key field. We do a bit of ad-hoc parsing here because the
  8696. * parser state machine has already decided that this is a string field
  8697. * name, and we are reinterpreting it as some arbitrary key type. In
  8698. * particular, integer and bool keys are quoted, so we need to parse the
  8699. * quoted string contents here. */
  8700. p->top->f = upb_msgdef_itof(p->top->m, UPB_MAPENTRY_KEY);
  8701. if (p->top->f == NULL) {
  8702. upb_status_seterrmsg(p->status, "mapentry message has no key");
  8703. return false;
  8704. }
  8705. switch (upb_fielddef_type(p->top->f)) {
  8706. case UPB_TYPE_INT32:
  8707. case UPB_TYPE_INT64:
  8708. case UPB_TYPE_UINT32:
  8709. case UPB_TYPE_UINT64:
  8710. /* Invoke end_number. The accum buffer has the number's text already. */
  8711. if (!parse_number(p, true)) {
  8712. return false;
  8713. }
  8714. break;
  8715. case UPB_TYPE_BOOL:
  8716. if (len == 4 && !strncmp(buf, "true", 4)) {
  8717. if (!parser_putbool(p, true)) {
  8718. return false;
  8719. }
  8720. } else if (len == 5 && !strncmp(buf, "false", 5)) {
  8721. if (!parser_putbool(p, false)) {
  8722. return false;
  8723. }
  8724. } else {
  8725. upb_status_seterrmsg(p->status,
  8726. "Map bool key not 'true' or 'false'");
  8727. return false;
  8728. }
  8729. multipart_end(p);
  8730. break;
  8731. case UPB_TYPE_STRING:
  8732. case UPB_TYPE_BYTES: {
  8733. upb_sink subsink;
  8734. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  8735. upb_sink_startstr(p->top->sink, sel, len, &subsink);
  8736. sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
  8737. upb_sink_putstring(subsink, sel, buf, len, NULL);
  8738. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  8739. upb_sink_endstr(subsink, sel);
  8740. multipart_end(p);
  8741. break;
  8742. }
  8743. default:
  8744. upb_status_seterrmsg(p->status, "Invalid field type for map key");
  8745. return false;
  8746. }
  8747. return true;
  8748. }
  8749. /* Helper: emit one map entry (as a submessage in the map field sequence). This
  8750. * is invoked from end_membername(), at the end of the map entry's key string,
  8751. * with the map key in the accumulate buffer. It parses the key from that
  8752. * buffer, emits the handler calls to start the mapentry submessage (setting up
  8753. * its subframe in the process), and sets up state in the subframe so that the
  8754. * value parser (invoked next) will emit the mapentry's value field and then
  8755. * end the mapentry message. */
  8756. static bool handle_mapentry(upb_json_parser *p) {
  8757. const upb_fielddef *mapfield;
  8758. const upb_msgdef *mapentrymsg;
  8759. upb_jsonparser_frame *inner;
  8760. upb_selector_t sel;
  8761. /* Map entry: p->top->sink is the seq frame, so we need to start a frame
  8762. * for the mapentry itself, and then set |f| in that frame so that the map
  8763. * value field is parsed, and also set a flag to end the frame after the
  8764. * map-entry value is parsed. */
  8765. if (!check_stack(p)) return false;
  8766. mapfield = p->top->mapfield;
  8767. mapentrymsg = upb_fielddef_msgsubdef(mapfield);
  8768. inner = start_jsonparser_frame(p);
  8769. p->top->f = mapfield;
  8770. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
  8771. upb_sink_startsubmsg(p->top->sink, sel, &inner->sink);
  8772. inner->m = mapentrymsg;
  8773. inner->mapfield = mapfield;
  8774. /* Don't set this to true *yet* -- we reuse parsing handlers below to push
  8775. * the key field value to the sink, and these handlers will pop the frame
  8776. * if they see is_mapentry (when invoked by the parser state machine, they
  8777. * would have just seen the map-entry value, not key). */
  8778. inner->is_mapentry = false;
  8779. p->top = inner;
  8780. /* send STARTMSG in submsg frame. */
  8781. upb_sink_startmsg(p->top->sink);
  8782. parse_mapentry_key(p);
  8783. /* Set up the value field to receive the map-entry value. */
  8784. p->top->f = upb_msgdef_itof(p->top->m, UPB_MAPENTRY_VALUE);
  8785. p->top->is_mapentry = true; /* set up to pop frame after value is parsed. */
  8786. p->top->mapfield = mapfield;
  8787. if (p->top->f == NULL) {
  8788. upb_status_seterrmsg(p->status, "mapentry message has no value");
  8789. return false;
  8790. }
  8791. return true;
  8792. }
  8793. static bool end_membername(upb_json_parser *p) {
  8794. UPB_ASSERT(!p->top->f);
  8795. if (!p->top->m) {
  8796. p->top->is_unknown_field = true;
  8797. multipart_end(p);
  8798. return true;
  8799. }
  8800. if (p->top->is_any) {
  8801. return end_any_membername(p);
  8802. } else if (p->top->is_map) {
  8803. return handle_mapentry(p);
  8804. } else {
  8805. size_t len;
  8806. const char *buf = accumulate_getptr(p, &len);
  8807. upb_value v;
  8808. if (upb_strtable_lookup2(p->top->name_table, buf, len, &v)) {
  8809. p->top->f = upb_value_getconstptr(v);
  8810. multipart_end(p);
  8811. return true;
  8812. } else if (p->ignore_json_unknown) {
  8813. p->top->is_unknown_field = true;
  8814. multipart_end(p);
  8815. return true;
  8816. } else {
  8817. upb_status_seterrf(p->status, "No such field: %.*s\n", (int)len, buf);
  8818. return false;
  8819. }
  8820. }
  8821. }
  8822. static bool end_any_membername(upb_json_parser *p) {
  8823. size_t len;
  8824. const char *buf = accumulate_getptr(p, &len);
  8825. upb_value v;
  8826. if (len == 5 && strncmp(buf, "@type", len) == 0) {
  8827. upb_strtable_lookup2(p->top->name_table, "type_url", 8, &v);
  8828. p->top->f = upb_value_getconstptr(v);
  8829. multipart_end(p);
  8830. return true;
  8831. } else {
  8832. p->top->is_unknown_field = true;
  8833. multipart_end(p);
  8834. return true;
  8835. }
  8836. }
  8837. static void end_member(upb_json_parser *p) {
  8838. /* If we just parsed a map-entry value, end that frame too. */
  8839. if (p->top->is_mapentry) {
  8840. upb_selector_t sel;
  8841. bool ok;
  8842. const upb_fielddef *mapfield;
  8843. UPB_ASSERT(p->top > p->stack);
  8844. /* send ENDMSG on submsg. */
  8845. upb_sink_endmsg(p->top->sink, p->status);
  8846. mapfield = p->top->mapfield;
  8847. /* send ENDSUBMSG in repeated-field-of-mapentries frame. */
  8848. p->top--;
  8849. ok = upb_handlers_getselector(mapfield, UPB_HANDLER_ENDSUBMSG, &sel);
  8850. UPB_ASSERT(ok);
  8851. upb_sink_endsubmsg(p->top->sink, sel);
  8852. }
  8853. p->top->f = NULL;
  8854. p->top->is_unknown_field = false;
  8855. }
  8856. static void start_any_member(upb_json_parser *p, const char *ptr) {
  8857. start_member(p);
  8858. json_parser_any_frame_set_after_type_url_start_once(p->top->any_frame, ptr);
  8859. }
  8860. static void end_any_member(upb_json_parser *p, const char *ptr) {
  8861. json_parser_any_frame_set_before_type_url_end(p->top->any_frame, ptr);
  8862. end_member(p);
  8863. }
  8864. static bool start_subobject(upb_json_parser *p) {
  8865. if (p->top->is_unknown_field) {
  8866. if (!check_stack(p)) return false;
  8867. p->top = start_jsonparser_frame(p);
  8868. return true;
  8869. }
  8870. if (upb_fielddef_ismap(p->top->f)) {
  8871. upb_jsonparser_frame *inner;
  8872. upb_selector_t sel;
  8873. /* Beginning of a map. Start a new parser frame in a repeated-field
  8874. * context. */
  8875. if (!check_stack(p)) return false;
  8876. inner = start_jsonparser_frame(p);
  8877. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
  8878. upb_sink_startseq(p->top->sink, sel, &inner->sink);
  8879. inner->m = upb_fielddef_msgsubdef(p->top->f);
  8880. inner->mapfield = p->top->f;
  8881. inner->is_map = true;
  8882. p->top = inner;
  8883. return true;
  8884. } else if (upb_fielddef_issubmsg(p->top->f)) {
  8885. upb_jsonparser_frame *inner;
  8886. upb_selector_t sel;
  8887. /* Beginning of a subobject. Start a new parser frame in the submsg
  8888. * context. */
  8889. if (!check_stack(p)) return false;
  8890. inner = start_jsonparser_frame(p);
  8891. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
  8892. upb_sink_startsubmsg(p->top->sink, sel, &inner->sink);
  8893. inner->m = upb_fielddef_msgsubdef(p->top->f);
  8894. set_name_table(p, inner);
  8895. p->top = inner;
  8896. if (is_wellknown_msg(p, UPB_WELLKNOWN_ANY)) {
  8897. p->top->is_any = true;
  8898. p->top->any_frame = json_parser_any_frame_new(p);
  8899. } else {
  8900. p->top->is_any = false;
  8901. p->top->any_frame = NULL;
  8902. }
  8903. return true;
  8904. } else {
  8905. upb_status_seterrf(p->status,
  8906. "Object specified for non-message/group field: %s",
  8907. upb_fielddef_name(p->top->f));
  8908. return false;
  8909. }
  8910. }
  8911. static bool start_subobject_full(upb_json_parser *p) {
  8912. if (is_top_level(p)) {
  8913. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8914. start_value_object(p, VALUE_STRUCTVALUE);
  8915. if (!start_subobject(p)) return false;
  8916. start_structvalue_object(p);
  8917. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_STRUCT)) {
  8918. start_structvalue_object(p);
  8919. } else {
  8920. return true;
  8921. }
  8922. } else if (is_wellknown_field(p, UPB_WELLKNOWN_STRUCT)) {
  8923. if (!start_subobject(p)) return false;
  8924. start_structvalue_object(p);
  8925. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  8926. if (!start_subobject(p)) return false;
  8927. start_value_object(p, VALUE_STRUCTVALUE);
  8928. if (!start_subobject(p)) return false;
  8929. start_structvalue_object(p);
  8930. }
  8931. return start_subobject(p);
  8932. }
  8933. static void end_subobject(upb_json_parser *p) {
  8934. if (is_top_level(p)) {
  8935. return;
  8936. }
  8937. if (p->top->is_map) {
  8938. upb_selector_t sel;
  8939. p->top--;
  8940. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
  8941. upb_sink_endseq(p->top->sink, sel);
  8942. } else {
  8943. upb_selector_t sel;
  8944. bool is_unknown = p->top->m == NULL;
  8945. p->top--;
  8946. if (!is_unknown) {
  8947. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSUBMSG);
  8948. upb_sink_endsubmsg(p->top->sink, sel);
  8949. }
  8950. }
  8951. }
  8952. static void end_subobject_full(upb_json_parser *p) {
  8953. end_subobject(p);
  8954. if (is_wellknown_msg(p, UPB_WELLKNOWN_STRUCT)) {
  8955. end_structvalue_object(p);
  8956. if (!is_top_level(p)) {
  8957. end_subobject(p);
  8958. }
  8959. }
  8960. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8961. end_value_object(p);
  8962. if (!is_top_level(p)) {
  8963. end_subobject(p);
  8964. }
  8965. }
  8966. }
  8967. static bool start_array(upb_json_parser *p) {
  8968. upb_jsonparser_frame *inner;
  8969. upb_selector_t sel;
  8970. if (is_top_level(p)) {
  8971. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8972. start_value_object(p, VALUE_LISTVALUE);
  8973. if (!start_subobject(p)) return false;
  8974. start_listvalue_object(p);
  8975. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_LISTVALUE)) {
  8976. start_listvalue_object(p);
  8977. } else {
  8978. return false;
  8979. }
  8980. } else if (is_wellknown_field(p, UPB_WELLKNOWN_LISTVALUE) &&
  8981. (!upb_fielddef_isseq(p->top->f) ||
  8982. p->top->is_repeated)) {
  8983. if (!start_subobject(p)) return false;
  8984. start_listvalue_object(p);
  8985. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE) &&
  8986. (!upb_fielddef_isseq(p->top->f) ||
  8987. p->top->is_repeated)) {
  8988. if (!start_subobject(p)) return false;
  8989. start_value_object(p, VALUE_LISTVALUE);
  8990. if (!start_subobject(p)) return false;
  8991. start_listvalue_object(p);
  8992. }
  8993. if (p->top->is_unknown_field) {
  8994. inner = start_jsonparser_frame(p);
  8995. inner->is_unknown_field = true;
  8996. p->top = inner;
  8997. return true;
  8998. }
  8999. if (!upb_fielddef_isseq(p->top->f)) {
  9000. upb_status_seterrf(p->status,
  9001. "Array specified for non-repeated field: %s",
  9002. upb_fielddef_name(p->top->f));
  9003. return false;
  9004. }
  9005. if (!check_stack(p)) return false;
  9006. inner = start_jsonparser_frame(p);
  9007. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
  9008. upb_sink_startseq(p->top->sink, sel, &inner->sink);
  9009. inner->m = p->top->m;
  9010. inner->f = p->top->f;
  9011. inner->is_repeated = true;
  9012. p->top = inner;
  9013. return true;
  9014. }
  9015. static void end_array(upb_json_parser *p) {
  9016. upb_selector_t sel;
  9017. UPB_ASSERT(p->top > p->stack);
  9018. p->top--;
  9019. if (p->top->is_unknown_field) {
  9020. return;
  9021. }
  9022. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
  9023. upb_sink_endseq(p->top->sink, sel);
  9024. if (is_wellknown_msg(p, UPB_WELLKNOWN_LISTVALUE)) {
  9025. end_listvalue_object(p);
  9026. if (!is_top_level(p)) {
  9027. end_subobject(p);
  9028. }
  9029. }
  9030. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  9031. end_value_object(p);
  9032. if (!is_top_level(p)) {
  9033. end_subobject(p);
  9034. }
  9035. }
  9036. }
  9037. static void start_object(upb_json_parser *p) {
  9038. if (!p->top->is_map && p->top->m != NULL) {
  9039. upb_sink_startmsg(p->top->sink);
  9040. }
  9041. }
  9042. static void end_object(upb_json_parser *p) {
  9043. if (!p->top->is_map && p->top->m != NULL) {
  9044. upb_sink_endmsg(p->top->sink, p->status);
  9045. }
  9046. }
  9047. static void start_any_object(upb_json_parser *p, const char *ptr) {
  9048. start_object(p);
  9049. p->top->any_frame->before_type_url_start = ptr;
  9050. p->top->any_frame->before_type_url_end = ptr;
  9051. }
  9052. static bool end_any_object(upb_json_parser *p, const char *ptr) {
  9053. const char *value_membername = "value";
  9054. bool is_well_known_packed = false;
  9055. const char *packed_end = ptr + 1;
  9056. upb_selector_t sel;
  9057. upb_jsonparser_frame *inner;
  9058. if (json_parser_any_frame_has_value(p->top->any_frame) &&
  9059. !json_parser_any_frame_has_type_url(p->top->any_frame)) {
  9060. upb_status_seterrmsg(p->status, "No valid type url");
  9061. return false;
  9062. }
  9063. /* Well known types data is represented as value field. */
  9064. if (upb_msgdef_wellknowntype(p->top->any_frame->parser->top->m) !=
  9065. UPB_WELLKNOWN_UNSPECIFIED) {
  9066. is_well_known_packed = true;
  9067. if (json_parser_any_frame_has_value_before_type_url(p->top->any_frame)) {
  9068. p->top->any_frame->before_type_url_start =
  9069. memchr(p->top->any_frame->before_type_url_start, ':',
  9070. p->top->any_frame->before_type_url_end -
  9071. p->top->any_frame->before_type_url_start);
  9072. if (p->top->any_frame->before_type_url_start == NULL) {
  9073. upb_status_seterrmsg(p->status, "invalid data for well known type.");
  9074. return false;
  9075. }
  9076. p->top->any_frame->before_type_url_start++;
  9077. }
  9078. if (json_parser_any_frame_has_value_after_type_url(p->top->any_frame)) {
  9079. p->top->any_frame->after_type_url_start =
  9080. memchr(p->top->any_frame->after_type_url_start, ':',
  9081. (ptr + 1) -
  9082. p->top->any_frame->after_type_url_start);
  9083. if (p->top->any_frame->after_type_url_start == NULL) {
  9084. upb_status_seterrmsg(p->status, "Invalid data for well known type.");
  9085. return false;
  9086. }
  9087. p->top->any_frame->after_type_url_start++;
  9088. packed_end = ptr;
  9089. }
  9090. }
  9091. if (json_parser_any_frame_has_value_before_type_url(p->top->any_frame)) {
  9092. if (!parse(p->top->any_frame->parser, NULL,
  9093. p->top->any_frame->before_type_url_start,
  9094. p->top->any_frame->before_type_url_end -
  9095. p->top->any_frame->before_type_url_start, NULL)) {
  9096. return false;
  9097. }
  9098. } else {
  9099. if (!is_well_known_packed) {
  9100. if (!parse(p->top->any_frame->parser, NULL, "{", 1, NULL)) {
  9101. return false;
  9102. }
  9103. }
  9104. }
  9105. if (json_parser_any_frame_has_value_before_type_url(p->top->any_frame) &&
  9106. json_parser_any_frame_has_value_after_type_url(p->top->any_frame)) {
  9107. if (!parse(p->top->any_frame->parser, NULL, ",", 1, NULL)) {
  9108. return false;
  9109. }
  9110. }
  9111. if (json_parser_any_frame_has_value_after_type_url(p->top->any_frame)) {
  9112. if (!parse(p->top->any_frame->parser, NULL,
  9113. p->top->any_frame->after_type_url_start,
  9114. packed_end - p->top->any_frame->after_type_url_start, NULL)) {
  9115. return false;
  9116. }
  9117. } else {
  9118. if (!is_well_known_packed) {
  9119. if (!parse(p->top->any_frame->parser, NULL, "}", 1, NULL)) {
  9120. return false;
  9121. }
  9122. }
  9123. }
  9124. if (!end(p->top->any_frame->parser, NULL)) {
  9125. return false;
  9126. }
  9127. p->top->is_any = false;
  9128. /* Set value */
  9129. start_member(p);
  9130. capture_begin(p, value_membername);
  9131. capture_end(p, value_membername + 5);
  9132. end_membername(p);
  9133. if (!check_stack(p)) return false;
  9134. inner = p->top + 1;
  9135. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  9136. upb_sink_startstr(p->top->sink, sel, 0, &inner->sink);
  9137. sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
  9138. upb_sink_putstring(inner->sink, sel, p->top->any_frame->stringsink.ptr,
  9139. p->top->any_frame->stringsink.len, NULL);
  9140. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  9141. upb_sink_endstr(inner->sink, sel);
  9142. end_member(p);
  9143. end_object(p);
  9144. /* Deallocate any parse frame. */
  9145. json_parser_any_frame_free(p->top->any_frame);
  9146. return true;
  9147. }
  9148. static bool is_string_wrapper(const upb_msgdef *m) {
  9149. upb_wellknowntype_t type = upb_msgdef_wellknowntype(m);
  9150. return type == UPB_WELLKNOWN_STRINGVALUE ||
  9151. type == UPB_WELLKNOWN_BYTESVALUE;
  9152. }
  9153. static bool is_fieldmask(const upb_msgdef *m) {
  9154. upb_wellknowntype_t type = upb_msgdef_wellknowntype(m);
  9155. return type == UPB_WELLKNOWN_FIELDMASK;
  9156. }
  9157. static void start_fieldmask_object(upb_json_parser *p) {
  9158. const char *membername = "paths";
  9159. start_object(p);
  9160. /* Set up context for parsing value */
  9161. start_member(p);
  9162. capture_begin(p, membername);
  9163. capture_end(p, membername + 5);
  9164. end_membername(p);
  9165. start_array(p);
  9166. }
  9167. static void end_fieldmask_object(upb_json_parser *p) {
  9168. end_array(p);
  9169. end_member(p);
  9170. end_object(p);
  9171. }
  9172. static void start_wrapper_object(upb_json_parser *p) {
  9173. const char *membername = "value";
  9174. start_object(p);
  9175. /* Set up context for parsing value */
  9176. start_member(p);
  9177. capture_begin(p, membername);
  9178. capture_end(p, membername + 5);
  9179. end_membername(p);
  9180. }
  9181. static void end_wrapper_object(upb_json_parser *p) {
  9182. end_member(p);
  9183. end_object(p);
  9184. }
  9185. static void start_value_object(upb_json_parser *p, int value_type) {
  9186. const char *nullmember = "null_value";
  9187. const char *numbermember = "number_value";
  9188. const char *stringmember = "string_value";
  9189. const char *boolmember = "bool_value";
  9190. const char *structmember = "struct_value";
  9191. const char *listmember = "list_value";
  9192. const char *membername = "";
  9193. switch (value_type) {
  9194. case VALUE_NULLVALUE:
  9195. membername = nullmember;
  9196. break;
  9197. case VALUE_NUMBERVALUE:
  9198. membername = numbermember;
  9199. break;
  9200. case VALUE_STRINGVALUE:
  9201. membername = stringmember;
  9202. break;
  9203. case VALUE_BOOLVALUE:
  9204. membername = boolmember;
  9205. break;
  9206. case VALUE_STRUCTVALUE:
  9207. membername = structmember;
  9208. break;
  9209. case VALUE_LISTVALUE:
  9210. membername = listmember;
  9211. break;
  9212. }
  9213. start_object(p);
  9214. /* Set up context for parsing value */
  9215. start_member(p);
  9216. capture_begin(p, membername);
  9217. capture_end(p, membername + strlen(membername));
  9218. end_membername(p);
  9219. }
  9220. static void end_value_object(upb_json_parser *p) {
  9221. end_member(p);
  9222. end_object(p);
  9223. }
  9224. static void start_listvalue_object(upb_json_parser *p) {
  9225. const char *membername = "values";
  9226. start_object(p);
  9227. /* Set up context for parsing value */
  9228. start_member(p);
  9229. capture_begin(p, membername);
  9230. capture_end(p, membername + strlen(membername));
  9231. end_membername(p);
  9232. }
  9233. static void end_listvalue_object(upb_json_parser *p) {
  9234. end_member(p);
  9235. end_object(p);
  9236. }
  9237. static void start_structvalue_object(upb_json_parser *p) {
  9238. const char *membername = "fields";
  9239. start_object(p);
  9240. /* Set up context for parsing value */
  9241. start_member(p);
  9242. capture_begin(p, membername);
  9243. capture_end(p, membername + strlen(membername));
  9244. end_membername(p);
  9245. }
  9246. static void end_structvalue_object(upb_json_parser *p) {
  9247. end_member(p);
  9248. end_object(p);
  9249. }
  9250. static bool is_top_level(upb_json_parser *p) {
  9251. return p->top == p->stack && p->top->f == NULL && !p->top->is_unknown_field;
  9252. }
  9253. static bool is_wellknown_msg(upb_json_parser *p, upb_wellknowntype_t type) {
  9254. return p->top->m != NULL && upb_msgdef_wellknowntype(p->top->m) == type;
  9255. }
  9256. static bool is_wellknown_field(upb_json_parser *p, upb_wellknowntype_t type) {
  9257. return p->top->f != NULL &&
  9258. upb_fielddef_issubmsg(p->top->f) &&
  9259. (upb_msgdef_wellknowntype(upb_fielddef_msgsubdef(p->top->f))
  9260. == type);
  9261. }
  9262. static bool does_number_wrapper_start(upb_json_parser *p) {
  9263. return p->top->f != NULL &&
  9264. upb_fielddef_issubmsg(p->top->f) &&
  9265. upb_msgdef_isnumberwrapper(upb_fielddef_msgsubdef(p->top->f));
  9266. }
  9267. static bool does_number_wrapper_end(upb_json_parser *p) {
  9268. return p->top->m != NULL && upb_msgdef_isnumberwrapper(p->top->m);
  9269. }
  9270. static bool is_number_wrapper_object(upb_json_parser *p) {
  9271. return p->top->m != NULL && upb_msgdef_isnumberwrapper(p->top->m);
  9272. }
  9273. static bool does_string_wrapper_start(upb_json_parser *p) {
  9274. return p->top->f != NULL &&
  9275. upb_fielddef_issubmsg(p->top->f) &&
  9276. is_string_wrapper(upb_fielddef_msgsubdef(p->top->f));
  9277. }
  9278. static bool does_string_wrapper_end(upb_json_parser *p) {
  9279. return p->top->m != NULL && is_string_wrapper(p->top->m);
  9280. }
  9281. static bool is_string_wrapper_object(upb_json_parser *p) {
  9282. return p->top->m != NULL && is_string_wrapper(p->top->m);
  9283. }
  9284. static bool does_fieldmask_start(upb_json_parser *p) {
  9285. return p->top->f != NULL &&
  9286. upb_fielddef_issubmsg(p->top->f) &&
  9287. is_fieldmask(upb_fielddef_msgsubdef(p->top->f));
  9288. }
  9289. static bool does_fieldmask_end(upb_json_parser *p) {
  9290. return p->top->m != NULL && is_fieldmask(p->top->m);
  9291. }
  9292. #define CHECK_RETURN_TOP(x) if (!(x)) goto error
  9293. /* The actual parser **********************************************************/
  9294. /* What follows is the Ragel parser itself. The language is specified in Ragel
  9295. * and the actions call our C functions above.
  9296. *
  9297. * Ragel has an extensive set of functionality, and we use only a small part of
  9298. * it. There are many action types but we only use a few:
  9299. *
  9300. * ">" -- transition into a machine
  9301. * "%" -- transition out of a machine
  9302. * "@" -- transition into a final state of a machine.
  9303. *
  9304. * "@" transitions are tricky because a machine can transition into a final
  9305. * state repeatedly. But in some cases we know this can't happen, for example
  9306. * a string which is delimited by a final '"' can only transition into its
  9307. * final state once, when the closing '"' is seen. */
  9308. #line 2791 "upb/json/parser.rl"
  9309. #line 2594 "upb/json/parser.c"
  9310. static const char _json_actions[] = {
  9311. 0, 1, 0, 1, 1, 1, 3, 1,
  9312. 4, 1, 6, 1, 7, 1, 8, 1,
  9313. 9, 1, 11, 1, 12, 1, 13, 1,
  9314. 14, 1, 15, 1, 16, 1, 17, 1,
  9315. 18, 1, 19, 1, 20, 1, 22, 1,
  9316. 23, 1, 24, 1, 35, 1, 37, 1,
  9317. 39, 1, 40, 1, 42, 1, 43, 1,
  9318. 44, 1, 46, 1, 48, 1, 49, 1,
  9319. 50, 1, 51, 1, 53, 1, 54, 2,
  9320. 4, 9, 2, 5, 6, 2, 7, 3,
  9321. 2, 7, 9, 2, 21, 26, 2, 25,
  9322. 10, 2, 27, 28, 2, 29, 30, 2,
  9323. 32, 34, 2, 33, 31, 2, 38, 36,
  9324. 2, 40, 42, 2, 45, 2, 2, 46,
  9325. 54, 2, 47, 36, 2, 49, 54, 2,
  9326. 50, 54, 2, 51, 54, 2, 52, 41,
  9327. 2, 53, 54, 3, 32, 34, 35, 4,
  9328. 21, 26, 27, 28
  9329. };
  9330. static const short _json_key_offsets[] = {
  9331. 0, 0, 12, 13, 18, 23, 28, 29,
  9332. 30, 31, 32, 33, 34, 35, 36, 37,
  9333. 38, 43, 44, 48, 53, 58, 63, 67,
  9334. 71, 74, 77, 79, 83, 87, 89, 91,
  9335. 96, 98, 100, 109, 115, 121, 127, 133,
  9336. 135, 139, 142, 144, 146, 149, 150, 154,
  9337. 156, 158, 160, 162, 163, 165, 167, 168,
  9338. 170, 172, 173, 175, 177, 178, 180, 182,
  9339. 183, 185, 187, 191, 193, 195, 196, 197,
  9340. 198, 199, 201, 206, 208, 210, 212, 221,
  9341. 222, 222, 222, 227, 232, 237, 238, 239,
  9342. 240, 241, 241, 242, 243, 244, 244, 245,
  9343. 246, 247, 247, 252, 253, 257, 262, 267,
  9344. 272, 276, 276, 279, 282, 285, 288, 291,
  9345. 294, 294, 294, 294, 294, 294
  9346. };
  9347. static const char _json_trans_keys[] = {
  9348. 32, 34, 45, 91, 102, 110, 116, 123,
  9349. 9, 13, 48, 57, 34, 32, 93, 125,
  9350. 9, 13, 32, 44, 93, 9, 13, 32,
  9351. 93, 125, 9, 13, 97, 108, 115, 101,
  9352. 117, 108, 108, 114, 117, 101, 32, 34,
  9353. 125, 9, 13, 34, 32, 58, 9, 13,
  9354. 32, 93, 125, 9, 13, 32, 44, 125,
  9355. 9, 13, 32, 44, 125, 9, 13, 32,
  9356. 34, 9, 13, 45, 48, 49, 57, 48,
  9357. 49, 57, 46, 69, 101, 48, 57, 69,
  9358. 101, 48, 57, 43, 45, 48, 57, 48,
  9359. 57, 48, 57, 46, 69, 101, 48, 57,
  9360. 34, 92, 34, 92, 34, 47, 92, 98,
  9361. 102, 110, 114, 116, 117, 48, 57, 65,
  9362. 70, 97, 102, 48, 57, 65, 70, 97,
  9363. 102, 48, 57, 65, 70, 97, 102, 48,
  9364. 57, 65, 70, 97, 102, 34, 92, 45,
  9365. 48, 49, 57, 48, 49, 57, 46, 115,
  9366. 48, 57, 115, 48, 57, 34, 46, 115,
  9367. 48, 57, 48, 57, 48, 57, 48, 57,
  9368. 48, 57, 45, 48, 57, 48, 57, 45,
  9369. 48, 57, 48, 57, 84, 48, 57, 48,
  9370. 57, 58, 48, 57, 48, 57, 58, 48,
  9371. 57, 48, 57, 43, 45, 46, 90, 48,
  9372. 57, 48, 57, 58, 48, 48, 34, 48,
  9373. 57, 43, 45, 90, 48, 57, 34, 44,
  9374. 34, 44, 34, 44, 34, 45, 91, 102,
  9375. 110, 116, 123, 48, 57, 34, 32, 93,
  9376. 125, 9, 13, 32, 44, 93, 9, 13,
  9377. 32, 93, 125, 9, 13, 97, 108, 115,
  9378. 101, 117, 108, 108, 114, 117, 101, 32,
  9379. 34, 125, 9, 13, 34, 32, 58, 9,
  9380. 13, 32, 93, 125, 9, 13, 32, 44,
  9381. 125, 9, 13, 32, 44, 125, 9, 13,
  9382. 32, 34, 9, 13, 32, 9, 13, 32,
  9383. 9, 13, 32, 9, 13, 32, 9, 13,
  9384. 32, 9, 13, 32, 9, 13, 0
  9385. };
  9386. static const char _json_single_lengths[] = {
  9387. 0, 8, 1, 3, 3, 3, 1, 1,
  9388. 1, 1, 1, 1, 1, 1, 1, 1,
  9389. 3, 1, 2, 3, 3, 3, 2, 2,
  9390. 1, 3, 0, 2, 2, 0, 0, 3,
  9391. 2, 2, 9, 0, 0, 0, 0, 2,
  9392. 2, 1, 2, 0, 1, 1, 2, 0,
  9393. 0, 0, 0, 1, 0, 0, 1, 0,
  9394. 0, 1, 0, 0, 1, 0, 0, 1,
  9395. 0, 0, 4, 0, 0, 1, 1, 1,
  9396. 1, 0, 3, 2, 2, 2, 7, 1,
  9397. 0, 0, 3, 3, 3, 1, 1, 1,
  9398. 1, 0, 1, 1, 1, 0, 1, 1,
  9399. 1, 0, 3, 1, 2, 3, 3, 3,
  9400. 2, 0, 1, 1, 1, 1, 1, 1,
  9401. 0, 0, 0, 0, 0, 0
  9402. };
  9403. static const char _json_range_lengths[] = {
  9404. 0, 2, 0, 1, 1, 1, 0, 0,
  9405. 0, 0, 0, 0, 0, 0, 0, 0,
  9406. 1, 0, 1, 1, 1, 1, 1, 1,
  9407. 1, 0, 1, 1, 1, 1, 1, 1,
  9408. 0, 0, 0, 3, 3, 3, 3, 0,
  9409. 1, 1, 0, 1, 1, 0, 1, 1,
  9410. 1, 1, 1, 0, 1, 1, 0, 1,
  9411. 1, 0, 1, 1, 0, 1, 1, 0,
  9412. 1, 1, 0, 1, 1, 0, 0, 0,
  9413. 0, 1, 1, 0, 0, 0, 1, 0,
  9414. 0, 0, 1, 1, 1, 0, 0, 0,
  9415. 0, 0, 0, 0, 0, 0, 0, 0,
  9416. 0, 0, 1, 0, 1, 1, 1, 1,
  9417. 1, 0, 1, 1, 1, 1, 1, 1,
  9418. 0, 0, 0, 0, 0, 0
  9419. };
  9420. static const short _json_index_offsets[] = {
  9421. 0, 0, 11, 13, 18, 23, 28, 30,
  9422. 32, 34, 36, 38, 40, 42, 44, 46,
  9423. 48, 53, 55, 59, 64, 69, 74, 78,
  9424. 82, 85, 89, 91, 95, 99, 101, 103,
  9425. 108, 111, 114, 124, 128, 132, 136, 140,
  9426. 143, 147, 150, 153, 155, 158, 160, 164,
  9427. 166, 168, 170, 172, 174, 176, 178, 180,
  9428. 182, 184, 186, 188, 190, 192, 194, 196,
  9429. 198, 200, 202, 207, 209, 211, 213, 215,
  9430. 217, 219, 221, 226, 229, 232, 235, 244,
  9431. 246, 247, 248, 253, 258, 263, 265, 267,
  9432. 269, 271, 272, 274, 276, 278, 279, 281,
  9433. 283, 285, 286, 291, 293, 297, 302, 307,
  9434. 312, 316, 317, 320, 323, 326, 329, 332,
  9435. 335, 336, 337, 338, 339, 340
  9436. };
  9437. static const unsigned char _json_indicies[] = {
  9438. 0, 2, 3, 4, 5, 6, 7, 8,
  9439. 0, 3, 1, 9, 1, 11, 12, 1,
  9440. 11, 10, 13, 14, 12, 13, 1, 14,
  9441. 1, 1, 14, 10, 15, 1, 16, 1,
  9442. 17, 1, 18, 1, 19, 1, 20, 1,
  9443. 21, 1, 22, 1, 23, 1, 24, 1,
  9444. 25, 26, 27, 25, 1, 28, 1, 29,
  9445. 30, 29, 1, 30, 1, 1, 30, 31,
  9446. 32, 33, 34, 32, 1, 35, 36, 27,
  9447. 35, 1, 36, 26, 36, 1, 37, 38,
  9448. 39, 1, 38, 39, 1, 41, 42, 42,
  9449. 40, 43, 1, 42, 42, 43, 40, 44,
  9450. 44, 45, 1, 45, 1, 45, 40, 41,
  9451. 42, 42, 39, 40, 47, 48, 46, 50,
  9452. 51, 49, 52, 52, 52, 52, 52, 52,
  9453. 52, 52, 53, 1, 54, 54, 54, 1,
  9454. 55, 55, 55, 1, 56, 56, 56, 1,
  9455. 57, 57, 57, 1, 59, 60, 58, 61,
  9456. 62, 63, 1, 64, 65, 1, 66, 67,
  9457. 1, 68, 1, 67, 68, 1, 69, 1,
  9458. 66, 67, 65, 1, 70, 1, 71, 1,
  9459. 72, 1, 73, 1, 74, 1, 75, 1,
  9460. 76, 1, 77, 1, 78, 1, 79, 1,
  9461. 80, 1, 81, 1, 82, 1, 83, 1,
  9462. 84, 1, 85, 1, 86, 1, 87, 1,
  9463. 88, 1, 89, 89, 90, 91, 1, 92,
  9464. 1, 93, 1, 94, 1, 95, 1, 96,
  9465. 1, 97, 1, 98, 1, 99, 99, 100,
  9466. 98, 1, 102, 1, 101, 104, 105, 103,
  9467. 1, 1, 101, 106, 107, 108, 109, 110,
  9468. 111, 112, 107, 1, 113, 1, 114, 115,
  9469. 117, 118, 1, 117, 116, 119, 120, 118,
  9470. 119, 1, 120, 1, 1, 120, 116, 121,
  9471. 1, 122, 1, 123, 1, 124, 1, 125,
  9472. 126, 1, 127, 1, 128, 1, 129, 130,
  9473. 1, 131, 1, 132, 1, 133, 134, 135,
  9474. 136, 134, 1, 137, 1, 138, 139, 138,
  9475. 1, 139, 1, 1, 139, 140, 141, 142,
  9476. 143, 141, 1, 144, 145, 136, 144, 1,
  9477. 145, 135, 145, 1, 146, 147, 147, 1,
  9478. 148, 148, 1, 149, 149, 1, 150, 150,
  9479. 1, 151, 151, 1, 152, 152, 1, 1,
  9480. 1, 1, 1, 1, 1, 0
  9481. };
  9482. static const char _json_trans_targs[] = {
  9483. 1, 0, 2, 107, 3, 6, 10, 13,
  9484. 16, 106, 4, 3, 106, 4, 5, 7,
  9485. 8, 9, 108, 11, 12, 109, 14, 15,
  9486. 110, 16, 17, 111, 18, 18, 19, 20,
  9487. 21, 22, 111, 21, 22, 24, 25, 31,
  9488. 112, 26, 28, 27, 29, 30, 33, 113,
  9489. 34, 33, 113, 34, 32, 35, 36, 37,
  9490. 38, 39, 33, 113, 34, 41, 42, 46,
  9491. 42, 46, 43, 45, 44, 114, 48, 49,
  9492. 50, 51, 52, 53, 54, 55, 56, 57,
  9493. 58, 59, 60, 61, 62, 63, 64, 65,
  9494. 66, 67, 73, 72, 68, 69, 70, 71,
  9495. 72, 115, 74, 67, 72, 76, 116, 76,
  9496. 116, 77, 79, 81, 82, 85, 90, 94,
  9497. 98, 80, 117, 117, 83, 82, 80, 83,
  9498. 84, 86, 87, 88, 89, 117, 91, 92,
  9499. 93, 117, 95, 96, 97, 117, 98, 99,
  9500. 105, 100, 100, 101, 102, 103, 104, 105,
  9501. 103, 104, 117, 106, 106, 106, 106, 106,
  9502. 106
  9503. };
  9504. static const unsigned char _json_trans_actions[] = {
  9505. 0, 0, 113, 107, 53, 0, 0, 0,
  9506. 125, 59, 45, 0, 55, 0, 0, 0,
  9507. 0, 0, 0, 0, 0, 0, 0, 0,
  9508. 0, 0, 101, 51, 47, 0, 0, 45,
  9509. 49, 49, 104, 0, 0, 0, 0, 0,
  9510. 3, 0, 0, 0, 0, 0, 5, 15,
  9511. 0, 0, 71, 7, 13, 0, 74, 9,
  9512. 9, 9, 77, 80, 11, 37, 37, 37,
  9513. 0, 0, 0, 39, 0, 41, 86, 0,
  9514. 0, 0, 17, 19, 0, 21, 23, 0,
  9515. 25, 27, 0, 29, 31, 0, 33, 35,
  9516. 0, 135, 83, 135, 0, 0, 0, 0,
  9517. 0, 92, 0, 89, 89, 98, 43, 0,
  9518. 131, 95, 113, 107, 53, 0, 0, 0,
  9519. 125, 59, 69, 110, 45, 0, 55, 0,
  9520. 0, 0, 0, 0, 0, 119, 0, 0,
  9521. 0, 122, 0, 0, 0, 116, 0, 101,
  9522. 51, 47, 0, 0, 45, 49, 49, 104,
  9523. 0, 0, 128, 0, 57, 63, 65, 61,
  9524. 67
  9525. };
  9526. static const unsigned char _json_eof_actions[] = {
  9527. 0, 0, 0, 0, 0, 0, 0, 0,
  9528. 0, 0, 0, 0, 0, 0, 0, 0,
  9529. 0, 0, 0, 0, 0, 0, 0, 0,
  9530. 0, 1, 0, 1, 0, 0, 1, 1,
  9531. 0, 0, 0, 0, 0, 0, 0, 0,
  9532. 0, 0, 0, 0, 0, 0, 0, 0,
  9533. 0, 0, 0, 0, 0, 0, 0, 0,
  9534. 0, 0, 0, 0, 0, 0, 0, 0,
  9535. 0, 0, 0, 0, 0, 0, 0, 0,
  9536. 0, 0, 0, 0, 0, 0, 0, 0,
  9537. 0, 0, 0, 0, 0, 0, 0, 0,
  9538. 0, 0, 0, 0, 0, 0, 0, 0,
  9539. 0, 0, 0, 0, 0, 0, 0, 0,
  9540. 0, 0, 0, 57, 63, 65, 61, 67,
  9541. 0, 0, 0, 0, 0, 0
  9542. };
  9543. static const int json_start = 1;
  9544. static const int json_en_number_machine = 23;
  9545. static const int json_en_string_machine = 32;
  9546. static const int json_en_duration_machine = 40;
  9547. static const int json_en_timestamp_machine = 47;
  9548. static const int json_en_fieldmask_machine = 75;
  9549. static const int json_en_value_machine = 78;
  9550. static const int json_en_main = 1;
  9551. #line 2794 "upb/json/parser.rl"
  9552. size_t parse(void *closure, const void *hd, const char *buf, size_t size,
  9553. const upb_bufhandle *handle) {
  9554. upb_json_parser *parser = closure;
  9555. /* Variables used by Ragel's generated code. */
  9556. int cs = parser->current_state;
  9557. int *stack = parser->parser_stack;
  9558. int top = parser->parser_top;
  9559. const char *p = buf;
  9560. const char *pe = buf + size;
  9561. const char *eof = &eof_ch;
  9562. parser->handle = handle;
  9563. UPB_UNUSED(hd);
  9564. UPB_UNUSED(handle);
  9565. capture_resume(parser, buf);
  9566. #line 2872 "upb/json/parser.c"
  9567. {
  9568. int _klen;
  9569. unsigned int _trans;
  9570. const char *_acts;
  9571. unsigned int _nacts;
  9572. const char *_keys;
  9573. if ( p == pe )
  9574. goto _test_eof;
  9575. if ( cs == 0 )
  9576. goto _out;
  9577. _resume:
  9578. _keys = _json_trans_keys + _json_key_offsets[cs];
  9579. _trans = _json_index_offsets[cs];
  9580. _klen = _json_single_lengths[cs];
  9581. if ( _klen > 0 ) {
  9582. const char *_lower = _keys;
  9583. const char *_mid;
  9584. const char *_upper = _keys + _klen - 1;
  9585. while (1) {
  9586. if ( _upper < _lower )
  9587. break;
  9588. _mid = _lower + ((_upper-_lower) >> 1);
  9589. if ( (*p) < *_mid )
  9590. _upper = _mid - 1;
  9591. else if ( (*p) > *_mid )
  9592. _lower = _mid + 1;
  9593. else {
  9594. _trans += (unsigned int)(_mid - _keys);
  9595. goto _match;
  9596. }
  9597. }
  9598. _keys += _klen;
  9599. _trans += _klen;
  9600. }
  9601. _klen = _json_range_lengths[cs];
  9602. if ( _klen > 0 ) {
  9603. const char *_lower = _keys;
  9604. const char *_mid;
  9605. const char *_upper = _keys + (_klen<<1) - 2;
  9606. while (1) {
  9607. if ( _upper < _lower )
  9608. break;
  9609. _mid = _lower + (((_upper-_lower) >> 1) & ~1);
  9610. if ( (*p) < _mid[0] )
  9611. _upper = _mid - 2;
  9612. else if ( (*p) > _mid[1] )
  9613. _lower = _mid + 2;
  9614. else {
  9615. _trans += (unsigned int)((_mid - _keys)>>1);
  9616. goto _match;
  9617. }
  9618. }
  9619. _trans += _klen;
  9620. }
  9621. _match:
  9622. _trans = _json_indicies[_trans];
  9623. cs = _json_trans_targs[_trans];
  9624. if ( _json_trans_actions[_trans] == 0 )
  9625. goto _again;
  9626. _acts = _json_actions + _json_trans_actions[_trans];
  9627. _nacts = (unsigned int) *_acts++;
  9628. while ( _nacts-- > 0 )
  9629. {
  9630. switch ( *_acts++ )
  9631. {
  9632. case 1:
  9633. #line 2599 "upb/json/parser.rl"
  9634. { p--; {cs = stack[--top]; goto _again;} }
  9635. break;
  9636. case 2:
  9637. #line 2601 "upb/json/parser.rl"
  9638. { p--; {stack[top++] = cs; cs = 23;goto _again;} }
  9639. break;
  9640. case 3:
  9641. #line 2605 "upb/json/parser.rl"
  9642. { start_text(parser, p); }
  9643. break;
  9644. case 4:
  9645. #line 2606 "upb/json/parser.rl"
  9646. { CHECK_RETURN_TOP(end_text(parser, p)); }
  9647. break;
  9648. case 5:
  9649. #line 2612 "upb/json/parser.rl"
  9650. { start_hex(parser); }
  9651. break;
  9652. case 6:
  9653. #line 2613 "upb/json/parser.rl"
  9654. { hexdigit(parser, p); }
  9655. break;
  9656. case 7:
  9657. #line 2614 "upb/json/parser.rl"
  9658. { CHECK_RETURN_TOP(end_hex(parser)); }
  9659. break;
  9660. case 8:
  9661. #line 2620 "upb/json/parser.rl"
  9662. { CHECK_RETURN_TOP(escape(parser, p)); }
  9663. break;
  9664. case 9:
  9665. #line 2626 "upb/json/parser.rl"
  9666. { p--; {cs = stack[--top]; goto _again;} }
  9667. break;
  9668. case 10:
  9669. #line 2631 "upb/json/parser.rl"
  9670. { start_year(parser, p); }
  9671. break;
  9672. case 11:
  9673. #line 2632 "upb/json/parser.rl"
  9674. { CHECK_RETURN_TOP(end_year(parser, p)); }
  9675. break;
  9676. case 12:
  9677. #line 2636 "upb/json/parser.rl"
  9678. { start_month(parser, p); }
  9679. break;
  9680. case 13:
  9681. #line 2637 "upb/json/parser.rl"
  9682. { CHECK_RETURN_TOP(end_month(parser, p)); }
  9683. break;
  9684. case 14:
  9685. #line 2641 "upb/json/parser.rl"
  9686. { start_day(parser, p); }
  9687. break;
  9688. case 15:
  9689. #line 2642 "upb/json/parser.rl"
  9690. { CHECK_RETURN_TOP(end_day(parser, p)); }
  9691. break;
  9692. case 16:
  9693. #line 2646 "upb/json/parser.rl"
  9694. { start_hour(parser, p); }
  9695. break;
  9696. case 17:
  9697. #line 2647 "upb/json/parser.rl"
  9698. { CHECK_RETURN_TOP(end_hour(parser, p)); }
  9699. break;
  9700. case 18:
  9701. #line 2651 "upb/json/parser.rl"
  9702. { start_minute(parser, p); }
  9703. break;
  9704. case 19:
  9705. #line 2652 "upb/json/parser.rl"
  9706. { CHECK_RETURN_TOP(end_minute(parser, p)); }
  9707. break;
  9708. case 20:
  9709. #line 2656 "upb/json/parser.rl"
  9710. { start_second(parser, p); }
  9711. break;
  9712. case 21:
  9713. #line 2657 "upb/json/parser.rl"
  9714. { CHECK_RETURN_TOP(end_second(parser, p)); }
  9715. break;
  9716. case 22:
  9717. #line 2662 "upb/json/parser.rl"
  9718. { start_duration_base(parser, p); }
  9719. break;
  9720. case 23:
  9721. #line 2663 "upb/json/parser.rl"
  9722. { CHECK_RETURN_TOP(end_duration_base(parser, p)); }
  9723. break;
  9724. case 24:
  9725. #line 2665 "upb/json/parser.rl"
  9726. { p--; {cs = stack[--top]; goto _again;} }
  9727. break;
  9728. case 25:
  9729. #line 2670 "upb/json/parser.rl"
  9730. { start_timestamp_base(parser); }
  9731. break;
  9732. case 26:
  9733. #line 2672 "upb/json/parser.rl"
  9734. { start_timestamp_fraction(parser, p); }
  9735. break;
  9736. case 27:
  9737. #line 2673 "upb/json/parser.rl"
  9738. { CHECK_RETURN_TOP(end_timestamp_fraction(parser, p)); }
  9739. break;
  9740. case 28:
  9741. #line 2675 "upb/json/parser.rl"
  9742. { start_timestamp_zone(parser, p); }
  9743. break;
  9744. case 29:
  9745. #line 2676 "upb/json/parser.rl"
  9746. { CHECK_RETURN_TOP(end_timestamp_zone(parser, p)); }
  9747. break;
  9748. case 30:
  9749. #line 2678 "upb/json/parser.rl"
  9750. { p--; {cs = stack[--top]; goto _again;} }
  9751. break;
  9752. case 31:
  9753. #line 2683 "upb/json/parser.rl"
  9754. { start_fieldmask_path_text(parser, p); }
  9755. break;
  9756. case 32:
  9757. #line 2684 "upb/json/parser.rl"
  9758. { end_fieldmask_path_text(parser, p); }
  9759. break;
  9760. case 33:
  9761. #line 2689 "upb/json/parser.rl"
  9762. { start_fieldmask_path(parser); }
  9763. break;
  9764. case 34:
  9765. #line 2690 "upb/json/parser.rl"
  9766. { end_fieldmask_path(parser); }
  9767. break;
  9768. case 35:
  9769. #line 2696 "upb/json/parser.rl"
  9770. { p--; {cs = stack[--top]; goto _again;} }
  9771. break;
  9772. case 36:
  9773. #line 2701 "upb/json/parser.rl"
  9774. {
  9775. if (is_wellknown_msg(parser, UPB_WELLKNOWN_TIMESTAMP)) {
  9776. {stack[top++] = cs; cs = 47;goto _again;}
  9777. } else if (is_wellknown_msg(parser, UPB_WELLKNOWN_DURATION)) {
  9778. {stack[top++] = cs; cs = 40;goto _again;}
  9779. } else if (is_wellknown_msg(parser, UPB_WELLKNOWN_FIELDMASK)) {
  9780. {stack[top++] = cs; cs = 75;goto _again;}
  9781. } else {
  9782. {stack[top++] = cs; cs = 32;goto _again;}
  9783. }
  9784. }
  9785. break;
  9786. case 37:
  9787. #line 2714 "upb/json/parser.rl"
  9788. { p--; {stack[top++] = cs; cs = 78;goto _again;} }
  9789. break;
  9790. case 38:
  9791. #line 2719 "upb/json/parser.rl"
  9792. {
  9793. if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
  9794. start_any_member(parser, p);
  9795. } else {
  9796. start_member(parser);
  9797. }
  9798. }
  9799. break;
  9800. case 39:
  9801. #line 2726 "upb/json/parser.rl"
  9802. { CHECK_RETURN_TOP(end_membername(parser)); }
  9803. break;
  9804. case 40:
  9805. #line 2729 "upb/json/parser.rl"
  9806. {
  9807. if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
  9808. end_any_member(parser, p);
  9809. } else {
  9810. end_member(parser);
  9811. }
  9812. }
  9813. break;
  9814. case 41:
  9815. #line 2740 "upb/json/parser.rl"
  9816. {
  9817. if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
  9818. start_any_object(parser, p);
  9819. } else {
  9820. start_object(parser);
  9821. }
  9822. }
  9823. break;
  9824. case 42:
  9825. #line 2749 "upb/json/parser.rl"
  9826. {
  9827. if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
  9828. CHECK_RETURN_TOP(end_any_object(parser, p));
  9829. } else {
  9830. end_object(parser);
  9831. }
  9832. }
  9833. break;
  9834. case 43:
  9835. #line 2761 "upb/json/parser.rl"
  9836. { CHECK_RETURN_TOP(start_array(parser)); }
  9837. break;
  9838. case 44:
  9839. #line 2765 "upb/json/parser.rl"
  9840. { end_array(parser); }
  9841. break;
  9842. case 45:
  9843. #line 2770 "upb/json/parser.rl"
  9844. { CHECK_RETURN_TOP(start_number(parser, p)); }
  9845. break;
  9846. case 46:
  9847. #line 2771 "upb/json/parser.rl"
  9848. { CHECK_RETURN_TOP(end_number(parser, p)); }
  9849. break;
  9850. case 47:
  9851. #line 2773 "upb/json/parser.rl"
  9852. { CHECK_RETURN_TOP(start_stringval(parser)); }
  9853. break;
  9854. case 48:
  9855. #line 2774 "upb/json/parser.rl"
  9856. { CHECK_RETURN_TOP(end_stringval(parser)); }
  9857. break;
  9858. case 49:
  9859. #line 2776 "upb/json/parser.rl"
  9860. { CHECK_RETURN_TOP(end_bool(parser, true)); }
  9861. break;
  9862. case 50:
  9863. #line 2778 "upb/json/parser.rl"
  9864. { CHECK_RETURN_TOP(end_bool(parser, false)); }
  9865. break;
  9866. case 51:
  9867. #line 2780 "upb/json/parser.rl"
  9868. { CHECK_RETURN_TOP(end_null(parser)); }
  9869. break;
  9870. case 52:
  9871. #line 2782 "upb/json/parser.rl"
  9872. { CHECK_RETURN_TOP(start_subobject_full(parser)); }
  9873. break;
  9874. case 53:
  9875. #line 2783 "upb/json/parser.rl"
  9876. { end_subobject_full(parser); }
  9877. break;
  9878. case 54:
  9879. #line 2788 "upb/json/parser.rl"
  9880. { p--; {cs = stack[--top]; goto _again;} }
  9881. break;
  9882. #line 3196 "upb/json/parser.c"
  9883. }
  9884. }
  9885. _again:
  9886. if ( cs == 0 )
  9887. goto _out;
  9888. if ( ++p != pe )
  9889. goto _resume;
  9890. _test_eof: {}
  9891. if ( p == eof )
  9892. {
  9893. const char *__acts = _json_actions + _json_eof_actions[cs];
  9894. unsigned int __nacts = (unsigned int) *__acts++;
  9895. while ( __nacts-- > 0 ) {
  9896. switch ( *__acts++ ) {
  9897. case 0:
  9898. #line 2597 "upb/json/parser.rl"
  9899. { p--; {cs = stack[--top]; if ( p == pe )
  9900. goto _test_eof;
  9901. goto _again;} }
  9902. break;
  9903. case 46:
  9904. #line 2771 "upb/json/parser.rl"
  9905. { CHECK_RETURN_TOP(end_number(parser, p)); }
  9906. break;
  9907. case 49:
  9908. #line 2776 "upb/json/parser.rl"
  9909. { CHECK_RETURN_TOP(end_bool(parser, true)); }
  9910. break;
  9911. case 50:
  9912. #line 2778 "upb/json/parser.rl"
  9913. { CHECK_RETURN_TOP(end_bool(parser, false)); }
  9914. break;
  9915. case 51:
  9916. #line 2780 "upb/json/parser.rl"
  9917. { CHECK_RETURN_TOP(end_null(parser)); }
  9918. break;
  9919. case 53:
  9920. #line 2783 "upb/json/parser.rl"
  9921. { end_subobject_full(parser); }
  9922. break;
  9923. #line 3238 "upb/json/parser.c"
  9924. }
  9925. }
  9926. }
  9927. _out: {}
  9928. }
  9929. #line 2816 "upb/json/parser.rl"
  9930. if (p != pe) {
  9931. upb_status_seterrf(parser->status, "Parse error at '%.*s'\n", pe - p, p);
  9932. } else {
  9933. capture_suspend(parser, &p);
  9934. }
  9935. error:
  9936. /* Save parsing state back to parser. */
  9937. parser->current_state = cs;
  9938. parser->parser_top = top;
  9939. return p - buf;
  9940. }
  9941. static bool end(void *closure, const void *hd) {
  9942. upb_json_parser *parser = closure;
  9943. /* Prevent compile warning on unused static constants. */
  9944. UPB_UNUSED(json_start);
  9945. UPB_UNUSED(json_en_duration_machine);
  9946. UPB_UNUSED(json_en_fieldmask_machine);
  9947. UPB_UNUSED(json_en_number_machine);
  9948. UPB_UNUSED(json_en_string_machine);
  9949. UPB_UNUSED(json_en_timestamp_machine);
  9950. UPB_UNUSED(json_en_value_machine);
  9951. UPB_UNUSED(json_en_main);
  9952. parse(parser, hd, &eof_ch, 0, NULL);
  9953. return parser->current_state >= 106;
  9954. }
  9955. static void json_parser_reset(upb_json_parser *p) {
  9956. int cs;
  9957. int top;
  9958. p->top = p->stack;
  9959. init_frame(p->top);
  9960. /* Emit Ragel initialization of the parser. */
  9961. #line 3289 "upb/json/parser.c"
  9962. {
  9963. cs = json_start;
  9964. top = 0;
  9965. }
  9966. #line 2858 "upb/json/parser.rl"
  9967. p->current_state = cs;
  9968. p->parser_top = top;
  9969. accumulate_clear(p);
  9970. p->multipart_state = MULTIPART_INACTIVE;
  9971. p->capture = NULL;
  9972. p->accumulated = NULL;
  9973. }
  9974. static upb_json_parsermethod *parsermethod_new(upb_json_codecache *c,
  9975. const upb_msgdef *md) {
  9976. upb_msg_field_iter i;
  9977. upb_alloc *alloc = upb_arena_alloc(c->arena);
  9978. upb_json_parsermethod *m = upb_malloc(alloc, sizeof(*m));
  9979. m->cache = c;
  9980. upb_byteshandler_init(&m->input_handler_);
  9981. upb_byteshandler_setstring(&m->input_handler_, parse, m);
  9982. upb_byteshandler_setendstr(&m->input_handler_, end, m);
  9983. upb_strtable_init2(&m->name_table, UPB_CTYPE_CONSTPTR, alloc);
  9984. /* Build name_table */
  9985. for(upb_msg_field_begin(&i, md);
  9986. !upb_msg_field_done(&i);
  9987. upb_msg_field_next(&i)) {
  9988. const upb_fielddef *f = upb_msg_iter_field(&i);
  9989. upb_value v = upb_value_constptr(f);
  9990. char *buf;
  9991. /* Add an entry for the JSON name. */
  9992. size_t len = upb_fielddef_getjsonname(f, NULL, 0);
  9993. buf = upb_malloc(alloc, len);
  9994. upb_fielddef_getjsonname(f, buf, len);
  9995. upb_strtable_insert3(&m->name_table, buf, strlen(buf), v, alloc);
  9996. if (strcmp(buf, upb_fielddef_name(f)) != 0) {
  9997. /* Since the JSON name is different from the regular field name, add an
  9998. * entry for the raw name (compliant proto3 JSON parsers must accept
  9999. * both). */
  10000. const char *name = upb_fielddef_name(f);
  10001. upb_strtable_insert3(&m->name_table, name, strlen(name), v, alloc);
  10002. }
  10003. }
  10004. return m;
  10005. }
  10006. /* Public API *****************************************************************/
  10007. upb_json_parser *upb_json_parser_create(upb_arena *arena,
  10008. const upb_json_parsermethod *method,
  10009. const upb_symtab* symtab,
  10010. upb_sink output,
  10011. upb_status *status,
  10012. bool ignore_json_unknown) {
  10013. #ifndef NDEBUG
  10014. const size_t size_before = upb_arena_bytesallocated(arena);
  10015. #endif
  10016. upb_json_parser *p = upb_arena_malloc(arena, sizeof(upb_json_parser));
  10017. if (!p) return false;
  10018. p->arena = arena;
  10019. p->method = method;
  10020. p->status = status;
  10021. p->limit = p->stack + UPB_JSON_MAX_DEPTH;
  10022. p->accumulate_buf = NULL;
  10023. p->accumulate_buf_size = 0;
  10024. upb_bytessink_reset(&p->input_, &method->input_handler_, p);
  10025. json_parser_reset(p);
  10026. p->top->sink = output;
  10027. p->top->m = upb_handlers_msgdef(output.handlers);
  10028. if (is_wellknown_msg(p, UPB_WELLKNOWN_ANY)) {
  10029. p->top->is_any = true;
  10030. p->top->any_frame = json_parser_any_frame_new(p);
  10031. } else {
  10032. p->top->is_any = false;
  10033. p->top->any_frame = NULL;
  10034. }
  10035. set_name_table(p, p->top);
  10036. p->symtab = symtab;
  10037. p->ignore_json_unknown = ignore_json_unknown;
  10038. /* If this fails, uncomment and increase the value in parser.h. */
  10039. /* fprintf(stderr, "%zd\n", upb_arena_bytesallocated(arena) - size_before); */
  10040. UPB_ASSERT_DEBUGVAR(upb_arena_bytesallocated(arena) - size_before <=
  10041. UPB_JSON_PARSER_SIZE);
  10042. return p;
  10043. }
  10044. upb_bytessink upb_json_parser_input(upb_json_parser *p) {
  10045. return p->input_;
  10046. }
  10047. const upb_byteshandler *upb_json_parsermethod_inputhandler(
  10048. const upb_json_parsermethod *m) {
  10049. return &m->input_handler_;
  10050. }
  10051. upb_json_codecache *upb_json_codecache_new(void) {
  10052. upb_alloc *alloc;
  10053. upb_json_codecache *c;
  10054. c = upb_gmalloc(sizeof(*c));
  10055. c->arena = upb_arena_new();
  10056. alloc = upb_arena_alloc(c->arena);
  10057. upb_inttable_init2(&c->methods, UPB_CTYPE_CONSTPTR, alloc);
  10058. return c;
  10059. }
  10060. void upb_json_codecache_free(upb_json_codecache *c) {
  10061. upb_arena_free(c->arena);
  10062. upb_gfree(c);
  10063. }
  10064. const upb_json_parsermethod *upb_json_codecache_get(upb_json_codecache *c,
  10065. const upb_msgdef *md) {
  10066. upb_json_parsermethod *m;
  10067. upb_value v;
  10068. upb_msg_field_iter i;
  10069. upb_alloc *alloc = upb_arena_alloc(c->arena);
  10070. if (upb_inttable_lookupptr(&c->methods, md, &v)) {
  10071. return upb_value_getconstptr(v);
  10072. }
  10073. m = parsermethod_new(c, md);
  10074. v = upb_value_constptr(m);
  10075. if (!m) return NULL;
  10076. if (!upb_inttable_insertptr2(&c->methods, md, v, alloc)) return NULL;
  10077. /* Populate parser methods for all submessages, so the name tables will
  10078. * be available during parsing. */
  10079. for(upb_msg_field_begin(&i, md);
  10080. !upb_msg_field_done(&i);
  10081. upb_msg_field_next(&i)) {
  10082. upb_fielddef *f = upb_msg_iter_field(&i);
  10083. if (upb_fielddef_issubmsg(f)) {
  10084. const upb_msgdef *subdef = upb_fielddef_msgsubdef(f);
  10085. const upb_json_parsermethod *sub_method =
  10086. upb_json_codecache_get(c, subdef);
  10087. if (!sub_method) return NULL;
  10088. }
  10089. }
  10090. return m;
  10091. }
  10092. /*
  10093. ** This currently uses snprintf() to format primitives, and could be optimized
  10094. ** further.
  10095. */
  10096. #include <ctype.h>
  10097. #include <stdint.h>
  10098. #include <string.h>
  10099. #include <time.h>
  10100. struct upb_json_printer {
  10101. upb_sink input_;
  10102. /* BytesSink closure. */
  10103. void *subc_;
  10104. upb_bytessink output_;
  10105. /* We track the depth so that we know when to emit startstr/endstr on the
  10106. * output. */
  10107. int depth_;
  10108. /* Have we emitted the first element? This state is necessary to emit commas
  10109. * without leaving a trailing comma in arrays/maps. We keep this state per
  10110. * frame depth.
  10111. *
  10112. * Why max_depth * 2? UPB_MAX_HANDLER_DEPTH counts depth as nested messages.
  10113. * We count frames (contexts in which we separate elements by commas) as both
  10114. * repeated fields and messages (maps), and the worst case is a
  10115. * message->repeated field->submessage->repeated field->... nesting. */
  10116. bool first_elem_[UPB_MAX_HANDLER_DEPTH * 2];
  10117. /* To print timestamp, printer needs to cache its seconds and nanos values
  10118. * and convert them when ending timestamp message. See comments of
  10119. * printer_sethandlers_timestamp for more detail. */
  10120. int64_t seconds;
  10121. int32_t nanos;
  10122. };
  10123. /* StringPiece; a pointer plus a length. */
  10124. typedef struct {
  10125. char *ptr;
  10126. size_t len;
  10127. } strpc;
  10128. void freestrpc(void *ptr) {
  10129. strpc *pc = ptr;
  10130. upb_gfree(pc->ptr);
  10131. upb_gfree(pc);
  10132. }
  10133. typedef struct {
  10134. bool preserve_fieldnames;
  10135. } upb_json_printercache;
  10136. /* Convert fielddef name to JSON name and return as a string piece. */
  10137. strpc *newstrpc(upb_handlers *h, const upb_fielddef *f,
  10138. bool preserve_fieldnames) {
  10139. /* TODO(haberman): handle malloc failure. */
  10140. strpc *ret = upb_gmalloc(sizeof(*ret));
  10141. if (preserve_fieldnames) {
  10142. ret->ptr = upb_gstrdup(upb_fielddef_name(f));
  10143. ret->len = strlen(ret->ptr);
  10144. } else {
  10145. size_t len;
  10146. ret->len = upb_fielddef_getjsonname(f, NULL, 0);
  10147. ret->ptr = upb_gmalloc(ret->len);
  10148. len = upb_fielddef_getjsonname(f, ret->ptr, ret->len);
  10149. UPB_ASSERT(len == ret->len);
  10150. ret->len--; /* NULL */
  10151. }
  10152. upb_handlers_addcleanup(h, ret, freestrpc);
  10153. return ret;
  10154. }
  10155. /* Convert a null-terminated const char* to a string piece. */
  10156. strpc *newstrpc_str(upb_handlers *h, const char * str) {
  10157. strpc * ret = upb_gmalloc(sizeof(*ret));
  10158. ret->ptr = upb_gstrdup(str);
  10159. ret->len = strlen(str);
  10160. upb_handlers_addcleanup(h, ret, freestrpc);
  10161. return ret;
  10162. }
  10163. /* ------------ JSON string printing: values, maps, arrays ------------------ */
  10164. static void print_data(
  10165. upb_json_printer *p, const char *buf, unsigned int len) {
  10166. /* TODO: Will need to change if we support pushback from the sink. */
  10167. size_t n = upb_bytessink_putbuf(p->output_, p->subc_, buf, len, NULL);
  10168. UPB_ASSERT(n == len);
  10169. }
  10170. static void print_comma(upb_json_printer *p) {
  10171. if (!p->first_elem_[p->depth_]) {
  10172. print_data(p, ",", 1);
  10173. }
  10174. p->first_elem_[p->depth_] = false;
  10175. }
  10176. /* Helpers that print properly formatted elements to the JSON output stream. */
  10177. /* Used for escaping control chars in strings. */
  10178. static const char kControlCharLimit = 0x20;
  10179. UPB_INLINE bool is_json_escaped(char c) {
  10180. /* See RFC 4627. */
  10181. unsigned char uc = (unsigned char)c;
  10182. return uc < kControlCharLimit || uc == '"' || uc == '\\';
  10183. }
  10184. UPB_INLINE const char* json_nice_escape(char c) {
  10185. switch (c) {
  10186. case '"': return "\\\"";
  10187. case '\\': return "\\\\";
  10188. case '\b': return "\\b";
  10189. case '\f': return "\\f";
  10190. case '\n': return "\\n";
  10191. case '\r': return "\\r";
  10192. case '\t': return "\\t";
  10193. default: return NULL;
  10194. }
  10195. }
  10196. /* Write a properly escaped string chunk. The surrounding quotes are *not*
  10197. * printed; this is so that the caller has the option of emitting the string
  10198. * content in chunks. */
  10199. static void putstring(upb_json_printer *p, const char *buf, unsigned int len) {
  10200. const char* unescaped_run = NULL;
  10201. unsigned int i;
  10202. for (i = 0; i < len; i++) {
  10203. char c = buf[i];
  10204. /* Handle escaping. */
  10205. if (is_json_escaped(c)) {
  10206. /* Use a "nice" escape, like \n, if one exists for this character. */
  10207. const char* escape = json_nice_escape(c);
  10208. /* If we don't have a specific 'nice' escape code, use a \uXXXX-style
  10209. * escape. */
  10210. char escape_buf[8];
  10211. if (!escape) {
  10212. unsigned char byte = (unsigned char)c;
  10213. _upb_snprintf(escape_buf, sizeof(escape_buf), "\\u%04x", (int)byte);
  10214. escape = escape_buf;
  10215. }
  10216. /* N.B. that we assume that the input encoding is equal to the output
  10217. * encoding (both UTF-8 for now), so for chars >= 0x20 and != \, ", we
  10218. * can simply pass the bytes through. */
  10219. /* If there's a current run of unescaped chars, print that run first. */
  10220. if (unescaped_run) {
  10221. print_data(p, unescaped_run, &buf[i] - unescaped_run);
  10222. unescaped_run = NULL;
  10223. }
  10224. /* Then print the escape code. */
  10225. print_data(p, escape, strlen(escape));
  10226. } else {
  10227. /* Add to the current unescaped run of characters. */
  10228. if (unescaped_run == NULL) {
  10229. unescaped_run = &buf[i];
  10230. }
  10231. }
  10232. }
  10233. /* If the string ended in a run of unescaped characters, print that last run. */
  10234. if (unescaped_run) {
  10235. print_data(p, unescaped_run, &buf[len] - unescaped_run);
  10236. }
  10237. }
  10238. #define CHKLENGTH(x) if (!(x)) return -1;
  10239. /* Helpers that format floating point values according to our custom formats.
  10240. * Right now we use %.8g and %.17g for float/double, respectively, to match
  10241. * proto2::util::JsonFormat's defaults. May want to change this later. */
  10242. const char neginf[] = "\"-Infinity\"";
  10243. const char inf[] = "\"Infinity\"";
  10244. static size_t fmt_double(double val, char* buf, size_t length) {
  10245. if (val == UPB_INFINITY) {
  10246. CHKLENGTH(length >= strlen(inf));
  10247. strcpy(buf, inf);
  10248. return strlen(inf);
  10249. } else if (val == -UPB_INFINITY) {
  10250. CHKLENGTH(length >= strlen(neginf));
  10251. strcpy(buf, neginf);
  10252. return strlen(neginf);
  10253. } else {
  10254. size_t n = _upb_snprintf(buf, length, "%.17g", val);
  10255. CHKLENGTH(n > 0 && n < length);
  10256. return n;
  10257. }
  10258. }
  10259. static size_t fmt_float(float val, char* buf, size_t length) {
  10260. size_t n = _upb_snprintf(buf, length, "%.8g", val);
  10261. CHKLENGTH(n > 0 && n < length);
  10262. return n;
  10263. }
  10264. static size_t fmt_bool(bool val, char* buf, size_t length) {
  10265. size_t n = _upb_snprintf(buf, length, "%s", (val ? "true" : "false"));
  10266. CHKLENGTH(n > 0 && n < length);
  10267. return n;
  10268. }
  10269. static size_t fmt_int64_as_number(long long val, char* buf, size_t length) {
  10270. size_t n = _upb_snprintf(buf, length, "%lld", val);
  10271. CHKLENGTH(n > 0 && n < length);
  10272. return n;
  10273. }
  10274. static size_t fmt_uint64_as_number(
  10275. unsigned long long val, char* buf, size_t length) {
  10276. size_t n = _upb_snprintf(buf, length, "%llu", val);
  10277. CHKLENGTH(n > 0 && n < length);
  10278. return n;
  10279. }
  10280. static size_t fmt_int64_as_string(long long val, char* buf, size_t length) {
  10281. size_t n = _upb_snprintf(buf, length, "\"%lld\"", val);
  10282. CHKLENGTH(n > 0 && n < length);
  10283. return n;
  10284. }
  10285. static size_t fmt_uint64_as_string(
  10286. unsigned long long val, char* buf, size_t length) {
  10287. size_t n = _upb_snprintf(buf, length, "\"%llu\"", val);
  10288. CHKLENGTH(n > 0 && n < length);
  10289. return n;
  10290. }
  10291. /* Print a map key given a field name. Called by scalar field handlers and by
  10292. * startseq for repeated fields. */
  10293. static bool putkey(void *closure, const void *handler_data) {
  10294. upb_json_printer *p = closure;
  10295. const strpc *key = handler_data;
  10296. print_comma(p);
  10297. print_data(p, "\"", 1);
  10298. putstring(p, key->ptr, key->len);
  10299. print_data(p, "\":", 2);
  10300. return true;
  10301. }
  10302. #define CHKFMT(val) if ((val) == (size_t)-1) return false;
  10303. #define CHK(val) if (!(val)) return false;
  10304. #define TYPE_HANDLERS(type, fmt_func) \
  10305. static bool put##type(void *closure, const void *handler_data, type val) { \
  10306. upb_json_printer *p = closure; \
  10307. char data[64]; \
  10308. size_t length = fmt_func(val, data, sizeof(data)); \
  10309. UPB_UNUSED(handler_data); \
  10310. CHKFMT(length); \
  10311. print_data(p, data, length); \
  10312. return true; \
  10313. } \
  10314. static bool scalar_##type(void *closure, const void *handler_data, \
  10315. type val) { \
  10316. CHK(putkey(closure, handler_data)); \
  10317. CHK(put##type(closure, handler_data, val)); \
  10318. return true; \
  10319. } \
  10320. static bool repeated_##type(void *closure, const void *handler_data, \
  10321. type val) { \
  10322. upb_json_printer *p = closure; \
  10323. print_comma(p); \
  10324. CHK(put##type(closure, handler_data, val)); \
  10325. return true; \
  10326. }
  10327. #define TYPE_HANDLERS_MAPKEY(type, fmt_func) \
  10328. static bool putmapkey_##type(void *closure, const void *handler_data, \
  10329. type val) { \
  10330. upb_json_printer *p = closure; \
  10331. char data[64]; \
  10332. size_t length = fmt_func(val, data, sizeof(data)); \
  10333. UPB_UNUSED(handler_data); \
  10334. print_data(p, "\"", 1); \
  10335. print_data(p, data, length); \
  10336. print_data(p, "\":", 2); \
  10337. return true; \
  10338. }
  10339. TYPE_HANDLERS(double, fmt_double)
  10340. TYPE_HANDLERS(float, fmt_float)
  10341. TYPE_HANDLERS(bool, fmt_bool)
  10342. TYPE_HANDLERS(int32_t, fmt_int64_as_number)
  10343. TYPE_HANDLERS(uint32_t, fmt_int64_as_number)
  10344. TYPE_HANDLERS(int64_t, fmt_int64_as_string)
  10345. TYPE_HANDLERS(uint64_t, fmt_uint64_as_string)
  10346. /* double and float are not allowed to be map keys. */
  10347. TYPE_HANDLERS_MAPKEY(bool, fmt_bool)
  10348. TYPE_HANDLERS_MAPKEY(int32_t, fmt_int64_as_number)
  10349. TYPE_HANDLERS_MAPKEY(uint32_t, fmt_int64_as_number)
  10350. TYPE_HANDLERS_MAPKEY(int64_t, fmt_int64_as_number)
  10351. TYPE_HANDLERS_MAPKEY(uint64_t, fmt_uint64_as_number)
  10352. #undef TYPE_HANDLERS
  10353. #undef TYPE_HANDLERS_MAPKEY
  10354. typedef struct {
  10355. void *keyname;
  10356. const upb_enumdef *enumdef;
  10357. } EnumHandlerData;
  10358. static bool scalar_enum(void *closure, const void *handler_data,
  10359. int32_t val) {
  10360. const EnumHandlerData *hd = handler_data;
  10361. upb_json_printer *p = closure;
  10362. const char *symbolic_name;
  10363. CHK(putkey(closure, hd->keyname));
  10364. symbolic_name = upb_enumdef_iton(hd->enumdef, val);
  10365. if (symbolic_name) {
  10366. print_data(p, "\"", 1);
  10367. putstring(p, symbolic_name, strlen(symbolic_name));
  10368. print_data(p, "\"", 1);
  10369. } else {
  10370. putint32_t(closure, NULL, val);
  10371. }
  10372. return true;
  10373. }
  10374. static void print_enum_symbolic_name(upb_json_printer *p,
  10375. const upb_enumdef *def,
  10376. int32_t val) {
  10377. const char *symbolic_name = upb_enumdef_iton(def, val);
  10378. if (symbolic_name) {
  10379. print_data(p, "\"", 1);
  10380. putstring(p, symbolic_name, strlen(symbolic_name));
  10381. print_data(p, "\"", 1);
  10382. } else {
  10383. putint32_t(p, NULL, val);
  10384. }
  10385. }
  10386. static bool repeated_enum(void *closure, const void *handler_data,
  10387. int32_t val) {
  10388. const EnumHandlerData *hd = handler_data;
  10389. upb_json_printer *p = closure;
  10390. print_comma(p);
  10391. print_enum_symbolic_name(p, hd->enumdef, val);
  10392. return true;
  10393. }
  10394. static bool mapvalue_enum(void *closure, const void *handler_data,
  10395. int32_t val) {
  10396. const EnumHandlerData *hd = handler_data;
  10397. upb_json_printer *p = closure;
  10398. print_enum_symbolic_name(p, hd->enumdef, val);
  10399. return true;
  10400. }
  10401. static void *scalar_startsubmsg(void *closure, const void *handler_data) {
  10402. return putkey(closure, handler_data) ? closure : UPB_BREAK;
  10403. }
  10404. static void *repeated_startsubmsg(void *closure, const void *handler_data) {
  10405. upb_json_printer *p = closure;
  10406. UPB_UNUSED(handler_data);
  10407. print_comma(p);
  10408. return closure;
  10409. }
  10410. static void start_frame(upb_json_printer *p) {
  10411. p->depth_++;
  10412. p->first_elem_[p->depth_] = true;
  10413. print_data(p, "{", 1);
  10414. }
  10415. static void end_frame(upb_json_printer *p) {
  10416. print_data(p, "}", 1);
  10417. p->depth_--;
  10418. }
  10419. static bool printer_startmsg(void *closure, const void *handler_data) {
  10420. upb_json_printer *p = closure;
  10421. UPB_UNUSED(handler_data);
  10422. if (p->depth_ == 0) {
  10423. upb_bytessink_start(p->output_, 0, &p->subc_);
  10424. }
  10425. start_frame(p);
  10426. return true;
  10427. }
  10428. static bool printer_endmsg(void *closure, const void *handler_data, upb_status *s) {
  10429. upb_json_printer *p = closure;
  10430. UPB_UNUSED(handler_data);
  10431. UPB_UNUSED(s);
  10432. end_frame(p);
  10433. if (p->depth_ == 0) {
  10434. upb_bytessink_end(p->output_);
  10435. }
  10436. return true;
  10437. }
  10438. static void *startseq(void *closure, const void *handler_data) {
  10439. upb_json_printer *p = closure;
  10440. CHK(putkey(closure, handler_data));
  10441. p->depth_++;
  10442. p->first_elem_[p->depth_] = true;
  10443. print_data(p, "[", 1);
  10444. return closure;
  10445. }
  10446. static bool endseq(void *closure, const void *handler_data) {
  10447. upb_json_printer *p = closure;
  10448. UPB_UNUSED(handler_data);
  10449. print_data(p, "]", 1);
  10450. p->depth_--;
  10451. return true;
  10452. }
  10453. static void *startmap(void *closure, const void *handler_data) {
  10454. upb_json_printer *p = closure;
  10455. CHK(putkey(closure, handler_data));
  10456. p->depth_++;
  10457. p->first_elem_[p->depth_] = true;
  10458. print_data(p, "{", 1);
  10459. return closure;
  10460. }
  10461. static bool endmap(void *closure, const void *handler_data) {
  10462. upb_json_printer *p = closure;
  10463. UPB_UNUSED(handler_data);
  10464. print_data(p, "}", 1);
  10465. p->depth_--;
  10466. return true;
  10467. }
  10468. static size_t putstr(void *closure, const void *handler_data, const char *str,
  10469. size_t len, const upb_bufhandle *handle) {
  10470. upb_json_printer *p = closure;
  10471. UPB_UNUSED(handler_data);
  10472. UPB_UNUSED(handle);
  10473. putstring(p, str, len);
  10474. return len;
  10475. }
  10476. /* This has to Base64 encode the bytes, because JSON has no "bytes" type. */
  10477. static size_t putbytes(void *closure, const void *handler_data, const char *str,
  10478. size_t len, const upb_bufhandle *handle) {
  10479. upb_json_printer *p = closure;
  10480. /* This is the regular base64, not the "web-safe" version. */
  10481. static const char base64[] =
  10482. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  10483. /* Base64-encode. */
  10484. char data[16000];
  10485. const char *limit = data + sizeof(data);
  10486. const unsigned char *from = (const unsigned char*)str;
  10487. char *to = data;
  10488. size_t remaining = len;
  10489. size_t bytes;
  10490. UPB_UNUSED(handler_data);
  10491. UPB_UNUSED(handle);
  10492. print_data(p, "\"", 1);
  10493. while (remaining > 2) {
  10494. if (limit - to < 4) {
  10495. bytes = to - data;
  10496. putstring(p, data, bytes);
  10497. to = data;
  10498. }
  10499. to[0] = base64[from[0] >> 2];
  10500. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  10501. to[2] = base64[((from[1] & 0xf) << 2) | (from[2] >> 6)];
  10502. to[3] = base64[from[2] & 0x3f];
  10503. remaining -= 3;
  10504. to += 4;
  10505. from += 3;
  10506. }
  10507. switch (remaining) {
  10508. case 2:
  10509. to[0] = base64[from[0] >> 2];
  10510. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  10511. to[2] = base64[(from[1] & 0xf) << 2];
  10512. to[3] = '=';
  10513. to += 4;
  10514. from += 2;
  10515. break;
  10516. case 1:
  10517. to[0] = base64[from[0] >> 2];
  10518. to[1] = base64[((from[0] & 0x3) << 4)];
  10519. to[2] = '=';
  10520. to[3] = '=';
  10521. to += 4;
  10522. from += 1;
  10523. break;
  10524. }
  10525. bytes = to - data;
  10526. putstring(p, data, bytes);
  10527. print_data(p, "\"", 1);
  10528. return len;
  10529. }
  10530. static void *scalar_startstr(void *closure, const void *handler_data,
  10531. size_t size_hint) {
  10532. upb_json_printer *p = closure;
  10533. UPB_UNUSED(handler_data);
  10534. UPB_UNUSED(size_hint);
  10535. CHK(putkey(closure, handler_data));
  10536. print_data(p, "\"", 1);
  10537. return p;
  10538. }
  10539. static size_t scalar_str(void *closure, const void *handler_data,
  10540. const char *str, size_t len,
  10541. const upb_bufhandle *handle) {
  10542. CHK(putstr(closure, handler_data, str, len, handle));
  10543. return len;
  10544. }
  10545. static bool scalar_endstr(void *closure, const void *handler_data) {
  10546. upb_json_printer *p = closure;
  10547. UPB_UNUSED(handler_data);
  10548. print_data(p, "\"", 1);
  10549. return true;
  10550. }
  10551. static void *repeated_startstr(void *closure, const void *handler_data,
  10552. size_t size_hint) {
  10553. upb_json_printer *p = closure;
  10554. UPB_UNUSED(handler_data);
  10555. UPB_UNUSED(size_hint);
  10556. print_comma(p);
  10557. print_data(p, "\"", 1);
  10558. return p;
  10559. }
  10560. static size_t repeated_str(void *closure, const void *handler_data,
  10561. const char *str, size_t len,
  10562. const upb_bufhandle *handle) {
  10563. CHK(putstr(closure, handler_data, str, len, handle));
  10564. return len;
  10565. }
  10566. static bool repeated_endstr(void *closure, const void *handler_data) {
  10567. upb_json_printer *p = closure;
  10568. UPB_UNUSED(handler_data);
  10569. print_data(p, "\"", 1);
  10570. return true;
  10571. }
  10572. static void *mapkeyval_startstr(void *closure, const void *handler_data,
  10573. size_t size_hint) {
  10574. upb_json_printer *p = closure;
  10575. UPB_UNUSED(handler_data);
  10576. UPB_UNUSED(size_hint);
  10577. print_data(p, "\"", 1);
  10578. return p;
  10579. }
  10580. static size_t mapkey_str(void *closure, const void *handler_data,
  10581. const char *str, size_t len,
  10582. const upb_bufhandle *handle) {
  10583. CHK(putstr(closure, handler_data, str, len, handle));
  10584. return len;
  10585. }
  10586. static bool mapkey_endstr(void *closure, const void *handler_data) {
  10587. upb_json_printer *p = closure;
  10588. UPB_UNUSED(handler_data);
  10589. print_data(p, "\":", 2);
  10590. return true;
  10591. }
  10592. static bool mapvalue_endstr(void *closure, const void *handler_data) {
  10593. upb_json_printer *p = closure;
  10594. UPB_UNUSED(handler_data);
  10595. print_data(p, "\"", 1);
  10596. return true;
  10597. }
  10598. static size_t scalar_bytes(void *closure, const void *handler_data,
  10599. const char *str, size_t len,
  10600. const upb_bufhandle *handle) {
  10601. CHK(putkey(closure, handler_data));
  10602. CHK(putbytes(closure, handler_data, str, len, handle));
  10603. return len;
  10604. }
  10605. static size_t repeated_bytes(void *closure, const void *handler_data,
  10606. const char *str, size_t len,
  10607. const upb_bufhandle *handle) {
  10608. upb_json_printer *p = closure;
  10609. print_comma(p);
  10610. CHK(putbytes(closure, handler_data, str, len, handle));
  10611. return len;
  10612. }
  10613. static size_t mapkey_bytes(void *closure, const void *handler_data,
  10614. const char *str, size_t len,
  10615. const upb_bufhandle *handle) {
  10616. upb_json_printer *p = closure;
  10617. CHK(putbytes(closure, handler_data, str, len, handle));
  10618. print_data(p, ":", 1);
  10619. return len;
  10620. }
  10621. static void set_enum_hd(upb_handlers *h,
  10622. const upb_fielddef *f,
  10623. bool preserve_fieldnames,
  10624. upb_handlerattr *attr) {
  10625. EnumHandlerData *hd = upb_gmalloc(sizeof(EnumHandlerData));
  10626. hd->enumdef = upb_fielddef_enumsubdef(f);
  10627. hd->keyname = newstrpc(h, f, preserve_fieldnames);
  10628. upb_handlers_addcleanup(h, hd, upb_gfree);
  10629. attr->handler_data = hd;
  10630. }
  10631. /* Set up handlers for a mapentry submessage (i.e., an individual key/value pair
  10632. * in a map).
  10633. *
  10634. * TODO: Handle missing key, missing value, out-of-order key/value, or repeated
  10635. * key or value cases properly. The right way to do this is to allocate a
  10636. * temporary structure at the start of a mapentry submessage, store key and
  10637. * value data in it as key and value handlers are called, and then print the
  10638. * key/value pair once at the end of the submessage. If we don't do this, we
  10639. * should at least detect the case and throw an error. However, so far all of
  10640. * our sources that emit mapentry messages do so canonically (with one key
  10641. * field, and then one value field), so this is not a pressing concern at the
  10642. * moment. */
  10643. void printer_sethandlers_mapentry(const void *closure, bool preserve_fieldnames,
  10644. upb_handlers *h) {
  10645. const upb_msgdef *md = upb_handlers_msgdef(h);
  10646. /* A mapentry message is printed simply as '"key": value'. Rather than
  10647. * special-case key and value for every type below, we just handle both
  10648. * fields explicitly here. */
  10649. const upb_fielddef* key_field = upb_msgdef_itof(md, UPB_MAPENTRY_KEY);
  10650. const upb_fielddef* value_field = upb_msgdef_itof(md, UPB_MAPENTRY_VALUE);
  10651. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  10652. UPB_UNUSED(closure);
  10653. switch (upb_fielddef_type(key_field)) {
  10654. case UPB_TYPE_INT32:
  10655. upb_handlers_setint32(h, key_field, putmapkey_int32_t, &empty_attr);
  10656. break;
  10657. case UPB_TYPE_INT64:
  10658. upb_handlers_setint64(h, key_field, putmapkey_int64_t, &empty_attr);
  10659. break;
  10660. case UPB_TYPE_UINT32:
  10661. upb_handlers_setuint32(h, key_field, putmapkey_uint32_t, &empty_attr);
  10662. break;
  10663. case UPB_TYPE_UINT64:
  10664. upb_handlers_setuint64(h, key_field, putmapkey_uint64_t, &empty_attr);
  10665. break;
  10666. case UPB_TYPE_BOOL:
  10667. upb_handlers_setbool(h, key_field, putmapkey_bool, &empty_attr);
  10668. break;
  10669. case UPB_TYPE_STRING:
  10670. upb_handlers_setstartstr(h, key_field, mapkeyval_startstr, &empty_attr);
  10671. upb_handlers_setstring(h, key_field, mapkey_str, &empty_attr);
  10672. upb_handlers_setendstr(h, key_field, mapkey_endstr, &empty_attr);
  10673. break;
  10674. case UPB_TYPE_BYTES:
  10675. upb_handlers_setstring(h, key_field, mapkey_bytes, &empty_attr);
  10676. break;
  10677. default:
  10678. UPB_ASSERT(false);
  10679. break;
  10680. }
  10681. switch (upb_fielddef_type(value_field)) {
  10682. case UPB_TYPE_INT32:
  10683. upb_handlers_setint32(h, value_field, putint32_t, &empty_attr);
  10684. break;
  10685. case UPB_TYPE_INT64:
  10686. upb_handlers_setint64(h, value_field, putint64_t, &empty_attr);
  10687. break;
  10688. case UPB_TYPE_UINT32:
  10689. upb_handlers_setuint32(h, value_field, putuint32_t, &empty_attr);
  10690. break;
  10691. case UPB_TYPE_UINT64:
  10692. upb_handlers_setuint64(h, value_field, putuint64_t, &empty_attr);
  10693. break;
  10694. case UPB_TYPE_BOOL:
  10695. upb_handlers_setbool(h, value_field, putbool, &empty_attr);
  10696. break;
  10697. case UPB_TYPE_FLOAT:
  10698. upb_handlers_setfloat(h, value_field, putfloat, &empty_attr);
  10699. break;
  10700. case UPB_TYPE_DOUBLE:
  10701. upb_handlers_setdouble(h, value_field, putdouble, &empty_attr);
  10702. break;
  10703. case UPB_TYPE_STRING:
  10704. upb_handlers_setstartstr(h, value_field, mapkeyval_startstr, &empty_attr);
  10705. upb_handlers_setstring(h, value_field, putstr, &empty_attr);
  10706. upb_handlers_setendstr(h, value_field, mapvalue_endstr, &empty_attr);
  10707. break;
  10708. case UPB_TYPE_BYTES:
  10709. upb_handlers_setstring(h, value_field, putbytes, &empty_attr);
  10710. break;
  10711. case UPB_TYPE_ENUM: {
  10712. upb_handlerattr enum_attr = UPB_HANDLERATTR_INIT;
  10713. set_enum_hd(h, value_field, preserve_fieldnames, &enum_attr);
  10714. upb_handlers_setint32(h, value_field, mapvalue_enum, &enum_attr);
  10715. break;
  10716. }
  10717. case UPB_TYPE_MESSAGE:
  10718. /* No handler necessary -- the submsg handlers will print the message
  10719. * as appropriate. */
  10720. break;
  10721. }
  10722. }
  10723. static bool putseconds(void *closure, const void *handler_data,
  10724. int64_t seconds) {
  10725. upb_json_printer *p = closure;
  10726. p->seconds = seconds;
  10727. UPB_UNUSED(handler_data);
  10728. return true;
  10729. }
  10730. static bool putnanos(void *closure, const void *handler_data,
  10731. int32_t nanos) {
  10732. upb_json_printer *p = closure;
  10733. p->nanos = nanos;
  10734. UPB_UNUSED(handler_data);
  10735. return true;
  10736. }
  10737. static void *scalar_startstr_nokey(void *closure, const void *handler_data,
  10738. size_t size_hint) {
  10739. upb_json_printer *p = closure;
  10740. UPB_UNUSED(handler_data);
  10741. UPB_UNUSED(size_hint);
  10742. print_data(p, "\"", 1);
  10743. return p;
  10744. }
  10745. static size_t putstr_nokey(void *closure, const void *handler_data,
  10746. const char *str, size_t len,
  10747. const upb_bufhandle *handle) {
  10748. upb_json_printer *p = closure;
  10749. UPB_UNUSED(handler_data);
  10750. UPB_UNUSED(handle);
  10751. print_data(p, "\"", 1);
  10752. putstring(p, str, len);
  10753. print_data(p, "\"", 1);
  10754. return len + 2;
  10755. }
  10756. static void *startseq_nokey(void *closure, const void *handler_data) {
  10757. upb_json_printer *p = closure;
  10758. UPB_UNUSED(handler_data);
  10759. p->depth_++;
  10760. p->first_elem_[p->depth_] = true;
  10761. print_data(p, "[", 1);
  10762. return closure;
  10763. }
  10764. static void *startseq_fieldmask(void *closure, const void *handler_data) {
  10765. upb_json_printer *p = closure;
  10766. UPB_UNUSED(handler_data);
  10767. p->depth_++;
  10768. p->first_elem_[p->depth_] = true;
  10769. return closure;
  10770. }
  10771. static bool endseq_fieldmask(void *closure, const void *handler_data) {
  10772. upb_json_printer *p = closure;
  10773. UPB_UNUSED(handler_data);
  10774. p->depth_--;
  10775. return true;
  10776. }
  10777. static void *repeated_startstr_fieldmask(
  10778. void *closure, const void *handler_data,
  10779. size_t size_hint) {
  10780. upb_json_printer *p = closure;
  10781. UPB_UNUSED(handler_data);
  10782. UPB_UNUSED(size_hint);
  10783. print_comma(p);
  10784. return p;
  10785. }
  10786. static size_t repeated_str_fieldmask(
  10787. void *closure, const void *handler_data,
  10788. const char *str, size_t len,
  10789. const upb_bufhandle *handle) {
  10790. const char* limit = str + len;
  10791. bool upper = false;
  10792. size_t result_len = 0;
  10793. for (; str < limit; str++) {
  10794. if (*str == '_') {
  10795. upper = true;
  10796. continue;
  10797. }
  10798. if (upper && *str >= 'a' && *str <= 'z') {
  10799. char upper_char = toupper(*str);
  10800. CHK(putstr(closure, handler_data, &upper_char, 1, handle));
  10801. } else {
  10802. CHK(putstr(closure, handler_data, str, 1, handle));
  10803. }
  10804. upper = false;
  10805. result_len++;
  10806. }
  10807. return result_len;
  10808. }
  10809. static void *startmap_nokey(void *closure, const void *handler_data) {
  10810. upb_json_printer *p = closure;
  10811. UPB_UNUSED(handler_data);
  10812. p->depth_++;
  10813. p->first_elem_[p->depth_] = true;
  10814. print_data(p, "{", 1);
  10815. return closure;
  10816. }
  10817. static bool putnull(void *closure, const void *handler_data,
  10818. int32_t null) {
  10819. upb_json_printer *p = closure;
  10820. print_data(p, "null", 4);
  10821. UPB_UNUSED(handler_data);
  10822. UPB_UNUSED(null);
  10823. return true;
  10824. }
  10825. static bool printer_startdurationmsg(void *closure, const void *handler_data) {
  10826. upb_json_printer *p = closure;
  10827. UPB_UNUSED(handler_data);
  10828. if (p->depth_ == 0) {
  10829. upb_bytessink_start(p->output_, 0, &p->subc_);
  10830. }
  10831. return true;
  10832. }
  10833. #define UPB_DURATION_MAX_JSON_LEN 23
  10834. #define UPB_DURATION_MAX_NANO_LEN 9
  10835. static bool printer_enddurationmsg(void *closure, const void *handler_data,
  10836. upb_status *s) {
  10837. upb_json_printer *p = closure;
  10838. char buffer[UPB_DURATION_MAX_JSON_LEN];
  10839. size_t base_len;
  10840. size_t curr;
  10841. size_t i;
  10842. memset(buffer, 0, UPB_DURATION_MAX_JSON_LEN);
  10843. if (p->seconds < -315576000000) {
  10844. upb_status_seterrf(s, "error parsing duration: "
  10845. "minimum acceptable value is "
  10846. "-315576000000");
  10847. return false;
  10848. }
  10849. if (p->seconds > 315576000000) {
  10850. upb_status_seterrf(s, "error serializing duration: "
  10851. "maximum acceptable value is "
  10852. "315576000000");
  10853. return false;
  10854. }
  10855. _upb_snprintf(buffer, sizeof(buffer), "%ld", (long)p->seconds);
  10856. base_len = strlen(buffer);
  10857. if (p->nanos != 0) {
  10858. char nanos_buffer[UPB_DURATION_MAX_NANO_LEN + 3];
  10859. _upb_snprintf(nanos_buffer, sizeof(nanos_buffer), "%.9f",
  10860. p->nanos / 1000000000.0);
  10861. /* Remove trailing 0. */
  10862. for (i = UPB_DURATION_MAX_NANO_LEN + 2;
  10863. nanos_buffer[i] == '0'; i--) {
  10864. nanos_buffer[i] = 0;
  10865. }
  10866. strcpy(buffer + base_len, nanos_buffer + 1);
  10867. }
  10868. curr = strlen(buffer);
  10869. strcpy(buffer + curr, "s");
  10870. p->seconds = 0;
  10871. p->nanos = 0;
  10872. print_data(p, "\"", 1);
  10873. print_data(p, buffer, strlen(buffer));
  10874. print_data(p, "\"", 1);
  10875. if (p->depth_ == 0) {
  10876. upb_bytessink_end(p->output_);
  10877. }
  10878. UPB_UNUSED(handler_data);
  10879. return true;
  10880. }
  10881. static bool printer_starttimestampmsg(void *closure, const void *handler_data) {
  10882. upb_json_printer *p = closure;
  10883. UPB_UNUSED(handler_data);
  10884. if (p->depth_ == 0) {
  10885. upb_bytessink_start(p->output_, 0, &p->subc_);
  10886. }
  10887. return true;
  10888. }
  10889. #define UPB_TIMESTAMP_MAX_JSON_LEN 31
  10890. #define UPB_TIMESTAMP_BEFORE_NANO_LEN 19
  10891. #define UPB_TIMESTAMP_MAX_NANO_LEN 9
  10892. static bool printer_endtimestampmsg(void *closure, const void *handler_data,
  10893. upb_status *s) {
  10894. upb_json_printer *p = closure;
  10895. char buffer[UPB_TIMESTAMP_MAX_JSON_LEN];
  10896. time_t time = p->seconds;
  10897. size_t curr;
  10898. size_t i;
  10899. size_t year_length =
  10900. strftime(buffer, UPB_TIMESTAMP_MAX_JSON_LEN, "%Y", gmtime(&time));
  10901. if (p->seconds < -62135596800) {
  10902. upb_status_seterrf(s, "error parsing timestamp: "
  10903. "minimum acceptable value is "
  10904. "0001-01-01T00:00:00Z");
  10905. return false;
  10906. }
  10907. if (p->seconds > 253402300799) {
  10908. upb_status_seterrf(s, "error parsing timestamp: "
  10909. "maximum acceptable value is "
  10910. "9999-12-31T23:59:59Z");
  10911. return false;
  10912. }
  10913. /* strftime doesn't guarantee 4 digits for year. Prepend 0 by ourselves. */
  10914. for (i = 0; i < 4 - year_length; i++) {
  10915. buffer[i] = '0';
  10916. }
  10917. strftime(buffer + (4 - year_length), UPB_TIMESTAMP_MAX_JSON_LEN,
  10918. "%Y-%m-%dT%H:%M:%S", gmtime(&time));
  10919. if (p->nanos != 0) {
  10920. char nanos_buffer[UPB_TIMESTAMP_MAX_NANO_LEN + 3];
  10921. _upb_snprintf(nanos_buffer, sizeof(nanos_buffer), "%.9f",
  10922. p->nanos / 1000000000.0);
  10923. /* Remove trailing 0. */
  10924. for (i = UPB_TIMESTAMP_MAX_NANO_LEN + 2;
  10925. nanos_buffer[i] == '0'; i--) {
  10926. nanos_buffer[i] = 0;
  10927. }
  10928. strcpy(buffer + UPB_TIMESTAMP_BEFORE_NANO_LEN, nanos_buffer + 1);
  10929. }
  10930. curr = strlen(buffer);
  10931. strcpy(buffer + curr, "Z");
  10932. p->seconds = 0;
  10933. p->nanos = 0;
  10934. print_data(p, "\"", 1);
  10935. print_data(p, buffer, strlen(buffer));
  10936. print_data(p, "\"", 1);
  10937. if (p->depth_ == 0) {
  10938. upb_bytessink_end(p->output_);
  10939. }
  10940. UPB_UNUSED(handler_data);
  10941. UPB_UNUSED(s);
  10942. return true;
  10943. }
  10944. static bool printer_startmsg_noframe(void *closure, const void *handler_data) {
  10945. upb_json_printer *p = closure;
  10946. UPB_UNUSED(handler_data);
  10947. if (p->depth_ == 0) {
  10948. upb_bytessink_start(p->output_, 0, &p->subc_);
  10949. }
  10950. return true;
  10951. }
  10952. static bool printer_endmsg_noframe(
  10953. void *closure, const void *handler_data, upb_status *s) {
  10954. upb_json_printer *p = closure;
  10955. UPB_UNUSED(handler_data);
  10956. UPB_UNUSED(s);
  10957. if (p->depth_ == 0) {
  10958. upb_bytessink_end(p->output_);
  10959. }
  10960. return true;
  10961. }
  10962. static bool printer_startmsg_fieldmask(
  10963. void *closure, const void *handler_data) {
  10964. upb_json_printer *p = closure;
  10965. UPB_UNUSED(handler_data);
  10966. if (p->depth_ == 0) {
  10967. upb_bytessink_start(p->output_, 0, &p->subc_);
  10968. }
  10969. print_data(p, "\"", 1);
  10970. return true;
  10971. }
  10972. static bool printer_endmsg_fieldmask(
  10973. void *closure, const void *handler_data, upb_status *s) {
  10974. upb_json_printer *p = closure;
  10975. UPB_UNUSED(handler_data);
  10976. UPB_UNUSED(s);
  10977. print_data(p, "\"", 1);
  10978. if (p->depth_ == 0) {
  10979. upb_bytessink_end(p->output_);
  10980. }
  10981. return true;
  10982. }
  10983. static void *scalar_startstr_onlykey(
  10984. void *closure, const void *handler_data, size_t size_hint) {
  10985. upb_json_printer *p = closure;
  10986. UPB_UNUSED(size_hint);
  10987. CHK(putkey(closure, handler_data));
  10988. return p;
  10989. }
  10990. /* Set up handlers for an Any submessage. */
  10991. void printer_sethandlers_any(const void *closure, upb_handlers *h) {
  10992. const upb_msgdef *md = upb_handlers_msgdef(h);
  10993. const upb_fielddef* type_field = upb_msgdef_itof(md, UPB_ANY_TYPE);
  10994. const upb_fielddef* value_field = upb_msgdef_itof(md, UPB_ANY_VALUE);
  10995. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  10996. /* type_url's json name is "@type" */
  10997. upb_handlerattr type_name_attr = UPB_HANDLERATTR_INIT;
  10998. upb_handlerattr value_name_attr = UPB_HANDLERATTR_INIT;
  10999. strpc *type_url_json_name = newstrpc_str(h, "@type");
  11000. strpc *value_json_name = newstrpc_str(h, "value");
  11001. type_name_attr.handler_data = type_url_json_name;
  11002. value_name_attr.handler_data = value_json_name;
  11003. /* Set up handlers. */
  11004. upb_handlers_setstartmsg(h, printer_startmsg, &empty_attr);
  11005. upb_handlers_setendmsg(h, printer_endmsg, &empty_attr);
  11006. upb_handlers_setstartstr(h, type_field, scalar_startstr, &type_name_attr);
  11007. upb_handlers_setstring(h, type_field, scalar_str, &empty_attr);
  11008. upb_handlers_setendstr(h, type_field, scalar_endstr, &empty_attr);
  11009. /* This is not the full and correct JSON encoding for the Any value field. It
  11010. * requires further processing by the wrapper code based on the type URL.
  11011. */
  11012. upb_handlers_setstartstr(h, value_field, scalar_startstr_onlykey,
  11013. &value_name_attr);
  11014. UPB_UNUSED(closure);
  11015. }
  11016. /* Set up handlers for a fieldmask submessage. */
  11017. void printer_sethandlers_fieldmask(const void *closure, upb_handlers *h) {
  11018. const upb_msgdef *md = upb_handlers_msgdef(h);
  11019. const upb_fielddef* f = upb_msgdef_itof(md, 1);
  11020. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11021. upb_handlers_setstartseq(h, f, startseq_fieldmask, &empty_attr);
  11022. upb_handlers_setendseq(h, f, endseq_fieldmask, &empty_attr);
  11023. upb_handlers_setstartmsg(h, printer_startmsg_fieldmask, &empty_attr);
  11024. upb_handlers_setendmsg(h, printer_endmsg_fieldmask, &empty_attr);
  11025. upb_handlers_setstartstr(h, f, repeated_startstr_fieldmask, &empty_attr);
  11026. upb_handlers_setstring(h, f, repeated_str_fieldmask, &empty_attr);
  11027. UPB_UNUSED(closure);
  11028. }
  11029. /* Set up handlers for a duration submessage. */
  11030. void printer_sethandlers_duration(const void *closure, upb_handlers *h) {
  11031. const upb_msgdef *md = upb_handlers_msgdef(h);
  11032. const upb_fielddef* seconds_field =
  11033. upb_msgdef_itof(md, UPB_DURATION_SECONDS);
  11034. const upb_fielddef* nanos_field =
  11035. upb_msgdef_itof(md, UPB_DURATION_NANOS);
  11036. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11037. upb_handlers_setstartmsg(h, printer_startdurationmsg, &empty_attr);
  11038. upb_handlers_setint64(h, seconds_field, putseconds, &empty_attr);
  11039. upb_handlers_setint32(h, nanos_field, putnanos, &empty_attr);
  11040. upb_handlers_setendmsg(h, printer_enddurationmsg, &empty_attr);
  11041. UPB_UNUSED(closure);
  11042. }
  11043. /* Set up handlers for a timestamp submessage. Instead of printing fields
  11044. * separately, the json representation of timestamp follows RFC 3339 */
  11045. void printer_sethandlers_timestamp(const void *closure, upb_handlers *h) {
  11046. const upb_msgdef *md = upb_handlers_msgdef(h);
  11047. const upb_fielddef* seconds_field =
  11048. upb_msgdef_itof(md, UPB_TIMESTAMP_SECONDS);
  11049. const upb_fielddef* nanos_field =
  11050. upb_msgdef_itof(md, UPB_TIMESTAMP_NANOS);
  11051. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11052. upb_handlers_setstartmsg(h, printer_starttimestampmsg, &empty_attr);
  11053. upb_handlers_setint64(h, seconds_field, putseconds, &empty_attr);
  11054. upb_handlers_setint32(h, nanos_field, putnanos, &empty_attr);
  11055. upb_handlers_setendmsg(h, printer_endtimestampmsg, &empty_attr);
  11056. UPB_UNUSED(closure);
  11057. }
  11058. void printer_sethandlers_value(const void *closure, upb_handlers *h) {
  11059. const upb_msgdef *md = upb_handlers_msgdef(h);
  11060. upb_msg_field_iter i;
  11061. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11062. upb_handlers_setstartmsg(h, printer_startmsg_noframe, &empty_attr);
  11063. upb_handlers_setendmsg(h, printer_endmsg_noframe, &empty_attr);
  11064. upb_msg_field_begin(&i, md);
  11065. for(; !upb_msg_field_done(&i); upb_msg_field_next(&i)) {
  11066. const upb_fielddef *f = upb_msg_iter_field(&i);
  11067. switch (upb_fielddef_type(f)) {
  11068. case UPB_TYPE_ENUM:
  11069. upb_handlers_setint32(h, f, putnull, &empty_attr);
  11070. break;
  11071. case UPB_TYPE_DOUBLE:
  11072. upb_handlers_setdouble(h, f, putdouble, &empty_attr);
  11073. break;
  11074. case UPB_TYPE_STRING:
  11075. upb_handlers_setstartstr(h, f, scalar_startstr_nokey, &empty_attr);
  11076. upb_handlers_setstring(h, f, scalar_str, &empty_attr);
  11077. upb_handlers_setendstr(h, f, scalar_endstr, &empty_attr);
  11078. break;
  11079. case UPB_TYPE_BOOL:
  11080. upb_handlers_setbool(h, f, putbool, &empty_attr);
  11081. break;
  11082. case UPB_TYPE_MESSAGE:
  11083. break;
  11084. default:
  11085. UPB_ASSERT(false);
  11086. break;
  11087. }
  11088. }
  11089. UPB_UNUSED(closure);
  11090. }
  11091. #define WRAPPER_SETHANDLERS(wrapper, type, putmethod) \
  11092. void printer_sethandlers_##wrapper(const void *closure, upb_handlers *h) { \
  11093. const upb_msgdef *md = upb_handlers_msgdef(h); \
  11094. const upb_fielddef* f = upb_msgdef_itof(md, 1); \
  11095. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT; \
  11096. upb_handlers_setstartmsg(h, printer_startmsg_noframe, &empty_attr); \
  11097. upb_handlers_setendmsg(h, printer_endmsg_noframe, &empty_attr); \
  11098. upb_handlers_set##type(h, f, putmethod, &empty_attr); \
  11099. UPB_UNUSED(closure); \
  11100. }
  11101. WRAPPER_SETHANDLERS(doublevalue, double, putdouble)
  11102. WRAPPER_SETHANDLERS(floatvalue, float, putfloat)
  11103. WRAPPER_SETHANDLERS(int64value, int64, putint64_t)
  11104. WRAPPER_SETHANDLERS(uint64value, uint64, putuint64_t)
  11105. WRAPPER_SETHANDLERS(int32value, int32, putint32_t)
  11106. WRAPPER_SETHANDLERS(uint32value, uint32, putuint32_t)
  11107. WRAPPER_SETHANDLERS(boolvalue, bool, putbool)
  11108. WRAPPER_SETHANDLERS(stringvalue, string, putstr_nokey)
  11109. WRAPPER_SETHANDLERS(bytesvalue, string, putbytes)
  11110. #undef WRAPPER_SETHANDLERS
  11111. void printer_sethandlers_listvalue(const void *closure, upb_handlers *h) {
  11112. const upb_msgdef *md = upb_handlers_msgdef(h);
  11113. const upb_fielddef* f = upb_msgdef_itof(md, 1);
  11114. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11115. upb_handlers_setstartseq(h, f, startseq_nokey, &empty_attr);
  11116. upb_handlers_setendseq(h, f, endseq, &empty_attr);
  11117. upb_handlers_setstartmsg(h, printer_startmsg_noframe, &empty_attr);
  11118. upb_handlers_setendmsg(h, printer_endmsg_noframe, &empty_attr);
  11119. upb_handlers_setstartsubmsg(h, f, repeated_startsubmsg, &empty_attr);
  11120. UPB_UNUSED(closure);
  11121. }
  11122. void printer_sethandlers_structvalue(const void *closure, upb_handlers *h) {
  11123. const upb_msgdef *md = upb_handlers_msgdef(h);
  11124. const upb_fielddef* f = upb_msgdef_itof(md, 1);
  11125. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11126. upb_handlers_setstartseq(h, f, startmap_nokey, &empty_attr);
  11127. upb_handlers_setendseq(h, f, endmap, &empty_attr);
  11128. upb_handlers_setstartmsg(h, printer_startmsg_noframe, &empty_attr);
  11129. upb_handlers_setendmsg(h, printer_endmsg_noframe, &empty_attr);
  11130. upb_handlers_setstartsubmsg(h, f, repeated_startsubmsg, &empty_attr);
  11131. UPB_UNUSED(closure);
  11132. }
  11133. void printer_sethandlers(const void *closure, upb_handlers *h) {
  11134. const upb_msgdef *md = upb_handlers_msgdef(h);
  11135. bool is_mapentry = upb_msgdef_mapentry(md);
  11136. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11137. upb_msg_field_iter i;
  11138. const upb_json_printercache *cache = closure;
  11139. const bool preserve_fieldnames = cache->preserve_fieldnames;
  11140. if (is_mapentry) {
  11141. /* mapentry messages are sufficiently different that we handle them
  11142. * separately. */
  11143. printer_sethandlers_mapentry(closure, preserve_fieldnames, h);
  11144. return;
  11145. }
  11146. switch (upb_msgdef_wellknowntype(md)) {
  11147. case UPB_WELLKNOWN_UNSPECIFIED:
  11148. break;
  11149. case UPB_WELLKNOWN_ANY:
  11150. printer_sethandlers_any(closure, h);
  11151. return;
  11152. case UPB_WELLKNOWN_FIELDMASK:
  11153. printer_sethandlers_fieldmask(closure, h);
  11154. return;
  11155. case UPB_WELLKNOWN_DURATION:
  11156. printer_sethandlers_duration(closure, h);
  11157. return;
  11158. case UPB_WELLKNOWN_TIMESTAMP:
  11159. printer_sethandlers_timestamp(closure, h);
  11160. return;
  11161. case UPB_WELLKNOWN_VALUE:
  11162. printer_sethandlers_value(closure, h);
  11163. return;
  11164. case UPB_WELLKNOWN_LISTVALUE:
  11165. printer_sethandlers_listvalue(closure, h);
  11166. return;
  11167. case UPB_WELLKNOWN_STRUCT:
  11168. printer_sethandlers_structvalue(closure, h);
  11169. return;
  11170. #define WRAPPER(wellknowntype, name) \
  11171. case wellknowntype: \
  11172. printer_sethandlers_##name(closure, h); \
  11173. return; \
  11174. WRAPPER(UPB_WELLKNOWN_DOUBLEVALUE, doublevalue);
  11175. WRAPPER(UPB_WELLKNOWN_FLOATVALUE, floatvalue);
  11176. WRAPPER(UPB_WELLKNOWN_INT64VALUE, int64value);
  11177. WRAPPER(UPB_WELLKNOWN_UINT64VALUE, uint64value);
  11178. WRAPPER(UPB_WELLKNOWN_INT32VALUE, int32value);
  11179. WRAPPER(UPB_WELLKNOWN_UINT32VALUE, uint32value);
  11180. WRAPPER(UPB_WELLKNOWN_BOOLVALUE, boolvalue);
  11181. WRAPPER(UPB_WELLKNOWN_STRINGVALUE, stringvalue);
  11182. WRAPPER(UPB_WELLKNOWN_BYTESVALUE, bytesvalue);
  11183. #undef WRAPPER
  11184. }
  11185. upb_handlers_setstartmsg(h, printer_startmsg, &empty_attr);
  11186. upb_handlers_setendmsg(h, printer_endmsg, &empty_attr);
  11187. #define TYPE(type, name, ctype) \
  11188. case type: \
  11189. if (upb_fielddef_isseq(f)) { \
  11190. upb_handlers_set##name(h, f, repeated_##ctype, &empty_attr); \
  11191. } else { \
  11192. upb_handlers_set##name(h, f, scalar_##ctype, &name_attr); \
  11193. } \
  11194. break;
  11195. upb_msg_field_begin(&i, md);
  11196. for(; !upb_msg_field_done(&i); upb_msg_field_next(&i)) {
  11197. const upb_fielddef *f = upb_msg_iter_field(&i);
  11198. upb_handlerattr name_attr = UPB_HANDLERATTR_INIT;
  11199. name_attr.handler_data = newstrpc(h, f, preserve_fieldnames);
  11200. if (upb_fielddef_ismap(f)) {
  11201. upb_handlers_setstartseq(h, f, startmap, &name_attr);
  11202. upb_handlers_setendseq(h, f, endmap, &name_attr);
  11203. } else if (upb_fielddef_isseq(f)) {
  11204. upb_handlers_setstartseq(h, f, startseq, &name_attr);
  11205. upb_handlers_setendseq(h, f, endseq, &empty_attr);
  11206. }
  11207. switch (upb_fielddef_type(f)) {
  11208. TYPE(UPB_TYPE_FLOAT, float, float);
  11209. TYPE(UPB_TYPE_DOUBLE, double, double);
  11210. TYPE(UPB_TYPE_BOOL, bool, bool);
  11211. TYPE(UPB_TYPE_INT32, int32, int32_t);
  11212. TYPE(UPB_TYPE_UINT32, uint32, uint32_t);
  11213. TYPE(UPB_TYPE_INT64, int64, int64_t);
  11214. TYPE(UPB_TYPE_UINT64, uint64, uint64_t);
  11215. case UPB_TYPE_ENUM: {
  11216. /* For now, we always emit symbolic names for enums. We may want an
  11217. * option later to control this behavior, but we will wait for a real
  11218. * need first. */
  11219. upb_handlerattr enum_attr = UPB_HANDLERATTR_INIT;
  11220. set_enum_hd(h, f, preserve_fieldnames, &enum_attr);
  11221. if (upb_fielddef_isseq(f)) {
  11222. upb_handlers_setint32(h, f, repeated_enum, &enum_attr);
  11223. } else {
  11224. upb_handlers_setint32(h, f, scalar_enum, &enum_attr);
  11225. }
  11226. break;
  11227. }
  11228. case UPB_TYPE_STRING:
  11229. if (upb_fielddef_isseq(f)) {
  11230. upb_handlers_setstartstr(h, f, repeated_startstr, &empty_attr);
  11231. upb_handlers_setstring(h, f, repeated_str, &empty_attr);
  11232. upb_handlers_setendstr(h, f, repeated_endstr, &empty_attr);
  11233. } else {
  11234. upb_handlers_setstartstr(h, f, scalar_startstr, &name_attr);
  11235. upb_handlers_setstring(h, f, scalar_str, &empty_attr);
  11236. upb_handlers_setendstr(h, f, scalar_endstr, &empty_attr);
  11237. }
  11238. break;
  11239. case UPB_TYPE_BYTES:
  11240. /* XXX: this doesn't support strings that span buffers yet. The base64
  11241. * encoder will need to be made resumable for this to work properly. */
  11242. if (upb_fielddef_isseq(f)) {
  11243. upb_handlers_setstring(h, f, repeated_bytes, &empty_attr);
  11244. } else {
  11245. upb_handlers_setstring(h, f, scalar_bytes, &name_attr);
  11246. }
  11247. break;
  11248. case UPB_TYPE_MESSAGE:
  11249. if (upb_fielddef_isseq(f)) {
  11250. upb_handlers_setstartsubmsg(h, f, repeated_startsubmsg, &name_attr);
  11251. } else {
  11252. upb_handlers_setstartsubmsg(h, f, scalar_startsubmsg, &name_attr);
  11253. }
  11254. break;
  11255. }
  11256. }
  11257. #undef TYPE
  11258. }
  11259. static void json_printer_reset(upb_json_printer *p) {
  11260. p->depth_ = 0;
  11261. }
  11262. /* Public API *****************************************************************/
  11263. upb_json_printer *upb_json_printer_create(upb_arena *a, const upb_handlers *h,
  11264. upb_bytessink output) {
  11265. #ifndef NDEBUG
  11266. size_t size_before = upb_arena_bytesallocated(a);
  11267. #endif
  11268. upb_json_printer *p = upb_arena_malloc(a, sizeof(upb_json_printer));
  11269. if (!p) return NULL;
  11270. p->output_ = output;
  11271. json_printer_reset(p);
  11272. upb_sink_reset(&p->input_, h, p);
  11273. p->seconds = 0;
  11274. p->nanos = 0;
  11275. /* If this fails, increase the value in printer.h. */
  11276. UPB_ASSERT_DEBUGVAR(upb_arena_bytesallocated(a) - size_before <=
  11277. UPB_JSON_PRINTER_SIZE);
  11278. return p;
  11279. }
  11280. upb_sink upb_json_printer_input(upb_json_printer *p) {
  11281. return p->input_;
  11282. }
  11283. upb_handlercache *upb_json_printer_newcache(bool preserve_proto_fieldnames) {
  11284. upb_json_printercache *cache = upb_gmalloc(sizeof(*cache));
  11285. upb_handlercache *ret = upb_handlercache_new(printer_sethandlers, cache);
  11286. cache->preserve_fieldnames = preserve_proto_fieldnames;
  11287. upb_handlercache_addcleanup(ret, cache, upb_gfree);
  11288. return ret;
  11289. }
  11290. /* See port_def.inc. This should #undef all macros #defined there. */
  11291. #undef UPB_SIZE
  11292. #undef UPB_FIELD_AT
  11293. #undef UPB_READ_ONEOF
  11294. #undef UPB_WRITE_ONEOF
  11295. #undef UPB_INLINE
  11296. #undef UPB_FORCEINLINE
  11297. #undef UPB_NOINLINE
  11298. #undef UPB_NORETURN
  11299. #undef UPB_MAX
  11300. #undef UPB_MIN
  11301. #undef UPB_UNUSED
  11302. #undef UPB_ASSERT
  11303. #undef UPB_ASSERT_DEBUGVAR
  11304. #undef UPB_UNREACHABLE
  11305. #undef UPB_INFINITY
  11306. #undef UPB_MSVC_VSNPRINTF
  11307. #undef _upb_snprintf
  11308. #undef _upb_vsnprintf
  11309. #undef _upb_va_copy