upb.c 555 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318
  1. // Amalgamated source file
  2. #include "upb.h"
  3. #if UINTPTR_MAX == 0xffffffff
  4. #define UPB_SIZE(size32, size64) size32
  5. #else
  6. #define UPB_SIZE(size32, size64) size64
  7. #endif
  8. #define UPB_FIELD_AT(msg, fieldtype, offset) \
  9. *(fieldtype*)((const char*)(msg) + offset)
  10. #define UPB_READ_ONEOF(msg, fieldtype, offset, case_offset, case_val, default) \
  11. UPB_FIELD_AT(msg, int, case_offset) == case_val \
  12. ? UPB_FIELD_AT(msg, fieldtype, offset) \
  13. : default
  14. #define UPB_WRITE_ONEOF(msg, fieldtype, offset, value, case_offset, case_val) \
  15. UPB_FIELD_AT(msg, int, case_offset) = case_val; \
  16. UPB_FIELD_AT(msg, fieldtype, offset) = value;
  17. /* This file was generated by upbc (the upb compiler) from the input
  18. * file:
  19. *
  20. * google/protobuf/descriptor.proto
  21. *
  22. * Do not edit -- your changes will be discarded when the file is
  23. * regenerated. */
  24. #include <stddef.h>
  25. static const upb_msglayout *const google_protobuf_FileDescriptorSet_submsgs[1] = {
  26. &google_protobuf_FileDescriptorProto_msginit,
  27. };
  28. static const upb_msglayout_field google_protobuf_FileDescriptorSet__fields[1] = {
  29. {1, UPB_SIZE(0, 0), 0, 0, 11, 3},
  30. };
  31. const upb_msglayout google_protobuf_FileDescriptorSet_msginit = {
  32. &google_protobuf_FileDescriptorSet_submsgs[0],
  33. &google_protobuf_FileDescriptorSet__fields[0],
  34. UPB_SIZE(4, 8), 1, false,
  35. };
  36. static const upb_msglayout *const google_protobuf_FileDescriptorProto_submsgs[6] = {
  37. &google_protobuf_DescriptorProto_msginit,
  38. &google_protobuf_EnumDescriptorProto_msginit,
  39. &google_protobuf_FieldDescriptorProto_msginit,
  40. &google_protobuf_FileOptions_msginit,
  41. &google_protobuf_ServiceDescriptorProto_msginit,
  42. &google_protobuf_SourceCodeInfo_msginit,
  43. };
  44. static const upb_msglayout_field google_protobuf_FileDescriptorProto__fields[12] = {
  45. {1, UPB_SIZE(8, 16), 1, 0, 9, 1},
  46. {2, UPB_SIZE(16, 32), 2, 0, 9, 1},
  47. {3, UPB_SIZE(40, 80), 0, 0, 9, 3},
  48. {4, UPB_SIZE(44, 88), 0, 0, 11, 3},
  49. {5, UPB_SIZE(48, 96), 0, 1, 11, 3},
  50. {6, UPB_SIZE(52, 104), 0, 4, 11, 3},
  51. {7, UPB_SIZE(56, 112), 0, 2, 11, 3},
  52. {8, UPB_SIZE(32, 64), 4, 3, 11, 1},
  53. {9, UPB_SIZE(36, 72), 5, 5, 11, 1},
  54. {10, UPB_SIZE(60, 120), 0, 0, 5, 3},
  55. {11, UPB_SIZE(64, 128), 0, 0, 5, 3},
  56. {12, UPB_SIZE(24, 48), 3, 0, 9, 1},
  57. };
  58. const upb_msglayout google_protobuf_FileDescriptorProto_msginit = {
  59. &google_protobuf_FileDescriptorProto_submsgs[0],
  60. &google_protobuf_FileDescriptorProto__fields[0],
  61. UPB_SIZE(72, 144), 12, false,
  62. };
  63. static const upb_msglayout *const google_protobuf_DescriptorProto_submsgs[8] = {
  64. &google_protobuf_DescriptorProto_msginit,
  65. &google_protobuf_DescriptorProto_ExtensionRange_msginit,
  66. &google_protobuf_DescriptorProto_ReservedRange_msginit,
  67. &google_protobuf_EnumDescriptorProto_msginit,
  68. &google_protobuf_FieldDescriptorProto_msginit,
  69. &google_protobuf_MessageOptions_msginit,
  70. &google_protobuf_OneofDescriptorProto_msginit,
  71. };
  72. static const upb_msglayout_field google_protobuf_DescriptorProto__fields[10] = {
  73. {1, UPB_SIZE(8, 16), 1, 0, 9, 1},
  74. {2, UPB_SIZE(20, 40), 0, 4, 11, 3},
  75. {3, UPB_SIZE(24, 48), 0, 0, 11, 3},
  76. {4, UPB_SIZE(28, 56), 0, 3, 11, 3},
  77. {5, UPB_SIZE(32, 64), 0, 1, 11, 3},
  78. {6, UPB_SIZE(36, 72), 0, 4, 11, 3},
  79. {7, UPB_SIZE(16, 32), 2, 5, 11, 1},
  80. {8, UPB_SIZE(40, 80), 0, 6, 11, 3},
  81. {9, UPB_SIZE(44, 88), 0, 2, 11, 3},
  82. {10, UPB_SIZE(48, 96), 0, 0, 9, 3},
  83. };
  84. const upb_msglayout google_protobuf_DescriptorProto_msginit = {
  85. &google_protobuf_DescriptorProto_submsgs[0],
  86. &google_protobuf_DescriptorProto__fields[0],
  87. UPB_SIZE(56, 112), 10, false,
  88. };
  89. static const upb_msglayout *const google_protobuf_DescriptorProto_ExtensionRange_submsgs[1] = {
  90. &google_protobuf_ExtensionRangeOptions_msginit,
  91. };
  92. static const upb_msglayout_field google_protobuf_DescriptorProto_ExtensionRange__fields[3] = {
  93. {1, UPB_SIZE(4, 4), 1, 0, 5, 1},
  94. {2, UPB_SIZE(8, 8), 2, 0, 5, 1},
  95. {3, UPB_SIZE(12, 16), 3, 0, 11, 1},
  96. };
  97. const upb_msglayout google_protobuf_DescriptorProto_ExtensionRange_msginit = {
  98. &google_protobuf_DescriptorProto_ExtensionRange_submsgs[0],
  99. &google_protobuf_DescriptorProto_ExtensionRange__fields[0],
  100. UPB_SIZE(16, 24), 3, false,
  101. };
  102. static const upb_msglayout_field google_protobuf_DescriptorProto_ReservedRange__fields[2] = {
  103. {1, UPB_SIZE(4, 4), 1, 0, 5, 1},
  104. {2, UPB_SIZE(8, 8), 2, 0, 5, 1},
  105. };
  106. const upb_msglayout google_protobuf_DescriptorProto_ReservedRange_msginit = {
  107. NULL,
  108. &google_protobuf_DescriptorProto_ReservedRange__fields[0],
  109. UPB_SIZE(12, 12), 2, false,
  110. };
  111. static const upb_msglayout *const google_protobuf_ExtensionRangeOptions_submsgs[1] = {
  112. &google_protobuf_UninterpretedOption_msginit,
  113. };
  114. static const upb_msglayout_field google_protobuf_ExtensionRangeOptions__fields[1] = {
  115. {999, UPB_SIZE(0, 0), 0, 0, 11, 3},
  116. };
  117. const upb_msglayout google_protobuf_ExtensionRangeOptions_msginit = {
  118. &google_protobuf_ExtensionRangeOptions_submsgs[0],
  119. &google_protobuf_ExtensionRangeOptions__fields[0],
  120. UPB_SIZE(4, 8), 1, false,
  121. };
  122. static const upb_msglayout *const google_protobuf_FieldDescriptorProto_submsgs[1] = {
  123. &google_protobuf_FieldOptions_msginit,
  124. };
  125. static const upb_msglayout_field google_protobuf_FieldDescriptorProto__fields[10] = {
  126. {1, UPB_SIZE(32, 32), 5, 0, 9, 1},
  127. {2, UPB_SIZE(40, 48), 6, 0, 9, 1},
  128. {3, UPB_SIZE(24, 24), 3, 0, 5, 1},
  129. {4, UPB_SIZE(8, 8), 1, 0, 14, 1},
  130. {5, UPB_SIZE(16, 16), 2, 0, 14, 1},
  131. {6, UPB_SIZE(48, 64), 7, 0, 9, 1},
  132. {7, UPB_SIZE(56, 80), 8, 0, 9, 1},
  133. {8, UPB_SIZE(72, 112), 10, 0, 11, 1},
  134. {9, UPB_SIZE(28, 28), 4, 0, 5, 1},
  135. {10, UPB_SIZE(64, 96), 9, 0, 9, 1},
  136. };
  137. const upb_msglayout google_protobuf_FieldDescriptorProto_msginit = {
  138. &google_protobuf_FieldDescriptorProto_submsgs[0],
  139. &google_protobuf_FieldDescriptorProto__fields[0],
  140. UPB_SIZE(80, 128), 10, false,
  141. };
  142. static const upb_msglayout *const google_protobuf_OneofDescriptorProto_submsgs[1] = {
  143. &google_protobuf_OneofOptions_msginit,
  144. };
  145. static const upb_msglayout_field google_protobuf_OneofDescriptorProto__fields[2] = {
  146. {1, UPB_SIZE(8, 16), 1, 0, 9, 1},
  147. {2, UPB_SIZE(16, 32), 2, 0, 11, 1},
  148. };
  149. const upb_msglayout google_protobuf_OneofDescriptorProto_msginit = {
  150. &google_protobuf_OneofDescriptorProto_submsgs[0],
  151. &google_protobuf_OneofDescriptorProto__fields[0],
  152. UPB_SIZE(24, 48), 2, false,
  153. };
  154. static const upb_msglayout *const google_protobuf_EnumDescriptorProto_submsgs[3] = {
  155. &google_protobuf_EnumDescriptorProto_EnumReservedRange_msginit,
  156. &google_protobuf_EnumOptions_msginit,
  157. &google_protobuf_EnumValueDescriptorProto_msginit,
  158. };
  159. static const upb_msglayout_field google_protobuf_EnumDescriptorProto__fields[5] = {
  160. {1, UPB_SIZE(8, 16), 1, 0, 9, 1},
  161. {2, UPB_SIZE(20, 40), 0, 2, 11, 3},
  162. {3, UPB_SIZE(16, 32), 2, 1, 11, 1},
  163. {4, UPB_SIZE(24, 48), 0, 0, 11, 3},
  164. {5, UPB_SIZE(28, 56), 0, 0, 9, 3},
  165. };
  166. const upb_msglayout google_protobuf_EnumDescriptorProto_msginit = {
  167. &google_protobuf_EnumDescriptorProto_submsgs[0],
  168. &google_protobuf_EnumDescriptorProto__fields[0],
  169. UPB_SIZE(32, 64), 5, false,
  170. };
  171. static const upb_msglayout_field google_protobuf_EnumDescriptorProto_EnumReservedRange__fields[2] = {
  172. {1, UPB_SIZE(4, 4), 1, 0, 5, 1},
  173. {2, UPB_SIZE(8, 8), 2, 0, 5, 1},
  174. };
  175. const upb_msglayout google_protobuf_EnumDescriptorProto_EnumReservedRange_msginit = {
  176. NULL,
  177. &google_protobuf_EnumDescriptorProto_EnumReservedRange__fields[0],
  178. UPB_SIZE(12, 12), 2, false,
  179. };
  180. static const upb_msglayout *const google_protobuf_EnumValueDescriptorProto_submsgs[1] = {
  181. &google_protobuf_EnumValueOptions_msginit,
  182. };
  183. static const upb_msglayout_field google_protobuf_EnumValueDescriptorProto__fields[3] = {
  184. {1, UPB_SIZE(8, 16), 2, 0, 9, 1},
  185. {2, UPB_SIZE(4, 4), 1, 0, 5, 1},
  186. {3, UPB_SIZE(16, 32), 3, 0, 11, 1},
  187. };
  188. const upb_msglayout google_protobuf_EnumValueDescriptorProto_msginit = {
  189. &google_protobuf_EnumValueDescriptorProto_submsgs[0],
  190. &google_protobuf_EnumValueDescriptorProto__fields[0],
  191. UPB_SIZE(24, 48), 3, false,
  192. };
  193. static const upb_msglayout *const google_protobuf_ServiceDescriptorProto_submsgs[2] = {
  194. &google_protobuf_MethodDescriptorProto_msginit,
  195. &google_protobuf_ServiceOptions_msginit,
  196. };
  197. static const upb_msglayout_field google_protobuf_ServiceDescriptorProto__fields[3] = {
  198. {1, UPB_SIZE(8, 16), 1, 0, 9, 1},
  199. {2, UPB_SIZE(20, 40), 0, 0, 11, 3},
  200. {3, UPB_SIZE(16, 32), 2, 1, 11, 1},
  201. };
  202. const upb_msglayout google_protobuf_ServiceDescriptorProto_msginit = {
  203. &google_protobuf_ServiceDescriptorProto_submsgs[0],
  204. &google_protobuf_ServiceDescriptorProto__fields[0],
  205. UPB_SIZE(24, 48), 3, false,
  206. };
  207. static const upb_msglayout *const google_protobuf_MethodDescriptorProto_submsgs[1] = {
  208. &google_protobuf_MethodOptions_msginit,
  209. };
  210. static const upb_msglayout_field google_protobuf_MethodDescriptorProto__fields[6] = {
  211. {1, UPB_SIZE(8, 16), 3, 0, 9, 1},
  212. {2, UPB_SIZE(16, 32), 4, 0, 9, 1},
  213. {3, UPB_SIZE(24, 48), 5, 0, 9, 1},
  214. {4, UPB_SIZE(32, 64), 6, 0, 11, 1},
  215. {5, UPB_SIZE(1, 1), 1, 0, 8, 1},
  216. {6, UPB_SIZE(2, 2), 2, 0, 8, 1},
  217. };
  218. const upb_msglayout google_protobuf_MethodDescriptorProto_msginit = {
  219. &google_protobuf_MethodDescriptorProto_submsgs[0],
  220. &google_protobuf_MethodDescriptorProto__fields[0],
  221. UPB_SIZE(40, 80), 6, false,
  222. };
  223. static const upb_msglayout *const google_protobuf_FileOptions_submsgs[1] = {
  224. &google_protobuf_UninterpretedOption_msginit,
  225. };
  226. static const upb_msglayout_field google_protobuf_FileOptions__fields[19] = {
  227. {1, UPB_SIZE(32, 32), 11, 0, 9, 1},
  228. {8, UPB_SIZE(40, 48), 12, 0, 9, 1},
  229. {9, UPB_SIZE(8, 8), 1, 0, 14, 1},
  230. {10, UPB_SIZE(16, 16), 2, 0, 8, 1},
  231. {11, UPB_SIZE(48, 64), 13, 0, 9, 1},
  232. {16, UPB_SIZE(17, 17), 3, 0, 8, 1},
  233. {17, UPB_SIZE(18, 18), 4, 0, 8, 1},
  234. {18, UPB_SIZE(19, 19), 5, 0, 8, 1},
  235. {20, UPB_SIZE(20, 20), 6, 0, 8, 1},
  236. {23, UPB_SIZE(21, 21), 7, 0, 8, 1},
  237. {27, UPB_SIZE(22, 22), 8, 0, 8, 1},
  238. {31, UPB_SIZE(23, 23), 9, 0, 8, 1},
  239. {36, UPB_SIZE(56, 80), 14, 0, 9, 1},
  240. {37, UPB_SIZE(64, 96), 15, 0, 9, 1},
  241. {39, UPB_SIZE(72, 112), 16, 0, 9, 1},
  242. {40, UPB_SIZE(80, 128), 17, 0, 9, 1},
  243. {41, UPB_SIZE(88, 144), 18, 0, 9, 1},
  244. {42, UPB_SIZE(24, 24), 10, 0, 8, 1},
  245. {999, UPB_SIZE(96, 160), 0, 0, 11, 3},
  246. };
  247. const upb_msglayout google_protobuf_FileOptions_msginit = {
  248. &google_protobuf_FileOptions_submsgs[0],
  249. &google_protobuf_FileOptions__fields[0],
  250. UPB_SIZE(104, 176), 19, false,
  251. };
  252. static const upb_msglayout *const google_protobuf_MessageOptions_submsgs[1] = {
  253. &google_protobuf_UninterpretedOption_msginit,
  254. };
  255. static const upb_msglayout_field google_protobuf_MessageOptions__fields[5] = {
  256. {1, UPB_SIZE(1, 1), 1, 0, 8, 1},
  257. {2, UPB_SIZE(2, 2), 2, 0, 8, 1},
  258. {3, UPB_SIZE(3, 3), 3, 0, 8, 1},
  259. {7, UPB_SIZE(4, 4), 4, 0, 8, 1},
  260. {999, UPB_SIZE(8, 8), 0, 0, 11, 3},
  261. };
  262. const upb_msglayout google_protobuf_MessageOptions_msginit = {
  263. &google_protobuf_MessageOptions_submsgs[0],
  264. &google_protobuf_MessageOptions__fields[0],
  265. UPB_SIZE(12, 16), 5, false,
  266. };
  267. static const upb_msglayout *const google_protobuf_FieldOptions_submsgs[1] = {
  268. &google_protobuf_UninterpretedOption_msginit,
  269. };
  270. static const upb_msglayout_field google_protobuf_FieldOptions__fields[7] = {
  271. {1, UPB_SIZE(8, 8), 1, 0, 14, 1},
  272. {2, UPB_SIZE(24, 24), 3, 0, 8, 1},
  273. {3, UPB_SIZE(25, 25), 4, 0, 8, 1},
  274. {5, UPB_SIZE(26, 26), 5, 0, 8, 1},
  275. {6, UPB_SIZE(16, 16), 2, 0, 14, 1},
  276. {10, UPB_SIZE(27, 27), 6, 0, 8, 1},
  277. {999, UPB_SIZE(28, 32), 0, 0, 11, 3},
  278. };
  279. const upb_msglayout google_protobuf_FieldOptions_msginit = {
  280. &google_protobuf_FieldOptions_submsgs[0],
  281. &google_protobuf_FieldOptions__fields[0],
  282. UPB_SIZE(32, 40), 7, false,
  283. };
  284. static const upb_msglayout *const google_protobuf_OneofOptions_submsgs[1] = {
  285. &google_protobuf_UninterpretedOption_msginit,
  286. };
  287. static const upb_msglayout_field google_protobuf_OneofOptions__fields[1] = {
  288. {999, UPB_SIZE(0, 0), 0, 0, 11, 3},
  289. };
  290. const upb_msglayout google_protobuf_OneofOptions_msginit = {
  291. &google_protobuf_OneofOptions_submsgs[0],
  292. &google_protobuf_OneofOptions__fields[0],
  293. UPB_SIZE(4, 8), 1, false,
  294. };
  295. static const upb_msglayout *const google_protobuf_EnumOptions_submsgs[1] = {
  296. &google_protobuf_UninterpretedOption_msginit,
  297. };
  298. static const upb_msglayout_field google_protobuf_EnumOptions__fields[3] = {
  299. {2, UPB_SIZE(1, 1), 1, 0, 8, 1},
  300. {3, UPB_SIZE(2, 2), 2, 0, 8, 1},
  301. {999, UPB_SIZE(4, 8), 0, 0, 11, 3},
  302. };
  303. const upb_msglayout google_protobuf_EnumOptions_msginit = {
  304. &google_protobuf_EnumOptions_submsgs[0],
  305. &google_protobuf_EnumOptions__fields[0],
  306. UPB_SIZE(8, 16), 3, false,
  307. };
  308. static const upb_msglayout *const google_protobuf_EnumValueOptions_submsgs[1] = {
  309. &google_protobuf_UninterpretedOption_msginit,
  310. };
  311. static const upb_msglayout_field google_protobuf_EnumValueOptions__fields[2] = {
  312. {1, UPB_SIZE(1, 1), 1, 0, 8, 1},
  313. {999, UPB_SIZE(4, 8), 0, 0, 11, 3},
  314. };
  315. const upb_msglayout google_protobuf_EnumValueOptions_msginit = {
  316. &google_protobuf_EnumValueOptions_submsgs[0],
  317. &google_protobuf_EnumValueOptions__fields[0],
  318. UPB_SIZE(8, 16), 2, false,
  319. };
  320. static const upb_msglayout *const google_protobuf_ServiceOptions_submsgs[1] = {
  321. &google_protobuf_UninterpretedOption_msginit,
  322. };
  323. static const upb_msglayout_field google_protobuf_ServiceOptions__fields[2] = {
  324. {33, UPB_SIZE(1, 1), 1, 0, 8, 1},
  325. {999, UPB_SIZE(4, 8), 0, 0, 11, 3},
  326. };
  327. const upb_msglayout google_protobuf_ServiceOptions_msginit = {
  328. &google_protobuf_ServiceOptions_submsgs[0],
  329. &google_protobuf_ServiceOptions__fields[0],
  330. UPB_SIZE(8, 16), 2, false,
  331. };
  332. static const upb_msglayout *const google_protobuf_MethodOptions_submsgs[1] = {
  333. &google_protobuf_UninterpretedOption_msginit,
  334. };
  335. static const upb_msglayout_field google_protobuf_MethodOptions__fields[3] = {
  336. {33, UPB_SIZE(16, 16), 2, 0, 8, 1},
  337. {34, UPB_SIZE(8, 8), 1, 0, 14, 1},
  338. {999, UPB_SIZE(20, 24), 0, 0, 11, 3},
  339. };
  340. const upb_msglayout google_protobuf_MethodOptions_msginit = {
  341. &google_protobuf_MethodOptions_submsgs[0],
  342. &google_protobuf_MethodOptions__fields[0],
  343. UPB_SIZE(24, 32), 3, false,
  344. };
  345. static const upb_msglayout *const google_protobuf_UninterpretedOption_submsgs[1] = {
  346. &google_protobuf_UninterpretedOption_NamePart_msginit,
  347. };
  348. static const upb_msglayout_field google_protobuf_UninterpretedOption__fields[7] = {
  349. {2, UPB_SIZE(56, 80), 0, 0, 11, 3},
  350. {3, UPB_SIZE(32, 32), 4, 0, 9, 1},
  351. {4, UPB_SIZE(8, 8), 1, 0, 4, 1},
  352. {5, UPB_SIZE(16, 16), 2, 0, 3, 1},
  353. {6, UPB_SIZE(24, 24), 3, 0, 1, 1},
  354. {7, UPB_SIZE(40, 48), 5, 0, 12, 1},
  355. {8, UPB_SIZE(48, 64), 6, 0, 9, 1},
  356. };
  357. const upb_msglayout google_protobuf_UninterpretedOption_msginit = {
  358. &google_protobuf_UninterpretedOption_submsgs[0],
  359. &google_protobuf_UninterpretedOption__fields[0],
  360. UPB_SIZE(64, 96), 7, false,
  361. };
  362. static const upb_msglayout_field google_protobuf_UninterpretedOption_NamePart__fields[2] = {
  363. {1, UPB_SIZE(8, 16), 2, 0, 9, 2},
  364. {2, UPB_SIZE(1, 1), 1, 0, 8, 2},
  365. };
  366. const upb_msglayout google_protobuf_UninterpretedOption_NamePart_msginit = {
  367. NULL,
  368. &google_protobuf_UninterpretedOption_NamePart__fields[0],
  369. UPB_SIZE(16, 32), 2, false,
  370. };
  371. static const upb_msglayout *const google_protobuf_SourceCodeInfo_submsgs[1] = {
  372. &google_protobuf_SourceCodeInfo_Location_msginit,
  373. };
  374. static const upb_msglayout_field google_protobuf_SourceCodeInfo__fields[1] = {
  375. {1, UPB_SIZE(0, 0), 0, 0, 11, 3},
  376. };
  377. const upb_msglayout google_protobuf_SourceCodeInfo_msginit = {
  378. &google_protobuf_SourceCodeInfo_submsgs[0],
  379. &google_protobuf_SourceCodeInfo__fields[0],
  380. UPB_SIZE(4, 8), 1, false,
  381. };
  382. static const upb_msglayout_field google_protobuf_SourceCodeInfo_Location__fields[5] = {
  383. {1, UPB_SIZE(24, 48), 0, 0, 5, 3},
  384. {2, UPB_SIZE(28, 56), 0, 0, 5, 3},
  385. {3, UPB_SIZE(8, 16), 1, 0, 9, 1},
  386. {4, UPB_SIZE(16, 32), 2, 0, 9, 1},
  387. {6, UPB_SIZE(32, 64), 0, 0, 9, 3},
  388. };
  389. const upb_msglayout google_protobuf_SourceCodeInfo_Location_msginit = {
  390. NULL,
  391. &google_protobuf_SourceCodeInfo_Location__fields[0],
  392. UPB_SIZE(40, 80), 5, false,
  393. };
  394. static const upb_msglayout *const google_protobuf_GeneratedCodeInfo_submsgs[1] = {
  395. &google_protobuf_GeneratedCodeInfo_Annotation_msginit,
  396. };
  397. static const upb_msglayout_field google_protobuf_GeneratedCodeInfo__fields[1] = {
  398. {1, UPB_SIZE(0, 0), 0, 0, 11, 3},
  399. };
  400. const upb_msglayout google_protobuf_GeneratedCodeInfo_msginit = {
  401. &google_protobuf_GeneratedCodeInfo_submsgs[0],
  402. &google_protobuf_GeneratedCodeInfo__fields[0],
  403. UPB_SIZE(4, 8), 1, false,
  404. };
  405. static const upb_msglayout_field google_protobuf_GeneratedCodeInfo_Annotation__fields[4] = {
  406. {1, UPB_SIZE(24, 32), 0, 0, 5, 3},
  407. {2, UPB_SIZE(16, 16), 3, 0, 9, 1},
  408. {3, UPB_SIZE(4, 4), 1, 0, 5, 1},
  409. {4, UPB_SIZE(8, 8), 2, 0, 5, 1},
  410. };
  411. const upb_msglayout google_protobuf_GeneratedCodeInfo_Annotation_msginit = {
  412. NULL,
  413. &google_protobuf_GeneratedCodeInfo_Annotation__fields[0],
  414. UPB_SIZE(32, 48), 4, false,
  415. };
  416. /* Maps descriptor type -> upb field type. */
  417. const uint8_t upb_desctype_to_fieldtype[] = {
  418. UPB_WIRE_TYPE_END_GROUP, /* ENDGROUP */
  419. UPB_TYPE_DOUBLE, /* DOUBLE */
  420. UPB_TYPE_FLOAT, /* FLOAT */
  421. UPB_TYPE_INT64, /* INT64 */
  422. UPB_TYPE_UINT64, /* UINT64 */
  423. UPB_TYPE_INT32, /* INT32 */
  424. UPB_TYPE_UINT64, /* FIXED64 */
  425. UPB_TYPE_UINT32, /* FIXED32 */
  426. UPB_TYPE_BOOL, /* BOOL */
  427. UPB_TYPE_STRING, /* STRING */
  428. UPB_TYPE_MESSAGE, /* GROUP */
  429. UPB_TYPE_MESSAGE, /* MESSAGE */
  430. UPB_TYPE_BYTES, /* BYTES */
  431. UPB_TYPE_UINT32, /* UINT32 */
  432. UPB_TYPE_ENUM, /* ENUM */
  433. UPB_TYPE_INT32, /* SFIXED32 */
  434. UPB_TYPE_INT64, /* SFIXED64 */
  435. UPB_TYPE_INT32, /* SINT32 */
  436. UPB_TYPE_INT64, /* SINT64 */
  437. };
  438. /* Data pertaining to the parse. */
  439. typedef struct {
  440. /* Current decoding pointer. Points to the beginning of a field until we
  441. * have finished decoding the whole field. */
  442. const char *ptr;
  443. } upb_decstate;
  444. /* Data pertaining to a single message frame. */
  445. typedef struct {
  446. const char *limit;
  447. int32_t group_number; /* 0 if we are not parsing a group. */
  448. /* These members are unset for an unknown group frame. */
  449. char *msg;
  450. const upb_msglayout *m;
  451. } upb_decframe;
  452. #define CHK(x) if (!(x)) { return false; }
  453. static bool upb_skip_unknowngroup(upb_decstate *d, int field_number,
  454. const char *limit);
  455. static bool upb_decode_message(upb_decstate *d, const char *limit,
  456. int group_number, char *msg,
  457. const upb_msglayout *l);
  458. static bool upb_decode_varint(const char **ptr, const char *limit,
  459. uint64_t *val) {
  460. uint8_t byte;
  461. int bitpos = 0;
  462. const char *p = *ptr;
  463. *val = 0;
  464. do {
  465. CHK(bitpos < 70 && p < limit);
  466. byte = *p;
  467. *val |= (uint64_t)(byte & 0x7F) << bitpos;
  468. p++;
  469. bitpos += 7;
  470. } while (byte & 0x80);
  471. *ptr = p;
  472. return true;
  473. }
  474. static bool upb_decode_varint32(const char **ptr, const char *limit,
  475. uint32_t *val) {
  476. uint64_t u64;
  477. CHK(upb_decode_varint(ptr, limit, &u64) && u64 <= UINT32_MAX);
  478. *val = u64;
  479. return true;
  480. }
  481. static bool upb_decode_64bit(const char **ptr, const char *limit,
  482. uint64_t *val) {
  483. CHK(limit - *ptr >= 8);
  484. memcpy(val, *ptr, 8);
  485. *ptr += 8;
  486. return true;
  487. }
  488. static bool upb_decode_32bit(const char **ptr, const char *limit,
  489. uint32_t *val) {
  490. CHK(limit - *ptr >= 4);
  491. memcpy(val, *ptr, 4);
  492. *ptr += 4;
  493. return true;
  494. }
  495. static bool upb_decode_tag(const char **ptr, const char *limit,
  496. int *field_number, int *wire_type) {
  497. uint32_t tag = 0;
  498. CHK(upb_decode_varint32(ptr, limit, &tag));
  499. *field_number = tag >> 3;
  500. *wire_type = tag & 7;
  501. return true;
  502. }
  503. static int32_t upb_zzdecode_32(uint32_t n) {
  504. return (n >> 1) ^ -(int32_t)(n & 1);
  505. }
  506. static int64_t upb_zzdecode_64(uint64_t n) {
  507. return (n >> 1) ^ -(int64_t)(n & 1);
  508. }
  509. static bool upb_decode_string(const char **ptr, const char *limit,
  510. upb_stringview *val) {
  511. uint32_t len;
  512. CHK(upb_decode_varint32(ptr, limit, &len) &&
  513. len < INT32_MAX &&
  514. limit - *ptr >= (int32_t)len);
  515. *val = upb_stringview_make(*ptr, len);
  516. *ptr += len;
  517. return true;
  518. }
  519. static void upb_set32(void *msg, size_t ofs, uint32_t val) {
  520. memcpy((char*)msg + ofs, &val, sizeof(val));
  521. }
  522. static bool upb_append_unknown(upb_decstate *d, upb_decframe *frame,
  523. const char *start) {
  524. upb_msg_addunknown(frame->msg, start, d->ptr - start);
  525. return true;
  526. }
  527. static bool upb_skip_unknownfielddata(upb_decstate *d, upb_decframe *frame,
  528. int field_number, int wire_type) {
  529. switch (wire_type) {
  530. case UPB_WIRE_TYPE_VARINT: {
  531. uint64_t val;
  532. return upb_decode_varint(&d->ptr, frame->limit, &val);
  533. }
  534. case UPB_WIRE_TYPE_32BIT: {
  535. uint32_t val;
  536. return upb_decode_32bit(&d->ptr, frame->limit, &val);
  537. }
  538. case UPB_WIRE_TYPE_64BIT: {
  539. uint64_t val;
  540. return upb_decode_64bit(&d->ptr, frame->limit, &val);
  541. }
  542. case UPB_WIRE_TYPE_DELIMITED: {
  543. upb_stringview val;
  544. return upb_decode_string(&d->ptr, frame->limit, &val);
  545. }
  546. case UPB_WIRE_TYPE_START_GROUP:
  547. return upb_skip_unknowngroup(d, field_number, frame->limit);
  548. case UPB_WIRE_TYPE_END_GROUP:
  549. CHK(field_number == frame->group_number);
  550. frame->limit = d->ptr;
  551. return true;
  552. }
  553. return false;
  554. }
  555. static bool upb_array_grow(upb_array *arr, size_t elements) {
  556. size_t needed = arr->len + elements;
  557. size_t new_size = UPB_MAX(arr->size, 8);
  558. size_t new_bytes;
  559. size_t old_bytes;
  560. void *new_data;
  561. upb_alloc *alloc = upb_arena_alloc(arr->arena);
  562. while (new_size < needed) {
  563. new_size *= 2;
  564. }
  565. old_bytes = arr->len * arr->element_size;
  566. new_bytes = new_size * arr->element_size;
  567. new_data = upb_realloc(alloc, arr->data, old_bytes, new_bytes);
  568. CHK(new_data);
  569. arr->data = new_data;
  570. arr->size = new_size;
  571. return true;
  572. }
  573. static void *upb_array_reserve(upb_array *arr, size_t elements) {
  574. if (arr->size - arr->len < elements) {
  575. CHK(upb_array_grow(arr, elements));
  576. }
  577. return (char*)arr->data + (arr->len * arr->element_size);
  578. }
  579. static void *upb_array_add(upb_array *arr, size_t elements) {
  580. void *ret = upb_array_reserve(arr, elements);
  581. arr->len += elements;
  582. return ret;
  583. }
  584. static upb_array *upb_getarr(upb_decframe *frame,
  585. const upb_msglayout_field *field) {
  586. UPB_ASSERT(field->label == UPB_LABEL_REPEATED);
  587. return *(upb_array**)&frame->msg[field->offset];
  588. }
  589. static upb_array *upb_getorcreatearr(upb_decframe *frame,
  590. const upb_msglayout_field *field) {
  591. upb_array *arr = upb_getarr(frame, field);
  592. if (!arr) {
  593. upb_fieldtype_t type = upb_desctype_to_fieldtype[field->descriptortype];
  594. arr = upb_array_new(type, upb_msg_arena(frame->msg));
  595. if (!arr) {
  596. return NULL;
  597. }
  598. *(upb_array**)&frame->msg[field->offset] = arr;
  599. }
  600. return arr;
  601. }
  602. static void upb_sethasbit(upb_decframe *frame,
  603. const upb_msglayout_field *field) {
  604. int32_t hasbit = field->presence;
  605. UPB_ASSERT(field->presence > 0);
  606. frame->msg[hasbit / 8] |= (1 << (hasbit % 8));
  607. }
  608. static void upb_setoneofcase(upb_decframe *frame,
  609. const upb_msglayout_field *field) {
  610. UPB_ASSERT(field->presence < 0);
  611. upb_set32(frame->msg, ~field->presence, field->number);
  612. }
  613. static char *upb_decode_prepareslot(upb_decframe *frame,
  614. const upb_msglayout_field *field) {
  615. char *field_mem = frame->msg + field->offset;
  616. upb_array *arr;
  617. if (field->label == UPB_LABEL_REPEATED) {
  618. arr = upb_getorcreatearr(frame, field);
  619. field_mem = upb_array_reserve(arr, 1);
  620. }
  621. return field_mem;
  622. }
  623. static void upb_decode_setpresent(upb_decframe *frame,
  624. const upb_msglayout_field *field) {
  625. if (field->label == UPB_LABEL_REPEATED) {
  626. upb_array *arr = upb_getarr(frame, field);
  627. UPB_ASSERT(arr->len < arr->size);
  628. arr->len++;
  629. } else if (field->presence < 0) {
  630. upb_setoneofcase(frame, field);
  631. } else if (field->presence > 0) {
  632. upb_sethasbit(frame, field);
  633. }
  634. }
  635. static bool upb_decode_submsg(upb_decstate *d, upb_decframe *frame,
  636. const char *limit,
  637. const upb_msglayout_field *field,
  638. int group_number) {
  639. char *submsg_slot = upb_decode_prepareslot(frame, field);
  640. char *submsg = *(void **)submsg_slot;
  641. const upb_msglayout *subm;
  642. subm = frame->m->submsgs[field->submsg_index];
  643. UPB_ASSERT(subm);
  644. if (!submsg) {
  645. submsg = upb_msg_new(subm, upb_msg_arena(frame->msg));
  646. CHK(submsg);
  647. *(void**)submsg_slot = submsg;
  648. }
  649. upb_decode_message(d, limit, group_number, submsg, subm);
  650. return true;
  651. }
  652. static bool upb_decode_varintfield(upb_decstate *d, upb_decframe *frame,
  653. const char *field_start,
  654. const upb_msglayout_field *field) {
  655. uint64_t val;
  656. void *field_mem;
  657. field_mem = upb_decode_prepareslot(frame, field);
  658. CHK(field_mem);
  659. CHK(upb_decode_varint(&d->ptr, frame->limit, &val));
  660. switch ((upb_descriptortype_t)field->descriptortype) {
  661. case UPB_DESCRIPTOR_TYPE_INT64:
  662. case UPB_DESCRIPTOR_TYPE_UINT64:
  663. memcpy(field_mem, &val, sizeof(val));
  664. break;
  665. case UPB_DESCRIPTOR_TYPE_INT32:
  666. case UPB_DESCRIPTOR_TYPE_UINT32:
  667. case UPB_DESCRIPTOR_TYPE_ENUM: {
  668. uint32_t val32 = val;
  669. memcpy(field_mem, &val32, sizeof(val32));
  670. break;
  671. }
  672. case UPB_DESCRIPTOR_TYPE_BOOL: {
  673. bool valbool = val != 0;
  674. memcpy(field_mem, &valbool, sizeof(valbool));
  675. break;
  676. }
  677. case UPB_DESCRIPTOR_TYPE_SINT32: {
  678. int32_t decoded = upb_zzdecode_32(val);
  679. memcpy(field_mem, &decoded, sizeof(decoded));
  680. break;
  681. }
  682. case UPB_DESCRIPTOR_TYPE_SINT64: {
  683. int64_t decoded = upb_zzdecode_64(val);
  684. memcpy(field_mem, &decoded, sizeof(decoded));
  685. break;
  686. }
  687. default:
  688. return upb_append_unknown(d, frame, field_start);
  689. }
  690. upb_decode_setpresent(frame, field);
  691. return true;
  692. }
  693. static bool upb_decode_64bitfield(upb_decstate *d, upb_decframe *frame,
  694. const char *field_start,
  695. const upb_msglayout_field *field) {
  696. void *field_mem;
  697. uint64_t val;
  698. field_mem = upb_decode_prepareslot(frame, field);
  699. CHK(field_mem);
  700. CHK(upb_decode_64bit(&d->ptr, frame->limit, &val));
  701. switch ((upb_descriptortype_t)field->descriptortype) {
  702. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  703. case UPB_DESCRIPTOR_TYPE_FIXED64:
  704. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  705. memcpy(field_mem, &val, sizeof(val));
  706. break;
  707. default:
  708. return upb_append_unknown(d, frame, field_start);
  709. }
  710. upb_decode_setpresent(frame, field);
  711. return true;
  712. }
  713. static bool upb_decode_32bitfield(upb_decstate *d, upb_decframe *frame,
  714. const char *field_start,
  715. const upb_msglayout_field *field) {
  716. void *field_mem;
  717. uint32_t val;
  718. field_mem = upb_decode_prepareslot(frame, field);
  719. CHK(field_mem);
  720. CHK(upb_decode_32bit(&d->ptr, frame->limit, &val));
  721. switch ((upb_descriptortype_t)field->descriptortype) {
  722. case UPB_DESCRIPTOR_TYPE_FLOAT:
  723. case UPB_DESCRIPTOR_TYPE_FIXED32:
  724. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  725. memcpy(field_mem, &val, sizeof(val));
  726. break;
  727. default:
  728. return upb_append_unknown(d, frame, field_start);
  729. }
  730. upb_decode_setpresent(frame, field);
  731. return true;
  732. }
  733. static bool upb_decode_fixedpacked(upb_array *arr, upb_stringview data,
  734. int elem_size) {
  735. int elements = data.size / elem_size;
  736. void *field_mem;
  737. CHK((size_t)(elements * elem_size) == data.size);
  738. field_mem = upb_array_add(arr, elements);
  739. CHK(field_mem);
  740. memcpy(field_mem, data.data, data.size);
  741. return true;
  742. }
  743. static bool upb_decode_toarray(upb_decstate *d, upb_decframe *frame,
  744. const char *field_start,
  745. const upb_msglayout_field *field,
  746. upb_stringview val) {
  747. upb_array *arr = upb_getorcreatearr(frame, field);
  748. #define VARINT_CASE(ctype, decode) { \
  749. const char *ptr = val.data; \
  750. const char *limit = ptr + val.size; \
  751. while (ptr < limit) { \
  752. uint64_t val; \
  753. void *field_mem; \
  754. ctype decoded; \
  755. CHK(upb_decode_varint(&ptr, limit, &val)); \
  756. decoded = (decode)(val); \
  757. field_mem = upb_array_add(arr, 1); \
  758. CHK(field_mem); \
  759. memcpy(field_mem, &decoded, sizeof(ctype)); \
  760. } \
  761. return true; \
  762. }
  763. switch ((upb_descriptortype_t)field->descriptortype) {
  764. case UPB_DESCRIPTOR_TYPE_STRING:
  765. case UPB_DESCRIPTOR_TYPE_BYTES: {
  766. void *field_mem = upb_array_add(arr, 1);
  767. CHK(field_mem);
  768. memcpy(field_mem, &val, sizeof(val));
  769. return true;
  770. }
  771. case UPB_DESCRIPTOR_TYPE_FLOAT:
  772. case UPB_DESCRIPTOR_TYPE_FIXED32:
  773. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  774. return upb_decode_fixedpacked(arr, val, sizeof(int32_t));
  775. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  776. case UPB_DESCRIPTOR_TYPE_FIXED64:
  777. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  778. return upb_decode_fixedpacked(arr, val, sizeof(int64_t));
  779. case UPB_DESCRIPTOR_TYPE_INT32:
  780. case UPB_DESCRIPTOR_TYPE_UINT32:
  781. case UPB_DESCRIPTOR_TYPE_ENUM:
  782. /* TODO: proto2 enum field that isn't in the enum. */
  783. VARINT_CASE(uint32_t, uint32_t);
  784. case UPB_DESCRIPTOR_TYPE_INT64:
  785. case UPB_DESCRIPTOR_TYPE_UINT64:
  786. VARINT_CASE(uint64_t, uint64_t);
  787. case UPB_DESCRIPTOR_TYPE_BOOL:
  788. VARINT_CASE(bool, bool);
  789. case UPB_DESCRIPTOR_TYPE_SINT32:
  790. VARINT_CASE(int32_t, upb_zzdecode_32);
  791. case UPB_DESCRIPTOR_TYPE_SINT64:
  792. VARINT_CASE(int64_t, upb_zzdecode_64);
  793. case UPB_DESCRIPTOR_TYPE_MESSAGE: {
  794. const upb_msglayout *subm;
  795. char *submsg;
  796. void *field_mem;
  797. CHK(val.size <= (size_t)(frame->limit - val.data));
  798. d->ptr -= val.size;
  799. /* Create elemente message. */
  800. subm = frame->m->submsgs[field->submsg_index];
  801. UPB_ASSERT(subm);
  802. submsg = upb_msg_new(subm, upb_msg_arena(frame->msg));
  803. CHK(submsg);
  804. field_mem = upb_array_add(arr, 1);
  805. CHK(field_mem);
  806. *(void**)field_mem = submsg;
  807. return upb_decode_message(
  808. d, val.data + val.size, frame->group_number, submsg, subm);
  809. }
  810. case UPB_DESCRIPTOR_TYPE_GROUP:
  811. return upb_append_unknown(d, frame, field_start);
  812. }
  813. #undef VARINT_CASE
  814. UPB_UNREACHABLE();
  815. }
  816. static bool upb_decode_delimitedfield(upb_decstate *d, upb_decframe *frame,
  817. const char *field_start,
  818. const upb_msglayout_field *field) {
  819. upb_stringview val;
  820. CHK(upb_decode_string(&d->ptr, frame->limit, &val));
  821. if (field->label == UPB_LABEL_REPEATED) {
  822. return upb_decode_toarray(d, frame, field_start, field, val);
  823. } else {
  824. switch ((upb_descriptortype_t)field->descriptortype) {
  825. case UPB_DESCRIPTOR_TYPE_STRING:
  826. case UPB_DESCRIPTOR_TYPE_BYTES: {
  827. void *field_mem = upb_decode_prepareslot(frame, field);
  828. CHK(field_mem);
  829. memcpy(field_mem, &val, sizeof(val));
  830. break;
  831. }
  832. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  833. CHK(val.size <= (size_t)(frame->limit - val.data));
  834. d->ptr -= val.size;
  835. CHK(upb_decode_submsg(d, frame, val.data + val.size, field, 0));
  836. break;
  837. default:
  838. /* TODO(haberman): should we accept the last element of a packed? */
  839. return upb_append_unknown(d, frame, field_start);
  840. }
  841. upb_decode_setpresent(frame, field);
  842. return true;
  843. }
  844. }
  845. static const upb_msglayout_field *upb_find_field(const upb_msglayout *l,
  846. uint32_t field_number) {
  847. /* Lots of optimization opportunities here. */
  848. int i;
  849. for (i = 0; i < l->field_count; i++) {
  850. if (l->fields[i].number == field_number) {
  851. return &l->fields[i];
  852. }
  853. }
  854. return NULL; /* Unknown field. */
  855. }
  856. static bool upb_decode_field(upb_decstate *d, upb_decframe *frame) {
  857. int field_number;
  858. int wire_type;
  859. const char *field_start = d->ptr;
  860. const upb_msglayout_field *field;
  861. CHK(upb_decode_tag(&d->ptr, frame->limit, &field_number, &wire_type));
  862. field = upb_find_field(frame->m, field_number);
  863. if (field) {
  864. switch (wire_type) {
  865. case UPB_WIRE_TYPE_VARINT:
  866. return upb_decode_varintfield(d, frame, field_start, field);
  867. case UPB_WIRE_TYPE_32BIT:
  868. return upb_decode_32bitfield(d, frame, field_start, field);
  869. case UPB_WIRE_TYPE_64BIT:
  870. return upb_decode_64bitfield(d, frame, field_start, field);
  871. case UPB_WIRE_TYPE_DELIMITED:
  872. return upb_decode_delimitedfield(d, frame, field_start, field);
  873. case UPB_WIRE_TYPE_START_GROUP:
  874. CHK(field->descriptortype == UPB_DESCRIPTOR_TYPE_GROUP);
  875. return upb_decode_submsg(d, frame, frame->limit, field, field_number);
  876. case UPB_WIRE_TYPE_END_GROUP:
  877. CHK(frame->group_number == field_number)
  878. frame->limit = d->ptr;
  879. return true;
  880. default:
  881. return false;
  882. }
  883. } else {
  884. CHK(field_number != 0);
  885. CHK(upb_skip_unknownfielddata(d, frame, field_number, wire_type));
  886. CHK(upb_append_unknown(d, frame, field_start));
  887. return true;
  888. }
  889. }
  890. static bool upb_skip_unknowngroup(upb_decstate *d, int field_number,
  891. const char *limit) {
  892. upb_decframe frame;
  893. frame.msg = NULL;
  894. frame.m = NULL;
  895. frame.group_number = field_number;
  896. frame.limit = limit;
  897. while (d->ptr < frame.limit) {
  898. int wire_type;
  899. int field_number;
  900. CHK(upb_decode_tag(&d->ptr, frame.limit, &field_number, &wire_type));
  901. CHK(upb_skip_unknownfielddata(d, &frame, field_number, wire_type));
  902. }
  903. return true;
  904. }
  905. static bool upb_decode_message(upb_decstate *d, const char *limit,
  906. int group_number, char *msg,
  907. const upb_msglayout *l) {
  908. upb_decframe frame;
  909. frame.group_number = group_number;
  910. frame.limit = limit;
  911. frame.msg = msg;
  912. frame.m = l;
  913. while (d->ptr < frame.limit) {
  914. CHK(upb_decode_field(d, &frame));
  915. }
  916. return true;
  917. }
  918. bool upb_decode(upb_stringview buf, void *msg, const upb_msglayout *l) {
  919. upb_decstate state;
  920. state.ptr = buf.data;
  921. return upb_decode_message(&state, buf.data + buf.size, 0, msg, l);
  922. }
  923. #undef CHK
  924. #include <ctype.h>
  925. #include <stdlib.h>
  926. #include <string.h>
  927. typedef struct {
  928. size_t len;
  929. char str[1]; /* Null-terminated string data follows. */
  930. } str_t;
  931. static str_t *newstr(const char *data, size_t len) {
  932. str_t *ret = upb_gmalloc(sizeof(*ret) + len);
  933. if (!ret) return NULL;
  934. ret->len = len;
  935. memcpy(ret->str, data, len);
  936. ret->str[len] = '\0';
  937. return ret;
  938. }
  939. static void freestr(str_t *s) { upb_gfree(s); }
  940. /* isalpha() etc. from <ctype.h> are locale-dependent, which we don't want. */
  941. static bool upb_isbetween(char c, char low, char high) {
  942. return c >= low && c <= high;
  943. }
  944. static bool upb_isletter(char c) {
  945. return upb_isbetween(c, 'A', 'Z') || upb_isbetween(c, 'a', 'z') || c == '_';
  946. }
  947. static bool upb_isalphanum(char c) {
  948. return upb_isletter(c) || upb_isbetween(c, '0', '9');
  949. }
  950. static bool upb_isident(const char *str, size_t len, bool full, upb_status *s) {
  951. bool start = true;
  952. size_t i;
  953. for (i = 0; i < len; i++) {
  954. char c = str[i];
  955. if (c == '.') {
  956. if (start || !full) {
  957. upb_status_seterrf(s, "invalid name: unexpected '.' (%s)", str);
  958. return false;
  959. }
  960. start = true;
  961. } else if (start) {
  962. if (!upb_isletter(c)) {
  963. upb_status_seterrf(
  964. s, "invalid name: path components must start with a letter (%s)",
  965. str);
  966. return false;
  967. }
  968. start = false;
  969. } else {
  970. if (!upb_isalphanum(c)) {
  971. upb_status_seterrf(s, "invalid name: non-alphanumeric character (%s)",
  972. str);
  973. return false;
  974. }
  975. }
  976. }
  977. return !start;
  978. }
  979. static bool upb_isoneof(const upb_refcounted *def) {
  980. return def->vtbl == &upb_oneofdef_vtbl;
  981. }
  982. static bool upb_isfield(const upb_refcounted *def) {
  983. return def->vtbl == &upb_fielddef_vtbl;
  984. }
  985. static const upb_oneofdef *upb_trygetoneof(const upb_refcounted *def) {
  986. return upb_isoneof(def) ? (const upb_oneofdef*)def : NULL;
  987. }
  988. static const upb_fielddef *upb_trygetfield(const upb_refcounted *def) {
  989. return upb_isfield(def) ? (const upb_fielddef*)def : NULL;
  990. }
  991. /* upb_def ********************************************************************/
  992. upb_deftype_t upb_def_type(const upb_def *d) { return d->type; }
  993. const char *upb_def_fullname(const upb_def *d) { return d->fullname; }
  994. const char *upb_def_name(const upb_def *d) {
  995. const char *p;
  996. if (d->fullname == NULL) {
  997. return NULL;
  998. } else if ((p = strrchr(d->fullname, '.')) == NULL) {
  999. /* No '.' in the name, return the full string. */
  1000. return d->fullname;
  1001. } else {
  1002. /* Return one past the last '.'. */
  1003. return p + 1;
  1004. }
  1005. }
  1006. bool upb_def_setfullname(upb_def *def, const char *fullname, upb_status *s) {
  1007. UPB_ASSERT(!upb_def_isfrozen(def));
  1008. if (!upb_isident(fullname, strlen(fullname), true, s)) {
  1009. return false;
  1010. }
  1011. fullname = upb_gstrdup(fullname);
  1012. if (!fullname) {
  1013. upb_upberr_setoom(s);
  1014. return false;
  1015. }
  1016. upb_gfree((void*)def->fullname);
  1017. def->fullname = fullname;
  1018. return true;
  1019. }
  1020. const upb_filedef *upb_def_file(const upb_def *d) { return d->file; }
  1021. static bool upb_def_init(upb_def *def, upb_deftype_t type,
  1022. const struct upb_refcounted_vtbl *vtbl,
  1023. const void *owner) {
  1024. if (!upb_refcounted_init(upb_def_upcast_mutable(def), vtbl, owner)) return false;
  1025. def->type = type;
  1026. def->fullname = NULL;
  1027. def->came_from_user = false;
  1028. def->file = NULL;
  1029. return true;
  1030. }
  1031. static void upb_def_uninit(upb_def *def) {
  1032. upb_gfree((void*)def->fullname);
  1033. }
  1034. static const char *msgdef_name(const upb_msgdef *m) {
  1035. const char *name = upb_def_fullname(upb_msgdef_upcast(m));
  1036. return name ? name : "(anonymous)";
  1037. }
  1038. static bool upb_validate_field(upb_fielddef *f, upb_status *s) {
  1039. if (upb_fielddef_name(f) == NULL || upb_fielddef_number(f) == 0) {
  1040. upb_status_seterrmsg(s, "fielddef must have name and number set");
  1041. return false;
  1042. }
  1043. if (!f->type_is_set_) {
  1044. upb_status_seterrmsg(s, "fielddef type was not initialized");
  1045. return false;
  1046. }
  1047. if (upb_fielddef_lazy(f) &&
  1048. upb_fielddef_descriptortype(f) != UPB_DESCRIPTOR_TYPE_MESSAGE) {
  1049. upb_status_seterrmsg(s,
  1050. "only length-delimited submessage fields may be lazy");
  1051. return false;
  1052. }
  1053. if (upb_fielddef_hassubdef(f)) {
  1054. const upb_def *subdef;
  1055. if (f->subdef_is_symbolic) {
  1056. upb_status_seterrf(s, "field '%s.%s' has not been resolved",
  1057. msgdef_name(f->msg.def), upb_fielddef_name(f));
  1058. return false;
  1059. }
  1060. subdef = upb_fielddef_subdef(f);
  1061. if (subdef == NULL) {
  1062. upb_status_seterrf(s, "field %s.%s is missing required subdef",
  1063. msgdef_name(f->msg.def), upb_fielddef_name(f));
  1064. return false;
  1065. }
  1066. if (!upb_def_isfrozen(subdef) && !subdef->came_from_user) {
  1067. upb_status_seterrf(s,
  1068. "subdef of field %s.%s is not frozen or being frozen",
  1069. msgdef_name(f->msg.def), upb_fielddef_name(f));
  1070. return false;
  1071. }
  1072. }
  1073. if (upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  1074. bool has_default_name = upb_fielddef_enumhasdefaultstr(f);
  1075. bool has_default_number = upb_fielddef_enumhasdefaultint32(f);
  1076. /* Previously verified by upb_validate_enumdef(). */
  1077. UPB_ASSERT(upb_enumdef_numvals(upb_fielddef_enumsubdef(f)) > 0);
  1078. /* We've already validated that we have an associated enumdef and that it
  1079. * has at least one member, so at least one of these should be true.
  1080. * Because if the user didn't set anything, we'll pick up the enum's
  1081. * default, but if the user *did* set something we should at least pick up
  1082. * the one they set (int32 or string). */
  1083. UPB_ASSERT(has_default_name || has_default_number);
  1084. if (!has_default_name) {
  1085. upb_status_seterrf(s,
  1086. "enum default for field %s.%s (%d) is not in the enum",
  1087. msgdef_name(f->msg.def), upb_fielddef_name(f),
  1088. upb_fielddef_defaultint32(f));
  1089. return false;
  1090. }
  1091. if (!has_default_number) {
  1092. upb_status_seterrf(s,
  1093. "enum default for field %s.%s (%s) is not in the enum",
  1094. msgdef_name(f->msg.def), upb_fielddef_name(f),
  1095. upb_fielddef_defaultstr(f, NULL));
  1096. return false;
  1097. }
  1098. /* Lift the effective numeric default into the field's default slot, in case
  1099. * we were only getting it "by reference" from the enumdef. */
  1100. upb_fielddef_setdefaultint32(f, upb_fielddef_defaultint32(f));
  1101. }
  1102. /* Ensure that MapEntry submessages only appear as repeated fields, not
  1103. * optional/required (singular) fields. */
  1104. if (upb_fielddef_type(f) == UPB_TYPE_MESSAGE &&
  1105. upb_fielddef_msgsubdef(f) != NULL) {
  1106. const upb_msgdef *subdef = upb_fielddef_msgsubdef(f);
  1107. if (upb_msgdef_mapentry(subdef) && !upb_fielddef_isseq(f)) {
  1108. upb_status_seterrf(s,
  1109. "Field %s refers to mapentry message but is not "
  1110. "a repeated field",
  1111. upb_fielddef_name(f) ? upb_fielddef_name(f) :
  1112. "(unnamed)");
  1113. return false;
  1114. }
  1115. }
  1116. return true;
  1117. }
  1118. static bool upb_validate_enumdef(const upb_enumdef *e, upb_status *s) {
  1119. if (upb_enumdef_numvals(e) == 0) {
  1120. upb_status_seterrf(s, "enum %s has no members (must have at least one)",
  1121. upb_enumdef_fullname(e));
  1122. return false;
  1123. }
  1124. return true;
  1125. }
  1126. /* All submessage fields are lower than all other fields.
  1127. * Secondly, fields are increasing in order. */
  1128. uint32_t field_rank(const upb_fielddef *f) {
  1129. uint32_t ret = upb_fielddef_number(f);
  1130. const uint32_t high_bit = 1 << 30;
  1131. UPB_ASSERT(ret < high_bit);
  1132. if (!upb_fielddef_issubmsg(f))
  1133. ret |= high_bit;
  1134. return ret;
  1135. }
  1136. int cmp_fields(const void *p1, const void *p2) {
  1137. const upb_fielddef *f1 = *(upb_fielddef*const*)p1;
  1138. const upb_fielddef *f2 = *(upb_fielddef*const*)p2;
  1139. return field_rank(f1) - field_rank(f2);
  1140. }
  1141. static bool assign_msg_indices(upb_msgdef *m, upb_status *s) {
  1142. /* Sort fields. upb internally relies on UPB_TYPE_MESSAGE fields having the
  1143. * lowest indexes, but we do not publicly guarantee this. */
  1144. upb_msg_field_iter j;
  1145. upb_msg_oneof_iter k;
  1146. int i;
  1147. uint32_t selector;
  1148. int n = upb_msgdef_numfields(m);
  1149. upb_fielddef **fields;
  1150. if (n == 0) {
  1151. m->selector_count = UPB_STATIC_SELECTOR_COUNT;
  1152. m->submsg_field_count = 0;
  1153. return true;
  1154. }
  1155. fields = upb_gmalloc(n * sizeof(*fields));
  1156. if (!fields) {
  1157. upb_upberr_setoom(s);
  1158. return false;
  1159. }
  1160. m->submsg_field_count = 0;
  1161. for(i = 0, upb_msg_field_begin(&j, m);
  1162. !upb_msg_field_done(&j);
  1163. upb_msg_field_next(&j), i++) {
  1164. upb_fielddef *f = upb_msg_iter_field(&j);
  1165. UPB_ASSERT(f->msg.def == m);
  1166. if (!upb_validate_field(f, s)) {
  1167. upb_gfree(fields);
  1168. return false;
  1169. }
  1170. if (upb_fielddef_issubmsg(f)) {
  1171. m->submsg_field_count++;
  1172. }
  1173. fields[i] = f;
  1174. }
  1175. qsort(fields, n, sizeof(*fields), cmp_fields);
  1176. selector = UPB_STATIC_SELECTOR_COUNT + m->submsg_field_count;
  1177. for (i = 0; i < n; i++) {
  1178. upb_fielddef *f = fields[i];
  1179. f->index_ = i;
  1180. f->selector_base = selector + upb_handlers_selectorbaseoffset(f);
  1181. selector += upb_handlers_selectorcount(f);
  1182. }
  1183. m->selector_count = selector;
  1184. #ifndef NDEBUG
  1185. {
  1186. /* Verify that all selectors for the message are distinct. */
  1187. #define TRY(type) \
  1188. if (upb_handlers_getselector(f, type, &sel)) upb_inttable_insert(&t, sel, v);
  1189. upb_inttable t;
  1190. upb_value v;
  1191. upb_selector_t sel;
  1192. upb_inttable_init(&t, UPB_CTYPE_BOOL);
  1193. v = upb_value_bool(true);
  1194. upb_inttable_insert(&t, UPB_STARTMSG_SELECTOR, v);
  1195. upb_inttable_insert(&t, UPB_ENDMSG_SELECTOR, v);
  1196. upb_inttable_insert(&t, UPB_UNKNOWN_SELECTOR, v);
  1197. for(upb_msg_field_begin(&j, m);
  1198. !upb_msg_field_done(&j);
  1199. upb_msg_field_next(&j)) {
  1200. upb_fielddef *f = upb_msg_iter_field(&j);
  1201. /* These calls will assert-fail in upb_table if the value already
  1202. * exists. */
  1203. TRY(UPB_HANDLER_INT32);
  1204. TRY(UPB_HANDLER_INT64)
  1205. TRY(UPB_HANDLER_UINT32)
  1206. TRY(UPB_HANDLER_UINT64)
  1207. TRY(UPB_HANDLER_FLOAT)
  1208. TRY(UPB_HANDLER_DOUBLE)
  1209. TRY(UPB_HANDLER_BOOL)
  1210. TRY(UPB_HANDLER_STARTSTR)
  1211. TRY(UPB_HANDLER_STRING)
  1212. TRY(UPB_HANDLER_ENDSTR)
  1213. TRY(UPB_HANDLER_STARTSUBMSG)
  1214. TRY(UPB_HANDLER_ENDSUBMSG)
  1215. TRY(UPB_HANDLER_STARTSEQ)
  1216. TRY(UPB_HANDLER_ENDSEQ)
  1217. }
  1218. upb_inttable_uninit(&t);
  1219. }
  1220. #undef TRY
  1221. #endif
  1222. for(upb_msg_oneof_begin(&k, m), i = 0;
  1223. !upb_msg_oneof_done(&k);
  1224. upb_msg_oneof_next(&k), i++) {
  1225. upb_oneofdef *o = upb_msg_iter_oneof(&k);
  1226. o->index = i;
  1227. }
  1228. upb_gfree(fields);
  1229. return true;
  1230. }
  1231. static void assign_msg_wellknowntype(upb_msgdef *m) {
  1232. const char *name = upb_msgdef_fullname(m);
  1233. if (name == NULL) {
  1234. m->well_known_type = UPB_WELLKNOWN_UNSPECIFIED;
  1235. return;
  1236. }
  1237. if (!strcmp(name, "google.protobuf.Any")) {
  1238. m->well_known_type = UPB_WELLKNOWN_ANY;
  1239. } else if (!strcmp(name, "google.protobuf.FieldMask")) {
  1240. m->well_known_type = UPB_WELLKNOWN_FIELDMASK;
  1241. } else if (!strcmp(name, "google.protobuf.Duration")) {
  1242. m->well_known_type = UPB_WELLKNOWN_DURATION;
  1243. } else if (!strcmp(name, "google.protobuf.Timestamp")) {
  1244. m->well_known_type = UPB_WELLKNOWN_TIMESTAMP;
  1245. } else if (!strcmp(name, "google.protobuf.DoubleValue")) {
  1246. m->well_known_type = UPB_WELLKNOWN_DOUBLEVALUE;
  1247. } else if (!strcmp(name, "google.protobuf.FloatValue")) {
  1248. m->well_known_type = UPB_WELLKNOWN_FLOATVALUE;
  1249. } else if (!strcmp(name, "google.protobuf.Int64Value")) {
  1250. m->well_known_type = UPB_WELLKNOWN_INT64VALUE;
  1251. } else if (!strcmp(name, "google.protobuf.UInt64Value")) {
  1252. m->well_known_type = UPB_WELLKNOWN_UINT64VALUE;
  1253. } else if (!strcmp(name, "google.protobuf.Int32Value")) {
  1254. m->well_known_type = UPB_WELLKNOWN_INT32VALUE;
  1255. } else if (!strcmp(name, "google.protobuf.UInt32Value")) {
  1256. m->well_known_type = UPB_WELLKNOWN_UINT32VALUE;
  1257. } else if (!strcmp(name, "google.protobuf.BoolValue")) {
  1258. m->well_known_type = UPB_WELLKNOWN_BOOLVALUE;
  1259. } else if (!strcmp(name, "google.protobuf.StringValue")) {
  1260. m->well_known_type = UPB_WELLKNOWN_STRINGVALUE;
  1261. } else if (!strcmp(name, "google.protobuf.BytesValue")) {
  1262. m->well_known_type = UPB_WELLKNOWN_BYTESVALUE;
  1263. } else if (!strcmp(name, "google.protobuf.Value")) {
  1264. m->well_known_type = UPB_WELLKNOWN_VALUE;
  1265. } else if (!strcmp(name, "google.protobuf.ListValue")) {
  1266. m->well_known_type = UPB_WELLKNOWN_LISTVALUE;
  1267. } else if (!strcmp(name, "google.protobuf.Struct")) {
  1268. m->well_known_type = UPB_WELLKNOWN_STRUCT;
  1269. } else {
  1270. m->well_known_type = UPB_WELLKNOWN_UNSPECIFIED;
  1271. }
  1272. }
  1273. bool _upb_def_validate(upb_def *const*defs, size_t n, upb_status *s) {
  1274. size_t i;
  1275. /* First perform validation, in two passes so we can check that we have a
  1276. * transitive closure without needing to search. */
  1277. for (i = 0; i < n; i++) {
  1278. upb_def *def = defs[i];
  1279. if (upb_def_isfrozen(def)) {
  1280. /* Could relax this requirement if it's annoying. */
  1281. upb_status_seterrmsg(s, "def is already frozen");
  1282. goto err;
  1283. } else if (def->type == UPB_DEF_FIELD) {
  1284. upb_status_seterrmsg(s, "standalone fielddefs can not be frozen");
  1285. goto err;
  1286. } else {
  1287. /* Set now to detect transitive closure in the second pass. */
  1288. def->came_from_user = true;
  1289. if (def->type == UPB_DEF_ENUM &&
  1290. !upb_validate_enumdef(upb_dyncast_enumdef(def), s)) {
  1291. goto err;
  1292. }
  1293. }
  1294. }
  1295. /* Second pass of validation. Also assign selector bases and indexes, and
  1296. * compact tables. */
  1297. for (i = 0; i < n; i++) {
  1298. upb_def *def = defs[i];
  1299. upb_msgdef *m = upb_dyncast_msgdef_mutable(def);
  1300. upb_enumdef *e = upb_dyncast_enumdef_mutable(def);
  1301. if (m) {
  1302. upb_inttable_compact(&m->itof);
  1303. if (!assign_msg_indices(m, s)) {
  1304. goto err;
  1305. }
  1306. assign_msg_wellknowntype(m);
  1307. /* m->well_known_type = UPB_WELLKNOWN_UNSPECIFIED; */
  1308. } else if (e) {
  1309. upb_inttable_compact(&e->iton);
  1310. }
  1311. }
  1312. return true;
  1313. err:
  1314. for (i = 0; i < n; i++) {
  1315. upb_def *def = defs[i];
  1316. def->came_from_user = false;
  1317. }
  1318. UPB_ASSERT(!(s && upb_ok(s)));
  1319. return false;
  1320. }
  1321. bool upb_def_freeze(upb_def *const* defs, size_t n, upb_status *s) {
  1322. /* Def graph contains FieldDefs between each MessageDef, so double the
  1323. * limit. */
  1324. const size_t maxdepth = UPB_MAX_MESSAGE_DEPTH * 2;
  1325. if (!_upb_def_validate(defs, n, s)) {
  1326. return false;
  1327. }
  1328. /* Validation all passed; freeze the objects. */
  1329. return upb_refcounted_freeze((upb_refcounted *const*)defs, n, s, maxdepth);
  1330. }
  1331. /* upb_enumdef ****************************************************************/
  1332. static void visitenum(const upb_refcounted *r, upb_refcounted_visit *visit,
  1333. void *closure) {
  1334. const upb_enumdef *e = (const upb_enumdef*)r;
  1335. const upb_def *def = upb_enumdef_upcast(e);
  1336. if (upb_def_file(def)) {
  1337. visit(r, upb_filedef_upcast(upb_def_file(def)), closure);
  1338. }
  1339. }
  1340. static void freeenum(upb_refcounted *r) {
  1341. upb_enumdef *e = (upb_enumdef*)r;
  1342. upb_inttable_iter i;
  1343. upb_inttable_begin(&i, &e->iton);
  1344. for( ; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  1345. /* To clean up the upb_gstrdup() from upb_enumdef_addval(). */
  1346. upb_gfree(upb_value_getcstr(upb_inttable_iter_value(&i)));
  1347. }
  1348. upb_strtable_uninit(&e->ntoi);
  1349. upb_inttable_uninit(&e->iton);
  1350. upb_def_uninit(upb_enumdef_upcast_mutable(e));
  1351. upb_gfree(e);
  1352. }
  1353. const struct upb_refcounted_vtbl upb_enumdef_vtbl = {&visitenum, &freeenum};
  1354. upb_enumdef *upb_enumdef_new(const void *owner) {
  1355. upb_enumdef *e = upb_gmalloc(sizeof(*e));
  1356. if (!e) return NULL;
  1357. if (!upb_def_init(upb_enumdef_upcast_mutable(e), UPB_DEF_ENUM,
  1358. &upb_enumdef_vtbl, owner)) {
  1359. goto err2;
  1360. }
  1361. if (!upb_strtable_init(&e->ntoi, UPB_CTYPE_INT32)) goto err2;
  1362. if (!upb_inttable_init(&e->iton, UPB_CTYPE_CSTR)) goto err1;
  1363. return e;
  1364. err1:
  1365. upb_strtable_uninit(&e->ntoi);
  1366. err2:
  1367. upb_gfree(e);
  1368. return NULL;
  1369. }
  1370. bool upb_enumdef_freeze(upb_enumdef *e, upb_status *status) {
  1371. upb_def *d = upb_enumdef_upcast_mutable(e);
  1372. return upb_def_freeze(&d, 1, status);
  1373. }
  1374. const char *upb_enumdef_fullname(const upb_enumdef *e) {
  1375. return upb_def_fullname(upb_enumdef_upcast(e));
  1376. }
  1377. const char *upb_enumdef_name(const upb_enumdef *e) {
  1378. return upb_def_name(upb_enumdef_upcast(e));
  1379. }
  1380. bool upb_enumdef_setfullname(upb_enumdef *e, const char *fullname,
  1381. upb_status *s) {
  1382. return upb_def_setfullname(upb_enumdef_upcast_mutable(e), fullname, s);
  1383. }
  1384. bool upb_enumdef_addval(upb_enumdef *e, const char *name, int32_t num,
  1385. upb_status *status) {
  1386. char *name2;
  1387. if (!upb_isident(name, strlen(name), false, status)) {
  1388. return false;
  1389. }
  1390. if (upb_enumdef_ntoiz(e, name, NULL)) {
  1391. upb_status_seterrf(status, "name '%s' is already defined", name);
  1392. return false;
  1393. }
  1394. if (!upb_strtable_insert(&e->ntoi, name, upb_value_int32(num))) {
  1395. upb_status_seterrmsg(status, "out of memory");
  1396. return false;
  1397. }
  1398. if (!upb_inttable_lookup(&e->iton, num, NULL)) {
  1399. name2 = upb_gstrdup(name);
  1400. if (!name2 || !upb_inttable_insert(&e->iton, num, upb_value_cstr(name2))) {
  1401. upb_status_seterrmsg(status, "out of memory");
  1402. upb_strtable_remove(&e->ntoi, name, NULL);
  1403. return false;
  1404. }
  1405. }
  1406. if (upb_enumdef_numvals(e) == 1) {
  1407. bool ok = upb_enumdef_setdefault(e, num, NULL);
  1408. UPB_ASSERT(ok);
  1409. }
  1410. return true;
  1411. }
  1412. int32_t upb_enumdef_default(const upb_enumdef *e) {
  1413. UPB_ASSERT(upb_enumdef_iton(e, e->defaultval));
  1414. return e->defaultval;
  1415. }
  1416. bool upb_enumdef_setdefault(upb_enumdef *e, int32_t val, upb_status *s) {
  1417. UPB_ASSERT(!upb_enumdef_isfrozen(e));
  1418. if (!upb_enumdef_iton(e, val)) {
  1419. upb_status_seterrf(s, "number '%d' is not in the enum.", val);
  1420. return false;
  1421. }
  1422. e->defaultval = val;
  1423. return true;
  1424. }
  1425. int upb_enumdef_numvals(const upb_enumdef *e) {
  1426. return upb_strtable_count(&e->ntoi);
  1427. }
  1428. void upb_enum_begin(upb_enum_iter *i, const upb_enumdef *e) {
  1429. /* We iterate over the ntoi table, to account for duplicate numbers. */
  1430. upb_strtable_begin(i, &e->ntoi);
  1431. }
  1432. void upb_enum_next(upb_enum_iter *iter) { upb_strtable_next(iter); }
  1433. bool upb_enum_done(upb_enum_iter *iter) { return upb_strtable_done(iter); }
  1434. bool upb_enumdef_ntoi(const upb_enumdef *def, const char *name,
  1435. size_t len, int32_t *num) {
  1436. upb_value v;
  1437. if (!upb_strtable_lookup2(&def->ntoi, name, len, &v)) {
  1438. return false;
  1439. }
  1440. if (num) *num = upb_value_getint32(v);
  1441. return true;
  1442. }
  1443. const char *upb_enumdef_iton(const upb_enumdef *def, int32_t num) {
  1444. upb_value v;
  1445. return upb_inttable_lookup32(&def->iton, num, &v) ?
  1446. upb_value_getcstr(v) : NULL;
  1447. }
  1448. const char *upb_enum_iter_name(upb_enum_iter *iter) {
  1449. return upb_strtable_iter_key(iter);
  1450. }
  1451. int32_t upb_enum_iter_number(upb_enum_iter *iter) {
  1452. return upb_value_getint32(upb_strtable_iter_value(iter));
  1453. }
  1454. /* upb_fielddef ***************************************************************/
  1455. static void upb_fielddef_init_default(upb_fielddef *f);
  1456. static void upb_fielddef_uninit_default(upb_fielddef *f) {
  1457. if (f->type_is_set_ && f->default_is_string && f->defaultval.bytes)
  1458. freestr(f->defaultval.bytes);
  1459. }
  1460. const char *upb_fielddef_fullname(const upb_fielddef *e) {
  1461. return upb_def_fullname(upb_fielddef_upcast(e));
  1462. }
  1463. static void visitfield(const upb_refcounted *r, upb_refcounted_visit *visit,
  1464. void *closure) {
  1465. const upb_fielddef *f = (const upb_fielddef*)r;
  1466. const upb_def *def = upb_fielddef_upcast(f);
  1467. if (upb_fielddef_containingtype(f)) {
  1468. visit(r, upb_msgdef_upcast2(upb_fielddef_containingtype(f)), closure);
  1469. }
  1470. if (upb_fielddef_containingoneof(f)) {
  1471. visit(r, upb_oneofdef_upcast(upb_fielddef_containingoneof(f)), closure);
  1472. }
  1473. if (upb_fielddef_subdef(f)) {
  1474. visit(r, upb_def_upcast(upb_fielddef_subdef(f)), closure);
  1475. }
  1476. if (upb_def_file(def)) {
  1477. visit(r, upb_filedef_upcast(upb_def_file(def)), closure);
  1478. }
  1479. }
  1480. static void freefield(upb_refcounted *r) {
  1481. upb_fielddef *f = (upb_fielddef*)r;
  1482. upb_fielddef_uninit_default(f);
  1483. if (f->subdef_is_symbolic)
  1484. upb_gfree(f->sub.name);
  1485. upb_def_uninit(upb_fielddef_upcast_mutable(f));
  1486. upb_gfree(f);
  1487. }
  1488. static const char *enumdefaultstr(const upb_fielddef *f) {
  1489. const upb_enumdef *e;
  1490. UPB_ASSERT(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  1491. e = upb_fielddef_enumsubdef(f);
  1492. if (f->default_is_string && f->defaultval.bytes) {
  1493. /* Default was explicitly set as a string. */
  1494. str_t *s = f->defaultval.bytes;
  1495. return s->str;
  1496. } else if (e) {
  1497. if (!f->default_is_string) {
  1498. /* Default was explicitly set as an integer; look it up in enumdef. */
  1499. const char *name = upb_enumdef_iton(e, f->defaultval.sint);
  1500. if (name) {
  1501. return name;
  1502. }
  1503. } else {
  1504. /* Default is completely unset; pull enumdef default. */
  1505. if (upb_enumdef_numvals(e) > 0) {
  1506. const char *name = upb_enumdef_iton(e, upb_enumdef_default(e));
  1507. UPB_ASSERT(name);
  1508. return name;
  1509. }
  1510. }
  1511. }
  1512. return NULL;
  1513. }
  1514. static bool enumdefaultint32(const upb_fielddef *f, int32_t *val) {
  1515. const upb_enumdef *e;
  1516. UPB_ASSERT(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  1517. e = upb_fielddef_enumsubdef(f);
  1518. if (!f->default_is_string) {
  1519. /* Default was explicitly set as an integer. */
  1520. *val = f->defaultval.sint;
  1521. return true;
  1522. } else if (e) {
  1523. if (f->defaultval.bytes) {
  1524. /* Default was explicitly set as a str; try to lookup corresponding int. */
  1525. str_t *s = f->defaultval.bytes;
  1526. if (upb_enumdef_ntoiz(e, s->str, val)) {
  1527. return true;
  1528. }
  1529. } else {
  1530. /* Default is unset; try to pull in enumdef default. */
  1531. if (upb_enumdef_numvals(e) > 0) {
  1532. *val = upb_enumdef_default(e);
  1533. return true;
  1534. }
  1535. }
  1536. }
  1537. return false;
  1538. }
  1539. const struct upb_refcounted_vtbl upb_fielddef_vtbl = {visitfield, freefield};
  1540. upb_fielddef *upb_fielddef_new(const void *o) {
  1541. upb_fielddef *f = upb_gmalloc(sizeof(*f));
  1542. if (!f) return NULL;
  1543. if (!upb_def_init(upb_fielddef_upcast_mutable(f), UPB_DEF_FIELD,
  1544. &upb_fielddef_vtbl, o)) {
  1545. upb_gfree(f);
  1546. return NULL;
  1547. }
  1548. f->msg.def = NULL;
  1549. f->sub.def = NULL;
  1550. f->oneof = NULL;
  1551. f->subdef_is_symbolic = false;
  1552. f->msg_is_symbolic = false;
  1553. f->label_ = UPB_LABEL_OPTIONAL;
  1554. f->type_ = UPB_TYPE_INT32;
  1555. f->number_ = 0;
  1556. f->type_is_set_ = false;
  1557. f->tagdelim = false;
  1558. f->is_extension_ = false;
  1559. f->lazy_ = false;
  1560. f->packed_ = true;
  1561. /* For the moment we default this to UPB_INTFMT_VARIABLE, since it will work
  1562. * with all integer types and is in some since more "default" since the most
  1563. * normal-looking proto2 types int32/int64/uint32/uint64 use variable.
  1564. *
  1565. * Other options to consider:
  1566. * - there is no default; users must set this manually (like type).
  1567. * - default signed integers to UPB_INTFMT_ZIGZAG, since it's more likely to
  1568. * be an optimal default for signed integers. */
  1569. f->intfmt = UPB_INTFMT_VARIABLE;
  1570. return f;
  1571. }
  1572. bool upb_fielddef_typeisset(const upb_fielddef *f) {
  1573. return f->type_is_set_;
  1574. }
  1575. upb_fieldtype_t upb_fielddef_type(const upb_fielddef *f) {
  1576. UPB_ASSERT(f->type_is_set_);
  1577. return f->type_;
  1578. }
  1579. uint32_t upb_fielddef_index(const upb_fielddef *f) {
  1580. return f->index_;
  1581. }
  1582. upb_label_t upb_fielddef_label(const upb_fielddef *f) {
  1583. return f->label_;
  1584. }
  1585. upb_intfmt_t upb_fielddef_intfmt(const upb_fielddef *f) {
  1586. return f->intfmt;
  1587. }
  1588. bool upb_fielddef_istagdelim(const upb_fielddef *f) {
  1589. return f->tagdelim;
  1590. }
  1591. uint32_t upb_fielddef_number(const upb_fielddef *f) {
  1592. return f->number_;
  1593. }
  1594. bool upb_fielddef_isextension(const upb_fielddef *f) {
  1595. return f->is_extension_;
  1596. }
  1597. bool upb_fielddef_lazy(const upb_fielddef *f) {
  1598. return f->lazy_;
  1599. }
  1600. bool upb_fielddef_packed(const upb_fielddef *f) {
  1601. return f->packed_;
  1602. }
  1603. const char *upb_fielddef_name(const upb_fielddef *f) {
  1604. return upb_def_fullname(upb_fielddef_upcast(f));
  1605. }
  1606. size_t upb_fielddef_getjsonname(const upb_fielddef *f, char *buf, size_t len) {
  1607. const char *name = upb_fielddef_name(f);
  1608. size_t src, dst = 0;
  1609. bool ucase_next = false;
  1610. #define WRITE(byte) \
  1611. ++dst; \
  1612. if (dst < len) buf[dst - 1] = byte; \
  1613. else if (dst == len) buf[dst - 1] = '\0'
  1614. if (!name) {
  1615. WRITE('\0');
  1616. return 0;
  1617. }
  1618. /* Implement the transformation as described in the spec:
  1619. * 1. upper case all letters after an underscore.
  1620. * 2. remove all underscores.
  1621. */
  1622. for (src = 0; name[src]; src++) {
  1623. if (name[src] == '_') {
  1624. ucase_next = true;
  1625. continue;
  1626. }
  1627. if (ucase_next) {
  1628. WRITE(toupper(name[src]));
  1629. ucase_next = false;
  1630. } else {
  1631. WRITE(name[src]);
  1632. }
  1633. }
  1634. WRITE('\0');
  1635. return dst;
  1636. #undef WRITE
  1637. }
  1638. const upb_msgdef *upb_fielddef_containingtype(const upb_fielddef *f) {
  1639. return f->msg_is_symbolic ? NULL : f->msg.def;
  1640. }
  1641. const upb_oneofdef *upb_fielddef_containingoneof(const upb_fielddef *f) {
  1642. return f->oneof;
  1643. }
  1644. upb_msgdef *upb_fielddef_containingtype_mutable(upb_fielddef *f) {
  1645. return (upb_msgdef*)upb_fielddef_containingtype(f);
  1646. }
  1647. const char *upb_fielddef_containingtypename(upb_fielddef *f) {
  1648. return f->msg_is_symbolic ? f->msg.name : NULL;
  1649. }
  1650. static void release_containingtype(upb_fielddef *f) {
  1651. if (f->msg_is_symbolic) upb_gfree(f->msg.name);
  1652. }
  1653. bool upb_fielddef_setcontainingtypename(upb_fielddef *f, const char *name,
  1654. upb_status *s) {
  1655. char *name_copy;
  1656. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  1657. if (upb_fielddef_containingtype(f)) {
  1658. upb_status_seterrmsg(s, "field has already been added to a message.");
  1659. return false;
  1660. }
  1661. /* TODO: validate name (upb_isident() doesn't quite work atm because this name
  1662. * may have a leading "."). */
  1663. name_copy = upb_gstrdup(name);
  1664. if (!name_copy) {
  1665. upb_upberr_setoom(s);
  1666. return false;
  1667. }
  1668. release_containingtype(f);
  1669. f->msg.name = name_copy;
  1670. f->msg_is_symbolic = true;
  1671. return true;
  1672. }
  1673. bool upb_fielddef_setname(upb_fielddef *f, const char *name, upb_status *s) {
  1674. if (upb_fielddef_containingtype(f) || upb_fielddef_containingoneof(f)) {
  1675. upb_status_seterrmsg(s, "Already added to message or oneof");
  1676. return false;
  1677. }
  1678. return upb_def_setfullname(upb_fielddef_upcast_mutable(f), name, s);
  1679. }
  1680. static void chkdefaulttype(const upb_fielddef *f, upb_fieldtype_t type) {
  1681. UPB_UNUSED(f);
  1682. UPB_UNUSED(type);
  1683. UPB_ASSERT(f->type_is_set_ && upb_fielddef_type(f) == type);
  1684. }
  1685. int64_t upb_fielddef_defaultint64(const upb_fielddef *f) {
  1686. chkdefaulttype(f, UPB_TYPE_INT64);
  1687. return f->defaultval.sint;
  1688. }
  1689. int32_t upb_fielddef_defaultint32(const upb_fielddef *f) {
  1690. if (f->type_is_set_ && upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  1691. int32_t val;
  1692. bool ok = enumdefaultint32(f, &val);
  1693. UPB_ASSERT(ok);
  1694. return val;
  1695. } else {
  1696. chkdefaulttype(f, UPB_TYPE_INT32);
  1697. return f->defaultval.sint;
  1698. }
  1699. }
  1700. uint64_t upb_fielddef_defaultuint64(const upb_fielddef *f) {
  1701. chkdefaulttype(f, UPB_TYPE_UINT64);
  1702. return f->defaultval.uint;
  1703. }
  1704. uint32_t upb_fielddef_defaultuint32(const upb_fielddef *f) {
  1705. chkdefaulttype(f, UPB_TYPE_UINT32);
  1706. return f->defaultval.uint;
  1707. }
  1708. bool upb_fielddef_defaultbool(const upb_fielddef *f) {
  1709. chkdefaulttype(f, UPB_TYPE_BOOL);
  1710. return f->defaultval.uint;
  1711. }
  1712. float upb_fielddef_defaultfloat(const upb_fielddef *f) {
  1713. chkdefaulttype(f, UPB_TYPE_FLOAT);
  1714. return f->defaultval.flt;
  1715. }
  1716. double upb_fielddef_defaultdouble(const upb_fielddef *f) {
  1717. chkdefaulttype(f, UPB_TYPE_DOUBLE);
  1718. return f->defaultval.dbl;
  1719. }
  1720. const char *upb_fielddef_defaultstr(const upb_fielddef *f, size_t *len) {
  1721. UPB_ASSERT(f->type_is_set_);
  1722. UPB_ASSERT(upb_fielddef_type(f) == UPB_TYPE_STRING ||
  1723. upb_fielddef_type(f) == UPB_TYPE_BYTES ||
  1724. upb_fielddef_type(f) == UPB_TYPE_ENUM);
  1725. if (upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  1726. const char *ret = enumdefaultstr(f);
  1727. UPB_ASSERT(ret);
  1728. /* Enum defaults can't have embedded NULLs. */
  1729. if (len) *len = strlen(ret);
  1730. return ret;
  1731. }
  1732. if (f->default_is_string) {
  1733. str_t *str = f->defaultval.bytes;
  1734. if (len) *len = str->len;
  1735. return str->str;
  1736. }
  1737. return NULL;
  1738. }
  1739. static void upb_fielddef_init_default(upb_fielddef *f) {
  1740. f->default_is_string = false;
  1741. switch (upb_fielddef_type(f)) {
  1742. case UPB_TYPE_DOUBLE: f->defaultval.dbl = 0; break;
  1743. case UPB_TYPE_FLOAT: f->defaultval.flt = 0; break;
  1744. case UPB_TYPE_INT32:
  1745. case UPB_TYPE_INT64: f->defaultval.sint = 0; break;
  1746. case UPB_TYPE_UINT64:
  1747. case UPB_TYPE_UINT32:
  1748. case UPB_TYPE_BOOL: f->defaultval.uint = 0; break;
  1749. case UPB_TYPE_STRING:
  1750. case UPB_TYPE_BYTES:
  1751. f->defaultval.bytes = newstr("", 0);
  1752. f->default_is_string = true;
  1753. break;
  1754. case UPB_TYPE_MESSAGE: break;
  1755. case UPB_TYPE_ENUM:
  1756. /* This is our special sentinel that indicates "not set" for an enum. */
  1757. f->default_is_string = true;
  1758. f->defaultval.bytes = NULL;
  1759. break;
  1760. }
  1761. }
  1762. const upb_def *upb_fielddef_subdef(const upb_fielddef *f) {
  1763. return f->subdef_is_symbolic ? NULL : f->sub.def;
  1764. }
  1765. const upb_msgdef *upb_fielddef_msgsubdef(const upb_fielddef *f) {
  1766. const upb_def *def = upb_fielddef_subdef(f);
  1767. return def ? upb_dyncast_msgdef(def) : NULL;
  1768. }
  1769. const upb_enumdef *upb_fielddef_enumsubdef(const upb_fielddef *f) {
  1770. const upb_def *def = upb_fielddef_subdef(f);
  1771. return def ? upb_dyncast_enumdef(def) : NULL;
  1772. }
  1773. upb_def *upb_fielddef_subdef_mutable(upb_fielddef *f) {
  1774. return (upb_def*)upb_fielddef_subdef(f);
  1775. }
  1776. const char *upb_fielddef_subdefname(const upb_fielddef *f) {
  1777. if (f->subdef_is_symbolic) {
  1778. return f->sub.name;
  1779. } else if (f->sub.def) {
  1780. return upb_def_fullname(f->sub.def);
  1781. } else {
  1782. return NULL;
  1783. }
  1784. }
  1785. bool upb_fielddef_setnumber(upb_fielddef *f, uint32_t number, upb_status *s) {
  1786. if (upb_fielddef_containingtype(f)) {
  1787. upb_status_seterrmsg(
  1788. s, "cannot change field number after adding to a message");
  1789. return false;
  1790. }
  1791. if (number == 0 || number > UPB_MAX_FIELDNUMBER) {
  1792. upb_status_seterrf(s, "invalid field number (%u)", number);
  1793. return false;
  1794. }
  1795. f->number_ = number;
  1796. return true;
  1797. }
  1798. void upb_fielddef_settype(upb_fielddef *f, upb_fieldtype_t type) {
  1799. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  1800. UPB_ASSERT(upb_fielddef_checktype(type));
  1801. upb_fielddef_uninit_default(f);
  1802. f->type_ = type;
  1803. f->type_is_set_ = true;
  1804. upb_fielddef_init_default(f);
  1805. }
  1806. void upb_fielddef_setdescriptortype(upb_fielddef *f, int type) {
  1807. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  1808. switch (type) {
  1809. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  1810. upb_fielddef_settype(f, UPB_TYPE_DOUBLE);
  1811. break;
  1812. case UPB_DESCRIPTOR_TYPE_FLOAT:
  1813. upb_fielddef_settype(f, UPB_TYPE_FLOAT);
  1814. break;
  1815. case UPB_DESCRIPTOR_TYPE_INT64:
  1816. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  1817. case UPB_DESCRIPTOR_TYPE_SINT64:
  1818. upb_fielddef_settype(f, UPB_TYPE_INT64);
  1819. break;
  1820. case UPB_DESCRIPTOR_TYPE_UINT64:
  1821. case UPB_DESCRIPTOR_TYPE_FIXED64:
  1822. upb_fielddef_settype(f, UPB_TYPE_UINT64);
  1823. break;
  1824. case UPB_DESCRIPTOR_TYPE_INT32:
  1825. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  1826. case UPB_DESCRIPTOR_TYPE_SINT32:
  1827. upb_fielddef_settype(f, UPB_TYPE_INT32);
  1828. break;
  1829. case UPB_DESCRIPTOR_TYPE_UINT32:
  1830. case UPB_DESCRIPTOR_TYPE_FIXED32:
  1831. upb_fielddef_settype(f, UPB_TYPE_UINT32);
  1832. break;
  1833. case UPB_DESCRIPTOR_TYPE_BOOL:
  1834. upb_fielddef_settype(f, UPB_TYPE_BOOL);
  1835. break;
  1836. case UPB_DESCRIPTOR_TYPE_STRING:
  1837. upb_fielddef_settype(f, UPB_TYPE_STRING);
  1838. break;
  1839. case UPB_DESCRIPTOR_TYPE_BYTES:
  1840. upb_fielddef_settype(f, UPB_TYPE_BYTES);
  1841. break;
  1842. case UPB_DESCRIPTOR_TYPE_GROUP:
  1843. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  1844. upb_fielddef_settype(f, UPB_TYPE_MESSAGE);
  1845. break;
  1846. case UPB_DESCRIPTOR_TYPE_ENUM:
  1847. upb_fielddef_settype(f, UPB_TYPE_ENUM);
  1848. break;
  1849. default: UPB_ASSERT(false);
  1850. }
  1851. if (type == UPB_DESCRIPTOR_TYPE_FIXED64 ||
  1852. type == UPB_DESCRIPTOR_TYPE_FIXED32 ||
  1853. type == UPB_DESCRIPTOR_TYPE_SFIXED64 ||
  1854. type == UPB_DESCRIPTOR_TYPE_SFIXED32) {
  1855. upb_fielddef_setintfmt(f, UPB_INTFMT_FIXED);
  1856. } else if (type == UPB_DESCRIPTOR_TYPE_SINT64 ||
  1857. type == UPB_DESCRIPTOR_TYPE_SINT32) {
  1858. upb_fielddef_setintfmt(f, UPB_INTFMT_ZIGZAG);
  1859. } else {
  1860. upb_fielddef_setintfmt(f, UPB_INTFMT_VARIABLE);
  1861. }
  1862. upb_fielddef_settagdelim(f, type == UPB_DESCRIPTOR_TYPE_GROUP);
  1863. }
  1864. upb_descriptortype_t upb_fielddef_descriptortype(const upb_fielddef *f) {
  1865. switch (upb_fielddef_type(f)) {
  1866. case UPB_TYPE_FLOAT: return UPB_DESCRIPTOR_TYPE_FLOAT;
  1867. case UPB_TYPE_DOUBLE: return UPB_DESCRIPTOR_TYPE_DOUBLE;
  1868. case UPB_TYPE_BOOL: return UPB_DESCRIPTOR_TYPE_BOOL;
  1869. case UPB_TYPE_STRING: return UPB_DESCRIPTOR_TYPE_STRING;
  1870. case UPB_TYPE_BYTES: return UPB_DESCRIPTOR_TYPE_BYTES;
  1871. case UPB_TYPE_ENUM: return UPB_DESCRIPTOR_TYPE_ENUM;
  1872. case UPB_TYPE_INT32:
  1873. switch (upb_fielddef_intfmt(f)) {
  1874. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_INT32;
  1875. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_SFIXED32;
  1876. case UPB_INTFMT_ZIGZAG: return UPB_DESCRIPTOR_TYPE_SINT32;
  1877. }
  1878. case UPB_TYPE_INT64:
  1879. switch (upb_fielddef_intfmt(f)) {
  1880. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_INT64;
  1881. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_SFIXED64;
  1882. case UPB_INTFMT_ZIGZAG: return UPB_DESCRIPTOR_TYPE_SINT64;
  1883. }
  1884. case UPB_TYPE_UINT32:
  1885. switch (upb_fielddef_intfmt(f)) {
  1886. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_UINT32;
  1887. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_FIXED32;
  1888. case UPB_INTFMT_ZIGZAG: return -1;
  1889. }
  1890. case UPB_TYPE_UINT64:
  1891. switch (upb_fielddef_intfmt(f)) {
  1892. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_UINT64;
  1893. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_FIXED64;
  1894. case UPB_INTFMT_ZIGZAG: return -1;
  1895. }
  1896. case UPB_TYPE_MESSAGE:
  1897. return upb_fielddef_istagdelim(f) ?
  1898. UPB_DESCRIPTOR_TYPE_GROUP : UPB_DESCRIPTOR_TYPE_MESSAGE;
  1899. }
  1900. return 0;
  1901. }
  1902. void upb_fielddef_setisextension(upb_fielddef *f, bool is_extension) {
  1903. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  1904. f->is_extension_ = is_extension;
  1905. }
  1906. void upb_fielddef_setlazy(upb_fielddef *f, bool lazy) {
  1907. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  1908. f->lazy_ = lazy;
  1909. }
  1910. void upb_fielddef_setpacked(upb_fielddef *f, bool packed) {
  1911. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  1912. f->packed_ = packed;
  1913. }
  1914. void upb_fielddef_setlabel(upb_fielddef *f, upb_label_t label) {
  1915. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  1916. UPB_ASSERT(upb_fielddef_checklabel(label));
  1917. f->label_ = label;
  1918. }
  1919. void upb_fielddef_setintfmt(upb_fielddef *f, upb_intfmt_t fmt) {
  1920. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  1921. UPB_ASSERT(upb_fielddef_checkintfmt(fmt));
  1922. f->intfmt = fmt;
  1923. }
  1924. void upb_fielddef_settagdelim(upb_fielddef *f, bool tag_delim) {
  1925. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  1926. f->tagdelim = tag_delim;
  1927. f->tagdelim = tag_delim;
  1928. }
  1929. static bool checksetdefault(upb_fielddef *f, upb_fieldtype_t type) {
  1930. if (!f->type_is_set_ || upb_fielddef_isfrozen(f) ||
  1931. upb_fielddef_type(f) != type) {
  1932. UPB_ASSERT(false);
  1933. return false;
  1934. }
  1935. if (f->default_is_string) {
  1936. str_t *s = f->defaultval.bytes;
  1937. UPB_ASSERT(s || type == UPB_TYPE_ENUM);
  1938. if (s) freestr(s);
  1939. }
  1940. f->default_is_string = false;
  1941. return true;
  1942. }
  1943. void upb_fielddef_setdefaultint64(upb_fielddef *f, int64_t value) {
  1944. if (checksetdefault(f, UPB_TYPE_INT64))
  1945. f->defaultval.sint = value;
  1946. }
  1947. void upb_fielddef_setdefaultint32(upb_fielddef *f, int32_t value) {
  1948. if ((upb_fielddef_type(f) == UPB_TYPE_ENUM &&
  1949. checksetdefault(f, UPB_TYPE_ENUM)) ||
  1950. checksetdefault(f, UPB_TYPE_INT32)) {
  1951. f->defaultval.sint = value;
  1952. }
  1953. }
  1954. void upb_fielddef_setdefaultuint64(upb_fielddef *f, uint64_t value) {
  1955. if (checksetdefault(f, UPB_TYPE_UINT64))
  1956. f->defaultval.uint = value;
  1957. }
  1958. void upb_fielddef_setdefaultuint32(upb_fielddef *f, uint32_t value) {
  1959. if (checksetdefault(f, UPB_TYPE_UINT32))
  1960. f->defaultval.uint = value;
  1961. }
  1962. void upb_fielddef_setdefaultbool(upb_fielddef *f, bool value) {
  1963. if (checksetdefault(f, UPB_TYPE_BOOL))
  1964. f->defaultval.uint = value;
  1965. }
  1966. void upb_fielddef_setdefaultfloat(upb_fielddef *f, float value) {
  1967. if (checksetdefault(f, UPB_TYPE_FLOAT))
  1968. f->defaultval.flt = value;
  1969. }
  1970. void upb_fielddef_setdefaultdouble(upb_fielddef *f, double value) {
  1971. if (checksetdefault(f, UPB_TYPE_DOUBLE))
  1972. f->defaultval.dbl = value;
  1973. }
  1974. bool upb_fielddef_setdefaultstr(upb_fielddef *f, const void *str, size_t len,
  1975. upb_status *s) {
  1976. str_t *str2;
  1977. UPB_ASSERT(upb_fielddef_isstring(f) || f->type_ == UPB_TYPE_ENUM);
  1978. if (f->type_ == UPB_TYPE_ENUM && !upb_isident(str, len, false, s))
  1979. return false;
  1980. if (f->default_is_string) {
  1981. str_t *s = f->defaultval.bytes;
  1982. UPB_ASSERT(s || f->type_ == UPB_TYPE_ENUM);
  1983. if (s) freestr(s);
  1984. } else {
  1985. UPB_ASSERT(f->type_ == UPB_TYPE_ENUM);
  1986. }
  1987. str2 = newstr(str, len);
  1988. f->defaultval.bytes = str2;
  1989. f->default_is_string = true;
  1990. return true;
  1991. }
  1992. void upb_fielddef_setdefaultcstr(upb_fielddef *f, const char *str,
  1993. upb_status *s) {
  1994. UPB_ASSERT(f->type_is_set_);
  1995. upb_fielddef_setdefaultstr(f, str, str ? strlen(str) : 0, s);
  1996. }
  1997. bool upb_fielddef_enumhasdefaultint32(const upb_fielddef *f) {
  1998. int32_t val;
  1999. UPB_ASSERT(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  2000. return enumdefaultint32(f, &val);
  2001. }
  2002. bool upb_fielddef_enumhasdefaultstr(const upb_fielddef *f) {
  2003. UPB_ASSERT(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  2004. return enumdefaultstr(f) != NULL;
  2005. }
  2006. static bool upb_subdef_typecheck(upb_fielddef *f, const upb_def *subdef,
  2007. upb_status *s) {
  2008. if (f->type_ == UPB_TYPE_MESSAGE) {
  2009. if (upb_dyncast_msgdef(subdef)) return true;
  2010. upb_status_seterrmsg(s, "invalid subdef type for this submessage field");
  2011. return false;
  2012. } else if (f->type_ == UPB_TYPE_ENUM) {
  2013. if (upb_dyncast_enumdef(subdef)) return true;
  2014. upb_status_seterrmsg(s, "invalid subdef type for this enum field");
  2015. return false;
  2016. } else {
  2017. upb_status_seterrmsg(s, "only message and enum fields can have a subdef");
  2018. return false;
  2019. }
  2020. }
  2021. static void release_subdef(upb_fielddef *f) {
  2022. if (f->subdef_is_symbolic) {
  2023. upb_gfree(f->sub.name);
  2024. } else if (f->sub.def) {
  2025. upb_unref2(f->sub.def, f);
  2026. }
  2027. }
  2028. bool upb_fielddef_setsubdef(upb_fielddef *f, const upb_def *subdef,
  2029. upb_status *s) {
  2030. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  2031. UPB_ASSERT(upb_fielddef_hassubdef(f));
  2032. if (subdef && !upb_subdef_typecheck(f, subdef, s)) return false;
  2033. release_subdef(f);
  2034. f->sub.def = subdef;
  2035. f->subdef_is_symbolic = false;
  2036. if (f->sub.def) upb_ref2(f->sub.def, f);
  2037. return true;
  2038. }
  2039. bool upb_fielddef_setmsgsubdef(upb_fielddef *f, const upb_msgdef *subdef,
  2040. upb_status *s) {
  2041. return upb_fielddef_setsubdef(f, upb_msgdef_upcast(subdef), s);
  2042. }
  2043. bool upb_fielddef_setenumsubdef(upb_fielddef *f, const upb_enumdef *subdef,
  2044. upb_status *s) {
  2045. return upb_fielddef_setsubdef(f, upb_enumdef_upcast(subdef), s);
  2046. }
  2047. bool upb_fielddef_setsubdefname(upb_fielddef *f, const char *name,
  2048. upb_status *s) {
  2049. char *name_copy;
  2050. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  2051. if (!upb_fielddef_hassubdef(f)) {
  2052. upb_status_seterrmsg(s, "field type does not accept a subdef");
  2053. return false;
  2054. }
  2055. name_copy = upb_gstrdup(name);
  2056. if (!name_copy) {
  2057. upb_upberr_setoom(s);
  2058. return false;
  2059. }
  2060. /* TODO: validate name (upb_isident() doesn't quite work atm because this name
  2061. * may have a leading "."). */
  2062. release_subdef(f);
  2063. f->sub.name = name_copy;
  2064. f->subdef_is_symbolic = true;
  2065. return true;
  2066. }
  2067. bool upb_fielddef_issubmsg(const upb_fielddef *f) {
  2068. return upb_fielddef_type(f) == UPB_TYPE_MESSAGE;
  2069. }
  2070. bool upb_fielddef_isstring(const upb_fielddef *f) {
  2071. return upb_fielddef_type(f) == UPB_TYPE_STRING ||
  2072. upb_fielddef_type(f) == UPB_TYPE_BYTES;
  2073. }
  2074. bool upb_fielddef_isseq(const upb_fielddef *f) {
  2075. return upb_fielddef_label(f) == UPB_LABEL_REPEATED;
  2076. }
  2077. bool upb_fielddef_isprimitive(const upb_fielddef *f) {
  2078. return !upb_fielddef_isstring(f) && !upb_fielddef_issubmsg(f);
  2079. }
  2080. bool upb_fielddef_ismap(const upb_fielddef *f) {
  2081. return upb_fielddef_isseq(f) && upb_fielddef_issubmsg(f) &&
  2082. upb_msgdef_mapentry(upb_fielddef_msgsubdef(f));
  2083. }
  2084. bool upb_fielddef_haspresence(const upb_fielddef *f) {
  2085. if (upb_fielddef_isseq(f)) return false;
  2086. if (upb_fielddef_issubmsg(f)) return true;
  2087. /* Primitive field: return true unless there is a message that specifies
  2088. * presence should not exist. */
  2089. if (f->msg_is_symbolic || !f->msg.def) return true;
  2090. return f->msg.def->syntax == UPB_SYNTAX_PROTO2;
  2091. }
  2092. bool upb_fielddef_hassubdef(const upb_fielddef *f) {
  2093. return upb_fielddef_issubmsg(f) || upb_fielddef_type(f) == UPB_TYPE_ENUM;
  2094. }
  2095. static bool between(int32_t x, int32_t low, int32_t high) {
  2096. return x >= low && x <= high;
  2097. }
  2098. bool upb_fielddef_checklabel(int32_t label) { return between(label, 1, 3); }
  2099. bool upb_fielddef_checktype(int32_t type) { return between(type, 1, 11); }
  2100. bool upb_fielddef_checkintfmt(int32_t fmt) { return between(fmt, 1, 3); }
  2101. bool upb_fielddef_checkdescriptortype(int32_t type) {
  2102. return between(type, 1, 18);
  2103. }
  2104. /* upb_msgdef *****************************************************************/
  2105. static void visitmsg(const upb_refcounted *r, upb_refcounted_visit *visit,
  2106. void *closure) {
  2107. upb_msg_oneof_iter o;
  2108. const upb_msgdef *m = (const upb_msgdef*)r;
  2109. const upb_def *def = upb_msgdef_upcast(m);
  2110. upb_msg_field_iter i;
  2111. for(upb_msg_field_begin(&i, m);
  2112. !upb_msg_field_done(&i);
  2113. upb_msg_field_next(&i)) {
  2114. upb_fielddef *f = upb_msg_iter_field(&i);
  2115. visit(r, upb_fielddef_upcast2(f), closure);
  2116. }
  2117. for(upb_msg_oneof_begin(&o, m);
  2118. !upb_msg_oneof_done(&o);
  2119. upb_msg_oneof_next(&o)) {
  2120. upb_oneofdef *f = upb_msg_iter_oneof(&o);
  2121. visit(r, upb_oneofdef_upcast(f), closure);
  2122. }
  2123. if (upb_def_file(def)) {
  2124. visit(r, upb_filedef_upcast(upb_def_file(def)), closure);
  2125. }
  2126. }
  2127. static void freemsg(upb_refcounted *r) {
  2128. upb_msgdef *m = (upb_msgdef*)r;
  2129. upb_strtable_uninit(&m->ntof);
  2130. upb_inttable_uninit(&m->itof);
  2131. upb_def_uninit(upb_msgdef_upcast_mutable(m));
  2132. upb_gfree(m);
  2133. }
  2134. const struct upb_refcounted_vtbl upb_msgdef_vtbl = {visitmsg, freemsg};
  2135. upb_msgdef *upb_msgdef_new(const void *owner) {
  2136. upb_msgdef *m = upb_gmalloc(sizeof(*m));
  2137. if (!m) return NULL;
  2138. if (!upb_def_init(upb_msgdef_upcast_mutable(m), UPB_DEF_MSG, &upb_msgdef_vtbl,
  2139. owner)) {
  2140. goto err2;
  2141. }
  2142. if (!upb_inttable_init(&m->itof, UPB_CTYPE_PTR)) goto err2;
  2143. if (!upb_strtable_init(&m->ntof, UPB_CTYPE_PTR)) goto err1;
  2144. m->map_entry = false;
  2145. m->syntax = UPB_SYNTAX_PROTO2;
  2146. return m;
  2147. err1:
  2148. upb_inttable_uninit(&m->itof);
  2149. err2:
  2150. upb_gfree(m);
  2151. return NULL;
  2152. }
  2153. bool upb_msgdef_freeze(upb_msgdef *m, upb_status *status) {
  2154. upb_def *d = upb_msgdef_upcast_mutable(m);
  2155. return upb_def_freeze(&d, 1, status);
  2156. }
  2157. const char *upb_msgdef_fullname(const upb_msgdef *m) {
  2158. return upb_def_fullname(upb_msgdef_upcast(m));
  2159. }
  2160. const char *upb_msgdef_name(const upb_msgdef *m) {
  2161. return upb_def_name(upb_msgdef_upcast(m));
  2162. }
  2163. bool upb_msgdef_setfullname(upb_msgdef *m, const char *fullname,
  2164. upb_status *s) {
  2165. return upb_def_setfullname(upb_msgdef_upcast_mutable(m), fullname, s);
  2166. }
  2167. bool upb_msgdef_setsyntax(upb_msgdef *m, upb_syntax_t syntax) {
  2168. if (syntax != UPB_SYNTAX_PROTO2 && syntax != UPB_SYNTAX_PROTO3) {
  2169. return false;
  2170. }
  2171. m->syntax = syntax;
  2172. return true;
  2173. }
  2174. upb_syntax_t upb_msgdef_syntax(const upb_msgdef *m) {
  2175. return m->syntax;
  2176. }
  2177. /* Helper: check that the field |f| is safe to add to msgdef |m|. Set an error
  2178. * on status |s| and return false if not. */
  2179. static bool check_field_add(const upb_msgdef *m, const upb_fielddef *f,
  2180. upb_status *s) {
  2181. if (upb_fielddef_containingtype(f) != NULL) {
  2182. upb_status_seterrmsg(s, "fielddef already belongs to a message");
  2183. return false;
  2184. } else if (upb_fielddef_name(f) == NULL || upb_fielddef_number(f) == 0) {
  2185. upb_status_seterrmsg(s, "field name or number were not set");
  2186. return false;
  2187. } else if (upb_msgdef_itof(m, upb_fielddef_number(f))) {
  2188. upb_status_seterrmsg(s, "duplicate field number");
  2189. return false;
  2190. } else if (upb_strtable_lookup(&m->ntof, upb_fielddef_name(f), NULL)) {
  2191. upb_status_seterrmsg(s, "name conflicts with existing field or oneof");
  2192. return false;
  2193. }
  2194. return true;
  2195. }
  2196. static void add_field(upb_msgdef *m, upb_fielddef *f, const void *ref_donor) {
  2197. release_containingtype(f);
  2198. f->msg.def = m;
  2199. f->msg_is_symbolic = false;
  2200. upb_inttable_insert(&m->itof, upb_fielddef_number(f), upb_value_ptr(f));
  2201. upb_strtable_insert(&m->ntof, upb_fielddef_name(f), upb_value_ptr(f));
  2202. upb_ref2(f, m);
  2203. upb_ref2(m, f);
  2204. if (ref_donor) upb_fielddef_unref(f, ref_donor);
  2205. }
  2206. bool upb_msgdef_addfield(upb_msgdef *m, upb_fielddef *f, const void *ref_donor,
  2207. upb_status *s) {
  2208. /* TODO: extensions need to have a separate namespace, because proto2 allows a
  2209. * top-level extension (ie. one not in any package) to have the same name as a
  2210. * field from the message.
  2211. *
  2212. * This also implies that there needs to be a separate lookup-by-name method
  2213. * for extensions. It seems desirable for iteration to return both extensions
  2214. * and non-extensions though.
  2215. *
  2216. * We also need to validate that the field number is in an extension range iff
  2217. * it is an extension.
  2218. *
  2219. * This method is idempotent. Check if |f| is already part of this msgdef and
  2220. * return immediately if so. */
  2221. if (upb_fielddef_containingtype(f) == m) {
  2222. if (ref_donor) upb_fielddef_unref(f, ref_donor);
  2223. return true;
  2224. }
  2225. /* Check constraints for all fields before performing any action. */
  2226. if (!check_field_add(m, f, s)) {
  2227. return false;
  2228. } else if (upb_fielddef_containingoneof(f) != NULL) {
  2229. /* Fields in a oneof can only be added by adding the oneof to the msgdef. */
  2230. upb_status_seterrmsg(s, "fielddef is part of a oneof");
  2231. return false;
  2232. }
  2233. /* Constraint checks ok, perform the action. */
  2234. add_field(m, f, ref_donor);
  2235. return true;
  2236. }
  2237. bool upb_msgdef_addoneof(upb_msgdef *m, upb_oneofdef *o, const void *ref_donor,
  2238. upb_status *s) {
  2239. upb_oneof_iter it;
  2240. /* Check various conditions that would prevent this oneof from being added. */
  2241. if (upb_oneofdef_containingtype(o)) {
  2242. upb_status_seterrmsg(s, "oneofdef already belongs to a message");
  2243. return false;
  2244. } else if (upb_oneofdef_name(o) == NULL) {
  2245. upb_status_seterrmsg(s, "oneofdef name was not set");
  2246. return false;
  2247. } else if (upb_strtable_lookup(&m->ntof, upb_oneofdef_name(o), NULL)) {
  2248. upb_status_seterrmsg(s, "name conflicts with existing field or oneof");
  2249. return false;
  2250. }
  2251. /* Check that all of the oneof's fields do not conflict with names or numbers
  2252. * of fields already in the message. */
  2253. for (upb_oneof_begin(&it, o); !upb_oneof_done(&it); upb_oneof_next(&it)) {
  2254. const upb_fielddef *f = upb_oneof_iter_field(&it);
  2255. if (!check_field_add(m, f, s)) {
  2256. return false;
  2257. }
  2258. }
  2259. /* Everything checks out -- commit now. */
  2260. /* Add oneof itself first. */
  2261. o->parent = m;
  2262. upb_strtable_insert(&m->ntof, upb_oneofdef_name(o), upb_value_ptr(o));
  2263. upb_ref2(o, m);
  2264. upb_ref2(m, o);
  2265. /* Add each field of the oneof directly to the msgdef. */
  2266. for (upb_oneof_begin(&it, o); !upb_oneof_done(&it); upb_oneof_next(&it)) {
  2267. upb_fielddef *f = upb_oneof_iter_field(&it);
  2268. add_field(m, f, NULL);
  2269. }
  2270. if (ref_donor) upb_oneofdef_unref(o, ref_donor);
  2271. return true;
  2272. }
  2273. const upb_fielddef *upb_msgdef_itof(const upb_msgdef *m, uint32_t i) {
  2274. upb_value val;
  2275. return upb_inttable_lookup32(&m->itof, i, &val) ?
  2276. upb_value_getptr(val) : NULL;
  2277. }
  2278. const upb_fielddef *upb_msgdef_ntof(const upb_msgdef *m, const char *name,
  2279. size_t len) {
  2280. upb_value val;
  2281. if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
  2282. return NULL;
  2283. }
  2284. return upb_trygetfield(upb_value_getptr(val));
  2285. }
  2286. const upb_oneofdef *upb_msgdef_ntoo(const upb_msgdef *m, const char *name,
  2287. size_t len) {
  2288. upb_value val;
  2289. if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
  2290. return NULL;
  2291. }
  2292. return upb_trygetoneof(upb_value_getptr(val));
  2293. }
  2294. bool upb_msgdef_lookupname(const upb_msgdef *m, const char *name, size_t len,
  2295. const upb_fielddef **f, const upb_oneofdef **o) {
  2296. upb_value val;
  2297. if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
  2298. return false;
  2299. }
  2300. *o = upb_trygetoneof(upb_value_getptr(val));
  2301. *f = upb_trygetfield(upb_value_getptr(val));
  2302. UPB_ASSERT((*o != NULL) ^ (*f != NULL)); /* Exactly one of the two should be set. */
  2303. return true;
  2304. }
  2305. int upb_msgdef_numfields(const upb_msgdef *m) {
  2306. /* The number table contains only fields. */
  2307. return upb_inttable_count(&m->itof);
  2308. }
  2309. int upb_msgdef_numoneofs(const upb_msgdef *m) {
  2310. /* The name table includes oneofs, and the number table does not. */
  2311. return upb_strtable_count(&m->ntof) - upb_inttable_count(&m->itof);
  2312. }
  2313. void upb_msgdef_setmapentry(upb_msgdef *m, bool map_entry) {
  2314. UPB_ASSERT(!upb_msgdef_isfrozen(m));
  2315. m->map_entry = map_entry;
  2316. }
  2317. bool upb_msgdef_mapentry(const upb_msgdef *m) {
  2318. return m->map_entry;
  2319. }
  2320. upb_wellknowntype_t upb_msgdef_wellknowntype(const upb_msgdef *m) {
  2321. return m->well_known_type;
  2322. }
  2323. bool upb_msgdef_isnumberwrapper(const upb_msgdef *m) {
  2324. upb_wellknowntype_t type = upb_msgdef_wellknowntype(m);
  2325. return type >= UPB_WELLKNOWN_DOUBLEVALUE &&
  2326. type <= UPB_WELLKNOWN_UINT32VALUE;
  2327. }
  2328. void upb_msg_field_begin(upb_msg_field_iter *iter, const upb_msgdef *m) {
  2329. upb_inttable_begin(iter, &m->itof);
  2330. }
  2331. void upb_msg_field_next(upb_msg_field_iter *iter) { upb_inttable_next(iter); }
  2332. bool upb_msg_field_done(const upb_msg_field_iter *iter) {
  2333. return upb_inttable_done(iter);
  2334. }
  2335. upb_fielddef *upb_msg_iter_field(const upb_msg_field_iter *iter) {
  2336. return (upb_fielddef*)upb_value_getptr(upb_inttable_iter_value(iter));
  2337. }
  2338. void upb_msg_field_iter_setdone(upb_msg_field_iter *iter) {
  2339. upb_inttable_iter_setdone(iter);
  2340. }
  2341. void upb_msg_oneof_begin(upb_msg_oneof_iter *iter, const upb_msgdef *m) {
  2342. upb_strtable_begin(iter, &m->ntof);
  2343. /* We need to skip past any initial fields. */
  2344. while (!upb_strtable_done(iter) &&
  2345. !upb_isoneof(upb_value_getptr(upb_strtable_iter_value(iter)))) {
  2346. upb_strtable_next(iter);
  2347. }
  2348. }
  2349. void upb_msg_oneof_next(upb_msg_oneof_iter *iter) {
  2350. /* We need to skip past fields to return only oneofs. */
  2351. do {
  2352. upb_strtable_next(iter);
  2353. } while (!upb_strtable_done(iter) &&
  2354. !upb_isoneof(upb_value_getptr(upb_strtable_iter_value(iter))));
  2355. }
  2356. bool upb_msg_oneof_done(const upb_msg_oneof_iter *iter) {
  2357. return upb_strtable_done(iter);
  2358. }
  2359. upb_oneofdef *upb_msg_iter_oneof(const upb_msg_oneof_iter *iter) {
  2360. return (upb_oneofdef*)upb_value_getptr(upb_strtable_iter_value(iter));
  2361. }
  2362. void upb_msg_oneof_iter_setdone(upb_msg_oneof_iter *iter) {
  2363. upb_strtable_iter_setdone(iter);
  2364. }
  2365. /* upb_oneofdef ***************************************************************/
  2366. static void visitoneof(const upb_refcounted *r, upb_refcounted_visit *visit,
  2367. void *closure) {
  2368. const upb_oneofdef *o = (const upb_oneofdef*)r;
  2369. upb_oneof_iter i;
  2370. for (upb_oneof_begin(&i, o); !upb_oneof_done(&i); upb_oneof_next(&i)) {
  2371. const upb_fielddef *f = upb_oneof_iter_field(&i);
  2372. visit(r, upb_fielddef_upcast2(f), closure);
  2373. }
  2374. if (o->parent) {
  2375. visit(r, upb_msgdef_upcast2(o->parent), closure);
  2376. }
  2377. }
  2378. static void freeoneof(upb_refcounted *r) {
  2379. upb_oneofdef *o = (upb_oneofdef*)r;
  2380. upb_strtable_uninit(&o->ntof);
  2381. upb_inttable_uninit(&o->itof);
  2382. upb_gfree((void*)o->name);
  2383. upb_gfree(o);
  2384. }
  2385. const struct upb_refcounted_vtbl upb_oneofdef_vtbl = {visitoneof, freeoneof};
  2386. upb_oneofdef *upb_oneofdef_new(const void *owner) {
  2387. upb_oneofdef *o = upb_gmalloc(sizeof(*o));
  2388. if (!o) {
  2389. return NULL;
  2390. }
  2391. o->parent = NULL;
  2392. o->name = NULL;
  2393. if (!upb_refcounted_init(upb_oneofdef_upcast_mutable(o), &upb_oneofdef_vtbl,
  2394. owner)) {
  2395. goto err2;
  2396. }
  2397. if (!upb_inttable_init(&o->itof, UPB_CTYPE_PTR)) goto err2;
  2398. if (!upb_strtable_init(&o->ntof, UPB_CTYPE_PTR)) goto err1;
  2399. return o;
  2400. err1:
  2401. upb_inttable_uninit(&o->itof);
  2402. err2:
  2403. upb_gfree(o);
  2404. return NULL;
  2405. }
  2406. const char *upb_oneofdef_name(const upb_oneofdef *o) { return o->name; }
  2407. bool upb_oneofdef_setname(upb_oneofdef *o, const char *name, upb_status *s) {
  2408. UPB_ASSERT(!upb_oneofdef_isfrozen(o));
  2409. if (upb_oneofdef_containingtype(o)) {
  2410. upb_status_seterrmsg(s, "oneof already added to a message");
  2411. return false;
  2412. }
  2413. if (!upb_isident(name, strlen(name), true, s)) {
  2414. return false;
  2415. }
  2416. name = upb_gstrdup(name);
  2417. if (!name) {
  2418. upb_status_seterrmsg(s, "One of memory");
  2419. return false;
  2420. }
  2421. upb_gfree((void*)o->name);
  2422. o->name = name;
  2423. return true;
  2424. }
  2425. const upb_msgdef *upb_oneofdef_containingtype(const upb_oneofdef *o) {
  2426. return o->parent;
  2427. }
  2428. int upb_oneofdef_numfields(const upb_oneofdef *o) {
  2429. return upb_strtable_count(&o->ntof);
  2430. }
  2431. uint32_t upb_oneofdef_index(const upb_oneofdef *o) {
  2432. return o->index;
  2433. }
  2434. bool upb_oneofdef_addfield(upb_oneofdef *o, upb_fielddef *f,
  2435. const void *ref_donor,
  2436. upb_status *s) {
  2437. UPB_ASSERT(!upb_oneofdef_isfrozen(o));
  2438. UPB_ASSERT(!o->parent || !upb_msgdef_isfrozen(o->parent));
  2439. /* This method is idempotent. Check if |f| is already part of this oneofdef
  2440. * and return immediately if so. */
  2441. if (upb_fielddef_containingoneof(f) == o) {
  2442. return true;
  2443. }
  2444. /* The field must have an OPTIONAL label. */
  2445. if (upb_fielddef_label(f) != UPB_LABEL_OPTIONAL) {
  2446. upb_status_seterrmsg(s, "fields in oneof must have OPTIONAL label");
  2447. return false;
  2448. }
  2449. /* Check that no field with this name or number exists already in the oneof.
  2450. * Also check that the field is not already part of a oneof. */
  2451. if (upb_fielddef_name(f) == NULL || upb_fielddef_number(f) == 0) {
  2452. upb_status_seterrmsg(s, "field name or number were not set");
  2453. return false;
  2454. } else if (upb_oneofdef_itof(o, upb_fielddef_number(f)) ||
  2455. upb_oneofdef_ntofz(o, upb_fielddef_name(f))) {
  2456. upb_status_seterrmsg(s, "duplicate field name or number");
  2457. return false;
  2458. } else if (upb_fielddef_containingoneof(f) != NULL) {
  2459. upb_status_seterrmsg(s, "fielddef already belongs to a oneof");
  2460. return false;
  2461. }
  2462. /* We allow adding a field to the oneof either if the field is not part of a
  2463. * msgdef, or if it is and we are also part of the same msgdef. */
  2464. if (o->parent == NULL) {
  2465. /* If we're not in a msgdef, the field cannot be either. Otherwise we would
  2466. * need to magically add this oneof to a msgdef to remain consistent, which
  2467. * is surprising behavior. */
  2468. if (upb_fielddef_containingtype(f) != NULL) {
  2469. upb_status_seterrmsg(s, "fielddef already belongs to a message, but "
  2470. "oneof does not");
  2471. return false;
  2472. }
  2473. } else {
  2474. /* If we're in a msgdef, the user can add fields that either aren't in any
  2475. * msgdef (in which case they're added to our msgdef) or already a part of
  2476. * our msgdef. */
  2477. if (upb_fielddef_containingtype(f) != NULL &&
  2478. upb_fielddef_containingtype(f) != o->parent) {
  2479. upb_status_seterrmsg(s, "fielddef belongs to a different message "
  2480. "than oneof");
  2481. return false;
  2482. }
  2483. }
  2484. /* Commit phase. First add the field to our parent msgdef, if any, because
  2485. * that may fail; then add the field to our own tables. */
  2486. if (o->parent != NULL && upb_fielddef_containingtype(f) == NULL) {
  2487. if (!upb_msgdef_addfield((upb_msgdef*)o->parent, f, NULL, s)) {
  2488. return false;
  2489. }
  2490. }
  2491. release_containingtype(f);
  2492. f->oneof = o;
  2493. upb_inttable_insert(&o->itof, upb_fielddef_number(f), upb_value_ptr(f));
  2494. upb_strtable_insert(&o->ntof, upb_fielddef_name(f), upb_value_ptr(f));
  2495. upb_ref2(f, o);
  2496. upb_ref2(o, f);
  2497. if (ref_donor) upb_fielddef_unref(f, ref_donor);
  2498. return true;
  2499. }
  2500. const upb_fielddef *upb_oneofdef_ntof(const upb_oneofdef *o,
  2501. const char *name, size_t length) {
  2502. upb_value val;
  2503. return upb_strtable_lookup2(&o->ntof, name, length, &val) ?
  2504. upb_value_getptr(val) : NULL;
  2505. }
  2506. const upb_fielddef *upb_oneofdef_itof(const upb_oneofdef *o, uint32_t num) {
  2507. upb_value val;
  2508. return upb_inttable_lookup32(&o->itof, num, &val) ?
  2509. upb_value_getptr(val) : NULL;
  2510. }
  2511. void upb_oneof_begin(upb_oneof_iter *iter, const upb_oneofdef *o) {
  2512. upb_inttable_begin(iter, &o->itof);
  2513. }
  2514. void upb_oneof_next(upb_oneof_iter *iter) {
  2515. upb_inttable_next(iter);
  2516. }
  2517. bool upb_oneof_done(upb_oneof_iter *iter) {
  2518. return upb_inttable_done(iter);
  2519. }
  2520. upb_fielddef *upb_oneof_iter_field(const upb_oneof_iter *iter) {
  2521. return (upb_fielddef*)upb_value_getptr(upb_inttable_iter_value(iter));
  2522. }
  2523. void upb_oneof_iter_setdone(upb_oneof_iter *iter) {
  2524. upb_inttable_iter_setdone(iter);
  2525. }
  2526. /* upb_filedef ****************************************************************/
  2527. static void visitfiledef(const upb_refcounted *r, upb_refcounted_visit *visit,
  2528. void *closure) {
  2529. const upb_filedef *f = (const upb_filedef*)r;
  2530. size_t i;
  2531. for(i = 0; i < upb_filedef_defcount(f); i++) {
  2532. visit(r, upb_def_upcast(upb_filedef_def(f, i)), closure);
  2533. }
  2534. }
  2535. static void freefiledef(upb_refcounted *r) {
  2536. upb_filedef *f = (upb_filedef*)r;
  2537. size_t i;
  2538. for(i = 0; i < upb_filedef_depcount(f); i++) {
  2539. upb_filedef_unref(upb_filedef_dep(f, i), f);
  2540. }
  2541. upb_inttable_uninit(&f->defs);
  2542. upb_inttable_uninit(&f->deps);
  2543. upb_gfree((void*)f->name);
  2544. upb_gfree((void*)f->package);
  2545. upb_gfree((void*)f->phpprefix);
  2546. upb_gfree((void*)f->phpnamespace);
  2547. upb_gfree(f);
  2548. }
  2549. const struct upb_refcounted_vtbl upb_filedef_vtbl = {visitfiledef, freefiledef};
  2550. upb_filedef *upb_filedef_new(const void *owner) {
  2551. upb_filedef *f = upb_gmalloc(sizeof(*f));
  2552. if (!f) {
  2553. return NULL;
  2554. }
  2555. f->package = NULL;
  2556. f->name = NULL;
  2557. f->phpprefix = NULL;
  2558. f->phpnamespace = NULL;
  2559. f->syntax = UPB_SYNTAX_PROTO2;
  2560. if (!upb_refcounted_init(upb_filedef_upcast_mutable(f), &upb_filedef_vtbl,
  2561. owner)) {
  2562. goto err;
  2563. }
  2564. if (!upb_inttable_init(&f->defs, UPB_CTYPE_CONSTPTR)) {
  2565. goto err;
  2566. }
  2567. if (!upb_inttable_init(&f->deps, UPB_CTYPE_CONSTPTR)) {
  2568. goto err2;
  2569. }
  2570. return f;
  2571. err2:
  2572. upb_inttable_uninit(&f->defs);
  2573. err:
  2574. upb_gfree(f);
  2575. return NULL;
  2576. }
  2577. const char *upb_filedef_name(const upb_filedef *f) {
  2578. return f->name;
  2579. }
  2580. const char *upb_filedef_package(const upb_filedef *f) {
  2581. return f->package;
  2582. }
  2583. const char *upb_filedef_phpprefix(const upb_filedef *f) {
  2584. return f->phpprefix;
  2585. }
  2586. const char *upb_filedef_phpnamespace(const upb_filedef *f) {
  2587. return f->phpnamespace;
  2588. }
  2589. upb_syntax_t upb_filedef_syntax(const upb_filedef *f) {
  2590. return f->syntax;
  2591. }
  2592. size_t upb_filedef_defcount(const upb_filedef *f) {
  2593. return upb_inttable_count(&f->defs);
  2594. }
  2595. size_t upb_filedef_depcount(const upb_filedef *f) {
  2596. return upb_inttable_count(&f->deps);
  2597. }
  2598. const upb_def *upb_filedef_def(const upb_filedef *f, size_t i) {
  2599. upb_value v;
  2600. if (upb_inttable_lookup32(&f->defs, i, &v)) {
  2601. return upb_value_getconstptr(v);
  2602. } else {
  2603. return NULL;
  2604. }
  2605. }
  2606. const upb_filedef *upb_filedef_dep(const upb_filedef *f, size_t i) {
  2607. upb_value v;
  2608. if (upb_inttable_lookup32(&f->deps, i, &v)) {
  2609. return upb_value_getconstptr(v);
  2610. } else {
  2611. return NULL;
  2612. }
  2613. }
  2614. bool upb_filedef_setname(upb_filedef *f, const char *name, upb_status *s) {
  2615. name = upb_gstrdup(name);
  2616. if (!name) {
  2617. upb_upberr_setoom(s);
  2618. return false;
  2619. }
  2620. upb_gfree((void*)f->name);
  2621. f->name = name;
  2622. return true;
  2623. }
  2624. bool upb_filedef_setpackage(upb_filedef *f, const char *package,
  2625. upb_status *s) {
  2626. if (!upb_isident(package, strlen(package), true, s)) return false;
  2627. package = upb_gstrdup(package);
  2628. if (!package) {
  2629. upb_upberr_setoom(s);
  2630. return false;
  2631. }
  2632. upb_gfree((void*)f->package);
  2633. f->package = package;
  2634. return true;
  2635. }
  2636. bool upb_filedef_setphpprefix(upb_filedef *f, const char *phpprefix,
  2637. upb_status *s) {
  2638. phpprefix = upb_gstrdup(phpprefix);
  2639. if (!phpprefix) {
  2640. upb_upberr_setoom(s);
  2641. return false;
  2642. }
  2643. upb_gfree((void*)f->phpprefix);
  2644. f->phpprefix = phpprefix;
  2645. return true;
  2646. }
  2647. bool upb_filedef_setphpnamespace(upb_filedef *f, const char *phpnamespace,
  2648. upb_status *s) {
  2649. phpnamespace = upb_gstrdup(phpnamespace);
  2650. if (!phpnamespace) {
  2651. upb_upberr_setoom(s);
  2652. return false;
  2653. }
  2654. upb_gfree((void*)f->phpnamespace);
  2655. f->phpnamespace = phpnamespace;
  2656. return true;
  2657. }
  2658. bool upb_filedef_setsyntax(upb_filedef *f, upb_syntax_t syntax,
  2659. upb_status *s) {
  2660. UPB_UNUSED(s);
  2661. if (syntax != UPB_SYNTAX_PROTO2 &&
  2662. syntax != UPB_SYNTAX_PROTO3) {
  2663. upb_status_seterrmsg(s, "Unknown syntax value.");
  2664. return false;
  2665. }
  2666. f->syntax = syntax;
  2667. {
  2668. /* Set all messages in this file to match. */
  2669. size_t i;
  2670. for (i = 0; i < upb_filedef_defcount(f); i++) {
  2671. /* Casting const away is safe since all defs in mutable filedef must
  2672. * also be mutable. */
  2673. upb_def *def = (upb_def*)upb_filedef_def(f, i);
  2674. upb_msgdef *m = upb_dyncast_msgdef_mutable(def);
  2675. if (m) {
  2676. m->syntax = syntax;
  2677. }
  2678. }
  2679. }
  2680. return true;
  2681. }
  2682. bool upb_filedef_adddef(upb_filedef *f, upb_def *def, const void *ref_donor,
  2683. upb_status *s) {
  2684. if (def->file) {
  2685. upb_status_seterrmsg(s, "Def is already part of another filedef.");
  2686. return false;
  2687. }
  2688. if (upb_inttable_push(&f->defs, upb_value_constptr(def))) {
  2689. def->file = f;
  2690. upb_ref2(def, f);
  2691. upb_ref2(f, def);
  2692. if (ref_donor) upb_def_unref(def, ref_donor);
  2693. if (def->type == UPB_DEF_MSG) {
  2694. upb_downcast_msgdef_mutable(def)->syntax = f->syntax;
  2695. }
  2696. return true;
  2697. } else {
  2698. upb_upberr_setoom(s);
  2699. return false;
  2700. }
  2701. }
  2702. bool upb_filedef_adddep(upb_filedef *f, const upb_filedef *dep) {
  2703. if (upb_inttable_push(&f->deps, upb_value_constptr(dep))) {
  2704. /* Regular ref instead of ref2 because files can't form cycles. */
  2705. upb_filedef_ref(dep, f);
  2706. return true;
  2707. } else {
  2708. return false;
  2709. }
  2710. }
  2711. void upb_symtab_free(upb_symtab *s) {
  2712. upb_strtable_iter i;
  2713. upb_strtable_begin(&i, &s->symtab);
  2714. for (; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  2715. const upb_def *def = upb_value_getptr(upb_strtable_iter_value(&i));
  2716. upb_def_unref(def, s);
  2717. }
  2718. upb_strtable_uninit(&s->symtab);
  2719. upb_gfree(s);
  2720. }
  2721. upb_symtab *upb_symtab_new() {
  2722. upb_symtab *s = upb_gmalloc(sizeof(*s));
  2723. if (!s) {
  2724. return NULL;
  2725. }
  2726. upb_strtable_init(&s->symtab, UPB_CTYPE_PTR);
  2727. return s;
  2728. }
  2729. const upb_def *upb_symtab_lookup(const upb_symtab *s, const char *sym) {
  2730. upb_value v;
  2731. upb_def *ret = upb_strtable_lookup(&s->symtab, sym, &v) ?
  2732. upb_value_getptr(v) : NULL;
  2733. return ret;
  2734. }
  2735. const upb_msgdef *upb_symtab_lookupmsg(const upb_symtab *s, const char *sym) {
  2736. upb_value v;
  2737. upb_def *def = upb_strtable_lookup(&s->symtab, sym, &v) ?
  2738. upb_value_getptr(v) : NULL;
  2739. return def ? upb_dyncast_msgdef(def) : NULL;
  2740. }
  2741. const upb_msgdef *upb_symtab_lookupmsg2(const upb_symtab *s, const char *sym,
  2742. size_t len) {
  2743. upb_value v;
  2744. upb_def *def = upb_strtable_lookup2(&s->symtab, sym, len, &v) ?
  2745. upb_value_getptr(v) : NULL;
  2746. return def ? upb_dyncast_msgdef(def) : NULL;
  2747. }
  2748. const upb_enumdef *upb_symtab_lookupenum(const upb_symtab *s, const char *sym) {
  2749. upb_value v;
  2750. upb_def *def = upb_strtable_lookup(&s->symtab, sym, &v) ?
  2751. upb_value_getptr(v) : NULL;
  2752. return def ? upb_dyncast_enumdef(def) : NULL;
  2753. }
  2754. /* Given a symbol and the base symbol inside which it is defined, find the
  2755. * symbol's definition in t. */
  2756. static upb_def *upb_resolvename(const upb_strtable *t,
  2757. const char *base, const char *sym) {
  2758. if(strlen(sym) == 0) return NULL;
  2759. if(sym[0] == '.') {
  2760. /* Symbols starting with '.' are absolute, so we do a single lookup.
  2761. * Slice to omit the leading '.' */
  2762. upb_value v;
  2763. return upb_strtable_lookup(t, sym + 1, &v) ? upb_value_getptr(v) : NULL;
  2764. } else {
  2765. /* Remove components from base until we find an entry or run out.
  2766. * TODO: This branch is totally broken, but currently not used. */
  2767. (void)base;
  2768. UPB_ASSERT(false);
  2769. return NULL;
  2770. }
  2771. }
  2772. const upb_def *upb_symtab_resolve(const upb_symtab *s, const char *base,
  2773. const char *sym) {
  2774. upb_def *ret = upb_resolvename(&s->symtab, base, sym);
  2775. return ret;
  2776. }
  2777. /* TODO(haberman): we need a lot more testing of error conditions. */
  2778. static bool symtab_add(upb_symtab *s, upb_def *const*defs, size_t n,
  2779. void *ref_donor, upb_refcounted *freeze_also,
  2780. upb_status *status) {
  2781. size_t i;
  2782. size_t add_n;
  2783. size_t freeze_n;
  2784. upb_strtable_iter iter;
  2785. upb_refcounted **add_objs = NULL;
  2786. upb_def **add_defs = NULL;
  2787. size_t add_objs_size;
  2788. upb_strtable addtab;
  2789. if (n == 0 && !freeze_also) {
  2790. return true;
  2791. }
  2792. if (!upb_strtable_init(&addtab, UPB_CTYPE_PTR)) {
  2793. upb_status_seterrmsg(status, "out of memory");
  2794. return false;
  2795. }
  2796. /* Add new defs to our "add" set. */
  2797. for (i = 0; i < n; i++) {
  2798. upb_def *def = defs[i];
  2799. const char *fullname;
  2800. upb_fielddef *f;
  2801. if (upb_def_isfrozen(def)) {
  2802. upb_status_seterrmsg(status, "added defs must be mutable");
  2803. goto err;
  2804. }
  2805. UPB_ASSERT(!upb_def_isfrozen(def));
  2806. fullname = upb_def_fullname(def);
  2807. if (!fullname) {
  2808. upb_status_seterrmsg(
  2809. status, "Anonymous defs cannot be added to a symtab");
  2810. goto err;
  2811. }
  2812. f = upb_dyncast_fielddef_mutable(def);
  2813. if (f) {
  2814. if (!upb_fielddef_containingtypename(f)) {
  2815. upb_status_seterrmsg(status,
  2816. "Standalone fielddefs must have a containing type "
  2817. "(extendee) name set");
  2818. goto err;
  2819. }
  2820. } else {
  2821. if (upb_strtable_lookup(&addtab, fullname, NULL)) {
  2822. upb_status_seterrf(status, "Conflicting defs named '%s'", fullname);
  2823. goto err;
  2824. }
  2825. if (upb_strtable_lookup(&s->symtab, fullname, NULL)) {
  2826. upb_status_seterrf(status, "Symtab already has a def named '%s'",
  2827. fullname);
  2828. goto err;
  2829. }
  2830. if (!upb_strtable_insert(&addtab, fullname, upb_value_ptr(def)))
  2831. goto oom_err;
  2832. upb_def_donateref(def, ref_donor, s);
  2833. }
  2834. if (upb_dyncast_fielddef_mutable(def)) {
  2835. /* TODO(haberman): allow adding extensions attached to files. */
  2836. upb_status_seterrf(status, "Can't add extensions to symtab.\n");
  2837. goto err;
  2838. }
  2839. }
  2840. /* Now using the table, resolve symbolic references for subdefs. */
  2841. upb_strtable_begin(&iter, &addtab);
  2842. for (; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
  2843. const char *base;
  2844. upb_def *def = upb_value_getptr(upb_strtable_iter_value(&iter));
  2845. upb_msgdef *m = upb_dyncast_msgdef_mutable(def);
  2846. upb_msg_field_iter j;
  2847. if (!m) continue;
  2848. /* Type names are resolved relative to the message in which they appear. */
  2849. base = upb_msgdef_fullname(m);
  2850. for(upb_msg_field_begin(&j, m);
  2851. !upb_msg_field_done(&j);
  2852. upb_msg_field_next(&j)) {
  2853. upb_fielddef *f = upb_msg_iter_field(&j);
  2854. const char *name = upb_fielddef_subdefname(f);
  2855. if (name && !upb_fielddef_subdef(f)) {
  2856. /* Try the lookup in the current set of to-be-added defs first. If not
  2857. * there, try existing defs. */
  2858. upb_def *subdef = upb_resolvename(&addtab, base, name);
  2859. if (subdef == NULL) {
  2860. subdef = upb_resolvename(&s->symtab, base, name);
  2861. }
  2862. if (subdef == NULL) {
  2863. upb_status_seterrf(
  2864. status, "couldn't resolve name '%s' in message '%s'", name, base);
  2865. goto err;
  2866. } else if (!upb_fielddef_setsubdef(f, subdef, status)) {
  2867. goto err;
  2868. }
  2869. }
  2870. }
  2871. }
  2872. /* We need an array of the defs in addtab, for passing to
  2873. * upb_refcounted_freeze(). */
  2874. add_objs_size = upb_strtable_count(&addtab);
  2875. if (freeze_also) {
  2876. add_objs_size++;
  2877. }
  2878. add_defs = upb_gmalloc(sizeof(void*) * add_objs_size);
  2879. if (add_defs == NULL) goto oom_err;
  2880. upb_strtable_begin(&iter, &addtab);
  2881. for (add_n = 0; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
  2882. add_defs[add_n++] = upb_value_getptr(upb_strtable_iter_value(&iter));
  2883. }
  2884. /* Validate defs. */
  2885. if (!_upb_def_validate(add_defs, add_n, status)) {
  2886. goto err;
  2887. }
  2888. /* Cheat a little and give the array a new type.
  2889. * This is probably undefined behavior, but this code will be deleted soon. */
  2890. add_objs = (upb_refcounted**)add_defs;
  2891. freeze_n = add_n;
  2892. if (freeze_also) {
  2893. add_objs[freeze_n++] = freeze_also;
  2894. }
  2895. if (!upb_refcounted_freeze(add_objs, freeze_n, status,
  2896. UPB_MAX_MESSAGE_DEPTH * 2)) {
  2897. goto err;
  2898. }
  2899. /* This must be delayed until all errors have been detected, since error
  2900. * recovery code uses this table to cleanup defs. */
  2901. upb_strtable_uninit(&addtab);
  2902. /* TODO(haberman) we don't properly handle errors after this point (like
  2903. * OOM in upb_strtable_insert() below). */
  2904. for (i = 0; i < add_n; i++) {
  2905. upb_def *def = (upb_def*)add_objs[i];
  2906. const char *name = upb_def_fullname(def);
  2907. bool success;
  2908. success = upb_strtable_insert(&s->symtab, name, upb_value_ptr(def));
  2909. UPB_ASSERT(success);
  2910. }
  2911. upb_gfree(add_defs);
  2912. return true;
  2913. oom_err:
  2914. upb_status_seterrmsg(status, "out of memory");
  2915. err: {
  2916. /* We need to donate the refs back. */
  2917. upb_strtable_begin(&iter, &addtab);
  2918. for (; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
  2919. upb_def *def = upb_value_getptr(upb_strtable_iter_value(&iter));
  2920. upb_def_donateref(def, s, ref_donor);
  2921. }
  2922. }
  2923. upb_strtable_uninit(&addtab);
  2924. upb_gfree(add_defs);
  2925. UPB_ASSERT(!upb_ok(status));
  2926. return false;
  2927. }
  2928. bool upb_symtab_add(upb_symtab *s, upb_def *const*defs, size_t n,
  2929. void *ref_donor, upb_status *status) {
  2930. return symtab_add(s, defs, n, ref_donor, NULL, status);
  2931. }
  2932. bool upb_symtab_addfile(upb_symtab *s, upb_filedef *file, upb_status *status) {
  2933. size_t n;
  2934. size_t i;
  2935. upb_def **defs;
  2936. bool ret;
  2937. n = upb_filedef_defcount(file);
  2938. if (n == 0) {
  2939. return true;
  2940. }
  2941. defs = upb_gmalloc(sizeof(*defs) * n);
  2942. if (defs == NULL) {
  2943. upb_status_seterrmsg(status, "Out of memory");
  2944. return false;
  2945. }
  2946. for (i = 0; i < n; i++) {
  2947. defs[i] = upb_filedef_mutabledef(file, i);
  2948. }
  2949. ret = symtab_add(s, defs, n, NULL, upb_filedef_upcast_mutable(file), status);
  2950. upb_gfree(defs);
  2951. return ret;
  2952. }
  2953. /* Iteration. */
  2954. static void advance_to_matching(upb_symtab_iter *iter) {
  2955. if (iter->type == UPB_DEF_ANY)
  2956. return;
  2957. while (!upb_strtable_done(&iter->iter) &&
  2958. iter->type != upb_symtab_iter_def(iter)->type) {
  2959. upb_strtable_next(&iter->iter);
  2960. }
  2961. }
  2962. void upb_symtab_begin(upb_symtab_iter *iter, const upb_symtab *s,
  2963. upb_deftype_t type) {
  2964. upb_strtable_begin(&iter->iter, &s->symtab);
  2965. iter->type = type;
  2966. advance_to_matching(iter);
  2967. }
  2968. void upb_symtab_next(upb_symtab_iter *iter) {
  2969. upb_strtable_next(&iter->iter);
  2970. advance_to_matching(iter);
  2971. }
  2972. bool upb_symtab_done(const upb_symtab_iter *iter) {
  2973. return upb_strtable_done(&iter->iter);
  2974. }
  2975. const upb_def *upb_symtab_iter_def(const upb_symtab_iter *iter) {
  2976. return upb_value_getptr(upb_strtable_iter_value(&iter->iter));
  2977. }
  2978. /* We encode backwards, to avoid pre-computing lengths (one-pass encode). */
  2979. #define UPB_PB_VARINT_MAX_LEN 10
  2980. #define CHK(x) do { if (!(x)) { return false; } } while(0)
  2981. /* Maps descriptor type -> upb field type. */
  2982. static const uint8_t upb_desctype_to_fieldtype2[] = {
  2983. UPB_WIRE_TYPE_END_GROUP, /* ENDGROUP */
  2984. UPB_TYPE_DOUBLE, /* DOUBLE */
  2985. UPB_TYPE_FLOAT, /* FLOAT */
  2986. UPB_TYPE_INT64, /* INT64 */
  2987. UPB_TYPE_UINT64, /* UINT64 */
  2988. UPB_TYPE_INT32, /* INT32 */
  2989. UPB_TYPE_UINT64, /* FIXED64 */
  2990. UPB_TYPE_UINT32, /* FIXED32 */
  2991. UPB_TYPE_BOOL, /* BOOL */
  2992. UPB_TYPE_STRING, /* STRING */
  2993. UPB_TYPE_MESSAGE, /* GROUP */
  2994. UPB_TYPE_MESSAGE, /* MESSAGE */
  2995. UPB_TYPE_BYTES, /* BYTES */
  2996. UPB_TYPE_UINT32, /* UINT32 */
  2997. UPB_TYPE_ENUM, /* ENUM */
  2998. UPB_TYPE_INT32, /* SFIXED32 */
  2999. UPB_TYPE_INT64, /* SFIXED64 */
  3000. UPB_TYPE_INT32, /* SINT32 */
  3001. UPB_TYPE_INT64, /* SINT64 */
  3002. };
  3003. static size_t upb_encode_varint(uint64_t val, char *buf) {
  3004. size_t i;
  3005. if (val < 128) { buf[0] = val; return 1; }
  3006. i = 0;
  3007. while (val) {
  3008. uint8_t byte = val & 0x7fU;
  3009. val >>= 7;
  3010. if (val) byte |= 0x80U;
  3011. buf[i++] = byte;
  3012. }
  3013. return i;
  3014. }
  3015. static uint32_t upb_zzencode_32(int32_t n) { return (n << 1) ^ (n >> 31); }
  3016. static uint64_t upb_zzencode_64(int64_t n) { return (n << 1) ^ (n >> 63); }
  3017. typedef struct {
  3018. upb_alloc *alloc;
  3019. char *buf, *ptr, *limit;
  3020. } upb_encstate;
  3021. static size_t upb_roundup_pow2(size_t bytes) {
  3022. size_t ret = 128;
  3023. while (ret < bytes) {
  3024. ret *= 2;
  3025. }
  3026. return ret;
  3027. }
  3028. static bool upb_encode_growbuffer(upb_encstate *e, size_t bytes) {
  3029. size_t old_size = e->limit - e->buf;
  3030. size_t new_size = upb_roundup_pow2(bytes + (e->limit - e->ptr));
  3031. char *new_buf = upb_realloc(e->alloc, e->buf, old_size, new_size);
  3032. CHK(new_buf);
  3033. /* We want previous data at the end, realloc() put it at the beginning. */
  3034. memmove(new_buf + new_size - old_size, e->buf, old_size);
  3035. e->ptr = new_buf + new_size - (e->limit - e->ptr);
  3036. e->limit = new_buf + new_size;
  3037. e->buf = new_buf;
  3038. return true;
  3039. }
  3040. /* Call to ensure that at least "bytes" bytes are available for writing at
  3041. * e->ptr. Returns false if the bytes could not be allocated. */
  3042. static bool upb_encode_reserve(upb_encstate *e, size_t bytes) {
  3043. CHK(UPB_LIKELY((size_t)(e->ptr - e->buf) >= bytes) ||
  3044. upb_encode_growbuffer(e, bytes));
  3045. e->ptr -= bytes;
  3046. return true;
  3047. }
  3048. /* Writes the given bytes to the buffer, handling reserve/advance. */
  3049. static bool upb_put_bytes(upb_encstate *e, const void *data, size_t len) {
  3050. CHK(upb_encode_reserve(e, len));
  3051. memcpy(e->ptr, data, len);
  3052. return true;
  3053. }
  3054. static bool upb_put_fixed64(upb_encstate *e, uint64_t val) {
  3055. /* TODO(haberman): byte-swap for big endian. */
  3056. return upb_put_bytes(e, &val, sizeof(uint64_t));
  3057. }
  3058. static bool upb_put_fixed32(upb_encstate *e, uint32_t val) {
  3059. /* TODO(haberman): byte-swap for big endian. */
  3060. return upb_put_bytes(e, &val, sizeof(uint32_t));
  3061. }
  3062. static bool upb_put_varint(upb_encstate *e, uint64_t val) {
  3063. size_t len;
  3064. char *start;
  3065. CHK(upb_encode_reserve(e, UPB_PB_VARINT_MAX_LEN));
  3066. len = upb_encode_varint(val, e->ptr);
  3067. start = e->ptr + UPB_PB_VARINT_MAX_LEN - len;
  3068. memmove(start, e->ptr, len);
  3069. e->ptr = start;
  3070. return true;
  3071. }
  3072. static bool upb_put_double(upb_encstate *e, double d) {
  3073. uint64_t u64;
  3074. UPB_ASSERT(sizeof(double) == sizeof(uint64_t));
  3075. memcpy(&u64, &d, sizeof(uint64_t));
  3076. return upb_put_fixed64(e, u64);
  3077. }
  3078. static bool upb_put_float(upb_encstate *e, float d) {
  3079. uint32_t u32;
  3080. UPB_ASSERT(sizeof(float) == sizeof(uint32_t));
  3081. memcpy(&u32, &d, sizeof(uint32_t));
  3082. return upb_put_fixed32(e, u32);
  3083. }
  3084. static uint32_t upb_readcase(const char *msg, const upb_msglayout_field *f) {
  3085. uint32_t ret;
  3086. uint32_t offset = ~f->presence;
  3087. memcpy(&ret, msg + offset, sizeof(ret));
  3088. return ret;
  3089. }
  3090. static bool upb_readhasbit(const char *msg, const upb_msglayout_field *f) {
  3091. uint32_t hasbit = f->presence;
  3092. UPB_ASSERT(f->presence > 0);
  3093. return msg[hasbit / 8] & (1 << (hasbit % 8));
  3094. }
  3095. static bool upb_put_tag(upb_encstate *e, int field_number, int wire_type) {
  3096. return upb_put_varint(e, (field_number << 3) | wire_type);
  3097. }
  3098. static bool upb_put_fixedarray(upb_encstate *e, const upb_array *arr,
  3099. size_t size) {
  3100. size_t bytes = arr->len * size;
  3101. return upb_put_bytes(e, arr->data, bytes) && upb_put_varint(e, bytes);
  3102. }
  3103. bool upb_encode_message(upb_encstate *e, const char *msg,
  3104. const upb_msglayout *m, size_t *size);
  3105. static bool upb_encode_array(upb_encstate *e, const char *field_mem,
  3106. const upb_msglayout *m,
  3107. const upb_msglayout_field *f) {
  3108. const upb_array *arr = *(const upb_array**)field_mem;
  3109. if (arr == NULL || arr->len == 0) {
  3110. return true;
  3111. }
  3112. UPB_ASSERT(arr->type == upb_desctype_to_fieldtype2[f->descriptortype]);
  3113. #define VARINT_CASE(ctype, encode) { \
  3114. ctype *start = arr->data; \
  3115. ctype *ptr = start + arr->len; \
  3116. size_t pre_len = e->limit - e->ptr; \
  3117. do { \
  3118. ptr--; \
  3119. CHK(upb_put_varint(e, encode)); \
  3120. } while (ptr != start); \
  3121. CHK(upb_put_varint(e, e->limit - e->ptr - pre_len)); \
  3122. } \
  3123. break; \
  3124. do { ; } while(0)
  3125. switch (f->descriptortype) {
  3126. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  3127. CHK(upb_put_fixedarray(e, arr, sizeof(double)));
  3128. break;
  3129. case UPB_DESCRIPTOR_TYPE_FLOAT:
  3130. CHK(upb_put_fixedarray(e, arr, sizeof(float)));
  3131. break;
  3132. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  3133. case UPB_DESCRIPTOR_TYPE_FIXED64:
  3134. CHK(upb_put_fixedarray(e, arr, sizeof(uint64_t)));
  3135. break;
  3136. case UPB_DESCRIPTOR_TYPE_FIXED32:
  3137. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  3138. CHK(upb_put_fixedarray(e, arr, sizeof(uint32_t)));
  3139. break;
  3140. case UPB_DESCRIPTOR_TYPE_INT64:
  3141. case UPB_DESCRIPTOR_TYPE_UINT64:
  3142. VARINT_CASE(uint64_t, *ptr);
  3143. case UPB_DESCRIPTOR_TYPE_UINT32:
  3144. VARINT_CASE(uint32_t, *ptr);
  3145. case UPB_DESCRIPTOR_TYPE_INT32:
  3146. case UPB_DESCRIPTOR_TYPE_ENUM:
  3147. VARINT_CASE(int32_t, (int64_t)*ptr);
  3148. case UPB_DESCRIPTOR_TYPE_BOOL:
  3149. VARINT_CASE(bool, *ptr);
  3150. case UPB_DESCRIPTOR_TYPE_SINT32:
  3151. VARINT_CASE(int32_t, upb_zzencode_32(*ptr));
  3152. case UPB_DESCRIPTOR_TYPE_SINT64:
  3153. VARINT_CASE(int64_t, upb_zzencode_64(*ptr));
  3154. case UPB_DESCRIPTOR_TYPE_STRING:
  3155. case UPB_DESCRIPTOR_TYPE_BYTES: {
  3156. upb_stringview *start = arr->data;
  3157. upb_stringview *ptr = start + arr->len;
  3158. do {
  3159. ptr--;
  3160. CHK(upb_put_bytes(e, ptr->data, ptr->size) &&
  3161. upb_put_varint(e, ptr->size) &&
  3162. upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
  3163. } while (ptr != start);
  3164. return true;
  3165. }
  3166. case UPB_DESCRIPTOR_TYPE_GROUP: {
  3167. void **start = arr->data;
  3168. void **ptr = start + arr->len;
  3169. const upb_msglayout *subm = m->submsgs[f->submsg_index];
  3170. do {
  3171. size_t size;
  3172. ptr--;
  3173. CHK(upb_put_tag(e, f->number, UPB_WIRE_TYPE_END_GROUP) &&
  3174. upb_encode_message(e, *ptr, subm, &size) &&
  3175. upb_put_tag(e, f->number, UPB_WIRE_TYPE_START_GROUP));
  3176. } while (ptr != start);
  3177. return true;
  3178. }
  3179. case UPB_DESCRIPTOR_TYPE_MESSAGE: {
  3180. void **start = arr->data;
  3181. void **ptr = start + arr->len;
  3182. const upb_msglayout *subm = m->submsgs[f->submsg_index];
  3183. do {
  3184. size_t size;
  3185. ptr--;
  3186. CHK(upb_encode_message(e, *ptr, subm, &size) &&
  3187. upb_put_varint(e, size) &&
  3188. upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
  3189. } while (ptr != start);
  3190. return true;
  3191. }
  3192. }
  3193. #undef VARINT_CASE
  3194. /* We encode all primitive arrays as packed, regardless of what was specified
  3195. * in the .proto file. Could special case 1-sized arrays. */
  3196. CHK(upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
  3197. return true;
  3198. }
  3199. static bool upb_encode_scalarfield(upb_encstate *e, const char *field_mem,
  3200. const upb_msglayout *m,
  3201. const upb_msglayout_field *f,
  3202. bool skip_zero_value) {
  3203. #define CASE(ctype, type, wire_type, encodeval) do { \
  3204. ctype val = *(ctype*)field_mem; \
  3205. if (skip_zero_value && val == 0) { \
  3206. return true; \
  3207. } \
  3208. return upb_put_ ## type(e, encodeval) && \
  3209. upb_put_tag(e, f->number, wire_type); \
  3210. } while(0)
  3211. switch (f->descriptortype) {
  3212. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  3213. CASE(double, double, UPB_WIRE_TYPE_64BIT, val);
  3214. case UPB_DESCRIPTOR_TYPE_FLOAT:
  3215. CASE(float, float, UPB_WIRE_TYPE_32BIT, val);
  3216. case UPB_DESCRIPTOR_TYPE_INT64:
  3217. case UPB_DESCRIPTOR_TYPE_UINT64:
  3218. CASE(uint64_t, varint, UPB_WIRE_TYPE_VARINT, val);
  3219. case UPB_DESCRIPTOR_TYPE_UINT32:
  3220. CASE(uint32_t, varint, UPB_WIRE_TYPE_VARINT, val);
  3221. case UPB_DESCRIPTOR_TYPE_INT32:
  3222. case UPB_DESCRIPTOR_TYPE_ENUM:
  3223. CASE(int32_t, varint, UPB_WIRE_TYPE_VARINT, (int64_t)val);
  3224. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  3225. case UPB_DESCRIPTOR_TYPE_FIXED64:
  3226. CASE(uint64_t, fixed64, UPB_WIRE_TYPE_64BIT, val);
  3227. case UPB_DESCRIPTOR_TYPE_FIXED32:
  3228. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  3229. CASE(uint32_t, fixed32, UPB_WIRE_TYPE_32BIT, val);
  3230. case UPB_DESCRIPTOR_TYPE_BOOL:
  3231. CASE(bool, varint, UPB_WIRE_TYPE_VARINT, val);
  3232. case UPB_DESCRIPTOR_TYPE_SINT32:
  3233. CASE(int32_t, varint, UPB_WIRE_TYPE_VARINT, upb_zzencode_32(val));
  3234. case UPB_DESCRIPTOR_TYPE_SINT64:
  3235. CASE(int64_t, varint, UPB_WIRE_TYPE_VARINT, upb_zzencode_64(val));
  3236. case UPB_DESCRIPTOR_TYPE_STRING:
  3237. case UPB_DESCRIPTOR_TYPE_BYTES: {
  3238. upb_stringview view = *(upb_stringview*)field_mem;
  3239. if (skip_zero_value && view.size == 0) {
  3240. return true;
  3241. }
  3242. return upb_put_bytes(e, view.data, view.size) &&
  3243. upb_put_varint(e, view.size) &&
  3244. upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED);
  3245. }
  3246. case UPB_DESCRIPTOR_TYPE_GROUP: {
  3247. size_t size;
  3248. void *submsg = *(void **)field_mem;
  3249. const upb_msglayout *subm = m->submsgs[f->submsg_index];
  3250. if (submsg == NULL) {
  3251. return true;
  3252. }
  3253. return upb_put_tag(e, f->number, UPB_WIRE_TYPE_END_GROUP) &&
  3254. upb_encode_message(e, submsg, subm, &size) &&
  3255. upb_put_tag(e, f->number, UPB_WIRE_TYPE_START_GROUP);
  3256. }
  3257. case UPB_DESCRIPTOR_TYPE_MESSAGE: {
  3258. size_t size;
  3259. void *submsg = *(void **)field_mem;
  3260. const upb_msglayout *subm = m->submsgs[f->submsg_index];
  3261. if (submsg == NULL) {
  3262. return true;
  3263. }
  3264. return upb_encode_message(e, submsg, subm, &size) &&
  3265. upb_put_varint(e, size) &&
  3266. upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED);
  3267. }
  3268. }
  3269. #undef CASE
  3270. UPB_UNREACHABLE();
  3271. }
  3272. bool upb_encode_message(upb_encstate *e, const char *msg,
  3273. const upb_msglayout *m, size_t *size) {
  3274. int i;
  3275. size_t pre_len = e->limit - e->ptr;
  3276. const char *unknown;
  3277. size_t unknown_size;
  3278. for (i = m->field_count - 1; i >= 0; i--) {
  3279. const upb_msglayout_field *f = &m->fields[i];
  3280. if (f->label == UPB_LABEL_REPEATED) {
  3281. CHK(upb_encode_array(e, msg + f->offset, m, f));
  3282. } else {
  3283. bool skip_empty = false;
  3284. if (f->presence == 0) {
  3285. /* Proto3 presence. */
  3286. skip_empty = true;
  3287. } else if (f->presence > 0) {
  3288. /* Proto2 presence: hasbit. */
  3289. if (!upb_readhasbit(msg, f)) {
  3290. continue;
  3291. }
  3292. } else {
  3293. /* Field is in a oneof. */
  3294. if (upb_readcase(msg, f) != f->number) {
  3295. continue;
  3296. }
  3297. }
  3298. CHK(upb_encode_scalarfield(e, msg + f->offset, m, f, skip_empty));
  3299. }
  3300. }
  3301. unknown = upb_msg_getunknown(msg, &unknown_size);
  3302. if (unknown) {
  3303. upb_put_bytes(e, unknown, unknown_size);
  3304. }
  3305. *size = (e->limit - e->ptr) - pre_len;
  3306. return true;
  3307. }
  3308. char *upb_encode(const void *msg, const upb_msglayout *m, upb_arena *arena,
  3309. size_t *size) {
  3310. upb_encstate e;
  3311. e.alloc = upb_arena_alloc(arena);
  3312. e.buf = NULL;
  3313. e.limit = NULL;
  3314. e.ptr = NULL;
  3315. if (!upb_encode_message(&e, msg, m, size)) {
  3316. *size = 0;
  3317. return NULL;
  3318. }
  3319. *size = e.limit - e.ptr;
  3320. if (*size == 0) {
  3321. static char ch;
  3322. return &ch;
  3323. } else {
  3324. UPB_ASSERT(e.ptr);
  3325. return e.ptr;
  3326. }
  3327. }
  3328. #undef CHK
  3329. /*
  3330. ** TODO(haberman): it's unclear whether a lot of the consistency checks should
  3331. ** UPB_ASSERT() or return false.
  3332. */
  3333. #include <string.h>
  3334. static void *upb_calloc(size_t size) {
  3335. void *mem = upb_gmalloc(size);
  3336. if (mem) {
  3337. memset(mem, 0, size);
  3338. }
  3339. return mem;
  3340. }
  3341. /* Defined for the sole purpose of having a unique pointer value for
  3342. * UPB_NO_CLOSURE. */
  3343. char _upb_noclosure;
  3344. static void freehandlers(upb_refcounted *r) {
  3345. upb_handlers *h = (upb_handlers*)r;
  3346. upb_inttable_iter i;
  3347. upb_inttable_begin(&i, &h->cleanup_);
  3348. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  3349. void *val = (void*)upb_inttable_iter_key(&i);
  3350. upb_value func_val = upb_inttable_iter_value(&i);
  3351. upb_handlerfree *func = upb_value_getfptr(func_val);
  3352. func(val);
  3353. }
  3354. upb_inttable_uninit(&h->cleanup_);
  3355. upb_msgdef_unref(h->msg, h);
  3356. upb_gfree(h->sub);
  3357. upb_gfree(h);
  3358. }
  3359. static void visithandlers(const upb_refcounted *r, upb_refcounted_visit *visit,
  3360. void *closure) {
  3361. const upb_handlers *h = (const upb_handlers*)r;
  3362. upb_msg_field_iter i;
  3363. for(upb_msg_field_begin(&i, h->msg);
  3364. !upb_msg_field_done(&i);
  3365. upb_msg_field_next(&i)) {
  3366. upb_fielddef *f = upb_msg_iter_field(&i);
  3367. const upb_handlers *sub;
  3368. if (!upb_fielddef_issubmsg(f)) continue;
  3369. sub = upb_handlers_getsubhandlers(h, f);
  3370. if (sub) visit(r, upb_handlers_upcast(sub), closure);
  3371. }
  3372. }
  3373. static const struct upb_refcounted_vtbl vtbl = {visithandlers, freehandlers};
  3374. typedef struct {
  3375. upb_inttable tab; /* maps upb_msgdef* -> upb_handlers*. */
  3376. upb_handlers_callback *callback;
  3377. const void *closure;
  3378. } dfs_state;
  3379. /* TODO(haberman): discard upb_handlers* objects that do not actually have any
  3380. * handlers set and cannot reach any upb_handlers* object that does. This is
  3381. * slightly tricky to do correctly. */
  3382. static upb_handlers *newformsg(const upb_msgdef *m, const void *owner,
  3383. dfs_state *s) {
  3384. upb_msg_field_iter i;
  3385. upb_handlers *h = upb_handlers_new(m, owner);
  3386. if (!h) return NULL;
  3387. if (!upb_inttable_insertptr(&s->tab, m, upb_value_ptr(h))) goto oom;
  3388. s->callback(s->closure, h);
  3389. /* For each submessage field, get or create a handlers object and set it as
  3390. * the subhandlers. */
  3391. for(upb_msg_field_begin(&i, m);
  3392. !upb_msg_field_done(&i);
  3393. upb_msg_field_next(&i)) {
  3394. upb_fielddef *f = upb_msg_iter_field(&i);
  3395. const upb_msgdef *subdef;
  3396. upb_value subm_ent;
  3397. if (!upb_fielddef_issubmsg(f)) continue;
  3398. subdef = upb_downcast_msgdef(upb_fielddef_subdef(f));
  3399. if (upb_inttable_lookupptr(&s->tab, subdef, &subm_ent)) {
  3400. upb_handlers_setsubhandlers(h, f, upb_value_getptr(subm_ent));
  3401. } else {
  3402. upb_handlers *sub_mh = newformsg(subdef, &sub_mh, s);
  3403. if (!sub_mh) goto oom;
  3404. upb_handlers_setsubhandlers(h, f, sub_mh);
  3405. upb_handlers_unref(sub_mh, &sub_mh);
  3406. }
  3407. }
  3408. return h;
  3409. oom:
  3410. upb_handlers_unref(h, owner);
  3411. return NULL;
  3412. }
  3413. /* Given a selector for a STARTSUBMSG handler, resolves to a pointer to the
  3414. * subhandlers for this submessage field. */
  3415. #define SUBH(h, selector) (h->sub[selector])
  3416. /* The selector for a submessage field is the field index. */
  3417. #define SUBH_F(h, f) SUBH(h, f->index_)
  3418. static int32_t trygetsel(upb_handlers *h, const upb_fielddef *f,
  3419. upb_handlertype_t type) {
  3420. upb_selector_t sel;
  3421. UPB_ASSERT(!upb_handlers_isfrozen(h));
  3422. if (upb_handlers_msgdef(h) != upb_fielddef_containingtype(f)) {
  3423. upb_status_seterrf(
  3424. &h->status_, "type mismatch: field %s does not belong to message %s",
  3425. upb_fielddef_name(f), upb_msgdef_fullname(upb_handlers_msgdef(h)));
  3426. return -1;
  3427. }
  3428. if (!upb_handlers_getselector(f, type, &sel)) {
  3429. upb_status_seterrf(
  3430. &h->status_,
  3431. "type mismatch: cannot register handler type %d for field %s",
  3432. type, upb_fielddef_name(f));
  3433. return -1;
  3434. }
  3435. return sel;
  3436. }
  3437. static upb_selector_t handlers_getsel(upb_handlers *h, const upb_fielddef *f,
  3438. upb_handlertype_t type) {
  3439. int32_t sel = trygetsel(h, f, type);
  3440. UPB_ASSERT(sel >= 0);
  3441. return sel;
  3442. }
  3443. static const void **returntype(upb_handlers *h, const upb_fielddef *f,
  3444. upb_handlertype_t type) {
  3445. return &h->table[handlers_getsel(h, f, type)].attr.return_closure_type_;
  3446. }
  3447. static bool doset(upb_handlers *h, int32_t sel, const upb_fielddef *f,
  3448. upb_handlertype_t type, upb_func *func,
  3449. upb_handlerattr *attr) {
  3450. upb_handlerattr set_attr = UPB_HANDLERATTR_INITIALIZER;
  3451. const void *closure_type;
  3452. const void **context_closure_type;
  3453. UPB_ASSERT(!upb_handlers_isfrozen(h));
  3454. if (sel < 0) {
  3455. upb_status_seterrmsg(&h->status_,
  3456. "incorrect handler type for this field.");
  3457. return false;
  3458. }
  3459. if (h->table[sel].func) {
  3460. upb_status_seterrmsg(&h->status_,
  3461. "cannot change handler once it has been set.");
  3462. return false;
  3463. }
  3464. if (attr) {
  3465. set_attr = *attr;
  3466. }
  3467. /* Check that the given closure type matches the closure type that has been
  3468. * established for this context (if any). */
  3469. closure_type = upb_handlerattr_closuretype(&set_attr);
  3470. if (type == UPB_HANDLER_STRING) {
  3471. context_closure_type = returntype(h, f, UPB_HANDLER_STARTSTR);
  3472. } else if (f && upb_fielddef_isseq(f) &&
  3473. type != UPB_HANDLER_STARTSEQ &&
  3474. type != UPB_HANDLER_ENDSEQ) {
  3475. context_closure_type = returntype(h, f, UPB_HANDLER_STARTSEQ);
  3476. } else {
  3477. context_closure_type = &h->top_closure_type;
  3478. }
  3479. if (closure_type && *context_closure_type &&
  3480. closure_type != *context_closure_type) {
  3481. /* TODO(haberman): better message for debugging. */
  3482. if (f) {
  3483. upb_status_seterrf(&h->status_,
  3484. "closure type does not match for field %s",
  3485. upb_fielddef_name(f));
  3486. } else {
  3487. upb_status_seterrmsg(
  3488. &h->status_, "closure type does not match for message-level handler");
  3489. }
  3490. return false;
  3491. }
  3492. if (closure_type)
  3493. *context_closure_type = closure_type;
  3494. /* If this is a STARTSEQ or STARTSTR handler, check that the returned pointer
  3495. * matches any pre-existing expectations about what type is expected. */
  3496. if (type == UPB_HANDLER_STARTSEQ || type == UPB_HANDLER_STARTSTR) {
  3497. const void *return_type = upb_handlerattr_returnclosuretype(&set_attr);
  3498. const void *table_return_type =
  3499. upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  3500. if (return_type && table_return_type && return_type != table_return_type) {
  3501. upb_status_seterrmsg(&h->status_, "closure return type does not match");
  3502. return false;
  3503. }
  3504. if (table_return_type && !return_type)
  3505. upb_handlerattr_setreturnclosuretype(&set_attr, table_return_type);
  3506. }
  3507. h->table[sel].func = (upb_func*)func;
  3508. h->table[sel].attr = set_attr;
  3509. return true;
  3510. }
  3511. /* Returns the effective closure type for this handler (which will propagate
  3512. * from outer frames if this frame has no START* handler). Not implemented for
  3513. * UPB_HANDLER_STRING at the moment since this is not needed. Returns NULL is
  3514. * the effective closure type is unspecified (either no handler was registered
  3515. * to specify it or the handler that was registered did not specify the closure
  3516. * type). */
  3517. const void *effective_closure_type(upb_handlers *h, const upb_fielddef *f,
  3518. upb_handlertype_t type) {
  3519. const void *ret;
  3520. upb_selector_t sel;
  3521. UPB_ASSERT(type != UPB_HANDLER_STRING);
  3522. ret = h->top_closure_type;
  3523. if (upb_fielddef_isseq(f) &&
  3524. type != UPB_HANDLER_STARTSEQ &&
  3525. type != UPB_HANDLER_ENDSEQ &&
  3526. h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSEQ)].func) {
  3527. ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  3528. }
  3529. if (type == UPB_HANDLER_STRING &&
  3530. h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSTR)].func) {
  3531. ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  3532. }
  3533. /* The effective type of the submessage; not used yet.
  3534. * if (type == SUBMESSAGE &&
  3535. * h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSUBMSG)].func) {
  3536. * ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  3537. * } */
  3538. return ret;
  3539. }
  3540. /* Checks whether the START* handler specified by f & type is missing even
  3541. * though it is required to convert the established type of an outer frame
  3542. * ("closure_type") into the established type of an inner frame (represented in
  3543. * the return closure type of this handler's attr. */
  3544. bool checkstart(upb_handlers *h, const upb_fielddef *f, upb_handlertype_t type,
  3545. upb_status *status) {
  3546. const void *closure_type;
  3547. const upb_handlerattr *attr;
  3548. const void *return_closure_type;
  3549. upb_selector_t sel = handlers_getsel(h, f, type);
  3550. if (h->table[sel].func) return true;
  3551. closure_type = effective_closure_type(h, f, type);
  3552. attr = &h->table[sel].attr;
  3553. return_closure_type = upb_handlerattr_returnclosuretype(attr);
  3554. if (closure_type && return_closure_type &&
  3555. closure_type != return_closure_type) {
  3556. upb_status_seterrf(status,
  3557. "expected start handler to return sub type for field %f",
  3558. upb_fielddef_name(f));
  3559. return false;
  3560. }
  3561. return true;
  3562. }
  3563. /* Public interface ***********************************************************/
  3564. upb_handlers *upb_handlers_new(const upb_msgdef *md, const void *owner) {
  3565. int extra;
  3566. upb_handlers *h;
  3567. UPB_ASSERT(upb_msgdef_isfrozen(md));
  3568. extra = sizeof(upb_handlers_tabent) * (md->selector_count - 1);
  3569. h = upb_calloc(sizeof(*h) + extra);
  3570. if (!h) return NULL;
  3571. h->msg = md;
  3572. upb_msgdef_ref(h->msg, h);
  3573. upb_status_clear(&h->status_);
  3574. if (md->submsg_field_count > 0) {
  3575. h->sub = upb_calloc(md->submsg_field_count * sizeof(*h->sub));
  3576. if (!h->sub) goto oom;
  3577. } else {
  3578. h->sub = 0;
  3579. }
  3580. if (!upb_refcounted_init(upb_handlers_upcast_mutable(h), &vtbl, owner))
  3581. goto oom;
  3582. if (!upb_inttable_init(&h->cleanup_, UPB_CTYPE_FPTR)) goto oom;
  3583. /* calloc() above initialized all handlers to NULL. */
  3584. return h;
  3585. oom:
  3586. freehandlers(upb_handlers_upcast_mutable(h));
  3587. return NULL;
  3588. }
  3589. const upb_handlers *upb_handlers_newfrozen(const upb_msgdef *m,
  3590. const void *owner,
  3591. upb_handlers_callback *callback,
  3592. const void *closure) {
  3593. dfs_state state;
  3594. upb_handlers *ret;
  3595. bool ok;
  3596. upb_refcounted *r;
  3597. state.callback = callback;
  3598. state.closure = closure;
  3599. if (!upb_inttable_init(&state.tab, UPB_CTYPE_PTR)) return NULL;
  3600. ret = newformsg(m, owner, &state);
  3601. upb_inttable_uninit(&state.tab);
  3602. if (!ret) return NULL;
  3603. r = upb_handlers_upcast_mutable(ret);
  3604. ok = upb_refcounted_freeze(&r, 1, NULL, UPB_MAX_HANDLER_DEPTH);
  3605. UPB_ASSERT(ok);
  3606. return ret;
  3607. }
  3608. const upb_status *upb_handlers_status(upb_handlers *h) {
  3609. UPB_ASSERT(!upb_handlers_isfrozen(h));
  3610. return &h->status_;
  3611. }
  3612. void upb_handlers_clearerr(upb_handlers *h) {
  3613. UPB_ASSERT(!upb_handlers_isfrozen(h));
  3614. upb_status_clear(&h->status_);
  3615. }
  3616. #define SETTER(name, handlerctype, handlertype) \
  3617. bool upb_handlers_set ## name(upb_handlers *h, const upb_fielddef *f, \
  3618. handlerctype func, upb_handlerattr *attr) { \
  3619. int32_t sel = trygetsel(h, f, handlertype); \
  3620. return doset(h, sel, f, handlertype, (upb_func*)func, attr); \
  3621. }
  3622. SETTER(int32, upb_int32_handlerfunc*, UPB_HANDLER_INT32)
  3623. SETTER(int64, upb_int64_handlerfunc*, UPB_HANDLER_INT64)
  3624. SETTER(uint32, upb_uint32_handlerfunc*, UPB_HANDLER_UINT32)
  3625. SETTER(uint64, upb_uint64_handlerfunc*, UPB_HANDLER_UINT64)
  3626. SETTER(float, upb_float_handlerfunc*, UPB_HANDLER_FLOAT)
  3627. SETTER(double, upb_double_handlerfunc*, UPB_HANDLER_DOUBLE)
  3628. SETTER(bool, upb_bool_handlerfunc*, UPB_HANDLER_BOOL)
  3629. SETTER(startstr, upb_startstr_handlerfunc*, UPB_HANDLER_STARTSTR)
  3630. SETTER(string, upb_string_handlerfunc*, UPB_HANDLER_STRING)
  3631. SETTER(endstr, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSTR)
  3632. SETTER(startseq, upb_startfield_handlerfunc*, UPB_HANDLER_STARTSEQ)
  3633. SETTER(startsubmsg, upb_startfield_handlerfunc*, UPB_HANDLER_STARTSUBMSG)
  3634. SETTER(endsubmsg, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSUBMSG)
  3635. SETTER(endseq, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSEQ)
  3636. #undef SETTER
  3637. bool upb_handlers_setunknown(upb_handlers *h, upb_unknown_handlerfunc *func,
  3638. upb_handlerattr *attr) {
  3639. return doset(h, UPB_UNKNOWN_SELECTOR, NULL, UPB_HANDLER_INT32,
  3640. (upb_func *)func, attr);
  3641. }
  3642. bool upb_handlers_setstartmsg(upb_handlers *h, upb_startmsg_handlerfunc *func,
  3643. upb_handlerattr *attr) {
  3644. return doset(h, UPB_STARTMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
  3645. (upb_func *)func, attr);
  3646. }
  3647. bool upb_handlers_setendmsg(upb_handlers *h, upb_endmsg_handlerfunc *func,
  3648. upb_handlerattr *attr) {
  3649. UPB_ASSERT(!upb_handlers_isfrozen(h));
  3650. return doset(h, UPB_ENDMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
  3651. (upb_func *)func, attr);
  3652. }
  3653. bool upb_handlers_setsubhandlers(upb_handlers *h, const upb_fielddef *f,
  3654. const upb_handlers *sub) {
  3655. UPB_ASSERT(sub);
  3656. UPB_ASSERT(!upb_handlers_isfrozen(h));
  3657. UPB_ASSERT(upb_fielddef_issubmsg(f));
  3658. if (SUBH_F(h, f)) return false; /* Can't reset. */
  3659. if (upb_msgdef_upcast(upb_handlers_msgdef(sub)) != upb_fielddef_subdef(f)) {
  3660. return false;
  3661. }
  3662. SUBH_F(h, f) = sub;
  3663. upb_ref2(sub, h);
  3664. return true;
  3665. }
  3666. const upb_handlers *upb_handlers_getsubhandlers(const upb_handlers *h,
  3667. const upb_fielddef *f) {
  3668. UPB_ASSERT(upb_fielddef_issubmsg(f));
  3669. return SUBH_F(h, f);
  3670. }
  3671. bool upb_handlers_getattr(const upb_handlers *h, upb_selector_t sel,
  3672. upb_handlerattr *attr) {
  3673. if (!upb_handlers_gethandler(h, sel))
  3674. return false;
  3675. *attr = h->table[sel].attr;
  3676. return true;
  3677. }
  3678. const upb_handlers *upb_handlers_getsubhandlers_sel(const upb_handlers *h,
  3679. upb_selector_t sel) {
  3680. /* STARTSUBMSG selector in sel is the field's selector base. */
  3681. return SUBH(h, sel - UPB_STATIC_SELECTOR_COUNT);
  3682. }
  3683. const upb_msgdef *upb_handlers_msgdef(const upb_handlers *h) { return h->msg; }
  3684. bool upb_handlers_addcleanup(upb_handlers *h, void *p, upb_handlerfree *func) {
  3685. bool ok;
  3686. if (upb_inttable_lookupptr(&h->cleanup_, p, NULL)) {
  3687. return false;
  3688. }
  3689. ok = upb_inttable_insertptr(&h->cleanup_, p, upb_value_fptr(func));
  3690. UPB_ASSERT(ok);
  3691. return true;
  3692. }
  3693. /* "Static" methods ***********************************************************/
  3694. bool upb_handlers_freeze(upb_handlers *const*handlers, int n, upb_status *s) {
  3695. /* TODO: verify we have a transitive closure. */
  3696. int i;
  3697. for (i = 0; i < n; i++) {
  3698. upb_msg_field_iter j;
  3699. upb_handlers *h = handlers[i];
  3700. if (!upb_ok(&h->status_)) {
  3701. upb_status_seterrf(s, "handlers for message %s had error status: %s",
  3702. upb_msgdef_fullname(upb_handlers_msgdef(h)),
  3703. upb_status_errmsg(&h->status_));
  3704. return false;
  3705. }
  3706. /* Check that there are no closure mismatches due to missing Start* handlers
  3707. * or subhandlers with different type-level types. */
  3708. for(upb_msg_field_begin(&j, h->msg);
  3709. !upb_msg_field_done(&j);
  3710. upb_msg_field_next(&j)) {
  3711. const upb_fielddef *f = upb_msg_iter_field(&j);
  3712. if (upb_fielddef_isseq(f)) {
  3713. if (!checkstart(h, f, UPB_HANDLER_STARTSEQ, s))
  3714. return false;
  3715. }
  3716. if (upb_fielddef_isstring(f)) {
  3717. if (!checkstart(h, f, UPB_HANDLER_STARTSTR, s))
  3718. return false;
  3719. }
  3720. if (upb_fielddef_issubmsg(f)) {
  3721. bool hashandler = false;
  3722. if (upb_handlers_gethandler(
  3723. h, handlers_getsel(h, f, UPB_HANDLER_STARTSUBMSG)) ||
  3724. upb_handlers_gethandler(
  3725. h, handlers_getsel(h, f, UPB_HANDLER_ENDSUBMSG))) {
  3726. hashandler = true;
  3727. }
  3728. if (upb_fielddef_isseq(f) &&
  3729. (upb_handlers_gethandler(
  3730. h, handlers_getsel(h, f, UPB_HANDLER_STARTSEQ)) ||
  3731. upb_handlers_gethandler(
  3732. h, handlers_getsel(h, f, UPB_HANDLER_ENDSEQ)))) {
  3733. hashandler = true;
  3734. }
  3735. if (hashandler && !upb_handlers_getsubhandlers(h, f)) {
  3736. /* For now we add an empty subhandlers in this case. It makes the
  3737. * decoder code generator simpler, because it only has to handle two
  3738. * cases (submessage has handlers or not) as opposed to three
  3739. * (submessage has handlers in enclosing message but no subhandlers).
  3740. *
  3741. * This makes parsing less efficient in the case that we want to
  3742. * notice a submessage but skip its contents (like if we're testing
  3743. * for submessage presence or counting the number of repeated
  3744. * submessages). In this case we will end up parsing the submessage
  3745. * field by field and throwing away the results for each, instead of
  3746. * skipping the whole delimited thing at once. If this is an issue we
  3747. * can revisit it, but do remember that this only arises when you have
  3748. * handlers (startseq/startsubmsg/endsubmsg/endseq) set for the
  3749. * submessage but no subhandlers. The uses cases for this are
  3750. * limited. */
  3751. upb_handlers *sub = upb_handlers_new(upb_fielddef_msgsubdef(f), &sub);
  3752. upb_handlers_setsubhandlers(h, f, sub);
  3753. upb_handlers_unref(sub, &sub);
  3754. }
  3755. /* TODO(haberman): check type of submessage.
  3756. * This is slightly tricky; also consider whether we should check that
  3757. * they match at setsubhandlers time. */
  3758. }
  3759. }
  3760. }
  3761. if (!upb_refcounted_freeze((upb_refcounted*const*)handlers, n, s,
  3762. UPB_MAX_HANDLER_DEPTH)) {
  3763. return false;
  3764. }
  3765. return true;
  3766. }
  3767. upb_handlertype_t upb_handlers_getprimitivehandlertype(const upb_fielddef *f) {
  3768. switch (upb_fielddef_type(f)) {
  3769. case UPB_TYPE_INT32:
  3770. case UPB_TYPE_ENUM: return UPB_HANDLER_INT32;
  3771. case UPB_TYPE_INT64: return UPB_HANDLER_INT64;
  3772. case UPB_TYPE_UINT32: return UPB_HANDLER_UINT32;
  3773. case UPB_TYPE_UINT64: return UPB_HANDLER_UINT64;
  3774. case UPB_TYPE_FLOAT: return UPB_HANDLER_FLOAT;
  3775. case UPB_TYPE_DOUBLE: return UPB_HANDLER_DOUBLE;
  3776. case UPB_TYPE_BOOL: return UPB_HANDLER_BOOL;
  3777. default: UPB_ASSERT(false); return -1; /* Invalid input. */
  3778. }
  3779. }
  3780. bool upb_handlers_getselector(const upb_fielddef *f, upb_handlertype_t type,
  3781. upb_selector_t *s) {
  3782. switch (type) {
  3783. case UPB_HANDLER_INT32:
  3784. case UPB_HANDLER_INT64:
  3785. case UPB_HANDLER_UINT32:
  3786. case UPB_HANDLER_UINT64:
  3787. case UPB_HANDLER_FLOAT:
  3788. case UPB_HANDLER_DOUBLE:
  3789. case UPB_HANDLER_BOOL:
  3790. if (!upb_fielddef_isprimitive(f) ||
  3791. upb_handlers_getprimitivehandlertype(f) != type)
  3792. return false;
  3793. *s = f->selector_base;
  3794. break;
  3795. case UPB_HANDLER_STRING:
  3796. if (upb_fielddef_isstring(f)) {
  3797. *s = f->selector_base;
  3798. } else if (upb_fielddef_lazy(f)) {
  3799. *s = f->selector_base + 3;
  3800. } else {
  3801. return false;
  3802. }
  3803. break;
  3804. case UPB_HANDLER_STARTSTR:
  3805. if (upb_fielddef_isstring(f) || upb_fielddef_lazy(f)) {
  3806. *s = f->selector_base + 1;
  3807. } else {
  3808. return false;
  3809. }
  3810. break;
  3811. case UPB_HANDLER_ENDSTR:
  3812. if (upb_fielddef_isstring(f) || upb_fielddef_lazy(f)) {
  3813. *s = f->selector_base + 2;
  3814. } else {
  3815. return false;
  3816. }
  3817. break;
  3818. case UPB_HANDLER_STARTSEQ:
  3819. if (!upb_fielddef_isseq(f)) return false;
  3820. *s = f->selector_base - 2;
  3821. break;
  3822. case UPB_HANDLER_ENDSEQ:
  3823. if (!upb_fielddef_isseq(f)) return false;
  3824. *s = f->selector_base - 1;
  3825. break;
  3826. case UPB_HANDLER_STARTSUBMSG:
  3827. if (!upb_fielddef_issubmsg(f)) return false;
  3828. /* Selectors for STARTSUBMSG are at the beginning of the table so that the
  3829. * selector can also be used as an index into the "sub" array of
  3830. * subhandlers. The indexes for the two into these two tables are the
  3831. * same, except that in the handler table the static selectors come first. */
  3832. *s = f->index_ + UPB_STATIC_SELECTOR_COUNT;
  3833. break;
  3834. case UPB_HANDLER_ENDSUBMSG:
  3835. if (!upb_fielddef_issubmsg(f)) return false;
  3836. *s = f->selector_base;
  3837. break;
  3838. }
  3839. UPB_ASSERT((size_t)*s < upb_fielddef_containingtype(f)->selector_count);
  3840. return true;
  3841. }
  3842. uint32_t upb_handlers_selectorbaseoffset(const upb_fielddef *f) {
  3843. return upb_fielddef_isseq(f) ? 2 : 0;
  3844. }
  3845. uint32_t upb_handlers_selectorcount(const upb_fielddef *f) {
  3846. uint32_t ret = 1;
  3847. if (upb_fielddef_isseq(f)) ret += 2; /* STARTSEQ/ENDSEQ */
  3848. if (upb_fielddef_isstring(f)) ret += 2; /* [STRING]/STARTSTR/ENDSTR */
  3849. if (upb_fielddef_issubmsg(f)) {
  3850. /* ENDSUBMSG (STARTSUBMSG is at table beginning) */
  3851. ret += 0;
  3852. if (upb_fielddef_lazy(f)) {
  3853. /* STARTSTR/ENDSTR/STRING (for lazy) */
  3854. ret += 3;
  3855. }
  3856. }
  3857. return ret;
  3858. }
  3859. /* upb_handlerattr ************************************************************/
  3860. void upb_handlerattr_init(upb_handlerattr *attr) {
  3861. upb_handlerattr from = UPB_HANDLERATTR_INITIALIZER;
  3862. memcpy(attr, &from, sizeof(*attr));
  3863. }
  3864. void upb_handlerattr_uninit(upb_handlerattr *attr) {
  3865. UPB_UNUSED(attr);
  3866. }
  3867. bool upb_handlerattr_sethandlerdata(upb_handlerattr *attr, const void *hd) {
  3868. attr->handler_data_ = hd;
  3869. return true;
  3870. }
  3871. bool upb_handlerattr_setclosuretype(upb_handlerattr *attr, const void *type) {
  3872. attr->closure_type_ = type;
  3873. return true;
  3874. }
  3875. const void *upb_handlerattr_closuretype(const upb_handlerattr *attr) {
  3876. return attr->closure_type_;
  3877. }
  3878. bool upb_handlerattr_setreturnclosuretype(upb_handlerattr *attr,
  3879. const void *type) {
  3880. attr->return_closure_type_ = type;
  3881. return true;
  3882. }
  3883. const void *upb_handlerattr_returnclosuretype(const upb_handlerattr *attr) {
  3884. return attr->return_closure_type_;
  3885. }
  3886. bool upb_handlerattr_setalwaysok(upb_handlerattr *attr, bool alwaysok) {
  3887. attr->alwaysok_ = alwaysok;
  3888. return true;
  3889. }
  3890. bool upb_handlerattr_alwaysok(const upb_handlerattr *attr) {
  3891. return attr->alwaysok_;
  3892. }
  3893. /* upb_bufhandle **************************************************************/
  3894. size_t upb_bufhandle_objofs(const upb_bufhandle *h) {
  3895. return h->objofs_;
  3896. }
  3897. /* upb_byteshandler ***********************************************************/
  3898. void upb_byteshandler_init(upb_byteshandler* h) {
  3899. memset(h, 0, sizeof(*h));
  3900. }
  3901. /* For when we support handlerfree callbacks. */
  3902. void upb_byteshandler_uninit(upb_byteshandler* h) {
  3903. UPB_UNUSED(h);
  3904. }
  3905. bool upb_byteshandler_setstartstr(upb_byteshandler *h,
  3906. upb_startstr_handlerfunc *func, void *d) {
  3907. h->table[UPB_STARTSTR_SELECTOR].func = (upb_func*)func;
  3908. h->table[UPB_STARTSTR_SELECTOR].attr.handler_data_ = d;
  3909. return true;
  3910. }
  3911. bool upb_byteshandler_setstring(upb_byteshandler *h,
  3912. upb_string_handlerfunc *func, void *d) {
  3913. h->table[UPB_STRING_SELECTOR].func = (upb_func*)func;
  3914. h->table[UPB_STRING_SELECTOR].attr.handler_data_ = d;
  3915. return true;
  3916. }
  3917. bool upb_byteshandler_setendstr(upb_byteshandler *h,
  3918. upb_endfield_handlerfunc *func, void *d) {
  3919. h->table[UPB_ENDSTR_SELECTOR].func = (upb_func*)func;
  3920. h->table[UPB_ENDSTR_SELECTOR].attr.handler_data_ = d;
  3921. return true;
  3922. }
  3923. /** Handlers for upb_msg ******************************************************/
  3924. typedef struct {
  3925. size_t offset;
  3926. int32_t hasbit;
  3927. } upb_msg_handlerdata;
  3928. /* Fallback implementation if the handler is not specialized by the producer. */
  3929. #define MSG_WRITER(type, ctype) \
  3930. bool upb_msg_set ## type (void *c, const void *hd, ctype val) { \
  3931. uint8_t *m = c; \
  3932. const upb_msg_handlerdata *d = hd; \
  3933. if (d->hasbit > 0) \
  3934. *(uint8_t*)&m[d->hasbit / 8] |= 1 << (d->hasbit % 8); \
  3935. *(ctype*)&m[d->offset] = val; \
  3936. return true; \
  3937. } \
  3938. MSG_WRITER(double, double)
  3939. MSG_WRITER(float, float)
  3940. MSG_WRITER(int32, int32_t)
  3941. MSG_WRITER(int64, int64_t)
  3942. MSG_WRITER(uint32, uint32_t)
  3943. MSG_WRITER(uint64, uint64_t)
  3944. MSG_WRITER(bool, bool)
  3945. bool upb_msg_setscalarhandler(upb_handlers *h, const upb_fielddef *f,
  3946. size_t offset, int32_t hasbit) {
  3947. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  3948. bool ok;
  3949. upb_msg_handlerdata *d = upb_gmalloc(sizeof(*d));
  3950. if (!d) return false;
  3951. d->offset = offset;
  3952. d->hasbit = hasbit;
  3953. upb_handlerattr_sethandlerdata(&attr, d);
  3954. upb_handlerattr_setalwaysok(&attr, true);
  3955. upb_handlers_addcleanup(h, d, upb_gfree);
  3956. #define TYPE(u, l) \
  3957. case UPB_TYPE_##u: \
  3958. ok = upb_handlers_set##l(h, f, upb_msg_set##l, &attr); break;
  3959. ok = false;
  3960. switch (upb_fielddef_type(f)) {
  3961. TYPE(INT64, int64);
  3962. TYPE(INT32, int32);
  3963. TYPE(ENUM, int32);
  3964. TYPE(UINT64, uint64);
  3965. TYPE(UINT32, uint32);
  3966. TYPE(DOUBLE, double);
  3967. TYPE(FLOAT, float);
  3968. TYPE(BOOL, bool);
  3969. default: UPB_ASSERT(false); break;
  3970. }
  3971. #undef TYPE
  3972. upb_handlerattr_uninit(&attr);
  3973. return ok;
  3974. }
  3975. bool upb_msg_getscalarhandlerdata(const upb_handlers *h,
  3976. upb_selector_t s,
  3977. upb_fieldtype_t *type,
  3978. size_t *offset,
  3979. int32_t *hasbit) {
  3980. const upb_msg_handlerdata *d;
  3981. upb_func *f = upb_handlers_gethandler(h, s);
  3982. if ((upb_int64_handlerfunc*)f == upb_msg_setint64) {
  3983. *type = UPB_TYPE_INT64;
  3984. } else if ((upb_int32_handlerfunc*)f == upb_msg_setint32) {
  3985. *type = UPB_TYPE_INT32;
  3986. } else if ((upb_uint64_handlerfunc*)f == upb_msg_setuint64) {
  3987. *type = UPB_TYPE_UINT64;
  3988. } else if ((upb_uint32_handlerfunc*)f == upb_msg_setuint32) {
  3989. *type = UPB_TYPE_UINT32;
  3990. } else if ((upb_double_handlerfunc*)f == upb_msg_setdouble) {
  3991. *type = UPB_TYPE_DOUBLE;
  3992. } else if ((upb_float_handlerfunc*)f == upb_msg_setfloat) {
  3993. *type = UPB_TYPE_FLOAT;
  3994. } else if ((upb_bool_handlerfunc*)f == upb_msg_setbool) {
  3995. *type = UPB_TYPE_BOOL;
  3996. } else {
  3997. return false;
  3998. }
  3999. d = upb_handlers_gethandlerdata(h, s);
  4000. *offset = d->offset;
  4001. *hasbit = d->hasbit;
  4002. return true;
  4003. }
  4004. bool upb_fieldtype_mapkeyok(upb_fieldtype_t type) {
  4005. return type == UPB_TYPE_BOOL || type == UPB_TYPE_INT32 ||
  4006. type == UPB_TYPE_UINT32 || type == UPB_TYPE_INT64 ||
  4007. type == UPB_TYPE_UINT64 || type == UPB_TYPE_STRING;
  4008. }
  4009. #define PTR_AT(msg, ofs, type) (type*)((char*)msg + ofs)
  4010. #define VOIDPTR_AT(msg, ofs) PTR_AT(msg, ofs, void)
  4011. #define ENCODE_MAX_NESTING 64
  4012. #define CHECK_TRUE(x) if (!(x)) { return false; }
  4013. /** upb_msgval ****************************************************************/
  4014. #define upb_alignof(t) offsetof(struct { char c; t x; }, x)
  4015. /* These functions will generate real memcpy() calls on ARM sadly, because
  4016. * the compiler assumes they might not be aligned. */
  4017. static upb_msgval upb_msgval_read(const void *p, size_t ofs,
  4018. uint8_t size) {
  4019. upb_msgval val;
  4020. p = (char*)p + ofs;
  4021. memcpy(&val, p, size);
  4022. return val;
  4023. }
  4024. static void upb_msgval_write(void *p, size_t ofs, upb_msgval val,
  4025. uint8_t size) {
  4026. p = (char*)p + ofs;
  4027. memcpy(p, &val, size);
  4028. }
  4029. static size_t upb_msgval_sizeof(upb_fieldtype_t type) {
  4030. switch (type) {
  4031. case UPB_TYPE_DOUBLE:
  4032. case UPB_TYPE_INT64:
  4033. case UPB_TYPE_UINT64:
  4034. return 8;
  4035. case UPB_TYPE_ENUM:
  4036. case UPB_TYPE_INT32:
  4037. case UPB_TYPE_UINT32:
  4038. case UPB_TYPE_FLOAT:
  4039. return 4;
  4040. case UPB_TYPE_BOOL:
  4041. return 1;
  4042. case UPB_TYPE_MESSAGE:
  4043. return sizeof(void*);
  4044. case UPB_TYPE_BYTES:
  4045. case UPB_TYPE_STRING:
  4046. return sizeof(upb_stringview);
  4047. }
  4048. UPB_UNREACHABLE();
  4049. }
  4050. static uint8_t upb_msg_fieldsize(const upb_msglayout_field *field) {
  4051. if (field->label == UPB_LABEL_REPEATED) {
  4052. return sizeof(void*);
  4053. } else {
  4054. return upb_msgval_sizeof(upb_desctype_to_fieldtype[field->descriptortype]);
  4055. }
  4056. }
  4057. /* TODO(haberman): this is broken right now because upb_msgval can contain
  4058. * a char* / size_t pair, which is too big for a upb_value. To fix this
  4059. * we'll probably need to dynamically allocate a upb_msgval and store a
  4060. * pointer to that in the tables for extensions/maps. */
  4061. static upb_value upb_toval(upb_msgval val) {
  4062. upb_value ret;
  4063. UPB_UNUSED(val);
  4064. memset(&ret, 0, sizeof(upb_value)); /* XXX */
  4065. return ret;
  4066. }
  4067. static upb_msgval upb_msgval_fromval(upb_value val) {
  4068. upb_msgval ret;
  4069. UPB_UNUSED(val);
  4070. memset(&ret, 0, sizeof(upb_msgval)); /* XXX */
  4071. return ret;
  4072. }
  4073. static upb_ctype_t upb_fieldtotabtype(upb_fieldtype_t type) {
  4074. switch (type) {
  4075. case UPB_TYPE_FLOAT: return UPB_CTYPE_FLOAT;
  4076. case UPB_TYPE_DOUBLE: return UPB_CTYPE_DOUBLE;
  4077. case UPB_TYPE_BOOL: return UPB_CTYPE_BOOL;
  4078. case UPB_TYPE_BYTES:
  4079. case UPB_TYPE_MESSAGE:
  4080. case UPB_TYPE_STRING: return UPB_CTYPE_CONSTPTR;
  4081. case UPB_TYPE_ENUM:
  4082. case UPB_TYPE_INT32: return UPB_CTYPE_INT32;
  4083. case UPB_TYPE_UINT32: return UPB_CTYPE_UINT32;
  4084. case UPB_TYPE_INT64: return UPB_CTYPE_INT64;
  4085. case UPB_TYPE_UINT64: return UPB_CTYPE_UINT64;
  4086. default: UPB_ASSERT(false); return 0;
  4087. }
  4088. }
  4089. /** upb_msg *******************************************************************/
  4090. /* If we always read/write as a consistent type to each address, this shouldn't
  4091. * violate aliasing.
  4092. */
  4093. #define DEREF(msg, ofs, type) *PTR_AT(msg, ofs, type)
  4094. /* Internal members of a upb_msg. We can change this without breaking binary
  4095. * compatibility. We put these before the user's data. The user's upb_msg*
  4096. * points after the upb_msg_internal. */
  4097. /* Used when a message is not extendable. */
  4098. typedef struct {
  4099. /* TODO(haberman): use pointer tagging so we we are slim when known unknown
  4100. * fields are not present. */
  4101. upb_arena *arena;
  4102. char *unknown;
  4103. size_t unknown_len;
  4104. size_t unknown_size;
  4105. } upb_msg_internal;
  4106. /* Used when a message is extendable. */
  4107. typedef struct {
  4108. upb_inttable *extdict;
  4109. upb_msg_internal base;
  4110. } upb_msg_internal_withext;
  4111. static int upb_msg_internalsize(const upb_msglayout *l) {
  4112. return sizeof(upb_msg_internal) - l->extendable * sizeof(void *);
  4113. }
  4114. static upb_msg_internal *upb_msg_getinternal(upb_msg *msg) {
  4115. return VOIDPTR_AT(msg, -sizeof(upb_msg_internal));
  4116. }
  4117. static const upb_msg_internal *upb_msg_getinternal_const(const upb_msg *msg) {
  4118. return VOIDPTR_AT(msg, -sizeof(upb_msg_internal));
  4119. }
  4120. static upb_msg_internal_withext *upb_msg_getinternalwithext(
  4121. upb_msg *msg, const upb_msglayout *l) {
  4122. UPB_ASSERT(l->extendable);
  4123. return VOIDPTR_AT(msg, -sizeof(upb_msg_internal_withext));
  4124. }
  4125. void upb_msg_addunknown(upb_msg *msg, const char *data, size_t len) {
  4126. upb_msg_internal* in = upb_msg_getinternal(msg);
  4127. if (len > in->unknown_size - in->unknown_len) {
  4128. upb_alloc *alloc = upb_arena_alloc(in->arena);
  4129. size_t need = in->unknown_size + len;
  4130. size_t newsize = UPB_MAX(in->unknown_size * 2, need);
  4131. in->unknown = upb_realloc(alloc, in->unknown, in->unknown_size, newsize);
  4132. in->unknown_size = newsize;
  4133. }
  4134. memcpy(in->unknown + in->unknown_len, data, len);
  4135. in->unknown_len += len;
  4136. }
  4137. const char *upb_msg_getunknown(const upb_msg *msg, size_t *len) {
  4138. const upb_msg_internal* in = upb_msg_getinternal_const(msg);
  4139. *len = in->unknown_len;
  4140. return in->unknown;
  4141. }
  4142. static const upb_msglayout_field *upb_msg_checkfield(int field_index,
  4143. const upb_msglayout *l) {
  4144. UPB_ASSERT(field_index >= 0 && field_index < l->field_count);
  4145. return &l->fields[field_index];
  4146. }
  4147. static bool upb_msg_inoneof(const upb_msglayout_field *field) {
  4148. return field->presence < 0;
  4149. }
  4150. static uint32_t *upb_msg_oneofcase(const upb_msg *msg, int field_index,
  4151. const upb_msglayout *l) {
  4152. const upb_msglayout_field *field = upb_msg_checkfield(field_index, l);
  4153. UPB_ASSERT(upb_msg_inoneof(field));
  4154. return PTR_AT(msg, ~field->presence, uint32_t);
  4155. }
  4156. static size_t upb_msg_sizeof(const upb_msglayout *l) {
  4157. return l->size + upb_msg_internalsize(l);
  4158. }
  4159. upb_msg *upb_msg_new(const upb_msglayout *l, upb_arena *a) {
  4160. upb_alloc *alloc = upb_arena_alloc(a);
  4161. void *mem = upb_malloc(alloc, upb_msg_sizeof(l));
  4162. upb_msg_internal *in;
  4163. upb_msg *msg;
  4164. if (!mem) {
  4165. return NULL;
  4166. }
  4167. msg = VOIDPTR_AT(mem, upb_msg_internalsize(l));
  4168. /* Initialize normal members. */
  4169. memset(msg, 0, l->size);
  4170. /* Initialize internal members. */
  4171. in = upb_msg_getinternal(msg);
  4172. in->arena = a;
  4173. in->unknown = NULL;
  4174. in->unknown_len = 0;
  4175. in->unknown_size = 0;
  4176. if (l->extendable) {
  4177. upb_msg_getinternalwithext(msg, l)->extdict = NULL;
  4178. }
  4179. return msg;
  4180. }
  4181. upb_arena *upb_msg_arena(const upb_msg *msg) {
  4182. return upb_msg_getinternal_const(msg)->arena;
  4183. }
  4184. bool upb_msg_has(const upb_msg *msg,
  4185. int field_index,
  4186. const upb_msglayout *l) {
  4187. const upb_msglayout_field *field = upb_msg_checkfield(field_index, l);
  4188. UPB_ASSERT(field->presence);
  4189. if (upb_msg_inoneof(field)) {
  4190. /* Oneofs are set when the oneof number is set to this field. */
  4191. return *upb_msg_oneofcase(msg, field_index, l) == field->number;
  4192. } else {
  4193. /* Other fields are set when their hasbit is set. */
  4194. uint32_t hasbit = field->presence;
  4195. return DEREF(msg, hasbit / 8, char) | (1 << (hasbit % 8));
  4196. }
  4197. }
  4198. upb_msgval upb_msg_get(const upb_msg *msg, int field_index,
  4199. const upb_msglayout *l) {
  4200. const upb_msglayout_field *field = upb_msg_checkfield(field_index, l);
  4201. int size = upb_msg_fieldsize(field);
  4202. return upb_msgval_read(msg, field->offset, size);
  4203. }
  4204. void upb_msg_set(upb_msg *msg, int field_index, upb_msgval val,
  4205. const upb_msglayout *l) {
  4206. const upb_msglayout_field *field = upb_msg_checkfield(field_index, l);
  4207. int size = upb_msg_fieldsize(field);
  4208. upb_msgval_write(msg, field->offset, val, size);
  4209. }
  4210. /** upb_array *****************************************************************/
  4211. #define DEREF_ARR(arr, i, type) ((type*)arr->data)[i]
  4212. upb_array *upb_array_new(upb_fieldtype_t type, upb_arena *a) {
  4213. upb_alloc *alloc = upb_arena_alloc(a);
  4214. upb_array *ret = upb_malloc(alloc, sizeof(upb_array));
  4215. if (!ret) {
  4216. return NULL;
  4217. }
  4218. ret->type = type;
  4219. ret->data = NULL;
  4220. ret->len = 0;
  4221. ret->size = 0;
  4222. ret->element_size = upb_msgval_sizeof(type);
  4223. ret->arena = a;
  4224. return ret;
  4225. }
  4226. size_t upb_array_size(const upb_array *arr) {
  4227. return arr->len;
  4228. }
  4229. upb_fieldtype_t upb_array_type(const upb_array *arr) {
  4230. return arr->type;
  4231. }
  4232. upb_msgval upb_array_get(const upb_array *arr, size_t i) {
  4233. UPB_ASSERT(i < arr->len);
  4234. return upb_msgval_read(arr->data, i * arr->element_size, arr->element_size);
  4235. }
  4236. bool upb_array_set(upb_array *arr, size_t i, upb_msgval val) {
  4237. UPB_ASSERT(i <= arr->len);
  4238. if (i == arr->len) {
  4239. /* Extending the array. */
  4240. if (i == arr->size) {
  4241. /* Need to reallocate. */
  4242. size_t new_size = UPB_MAX(arr->size * 2, 8);
  4243. size_t new_bytes = new_size * arr->element_size;
  4244. size_t old_bytes = arr->size * arr->element_size;
  4245. upb_alloc *alloc = upb_arena_alloc(arr->arena);
  4246. upb_msgval *new_data =
  4247. upb_realloc(alloc, arr->data, old_bytes, new_bytes);
  4248. if (!new_data) {
  4249. return false;
  4250. }
  4251. arr->data = new_data;
  4252. arr->size = new_size;
  4253. }
  4254. arr->len = i + 1;
  4255. }
  4256. upb_msgval_write(arr->data, i * arr->element_size, val, arr->element_size);
  4257. return true;
  4258. }
  4259. /** upb_map *******************************************************************/
  4260. struct upb_map {
  4261. upb_fieldtype_t key_type;
  4262. upb_fieldtype_t val_type;
  4263. /* We may want to optimize this to use inttable where possible, for greater
  4264. * efficiency and lower memory footprint. */
  4265. upb_strtable strtab;
  4266. upb_arena *arena;
  4267. };
  4268. static void upb_map_tokey(upb_fieldtype_t type, upb_msgval *key,
  4269. const char **out_key, size_t *out_len) {
  4270. switch (type) {
  4271. case UPB_TYPE_STRING:
  4272. /* Point to string data of the input key. */
  4273. *out_key = key->str.data;
  4274. *out_len = key->str.size;
  4275. return;
  4276. case UPB_TYPE_BOOL:
  4277. case UPB_TYPE_INT32:
  4278. case UPB_TYPE_UINT32:
  4279. case UPB_TYPE_INT64:
  4280. case UPB_TYPE_UINT64:
  4281. /* Point to the key itself. XXX: big-endian. */
  4282. *out_key = (const char*)key;
  4283. *out_len = upb_msgval_sizeof(type);
  4284. return;
  4285. case UPB_TYPE_BYTES:
  4286. case UPB_TYPE_DOUBLE:
  4287. case UPB_TYPE_ENUM:
  4288. case UPB_TYPE_FLOAT:
  4289. case UPB_TYPE_MESSAGE:
  4290. break; /* Cannot be a map key. */
  4291. }
  4292. UPB_UNREACHABLE();
  4293. }
  4294. static upb_msgval upb_map_fromkey(upb_fieldtype_t type, const char *key,
  4295. size_t len) {
  4296. switch (type) {
  4297. case UPB_TYPE_STRING:
  4298. return upb_msgval_makestr(key, len);
  4299. case UPB_TYPE_BOOL:
  4300. case UPB_TYPE_INT32:
  4301. case UPB_TYPE_UINT32:
  4302. case UPB_TYPE_INT64:
  4303. case UPB_TYPE_UINT64:
  4304. return upb_msgval_read(key, 0, upb_msgval_sizeof(type));
  4305. case UPB_TYPE_BYTES:
  4306. case UPB_TYPE_DOUBLE:
  4307. case UPB_TYPE_ENUM:
  4308. case UPB_TYPE_FLOAT:
  4309. case UPB_TYPE_MESSAGE:
  4310. break; /* Cannot be a map key. */
  4311. }
  4312. UPB_UNREACHABLE();
  4313. }
  4314. upb_map *upb_map_new(upb_fieldtype_t ktype, upb_fieldtype_t vtype,
  4315. upb_arena *a) {
  4316. upb_ctype_t vtabtype = upb_fieldtotabtype(vtype);
  4317. upb_alloc *alloc = upb_arena_alloc(a);
  4318. upb_map *map = upb_malloc(alloc, sizeof(upb_map));
  4319. if (!map) {
  4320. return NULL;
  4321. }
  4322. UPB_ASSERT(upb_fieldtype_mapkeyok(ktype));
  4323. map->key_type = ktype;
  4324. map->val_type = vtype;
  4325. map->arena = a;
  4326. if (!upb_strtable_init2(&map->strtab, vtabtype, alloc)) {
  4327. return NULL;
  4328. }
  4329. return map;
  4330. }
  4331. size_t upb_map_size(const upb_map *map) {
  4332. return upb_strtable_count(&map->strtab);
  4333. }
  4334. upb_fieldtype_t upb_map_keytype(const upb_map *map) {
  4335. return map->key_type;
  4336. }
  4337. upb_fieldtype_t upb_map_valuetype(const upb_map *map) {
  4338. return map->val_type;
  4339. }
  4340. bool upb_map_get(const upb_map *map, upb_msgval key, upb_msgval *val) {
  4341. upb_value tabval;
  4342. const char *key_str;
  4343. size_t key_len;
  4344. bool ret;
  4345. upb_map_tokey(map->key_type, &key, &key_str, &key_len);
  4346. ret = upb_strtable_lookup2(&map->strtab, key_str, key_len, &tabval);
  4347. if (ret) {
  4348. memcpy(val, &tabval, sizeof(tabval));
  4349. }
  4350. return ret;
  4351. }
  4352. bool upb_map_set(upb_map *map, upb_msgval key, upb_msgval val,
  4353. upb_msgval *removed) {
  4354. const char *key_str;
  4355. size_t key_len;
  4356. upb_value tabval = upb_toval(val);
  4357. upb_value removedtabval;
  4358. upb_alloc *a = upb_arena_alloc(map->arena);
  4359. upb_map_tokey(map->key_type, &key, &key_str, &key_len);
  4360. /* TODO(haberman): add overwrite operation to minimize number of lookups. */
  4361. if (upb_strtable_lookup2(&map->strtab, key_str, key_len, NULL)) {
  4362. upb_strtable_remove3(&map->strtab, key_str, key_len, &removedtabval, a);
  4363. memcpy(&removed, &removedtabval, sizeof(removed));
  4364. }
  4365. return upb_strtable_insert3(&map->strtab, key_str, key_len, tabval, a);
  4366. }
  4367. bool upb_map_del(upb_map *map, upb_msgval key) {
  4368. const char *key_str;
  4369. size_t key_len;
  4370. upb_alloc *a = upb_arena_alloc(map->arena);
  4371. upb_map_tokey(map->key_type, &key, &key_str, &key_len);
  4372. return upb_strtable_remove3(&map->strtab, key_str, key_len, NULL, a);
  4373. }
  4374. /** upb_mapiter ***************************************************************/
  4375. struct upb_mapiter {
  4376. upb_strtable_iter iter;
  4377. upb_fieldtype_t key_type;
  4378. };
  4379. size_t upb_mapiter_sizeof() {
  4380. return sizeof(upb_mapiter);
  4381. }
  4382. void upb_mapiter_begin(upb_mapiter *i, const upb_map *map) {
  4383. upb_strtable_begin(&i->iter, &map->strtab);
  4384. i->key_type = map->key_type;
  4385. }
  4386. upb_mapiter *upb_mapiter_new(const upb_map *t, upb_alloc *a) {
  4387. upb_mapiter *ret = upb_malloc(a, upb_mapiter_sizeof());
  4388. if (!ret) {
  4389. return NULL;
  4390. }
  4391. upb_mapiter_begin(ret, t);
  4392. return ret;
  4393. }
  4394. void upb_mapiter_free(upb_mapiter *i, upb_alloc *a) {
  4395. upb_free(a, i);
  4396. }
  4397. void upb_mapiter_next(upb_mapiter *i) {
  4398. upb_strtable_next(&i->iter);
  4399. }
  4400. bool upb_mapiter_done(const upb_mapiter *i) {
  4401. return upb_strtable_done(&i->iter);
  4402. }
  4403. upb_msgval upb_mapiter_key(const upb_mapiter *i) {
  4404. return upb_map_fromkey(i->key_type, upb_strtable_iter_key(&i->iter),
  4405. upb_strtable_iter_keylength(&i->iter));
  4406. }
  4407. upb_msgval upb_mapiter_value(const upb_mapiter *i) {
  4408. return upb_msgval_fromval(upb_strtable_iter_value(&i->iter));
  4409. }
  4410. void upb_mapiter_setdone(upb_mapiter *i) {
  4411. upb_strtable_iter_setdone(&i->iter);
  4412. }
  4413. bool upb_mapiter_isequal(const upb_mapiter *i1, const upb_mapiter *i2) {
  4414. return upb_strtable_iter_isequal(&i1->iter, &i2->iter);
  4415. }
  4416. static bool is_power_of_two(size_t val) {
  4417. return (val & (val - 1)) == 0;
  4418. }
  4419. /* Align up to the given power of 2. */
  4420. static size_t align_up(size_t val, size_t align) {
  4421. UPB_ASSERT(is_power_of_two(align));
  4422. return (val + align - 1) & ~(align - 1);
  4423. }
  4424. static size_t div_round_up(size_t n, size_t d) {
  4425. return (n + d - 1) / d;
  4426. }
  4427. static size_t upb_msgval_sizeof2(upb_fieldtype_t type) {
  4428. switch (type) {
  4429. case UPB_TYPE_DOUBLE:
  4430. case UPB_TYPE_INT64:
  4431. case UPB_TYPE_UINT64:
  4432. return 8;
  4433. case UPB_TYPE_ENUM:
  4434. case UPB_TYPE_INT32:
  4435. case UPB_TYPE_UINT32:
  4436. case UPB_TYPE_FLOAT:
  4437. return 4;
  4438. case UPB_TYPE_BOOL:
  4439. return 1;
  4440. case UPB_TYPE_MESSAGE:
  4441. return sizeof(void*);
  4442. case UPB_TYPE_BYTES:
  4443. case UPB_TYPE_STRING:
  4444. return sizeof(upb_stringview);
  4445. }
  4446. UPB_UNREACHABLE();
  4447. }
  4448. static uint8_t upb_msg_fielddefsize(const upb_fielddef *f) {
  4449. if (upb_fielddef_isseq(f)) {
  4450. return sizeof(void*);
  4451. } else {
  4452. return upb_msgval_sizeof2(upb_fielddef_type(f));
  4453. }
  4454. }
  4455. /** upb_msglayout *************************************************************/
  4456. static void upb_msglayout_free(upb_msglayout *l) {
  4457. upb_gfree(l);
  4458. }
  4459. static size_t upb_msglayout_place(upb_msglayout *l, size_t size) {
  4460. size_t ret;
  4461. l->size = align_up(l->size, size);
  4462. ret = l->size;
  4463. l->size += size;
  4464. return ret;
  4465. }
  4466. static bool upb_msglayout_init(const upb_msgdef *m,
  4467. upb_msglayout *l,
  4468. upb_msgfactory *factory) {
  4469. upb_msg_field_iter it;
  4470. upb_msg_oneof_iter oit;
  4471. size_t hasbit;
  4472. size_t submsg_count = 0;
  4473. const upb_msglayout **submsgs;
  4474. upb_msglayout_field *fields;
  4475. for (upb_msg_field_begin(&it, m);
  4476. !upb_msg_field_done(&it);
  4477. upb_msg_field_next(&it)) {
  4478. const upb_fielddef* f = upb_msg_iter_field(&it);
  4479. if (upb_fielddef_issubmsg(f)) {
  4480. submsg_count++;
  4481. }
  4482. }
  4483. memset(l, 0, sizeof(*l));
  4484. fields = upb_gmalloc(upb_msgdef_numfields(m) * sizeof(*fields));
  4485. submsgs = upb_gmalloc(submsg_count * sizeof(*submsgs));
  4486. if ((!fields && upb_msgdef_numfields(m)) ||
  4487. (!submsgs && submsg_count)) {
  4488. /* OOM. */
  4489. upb_gfree(fields);
  4490. upb_gfree(submsgs);
  4491. return false;
  4492. }
  4493. l->field_count = upb_msgdef_numfields(m);
  4494. l->fields = fields;
  4495. l->submsgs = submsgs;
  4496. /* Allocate data offsets in three stages:
  4497. *
  4498. * 1. hasbits.
  4499. * 2. regular fields.
  4500. * 3. oneof fields.
  4501. *
  4502. * OPT: There is a lot of room for optimization here to minimize the size.
  4503. */
  4504. /* Allocate hasbits and set basic field attributes. */
  4505. submsg_count = 0;
  4506. for (upb_msg_field_begin(&it, m), hasbit = 0;
  4507. !upb_msg_field_done(&it);
  4508. upb_msg_field_next(&it)) {
  4509. const upb_fielddef* f = upb_msg_iter_field(&it);
  4510. upb_msglayout_field *field = &fields[upb_fielddef_index(f)];
  4511. field->number = upb_fielddef_number(f);
  4512. field->descriptortype = upb_fielddef_descriptortype(f);
  4513. field->label = upb_fielddef_label(f);
  4514. if (upb_fielddef_issubmsg(f)) {
  4515. const upb_msglayout *sub_layout =
  4516. upb_msgfactory_getlayout(factory, upb_fielddef_msgsubdef(f));
  4517. field->submsg_index = submsg_count++;
  4518. submsgs[field->submsg_index] = sub_layout;
  4519. }
  4520. if (upb_fielddef_haspresence(f) && !upb_fielddef_containingoneof(f)) {
  4521. field->presence = (hasbit++);
  4522. } else {
  4523. field->presence = 0;
  4524. }
  4525. }
  4526. /* Account for space used by hasbits. */
  4527. l->size = div_round_up(hasbit, 8);
  4528. /* Allocate non-oneof fields. */
  4529. for (upb_msg_field_begin(&it, m); !upb_msg_field_done(&it);
  4530. upb_msg_field_next(&it)) {
  4531. const upb_fielddef* f = upb_msg_iter_field(&it);
  4532. size_t field_size = upb_msg_fielddefsize(f);
  4533. size_t index = upb_fielddef_index(f);
  4534. if (upb_fielddef_containingoneof(f)) {
  4535. /* Oneofs are handled separately below. */
  4536. continue;
  4537. }
  4538. fields[index].offset = upb_msglayout_place(l, field_size);
  4539. }
  4540. /* Allocate oneof fields. Each oneof field consists of a uint32 for the case
  4541. * and space for the actual data. */
  4542. for (upb_msg_oneof_begin(&oit, m); !upb_msg_oneof_done(&oit);
  4543. upb_msg_oneof_next(&oit)) {
  4544. const upb_oneofdef* o = upb_msg_iter_oneof(&oit);
  4545. upb_oneof_iter fit;
  4546. size_t case_size = sizeof(uint32_t); /* Could potentially optimize this. */
  4547. size_t field_size = 0;
  4548. uint32_t case_offset;
  4549. uint32_t data_offset;
  4550. /* Calculate field size: the max of all field sizes. */
  4551. for (upb_oneof_begin(&fit, o);
  4552. !upb_oneof_done(&fit);
  4553. upb_oneof_next(&fit)) {
  4554. const upb_fielddef* f = upb_oneof_iter_field(&fit);
  4555. field_size = UPB_MAX(field_size, upb_msg_fielddefsize(f));
  4556. }
  4557. /* Align and allocate case offset. */
  4558. case_offset = upb_msglayout_place(l, case_size);
  4559. data_offset = upb_msglayout_place(l, field_size);
  4560. for (upb_oneof_begin(&fit, o);
  4561. !upb_oneof_done(&fit);
  4562. upb_oneof_next(&fit)) {
  4563. const upb_fielddef* f = upb_oneof_iter_field(&fit);
  4564. fields[upb_fielddef_index(f)].offset = data_offset;
  4565. fields[upb_fielddef_index(f)].presence = ~case_offset;
  4566. }
  4567. }
  4568. /* Size of the entire structure should be a multiple of its greatest
  4569. * alignment. TODO: track overall alignment for real? */
  4570. l->size = align_up(l->size, 8);
  4571. return true;
  4572. }
  4573. /** upb_msgfactory ************************************************************/
  4574. struct upb_msgfactory {
  4575. const upb_symtab *symtab; /* We own a ref. */
  4576. upb_inttable layouts;
  4577. upb_inttable mergehandlers;
  4578. };
  4579. upb_msgfactory *upb_msgfactory_new(const upb_symtab *symtab) {
  4580. upb_msgfactory *ret = upb_gmalloc(sizeof(*ret));
  4581. ret->symtab = symtab;
  4582. upb_inttable_init(&ret->layouts, UPB_CTYPE_PTR);
  4583. upb_inttable_init(&ret->mergehandlers, UPB_CTYPE_CONSTPTR);
  4584. return ret;
  4585. }
  4586. void upb_msgfactory_free(upb_msgfactory *f) {
  4587. upb_inttable_iter i;
  4588. upb_inttable_begin(&i, &f->layouts);
  4589. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  4590. upb_msglayout *l = upb_value_getptr(upb_inttable_iter_value(&i));
  4591. upb_msglayout_free(l);
  4592. }
  4593. upb_inttable_begin(&i, &f->mergehandlers);
  4594. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  4595. const upb_handlers *h = upb_value_getconstptr(upb_inttable_iter_value(&i));
  4596. upb_handlers_unref(h, f);
  4597. }
  4598. upb_inttable_uninit(&f->layouts);
  4599. upb_inttable_uninit(&f->mergehandlers);
  4600. upb_gfree(f);
  4601. }
  4602. const upb_symtab *upb_msgfactory_symtab(const upb_msgfactory *f) {
  4603. return f->symtab;
  4604. }
  4605. const upb_msglayout *upb_msgfactory_getlayout(upb_msgfactory *f,
  4606. const upb_msgdef *m) {
  4607. upb_value v;
  4608. UPB_ASSERT(upb_symtab_lookupmsg(f->symtab, upb_msgdef_fullname(m)) == m);
  4609. UPB_ASSERT(!upb_msgdef_mapentry(m));
  4610. if (upb_inttable_lookupptr(&f->layouts, m, &v)) {
  4611. UPB_ASSERT(upb_value_getptr(v));
  4612. return upb_value_getptr(v);
  4613. } else {
  4614. /* In case of circular dependency, layout has to be inserted first. */
  4615. upb_msglayout *l = upb_gmalloc(sizeof(*l));
  4616. upb_msgfactory *mutable_f = (void*)f;
  4617. upb_inttable_insertptr(&mutable_f->layouts, m, upb_value_ptr(l));
  4618. UPB_ASSERT(l);
  4619. if (!upb_msglayout_init(m, l, f)) {
  4620. upb_msglayout_free(l);
  4621. }
  4622. return l;
  4623. }
  4624. }
  4625. #if UINTPTR_MAX == 0xffffffff
  4626. #define UPB_SIZE(size32, size64) size32
  4627. #else
  4628. #define UPB_SIZE(size32, size64) size64
  4629. #endif
  4630. #define UPB_FIELD_AT(msg, fieldtype, offset) \
  4631. *(fieldtype*)((const char*)(msg) + offset)
  4632. #define UPB_READ_ONEOF(msg, fieldtype, offset, case_offset, case_val, default) \
  4633. UPB_FIELD_AT(msg, int, case_offset) == case_val \
  4634. ? UPB_FIELD_AT(msg, fieldtype, offset) \
  4635. : default
  4636. #define UPB_WRITE_ONEOF(msg, fieldtype, offset, value, case_offset, case_val) \
  4637. UPB_FIELD_AT(msg, int, case_offset) = case_val; \
  4638. UPB_FIELD_AT(msg, fieldtype, offset) = value;
  4639. #undef UPB_SIZE
  4640. #undef UPB_FIELD_AT
  4641. #undef UPB_READ_ONEOF
  4642. #undef UPB_WRITE_ONEOF
  4643. /*
  4644. ** upb::RefCounted Implementation
  4645. **
  4646. ** Our key invariants are:
  4647. ** 1. reference cycles never span groups
  4648. ** 2. for ref2(to, from), we increment to's count iff group(from) != group(to)
  4649. **
  4650. ** The previous two are how we avoid leaking cycles. Other important
  4651. ** invariants are:
  4652. ** 3. for mutable objects "from" and "to", if there exists a ref2(to, from)
  4653. ** this implies group(from) == group(to). (In practice, what we implement
  4654. ** is even stronger; "from" and "to" will share a group if there has *ever*
  4655. ** been a ref2(to, from), but all that is necessary for correctness is the
  4656. ** weaker one).
  4657. ** 4. mutable and immutable objects are never in the same group.
  4658. */
  4659. #include <setjmp.h>
  4660. static void freeobj(upb_refcounted *o);
  4661. const char untracked_val;
  4662. const void *UPB_UNTRACKED_REF = &untracked_val;
  4663. /* arch-specific atomic primitives *******************************************/
  4664. #ifdef UPB_THREAD_UNSAFE /*---------------------------------------------------*/
  4665. static void atomic_inc(uint32_t *a) { (*a)++; }
  4666. static bool atomic_dec(uint32_t *a) { return --(*a) == 0; }
  4667. #elif defined(__GNUC__) || defined(__clang__) /*------------------------------*/
  4668. static void atomic_inc(uint32_t *a) { __sync_fetch_and_add(a, 1); }
  4669. static bool atomic_dec(uint32_t *a) { return __sync_sub_and_fetch(a, 1) == 0; }
  4670. #elif defined(WIN32) /*-------------------------------------------------------*/
  4671. #include <Windows.h>
  4672. static void atomic_inc(upb_atomic_t *a) { InterlockedIncrement(&a->val); }
  4673. static bool atomic_dec(upb_atomic_t *a) {
  4674. return InterlockedDecrement(&a->val) == 0;
  4675. }
  4676. #else
  4677. #error Atomic primitives not defined for your platform/CPU. \
  4678. Implement them or compile with UPB_THREAD_UNSAFE.
  4679. #endif
  4680. /* All static objects point to this refcount.
  4681. * It is special-cased in ref/unref below. */
  4682. uint32_t static_refcount = -1;
  4683. /* We can avoid atomic ops for statically-declared objects.
  4684. * This is a minor optimization but nice since we can avoid degrading under
  4685. * contention in this case. */
  4686. static void refgroup(uint32_t *group) {
  4687. if (group != &static_refcount)
  4688. atomic_inc(group);
  4689. }
  4690. static bool unrefgroup(uint32_t *group) {
  4691. if (group == &static_refcount) {
  4692. return false;
  4693. } else {
  4694. return atomic_dec(group);
  4695. }
  4696. }
  4697. /* Reference tracking (debug only) ********************************************/
  4698. #ifdef UPB_DEBUG_REFS
  4699. #ifdef UPB_THREAD_UNSAFE
  4700. static void upb_lock() {}
  4701. static void upb_unlock() {}
  4702. #else
  4703. /* User must define functions that lock/unlock a global mutex and link this
  4704. * file against them. */
  4705. void upb_lock();
  4706. void upb_unlock();
  4707. #endif
  4708. /* UPB_DEBUG_REFS mode counts on being able to malloc() memory in some
  4709. * code-paths that can normally never fail, like upb_refcounted_ref(). Since
  4710. * we have no way to propagage out-of-memory errors back to the user, and since
  4711. * these errors can only occur in UPB_DEBUG_REFS mode, we use an allocator that
  4712. * immediately aborts on failure (avoiding the global allocator, which might
  4713. * inject failures). */
  4714. #include <stdlib.h>
  4715. static void *upb_debugrefs_allocfunc(upb_alloc *alloc, void *ptr,
  4716. size_t oldsize, size_t size) {
  4717. UPB_UNUSED(alloc);
  4718. UPB_UNUSED(oldsize);
  4719. if (size == 0) {
  4720. free(ptr);
  4721. return NULL;
  4722. } else {
  4723. void *ret = realloc(ptr, size);
  4724. if (!ret) {
  4725. abort();
  4726. }
  4727. return ret;
  4728. }
  4729. }
  4730. upb_alloc upb_alloc_debugrefs = {&upb_debugrefs_allocfunc};
  4731. typedef struct {
  4732. int count; /* How many refs there are (duplicates only allowed for ref2). */
  4733. bool is_ref2;
  4734. } trackedref;
  4735. static trackedref *trackedref_new(bool is_ref2) {
  4736. trackedref *ret = upb_malloc(&upb_alloc_debugrefs, sizeof(*ret));
  4737. ret->count = 1;
  4738. ret->is_ref2 = is_ref2;
  4739. return ret;
  4740. }
  4741. static void track(const upb_refcounted *r, const void *owner, bool ref2) {
  4742. upb_value v;
  4743. UPB_ASSERT(owner);
  4744. if (owner == UPB_UNTRACKED_REF) return;
  4745. upb_lock();
  4746. if (upb_inttable_lookupptr(r->refs, owner, &v)) {
  4747. trackedref *ref = upb_value_getptr(v);
  4748. /* Since we allow multiple ref2's for the same to/from pair without
  4749. * allocating separate memory for each one, we lose the fine-grained
  4750. * tracking behavior we get with regular refs. Since ref2s only happen
  4751. * inside upb, we'll accept this limitation until/unless there is a really
  4752. * difficult upb-internal bug that can't be figured out without it. */
  4753. UPB_ASSERT(ref2);
  4754. UPB_ASSERT(ref->is_ref2);
  4755. ref->count++;
  4756. } else {
  4757. trackedref *ref = trackedref_new(ref2);
  4758. upb_inttable_insertptr2(r->refs, owner, upb_value_ptr(ref),
  4759. &upb_alloc_debugrefs);
  4760. if (ref2) {
  4761. /* We know this cast is safe when it is a ref2, because it's coming from
  4762. * another refcounted object. */
  4763. const upb_refcounted *from = owner;
  4764. UPB_ASSERT(!upb_inttable_lookupptr(from->ref2s, r, NULL));
  4765. upb_inttable_insertptr2(from->ref2s, r, upb_value_ptr(NULL),
  4766. &upb_alloc_debugrefs);
  4767. }
  4768. }
  4769. upb_unlock();
  4770. }
  4771. static void untrack(const upb_refcounted *r, const void *owner, bool ref2) {
  4772. upb_value v;
  4773. bool found;
  4774. trackedref *ref;
  4775. UPB_ASSERT(owner);
  4776. if (owner == UPB_UNTRACKED_REF) return;
  4777. upb_lock();
  4778. found = upb_inttable_lookupptr(r->refs, owner, &v);
  4779. /* This assert will fail if an owner attempts to release a ref it didn't have. */
  4780. UPB_ASSERT(found);
  4781. ref = upb_value_getptr(v);
  4782. UPB_ASSERT(ref->is_ref2 == ref2);
  4783. if (--ref->count == 0) {
  4784. free(ref);
  4785. upb_inttable_removeptr(r->refs, owner, NULL);
  4786. if (ref2) {
  4787. /* We know this cast is safe when it is a ref2, because it's coming from
  4788. * another refcounted object. */
  4789. const upb_refcounted *from = owner;
  4790. bool removed = upb_inttable_removeptr(from->ref2s, r, NULL);
  4791. UPB_ASSERT(removed);
  4792. }
  4793. }
  4794. upb_unlock();
  4795. }
  4796. static void checkref(const upb_refcounted *r, const void *owner, bool ref2) {
  4797. upb_value v;
  4798. bool found;
  4799. trackedref *ref;
  4800. upb_lock();
  4801. found = upb_inttable_lookupptr(r->refs, owner, &v);
  4802. UPB_ASSERT(found);
  4803. ref = upb_value_getptr(v);
  4804. UPB_ASSERT(ref->is_ref2 == ref2);
  4805. upb_unlock();
  4806. }
  4807. /* Populates the given UPB_CTYPE_INT32 inttable with counts of ref2's that
  4808. * originate from the given owner. */
  4809. static void getref2s(const upb_refcounted *owner, upb_inttable *tab) {
  4810. upb_inttable_iter i;
  4811. upb_lock();
  4812. upb_inttable_begin(&i, owner->ref2s);
  4813. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  4814. upb_value v;
  4815. upb_value count;
  4816. trackedref *ref;
  4817. bool found;
  4818. upb_refcounted *to = (upb_refcounted*)upb_inttable_iter_key(&i);
  4819. /* To get the count we need to look in the target's table. */
  4820. found = upb_inttable_lookupptr(to->refs, owner, &v);
  4821. UPB_ASSERT(found);
  4822. ref = upb_value_getptr(v);
  4823. count = upb_value_int32(ref->count);
  4824. upb_inttable_insertptr2(tab, to, count, &upb_alloc_debugrefs);
  4825. }
  4826. upb_unlock();
  4827. }
  4828. typedef struct {
  4829. upb_inttable ref2;
  4830. const upb_refcounted *obj;
  4831. } check_state;
  4832. static void visit_check(const upb_refcounted *obj, const upb_refcounted *subobj,
  4833. void *closure) {
  4834. check_state *s = closure;
  4835. upb_inttable *ref2 = &s->ref2;
  4836. upb_value v;
  4837. bool removed;
  4838. int32_t newcount;
  4839. UPB_ASSERT(obj == s->obj);
  4840. UPB_ASSERT(subobj);
  4841. removed = upb_inttable_removeptr(ref2, subobj, &v);
  4842. /* The following assertion will fail if the visit() function visits a subobj
  4843. * that it did not have a ref2 on, or visits the same subobj too many times. */
  4844. UPB_ASSERT(removed);
  4845. newcount = upb_value_getint32(v) - 1;
  4846. if (newcount > 0) {
  4847. upb_inttable_insert2(ref2, (uintptr_t)subobj, upb_value_int32(newcount),
  4848. &upb_alloc_debugrefs);
  4849. }
  4850. }
  4851. static void visit(const upb_refcounted *r, upb_refcounted_visit *v,
  4852. void *closure) {
  4853. /* In DEBUG_REFS mode we know what existing ref2 refs there are, so we know
  4854. * exactly the set of nodes that visit() should visit. So we verify visit()'s
  4855. * correctness here. */
  4856. check_state state;
  4857. state.obj = r;
  4858. upb_inttable_init2(&state.ref2, UPB_CTYPE_INT32, &upb_alloc_debugrefs);
  4859. getref2s(r, &state.ref2);
  4860. /* This should visit any children in the ref2 table. */
  4861. if (r->vtbl->visit) r->vtbl->visit(r, visit_check, &state);
  4862. /* This assertion will fail if the visit() function missed any children. */
  4863. UPB_ASSERT(upb_inttable_count(&state.ref2) == 0);
  4864. upb_inttable_uninit2(&state.ref2, &upb_alloc_debugrefs);
  4865. if (r->vtbl->visit) r->vtbl->visit(r, v, closure);
  4866. }
  4867. static void trackinit(upb_refcounted *r) {
  4868. r->refs = upb_malloc(&upb_alloc_debugrefs, sizeof(*r->refs));
  4869. r->ref2s = upb_malloc(&upb_alloc_debugrefs, sizeof(*r->ref2s));
  4870. upb_inttable_init2(r->refs, UPB_CTYPE_PTR, &upb_alloc_debugrefs);
  4871. upb_inttable_init2(r->ref2s, UPB_CTYPE_PTR, &upb_alloc_debugrefs);
  4872. }
  4873. static void trackfree(const upb_refcounted *r) {
  4874. upb_inttable_uninit2(r->refs, &upb_alloc_debugrefs);
  4875. upb_inttable_uninit2(r->ref2s, &upb_alloc_debugrefs);
  4876. upb_free(&upb_alloc_debugrefs, r->refs);
  4877. upb_free(&upb_alloc_debugrefs, r->ref2s);
  4878. }
  4879. #else
  4880. static void track(const upb_refcounted *r, const void *owner, bool ref2) {
  4881. UPB_UNUSED(r);
  4882. UPB_UNUSED(owner);
  4883. UPB_UNUSED(ref2);
  4884. }
  4885. static void untrack(const upb_refcounted *r, const void *owner, bool ref2) {
  4886. UPB_UNUSED(r);
  4887. UPB_UNUSED(owner);
  4888. UPB_UNUSED(ref2);
  4889. }
  4890. static void checkref(const upb_refcounted *r, const void *owner, bool ref2) {
  4891. UPB_UNUSED(r);
  4892. UPB_UNUSED(owner);
  4893. UPB_UNUSED(ref2);
  4894. }
  4895. static void trackinit(upb_refcounted *r) {
  4896. UPB_UNUSED(r);
  4897. }
  4898. static void trackfree(const upb_refcounted *r) {
  4899. UPB_UNUSED(r);
  4900. }
  4901. static void visit(const upb_refcounted *r, upb_refcounted_visit *v,
  4902. void *closure) {
  4903. if (r->vtbl->visit) r->vtbl->visit(r, v, closure);
  4904. }
  4905. #endif /* UPB_DEBUG_REFS */
  4906. /* freeze() *******************************************************************/
  4907. /* The freeze() operation is by far the most complicated part of this scheme.
  4908. * We compute strongly-connected components and then mutate the graph such that
  4909. * we preserve the invariants documented at the top of this file. And we must
  4910. * handle out-of-memory errors gracefully (without leaving the graph
  4911. * inconsistent), which adds to the fun. */
  4912. /* The state used by the freeze operation (shared across many functions). */
  4913. typedef struct {
  4914. int depth;
  4915. int maxdepth;
  4916. uint64_t index;
  4917. /* Maps upb_refcounted* -> attributes (color, etc). attr layout varies by
  4918. * color. */
  4919. upb_inttable objattr;
  4920. upb_inttable stack; /* stack of upb_refcounted* for Tarjan's algorithm. */
  4921. upb_inttable groups; /* array of uint32_t*, malloc'd refcounts for new groups */
  4922. upb_status *status;
  4923. jmp_buf err;
  4924. } tarjan;
  4925. static void release_ref2(const upb_refcounted *obj,
  4926. const upb_refcounted *subobj,
  4927. void *closure);
  4928. /* Node attributes -----------------------------------------------------------*/
  4929. /* After our analysis phase all nodes will be either GRAY or WHITE. */
  4930. typedef enum {
  4931. BLACK = 0, /* Object has not been seen. */
  4932. GRAY, /* Object has been found via a refgroup but may not be reachable. */
  4933. GREEN, /* Object is reachable and is currently on the Tarjan stack. */
  4934. WHITE /* Object is reachable and has been assigned a group (SCC). */
  4935. } color_t;
  4936. UPB_NORETURN static void err(tarjan *t) { longjmp(t->err, 1); }
  4937. UPB_NORETURN static void oom(tarjan *t) {
  4938. upb_status_seterrmsg(t->status, "out of memory");
  4939. err(t);
  4940. }
  4941. static uint64_t trygetattr(const tarjan *t, const upb_refcounted *r) {
  4942. upb_value v;
  4943. return upb_inttable_lookupptr(&t->objattr, r, &v) ?
  4944. upb_value_getuint64(v) : 0;
  4945. }
  4946. static uint64_t getattr(const tarjan *t, const upb_refcounted *r) {
  4947. upb_value v;
  4948. bool found = upb_inttable_lookupptr(&t->objattr, r, &v);
  4949. UPB_ASSERT(found);
  4950. return upb_value_getuint64(v);
  4951. }
  4952. static void setattr(tarjan *t, const upb_refcounted *r, uint64_t attr) {
  4953. upb_inttable_removeptr(&t->objattr, r, NULL);
  4954. upb_inttable_insertptr(&t->objattr, r, upb_value_uint64(attr));
  4955. }
  4956. static color_t color(tarjan *t, const upb_refcounted *r) {
  4957. return trygetattr(t, r) & 0x3; /* Color is always stored in the low 2 bits. */
  4958. }
  4959. static void set_gray(tarjan *t, const upb_refcounted *r) {
  4960. UPB_ASSERT(color(t, r) == BLACK);
  4961. setattr(t, r, GRAY);
  4962. }
  4963. /* Pushes an obj onto the Tarjan stack and sets it to GREEN. */
  4964. static void push(tarjan *t, const upb_refcounted *r) {
  4965. UPB_ASSERT(color(t, r) == BLACK || color(t, r) == GRAY);
  4966. /* This defines the attr layout for the GREEN state. "index" and "lowlink"
  4967. * get 31 bits, which is plenty (limit of 2B objects frozen at a time). */
  4968. setattr(t, r, GREEN | (t->index << 2) | (t->index << 33));
  4969. if (++t->index == 0x80000000) {
  4970. upb_status_seterrmsg(t->status, "too many objects to freeze");
  4971. err(t);
  4972. }
  4973. upb_inttable_push(&t->stack, upb_value_ptr((void*)r));
  4974. }
  4975. /* Pops an obj from the Tarjan stack and sets it to WHITE, with a ptr to its
  4976. * SCC group. */
  4977. static upb_refcounted *pop(tarjan *t) {
  4978. upb_refcounted *r = upb_value_getptr(upb_inttable_pop(&t->stack));
  4979. UPB_ASSERT(color(t, r) == GREEN);
  4980. /* This defines the attr layout for nodes in the WHITE state.
  4981. * Top of group stack is [group, NULL]; we point at group. */
  4982. setattr(t, r, WHITE | (upb_inttable_count(&t->groups) - 2) << 8);
  4983. return r;
  4984. }
  4985. static void tarjan_newgroup(tarjan *t) {
  4986. uint32_t *group = upb_gmalloc(sizeof(*group));
  4987. if (!group) oom(t);
  4988. /* Push group and empty group leader (we'll fill in leader later). */
  4989. if (!upb_inttable_push(&t->groups, upb_value_ptr(group)) ||
  4990. !upb_inttable_push(&t->groups, upb_value_ptr(NULL))) {
  4991. upb_gfree(group);
  4992. oom(t);
  4993. }
  4994. *group = 0;
  4995. }
  4996. static uint32_t idx(tarjan *t, const upb_refcounted *r) {
  4997. UPB_ASSERT(color(t, r) == GREEN);
  4998. return (getattr(t, r) >> 2) & 0x7FFFFFFF;
  4999. }
  5000. static uint32_t lowlink(tarjan *t, const upb_refcounted *r) {
  5001. if (color(t, r) == GREEN) {
  5002. return getattr(t, r) >> 33;
  5003. } else {
  5004. return UINT32_MAX;
  5005. }
  5006. }
  5007. static void set_lowlink(tarjan *t, const upb_refcounted *r, uint32_t lowlink) {
  5008. UPB_ASSERT(color(t, r) == GREEN);
  5009. setattr(t, r, ((uint64_t)lowlink << 33) | (getattr(t, r) & 0x1FFFFFFFF));
  5010. }
  5011. static uint32_t *group(tarjan *t, upb_refcounted *r) {
  5012. uint64_t groupnum;
  5013. upb_value v;
  5014. bool found;
  5015. UPB_ASSERT(color(t, r) == WHITE);
  5016. groupnum = getattr(t, r) >> 8;
  5017. found = upb_inttable_lookup(&t->groups, groupnum, &v);
  5018. UPB_ASSERT(found);
  5019. return upb_value_getptr(v);
  5020. }
  5021. /* If the group leader for this object's group has not previously been set,
  5022. * the given object is assigned to be its leader. */
  5023. static upb_refcounted *groupleader(tarjan *t, upb_refcounted *r) {
  5024. uint64_t leader_slot;
  5025. upb_value v;
  5026. bool found;
  5027. UPB_ASSERT(color(t, r) == WHITE);
  5028. leader_slot = (getattr(t, r) >> 8) + 1;
  5029. found = upb_inttable_lookup(&t->groups, leader_slot, &v);
  5030. UPB_ASSERT(found);
  5031. if (upb_value_getptr(v)) {
  5032. return upb_value_getptr(v);
  5033. } else {
  5034. upb_inttable_remove(&t->groups, leader_slot, NULL);
  5035. upb_inttable_insert(&t->groups, leader_slot, upb_value_ptr(r));
  5036. return r;
  5037. }
  5038. }
  5039. /* Tarjan's algorithm --------------------------------------------------------*/
  5040. /* See:
  5041. * http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm */
  5042. static void do_tarjan(const upb_refcounted *obj, tarjan *t);
  5043. static void tarjan_visit(const upb_refcounted *obj,
  5044. const upb_refcounted *subobj,
  5045. void *closure) {
  5046. tarjan *t = closure;
  5047. if (++t->depth > t->maxdepth) {
  5048. upb_status_seterrf(t->status, "graph too deep to freeze (%d)", t->maxdepth);
  5049. err(t);
  5050. } else if (subobj->is_frozen || color(t, subobj) == WHITE) {
  5051. /* Do nothing: we don't want to visit or color already-frozen nodes,
  5052. * and WHITE nodes have already been assigned a SCC. */
  5053. } else if (color(t, subobj) < GREEN) {
  5054. /* Subdef has not yet been visited; recurse on it. */
  5055. do_tarjan(subobj, t);
  5056. set_lowlink(t, obj, UPB_MIN(lowlink(t, obj), lowlink(t, subobj)));
  5057. } else if (color(t, subobj) == GREEN) {
  5058. /* Subdef is in the stack and hence in the current SCC. */
  5059. set_lowlink(t, obj, UPB_MIN(lowlink(t, obj), idx(t, subobj)));
  5060. }
  5061. --t->depth;
  5062. }
  5063. static void do_tarjan(const upb_refcounted *obj, tarjan *t) {
  5064. if (color(t, obj) == BLACK) {
  5065. /* We haven't seen this object's group; mark the whole group GRAY. */
  5066. const upb_refcounted *o = obj;
  5067. do { set_gray(t, o); } while ((o = o->next) != obj);
  5068. }
  5069. push(t, obj);
  5070. visit(obj, tarjan_visit, t);
  5071. if (lowlink(t, obj) == idx(t, obj)) {
  5072. tarjan_newgroup(t);
  5073. while (pop(t) != obj)
  5074. ;
  5075. }
  5076. }
  5077. /* freeze() ------------------------------------------------------------------*/
  5078. static void crossref(const upb_refcounted *r, const upb_refcounted *subobj,
  5079. void *_t) {
  5080. tarjan *t = _t;
  5081. UPB_ASSERT(color(t, r) > BLACK);
  5082. if (color(t, subobj) > BLACK && r->group != subobj->group) {
  5083. /* Previously this ref was not reflected in subobj->group because they
  5084. * were in the same group; now that they are split a ref must be taken. */
  5085. refgroup(subobj->group);
  5086. }
  5087. }
  5088. static bool freeze(upb_refcounted *const*roots, int n, upb_status *s,
  5089. int maxdepth) {
  5090. volatile bool ret = false;
  5091. int i;
  5092. upb_inttable_iter iter;
  5093. /* We run in two passes so that we can allocate all memory before performing
  5094. * any mutation of the input -- this allows us to leave the input unchanged
  5095. * in the case of memory allocation failure. */
  5096. tarjan t;
  5097. t.index = 0;
  5098. t.depth = 0;
  5099. t.maxdepth = maxdepth;
  5100. t.status = s;
  5101. if (!upb_inttable_init(&t.objattr, UPB_CTYPE_UINT64)) goto err1;
  5102. if (!upb_inttable_init(&t.stack, UPB_CTYPE_PTR)) goto err2;
  5103. if (!upb_inttable_init(&t.groups, UPB_CTYPE_PTR)) goto err3;
  5104. if (setjmp(t.err) != 0) goto err4;
  5105. for (i = 0; i < n; i++) {
  5106. if (color(&t, roots[i]) < GREEN) {
  5107. do_tarjan(roots[i], &t);
  5108. }
  5109. }
  5110. /* If we've made it this far, no further errors are possible so it's safe to
  5111. * mutate the objects without risk of leaving them in an inconsistent state. */
  5112. ret = true;
  5113. /* The transformation that follows requires care. The preconditions are:
  5114. * - all objects in attr map are WHITE or GRAY, and are in mutable groups
  5115. * (groups of all mutable objs)
  5116. * - no ref2(to, from) refs have incremented count(to) if both "to" and
  5117. * "from" are in our attr map (this follows from invariants (2) and (3)) */
  5118. /* Pass 1: we remove WHITE objects from their mutable groups, and add them to
  5119. * new groups according to the SCC's we computed. These new groups will
  5120. * consist of only frozen objects. None will be immediately collectible,
  5121. * because WHITE objects are by definition reachable from one of "roots",
  5122. * which the caller must own refs on. */
  5123. upb_inttable_begin(&iter, &t.objattr);
  5124. for(; !upb_inttable_done(&iter); upb_inttable_next(&iter)) {
  5125. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&iter);
  5126. /* Since removal from a singly-linked list requires access to the object's
  5127. * predecessor, we consider obj->next instead of obj for moving. With the
  5128. * while() loop we guarantee that we will visit every node's predecessor.
  5129. * Proof:
  5130. * 1. every node's predecessor is in our attr map.
  5131. * 2. though the loop body may change a node's predecessor, it will only
  5132. * change it to be the node we are currently operating on, so with a
  5133. * while() loop we guarantee ourselves the chance to remove each node. */
  5134. while (color(&t, obj->next) == WHITE &&
  5135. group(&t, obj->next) != obj->next->group) {
  5136. upb_refcounted *leader;
  5137. /* Remove from old group. */
  5138. upb_refcounted *move = obj->next;
  5139. if (obj == move) {
  5140. /* Removing the last object from a group. */
  5141. UPB_ASSERT(*obj->group == obj->individual_count);
  5142. upb_gfree(obj->group);
  5143. } else {
  5144. obj->next = move->next;
  5145. /* This may decrease to zero; we'll collect GRAY objects (if any) that
  5146. * remain in the group in the third pass. */
  5147. UPB_ASSERT(*move->group >= move->individual_count);
  5148. *move->group -= move->individual_count;
  5149. }
  5150. /* Add to new group. */
  5151. leader = groupleader(&t, move);
  5152. if (move == leader) {
  5153. /* First object added to new group is its leader. */
  5154. move->group = group(&t, move);
  5155. move->next = move;
  5156. *move->group = move->individual_count;
  5157. } else {
  5158. /* Group already has at least one object in it. */
  5159. UPB_ASSERT(leader->group == group(&t, move));
  5160. move->group = group(&t, move);
  5161. move->next = leader->next;
  5162. leader->next = move;
  5163. *move->group += move->individual_count;
  5164. }
  5165. move->is_frozen = true;
  5166. }
  5167. }
  5168. /* Pass 2: GRAY and WHITE objects "obj" with ref2(to, obj) references must
  5169. * increment count(to) if group(obj) != group(to) (which could now be the
  5170. * case if "to" was just frozen). */
  5171. upb_inttable_begin(&iter, &t.objattr);
  5172. for(; !upb_inttable_done(&iter); upb_inttable_next(&iter)) {
  5173. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&iter);
  5174. visit(obj, crossref, &t);
  5175. }
  5176. /* Pass 3: GRAY objects are collected if their group's refcount dropped to
  5177. * zero when we removed its white nodes. This can happen if they had only
  5178. * been kept alive by virtue of sharing a group with an object that was just
  5179. * frozen.
  5180. *
  5181. * It is important that we do this last, since the GRAY object's free()
  5182. * function could call unref2() on just-frozen objects, which will decrement
  5183. * refs that were added in pass 2. */
  5184. upb_inttable_begin(&iter, &t.objattr);
  5185. for(; !upb_inttable_done(&iter); upb_inttable_next(&iter)) {
  5186. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&iter);
  5187. if (obj->group == NULL || *obj->group == 0) {
  5188. if (obj->group) {
  5189. upb_refcounted *o;
  5190. /* We eagerly free() the group's count (since we can't easily determine
  5191. * the group's remaining size it's the easiest way to ensure it gets
  5192. * done). */
  5193. upb_gfree(obj->group);
  5194. /* Visit to release ref2's (done in a separate pass since release_ref2
  5195. * depends on o->group being unmodified so it can test merged()). */
  5196. o = obj;
  5197. do { visit(o, release_ref2, NULL); } while ((o = o->next) != obj);
  5198. /* Mark "group" fields as NULL so we know to free the objects later in
  5199. * this loop, but also don't try to delete the group twice. */
  5200. o = obj;
  5201. do { o->group = NULL; } while ((o = o->next) != obj);
  5202. }
  5203. freeobj(obj);
  5204. }
  5205. }
  5206. err4:
  5207. if (!ret) {
  5208. upb_inttable_begin(&iter, &t.groups);
  5209. for(; !upb_inttable_done(&iter); upb_inttable_next(&iter))
  5210. upb_gfree(upb_value_getptr(upb_inttable_iter_value(&iter)));
  5211. }
  5212. upb_inttable_uninit(&t.groups);
  5213. err3:
  5214. upb_inttable_uninit(&t.stack);
  5215. err2:
  5216. upb_inttable_uninit(&t.objattr);
  5217. err1:
  5218. return ret;
  5219. }
  5220. /* Misc internal functions ***************************************************/
  5221. static bool merged(const upb_refcounted *r, const upb_refcounted *r2) {
  5222. return r->group == r2->group;
  5223. }
  5224. static void merge(upb_refcounted *r, upb_refcounted *from) {
  5225. upb_refcounted *base;
  5226. upb_refcounted *tmp;
  5227. if (merged(r, from)) return;
  5228. *r->group += *from->group;
  5229. upb_gfree(from->group);
  5230. base = from;
  5231. /* Set all refcount pointers in the "from" chain to the merged refcount.
  5232. *
  5233. * TODO(haberman): this linear algorithm can result in an overall O(n^2) bound
  5234. * if the user continuously extends a group by one object. Prevent this by
  5235. * using one of the techniques in this paper:
  5236. * http://bioinfo.ict.ac.cn/~dbu/AlgorithmCourses/Lectures/Union-Find-Tarjan.pdf */
  5237. do { from->group = r->group; } while ((from = from->next) != base);
  5238. /* Merge the two circularly linked lists by swapping their next pointers. */
  5239. tmp = r->next;
  5240. r->next = base->next;
  5241. base->next = tmp;
  5242. }
  5243. static void unref(const upb_refcounted *r);
  5244. static void release_ref2(const upb_refcounted *obj,
  5245. const upb_refcounted *subobj,
  5246. void *closure) {
  5247. UPB_UNUSED(closure);
  5248. untrack(subobj, obj, true);
  5249. if (!merged(obj, subobj)) {
  5250. UPB_ASSERT(subobj->is_frozen);
  5251. unref(subobj);
  5252. }
  5253. }
  5254. static void unref(const upb_refcounted *r) {
  5255. if (unrefgroup(r->group)) {
  5256. const upb_refcounted *o;
  5257. upb_gfree(r->group);
  5258. /* In two passes, since release_ref2 needs a guarantee that any subobjs
  5259. * are alive. */
  5260. o = r;
  5261. do { visit(o, release_ref2, NULL); } while((o = o->next) != r);
  5262. o = r;
  5263. do {
  5264. const upb_refcounted *next = o->next;
  5265. UPB_ASSERT(o->is_frozen || o->individual_count == 0);
  5266. freeobj((upb_refcounted*)o);
  5267. o = next;
  5268. } while(o != r);
  5269. }
  5270. }
  5271. static void freeobj(upb_refcounted *o) {
  5272. trackfree(o);
  5273. o->vtbl->free((upb_refcounted*)o);
  5274. }
  5275. /* Public interface ***********************************************************/
  5276. bool upb_refcounted_init(upb_refcounted *r,
  5277. const struct upb_refcounted_vtbl *vtbl,
  5278. const void *owner) {
  5279. #ifndef NDEBUG
  5280. /* Endianness check. This is unrelated to upb_refcounted, it's just a
  5281. * convenient place to put the check that we can be assured will run for
  5282. * basically every program using upb. */
  5283. const int x = 1;
  5284. #ifdef UPB_BIG_ENDIAN
  5285. UPB_ASSERT(*(char*)&x != 1);
  5286. #else
  5287. UPB_ASSERT(*(char*)&x == 1);
  5288. #endif
  5289. #endif
  5290. r->next = r;
  5291. r->vtbl = vtbl;
  5292. r->individual_count = 0;
  5293. r->is_frozen = false;
  5294. r->group = upb_gmalloc(sizeof(*r->group));
  5295. if (!r->group) return false;
  5296. *r->group = 0;
  5297. trackinit(r);
  5298. upb_refcounted_ref(r, owner);
  5299. return true;
  5300. }
  5301. bool upb_refcounted_isfrozen(const upb_refcounted *r) {
  5302. return r->is_frozen;
  5303. }
  5304. void upb_refcounted_ref(const upb_refcounted *r, const void *owner) {
  5305. track(r, owner, false);
  5306. if (!r->is_frozen)
  5307. ((upb_refcounted*)r)->individual_count++;
  5308. refgroup(r->group);
  5309. }
  5310. void upb_refcounted_unref(const upb_refcounted *r, const void *owner) {
  5311. untrack(r, owner, false);
  5312. if (!r->is_frozen)
  5313. ((upb_refcounted*)r)->individual_count--;
  5314. unref(r);
  5315. }
  5316. void upb_refcounted_ref2(const upb_refcounted *r, upb_refcounted *from) {
  5317. UPB_ASSERT(!from->is_frozen); /* Non-const pointer implies this. */
  5318. track(r, from, true);
  5319. if (r->is_frozen) {
  5320. refgroup(r->group);
  5321. } else {
  5322. merge((upb_refcounted*)r, from);
  5323. }
  5324. }
  5325. void upb_refcounted_unref2(const upb_refcounted *r, upb_refcounted *from) {
  5326. UPB_ASSERT(!from->is_frozen); /* Non-const pointer implies this. */
  5327. untrack(r, from, true);
  5328. if (r->is_frozen) {
  5329. unref(r);
  5330. } else {
  5331. UPB_ASSERT(merged(r, from));
  5332. }
  5333. }
  5334. void upb_refcounted_donateref(
  5335. const upb_refcounted *r, const void *from, const void *to) {
  5336. UPB_ASSERT(from != to);
  5337. if (to != NULL)
  5338. upb_refcounted_ref(r, to);
  5339. if (from != NULL)
  5340. upb_refcounted_unref(r, from);
  5341. }
  5342. void upb_refcounted_checkref(const upb_refcounted *r, const void *owner) {
  5343. checkref(r, owner, false);
  5344. }
  5345. bool upb_refcounted_freeze(upb_refcounted *const*roots, int n, upb_status *s,
  5346. int maxdepth) {
  5347. int i;
  5348. bool ret;
  5349. for (i = 0; i < n; i++) {
  5350. UPB_ASSERT(!roots[i]->is_frozen);
  5351. }
  5352. ret = freeze(roots, n, s, maxdepth);
  5353. UPB_ASSERT(!s || ret == upb_ok(s));
  5354. return ret;
  5355. }
  5356. bool upb_bufsrc_putbuf(const char *buf, size_t len, upb_bytessink *sink) {
  5357. void *subc;
  5358. bool ret;
  5359. upb_bufhandle handle;
  5360. upb_bufhandle_init(&handle);
  5361. upb_bufhandle_setbuf(&handle, buf, 0);
  5362. ret = upb_bytessink_start(sink, len, &subc);
  5363. if (ret && len != 0) {
  5364. ret = (upb_bytessink_putbuf(sink, subc, buf, len, &handle) >= len);
  5365. }
  5366. if (ret) {
  5367. ret = upb_bytessink_end(sink);
  5368. }
  5369. upb_bufhandle_uninit(&handle);
  5370. return ret;
  5371. }
  5372. struct upb_bufsink {
  5373. upb_byteshandler handler;
  5374. upb_bytessink sink;
  5375. upb_env *env;
  5376. char *ptr;
  5377. size_t len, size;
  5378. };
  5379. static void *upb_bufsink_start(void *_sink, const void *hd, size_t size_hint) {
  5380. upb_bufsink *sink = _sink;
  5381. UPB_UNUSED(hd);
  5382. UPB_UNUSED(size_hint);
  5383. sink->len = 0;
  5384. return sink;
  5385. }
  5386. static size_t upb_bufsink_string(void *_sink, const void *hd, const char *ptr,
  5387. size_t len, const upb_bufhandle *handle) {
  5388. upb_bufsink *sink = _sink;
  5389. size_t new_size = sink->size;
  5390. UPB_ASSERT(new_size > 0);
  5391. UPB_UNUSED(hd);
  5392. UPB_UNUSED(handle);
  5393. while (sink->len + len > new_size) {
  5394. new_size *= 2;
  5395. }
  5396. if (new_size != sink->size) {
  5397. sink->ptr = upb_env_realloc(sink->env, sink->ptr, sink->size, new_size);
  5398. sink->size = new_size;
  5399. }
  5400. memcpy(sink->ptr + sink->len, ptr, len);
  5401. sink->len += len;
  5402. return len;
  5403. }
  5404. upb_bufsink *upb_bufsink_new(upb_env *env) {
  5405. upb_bufsink *sink = upb_env_malloc(env, sizeof(upb_bufsink));
  5406. upb_byteshandler_init(&sink->handler);
  5407. upb_byteshandler_setstartstr(&sink->handler, upb_bufsink_start, NULL);
  5408. upb_byteshandler_setstring(&sink->handler, upb_bufsink_string, NULL);
  5409. upb_bytessink_reset(&sink->sink, &sink->handler, sink);
  5410. sink->env = env;
  5411. sink->size = 32;
  5412. sink->ptr = upb_env_malloc(env, sink->size);
  5413. sink->len = 0;
  5414. return sink;
  5415. }
  5416. void upb_bufsink_free(upb_bufsink *sink) {
  5417. upb_env_free(sink->env, sink->ptr);
  5418. upb_env_free(sink->env, sink);
  5419. }
  5420. upb_bytessink *upb_bufsink_sink(upb_bufsink *sink) {
  5421. return &sink->sink;
  5422. }
  5423. const char *upb_bufsink_getdata(const upb_bufsink *sink, size_t *len) {
  5424. *len = sink->len;
  5425. return sink->ptr;
  5426. }
  5427. /*
  5428. ** upb_table Implementation
  5429. **
  5430. ** Implementation is heavily inspired by Lua's ltable.c.
  5431. */
  5432. #include <string.h>
  5433. #define UPB_MAXARRSIZE 16 /* 64k. */
  5434. /* From Chromium. */
  5435. #define ARRAY_SIZE(x) \
  5436. ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x])))))
  5437. static void upb_check_alloc(upb_table *t, upb_alloc *a) {
  5438. UPB_UNUSED(t);
  5439. UPB_UNUSED(a);
  5440. UPB_ASSERT_DEBUGVAR(t->alloc == a);
  5441. }
  5442. static const double MAX_LOAD = 0.85;
  5443. /* The minimum utilization of the array part of a mixed hash/array table. This
  5444. * is a speed/memory-usage tradeoff (though it's not straightforward because of
  5445. * cache effects). The lower this is, the more memory we'll use. */
  5446. static const double MIN_DENSITY = 0.1;
  5447. bool is_pow2(uint64_t v) { return v == 0 || (v & (v - 1)) == 0; }
  5448. int log2ceil(uint64_t v) {
  5449. int ret = 0;
  5450. bool pow2 = is_pow2(v);
  5451. while (v >>= 1) ret++;
  5452. ret = pow2 ? ret : ret + 1; /* Ceiling. */
  5453. return UPB_MIN(UPB_MAXARRSIZE, ret);
  5454. }
  5455. char *upb_strdup(const char *s, upb_alloc *a) {
  5456. return upb_strdup2(s, strlen(s), a);
  5457. }
  5458. char *upb_strdup2(const char *s, size_t len, upb_alloc *a) {
  5459. size_t n;
  5460. char *p;
  5461. /* Prevent overflow errors. */
  5462. if (len == SIZE_MAX) return NULL;
  5463. /* Always null-terminate, even if binary data; but don't rely on the input to
  5464. * have a null-terminating byte since it may be a raw binary buffer. */
  5465. n = len + 1;
  5466. p = upb_malloc(a, n);
  5467. if (p) {
  5468. memcpy(p, s, len);
  5469. p[len] = 0;
  5470. }
  5471. return p;
  5472. }
  5473. /* A type to represent the lookup key of either a strtable or an inttable. */
  5474. typedef union {
  5475. uintptr_t num;
  5476. struct {
  5477. const char *str;
  5478. size_t len;
  5479. } str;
  5480. } lookupkey_t;
  5481. static lookupkey_t strkey2(const char *str, size_t len) {
  5482. lookupkey_t k;
  5483. k.str.str = str;
  5484. k.str.len = len;
  5485. return k;
  5486. }
  5487. static lookupkey_t intkey(uintptr_t key) {
  5488. lookupkey_t k;
  5489. k.num = key;
  5490. return k;
  5491. }
  5492. typedef uint32_t hashfunc_t(upb_tabkey key);
  5493. typedef bool eqlfunc_t(upb_tabkey k1, lookupkey_t k2);
  5494. /* Base table (shared code) ***************************************************/
  5495. /* For when we need to cast away const. */
  5496. static upb_tabent *mutable_entries(upb_table *t) {
  5497. return (upb_tabent*)t->entries;
  5498. }
  5499. static bool isfull(upb_table *t) {
  5500. if (upb_table_size(t) == 0) {
  5501. return true;
  5502. } else {
  5503. return ((double)(t->count + 1) / upb_table_size(t)) > MAX_LOAD;
  5504. }
  5505. }
  5506. static bool init(upb_table *t, upb_ctype_t ctype, uint8_t size_lg2,
  5507. upb_alloc *a) {
  5508. size_t bytes;
  5509. t->count = 0;
  5510. t->ctype = ctype;
  5511. t->size_lg2 = size_lg2;
  5512. t->mask = upb_table_size(t) ? upb_table_size(t) - 1 : 0;
  5513. #ifndef NDEBUG
  5514. t->alloc = a;
  5515. #endif
  5516. bytes = upb_table_size(t) * sizeof(upb_tabent);
  5517. if (bytes > 0) {
  5518. t->entries = upb_malloc(a, bytes);
  5519. if (!t->entries) return false;
  5520. memset(mutable_entries(t), 0, bytes);
  5521. } else {
  5522. t->entries = NULL;
  5523. }
  5524. return true;
  5525. }
  5526. static void uninit(upb_table *t, upb_alloc *a) {
  5527. upb_check_alloc(t, a);
  5528. upb_free(a, mutable_entries(t));
  5529. }
  5530. static upb_tabent *emptyent(upb_table *t) {
  5531. upb_tabent *e = mutable_entries(t) + upb_table_size(t);
  5532. while (1) { if (upb_tabent_isempty(--e)) return e; UPB_ASSERT(e > t->entries); }
  5533. }
  5534. static upb_tabent *getentry_mutable(upb_table *t, uint32_t hash) {
  5535. return (upb_tabent*)upb_getentry(t, hash);
  5536. }
  5537. static const upb_tabent *findentry(const upb_table *t, lookupkey_t key,
  5538. uint32_t hash, eqlfunc_t *eql) {
  5539. const upb_tabent *e;
  5540. if (t->size_lg2 == 0) return NULL;
  5541. e = upb_getentry(t, hash);
  5542. if (upb_tabent_isempty(e)) return NULL;
  5543. while (1) {
  5544. if (eql(e->key, key)) return e;
  5545. if ((e = e->next) == NULL) return NULL;
  5546. }
  5547. }
  5548. static upb_tabent *findentry_mutable(upb_table *t, lookupkey_t key,
  5549. uint32_t hash, eqlfunc_t *eql) {
  5550. return (upb_tabent*)findentry(t, key, hash, eql);
  5551. }
  5552. static bool lookup(const upb_table *t, lookupkey_t key, upb_value *v,
  5553. uint32_t hash, eqlfunc_t *eql) {
  5554. const upb_tabent *e = findentry(t, key, hash, eql);
  5555. if (e) {
  5556. if (v) {
  5557. _upb_value_setval(v, e->val.val, t->ctype);
  5558. }
  5559. return true;
  5560. } else {
  5561. return false;
  5562. }
  5563. }
  5564. /* The given key must not already exist in the table. */
  5565. static void insert(upb_table *t, lookupkey_t key, upb_tabkey tabkey,
  5566. upb_value val, uint32_t hash,
  5567. hashfunc_t *hashfunc, eqlfunc_t *eql) {
  5568. upb_tabent *mainpos_e;
  5569. upb_tabent *our_e;
  5570. UPB_ASSERT(findentry(t, key, hash, eql) == NULL);
  5571. UPB_ASSERT_DEBUGVAR(val.ctype == t->ctype);
  5572. t->count++;
  5573. mainpos_e = getentry_mutable(t, hash);
  5574. our_e = mainpos_e;
  5575. if (upb_tabent_isempty(mainpos_e)) {
  5576. /* Our main position is empty; use it. */
  5577. our_e->next = NULL;
  5578. } else {
  5579. /* Collision. */
  5580. upb_tabent *new_e = emptyent(t);
  5581. /* Head of collider's chain. */
  5582. upb_tabent *chain = getentry_mutable(t, hashfunc(mainpos_e->key));
  5583. if (chain == mainpos_e) {
  5584. /* Existing ent is in its main posisiton (it has the same hash as us, and
  5585. * is the head of our chain). Insert to new ent and append to this chain. */
  5586. new_e->next = mainpos_e->next;
  5587. mainpos_e->next = new_e;
  5588. our_e = new_e;
  5589. } else {
  5590. /* Existing ent is not in its main position (it is a node in some other
  5591. * chain). This implies that no existing ent in the table has our hash.
  5592. * Evict it (updating its chain) and use its ent for head of our chain. */
  5593. *new_e = *mainpos_e; /* copies next. */
  5594. while (chain->next != mainpos_e) {
  5595. chain = (upb_tabent*)chain->next;
  5596. UPB_ASSERT(chain);
  5597. }
  5598. chain->next = new_e;
  5599. our_e = mainpos_e;
  5600. our_e->next = NULL;
  5601. }
  5602. }
  5603. our_e->key = tabkey;
  5604. our_e->val.val = val.val;
  5605. UPB_ASSERT(findentry(t, key, hash, eql) == our_e);
  5606. }
  5607. static bool rm(upb_table *t, lookupkey_t key, upb_value *val,
  5608. upb_tabkey *removed, uint32_t hash, eqlfunc_t *eql) {
  5609. upb_tabent *chain = getentry_mutable(t, hash);
  5610. if (upb_tabent_isempty(chain)) return false;
  5611. if (eql(chain->key, key)) {
  5612. /* Element to remove is at the head of its chain. */
  5613. t->count--;
  5614. if (val) _upb_value_setval(val, chain->val.val, t->ctype);
  5615. if (removed) *removed = chain->key;
  5616. if (chain->next) {
  5617. upb_tabent *move = (upb_tabent*)chain->next;
  5618. *chain = *move;
  5619. move->key = 0; /* Make the slot empty. */
  5620. } else {
  5621. chain->key = 0; /* Make the slot empty. */
  5622. }
  5623. return true;
  5624. } else {
  5625. /* Element to remove is either in a non-head position or not in the
  5626. * table. */
  5627. while (chain->next && !eql(chain->next->key, key)) {
  5628. chain = (upb_tabent*)chain->next;
  5629. }
  5630. if (chain->next) {
  5631. /* Found element to remove. */
  5632. upb_tabent *rm = (upb_tabent*)chain->next;
  5633. t->count--;
  5634. if (val) _upb_value_setval(val, chain->next->val.val, t->ctype);
  5635. if (removed) *removed = rm->key;
  5636. rm->key = 0; /* Make the slot empty. */
  5637. chain->next = rm->next;
  5638. return true;
  5639. } else {
  5640. /* Element to remove is not in the table. */
  5641. return false;
  5642. }
  5643. }
  5644. }
  5645. static size_t next(const upb_table *t, size_t i) {
  5646. do {
  5647. if (++i >= upb_table_size(t))
  5648. return SIZE_MAX;
  5649. } while(upb_tabent_isempty(&t->entries[i]));
  5650. return i;
  5651. }
  5652. static size_t begin(const upb_table *t) {
  5653. return next(t, -1);
  5654. }
  5655. /* upb_strtable ***************************************************************/
  5656. /* A simple "subclass" of upb_table that only adds a hash function for strings. */
  5657. static upb_tabkey strcopy(lookupkey_t k2, upb_alloc *a) {
  5658. uint32_t len = (uint32_t) k2.str.len;
  5659. char *str = upb_malloc(a, k2.str.len + sizeof(uint32_t) + 1);
  5660. if (str == NULL) return 0;
  5661. memcpy(str, &len, sizeof(uint32_t));
  5662. memcpy(str + sizeof(uint32_t), k2.str.str, k2.str.len + 1);
  5663. return (uintptr_t)str;
  5664. }
  5665. static uint32_t strhash(upb_tabkey key) {
  5666. uint32_t len;
  5667. char *str = upb_tabstr(key, &len);
  5668. return MurmurHash2(str, len, 0);
  5669. }
  5670. static bool streql(upb_tabkey k1, lookupkey_t k2) {
  5671. uint32_t len;
  5672. char *str = upb_tabstr(k1, &len);
  5673. return len == k2.str.len && memcmp(str, k2.str.str, len) == 0;
  5674. }
  5675. bool upb_strtable_init2(upb_strtable *t, upb_ctype_t ctype, upb_alloc *a) {
  5676. return init(&t->t, ctype, 2, a);
  5677. }
  5678. void upb_strtable_uninit2(upb_strtable *t, upb_alloc *a) {
  5679. size_t i;
  5680. for (i = 0; i < upb_table_size(&t->t); i++)
  5681. upb_free(a, (void*)t->t.entries[i].key);
  5682. uninit(&t->t, a);
  5683. }
  5684. bool upb_strtable_resize(upb_strtable *t, size_t size_lg2, upb_alloc *a) {
  5685. upb_strtable new_table;
  5686. upb_strtable_iter i;
  5687. upb_check_alloc(&t->t, a);
  5688. if (!init(&new_table.t, t->t.ctype, size_lg2, a))
  5689. return false;
  5690. upb_strtable_begin(&i, t);
  5691. for ( ; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  5692. upb_strtable_insert3(
  5693. &new_table,
  5694. upb_strtable_iter_key(&i),
  5695. upb_strtable_iter_keylength(&i),
  5696. upb_strtable_iter_value(&i),
  5697. a);
  5698. }
  5699. upb_strtable_uninit2(t, a);
  5700. *t = new_table;
  5701. return true;
  5702. }
  5703. bool upb_strtable_insert3(upb_strtable *t, const char *k, size_t len,
  5704. upb_value v, upb_alloc *a) {
  5705. lookupkey_t key;
  5706. upb_tabkey tabkey;
  5707. uint32_t hash;
  5708. upb_check_alloc(&t->t, a);
  5709. if (isfull(&t->t)) {
  5710. /* Need to resize. New table of double the size, add old elements to it. */
  5711. if (!upb_strtable_resize(t, t->t.size_lg2 + 1, a)) {
  5712. return false;
  5713. }
  5714. }
  5715. key = strkey2(k, len);
  5716. tabkey = strcopy(key, a);
  5717. if (tabkey == 0) return false;
  5718. hash = MurmurHash2(key.str.str, key.str.len, 0);
  5719. insert(&t->t, key, tabkey, v, hash, &strhash, &streql);
  5720. return true;
  5721. }
  5722. bool upb_strtable_lookup2(const upb_strtable *t, const char *key, size_t len,
  5723. upb_value *v) {
  5724. uint32_t hash = MurmurHash2(key, len, 0);
  5725. return lookup(&t->t, strkey2(key, len), v, hash, &streql);
  5726. }
  5727. bool upb_strtable_remove3(upb_strtable *t, const char *key, size_t len,
  5728. upb_value *val, upb_alloc *alloc) {
  5729. uint32_t hash = MurmurHash2(key, len, 0);
  5730. upb_tabkey tabkey;
  5731. if (rm(&t->t, strkey2(key, len), val, &tabkey, hash, &streql)) {
  5732. upb_free(alloc, (void*)tabkey);
  5733. return true;
  5734. } else {
  5735. return false;
  5736. }
  5737. }
  5738. /* Iteration */
  5739. static const upb_tabent *str_tabent(const upb_strtable_iter *i) {
  5740. return &i->t->t.entries[i->index];
  5741. }
  5742. void upb_strtable_begin(upb_strtable_iter *i, const upb_strtable *t) {
  5743. i->t = t;
  5744. i->index = begin(&t->t);
  5745. }
  5746. void upb_strtable_next(upb_strtable_iter *i) {
  5747. i->index = next(&i->t->t, i->index);
  5748. }
  5749. bool upb_strtable_done(const upb_strtable_iter *i) {
  5750. return i->index >= upb_table_size(&i->t->t) ||
  5751. upb_tabent_isempty(str_tabent(i));
  5752. }
  5753. const char *upb_strtable_iter_key(const upb_strtable_iter *i) {
  5754. UPB_ASSERT(!upb_strtable_done(i));
  5755. return upb_tabstr(str_tabent(i)->key, NULL);
  5756. }
  5757. size_t upb_strtable_iter_keylength(const upb_strtable_iter *i) {
  5758. uint32_t len;
  5759. UPB_ASSERT(!upb_strtable_done(i));
  5760. upb_tabstr(str_tabent(i)->key, &len);
  5761. return len;
  5762. }
  5763. upb_value upb_strtable_iter_value(const upb_strtable_iter *i) {
  5764. UPB_ASSERT(!upb_strtable_done(i));
  5765. return _upb_value_val(str_tabent(i)->val.val, i->t->t.ctype);
  5766. }
  5767. void upb_strtable_iter_setdone(upb_strtable_iter *i) {
  5768. i->index = SIZE_MAX;
  5769. }
  5770. bool upb_strtable_iter_isequal(const upb_strtable_iter *i1,
  5771. const upb_strtable_iter *i2) {
  5772. if (upb_strtable_done(i1) && upb_strtable_done(i2))
  5773. return true;
  5774. return i1->t == i2->t && i1->index == i2->index;
  5775. }
  5776. /* upb_inttable ***************************************************************/
  5777. /* For inttables we use a hybrid structure where small keys are kept in an
  5778. * array and large keys are put in the hash table. */
  5779. static uint32_t inthash(upb_tabkey key) { return upb_inthash(key); }
  5780. static bool inteql(upb_tabkey k1, lookupkey_t k2) {
  5781. return k1 == k2.num;
  5782. }
  5783. static upb_tabval *mutable_array(upb_inttable *t) {
  5784. return (upb_tabval*)t->array;
  5785. }
  5786. static upb_tabval *inttable_val(upb_inttable *t, uintptr_t key) {
  5787. if (key < t->array_size) {
  5788. return upb_arrhas(t->array[key]) ? &(mutable_array(t)[key]) : NULL;
  5789. } else {
  5790. upb_tabent *e =
  5791. findentry_mutable(&t->t, intkey(key), upb_inthash(key), &inteql);
  5792. return e ? &e->val : NULL;
  5793. }
  5794. }
  5795. static const upb_tabval *inttable_val_const(const upb_inttable *t,
  5796. uintptr_t key) {
  5797. return inttable_val((upb_inttable*)t, key);
  5798. }
  5799. size_t upb_inttable_count(const upb_inttable *t) {
  5800. return t->t.count + t->array_count;
  5801. }
  5802. static void check(upb_inttable *t) {
  5803. UPB_UNUSED(t);
  5804. #if defined(UPB_DEBUG_TABLE) && !defined(NDEBUG)
  5805. {
  5806. /* This check is very expensive (makes inserts/deletes O(N)). */
  5807. size_t count = 0;
  5808. upb_inttable_iter i;
  5809. upb_inttable_begin(&i, t);
  5810. for(; !upb_inttable_done(&i); upb_inttable_next(&i), count++) {
  5811. UPB_ASSERT(upb_inttable_lookup(t, upb_inttable_iter_key(&i), NULL));
  5812. }
  5813. UPB_ASSERT(count == upb_inttable_count(t));
  5814. }
  5815. #endif
  5816. }
  5817. bool upb_inttable_sizedinit(upb_inttable *t, upb_ctype_t ctype,
  5818. size_t asize, int hsize_lg2, upb_alloc *a) {
  5819. size_t array_bytes;
  5820. if (!init(&t->t, ctype, hsize_lg2, a)) return false;
  5821. /* Always make the array part at least 1 long, so that we know key 0
  5822. * won't be in the hash part, which simplifies things. */
  5823. t->array_size = UPB_MAX(1, asize);
  5824. t->array_count = 0;
  5825. array_bytes = t->array_size * sizeof(upb_value);
  5826. t->array = upb_malloc(a, array_bytes);
  5827. if (!t->array) {
  5828. uninit(&t->t, a);
  5829. return false;
  5830. }
  5831. memset(mutable_array(t), 0xff, array_bytes);
  5832. check(t);
  5833. return true;
  5834. }
  5835. bool upb_inttable_init2(upb_inttable *t, upb_ctype_t ctype, upb_alloc *a) {
  5836. return upb_inttable_sizedinit(t, ctype, 0, 4, a);
  5837. }
  5838. void upb_inttable_uninit2(upb_inttable *t, upb_alloc *a) {
  5839. uninit(&t->t, a);
  5840. upb_free(a, mutable_array(t));
  5841. }
  5842. bool upb_inttable_insert2(upb_inttable *t, uintptr_t key, upb_value val,
  5843. upb_alloc *a) {
  5844. upb_tabval tabval;
  5845. tabval.val = val.val;
  5846. UPB_ASSERT(upb_arrhas(tabval)); /* This will reject (uint64_t)-1. Fix this. */
  5847. upb_check_alloc(&t->t, a);
  5848. if (key < t->array_size) {
  5849. UPB_ASSERT(!upb_arrhas(t->array[key]));
  5850. t->array_count++;
  5851. mutable_array(t)[key].val = val.val;
  5852. } else {
  5853. if (isfull(&t->t)) {
  5854. /* Need to resize the hash part, but we re-use the array part. */
  5855. size_t i;
  5856. upb_table new_table;
  5857. if (!init(&new_table, t->t.ctype, t->t.size_lg2 + 1, a)) {
  5858. return false;
  5859. }
  5860. for (i = begin(&t->t); i < upb_table_size(&t->t); i = next(&t->t, i)) {
  5861. const upb_tabent *e = &t->t.entries[i];
  5862. uint32_t hash;
  5863. upb_value v;
  5864. _upb_value_setval(&v, e->val.val, t->t.ctype);
  5865. hash = upb_inthash(e->key);
  5866. insert(&new_table, intkey(e->key), e->key, v, hash, &inthash, &inteql);
  5867. }
  5868. UPB_ASSERT(t->t.count == new_table.count);
  5869. uninit(&t->t, a);
  5870. t->t = new_table;
  5871. }
  5872. insert(&t->t, intkey(key), key, val, upb_inthash(key), &inthash, &inteql);
  5873. }
  5874. check(t);
  5875. return true;
  5876. }
  5877. bool upb_inttable_lookup(const upb_inttable *t, uintptr_t key, upb_value *v) {
  5878. const upb_tabval *table_v = inttable_val_const(t, key);
  5879. if (!table_v) return false;
  5880. if (v) _upb_value_setval(v, table_v->val, t->t.ctype);
  5881. return true;
  5882. }
  5883. bool upb_inttable_replace(upb_inttable *t, uintptr_t key, upb_value val) {
  5884. upb_tabval *table_v = inttable_val(t, key);
  5885. if (!table_v) return false;
  5886. table_v->val = val.val;
  5887. return true;
  5888. }
  5889. bool upb_inttable_remove(upb_inttable *t, uintptr_t key, upb_value *val) {
  5890. bool success;
  5891. if (key < t->array_size) {
  5892. if (upb_arrhas(t->array[key])) {
  5893. upb_tabval empty = UPB_TABVALUE_EMPTY_INIT;
  5894. t->array_count--;
  5895. if (val) {
  5896. _upb_value_setval(val, t->array[key].val, t->t.ctype);
  5897. }
  5898. mutable_array(t)[key] = empty;
  5899. success = true;
  5900. } else {
  5901. success = false;
  5902. }
  5903. } else {
  5904. success = rm(&t->t, intkey(key), val, NULL, upb_inthash(key), &inteql);
  5905. }
  5906. check(t);
  5907. return success;
  5908. }
  5909. bool upb_inttable_push2(upb_inttable *t, upb_value val, upb_alloc *a) {
  5910. upb_check_alloc(&t->t, a);
  5911. return upb_inttable_insert2(t, upb_inttable_count(t), val, a);
  5912. }
  5913. upb_value upb_inttable_pop(upb_inttable *t) {
  5914. upb_value val;
  5915. bool ok = upb_inttable_remove(t, upb_inttable_count(t) - 1, &val);
  5916. UPB_ASSERT(ok);
  5917. return val;
  5918. }
  5919. bool upb_inttable_insertptr2(upb_inttable *t, const void *key, upb_value val,
  5920. upb_alloc *a) {
  5921. upb_check_alloc(&t->t, a);
  5922. return upb_inttable_insert2(t, (uintptr_t)key, val, a);
  5923. }
  5924. bool upb_inttable_lookupptr(const upb_inttable *t, const void *key,
  5925. upb_value *v) {
  5926. return upb_inttable_lookup(t, (uintptr_t)key, v);
  5927. }
  5928. bool upb_inttable_removeptr(upb_inttable *t, const void *key, upb_value *val) {
  5929. return upb_inttable_remove(t, (uintptr_t)key, val);
  5930. }
  5931. void upb_inttable_compact2(upb_inttable *t, upb_alloc *a) {
  5932. /* A power-of-two histogram of the table keys. */
  5933. size_t counts[UPB_MAXARRSIZE + 1] = {0};
  5934. /* The max key in each bucket. */
  5935. uintptr_t max[UPB_MAXARRSIZE + 1] = {0};
  5936. upb_inttable_iter i;
  5937. size_t arr_count;
  5938. int size_lg2;
  5939. upb_inttable new_t;
  5940. upb_check_alloc(&t->t, a);
  5941. upb_inttable_begin(&i, t);
  5942. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5943. uintptr_t key = upb_inttable_iter_key(&i);
  5944. int bucket = log2ceil(key);
  5945. max[bucket] = UPB_MAX(max[bucket], key);
  5946. counts[bucket]++;
  5947. }
  5948. /* Find the largest power of two that satisfies the MIN_DENSITY
  5949. * definition (while actually having some keys). */
  5950. arr_count = upb_inttable_count(t);
  5951. for (size_lg2 = ARRAY_SIZE(counts) - 1; size_lg2 > 0; size_lg2--) {
  5952. if (counts[size_lg2] == 0) {
  5953. /* We can halve again without losing any entries. */
  5954. continue;
  5955. } else if (arr_count >= (1 << size_lg2) * MIN_DENSITY) {
  5956. break;
  5957. }
  5958. arr_count -= counts[size_lg2];
  5959. }
  5960. UPB_ASSERT(arr_count <= upb_inttable_count(t));
  5961. {
  5962. /* Insert all elements into new, perfectly-sized table. */
  5963. size_t arr_size = max[size_lg2] + 1; /* +1 so arr[max] will fit. */
  5964. size_t hash_count = upb_inttable_count(t) - arr_count;
  5965. size_t hash_size = hash_count ? (hash_count / MAX_LOAD) + 1 : 0;
  5966. size_t hashsize_lg2 = log2ceil(hash_size);
  5967. upb_inttable_sizedinit(&new_t, t->t.ctype, arr_size, hashsize_lg2, a);
  5968. upb_inttable_begin(&i, t);
  5969. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5970. uintptr_t k = upb_inttable_iter_key(&i);
  5971. upb_inttable_insert2(&new_t, k, upb_inttable_iter_value(&i), a);
  5972. }
  5973. UPB_ASSERT(new_t.array_size == arr_size);
  5974. UPB_ASSERT(new_t.t.size_lg2 == hashsize_lg2);
  5975. }
  5976. upb_inttable_uninit2(t, a);
  5977. *t = new_t;
  5978. }
  5979. /* Iteration. */
  5980. static const upb_tabent *int_tabent(const upb_inttable_iter *i) {
  5981. UPB_ASSERT(!i->array_part);
  5982. return &i->t->t.entries[i->index];
  5983. }
  5984. static upb_tabval int_arrent(const upb_inttable_iter *i) {
  5985. UPB_ASSERT(i->array_part);
  5986. return i->t->array[i->index];
  5987. }
  5988. void upb_inttable_begin(upb_inttable_iter *i, const upb_inttable *t) {
  5989. i->t = t;
  5990. i->index = -1;
  5991. i->array_part = true;
  5992. upb_inttable_next(i);
  5993. }
  5994. void upb_inttable_next(upb_inttable_iter *iter) {
  5995. const upb_inttable *t = iter->t;
  5996. if (iter->array_part) {
  5997. while (++iter->index < t->array_size) {
  5998. if (upb_arrhas(int_arrent(iter))) {
  5999. return;
  6000. }
  6001. }
  6002. iter->array_part = false;
  6003. iter->index = begin(&t->t);
  6004. } else {
  6005. iter->index = next(&t->t, iter->index);
  6006. }
  6007. }
  6008. bool upb_inttable_done(const upb_inttable_iter *i) {
  6009. if (i->array_part) {
  6010. return i->index >= i->t->array_size ||
  6011. !upb_arrhas(int_arrent(i));
  6012. } else {
  6013. return i->index >= upb_table_size(&i->t->t) ||
  6014. upb_tabent_isempty(int_tabent(i));
  6015. }
  6016. }
  6017. uintptr_t upb_inttable_iter_key(const upb_inttable_iter *i) {
  6018. UPB_ASSERT(!upb_inttable_done(i));
  6019. return i->array_part ? i->index : int_tabent(i)->key;
  6020. }
  6021. upb_value upb_inttable_iter_value(const upb_inttable_iter *i) {
  6022. UPB_ASSERT(!upb_inttable_done(i));
  6023. return _upb_value_val(
  6024. i->array_part ? i->t->array[i->index].val : int_tabent(i)->val.val,
  6025. i->t->t.ctype);
  6026. }
  6027. void upb_inttable_iter_setdone(upb_inttable_iter *i) {
  6028. i->index = SIZE_MAX;
  6029. i->array_part = false;
  6030. }
  6031. bool upb_inttable_iter_isequal(const upb_inttable_iter *i1,
  6032. const upb_inttable_iter *i2) {
  6033. if (upb_inttable_done(i1) && upb_inttable_done(i2))
  6034. return true;
  6035. return i1->t == i2->t && i1->index == i2->index &&
  6036. i1->array_part == i2->array_part;
  6037. }
  6038. #ifdef UPB_UNALIGNED_READS_OK
  6039. /* -----------------------------------------------------------------------------
  6040. * MurmurHash2, by Austin Appleby (released as public domain).
  6041. * Reformatted and C99-ified by Joshua Haberman.
  6042. * Note - This code makes a few assumptions about how your machine behaves -
  6043. * 1. We can read a 4-byte value from any address without crashing
  6044. * 2. sizeof(int) == 4 (in upb this limitation is removed by using uint32_t
  6045. * And it has a few limitations -
  6046. * 1. It will not work incrementally.
  6047. * 2. It will not produce the same results on little-endian and big-endian
  6048. * machines. */
  6049. uint32_t MurmurHash2(const void *key, size_t len, uint32_t seed) {
  6050. /* 'm' and 'r' are mixing constants generated offline.
  6051. * They're not really 'magic', they just happen to work well. */
  6052. const uint32_t m = 0x5bd1e995;
  6053. const int32_t r = 24;
  6054. /* Initialize the hash to a 'random' value */
  6055. uint32_t h = seed ^ len;
  6056. /* Mix 4 bytes at a time into the hash */
  6057. const uint8_t * data = (const uint8_t *)key;
  6058. while(len >= 4) {
  6059. uint32_t k = *(uint32_t *)data;
  6060. k *= m;
  6061. k ^= k >> r;
  6062. k *= m;
  6063. h *= m;
  6064. h ^= k;
  6065. data += 4;
  6066. len -= 4;
  6067. }
  6068. /* Handle the last few bytes of the input array */
  6069. switch(len) {
  6070. case 3: h ^= data[2] << 16;
  6071. case 2: h ^= data[1] << 8;
  6072. case 1: h ^= data[0]; h *= m;
  6073. };
  6074. /* Do a few final mixes of the hash to ensure the last few
  6075. * bytes are well-incorporated. */
  6076. h ^= h >> 13;
  6077. h *= m;
  6078. h ^= h >> 15;
  6079. return h;
  6080. }
  6081. #else /* !UPB_UNALIGNED_READS_OK */
  6082. /* -----------------------------------------------------------------------------
  6083. * MurmurHashAligned2, by Austin Appleby
  6084. * Same algorithm as MurmurHash2, but only does aligned reads - should be safer
  6085. * on certain platforms.
  6086. * Performance will be lower than MurmurHash2 */
  6087. #define MIX(h,k,m) { k *= m; k ^= k >> r; k *= m; h *= m; h ^= k; }
  6088. uint32_t MurmurHash2(const void * key, size_t len, uint32_t seed) {
  6089. const uint32_t m = 0x5bd1e995;
  6090. const int32_t r = 24;
  6091. const uint8_t * data = (const uint8_t *)key;
  6092. uint32_t h = seed ^ len;
  6093. uint8_t align = (uintptr_t)data & 3;
  6094. if(align && (len >= 4)) {
  6095. /* Pre-load the temp registers */
  6096. uint32_t t = 0, d = 0;
  6097. int32_t sl;
  6098. int32_t sr;
  6099. switch(align) {
  6100. case 1: t |= data[2] << 16;
  6101. case 2: t |= data[1] << 8;
  6102. case 3: t |= data[0];
  6103. }
  6104. t <<= (8 * align);
  6105. data += 4-align;
  6106. len -= 4-align;
  6107. sl = 8 * (4-align);
  6108. sr = 8 * align;
  6109. /* Mix */
  6110. while(len >= 4) {
  6111. uint32_t k;
  6112. d = *(uint32_t *)data;
  6113. t = (t >> sr) | (d << sl);
  6114. k = t;
  6115. MIX(h,k,m);
  6116. t = d;
  6117. data += 4;
  6118. len -= 4;
  6119. }
  6120. /* Handle leftover data in temp registers */
  6121. d = 0;
  6122. if(len >= align) {
  6123. uint32_t k;
  6124. switch(align) {
  6125. case 3: d |= data[2] << 16;
  6126. case 2: d |= data[1] << 8;
  6127. case 1: d |= data[0];
  6128. }
  6129. k = (t >> sr) | (d << sl);
  6130. MIX(h,k,m);
  6131. data += align;
  6132. len -= align;
  6133. /* ----------
  6134. * Handle tail bytes */
  6135. switch(len) {
  6136. case 3: h ^= data[2] << 16;
  6137. case 2: h ^= data[1] << 8;
  6138. case 1: h ^= data[0]; h *= m;
  6139. };
  6140. } else {
  6141. switch(len) {
  6142. case 3: d |= data[2] << 16;
  6143. case 2: d |= data[1] << 8;
  6144. case 1: d |= data[0];
  6145. case 0: h ^= (t >> sr) | (d << sl); h *= m;
  6146. }
  6147. }
  6148. h ^= h >> 13;
  6149. h *= m;
  6150. h ^= h >> 15;
  6151. return h;
  6152. } else {
  6153. while(len >= 4) {
  6154. uint32_t k = *(uint32_t *)data;
  6155. MIX(h,k,m);
  6156. data += 4;
  6157. len -= 4;
  6158. }
  6159. /* ----------
  6160. * Handle tail bytes */
  6161. switch(len) {
  6162. case 3: h ^= data[2] << 16;
  6163. case 2: h ^= data[1] << 8;
  6164. case 1: h ^= data[0]; h *= m;
  6165. };
  6166. h ^= h >> 13;
  6167. h *= m;
  6168. h ^= h >> 15;
  6169. return h;
  6170. }
  6171. }
  6172. #undef MIX
  6173. #endif /* UPB_UNALIGNED_READS_OK */
  6174. #include <errno.h>
  6175. #include <stdarg.h>
  6176. #include <stddef.h>
  6177. #include <stdint.h>
  6178. #include <stdio.h>
  6179. #include <stdlib.h>
  6180. #include <string.h>
  6181. bool upb_dumptostderr(void *closure, const upb_status* status) {
  6182. UPB_UNUSED(closure);
  6183. fprintf(stderr, "%s\n", upb_status_errmsg(status));
  6184. return false;
  6185. }
  6186. /* Guarantee null-termination and provide ellipsis truncation.
  6187. * It may be tempting to "optimize" this by initializing these final
  6188. * four bytes up-front and then being careful never to overwrite them,
  6189. * this is safer and simpler. */
  6190. static void nullz(upb_status *status) {
  6191. const char *ellipsis = "...";
  6192. size_t len = strlen(ellipsis);
  6193. UPB_ASSERT(sizeof(status->msg) > len);
  6194. memcpy(status->msg + sizeof(status->msg) - len, ellipsis, len);
  6195. }
  6196. /* upb_upberr *****************************************************************/
  6197. upb_errorspace upb_upberr = {"upb error"};
  6198. void upb_upberr_setoom(upb_status *status) {
  6199. status->error_space_ = &upb_upberr;
  6200. upb_status_seterrmsg(status, "Out of memory");
  6201. }
  6202. /* upb_status *****************************************************************/
  6203. void upb_status_clear(upb_status *status) {
  6204. if (!status) return;
  6205. status->ok_ = true;
  6206. status->code_ = 0;
  6207. status->msg[0] = '\0';
  6208. }
  6209. bool upb_ok(const upb_status *status) { return status->ok_; }
  6210. upb_errorspace *upb_status_errspace(const upb_status *status) {
  6211. return status->error_space_;
  6212. }
  6213. int upb_status_errcode(const upb_status *status) { return status->code_; }
  6214. const char *upb_status_errmsg(const upb_status *status) { return status->msg; }
  6215. void upb_status_seterrmsg(upb_status *status, const char *msg) {
  6216. if (!status) return;
  6217. status->ok_ = false;
  6218. strncpy(status->msg, msg, sizeof(status->msg));
  6219. nullz(status);
  6220. }
  6221. void upb_status_seterrf(upb_status *status, const char *fmt, ...) {
  6222. va_list args;
  6223. va_start(args, fmt);
  6224. upb_status_vseterrf(status, fmt, args);
  6225. va_end(args);
  6226. }
  6227. void upb_status_vseterrf(upb_status *status, const char *fmt, va_list args) {
  6228. if (!status) return;
  6229. status->ok_ = false;
  6230. _upb_vsnprintf(status->msg, sizeof(status->msg), fmt, args);
  6231. nullz(status);
  6232. }
  6233. void upb_status_copy(upb_status *to, const upb_status *from) {
  6234. if (!to) return;
  6235. *to = *from;
  6236. }
  6237. /* upb_alloc ******************************************************************/
  6238. static void *upb_global_allocfunc(upb_alloc *alloc, void *ptr, size_t oldsize,
  6239. size_t size) {
  6240. UPB_UNUSED(alloc);
  6241. UPB_UNUSED(oldsize);
  6242. if (size == 0) {
  6243. free(ptr);
  6244. return NULL;
  6245. } else {
  6246. return realloc(ptr, size);
  6247. }
  6248. }
  6249. upb_alloc upb_alloc_global = {&upb_global_allocfunc};
  6250. /* upb_arena ******************************************************************/
  6251. /* Be conservative and choose 16 in case anyone is using SSE. */
  6252. static const size_t maxalign = 16;
  6253. static size_t align_up_max(size_t size) {
  6254. return ((size + maxalign - 1) / maxalign) * maxalign;
  6255. }
  6256. typedef struct mem_block {
  6257. struct mem_block *next;
  6258. size_t size;
  6259. size_t used;
  6260. bool owned;
  6261. /* Data follows. */
  6262. } mem_block;
  6263. typedef struct cleanup_ent {
  6264. struct cleanup_ent *next;
  6265. upb_cleanup_func *cleanup;
  6266. void *ud;
  6267. } cleanup_ent;
  6268. static void upb_arena_addblock(upb_arena *a, void *ptr, size_t size,
  6269. bool owned) {
  6270. mem_block *block = ptr;
  6271. block->next = a->block_head;
  6272. block->size = size;
  6273. block->used = align_up_max(sizeof(mem_block));
  6274. block->owned = owned;
  6275. a->block_head = block;
  6276. /* TODO(haberman): ASAN poison. */
  6277. }
  6278. static mem_block *upb_arena_allocblock(upb_arena *a, size_t size) {
  6279. size_t block_size = UPB_MAX(size, a->next_block_size) + sizeof(mem_block);
  6280. mem_block *block = upb_malloc(a->block_alloc, block_size);
  6281. if (!block) {
  6282. return NULL;
  6283. }
  6284. upb_arena_addblock(a, block, block_size, true);
  6285. a->next_block_size = UPB_MIN(block_size * 2, a->max_block_size);
  6286. return block;
  6287. }
  6288. static void *upb_arena_doalloc(upb_alloc *alloc, void *ptr, size_t oldsize,
  6289. size_t size) {
  6290. upb_arena *a = (upb_arena*)alloc; /* upb_alloc is initial member. */
  6291. mem_block *block = a->block_head;
  6292. void *ret;
  6293. if (size == 0) {
  6294. return NULL; /* We are an arena, don't need individual frees. */
  6295. }
  6296. size = align_up_max(size);
  6297. /* TODO(haberman): special-case if this is a realloc of the last alloc? */
  6298. if (!block || block->size - block->used < size) {
  6299. /* Slow path: have to allocate a new block. */
  6300. block = upb_arena_allocblock(a, size);
  6301. if (!block) {
  6302. return NULL; /* Out of memory. */
  6303. }
  6304. }
  6305. ret = (char*)block + block->used;
  6306. block->used += size;
  6307. if (oldsize > 0) {
  6308. memcpy(ret, ptr, oldsize); /* Preserve existing data. */
  6309. }
  6310. /* TODO(haberman): ASAN unpoison. */
  6311. a->bytes_allocated += size;
  6312. return ret;
  6313. }
  6314. /* Public Arena API ***********************************************************/
  6315. void upb_arena_init(upb_arena *a) {
  6316. a->alloc.func = &upb_arena_doalloc;
  6317. a->block_alloc = &upb_alloc_global;
  6318. a->bytes_allocated = 0;
  6319. a->next_block_size = 256;
  6320. a->max_block_size = 16384;
  6321. a->cleanup_head = NULL;
  6322. a->block_head = NULL;
  6323. }
  6324. void upb_arena_init2(upb_arena *a, void *mem, size_t size, upb_alloc *alloc) {
  6325. upb_arena_init(a);
  6326. if (size > sizeof(mem_block)) {
  6327. upb_arena_addblock(a, mem, size, false);
  6328. }
  6329. if (alloc) {
  6330. a->block_alloc = alloc;
  6331. }
  6332. }
  6333. void upb_arena_uninit(upb_arena *a) {
  6334. cleanup_ent *ent = a->cleanup_head;
  6335. mem_block *block = a->block_head;
  6336. while (ent) {
  6337. ent->cleanup(ent->ud);
  6338. ent = ent->next;
  6339. }
  6340. /* Must do this after running cleanup functions, because this will delete
  6341. * the memory we store our cleanup entries in! */
  6342. while (block) {
  6343. mem_block *next = block->next;
  6344. if (block->owned) {
  6345. upb_free(a->block_alloc, block);
  6346. }
  6347. block = next;
  6348. }
  6349. /* Protect against multiple-uninit. */
  6350. a->cleanup_head = NULL;
  6351. a->block_head = NULL;
  6352. }
  6353. bool upb_arena_addcleanup(upb_arena *a, upb_cleanup_func *func, void *ud) {
  6354. cleanup_ent *ent = upb_malloc(&a->alloc, sizeof(cleanup_ent));
  6355. if (!ent) {
  6356. return false; /* Out of memory. */
  6357. }
  6358. ent->cleanup = func;
  6359. ent->ud = ud;
  6360. ent->next = a->cleanup_head;
  6361. a->cleanup_head = ent;
  6362. return true;
  6363. }
  6364. size_t upb_arena_bytesallocated(const upb_arena *a) {
  6365. return a->bytes_allocated;
  6366. }
  6367. /* Standard error functions ***************************************************/
  6368. static bool default_err(void *ud, const upb_status *status) {
  6369. UPB_UNUSED(ud);
  6370. UPB_UNUSED(status);
  6371. return false;
  6372. }
  6373. static bool write_err_to(void *ud, const upb_status *status) {
  6374. upb_status *copy_to = ud;
  6375. upb_status_copy(copy_to, status);
  6376. return false;
  6377. }
  6378. /* upb_env ********************************************************************/
  6379. void upb_env_initonly(upb_env *e) {
  6380. e->ok_ = true;
  6381. e->error_func_ = &default_err;
  6382. e->error_ud_ = NULL;
  6383. }
  6384. void upb_env_init(upb_env *e) {
  6385. upb_arena_init(&e->arena_);
  6386. upb_env_initonly(e);
  6387. }
  6388. void upb_env_init2(upb_env *e, void *mem, size_t n, upb_alloc *alloc) {
  6389. upb_arena_init2(&e->arena_, mem, n, alloc);
  6390. upb_env_initonly(e);
  6391. }
  6392. void upb_env_uninit(upb_env *e) {
  6393. upb_arena_uninit(&e->arena_);
  6394. }
  6395. void upb_env_seterrorfunc(upb_env *e, upb_error_func *func, void *ud) {
  6396. e->error_func_ = func;
  6397. e->error_ud_ = ud;
  6398. }
  6399. void upb_env_reporterrorsto(upb_env *e, upb_status *s) {
  6400. e->error_func_ = &write_err_to;
  6401. e->error_ud_ = s;
  6402. }
  6403. bool upb_env_reporterror(upb_env *e, const upb_status *status) {
  6404. e->ok_ = false;
  6405. return e->error_func_(e->error_ud_, status);
  6406. }
  6407. void *upb_env_malloc(upb_env *e, size_t size) {
  6408. return upb_malloc(&e->arena_.alloc, size);
  6409. }
  6410. void *upb_env_realloc(upb_env *e, void *ptr, size_t oldsize, size_t size) {
  6411. return upb_realloc(&e->arena_.alloc, ptr, oldsize, size);
  6412. }
  6413. void upb_env_free(upb_env *e, void *ptr) {
  6414. upb_free(&e->arena_.alloc, ptr);
  6415. }
  6416. bool upb_env_addcleanup(upb_env *e, upb_cleanup_func *func, void *ud) {
  6417. return upb_arena_addcleanup(&e->arena_, func, ud);
  6418. }
  6419. size_t upb_env_bytesallocated(const upb_env *e) {
  6420. return upb_arena_bytesallocated(&e->arena_);
  6421. }
  6422. /* This file was generated by upbc (the upb compiler) from the input
  6423. * file:
  6424. *
  6425. * upb/descriptor/descriptor.proto
  6426. *
  6427. * Do not edit -- your changes will be discarded when the file is
  6428. * regenerated. */
  6429. static const upb_msgdef msgs[22];
  6430. static const upb_fielddef fields[107];
  6431. static const upb_enumdef enums[5];
  6432. static const upb_tabent strentries[236];
  6433. static const upb_tabent intentries[18];
  6434. static const upb_tabval arrays[187];
  6435. #ifdef UPB_DEBUG_REFS
  6436. static upb_inttable reftables[268];
  6437. #endif
  6438. static const upb_msgdef msgs[22] = {
  6439. UPB_MSGDEF_INIT("google.protobuf.DescriptorProto", 41, 8, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[0], 11, 10), UPB_STRTABLE_INIT(10, 15, UPB_CTYPE_PTR, 4, &strentries[0]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[0], &reftables[1]),
  6440. UPB_MSGDEF_INIT("google.protobuf.DescriptorProto.ExtensionRange", 5, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[11], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[16]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[2], &reftables[3]),
  6441. UPB_MSGDEF_INIT("google.protobuf.DescriptorProto.ReservedRange", 5, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[14], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[20]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[4], &reftables[5]),
  6442. UPB_MSGDEF_INIT("google.protobuf.EnumDescriptorProto", 12, 2, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[17], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[24]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[6], &reftables[7]),
  6443. UPB_MSGDEF_INIT("google.protobuf.EnumOptions", 9, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[0], &arrays[21], 4, 2), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[28]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[8], &reftables[9]),
  6444. UPB_MSGDEF_INIT("google.protobuf.EnumValueDescriptorProto", 9, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[25], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[32]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[10], &reftables[11]),
  6445. UPB_MSGDEF_INIT("google.protobuf.EnumValueOptions", 8, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[2], &arrays[29], 2, 1), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[36]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[12], &reftables[13]),
  6446. UPB_MSGDEF_INIT("google.protobuf.FieldDescriptorProto", 24, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[31], 11, 10), UPB_STRTABLE_INIT(10, 15, UPB_CTYPE_PTR, 4, &strentries[40]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[14], &reftables[15]),
  6447. UPB_MSGDEF_INIT("google.protobuf.FieldOptions", 13, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[4], &arrays[42], 11, 6), UPB_STRTABLE_INIT(7, 15, UPB_CTYPE_PTR, 4, &strentries[56]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[16], &reftables[17]),
  6448. UPB_MSGDEF_INIT("google.protobuf.FileDescriptorProto", 43, 6, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[53], 13, 12), UPB_STRTABLE_INIT(12, 15, UPB_CTYPE_PTR, 4, &strentries[72]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[18], &reftables[19]),
  6449. UPB_MSGDEF_INIT("google.protobuf.FileDescriptorSet", 7, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[66], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[88]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[20], &reftables[21]),
  6450. UPB_MSGDEF_INIT("google.protobuf.FileOptions", 38, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[6], &arrays[68], 42, 17), UPB_STRTABLE_INIT(18, 31, UPB_CTYPE_PTR, 5, &strentries[92]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[22], &reftables[23]),
  6451. UPB_MSGDEF_INIT("google.protobuf.MessageOptions", 11, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[8], &arrays[110], 8, 4), UPB_STRTABLE_INIT(5, 7, UPB_CTYPE_PTR, 3, &strentries[124]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[24], &reftables[25]),
  6452. UPB_MSGDEF_INIT("google.protobuf.MethodDescriptorProto", 16, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[118], 7, 6), UPB_STRTABLE_INIT(6, 7, UPB_CTYPE_PTR, 3, &strentries[132]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[26], &reftables[27]),
  6453. UPB_MSGDEF_INIT("google.protobuf.MethodOptions", 8, 1, UPB_INTTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &intentries[10], &arrays[125], 1, 0), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[140]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[28], &reftables[29]),
  6454. UPB_MSGDEF_INIT("google.protobuf.OneofDescriptorProto", 6, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[126], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[144]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[30], &reftables[31]),
  6455. UPB_MSGDEF_INIT("google.protobuf.ServiceDescriptorProto", 12, 2, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[128], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[148]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[32], &reftables[33]),
  6456. UPB_MSGDEF_INIT("google.protobuf.ServiceOptions", 8, 1, UPB_INTTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &intentries[14], &arrays[132], 1, 0), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[152]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[34], &reftables[35]),
  6457. UPB_MSGDEF_INIT("google.protobuf.SourceCodeInfo", 7, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[133], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[156]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[36], &reftables[37]),
  6458. UPB_MSGDEF_INIT("google.protobuf.SourceCodeInfo.Location", 20, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[135], 7, 5), UPB_STRTABLE_INIT(5, 7, UPB_CTYPE_PTR, 3, &strentries[160]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[38], &reftables[39]),
  6459. UPB_MSGDEF_INIT("google.protobuf.UninterpretedOption", 19, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[142], 9, 7), UPB_STRTABLE_INIT(7, 15, UPB_CTYPE_PTR, 4, &strentries[168]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[40], &reftables[41]),
  6460. UPB_MSGDEF_INIT("google.protobuf.UninterpretedOption.NamePart", 7, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[151], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[184]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[42], &reftables[43]),
  6461. };
  6462. static const upb_fielddef fields[107] = {
  6463. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "aggregate_value", 8, &msgs[20], NULL, 16, 6, {0},&reftables[44], &reftables[45]),
  6464. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "allow_alias", 2, &msgs[4], NULL, 7, 1, {0},&reftables[46], &reftables[47]),
  6465. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "cc_enable_arenas", 31, &msgs[11], NULL, 24, 12, {0},&reftables[48], &reftables[49]),
  6466. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "cc_generic_services", 16, &msgs[11], NULL, 18, 6, {0},&reftables[50], &reftables[51]),
  6467. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "client_streaming", 5, &msgs[13], NULL, 14, 4, {0},&reftables[52], &reftables[53]),
  6468. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "csharp_namespace", 37, &msgs[11], NULL, 28, 14, {0},&reftables[54], &reftables[55]),
  6469. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "ctype", 1, &msgs[8], (const upb_def*)(&enums[2]), 7, 1, {0},&reftables[56], &reftables[57]),
  6470. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "default_value", 7, &msgs[7], NULL, 17, 7, {0},&reftables[58], &reftables[59]),
  6471. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_STRING, 0, false, false, false, false, "dependency", 3, &msgs[9], NULL, 31, 8, {0},&reftables[60], &reftables[61]),
  6472. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[8], NULL, 9, 3, {0},&reftables[62], &reftables[63]),
  6473. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 33, &msgs[14], NULL, 7, 1, {0},&reftables[64], &reftables[65]),
  6474. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[12], NULL, 9, 3, {0},&reftables[66], &reftables[67]),
  6475. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 23, &msgs[11], NULL, 22, 10, {0},&reftables[68], &reftables[69]),
  6476. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 1, &msgs[6], NULL, 7, 1, {0},&reftables[70], &reftables[71]),
  6477. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[4], NULL, 8, 2, {0},&reftables[72], &reftables[73]),
  6478. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 33, &msgs[17], NULL, 7, 1, {0},&reftables[74], &reftables[75]),
  6479. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_DOUBLE, 0, false, false, false, false, "double_value", 6, &msgs[20], NULL, 12, 4, {0},&reftables[76], &reftables[77]),
  6480. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "end", 2, &msgs[2], NULL, 4, 1, {0},&reftables[78], &reftables[79]),
  6481. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "end", 2, &msgs[1], NULL, 4, 1, {0},&reftables[80], &reftables[81]),
  6482. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "enum_type", 5, &msgs[9], (const upb_def*)(&msgs[3]), 14, 1, {0},&reftables[82], &reftables[83]),
  6483. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "enum_type", 4, &msgs[0], (const upb_def*)(&msgs[3]), 19, 2, {0},&reftables[84], &reftables[85]),
  6484. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "extendee", 2, &msgs[7], NULL, 8, 2, {0},&reftables[86], &reftables[87]),
  6485. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension", 6, &msgs[0], (const upb_def*)(&msgs[7]), 25, 4, {0},&reftables[88], &reftables[89]),
  6486. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension", 7, &msgs[9], (const upb_def*)(&msgs[7]), 20, 3, {0},&reftables[90], &reftables[91]),
  6487. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension_range", 5, &msgs[0], (const upb_def*)(&msgs[1]), 22, 3, {0},&reftables[92], &reftables[93]),
  6488. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "field", 2, &msgs[0], (const upb_def*)(&msgs[7]), 13, 0, {0},&reftables[94], &reftables[95]),
  6489. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "file", 1, &msgs[10], (const upb_def*)(&msgs[9]), 6, 0, {0},&reftables[96], &reftables[97]),
  6490. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "go_package", 11, &msgs[11], NULL, 15, 5, {0},&reftables[98], &reftables[99]),
  6491. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "identifier_value", 3, &msgs[20], NULL, 7, 1, {0},&reftables[100], &reftables[101]),
  6492. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "input_type", 2, &msgs[13], NULL, 8, 2, {0},&reftables[102], &reftables[103]),
  6493. UPB_FIELDDEF_INIT(UPB_LABEL_REQUIRED, UPB_TYPE_BOOL, 0, false, false, false, false, "is_extension", 2, &msgs[21], NULL, 6, 1, {0},&reftables[104], &reftables[105]),
  6494. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_generate_equals_and_hash", 20, &msgs[11], NULL, 21, 9, {0},&reftables[106], &reftables[107]),
  6495. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_generic_services", 17, &msgs[11], NULL, 19, 7, {0},&reftables[108], &reftables[109]),
  6496. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_multiple_files", 10, &msgs[11], NULL, 14, 4, {0},&reftables[110], &reftables[111]),
  6497. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "java_outer_classname", 8, &msgs[11], NULL, 10, 2, {0},&reftables[112], &reftables[113]),
  6498. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "java_package", 1, &msgs[11], NULL, 7, 1, {0},&reftables[114], &reftables[115]),
  6499. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_string_check_utf8", 27, &msgs[11], NULL, 23, 11, {0},&reftables[116], &reftables[117]),
  6500. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "javanano_use_deprecated_package", 38, &msgs[11], NULL, 31, 15, {0},&reftables[118], &reftables[119]),
  6501. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "json_name", 10, &msgs[7], NULL, 21, 9, {0},&reftables[120], &reftables[121]),
  6502. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "jstype", 6, &msgs[8], (const upb_def*)(&enums[3]), 11, 5, {0},&reftables[122], &reftables[123]),
  6503. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "label", 4, &msgs[7], (const upb_def*)(&enums[0]), 12, 4, {0},&reftables[124], &reftables[125]),
  6504. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "lazy", 5, &msgs[8], NULL, 10, 4, {0},&reftables[126], &reftables[127]),
  6505. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "leading_comments", 3, &msgs[19], NULL, 9, 2, {0},&reftables[128], &reftables[129]),
  6506. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_STRING, 0, false, false, false, false, "leading_detached_comments", 6, &msgs[19], NULL, 17, 4, {0},&reftables[130], &reftables[131]),
  6507. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "location", 1, &msgs[18], (const upb_def*)(&msgs[19]), 6, 0, {0},&reftables[132], &reftables[133]),
  6508. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "map_entry", 7, &msgs[12], NULL, 10, 4, {0},&reftables[134], &reftables[135]),
  6509. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "message_set_wire_format", 1, &msgs[12], NULL, 7, 1, {0},&reftables[136], &reftables[137]),
  6510. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "message_type", 4, &msgs[9], (const upb_def*)(&msgs[0]), 11, 0, {0},&reftables[138], &reftables[139]),
  6511. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "method", 2, &msgs[16], (const upb_def*)(&msgs[13]), 7, 0, {0},&reftables[140], &reftables[141]),
  6512. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "name", 2, &msgs[20], (const upb_def*)(&msgs[21]), 6, 0, {0},&reftables[142], &reftables[143]),
  6513. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[5], NULL, 5, 1, {0},&reftables[144], &reftables[145]),
  6514. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[9], NULL, 23, 6, {0},&reftables[146], &reftables[147]),
  6515. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[3], NULL, 9, 2, {0},&reftables[148], &reftables[149]),
  6516. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[16], NULL, 9, 2, {0},&reftables[150], &reftables[151]),
  6517. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[15], NULL, 3, 0, {0},&reftables[152], &reftables[153]),
  6518. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[13], NULL, 5, 1, {0},&reftables[154], &reftables[155]),
  6519. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[7], NULL, 5, 1, {0},&reftables[156], &reftables[157]),
  6520. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[0], NULL, 33, 8, {0},&reftables[158], &reftables[159]),
  6521. UPB_FIELDDEF_INIT(UPB_LABEL_REQUIRED, UPB_TYPE_STRING, 0, false, false, false, false, "name_part", 1, &msgs[21], NULL, 3, 0, {0},&reftables[160], &reftables[161]),
  6522. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT64, UPB_INTFMT_VARIABLE, false, false, false, false, "negative_int_value", 5, &msgs[20], NULL, 11, 3, {0},&reftables[162], &reftables[163]),
  6523. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "nested_type", 3, &msgs[0], (const upb_def*)(&msgs[0]), 16, 1, {0},&reftables[164], &reftables[165]),
  6524. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "no_standard_descriptor_accessor", 2, &msgs[12], NULL, 8, 2, {0},&reftables[166], &reftables[167]),
  6525. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "number", 3, &msgs[7], NULL, 11, 3, {0},&reftables[168], &reftables[169]),
  6526. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "number", 2, &msgs[5], NULL, 8, 2, {0},&reftables[170], &reftables[171]),
  6527. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "objc_class_prefix", 36, &msgs[11], NULL, 25, 13, {0},&reftables[172], &reftables[173]),
  6528. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "oneof_decl", 8, &msgs[0], (const upb_def*)(&msgs[15]), 29, 6, {0},&reftables[174], &reftables[175]),
  6529. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "oneof_index", 9, &msgs[7], NULL, 20, 8, {0},&reftables[176], &reftables[177]),
  6530. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "optimize_for", 9, &msgs[11], (const upb_def*)(&enums[4]), 13, 3, {0},&reftables[178], &reftables[179]),
  6531. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 7, &msgs[0], (const upb_def*)(&msgs[12]), 26, 5, {0},&reftables[180], &reftables[181]),
  6532. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 8, &msgs[9], (const upb_def*)(&msgs[11]), 21, 4, {0},&reftables[182], &reftables[183]),
  6533. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 8, &msgs[7], (const upb_def*)(&msgs[8]), 4, 0, {0},&reftables[184], &reftables[185]),
  6534. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 4, &msgs[13], (const upb_def*)(&msgs[14]), 4, 0, {0},&reftables[186], &reftables[187]),
  6535. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[16], (const upb_def*)(&msgs[17]), 8, 1, {0},&reftables[188], &reftables[189]),
  6536. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[3], (const upb_def*)(&msgs[4]), 8, 1, {0},&reftables[190], &reftables[191]),
  6537. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[5], (const upb_def*)(&msgs[6]), 4, 0, {0},&reftables[192], &reftables[193]),
  6538. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "output_type", 3, &msgs[13], NULL, 11, 3, {0},&reftables[194], &reftables[195]),
  6539. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "package", 2, &msgs[9], NULL, 26, 7, {0},&reftables[196], &reftables[197]),
  6540. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "packed", 2, &msgs[8], NULL, 8, 2, {0},&reftables[198], &reftables[199]),
  6541. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, true, "path", 1, &msgs[19], NULL, 5, 0, {0},&reftables[200], &reftables[201]),
  6542. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "php_class_prefix", 40, &msgs[11], NULL, 32, 16, {0},&reftables[202], &reftables[203]),
  6543. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "php_namespace", 41, &msgs[11], NULL, 35, 17, {0},&reftables[204], &reftables[205]),
  6544. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_UINT64, UPB_INTFMT_VARIABLE, false, false, false, false, "positive_int_value", 4, &msgs[20], NULL, 10, 2, {0},&reftables[206], &reftables[207]),
  6545. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "public_dependency", 10, &msgs[9], NULL, 36, 9, {0},&reftables[208], &reftables[209]),
  6546. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "py_generic_services", 18, &msgs[11], NULL, 20, 8, {0},&reftables[210], &reftables[211]),
  6547. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_STRING, 0, false, false, false, false, "reserved_name", 10, &msgs[0], NULL, 38, 9, {0},&reftables[212], &reftables[213]),
  6548. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "reserved_range", 9, &msgs[0], (const upb_def*)(&msgs[2]), 32, 7, {0},&reftables[214], &reftables[215]),
  6549. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "server_streaming", 6, &msgs[13], NULL, 15, 5, {0},&reftables[216], &reftables[217]),
  6550. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "service", 6, &msgs[9], (const upb_def*)(&msgs[16]), 17, 2, {0},&reftables[218], &reftables[219]),
  6551. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "source_code_info", 9, &msgs[9], (const upb_def*)(&msgs[18]), 22, 5, {0},&reftables[220], &reftables[221]),
  6552. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, true, "span", 2, &msgs[19], NULL, 8, 1, {0},&reftables[222], &reftables[223]),
  6553. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "start", 1, &msgs[2], NULL, 3, 0, {0},&reftables[224], &reftables[225]),
  6554. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "start", 1, &msgs[1], NULL, 3, 0, {0},&reftables[226], &reftables[227]),
  6555. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BYTES, 0, false, false, false, false, "string_value", 7, &msgs[20], NULL, 13, 5, {0},&reftables[228], &reftables[229]),
  6556. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "syntax", 12, &msgs[9], NULL, 40, 11, {0},&reftables[230], &reftables[231]),
  6557. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "trailing_comments", 4, &msgs[19], NULL, 12, 3, {0},&reftables[232], &reftables[233]),
  6558. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "type", 5, &msgs[7], (const upb_def*)(&enums[1]), 13, 5, {0},&reftables[234], &reftables[235]),
  6559. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "type_name", 6, &msgs[7], NULL, 14, 6, {0},&reftables[236], &reftables[237]),
  6560. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[12], (const upb_def*)(&msgs[20]), 6, 0, {0},&reftables[238], &reftables[239]),
  6561. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[17], (const upb_def*)(&msgs[20]), 6, 0, {0},&reftables[240], &reftables[241]),
  6562. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[11], (const upb_def*)(&msgs[20]), 6, 0, {0},&reftables[242], &reftables[243]),
  6563. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[14], (const upb_def*)(&msgs[20]), 6, 0, {0},&reftables[244], &reftables[245]),
  6564. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[8], (const upb_def*)(&msgs[20]), 6, 0, {0},&reftables[246], &reftables[247]),
  6565. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[6], (const upb_def*)(&msgs[20]), 6, 0, {0},&reftables[248], &reftables[249]),
  6566. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[4], (const upb_def*)(&msgs[20]), 6, 0, {0},&reftables[250], &reftables[251]),
  6567. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "value", 2, &msgs[3], (const upb_def*)(&msgs[5]), 7, 0, {0},&reftables[252], &reftables[253]),
  6568. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "weak", 10, &msgs[8], NULL, 12, 6, {0},&reftables[254], &reftables[255]),
  6569. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "weak_dependency", 11, &msgs[9], NULL, 39, 10, {0},&reftables[256], &reftables[257]),
  6570. };
  6571. static const upb_enumdef enums[5] = {
  6572. UPB_ENUMDEF_INIT("google.protobuf.FieldDescriptorProto.Label", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[188]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[154], 4, 3), 0, &reftables[258], &reftables[259]),
  6573. UPB_ENUMDEF_INIT("google.protobuf.FieldDescriptorProto.Type", UPB_STRTABLE_INIT(18, 31, UPB_CTYPE_INT32, 5, &strentries[192]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[158], 19, 18), 0, &reftables[260], &reftables[261]),
  6574. UPB_ENUMDEF_INIT("google.protobuf.FieldOptions.CType", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[224]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[177], 3, 3), 0, &reftables[262], &reftables[263]),
  6575. UPB_ENUMDEF_INIT("google.protobuf.FieldOptions.JSType", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[228]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[180], 3, 3), 0, &reftables[264], &reftables[265]),
  6576. UPB_ENUMDEF_INIT("google.protobuf.FileOptions.OptimizeMode", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[232]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[183], 4, 3), 0, &reftables[266], &reftables[267]),
  6577. };
  6578. static const upb_tabent strentries[236] = {
  6579. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "extension"), UPB_TABVALUE_PTR_INIT(&fields[22]), NULL},
  6580. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6581. {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "reserved_name"), UPB_TABVALUE_PTR_INIT(&fields[84]), NULL},
  6582. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[57]), NULL},
  6583. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6584. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6585. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6586. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "field"), UPB_TABVALUE_PTR_INIT(&fields[25]), &strentries[12]},
  6587. {UPB_TABKEY_STR("\017", "\000", "\000", "\000", "extension_range"), UPB_TABVALUE_PTR_INIT(&fields[24]), &strentries[14]},
  6588. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6589. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "nested_type"), UPB_TABVALUE_PTR_INIT(&fields[60]), NULL},
  6590. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6591. {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "reserved_range"), UPB_TABVALUE_PTR_INIT(&fields[85]), NULL},
  6592. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[68]), NULL},
  6593. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "oneof_decl"), UPB_TABVALUE_PTR_INIT(&fields[65]), NULL},
  6594. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "enum_type"), UPB_TABVALUE_PTR_INIT(&fields[20]), &strentries[13]},
  6595. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "start"), UPB_TABVALUE_PTR_INIT(&fields[91]), NULL},
  6596. {UPB_TABKEY_STR("\003", "\000", "\000", "\000", "end"), UPB_TABVALUE_PTR_INIT(&fields[18]), NULL},
  6597. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6598. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6599. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "start"), UPB_TABVALUE_PTR_INIT(&fields[90]), NULL},
  6600. {UPB_TABKEY_STR("\003", "\000", "\000", "\000", "end"), UPB_TABVALUE_PTR_INIT(&fields[17]), NULL},
  6601. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6602. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6603. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6604. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "value"), UPB_TABVALUE_PTR_INIT(&fields[104]), NULL},
  6605. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[73]), NULL},
  6606. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[52]), &strentries[26]},
  6607. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[103]), NULL},
  6608. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[14]), NULL},
  6609. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "allow_alias"), UPB_TABVALUE_PTR_INIT(&fields[1]), NULL},
  6610. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6611. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "number"), UPB_TABVALUE_PTR_INIT(&fields[63]), NULL},
  6612. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6613. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[74]), NULL},
  6614. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[50]), &strentries[34]},
  6615. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[102]), NULL},
  6616. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[13]), NULL},
  6617. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6618. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6619. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "oneof_index"), UPB_TABVALUE_PTR_INIT(&fields[66]), NULL},
  6620. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "label"), UPB_TABVALUE_PTR_INIT(&fields[40]), NULL},
  6621. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6622. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[56]), NULL},
  6623. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6624. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6625. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6626. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6627. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "number"), UPB_TABVALUE_PTR_INIT(&fields[62]), &strentries[53]},
  6628. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6629. {UPB_TABKEY_STR("\010", "\000", "\000", "\000", "extendee"), UPB_TABVALUE_PTR_INIT(&fields[21]), NULL},
  6630. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "type_name"), UPB_TABVALUE_PTR_INIT(&fields[96]), NULL},
  6631. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "json_name"), UPB_TABVALUE_PTR_INIT(&fields[38]), NULL},
  6632. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "type"), UPB_TABVALUE_PTR_INIT(&fields[95]), &strentries[50]},
  6633. {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "default_value"), UPB_TABVALUE_PTR_INIT(&fields[7]), NULL},
  6634. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[70]), NULL},
  6635. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[101]), NULL},
  6636. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6637. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "weak"), UPB_TABVALUE_PTR_INIT(&fields[105]), NULL},
  6638. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6639. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6640. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6641. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6642. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "packed"), UPB_TABVALUE_PTR_INIT(&fields[77]), NULL},
  6643. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "lazy"), UPB_TABVALUE_PTR_INIT(&fields[41]), NULL},
  6644. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6645. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "ctype"), UPB_TABVALUE_PTR_INIT(&fields[6]), NULL},
  6646. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6647. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "jstype"), UPB_TABVALUE_PTR_INIT(&fields[39]), NULL},
  6648. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[9]), NULL},
  6649. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6650. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6651. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "extension"), UPB_TABVALUE_PTR_INIT(&fields[23]), NULL},
  6652. {UPB_TABKEY_STR("\017", "\000", "\000", "\000", "weak_dependency"), UPB_TABVALUE_PTR_INIT(&fields[106]), NULL},
  6653. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6654. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[51]), NULL},
  6655. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "service"), UPB_TABVALUE_PTR_INIT(&fields[87]), NULL},
  6656. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6657. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "source_code_info"), UPB_TABVALUE_PTR_INIT(&fields[88]), NULL},
  6658. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6659. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6660. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "syntax"), UPB_TABVALUE_PTR_INIT(&fields[93]), NULL},
  6661. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "dependency"), UPB_TABVALUE_PTR_INIT(&fields[8]), NULL},
  6662. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "message_type"), UPB_TABVALUE_PTR_INIT(&fields[47]), NULL},
  6663. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "package"), UPB_TABVALUE_PTR_INIT(&fields[76]), NULL},
  6664. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[69]), &strentries[86]},
  6665. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "enum_type"), UPB_TABVALUE_PTR_INIT(&fields[19]), NULL},
  6666. {UPB_TABKEY_STR("\021", "\000", "\000", "\000", "public_dependency"), UPB_TABVALUE_PTR_INIT(&fields[82]), &strentries[85]},
  6667. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6668. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "file"), UPB_TABVALUE_PTR_INIT(&fields[26]), NULL},
  6669. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6670. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6671. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6672. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6673. {UPB_TABKEY_STR("\023", "\000", "\000", "\000", "cc_generic_services"), UPB_TABVALUE_PTR_INIT(&fields[3]), NULL},
  6674. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "csharp_namespace"), UPB_TABVALUE_PTR_INIT(&fields[5]), &strentries[116]},
  6675. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6676. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6677. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6678. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6679. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6680. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6681. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6682. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "go_package"), UPB_TABVALUE_PTR_INIT(&fields[27]), NULL},
  6683. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "java_package"), UPB_TABVALUE_PTR_INIT(&fields[35]), &strentries[120]},
  6684. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6685. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6686. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "java_outer_classname"), UPB_TABVALUE_PTR_INIT(&fields[34]), NULL},
  6687. {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "php_namespace"), UPB_TABVALUE_PTR_INIT(&fields[80]), &strentries[113]},
  6688. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6689. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6690. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6691. {UPB_TABKEY_STR("\023", "\000", "\000", "\000", "java_multiple_files"), UPB_TABVALUE_PTR_INIT(&fields[33]), &strentries[117]},
  6692. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[99]), NULL},
  6693. {UPB_TABKEY_STR("\025", "\000", "\000", "\000", "java_generic_services"), UPB_TABVALUE_PTR_INIT(&fields[32]), &strentries[118]},
  6694. {UPB_TABKEY_STR("\035", "\000", "\000", "\000", "java_generate_equals_and_hash"), UPB_TABVALUE_PTR_INIT(&fields[31]), NULL},
  6695. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "php_class_prefix"), UPB_TABVALUE_PTR_INIT(&fields[79]), NULL},
  6696. {UPB_TABKEY_STR("\037", "\000", "\000", "\000", "javanano_use_deprecated_package"), UPB_TABVALUE_PTR_INIT(&fields[37]), &strentries[123]},
  6697. {UPB_TABKEY_STR("\023", "\000", "\000", "\000", "py_generic_services"), UPB_TABVALUE_PTR_INIT(&fields[83]), NULL},
  6698. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "optimize_for"), UPB_TABVALUE_PTR_INIT(&fields[67]), NULL},
  6699. {UPB_TABKEY_STR("\026", "\000", "\000", "\000", "java_string_check_utf8"), UPB_TABVALUE_PTR_INIT(&fields[36]), NULL},
  6700. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[12]), &strentries[119]},
  6701. {UPB_TABKEY_STR("\021", "\000", "\000", "\000", "objc_class_prefix"), UPB_TABVALUE_PTR_INIT(&fields[64]), NULL},
  6702. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "cc_enable_arenas"), UPB_TABVALUE_PTR_INIT(&fields[2]), NULL},
  6703. {UPB_TABKEY_STR("\027", "\000", "\000", "\000", "message_set_wire_format"), UPB_TABVALUE_PTR_INIT(&fields[46]), &strentries[128]},
  6704. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6705. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6706. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6707. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[97]), NULL},
  6708. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[11]), NULL},
  6709. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "map_entry"), UPB_TABVALUE_PTR_INIT(&fields[45]), NULL},
  6710. {UPB_TABKEY_STR("\037", "\000", "\000", "\000", "no_standard_descriptor_accessor"), UPB_TABVALUE_PTR_INIT(&fields[61]), NULL},
  6711. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6712. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "client_streaming"), UPB_TABVALUE_PTR_INIT(&fields[4]), NULL},
  6713. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "server_streaming"), UPB_TABVALUE_PTR_INIT(&fields[86]), NULL},
  6714. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[55]), NULL},
  6715. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "input_type"), UPB_TABVALUE_PTR_INIT(&fields[29]), NULL},
  6716. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6717. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "output_type"), UPB_TABVALUE_PTR_INIT(&fields[75]), NULL},
  6718. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[71]), NULL},
  6719. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[100]), NULL},
  6720. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[10]), NULL},
  6721. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6722. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6723. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6724. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6725. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6726. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[54]), NULL},
  6727. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6728. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[72]), &strentries[150]},
  6729. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "method"), UPB_TABVALUE_PTR_INIT(&fields[48]), NULL},
  6730. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[53]), &strentries[149]},
  6731. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[98]), NULL},
  6732. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[15]), NULL},
  6733. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6734. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6735. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6736. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6737. {UPB_TABKEY_STR("\010", "\000", "\000", "\000", "location"), UPB_TABVALUE_PTR_INIT(&fields[44]), NULL},
  6738. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6739. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6740. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6741. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6742. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "span"), UPB_TABVALUE_PTR_INIT(&fields[89]), &strentries[167]},
  6743. {UPB_TABKEY_STR("\031", "\000", "\000", "\000", "leading_detached_comments"), UPB_TABVALUE_PTR_INIT(&fields[43]), &strentries[165]},
  6744. {UPB_TABKEY_STR("\021", "\000", "\000", "\000", "trailing_comments"), UPB_TABVALUE_PTR_INIT(&fields[94]), NULL},
  6745. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "leading_comments"), UPB_TABVALUE_PTR_INIT(&fields[42]), &strentries[164]},
  6746. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "path"), UPB_TABVALUE_PTR_INIT(&fields[78]), NULL},
  6747. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "double_value"), UPB_TABVALUE_PTR_INIT(&fields[16]), NULL},
  6748. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6749. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6750. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[49]), NULL},
  6751. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6752. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6753. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6754. {UPB_TABKEY_STR("\022", "\000", "\000", "\000", "negative_int_value"), UPB_TABVALUE_PTR_INIT(&fields[59]), NULL},
  6755. {UPB_TABKEY_STR("\017", "\000", "\000", "\000", "aggregate_value"), UPB_TABVALUE_PTR_INIT(&fields[0]), NULL},
  6756. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6757. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6758. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6759. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6760. {UPB_TABKEY_STR("\022", "\000", "\000", "\000", "positive_int_value"), UPB_TABVALUE_PTR_INIT(&fields[81]), NULL},
  6761. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "identifier_value"), UPB_TABVALUE_PTR_INIT(&fields[28]), NULL},
  6762. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "string_value"), UPB_TABVALUE_PTR_INIT(&fields[92]), &strentries[182]},
  6763. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6764. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6765. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "is_extension"), UPB_TABVALUE_PTR_INIT(&fields[30]), NULL},
  6766. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "name_part"), UPB_TABVALUE_PTR_INIT(&fields[58]), NULL},
  6767. {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "LABEL_REQUIRED"), UPB_TABVALUE_INT_INIT(2), &strentries[190]},
  6768. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6769. {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "LABEL_REPEATED"), UPB_TABVALUE_INT_INIT(3), NULL},
  6770. {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "LABEL_OPTIONAL"), UPB_TABVALUE_INT_INIT(1), NULL},
  6771. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "TYPE_FIXED64"), UPB_TABVALUE_INT_INIT(6), NULL},
  6772. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6773. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6774. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6775. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6776. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_STRING"), UPB_TABVALUE_INT_INIT(9), NULL},
  6777. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_FLOAT"), UPB_TABVALUE_INT_INIT(2), &strentries[221]},
  6778. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_DOUBLE"), UPB_TABVALUE_INT_INIT(1), NULL},
  6779. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6780. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_INT32"), UPB_TABVALUE_INT_INIT(5), NULL},
  6781. {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "TYPE_SFIXED32"), UPB_TABVALUE_INT_INIT(15), NULL},
  6782. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "TYPE_FIXED32"), UPB_TABVALUE_INT_INIT(7), NULL},
  6783. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6784. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "TYPE_MESSAGE"), UPB_TABVALUE_INT_INIT(11), &strentries[222]},
  6785. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6786. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6787. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_INT64"), UPB_TABVALUE_INT_INIT(3), &strentries[219]},
  6788. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6789. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6790. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6791. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6792. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "TYPE_ENUM"), UPB_TABVALUE_INT_INIT(14), NULL},
  6793. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_UINT32"), UPB_TABVALUE_INT_INIT(13), NULL},
  6794. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6795. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_UINT64"), UPB_TABVALUE_INT_INIT(4), &strentries[218]},
  6796. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6797. {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "TYPE_SFIXED64"), UPB_TABVALUE_INT_INIT(16), NULL},
  6798. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_BYTES"), UPB_TABVALUE_INT_INIT(12), NULL},
  6799. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_SINT64"), UPB_TABVALUE_INT_INIT(18), NULL},
  6800. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "TYPE_BOOL"), UPB_TABVALUE_INT_INIT(8), NULL},
  6801. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_GROUP"), UPB_TABVALUE_INT_INIT(10), NULL},
  6802. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_SINT32"), UPB_TABVALUE_INT_INIT(17), NULL},
  6803. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6804. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "CORD"), UPB_TABVALUE_INT_INIT(1), NULL},
  6805. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "STRING"), UPB_TABVALUE_INT_INIT(0), &strentries[225]},
  6806. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "STRING_PIECE"), UPB_TABVALUE_INT_INIT(2), NULL},
  6807. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6808. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "JS_NORMAL"), UPB_TABVALUE_INT_INIT(0), NULL},
  6809. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "JS_NUMBER"), UPB_TABVALUE_INT_INIT(2), NULL},
  6810. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "JS_STRING"), UPB_TABVALUE_INT_INIT(1), NULL},
  6811. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "CODE_SIZE"), UPB_TABVALUE_INT_INIT(2), NULL},
  6812. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "SPEED"), UPB_TABVALUE_INT_INIT(1), &strentries[235]},
  6813. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6814. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "LITE_RUNTIME"), UPB_TABVALUE_INT_INIT(3), NULL},
  6815. };
  6816. static const upb_tabent intentries[18] = {
  6817. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6818. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[103]), NULL},
  6819. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6820. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[102]), NULL},
  6821. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6822. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[101]), NULL},
  6823. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6824. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[99]), NULL},
  6825. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6826. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[97]), NULL},
  6827. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6828. {UPB_TABKEY_NUM(33), UPB_TABVALUE_PTR_INIT(&fields[10]), NULL},
  6829. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6830. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[100]), NULL},
  6831. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6832. {UPB_TABKEY_NUM(33), UPB_TABVALUE_PTR_INIT(&fields[15]), NULL},
  6833. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6834. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[98]), NULL},
  6835. };
  6836. static const upb_tabval arrays[187] = {
  6837. UPB_TABVALUE_EMPTY_INIT,
  6838. UPB_TABVALUE_PTR_INIT(&fields[57]),
  6839. UPB_TABVALUE_PTR_INIT(&fields[25]),
  6840. UPB_TABVALUE_PTR_INIT(&fields[60]),
  6841. UPB_TABVALUE_PTR_INIT(&fields[20]),
  6842. UPB_TABVALUE_PTR_INIT(&fields[24]),
  6843. UPB_TABVALUE_PTR_INIT(&fields[22]),
  6844. UPB_TABVALUE_PTR_INIT(&fields[68]),
  6845. UPB_TABVALUE_PTR_INIT(&fields[65]),
  6846. UPB_TABVALUE_PTR_INIT(&fields[85]),
  6847. UPB_TABVALUE_PTR_INIT(&fields[84]),
  6848. UPB_TABVALUE_EMPTY_INIT,
  6849. UPB_TABVALUE_PTR_INIT(&fields[91]),
  6850. UPB_TABVALUE_PTR_INIT(&fields[18]),
  6851. UPB_TABVALUE_EMPTY_INIT,
  6852. UPB_TABVALUE_PTR_INIT(&fields[90]),
  6853. UPB_TABVALUE_PTR_INIT(&fields[17]),
  6854. UPB_TABVALUE_EMPTY_INIT,
  6855. UPB_TABVALUE_PTR_INIT(&fields[52]),
  6856. UPB_TABVALUE_PTR_INIT(&fields[104]),
  6857. UPB_TABVALUE_PTR_INIT(&fields[73]),
  6858. UPB_TABVALUE_EMPTY_INIT,
  6859. UPB_TABVALUE_EMPTY_INIT,
  6860. UPB_TABVALUE_PTR_INIT(&fields[1]),
  6861. UPB_TABVALUE_PTR_INIT(&fields[14]),
  6862. UPB_TABVALUE_EMPTY_INIT,
  6863. UPB_TABVALUE_PTR_INIT(&fields[50]),
  6864. UPB_TABVALUE_PTR_INIT(&fields[63]),
  6865. UPB_TABVALUE_PTR_INIT(&fields[74]),
  6866. UPB_TABVALUE_EMPTY_INIT,
  6867. UPB_TABVALUE_PTR_INIT(&fields[13]),
  6868. UPB_TABVALUE_EMPTY_INIT,
  6869. UPB_TABVALUE_PTR_INIT(&fields[56]),
  6870. UPB_TABVALUE_PTR_INIT(&fields[21]),
  6871. UPB_TABVALUE_PTR_INIT(&fields[62]),
  6872. UPB_TABVALUE_PTR_INIT(&fields[40]),
  6873. UPB_TABVALUE_PTR_INIT(&fields[95]),
  6874. UPB_TABVALUE_PTR_INIT(&fields[96]),
  6875. UPB_TABVALUE_PTR_INIT(&fields[7]),
  6876. UPB_TABVALUE_PTR_INIT(&fields[70]),
  6877. UPB_TABVALUE_PTR_INIT(&fields[66]),
  6878. UPB_TABVALUE_PTR_INIT(&fields[38]),
  6879. UPB_TABVALUE_EMPTY_INIT,
  6880. UPB_TABVALUE_PTR_INIT(&fields[6]),
  6881. UPB_TABVALUE_PTR_INIT(&fields[77]),
  6882. UPB_TABVALUE_PTR_INIT(&fields[9]),
  6883. UPB_TABVALUE_EMPTY_INIT,
  6884. UPB_TABVALUE_PTR_INIT(&fields[41]),
  6885. UPB_TABVALUE_PTR_INIT(&fields[39]),
  6886. UPB_TABVALUE_EMPTY_INIT,
  6887. UPB_TABVALUE_EMPTY_INIT,
  6888. UPB_TABVALUE_EMPTY_INIT,
  6889. UPB_TABVALUE_PTR_INIT(&fields[105]),
  6890. UPB_TABVALUE_EMPTY_INIT,
  6891. UPB_TABVALUE_PTR_INIT(&fields[51]),
  6892. UPB_TABVALUE_PTR_INIT(&fields[76]),
  6893. UPB_TABVALUE_PTR_INIT(&fields[8]),
  6894. UPB_TABVALUE_PTR_INIT(&fields[47]),
  6895. UPB_TABVALUE_PTR_INIT(&fields[19]),
  6896. UPB_TABVALUE_PTR_INIT(&fields[87]),
  6897. UPB_TABVALUE_PTR_INIT(&fields[23]),
  6898. UPB_TABVALUE_PTR_INIT(&fields[69]),
  6899. UPB_TABVALUE_PTR_INIT(&fields[88]),
  6900. UPB_TABVALUE_PTR_INIT(&fields[82]),
  6901. UPB_TABVALUE_PTR_INIT(&fields[106]),
  6902. UPB_TABVALUE_PTR_INIT(&fields[93]),
  6903. UPB_TABVALUE_EMPTY_INIT,
  6904. UPB_TABVALUE_PTR_INIT(&fields[26]),
  6905. UPB_TABVALUE_EMPTY_INIT,
  6906. UPB_TABVALUE_PTR_INIT(&fields[35]),
  6907. UPB_TABVALUE_EMPTY_INIT,
  6908. UPB_TABVALUE_EMPTY_INIT,
  6909. UPB_TABVALUE_EMPTY_INIT,
  6910. UPB_TABVALUE_EMPTY_INIT,
  6911. UPB_TABVALUE_EMPTY_INIT,
  6912. UPB_TABVALUE_EMPTY_INIT,
  6913. UPB_TABVALUE_PTR_INIT(&fields[34]),
  6914. UPB_TABVALUE_PTR_INIT(&fields[67]),
  6915. UPB_TABVALUE_PTR_INIT(&fields[33]),
  6916. UPB_TABVALUE_PTR_INIT(&fields[27]),
  6917. UPB_TABVALUE_EMPTY_INIT,
  6918. UPB_TABVALUE_EMPTY_INIT,
  6919. UPB_TABVALUE_EMPTY_INIT,
  6920. UPB_TABVALUE_EMPTY_INIT,
  6921. UPB_TABVALUE_PTR_INIT(&fields[3]),
  6922. UPB_TABVALUE_PTR_INIT(&fields[32]),
  6923. UPB_TABVALUE_PTR_INIT(&fields[83]),
  6924. UPB_TABVALUE_EMPTY_INIT,
  6925. UPB_TABVALUE_PTR_INIT(&fields[31]),
  6926. UPB_TABVALUE_EMPTY_INIT,
  6927. UPB_TABVALUE_EMPTY_INIT,
  6928. UPB_TABVALUE_PTR_INIT(&fields[12]),
  6929. UPB_TABVALUE_EMPTY_INIT,
  6930. UPB_TABVALUE_EMPTY_INIT,
  6931. UPB_TABVALUE_EMPTY_INIT,
  6932. UPB_TABVALUE_PTR_INIT(&fields[36]),
  6933. UPB_TABVALUE_EMPTY_INIT,
  6934. UPB_TABVALUE_EMPTY_INIT,
  6935. UPB_TABVALUE_EMPTY_INIT,
  6936. UPB_TABVALUE_PTR_INIT(&fields[2]),
  6937. UPB_TABVALUE_EMPTY_INIT,
  6938. UPB_TABVALUE_EMPTY_INIT,
  6939. UPB_TABVALUE_EMPTY_INIT,
  6940. UPB_TABVALUE_EMPTY_INIT,
  6941. UPB_TABVALUE_PTR_INIT(&fields[64]),
  6942. UPB_TABVALUE_PTR_INIT(&fields[5]),
  6943. UPB_TABVALUE_PTR_INIT(&fields[37]),
  6944. UPB_TABVALUE_EMPTY_INIT,
  6945. UPB_TABVALUE_PTR_INIT(&fields[79]),
  6946. UPB_TABVALUE_PTR_INIT(&fields[80]),
  6947. UPB_TABVALUE_EMPTY_INIT,
  6948. UPB_TABVALUE_PTR_INIT(&fields[46]),
  6949. UPB_TABVALUE_PTR_INIT(&fields[61]),
  6950. UPB_TABVALUE_PTR_INIT(&fields[11]),
  6951. UPB_TABVALUE_EMPTY_INIT,
  6952. UPB_TABVALUE_EMPTY_INIT,
  6953. UPB_TABVALUE_EMPTY_INIT,
  6954. UPB_TABVALUE_PTR_INIT(&fields[45]),
  6955. UPB_TABVALUE_EMPTY_INIT,
  6956. UPB_TABVALUE_PTR_INIT(&fields[55]),
  6957. UPB_TABVALUE_PTR_INIT(&fields[29]),
  6958. UPB_TABVALUE_PTR_INIT(&fields[75]),
  6959. UPB_TABVALUE_PTR_INIT(&fields[71]),
  6960. UPB_TABVALUE_PTR_INIT(&fields[4]),
  6961. UPB_TABVALUE_PTR_INIT(&fields[86]),
  6962. UPB_TABVALUE_EMPTY_INIT,
  6963. UPB_TABVALUE_EMPTY_INIT,
  6964. UPB_TABVALUE_PTR_INIT(&fields[54]),
  6965. UPB_TABVALUE_EMPTY_INIT,
  6966. UPB_TABVALUE_PTR_INIT(&fields[53]),
  6967. UPB_TABVALUE_PTR_INIT(&fields[48]),
  6968. UPB_TABVALUE_PTR_INIT(&fields[72]),
  6969. UPB_TABVALUE_EMPTY_INIT,
  6970. UPB_TABVALUE_EMPTY_INIT,
  6971. UPB_TABVALUE_PTR_INIT(&fields[44]),
  6972. UPB_TABVALUE_EMPTY_INIT,
  6973. UPB_TABVALUE_PTR_INIT(&fields[78]),
  6974. UPB_TABVALUE_PTR_INIT(&fields[89]),
  6975. UPB_TABVALUE_PTR_INIT(&fields[42]),
  6976. UPB_TABVALUE_PTR_INIT(&fields[94]),
  6977. UPB_TABVALUE_EMPTY_INIT,
  6978. UPB_TABVALUE_PTR_INIT(&fields[43]),
  6979. UPB_TABVALUE_EMPTY_INIT,
  6980. UPB_TABVALUE_EMPTY_INIT,
  6981. UPB_TABVALUE_PTR_INIT(&fields[49]),
  6982. UPB_TABVALUE_PTR_INIT(&fields[28]),
  6983. UPB_TABVALUE_PTR_INIT(&fields[81]),
  6984. UPB_TABVALUE_PTR_INIT(&fields[59]),
  6985. UPB_TABVALUE_PTR_INIT(&fields[16]),
  6986. UPB_TABVALUE_PTR_INIT(&fields[92]),
  6987. UPB_TABVALUE_PTR_INIT(&fields[0]),
  6988. UPB_TABVALUE_EMPTY_INIT,
  6989. UPB_TABVALUE_PTR_INIT(&fields[58]),
  6990. UPB_TABVALUE_PTR_INIT(&fields[30]),
  6991. UPB_TABVALUE_EMPTY_INIT,
  6992. UPB_TABVALUE_PTR_INIT("LABEL_OPTIONAL"),
  6993. UPB_TABVALUE_PTR_INIT("LABEL_REQUIRED"),
  6994. UPB_TABVALUE_PTR_INIT("LABEL_REPEATED"),
  6995. UPB_TABVALUE_EMPTY_INIT,
  6996. UPB_TABVALUE_PTR_INIT("TYPE_DOUBLE"),
  6997. UPB_TABVALUE_PTR_INIT("TYPE_FLOAT"),
  6998. UPB_TABVALUE_PTR_INIT("TYPE_INT64"),
  6999. UPB_TABVALUE_PTR_INIT("TYPE_UINT64"),
  7000. UPB_TABVALUE_PTR_INIT("TYPE_INT32"),
  7001. UPB_TABVALUE_PTR_INIT("TYPE_FIXED64"),
  7002. UPB_TABVALUE_PTR_INIT("TYPE_FIXED32"),
  7003. UPB_TABVALUE_PTR_INIT("TYPE_BOOL"),
  7004. UPB_TABVALUE_PTR_INIT("TYPE_STRING"),
  7005. UPB_TABVALUE_PTR_INIT("TYPE_GROUP"),
  7006. UPB_TABVALUE_PTR_INIT("TYPE_MESSAGE"),
  7007. UPB_TABVALUE_PTR_INIT("TYPE_BYTES"),
  7008. UPB_TABVALUE_PTR_INIT("TYPE_UINT32"),
  7009. UPB_TABVALUE_PTR_INIT("TYPE_ENUM"),
  7010. UPB_TABVALUE_PTR_INIT("TYPE_SFIXED32"),
  7011. UPB_TABVALUE_PTR_INIT("TYPE_SFIXED64"),
  7012. UPB_TABVALUE_PTR_INIT("TYPE_SINT32"),
  7013. UPB_TABVALUE_PTR_INIT("TYPE_SINT64"),
  7014. UPB_TABVALUE_PTR_INIT("STRING"),
  7015. UPB_TABVALUE_PTR_INIT("CORD"),
  7016. UPB_TABVALUE_PTR_INIT("STRING_PIECE"),
  7017. UPB_TABVALUE_PTR_INIT("JS_NORMAL"),
  7018. UPB_TABVALUE_PTR_INIT("JS_STRING"),
  7019. UPB_TABVALUE_PTR_INIT("JS_NUMBER"),
  7020. UPB_TABVALUE_EMPTY_INIT,
  7021. UPB_TABVALUE_PTR_INIT("SPEED"),
  7022. UPB_TABVALUE_PTR_INIT("CODE_SIZE"),
  7023. UPB_TABVALUE_PTR_INIT("LITE_RUNTIME"),
  7024. };
  7025. #ifdef UPB_DEBUG_REFS
  7026. static upb_inttable reftables[268] = {
  7027. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7028. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7029. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7030. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7031. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7032. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7033. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7034. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7035. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7036. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7037. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7038. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7039. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7040. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7041. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7042. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7043. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7044. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7045. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7046. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7047. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7048. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7049. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7050. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7051. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7052. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7053. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7054. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7055. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7056. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7057. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7058. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7059. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7060. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7061. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7062. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7063. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7064. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7065. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7066. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7067. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7068. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7069. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7070. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7071. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7072. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7073. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7074. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7075. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7076. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7077. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7078. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7079. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7080. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7081. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7082. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7083. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7084. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7085. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7086. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7087. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7088. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7089. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7090. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7091. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7092. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7093. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7094. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7095. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7096. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7097. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7098. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7099. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7100. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7101. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7102. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7103. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7104. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7105. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7106. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7107. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7108. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7109. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7110. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7111. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7112. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7113. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7114. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7115. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7116. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7117. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7118. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7119. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7120. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7121. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7122. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7123. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7124. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7125. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7126. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7127. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7128. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7129. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7130. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7131. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7132. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7133. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7134. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7135. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7136. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7137. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7138. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7139. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7140. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7141. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7142. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7143. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7144. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7145. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7146. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7147. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7148. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7149. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7150. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7151. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7152. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7153. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7154. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7155. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7156. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7157. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7158. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7159. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7160. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7161. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7162. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7163. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7164. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7165. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7166. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7167. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7168. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7169. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7170. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7171. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7172. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7173. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7174. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7175. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7176. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7177. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7178. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7179. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7180. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7181. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7182. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7183. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7184. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7185. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7186. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7187. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7188. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7189. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7190. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7191. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7192. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7193. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7194. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7195. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7196. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7197. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7198. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7199. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7200. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7201. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7202. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7203. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7204. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7205. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7206. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7207. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7208. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7209. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7210. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7211. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7212. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7213. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7214. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7215. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7216. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7217. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7218. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7219. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7220. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7221. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7222. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7223. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7224. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7225. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7226. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7227. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7228. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7229. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7230. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7231. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7232. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7233. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7234. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7235. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7236. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7237. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7238. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7239. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7240. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7241. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7242. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7243. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7244. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7245. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7246. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7247. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7248. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7249. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7250. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7251. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7252. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7253. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7254. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7255. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7256. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7257. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7258. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7259. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7260. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7261. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7262. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7263. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7264. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7265. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7266. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7267. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7268. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7269. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7270. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7271. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7272. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7273. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7274. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7275. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7276. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7277. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7278. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7279. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7280. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7281. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7282. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7283. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7284. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7285. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7286. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7287. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7288. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7289. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7290. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7291. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7292. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7293. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7294. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7295. };
  7296. #endif
  7297. static const upb_msgdef *refm(const upb_msgdef *m, const void *owner) {
  7298. upb_msgdef_ref(m, owner);
  7299. return m;
  7300. }
  7301. static const upb_enumdef *refe(const upb_enumdef *e, const void *owner) {
  7302. upb_enumdef_ref(e, owner);
  7303. return e;
  7304. }
  7305. /* Public API. */
  7306. const upb_msgdef *upbdefs_google_protobuf_DescriptorProto_get(const void *owner) { return refm(&msgs[0], owner); }
  7307. const upb_msgdef *upbdefs_google_protobuf_DescriptorProto_ExtensionRange_get(const void *owner) { return refm(&msgs[1], owner); }
  7308. const upb_msgdef *upbdefs_google_protobuf_DescriptorProto_ReservedRange_get(const void *owner) { return refm(&msgs[2], owner); }
  7309. const upb_msgdef *upbdefs_google_protobuf_EnumDescriptorProto_get(const void *owner) { return refm(&msgs[3], owner); }
  7310. const upb_msgdef *upbdefs_google_protobuf_EnumOptions_get(const void *owner) { return refm(&msgs[4], owner); }
  7311. const upb_msgdef *upbdefs_google_protobuf_EnumValueDescriptorProto_get(const void *owner) { return refm(&msgs[5], owner); }
  7312. const upb_msgdef *upbdefs_google_protobuf_EnumValueOptions_get(const void *owner) { return refm(&msgs[6], owner); }
  7313. const upb_msgdef *upbdefs_google_protobuf_FieldDescriptorProto_get(const void *owner) { return refm(&msgs[7], owner); }
  7314. const upb_msgdef *upbdefs_google_protobuf_FieldOptions_get(const void *owner) { return refm(&msgs[8], owner); }
  7315. const upb_msgdef *upbdefs_google_protobuf_FileDescriptorProto_get(const void *owner) { return refm(&msgs[9], owner); }
  7316. const upb_msgdef *upbdefs_google_protobuf_FileDescriptorSet_get(const void *owner) { return refm(&msgs[10], owner); }
  7317. const upb_msgdef *upbdefs_google_protobuf_FileOptions_get(const void *owner) { return refm(&msgs[11], owner); }
  7318. const upb_msgdef *upbdefs_google_protobuf_MessageOptions_get(const void *owner) { return refm(&msgs[12], owner); }
  7319. const upb_msgdef *upbdefs_google_protobuf_MethodDescriptorProto_get(const void *owner) { return refm(&msgs[13], owner); }
  7320. const upb_msgdef *upbdefs_google_protobuf_MethodOptions_get(const void *owner) { return refm(&msgs[14], owner); }
  7321. const upb_msgdef *upbdefs_google_protobuf_OneofDescriptorProto_get(const void *owner) { return refm(&msgs[15], owner); }
  7322. const upb_msgdef *upbdefs_google_protobuf_ServiceDescriptorProto_get(const void *owner) { return refm(&msgs[16], owner); }
  7323. const upb_msgdef *upbdefs_google_protobuf_ServiceOptions_get(const void *owner) { return refm(&msgs[17], owner); }
  7324. const upb_msgdef *upbdefs_google_protobuf_SourceCodeInfo_get(const void *owner) { return refm(&msgs[18], owner); }
  7325. const upb_msgdef *upbdefs_google_protobuf_SourceCodeInfo_Location_get(const void *owner) { return refm(&msgs[19], owner); }
  7326. const upb_msgdef *upbdefs_google_protobuf_UninterpretedOption_get(const void *owner) { return refm(&msgs[20], owner); }
  7327. const upb_msgdef *upbdefs_google_protobuf_UninterpretedOption_NamePart_get(const void *owner) { return refm(&msgs[21], owner); }
  7328. const upb_enumdef *upbdefs_google_protobuf_FieldDescriptorProto_Label_get(const void *owner) { return refe(&enums[0], owner); }
  7329. const upb_enumdef *upbdefs_google_protobuf_FieldDescriptorProto_Type_get(const void *owner) { return refe(&enums[1], owner); }
  7330. const upb_enumdef *upbdefs_google_protobuf_FieldOptions_CType_get(const void *owner) { return refe(&enums[2], owner); }
  7331. const upb_enumdef *upbdefs_google_protobuf_FieldOptions_JSType_get(const void *owner) { return refe(&enums[3], owner); }
  7332. const upb_enumdef *upbdefs_google_protobuf_FileOptions_OptimizeMode_get(const void *owner) { return refe(&enums[4], owner); }
  7333. /*
  7334. ** XXX: The routines in this file that consume a string do not currently
  7335. ** support having the string span buffers. In the future, as upb_sink and
  7336. ** its buffering/sharing functionality evolve there should be an easy and
  7337. ** idiomatic way of correctly handling this case. For now, we accept this
  7338. ** limitation since we currently only parse descriptors from single strings.
  7339. */
  7340. #include <errno.h>
  7341. #include <stdlib.h>
  7342. #include <string.h>
  7343. /* Compares a NULL-terminated string with a non-NULL-terminated string. */
  7344. static bool upb_streq(const char *str, const char *buf, size_t n) {
  7345. return strlen(str) == n && memcmp(str, buf, n) == 0;
  7346. }
  7347. /* We keep a stack of all the messages scopes we are currently in, as well as
  7348. * the top-level file scope. This is necessary to correctly qualify the
  7349. * definitions that are contained inside. "name" tracks the name of the
  7350. * message or package (a bare name -- not qualified by any enclosing scopes). */
  7351. typedef struct {
  7352. char *name;
  7353. /* Index of the first def that is under this scope. For msgdefs, the
  7354. * msgdef itself is at start-1. */
  7355. int start;
  7356. uint32_t oneof_start;
  7357. uint32_t oneof_index;
  7358. } upb_descreader_frame;
  7359. /* The maximum number of nested declarations that are allowed, ie.
  7360. * message Foo {
  7361. * message Bar {
  7362. * message Baz {
  7363. * }
  7364. * }
  7365. * }
  7366. *
  7367. * This is a resource limit that affects how big our runtime stack can grow.
  7368. * TODO: make this a runtime-settable property of the Reader instance. */
  7369. #define UPB_MAX_MESSAGE_NESTING 64
  7370. struct upb_descreader {
  7371. upb_sink sink;
  7372. upb_inttable files;
  7373. upb_strtable files_by_name;
  7374. upb_filedef *file; /* The last file in files. */
  7375. upb_descreader_frame stack[UPB_MAX_MESSAGE_NESTING];
  7376. int stack_len;
  7377. upb_inttable oneofs;
  7378. uint32_t number;
  7379. char *name;
  7380. bool saw_number;
  7381. bool saw_name;
  7382. char *default_string;
  7383. upb_fielddef *f;
  7384. };
  7385. static char *upb_gstrndup(const char *buf, size_t n) {
  7386. char *ret = upb_gmalloc(n + 1);
  7387. if (!ret) return NULL;
  7388. memcpy(ret, buf, n);
  7389. ret[n] = '\0';
  7390. return ret;
  7391. }
  7392. /* Returns a newly allocated string that joins input strings together, for
  7393. * example:
  7394. * join("Foo.Bar", "Baz") -> "Foo.Bar.Baz"
  7395. * join("", "Baz") -> "Baz"
  7396. * Caller owns a ref on the returned string. */
  7397. static char *upb_join(const char *base, const char *name) {
  7398. if (!base || strlen(base) == 0) {
  7399. return upb_gstrdup(name);
  7400. } else {
  7401. char *ret = upb_gmalloc(strlen(base) + strlen(name) + 2);
  7402. if (!ret) {
  7403. return NULL;
  7404. }
  7405. ret[0] = '\0';
  7406. strcat(ret, base);
  7407. strcat(ret, ".");
  7408. strcat(ret, name);
  7409. return ret;
  7410. }
  7411. }
  7412. /* Qualify the defname for all defs starting with offset "start" with "str". */
  7413. static bool upb_descreader_qualify(upb_filedef *f, char *str, int32_t start) {
  7414. size_t i;
  7415. for (i = start; i < upb_filedef_defcount(f); i++) {
  7416. upb_def *def = upb_filedef_mutabledef(f, i);
  7417. char *name = upb_join(str, upb_def_fullname(def));
  7418. if (!name) {
  7419. /* Need better logic here; at this point we've qualified some names but
  7420. * not others. */
  7421. return false;
  7422. }
  7423. upb_def_setfullname(def, name, NULL);
  7424. upb_gfree(name);
  7425. }
  7426. return true;
  7427. }
  7428. /* upb_descreader ************************************************************/
  7429. static upb_msgdef *upb_descreader_top(upb_descreader *r) {
  7430. int index;
  7431. UPB_ASSERT(r->stack_len > 1);
  7432. index = r->stack[r->stack_len-1].start - 1;
  7433. UPB_ASSERT(index >= 0);
  7434. return upb_downcast_msgdef_mutable(upb_filedef_mutabledef(r->file, index));
  7435. }
  7436. static upb_def *upb_descreader_last(upb_descreader *r) {
  7437. return upb_filedef_mutabledef(r->file, upb_filedef_defcount(r->file) - 1);
  7438. }
  7439. /* Start/end handlers for FileDescriptorProto and DescriptorProto (the two
  7440. * entities that have names and can contain sub-definitions. */
  7441. void upb_descreader_startcontainer(upb_descreader *r) {
  7442. upb_descreader_frame *f = &r->stack[r->stack_len++];
  7443. f->start = upb_filedef_defcount(r->file);
  7444. f->oneof_start = upb_inttable_count(&r->oneofs);
  7445. f->oneof_index = 0;
  7446. f->name = NULL;
  7447. }
  7448. bool upb_descreader_endcontainer(upb_descreader *r) {
  7449. upb_descreader_frame *f = &r->stack[r->stack_len - 1];
  7450. while (upb_inttable_count(&r->oneofs) > f->oneof_start) {
  7451. upb_oneofdef *o = upb_value_getptr(upb_inttable_pop(&r->oneofs));
  7452. bool ok = upb_msgdef_addoneof(upb_descreader_top(r), o, &r->oneofs, NULL);
  7453. UPB_ASSERT(ok);
  7454. }
  7455. if (!upb_descreader_qualify(r->file, f->name, f->start)) {
  7456. return false;
  7457. }
  7458. upb_gfree(f->name);
  7459. f->name = NULL;
  7460. r->stack_len--;
  7461. return true;
  7462. }
  7463. void upb_descreader_setscopename(upb_descreader *r, char *str) {
  7464. upb_descreader_frame *f = &r->stack[r->stack_len-1];
  7465. upb_gfree(f->name);
  7466. f->name = str;
  7467. }
  7468. static upb_oneofdef *upb_descreader_getoneof(upb_descreader *r,
  7469. uint32_t index) {
  7470. bool found;
  7471. upb_value val;
  7472. upb_descreader_frame *f = &r->stack[r->stack_len-1];
  7473. /* DescriptorProto messages can be nested, so we will see the nested messages
  7474. * between when we see the FieldDescriptorProto and the OneofDescriptorProto.
  7475. * We need to preserve the oneofs in between these two things. */
  7476. index += f->oneof_start;
  7477. while (upb_inttable_count(&r->oneofs) <= index) {
  7478. upb_inttable_push(&r->oneofs, upb_value_ptr(upb_oneofdef_new(&r->oneofs)));
  7479. }
  7480. found = upb_inttable_lookup(&r->oneofs, index, &val);
  7481. UPB_ASSERT(found);
  7482. return upb_value_getptr(val);
  7483. }
  7484. /** Handlers for google.protobuf.FileDescriptorSet. ***************************/
  7485. static void *fileset_startfile(void *closure, const void *hd) {
  7486. upb_descreader *r = closure;
  7487. UPB_UNUSED(hd);
  7488. r->file = upb_filedef_new(&r->files);
  7489. upb_inttable_push(&r->files, upb_value_ptr(r->file));
  7490. return r;
  7491. }
  7492. /** Handlers for google.protobuf.FileDescriptorProto. *************************/
  7493. static bool file_start(void *closure, const void *hd) {
  7494. upb_descreader *r = closure;
  7495. UPB_UNUSED(hd);
  7496. upb_descreader_startcontainer(r);
  7497. return true;
  7498. }
  7499. static bool file_end(void *closure, const void *hd, upb_status *status) {
  7500. upb_descreader *r = closure;
  7501. UPB_UNUSED(hd);
  7502. UPB_UNUSED(status);
  7503. return upb_descreader_endcontainer(r);
  7504. }
  7505. static size_t file_onname(void *closure, const void *hd, const char *buf,
  7506. size_t n, const upb_bufhandle *handle) {
  7507. upb_descreader *r = closure;
  7508. char *name;
  7509. bool ok;
  7510. UPB_UNUSED(hd);
  7511. UPB_UNUSED(handle);
  7512. name = upb_gstrndup(buf, n);
  7513. upb_strtable_insert(&r->files_by_name, name, upb_value_ptr(r->file));
  7514. /* XXX: see comment at the top of the file. */
  7515. ok = upb_filedef_setname(r->file, name, NULL);
  7516. upb_gfree(name);
  7517. UPB_ASSERT(ok);
  7518. return n;
  7519. }
  7520. static size_t file_onpackage(void *closure, const void *hd, const char *buf,
  7521. size_t n, const upb_bufhandle *handle) {
  7522. upb_descreader *r = closure;
  7523. char *package;
  7524. bool ok;
  7525. UPB_UNUSED(hd);
  7526. UPB_UNUSED(handle);
  7527. package = upb_gstrndup(buf, n);
  7528. /* XXX: see comment at the top of the file. */
  7529. upb_descreader_setscopename(r, package);
  7530. ok = upb_filedef_setpackage(r->file, package, NULL);
  7531. UPB_ASSERT(ok);
  7532. return n;
  7533. }
  7534. static void *file_startphpnamespace(void *closure, const void *hd,
  7535. size_t size_hint) {
  7536. upb_descreader *r = closure;
  7537. bool ok;
  7538. UPB_UNUSED(hd);
  7539. UPB_UNUSED(size_hint);
  7540. ok = upb_filedef_setphpnamespace(r->file, "", NULL);
  7541. UPB_ASSERT(ok);
  7542. return closure;
  7543. }
  7544. static size_t file_onphpnamespace(void *closure, const void *hd,
  7545. const char *buf, size_t n,
  7546. const upb_bufhandle *handle) {
  7547. upb_descreader *r = closure;
  7548. char *php_namespace;
  7549. bool ok;
  7550. UPB_UNUSED(hd);
  7551. UPB_UNUSED(handle);
  7552. php_namespace = upb_gstrndup(buf, n);
  7553. ok = upb_filedef_setphpnamespace(r->file, php_namespace, NULL);
  7554. upb_gfree(php_namespace);
  7555. UPB_ASSERT(ok);
  7556. return n;
  7557. }
  7558. static size_t file_onphpprefix(void *closure, const void *hd, const char *buf,
  7559. size_t n, const upb_bufhandle *handle) {
  7560. upb_descreader *r = closure;
  7561. char *prefix;
  7562. bool ok;
  7563. UPB_UNUSED(hd);
  7564. UPB_UNUSED(handle);
  7565. prefix = upb_gstrndup(buf, n);
  7566. ok = upb_filedef_setphpprefix(r->file, prefix, NULL);
  7567. upb_gfree(prefix);
  7568. UPB_ASSERT(ok);
  7569. return n;
  7570. }
  7571. static size_t file_onsyntax(void *closure, const void *hd, const char *buf,
  7572. size_t n, const upb_bufhandle *handle) {
  7573. upb_descreader *r = closure;
  7574. bool ok;
  7575. UPB_UNUSED(hd);
  7576. UPB_UNUSED(handle);
  7577. /* XXX: see comment at the top of the file. */
  7578. if (upb_streq("proto2", buf, n)) {
  7579. ok = upb_filedef_setsyntax(r->file, UPB_SYNTAX_PROTO2, NULL);
  7580. } else if (upb_streq("proto3", buf, n)) {
  7581. ok = upb_filedef_setsyntax(r->file, UPB_SYNTAX_PROTO3, NULL);
  7582. } else {
  7583. ok = false;
  7584. }
  7585. UPB_ASSERT(ok);
  7586. return n;
  7587. }
  7588. static void *file_startmsg(void *closure, const void *hd) {
  7589. upb_descreader *r = closure;
  7590. upb_msgdef *m = upb_msgdef_new(&m);
  7591. bool ok = upb_filedef_addmsg(r->file, m, &m, NULL);
  7592. UPB_UNUSED(hd);
  7593. UPB_ASSERT(ok);
  7594. return r;
  7595. }
  7596. static void *file_startenum(void *closure, const void *hd) {
  7597. upb_descreader *r = closure;
  7598. upb_enumdef *e = upb_enumdef_new(&e);
  7599. bool ok = upb_filedef_addenum(r->file, e, &e, NULL);
  7600. UPB_UNUSED(hd);
  7601. UPB_ASSERT(ok);
  7602. return r;
  7603. }
  7604. static void *file_startext(void *closure, const void *hd) {
  7605. upb_descreader *r = closure;
  7606. bool ok;
  7607. r->f = upb_fielddef_new(r);
  7608. ok = upb_filedef_addext(r->file, r->f, r, NULL);
  7609. UPB_UNUSED(hd);
  7610. UPB_ASSERT(ok);
  7611. return r;
  7612. }
  7613. static size_t file_ondep(void *closure, const void *hd, const char *buf,
  7614. size_t n, const upb_bufhandle *handle) {
  7615. upb_descreader *r = closure;
  7616. upb_value val;
  7617. if (upb_strtable_lookup2(&r->files_by_name, buf, n, &val)) {
  7618. upb_filedef_adddep(r->file, upb_value_getptr(val));
  7619. }
  7620. UPB_UNUSED(hd);
  7621. UPB_UNUSED(handle);
  7622. return n;
  7623. }
  7624. /** Handlers for google.protobuf.EnumValueDescriptorProto. *********************/
  7625. static bool enumval_startmsg(void *closure, const void *hd) {
  7626. upb_descreader *r = closure;
  7627. UPB_UNUSED(hd);
  7628. r->saw_number = false;
  7629. r->saw_name = false;
  7630. return true;
  7631. }
  7632. static size_t enumval_onname(void *closure, const void *hd, const char *buf,
  7633. size_t n, const upb_bufhandle *handle) {
  7634. upb_descreader *r = closure;
  7635. UPB_UNUSED(hd);
  7636. UPB_UNUSED(handle);
  7637. /* XXX: see comment at the top of the file. */
  7638. upb_gfree(r->name);
  7639. r->name = upb_gstrndup(buf, n);
  7640. r->saw_name = true;
  7641. return n;
  7642. }
  7643. static bool enumval_onnumber(void *closure, const void *hd, int32_t val) {
  7644. upb_descreader *r = closure;
  7645. UPB_UNUSED(hd);
  7646. r->number = val;
  7647. r->saw_number = true;
  7648. return true;
  7649. }
  7650. static bool enumval_endmsg(void *closure, const void *hd, upb_status *status) {
  7651. upb_descreader *r = closure;
  7652. upb_enumdef *e;
  7653. UPB_UNUSED(hd);
  7654. if(!r->saw_number || !r->saw_name) {
  7655. upb_status_seterrmsg(status, "Enum value missing name or number.");
  7656. return false;
  7657. }
  7658. e = upb_downcast_enumdef_mutable(upb_descreader_last(r));
  7659. upb_enumdef_addval(e, r->name, r->number, status);
  7660. upb_gfree(r->name);
  7661. r->name = NULL;
  7662. return true;
  7663. }
  7664. /** Handlers for google.protobuf.EnumDescriptorProto. *************************/
  7665. static bool enum_endmsg(void *closure, const void *hd, upb_status *status) {
  7666. upb_descreader *r = closure;
  7667. upb_enumdef *e;
  7668. UPB_UNUSED(hd);
  7669. e = upb_downcast_enumdef_mutable(upb_descreader_last(r));
  7670. if (upb_def_fullname(upb_descreader_last(r)) == NULL) {
  7671. upb_status_seterrmsg(status, "Enum had no name.");
  7672. return false;
  7673. }
  7674. if (upb_enumdef_numvals(e) == 0) {
  7675. upb_status_seterrmsg(status, "Enum had no values.");
  7676. return false;
  7677. }
  7678. return true;
  7679. }
  7680. static size_t enum_onname(void *closure, const void *hd, const char *buf,
  7681. size_t n, const upb_bufhandle *handle) {
  7682. upb_descreader *r = closure;
  7683. char *fullname = upb_gstrndup(buf, n);
  7684. UPB_UNUSED(hd);
  7685. UPB_UNUSED(handle);
  7686. /* XXX: see comment at the top of the file. */
  7687. upb_def_setfullname(upb_descreader_last(r), fullname, NULL);
  7688. upb_gfree(fullname);
  7689. return n;
  7690. }
  7691. /** Handlers for google.protobuf.FieldDescriptorProto *************************/
  7692. static bool field_startmsg(void *closure, const void *hd) {
  7693. upb_descreader *r = closure;
  7694. UPB_UNUSED(hd);
  7695. UPB_ASSERT(r->f);
  7696. upb_gfree(r->default_string);
  7697. r->default_string = NULL;
  7698. /* fielddefs default to packed, but descriptors default to non-packed. */
  7699. upb_fielddef_setpacked(r->f, false);
  7700. return true;
  7701. }
  7702. /* Converts the default value in string "str" into "d". Passes a ref on str.
  7703. * Returns true on success. */
  7704. static bool parse_default(char *str, upb_fielddef *f) {
  7705. bool success = true;
  7706. char *end;
  7707. switch (upb_fielddef_type(f)) {
  7708. case UPB_TYPE_INT32: {
  7709. long val = strtol(str, &end, 0);
  7710. if (val > INT32_MAX || val < INT32_MIN || errno == ERANGE || *end)
  7711. success = false;
  7712. else
  7713. upb_fielddef_setdefaultint32(f, val);
  7714. break;
  7715. }
  7716. case UPB_TYPE_INT64: {
  7717. /* XXX: Need to write our own strtoll, since it's not available in c89. */
  7718. long long val = strtol(str, &end, 0);
  7719. if (val > INT64_MAX || val < INT64_MIN || errno == ERANGE || *end)
  7720. success = false;
  7721. else
  7722. upb_fielddef_setdefaultint64(f, val);
  7723. break;
  7724. }
  7725. case UPB_TYPE_UINT32: {
  7726. unsigned long val = strtoul(str, &end, 0);
  7727. if (val > UINT32_MAX || errno == ERANGE || *end)
  7728. success = false;
  7729. else
  7730. upb_fielddef_setdefaultuint32(f, val);
  7731. break;
  7732. }
  7733. case UPB_TYPE_UINT64: {
  7734. /* XXX: Need to write our own strtoull, since it's not available in c89. */
  7735. unsigned long long val = strtoul(str, &end, 0);
  7736. if (val > UINT64_MAX || errno == ERANGE || *end)
  7737. success = false;
  7738. else
  7739. upb_fielddef_setdefaultuint64(f, val);
  7740. break;
  7741. }
  7742. case UPB_TYPE_DOUBLE: {
  7743. double val = strtod(str, &end);
  7744. if (errno == ERANGE || *end)
  7745. success = false;
  7746. else
  7747. upb_fielddef_setdefaultdouble(f, val);
  7748. break;
  7749. }
  7750. case UPB_TYPE_FLOAT: {
  7751. /* XXX: Need to write our own strtof, since it's not available in c89. */
  7752. float val = strtod(str, &end);
  7753. if (errno == ERANGE || *end)
  7754. success = false;
  7755. else
  7756. upb_fielddef_setdefaultfloat(f, val);
  7757. break;
  7758. }
  7759. case UPB_TYPE_BOOL: {
  7760. if (strcmp(str, "false") == 0)
  7761. upb_fielddef_setdefaultbool(f, false);
  7762. else if (strcmp(str, "true") == 0)
  7763. upb_fielddef_setdefaultbool(f, true);
  7764. else
  7765. success = false;
  7766. break;
  7767. }
  7768. default: abort();
  7769. }
  7770. return success;
  7771. }
  7772. static bool field_endmsg(void *closure, const void *hd, upb_status *status) {
  7773. upb_descreader *r = closure;
  7774. upb_fielddef *f = r->f;
  7775. UPB_UNUSED(hd);
  7776. /* TODO: verify that all required fields were present. */
  7777. UPB_ASSERT(upb_fielddef_number(f) != 0);
  7778. UPB_ASSERT(upb_fielddef_name(f) != NULL);
  7779. UPB_ASSERT((upb_fielddef_subdefname(f) != NULL) == upb_fielddef_hassubdef(f));
  7780. if (r->default_string) {
  7781. if (upb_fielddef_issubmsg(f)) {
  7782. upb_status_seterrmsg(status, "Submessages cannot have defaults.");
  7783. return false;
  7784. }
  7785. if (upb_fielddef_isstring(f) || upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  7786. upb_fielddef_setdefaultcstr(f, r->default_string, NULL);
  7787. } else {
  7788. if (r->default_string && !parse_default(r->default_string, f)) {
  7789. /* We don't worry too much about giving a great error message since the
  7790. * compiler should have ensured this was correct. */
  7791. upb_status_seterrmsg(status, "Error converting default value.");
  7792. return false;
  7793. }
  7794. }
  7795. }
  7796. return true;
  7797. }
  7798. static bool field_onlazy(void *closure, const void *hd, bool val) {
  7799. upb_descreader *r = closure;
  7800. UPB_UNUSED(hd);
  7801. upb_fielddef_setlazy(r->f, val);
  7802. return true;
  7803. }
  7804. static bool field_onpacked(void *closure, const void *hd, bool val) {
  7805. upb_descreader *r = closure;
  7806. UPB_UNUSED(hd);
  7807. upb_fielddef_setpacked(r->f, val);
  7808. return true;
  7809. }
  7810. static bool field_ontype(void *closure, const void *hd, int32_t val) {
  7811. upb_descreader *r = closure;
  7812. UPB_UNUSED(hd);
  7813. upb_fielddef_setdescriptortype(r->f, val);
  7814. return true;
  7815. }
  7816. static bool field_onlabel(void *closure, const void *hd, int32_t val) {
  7817. upb_descreader *r = closure;
  7818. UPB_UNUSED(hd);
  7819. upb_fielddef_setlabel(r->f, val);
  7820. return true;
  7821. }
  7822. static bool field_onnumber(void *closure, const void *hd, int32_t val) {
  7823. upb_descreader *r = closure;
  7824. bool ok;
  7825. UPB_UNUSED(hd);
  7826. ok = upb_fielddef_setnumber(r->f, val, NULL);
  7827. UPB_ASSERT(ok);
  7828. return true;
  7829. }
  7830. static size_t field_onname(void *closure, const void *hd, const char *buf,
  7831. size_t n, const upb_bufhandle *handle) {
  7832. upb_descreader *r = closure;
  7833. char *name = upb_gstrndup(buf, n);
  7834. UPB_UNUSED(hd);
  7835. UPB_UNUSED(handle);
  7836. /* XXX: see comment at the top of the file. */
  7837. upb_fielddef_setname(r->f, name, NULL);
  7838. upb_gfree(name);
  7839. return n;
  7840. }
  7841. static size_t field_ontypename(void *closure, const void *hd, const char *buf,
  7842. size_t n, const upb_bufhandle *handle) {
  7843. upb_descreader *r = closure;
  7844. char *name = upb_gstrndup(buf, n);
  7845. UPB_UNUSED(hd);
  7846. UPB_UNUSED(handle);
  7847. /* XXX: see comment at the top of the file. */
  7848. upb_fielddef_setsubdefname(r->f, name, NULL);
  7849. upb_gfree(name);
  7850. return n;
  7851. }
  7852. static size_t field_onextendee(void *closure, const void *hd, const char *buf,
  7853. size_t n, const upb_bufhandle *handle) {
  7854. upb_descreader *r = closure;
  7855. char *name = upb_gstrndup(buf, n);
  7856. UPB_UNUSED(hd);
  7857. UPB_UNUSED(handle);
  7858. /* XXX: see comment at the top of the file. */
  7859. upb_fielddef_setcontainingtypename(r->f, name, NULL);
  7860. upb_gfree(name);
  7861. return n;
  7862. }
  7863. static size_t field_ondefaultval(void *closure, const void *hd, const char *buf,
  7864. size_t n, const upb_bufhandle *handle) {
  7865. upb_descreader *r = closure;
  7866. UPB_UNUSED(hd);
  7867. UPB_UNUSED(handle);
  7868. /* Have to convert from string to the correct type, but we might not know the
  7869. * type yet, so we save it as a string until the end of the field.
  7870. * XXX: see comment at the top of the file. */
  7871. upb_gfree(r->default_string);
  7872. r->default_string = upb_gstrndup(buf, n);
  7873. return n;
  7874. }
  7875. static bool field_ononeofindex(void *closure, const void *hd, int32_t index) {
  7876. upb_descreader *r = closure;
  7877. upb_oneofdef *o = upb_descreader_getoneof(r, index);
  7878. bool ok = upb_oneofdef_addfield(o, r->f, &r->f, NULL);
  7879. UPB_UNUSED(hd);
  7880. UPB_ASSERT(ok);
  7881. return true;
  7882. }
  7883. /** Handlers for google.protobuf.OneofDescriptorProto. ************************/
  7884. static size_t oneof_name(void *closure, const void *hd, const char *buf,
  7885. size_t n, const upb_bufhandle *handle) {
  7886. upb_descreader *r = closure;
  7887. upb_descreader_frame *f = &r->stack[r->stack_len-1];
  7888. upb_oneofdef *o = upb_descreader_getoneof(r, f->oneof_index++);
  7889. char *name_null_terminated = upb_gstrndup(buf, n);
  7890. bool ok = upb_oneofdef_setname(o, name_null_terminated, NULL);
  7891. UPB_UNUSED(hd);
  7892. UPB_UNUSED(handle);
  7893. UPB_ASSERT(ok);
  7894. free(name_null_terminated);
  7895. return n;
  7896. }
  7897. /** Handlers for google.protobuf.DescriptorProto ******************************/
  7898. static bool msg_start(void *closure, const void *hd) {
  7899. upb_descreader *r = closure;
  7900. UPB_UNUSED(hd);
  7901. upb_descreader_startcontainer(r);
  7902. return true;
  7903. }
  7904. static bool msg_end(void *closure, const void *hd, upb_status *status) {
  7905. upb_descreader *r = closure;
  7906. upb_msgdef *m = upb_descreader_top(r);
  7907. UPB_UNUSED(hd);
  7908. if(!upb_def_fullname(upb_msgdef_upcast_mutable(m))) {
  7909. upb_status_seterrmsg(status, "Encountered message with no name.");
  7910. return false;
  7911. }
  7912. return upb_descreader_endcontainer(r);
  7913. }
  7914. static size_t msg_name(void *closure, const void *hd, const char *buf,
  7915. size_t n, const upb_bufhandle *handle) {
  7916. upb_descreader *r = closure;
  7917. upb_msgdef *m = upb_descreader_top(r);
  7918. /* XXX: see comment at the top of the file. */
  7919. char *name = upb_gstrndup(buf, n);
  7920. UPB_UNUSED(hd);
  7921. UPB_UNUSED(handle);
  7922. upb_def_setfullname(upb_msgdef_upcast_mutable(m), name, NULL);
  7923. upb_descreader_setscopename(r, name); /* Passes ownership of name. */
  7924. return n;
  7925. }
  7926. static void *msg_startmsg(void *closure, const void *hd) {
  7927. upb_descreader *r = closure;
  7928. upb_msgdef *m = upb_msgdef_new(&m);
  7929. bool ok = upb_filedef_addmsg(r->file, m, &m, NULL);
  7930. UPB_UNUSED(hd);
  7931. UPB_ASSERT(ok);
  7932. return r;
  7933. }
  7934. static void *msg_startext(void *closure, const void *hd) {
  7935. upb_descreader *r = closure;
  7936. upb_fielddef *f = upb_fielddef_new(&f);
  7937. bool ok = upb_filedef_addext(r->file, f, &f, NULL);
  7938. UPB_UNUSED(hd);
  7939. UPB_ASSERT(ok);
  7940. return r;
  7941. }
  7942. static void *msg_startfield(void *closure, const void *hd) {
  7943. upb_descreader *r = closure;
  7944. r->f = upb_fielddef_new(&r->f);
  7945. /* We can't add the new field to the message until its name/number are
  7946. * filled in. */
  7947. UPB_UNUSED(hd);
  7948. return r;
  7949. }
  7950. static bool msg_endfield(void *closure, const void *hd) {
  7951. upb_descreader *r = closure;
  7952. upb_msgdef *m = upb_descreader_top(r);
  7953. bool ok;
  7954. UPB_UNUSED(hd);
  7955. /* Oneof fields are added to the msgdef through their oneof, so don't need to
  7956. * be added here. */
  7957. if (upb_fielddef_containingoneof(r->f) == NULL) {
  7958. ok = upb_msgdef_addfield(m, r->f, &r->f, NULL);
  7959. UPB_ASSERT(ok);
  7960. }
  7961. r->f = NULL;
  7962. return true;
  7963. }
  7964. static bool msg_onmapentry(void *closure, const void *hd, bool mapentry) {
  7965. upb_descreader *r = closure;
  7966. upb_msgdef *m = upb_descreader_top(r);
  7967. UPB_UNUSED(hd);
  7968. upb_msgdef_setmapentry(m, mapentry);
  7969. r->f = NULL;
  7970. return true;
  7971. }
  7972. /** Code to register handlers *************************************************/
  7973. #define F(msg, field) upbdefs_google_protobuf_ ## msg ## _f_ ## field(m)
  7974. static void reghandlers(const void *closure, upb_handlers *h) {
  7975. const upb_msgdef *m = upb_handlers_msgdef(h);
  7976. UPB_UNUSED(closure);
  7977. if (upbdefs_google_protobuf_FileDescriptorSet_is(m)) {
  7978. upb_handlers_setstartsubmsg(h, F(FileDescriptorSet, file),
  7979. &fileset_startfile, NULL);
  7980. } else if (upbdefs_google_protobuf_DescriptorProto_is(m)) {
  7981. upb_handlers_setstartmsg(h, &msg_start, NULL);
  7982. upb_handlers_setendmsg(h, &msg_end, NULL);
  7983. upb_handlers_setstring(h, F(DescriptorProto, name), &msg_name, NULL);
  7984. upb_handlers_setstartsubmsg(h, F(DescriptorProto, extension), &msg_startext,
  7985. NULL);
  7986. upb_handlers_setstartsubmsg(h, F(DescriptorProto, nested_type),
  7987. &msg_startmsg, NULL);
  7988. upb_handlers_setstartsubmsg(h, F(DescriptorProto, field),
  7989. &msg_startfield, NULL);
  7990. upb_handlers_setendsubmsg(h, F(DescriptorProto, field),
  7991. &msg_endfield, NULL);
  7992. upb_handlers_setstartsubmsg(h, F(DescriptorProto, enum_type),
  7993. &file_startenum, NULL);
  7994. } else if (upbdefs_google_protobuf_FileDescriptorProto_is(m)) {
  7995. upb_handlers_setstartmsg(h, &file_start, NULL);
  7996. upb_handlers_setendmsg(h, &file_end, NULL);
  7997. upb_handlers_setstring(h, F(FileDescriptorProto, name), &file_onname,
  7998. NULL);
  7999. upb_handlers_setstring(h, F(FileDescriptorProto, package), &file_onpackage,
  8000. NULL);
  8001. upb_handlers_setstring(h, F(FileDescriptorProto, syntax), &file_onsyntax,
  8002. NULL);
  8003. upb_handlers_setstartsubmsg(h, F(FileDescriptorProto, message_type),
  8004. &file_startmsg, NULL);
  8005. upb_handlers_setstartsubmsg(h, F(FileDescriptorProto, enum_type),
  8006. &file_startenum, NULL);
  8007. upb_handlers_setstartsubmsg(h, F(FileDescriptorProto, extension),
  8008. &file_startext, NULL);
  8009. upb_handlers_setstring(h, F(FileDescriptorProto, dependency),
  8010. &file_ondep, NULL);
  8011. } else if (upbdefs_google_protobuf_EnumValueDescriptorProto_is(m)) {
  8012. upb_handlers_setstartmsg(h, &enumval_startmsg, NULL);
  8013. upb_handlers_setendmsg(h, &enumval_endmsg, NULL);
  8014. upb_handlers_setstring(h, F(EnumValueDescriptorProto, name), &enumval_onname, NULL);
  8015. upb_handlers_setint32(h, F(EnumValueDescriptorProto, number), &enumval_onnumber,
  8016. NULL);
  8017. } else if (upbdefs_google_protobuf_EnumDescriptorProto_is(m)) {
  8018. upb_handlers_setendmsg(h, &enum_endmsg, NULL);
  8019. upb_handlers_setstring(h, F(EnumDescriptorProto, name), &enum_onname, NULL);
  8020. } else if (upbdefs_google_protobuf_FieldDescriptorProto_is(m)) {
  8021. upb_handlers_setstartmsg(h, &field_startmsg, NULL);
  8022. upb_handlers_setendmsg(h, &field_endmsg, NULL);
  8023. upb_handlers_setint32(h, F(FieldDescriptorProto, type), &field_ontype,
  8024. NULL);
  8025. upb_handlers_setint32(h, F(FieldDescriptorProto, label), &field_onlabel,
  8026. NULL);
  8027. upb_handlers_setint32(h, F(FieldDescriptorProto, number), &field_onnumber,
  8028. NULL);
  8029. upb_handlers_setstring(h, F(FieldDescriptorProto, name), &field_onname,
  8030. NULL);
  8031. upb_handlers_setstring(h, F(FieldDescriptorProto, type_name),
  8032. &field_ontypename, NULL);
  8033. upb_handlers_setstring(h, F(FieldDescriptorProto, extendee),
  8034. &field_onextendee, NULL);
  8035. upb_handlers_setstring(h, F(FieldDescriptorProto, default_value),
  8036. &field_ondefaultval, NULL);
  8037. upb_handlers_setint32(h, F(FieldDescriptorProto, oneof_index),
  8038. &field_ononeofindex, NULL);
  8039. } else if (upbdefs_google_protobuf_OneofDescriptorProto_is(m)) {
  8040. upb_handlers_setstring(h, F(OneofDescriptorProto, name), &oneof_name, NULL);
  8041. } else if (upbdefs_google_protobuf_FieldOptions_is(m)) {
  8042. upb_handlers_setbool(h, F(FieldOptions, lazy), &field_onlazy, NULL);
  8043. upb_handlers_setbool(h, F(FieldOptions, packed), &field_onpacked, NULL);
  8044. } else if (upbdefs_google_protobuf_MessageOptions_is(m)) {
  8045. upb_handlers_setbool(h, F(MessageOptions, map_entry), &msg_onmapentry, NULL);
  8046. } else if (upbdefs_google_protobuf_FileOptions_is(m)) {
  8047. upb_handlers_setstring(h, F(FileOptions, php_class_prefix),
  8048. &file_onphpprefix, NULL);
  8049. upb_handlers_setstartstr(h, F(FileOptions, php_namespace),
  8050. &file_startphpnamespace, NULL);
  8051. upb_handlers_setstring(h, F(FileOptions, php_namespace),
  8052. &file_onphpnamespace, NULL);
  8053. }
  8054. UPB_ASSERT(upb_ok(upb_handlers_status(h)));
  8055. }
  8056. #undef F
  8057. void descreader_cleanup(void *_r) {
  8058. upb_descreader *r = _r;
  8059. size_t i;
  8060. for (i = 0; i < upb_descreader_filecount(r); i++) {
  8061. upb_filedef_unref(upb_descreader_file(r, i), &r->files);
  8062. }
  8063. upb_gfree(r->name);
  8064. upb_inttable_uninit(&r->files);
  8065. upb_strtable_uninit(&r->files_by_name);
  8066. upb_inttable_uninit(&r->oneofs);
  8067. upb_gfree(r->default_string);
  8068. while (r->stack_len > 0) {
  8069. upb_descreader_frame *f = &r->stack[--r->stack_len];
  8070. upb_gfree(f->name);
  8071. }
  8072. }
  8073. /* Public API ****************************************************************/
  8074. upb_descreader *upb_descreader_create(upb_env *e, const upb_handlers *h) {
  8075. upb_descreader *r = upb_env_malloc(e, sizeof(upb_descreader));
  8076. if (!r || !upb_env_addcleanup(e, descreader_cleanup, r)) {
  8077. return NULL;
  8078. }
  8079. upb_inttable_init(&r->files, UPB_CTYPE_PTR);
  8080. upb_strtable_init(&r->files_by_name, UPB_CTYPE_PTR);
  8081. upb_inttable_init(&r->oneofs, UPB_CTYPE_PTR);
  8082. upb_sink_reset(upb_descreader_input(r), h, r);
  8083. r->stack_len = 0;
  8084. r->name = NULL;
  8085. r->default_string = NULL;
  8086. return r;
  8087. }
  8088. size_t upb_descreader_filecount(const upb_descreader *r) {
  8089. return upb_inttable_count(&r->files);
  8090. }
  8091. upb_filedef *upb_descreader_file(const upb_descreader *r, size_t i) {
  8092. upb_value v;
  8093. if (upb_inttable_lookup(&r->files, i, &v)) {
  8094. return upb_value_getptr(v);
  8095. } else {
  8096. return NULL;
  8097. }
  8098. }
  8099. upb_sink *upb_descreader_input(upb_descreader *r) {
  8100. return &r->sink;
  8101. }
  8102. const upb_handlers *upb_descreader_newhandlers(const void *owner) {
  8103. const upb_msgdef *m = upbdefs_google_protobuf_FileDescriptorSet_get(&m);
  8104. const upb_handlers *h = upb_handlers_newfrozen(m, owner, reghandlers, NULL);
  8105. upb_msgdef_unref(m, &m);
  8106. return h;
  8107. }
  8108. /*
  8109. ** protobuf decoder bytecode compiler
  8110. **
  8111. ** Code to compile a upb::Handlers into bytecode for decoding a protobuf
  8112. ** according to that specific schema and destination handlers.
  8113. **
  8114. ** Compiling to bytecode is always the first step. If we are using the
  8115. ** interpreted decoder we leave it as bytecode and interpret that. If we are
  8116. ** using a JIT decoder we use a code generator to turn the bytecode into native
  8117. ** code, LLVM IR, etc.
  8118. **
  8119. ** Bytecode definition is in decoder.int.h.
  8120. */
  8121. #include <stdarg.h>
  8122. #ifdef UPB_DUMP_BYTECODE
  8123. #include <stdio.h>
  8124. #endif
  8125. #define MAXLABEL 5
  8126. #define EMPTYLABEL -1
  8127. /* mgroup *********************************************************************/
  8128. static void freegroup(upb_refcounted *r) {
  8129. mgroup *g = (mgroup*)r;
  8130. upb_inttable_uninit(&g->methods);
  8131. #ifdef UPB_USE_JIT_X64
  8132. upb_pbdecoder_freejit(g);
  8133. #endif
  8134. upb_gfree(g->bytecode);
  8135. upb_gfree(g);
  8136. }
  8137. static void visitgroup(const upb_refcounted *r, upb_refcounted_visit *visit,
  8138. void *closure) {
  8139. const mgroup *g = (const mgroup*)r;
  8140. upb_inttable_iter i;
  8141. upb_inttable_begin(&i, &g->methods);
  8142. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  8143. upb_pbdecodermethod *method = upb_value_getptr(upb_inttable_iter_value(&i));
  8144. visit(r, upb_pbdecodermethod_upcast(method), closure);
  8145. }
  8146. }
  8147. mgroup *newgroup(const void *owner) {
  8148. mgroup *g = upb_gmalloc(sizeof(*g));
  8149. static const struct upb_refcounted_vtbl vtbl = {visitgroup, freegroup};
  8150. upb_refcounted_init(mgroup_upcast_mutable(g), &vtbl, owner);
  8151. upb_inttable_init(&g->methods, UPB_CTYPE_PTR);
  8152. g->bytecode = NULL;
  8153. g->bytecode_end = NULL;
  8154. return g;
  8155. }
  8156. /* upb_pbdecodermethod ********************************************************/
  8157. static void freemethod(upb_refcounted *r) {
  8158. upb_pbdecodermethod *method = (upb_pbdecodermethod*)r;
  8159. if (method->dest_handlers_) {
  8160. upb_handlers_unref(method->dest_handlers_, method);
  8161. }
  8162. upb_inttable_uninit(&method->dispatch);
  8163. upb_gfree(method);
  8164. }
  8165. static void visitmethod(const upb_refcounted *r, upb_refcounted_visit *visit,
  8166. void *closure) {
  8167. const upb_pbdecodermethod *m = (const upb_pbdecodermethod*)r;
  8168. visit(r, m->group, closure);
  8169. }
  8170. static upb_pbdecodermethod *newmethod(const upb_handlers *dest_handlers,
  8171. mgroup *group) {
  8172. static const struct upb_refcounted_vtbl vtbl = {visitmethod, freemethod};
  8173. upb_pbdecodermethod *ret = upb_gmalloc(sizeof(*ret));
  8174. upb_refcounted_init(upb_pbdecodermethod_upcast_mutable(ret), &vtbl, &ret);
  8175. upb_byteshandler_init(&ret->input_handler_);
  8176. /* The method references the group and vice-versa, in a circular reference. */
  8177. upb_ref2(ret, group);
  8178. upb_ref2(group, ret);
  8179. upb_inttable_insertptr(&group->methods, dest_handlers, upb_value_ptr(ret));
  8180. upb_pbdecodermethod_unref(ret, &ret);
  8181. ret->group = mgroup_upcast_mutable(group);
  8182. ret->dest_handlers_ = dest_handlers;
  8183. ret->is_native_ = false; /* If we JIT, it will update this later. */
  8184. upb_inttable_init(&ret->dispatch, UPB_CTYPE_UINT64);
  8185. if (ret->dest_handlers_) {
  8186. upb_handlers_ref(ret->dest_handlers_, ret);
  8187. }
  8188. return ret;
  8189. }
  8190. const upb_handlers *upb_pbdecodermethod_desthandlers(
  8191. const upb_pbdecodermethod *m) {
  8192. return m->dest_handlers_;
  8193. }
  8194. const upb_byteshandler *upb_pbdecodermethod_inputhandler(
  8195. const upb_pbdecodermethod *m) {
  8196. return &m->input_handler_;
  8197. }
  8198. bool upb_pbdecodermethod_isnative(const upb_pbdecodermethod *m) {
  8199. return m->is_native_;
  8200. }
  8201. const upb_pbdecodermethod *upb_pbdecodermethod_new(
  8202. const upb_pbdecodermethodopts *opts, const void *owner) {
  8203. const upb_pbdecodermethod *ret;
  8204. upb_pbcodecache cache;
  8205. upb_pbcodecache_init(&cache);
  8206. ret = upb_pbcodecache_getdecodermethod(&cache, opts);
  8207. upb_pbdecodermethod_ref(ret, owner);
  8208. upb_pbcodecache_uninit(&cache);
  8209. return ret;
  8210. }
  8211. /* bytecode compiler **********************************************************/
  8212. /* Data used only at compilation time. */
  8213. typedef struct {
  8214. mgroup *group;
  8215. uint32_t *pc;
  8216. int fwd_labels[MAXLABEL];
  8217. int back_labels[MAXLABEL];
  8218. /* For fields marked "lazy", parse them lazily or eagerly? */
  8219. bool lazy;
  8220. } compiler;
  8221. static compiler *newcompiler(mgroup *group, bool lazy) {
  8222. compiler *ret = upb_gmalloc(sizeof(*ret));
  8223. int i;
  8224. ret->group = group;
  8225. ret->lazy = lazy;
  8226. for (i = 0; i < MAXLABEL; i++) {
  8227. ret->fwd_labels[i] = EMPTYLABEL;
  8228. ret->back_labels[i] = EMPTYLABEL;
  8229. }
  8230. return ret;
  8231. }
  8232. static void freecompiler(compiler *c) {
  8233. upb_gfree(c);
  8234. }
  8235. const size_t ptr_words = sizeof(void*) / sizeof(uint32_t);
  8236. /* How many words an instruction is. */
  8237. static int instruction_len(uint32_t instr) {
  8238. switch (getop(instr)) {
  8239. case OP_SETDISPATCH: return 1 + ptr_words;
  8240. case OP_TAGN: return 3;
  8241. case OP_SETBIGGROUPNUM: return 2;
  8242. default: return 1;
  8243. }
  8244. }
  8245. bool op_has_longofs(int32_t instruction) {
  8246. switch (getop(instruction)) {
  8247. case OP_CALL:
  8248. case OP_BRANCH:
  8249. case OP_CHECKDELIM:
  8250. return true;
  8251. /* The "tag" instructions only have 8 bytes available for the jump target,
  8252. * but that is ok because these opcodes only require short jumps. */
  8253. case OP_TAG1:
  8254. case OP_TAG2:
  8255. case OP_TAGN:
  8256. return false;
  8257. default:
  8258. UPB_ASSERT(false);
  8259. return false;
  8260. }
  8261. }
  8262. static int32_t getofs(uint32_t instruction) {
  8263. if (op_has_longofs(instruction)) {
  8264. return (int32_t)instruction >> 8;
  8265. } else {
  8266. return (int8_t)(instruction >> 8);
  8267. }
  8268. }
  8269. static void setofs(uint32_t *instruction, int32_t ofs) {
  8270. if (op_has_longofs(*instruction)) {
  8271. *instruction = getop(*instruction) | ofs << 8;
  8272. } else {
  8273. *instruction = (*instruction & ~0xff00) | ((ofs & 0xff) << 8);
  8274. }
  8275. UPB_ASSERT(getofs(*instruction) == ofs); /* Would fail in cases of overflow. */
  8276. }
  8277. static uint32_t pcofs(compiler *c) { return c->pc - c->group->bytecode; }
  8278. /* Defines a local label at the current PC location. All previous forward
  8279. * references are updated to point to this location. The location is noted
  8280. * for any future backward references. */
  8281. static void label(compiler *c, unsigned int label) {
  8282. int val;
  8283. uint32_t *codep;
  8284. UPB_ASSERT(label < MAXLABEL);
  8285. val = c->fwd_labels[label];
  8286. codep = (val == EMPTYLABEL) ? NULL : c->group->bytecode + val;
  8287. while (codep) {
  8288. int ofs = getofs(*codep);
  8289. setofs(codep, c->pc - codep - instruction_len(*codep));
  8290. codep = ofs ? codep + ofs : NULL;
  8291. }
  8292. c->fwd_labels[label] = EMPTYLABEL;
  8293. c->back_labels[label] = pcofs(c);
  8294. }
  8295. /* Creates a reference to a numbered label; either a forward reference
  8296. * (positive arg) or backward reference (negative arg). For forward references
  8297. * the value returned now is actually a "next" pointer into a linked list of all
  8298. * instructions that use this label and will be patched later when the label is
  8299. * defined with label().
  8300. *
  8301. * The returned value is the offset that should be written into the instruction.
  8302. */
  8303. static int32_t labelref(compiler *c, int label) {
  8304. UPB_ASSERT(label < MAXLABEL);
  8305. if (label == LABEL_DISPATCH) {
  8306. /* No resolving required. */
  8307. return 0;
  8308. } else if (label < 0) {
  8309. /* Backward local label. Relative to the next instruction. */
  8310. uint32_t from = (c->pc + 1) - c->group->bytecode;
  8311. return c->back_labels[-label] - from;
  8312. } else {
  8313. /* Forward local label: prepend to (possibly-empty) linked list. */
  8314. int *lptr = &c->fwd_labels[label];
  8315. int32_t ret = (*lptr == EMPTYLABEL) ? 0 : *lptr - pcofs(c);
  8316. *lptr = pcofs(c);
  8317. return ret;
  8318. }
  8319. }
  8320. static void put32(compiler *c, uint32_t v) {
  8321. mgroup *g = c->group;
  8322. if (c->pc == g->bytecode_end) {
  8323. int ofs = pcofs(c);
  8324. size_t oldsize = g->bytecode_end - g->bytecode;
  8325. size_t newsize = UPB_MAX(oldsize * 2, 64);
  8326. /* TODO(haberman): handle OOM. */
  8327. g->bytecode = upb_grealloc(g->bytecode, oldsize * sizeof(uint32_t),
  8328. newsize * sizeof(uint32_t));
  8329. g->bytecode_end = g->bytecode + newsize;
  8330. c->pc = g->bytecode + ofs;
  8331. }
  8332. *c->pc++ = v;
  8333. }
  8334. static void putop(compiler *c, int op, ...) {
  8335. va_list ap;
  8336. va_start(ap, op);
  8337. switch (op) {
  8338. case OP_SETDISPATCH: {
  8339. uintptr_t ptr = (uintptr_t)va_arg(ap, void*);
  8340. put32(c, OP_SETDISPATCH);
  8341. put32(c, ptr);
  8342. if (sizeof(uintptr_t) > sizeof(uint32_t))
  8343. put32(c, (uint64_t)ptr >> 32);
  8344. break;
  8345. }
  8346. case OP_STARTMSG:
  8347. case OP_ENDMSG:
  8348. case OP_PUSHLENDELIM:
  8349. case OP_POP:
  8350. case OP_SETDELIM:
  8351. case OP_HALT:
  8352. case OP_RET:
  8353. case OP_DISPATCH:
  8354. put32(c, op);
  8355. break;
  8356. case OP_PARSE_DOUBLE:
  8357. case OP_PARSE_FLOAT:
  8358. case OP_PARSE_INT64:
  8359. case OP_PARSE_UINT64:
  8360. case OP_PARSE_INT32:
  8361. case OP_PARSE_FIXED64:
  8362. case OP_PARSE_FIXED32:
  8363. case OP_PARSE_BOOL:
  8364. case OP_PARSE_UINT32:
  8365. case OP_PARSE_SFIXED32:
  8366. case OP_PARSE_SFIXED64:
  8367. case OP_PARSE_SINT32:
  8368. case OP_PARSE_SINT64:
  8369. case OP_STARTSEQ:
  8370. case OP_ENDSEQ:
  8371. case OP_STARTSUBMSG:
  8372. case OP_ENDSUBMSG:
  8373. case OP_STARTSTR:
  8374. case OP_STRING:
  8375. case OP_ENDSTR:
  8376. case OP_PUSHTAGDELIM:
  8377. put32(c, op | va_arg(ap, upb_selector_t) << 8);
  8378. break;
  8379. case OP_SETBIGGROUPNUM:
  8380. put32(c, op);
  8381. put32(c, va_arg(ap, int));
  8382. break;
  8383. case OP_CALL: {
  8384. const upb_pbdecodermethod *method = va_arg(ap, upb_pbdecodermethod *);
  8385. put32(c, op | (method->code_base.ofs - (pcofs(c) + 1)) << 8);
  8386. break;
  8387. }
  8388. case OP_CHECKDELIM:
  8389. case OP_BRANCH: {
  8390. uint32_t instruction = op;
  8391. int label = va_arg(ap, int);
  8392. setofs(&instruction, labelref(c, label));
  8393. put32(c, instruction);
  8394. break;
  8395. }
  8396. case OP_TAG1:
  8397. case OP_TAG2: {
  8398. int label = va_arg(ap, int);
  8399. uint64_t tag = va_arg(ap, uint64_t);
  8400. uint32_t instruction = op | (tag << 16);
  8401. UPB_ASSERT(tag <= 0xffff);
  8402. setofs(&instruction, labelref(c, label));
  8403. put32(c, instruction);
  8404. break;
  8405. }
  8406. case OP_TAGN: {
  8407. int label = va_arg(ap, int);
  8408. uint64_t tag = va_arg(ap, uint64_t);
  8409. uint32_t instruction = op | (upb_value_size(tag) << 16);
  8410. setofs(&instruction, labelref(c, label));
  8411. put32(c, instruction);
  8412. put32(c, tag);
  8413. put32(c, tag >> 32);
  8414. break;
  8415. }
  8416. }
  8417. va_end(ap);
  8418. }
  8419. #if defined(UPB_USE_JIT_X64) || defined(UPB_DUMP_BYTECODE)
  8420. const char *upb_pbdecoder_getopname(unsigned int op) {
  8421. #define QUOTE(x) #x
  8422. #define EXPAND_AND_QUOTE(x) QUOTE(x)
  8423. #define OPNAME(x) OP_##x
  8424. #define OP(x) case OPNAME(x): return EXPAND_AND_QUOTE(OPNAME(x));
  8425. #define T(x) OP(PARSE_##x)
  8426. /* Keep in sync with list in decoder.int.h. */
  8427. switch ((opcode)op) {
  8428. T(DOUBLE) T(FLOAT) T(INT64) T(UINT64) T(INT32) T(FIXED64) T(FIXED32)
  8429. T(BOOL) T(UINT32) T(SFIXED32) T(SFIXED64) T(SINT32) T(SINT64)
  8430. OP(STARTMSG) OP(ENDMSG) OP(STARTSEQ) OP(ENDSEQ) OP(STARTSUBMSG)
  8431. OP(ENDSUBMSG) OP(STARTSTR) OP(STRING) OP(ENDSTR) OP(CALL) OP(RET)
  8432. OP(PUSHLENDELIM) OP(PUSHTAGDELIM) OP(SETDELIM) OP(CHECKDELIM)
  8433. OP(BRANCH) OP(TAG1) OP(TAG2) OP(TAGN) OP(SETDISPATCH) OP(POP)
  8434. OP(SETBIGGROUPNUM) OP(DISPATCH) OP(HALT)
  8435. }
  8436. return "<unknown op>";
  8437. #undef OP
  8438. #undef T
  8439. }
  8440. #endif
  8441. #ifdef UPB_DUMP_BYTECODE
  8442. static void dumpbc(uint32_t *p, uint32_t *end, FILE *f) {
  8443. uint32_t *begin = p;
  8444. while (p < end) {
  8445. fprintf(f, "%p %8tx", p, p - begin);
  8446. uint32_t instr = *p++;
  8447. uint8_t op = getop(instr);
  8448. fprintf(f, " %s", upb_pbdecoder_getopname(op));
  8449. switch ((opcode)op) {
  8450. case OP_SETDISPATCH: {
  8451. const upb_inttable *dispatch;
  8452. memcpy(&dispatch, p, sizeof(void*));
  8453. p += ptr_words;
  8454. const upb_pbdecodermethod *method =
  8455. (void *)((char *)dispatch -
  8456. offsetof(upb_pbdecodermethod, dispatch));
  8457. fprintf(f, " %s", upb_msgdef_fullname(
  8458. upb_handlers_msgdef(method->dest_handlers_)));
  8459. break;
  8460. }
  8461. case OP_DISPATCH:
  8462. case OP_STARTMSG:
  8463. case OP_ENDMSG:
  8464. case OP_PUSHLENDELIM:
  8465. case OP_POP:
  8466. case OP_SETDELIM:
  8467. case OP_HALT:
  8468. case OP_RET:
  8469. break;
  8470. case OP_PARSE_DOUBLE:
  8471. case OP_PARSE_FLOAT:
  8472. case OP_PARSE_INT64:
  8473. case OP_PARSE_UINT64:
  8474. case OP_PARSE_INT32:
  8475. case OP_PARSE_FIXED64:
  8476. case OP_PARSE_FIXED32:
  8477. case OP_PARSE_BOOL:
  8478. case OP_PARSE_UINT32:
  8479. case OP_PARSE_SFIXED32:
  8480. case OP_PARSE_SFIXED64:
  8481. case OP_PARSE_SINT32:
  8482. case OP_PARSE_SINT64:
  8483. case OP_STARTSEQ:
  8484. case OP_ENDSEQ:
  8485. case OP_STARTSUBMSG:
  8486. case OP_ENDSUBMSG:
  8487. case OP_STARTSTR:
  8488. case OP_STRING:
  8489. case OP_ENDSTR:
  8490. case OP_PUSHTAGDELIM:
  8491. fprintf(f, " %d", instr >> 8);
  8492. break;
  8493. case OP_SETBIGGROUPNUM:
  8494. fprintf(f, " %d", *p++);
  8495. break;
  8496. case OP_CHECKDELIM:
  8497. case OP_CALL:
  8498. case OP_BRANCH:
  8499. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  8500. break;
  8501. case OP_TAG1:
  8502. case OP_TAG2: {
  8503. fprintf(f, " tag:0x%x", instr >> 16);
  8504. if (getofs(instr)) {
  8505. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  8506. }
  8507. break;
  8508. }
  8509. case OP_TAGN: {
  8510. uint64_t tag = *p++;
  8511. tag |= (uint64_t)*p++ << 32;
  8512. fprintf(f, " tag:0x%llx", (long long)tag);
  8513. fprintf(f, " n:%d", instr >> 16);
  8514. if (getofs(instr)) {
  8515. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  8516. }
  8517. break;
  8518. }
  8519. }
  8520. fputs("\n", f);
  8521. }
  8522. }
  8523. #endif
  8524. static uint64_t get_encoded_tag(const upb_fielddef *f, int wire_type) {
  8525. uint32_t tag = (upb_fielddef_number(f) << 3) | wire_type;
  8526. uint64_t encoded_tag = upb_vencode32(tag);
  8527. /* No tag should be greater than 5 bytes. */
  8528. UPB_ASSERT(encoded_tag <= 0xffffffffff);
  8529. return encoded_tag;
  8530. }
  8531. static void putchecktag(compiler *c, const upb_fielddef *f,
  8532. int wire_type, int dest) {
  8533. uint64_t tag = get_encoded_tag(f, wire_type);
  8534. switch (upb_value_size(tag)) {
  8535. case 1:
  8536. putop(c, OP_TAG1, dest, tag);
  8537. break;
  8538. case 2:
  8539. putop(c, OP_TAG2, dest, tag);
  8540. break;
  8541. default:
  8542. putop(c, OP_TAGN, dest, tag);
  8543. break;
  8544. }
  8545. }
  8546. static upb_selector_t getsel(const upb_fielddef *f, upb_handlertype_t type) {
  8547. upb_selector_t selector;
  8548. bool ok = upb_handlers_getselector(f, type, &selector);
  8549. UPB_ASSERT(ok);
  8550. return selector;
  8551. }
  8552. /* Takes an existing, primary dispatch table entry and repacks it with a
  8553. * different alternate wire type. Called when we are inserting a secondary
  8554. * dispatch table entry for an alternate wire type. */
  8555. static uint64_t repack(uint64_t dispatch, int new_wt2) {
  8556. uint64_t ofs;
  8557. uint8_t wt1;
  8558. uint8_t old_wt2;
  8559. upb_pbdecoder_unpackdispatch(dispatch, &ofs, &wt1, &old_wt2);
  8560. UPB_ASSERT(old_wt2 == NO_WIRE_TYPE); /* wt2 should not be set yet. */
  8561. return upb_pbdecoder_packdispatch(ofs, wt1, new_wt2);
  8562. }
  8563. /* Marks the current bytecode position as the dispatch target for this message,
  8564. * field, and wire type. */
  8565. static void dispatchtarget(compiler *c, upb_pbdecodermethod *method,
  8566. const upb_fielddef *f, int wire_type) {
  8567. /* Offset is relative to msg base. */
  8568. uint64_t ofs = pcofs(c) - method->code_base.ofs;
  8569. uint32_t fn = upb_fielddef_number(f);
  8570. upb_inttable *d = &method->dispatch;
  8571. upb_value v;
  8572. if (upb_inttable_remove(d, fn, &v)) {
  8573. /* TODO: prioritize based on packed setting in .proto file. */
  8574. uint64_t repacked = repack(upb_value_getuint64(v), wire_type);
  8575. upb_inttable_insert(d, fn, upb_value_uint64(repacked));
  8576. upb_inttable_insert(d, fn + UPB_MAX_FIELDNUMBER, upb_value_uint64(ofs));
  8577. } else {
  8578. uint64_t val = upb_pbdecoder_packdispatch(ofs, wire_type, NO_WIRE_TYPE);
  8579. upb_inttable_insert(d, fn, upb_value_uint64(val));
  8580. }
  8581. }
  8582. static void putpush(compiler *c, const upb_fielddef *f) {
  8583. if (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE) {
  8584. putop(c, OP_PUSHLENDELIM);
  8585. } else {
  8586. uint32_t fn = upb_fielddef_number(f);
  8587. if (fn >= 1 << 24) {
  8588. putop(c, OP_PUSHTAGDELIM, 0);
  8589. putop(c, OP_SETBIGGROUPNUM, fn);
  8590. } else {
  8591. putop(c, OP_PUSHTAGDELIM, fn);
  8592. }
  8593. }
  8594. }
  8595. static upb_pbdecodermethod *find_submethod(const compiler *c,
  8596. const upb_pbdecodermethod *method,
  8597. const upb_fielddef *f) {
  8598. const upb_handlers *sub =
  8599. upb_handlers_getsubhandlers(method->dest_handlers_, f);
  8600. upb_value v;
  8601. return upb_inttable_lookupptr(&c->group->methods, sub, &v)
  8602. ? upb_value_getptr(v)
  8603. : NULL;
  8604. }
  8605. static void putsel(compiler *c, opcode op, upb_selector_t sel,
  8606. const upb_handlers *h) {
  8607. if (upb_handlers_gethandler(h, sel)) {
  8608. putop(c, op, sel);
  8609. }
  8610. }
  8611. /* Puts an opcode to call a callback, but only if a callback actually exists for
  8612. * this field and handler type. */
  8613. static void maybeput(compiler *c, opcode op, const upb_handlers *h,
  8614. const upb_fielddef *f, upb_handlertype_t type) {
  8615. putsel(c, op, getsel(f, type), h);
  8616. }
  8617. static bool haslazyhandlers(const upb_handlers *h, const upb_fielddef *f) {
  8618. if (!upb_fielddef_lazy(f))
  8619. return false;
  8620. return upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STARTSTR)) ||
  8621. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STRING)) ||
  8622. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_ENDSTR));
  8623. }
  8624. /* bytecode compiler code generation ******************************************/
  8625. /* Symbolic names for our local labels. */
  8626. #define LABEL_LOOPSTART 1 /* Top of a repeated field loop. */
  8627. #define LABEL_LOOPBREAK 2 /* To jump out of a repeated loop */
  8628. #define LABEL_FIELD 3 /* Jump backward to find the most recent field. */
  8629. #define LABEL_ENDMSG 4 /* To reach the OP_ENDMSG instr for this msg. */
  8630. /* Generates bytecode to parse a single non-lazy message field. */
  8631. static void generate_msgfield(compiler *c, const upb_fielddef *f,
  8632. upb_pbdecodermethod *method) {
  8633. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  8634. const upb_pbdecodermethod *sub_m = find_submethod(c, method, f);
  8635. int wire_type;
  8636. if (!sub_m) {
  8637. /* Don't emit any code for this field at all; it will be parsed as an
  8638. * unknown field.
  8639. *
  8640. * TODO(haberman): we should change this to parse it as a string field
  8641. * instead. It will probably be faster, but more importantly, once we
  8642. * start vending unknown fields, a field shouldn't be treated as unknown
  8643. * just because it doesn't have subhandlers registered. */
  8644. return;
  8645. }
  8646. label(c, LABEL_FIELD);
  8647. wire_type =
  8648. (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE)
  8649. ? UPB_WIRE_TYPE_DELIMITED
  8650. : UPB_WIRE_TYPE_START_GROUP;
  8651. if (upb_fielddef_isseq(f)) {
  8652. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  8653. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  8654. dispatchtarget(c, method, f, wire_type);
  8655. putop(c, OP_PUSHTAGDELIM, 0);
  8656. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  8657. label(c, LABEL_LOOPSTART);
  8658. putpush(c, f);
  8659. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  8660. putop(c, OP_CALL, sub_m);
  8661. putop(c, OP_POP);
  8662. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  8663. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  8664. putop(c, OP_SETDELIM);
  8665. }
  8666. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  8667. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  8668. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  8669. label(c, LABEL_LOOPBREAK);
  8670. putop(c, OP_POP);
  8671. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  8672. } else {
  8673. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  8674. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  8675. dispatchtarget(c, method, f, wire_type);
  8676. putpush(c, f);
  8677. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  8678. putop(c, OP_CALL, sub_m);
  8679. putop(c, OP_POP);
  8680. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  8681. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  8682. putop(c, OP_SETDELIM);
  8683. }
  8684. }
  8685. }
  8686. /* Generates bytecode to parse a single string or lazy submessage field. */
  8687. static void generate_delimfield(compiler *c, const upb_fielddef *f,
  8688. upb_pbdecodermethod *method) {
  8689. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  8690. label(c, LABEL_FIELD);
  8691. if (upb_fielddef_isseq(f)) {
  8692. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  8693. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  8694. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  8695. putop(c, OP_PUSHTAGDELIM, 0);
  8696. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  8697. label(c, LABEL_LOOPSTART);
  8698. putop(c, OP_PUSHLENDELIM);
  8699. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  8700. /* Need to emit even if no handler to skip past the string. */
  8701. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  8702. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  8703. putop(c, OP_POP);
  8704. putop(c, OP_SETDELIM);
  8705. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  8706. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_LOOPBREAK);
  8707. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  8708. label(c, LABEL_LOOPBREAK);
  8709. putop(c, OP_POP);
  8710. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  8711. } else {
  8712. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  8713. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  8714. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  8715. putop(c, OP_PUSHLENDELIM);
  8716. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  8717. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  8718. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  8719. putop(c, OP_POP);
  8720. putop(c, OP_SETDELIM);
  8721. }
  8722. }
  8723. /* Generates bytecode to parse a single primitive field. */
  8724. static void generate_primitivefield(compiler *c, const upb_fielddef *f,
  8725. upb_pbdecodermethod *method) {
  8726. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  8727. upb_descriptortype_t descriptor_type = upb_fielddef_descriptortype(f);
  8728. opcode parse_type;
  8729. upb_selector_t sel;
  8730. int wire_type;
  8731. label(c, LABEL_FIELD);
  8732. /* From a decoding perspective, ENUM is the same as INT32. */
  8733. if (descriptor_type == UPB_DESCRIPTOR_TYPE_ENUM)
  8734. descriptor_type = UPB_DESCRIPTOR_TYPE_INT32;
  8735. parse_type = (opcode)descriptor_type;
  8736. /* TODO(haberman): generate packed or non-packed first depending on "packed"
  8737. * setting in the fielddef. This will favor (in speed) whichever was
  8738. * specified. */
  8739. UPB_ASSERT((int)parse_type >= 0 && parse_type <= OP_MAX);
  8740. sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  8741. wire_type = upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  8742. if (upb_fielddef_isseq(f)) {
  8743. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  8744. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  8745. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  8746. putop(c, OP_PUSHLENDELIM);
  8747. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); /* Packed */
  8748. label(c, LABEL_LOOPSTART);
  8749. putop(c, parse_type, sel);
  8750. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  8751. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  8752. dispatchtarget(c, method, f, wire_type);
  8753. putop(c, OP_PUSHTAGDELIM, 0);
  8754. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); /* Non-packed */
  8755. label(c, LABEL_LOOPSTART);
  8756. putop(c, parse_type, sel);
  8757. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  8758. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  8759. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  8760. label(c, LABEL_LOOPBREAK);
  8761. putop(c, OP_POP); /* Packed and non-packed join. */
  8762. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  8763. putop(c, OP_SETDELIM); /* Could remove for non-packed by dup ENDSEQ. */
  8764. } else {
  8765. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  8766. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  8767. dispatchtarget(c, method, f, wire_type);
  8768. putop(c, parse_type, sel);
  8769. }
  8770. }
  8771. /* Adds bytecode for parsing the given message to the given decoderplan,
  8772. * while adding all dispatch targets to this message's dispatch table. */
  8773. static void compile_method(compiler *c, upb_pbdecodermethod *method) {
  8774. const upb_handlers *h;
  8775. const upb_msgdef *md;
  8776. uint32_t* start_pc;
  8777. upb_msg_field_iter i;
  8778. upb_value val;
  8779. UPB_ASSERT(method);
  8780. /* Clear all entries in the dispatch table. */
  8781. upb_inttable_uninit(&method->dispatch);
  8782. upb_inttable_init(&method->dispatch, UPB_CTYPE_UINT64);
  8783. h = upb_pbdecodermethod_desthandlers(method);
  8784. md = upb_handlers_msgdef(h);
  8785. method->code_base.ofs = pcofs(c);
  8786. putop(c, OP_SETDISPATCH, &method->dispatch);
  8787. putsel(c, OP_STARTMSG, UPB_STARTMSG_SELECTOR, h);
  8788. label(c, LABEL_FIELD);
  8789. start_pc = c->pc;
  8790. for(upb_msg_field_begin(&i, md);
  8791. !upb_msg_field_done(&i);
  8792. upb_msg_field_next(&i)) {
  8793. const upb_fielddef *f = upb_msg_iter_field(&i);
  8794. upb_fieldtype_t type = upb_fielddef_type(f);
  8795. if (type == UPB_TYPE_MESSAGE && !(haslazyhandlers(h, f) && c->lazy)) {
  8796. generate_msgfield(c, f, method);
  8797. } else if (type == UPB_TYPE_STRING || type == UPB_TYPE_BYTES ||
  8798. type == UPB_TYPE_MESSAGE) {
  8799. generate_delimfield(c, f, method);
  8800. } else {
  8801. generate_primitivefield(c, f, method);
  8802. }
  8803. }
  8804. /* If there were no fields, or if no handlers were defined, we need to
  8805. * generate a non-empty loop body so that we can at least dispatch for unknown
  8806. * fields and check for the end of the message. */
  8807. if (c->pc == start_pc) {
  8808. /* Check for end-of-message. */
  8809. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  8810. /* Unconditionally dispatch. */
  8811. putop(c, OP_DISPATCH, 0);
  8812. }
  8813. /* For now we just loop back to the last field of the message (or if none,
  8814. * the DISPATCH opcode for the message). */
  8815. putop(c, OP_BRANCH, -LABEL_FIELD);
  8816. /* Insert both a label and a dispatch table entry for this end-of-msg. */
  8817. label(c, LABEL_ENDMSG);
  8818. val = upb_value_uint64(pcofs(c) - method->code_base.ofs);
  8819. upb_inttable_insert(&method->dispatch, DISPATCH_ENDMSG, val);
  8820. putsel(c, OP_ENDMSG, UPB_ENDMSG_SELECTOR, h);
  8821. putop(c, OP_RET);
  8822. upb_inttable_compact(&method->dispatch);
  8823. }
  8824. /* Populate "methods" with new upb_pbdecodermethod objects reachable from "h".
  8825. * Returns the method for these handlers.
  8826. *
  8827. * Generates a new method for every destination handlers reachable from "h". */
  8828. static void find_methods(compiler *c, const upb_handlers *h) {
  8829. upb_value v;
  8830. upb_msg_field_iter i;
  8831. const upb_msgdef *md;
  8832. if (upb_inttable_lookupptr(&c->group->methods, h, &v))
  8833. return;
  8834. newmethod(h, c->group);
  8835. /* Find submethods. */
  8836. md = upb_handlers_msgdef(h);
  8837. for(upb_msg_field_begin(&i, md);
  8838. !upb_msg_field_done(&i);
  8839. upb_msg_field_next(&i)) {
  8840. const upb_fielddef *f = upb_msg_iter_field(&i);
  8841. const upb_handlers *sub_h;
  8842. if (upb_fielddef_type(f) == UPB_TYPE_MESSAGE &&
  8843. (sub_h = upb_handlers_getsubhandlers(h, f)) != NULL) {
  8844. /* We only generate a decoder method for submessages with handlers.
  8845. * Others will be parsed as unknown fields. */
  8846. find_methods(c, sub_h);
  8847. }
  8848. }
  8849. }
  8850. /* (Re-)compile bytecode for all messages in "msgs."
  8851. * Overwrites any existing bytecode in "c". */
  8852. static void compile_methods(compiler *c) {
  8853. upb_inttable_iter i;
  8854. /* Start over at the beginning of the bytecode. */
  8855. c->pc = c->group->bytecode;
  8856. upb_inttable_begin(&i, &c->group->methods);
  8857. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  8858. upb_pbdecodermethod *method = upb_value_getptr(upb_inttable_iter_value(&i));
  8859. compile_method(c, method);
  8860. }
  8861. }
  8862. static void set_bytecode_handlers(mgroup *g) {
  8863. upb_inttable_iter i;
  8864. upb_inttable_begin(&i, &g->methods);
  8865. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  8866. upb_pbdecodermethod *m = upb_value_getptr(upb_inttable_iter_value(&i));
  8867. upb_byteshandler *h = &m->input_handler_;
  8868. m->code_base.ptr = g->bytecode + m->code_base.ofs;
  8869. upb_byteshandler_setstartstr(h, upb_pbdecoder_startbc, m->code_base.ptr);
  8870. upb_byteshandler_setstring(h, upb_pbdecoder_decode, g);
  8871. upb_byteshandler_setendstr(h, upb_pbdecoder_end, m);
  8872. }
  8873. }
  8874. /* JIT setup. *****************************************************************/
  8875. #ifdef UPB_USE_JIT_X64
  8876. static void sethandlers(mgroup *g, bool allowjit) {
  8877. g->jit_code = NULL;
  8878. if (allowjit) {
  8879. /* Compile byte-code into machine code, create handlers. */
  8880. upb_pbdecoder_jit(g);
  8881. } else {
  8882. set_bytecode_handlers(g);
  8883. }
  8884. }
  8885. #else /* UPB_USE_JIT_X64 */
  8886. static void sethandlers(mgroup *g, bool allowjit) {
  8887. /* No JIT compiled in; use bytecode handlers unconditionally. */
  8888. UPB_UNUSED(allowjit);
  8889. set_bytecode_handlers(g);
  8890. }
  8891. #endif /* UPB_USE_JIT_X64 */
  8892. /* TODO(haberman): allow this to be constructed for an arbitrary set of dest
  8893. * handlers and other mgroups (but verify we have a transitive closure). */
  8894. const mgroup *mgroup_new(const upb_handlers *dest, bool allowjit, bool lazy,
  8895. const void *owner) {
  8896. mgroup *g;
  8897. compiler *c;
  8898. UPB_UNUSED(allowjit);
  8899. UPB_ASSERT(upb_handlers_isfrozen(dest));
  8900. g = newgroup(owner);
  8901. c = newcompiler(g, lazy);
  8902. find_methods(c, dest);
  8903. /* We compile in two passes:
  8904. * 1. all messages are assigned relative offsets from the beginning of the
  8905. * bytecode (saved in method->code_base).
  8906. * 2. forwards OP_CALL instructions can be correctly linked since message
  8907. * offsets have been previously assigned.
  8908. *
  8909. * Could avoid the second pass by linking OP_CALL instructions somehow. */
  8910. compile_methods(c);
  8911. compile_methods(c);
  8912. g->bytecode_end = c->pc;
  8913. freecompiler(c);
  8914. #ifdef UPB_DUMP_BYTECODE
  8915. {
  8916. FILE *f = fopen("/tmp/upb-bytecode", "w");
  8917. UPB_ASSERT(f);
  8918. dumpbc(g->bytecode, g->bytecode_end, stderr);
  8919. dumpbc(g->bytecode, g->bytecode_end, f);
  8920. fclose(f);
  8921. f = fopen("/tmp/upb-bytecode.bin", "wb");
  8922. UPB_ASSERT(f);
  8923. fwrite(g->bytecode, 1, g->bytecode_end - g->bytecode, f);
  8924. fclose(f);
  8925. }
  8926. #endif
  8927. sethandlers(g, allowjit);
  8928. return g;
  8929. }
  8930. /* upb_pbcodecache ************************************************************/
  8931. void upb_pbcodecache_init(upb_pbcodecache *c) {
  8932. upb_inttable_init(&c->groups, UPB_CTYPE_CONSTPTR);
  8933. c->allow_jit_ = true;
  8934. }
  8935. void upb_pbcodecache_uninit(upb_pbcodecache *c) {
  8936. upb_inttable_iter i;
  8937. upb_inttable_begin(&i, &c->groups);
  8938. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  8939. const mgroup *group = upb_value_getconstptr(upb_inttable_iter_value(&i));
  8940. mgroup_unref(group, c);
  8941. }
  8942. upb_inttable_uninit(&c->groups);
  8943. }
  8944. bool upb_pbcodecache_allowjit(const upb_pbcodecache *c) {
  8945. return c->allow_jit_;
  8946. }
  8947. bool upb_pbcodecache_setallowjit(upb_pbcodecache *c, bool allow) {
  8948. if (upb_inttable_count(&c->groups) > 0)
  8949. return false;
  8950. c->allow_jit_ = allow;
  8951. return true;
  8952. }
  8953. const upb_pbdecodermethod *upb_pbcodecache_getdecodermethod(
  8954. upb_pbcodecache *c, const upb_pbdecodermethodopts *opts) {
  8955. upb_value v;
  8956. bool ok;
  8957. /* Right now we build a new DecoderMethod every time.
  8958. * TODO(haberman): properly cache methods by their true key. */
  8959. const mgroup *g = mgroup_new(opts->handlers, c->allow_jit_, opts->lazy, c);
  8960. upb_inttable_push(&c->groups, upb_value_constptr(g));
  8961. ok = upb_inttable_lookupptr(&g->methods, opts->handlers, &v);
  8962. UPB_ASSERT(ok);
  8963. return upb_value_getptr(v);
  8964. }
  8965. /* upb_pbdecodermethodopts ****************************************************/
  8966. void upb_pbdecodermethodopts_init(upb_pbdecodermethodopts *opts,
  8967. const upb_handlers *h) {
  8968. opts->handlers = h;
  8969. opts->lazy = false;
  8970. }
  8971. void upb_pbdecodermethodopts_setlazy(upb_pbdecodermethodopts *opts, bool lazy) {
  8972. opts->lazy = lazy;
  8973. }
  8974. /*
  8975. ** upb::Decoder (Bytecode Decoder VM)
  8976. **
  8977. ** Bytecode must previously have been generated using the bytecode compiler in
  8978. ** compile_decoder.c. This decoder then walks through the bytecode op-by-op to
  8979. ** parse the input.
  8980. **
  8981. ** Decoding is fully resumable; we just keep a pointer to the current bytecode
  8982. ** instruction and resume from there. A fair amount of the logic here is to
  8983. ** handle the fact that values can span buffer seams and we have to be able to
  8984. ** be capable of suspending/resuming from any byte in the stream. This
  8985. ** sometimes requires keeping a few trailing bytes from the last buffer around
  8986. ** in the "residual" buffer.
  8987. */
  8988. #include <inttypes.h>
  8989. #include <stddef.h>
  8990. #ifdef UPB_DUMP_BYTECODE
  8991. #include <stdio.h>
  8992. #endif
  8993. #define CHECK_SUSPEND(x) if (!(x)) return upb_pbdecoder_suspend(d);
  8994. /* Error messages that are shared between the bytecode and JIT decoders. */
  8995. const char *kPbDecoderStackOverflow = "Nesting too deep.";
  8996. const char *kPbDecoderSubmessageTooLong =
  8997. "Submessage end extends past enclosing submessage.";
  8998. /* Error messages shared within this file. */
  8999. static const char *kUnterminatedVarint = "Unterminated varint.";
  9000. /* upb_pbdecoder **************************************************************/
  9001. static opcode halt = OP_HALT;
  9002. /* A dummy character we can point to when the user passes us a NULL buffer.
  9003. * We need this because in C (NULL + 0) and (NULL - NULL) are undefined
  9004. * behavior, which would invalidate functions like curbufleft(). */
  9005. static const char dummy_char;
  9006. /* Whether an op consumes any of the input buffer. */
  9007. static bool consumes_input(opcode op) {
  9008. switch (op) {
  9009. case OP_SETDISPATCH:
  9010. case OP_STARTMSG:
  9011. case OP_ENDMSG:
  9012. case OP_STARTSEQ:
  9013. case OP_ENDSEQ:
  9014. case OP_STARTSUBMSG:
  9015. case OP_ENDSUBMSG:
  9016. case OP_STARTSTR:
  9017. case OP_ENDSTR:
  9018. case OP_PUSHTAGDELIM:
  9019. case OP_POP:
  9020. case OP_SETDELIM:
  9021. case OP_SETBIGGROUPNUM:
  9022. case OP_CHECKDELIM:
  9023. case OP_CALL:
  9024. case OP_RET:
  9025. case OP_BRANCH:
  9026. return false;
  9027. default:
  9028. return true;
  9029. }
  9030. }
  9031. static size_t stacksize(upb_pbdecoder *d, size_t entries) {
  9032. UPB_UNUSED(d);
  9033. return entries * sizeof(upb_pbdecoder_frame);
  9034. }
  9035. static size_t callstacksize(upb_pbdecoder *d, size_t entries) {
  9036. UPB_UNUSED(d);
  9037. #ifdef UPB_USE_JIT_X64
  9038. if (d->method_->is_native_) {
  9039. /* Each native stack frame needs two pointers, plus we need a few frames for
  9040. * the enter/exit trampolines. */
  9041. size_t ret = entries * sizeof(void*) * 2;
  9042. ret += sizeof(void*) * 10;
  9043. return ret;
  9044. }
  9045. #endif
  9046. return entries * sizeof(uint32_t*);
  9047. }
  9048. static bool in_residual_buf(const upb_pbdecoder *d, const char *p);
  9049. /* It's unfortunate that we have to micro-manage the compiler with
  9050. * UPB_FORCEINLINE and UPB_NOINLINE, especially since this tuning is necessarily
  9051. * specific to one hardware configuration. But empirically on a Core i7,
  9052. * performance increases 30-50% with these annotations. Every instance where
  9053. * these appear, gcc 4.2.1 made the wrong decision and degraded performance in
  9054. * benchmarks. */
  9055. static void seterr(upb_pbdecoder *d, const char *msg) {
  9056. upb_status status = UPB_STATUS_INIT;
  9057. upb_status_seterrmsg(&status, msg);
  9058. upb_env_reporterror(d->env, &status);
  9059. }
  9060. void upb_pbdecoder_seterr(upb_pbdecoder *d, const char *msg) {
  9061. seterr(d, msg);
  9062. }
  9063. /* Buffering ******************************************************************/
  9064. /* We operate on one buffer at a time, which is either the user's buffer passed
  9065. * to our "decode" callback or some residual bytes from the previous buffer. */
  9066. /* How many bytes can be safely read from d->ptr without reading past end-of-buf
  9067. * or past the current delimited end. */
  9068. static size_t curbufleft(const upb_pbdecoder *d) {
  9069. UPB_ASSERT(d->data_end >= d->ptr);
  9070. return d->data_end - d->ptr;
  9071. }
  9072. /* How many bytes are available before end-of-buffer. */
  9073. static size_t bufleft(const upb_pbdecoder *d) {
  9074. return d->end - d->ptr;
  9075. }
  9076. /* Overall stream offset of d->ptr. */
  9077. uint64_t offset(const upb_pbdecoder *d) {
  9078. return d->bufstart_ofs + (d->ptr - d->buf);
  9079. }
  9080. /* How many bytes are available before the end of this delimited region. */
  9081. size_t delim_remaining(const upb_pbdecoder *d) {
  9082. return d->top->end_ofs - offset(d);
  9083. }
  9084. /* Advances d->ptr. */
  9085. static void advance(upb_pbdecoder *d, size_t len) {
  9086. UPB_ASSERT(curbufleft(d) >= len);
  9087. d->ptr += len;
  9088. }
  9089. static bool in_buf(const char *p, const char *buf, const char *end) {
  9090. return p >= buf && p <= end;
  9091. }
  9092. static bool in_residual_buf(const upb_pbdecoder *d, const char *p) {
  9093. return in_buf(p, d->residual, d->residual_end);
  9094. }
  9095. /* Calculates the delim_end value, which is affected by both the current buffer
  9096. * and the parsing stack, so must be called whenever either is updated. */
  9097. static void set_delim_end(upb_pbdecoder *d) {
  9098. size_t delim_ofs = d->top->end_ofs - d->bufstart_ofs;
  9099. if (delim_ofs <= (size_t)(d->end - d->buf)) {
  9100. d->delim_end = d->buf + delim_ofs;
  9101. d->data_end = d->delim_end;
  9102. } else {
  9103. d->data_end = d->end;
  9104. d->delim_end = NULL;
  9105. }
  9106. }
  9107. static void switchtobuf(upb_pbdecoder *d, const char *buf, const char *end) {
  9108. d->ptr = buf;
  9109. d->buf = buf;
  9110. d->end = end;
  9111. set_delim_end(d);
  9112. }
  9113. static void advancetobuf(upb_pbdecoder *d, const char *buf, size_t len) {
  9114. UPB_ASSERT(curbufleft(d) == 0);
  9115. d->bufstart_ofs += (d->end - d->buf);
  9116. switchtobuf(d, buf, buf + len);
  9117. }
  9118. static void checkpoint(upb_pbdecoder *d) {
  9119. /* The assertion here is in the interests of efficiency, not correctness.
  9120. * We are trying to ensure that we don't checkpoint() more often than
  9121. * necessary. */
  9122. UPB_ASSERT(d->checkpoint != d->ptr);
  9123. d->checkpoint = d->ptr;
  9124. }
  9125. /* Skips "bytes" bytes in the stream, which may be more than available. If we
  9126. * skip more bytes than are available, we return a long read count to the caller
  9127. * indicating how many bytes can be skipped over before passing actual data
  9128. * again. Skipped bytes can pass a NULL buffer and the decoder guarantees they
  9129. * won't actually be read.
  9130. */
  9131. static int32_t skip(upb_pbdecoder *d, size_t bytes) {
  9132. UPB_ASSERT(!in_residual_buf(d, d->ptr) || d->size_param == 0);
  9133. UPB_ASSERT(d->skip == 0);
  9134. if (bytes > delim_remaining(d)) {
  9135. seterr(d, "Skipped value extended beyond enclosing submessage.");
  9136. return upb_pbdecoder_suspend(d);
  9137. } else if (bufleft(d) >= bytes) {
  9138. /* Skipped data is all in current buffer, and more is still available. */
  9139. advance(d, bytes);
  9140. d->skip = 0;
  9141. return DECODE_OK;
  9142. } else {
  9143. /* Skipped data extends beyond currently available buffers. */
  9144. d->pc = d->last;
  9145. d->skip = bytes - curbufleft(d);
  9146. d->bufstart_ofs += (d->end - d->buf);
  9147. d->residual_end = d->residual;
  9148. switchtobuf(d, d->residual, d->residual_end);
  9149. return d->size_param + d->skip;
  9150. }
  9151. }
  9152. /* Resumes the decoder from an initial state or from a previous suspend. */
  9153. int32_t upb_pbdecoder_resume(upb_pbdecoder *d, void *p, const char *buf,
  9154. size_t size, const upb_bufhandle *handle) {
  9155. UPB_UNUSED(p); /* Useless; just for the benefit of the JIT. */
  9156. /* d->skip and d->residual_end could probably elegantly be represented
  9157. * as a single variable, to more easily represent this invariant. */
  9158. UPB_ASSERT(!(d->skip && d->residual_end > d->residual));
  9159. /* We need to remember the original size_param, so that the value we return
  9160. * is relative to it, even if we do some skipping first. */
  9161. d->size_param = size;
  9162. d->handle = handle;
  9163. /* Have to handle this case specially (ie. not with skip()) because the user
  9164. * is allowed to pass a NULL buffer here, which won't allow us to safely
  9165. * calculate a d->end or use our normal functions like curbufleft(). */
  9166. if (d->skip && d->skip >= size) {
  9167. d->skip -= size;
  9168. d->bufstart_ofs += size;
  9169. buf = &dummy_char;
  9170. size = 0;
  9171. /* We can't just return now, because we might need to execute some ops
  9172. * like CHECKDELIM, which could call some callbacks and pop the stack. */
  9173. }
  9174. /* We need to pretend that this was the actual buffer param, since some of the
  9175. * calculations assume that d->ptr/d->buf is relative to this. */
  9176. d->buf_param = buf;
  9177. if (!buf) {
  9178. /* NULL buf is ok if its entire span is covered by the "skip" above, but
  9179. * by this point we know that "skip" doesn't cover the buffer. */
  9180. seterr(d, "Passed NULL buffer over non-skippable region.");
  9181. return upb_pbdecoder_suspend(d);
  9182. }
  9183. if (d->residual_end > d->residual) {
  9184. /* We have residual bytes from the last buffer. */
  9185. UPB_ASSERT(d->ptr == d->residual);
  9186. } else {
  9187. switchtobuf(d, buf, buf + size);
  9188. }
  9189. d->checkpoint = d->ptr;
  9190. /* Handle skips that don't cover the whole buffer (as above). */
  9191. if (d->skip) {
  9192. size_t skip_bytes = d->skip;
  9193. d->skip = 0;
  9194. CHECK_RETURN(skip(d, skip_bytes));
  9195. checkpoint(d);
  9196. }
  9197. /* If we're inside an unknown group, continue to parse unknown values. */
  9198. if (d->top->groupnum < 0) {
  9199. CHECK_RETURN(upb_pbdecoder_skipunknown(d, -1, 0));
  9200. checkpoint(d);
  9201. }
  9202. return DECODE_OK;
  9203. }
  9204. /* Suspends the decoder at the last checkpoint, without saving any residual
  9205. * bytes. If there are any unconsumed bytes, returns a short byte count. */
  9206. size_t upb_pbdecoder_suspend(upb_pbdecoder *d) {
  9207. d->pc = d->last;
  9208. if (d->checkpoint == d->residual) {
  9209. /* Checkpoint was in residual buf; no user bytes were consumed. */
  9210. d->ptr = d->residual;
  9211. return 0;
  9212. } else {
  9213. size_t ret = d->size_param - (d->end - d->checkpoint);
  9214. UPB_ASSERT(!in_residual_buf(d, d->checkpoint));
  9215. UPB_ASSERT(d->buf == d->buf_param || d->buf == &dummy_char);
  9216. d->bufstart_ofs += (d->checkpoint - d->buf);
  9217. d->residual_end = d->residual;
  9218. switchtobuf(d, d->residual, d->residual_end);
  9219. return ret;
  9220. }
  9221. }
  9222. /* Suspends the decoder at the last checkpoint, and saves any unconsumed
  9223. * bytes in our residual buffer. This is necessary if we need more user
  9224. * bytes to form a complete value, which might not be contiguous in the
  9225. * user's buffers. Always consumes all user bytes. */
  9226. static size_t suspend_save(upb_pbdecoder *d) {
  9227. /* We hit end-of-buffer before we could parse a full value.
  9228. * Save any unconsumed bytes (if any) to the residual buffer. */
  9229. d->pc = d->last;
  9230. if (d->checkpoint == d->residual) {
  9231. /* Checkpoint was in residual buf; append user byte(s) to residual buf. */
  9232. UPB_ASSERT((d->residual_end - d->residual) + d->size_param <=
  9233. sizeof(d->residual));
  9234. if (!in_residual_buf(d, d->ptr)) {
  9235. d->bufstart_ofs -= (d->residual_end - d->residual);
  9236. }
  9237. memcpy(d->residual_end, d->buf_param, d->size_param);
  9238. d->residual_end += d->size_param;
  9239. } else {
  9240. /* Checkpoint was in user buf; old residual bytes not needed. */
  9241. size_t save;
  9242. UPB_ASSERT(!in_residual_buf(d, d->checkpoint));
  9243. d->ptr = d->checkpoint;
  9244. save = curbufleft(d);
  9245. UPB_ASSERT(save <= sizeof(d->residual));
  9246. memcpy(d->residual, d->ptr, save);
  9247. d->residual_end = d->residual + save;
  9248. d->bufstart_ofs = offset(d);
  9249. }
  9250. switchtobuf(d, d->residual, d->residual_end);
  9251. return d->size_param;
  9252. }
  9253. /* Copies the next "bytes" bytes into "buf" and advances the stream.
  9254. * Requires that this many bytes are available in the current buffer. */
  9255. UPB_FORCEINLINE static void consumebytes(upb_pbdecoder *d, void *buf,
  9256. size_t bytes) {
  9257. UPB_ASSERT(bytes <= curbufleft(d));
  9258. memcpy(buf, d->ptr, bytes);
  9259. advance(d, bytes);
  9260. }
  9261. /* Slow path for getting the next "bytes" bytes, regardless of whether they are
  9262. * available in the current buffer or not. Returns a status code as described
  9263. * in decoder.int.h. */
  9264. UPB_NOINLINE static int32_t getbytes_slow(upb_pbdecoder *d, void *buf,
  9265. size_t bytes) {
  9266. const size_t avail = curbufleft(d);
  9267. consumebytes(d, buf, avail);
  9268. bytes -= avail;
  9269. UPB_ASSERT(bytes > 0);
  9270. if (in_residual_buf(d, d->ptr)) {
  9271. advancetobuf(d, d->buf_param, d->size_param);
  9272. }
  9273. if (curbufleft(d) >= bytes) {
  9274. consumebytes(d, (char *)buf + avail, bytes);
  9275. return DECODE_OK;
  9276. } else if (d->data_end == d->delim_end) {
  9277. seterr(d, "Submessage ended in the middle of a value or group");
  9278. return upb_pbdecoder_suspend(d);
  9279. } else {
  9280. return suspend_save(d);
  9281. }
  9282. }
  9283. /* Gets the next "bytes" bytes, regardless of whether they are available in the
  9284. * current buffer or not. Returns a status code as described in decoder.int.h.
  9285. */
  9286. UPB_FORCEINLINE static int32_t getbytes(upb_pbdecoder *d, void *buf,
  9287. size_t bytes) {
  9288. if (curbufleft(d) >= bytes) {
  9289. /* Buffer has enough data to satisfy. */
  9290. consumebytes(d, buf, bytes);
  9291. return DECODE_OK;
  9292. } else {
  9293. return getbytes_slow(d, buf, bytes);
  9294. }
  9295. }
  9296. UPB_NOINLINE static size_t peekbytes_slow(upb_pbdecoder *d, void *buf,
  9297. size_t bytes) {
  9298. size_t ret = curbufleft(d);
  9299. memcpy(buf, d->ptr, ret);
  9300. if (in_residual_buf(d, d->ptr)) {
  9301. size_t copy = UPB_MIN(bytes - ret, d->size_param);
  9302. memcpy((char *)buf + ret, d->buf_param, copy);
  9303. ret += copy;
  9304. }
  9305. return ret;
  9306. }
  9307. UPB_FORCEINLINE static size_t peekbytes(upb_pbdecoder *d, void *buf,
  9308. size_t bytes) {
  9309. if (curbufleft(d) >= bytes) {
  9310. memcpy(buf, d->ptr, bytes);
  9311. return bytes;
  9312. } else {
  9313. return peekbytes_slow(d, buf, bytes);
  9314. }
  9315. }
  9316. /* Decoding of wire types *****************************************************/
  9317. /* Slow path for decoding a varint from the current buffer position.
  9318. * Returns a status code as described in decoder.int.h. */
  9319. UPB_NOINLINE int32_t upb_pbdecoder_decode_varint_slow(upb_pbdecoder *d,
  9320. uint64_t *u64) {
  9321. uint8_t byte = 0x80;
  9322. int bitpos;
  9323. *u64 = 0;
  9324. for(bitpos = 0; bitpos < 70 && (byte & 0x80); bitpos += 7) {
  9325. CHECK_RETURN(getbytes(d, &byte, 1));
  9326. *u64 |= (uint64_t)(byte & 0x7F) << bitpos;
  9327. }
  9328. if(bitpos == 70 && (byte & 0x80)) {
  9329. seterr(d, kUnterminatedVarint);
  9330. return upb_pbdecoder_suspend(d);
  9331. }
  9332. return DECODE_OK;
  9333. }
  9334. /* Decodes a varint from the current buffer position.
  9335. * Returns a status code as described in decoder.int.h. */
  9336. UPB_FORCEINLINE static int32_t decode_varint(upb_pbdecoder *d, uint64_t *u64) {
  9337. if (curbufleft(d) > 0 && !(*d->ptr & 0x80)) {
  9338. *u64 = *d->ptr;
  9339. advance(d, 1);
  9340. return DECODE_OK;
  9341. } else if (curbufleft(d) >= 10) {
  9342. /* Fast case. */
  9343. upb_decoderet r = upb_vdecode_fast(d->ptr);
  9344. if (r.p == NULL) {
  9345. seterr(d, kUnterminatedVarint);
  9346. return upb_pbdecoder_suspend(d);
  9347. }
  9348. advance(d, r.p - d->ptr);
  9349. *u64 = r.val;
  9350. return DECODE_OK;
  9351. } else {
  9352. /* Slow case -- varint spans buffer seam. */
  9353. return upb_pbdecoder_decode_varint_slow(d, u64);
  9354. }
  9355. }
  9356. /* Decodes a 32-bit varint from the current buffer position.
  9357. * Returns a status code as described in decoder.int.h. */
  9358. UPB_FORCEINLINE static int32_t decode_v32(upb_pbdecoder *d, uint32_t *u32) {
  9359. uint64_t u64;
  9360. int32_t ret = decode_varint(d, &u64);
  9361. if (ret >= 0) return ret;
  9362. if (u64 > UINT32_MAX) {
  9363. seterr(d, "Unterminated 32-bit varint");
  9364. /* TODO(haberman) guarantee that this function return is >= 0 somehow,
  9365. * so we know this path will always be treated as error by our caller.
  9366. * Right now the size_t -> int32_t can overflow and produce negative values.
  9367. */
  9368. *u32 = 0;
  9369. return upb_pbdecoder_suspend(d);
  9370. }
  9371. *u32 = u64;
  9372. return DECODE_OK;
  9373. }
  9374. /* Decodes a fixed32 from the current buffer position.
  9375. * Returns a status code as described in decoder.int.h.
  9376. * TODO: proper byte swapping for big-endian machines. */
  9377. UPB_FORCEINLINE static int32_t decode_fixed32(upb_pbdecoder *d, uint32_t *u32) {
  9378. return getbytes(d, u32, 4);
  9379. }
  9380. /* Decodes a fixed64 from the current buffer position.
  9381. * Returns a status code as described in decoder.int.h.
  9382. * TODO: proper byte swapping for big-endian machines. */
  9383. UPB_FORCEINLINE static int32_t decode_fixed64(upb_pbdecoder *d, uint64_t *u64) {
  9384. return getbytes(d, u64, 8);
  9385. }
  9386. /* Non-static versions of the above functions.
  9387. * These are called by the JIT for fallback paths. */
  9388. int32_t upb_pbdecoder_decode_f32(upb_pbdecoder *d, uint32_t *u32) {
  9389. return decode_fixed32(d, u32);
  9390. }
  9391. int32_t upb_pbdecoder_decode_f64(upb_pbdecoder *d, uint64_t *u64) {
  9392. return decode_fixed64(d, u64);
  9393. }
  9394. static double as_double(uint64_t n) { double d; memcpy(&d, &n, 8); return d; }
  9395. static float as_float(uint32_t n) { float f; memcpy(&f, &n, 4); return f; }
  9396. /* Pushes a frame onto the decoder stack. */
  9397. static bool decoder_push(upb_pbdecoder *d, uint64_t end) {
  9398. upb_pbdecoder_frame *fr = d->top;
  9399. if (end > fr->end_ofs) {
  9400. seterr(d, kPbDecoderSubmessageTooLong);
  9401. return false;
  9402. } else if (fr == d->limit) {
  9403. seterr(d, kPbDecoderStackOverflow);
  9404. return false;
  9405. }
  9406. fr++;
  9407. fr->end_ofs = end;
  9408. fr->dispatch = NULL;
  9409. fr->groupnum = 0;
  9410. d->top = fr;
  9411. return true;
  9412. }
  9413. static bool pushtagdelim(upb_pbdecoder *d, uint32_t arg) {
  9414. /* While we expect to see an "end" tag (either ENDGROUP or a non-sequence
  9415. * field number) prior to hitting any enclosing submessage end, pushing our
  9416. * existing delim end prevents us from continuing to parse values from a
  9417. * corrupt proto that doesn't give us an END tag in time. */
  9418. if (!decoder_push(d, d->top->end_ofs))
  9419. return false;
  9420. d->top->groupnum = arg;
  9421. return true;
  9422. }
  9423. /* Pops a frame from the decoder stack. */
  9424. static void decoder_pop(upb_pbdecoder *d) { d->top--; }
  9425. UPB_NOINLINE int32_t upb_pbdecoder_checktag_slow(upb_pbdecoder *d,
  9426. uint64_t expected) {
  9427. uint64_t data = 0;
  9428. size_t bytes = upb_value_size(expected);
  9429. size_t read = peekbytes(d, &data, bytes);
  9430. if (read == bytes && data == expected) {
  9431. /* Advance past matched bytes. */
  9432. int32_t ok = getbytes(d, &data, read);
  9433. UPB_ASSERT(ok < 0);
  9434. return DECODE_OK;
  9435. } else if (read < bytes && memcmp(&data, &expected, read) == 0) {
  9436. return suspend_save(d);
  9437. } else {
  9438. return DECODE_MISMATCH;
  9439. }
  9440. }
  9441. int32_t upb_pbdecoder_skipunknown(upb_pbdecoder *d, int32_t fieldnum,
  9442. uint8_t wire_type) {
  9443. if (fieldnum >= 0)
  9444. goto have_tag;
  9445. while (true) {
  9446. uint32_t tag;
  9447. CHECK_RETURN(decode_v32(d, &tag));
  9448. wire_type = tag & 0x7;
  9449. fieldnum = tag >> 3;
  9450. have_tag:
  9451. if (fieldnum == 0) {
  9452. seterr(d, "Saw invalid field number (0)");
  9453. return upb_pbdecoder_suspend(d);
  9454. }
  9455. switch (wire_type) {
  9456. case UPB_WIRE_TYPE_32BIT:
  9457. CHECK_RETURN(skip(d, 4));
  9458. break;
  9459. case UPB_WIRE_TYPE_64BIT:
  9460. CHECK_RETURN(skip(d, 8));
  9461. break;
  9462. case UPB_WIRE_TYPE_VARINT: {
  9463. uint64_t u64;
  9464. CHECK_RETURN(decode_varint(d, &u64));
  9465. break;
  9466. }
  9467. case UPB_WIRE_TYPE_DELIMITED: {
  9468. uint32_t len;
  9469. CHECK_RETURN(decode_v32(d, &len));
  9470. CHECK_RETURN(skip(d, len));
  9471. break;
  9472. }
  9473. case UPB_WIRE_TYPE_START_GROUP:
  9474. CHECK_SUSPEND(pushtagdelim(d, -fieldnum));
  9475. break;
  9476. case UPB_WIRE_TYPE_END_GROUP:
  9477. if (fieldnum == -d->top->groupnum) {
  9478. decoder_pop(d);
  9479. } else if (fieldnum == d->top->groupnum) {
  9480. return DECODE_ENDGROUP;
  9481. } else {
  9482. seterr(d, "Unmatched ENDGROUP tag.");
  9483. return upb_pbdecoder_suspend(d);
  9484. }
  9485. break;
  9486. default:
  9487. seterr(d, "Invalid wire type");
  9488. return upb_pbdecoder_suspend(d);
  9489. }
  9490. if (d->top->groupnum >= 0) {
  9491. /* TODO: More code needed for handling unknown groups. */
  9492. upb_sink_putunknown(&d->top->sink, d->checkpoint, d->ptr - d->checkpoint);
  9493. return DECODE_OK;
  9494. }
  9495. /* Unknown group -- continue looping over unknown fields. */
  9496. checkpoint(d);
  9497. }
  9498. }
  9499. static void goto_endmsg(upb_pbdecoder *d) {
  9500. upb_value v;
  9501. bool found = upb_inttable_lookup32(d->top->dispatch, DISPATCH_ENDMSG, &v);
  9502. UPB_ASSERT(found);
  9503. d->pc = d->top->base + upb_value_getuint64(v);
  9504. }
  9505. /* Parses a tag and jumps to the corresponding bytecode instruction for this
  9506. * field.
  9507. *
  9508. * If the tag is unknown (or the wire type doesn't match), parses the field as
  9509. * unknown. If the tag is a valid ENDGROUP tag, jumps to the bytecode
  9510. * instruction for the end of message. */
  9511. static int32_t dispatch(upb_pbdecoder *d) {
  9512. upb_inttable *dispatch = d->top->dispatch;
  9513. uint32_t tag;
  9514. uint8_t wire_type;
  9515. uint32_t fieldnum;
  9516. upb_value val;
  9517. int32_t retval;
  9518. /* Decode tag. */
  9519. CHECK_RETURN(decode_v32(d, &tag));
  9520. wire_type = tag & 0x7;
  9521. fieldnum = tag >> 3;
  9522. /* Lookup tag. Because of packed/non-packed compatibility, we have to
  9523. * check the wire type against two possibilities. */
  9524. if (fieldnum != DISPATCH_ENDMSG &&
  9525. upb_inttable_lookup32(dispatch, fieldnum, &val)) {
  9526. uint64_t v = upb_value_getuint64(val);
  9527. if (wire_type == (v & 0xff)) {
  9528. d->pc = d->top->base + (v >> 16);
  9529. return DECODE_OK;
  9530. } else if (wire_type == ((v >> 8) & 0xff)) {
  9531. bool found =
  9532. upb_inttable_lookup(dispatch, fieldnum + UPB_MAX_FIELDNUMBER, &val);
  9533. UPB_ASSERT(found);
  9534. d->pc = d->top->base + upb_value_getuint64(val);
  9535. return DECODE_OK;
  9536. }
  9537. }
  9538. /* We have some unknown fields (or ENDGROUP) to parse. The DISPATCH or TAG
  9539. * bytecode that triggered this is preceded by a CHECKDELIM bytecode which
  9540. * we need to back up to, so that when we're done skipping unknown data we
  9541. * can re-check the delimited end. */
  9542. d->last--; /* Necessary if we get suspended */
  9543. d->pc = d->last;
  9544. UPB_ASSERT(getop(*d->last) == OP_CHECKDELIM);
  9545. /* Unknown field or ENDGROUP. */
  9546. retval = upb_pbdecoder_skipunknown(d, fieldnum, wire_type);
  9547. CHECK_RETURN(retval);
  9548. if (retval == DECODE_ENDGROUP) {
  9549. goto_endmsg(d);
  9550. return DECODE_OK;
  9551. }
  9552. return DECODE_OK;
  9553. }
  9554. /* Callers know that the stack is more than one deep because the opcodes that
  9555. * call this only occur after PUSH operations. */
  9556. upb_pbdecoder_frame *outer_frame(upb_pbdecoder *d) {
  9557. UPB_ASSERT(d->top != d->stack);
  9558. return d->top - 1;
  9559. }
  9560. /* The main decoding loop *****************************************************/
  9561. /* The main decoder VM function. Uses traditional bytecode dispatch loop with a
  9562. * switch() statement. */
  9563. size_t run_decoder_vm(upb_pbdecoder *d, const mgroup *group,
  9564. const upb_bufhandle* handle) {
  9565. #define VMCASE(op, code) \
  9566. case op: { code; if (consumes_input(op)) checkpoint(d); break; }
  9567. #define PRIMITIVE_OP(type, wt, name, convfunc, ctype) \
  9568. VMCASE(OP_PARSE_ ## type, { \
  9569. ctype val; \
  9570. CHECK_RETURN(decode_ ## wt(d, &val)); \
  9571. upb_sink_put ## name(&d->top->sink, arg, (convfunc)(val)); \
  9572. })
  9573. while(1) {
  9574. int32_t instruction;
  9575. opcode op;
  9576. uint32_t arg;
  9577. int32_t longofs;
  9578. d->last = d->pc;
  9579. instruction = *d->pc++;
  9580. op = getop(instruction);
  9581. arg = instruction >> 8;
  9582. longofs = arg;
  9583. UPB_ASSERT(d->ptr != d->residual_end);
  9584. UPB_UNUSED(group);
  9585. #ifdef UPB_DUMP_BYTECODE
  9586. fprintf(stderr, "s_ofs=%d buf_ofs=%d data_rem=%d buf_rem=%d delim_rem=%d "
  9587. "%x %s (%d)\n",
  9588. (int)offset(d),
  9589. (int)(d->ptr - d->buf),
  9590. (int)(d->data_end - d->ptr),
  9591. (int)(d->end - d->ptr),
  9592. (int)((d->top->end_ofs - d->bufstart_ofs) - (d->ptr - d->buf)),
  9593. (int)(d->pc - 1 - group->bytecode),
  9594. upb_pbdecoder_getopname(op),
  9595. arg);
  9596. #endif
  9597. switch (op) {
  9598. /* Technically, we are losing data if we see a 32-bit varint that is not
  9599. * properly sign-extended. We could detect this and error about the data
  9600. * loss, but proto2 does not do this, so we pass. */
  9601. PRIMITIVE_OP(INT32, varint, int32, int32_t, uint64_t)
  9602. PRIMITIVE_OP(INT64, varint, int64, int64_t, uint64_t)
  9603. PRIMITIVE_OP(UINT32, varint, uint32, uint32_t, uint64_t)
  9604. PRIMITIVE_OP(UINT64, varint, uint64, uint64_t, uint64_t)
  9605. PRIMITIVE_OP(FIXED32, fixed32, uint32, uint32_t, uint32_t)
  9606. PRIMITIVE_OP(FIXED64, fixed64, uint64, uint64_t, uint64_t)
  9607. PRIMITIVE_OP(SFIXED32, fixed32, int32, int32_t, uint32_t)
  9608. PRIMITIVE_OP(SFIXED64, fixed64, int64, int64_t, uint64_t)
  9609. PRIMITIVE_OP(BOOL, varint, bool, bool, uint64_t)
  9610. PRIMITIVE_OP(DOUBLE, fixed64, double, as_double, uint64_t)
  9611. PRIMITIVE_OP(FLOAT, fixed32, float, as_float, uint32_t)
  9612. PRIMITIVE_OP(SINT32, varint, int32, upb_zzdec_32, uint64_t)
  9613. PRIMITIVE_OP(SINT64, varint, int64, upb_zzdec_64, uint64_t)
  9614. VMCASE(OP_SETDISPATCH,
  9615. d->top->base = d->pc - 1;
  9616. memcpy(&d->top->dispatch, d->pc, sizeof(void*));
  9617. d->pc += sizeof(void*) / sizeof(uint32_t);
  9618. )
  9619. VMCASE(OP_STARTMSG,
  9620. CHECK_SUSPEND(upb_sink_startmsg(&d->top->sink));
  9621. )
  9622. VMCASE(OP_ENDMSG,
  9623. CHECK_SUSPEND(upb_sink_endmsg(&d->top->sink, d->status));
  9624. )
  9625. VMCASE(OP_STARTSEQ,
  9626. upb_pbdecoder_frame *outer = outer_frame(d);
  9627. CHECK_SUSPEND(upb_sink_startseq(&outer->sink, arg, &d->top->sink));
  9628. )
  9629. VMCASE(OP_ENDSEQ,
  9630. CHECK_SUSPEND(upb_sink_endseq(&d->top->sink, arg));
  9631. )
  9632. VMCASE(OP_STARTSUBMSG,
  9633. upb_pbdecoder_frame *outer = outer_frame(d);
  9634. CHECK_SUSPEND(upb_sink_startsubmsg(&outer->sink, arg, &d->top->sink));
  9635. )
  9636. VMCASE(OP_ENDSUBMSG,
  9637. CHECK_SUSPEND(upb_sink_endsubmsg(&d->top->sink, arg));
  9638. )
  9639. VMCASE(OP_STARTSTR,
  9640. uint32_t len = delim_remaining(d);
  9641. upb_pbdecoder_frame *outer = outer_frame(d);
  9642. CHECK_SUSPEND(upb_sink_startstr(&outer->sink, arg, len, &d->top->sink));
  9643. if (len == 0) {
  9644. d->pc++; /* Skip OP_STRING. */
  9645. }
  9646. )
  9647. VMCASE(OP_STRING,
  9648. uint32_t len = curbufleft(d);
  9649. size_t n = upb_sink_putstring(&d->top->sink, arg, d->ptr, len, handle);
  9650. if (n > len) {
  9651. if (n > delim_remaining(d)) {
  9652. seterr(d, "Tried to skip past end of string.");
  9653. return upb_pbdecoder_suspend(d);
  9654. } else {
  9655. int32_t ret = skip(d, n);
  9656. /* This shouldn't return DECODE_OK, because n > len. */
  9657. UPB_ASSERT(ret >= 0);
  9658. return ret;
  9659. }
  9660. }
  9661. advance(d, n);
  9662. if (n < len || d->delim_end == NULL) {
  9663. /* We aren't finished with this string yet. */
  9664. d->pc--; /* Repeat OP_STRING. */
  9665. if (n > 0) checkpoint(d);
  9666. return upb_pbdecoder_suspend(d);
  9667. }
  9668. )
  9669. VMCASE(OP_ENDSTR,
  9670. CHECK_SUSPEND(upb_sink_endstr(&d->top->sink, arg));
  9671. )
  9672. VMCASE(OP_PUSHTAGDELIM,
  9673. CHECK_SUSPEND(pushtagdelim(d, arg));
  9674. )
  9675. VMCASE(OP_SETBIGGROUPNUM,
  9676. d->top->groupnum = *d->pc++;
  9677. )
  9678. VMCASE(OP_POP,
  9679. UPB_ASSERT(d->top > d->stack);
  9680. decoder_pop(d);
  9681. )
  9682. VMCASE(OP_PUSHLENDELIM,
  9683. uint32_t len;
  9684. CHECK_RETURN(decode_v32(d, &len));
  9685. CHECK_SUSPEND(decoder_push(d, offset(d) + len));
  9686. set_delim_end(d);
  9687. )
  9688. VMCASE(OP_SETDELIM,
  9689. set_delim_end(d);
  9690. )
  9691. VMCASE(OP_CHECKDELIM,
  9692. /* We are guaranteed of this assert because we never allow ourselves to
  9693. * consume bytes beyond data_end, which covers delim_end when non-NULL.
  9694. */
  9695. UPB_ASSERT(!(d->delim_end && d->ptr > d->delim_end));
  9696. if (d->ptr == d->delim_end)
  9697. d->pc += longofs;
  9698. )
  9699. VMCASE(OP_CALL,
  9700. d->callstack[d->call_len++] = d->pc;
  9701. d->pc += longofs;
  9702. )
  9703. VMCASE(OP_RET,
  9704. UPB_ASSERT(d->call_len > 0);
  9705. d->pc = d->callstack[--d->call_len];
  9706. )
  9707. VMCASE(OP_BRANCH,
  9708. d->pc += longofs;
  9709. )
  9710. VMCASE(OP_TAG1,
  9711. uint8_t expected;
  9712. CHECK_SUSPEND(curbufleft(d) > 0);
  9713. expected = (arg >> 8) & 0xff;
  9714. if (*d->ptr == expected) {
  9715. advance(d, 1);
  9716. } else {
  9717. int8_t shortofs;
  9718. badtag:
  9719. shortofs = arg;
  9720. if (shortofs == LABEL_DISPATCH) {
  9721. CHECK_RETURN(dispatch(d));
  9722. } else {
  9723. d->pc += shortofs;
  9724. break; /* Avoid checkpoint(). */
  9725. }
  9726. }
  9727. )
  9728. VMCASE(OP_TAG2,
  9729. uint16_t expected;
  9730. CHECK_SUSPEND(curbufleft(d) > 0);
  9731. expected = (arg >> 8) & 0xffff;
  9732. if (curbufleft(d) >= 2) {
  9733. uint16_t actual;
  9734. memcpy(&actual, d->ptr, 2);
  9735. if (expected == actual) {
  9736. advance(d, 2);
  9737. } else {
  9738. goto badtag;
  9739. }
  9740. } else {
  9741. int32_t result = upb_pbdecoder_checktag_slow(d, expected);
  9742. if (result == DECODE_MISMATCH) goto badtag;
  9743. if (result >= 0) return result;
  9744. }
  9745. )
  9746. VMCASE(OP_TAGN, {
  9747. uint64_t expected;
  9748. int32_t result;
  9749. memcpy(&expected, d->pc, 8);
  9750. d->pc += 2;
  9751. result = upb_pbdecoder_checktag_slow(d, expected);
  9752. if (result == DECODE_MISMATCH) goto badtag;
  9753. if (result >= 0) return result;
  9754. })
  9755. VMCASE(OP_DISPATCH, {
  9756. CHECK_RETURN(dispatch(d));
  9757. })
  9758. VMCASE(OP_HALT, {
  9759. return d->size_param;
  9760. })
  9761. }
  9762. }
  9763. }
  9764. /* BytesHandler handlers ******************************************************/
  9765. void *upb_pbdecoder_startbc(void *closure, const void *pc, size_t size_hint) {
  9766. upb_pbdecoder *d = closure;
  9767. UPB_UNUSED(size_hint);
  9768. d->top->end_ofs = UINT64_MAX;
  9769. d->bufstart_ofs = 0;
  9770. d->call_len = 1;
  9771. d->callstack[0] = &halt;
  9772. d->pc = pc;
  9773. d->skip = 0;
  9774. return d;
  9775. }
  9776. void *upb_pbdecoder_startjit(void *closure, const void *hd, size_t size_hint) {
  9777. upb_pbdecoder *d = closure;
  9778. UPB_UNUSED(hd);
  9779. UPB_UNUSED(size_hint);
  9780. d->top->end_ofs = UINT64_MAX;
  9781. d->bufstart_ofs = 0;
  9782. d->call_len = 0;
  9783. d->skip = 0;
  9784. return d;
  9785. }
  9786. bool upb_pbdecoder_end(void *closure, const void *handler_data) {
  9787. upb_pbdecoder *d = closure;
  9788. const upb_pbdecodermethod *method = handler_data;
  9789. uint64_t end;
  9790. char dummy;
  9791. if (d->residual_end > d->residual) {
  9792. seterr(d, "Unexpected EOF: decoder still has buffered unparsed data");
  9793. return false;
  9794. }
  9795. if (d->skip) {
  9796. seterr(d, "Unexpected EOF inside skipped data");
  9797. return false;
  9798. }
  9799. if (d->top->end_ofs != UINT64_MAX) {
  9800. seterr(d, "Unexpected EOF inside delimited string");
  9801. return false;
  9802. }
  9803. /* The user's end() call indicates that the message ends here. */
  9804. end = offset(d);
  9805. d->top->end_ofs = end;
  9806. #ifdef UPB_USE_JIT_X64
  9807. if (method->is_native_) {
  9808. const mgroup *group = (const mgroup*)method->group;
  9809. if (d->top != d->stack)
  9810. d->stack->end_ofs = 0;
  9811. group->jit_code(closure, method->code_base.ptr, &dummy, 0, NULL);
  9812. } else
  9813. #endif
  9814. {
  9815. const uint32_t *p = d->pc;
  9816. d->stack->end_ofs = end;
  9817. /* Check the previous bytecode, but guard against beginning. */
  9818. if (p != method->code_base.ptr) p--;
  9819. if (getop(*p) == OP_CHECKDELIM) {
  9820. /* Rewind from OP_TAG* to OP_CHECKDELIM. */
  9821. UPB_ASSERT(getop(*d->pc) == OP_TAG1 ||
  9822. getop(*d->pc) == OP_TAG2 ||
  9823. getop(*d->pc) == OP_TAGN ||
  9824. getop(*d->pc) == OP_DISPATCH);
  9825. d->pc = p;
  9826. }
  9827. upb_pbdecoder_decode(closure, handler_data, &dummy, 0, NULL);
  9828. }
  9829. if (d->call_len != 0) {
  9830. seterr(d, "Unexpected EOF inside submessage or group");
  9831. return false;
  9832. }
  9833. return true;
  9834. }
  9835. size_t upb_pbdecoder_decode(void *decoder, const void *group, const char *buf,
  9836. size_t size, const upb_bufhandle *handle) {
  9837. int32_t result = upb_pbdecoder_resume(decoder, NULL, buf, size, handle);
  9838. if (result == DECODE_ENDGROUP) goto_endmsg(decoder);
  9839. CHECK_RETURN(result);
  9840. return run_decoder_vm(decoder, group, handle);
  9841. }
  9842. /* Public API *****************************************************************/
  9843. void upb_pbdecoder_reset(upb_pbdecoder *d) {
  9844. d->top = d->stack;
  9845. d->top->groupnum = 0;
  9846. d->ptr = d->residual;
  9847. d->buf = d->residual;
  9848. d->end = d->residual;
  9849. d->residual_end = d->residual;
  9850. }
  9851. upb_pbdecoder *upb_pbdecoder_create(upb_env *e, const upb_pbdecodermethod *m,
  9852. upb_sink *sink) {
  9853. const size_t default_max_nesting = 64;
  9854. #ifndef NDEBUG
  9855. size_t size_before = upb_env_bytesallocated(e);
  9856. #endif
  9857. upb_pbdecoder *d = upb_env_malloc(e, sizeof(upb_pbdecoder));
  9858. if (!d) return NULL;
  9859. d->method_ = m;
  9860. d->callstack = upb_env_malloc(e, callstacksize(d, default_max_nesting));
  9861. d->stack = upb_env_malloc(e, stacksize(d, default_max_nesting));
  9862. if (!d->stack || !d->callstack) {
  9863. return NULL;
  9864. }
  9865. d->env = e;
  9866. d->limit = d->stack + default_max_nesting - 1;
  9867. d->stack_size = default_max_nesting;
  9868. d->status = NULL;
  9869. upb_pbdecoder_reset(d);
  9870. upb_bytessink_reset(&d->input_, &m->input_handler_, d);
  9871. UPB_ASSERT(sink);
  9872. if (d->method_->dest_handlers_) {
  9873. if (sink->handlers != d->method_->dest_handlers_)
  9874. return NULL;
  9875. }
  9876. upb_sink_reset(&d->top->sink, sink->handlers, sink->closure);
  9877. /* If this fails, increase the value in decoder.h. */
  9878. UPB_ASSERT_DEBUGVAR(upb_env_bytesallocated(e) - size_before <=
  9879. UPB_PB_DECODER_SIZE);
  9880. return d;
  9881. }
  9882. uint64_t upb_pbdecoder_bytesparsed(const upb_pbdecoder *d) {
  9883. return offset(d);
  9884. }
  9885. const upb_pbdecodermethod *upb_pbdecoder_method(const upb_pbdecoder *d) {
  9886. return d->method_;
  9887. }
  9888. upb_bytessink *upb_pbdecoder_input(upb_pbdecoder *d) {
  9889. return &d->input_;
  9890. }
  9891. size_t upb_pbdecoder_maxnesting(const upb_pbdecoder *d) {
  9892. return d->stack_size;
  9893. }
  9894. bool upb_pbdecoder_setmaxnesting(upb_pbdecoder *d, size_t max) {
  9895. UPB_ASSERT(d->top >= d->stack);
  9896. if (max < (size_t)(d->top - d->stack)) {
  9897. /* Can't set a limit smaller than what we are currently at. */
  9898. return false;
  9899. }
  9900. if (max > d->stack_size) {
  9901. /* Need to reallocate stack and callstack to accommodate. */
  9902. size_t old_size = stacksize(d, d->stack_size);
  9903. size_t new_size = stacksize(d, max);
  9904. void *p = upb_env_realloc(d->env, d->stack, old_size, new_size);
  9905. if (!p) {
  9906. return false;
  9907. }
  9908. d->stack = p;
  9909. old_size = callstacksize(d, d->stack_size);
  9910. new_size = callstacksize(d, max);
  9911. p = upb_env_realloc(d->env, d->callstack, old_size, new_size);
  9912. if (!p) {
  9913. return false;
  9914. }
  9915. d->callstack = p;
  9916. d->stack_size = max;
  9917. }
  9918. d->limit = d->stack + max - 1;
  9919. return true;
  9920. }
  9921. /*
  9922. ** upb::Encoder
  9923. **
  9924. ** Since we are implementing pure handlers (ie. without any out-of-band access
  9925. ** to pre-computed lengths), we have to buffer all submessages before we can
  9926. ** emit even their first byte.
  9927. **
  9928. ** Not knowing the size of submessages also means we can't write a perfect
  9929. ** zero-copy implementation, even with buffering. Lengths are stored as
  9930. ** varints, which means that we don't know how many bytes to reserve for the
  9931. ** length until we know what the length is.
  9932. **
  9933. ** This leaves us with three main choices:
  9934. **
  9935. ** 1. buffer all submessage data in a temporary buffer, then copy it exactly
  9936. ** once into the output buffer.
  9937. **
  9938. ** 2. attempt to buffer data directly into the output buffer, estimating how
  9939. ** many bytes each length will take. When our guesses are wrong, use
  9940. ** memmove() to grow or shrink the allotted space.
  9941. **
  9942. ** 3. buffer directly into the output buffer, allocating a max length
  9943. ** ahead-of-time for each submessage length. If we overallocated, we waste
  9944. ** space, but no memcpy() or memmove() is required. This approach requires
  9945. ** defining a maximum size for submessages and rejecting submessages that
  9946. ** exceed that size.
  9947. **
  9948. ** (2) and (3) have the potential to have better performance, but they are more
  9949. ** complicated and subtle to implement:
  9950. **
  9951. ** (3) requires making an arbitrary choice of the maximum message size; it
  9952. ** wastes space when submessages are shorter than this and fails
  9953. ** completely when they are longer. This makes it more finicky and
  9954. ** requires configuration based on the input. It also makes it impossible
  9955. ** to perfectly match the output of reference encoders that always use the
  9956. ** optimal amount of space for each length.
  9957. **
  9958. ** (2) requires guessing the size upfront, and if multiple lengths are
  9959. ** guessed wrong the minimum required number of memmove() operations may
  9960. ** be complicated to compute correctly. Implemented properly, it may have
  9961. ** a useful amortized or average cost, but more investigation is required
  9962. ** to determine this and what the optimal algorithm is to achieve it.
  9963. **
  9964. ** (1) makes you always pay for exactly one copy, but its implementation is
  9965. ** the simplest and its performance is predictable.
  9966. **
  9967. ** So for now, we implement (1) only. If we wish to optimize later, we should
  9968. ** be able to do it without affecting users.
  9969. **
  9970. ** The strategy is to buffer the segments of data that do *not* depend on
  9971. ** unknown lengths in one buffer, and keep a separate buffer of segment pointers
  9972. ** and lengths. When the top-level submessage ends, we can go beginning to end,
  9973. ** alternating the writing of lengths with memcpy() of the rest of the data.
  9974. ** At the top level though, no buffering is required.
  9975. */
  9976. /* The output buffer is divided into segments; a segment is a string of data
  9977. * that is "ready to go" -- it does not need any varint lengths inserted into
  9978. * the middle. The seams between segments are where varints will be inserted
  9979. * once they are known.
  9980. *
  9981. * We also use the concept of a "run", which is a range of encoded bytes that
  9982. * occur at a single submessage level. Every segment contains one or more runs.
  9983. *
  9984. * A segment can span messages. Consider:
  9985. *
  9986. * .--Submessage lengths---------.
  9987. * | | |
  9988. * | V V
  9989. * V | |--------------- | |-----------------
  9990. * Submessages: | |-----------------------------------------------
  9991. * Top-level msg: ------------------------------------------------------------
  9992. *
  9993. * Segments: ----- ------------------- -----------------
  9994. * Runs: *---- *--------------*--- *----------------
  9995. * (* marks the start)
  9996. *
  9997. * Note that the top-level menssage is not in any segment because it does not
  9998. * have any length preceding it.
  9999. *
  10000. * A segment is only interrupted when another length needs to be inserted. So
  10001. * observe how the second segment spans both the inner submessage and part of
  10002. * the next enclosing message. */
  10003. typedef struct {
  10004. uint32_t msglen; /* The length to varint-encode before this segment. */
  10005. uint32_t seglen; /* Length of the segment. */
  10006. } upb_pb_encoder_segment;
  10007. struct upb_pb_encoder {
  10008. upb_env *env;
  10009. /* Our input and output. */
  10010. upb_sink input_;
  10011. upb_bytessink *output_;
  10012. /* The "subclosure" -- used as the inner closure as part of the bytessink
  10013. * protocol. */
  10014. void *subc;
  10015. /* The output buffer and limit, and our current write position. "buf"
  10016. * initially points to "initbuf", but is dynamically allocated if we need to
  10017. * grow beyond the initial size. */
  10018. char *buf, *ptr, *limit;
  10019. /* The beginning of the current run, or undefined if we are at the top
  10020. * level. */
  10021. char *runbegin;
  10022. /* The list of segments we are accumulating. */
  10023. upb_pb_encoder_segment *segbuf, *segptr, *seglimit;
  10024. /* The stack of enclosing submessages. Each entry in the stack points to the
  10025. * segment where this submessage's length is being accumulated. */
  10026. int *stack, *top, *stacklimit;
  10027. /* Depth of startmsg/endmsg calls. */
  10028. int depth;
  10029. };
  10030. /* low-level buffering ********************************************************/
  10031. /* Low-level functions for interacting with the output buffer. */
  10032. /* TODO(haberman): handle pushback */
  10033. static void putbuf(upb_pb_encoder *e, const char *buf, size_t len) {
  10034. size_t n = upb_bytessink_putbuf(e->output_, e->subc, buf, len, NULL);
  10035. UPB_ASSERT(n == len);
  10036. }
  10037. static upb_pb_encoder_segment *top(upb_pb_encoder *e) {
  10038. return &e->segbuf[*e->top];
  10039. }
  10040. /* Call to ensure that at least "bytes" bytes are available for writing at
  10041. * e->ptr. Returns false if the bytes could not be allocated. */
  10042. static bool reserve(upb_pb_encoder *e, size_t bytes) {
  10043. if ((size_t)(e->limit - e->ptr) < bytes) {
  10044. /* Grow buffer. */
  10045. char *new_buf;
  10046. size_t needed = bytes + (e->ptr - e->buf);
  10047. size_t old_size = e->limit - e->buf;
  10048. size_t new_size = old_size;
  10049. while (new_size < needed) {
  10050. new_size *= 2;
  10051. }
  10052. new_buf = upb_env_realloc(e->env, e->buf, old_size, new_size);
  10053. if (new_buf == NULL) {
  10054. return false;
  10055. }
  10056. e->ptr = new_buf + (e->ptr - e->buf);
  10057. e->runbegin = new_buf + (e->runbegin - e->buf);
  10058. e->limit = new_buf + new_size;
  10059. e->buf = new_buf;
  10060. }
  10061. return true;
  10062. }
  10063. /* Call when "bytes" bytes have been writte at e->ptr. The caller *must* have
  10064. * previously called reserve() with at least this many bytes. */
  10065. static void encoder_advance(upb_pb_encoder *e, size_t bytes) {
  10066. UPB_ASSERT((size_t)(e->limit - e->ptr) >= bytes);
  10067. e->ptr += bytes;
  10068. }
  10069. /* Call when all of the bytes for a handler have been written. Flushes the
  10070. * bytes if possible and necessary, returning false if this failed. */
  10071. static bool commit(upb_pb_encoder *e) {
  10072. if (!e->top) {
  10073. /* We aren't inside a delimited region. Flush our accumulated bytes to
  10074. * the output.
  10075. *
  10076. * TODO(haberman): in the future we may want to delay flushing for
  10077. * efficiency reasons. */
  10078. putbuf(e, e->buf, e->ptr - e->buf);
  10079. e->ptr = e->buf;
  10080. }
  10081. return true;
  10082. }
  10083. /* Writes the given bytes to the buffer, handling reserve/advance. */
  10084. static bool encode_bytes(upb_pb_encoder *e, const void *data, size_t len) {
  10085. if (!reserve(e, len)) {
  10086. return false;
  10087. }
  10088. memcpy(e->ptr, data, len);
  10089. encoder_advance(e, len);
  10090. return true;
  10091. }
  10092. /* Finish the current run by adding the run totals to the segment and message
  10093. * length. */
  10094. static void accumulate(upb_pb_encoder *e) {
  10095. size_t run_len;
  10096. UPB_ASSERT(e->ptr >= e->runbegin);
  10097. run_len = e->ptr - e->runbegin;
  10098. e->segptr->seglen += run_len;
  10099. top(e)->msglen += run_len;
  10100. e->runbegin = e->ptr;
  10101. }
  10102. /* Call to indicate the start of delimited region for which the full length is
  10103. * not yet known. All data will be buffered until the length is known.
  10104. * Delimited regions may be nested; their lengths will all be tracked properly. */
  10105. static bool start_delim(upb_pb_encoder *e) {
  10106. if (e->top) {
  10107. /* We are already buffering, advance to the next segment and push it on the
  10108. * stack. */
  10109. accumulate(e);
  10110. if (++e->top == e->stacklimit) {
  10111. /* TODO(haberman): grow stack? */
  10112. return false;
  10113. }
  10114. if (++e->segptr == e->seglimit) {
  10115. /* Grow segment buffer. */
  10116. size_t old_size =
  10117. (e->seglimit - e->segbuf) * sizeof(upb_pb_encoder_segment);
  10118. size_t new_size = old_size * 2;
  10119. upb_pb_encoder_segment *new_buf =
  10120. upb_env_realloc(e->env, e->segbuf, old_size, new_size);
  10121. if (new_buf == NULL) {
  10122. return false;
  10123. }
  10124. e->segptr = new_buf + (e->segptr - e->segbuf);
  10125. e->seglimit = new_buf + (new_size / sizeof(upb_pb_encoder_segment));
  10126. e->segbuf = new_buf;
  10127. }
  10128. } else {
  10129. /* We were previously at the top level, start buffering. */
  10130. e->segptr = e->segbuf;
  10131. e->top = e->stack;
  10132. e->runbegin = e->ptr;
  10133. }
  10134. *e->top = e->segptr - e->segbuf;
  10135. e->segptr->seglen = 0;
  10136. e->segptr->msglen = 0;
  10137. return true;
  10138. }
  10139. /* Call to indicate the end of a delimited region. We now know the length of
  10140. * the delimited region. If we are not nested inside any other delimited
  10141. * regions, we can now emit all of the buffered data we accumulated. */
  10142. static bool end_delim(upb_pb_encoder *e) {
  10143. size_t msglen;
  10144. accumulate(e);
  10145. msglen = top(e)->msglen;
  10146. if (e->top == e->stack) {
  10147. /* All lengths are now available, emit all buffered data. */
  10148. char buf[UPB_PB_VARINT_MAX_LEN];
  10149. upb_pb_encoder_segment *s;
  10150. const char *ptr = e->buf;
  10151. for (s = e->segbuf; s <= e->segptr; s++) {
  10152. size_t lenbytes = upb_vencode64(s->msglen, buf);
  10153. putbuf(e, buf, lenbytes);
  10154. putbuf(e, ptr, s->seglen);
  10155. ptr += s->seglen;
  10156. }
  10157. e->ptr = e->buf;
  10158. e->top = NULL;
  10159. } else {
  10160. /* Need to keep buffering; propagate length info into enclosing
  10161. * submessages. */
  10162. --e->top;
  10163. top(e)->msglen += msglen + upb_varint_size(msglen);
  10164. }
  10165. return true;
  10166. }
  10167. /* tag_t **********************************************************************/
  10168. /* A precomputed (pre-encoded) tag and length. */
  10169. typedef struct {
  10170. uint8_t bytes;
  10171. char tag[7];
  10172. } tag_t;
  10173. /* Allocates a new tag for this field, and sets it in these handlerattr. */
  10174. static void new_tag(upb_handlers *h, const upb_fielddef *f, upb_wiretype_t wt,
  10175. upb_handlerattr *attr) {
  10176. uint32_t n = upb_fielddef_number(f);
  10177. tag_t *tag = upb_gmalloc(sizeof(tag_t));
  10178. tag->bytes = upb_vencode64((n << 3) | wt, tag->tag);
  10179. upb_handlerattr_init(attr);
  10180. upb_handlerattr_sethandlerdata(attr, tag);
  10181. upb_handlers_addcleanup(h, tag, upb_gfree);
  10182. }
  10183. static bool encode_tag(upb_pb_encoder *e, const tag_t *tag) {
  10184. return encode_bytes(e, tag->tag, tag->bytes);
  10185. }
  10186. /* encoding of wire types *****************************************************/
  10187. static bool encode_fixed64(upb_pb_encoder *e, uint64_t val) {
  10188. /* TODO(haberman): byte-swap for big endian. */
  10189. return encode_bytes(e, &val, sizeof(uint64_t));
  10190. }
  10191. static bool encode_fixed32(upb_pb_encoder *e, uint32_t val) {
  10192. /* TODO(haberman): byte-swap for big endian. */
  10193. return encode_bytes(e, &val, sizeof(uint32_t));
  10194. }
  10195. static bool encode_varint(upb_pb_encoder *e, uint64_t val) {
  10196. if (!reserve(e, UPB_PB_VARINT_MAX_LEN)) {
  10197. return false;
  10198. }
  10199. encoder_advance(e, upb_vencode64(val, e->ptr));
  10200. return true;
  10201. }
  10202. static uint64_t dbl2uint64(double d) {
  10203. uint64_t ret;
  10204. memcpy(&ret, &d, sizeof(uint64_t));
  10205. return ret;
  10206. }
  10207. static uint32_t flt2uint32(float d) {
  10208. uint32_t ret;
  10209. memcpy(&ret, &d, sizeof(uint32_t));
  10210. return ret;
  10211. }
  10212. /* encoding of proto types ****************************************************/
  10213. static bool startmsg(void *c, const void *hd) {
  10214. upb_pb_encoder *e = c;
  10215. UPB_UNUSED(hd);
  10216. if (e->depth++ == 0) {
  10217. upb_bytessink_start(e->output_, 0, &e->subc);
  10218. }
  10219. return true;
  10220. }
  10221. static bool endmsg(void *c, const void *hd, upb_status *status) {
  10222. upb_pb_encoder *e = c;
  10223. UPB_UNUSED(hd);
  10224. UPB_UNUSED(status);
  10225. if (--e->depth == 0) {
  10226. upb_bytessink_end(e->output_);
  10227. }
  10228. return true;
  10229. }
  10230. static void *encode_startdelimfield(void *c, const void *hd) {
  10231. bool ok = encode_tag(c, hd) && commit(c) && start_delim(c);
  10232. return ok ? c : UPB_BREAK;
  10233. }
  10234. static bool encode_unknown(void *c, const void *hd, const char *buf,
  10235. size_t len) {
  10236. UPB_UNUSED(hd);
  10237. return encode_bytes(c, buf, len) && commit(c);
  10238. }
  10239. static bool encode_enddelimfield(void *c, const void *hd) {
  10240. UPB_UNUSED(hd);
  10241. return end_delim(c);
  10242. }
  10243. static void *encode_startgroup(void *c, const void *hd) {
  10244. return (encode_tag(c, hd) && commit(c)) ? c : UPB_BREAK;
  10245. }
  10246. static bool encode_endgroup(void *c, const void *hd) {
  10247. return encode_tag(c, hd) && commit(c);
  10248. }
  10249. static void *encode_startstr(void *c, const void *hd, size_t size_hint) {
  10250. UPB_UNUSED(size_hint);
  10251. return encode_startdelimfield(c, hd);
  10252. }
  10253. static size_t encode_strbuf(void *c, const void *hd, const char *buf,
  10254. size_t len, const upb_bufhandle *h) {
  10255. UPB_UNUSED(hd);
  10256. UPB_UNUSED(h);
  10257. return encode_bytes(c, buf, len) ? len : 0;
  10258. }
  10259. #define T(type, ctype, convert, encode) \
  10260. static bool encode_scalar_##type(void *e, const void *hd, ctype val) { \
  10261. return encode_tag(e, hd) && encode(e, (convert)(val)) && commit(e); \
  10262. } \
  10263. static bool encode_packed_##type(void *e, const void *hd, ctype val) { \
  10264. UPB_UNUSED(hd); \
  10265. return encode(e, (convert)(val)); \
  10266. }
  10267. T(double, double, dbl2uint64, encode_fixed64)
  10268. T(float, float, flt2uint32, encode_fixed32)
  10269. T(int64, int64_t, uint64_t, encode_varint)
  10270. T(int32, int32_t, int64_t, encode_varint)
  10271. T(fixed64, uint64_t, uint64_t, encode_fixed64)
  10272. T(fixed32, uint32_t, uint32_t, encode_fixed32)
  10273. T(bool, bool, bool, encode_varint)
  10274. T(uint32, uint32_t, uint32_t, encode_varint)
  10275. T(uint64, uint64_t, uint64_t, encode_varint)
  10276. T(enum, int32_t, uint32_t, encode_varint)
  10277. T(sfixed32, int32_t, uint32_t, encode_fixed32)
  10278. T(sfixed64, int64_t, uint64_t, encode_fixed64)
  10279. T(sint32, int32_t, upb_zzenc_32, encode_varint)
  10280. T(sint64, int64_t, upb_zzenc_64, encode_varint)
  10281. #undef T
  10282. /* code to build the handlers *************************************************/
  10283. static void newhandlers_callback(const void *closure, upb_handlers *h) {
  10284. const upb_msgdef *m;
  10285. upb_msg_field_iter i;
  10286. UPB_UNUSED(closure);
  10287. upb_handlers_setstartmsg(h, startmsg, NULL);
  10288. upb_handlers_setendmsg(h, endmsg, NULL);
  10289. upb_handlers_setunknown(h, encode_unknown, NULL);
  10290. m = upb_handlers_msgdef(h);
  10291. for(upb_msg_field_begin(&i, m);
  10292. !upb_msg_field_done(&i);
  10293. upb_msg_field_next(&i)) {
  10294. const upb_fielddef *f = upb_msg_iter_field(&i);
  10295. bool packed = upb_fielddef_isseq(f) && upb_fielddef_isprimitive(f) &&
  10296. upb_fielddef_packed(f);
  10297. upb_handlerattr attr;
  10298. upb_wiretype_t wt =
  10299. packed ? UPB_WIRE_TYPE_DELIMITED
  10300. : upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  10301. /* Pre-encode the tag for this field. */
  10302. new_tag(h, f, wt, &attr);
  10303. if (packed) {
  10304. upb_handlers_setstartseq(h, f, encode_startdelimfield, &attr);
  10305. upb_handlers_setendseq(h, f, encode_enddelimfield, &attr);
  10306. }
  10307. #define T(upper, lower, upbtype) \
  10308. case UPB_DESCRIPTOR_TYPE_##upper: \
  10309. if (packed) { \
  10310. upb_handlers_set##upbtype(h, f, encode_packed_##lower, &attr); \
  10311. } else { \
  10312. upb_handlers_set##upbtype(h, f, encode_scalar_##lower, &attr); \
  10313. } \
  10314. break;
  10315. switch (upb_fielddef_descriptortype(f)) {
  10316. T(DOUBLE, double, double);
  10317. T(FLOAT, float, float);
  10318. T(INT64, int64, int64);
  10319. T(INT32, int32, int32);
  10320. T(FIXED64, fixed64, uint64);
  10321. T(FIXED32, fixed32, uint32);
  10322. T(BOOL, bool, bool);
  10323. T(UINT32, uint32, uint32);
  10324. T(UINT64, uint64, uint64);
  10325. T(ENUM, enum, int32);
  10326. T(SFIXED32, sfixed32, int32);
  10327. T(SFIXED64, sfixed64, int64);
  10328. T(SINT32, sint32, int32);
  10329. T(SINT64, sint64, int64);
  10330. case UPB_DESCRIPTOR_TYPE_STRING:
  10331. case UPB_DESCRIPTOR_TYPE_BYTES:
  10332. upb_handlers_setstartstr(h, f, encode_startstr, &attr);
  10333. upb_handlers_setendstr(h, f, encode_enddelimfield, &attr);
  10334. upb_handlers_setstring(h, f, encode_strbuf, &attr);
  10335. break;
  10336. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  10337. upb_handlers_setstartsubmsg(h, f, encode_startdelimfield, &attr);
  10338. upb_handlers_setendsubmsg(h, f, encode_enddelimfield, &attr);
  10339. break;
  10340. case UPB_DESCRIPTOR_TYPE_GROUP: {
  10341. /* Endgroup takes a different tag (wire_type = END_GROUP). */
  10342. upb_handlerattr attr2;
  10343. new_tag(h, f, UPB_WIRE_TYPE_END_GROUP, &attr2);
  10344. upb_handlers_setstartsubmsg(h, f, encode_startgroup, &attr);
  10345. upb_handlers_setendsubmsg(h, f, encode_endgroup, &attr2);
  10346. upb_handlerattr_uninit(&attr2);
  10347. break;
  10348. }
  10349. }
  10350. #undef T
  10351. upb_handlerattr_uninit(&attr);
  10352. }
  10353. }
  10354. void upb_pb_encoder_reset(upb_pb_encoder *e) {
  10355. e->segptr = NULL;
  10356. e->top = NULL;
  10357. e->depth = 0;
  10358. }
  10359. /* public API *****************************************************************/
  10360. const upb_handlers *upb_pb_encoder_newhandlers(const upb_msgdef *m,
  10361. const void *owner) {
  10362. return upb_handlers_newfrozen(m, owner, newhandlers_callback, NULL);
  10363. }
  10364. upb_pb_encoder *upb_pb_encoder_create(upb_env *env, const upb_handlers *h,
  10365. upb_bytessink *output) {
  10366. const size_t initial_bufsize = 256;
  10367. const size_t initial_segbufsize = 16;
  10368. /* TODO(haberman): make this configurable. */
  10369. const size_t stack_size = 64;
  10370. #ifndef NDEBUG
  10371. const size_t size_before = upb_env_bytesallocated(env);
  10372. #endif
  10373. upb_pb_encoder *e = upb_env_malloc(env, sizeof(upb_pb_encoder));
  10374. if (!e) return NULL;
  10375. e->buf = upb_env_malloc(env, initial_bufsize);
  10376. e->segbuf = upb_env_malloc(env, initial_segbufsize * sizeof(*e->segbuf));
  10377. e->stack = upb_env_malloc(env, stack_size * sizeof(*e->stack));
  10378. if (!e->buf || !e->segbuf || !e->stack) {
  10379. return NULL;
  10380. }
  10381. e->limit = e->buf + initial_bufsize;
  10382. e->seglimit = e->segbuf + initial_segbufsize;
  10383. e->stacklimit = e->stack + stack_size;
  10384. upb_pb_encoder_reset(e);
  10385. upb_sink_reset(&e->input_, h, e);
  10386. e->env = env;
  10387. e->output_ = output;
  10388. e->subc = output->closure;
  10389. e->ptr = e->buf;
  10390. /* If this fails, increase the value in encoder.h. */
  10391. UPB_ASSERT_DEBUGVAR(upb_env_bytesallocated(env) - size_before <=
  10392. UPB_PB_ENCODER_SIZE);
  10393. return e;
  10394. }
  10395. upb_sink *upb_pb_encoder_input(upb_pb_encoder *e) { return &e->input_; }
  10396. upb_filedef **upb_loaddescriptor(const char *buf, size_t n, const void *owner,
  10397. upb_status *status) {
  10398. /* Create handlers. */
  10399. const upb_pbdecodermethod *decoder_m;
  10400. const upb_handlers *reader_h = upb_descreader_newhandlers(&reader_h);
  10401. upb_env env;
  10402. upb_pbdecodermethodopts opts;
  10403. upb_pbdecoder *decoder;
  10404. upb_descreader *reader;
  10405. bool ok;
  10406. size_t i;
  10407. upb_filedef **ret = NULL;
  10408. upb_pbdecodermethodopts_init(&opts, reader_h);
  10409. decoder_m = upb_pbdecodermethod_new(&opts, &decoder_m);
  10410. upb_env_init(&env);
  10411. upb_env_reporterrorsto(&env, status);
  10412. reader = upb_descreader_create(&env, reader_h);
  10413. decoder = upb_pbdecoder_create(&env, decoder_m, upb_descreader_input(reader));
  10414. /* Push input data. */
  10415. ok = upb_bufsrc_putbuf(buf, n, upb_pbdecoder_input(decoder));
  10416. if (!ok) {
  10417. goto cleanup;
  10418. }
  10419. ret = upb_gmalloc(sizeof (*ret) * (upb_descreader_filecount(reader) + 1));
  10420. if (!ret) {
  10421. goto cleanup;
  10422. }
  10423. for (i = 0; i < upb_descreader_filecount(reader); i++) {
  10424. ret[i] = upb_descreader_file(reader, i);
  10425. upb_filedef_ref(ret[i], owner);
  10426. }
  10427. ret[i] = NULL;
  10428. cleanup:
  10429. upb_env_uninit(&env);
  10430. upb_handlers_unref(reader_h, &reader_h);
  10431. upb_pbdecodermethod_unref(decoder_m, &decoder_m);
  10432. return ret;
  10433. }
  10434. /*
  10435. * upb::pb::TextPrinter
  10436. *
  10437. * OPT: This is not optimized at all. It uses printf() which parses the format
  10438. * string every time, and it allocates memory for every put.
  10439. */
  10440. #include <ctype.h>
  10441. #include <float.h>
  10442. #include <inttypes.h>
  10443. #include <stdarg.h>
  10444. #include <stdio.h>
  10445. #include <string.h>
  10446. struct upb_textprinter {
  10447. upb_sink input_;
  10448. upb_bytessink *output_;
  10449. int indent_depth_;
  10450. bool single_line_;
  10451. void *subc;
  10452. };
  10453. #define CHECK(x) if ((x) < 0) goto err;
  10454. static const char *shortname(const char *longname) {
  10455. const char *last = strrchr(longname, '.');
  10456. return last ? last + 1 : longname;
  10457. }
  10458. static int indent(upb_textprinter *p) {
  10459. int i;
  10460. if (!p->single_line_)
  10461. for (i = 0; i < p->indent_depth_; i++)
  10462. upb_bytessink_putbuf(p->output_, p->subc, " ", 2, NULL);
  10463. return 0;
  10464. }
  10465. static int endfield(upb_textprinter *p) {
  10466. const char ch = (p->single_line_ ? ' ' : '\n');
  10467. upb_bytessink_putbuf(p->output_, p->subc, &ch, 1, NULL);
  10468. return 0;
  10469. }
  10470. static int putescaped(upb_textprinter *p, const char *buf, size_t len,
  10471. bool preserve_utf8) {
  10472. /* Based on CEscapeInternal() from Google's protobuf release. */
  10473. char dstbuf[4096], *dst = dstbuf, *dstend = dstbuf + sizeof(dstbuf);
  10474. const char *end = buf + len;
  10475. /* I think hex is prettier and more useful, but proto2 uses octal; should
  10476. * investigate whether it can parse hex also. */
  10477. const bool use_hex = false;
  10478. bool last_hex_escape = false; /* true if last output char was \xNN */
  10479. for (; buf < end; buf++) {
  10480. bool is_hex_escape;
  10481. if (dstend - dst < 4) {
  10482. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  10483. dst = dstbuf;
  10484. }
  10485. is_hex_escape = false;
  10486. switch (*buf) {
  10487. case '\n': *(dst++) = '\\'; *(dst++) = 'n'; break;
  10488. case '\r': *(dst++) = '\\'; *(dst++) = 'r'; break;
  10489. case '\t': *(dst++) = '\\'; *(dst++) = 't'; break;
  10490. case '\"': *(dst++) = '\\'; *(dst++) = '\"'; break;
  10491. case '\'': *(dst++) = '\\'; *(dst++) = '\''; break;
  10492. case '\\': *(dst++) = '\\'; *(dst++) = '\\'; break;
  10493. default:
  10494. /* Note that if we emit \xNN and the buf character after that is a hex
  10495. * digit then that digit must be escaped too to prevent it being
  10496. * interpreted as part of the character code by C. */
  10497. if ((!preserve_utf8 || (uint8_t)*buf < 0x80) &&
  10498. (!isprint(*buf) || (last_hex_escape && isxdigit(*buf)))) {
  10499. sprintf(dst, (use_hex ? "\\x%02x" : "\\%03o"), (uint8_t)*buf);
  10500. is_hex_escape = use_hex;
  10501. dst += 4;
  10502. } else {
  10503. *(dst++) = *buf; break;
  10504. }
  10505. }
  10506. last_hex_escape = is_hex_escape;
  10507. }
  10508. /* Flush remaining data. */
  10509. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  10510. return 0;
  10511. }
  10512. bool putf(upb_textprinter *p, const char *fmt, ...) {
  10513. va_list args;
  10514. va_list args_copy;
  10515. char *str;
  10516. int written;
  10517. int len;
  10518. bool ok;
  10519. va_start(args, fmt);
  10520. /* Run once to get the length of the string. */
  10521. _upb_va_copy(args_copy, args);
  10522. len = _upb_vsnprintf(NULL, 0, fmt, args_copy);
  10523. va_end(args_copy);
  10524. /* + 1 for NULL terminator (vsprintf() requires it even if we don't). */
  10525. str = upb_gmalloc(len + 1);
  10526. if (!str) return false;
  10527. written = vsprintf(str, fmt, args);
  10528. va_end(args);
  10529. UPB_ASSERT(written == len);
  10530. ok = upb_bytessink_putbuf(p->output_, p->subc, str, len, NULL);
  10531. upb_gfree(str);
  10532. return ok;
  10533. }
  10534. /* handlers *******************************************************************/
  10535. static bool textprinter_startmsg(void *c, const void *hd) {
  10536. upb_textprinter *p = c;
  10537. UPB_UNUSED(hd);
  10538. if (p->indent_depth_ == 0) {
  10539. upb_bytessink_start(p->output_, 0, &p->subc);
  10540. }
  10541. return true;
  10542. }
  10543. static bool textprinter_endmsg(void *c, const void *hd, upb_status *s) {
  10544. upb_textprinter *p = c;
  10545. UPB_UNUSED(hd);
  10546. UPB_UNUSED(s);
  10547. if (p->indent_depth_ == 0) {
  10548. upb_bytessink_end(p->output_);
  10549. }
  10550. return true;
  10551. }
  10552. #define TYPE(name, ctype, fmt) \
  10553. static bool textprinter_put ## name(void *closure, const void *handler_data, \
  10554. ctype val) { \
  10555. upb_textprinter *p = closure; \
  10556. const upb_fielddef *f = handler_data; \
  10557. CHECK(indent(p)); \
  10558. putf(p, "%s: " fmt, upb_fielddef_name(f), val); \
  10559. CHECK(endfield(p)); \
  10560. return true; \
  10561. err: \
  10562. return false; \
  10563. }
  10564. static bool textprinter_putbool(void *closure, const void *handler_data,
  10565. bool val) {
  10566. upb_textprinter *p = closure;
  10567. const upb_fielddef *f = handler_data;
  10568. CHECK(indent(p));
  10569. putf(p, "%s: %s", upb_fielddef_name(f), val ? "true" : "false");
  10570. CHECK(endfield(p));
  10571. return true;
  10572. err:
  10573. return false;
  10574. }
  10575. #define STRINGIFY_HELPER(x) #x
  10576. #define STRINGIFY_MACROVAL(x) STRINGIFY_HELPER(x)
  10577. TYPE(int32, int32_t, "%" PRId32)
  10578. TYPE(int64, int64_t, "%" PRId64)
  10579. TYPE(uint32, uint32_t, "%" PRIu32)
  10580. TYPE(uint64, uint64_t, "%" PRIu64)
  10581. TYPE(float, float, "%." STRINGIFY_MACROVAL(FLT_DIG) "g")
  10582. TYPE(double, double, "%." STRINGIFY_MACROVAL(DBL_DIG) "g")
  10583. #undef TYPE
  10584. /* Output a symbolic value from the enum if found, else just print as int32. */
  10585. static bool textprinter_putenum(void *closure, const void *handler_data,
  10586. int32_t val) {
  10587. upb_textprinter *p = closure;
  10588. const upb_fielddef *f = handler_data;
  10589. const upb_enumdef *enum_def = upb_downcast_enumdef(upb_fielddef_subdef(f));
  10590. const char *label = upb_enumdef_iton(enum_def, val);
  10591. if (label) {
  10592. indent(p);
  10593. putf(p, "%s: %s", upb_fielddef_name(f), label);
  10594. endfield(p);
  10595. } else {
  10596. if (!textprinter_putint32(closure, handler_data, val))
  10597. return false;
  10598. }
  10599. return true;
  10600. }
  10601. static void *textprinter_startstr(void *closure, const void *handler_data,
  10602. size_t size_hint) {
  10603. upb_textprinter *p = closure;
  10604. const upb_fielddef *f = handler_data;
  10605. UPB_UNUSED(size_hint);
  10606. indent(p);
  10607. putf(p, "%s: \"", upb_fielddef_name(f));
  10608. return p;
  10609. }
  10610. static bool textprinter_endstr(void *closure, const void *handler_data) {
  10611. upb_textprinter *p = closure;
  10612. UPB_UNUSED(handler_data);
  10613. putf(p, "\"");
  10614. endfield(p);
  10615. return true;
  10616. }
  10617. static size_t textprinter_putstr(void *closure, const void *hd, const char *buf,
  10618. size_t len, const upb_bufhandle *handle) {
  10619. upb_textprinter *p = closure;
  10620. const upb_fielddef *f = hd;
  10621. UPB_UNUSED(handle);
  10622. CHECK(putescaped(p, buf, len, upb_fielddef_type(f) == UPB_TYPE_STRING));
  10623. return len;
  10624. err:
  10625. return 0;
  10626. }
  10627. static void *textprinter_startsubmsg(void *closure, const void *handler_data) {
  10628. upb_textprinter *p = closure;
  10629. const char *name = handler_data;
  10630. CHECK(indent(p));
  10631. putf(p, "%s {%c", name, p->single_line_ ? ' ' : '\n');
  10632. p->indent_depth_++;
  10633. return p;
  10634. err:
  10635. return UPB_BREAK;
  10636. }
  10637. static bool textprinter_endsubmsg(void *closure, const void *handler_data) {
  10638. upb_textprinter *p = closure;
  10639. UPB_UNUSED(handler_data);
  10640. p->indent_depth_--;
  10641. CHECK(indent(p));
  10642. upb_bytessink_putbuf(p->output_, p->subc, "}", 1, NULL);
  10643. CHECK(endfield(p));
  10644. return true;
  10645. err:
  10646. return false;
  10647. }
  10648. static void onmreg(const void *c, upb_handlers *h) {
  10649. const upb_msgdef *m = upb_handlers_msgdef(h);
  10650. upb_msg_field_iter i;
  10651. UPB_UNUSED(c);
  10652. upb_handlers_setstartmsg(h, textprinter_startmsg, NULL);
  10653. upb_handlers_setendmsg(h, textprinter_endmsg, NULL);
  10654. for(upb_msg_field_begin(&i, m);
  10655. !upb_msg_field_done(&i);
  10656. upb_msg_field_next(&i)) {
  10657. upb_fielddef *f = upb_msg_iter_field(&i);
  10658. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  10659. upb_handlerattr_sethandlerdata(&attr, f);
  10660. switch (upb_fielddef_type(f)) {
  10661. case UPB_TYPE_INT32:
  10662. upb_handlers_setint32(h, f, textprinter_putint32, &attr);
  10663. break;
  10664. case UPB_TYPE_INT64:
  10665. upb_handlers_setint64(h, f, textprinter_putint64, &attr);
  10666. break;
  10667. case UPB_TYPE_UINT32:
  10668. upb_handlers_setuint32(h, f, textprinter_putuint32, &attr);
  10669. break;
  10670. case UPB_TYPE_UINT64:
  10671. upb_handlers_setuint64(h, f, textprinter_putuint64, &attr);
  10672. break;
  10673. case UPB_TYPE_FLOAT:
  10674. upb_handlers_setfloat(h, f, textprinter_putfloat, &attr);
  10675. break;
  10676. case UPB_TYPE_DOUBLE:
  10677. upb_handlers_setdouble(h, f, textprinter_putdouble, &attr);
  10678. break;
  10679. case UPB_TYPE_BOOL:
  10680. upb_handlers_setbool(h, f, textprinter_putbool, &attr);
  10681. break;
  10682. case UPB_TYPE_STRING:
  10683. case UPB_TYPE_BYTES:
  10684. upb_handlers_setstartstr(h, f, textprinter_startstr, &attr);
  10685. upb_handlers_setstring(h, f, textprinter_putstr, &attr);
  10686. upb_handlers_setendstr(h, f, textprinter_endstr, &attr);
  10687. break;
  10688. case UPB_TYPE_MESSAGE: {
  10689. const char *name =
  10690. upb_fielddef_istagdelim(f)
  10691. ? shortname(upb_msgdef_fullname(upb_fielddef_msgsubdef(f)))
  10692. : upb_fielddef_name(f);
  10693. upb_handlerattr_sethandlerdata(&attr, name);
  10694. upb_handlers_setstartsubmsg(h, f, textprinter_startsubmsg, &attr);
  10695. upb_handlers_setendsubmsg(h, f, textprinter_endsubmsg, &attr);
  10696. break;
  10697. }
  10698. case UPB_TYPE_ENUM:
  10699. upb_handlers_setint32(h, f, textprinter_putenum, &attr);
  10700. break;
  10701. }
  10702. }
  10703. }
  10704. static void textprinter_reset(upb_textprinter *p, bool single_line) {
  10705. p->single_line_ = single_line;
  10706. p->indent_depth_ = 0;
  10707. }
  10708. /* Public API *****************************************************************/
  10709. upb_textprinter *upb_textprinter_create(upb_env *env, const upb_handlers *h,
  10710. upb_bytessink *output) {
  10711. upb_textprinter *p = upb_env_malloc(env, sizeof(upb_textprinter));
  10712. if (!p) return NULL;
  10713. p->output_ = output;
  10714. upb_sink_reset(&p->input_, h, p);
  10715. textprinter_reset(p, false);
  10716. return p;
  10717. }
  10718. const upb_handlers *upb_textprinter_newhandlers(const upb_msgdef *m,
  10719. const void *owner) {
  10720. return upb_handlers_newfrozen(m, owner, &onmreg, NULL);
  10721. }
  10722. upb_sink *upb_textprinter_input(upb_textprinter *p) { return &p->input_; }
  10723. void upb_textprinter_setsingleline(upb_textprinter *p, bool single_line) {
  10724. p->single_line_ = single_line;
  10725. }
  10726. /* Index is descriptor type. */
  10727. const uint8_t upb_pb_native_wire_types[] = {
  10728. UPB_WIRE_TYPE_END_GROUP, /* ENDGROUP */
  10729. UPB_WIRE_TYPE_64BIT, /* DOUBLE */
  10730. UPB_WIRE_TYPE_32BIT, /* FLOAT */
  10731. UPB_WIRE_TYPE_VARINT, /* INT64 */
  10732. UPB_WIRE_TYPE_VARINT, /* UINT64 */
  10733. UPB_WIRE_TYPE_VARINT, /* INT32 */
  10734. UPB_WIRE_TYPE_64BIT, /* FIXED64 */
  10735. UPB_WIRE_TYPE_32BIT, /* FIXED32 */
  10736. UPB_WIRE_TYPE_VARINT, /* BOOL */
  10737. UPB_WIRE_TYPE_DELIMITED, /* STRING */
  10738. UPB_WIRE_TYPE_START_GROUP, /* GROUP */
  10739. UPB_WIRE_TYPE_DELIMITED, /* MESSAGE */
  10740. UPB_WIRE_TYPE_DELIMITED, /* BYTES */
  10741. UPB_WIRE_TYPE_VARINT, /* UINT32 */
  10742. UPB_WIRE_TYPE_VARINT, /* ENUM */
  10743. UPB_WIRE_TYPE_32BIT, /* SFIXED32 */
  10744. UPB_WIRE_TYPE_64BIT, /* SFIXED64 */
  10745. UPB_WIRE_TYPE_VARINT, /* SINT32 */
  10746. UPB_WIRE_TYPE_VARINT, /* SINT64 */
  10747. };
  10748. /* A basic branch-based decoder, uses 32-bit values to get good performance
  10749. * on 32-bit architectures (but performs well on 64-bits also).
  10750. * This scheme comes from the original Google Protobuf implementation
  10751. * (proto2). */
  10752. upb_decoderet upb_vdecode_max8_branch32(upb_decoderet r) {
  10753. upb_decoderet err = {NULL, 0};
  10754. const char *p = r.p;
  10755. uint32_t low = (uint32_t)r.val;
  10756. uint32_t high = 0;
  10757. uint32_t b;
  10758. b = *(p++); low |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  10759. b = *(p++); low |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  10760. b = *(p++); low |= (b & 0x7fU) << 28;
  10761. high = (b & 0x7fU) >> 4; if (!(b & 0x80)) goto done;
  10762. b = *(p++); high |= (b & 0x7fU) << 3; if (!(b & 0x80)) goto done;
  10763. b = *(p++); high |= (b & 0x7fU) << 10; if (!(b & 0x80)) goto done;
  10764. b = *(p++); high |= (b & 0x7fU) << 17; if (!(b & 0x80)) goto done;
  10765. b = *(p++); high |= (b & 0x7fU) << 24; if (!(b & 0x80)) goto done;
  10766. b = *(p++); high |= (b & 0x7fU) << 31; if (!(b & 0x80)) goto done;
  10767. return err;
  10768. done:
  10769. r.val = ((uint64_t)high << 32) | low;
  10770. r.p = p;
  10771. return r;
  10772. }
  10773. /* Like the previous, but uses 64-bit values. */
  10774. upb_decoderet upb_vdecode_max8_branch64(upb_decoderet r) {
  10775. const char *p = r.p;
  10776. uint64_t val = r.val;
  10777. uint64_t b;
  10778. upb_decoderet err = {NULL, 0};
  10779. b = *(p++); val |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  10780. b = *(p++); val |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  10781. b = *(p++); val |= (b & 0x7fU) << 28; if (!(b & 0x80)) goto done;
  10782. b = *(p++); val |= (b & 0x7fU) << 35; if (!(b & 0x80)) goto done;
  10783. b = *(p++); val |= (b & 0x7fU) << 42; if (!(b & 0x80)) goto done;
  10784. b = *(p++); val |= (b & 0x7fU) << 49; if (!(b & 0x80)) goto done;
  10785. b = *(p++); val |= (b & 0x7fU) << 56; if (!(b & 0x80)) goto done;
  10786. b = *(p++); val |= (b & 0x7fU) << 63; if (!(b & 0x80)) goto done;
  10787. return err;
  10788. done:
  10789. r.val = val;
  10790. r.p = p;
  10791. return r;
  10792. }
  10793. #line 1 "upb/json/parser.rl"
  10794. /*
  10795. ** upb::json::Parser (upb_json_parser)
  10796. **
  10797. ** A parser that uses the Ragel State Machine Compiler to generate
  10798. ** the finite automata.
  10799. **
  10800. ** Ragel only natively handles regular languages, but we can manually
  10801. ** program it a bit to handle context-free languages like JSON, by using
  10802. ** the "fcall" and "fret" constructs.
  10803. **
  10804. ** This parser can handle the basics, but needs several things to be fleshed
  10805. ** out:
  10806. **
  10807. ** - handling of unicode escape sequences (including high surrogate pairs).
  10808. ** - properly check and report errors for unknown fields, stack overflow,
  10809. ** improper array nesting (or lack of nesting).
  10810. ** - handling of base64 sequences with padding characters.
  10811. ** - handling of push-back (non-success returns from sink functions).
  10812. ** - handling of keys/escape-sequences/etc that span input buffers.
  10813. */
  10814. #include <errno.h>
  10815. #include <float.h>
  10816. #include <math.h>
  10817. #include <stdint.h>
  10818. #include <stdio.h>
  10819. #include <stdlib.h>
  10820. #include <string.h>
  10821. #include <time.h>
  10822. #define UPB_JSON_MAX_DEPTH 64
  10823. /* Type of value message */
  10824. enum {
  10825. VALUE_NULLVALUE = 0,
  10826. VALUE_NUMBERVALUE = 1,
  10827. VALUE_STRINGVALUE = 2,
  10828. VALUE_BOOLVALUE = 3,
  10829. VALUE_STRUCTVALUE = 4,
  10830. VALUE_LISTVALUE = 5
  10831. };
  10832. /* Forward declare */
  10833. static bool is_top_level(upb_json_parser *p);
  10834. static bool is_wellknown_msg(upb_json_parser *p, upb_wellknowntype_t type);
  10835. static bool is_wellknown_field(upb_json_parser *p, upb_wellknowntype_t type);
  10836. static bool is_number_wrapper_object(upb_json_parser *p);
  10837. static bool does_number_wrapper_start(upb_json_parser *p);
  10838. static bool does_number_wrapper_end(upb_json_parser *p);
  10839. static bool is_string_wrapper_object(upb_json_parser *p);
  10840. static bool does_string_wrapper_start(upb_json_parser *p);
  10841. static bool does_string_wrapper_end(upb_json_parser *p);
  10842. static bool is_fieldmask_object(upb_json_parser *p);
  10843. static bool does_fieldmask_start(upb_json_parser *p);
  10844. static bool does_fieldmask_end(upb_json_parser *p);
  10845. static void start_fieldmask_object(upb_json_parser *p);
  10846. static void end_fieldmask_object(upb_json_parser *p);
  10847. static void start_wrapper_object(upb_json_parser *p);
  10848. static void end_wrapper_object(upb_json_parser *p);
  10849. static void start_value_object(upb_json_parser *p, int value_type);
  10850. static void end_value_object(upb_json_parser *p);
  10851. static void start_listvalue_object(upb_json_parser *p);
  10852. static void end_listvalue_object(upb_json_parser *p);
  10853. static void start_structvalue_object(upb_json_parser *p);
  10854. static void end_structvalue_object(upb_json_parser *p);
  10855. static void start_object(upb_json_parser *p);
  10856. static void end_object(upb_json_parser *p);
  10857. static void start_any_object(upb_json_parser *p, const char *ptr);
  10858. static bool end_any_object(upb_json_parser *p, const char *ptr);
  10859. static bool start_subobject(upb_json_parser *p);
  10860. static void end_subobject(upb_json_parser *p);
  10861. static void start_member(upb_json_parser *p);
  10862. static void end_member(upb_json_parser *p);
  10863. static bool end_membername(upb_json_parser *p);
  10864. static void start_any_member(upb_json_parser *p, const char *ptr);
  10865. static void end_any_member(upb_json_parser *p, const char *ptr);
  10866. static bool end_any_membername(upb_json_parser *p);
  10867. size_t parse(void *closure, const void *hd, const char *buf, size_t size,
  10868. const upb_bufhandle *handle);
  10869. static bool end(void *closure, const void *hd);
  10870. static const char eof_ch = 'e';
  10871. /* stringsink */
  10872. typedef struct {
  10873. upb_byteshandler handler;
  10874. upb_bytessink sink;
  10875. char *ptr;
  10876. size_t len, size;
  10877. } upb_stringsink;
  10878. static void *stringsink_start(void *_sink, const void *hd, size_t size_hint) {
  10879. upb_stringsink *sink = _sink;
  10880. sink->len = 0;
  10881. UPB_UNUSED(hd);
  10882. UPB_UNUSED(size_hint);
  10883. return sink;
  10884. }
  10885. static size_t stringsink_string(void *_sink, const void *hd, const char *ptr,
  10886. size_t len, const upb_bufhandle *handle) {
  10887. upb_stringsink *sink = _sink;
  10888. size_t new_size = sink->size;
  10889. UPB_UNUSED(hd);
  10890. UPB_UNUSED(handle);
  10891. while (sink->len + len > new_size) {
  10892. new_size *= 2;
  10893. }
  10894. if (new_size != sink->size) {
  10895. sink->ptr = realloc(sink->ptr, new_size);
  10896. sink->size = new_size;
  10897. }
  10898. memcpy(sink->ptr + sink->len, ptr, len);
  10899. sink->len += len;
  10900. return len;
  10901. }
  10902. void upb_stringsink_init(upb_stringsink *sink) {
  10903. upb_byteshandler_init(&sink->handler);
  10904. upb_byteshandler_setstartstr(&sink->handler, stringsink_start, NULL);
  10905. upb_byteshandler_setstring(&sink->handler, stringsink_string, NULL);
  10906. upb_bytessink_reset(&sink->sink, &sink->handler, sink);
  10907. sink->size = 32;
  10908. sink->ptr = malloc(sink->size);
  10909. sink->len = 0;
  10910. }
  10911. void upb_stringsink_uninit(upb_stringsink *sink) { free(sink->ptr); }
  10912. typedef struct {
  10913. /* For encoding Any value field in binary format. */
  10914. const upb_handlers *encoder_handlers;
  10915. upb_pb_encoder *encoder;
  10916. upb_stringsink stringsink;
  10917. /* For decoding Any value field in json format. */
  10918. upb_json_parsermethod *parser_method;
  10919. upb_json_parser* parser;
  10920. upb_sink sink;
  10921. /* Mark the range of uninterpreted values in json input before type url. */
  10922. const char *before_type_url_start;
  10923. const char *before_type_url_end;
  10924. /* Mark the range of uninterpreted values in json input after type url. */
  10925. const char *after_type_url_start;
  10926. } upb_jsonparser_any_frame;
  10927. typedef struct {
  10928. upb_sink sink;
  10929. /* The current message in which we're parsing, and the field whose value we're
  10930. * expecting next. */
  10931. const upb_msgdef *m;
  10932. const upb_fielddef *f;
  10933. /* The table mapping json name to fielddef for this message. */
  10934. upb_strtable *name_table;
  10935. /* We are in a repeated-field context, ready to emit mapentries as
  10936. * submessages. This flag alters the start-of-object (open-brace) behavior to
  10937. * begin a sequence of mapentry messages rather than a single submessage. */
  10938. bool is_map;
  10939. /* We are in a map-entry message context. This flag is set when parsing the
  10940. * value field of a single map entry and indicates to all value-field parsers
  10941. * (subobjects, strings, numbers, and bools) that the map-entry submessage
  10942. * should end as soon as the value is parsed. */
  10943. bool is_mapentry;
  10944. /* If |is_map| or |is_mapentry| is true, |mapfield| refers to the parent
  10945. * message's map field that we're currently parsing. This differs from |f|
  10946. * because |f| is the field in the *current* message (i.e., the map-entry
  10947. * message itself), not the parent's field that leads to this map. */
  10948. const upb_fielddef *mapfield;
  10949. /* We are in an Any message context. This flag is set when parsing the Any
  10950. * message and indicates to all field parsers (subobjects, strings, numbers,
  10951. * and bools) that the parsed field should be serialized as binary data or
  10952. * cached (type url not found yet). */
  10953. bool is_any;
  10954. /* The type of packed message in Any. */
  10955. upb_jsonparser_any_frame *any_frame;
  10956. /* True if the field to be parsed is unknown. */
  10957. bool is_unknown_field;
  10958. } upb_jsonparser_frame;
  10959. struct upb_json_parser {
  10960. upb_env *env;
  10961. const upb_json_parsermethod *method;
  10962. upb_bytessink input_;
  10963. /* Stack to track the JSON scopes we are in. */
  10964. upb_jsonparser_frame stack[UPB_JSON_MAX_DEPTH];
  10965. upb_jsonparser_frame *top;
  10966. upb_jsonparser_frame *limit;
  10967. upb_status status;
  10968. /* Ragel's internal parsing stack for the parsing state machine. */
  10969. int current_state;
  10970. int parser_stack[UPB_JSON_MAX_DEPTH];
  10971. int parser_top;
  10972. /* The handle for the current buffer. */
  10973. const upb_bufhandle *handle;
  10974. /* Accumulate buffer. See details in parser.rl. */
  10975. const char *accumulated;
  10976. size_t accumulated_len;
  10977. char *accumulate_buf;
  10978. size_t accumulate_buf_size;
  10979. /* Multi-part text data. See details in parser.rl. */
  10980. int multipart_state;
  10981. upb_selector_t string_selector;
  10982. /* Input capture. See details in parser.rl. */
  10983. const char *capture;
  10984. /* Intermediate result of parsing a unicode escape sequence. */
  10985. uint32_t digit;
  10986. /* For resolve type url in Any. */
  10987. const upb_symtab *symtab;
  10988. /* Whether to proceed if unknown field is met. */
  10989. bool ignore_json_unknown;
  10990. /* Cache for parsing timestamp due to base and zone are handled in different
  10991. * handlers. */
  10992. struct tm tm;
  10993. };
  10994. struct upb_json_parsermethod {
  10995. upb_refcounted base;
  10996. upb_byteshandler input_handler_;
  10997. /* Mainly for the purposes of refcounting, so all the fielddefs we point
  10998. * to stay alive. */
  10999. const upb_msgdef *msg;
  11000. /* Keys are upb_msgdef*, values are upb_strtable (json_name -> fielddef) */
  11001. upb_inttable name_tables;
  11002. };
  11003. #define PARSER_CHECK_RETURN(x) if (!(x)) return false
  11004. static void json_parser_any_frame_reset(upb_jsonparser_any_frame *frame) {
  11005. frame->encoder_handlers = NULL;
  11006. frame->encoder = NULL;
  11007. frame->parser_method = NULL;
  11008. frame->parser = NULL;
  11009. frame->before_type_url_start = NULL;
  11010. frame->before_type_url_end = NULL;
  11011. frame->after_type_url_start = NULL;
  11012. }
  11013. static void json_parser_any_frame_set_payload_type(
  11014. upb_json_parser *p,
  11015. upb_jsonparser_any_frame *frame,
  11016. const upb_msgdef *payload_type) {
  11017. /* Initialize encoder. */
  11018. frame->encoder_handlers =
  11019. upb_pb_encoder_newhandlers(payload_type, &frame->encoder_handlers);
  11020. upb_stringsink_init(&frame->stringsink);
  11021. frame->encoder =
  11022. upb_pb_encoder_create(
  11023. p->env, frame->encoder_handlers,
  11024. &frame->stringsink.sink);
  11025. /* Initialize parser. */
  11026. frame->parser_method =
  11027. upb_json_parsermethod_new(payload_type, &frame->parser_method);
  11028. upb_sink_reset(&frame->sink, frame->encoder_handlers, frame->encoder);
  11029. frame->parser =
  11030. upb_json_parser_create(p->env, frame->parser_method, p->symtab,
  11031. &frame->sink, p->ignore_json_unknown);
  11032. }
  11033. static void json_parser_any_frame_free(upb_jsonparser_any_frame *frame) {
  11034. upb_handlers_unref(frame->encoder_handlers,
  11035. &frame->encoder_handlers);
  11036. upb_json_parsermethod_unref(frame->parser_method,
  11037. &frame->parser_method);
  11038. upb_stringsink_uninit(&frame->stringsink);
  11039. }
  11040. static bool json_parser_any_frame_has_type_url(
  11041. upb_jsonparser_any_frame *frame) {
  11042. return frame->encoder != NULL;
  11043. }
  11044. static bool json_parser_any_frame_has_value_before_type_url(
  11045. upb_jsonparser_any_frame *frame) {
  11046. return frame->before_type_url_start != frame->before_type_url_end;
  11047. }
  11048. static bool json_parser_any_frame_has_value_after_type_url(
  11049. upb_jsonparser_any_frame *frame) {
  11050. return frame->after_type_url_start != NULL;
  11051. }
  11052. static bool json_parser_any_frame_has_value(
  11053. upb_jsonparser_any_frame *frame) {
  11054. return json_parser_any_frame_has_value_before_type_url(frame) ||
  11055. json_parser_any_frame_has_value_after_type_url(frame);
  11056. }
  11057. static void json_parser_any_frame_set_before_type_url_end(
  11058. upb_jsonparser_any_frame *frame,
  11059. const char *ptr) {
  11060. if (frame->encoder == NULL) {
  11061. frame->before_type_url_end = ptr;
  11062. }
  11063. }
  11064. static void json_parser_any_frame_set_after_type_url_start_once(
  11065. upb_jsonparser_any_frame *frame,
  11066. const char *ptr) {
  11067. if (json_parser_any_frame_has_type_url(frame) &&
  11068. frame->after_type_url_start == NULL) {
  11069. frame->after_type_url_start = ptr;
  11070. }
  11071. }
  11072. /* Used to signal that a capture has been suspended. */
  11073. static char suspend_capture;
  11074. static upb_selector_t getsel_for_handlertype(upb_json_parser *p,
  11075. upb_handlertype_t type) {
  11076. upb_selector_t sel;
  11077. bool ok = upb_handlers_getselector(p->top->f, type, &sel);
  11078. UPB_ASSERT(ok);
  11079. return sel;
  11080. }
  11081. static upb_selector_t parser_getsel(upb_json_parser *p) {
  11082. return getsel_for_handlertype(
  11083. p, upb_handlers_getprimitivehandlertype(p->top->f));
  11084. }
  11085. static bool check_stack(upb_json_parser *p) {
  11086. if ((p->top + 1) == p->limit) {
  11087. upb_status_seterrmsg(&p->status, "Nesting too deep");
  11088. upb_env_reporterror(p->env, &p->status);
  11089. return false;
  11090. }
  11091. return true;
  11092. }
  11093. static void set_name_table(upb_json_parser *p, upb_jsonparser_frame *frame) {
  11094. upb_value v;
  11095. bool ok = upb_inttable_lookupptr(&p->method->name_tables, frame->m, &v);
  11096. UPB_ASSERT(ok);
  11097. frame->name_table = upb_value_getptr(v);
  11098. }
  11099. /* There are GCC/Clang built-ins for overflow checking which we could start
  11100. * using if there was any performance benefit to it. */
  11101. static bool checked_add(size_t a, size_t b, size_t *c) {
  11102. if (SIZE_MAX - a < b) return false;
  11103. *c = a + b;
  11104. return true;
  11105. }
  11106. static size_t saturating_multiply(size_t a, size_t b) {
  11107. /* size_t is unsigned, so this is defined behavior even on overflow. */
  11108. size_t ret = a * b;
  11109. if (b != 0 && ret / b != a) {
  11110. ret = SIZE_MAX;
  11111. }
  11112. return ret;
  11113. }
  11114. /* Base64 decoding ************************************************************/
  11115. /* TODO(haberman): make this streaming. */
  11116. static const signed char b64table[] = {
  11117. -1, -1, -1, -1, -1, -1, -1, -1,
  11118. -1, -1, -1, -1, -1, -1, -1, -1,
  11119. -1, -1, -1, -1, -1, -1, -1, -1,
  11120. -1, -1, -1, -1, -1, -1, -1, -1,
  11121. -1, -1, -1, -1, -1, -1, -1, -1,
  11122. -1, -1, -1, 62/*+*/, -1, -1, -1, 63/*/ */,
  11123. 52/*0*/, 53/*1*/, 54/*2*/, 55/*3*/, 56/*4*/, 57/*5*/, 58/*6*/, 59/*7*/,
  11124. 60/*8*/, 61/*9*/, -1, -1, -1, -1, -1, -1,
  11125. -1, 0/*A*/, 1/*B*/, 2/*C*/, 3/*D*/, 4/*E*/, 5/*F*/, 6/*G*/,
  11126. 07/*H*/, 8/*I*/, 9/*J*/, 10/*K*/, 11/*L*/, 12/*M*/, 13/*N*/, 14/*O*/,
  11127. 15/*P*/, 16/*Q*/, 17/*R*/, 18/*S*/, 19/*T*/, 20/*U*/, 21/*V*/, 22/*W*/,
  11128. 23/*X*/, 24/*Y*/, 25/*Z*/, -1, -1, -1, -1, -1,
  11129. -1, 26/*a*/, 27/*b*/, 28/*c*/, 29/*d*/, 30/*e*/, 31/*f*/, 32/*g*/,
  11130. 33/*h*/, 34/*i*/, 35/*j*/, 36/*k*/, 37/*l*/, 38/*m*/, 39/*n*/, 40/*o*/,
  11131. 41/*p*/, 42/*q*/, 43/*r*/, 44/*s*/, 45/*t*/, 46/*u*/, 47/*v*/, 48/*w*/,
  11132. 49/*x*/, 50/*y*/, 51/*z*/, -1, -1, -1, -1, -1,
  11133. -1, -1, -1, -1, -1, -1, -1, -1,
  11134. -1, -1, -1, -1, -1, -1, -1, -1,
  11135. -1, -1, -1, -1, -1, -1, -1, -1,
  11136. -1, -1, -1, -1, -1, -1, -1, -1,
  11137. -1, -1, -1, -1, -1, -1, -1, -1,
  11138. -1, -1, -1, -1, -1, -1, -1, -1,
  11139. -1, -1, -1, -1, -1, -1, -1, -1,
  11140. -1, -1, -1, -1, -1, -1, -1, -1,
  11141. -1, -1, -1, -1, -1, -1, -1, -1,
  11142. -1, -1, -1, -1, -1, -1, -1, -1,
  11143. -1, -1, -1, -1, -1, -1, -1, -1,
  11144. -1, -1, -1, -1, -1, -1, -1, -1,
  11145. -1, -1, -1, -1, -1, -1, -1, -1,
  11146. -1, -1, -1, -1, -1, -1, -1, -1,
  11147. -1, -1, -1, -1, -1, -1, -1, -1,
  11148. -1, -1, -1, -1, -1, -1, -1, -1
  11149. };
  11150. /* Returns the table value sign-extended to 32 bits. Knowing that the upper
  11151. * bits will be 1 for unrecognized characters makes it easier to check for
  11152. * this error condition later (see below). */
  11153. int32_t b64lookup(unsigned char ch) { return b64table[ch]; }
  11154. /* Returns true if the given character is not a valid base64 character or
  11155. * padding. */
  11156. bool nonbase64(unsigned char ch) { return b64lookup(ch) == -1 && ch != '='; }
  11157. static bool base64_push(upb_json_parser *p, upb_selector_t sel, const char *ptr,
  11158. size_t len) {
  11159. const char *limit = ptr + len;
  11160. for (; ptr < limit; ptr += 4) {
  11161. uint32_t val;
  11162. char output[3];
  11163. if (limit - ptr < 4) {
  11164. upb_status_seterrf(&p->status,
  11165. "Base64 input for bytes field not a multiple of 4: %s",
  11166. upb_fielddef_name(p->top->f));
  11167. upb_env_reporterror(p->env, &p->status);
  11168. return false;
  11169. }
  11170. val = b64lookup(ptr[0]) << 18 |
  11171. b64lookup(ptr[1]) << 12 |
  11172. b64lookup(ptr[2]) << 6 |
  11173. b64lookup(ptr[3]);
  11174. /* Test the upper bit; returns true if any of the characters returned -1. */
  11175. if (val & 0x80000000) {
  11176. goto otherchar;
  11177. }
  11178. output[0] = val >> 16;
  11179. output[1] = (val >> 8) & 0xff;
  11180. output[2] = val & 0xff;
  11181. upb_sink_putstring(&p->top->sink, sel, output, 3, NULL);
  11182. }
  11183. return true;
  11184. otherchar:
  11185. if (nonbase64(ptr[0]) || nonbase64(ptr[1]) || nonbase64(ptr[2]) ||
  11186. nonbase64(ptr[3]) ) {
  11187. upb_status_seterrf(&p->status,
  11188. "Non-base64 characters in bytes field: %s",
  11189. upb_fielddef_name(p->top->f));
  11190. upb_env_reporterror(p->env, &p->status);
  11191. return false;
  11192. } if (ptr[2] == '=') {
  11193. uint32_t val;
  11194. char output;
  11195. /* Last group contains only two input bytes, one output byte. */
  11196. if (ptr[0] == '=' || ptr[1] == '=' || ptr[3] != '=') {
  11197. goto badpadding;
  11198. }
  11199. val = b64lookup(ptr[0]) << 18 |
  11200. b64lookup(ptr[1]) << 12;
  11201. UPB_ASSERT(!(val & 0x80000000));
  11202. output = val >> 16;
  11203. upb_sink_putstring(&p->top->sink, sel, &output, 1, NULL);
  11204. return true;
  11205. } else {
  11206. uint32_t val;
  11207. char output[2];
  11208. /* Last group contains only three input bytes, two output bytes. */
  11209. if (ptr[0] == '=' || ptr[1] == '=' || ptr[2] == '=') {
  11210. goto badpadding;
  11211. }
  11212. val = b64lookup(ptr[0]) << 18 |
  11213. b64lookup(ptr[1]) << 12 |
  11214. b64lookup(ptr[2]) << 6;
  11215. output[0] = val >> 16;
  11216. output[1] = (val >> 8) & 0xff;
  11217. upb_sink_putstring(&p->top->sink, sel, output, 2, NULL);
  11218. return true;
  11219. }
  11220. badpadding:
  11221. upb_status_seterrf(&p->status,
  11222. "Incorrect base64 padding for field: %s (%.*s)",
  11223. upb_fielddef_name(p->top->f),
  11224. 4, ptr);
  11225. upb_env_reporterror(p->env, &p->status);
  11226. return false;
  11227. }
  11228. /* Accumulate buffer **********************************************************/
  11229. /* Functionality for accumulating a buffer.
  11230. *
  11231. * Some parts of the parser need an entire value as a contiguous string. For
  11232. * example, to look up a member name in a hash table, or to turn a string into
  11233. * a number, the relevant library routines need the input string to be in
  11234. * contiguous memory, even if the value spanned two or more buffers in the
  11235. * input. These routines handle that.
  11236. *
  11237. * In the common case we can just point to the input buffer to get this
  11238. * contiguous string and avoid any actual copy. So we optimistically begin
  11239. * this way. But there are a few cases where we must instead copy into a
  11240. * separate buffer:
  11241. *
  11242. * 1. The string was not contiguous in the input (it spanned buffers).
  11243. *
  11244. * 2. The string included escape sequences that need to be interpreted to get
  11245. * the true value in a contiguous buffer. */
  11246. static void assert_accumulate_empty(upb_json_parser *p) {
  11247. UPB_ASSERT(p->accumulated == NULL);
  11248. UPB_ASSERT(p->accumulated_len == 0);
  11249. }
  11250. static void accumulate_clear(upb_json_parser *p) {
  11251. p->accumulated = NULL;
  11252. p->accumulated_len = 0;
  11253. }
  11254. /* Used internally by accumulate_append(). */
  11255. static bool accumulate_realloc(upb_json_parser *p, size_t need) {
  11256. void *mem;
  11257. size_t old_size = p->accumulate_buf_size;
  11258. size_t new_size = UPB_MAX(old_size, 128);
  11259. while (new_size < need) {
  11260. new_size = saturating_multiply(new_size, 2);
  11261. }
  11262. mem = upb_env_realloc(p->env, p->accumulate_buf, old_size, new_size);
  11263. if (!mem) {
  11264. upb_status_seterrmsg(&p->status, "Out of memory allocating buffer.");
  11265. upb_env_reporterror(p->env, &p->status);
  11266. return false;
  11267. }
  11268. p->accumulate_buf = mem;
  11269. p->accumulate_buf_size = new_size;
  11270. return true;
  11271. }
  11272. /* Logically appends the given data to the append buffer.
  11273. * If "can_alias" is true, we will try to avoid actually copying, but the buffer
  11274. * must be valid until the next accumulate_append() call (if any). */
  11275. static bool accumulate_append(upb_json_parser *p, const char *buf, size_t len,
  11276. bool can_alias) {
  11277. size_t need;
  11278. if (!p->accumulated && can_alias) {
  11279. p->accumulated = buf;
  11280. p->accumulated_len = len;
  11281. return true;
  11282. }
  11283. if (!checked_add(p->accumulated_len, len, &need)) {
  11284. upb_status_seterrmsg(&p->status, "Integer overflow.");
  11285. upb_env_reporterror(p->env, &p->status);
  11286. return false;
  11287. }
  11288. if (need > p->accumulate_buf_size && !accumulate_realloc(p, need)) {
  11289. return false;
  11290. }
  11291. if (p->accumulated != p->accumulate_buf) {
  11292. memcpy(p->accumulate_buf, p->accumulated, p->accumulated_len);
  11293. p->accumulated = p->accumulate_buf;
  11294. }
  11295. memcpy(p->accumulate_buf + p->accumulated_len, buf, len);
  11296. p->accumulated_len += len;
  11297. return true;
  11298. }
  11299. /* Returns a pointer to the data accumulated since the last accumulate_clear()
  11300. * call, and writes the length to *len. This with point either to the input
  11301. * buffer or a temporary accumulate buffer. */
  11302. static const char *accumulate_getptr(upb_json_parser *p, size_t *len) {
  11303. UPB_ASSERT(p->accumulated);
  11304. *len = p->accumulated_len;
  11305. return p->accumulated;
  11306. }
  11307. /* Mult-part text data ********************************************************/
  11308. /* When we have text data in the input, it can often come in multiple segments.
  11309. * For example, there may be some raw string data followed by an escape
  11310. * sequence. The two segments are processed with different logic. Also buffer
  11311. * seams in the input can cause multiple segments.
  11312. *
  11313. * As we see segments, there are two main cases for how we want to process them:
  11314. *
  11315. * 1. we want to push the captured input directly to string handlers.
  11316. *
  11317. * 2. we need to accumulate all the parts into a contiguous buffer for further
  11318. * processing (field name lookup, string->number conversion, etc). */
  11319. /* This is the set of states for p->multipart_state. */
  11320. enum {
  11321. /* We are not currently processing multipart data. */
  11322. MULTIPART_INACTIVE = 0,
  11323. /* We are processing multipart data by accumulating it into a contiguous
  11324. * buffer. */
  11325. MULTIPART_ACCUMULATE = 1,
  11326. /* We are processing multipart data by pushing each part directly to the
  11327. * current string handlers. */
  11328. MULTIPART_PUSHEAGERLY = 2
  11329. };
  11330. /* Start a multi-part text value where we accumulate the data for processing at
  11331. * the end. */
  11332. static void multipart_startaccum(upb_json_parser *p) {
  11333. assert_accumulate_empty(p);
  11334. UPB_ASSERT(p->multipart_state == MULTIPART_INACTIVE);
  11335. p->multipart_state = MULTIPART_ACCUMULATE;
  11336. }
  11337. /* Start a multi-part text value where we immediately push text data to a string
  11338. * value with the given selector. */
  11339. static void multipart_start(upb_json_parser *p, upb_selector_t sel) {
  11340. assert_accumulate_empty(p);
  11341. UPB_ASSERT(p->multipart_state == MULTIPART_INACTIVE);
  11342. p->multipart_state = MULTIPART_PUSHEAGERLY;
  11343. p->string_selector = sel;
  11344. }
  11345. static bool multipart_text(upb_json_parser *p, const char *buf, size_t len,
  11346. bool can_alias) {
  11347. switch (p->multipart_state) {
  11348. case MULTIPART_INACTIVE:
  11349. upb_status_seterrmsg(
  11350. &p->status, "Internal error: unexpected state MULTIPART_INACTIVE");
  11351. upb_env_reporterror(p->env, &p->status);
  11352. return false;
  11353. case MULTIPART_ACCUMULATE:
  11354. if (!accumulate_append(p, buf, len, can_alias)) {
  11355. return false;
  11356. }
  11357. break;
  11358. case MULTIPART_PUSHEAGERLY: {
  11359. const upb_bufhandle *handle = can_alias ? p->handle : NULL;
  11360. upb_sink_putstring(&p->top->sink, p->string_selector, buf, len, handle);
  11361. break;
  11362. }
  11363. }
  11364. return true;
  11365. }
  11366. /* Note: this invalidates the accumulate buffer! Call only after reading its
  11367. * contents. */
  11368. static void multipart_end(upb_json_parser *p) {
  11369. UPB_ASSERT(p->multipart_state != MULTIPART_INACTIVE);
  11370. p->multipart_state = MULTIPART_INACTIVE;
  11371. accumulate_clear(p);
  11372. }
  11373. /* Input capture **************************************************************/
  11374. /* Functionality for capturing a region of the input as text. Gracefully
  11375. * handles the case where a buffer seam occurs in the middle of the captured
  11376. * region. */
  11377. static void capture_begin(upb_json_parser *p, const char *ptr) {
  11378. UPB_ASSERT(p->multipart_state != MULTIPART_INACTIVE);
  11379. UPB_ASSERT(p->capture == NULL);
  11380. p->capture = ptr;
  11381. }
  11382. static bool capture_end(upb_json_parser *p, const char *ptr) {
  11383. UPB_ASSERT(p->capture);
  11384. if (multipart_text(p, p->capture, ptr - p->capture, true)) {
  11385. p->capture = NULL;
  11386. return true;
  11387. } else {
  11388. return false;
  11389. }
  11390. }
  11391. /* This is called at the end of each input buffer (ie. when we have hit a
  11392. * buffer seam). If we are in the middle of capturing the input, this
  11393. * processes the unprocessed capture region. */
  11394. static void capture_suspend(upb_json_parser *p, const char **ptr) {
  11395. if (!p->capture) return;
  11396. if (multipart_text(p, p->capture, *ptr - p->capture, false)) {
  11397. /* We use this as a signal that we were in the middle of capturing, and
  11398. * that capturing should resume at the beginning of the next buffer.
  11399. *
  11400. * We can't use *ptr here, because we have no guarantee that this pointer
  11401. * will be valid when we resume (if the underlying memory is freed, then
  11402. * using the pointer at all, even to compare to NULL, is likely undefined
  11403. * behavior). */
  11404. p->capture = &suspend_capture;
  11405. } else {
  11406. /* Need to back up the pointer to the beginning of the capture, since
  11407. * we were not able to actually preserve it. */
  11408. *ptr = p->capture;
  11409. }
  11410. }
  11411. static void capture_resume(upb_json_parser *p, const char *ptr) {
  11412. if (p->capture) {
  11413. UPB_ASSERT(p->capture == &suspend_capture);
  11414. p->capture = ptr;
  11415. }
  11416. }
  11417. /* Callbacks from the parser **************************************************/
  11418. /* These are the functions called directly from the parser itself.
  11419. * We define these in the same order as their declarations in the parser. */
  11420. static char escape_char(char in) {
  11421. switch (in) {
  11422. case 'r': return '\r';
  11423. case 't': return '\t';
  11424. case 'n': return '\n';
  11425. case 'f': return '\f';
  11426. case 'b': return '\b';
  11427. case '/': return '/';
  11428. case '"': return '"';
  11429. case '\\': return '\\';
  11430. default:
  11431. UPB_ASSERT(0);
  11432. return 'x';
  11433. }
  11434. }
  11435. static bool escape(upb_json_parser *p, const char *ptr) {
  11436. char ch = escape_char(*ptr);
  11437. return multipart_text(p, &ch, 1, false);
  11438. }
  11439. static void start_hex(upb_json_parser *p) {
  11440. p->digit = 0;
  11441. }
  11442. static void hexdigit(upb_json_parser *p, const char *ptr) {
  11443. char ch = *ptr;
  11444. p->digit <<= 4;
  11445. if (ch >= '0' && ch <= '9') {
  11446. p->digit += (ch - '0');
  11447. } else if (ch >= 'a' && ch <= 'f') {
  11448. p->digit += ((ch - 'a') + 10);
  11449. } else {
  11450. UPB_ASSERT(ch >= 'A' && ch <= 'F');
  11451. p->digit += ((ch - 'A') + 10);
  11452. }
  11453. }
  11454. static bool end_hex(upb_json_parser *p) {
  11455. uint32_t codepoint = p->digit;
  11456. /* emit the codepoint as UTF-8. */
  11457. char utf8[3]; /* support \u0000 -- \uFFFF -- need only three bytes. */
  11458. int length = 0;
  11459. if (codepoint <= 0x7F) {
  11460. utf8[0] = codepoint;
  11461. length = 1;
  11462. } else if (codepoint <= 0x07FF) {
  11463. utf8[1] = (codepoint & 0x3F) | 0x80;
  11464. codepoint >>= 6;
  11465. utf8[0] = (codepoint & 0x1F) | 0xC0;
  11466. length = 2;
  11467. } else /* codepoint <= 0xFFFF */ {
  11468. utf8[2] = (codepoint & 0x3F) | 0x80;
  11469. codepoint >>= 6;
  11470. utf8[1] = (codepoint & 0x3F) | 0x80;
  11471. codepoint >>= 6;
  11472. utf8[0] = (codepoint & 0x0F) | 0xE0;
  11473. length = 3;
  11474. }
  11475. /* TODO(haberman): Handle high surrogates: if codepoint is a high surrogate
  11476. * we have to wait for the next escape to get the full code point). */
  11477. return multipart_text(p, utf8, length, false);
  11478. }
  11479. static void start_text(upb_json_parser *p, const char *ptr) {
  11480. capture_begin(p, ptr);
  11481. }
  11482. static bool end_text(upb_json_parser *p, const char *ptr) {
  11483. return capture_end(p, ptr);
  11484. }
  11485. static bool start_number(upb_json_parser *p, const char *ptr) {
  11486. if (is_top_level(p)) {
  11487. if (is_number_wrapper_object(p)) {
  11488. start_wrapper_object(p);
  11489. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  11490. start_value_object(p, VALUE_NUMBERVALUE);
  11491. } else {
  11492. return false;
  11493. }
  11494. } else if (does_number_wrapper_start(p)) {
  11495. if (!start_subobject(p)) {
  11496. return false;
  11497. }
  11498. start_wrapper_object(p);
  11499. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  11500. if (!start_subobject(p)) {
  11501. return false;
  11502. }
  11503. start_value_object(p, VALUE_NUMBERVALUE);
  11504. }
  11505. multipart_startaccum(p);
  11506. capture_begin(p, ptr);
  11507. return true;
  11508. }
  11509. static bool parse_number(upb_json_parser *p, bool is_quoted);
  11510. static bool end_number_nontop(upb_json_parser *p, const char *ptr) {
  11511. if (!capture_end(p, ptr)) {
  11512. return false;
  11513. }
  11514. if (p->top->f == NULL) {
  11515. multipart_end(p);
  11516. return true;
  11517. }
  11518. return parse_number(p, false);
  11519. }
  11520. static bool end_number(upb_json_parser *p, const char *ptr) {
  11521. if (!end_number_nontop(p, ptr)) {
  11522. return false;
  11523. }
  11524. if (does_number_wrapper_end(p)) {
  11525. end_wrapper_object(p);
  11526. if (!is_top_level(p)) {
  11527. end_subobject(p);
  11528. }
  11529. return true;
  11530. }
  11531. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  11532. end_value_object(p);
  11533. if (!is_top_level(p)) {
  11534. end_subobject(p);
  11535. }
  11536. return true;
  11537. }
  11538. return true;
  11539. }
  11540. /* |buf| is NULL-terminated. |buf| itself will never include quotes;
  11541. * |is_quoted| tells us whether this text originally appeared inside quotes. */
  11542. static bool parse_number_from_buffer(upb_json_parser *p, const char *buf,
  11543. bool is_quoted) {
  11544. size_t len = strlen(buf);
  11545. const char *bufend = buf + len;
  11546. char *end;
  11547. upb_fieldtype_t type = upb_fielddef_type(p->top->f);
  11548. double val;
  11549. double dummy;
  11550. double inf = 1.0 / 0.0; /* C89 does not have an INFINITY macro. */
  11551. errno = 0;
  11552. if (len == 0 || buf[0] == ' ') {
  11553. return false;
  11554. }
  11555. /* For integer types, first try parsing with integer-specific routines.
  11556. * If these succeed, they will be more accurate for int64/uint64 than
  11557. * strtod().
  11558. */
  11559. switch (type) {
  11560. case UPB_TYPE_ENUM:
  11561. case UPB_TYPE_INT32: {
  11562. long val = strtol(buf, &end, 0);
  11563. if (errno == ERANGE || end != bufend) {
  11564. break;
  11565. } else if (val > INT32_MAX || val < INT32_MIN) {
  11566. return false;
  11567. } else {
  11568. upb_sink_putint32(&p->top->sink, parser_getsel(p), val);
  11569. return true;
  11570. }
  11571. }
  11572. case UPB_TYPE_UINT32: {
  11573. unsigned long val = strtoul(buf, &end, 0);
  11574. if (end != bufend) {
  11575. break;
  11576. } else if (val > UINT32_MAX || errno == ERANGE) {
  11577. return false;
  11578. } else {
  11579. upb_sink_putuint32(&p->top->sink, parser_getsel(p), val);
  11580. return true;
  11581. }
  11582. }
  11583. /* XXX: We can't handle [u]int64 properly on 32-bit machines because
  11584. * strto[u]ll isn't in C89. */
  11585. case UPB_TYPE_INT64: {
  11586. long val = strtol(buf, &end, 0);
  11587. if (errno == ERANGE || end != bufend) {
  11588. break;
  11589. } else {
  11590. upb_sink_putint64(&p->top->sink, parser_getsel(p), val);
  11591. return true;
  11592. }
  11593. }
  11594. case UPB_TYPE_UINT64: {
  11595. unsigned long val = strtoul(p->accumulated, &end, 0);
  11596. if (end != bufend) {
  11597. break;
  11598. } else if (errno == ERANGE) {
  11599. return false;
  11600. } else {
  11601. upb_sink_putuint64(&p->top->sink, parser_getsel(p), val);
  11602. return true;
  11603. }
  11604. }
  11605. default:
  11606. break;
  11607. }
  11608. if (type != UPB_TYPE_DOUBLE && type != UPB_TYPE_FLOAT && is_quoted) {
  11609. /* Quoted numbers for integer types are not allowed to be in double form. */
  11610. return false;
  11611. }
  11612. if (len == strlen("Infinity") && strcmp(buf, "Infinity") == 0) {
  11613. /* C89 does not have an INFINITY macro. */
  11614. val = inf;
  11615. } else if (len == strlen("-Infinity") && strcmp(buf, "-Infinity") == 0) {
  11616. val = -inf;
  11617. } else {
  11618. val = strtod(buf, &end);
  11619. if (errno == ERANGE || end != bufend) {
  11620. return false;
  11621. }
  11622. }
  11623. switch (type) {
  11624. #define CASE(capitaltype, smalltype, ctype, min, max) \
  11625. case UPB_TYPE_ ## capitaltype: { \
  11626. if (modf(val, &dummy) != 0 || val > max || val < min) { \
  11627. return false; \
  11628. } else { \
  11629. upb_sink_put ## smalltype(&p->top->sink, parser_getsel(p), \
  11630. (ctype)val); \
  11631. return true; \
  11632. } \
  11633. break; \
  11634. }
  11635. case UPB_TYPE_ENUM:
  11636. CASE(INT32, int32, int32_t, INT32_MIN, INT32_MAX);
  11637. CASE(INT64, int64, int64_t, INT64_MIN, INT64_MAX);
  11638. CASE(UINT32, uint32, uint32_t, 0, UINT32_MAX);
  11639. CASE(UINT64, uint64, uint64_t, 0, UINT64_MAX);
  11640. #undef CASE
  11641. case UPB_TYPE_DOUBLE:
  11642. upb_sink_putdouble(&p->top->sink, parser_getsel(p), val);
  11643. return true;
  11644. case UPB_TYPE_FLOAT:
  11645. if ((val > FLT_MAX || val < -FLT_MAX) && val != inf && val != -inf) {
  11646. return false;
  11647. } else {
  11648. upb_sink_putfloat(&p->top->sink, parser_getsel(p), val);
  11649. return true;
  11650. }
  11651. default:
  11652. return false;
  11653. }
  11654. }
  11655. static bool parse_number(upb_json_parser *p, bool is_quoted) {
  11656. size_t len;
  11657. const char *buf;
  11658. /* strtol() and friends unfortunately do not support specifying the length of
  11659. * the input string, so we need to force a copy into a NULL-terminated buffer. */
  11660. if (!multipart_text(p, "\0", 1, false)) {
  11661. return false;
  11662. }
  11663. buf = accumulate_getptr(p, &len);
  11664. if (parse_number_from_buffer(p, buf, is_quoted)) {
  11665. multipart_end(p);
  11666. return true;
  11667. } else {
  11668. upb_status_seterrf(&p->status, "error parsing number: %s", buf);
  11669. upb_env_reporterror(p->env, &p->status);
  11670. multipart_end(p);
  11671. return false;
  11672. }
  11673. }
  11674. static bool parser_putbool(upb_json_parser *p, bool val) {
  11675. bool ok;
  11676. if (p->top->f == NULL) {
  11677. return true;
  11678. }
  11679. if (upb_fielddef_type(p->top->f) != UPB_TYPE_BOOL) {
  11680. upb_status_seterrf(&p->status,
  11681. "Boolean value specified for non-bool field: %s",
  11682. upb_fielddef_name(p->top->f));
  11683. upb_env_reporterror(p->env, &p->status);
  11684. return false;
  11685. }
  11686. ok = upb_sink_putbool(&p->top->sink, parser_getsel(p), val);
  11687. UPB_ASSERT(ok);
  11688. return true;
  11689. }
  11690. static bool end_bool(upb_json_parser *p, bool val) {
  11691. if (is_top_level(p)) {
  11692. if (is_wellknown_msg(p, UPB_WELLKNOWN_BOOLVALUE)) {
  11693. start_wrapper_object(p);
  11694. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  11695. start_value_object(p, VALUE_BOOLVALUE);
  11696. } else {
  11697. return false;
  11698. }
  11699. } else if (is_wellknown_field(p, UPB_WELLKNOWN_BOOLVALUE)) {
  11700. if (!start_subobject(p)) {
  11701. return false;
  11702. }
  11703. start_wrapper_object(p);
  11704. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  11705. if (!start_subobject(p)) {
  11706. return false;
  11707. }
  11708. start_value_object(p, VALUE_BOOLVALUE);
  11709. }
  11710. if (p->top->is_unknown_field) {
  11711. return true;
  11712. }
  11713. if (!parser_putbool(p, val)) {
  11714. return false;
  11715. }
  11716. if (is_wellknown_msg(p, UPB_WELLKNOWN_BOOLVALUE)) {
  11717. end_wrapper_object(p);
  11718. if (!is_top_level(p)) {
  11719. end_subobject(p);
  11720. }
  11721. return true;
  11722. }
  11723. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  11724. end_value_object(p);
  11725. if (!is_top_level(p)) {
  11726. end_subobject(p);
  11727. }
  11728. return true;
  11729. }
  11730. return true;
  11731. }
  11732. static bool end_null(upb_json_parser *p) {
  11733. const char *zero_ptr = "0";
  11734. if (is_top_level(p)) {
  11735. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  11736. start_value_object(p, VALUE_NULLVALUE);
  11737. } else {
  11738. return true;
  11739. }
  11740. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  11741. if (!start_subobject(p)) {
  11742. return false;
  11743. }
  11744. start_value_object(p, VALUE_NULLVALUE);
  11745. } else {
  11746. return true;
  11747. }
  11748. /* Fill null_value field. */
  11749. multipart_startaccum(p);
  11750. capture_begin(p, zero_ptr);
  11751. capture_end(p, zero_ptr + 1);
  11752. parse_number(p, false);
  11753. end_value_object(p);
  11754. if (!is_top_level(p)) {
  11755. end_subobject(p);
  11756. }
  11757. return true;
  11758. }
  11759. static bool start_any_stringval(upb_json_parser *p) {
  11760. multipart_startaccum(p);
  11761. return true;
  11762. }
  11763. static bool start_stringval(upb_json_parser *p) {
  11764. if (is_top_level(p)) {
  11765. if (is_string_wrapper_object(p)) {
  11766. start_wrapper_object(p);
  11767. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_FIELDMASK)) {
  11768. start_fieldmask_object(p);
  11769. return true;
  11770. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_TIMESTAMP) ||
  11771. is_wellknown_msg(p, UPB_WELLKNOWN_DURATION)) {
  11772. start_object(p);
  11773. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  11774. start_value_object(p, VALUE_STRINGVALUE);
  11775. } else {
  11776. return false;
  11777. }
  11778. } else if (does_string_wrapper_start(p)) {
  11779. if (!start_subobject(p)) {
  11780. return false;
  11781. }
  11782. start_wrapper_object(p);
  11783. } else if (does_fieldmask_start(p)) {
  11784. if (!start_subobject(p)) {
  11785. return false;
  11786. }
  11787. start_fieldmask_object(p);
  11788. return true;
  11789. } else if (is_wellknown_field(p, UPB_WELLKNOWN_TIMESTAMP) ||
  11790. is_wellknown_field(p, UPB_WELLKNOWN_DURATION)) {
  11791. if (!start_subobject(p)) {
  11792. return false;
  11793. }
  11794. start_object(p);
  11795. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  11796. if (!start_subobject(p)) {
  11797. return false;
  11798. }
  11799. start_value_object(p, VALUE_STRINGVALUE);
  11800. }
  11801. if (p->top->f == NULL) {
  11802. multipart_startaccum(p);
  11803. return true;
  11804. }
  11805. if (p->top->is_any) {
  11806. return start_any_stringval(p);
  11807. }
  11808. if (upb_fielddef_isstring(p->top->f)) {
  11809. upb_jsonparser_frame *inner;
  11810. upb_selector_t sel;
  11811. if (!check_stack(p)) return false;
  11812. /* Start a new parser frame: parser frames correspond one-to-one with
  11813. * handler frames, and string events occur in a sub-frame. */
  11814. inner = p->top + 1;
  11815. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  11816. upb_sink_startstr(&p->top->sink, sel, 0, &inner->sink);
  11817. inner->m = p->top->m;
  11818. inner->f = p->top->f;
  11819. inner->name_table = NULL;
  11820. inner->is_map = false;
  11821. inner->is_mapentry = false;
  11822. inner->is_any = false;
  11823. inner->any_frame = NULL;
  11824. inner->is_unknown_field = false;
  11825. p->top = inner;
  11826. if (upb_fielddef_type(p->top->f) == UPB_TYPE_STRING) {
  11827. /* For STRING fields we push data directly to the handlers as it is
  11828. * parsed. We don't do this yet for BYTES fields, because our base64
  11829. * decoder is not streaming.
  11830. *
  11831. * TODO(haberman): make base64 decoding streaming also. */
  11832. multipart_start(p, getsel_for_handlertype(p, UPB_HANDLER_STRING));
  11833. return true;
  11834. } else {
  11835. multipart_startaccum(p);
  11836. return true;
  11837. }
  11838. } else if (upb_fielddef_type(p->top->f) != UPB_TYPE_BOOL &&
  11839. upb_fielddef_type(p->top->f) != UPB_TYPE_MESSAGE) {
  11840. /* No need to push a frame -- numeric values in quotes remain in the
  11841. * current parser frame. These values must accmulate so we can convert
  11842. * them all at once at the end. */
  11843. multipart_startaccum(p);
  11844. return true;
  11845. } else {
  11846. upb_status_seterrf(&p->status,
  11847. "String specified for bool or submessage field: %s",
  11848. upb_fielddef_name(p->top->f));
  11849. upb_env_reporterror(p->env, &p->status);
  11850. return false;
  11851. }
  11852. }
  11853. static bool end_any_stringval(upb_json_parser *p) {
  11854. size_t len;
  11855. const char *buf = accumulate_getptr(p, &len);
  11856. /* Set type_url */
  11857. upb_selector_t sel;
  11858. upb_jsonparser_frame *inner;
  11859. if (!check_stack(p)) return false;
  11860. inner = p->top + 1;
  11861. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  11862. upb_sink_startstr(&p->top->sink, sel, 0, &inner->sink);
  11863. sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
  11864. upb_sink_putstring(&inner->sink, sel, buf, len, NULL);
  11865. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  11866. upb_sink_endstr(&inner->sink, sel);
  11867. multipart_end(p);
  11868. /* Resolve type url */
  11869. if (strncmp(buf, "type.googleapis.com/", 20) == 0 && len > 20) {
  11870. const upb_msgdef *payload_type = NULL;
  11871. buf += 20;
  11872. len -= 20;
  11873. payload_type = upb_symtab_lookupmsg2(p->symtab, buf, len);
  11874. if (payload_type == NULL) {
  11875. upb_status_seterrf(
  11876. &p->status, "Cannot find packed type: %.*s\n", (int)len, buf);
  11877. upb_env_reporterror(p->env, &p->status);
  11878. return false;
  11879. }
  11880. json_parser_any_frame_set_payload_type(p, p->top->any_frame, payload_type);
  11881. return true;
  11882. } else {
  11883. upb_status_seterrf(
  11884. &p->status, "Invalid type url: %.*s\n", (int)len, buf);
  11885. upb_env_reporterror(p->env, &p->status);
  11886. return false;
  11887. }
  11888. }
  11889. static bool end_stringval_nontop(upb_json_parser *p) {
  11890. bool ok = true;
  11891. if (is_wellknown_msg(p, UPB_WELLKNOWN_TIMESTAMP) ||
  11892. is_wellknown_msg(p, UPB_WELLKNOWN_DURATION)) {
  11893. multipart_end(p);
  11894. return true;
  11895. }
  11896. if (p->top->f == NULL) {
  11897. multipart_end(p);
  11898. return true;
  11899. }
  11900. if (p->top->is_any) {
  11901. return end_any_stringval(p);
  11902. }
  11903. switch (upb_fielddef_type(p->top->f)) {
  11904. case UPB_TYPE_BYTES:
  11905. if (!base64_push(p, getsel_for_handlertype(p, UPB_HANDLER_STRING),
  11906. p->accumulated, p->accumulated_len)) {
  11907. return false;
  11908. }
  11909. /* Fall through. */
  11910. case UPB_TYPE_STRING: {
  11911. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  11912. upb_sink_endstr(&p->top->sink, sel);
  11913. p->top--;
  11914. break;
  11915. }
  11916. case UPB_TYPE_ENUM: {
  11917. /* Resolve enum symbolic name to integer value. */
  11918. const upb_enumdef *enumdef =
  11919. (const upb_enumdef*)upb_fielddef_subdef(p->top->f);
  11920. size_t len;
  11921. const char *buf = accumulate_getptr(p, &len);
  11922. int32_t int_val = 0;
  11923. ok = upb_enumdef_ntoi(enumdef, buf, len, &int_val);
  11924. if (ok) {
  11925. upb_selector_t sel = parser_getsel(p);
  11926. upb_sink_putint32(&p->top->sink, sel, int_val);
  11927. } else {
  11928. upb_status_seterrf(&p->status, "Enum value unknown: '%.*s'", len, buf);
  11929. upb_env_reporterror(p->env, &p->status);
  11930. }
  11931. break;
  11932. }
  11933. case UPB_TYPE_INT32:
  11934. case UPB_TYPE_INT64:
  11935. case UPB_TYPE_UINT32:
  11936. case UPB_TYPE_UINT64:
  11937. case UPB_TYPE_DOUBLE:
  11938. case UPB_TYPE_FLOAT:
  11939. ok = parse_number(p, true);
  11940. break;
  11941. default:
  11942. UPB_ASSERT(false);
  11943. upb_status_seterrmsg(&p->status, "Internal error in JSON decoder");
  11944. upb_env_reporterror(p->env, &p->status);
  11945. ok = false;
  11946. break;
  11947. }
  11948. multipart_end(p);
  11949. return ok;
  11950. }
  11951. static bool end_stringval(upb_json_parser *p) {
  11952. /* FieldMask's stringvals have been ended when handling them. Only need to
  11953. * close FieldMask here.*/
  11954. if (does_fieldmask_end(p)) {
  11955. end_fieldmask_object(p);
  11956. if (!is_top_level(p)) {
  11957. end_subobject(p);
  11958. }
  11959. return true;
  11960. }
  11961. if (!end_stringval_nontop(p)) {
  11962. return false;
  11963. }
  11964. if (does_string_wrapper_end(p)) {
  11965. end_wrapper_object(p);
  11966. if (!is_top_level(p)) {
  11967. end_subobject(p);
  11968. }
  11969. return true;
  11970. }
  11971. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  11972. end_value_object(p);
  11973. if (!is_top_level(p)) {
  11974. end_subobject(p);
  11975. }
  11976. return true;
  11977. }
  11978. if (is_wellknown_msg(p, UPB_WELLKNOWN_TIMESTAMP) ||
  11979. is_wellknown_msg(p, UPB_WELLKNOWN_DURATION) ||
  11980. is_wellknown_msg(p, UPB_WELLKNOWN_FIELDMASK)) {
  11981. end_object(p);
  11982. if (!is_top_level(p)) {
  11983. end_subobject(p);
  11984. }
  11985. return true;
  11986. }
  11987. return true;
  11988. }
  11989. static void start_duration_base(upb_json_parser *p, const char *ptr) {
  11990. capture_begin(p, ptr);
  11991. }
  11992. static bool end_duration_base(upb_json_parser *p, const char *ptr) {
  11993. size_t len;
  11994. const char *buf;
  11995. char seconds_buf[14];
  11996. char nanos_buf[12];
  11997. char *end;
  11998. int64_t seconds = 0;
  11999. int32_t nanos = 0;
  12000. double val = 0.0;
  12001. const char *seconds_membername = "seconds";
  12002. const char *nanos_membername = "nanos";
  12003. size_t fraction_start;
  12004. if (!capture_end(p, ptr)) {
  12005. return false;
  12006. }
  12007. buf = accumulate_getptr(p, &len);
  12008. memset(seconds_buf, 0, 14);
  12009. memset(nanos_buf, 0, 12);
  12010. /* Find out base end. The maximus duration is 315576000000, which cannot be
  12011. * represented by double without losing precision. Thus, we need to handle
  12012. * fraction and base separately. */
  12013. for (fraction_start = 0; fraction_start < len && buf[fraction_start] != '.';
  12014. fraction_start++);
  12015. /* Parse base */
  12016. memcpy(seconds_buf, buf, fraction_start);
  12017. seconds = strtol(seconds_buf, &end, 10);
  12018. if (errno == ERANGE || end != seconds_buf + fraction_start) {
  12019. upb_status_seterrf(&p->status, "error parsing duration: %s",
  12020. seconds_buf);
  12021. upb_env_reporterror(p->env, &p->status);
  12022. return false;
  12023. }
  12024. if (seconds > 315576000000) {
  12025. upb_status_seterrf(&p->status, "error parsing duration: "
  12026. "maximum acceptable value is "
  12027. "315576000000");
  12028. upb_env_reporterror(p->env, &p->status);
  12029. return false;
  12030. }
  12031. if (seconds < -315576000000) {
  12032. upb_status_seterrf(&p->status, "error parsing duration: "
  12033. "minimum acceptable value is "
  12034. "-315576000000");
  12035. upb_env_reporterror(p->env, &p->status);
  12036. return false;
  12037. }
  12038. /* Parse fraction */
  12039. nanos_buf[0] = '0';
  12040. memcpy(nanos_buf + 1, buf + fraction_start, len - fraction_start);
  12041. val = strtod(nanos_buf, &end);
  12042. if (errno == ERANGE || end != nanos_buf + len - fraction_start + 1) {
  12043. upb_status_seterrf(&p->status, "error parsing duration: %s",
  12044. nanos_buf);
  12045. upb_env_reporterror(p->env, &p->status);
  12046. return false;
  12047. }
  12048. nanos = val * 1000000000;
  12049. if (seconds < 0) nanos = -nanos;
  12050. /* Clean up buffer */
  12051. multipart_end(p);
  12052. /* Set seconds */
  12053. start_member(p);
  12054. capture_begin(p, seconds_membername);
  12055. capture_end(p, seconds_membername + 7);
  12056. end_membername(p);
  12057. upb_sink_putint64(&p->top->sink, parser_getsel(p), seconds);
  12058. end_member(p);
  12059. /* Set nanos */
  12060. start_member(p);
  12061. capture_begin(p, nanos_membername);
  12062. capture_end(p, nanos_membername + 5);
  12063. end_membername(p);
  12064. upb_sink_putint32(&p->top->sink, parser_getsel(p), nanos);
  12065. end_member(p);
  12066. /* Continue previous environment */
  12067. multipart_startaccum(p);
  12068. return true;
  12069. }
  12070. static void start_timestamp_base(upb_json_parser *p, const char *ptr) {
  12071. capture_begin(p, ptr);
  12072. }
  12073. #define UPB_TIMESTAMP_BASE_SIZE 19
  12074. static bool end_timestamp_base(upb_json_parser *p, const char *ptr) {
  12075. size_t len;
  12076. const char *buf;
  12077. /* 3 for GMT and 1 for ending 0 */
  12078. char timestamp_buf[UPB_TIMESTAMP_BASE_SIZE + 4];
  12079. if (!capture_end(p, ptr)) {
  12080. return false;
  12081. }
  12082. buf = accumulate_getptr(p, &len);
  12083. UPB_ASSERT(len == UPB_TIMESTAMP_BASE_SIZE);
  12084. memcpy(timestamp_buf, buf, UPB_TIMESTAMP_BASE_SIZE);
  12085. memcpy(timestamp_buf + UPB_TIMESTAMP_BASE_SIZE, "GMT", 3);
  12086. timestamp_buf[UPB_TIMESTAMP_BASE_SIZE + 3] = 0;
  12087. #if defined __MINGW32__ || defined __MINGW64__
  12088. upb_status_seterrf(
  12089. &p->status, "error parsing timestamp: mingw doesn't support strptime");
  12090. upb_env_reporterror(p->env, &p->status);
  12091. return false;
  12092. #else
  12093. /* Parse seconds */
  12094. if (strptime(timestamp_buf, "%FT%H:%M:%S%Z", &p->tm) == NULL) {
  12095. upb_status_seterrf(&p->status, "error parsing timestamp: %s", buf);
  12096. upb_env_reporterror(p->env, &p->status);
  12097. return false;
  12098. }
  12099. #endif
  12100. /* Clean up buffer */
  12101. multipart_end(p);
  12102. multipart_startaccum(p);
  12103. return true;
  12104. }
  12105. static void start_timestamp_fraction(upb_json_parser *p, const char *ptr) {
  12106. capture_begin(p, ptr);
  12107. }
  12108. static bool end_timestamp_fraction(upb_json_parser *p, const char *ptr) {
  12109. size_t len;
  12110. const char *buf;
  12111. char nanos_buf[12];
  12112. char *end;
  12113. double val = 0.0;
  12114. int32_t nanos;
  12115. const char *nanos_membername = "nanos";
  12116. memset(nanos_buf, 0, 12);
  12117. if (!capture_end(p, ptr)) {
  12118. return false;
  12119. }
  12120. buf = accumulate_getptr(p, &len);
  12121. if (len > 10) {
  12122. upb_status_seterrf(&p->status,
  12123. "error parsing timestamp: at most 9-digit fraction.");
  12124. upb_env_reporterror(p->env, &p->status);
  12125. return false;
  12126. }
  12127. /* Parse nanos */
  12128. nanos_buf[0] = '0';
  12129. memcpy(nanos_buf + 1, buf, len);
  12130. val = strtod(nanos_buf, &end);
  12131. if (errno == ERANGE || end != nanos_buf + len + 1) {
  12132. upb_status_seterrf(&p->status, "error parsing timestamp nanos: %s",
  12133. nanos_buf);
  12134. upb_env_reporterror(p->env, &p->status);
  12135. return false;
  12136. }
  12137. nanos = val * 1000000000;
  12138. /* Clean up previous environment */
  12139. multipart_end(p);
  12140. /* Set nanos */
  12141. start_member(p);
  12142. capture_begin(p, nanos_membername);
  12143. capture_end(p, nanos_membername + 5);
  12144. end_membername(p);
  12145. upb_sink_putint32(&p->top->sink, parser_getsel(p), nanos);
  12146. end_member(p);
  12147. /* Continue previous environment */
  12148. multipart_startaccum(p);
  12149. return true;
  12150. }
  12151. static void start_timestamp_zone(upb_json_parser *p, const char *ptr) {
  12152. capture_begin(p, ptr);
  12153. }
  12154. static bool end_timestamp_zone(upb_json_parser *p, const char *ptr) {
  12155. size_t len;
  12156. const char *buf;
  12157. int hours;
  12158. int64_t seconds;
  12159. const char *seconds_membername = "seconds";
  12160. if (!capture_end(p, ptr)) {
  12161. return false;
  12162. }
  12163. buf = accumulate_getptr(p, &len);
  12164. if (buf[0] != 'Z') {
  12165. if (sscanf(buf + 1, "%2d:00", &hours) != 1) {
  12166. upb_status_seterrf(&p->status, "error parsing timestamp offset");
  12167. upb_env_reporterror(p->env, &p->status);
  12168. return false;
  12169. }
  12170. if (buf[0] == '+') {
  12171. hours = -hours;
  12172. }
  12173. p->tm.tm_hour += hours;
  12174. }
  12175. /* Normalize tm */
  12176. seconds = mktime(&p->tm);
  12177. /* Check timestamp boundary */
  12178. if (seconds < -62135596800) {
  12179. upb_status_seterrf(&p->status, "error parsing timestamp: "
  12180. "minimum acceptable value is "
  12181. "0001-01-01T00:00:00Z");
  12182. upb_env_reporterror(p->env, &p->status);
  12183. return false;
  12184. }
  12185. /* Clean up previous environment */
  12186. multipart_end(p);
  12187. /* Set seconds */
  12188. start_member(p);
  12189. capture_begin(p, seconds_membername);
  12190. capture_end(p, seconds_membername + 7);
  12191. end_membername(p);
  12192. upb_sink_putint64(&p->top->sink, parser_getsel(p), seconds);
  12193. end_member(p);
  12194. /* Continue previous environment */
  12195. multipart_startaccum(p);
  12196. return true;
  12197. }
  12198. static void start_fieldmask_path_text(upb_json_parser *p, const char *ptr) {
  12199. capture_begin(p, ptr);
  12200. }
  12201. static bool end_fieldmask_path_text(upb_json_parser *p, const char *ptr) {
  12202. if (!capture_end(p, ptr)) {
  12203. return false;
  12204. }
  12205. }
  12206. static bool start_fieldmask_path(upb_json_parser *p) {
  12207. upb_jsonparser_frame *inner;
  12208. upb_selector_t sel;
  12209. if (!check_stack(p)) return false;
  12210. /* Start a new parser frame: parser frames correspond one-to-one with
  12211. * handler frames, and string events occur in a sub-frame. */
  12212. inner = p->top + 1;
  12213. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  12214. upb_sink_startstr(&p->top->sink, sel, 0, &inner->sink);
  12215. inner->m = p->top->m;
  12216. inner->f = p->top->f;
  12217. inner->name_table = NULL;
  12218. inner->is_map = false;
  12219. inner->is_mapentry = false;
  12220. inner->is_any = false;
  12221. inner->any_frame = NULL;
  12222. inner->is_unknown_field = false;
  12223. p->top = inner;
  12224. multipart_startaccum(p);
  12225. return true;
  12226. }
  12227. static bool lower_camel_push(
  12228. upb_json_parser *p, upb_selector_t sel, const char *ptr, size_t len) {
  12229. const char *limit = ptr + len;
  12230. bool first = true;
  12231. for (;ptr < limit; ptr++) {
  12232. if (*ptr >= 'A' && *ptr <= 'Z' && !first) {
  12233. char lower = tolower(*ptr);
  12234. upb_sink_putstring(&p->top->sink, sel, "_", 1, NULL);
  12235. upb_sink_putstring(&p->top->sink, sel, &lower, 1, NULL);
  12236. } else {
  12237. upb_sink_putstring(&p->top->sink, sel, ptr, 1, NULL);
  12238. }
  12239. first = false;
  12240. }
  12241. return true;
  12242. }
  12243. static bool end_fieldmask_path(upb_json_parser *p) {
  12244. upb_selector_t sel;
  12245. if (!lower_camel_push(
  12246. p, getsel_for_handlertype(p, UPB_HANDLER_STRING),
  12247. p->accumulated, p->accumulated_len)) {
  12248. return false;
  12249. }
  12250. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  12251. upb_sink_endstr(&p->top->sink, sel);
  12252. p->top--;
  12253. multipart_end(p);
  12254. return true;
  12255. }
  12256. static void start_member(upb_json_parser *p) {
  12257. UPB_ASSERT(!p->top->f);
  12258. multipart_startaccum(p);
  12259. }
  12260. /* Helper: invoked during parse_mapentry() to emit the mapentry message's key
  12261. * field based on the current contents of the accumulate buffer. */
  12262. static bool parse_mapentry_key(upb_json_parser *p) {
  12263. size_t len;
  12264. const char *buf = accumulate_getptr(p, &len);
  12265. /* Emit the key field. We do a bit of ad-hoc parsing here because the
  12266. * parser state machine has already decided that this is a string field
  12267. * name, and we are reinterpreting it as some arbitrary key type. In
  12268. * particular, integer and bool keys are quoted, so we need to parse the
  12269. * quoted string contents here. */
  12270. p->top->f = upb_msgdef_itof(p->top->m, UPB_MAPENTRY_KEY);
  12271. if (p->top->f == NULL) {
  12272. upb_status_seterrmsg(&p->status, "mapentry message has no key");
  12273. upb_env_reporterror(p->env, &p->status);
  12274. return false;
  12275. }
  12276. switch (upb_fielddef_type(p->top->f)) {
  12277. case UPB_TYPE_INT32:
  12278. case UPB_TYPE_INT64:
  12279. case UPB_TYPE_UINT32:
  12280. case UPB_TYPE_UINT64:
  12281. /* Invoke end_number. The accum buffer has the number's text already. */
  12282. if (!parse_number(p, true)) {
  12283. return false;
  12284. }
  12285. break;
  12286. case UPB_TYPE_BOOL:
  12287. if (len == 4 && !strncmp(buf, "true", 4)) {
  12288. if (!parser_putbool(p, true)) {
  12289. return false;
  12290. }
  12291. } else if (len == 5 && !strncmp(buf, "false", 5)) {
  12292. if (!parser_putbool(p, false)) {
  12293. return false;
  12294. }
  12295. } else {
  12296. upb_status_seterrmsg(&p->status,
  12297. "Map bool key not 'true' or 'false'");
  12298. upb_env_reporterror(p->env, &p->status);
  12299. return false;
  12300. }
  12301. multipart_end(p);
  12302. break;
  12303. case UPB_TYPE_STRING:
  12304. case UPB_TYPE_BYTES: {
  12305. upb_sink subsink;
  12306. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  12307. upb_sink_startstr(&p->top->sink, sel, len, &subsink);
  12308. sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
  12309. upb_sink_putstring(&subsink, sel, buf, len, NULL);
  12310. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  12311. upb_sink_endstr(&subsink, sel);
  12312. multipart_end(p);
  12313. break;
  12314. }
  12315. default:
  12316. upb_status_seterrmsg(&p->status, "Invalid field type for map key");
  12317. upb_env_reporterror(p->env, &p->status);
  12318. return false;
  12319. }
  12320. return true;
  12321. }
  12322. /* Helper: emit one map entry (as a submessage in the map field sequence). This
  12323. * is invoked from end_membername(), at the end of the map entry's key string,
  12324. * with the map key in the accumulate buffer. It parses the key from that
  12325. * buffer, emits the handler calls to start the mapentry submessage (setting up
  12326. * its subframe in the process), and sets up state in the subframe so that the
  12327. * value parser (invoked next) will emit the mapentry's value field and then
  12328. * end the mapentry message. */
  12329. static bool handle_mapentry(upb_json_parser *p) {
  12330. const upb_fielddef *mapfield;
  12331. const upb_msgdef *mapentrymsg;
  12332. upb_jsonparser_frame *inner;
  12333. upb_selector_t sel;
  12334. /* Map entry: p->top->sink is the seq frame, so we need to start a frame
  12335. * for the mapentry itself, and then set |f| in that frame so that the map
  12336. * value field is parsed, and also set a flag to end the frame after the
  12337. * map-entry value is parsed. */
  12338. if (!check_stack(p)) return false;
  12339. mapfield = p->top->mapfield;
  12340. mapentrymsg = upb_fielddef_msgsubdef(mapfield);
  12341. inner = p->top + 1;
  12342. p->top->f = mapfield;
  12343. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
  12344. upb_sink_startsubmsg(&p->top->sink, sel, &inner->sink);
  12345. inner->m = mapentrymsg;
  12346. inner->name_table = NULL;
  12347. inner->mapfield = mapfield;
  12348. inner->is_map = false;
  12349. inner->is_any = false;
  12350. inner->any_frame = NULL;
  12351. inner->is_unknown_field = false;
  12352. /* Don't set this to true *yet* -- we reuse parsing handlers below to push
  12353. * the key field value to the sink, and these handlers will pop the frame
  12354. * if they see is_mapentry (when invoked by the parser state machine, they
  12355. * would have just seen the map-entry value, not key). */
  12356. inner->is_mapentry = false;
  12357. p->top = inner;
  12358. /* send STARTMSG in submsg frame. */
  12359. upb_sink_startmsg(&p->top->sink);
  12360. parse_mapentry_key(p);
  12361. /* Set up the value field to receive the map-entry value. */
  12362. p->top->f = upb_msgdef_itof(p->top->m, UPB_MAPENTRY_VALUE);
  12363. p->top->is_mapentry = true; /* set up to pop frame after value is parsed. */
  12364. p->top->mapfield = mapfield;
  12365. if (p->top->f == NULL) {
  12366. upb_status_seterrmsg(&p->status, "mapentry message has no value");
  12367. upb_env_reporterror(p->env, &p->status);
  12368. return false;
  12369. }
  12370. return true;
  12371. }
  12372. static bool end_membername(upb_json_parser *p) {
  12373. UPB_ASSERT(!p->top->f);
  12374. if (!p->top->m) {
  12375. p->top->is_unknown_field = true;
  12376. multipart_end(p);
  12377. return true;
  12378. }
  12379. if (p->top->is_any) {
  12380. return end_any_membername(p);
  12381. } else if (p->top->is_map) {
  12382. return handle_mapentry(p);
  12383. } else {
  12384. size_t len;
  12385. const char *buf = accumulate_getptr(p, &len);
  12386. upb_value v;
  12387. if (upb_strtable_lookup2(p->top->name_table, buf, len, &v)) {
  12388. p->top->f = upb_value_getconstptr(v);
  12389. multipart_end(p);
  12390. return true;
  12391. } else if (p->ignore_json_unknown) {
  12392. p->top->is_unknown_field = true;
  12393. multipart_end(p);
  12394. return true;
  12395. } else {
  12396. upb_status_seterrf(&p->status, "No such field: %.*s\n", (int)len, buf);
  12397. upb_env_reporterror(p->env, &p->status);
  12398. return false;
  12399. }
  12400. }
  12401. }
  12402. static bool end_any_membername(upb_json_parser *p) {
  12403. size_t len;
  12404. const char *buf = accumulate_getptr(p, &len);
  12405. upb_value v;
  12406. if (len == 5 && strncmp(buf, "@type", len) == 0) {
  12407. upb_strtable_lookup2(p->top->name_table, "type_url", 8, &v);
  12408. p->top->f = upb_value_getconstptr(v);
  12409. multipart_end(p);
  12410. return true;
  12411. } else {
  12412. p->top->is_unknown_field = true;
  12413. multipart_end(p);
  12414. return true;
  12415. }
  12416. }
  12417. static void end_member(upb_json_parser *p) {
  12418. /* If we just parsed a map-entry value, end that frame too. */
  12419. if (p->top->is_mapentry) {
  12420. upb_status s = UPB_STATUS_INIT;
  12421. upb_selector_t sel;
  12422. bool ok;
  12423. const upb_fielddef *mapfield;
  12424. UPB_ASSERT(p->top > p->stack);
  12425. /* send ENDMSG on submsg. */
  12426. upb_sink_endmsg(&p->top->sink, &s);
  12427. mapfield = p->top->mapfield;
  12428. /* send ENDSUBMSG in repeated-field-of-mapentries frame. */
  12429. p->top--;
  12430. ok = upb_handlers_getselector(mapfield, UPB_HANDLER_ENDSUBMSG, &sel);
  12431. UPB_ASSERT(ok);
  12432. upb_sink_endsubmsg(&p->top->sink, sel);
  12433. }
  12434. p->top->f = NULL;
  12435. p->top->is_unknown_field = false;
  12436. }
  12437. static void start_any_member(upb_json_parser *p, const char *ptr) {
  12438. start_member(p);
  12439. json_parser_any_frame_set_after_type_url_start_once(p->top->any_frame, ptr);
  12440. }
  12441. static void end_any_member(upb_json_parser *p, const char *ptr) {
  12442. json_parser_any_frame_set_before_type_url_end(p->top->any_frame, ptr);
  12443. end_member(p);
  12444. }
  12445. static bool start_subobject(upb_json_parser *p) {
  12446. if (p->top->is_unknown_field) {
  12447. upb_jsonparser_frame *inner;
  12448. if (!check_stack(p)) return false;
  12449. inner = p->top + 1;
  12450. inner->m = NULL;
  12451. inner->f = NULL;
  12452. inner->is_map = false;
  12453. inner->is_mapentry = false;
  12454. inner->is_any = false;
  12455. inner->any_frame = NULL;
  12456. inner->is_unknown_field = false;
  12457. p->top = inner;
  12458. return true;
  12459. }
  12460. if (upb_fielddef_ismap(p->top->f)) {
  12461. upb_jsonparser_frame *inner;
  12462. upb_selector_t sel;
  12463. /* Beginning of a map. Start a new parser frame in a repeated-field
  12464. * context. */
  12465. if (!check_stack(p)) return false;
  12466. inner = p->top + 1;
  12467. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
  12468. upb_sink_startseq(&p->top->sink, sel, &inner->sink);
  12469. inner->m = upb_fielddef_msgsubdef(p->top->f);
  12470. inner->name_table = NULL;
  12471. inner->mapfield = p->top->f;
  12472. inner->f = NULL;
  12473. inner->is_map = true;
  12474. inner->is_mapentry = false;
  12475. inner->is_any = false;
  12476. inner->any_frame = NULL;
  12477. inner->is_unknown_field = false;
  12478. p->top = inner;
  12479. return true;
  12480. } else if (upb_fielddef_issubmsg(p->top->f)) {
  12481. upb_jsonparser_frame *inner;
  12482. upb_selector_t sel;
  12483. /* Beginning of a subobject. Start a new parser frame in the submsg
  12484. * context. */
  12485. if (!check_stack(p)) return false;
  12486. inner = p->top + 1;
  12487. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
  12488. upb_sink_startsubmsg(&p->top->sink, sel, &inner->sink);
  12489. inner->m = upb_fielddef_msgsubdef(p->top->f);
  12490. set_name_table(p, inner);
  12491. inner->f = NULL;
  12492. inner->is_map = false;
  12493. inner->is_mapentry = false;
  12494. inner->is_unknown_field = false;
  12495. p->top = inner;
  12496. if (is_wellknown_msg(p, UPB_WELLKNOWN_ANY)) {
  12497. p->top->is_any = true;
  12498. p->top->any_frame =
  12499. upb_env_malloc(p->env, sizeof(upb_jsonparser_any_frame));
  12500. json_parser_any_frame_reset(p->top->any_frame);
  12501. } else {
  12502. p->top->is_any = false;
  12503. p->top->any_frame = NULL;
  12504. }
  12505. return true;
  12506. } else {
  12507. upb_status_seterrf(&p->status,
  12508. "Object specified for non-message/group field: %s",
  12509. upb_fielddef_name(p->top->f));
  12510. upb_env_reporterror(p->env, &p->status);
  12511. return false;
  12512. }
  12513. }
  12514. static bool start_subobject_full(upb_json_parser *p) {
  12515. if (is_top_level(p)) {
  12516. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  12517. start_value_object(p, VALUE_STRUCTVALUE);
  12518. if (!start_subobject(p)) return false;
  12519. start_structvalue_object(p);
  12520. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_STRUCT)) {
  12521. start_structvalue_object(p);
  12522. } else {
  12523. return true;
  12524. }
  12525. } else if (is_wellknown_field(p, UPB_WELLKNOWN_STRUCT)) {
  12526. if (!start_subobject(p)) return false;
  12527. start_structvalue_object(p);
  12528. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  12529. if (!start_subobject(p)) return false;
  12530. start_value_object(p, VALUE_STRUCTVALUE);
  12531. if (!start_subobject(p)) return false;
  12532. start_structvalue_object(p);
  12533. }
  12534. return start_subobject(p);
  12535. }
  12536. static void end_subobject(upb_json_parser *p) {
  12537. if (is_top_level(p)) {
  12538. return;
  12539. }
  12540. if (p->top->is_map) {
  12541. upb_selector_t sel;
  12542. p->top--;
  12543. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
  12544. upb_sink_endseq(&p->top->sink, sel);
  12545. } else {
  12546. upb_selector_t sel;
  12547. bool is_unknown = p->top->m == NULL;
  12548. p->top--;
  12549. if (!is_unknown) {
  12550. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSUBMSG);
  12551. upb_sink_endsubmsg(&p->top->sink, sel);
  12552. }
  12553. }
  12554. }
  12555. static void end_subobject_full(upb_json_parser *p) {
  12556. end_subobject(p);
  12557. if (is_wellknown_msg(p, UPB_WELLKNOWN_STRUCT)) {
  12558. end_structvalue_object(p);
  12559. if (!is_top_level(p)) {
  12560. end_subobject(p);
  12561. }
  12562. }
  12563. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  12564. end_value_object(p);
  12565. if (!is_top_level(p)) {
  12566. end_subobject(p);
  12567. }
  12568. }
  12569. }
  12570. static bool start_array(upb_json_parser *p) {
  12571. upb_jsonparser_frame *inner;
  12572. upb_selector_t sel;
  12573. if (is_top_level(p)) {
  12574. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  12575. start_value_object(p, VALUE_LISTVALUE);
  12576. if (!start_subobject(p)) return false;
  12577. start_listvalue_object(p);
  12578. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_LISTVALUE)) {
  12579. start_listvalue_object(p);
  12580. } else {
  12581. return false;
  12582. }
  12583. } else if (is_wellknown_field(p, UPB_WELLKNOWN_LISTVALUE)) {
  12584. if (!start_subobject(p)) return false;
  12585. start_listvalue_object(p);
  12586. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  12587. if (!start_subobject(p)) return false;
  12588. start_value_object(p, VALUE_LISTVALUE);
  12589. if (!start_subobject(p)) return false;
  12590. start_listvalue_object(p);
  12591. }
  12592. if (p->top->is_unknown_field) {
  12593. inner = p->top + 1;
  12594. inner->m = NULL;
  12595. inner->name_table = NULL;
  12596. inner->f = NULL;
  12597. inner->is_map = false;
  12598. inner->is_mapentry = false;
  12599. inner->is_any = false;
  12600. inner->any_frame = NULL;
  12601. inner->is_unknown_field = true;
  12602. p->top = inner;
  12603. return true;
  12604. }
  12605. if (!upb_fielddef_isseq(p->top->f)) {
  12606. upb_status_seterrf(&p->status,
  12607. "Array specified for non-repeated field: %s",
  12608. upb_fielddef_name(p->top->f));
  12609. upb_env_reporterror(p->env, &p->status);
  12610. return false;
  12611. }
  12612. if (!check_stack(p)) return false;
  12613. inner = p->top + 1;
  12614. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
  12615. upb_sink_startseq(&p->top->sink, sel, &inner->sink);
  12616. inner->m = p->top->m;
  12617. inner->name_table = NULL;
  12618. inner->f = p->top->f;
  12619. inner->is_map = false;
  12620. inner->is_mapentry = false;
  12621. inner->is_any = false;
  12622. inner->any_frame = NULL;
  12623. inner->is_unknown_field = false;
  12624. p->top = inner;
  12625. return true;
  12626. }
  12627. static void end_array(upb_json_parser *p) {
  12628. upb_selector_t sel;
  12629. UPB_ASSERT(p->top > p->stack);
  12630. p->top--;
  12631. if (p->top->is_unknown_field) {
  12632. return;
  12633. }
  12634. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
  12635. upb_sink_endseq(&p->top->sink, sel);
  12636. if (is_wellknown_msg(p, UPB_WELLKNOWN_LISTVALUE)) {
  12637. end_listvalue_object(p);
  12638. if (!is_top_level(p)) {
  12639. end_subobject(p);
  12640. }
  12641. }
  12642. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  12643. end_value_object(p);
  12644. if (!is_top_level(p)) {
  12645. end_subobject(p);
  12646. }
  12647. }
  12648. }
  12649. static void start_object(upb_json_parser *p) {
  12650. if (!p->top->is_map && p->top->m != NULL) {
  12651. upb_sink_startmsg(&p->top->sink);
  12652. }
  12653. }
  12654. static void end_object(upb_json_parser *p) {
  12655. if (!p->top->is_map && p->top->m != NULL) {
  12656. upb_status status;
  12657. upb_status_clear(&status);
  12658. upb_sink_endmsg(&p->top->sink, &status);
  12659. if (!upb_ok(&status)) {
  12660. upb_env_reporterror(p->env, &status);
  12661. }
  12662. }
  12663. }
  12664. static void start_any_object(upb_json_parser *p, const char *ptr) {
  12665. start_object(p);
  12666. p->top->any_frame->before_type_url_start = ptr;
  12667. p->top->any_frame->before_type_url_end = ptr;
  12668. }
  12669. static bool end_any_object(upb_json_parser *p, const char *ptr) {
  12670. const char *value_membername = "value";
  12671. bool is_well_known_packed = false;
  12672. const char *packed_end = ptr + 1;
  12673. upb_selector_t sel;
  12674. upb_jsonparser_frame *inner;
  12675. if (json_parser_any_frame_has_value(p->top->any_frame) &&
  12676. !json_parser_any_frame_has_type_url(p->top->any_frame)) {
  12677. upb_status_seterrmsg(&p->status, "No valid type url");
  12678. upb_env_reporterror(p->env, &p->status);
  12679. return false;
  12680. }
  12681. /* Well known types data is represented as value field. */
  12682. if (upb_msgdef_wellknowntype(p->top->any_frame->parser->top->m) !=
  12683. UPB_WELLKNOWN_UNSPECIFIED) {
  12684. is_well_known_packed = true;
  12685. if (json_parser_any_frame_has_value_before_type_url(p->top->any_frame)) {
  12686. p->top->any_frame->before_type_url_start =
  12687. memchr(p->top->any_frame->before_type_url_start, ':',
  12688. p->top->any_frame->before_type_url_end -
  12689. p->top->any_frame->before_type_url_start);
  12690. if (p->top->any_frame->before_type_url_start == NULL) {
  12691. upb_status_seterrmsg(&p->status, "invalid data for well known type.");
  12692. upb_env_reporterror(p->env, &p->status);
  12693. return false;
  12694. }
  12695. p->top->any_frame->before_type_url_start++;
  12696. }
  12697. if (json_parser_any_frame_has_value_after_type_url(p->top->any_frame)) {
  12698. p->top->any_frame->after_type_url_start =
  12699. memchr(p->top->any_frame->after_type_url_start, ':',
  12700. (ptr + 1) -
  12701. p->top->any_frame->after_type_url_start);
  12702. if (p->top->any_frame->after_type_url_start == NULL) {
  12703. upb_status_seterrmsg(&p->status, "Invalid data for well known type.");
  12704. upb_env_reporterror(p->env, &p->status);
  12705. return false;
  12706. }
  12707. p->top->any_frame->after_type_url_start++;
  12708. packed_end = ptr;
  12709. }
  12710. }
  12711. if (json_parser_any_frame_has_value_before_type_url(p->top->any_frame)) {
  12712. if (!parse(p->top->any_frame->parser, NULL,
  12713. p->top->any_frame->before_type_url_start,
  12714. p->top->any_frame->before_type_url_end -
  12715. p->top->any_frame->before_type_url_start, NULL)) {
  12716. return false;
  12717. }
  12718. } else {
  12719. if (!is_well_known_packed) {
  12720. if (!parse(p->top->any_frame->parser, NULL, "{", 1, NULL)) {
  12721. return false;
  12722. }
  12723. }
  12724. }
  12725. if (json_parser_any_frame_has_value_before_type_url(p->top->any_frame) &&
  12726. json_parser_any_frame_has_value_after_type_url(p->top->any_frame)) {
  12727. if (!parse(p->top->any_frame->parser, NULL, ",", 1, NULL)) {
  12728. return false;
  12729. }
  12730. }
  12731. if (json_parser_any_frame_has_value_after_type_url(p->top->any_frame)) {
  12732. if (!parse(p->top->any_frame->parser, NULL,
  12733. p->top->any_frame->after_type_url_start,
  12734. packed_end - p->top->any_frame->after_type_url_start, NULL)) {
  12735. return false;
  12736. }
  12737. } else {
  12738. if (!is_well_known_packed) {
  12739. if (!parse(p->top->any_frame->parser, NULL, "}", 1, NULL)) {
  12740. return false;
  12741. }
  12742. }
  12743. }
  12744. if (!end(p->top->any_frame->parser, NULL)) {
  12745. return false;
  12746. }
  12747. p->top->is_any = false;
  12748. /* Set value */
  12749. start_member(p);
  12750. capture_begin(p, value_membername);
  12751. capture_end(p, value_membername + 5);
  12752. end_membername(p);
  12753. if (!check_stack(p)) return false;
  12754. inner = p->top + 1;
  12755. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  12756. upb_sink_startstr(&p->top->sink, sel, 0, &inner->sink);
  12757. sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
  12758. upb_sink_putstring(&inner->sink, sel, p->top->any_frame->stringsink.ptr,
  12759. p->top->any_frame->stringsink.len, NULL);
  12760. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  12761. upb_sink_endstr(&inner->sink, sel);
  12762. end_member(p);
  12763. end_object(p);
  12764. /* Deallocate any parse frame. */
  12765. json_parser_any_frame_free(p->top->any_frame);
  12766. upb_env_free(p->env, p->top->any_frame);
  12767. return true;
  12768. }
  12769. static bool is_string_wrapper(const upb_msgdef *m) {
  12770. upb_wellknowntype_t type = upb_msgdef_wellknowntype(m);
  12771. return type == UPB_WELLKNOWN_STRINGVALUE ||
  12772. type == UPB_WELLKNOWN_BYTESVALUE;
  12773. }
  12774. static bool is_fieldmask(const upb_msgdef *m) {
  12775. upb_wellknowntype_t type = upb_msgdef_wellknowntype(m);
  12776. return type == UPB_WELLKNOWN_FIELDMASK;
  12777. }
  12778. static void start_fieldmask_object(upb_json_parser *p) {
  12779. const char *membername = "paths";
  12780. start_object(p);
  12781. /* Set up context for parsing value */
  12782. start_member(p);
  12783. capture_begin(p, membername);
  12784. capture_end(p, membername + 5);
  12785. end_membername(p);
  12786. start_array(p);
  12787. }
  12788. static void end_fieldmask_object(upb_json_parser *p) {
  12789. end_array(p);
  12790. end_member(p);
  12791. end_object(p);
  12792. }
  12793. static void start_wrapper_object(upb_json_parser *p) {
  12794. const char *membername = "value";
  12795. start_object(p);
  12796. /* Set up context for parsing value */
  12797. start_member(p);
  12798. capture_begin(p, membername);
  12799. capture_end(p, membername + 5);
  12800. end_membername(p);
  12801. }
  12802. static void end_wrapper_object(upb_json_parser *p) {
  12803. end_member(p);
  12804. end_object(p);
  12805. }
  12806. static void start_value_object(upb_json_parser *p, int value_type) {
  12807. const char *nullmember = "null_value";
  12808. const char *numbermember = "number_value";
  12809. const char *stringmember = "string_value";
  12810. const char *boolmember = "bool_value";
  12811. const char *structmember = "struct_value";
  12812. const char *listmember = "list_value";
  12813. const char *membername = "";
  12814. switch (value_type) {
  12815. case VALUE_NULLVALUE:
  12816. membername = nullmember;
  12817. break;
  12818. case VALUE_NUMBERVALUE:
  12819. membername = numbermember;
  12820. break;
  12821. case VALUE_STRINGVALUE:
  12822. membername = stringmember;
  12823. break;
  12824. case VALUE_BOOLVALUE:
  12825. membername = boolmember;
  12826. break;
  12827. case VALUE_STRUCTVALUE:
  12828. membername = structmember;
  12829. break;
  12830. case VALUE_LISTVALUE:
  12831. membername = listmember;
  12832. break;
  12833. }
  12834. start_object(p);
  12835. /* Set up context for parsing value */
  12836. start_member(p);
  12837. capture_begin(p, membername);
  12838. capture_end(p, membername + strlen(membername));
  12839. end_membername(p);
  12840. }
  12841. static void end_value_object(upb_json_parser *p) {
  12842. end_member(p);
  12843. end_object(p);
  12844. }
  12845. static void start_listvalue_object(upb_json_parser *p) {
  12846. const char *membername = "values";
  12847. start_object(p);
  12848. /* Set up context for parsing value */
  12849. start_member(p);
  12850. capture_begin(p, membername);
  12851. capture_end(p, membername + strlen(membername));
  12852. end_membername(p);
  12853. }
  12854. static void end_listvalue_object(upb_json_parser *p) {
  12855. end_member(p);
  12856. end_object(p);
  12857. }
  12858. static void start_structvalue_object(upb_json_parser *p) {
  12859. const char *membername = "fields";
  12860. start_object(p);
  12861. /* Set up context for parsing value */
  12862. start_member(p);
  12863. capture_begin(p, membername);
  12864. capture_end(p, membername + strlen(membername));
  12865. end_membername(p);
  12866. }
  12867. static void end_structvalue_object(upb_json_parser *p) {
  12868. end_member(p);
  12869. end_object(p);
  12870. }
  12871. static bool is_top_level(upb_json_parser *p) {
  12872. return p->top == p->stack && p->top->f == NULL && !p->top->is_unknown_field;
  12873. }
  12874. static bool is_wellknown_msg(upb_json_parser *p, upb_wellknowntype_t type) {
  12875. return p->top->m != NULL && upb_msgdef_wellknowntype(p->top->m) == type;
  12876. }
  12877. static bool is_wellknown_field(upb_json_parser *p, upb_wellknowntype_t type) {
  12878. return p->top->f != NULL &&
  12879. upb_fielddef_issubmsg(p->top->f) &&
  12880. (upb_msgdef_wellknowntype(upb_fielddef_msgsubdef(p->top->f))
  12881. == type);
  12882. }
  12883. static bool does_number_wrapper_start(upb_json_parser *p) {
  12884. return p->top->f != NULL &&
  12885. upb_fielddef_issubmsg(p->top->f) &&
  12886. upb_msgdef_isnumberwrapper(upb_fielddef_msgsubdef(p->top->f));
  12887. }
  12888. static bool does_number_wrapper_end(upb_json_parser *p) {
  12889. return p->top->m != NULL && upb_msgdef_isnumberwrapper(p->top->m);
  12890. }
  12891. static bool is_number_wrapper_object(upb_json_parser *p) {
  12892. return p->top->m != NULL && upb_msgdef_isnumberwrapper(p->top->m);
  12893. }
  12894. static bool does_string_wrapper_start(upb_json_parser *p) {
  12895. return p->top->f != NULL &&
  12896. upb_fielddef_issubmsg(p->top->f) &&
  12897. is_string_wrapper(upb_fielddef_msgsubdef(p->top->f));
  12898. }
  12899. static bool does_string_wrapper_end(upb_json_parser *p) {
  12900. return p->top->m != NULL && is_string_wrapper(p->top->m);
  12901. }
  12902. static bool is_string_wrapper_object(upb_json_parser *p) {
  12903. return p->top->m != NULL && is_string_wrapper(p->top->m);
  12904. }
  12905. static bool does_fieldmask_start(upb_json_parser *p) {
  12906. return p->top->f != NULL &&
  12907. upb_fielddef_issubmsg(p->top->f) &&
  12908. is_fieldmask(upb_fielddef_msgsubdef(p->top->f));
  12909. }
  12910. static bool does_fieldmask_end(upb_json_parser *p) {
  12911. return p->top->m != NULL && is_fieldmask(p->top->m);
  12912. }
  12913. static bool is_fieldmask_object(upb_json_parser *p) {
  12914. return p->top->m != NULL && is_fieldmask(p->top->m);
  12915. }
  12916. #define CHECK_RETURN_TOP(x) if (!(x)) goto error
  12917. /* The actual parser **********************************************************/
  12918. /* What follows is the Ragel parser itself. The language is specified in Ragel
  12919. * and the actions call our C functions above.
  12920. *
  12921. * Ragel has an extensive set of functionality, and we use only a small part of
  12922. * it. There are many action types but we only use a few:
  12923. *
  12924. * ">" -- transition into a machine
  12925. * "%" -- transition out of a machine
  12926. * "@" -- transition into a final state of a machine.
  12927. *
  12928. * "@" transitions are tricky because a machine can transition into a final
  12929. * state repeatedly. But in some cases we know this can't happen, for example
  12930. * a string which is delimited by a final '"' can only transition into its
  12931. * final state once, when the closing '"' is seen. */
  12932. #line 2730 "upb/json/parser.rl"
  12933. #line 2556 "upb/json/parser.c"
  12934. static const char _json_actions[] = {
  12935. 0, 1, 0, 1, 1, 1, 3, 1,
  12936. 4, 1, 6, 1, 7, 1, 8, 1,
  12937. 9, 1, 10, 1, 11, 1, 12, 1,
  12938. 13, 1, 24, 1, 26, 1, 28, 1,
  12939. 29, 1, 31, 1, 32, 1, 33, 1,
  12940. 35, 1, 37, 1, 38, 1, 39, 1,
  12941. 40, 1, 42, 1, 43, 2, 4, 9,
  12942. 2, 5, 6, 2, 7, 3, 2, 7,
  12943. 9, 2, 14, 15, 2, 16, 17, 2,
  12944. 18, 19, 2, 21, 23, 2, 22, 20,
  12945. 2, 27, 25, 2, 29, 31, 2, 34,
  12946. 2, 2, 35, 43, 2, 36, 25, 2,
  12947. 38, 43, 2, 39, 43, 2, 40, 43,
  12948. 2, 41, 30, 2, 42, 43, 3, 21,
  12949. 23, 24, 4, 14, 15, 16, 17
  12950. };
  12951. static const short _json_key_offsets[] = {
  12952. 0, 0, 12, 13, 18, 23, 28, 29,
  12953. 30, 31, 32, 33, 34, 35, 36, 37,
  12954. 38, 43, 44, 48, 53, 58, 63, 67,
  12955. 71, 74, 77, 79, 83, 87, 89, 91,
  12956. 96, 98, 100, 109, 115, 121, 127, 133,
  12957. 135, 139, 142, 144, 146, 149, 150, 154,
  12958. 156, 158, 160, 162, 163, 165, 167, 168,
  12959. 170, 172, 173, 175, 177, 178, 180, 182,
  12960. 183, 185, 187, 191, 193, 195, 196, 197,
  12961. 198, 199, 201, 206, 208, 210, 212, 221,
  12962. 222, 222, 222, 227, 232, 237, 238, 239,
  12963. 240, 241, 241, 242, 243, 244, 244, 245,
  12964. 246, 247, 247, 252, 253, 257, 262, 267,
  12965. 272, 276, 276, 279, 282, 285, 288, 291,
  12966. 294, 294, 294, 294, 294, 294
  12967. };
  12968. static const char _json_trans_keys[] = {
  12969. 32, 34, 45, 91, 102, 110, 116, 123,
  12970. 9, 13, 48, 57, 34, 32, 93, 125,
  12971. 9, 13, 32, 44, 93, 9, 13, 32,
  12972. 93, 125, 9, 13, 97, 108, 115, 101,
  12973. 117, 108, 108, 114, 117, 101, 32, 34,
  12974. 125, 9, 13, 34, 32, 58, 9, 13,
  12975. 32, 93, 125, 9, 13, 32, 44, 125,
  12976. 9, 13, 32, 44, 125, 9, 13, 32,
  12977. 34, 9, 13, 45, 48, 49, 57, 48,
  12978. 49, 57, 46, 69, 101, 48, 57, 69,
  12979. 101, 48, 57, 43, 45, 48, 57, 48,
  12980. 57, 48, 57, 46, 69, 101, 48, 57,
  12981. 34, 92, 34, 92, 34, 47, 92, 98,
  12982. 102, 110, 114, 116, 117, 48, 57, 65,
  12983. 70, 97, 102, 48, 57, 65, 70, 97,
  12984. 102, 48, 57, 65, 70, 97, 102, 48,
  12985. 57, 65, 70, 97, 102, 34, 92, 45,
  12986. 48, 49, 57, 48, 49, 57, 46, 115,
  12987. 48, 57, 115, 48, 57, 34, 46, 115,
  12988. 48, 57, 48, 57, 48, 57, 48, 57,
  12989. 48, 57, 45, 48, 57, 48, 57, 45,
  12990. 48, 57, 48, 57, 84, 48, 57, 48,
  12991. 57, 58, 48, 57, 48, 57, 58, 48,
  12992. 57, 48, 57, 43, 45, 46, 90, 48,
  12993. 57, 48, 57, 58, 48, 48, 34, 48,
  12994. 57, 43, 45, 90, 48, 57, 34, 44,
  12995. 34, 44, 34, 44, 34, 45, 91, 102,
  12996. 110, 116, 123, 48, 57, 34, 32, 93,
  12997. 125, 9, 13, 32, 44, 93, 9, 13,
  12998. 32, 93, 125, 9, 13, 97, 108, 115,
  12999. 101, 117, 108, 108, 114, 117, 101, 32,
  13000. 34, 125, 9, 13, 34, 32, 58, 9,
  13001. 13, 32, 93, 125, 9, 13, 32, 44,
  13002. 125, 9, 13, 32, 44, 125, 9, 13,
  13003. 32, 34, 9, 13, 32, 9, 13, 32,
  13004. 9, 13, 32, 9, 13, 32, 9, 13,
  13005. 32, 9, 13, 32, 9, 13, 0
  13006. };
  13007. static const char _json_single_lengths[] = {
  13008. 0, 8, 1, 3, 3, 3, 1, 1,
  13009. 1, 1, 1, 1, 1, 1, 1, 1,
  13010. 3, 1, 2, 3, 3, 3, 2, 2,
  13011. 1, 3, 0, 2, 2, 0, 0, 3,
  13012. 2, 2, 9, 0, 0, 0, 0, 2,
  13013. 2, 1, 2, 0, 1, 1, 2, 0,
  13014. 0, 0, 0, 1, 0, 0, 1, 0,
  13015. 0, 1, 0, 0, 1, 0, 0, 1,
  13016. 0, 0, 4, 0, 0, 1, 1, 1,
  13017. 1, 0, 3, 2, 2, 2, 7, 1,
  13018. 0, 0, 3, 3, 3, 1, 1, 1,
  13019. 1, 0, 1, 1, 1, 0, 1, 1,
  13020. 1, 0, 3, 1, 2, 3, 3, 3,
  13021. 2, 0, 1, 1, 1, 1, 1, 1,
  13022. 0, 0, 0, 0, 0, 0
  13023. };
  13024. static const char _json_range_lengths[] = {
  13025. 0, 2, 0, 1, 1, 1, 0, 0,
  13026. 0, 0, 0, 0, 0, 0, 0, 0,
  13027. 1, 0, 1, 1, 1, 1, 1, 1,
  13028. 1, 0, 1, 1, 1, 1, 1, 1,
  13029. 0, 0, 0, 3, 3, 3, 3, 0,
  13030. 1, 1, 0, 1, 1, 0, 1, 1,
  13031. 1, 1, 1, 0, 1, 1, 0, 1,
  13032. 1, 0, 1, 1, 0, 1, 1, 0,
  13033. 1, 1, 0, 1, 1, 0, 0, 0,
  13034. 0, 1, 1, 0, 0, 0, 1, 0,
  13035. 0, 0, 1, 1, 1, 0, 0, 0,
  13036. 0, 0, 0, 0, 0, 0, 0, 0,
  13037. 0, 0, 1, 0, 1, 1, 1, 1,
  13038. 1, 0, 1, 1, 1, 1, 1, 1,
  13039. 0, 0, 0, 0, 0, 0
  13040. };
  13041. static const short _json_index_offsets[] = {
  13042. 0, 0, 11, 13, 18, 23, 28, 30,
  13043. 32, 34, 36, 38, 40, 42, 44, 46,
  13044. 48, 53, 55, 59, 64, 69, 74, 78,
  13045. 82, 85, 89, 91, 95, 99, 101, 103,
  13046. 108, 111, 114, 124, 128, 132, 136, 140,
  13047. 143, 147, 150, 153, 155, 158, 160, 164,
  13048. 166, 168, 170, 172, 174, 176, 178, 180,
  13049. 182, 184, 186, 188, 190, 192, 194, 196,
  13050. 198, 200, 202, 207, 209, 211, 213, 215,
  13051. 217, 219, 221, 226, 229, 232, 235, 244,
  13052. 246, 247, 248, 253, 258, 263, 265, 267,
  13053. 269, 271, 272, 274, 276, 278, 279, 281,
  13054. 283, 285, 286, 291, 293, 297, 302, 307,
  13055. 312, 316, 317, 320, 323, 326, 329, 332,
  13056. 335, 336, 337, 338, 339, 340
  13057. };
  13058. static const unsigned char _json_indicies[] = {
  13059. 0, 2, 3, 4, 5, 6, 7, 8,
  13060. 0, 3, 1, 9, 1, 11, 12, 1,
  13061. 11, 10, 13, 14, 12, 13, 1, 14,
  13062. 1, 1, 14, 10, 15, 1, 16, 1,
  13063. 17, 1, 18, 1, 19, 1, 20, 1,
  13064. 21, 1, 22, 1, 23, 1, 24, 1,
  13065. 25, 26, 27, 25, 1, 28, 1, 29,
  13066. 30, 29, 1, 30, 1, 1, 30, 31,
  13067. 32, 33, 34, 32, 1, 35, 36, 27,
  13068. 35, 1, 36, 26, 36, 1, 37, 38,
  13069. 39, 1, 38, 39, 1, 41, 42, 42,
  13070. 40, 43, 1, 42, 42, 43, 40, 44,
  13071. 44, 45, 1, 45, 1, 45, 40, 41,
  13072. 42, 42, 39, 40, 47, 48, 46, 50,
  13073. 51, 49, 52, 52, 52, 52, 52, 52,
  13074. 52, 52, 53, 1, 54, 54, 54, 1,
  13075. 55, 55, 55, 1, 56, 56, 56, 1,
  13076. 57, 57, 57, 1, 59, 60, 58, 61,
  13077. 62, 63, 1, 64, 65, 1, 66, 67,
  13078. 1, 68, 1, 67, 68, 1, 69, 1,
  13079. 66, 67, 65, 1, 70, 1, 71, 1,
  13080. 72, 1, 73, 1, 74, 1, 75, 1,
  13081. 76, 1, 77, 1, 78, 1, 79, 1,
  13082. 80, 1, 81, 1, 82, 1, 83, 1,
  13083. 84, 1, 85, 1, 86, 1, 87, 1,
  13084. 88, 1, 89, 89, 90, 91, 1, 92,
  13085. 1, 93, 1, 94, 1, 95, 1, 96,
  13086. 1, 97, 1, 98, 1, 99, 99, 100,
  13087. 98, 1, 102, 1, 101, 104, 105, 103,
  13088. 1, 1, 101, 106, 107, 108, 109, 110,
  13089. 111, 112, 107, 1, 113, 1, 114, 115,
  13090. 117, 118, 1, 117, 116, 119, 120, 118,
  13091. 119, 1, 120, 1, 1, 120, 116, 121,
  13092. 1, 122, 1, 123, 1, 124, 1, 125,
  13093. 126, 1, 127, 1, 128, 1, 129, 130,
  13094. 1, 131, 1, 132, 1, 133, 134, 135,
  13095. 136, 134, 1, 137, 1, 138, 139, 138,
  13096. 1, 139, 1, 1, 139, 140, 141, 142,
  13097. 143, 141, 1, 144, 145, 136, 144, 1,
  13098. 145, 135, 145, 1, 146, 147, 147, 1,
  13099. 148, 148, 1, 149, 149, 1, 150, 150,
  13100. 1, 151, 151, 1, 152, 152, 1, 1,
  13101. 1, 1, 1, 1, 1, 0
  13102. };
  13103. static const char _json_trans_targs[] = {
  13104. 1, 0, 2, 107, 3, 6, 10, 13,
  13105. 16, 106, 4, 3, 106, 4, 5, 7,
  13106. 8, 9, 108, 11, 12, 109, 14, 15,
  13107. 110, 16, 17, 111, 18, 18, 19, 20,
  13108. 21, 22, 111, 21, 22, 24, 25, 31,
  13109. 112, 26, 28, 27, 29, 30, 33, 113,
  13110. 34, 33, 113, 34, 32, 35, 36, 37,
  13111. 38, 39, 33, 113, 34, 41, 42, 46,
  13112. 42, 46, 43, 45, 44, 114, 48, 49,
  13113. 50, 51, 52, 53, 54, 55, 56, 57,
  13114. 58, 59, 60, 61, 62, 63, 64, 65,
  13115. 66, 67, 73, 72, 68, 69, 70, 71,
  13116. 72, 115, 74, 67, 72, 76, 116, 76,
  13117. 116, 77, 79, 81, 82, 85, 90, 94,
  13118. 98, 80, 117, 117, 83, 82, 80, 83,
  13119. 84, 86, 87, 88, 89, 117, 91, 92,
  13120. 93, 117, 95, 96, 97, 117, 98, 99,
  13121. 105, 100, 100, 101, 102, 103, 104, 105,
  13122. 103, 104, 117, 106, 106, 106, 106, 106,
  13123. 106
  13124. };
  13125. static const char _json_trans_actions[] = {
  13126. 0, 0, 92, 86, 35, 0, 0, 0,
  13127. 104, 41, 27, 0, 37, 0, 0, 0,
  13128. 0, 0, 0, 0, 0, 0, 0, 0,
  13129. 0, 0, 80, 33, 29, 0, 0, 27,
  13130. 31, 31, 83, 0, 0, 0, 0, 0,
  13131. 3, 0, 0, 0, 0, 0, 5, 15,
  13132. 0, 0, 53, 7, 13, 0, 56, 9,
  13133. 9, 9, 59, 62, 11, 17, 17, 17,
  13134. 0, 0, 0, 19, 0, 21, 23, 0,
  13135. 0, 0, 0, 0, 0, 0, 0, 0,
  13136. 0, 0, 0, 0, 0, 0, 0, 0,
  13137. 0, 114, 65, 114, 0, 0, 0, 0,
  13138. 0, 71, 0, 68, 68, 77, 25, 0,
  13139. 110, 74, 92, 86, 35, 0, 0, 0,
  13140. 104, 41, 51, 89, 27, 0, 37, 0,
  13141. 0, 0, 0, 0, 0, 98, 0, 0,
  13142. 0, 101, 0, 0, 0, 95, 0, 80,
  13143. 33, 29, 0, 0, 27, 31, 31, 83,
  13144. 0, 0, 107, 0, 39, 45, 47, 43,
  13145. 49
  13146. };
  13147. static const char _json_eof_actions[] = {
  13148. 0, 0, 0, 0, 0, 0, 0, 0,
  13149. 0, 0, 0, 0, 0, 0, 0, 0,
  13150. 0, 0, 0, 0, 0, 0, 0, 0,
  13151. 0, 1, 0, 1, 0, 0, 1, 1,
  13152. 0, 0, 0, 0, 0, 0, 0, 0,
  13153. 0, 0, 0, 0, 0, 0, 0, 0,
  13154. 0, 0, 0, 0, 0, 0, 0, 0,
  13155. 0, 0, 0, 0, 0, 0, 0, 0,
  13156. 0, 0, 0, 0, 0, 0, 0, 0,
  13157. 0, 0, 0, 0, 0, 0, 0, 0,
  13158. 0, 0, 0, 0, 0, 0, 0, 0,
  13159. 0, 0, 0, 0, 0, 0, 0, 0,
  13160. 0, 0, 0, 0, 0, 0, 0, 0,
  13161. 0, 0, 0, 39, 45, 47, 43, 49,
  13162. 0, 0, 0, 0, 0, 0
  13163. };
  13164. static const int json_start = 1;
  13165. static const int json_en_number_machine = 23;
  13166. static const int json_en_string_machine = 32;
  13167. static const int json_en_duration_machine = 40;
  13168. static const int json_en_timestamp_machine = 47;
  13169. static const int json_en_fieldmask_machine = 75;
  13170. static const int json_en_value_machine = 78;
  13171. static const int json_en_main = 1;
  13172. #line 2733 "upb/json/parser.rl"
  13173. size_t parse(void *closure, const void *hd, const char *buf, size_t size,
  13174. const upb_bufhandle *handle) {
  13175. upb_json_parser *parser = closure;
  13176. /* Variables used by Ragel's generated code. */
  13177. int cs = parser->current_state;
  13178. int *stack = parser->parser_stack;
  13179. int top = parser->parser_top;
  13180. const char *p = buf;
  13181. const char *pe = buf + size;
  13182. const char *eof = &eof_ch;
  13183. parser->handle = handle;
  13184. UPB_UNUSED(hd);
  13185. UPB_UNUSED(handle);
  13186. capture_resume(parser, buf);
  13187. #line 2831 "upb/json/parser.c"
  13188. {
  13189. int _klen;
  13190. unsigned int _trans;
  13191. const char *_acts;
  13192. unsigned int _nacts;
  13193. const char *_keys;
  13194. if ( p == pe )
  13195. goto _test_eof;
  13196. if ( cs == 0 )
  13197. goto _out;
  13198. _resume:
  13199. _keys = _json_trans_keys + _json_key_offsets[cs];
  13200. _trans = _json_index_offsets[cs];
  13201. _klen = _json_single_lengths[cs];
  13202. if ( _klen > 0 ) {
  13203. const char *_lower = _keys;
  13204. const char *_mid;
  13205. const char *_upper = _keys + _klen - 1;
  13206. while (1) {
  13207. if ( _upper < _lower )
  13208. break;
  13209. _mid = _lower + ((_upper-_lower) >> 1);
  13210. if ( (*p) < *_mid )
  13211. _upper = _mid - 1;
  13212. else if ( (*p) > *_mid )
  13213. _lower = _mid + 1;
  13214. else {
  13215. _trans += (unsigned int)(_mid - _keys);
  13216. goto _match;
  13217. }
  13218. }
  13219. _keys += _klen;
  13220. _trans += _klen;
  13221. }
  13222. _klen = _json_range_lengths[cs];
  13223. if ( _klen > 0 ) {
  13224. const char *_lower = _keys;
  13225. const char *_mid;
  13226. const char *_upper = _keys + (_klen<<1) - 2;
  13227. while (1) {
  13228. if ( _upper < _lower )
  13229. break;
  13230. _mid = _lower + (((_upper-_lower) >> 1) & ~1);
  13231. if ( (*p) < _mid[0] )
  13232. _upper = _mid - 2;
  13233. else if ( (*p) > _mid[1] )
  13234. _lower = _mid + 2;
  13235. else {
  13236. _trans += (unsigned int)((_mid - _keys)>>1);
  13237. goto _match;
  13238. }
  13239. }
  13240. _trans += _klen;
  13241. }
  13242. _match:
  13243. _trans = _json_indicies[_trans];
  13244. cs = _json_trans_targs[_trans];
  13245. if ( _json_trans_actions[_trans] == 0 )
  13246. goto _again;
  13247. _acts = _json_actions + _json_trans_actions[_trans];
  13248. _nacts = (unsigned int) *_acts++;
  13249. while ( _nacts-- > 0 )
  13250. {
  13251. switch ( *_acts++ )
  13252. {
  13253. case 1:
  13254. #line 2561 "upb/json/parser.rl"
  13255. { p--; {cs = stack[--top]; goto _again;} }
  13256. break;
  13257. case 2:
  13258. #line 2563 "upb/json/parser.rl"
  13259. { p--; {stack[top++] = cs; cs = 23;goto _again;} }
  13260. break;
  13261. case 3:
  13262. #line 2567 "upb/json/parser.rl"
  13263. { start_text(parser, p); }
  13264. break;
  13265. case 4:
  13266. #line 2568 "upb/json/parser.rl"
  13267. { CHECK_RETURN_TOP(end_text(parser, p)); }
  13268. break;
  13269. case 5:
  13270. #line 2574 "upb/json/parser.rl"
  13271. { start_hex(parser); }
  13272. break;
  13273. case 6:
  13274. #line 2575 "upb/json/parser.rl"
  13275. { hexdigit(parser, p); }
  13276. break;
  13277. case 7:
  13278. #line 2576 "upb/json/parser.rl"
  13279. { CHECK_RETURN_TOP(end_hex(parser)); }
  13280. break;
  13281. case 8:
  13282. #line 2582 "upb/json/parser.rl"
  13283. { CHECK_RETURN_TOP(escape(parser, p)); }
  13284. break;
  13285. case 9:
  13286. #line 2588 "upb/json/parser.rl"
  13287. { p--; {cs = stack[--top]; goto _again;} }
  13288. break;
  13289. case 10:
  13290. #line 2600 "upb/json/parser.rl"
  13291. { start_duration_base(parser, p); }
  13292. break;
  13293. case 11:
  13294. #line 2601 "upb/json/parser.rl"
  13295. { CHECK_RETURN_TOP(end_duration_base(parser, p)); }
  13296. break;
  13297. case 12:
  13298. #line 2603 "upb/json/parser.rl"
  13299. { p--; {cs = stack[--top]; goto _again;} }
  13300. break;
  13301. case 13:
  13302. #line 2608 "upb/json/parser.rl"
  13303. { start_timestamp_base(parser, p); }
  13304. break;
  13305. case 14:
  13306. #line 2609 "upb/json/parser.rl"
  13307. { CHECK_RETURN_TOP(end_timestamp_base(parser, p)); }
  13308. break;
  13309. case 15:
  13310. #line 2611 "upb/json/parser.rl"
  13311. { start_timestamp_fraction(parser, p); }
  13312. break;
  13313. case 16:
  13314. #line 2612 "upb/json/parser.rl"
  13315. { CHECK_RETURN_TOP(end_timestamp_fraction(parser, p)); }
  13316. break;
  13317. case 17:
  13318. #line 2614 "upb/json/parser.rl"
  13319. { start_timestamp_zone(parser, p); }
  13320. break;
  13321. case 18:
  13322. #line 2615 "upb/json/parser.rl"
  13323. { CHECK_RETURN_TOP(end_timestamp_zone(parser, p)); }
  13324. break;
  13325. case 19:
  13326. #line 2617 "upb/json/parser.rl"
  13327. { p--; {cs = stack[--top]; goto _again;} }
  13328. break;
  13329. case 20:
  13330. #line 2622 "upb/json/parser.rl"
  13331. { start_fieldmask_path_text(parser, p); }
  13332. break;
  13333. case 21:
  13334. #line 2623 "upb/json/parser.rl"
  13335. { end_fieldmask_path_text(parser, p); }
  13336. break;
  13337. case 22:
  13338. #line 2628 "upb/json/parser.rl"
  13339. { start_fieldmask_path(parser); }
  13340. break;
  13341. case 23:
  13342. #line 2629 "upb/json/parser.rl"
  13343. { end_fieldmask_path(parser); }
  13344. break;
  13345. case 24:
  13346. #line 2635 "upb/json/parser.rl"
  13347. { p--; {cs = stack[--top]; goto _again;} }
  13348. break;
  13349. case 25:
  13350. #line 2640 "upb/json/parser.rl"
  13351. {
  13352. if (is_wellknown_msg(parser, UPB_WELLKNOWN_TIMESTAMP)) {
  13353. {stack[top++] = cs; cs = 47;goto _again;}
  13354. } else if (is_wellknown_msg(parser, UPB_WELLKNOWN_DURATION)) {
  13355. {stack[top++] = cs; cs = 40;goto _again;}
  13356. } else if (is_wellknown_msg(parser, UPB_WELLKNOWN_FIELDMASK)) {
  13357. {stack[top++] = cs; cs = 75;goto _again;}
  13358. } else {
  13359. {stack[top++] = cs; cs = 32;goto _again;}
  13360. }
  13361. }
  13362. break;
  13363. case 26:
  13364. #line 2653 "upb/json/parser.rl"
  13365. { p--; {stack[top++] = cs; cs = 78;goto _again;} }
  13366. break;
  13367. case 27:
  13368. #line 2658 "upb/json/parser.rl"
  13369. {
  13370. if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
  13371. start_any_member(parser, p);
  13372. } else {
  13373. start_member(parser);
  13374. }
  13375. }
  13376. break;
  13377. case 28:
  13378. #line 2665 "upb/json/parser.rl"
  13379. { CHECK_RETURN_TOP(end_membername(parser)); }
  13380. break;
  13381. case 29:
  13382. #line 2668 "upb/json/parser.rl"
  13383. {
  13384. if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
  13385. end_any_member(parser, p);
  13386. } else {
  13387. end_member(parser);
  13388. }
  13389. }
  13390. break;
  13391. case 30:
  13392. #line 2679 "upb/json/parser.rl"
  13393. {
  13394. if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
  13395. start_any_object(parser, p);
  13396. } else {
  13397. start_object(parser);
  13398. }
  13399. }
  13400. break;
  13401. case 31:
  13402. #line 2688 "upb/json/parser.rl"
  13403. {
  13404. if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
  13405. CHECK_RETURN_TOP(end_any_object(parser, p));
  13406. } else {
  13407. end_object(parser);
  13408. }
  13409. }
  13410. break;
  13411. case 32:
  13412. #line 2700 "upb/json/parser.rl"
  13413. { CHECK_RETURN_TOP(start_array(parser)); }
  13414. break;
  13415. case 33:
  13416. #line 2704 "upb/json/parser.rl"
  13417. { end_array(parser); }
  13418. break;
  13419. case 34:
  13420. #line 2709 "upb/json/parser.rl"
  13421. { CHECK_RETURN_TOP(start_number(parser, p)); }
  13422. break;
  13423. case 35:
  13424. #line 2710 "upb/json/parser.rl"
  13425. { CHECK_RETURN_TOP(end_number(parser, p)); }
  13426. break;
  13427. case 36:
  13428. #line 2712 "upb/json/parser.rl"
  13429. { CHECK_RETURN_TOP(start_stringval(parser)); }
  13430. break;
  13431. case 37:
  13432. #line 2713 "upb/json/parser.rl"
  13433. { CHECK_RETURN_TOP(end_stringval(parser)); }
  13434. break;
  13435. case 38:
  13436. #line 2715 "upb/json/parser.rl"
  13437. { CHECK_RETURN_TOP(end_bool(parser, true)); }
  13438. break;
  13439. case 39:
  13440. #line 2717 "upb/json/parser.rl"
  13441. { CHECK_RETURN_TOP(end_bool(parser, false)); }
  13442. break;
  13443. case 40:
  13444. #line 2719 "upb/json/parser.rl"
  13445. { CHECK_RETURN_TOP(end_null(parser)); }
  13446. break;
  13447. case 41:
  13448. #line 2721 "upb/json/parser.rl"
  13449. { CHECK_RETURN_TOP(start_subobject_full(parser)); }
  13450. break;
  13451. case 42:
  13452. #line 2722 "upb/json/parser.rl"
  13453. { end_subobject_full(parser); }
  13454. break;
  13455. case 43:
  13456. #line 2727 "upb/json/parser.rl"
  13457. { p--; {cs = stack[--top]; goto _again;} }
  13458. break;
  13459. #line 3111 "upb/json/parser.c"
  13460. }
  13461. }
  13462. _again:
  13463. if ( cs == 0 )
  13464. goto _out;
  13465. if ( ++p != pe )
  13466. goto _resume;
  13467. _test_eof: {}
  13468. if ( p == eof )
  13469. {
  13470. const char *__acts = _json_actions + _json_eof_actions[cs];
  13471. unsigned int __nacts = (unsigned int) *__acts++;
  13472. while ( __nacts-- > 0 ) {
  13473. switch ( *__acts++ ) {
  13474. case 0:
  13475. #line 2559 "upb/json/parser.rl"
  13476. { p--; {cs = stack[--top]; if ( p == pe )
  13477. goto _test_eof;
  13478. goto _again;} }
  13479. break;
  13480. case 35:
  13481. #line 2710 "upb/json/parser.rl"
  13482. { CHECK_RETURN_TOP(end_number(parser, p)); }
  13483. break;
  13484. case 38:
  13485. #line 2715 "upb/json/parser.rl"
  13486. { CHECK_RETURN_TOP(end_bool(parser, true)); }
  13487. break;
  13488. case 39:
  13489. #line 2717 "upb/json/parser.rl"
  13490. { CHECK_RETURN_TOP(end_bool(parser, false)); }
  13491. break;
  13492. case 40:
  13493. #line 2719 "upb/json/parser.rl"
  13494. { CHECK_RETURN_TOP(end_null(parser)); }
  13495. break;
  13496. case 42:
  13497. #line 2722 "upb/json/parser.rl"
  13498. { end_subobject_full(parser); }
  13499. break;
  13500. #line 3153 "upb/json/parser.c"
  13501. }
  13502. }
  13503. }
  13504. _out: {}
  13505. }
  13506. #line 2755 "upb/json/parser.rl"
  13507. if (p != pe) {
  13508. upb_status_seterrf(&parser->status, "Parse error at '%.*s'\n", pe - p, p);
  13509. upb_env_reporterror(parser->env, &parser->status);
  13510. } else {
  13511. capture_suspend(parser, &p);
  13512. }
  13513. error:
  13514. /* Save parsing state back to parser. */
  13515. parser->current_state = cs;
  13516. parser->parser_top = top;
  13517. return p - buf;
  13518. }
  13519. static bool end(void *closure, const void *hd) {
  13520. upb_json_parser *parser = closure;
  13521. /* Prevent compile warning on unused static constants. */
  13522. UPB_UNUSED(json_start);
  13523. UPB_UNUSED(json_en_duration_machine);
  13524. UPB_UNUSED(json_en_fieldmask_machine);
  13525. UPB_UNUSED(json_en_number_machine);
  13526. UPB_UNUSED(json_en_string_machine);
  13527. UPB_UNUSED(json_en_timestamp_machine);
  13528. UPB_UNUSED(json_en_value_machine);
  13529. UPB_UNUSED(json_en_main);
  13530. parse(parser, hd, &eof_ch, 0, NULL);
  13531. return parser->current_state >= 106;
  13532. }
  13533. static void json_parser_reset(upb_json_parser *p) {
  13534. int cs;
  13535. int top;
  13536. p->top = p->stack;
  13537. p->top->f = NULL;
  13538. p->top->is_map = false;
  13539. p->top->is_mapentry = false;
  13540. p->top->is_any = false;
  13541. p->top->any_frame = NULL;
  13542. p->top->is_unknown_field = false;
  13543. /* Emit Ragel initialization of the parser. */
  13544. #line 3210 "upb/json/parser.c"
  13545. {
  13546. cs = json_start;
  13547. top = 0;
  13548. }
  13549. #line 2803 "upb/json/parser.rl"
  13550. p->current_state = cs;
  13551. p->parser_top = top;
  13552. accumulate_clear(p);
  13553. p->multipart_state = MULTIPART_INACTIVE;
  13554. p->capture = NULL;
  13555. p->accumulated = NULL;
  13556. upb_status_clear(&p->status);
  13557. }
  13558. static void visit_json_parsermethod(const upb_refcounted *r,
  13559. upb_refcounted_visit *visit,
  13560. void *closure) {
  13561. const upb_json_parsermethod *method = (upb_json_parsermethod*)r;
  13562. visit(r, upb_msgdef_upcast2(method->msg), closure);
  13563. }
  13564. static void free_json_parsermethod(upb_refcounted *r) {
  13565. upb_json_parsermethod *method = (upb_json_parsermethod*)r;
  13566. upb_inttable_iter i;
  13567. upb_inttable_begin(&i, &method->name_tables);
  13568. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  13569. upb_value val = upb_inttable_iter_value(&i);
  13570. upb_strtable *t = upb_value_getptr(val);
  13571. upb_strtable_uninit(t);
  13572. upb_gfree(t);
  13573. }
  13574. upb_inttable_uninit(&method->name_tables);
  13575. upb_gfree(r);
  13576. }
  13577. static void add_jsonname_table(upb_json_parsermethod *m, const upb_msgdef* md) {
  13578. upb_msg_field_iter i;
  13579. upb_strtable *t;
  13580. /* It would be nice to stack-allocate this, but protobufs do not limit the
  13581. * length of fields to any reasonable limit. */
  13582. char *buf = NULL;
  13583. size_t len = 0;
  13584. if (upb_inttable_lookupptr(&m->name_tables, md, NULL)) {
  13585. return;
  13586. }
  13587. /* TODO(haberman): handle malloc failure. */
  13588. t = upb_gmalloc(sizeof(*t));
  13589. upb_strtable_init(t, UPB_CTYPE_CONSTPTR);
  13590. upb_inttable_insertptr(&m->name_tables, md, upb_value_ptr(t));
  13591. for(upb_msg_field_begin(&i, md);
  13592. !upb_msg_field_done(&i);
  13593. upb_msg_field_next(&i)) {
  13594. const upb_fielddef *f = upb_msg_iter_field(&i);
  13595. /* Add an entry for the JSON name. */
  13596. size_t field_len = upb_fielddef_getjsonname(f, buf, len);
  13597. if (field_len > len) {
  13598. size_t len2;
  13599. buf = upb_grealloc(buf, 0, field_len);
  13600. len = field_len;
  13601. len2 = upb_fielddef_getjsonname(f, buf, len);
  13602. UPB_ASSERT(len == len2);
  13603. }
  13604. upb_strtable_insert(t, buf, upb_value_constptr(f));
  13605. if (strcmp(buf, upb_fielddef_name(f)) != 0) {
  13606. /* Since the JSON name is different from the regular field name, add an
  13607. * entry for the raw name (compliant proto3 JSON parsers must accept
  13608. * both). */
  13609. upb_strtable_insert(t, upb_fielddef_name(f), upb_value_constptr(f));
  13610. }
  13611. if (upb_fielddef_issubmsg(f)) {
  13612. add_jsonname_table(m, upb_fielddef_msgsubdef(f));
  13613. }
  13614. }
  13615. upb_gfree(buf);
  13616. }
  13617. /* Public API *****************************************************************/
  13618. upb_json_parser *upb_json_parser_create(upb_env *env,
  13619. const upb_json_parsermethod *method,
  13620. const upb_symtab* symtab,
  13621. upb_sink *output,
  13622. bool ignore_json_unknown) {
  13623. #ifndef NDEBUG
  13624. const size_t size_before = upb_env_bytesallocated(env);
  13625. #endif
  13626. upb_json_parser *p = upb_env_malloc(env, sizeof(upb_json_parser));
  13627. if (!p) return false;
  13628. p->env = env;
  13629. p->method = method;
  13630. p->limit = p->stack + UPB_JSON_MAX_DEPTH;
  13631. p->accumulate_buf = NULL;
  13632. p->accumulate_buf_size = 0;
  13633. upb_bytessink_reset(&p->input_, &method->input_handler_, p);
  13634. json_parser_reset(p);
  13635. upb_sink_reset(&p->top->sink, output->handlers, output->closure);
  13636. p->top->m = upb_handlers_msgdef(output->handlers);
  13637. if (is_wellknown_msg(p, UPB_WELLKNOWN_ANY)) {
  13638. p->top->is_any = true;
  13639. p->top->any_frame =
  13640. upb_env_malloc(p->env, sizeof(upb_jsonparser_any_frame));
  13641. json_parser_any_frame_reset(p->top->any_frame);
  13642. } else {
  13643. p->top->is_any = false;
  13644. p->top->any_frame = NULL;
  13645. }
  13646. set_name_table(p, p->top);
  13647. p->symtab = symtab;
  13648. p->ignore_json_unknown = ignore_json_unknown;
  13649. /* If this fails, uncomment and increase the value in parser.h. */
  13650. /* fprintf(stderr, "%zd\n", upb_env_bytesallocated(env) - size_before); */
  13651. UPB_ASSERT_DEBUGVAR(upb_env_bytesallocated(env) - size_before <=
  13652. UPB_JSON_PARSER_SIZE);
  13653. return p;
  13654. }
  13655. upb_bytessink *upb_json_parser_input(upb_json_parser *p) {
  13656. return &p->input_;
  13657. }
  13658. upb_json_parsermethod *upb_json_parsermethod_new(const upb_msgdef* md,
  13659. const void* owner) {
  13660. static const struct upb_refcounted_vtbl vtbl = {visit_json_parsermethod,
  13661. free_json_parsermethod};
  13662. upb_json_parsermethod *ret = upb_gmalloc(sizeof(*ret));
  13663. upb_refcounted_init(upb_json_parsermethod_upcast_mutable(ret), &vtbl, owner);
  13664. ret->msg = md;
  13665. upb_ref2(md, ret);
  13666. upb_byteshandler_init(&ret->input_handler_);
  13667. upb_byteshandler_setstring(&ret->input_handler_, parse, ret);
  13668. upb_byteshandler_setendstr(&ret->input_handler_, end, ret);
  13669. upb_inttable_init(&ret->name_tables, UPB_CTYPE_PTR);
  13670. add_jsonname_table(ret, md);
  13671. return ret;
  13672. }
  13673. const upb_byteshandler *upb_json_parsermethod_inputhandler(
  13674. const upb_json_parsermethod *m) {
  13675. return &m->input_handler_;
  13676. }
  13677. /*
  13678. ** This currently uses snprintf() to format primitives, and could be optimized
  13679. ** further.
  13680. */
  13681. #include <string.h>
  13682. #include <stdint.h>
  13683. #include <time.h>
  13684. struct upb_json_printer {
  13685. upb_sink input_;
  13686. /* BytesSink closure. */
  13687. void *subc_;
  13688. upb_bytessink *output_;
  13689. /* We track the depth so that we know when to emit startstr/endstr on the
  13690. * output. */
  13691. int depth_;
  13692. /* Have we emitted the first element? This state is necessary to emit commas
  13693. * without leaving a trailing comma in arrays/maps. We keep this state per
  13694. * frame depth.
  13695. *
  13696. * Why max_depth * 2? UPB_MAX_HANDLER_DEPTH counts depth as nested messages.
  13697. * We count frames (contexts in which we separate elements by commas) as both
  13698. * repeated fields and messages (maps), and the worst case is a
  13699. * message->repeated field->submessage->repeated field->... nesting. */
  13700. bool first_elem_[UPB_MAX_HANDLER_DEPTH * 2];
  13701. /* To print timestamp, printer needs to cache its seconds and nanos values
  13702. * and convert them when ending timestamp message. See comments of
  13703. * printer_sethandlers_timestamp for more detail. */
  13704. int64_t seconds;
  13705. int32_t nanos;
  13706. };
  13707. /* StringPiece; a pointer plus a length. */
  13708. typedef struct {
  13709. char *ptr;
  13710. size_t len;
  13711. } strpc;
  13712. void freestrpc(void *ptr) {
  13713. strpc *pc = ptr;
  13714. upb_gfree(pc->ptr);
  13715. upb_gfree(pc);
  13716. }
  13717. /* Convert fielddef name to JSON name and return as a string piece. */
  13718. strpc *newstrpc(upb_handlers *h, const upb_fielddef *f,
  13719. bool preserve_fieldnames) {
  13720. /* TODO(haberman): handle malloc failure. */
  13721. strpc *ret = upb_gmalloc(sizeof(*ret));
  13722. if (preserve_fieldnames) {
  13723. ret->ptr = upb_gstrdup(upb_fielddef_name(f));
  13724. ret->len = strlen(ret->ptr);
  13725. } else {
  13726. size_t len;
  13727. ret->len = upb_fielddef_getjsonname(f, NULL, 0);
  13728. ret->ptr = upb_gmalloc(ret->len);
  13729. len = upb_fielddef_getjsonname(f, ret->ptr, ret->len);
  13730. UPB_ASSERT(len == ret->len);
  13731. ret->len--; /* NULL */
  13732. }
  13733. upb_handlers_addcleanup(h, ret, freestrpc);
  13734. return ret;
  13735. }
  13736. /* Convert a null-terminated const char* to a string piece. */
  13737. strpc *newstrpc_str(upb_handlers *h, const char * str) {
  13738. strpc * ret = upb_gmalloc(sizeof(*ret));
  13739. ret->ptr = upb_gstrdup(str);
  13740. ret->len = strlen(str);
  13741. upb_handlers_addcleanup(h, ret, freestrpc);
  13742. return ret;
  13743. }
  13744. /* ------------ JSON string printing: values, maps, arrays ------------------ */
  13745. static void print_data(
  13746. upb_json_printer *p, const char *buf, unsigned int len) {
  13747. /* TODO: Will need to change if we support pushback from the sink. */
  13748. size_t n = upb_bytessink_putbuf(p->output_, p->subc_, buf, len, NULL);
  13749. UPB_ASSERT(n == len);
  13750. }
  13751. static void print_comma(upb_json_printer *p) {
  13752. if (!p->first_elem_[p->depth_]) {
  13753. print_data(p, ",", 1);
  13754. }
  13755. p->first_elem_[p->depth_] = false;
  13756. }
  13757. /* Helpers that print properly formatted elements to the JSON output stream. */
  13758. /* Used for escaping control chars in strings. */
  13759. static const char kControlCharLimit = 0x20;
  13760. UPB_INLINE bool is_json_escaped(char c) {
  13761. /* See RFC 4627. */
  13762. unsigned char uc = (unsigned char)c;
  13763. return uc < kControlCharLimit || uc == '"' || uc == '\\';
  13764. }
  13765. UPB_INLINE const char* json_nice_escape(char c) {
  13766. switch (c) {
  13767. case '"': return "\\\"";
  13768. case '\\': return "\\\\";
  13769. case '\b': return "\\b";
  13770. case '\f': return "\\f";
  13771. case '\n': return "\\n";
  13772. case '\r': return "\\r";
  13773. case '\t': return "\\t";
  13774. default: return NULL;
  13775. }
  13776. }
  13777. /* Write a properly escaped string chunk. The surrounding quotes are *not*
  13778. * printed; this is so that the caller has the option of emitting the string
  13779. * content in chunks. */
  13780. static void putstring(upb_json_printer *p, const char *buf, unsigned int len) {
  13781. const char* unescaped_run = NULL;
  13782. unsigned int i;
  13783. for (i = 0; i < len; i++) {
  13784. char c = buf[i];
  13785. /* Handle escaping. */
  13786. if (is_json_escaped(c)) {
  13787. /* Use a "nice" escape, like \n, if one exists for this character. */
  13788. const char* escape = json_nice_escape(c);
  13789. /* If we don't have a specific 'nice' escape code, use a \uXXXX-style
  13790. * escape. */
  13791. char escape_buf[8];
  13792. if (!escape) {
  13793. unsigned char byte = (unsigned char)c;
  13794. _upb_snprintf(escape_buf, sizeof(escape_buf), "\\u%04x", (int)byte);
  13795. escape = escape_buf;
  13796. }
  13797. /* N.B. that we assume that the input encoding is equal to the output
  13798. * encoding (both UTF-8 for now), so for chars >= 0x20 and != \, ", we
  13799. * can simply pass the bytes through. */
  13800. /* If there's a current run of unescaped chars, print that run first. */
  13801. if (unescaped_run) {
  13802. print_data(p, unescaped_run, &buf[i] - unescaped_run);
  13803. unescaped_run = NULL;
  13804. }
  13805. /* Then print the escape code. */
  13806. print_data(p, escape, strlen(escape));
  13807. } else {
  13808. /* Add to the current unescaped run of characters. */
  13809. if (unescaped_run == NULL) {
  13810. unescaped_run = &buf[i];
  13811. }
  13812. }
  13813. }
  13814. /* If the string ended in a run of unescaped characters, print that last run. */
  13815. if (unescaped_run) {
  13816. print_data(p, unescaped_run, &buf[len] - unescaped_run);
  13817. }
  13818. }
  13819. #define CHKLENGTH(x) if (!(x)) return -1;
  13820. /* Helpers that format floating point values according to our custom formats.
  13821. * Right now we use %.8g and %.17g for float/double, respectively, to match
  13822. * proto2::util::JsonFormat's defaults. May want to change this later. */
  13823. const char neginf[] = "\"-Infinity\"";
  13824. const char inf[] = "\"Infinity\"";
  13825. static size_t fmt_double(double val, char* buf, size_t length) {
  13826. if (val == (1.0 / 0.0)) {
  13827. CHKLENGTH(length >= strlen(inf));
  13828. strcpy(buf, inf);
  13829. return strlen(inf);
  13830. } else if (val == (-1.0 / 0.0)) {
  13831. CHKLENGTH(length >= strlen(neginf));
  13832. strcpy(buf, neginf);
  13833. return strlen(neginf);
  13834. } else {
  13835. size_t n = _upb_snprintf(buf, length, "%.17g", val);
  13836. CHKLENGTH(n > 0 && n < length);
  13837. return n;
  13838. }
  13839. }
  13840. static size_t fmt_float(float val, char* buf, size_t length) {
  13841. size_t n = _upb_snprintf(buf, length, "%.8g", val);
  13842. CHKLENGTH(n > 0 && n < length);
  13843. return n;
  13844. }
  13845. static size_t fmt_bool(bool val, char* buf, size_t length) {
  13846. size_t n = _upb_snprintf(buf, length, "%s", (val ? "true" : "false"));
  13847. CHKLENGTH(n > 0 && n < length);
  13848. return n;
  13849. }
  13850. static size_t fmt_int64(long val, char* buf, size_t length) {
  13851. size_t n = _upb_snprintf(buf, length, "%ld", val);
  13852. CHKLENGTH(n > 0 && n < length);
  13853. return n;
  13854. }
  13855. static size_t fmt_uint64(unsigned long long val, char* buf, size_t length) {
  13856. size_t n = _upb_snprintf(buf, length, "%llu", val);
  13857. CHKLENGTH(n > 0 && n < length);
  13858. return n;
  13859. }
  13860. /* Print a map key given a field name. Called by scalar field handlers and by
  13861. * startseq for repeated fields. */
  13862. static bool putkey(void *closure, const void *handler_data) {
  13863. upb_json_printer *p = closure;
  13864. const strpc *key = handler_data;
  13865. print_comma(p);
  13866. print_data(p, "\"", 1);
  13867. putstring(p, key->ptr, key->len);
  13868. print_data(p, "\":", 2);
  13869. return true;
  13870. }
  13871. #define CHKFMT(val) if ((val) == (size_t)-1) return false;
  13872. #define CHK(val) if (!(val)) return false;
  13873. #define TYPE_HANDLERS(type, fmt_func) \
  13874. static bool put##type(void *closure, const void *handler_data, type val) { \
  13875. upb_json_printer *p = closure; \
  13876. char data[64]; \
  13877. size_t length = fmt_func(val, data, sizeof(data)); \
  13878. UPB_UNUSED(handler_data); \
  13879. CHKFMT(length); \
  13880. print_data(p, data, length); \
  13881. return true; \
  13882. } \
  13883. static bool scalar_##type(void *closure, const void *handler_data, \
  13884. type val) { \
  13885. CHK(putkey(closure, handler_data)); \
  13886. CHK(put##type(closure, handler_data, val)); \
  13887. return true; \
  13888. } \
  13889. static bool repeated_##type(void *closure, const void *handler_data, \
  13890. type val) { \
  13891. upb_json_printer *p = closure; \
  13892. print_comma(p); \
  13893. CHK(put##type(closure, handler_data, val)); \
  13894. return true; \
  13895. }
  13896. #define TYPE_HANDLERS_MAPKEY(type, fmt_func) \
  13897. static bool putmapkey_##type(void *closure, const void *handler_data, \
  13898. type val) { \
  13899. upb_json_printer *p = closure; \
  13900. print_data(p, "\"", 1); \
  13901. CHK(put##type(closure, handler_data, val)); \
  13902. print_data(p, "\":", 2); \
  13903. return true; \
  13904. }
  13905. TYPE_HANDLERS(double, fmt_double)
  13906. TYPE_HANDLERS(float, fmt_float)
  13907. TYPE_HANDLERS(bool, fmt_bool)
  13908. TYPE_HANDLERS(int32_t, fmt_int64)
  13909. TYPE_HANDLERS(uint32_t, fmt_int64)
  13910. TYPE_HANDLERS(int64_t, fmt_int64)
  13911. TYPE_HANDLERS(uint64_t, fmt_uint64)
  13912. /* double and float are not allowed to be map keys. */
  13913. TYPE_HANDLERS_MAPKEY(bool, fmt_bool)
  13914. TYPE_HANDLERS_MAPKEY(int32_t, fmt_int64)
  13915. TYPE_HANDLERS_MAPKEY(uint32_t, fmt_int64)
  13916. TYPE_HANDLERS_MAPKEY(int64_t, fmt_int64)
  13917. TYPE_HANDLERS_MAPKEY(uint64_t, fmt_uint64)
  13918. #undef TYPE_HANDLERS
  13919. #undef TYPE_HANDLERS_MAPKEY
  13920. typedef struct {
  13921. void *keyname;
  13922. const upb_enumdef *enumdef;
  13923. } EnumHandlerData;
  13924. static bool scalar_enum(void *closure, const void *handler_data,
  13925. int32_t val) {
  13926. const EnumHandlerData *hd = handler_data;
  13927. upb_json_printer *p = closure;
  13928. const char *symbolic_name;
  13929. CHK(putkey(closure, hd->keyname));
  13930. symbolic_name = upb_enumdef_iton(hd->enumdef, val);
  13931. if (symbolic_name) {
  13932. print_data(p, "\"", 1);
  13933. putstring(p, symbolic_name, strlen(symbolic_name));
  13934. print_data(p, "\"", 1);
  13935. } else {
  13936. putint32_t(closure, NULL, val);
  13937. }
  13938. return true;
  13939. }
  13940. static void print_enum_symbolic_name(upb_json_printer *p,
  13941. const upb_enumdef *def,
  13942. int32_t val) {
  13943. const char *symbolic_name = upb_enumdef_iton(def, val);
  13944. if (symbolic_name) {
  13945. print_data(p, "\"", 1);
  13946. putstring(p, symbolic_name, strlen(symbolic_name));
  13947. print_data(p, "\"", 1);
  13948. } else {
  13949. putint32_t(p, NULL, val);
  13950. }
  13951. }
  13952. static bool repeated_enum(void *closure, const void *handler_data,
  13953. int32_t val) {
  13954. const EnumHandlerData *hd = handler_data;
  13955. upb_json_printer *p = closure;
  13956. print_comma(p);
  13957. print_enum_symbolic_name(p, hd->enumdef, val);
  13958. return true;
  13959. }
  13960. static bool mapvalue_enum(void *closure, const void *handler_data,
  13961. int32_t val) {
  13962. const EnumHandlerData *hd = handler_data;
  13963. upb_json_printer *p = closure;
  13964. print_enum_symbolic_name(p, hd->enumdef, val);
  13965. return true;
  13966. }
  13967. static void *scalar_startsubmsg(void *closure, const void *handler_data) {
  13968. return putkey(closure, handler_data) ? closure : UPB_BREAK;
  13969. }
  13970. static void *repeated_startsubmsg(void *closure, const void *handler_data) {
  13971. upb_json_printer *p = closure;
  13972. UPB_UNUSED(handler_data);
  13973. print_comma(p);
  13974. return closure;
  13975. }
  13976. static void start_frame(upb_json_printer *p) {
  13977. p->depth_++;
  13978. p->first_elem_[p->depth_] = true;
  13979. print_data(p, "{", 1);
  13980. }
  13981. static void end_frame(upb_json_printer *p) {
  13982. print_data(p, "}", 1);
  13983. p->depth_--;
  13984. }
  13985. static bool printer_startmsg(void *closure, const void *handler_data) {
  13986. upb_json_printer *p = closure;
  13987. UPB_UNUSED(handler_data);
  13988. if (p->depth_ == 0) {
  13989. upb_bytessink_start(p->output_, 0, &p->subc_);
  13990. }
  13991. start_frame(p);
  13992. return true;
  13993. }
  13994. static bool printer_endmsg(void *closure, const void *handler_data, upb_status *s) {
  13995. upb_json_printer *p = closure;
  13996. UPB_UNUSED(handler_data);
  13997. UPB_UNUSED(s);
  13998. end_frame(p);
  13999. if (p->depth_ == 0) {
  14000. upb_bytessink_end(p->output_);
  14001. }
  14002. return true;
  14003. }
  14004. static void *startseq(void *closure, const void *handler_data) {
  14005. upb_json_printer *p = closure;
  14006. CHK(putkey(closure, handler_data));
  14007. p->depth_++;
  14008. p->first_elem_[p->depth_] = true;
  14009. print_data(p, "[", 1);
  14010. return closure;
  14011. }
  14012. static bool endseq(void *closure, const void *handler_data) {
  14013. upb_json_printer *p = closure;
  14014. UPB_UNUSED(handler_data);
  14015. print_data(p, "]", 1);
  14016. p->depth_--;
  14017. return true;
  14018. }
  14019. static void *startmap(void *closure, const void *handler_data) {
  14020. upb_json_printer *p = closure;
  14021. CHK(putkey(closure, handler_data));
  14022. p->depth_++;
  14023. p->first_elem_[p->depth_] = true;
  14024. print_data(p, "{", 1);
  14025. return closure;
  14026. }
  14027. static bool endmap(void *closure, const void *handler_data) {
  14028. upb_json_printer *p = closure;
  14029. UPB_UNUSED(handler_data);
  14030. print_data(p, "}", 1);
  14031. p->depth_--;
  14032. return true;
  14033. }
  14034. static size_t putstr(void *closure, const void *handler_data, const char *str,
  14035. size_t len, const upb_bufhandle *handle) {
  14036. upb_json_printer *p = closure;
  14037. UPB_UNUSED(handler_data);
  14038. UPB_UNUSED(handle);
  14039. putstring(p, str, len);
  14040. return len;
  14041. }
  14042. /* This has to Base64 encode the bytes, because JSON has no "bytes" type. */
  14043. static size_t putbytes(void *closure, const void *handler_data, const char *str,
  14044. size_t len, const upb_bufhandle *handle) {
  14045. upb_json_printer *p = closure;
  14046. /* This is the regular base64, not the "web-safe" version. */
  14047. static const char base64[] =
  14048. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  14049. /* Base64-encode. */
  14050. char data[16000];
  14051. const char *limit = data + sizeof(data);
  14052. const unsigned char *from = (const unsigned char*)str;
  14053. char *to = data;
  14054. size_t remaining = len;
  14055. size_t bytes;
  14056. UPB_UNUSED(handler_data);
  14057. UPB_UNUSED(handle);
  14058. while (remaining > 2) {
  14059. /* TODO(haberman): handle encoded lengths > sizeof(data) */
  14060. UPB_ASSERT((limit - to) >= 4);
  14061. to[0] = base64[from[0] >> 2];
  14062. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  14063. to[2] = base64[((from[1] & 0xf) << 2) | (from[2] >> 6)];
  14064. to[3] = base64[from[2] & 0x3f];
  14065. remaining -= 3;
  14066. to += 4;
  14067. from += 3;
  14068. }
  14069. switch (remaining) {
  14070. case 2:
  14071. to[0] = base64[from[0] >> 2];
  14072. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  14073. to[2] = base64[(from[1] & 0xf) << 2];
  14074. to[3] = '=';
  14075. to += 4;
  14076. from += 2;
  14077. break;
  14078. case 1:
  14079. to[0] = base64[from[0] >> 2];
  14080. to[1] = base64[((from[0] & 0x3) << 4)];
  14081. to[2] = '=';
  14082. to[3] = '=';
  14083. to += 4;
  14084. from += 1;
  14085. break;
  14086. }
  14087. bytes = to - data;
  14088. print_data(p, "\"", 1);
  14089. putstring(p, data, bytes);
  14090. print_data(p, "\"", 1);
  14091. return len;
  14092. }
  14093. static void *scalar_startstr(void *closure, const void *handler_data,
  14094. size_t size_hint) {
  14095. upb_json_printer *p = closure;
  14096. UPB_UNUSED(handler_data);
  14097. UPB_UNUSED(size_hint);
  14098. CHK(putkey(closure, handler_data));
  14099. print_data(p, "\"", 1);
  14100. return p;
  14101. }
  14102. static size_t scalar_str(void *closure, const void *handler_data,
  14103. const char *str, size_t len,
  14104. const upb_bufhandle *handle) {
  14105. CHK(putstr(closure, handler_data, str, len, handle));
  14106. return len;
  14107. }
  14108. static bool scalar_endstr(void *closure, const void *handler_data) {
  14109. upb_json_printer *p = closure;
  14110. UPB_UNUSED(handler_data);
  14111. print_data(p, "\"", 1);
  14112. return true;
  14113. }
  14114. static void *repeated_startstr(void *closure, const void *handler_data,
  14115. size_t size_hint) {
  14116. upb_json_printer *p = closure;
  14117. UPB_UNUSED(handler_data);
  14118. UPB_UNUSED(size_hint);
  14119. print_comma(p);
  14120. print_data(p, "\"", 1);
  14121. return p;
  14122. }
  14123. static size_t repeated_str(void *closure, const void *handler_data,
  14124. const char *str, size_t len,
  14125. const upb_bufhandle *handle) {
  14126. CHK(putstr(closure, handler_data, str, len, handle));
  14127. return len;
  14128. }
  14129. static bool repeated_endstr(void *closure, const void *handler_data) {
  14130. upb_json_printer *p = closure;
  14131. UPB_UNUSED(handler_data);
  14132. print_data(p, "\"", 1);
  14133. return true;
  14134. }
  14135. static void *mapkeyval_startstr(void *closure, const void *handler_data,
  14136. size_t size_hint) {
  14137. upb_json_printer *p = closure;
  14138. UPB_UNUSED(handler_data);
  14139. UPB_UNUSED(size_hint);
  14140. print_data(p, "\"", 1);
  14141. return p;
  14142. }
  14143. static size_t mapkey_str(void *closure, const void *handler_data,
  14144. const char *str, size_t len,
  14145. const upb_bufhandle *handle) {
  14146. CHK(putstr(closure, handler_data, str, len, handle));
  14147. return len;
  14148. }
  14149. static bool mapkey_endstr(void *closure, const void *handler_data) {
  14150. upb_json_printer *p = closure;
  14151. UPB_UNUSED(handler_data);
  14152. print_data(p, "\":", 2);
  14153. return true;
  14154. }
  14155. static bool mapvalue_endstr(void *closure, const void *handler_data) {
  14156. upb_json_printer *p = closure;
  14157. UPB_UNUSED(handler_data);
  14158. print_data(p, "\"", 1);
  14159. return true;
  14160. }
  14161. static size_t scalar_bytes(void *closure, const void *handler_data,
  14162. const char *str, size_t len,
  14163. const upb_bufhandle *handle) {
  14164. CHK(putkey(closure, handler_data));
  14165. CHK(putbytes(closure, handler_data, str, len, handle));
  14166. return len;
  14167. }
  14168. static size_t repeated_bytes(void *closure, const void *handler_data,
  14169. const char *str, size_t len,
  14170. const upb_bufhandle *handle) {
  14171. upb_json_printer *p = closure;
  14172. print_comma(p);
  14173. CHK(putbytes(closure, handler_data, str, len, handle));
  14174. return len;
  14175. }
  14176. static size_t mapkey_bytes(void *closure, const void *handler_data,
  14177. const char *str, size_t len,
  14178. const upb_bufhandle *handle) {
  14179. upb_json_printer *p = closure;
  14180. CHK(putbytes(closure, handler_data, str, len, handle));
  14181. print_data(p, ":", 1);
  14182. return len;
  14183. }
  14184. static void set_enum_hd(upb_handlers *h,
  14185. const upb_fielddef *f,
  14186. bool preserve_fieldnames,
  14187. upb_handlerattr *attr) {
  14188. EnumHandlerData *hd = upb_gmalloc(sizeof(EnumHandlerData));
  14189. hd->enumdef = (const upb_enumdef *)upb_fielddef_subdef(f);
  14190. hd->keyname = newstrpc(h, f, preserve_fieldnames);
  14191. upb_handlers_addcleanup(h, hd, upb_gfree);
  14192. upb_handlerattr_sethandlerdata(attr, hd);
  14193. }
  14194. /* Set up handlers for a mapentry submessage (i.e., an individual key/value pair
  14195. * in a map).
  14196. *
  14197. * TODO: Handle missing key, missing value, out-of-order key/value, or repeated
  14198. * key or value cases properly. The right way to do this is to allocate a
  14199. * temporary structure at the start of a mapentry submessage, store key and
  14200. * value data in it as key and value handlers are called, and then print the
  14201. * key/value pair once at the end of the submessage. If we don't do this, we
  14202. * should at least detect the case and throw an error. However, so far all of
  14203. * our sources that emit mapentry messages do so canonically (with one key
  14204. * field, and then one value field), so this is not a pressing concern at the
  14205. * moment. */
  14206. void printer_sethandlers_mapentry(const void *closure, bool preserve_fieldnames,
  14207. upb_handlers *h) {
  14208. const upb_msgdef *md = upb_handlers_msgdef(h);
  14209. /* A mapentry message is printed simply as '"key": value'. Rather than
  14210. * special-case key and value for every type below, we just handle both
  14211. * fields explicitly here. */
  14212. const upb_fielddef* key_field = upb_msgdef_itof(md, UPB_MAPENTRY_KEY);
  14213. const upb_fielddef* value_field = upb_msgdef_itof(md, UPB_MAPENTRY_VALUE);
  14214. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  14215. UPB_UNUSED(closure);
  14216. switch (upb_fielddef_type(key_field)) {
  14217. case UPB_TYPE_INT32:
  14218. upb_handlers_setint32(h, key_field, putmapkey_int32_t, &empty_attr);
  14219. break;
  14220. case UPB_TYPE_INT64:
  14221. upb_handlers_setint64(h, key_field, putmapkey_int64_t, &empty_attr);
  14222. break;
  14223. case UPB_TYPE_UINT32:
  14224. upb_handlers_setuint32(h, key_field, putmapkey_uint32_t, &empty_attr);
  14225. break;
  14226. case UPB_TYPE_UINT64:
  14227. upb_handlers_setuint64(h, key_field, putmapkey_uint64_t, &empty_attr);
  14228. break;
  14229. case UPB_TYPE_BOOL:
  14230. upb_handlers_setbool(h, key_field, putmapkey_bool, &empty_attr);
  14231. break;
  14232. case UPB_TYPE_STRING:
  14233. upb_handlers_setstartstr(h, key_field, mapkeyval_startstr, &empty_attr);
  14234. upb_handlers_setstring(h, key_field, mapkey_str, &empty_attr);
  14235. upb_handlers_setendstr(h, key_field, mapkey_endstr, &empty_attr);
  14236. break;
  14237. case UPB_TYPE_BYTES:
  14238. upb_handlers_setstring(h, key_field, mapkey_bytes, &empty_attr);
  14239. break;
  14240. default:
  14241. UPB_ASSERT(false);
  14242. break;
  14243. }
  14244. switch (upb_fielddef_type(value_field)) {
  14245. case UPB_TYPE_INT32:
  14246. upb_handlers_setint32(h, value_field, putint32_t, &empty_attr);
  14247. break;
  14248. case UPB_TYPE_INT64:
  14249. upb_handlers_setint64(h, value_field, putint64_t, &empty_attr);
  14250. break;
  14251. case UPB_TYPE_UINT32:
  14252. upb_handlers_setuint32(h, value_field, putuint32_t, &empty_attr);
  14253. break;
  14254. case UPB_TYPE_UINT64:
  14255. upb_handlers_setuint64(h, value_field, putuint64_t, &empty_attr);
  14256. break;
  14257. case UPB_TYPE_BOOL:
  14258. upb_handlers_setbool(h, value_field, putbool, &empty_attr);
  14259. break;
  14260. case UPB_TYPE_FLOAT:
  14261. upb_handlers_setfloat(h, value_field, putfloat, &empty_attr);
  14262. break;
  14263. case UPB_TYPE_DOUBLE:
  14264. upb_handlers_setdouble(h, value_field, putdouble, &empty_attr);
  14265. break;
  14266. case UPB_TYPE_STRING:
  14267. upb_handlers_setstartstr(h, value_field, mapkeyval_startstr, &empty_attr);
  14268. upb_handlers_setstring(h, value_field, putstr, &empty_attr);
  14269. upb_handlers_setendstr(h, value_field, mapvalue_endstr, &empty_attr);
  14270. break;
  14271. case UPB_TYPE_BYTES:
  14272. upb_handlers_setstring(h, value_field, putbytes, &empty_attr);
  14273. break;
  14274. case UPB_TYPE_ENUM: {
  14275. upb_handlerattr enum_attr = UPB_HANDLERATTR_INITIALIZER;
  14276. set_enum_hd(h, value_field, preserve_fieldnames, &enum_attr);
  14277. upb_handlers_setint32(h, value_field, mapvalue_enum, &enum_attr);
  14278. upb_handlerattr_uninit(&enum_attr);
  14279. break;
  14280. }
  14281. case UPB_TYPE_MESSAGE:
  14282. /* No handler necessary -- the submsg handlers will print the message
  14283. * as appropriate. */
  14284. break;
  14285. }
  14286. upb_handlerattr_uninit(&empty_attr);
  14287. }
  14288. static bool putseconds(void *closure, const void *handler_data,
  14289. int64_t seconds) {
  14290. upb_json_printer *p = closure;
  14291. p->seconds = seconds;
  14292. UPB_UNUSED(handler_data);
  14293. return true;
  14294. }
  14295. static bool putnanos(void *closure, const void *handler_data,
  14296. int32_t nanos) {
  14297. upb_json_printer *p = closure;
  14298. p->nanos = nanos;
  14299. UPB_UNUSED(handler_data);
  14300. return true;
  14301. }
  14302. static void *scalar_startstr_nokey(void *closure, const void *handler_data,
  14303. size_t size_hint) {
  14304. upb_json_printer *p = closure;
  14305. UPB_UNUSED(handler_data);
  14306. UPB_UNUSED(size_hint);
  14307. print_data(p, "\"", 1);
  14308. return p;
  14309. }
  14310. static size_t putstr_nokey(void *closure, const void *handler_data,
  14311. const char *str, size_t len,
  14312. const upb_bufhandle *handle) {
  14313. upb_json_printer *p = closure;
  14314. UPB_UNUSED(handler_data);
  14315. UPB_UNUSED(handle);
  14316. print_data(p, "\"", 1);
  14317. putstring(p, str, len);
  14318. print_data(p, "\"", 1);
  14319. return len + 2;
  14320. }
  14321. static void *startseq_nokey(void *closure, const void *handler_data) {
  14322. upb_json_printer *p = closure;
  14323. UPB_UNUSED(handler_data);
  14324. p->depth_++;
  14325. p->first_elem_[p->depth_] = true;
  14326. print_data(p, "[", 1);
  14327. return closure;
  14328. }
  14329. static void *startseq_fieldmask(void *closure, const void *handler_data) {
  14330. upb_json_printer *p = closure;
  14331. UPB_UNUSED(handler_data);
  14332. p->depth_++;
  14333. p->first_elem_[p->depth_] = true;
  14334. print_data(p, "\"", 1);
  14335. return closure;
  14336. }
  14337. static bool endseq_fieldmask(void *closure, const void *handler_data) {
  14338. upb_json_printer *p = closure;
  14339. UPB_UNUSED(handler_data);
  14340. p->depth_--;
  14341. print_data(p, "\"", 1);
  14342. return true;
  14343. }
  14344. static void *repeated_startstr_fieldmask(
  14345. void *closure, const void *handler_data,
  14346. size_t size_hint) {
  14347. upb_json_printer *p = closure;
  14348. UPB_UNUSED(handler_data);
  14349. UPB_UNUSED(size_hint);
  14350. print_comma(p);
  14351. return p;
  14352. }
  14353. static size_t repeated_str_fieldmask(
  14354. void *closure, const void *handler_data,
  14355. const char *str, size_t len,
  14356. const upb_bufhandle *handle) {
  14357. const char* limit = str + len;
  14358. bool upper = false;
  14359. size_t result_len = 0;
  14360. for (; str < limit; str++) {
  14361. if (*str == '_') {
  14362. upper = true;
  14363. continue;
  14364. }
  14365. if (upper && *str >= 'a' && *str <= 'z') {
  14366. char upper_char = toupper(*str);
  14367. CHK(putstr(closure, handler_data, &upper_char, 1, handle));
  14368. } else {
  14369. CHK(putstr(closure, handler_data, str, 1, handle));
  14370. }
  14371. upper = false;
  14372. result_len++;
  14373. }
  14374. return result_len;
  14375. }
  14376. static void *startmap_nokey(void *closure, const void *handler_data) {
  14377. upb_json_printer *p = closure;
  14378. UPB_UNUSED(handler_data);
  14379. p->depth_++;
  14380. p->first_elem_[p->depth_] = true;
  14381. print_data(p, "{", 1);
  14382. return closure;
  14383. }
  14384. static bool putnull(void *closure, const void *handler_data,
  14385. int32_t null) {
  14386. upb_json_printer *p = closure;
  14387. print_data(p, "null", 4);
  14388. UPB_UNUSED(handler_data);
  14389. UPB_UNUSED(null);
  14390. return true;
  14391. }
  14392. static bool printer_startdurationmsg(void *closure, const void *handler_data) {
  14393. upb_json_printer *p = closure;
  14394. UPB_UNUSED(handler_data);
  14395. if (p->depth_ == 0) {
  14396. upb_bytessink_start(p->output_, 0, &p->subc_);
  14397. }
  14398. return true;
  14399. }
  14400. #define UPB_DURATION_MAX_JSON_LEN 23
  14401. #define UPB_DURATION_MAX_NANO_LEN 9
  14402. static bool printer_enddurationmsg(void *closure, const void *handler_data,
  14403. upb_status *s) {
  14404. upb_json_printer *p = closure;
  14405. char buffer[UPB_DURATION_MAX_JSON_LEN];
  14406. size_t base_len;
  14407. size_t curr;
  14408. size_t i;
  14409. memset(buffer, 0, UPB_DURATION_MAX_JSON_LEN);
  14410. if (p->seconds < -315576000000) {
  14411. upb_status_seterrf(s, "error parsing duration: "
  14412. "minimum acceptable value is "
  14413. "-315576000000");
  14414. return false;
  14415. }
  14416. if (p->seconds > 315576000000) {
  14417. upb_status_seterrf(s, "error serializing duration: "
  14418. "maximum acceptable value is "
  14419. "315576000000");
  14420. return false;
  14421. }
  14422. _upb_snprintf(buffer, sizeof(buffer), "%ld", (long)p->seconds);
  14423. base_len = strlen(buffer);
  14424. if (p->nanos != 0) {
  14425. char nanos_buffer[UPB_DURATION_MAX_NANO_LEN + 3];
  14426. _upb_snprintf(nanos_buffer, sizeof(nanos_buffer), "%.9f",
  14427. p->nanos / 1000000000.0);
  14428. /* Remove trailing 0. */
  14429. for (i = UPB_DURATION_MAX_NANO_LEN + 2;
  14430. nanos_buffer[i] == '0'; i--) {
  14431. nanos_buffer[i] = 0;
  14432. }
  14433. strcpy(buffer + base_len, nanos_buffer + 1);
  14434. }
  14435. curr = strlen(buffer);
  14436. strcpy(buffer + curr, "s");
  14437. p->seconds = 0;
  14438. p->nanos = 0;
  14439. print_data(p, "\"", 1);
  14440. print_data(p, buffer, strlen(buffer));
  14441. print_data(p, "\"", 1);
  14442. if (p->depth_ == 0) {
  14443. upb_bytessink_end(p->output_);
  14444. }
  14445. UPB_UNUSED(handler_data);
  14446. return true;
  14447. }
  14448. static bool printer_starttimestampmsg(void *closure, const void *handler_data) {
  14449. upb_json_printer *p = closure;
  14450. UPB_UNUSED(handler_data);
  14451. if (p->depth_ == 0) {
  14452. upb_bytessink_start(p->output_, 0, &p->subc_);
  14453. }
  14454. return true;
  14455. }
  14456. #define UPB_TIMESTAMP_MAX_JSON_LEN 31
  14457. #define UPB_TIMESTAMP_BEFORE_NANO_LEN 19
  14458. #define UPB_TIMESTAMP_MAX_NANO_LEN 9
  14459. static bool printer_endtimestampmsg(void *closure, const void *handler_data,
  14460. upb_status *s) {
  14461. upb_json_printer *p = closure;
  14462. char buffer[UPB_TIMESTAMP_MAX_JSON_LEN];
  14463. time_t time = p->seconds;
  14464. size_t curr;
  14465. size_t i;
  14466. size_t year_length =
  14467. strftime(buffer, UPB_TIMESTAMP_MAX_JSON_LEN, "%Y", gmtime(&time));
  14468. if (p->seconds < -62135596800) {
  14469. upb_status_seterrf(s, "error parsing timestamp: "
  14470. "minimum acceptable value is "
  14471. "0001-01-01T00:00:00Z");
  14472. return false;
  14473. }
  14474. if (p->seconds > 253402300799) {
  14475. upb_status_seterrf(s, "error parsing timestamp: "
  14476. "maximum acceptable value is "
  14477. "9999-12-31T23:59:59Z");
  14478. return false;
  14479. }
  14480. /* strftime doesn't guarantee 4 digits for year. Prepend 0 by ourselves. */
  14481. for (i = 0; i < 4 - year_length; i++) {
  14482. buffer[i] = '0';
  14483. }
  14484. strftime(buffer + (4 - year_length), UPB_TIMESTAMP_MAX_JSON_LEN,
  14485. "%Y-%m-%dT%H:%M:%S", gmtime(&time));
  14486. if (p->nanos != 0) {
  14487. char nanos_buffer[UPB_TIMESTAMP_MAX_NANO_LEN + 3];
  14488. _upb_snprintf(nanos_buffer, sizeof(nanos_buffer), "%.9f",
  14489. p->nanos / 1000000000.0);
  14490. /* Remove trailing 0. */
  14491. for (i = UPB_TIMESTAMP_MAX_NANO_LEN + 2;
  14492. nanos_buffer[i] == '0'; i--) {
  14493. nanos_buffer[i] = 0;
  14494. }
  14495. strcpy(buffer + UPB_TIMESTAMP_BEFORE_NANO_LEN, nanos_buffer + 1);
  14496. }
  14497. curr = strlen(buffer);
  14498. strcpy(buffer + curr, "Z");
  14499. p->seconds = 0;
  14500. p->nanos = 0;
  14501. print_data(p, "\"", 1);
  14502. print_data(p, buffer, strlen(buffer));
  14503. print_data(p, "\"", 1);
  14504. if (p->depth_ == 0) {
  14505. upb_bytessink_end(p->output_);
  14506. }
  14507. UPB_UNUSED(handler_data);
  14508. UPB_UNUSED(s);
  14509. return true;
  14510. }
  14511. static bool printer_startmsg_noframe(void *closure, const void *handler_data) {
  14512. upb_json_printer *p = closure;
  14513. UPB_UNUSED(handler_data);
  14514. if (p->depth_ == 0) {
  14515. upb_bytessink_start(p->output_, 0, &p->subc_);
  14516. }
  14517. return true;
  14518. }
  14519. static bool printer_endmsg_noframe(
  14520. void *closure, const void *handler_data, upb_status *s) {
  14521. upb_json_printer *p = closure;
  14522. UPB_UNUSED(handler_data);
  14523. UPB_UNUSED(s);
  14524. if (p->depth_ == 0) {
  14525. upb_bytessink_end(p->output_);
  14526. }
  14527. return true;
  14528. }
  14529. static void *scalar_startstr_onlykey(
  14530. void *closure, const void *handler_data, size_t size_hint) {
  14531. upb_json_printer *p = closure;
  14532. UPB_UNUSED(size_hint);
  14533. CHK(putkey(closure, handler_data));
  14534. return p;
  14535. }
  14536. /* Set up handlers for an Any submessage. */
  14537. void printer_sethandlers_any(const void *closure, upb_handlers *h) {
  14538. const upb_msgdef *md = upb_handlers_msgdef(h);
  14539. const upb_fielddef* type_field = upb_msgdef_itof(md, UPB_ANY_TYPE);
  14540. const upb_fielddef* value_field = upb_msgdef_itof(md, UPB_ANY_VALUE);
  14541. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  14542. /* type_url's json name is "@type" */
  14543. upb_handlerattr type_name_attr = UPB_HANDLERATTR_INITIALIZER;
  14544. upb_handlerattr value_name_attr = UPB_HANDLERATTR_INITIALIZER;
  14545. strpc *type_url_json_name = newstrpc_str(h, "@type");
  14546. strpc *value_json_name = newstrpc_str(h, "value");
  14547. upb_handlerattr_sethandlerdata(&type_name_attr, type_url_json_name);
  14548. upb_handlerattr_sethandlerdata(&value_name_attr, value_json_name);
  14549. /* Set up handlers. */
  14550. upb_handlers_setstartmsg(h, printer_startmsg, &empty_attr);
  14551. upb_handlers_setendmsg(h, printer_endmsg, &empty_attr);
  14552. upb_handlers_setstartstr(h, type_field, scalar_startstr, &type_name_attr);
  14553. upb_handlers_setstring(h, type_field, scalar_str, &empty_attr);
  14554. upb_handlers_setendstr(h, type_field, scalar_endstr, &empty_attr);
  14555. /* This is not the full and correct JSON encoding for the Any value field. It
  14556. * requires further processing by the wrapper code based on the type URL.
  14557. */
  14558. upb_handlers_setstartstr(h, value_field, scalar_startstr_onlykey,
  14559. &value_name_attr);
  14560. UPB_UNUSED(closure);
  14561. }
  14562. /* Set up handlers for a fieldmask submessage. */
  14563. void printer_sethandlers_fieldmask(const void *closure, upb_handlers *h) {
  14564. const upb_msgdef *md = upb_handlers_msgdef(h);
  14565. const upb_fielddef* f = upb_msgdef_itof(md, 1);
  14566. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  14567. upb_handlers_setstartseq(h, f, startseq_fieldmask, &empty_attr);
  14568. upb_handlers_setendseq(h, f, endseq_fieldmask, &empty_attr);
  14569. upb_handlers_setstartmsg(h, printer_startmsg_noframe, &empty_attr);
  14570. upb_handlers_setendmsg(h, printer_endmsg_noframe, &empty_attr);
  14571. upb_handlers_setstartstr(h, f, repeated_startstr_fieldmask, &empty_attr);
  14572. upb_handlers_setstring(h, f, repeated_str_fieldmask, &empty_attr);
  14573. UPB_UNUSED(closure);
  14574. }
  14575. /* Set up handlers for a duration submessage. */
  14576. void printer_sethandlers_duration(const void *closure, upb_handlers *h) {
  14577. const upb_msgdef *md = upb_handlers_msgdef(h);
  14578. const upb_fielddef* seconds_field =
  14579. upb_msgdef_itof(md, UPB_DURATION_SECONDS);
  14580. const upb_fielddef* nanos_field =
  14581. upb_msgdef_itof(md, UPB_DURATION_NANOS);
  14582. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  14583. upb_handlers_setstartmsg(h, printer_startdurationmsg, &empty_attr);
  14584. upb_handlers_setint64(h, seconds_field, putseconds, &empty_attr);
  14585. upb_handlers_setint32(h, nanos_field, putnanos, &empty_attr);
  14586. upb_handlers_setendmsg(h, printer_enddurationmsg, &empty_attr);
  14587. UPB_UNUSED(closure);
  14588. }
  14589. /* Set up handlers for a timestamp submessage. Instead of printing fields
  14590. * separately, the json representation of timestamp follows RFC 3339 */
  14591. void printer_sethandlers_timestamp(const void *closure, upb_handlers *h) {
  14592. const upb_msgdef *md = upb_handlers_msgdef(h);
  14593. const upb_fielddef* seconds_field =
  14594. upb_msgdef_itof(md, UPB_TIMESTAMP_SECONDS);
  14595. const upb_fielddef* nanos_field =
  14596. upb_msgdef_itof(md, UPB_TIMESTAMP_NANOS);
  14597. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  14598. upb_handlers_setstartmsg(h, printer_starttimestampmsg, &empty_attr);
  14599. upb_handlers_setint64(h, seconds_field, putseconds, &empty_attr);
  14600. upb_handlers_setint32(h, nanos_field, putnanos, &empty_attr);
  14601. upb_handlers_setendmsg(h, printer_endtimestampmsg, &empty_attr);
  14602. UPB_UNUSED(closure);
  14603. }
  14604. void printer_sethandlers_value(const void *closure, upb_handlers *h) {
  14605. const upb_msgdef *md = upb_handlers_msgdef(h);
  14606. upb_msg_field_iter i;
  14607. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  14608. upb_handlers_setstartmsg(h, printer_startmsg_noframe, &empty_attr);
  14609. upb_handlers_setendmsg(h, printer_endmsg_noframe, &empty_attr);
  14610. upb_msg_field_begin(&i, md);
  14611. for(; !upb_msg_field_done(&i); upb_msg_field_next(&i)) {
  14612. const upb_fielddef *f = upb_msg_iter_field(&i);
  14613. switch (upb_fielddef_type(f)) {
  14614. case UPB_TYPE_ENUM:
  14615. upb_handlers_setint32(h, f, putnull, &empty_attr);
  14616. break;
  14617. case UPB_TYPE_DOUBLE:
  14618. upb_handlers_setdouble(h, f, putdouble, &empty_attr);
  14619. break;
  14620. case UPB_TYPE_STRING:
  14621. upb_handlers_setstartstr(h, f, scalar_startstr_nokey, &empty_attr);
  14622. upb_handlers_setstring(h, f, scalar_str, &empty_attr);
  14623. upb_handlers_setendstr(h, f, scalar_endstr, &empty_attr);
  14624. break;
  14625. case UPB_TYPE_BOOL:
  14626. upb_handlers_setbool(h, f, putbool, &empty_attr);
  14627. break;
  14628. case UPB_TYPE_MESSAGE:
  14629. break;
  14630. default:
  14631. UPB_ASSERT(false);
  14632. break;
  14633. }
  14634. }
  14635. UPB_UNUSED(closure);
  14636. }
  14637. #define WRAPPER_SETHANDLERS(wrapper, type, putmethod) \
  14638. void printer_sethandlers_##wrapper(const void *closure, upb_handlers *h) { \
  14639. const upb_msgdef *md = upb_handlers_msgdef(h); \
  14640. const upb_fielddef* f = upb_msgdef_itof(md, 1); \
  14641. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER; \
  14642. upb_handlers_setstartmsg(h, printer_startmsg_noframe, &empty_attr); \
  14643. upb_handlers_setendmsg(h, printer_endmsg_noframe, &empty_attr); \
  14644. upb_handlers_set##type(h, f, putmethod, &empty_attr); \
  14645. UPB_UNUSED(closure); \
  14646. }
  14647. WRAPPER_SETHANDLERS(doublevalue, double, putdouble)
  14648. WRAPPER_SETHANDLERS(floatvalue, float, putfloat)
  14649. WRAPPER_SETHANDLERS(int64value, int64, putint64_t)
  14650. WRAPPER_SETHANDLERS(uint64value, uint64, putuint64_t)
  14651. WRAPPER_SETHANDLERS(int32value, int32, putint32_t)
  14652. WRAPPER_SETHANDLERS(uint32value, uint32, putuint32_t)
  14653. WRAPPER_SETHANDLERS(boolvalue, bool, putbool)
  14654. WRAPPER_SETHANDLERS(stringvalue, string, putstr_nokey)
  14655. WRAPPER_SETHANDLERS(bytesvalue, string, putbytes)
  14656. #undef WRAPPER_SETHANDLERS
  14657. void printer_sethandlers_listvalue(const void *closure, upb_handlers *h) {
  14658. const upb_msgdef *md = upb_handlers_msgdef(h);
  14659. const upb_fielddef* f = upb_msgdef_itof(md, 1);
  14660. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  14661. upb_handlers_setstartseq(h, f, startseq_nokey, &empty_attr);
  14662. upb_handlers_setendseq(h, f, endseq, &empty_attr);
  14663. upb_handlers_setstartmsg(h, printer_startmsg_noframe, &empty_attr);
  14664. upb_handlers_setendmsg(h, printer_endmsg_noframe, &empty_attr);
  14665. upb_handlers_setstartsubmsg(h, f, repeated_startsubmsg, &empty_attr);
  14666. UPB_UNUSED(closure);
  14667. }
  14668. void printer_sethandlers_structvalue(const void *closure, upb_handlers *h) {
  14669. const upb_msgdef *md = upb_handlers_msgdef(h);
  14670. const upb_fielddef* f = upb_msgdef_itof(md, 1);
  14671. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  14672. upb_handlers_setstartseq(h, f, startmap_nokey, &empty_attr);
  14673. upb_handlers_setendseq(h, f, endmap, &empty_attr);
  14674. upb_handlers_setstartmsg(h, printer_startmsg_noframe, &empty_attr);
  14675. upb_handlers_setendmsg(h, printer_endmsg_noframe, &empty_attr);
  14676. upb_handlers_setstartsubmsg(h, f, repeated_startsubmsg, &empty_attr);
  14677. UPB_UNUSED(closure);
  14678. }
  14679. void printer_sethandlers(const void *closure, upb_handlers *h) {
  14680. const upb_msgdef *md = upb_handlers_msgdef(h);
  14681. bool is_mapentry = upb_msgdef_mapentry(md);
  14682. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  14683. upb_msg_field_iter i;
  14684. const bool *preserve_fieldnames_ptr = closure;
  14685. const bool preserve_fieldnames = *preserve_fieldnames_ptr;
  14686. if (is_mapentry) {
  14687. /* mapentry messages are sufficiently different that we handle them
  14688. * separately. */
  14689. printer_sethandlers_mapentry(closure, preserve_fieldnames, h);
  14690. return;
  14691. }
  14692. switch (upb_msgdef_wellknowntype(md)) {
  14693. case UPB_WELLKNOWN_UNSPECIFIED:
  14694. break;
  14695. case UPB_WELLKNOWN_ANY:
  14696. printer_sethandlers_any(closure, h);
  14697. return;
  14698. case UPB_WELLKNOWN_FIELDMASK:
  14699. printer_sethandlers_fieldmask(closure, h);
  14700. return;
  14701. case UPB_WELLKNOWN_DURATION:
  14702. printer_sethandlers_duration(closure, h);
  14703. return;
  14704. case UPB_WELLKNOWN_TIMESTAMP:
  14705. printer_sethandlers_timestamp(closure, h);
  14706. return;
  14707. case UPB_WELLKNOWN_VALUE:
  14708. printer_sethandlers_value(closure, h);
  14709. return;
  14710. case UPB_WELLKNOWN_LISTVALUE:
  14711. printer_sethandlers_listvalue(closure, h);
  14712. return;
  14713. case UPB_WELLKNOWN_STRUCT:
  14714. printer_sethandlers_structvalue(closure, h);
  14715. return;
  14716. #define WRAPPER(wellknowntype, name) \
  14717. case wellknowntype: \
  14718. printer_sethandlers_##name(closure, h); \
  14719. return; \
  14720. WRAPPER(UPB_WELLKNOWN_DOUBLEVALUE, doublevalue);
  14721. WRAPPER(UPB_WELLKNOWN_FLOATVALUE, floatvalue);
  14722. WRAPPER(UPB_WELLKNOWN_INT64VALUE, int64value);
  14723. WRAPPER(UPB_WELLKNOWN_UINT64VALUE, uint64value);
  14724. WRAPPER(UPB_WELLKNOWN_INT32VALUE, int32value);
  14725. WRAPPER(UPB_WELLKNOWN_UINT32VALUE, uint32value);
  14726. WRAPPER(UPB_WELLKNOWN_BOOLVALUE, boolvalue);
  14727. WRAPPER(UPB_WELLKNOWN_STRINGVALUE, stringvalue);
  14728. WRAPPER(UPB_WELLKNOWN_BYTESVALUE, bytesvalue);
  14729. #undef WRAPPER
  14730. }
  14731. upb_handlers_setstartmsg(h, printer_startmsg, &empty_attr);
  14732. upb_handlers_setendmsg(h, printer_endmsg, &empty_attr);
  14733. #define TYPE(type, name, ctype) \
  14734. case type: \
  14735. if (upb_fielddef_isseq(f)) { \
  14736. upb_handlers_set##name(h, f, repeated_##ctype, &empty_attr); \
  14737. } else { \
  14738. upb_handlers_set##name(h, f, scalar_##ctype, &name_attr); \
  14739. } \
  14740. break;
  14741. upb_msg_field_begin(&i, md);
  14742. for(; !upb_msg_field_done(&i); upb_msg_field_next(&i)) {
  14743. const upb_fielddef *f = upb_msg_iter_field(&i);
  14744. upb_handlerattr name_attr = UPB_HANDLERATTR_INITIALIZER;
  14745. upb_handlerattr_sethandlerdata(&name_attr,
  14746. newstrpc(h, f, preserve_fieldnames));
  14747. if (upb_fielddef_ismap(f)) {
  14748. upb_handlers_setstartseq(h, f, startmap, &name_attr);
  14749. upb_handlers_setendseq(h, f, endmap, &name_attr);
  14750. } else if (upb_fielddef_isseq(f)) {
  14751. upb_handlers_setstartseq(h, f, startseq, &name_attr);
  14752. upb_handlers_setendseq(h, f, endseq, &empty_attr);
  14753. }
  14754. switch (upb_fielddef_type(f)) {
  14755. TYPE(UPB_TYPE_FLOAT, float, float);
  14756. TYPE(UPB_TYPE_DOUBLE, double, double);
  14757. TYPE(UPB_TYPE_BOOL, bool, bool);
  14758. TYPE(UPB_TYPE_INT32, int32, int32_t);
  14759. TYPE(UPB_TYPE_UINT32, uint32, uint32_t);
  14760. TYPE(UPB_TYPE_INT64, int64, int64_t);
  14761. TYPE(UPB_TYPE_UINT64, uint64, uint64_t);
  14762. case UPB_TYPE_ENUM: {
  14763. /* For now, we always emit symbolic names for enums. We may want an
  14764. * option later to control this behavior, but we will wait for a real
  14765. * need first. */
  14766. upb_handlerattr enum_attr = UPB_HANDLERATTR_INITIALIZER;
  14767. set_enum_hd(h, f, preserve_fieldnames, &enum_attr);
  14768. if (upb_fielddef_isseq(f)) {
  14769. upb_handlers_setint32(h, f, repeated_enum, &enum_attr);
  14770. } else {
  14771. upb_handlers_setint32(h, f, scalar_enum, &enum_attr);
  14772. }
  14773. upb_handlerattr_uninit(&enum_attr);
  14774. break;
  14775. }
  14776. case UPB_TYPE_STRING:
  14777. if (upb_fielddef_isseq(f)) {
  14778. upb_handlers_setstartstr(h, f, repeated_startstr, &empty_attr);
  14779. upb_handlers_setstring(h, f, repeated_str, &empty_attr);
  14780. upb_handlers_setendstr(h, f, repeated_endstr, &empty_attr);
  14781. } else {
  14782. upb_handlers_setstartstr(h, f, scalar_startstr, &name_attr);
  14783. upb_handlers_setstring(h, f, scalar_str, &empty_attr);
  14784. upb_handlers_setendstr(h, f, scalar_endstr, &empty_attr);
  14785. }
  14786. break;
  14787. case UPB_TYPE_BYTES:
  14788. /* XXX: this doesn't support strings that span buffers yet. The base64
  14789. * encoder will need to be made resumable for this to work properly. */
  14790. if (upb_fielddef_isseq(f)) {
  14791. upb_handlers_setstring(h, f, repeated_bytes, &empty_attr);
  14792. } else {
  14793. upb_handlers_setstring(h, f, scalar_bytes, &name_attr);
  14794. }
  14795. break;
  14796. case UPB_TYPE_MESSAGE:
  14797. if (upb_fielddef_isseq(f)) {
  14798. upb_handlers_setstartsubmsg(h, f, repeated_startsubmsg, &name_attr);
  14799. } else {
  14800. upb_handlers_setstartsubmsg(h, f, scalar_startsubmsg, &name_attr);
  14801. }
  14802. break;
  14803. }
  14804. upb_handlerattr_uninit(&name_attr);
  14805. }
  14806. upb_handlerattr_uninit(&empty_attr);
  14807. #undef TYPE
  14808. }
  14809. static void json_printer_reset(upb_json_printer *p) {
  14810. p->depth_ = 0;
  14811. }
  14812. /* Public API *****************************************************************/
  14813. upb_json_printer *upb_json_printer_create(upb_env *e, const upb_handlers *h,
  14814. upb_bytessink *output) {
  14815. #ifndef NDEBUG
  14816. size_t size_before = upb_env_bytesallocated(e);
  14817. #endif
  14818. upb_json_printer *p = upb_env_malloc(e, sizeof(upb_json_printer));
  14819. if (!p) return NULL;
  14820. p->output_ = output;
  14821. json_printer_reset(p);
  14822. upb_sink_reset(&p->input_, h, p);
  14823. p->seconds = 0;
  14824. p->nanos = 0;
  14825. /* If this fails, increase the value in printer.h. */
  14826. UPB_ASSERT_DEBUGVAR(upb_env_bytesallocated(e) - size_before <=
  14827. UPB_JSON_PRINTER_SIZE);
  14828. return p;
  14829. }
  14830. upb_sink *upb_json_printer_input(upb_json_printer *p) {
  14831. return &p->input_;
  14832. }
  14833. const upb_handlers *upb_json_printer_newhandlers(const upb_msgdef *md,
  14834. bool preserve_fieldnames,
  14835. const void *owner) {
  14836. return upb_handlers_newfrozen(
  14837. md, owner, printer_sethandlers, &preserve_fieldnames);
  14838. }
  14839. #undef UPB_SIZE
  14840. #undef UPB_FIELD_AT
  14841. #undef UPB_READ_ONEOF
  14842. #undef UPB_WRITE_ONEOF