upb.c 389 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794
  1. // Amalgamated source file
  2. #include "upb.h"
  3. /*
  4. * upb - a minimalist implementation of protocol buffers.
  5. *
  6. * Copyright (c) 2008-2012 Google Inc. See LICENSE for details.
  7. * Author: Josh Haberman <jhaberman@gmail.com>
  8. */
  9. #include <stdlib.h>
  10. #include <string.h>
  11. typedef struct {
  12. size_t len;
  13. char str[1]; // Null-terminated string data follows.
  14. } str_t;
  15. static str_t *newstr(const char *data, size_t len) {
  16. str_t *ret = malloc(sizeof(*ret) + len);
  17. if (!ret) return NULL;
  18. ret->len = len;
  19. memcpy(ret->str, data, len);
  20. ret->str[len] = '\0';
  21. return ret;
  22. }
  23. static void freestr(str_t *s) { free(s); }
  24. // isalpha() etc. from <ctype.h> are locale-dependent, which we don't want.
  25. static bool upb_isbetween(char c, char low, char high) {
  26. return c >= low && c <= high;
  27. }
  28. static bool upb_isletter(char c) {
  29. return upb_isbetween(c, 'A', 'Z') || upb_isbetween(c, 'a', 'z') || c == '_';
  30. }
  31. static bool upb_isalphanum(char c) {
  32. return upb_isletter(c) || upb_isbetween(c, '0', '9');
  33. }
  34. static bool upb_isident(const char *str, size_t len, bool full, upb_status *s) {
  35. bool start = true;
  36. for (size_t i = 0; i < len; i++) {
  37. char c = str[i];
  38. if (c == '.') {
  39. if (start || !full) {
  40. upb_status_seterrf(s, "invalid name: unexpected '.' (%s)", str);
  41. return false;
  42. }
  43. start = true;
  44. } else if (start) {
  45. if (!upb_isletter(c)) {
  46. upb_status_seterrf(
  47. s, "invalid name: path components must start with a letter (%s)",
  48. str);
  49. return false;
  50. }
  51. start = false;
  52. } else {
  53. if (!upb_isalphanum(c)) {
  54. upb_status_seterrf(s, "invalid name: non-alphanumeric character (%s)",
  55. str);
  56. return false;
  57. }
  58. }
  59. }
  60. return !start;
  61. }
  62. /* upb_def ********************************************************************/
  63. upb_deftype_t upb_def_type(const upb_def *d) { return d->type; }
  64. const char *upb_def_fullname(const upb_def *d) { return d->fullname; }
  65. bool upb_def_setfullname(upb_def *def, const char *fullname, upb_status *s) {
  66. assert(!upb_def_isfrozen(def));
  67. if (!upb_isident(fullname, strlen(fullname), true, s)) return false;
  68. free((void*)def->fullname);
  69. def->fullname = upb_strdup(fullname);
  70. return true;
  71. }
  72. upb_def *upb_def_dup(const upb_def *def, const void *o) {
  73. switch (def->type) {
  74. case UPB_DEF_MSG:
  75. return UPB_UPCAST(upb_msgdef_dup(upb_downcast_msgdef(def), o));
  76. case UPB_DEF_FIELD:
  77. return UPB_UPCAST(upb_fielddef_dup(upb_downcast_fielddef(def), o));
  78. case UPB_DEF_ENUM:
  79. return UPB_UPCAST(upb_enumdef_dup(upb_downcast_enumdef(def), o));
  80. default: assert(false); return NULL;
  81. }
  82. }
  83. bool upb_def_isfrozen(const upb_def *def) {
  84. return upb_refcounted_isfrozen(UPB_UPCAST(def));
  85. }
  86. void upb_def_ref(const upb_def *def, const void *owner) {
  87. upb_refcounted_ref(UPB_UPCAST(def), owner);
  88. }
  89. void upb_def_unref(const upb_def *def, const void *owner) {
  90. upb_refcounted_unref(UPB_UPCAST(def), owner);
  91. }
  92. void upb_def_donateref(const upb_def *def, const void *from, const void *to) {
  93. upb_refcounted_donateref(UPB_UPCAST(def), from, to);
  94. }
  95. void upb_def_checkref(const upb_def *def, const void *owner) {
  96. upb_refcounted_checkref(UPB_UPCAST(def), owner);
  97. }
  98. static bool upb_def_init(upb_def *def, upb_deftype_t type,
  99. const struct upb_refcounted_vtbl *vtbl,
  100. const void *owner) {
  101. if (!upb_refcounted_init(UPB_UPCAST(def), vtbl, owner)) return false;
  102. def->type = type;
  103. def->fullname = NULL;
  104. def->came_from_user = false;
  105. return true;
  106. }
  107. static void upb_def_uninit(upb_def *def) {
  108. free((void*)def->fullname);
  109. }
  110. static const char *msgdef_name(const upb_msgdef *m) {
  111. const char *name = upb_def_fullname(UPB_UPCAST(m));
  112. return name ? name : "(anonymous)";
  113. }
  114. static bool upb_validate_field(upb_fielddef *f, upb_status *s) {
  115. if (upb_fielddef_name(f) == NULL || upb_fielddef_number(f) == 0) {
  116. upb_status_seterrmsg(s, "fielddef must have name and number set");
  117. return false;
  118. }
  119. if (!f->type_is_set_) {
  120. upb_status_seterrmsg(s, "fielddef type was not initialized");
  121. return false;
  122. }
  123. if (upb_fielddef_lazy(f) &&
  124. upb_fielddef_descriptortype(f) != UPB_DESCRIPTOR_TYPE_MESSAGE) {
  125. upb_status_seterrmsg(s,
  126. "only length-delimited submessage fields may be lazy");
  127. return false;
  128. }
  129. if (upb_fielddef_hassubdef(f)) {
  130. if (f->subdef_is_symbolic) {
  131. upb_status_seterrf(s, "field '%s.%s' has not been resolved",
  132. msgdef_name(f->msg.def), upb_fielddef_name(f));
  133. return false;
  134. }
  135. const upb_def *subdef = upb_fielddef_subdef(f);
  136. if (subdef == NULL) {
  137. upb_status_seterrf(s, "field %s.%s is missing required subdef",
  138. msgdef_name(f->msg.def), upb_fielddef_name(f));
  139. return false;
  140. }
  141. if (!upb_def_isfrozen(subdef) && !subdef->came_from_user) {
  142. upb_status_seterrf(s,
  143. "subdef of field %s.%s is not frozen or being frozen",
  144. msgdef_name(f->msg.def), upb_fielddef_name(f));
  145. return false;
  146. }
  147. }
  148. if (upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  149. bool has_default_name = upb_fielddef_enumhasdefaultstr(f);
  150. bool has_default_number = upb_fielddef_enumhasdefaultint32(f);
  151. // Previously verified by upb_validate_enumdef().
  152. assert(upb_enumdef_numvals(upb_fielddef_enumsubdef(f)) > 0);
  153. // We've already validated that we have an associated enumdef and that it
  154. // has at least one member, so at least one of these should be true.
  155. // Because if the user didn't set anything, we'll pick up the enum's
  156. // default, but if the user *did* set something we should at least pick up
  157. // the one they set (int32 or string).
  158. assert(has_default_name || has_default_number);
  159. if (!has_default_name) {
  160. upb_status_seterrf(s,
  161. "enum default for field %s.%s (%d) is not in the enum",
  162. msgdef_name(f->msg.def), upb_fielddef_name(f),
  163. upb_fielddef_defaultint32(f));
  164. return false;
  165. }
  166. if (!has_default_number) {
  167. upb_status_seterrf(s,
  168. "enum default for field %s.%s (%s) is not in the enum",
  169. msgdef_name(f->msg.def), upb_fielddef_name(f),
  170. upb_fielddef_defaultstr(f, NULL));
  171. return false;
  172. }
  173. // Lift the effective numeric default into the field's default slot, in case
  174. // we were only getting it "by reference" from the enumdef.
  175. upb_fielddef_setdefaultint32(f, upb_fielddef_defaultint32(f));
  176. }
  177. // Ensure that MapEntry submessages only appear as repeated fields, not
  178. // optional/required (singular) fields.
  179. if (upb_fielddef_type(f) == UPB_TYPE_MESSAGE &&
  180. upb_fielddef_msgsubdef(f) != NULL) {
  181. const upb_msgdef *subdef = upb_fielddef_msgsubdef(f);
  182. if (upb_msgdef_mapentry(subdef) && !upb_fielddef_isseq(f)) {
  183. upb_status_seterrf(s,
  184. "Field %s refers to mapentry message but is not "
  185. "a repeated field",
  186. upb_fielddef_name(f) ? upb_fielddef_name(f) :
  187. "(unnamed)");
  188. return false;
  189. }
  190. }
  191. return true;
  192. }
  193. static bool upb_validate_enumdef(const upb_enumdef *e, upb_status *s) {
  194. if (upb_enumdef_numvals(e) == 0) {
  195. upb_status_seterrf(s, "enum %s has no members (must have at least one)",
  196. upb_enumdef_fullname(e));
  197. return false;
  198. }
  199. return true;
  200. }
  201. // All submessage fields are lower than all other fields.
  202. // Secondly, fields are increasing in order.
  203. uint32_t field_rank(const upb_fielddef *f) {
  204. uint32_t ret = upb_fielddef_number(f);
  205. const uint32_t high_bit = 1 << 30;
  206. assert(ret < high_bit);
  207. if (!upb_fielddef_issubmsg(f))
  208. ret |= high_bit;
  209. return ret;
  210. }
  211. int cmp_fields(const void *p1, const void *p2) {
  212. const upb_fielddef *f1 = *(upb_fielddef*const*)p1;
  213. const upb_fielddef *f2 = *(upb_fielddef*const*)p2;
  214. return field_rank(f1) - field_rank(f2);
  215. }
  216. static bool assign_msg_indices(upb_msgdef *m, upb_status *s) {
  217. // Sort fields. upb internally relies on UPB_TYPE_MESSAGE fields having the
  218. // lowest indexes, but we do not publicly guarantee this.
  219. int n = upb_msgdef_numfields(m);
  220. upb_fielddef **fields = malloc(n * sizeof(*fields));
  221. if (!fields) return false;
  222. upb_msg_field_iter j;
  223. int i;
  224. m->submsg_field_count = 0;
  225. for(i = 0, upb_msg_field_begin(&j, m);
  226. !upb_msg_field_done(&j);
  227. upb_msg_field_next(&j), i++) {
  228. upb_fielddef *f = upb_msg_iter_field(&j);
  229. assert(f->msg.def == m);
  230. if (!upb_validate_field(f, s)) {
  231. free(fields);
  232. return false;
  233. }
  234. if (upb_fielddef_issubmsg(f)) {
  235. m->submsg_field_count++;
  236. }
  237. fields[i] = f;
  238. }
  239. qsort(fields, n, sizeof(*fields), cmp_fields);
  240. uint32_t selector = UPB_STATIC_SELECTOR_COUNT + m->submsg_field_count;
  241. for (i = 0; i < n; i++) {
  242. upb_fielddef *f = fields[i];
  243. f->index_ = i;
  244. f->selector_base = selector + upb_handlers_selectorbaseoffset(f);
  245. selector += upb_handlers_selectorcount(f);
  246. }
  247. m->selector_count = selector;
  248. #ifndef NDEBUG
  249. // Verify that all selectors for the message are distinct.
  250. //
  251. #define TRY(type) \
  252. if (upb_handlers_getselector(f, type, &sel)) upb_inttable_insert(&t, sel, v);
  253. upb_inttable t;
  254. upb_inttable_init(&t, UPB_CTYPE_BOOL);
  255. upb_value v = upb_value_bool(true);
  256. upb_selector_t sel;
  257. upb_inttable_insert(&t, UPB_STARTMSG_SELECTOR, v);
  258. upb_inttable_insert(&t, UPB_ENDMSG_SELECTOR, v);
  259. for(upb_msg_field_begin(&j, m);
  260. !upb_msg_field_done(&j);
  261. upb_msg_field_next(&j)) {
  262. upb_fielddef *f = upb_msg_iter_field(&j);
  263. // These calls will assert-fail in upb_table if the value already exists.
  264. TRY(UPB_HANDLER_INT32);
  265. TRY(UPB_HANDLER_INT64)
  266. TRY(UPB_HANDLER_UINT32)
  267. TRY(UPB_HANDLER_UINT64)
  268. TRY(UPB_HANDLER_FLOAT)
  269. TRY(UPB_HANDLER_DOUBLE)
  270. TRY(UPB_HANDLER_BOOL)
  271. TRY(UPB_HANDLER_STARTSTR)
  272. TRY(UPB_HANDLER_STRING)
  273. TRY(UPB_HANDLER_ENDSTR)
  274. TRY(UPB_HANDLER_STARTSUBMSG)
  275. TRY(UPB_HANDLER_ENDSUBMSG)
  276. TRY(UPB_HANDLER_STARTSEQ)
  277. TRY(UPB_HANDLER_ENDSEQ)
  278. }
  279. upb_inttable_uninit(&t);
  280. #undef TRY
  281. #endif
  282. free(fields);
  283. return true;
  284. }
  285. bool upb_def_freeze(upb_def *const* defs, int n, upb_status *s) {
  286. upb_status_clear(s);
  287. // First perform validation, in two passes so we can check that we have a
  288. // transitive closure without needing to search.
  289. for (int i = 0; i < n; i++) {
  290. upb_def *def = defs[i];
  291. if (upb_def_isfrozen(def)) {
  292. // Could relax this requirement if it's annoying.
  293. upb_status_seterrmsg(s, "def is already frozen");
  294. goto err;
  295. } else if (def->type == UPB_DEF_FIELD) {
  296. upb_status_seterrmsg(s, "standalone fielddefs can not be frozen");
  297. goto err;
  298. } else if (def->type == UPB_DEF_ENUM) {
  299. if (!upb_validate_enumdef(upb_dyncast_enumdef(def), s)) {
  300. goto err;
  301. }
  302. } else {
  303. // Set now to detect transitive closure in the second pass.
  304. def->came_from_user = true;
  305. }
  306. }
  307. // Second pass of validation. Also assign selector bases and indexes, and
  308. // compact tables.
  309. for (int i = 0; i < n; i++) {
  310. upb_msgdef *m = upb_dyncast_msgdef_mutable(defs[i]);
  311. upb_enumdef *e = upb_dyncast_enumdef_mutable(defs[i]);
  312. if (m) {
  313. upb_inttable_compact(&m->itof);
  314. if (!assign_msg_indices(m, s)) {
  315. goto err;
  316. }
  317. } else if (e) {
  318. upb_inttable_compact(&e->iton);
  319. }
  320. }
  321. // Def graph contains FieldDefs between each MessageDef, so double the limit.
  322. int maxdepth = UPB_MAX_MESSAGE_DEPTH * 2;
  323. // Validation all passed; freeze the defs.
  324. bool ret =
  325. upb_refcounted_freeze((upb_refcounted * const *)defs, n, s, maxdepth);
  326. assert(!(s && ret != upb_ok(s)));
  327. return ret;
  328. err:
  329. for (int i = 0; i < n; i++) {
  330. defs[i]->came_from_user = false;
  331. }
  332. assert(!(s && upb_ok(s)));
  333. return false;
  334. }
  335. /* upb_enumdef ****************************************************************/
  336. static void upb_enumdef_free(upb_refcounted *r) {
  337. upb_enumdef *e = (upb_enumdef*)r;
  338. upb_inttable_iter i;
  339. upb_inttable_begin(&i, &e->iton);
  340. for( ; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  341. // To clean up the upb_strdup() from upb_enumdef_addval().
  342. free(upb_value_getcstr(upb_inttable_iter_value(&i)));
  343. }
  344. upb_strtable_uninit(&e->ntoi);
  345. upb_inttable_uninit(&e->iton);
  346. upb_def_uninit(UPB_UPCAST(e));
  347. free(e);
  348. }
  349. upb_enumdef *upb_enumdef_new(const void *owner) {
  350. static const struct upb_refcounted_vtbl vtbl = {NULL, &upb_enumdef_free};
  351. upb_enumdef *e = malloc(sizeof(*e));
  352. if (!e) return NULL;
  353. if (!upb_def_init(UPB_UPCAST(e), UPB_DEF_ENUM, &vtbl, owner)) goto err2;
  354. if (!upb_strtable_init(&e->ntoi, UPB_CTYPE_INT32)) goto err2;
  355. if (!upb_inttable_init(&e->iton, UPB_CTYPE_CSTR)) goto err1;
  356. return e;
  357. err1:
  358. upb_strtable_uninit(&e->ntoi);
  359. err2:
  360. free(e);
  361. return NULL;
  362. }
  363. upb_enumdef *upb_enumdef_dup(const upb_enumdef *e, const void *owner) {
  364. upb_enumdef *new_e = upb_enumdef_new(owner);
  365. if (!new_e) return NULL;
  366. upb_enum_iter i;
  367. for(upb_enum_begin(&i, e); !upb_enum_done(&i); upb_enum_next(&i)) {
  368. bool success = upb_enumdef_addval(
  369. new_e, upb_enum_iter_name(&i),upb_enum_iter_number(&i), NULL);
  370. if (!success) {
  371. upb_enumdef_unref(new_e, owner);
  372. return NULL;
  373. }
  374. }
  375. return new_e;
  376. }
  377. bool upb_enumdef_isfrozen(const upb_enumdef *e) {
  378. return upb_def_isfrozen(UPB_UPCAST(e));
  379. }
  380. void upb_enumdef_ref(const upb_enumdef *e, const void *owner) {
  381. upb_def_ref(UPB_UPCAST(e), owner);
  382. }
  383. void upb_enumdef_unref(const upb_enumdef *e, const void *owner) {
  384. upb_def_unref(UPB_UPCAST(e), owner);
  385. }
  386. void upb_enumdef_donateref(
  387. const upb_enumdef *e, const void *from, const void *to) {
  388. upb_def_donateref(UPB_UPCAST(e), from, to);
  389. }
  390. void upb_enumdef_checkref(const upb_enumdef *e, const void *owner) {
  391. upb_def_checkref(UPB_UPCAST(e), owner);
  392. }
  393. bool upb_enumdef_freeze(upb_enumdef *e, upb_status *status) {
  394. upb_def *d = UPB_UPCAST(e);
  395. return upb_def_freeze(&d, 1, status);
  396. }
  397. const char *upb_enumdef_fullname(const upb_enumdef *e) {
  398. return upb_def_fullname(UPB_UPCAST(e));
  399. }
  400. bool upb_enumdef_setfullname(upb_enumdef *e, const char *fullname,
  401. upb_status *s) {
  402. return upb_def_setfullname(UPB_UPCAST(e), fullname, s);
  403. }
  404. bool upb_enumdef_addval(upb_enumdef *e, const char *name, int32_t num,
  405. upb_status *status) {
  406. if (!upb_isident(name, strlen(name), false, status)) {
  407. return false;
  408. }
  409. if (upb_enumdef_ntoiz(e, name, NULL)) {
  410. upb_status_seterrf(status, "name '%s' is already defined", name);
  411. return false;
  412. }
  413. if (!upb_strtable_insert(&e->ntoi, name, upb_value_int32(num))) {
  414. upb_status_seterrmsg(status, "out of memory");
  415. return false;
  416. }
  417. if (!upb_inttable_lookup(&e->iton, num, NULL) &&
  418. !upb_inttable_insert(&e->iton, num, upb_value_cstr(upb_strdup(name)))) {
  419. upb_status_seterrmsg(status, "out of memory");
  420. upb_strtable_remove(&e->ntoi, name, NULL);
  421. return false;
  422. }
  423. if (upb_enumdef_numvals(e) == 1) {
  424. bool ok = upb_enumdef_setdefault(e, num, NULL);
  425. UPB_ASSERT_VAR(ok, ok);
  426. }
  427. return true;
  428. }
  429. int32_t upb_enumdef_default(const upb_enumdef *e) {
  430. assert(upb_enumdef_iton(e, e->defaultval));
  431. return e->defaultval;
  432. }
  433. bool upb_enumdef_setdefault(upb_enumdef *e, int32_t val, upb_status *s) {
  434. assert(!upb_enumdef_isfrozen(e));
  435. if (!upb_enumdef_iton(e, val)) {
  436. upb_status_seterrf(s, "number '%d' is not in the enum.", val);
  437. return false;
  438. }
  439. e->defaultval = val;
  440. return true;
  441. }
  442. int upb_enumdef_numvals(const upb_enumdef *e) {
  443. return upb_strtable_count(&e->ntoi);
  444. }
  445. void upb_enum_begin(upb_enum_iter *i, const upb_enumdef *e) {
  446. // We iterate over the ntoi table, to account for duplicate numbers.
  447. upb_strtable_begin(i, &e->ntoi);
  448. }
  449. void upb_enum_next(upb_enum_iter *iter) { upb_strtable_next(iter); }
  450. bool upb_enum_done(upb_enum_iter *iter) { return upb_strtable_done(iter); }
  451. bool upb_enumdef_ntoi(const upb_enumdef *def, const char *name,
  452. size_t len, int32_t *num) {
  453. upb_value v;
  454. if (!upb_strtable_lookup2(&def->ntoi, name, len, &v)) {
  455. return false;
  456. }
  457. if (num) *num = upb_value_getint32(v);
  458. return true;
  459. }
  460. const char *upb_enumdef_iton(const upb_enumdef *def, int32_t num) {
  461. upb_value v;
  462. return upb_inttable_lookup32(&def->iton, num, &v) ?
  463. upb_value_getcstr(v) : NULL;
  464. }
  465. const char *upb_enum_iter_name(upb_enum_iter *iter) {
  466. return upb_strtable_iter_key(iter);
  467. }
  468. int32_t upb_enum_iter_number(upb_enum_iter *iter) {
  469. return upb_value_getint32(upb_strtable_iter_value(iter));
  470. }
  471. /* upb_fielddef ***************************************************************/
  472. static void upb_fielddef_init_default(upb_fielddef *f);
  473. static void upb_fielddef_uninit_default(upb_fielddef *f) {
  474. if (f->type_is_set_ && f->default_is_string && f->defaultval.bytes)
  475. freestr(f->defaultval.bytes);
  476. }
  477. static void visitfield(const upb_refcounted *r, upb_refcounted_visit *visit,
  478. void *closure) {
  479. const upb_fielddef *f = (const upb_fielddef*)r;
  480. if (upb_fielddef_containingtype(f)) {
  481. visit(r, UPB_UPCAST2(upb_fielddef_containingtype(f)), closure);
  482. }
  483. if (upb_fielddef_containingoneof(f)) {
  484. visit(r, UPB_UPCAST2(upb_fielddef_containingoneof(f)), closure);
  485. }
  486. if (upb_fielddef_subdef(f)) {
  487. visit(r, UPB_UPCAST(upb_fielddef_subdef(f)), closure);
  488. }
  489. }
  490. static void freefield(upb_refcounted *r) {
  491. upb_fielddef *f = (upb_fielddef*)r;
  492. upb_fielddef_uninit_default(f);
  493. if (f->subdef_is_symbolic)
  494. free(f->sub.name);
  495. upb_def_uninit(UPB_UPCAST(f));
  496. free(f);
  497. }
  498. static const char *enumdefaultstr(const upb_fielddef *f) {
  499. assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  500. const upb_enumdef *e = upb_fielddef_enumsubdef(f);
  501. if (f->default_is_string && f->defaultval.bytes) {
  502. // Default was explicitly set as a string.
  503. str_t *s = f->defaultval.bytes;
  504. return s->str;
  505. } else if (e) {
  506. if (!f->default_is_string) {
  507. // Default was explicitly set as an integer; look it up in enumdef.
  508. const char *name = upb_enumdef_iton(e, f->defaultval.sint);
  509. if (name) {
  510. return name;
  511. }
  512. } else {
  513. // Default is completely unset; pull enumdef default.
  514. if (upb_enumdef_numvals(e) > 0) {
  515. const char *name = upb_enumdef_iton(e, upb_enumdef_default(e));
  516. assert(name);
  517. return name;
  518. }
  519. }
  520. }
  521. return NULL;
  522. }
  523. static bool enumdefaultint32(const upb_fielddef *f, int32_t *val) {
  524. assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  525. const upb_enumdef *e = upb_fielddef_enumsubdef(f);
  526. if (!f->default_is_string) {
  527. // Default was explicitly set as an integer.
  528. *val = f->defaultval.sint;
  529. return true;
  530. } else if (e) {
  531. if (f->defaultval.bytes) {
  532. // Default was explicitly set as a str; try to lookup corresponding int.
  533. str_t *s = f->defaultval.bytes;
  534. if (upb_enumdef_ntoiz(e, s->str, val)) {
  535. return true;
  536. }
  537. } else {
  538. // Default is unset; try to pull in enumdef default.
  539. if (upb_enumdef_numvals(e) > 0) {
  540. *val = upb_enumdef_default(e);
  541. return true;
  542. }
  543. }
  544. }
  545. return false;
  546. }
  547. upb_fielddef *upb_fielddef_new(const void *owner) {
  548. static const struct upb_refcounted_vtbl vtbl = {visitfield, freefield};
  549. upb_fielddef *f = malloc(sizeof(*f));
  550. if (!f) return NULL;
  551. if (!upb_def_init(UPB_UPCAST(f), UPB_DEF_FIELD, &vtbl, owner)) {
  552. free(f);
  553. return NULL;
  554. }
  555. f->msg.def = NULL;
  556. f->sub.def = NULL;
  557. f->oneof = NULL;
  558. f->subdef_is_symbolic = false;
  559. f->msg_is_symbolic = false;
  560. f->label_ = UPB_LABEL_OPTIONAL;
  561. f->type_ = UPB_TYPE_INT32;
  562. f->number_ = 0;
  563. f->type_is_set_ = false;
  564. f->tagdelim = false;
  565. f->is_extension_ = false;
  566. f->lazy_ = false;
  567. f->packed_ = true;
  568. // For the moment we default this to UPB_INTFMT_VARIABLE, since it will work
  569. // with all integer types and is in some since more "default" since the most
  570. // normal-looking proto2 types int32/int64/uint32/uint64 use variable.
  571. //
  572. // Other options to consider:
  573. // - there is no default; users must set this manually (like type).
  574. // - default signed integers to UPB_INTFMT_ZIGZAG, since it's more likely to
  575. // be an optimal default for signed integers.
  576. f->intfmt = UPB_INTFMT_VARIABLE;
  577. return f;
  578. }
  579. upb_fielddef *upb_fielddef_dup(const upb_fielddef *f, const void *owner) {
  580. upb_fielddef *newf = upb_fielddef_new(owner);
  581. if (!newf) return NULL;
  582. upb_fielddef_settype(newf, upb_fielddef_type(f));
  583. upb_fielddef_setlabel(newf, upb_fielddef_label(f));
  584. upb_fielddef_setnumber(newf, upb_fielddef_number(f), NULL);
  585. upb_fielddef_setname(newf, upb_fielddef_name(f), NULL);
  586. if (f->default_is_string && f->defaultval.bytes) {
  587. str_t *s = f->defaultval.bytes;
  588. upb_fielddef_setdefaultstr(newf, s->str, s->len, NULL);
  589. } else {
  590. newf->default_is_string = f->default_is_string;
  591. newf->defaultval = f->defaultval;
  592. }
  593. const char *srcname;
  594. if (f->subdef_is_symbolic) {
  595. srcname = f->sub.name; // Might be NULL.
  596. } else {
  597. srcname = f->sub.def ? upb_def_fullname(f->sub.def) : NULL;
  598. }
  599. if (srcname) {
  600. char *newname = malloc(strlen(f->sub.def->fullname) + 2);
  601. if (!newname) {
  602. upb_fielddef_unref(newf, owner);
  603. return NULL;
  604. }
  605. strcpy(newname, ".");
  606. strcat(newname, f->sub.def->fullname);
  607. upb_fielddef_setsubdefname(newf, newname, NULL);
  608. free(newname);
  609. }
  610. return newf;
  611. }
  612. bool upb_fielddef_isfrozen(const upb_fielddef *f) {
  613. return upb_def_isfrozen(UPB_UPCAST(f));
  614. }
  615. void upb_fielddef_ref(const upb_fielddef *f, const void *owner) {
  616. upb_def_ref(UPB_UPCAST(f), owner);
  617. }
  618. void upb_fielddef_unref(const upb_fielddef *f, const void *owner) {
  619. upb_def_unref(UPB_UPCAST(f), owner);
  620. }
  621. void upb_fielddef_donateref(
  622. const upb_fielddef *f, const void *from, const void *to) {
  623. upb_def_donateref(UPB_UPCAST(f), from, to);
  624. }
  625. void upb_fielddef_checkref(const upb_fielddef *f, const void *owner) {
  626. upb_def_checkref(UPB_UPCAST(f), owner);
  627. }
  628. bool upb_fielddef_typeisset(const upb_fielddef *f) {
  629. return f->type_is_set_;
  630. }
  631. upb_fieldtype_t upb_fielddef_type(const upb_fielddef *f) {
  632. assert(f->type_is_set_);
  633. return f->type_;
  634. }
  635. uint32_t upb_fielddef_index(const upb_fielddef *f) {
  636. return f->index_;
  637. }
  638. upb_label_t upb_fielddef_label(const upb_fielddef *f) {
  639. return f->label_;
  640. }
  641. upb_intfmt_t upb_fielddef_intfmt(const upb_fielddef *f) {
  642. return f->intfmt;
  643. }
  644. bool upb_fielddef_istagdelim(const upb_fielddef *f) {
  645. return f->tagdelim;
  646. }
  647. uint32_t upb_fielddef_number(const upb_fielddef *f) {
  648. return f->number_;
  649. }
  650. bool upb_fielddef_isextension(const upb_fielddef *f) {
  651. return f->is_extension_;
  652. }
  653. bool upb_fielddef_lazy(const upb_fielddef *f) {
  654. return f->lazy_;
  655. }
  656. bool upb_fielddef_packed(const upb_fielddef *f) {
  657. return f->packed_;
  658. }
  659. const char *upb_fielddef_name(const upb_fielddef *f) {
  660. return upb_def_fullname(UPB_UPCAST(f));
  661. }
  662. const upb_msgdef *upb_fielddef_containingtype(const upb_fielddef *f) {
  663. return f->msg_is_symbolic ? NULL : f->msg.def;
  664. }
  665. const upb_oneofdef *upb_fielddef_containingoneof(const upb_fielddef *f) {
  666. return f->oneof;
  667. }
  668. upb_msgdef *upb_fielddef_containingtype_mutable(upb_fielddef *f) {
  669. return (upb_msgdef*)upb_fielddef_containingtype(f);
  670. }
  671. const char *upb_fielddef_containingtypename(upb_fielddef *f) {
  672. return f->msg_is_symbolic ? f->msg.name : NULL;
  673. }
  674. static void release_containingtype(upb_fielddef *f) {
  675. if (f->msg_is_symbolic) free(f->msg.name);
  676. }
  677. bool upb_fielddef_setcontainingtypename(upb_fielddef *f, const char *name,
  678. upb_status *s) {
  679. assert(!upb_fielddef_isfrozen(f));
  680. if (upb_fielddef_containingtype(f)) {
  681. upb_status_seterrmsg(s, "field has already been added to a message.");
  682. return false;
  683. }
  684. // TODO: validate name (upb_isident() doesn't quite work atm because this name
  685. // may have a leading ".").
  686. release_containingtype(f);
  687. f->msg.name = upb_strdup(name);
  688. f->msg_is_symbolic = true;
  689. return true;
  690. }
  691. bool upb_fielddef_setname(upb_fielddef *f, const char *name, upb_status *s) {
  692. if (upb_fielddef_containingtype(f) || upb_fielddef_containingoneof(f)) {
  693. upb_status_seterrmsg(s, "Already added to message or oneof");
  694. return false;
  695. }
  696. return upb_def_setfullname(UPB_UPCAST(f), name, s);
  697. }
  698. static void chkdefaulttype(const upb_fielddef *f, upb_fieldtype_t type) {
  699. UPB_UNUSED(f);
  700. UPB_UNUSED(type);
  701. assert(f->type_is_set_ && upb_fielddef_type(f) == type);
  702. }
  703. int64_t upb_fielddef_defaultint64(const upb_fielddef *f) {
  704. chkdefaulttype(f, UPB_TYPE_INT64);
  705. return f->defaultval.sint;
  706. }
  707. int32_t upb_fielddef_defaultint32(const upb_fielddef *f) {
  708. if (f->type_is_set_ && upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  709. int32_t val;
  710. bool ok = enumdefaultint32(f, &val);
  711. UPB_ASSERT_VAR(ok, ok);
  712. return val;
  713. } else {
  714. chkdefaulttype(f, UPB_TYPE_INT32);
  715. return f->defaultval.sint;
  716. }
  717. }
  718. uint64_t upb_fielddef_defaultuint64(const upb_fielddef *f) {
  719. chkdefaulttype(f, UPB_TYPE_UINT64);
  720. return f->defaultval.uint;
  721. }
  722. uint32_t upb_fielddef_defaultuint32(const upb_fielddef *f) {
  723. chkdefaulttype(f, UPB_TYPE_UINT32);
  724. return f->defaultval.uint;
  725. }
  726. bool upb_fielddef_defaultbool(const upb_fielddef *f) {
  727. chkdefaulttype(f, UPB_TYPE_BOOL);
  728. return f->defaultval.uint;
  729. }
  730. float upb_fielddef_defaultfloat(const upb_fielddef *f) {
  731. chkdefaulttype(f, UPB_TYPE_FLOAT);
  732. return f->defaultval.flt;
  733. }
  734. double upb_fielddef_defaultdouble(const upb_fielddef *f) {
  735. chkdefaulttype(f, UPB_TYPE_DOUBLE);
  736. return f->defaultval.dbl;
  737. }
  738. const char *upb_fielddef_defaultstr(const upb_fielddef *f, size_t *len) {
  739. assert(f->type_is_set_);
  740. assert(upb_fielddef_type(f) == UPB_TYPE_STRING ||
  741. upb_fielddef_type(f) == UPB_TYPE_BYTES ||
  742. upb_fielddef_type(f) == UPB_TYPE_ENUM);
  743. if (upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  744. const char *ret = enumdefaultstr(f);
  745. assert(ret);
  746. // Enum defaults can't have embedded NULLs.
  747. if (len) *len = strlen(ret);
  748. return ret;
  749. }
  750. if (f->default_is_string) {
  751. str_t *str = f->defaultval.bytes;
  752. if (len) *len = str->len;
  753. return str->str;
  754. }
  755. return NULL;
  756. }
  757. static void upb_fielddef_init_default(upb_fielddef *f) {
  758. f->default_is_string = false;
  759. switch (upb_fielddef_type(f)) {
  760. case UPB_TYPE_DOUBLE: f->defaultval.dbl = 0; break;
  761. case UPB_TYPE_FLOAT: f->defaultval.flt = 0; break;
  762. case UPB_TYPE_INT32:
  763. case UPB_TYPE_INT64: f->defaultval.sint = 0; break;
  764. case UPB_TYPE_UINT64:
  765. case UPB_TYPE_UINT32:
  766. case UPB_TYPE_BOOL: f->defaultval.uint = 0; break;
  767. case UPB_TYPE_STRING:
  768. case UPB_TYPE_BYTES:
  769. f->defaultval.bytes = newstr("", 0);
  770. f->default_is_string = true;
  771. break;
  772. case UPB_TYPE_MESSAGE: break;
  773. case UPB_TYPE_ENUM:
  774. // This is our special sentinel that indicates "not set" for an enum.
  775. f->default_is_string = true;
  776. f->defaultval.bytes = NULL;
  777. break;
  778. }
  779. }
  780. const upb_def *upb_fielddef_subdef(const upb_fielddef *f) {
  781. return f->subdef_is_symbolic ? NULL : f->sub.def;
  782. }
  783. const upb_msgdef *upb_fielddef_msgsubdef(const upb_fielddef *f) {
  784. const upb_def *def = upb_fielddef_subdef(f);
  785. return def ? upb_dyncast_msgdef(def) : NULL;
  786. }
  787. const upb_enumdef *upb_fielddef_enumsubdef(const upb_fielddef *f) {
  788. const upb_def *def = upb_fielddef_subdef(f);
  789. return def ? upb_dyncast_enumdef(def) : NULL;
  790. }
  791. upb_def *upb_fielddef_subdef_mutable(upb_fielddef *f) {
  792. return (upb_def*)upb_fielddef_subdef(f);
  793. }
  794. const char *upb_fielddef_subdefname(const upb_fielddef *f) {
  795. if (f->subdef_is_symbolic) {
  796. return f->sub.name;
  797. } else if (f->sub.def) {
  798. return upb_def_fullname(f->sub.def);
  799. } else {
  800. return NULL;
  801. }
  802. }
  803. bool upb_fielddef_setnumber(upb_fielddef *f, uint32_t number, upb_status *s) {
  804. if (upb_fielddef_containingtype(f)) {
  805. upb_status_seterrmsg(
  806. s, "cannot change field number after adding to a message");
  807. return false;
  808. }
  809. if (number == 0 || number > UPB_MAX_FIELDNUMBER) {
  810. upb_status_seterrf(s, "invalid field number (%u)", number);
  811. return false;
  812. }
  813. f->number_ = number;
  814. return true;
  815. }
  816. void upb_fielddef_settype(upb_fielddef *f, upb_fieldtype_t type) {
  817. assert(!upb_fielddef_isfrozen(f));
  818. assert(upb_fielddef_checktype(type));
  819. upb_fielddef_uninit_default(f);
  820. f->type_ = type;
  821. f->type_is_set_ = true;
  822. upb_fielddef_init_default(f);
  823. }
  824. void upb_fielddef_setdescriptortype(upb_fielddef *f, int type) {
  825. assert(!upb_fielddef_isfrozen(f));
  826. switch (type) {
  827. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  828. upb_fielddef_settype(f, UPB_TYPE_DOUBLE);
  829. break;
  830. case UPB_DESCRIPTOR_TYPE_FLOAT:
  831. upb_fielddef_settype(f, UPB_TYPE_FLOAT);
  832. break;
  833. case UPB_DESCRIPTOR_TYPE_INT64:
  834. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  835. case UPB_DESCRIPTOR_TYPE_SINT64:
  836. upb_fielddef_settype(f, UPB_TYPE_INT64);
  837. break;
  838. case UPB_DESCRIPTOR_TYPE_UINT64:
  839. case UPB_DESCRIPTOR_TYPE_FIXED64:
  840. upb_fielddef_settype(f, UPB_TYPE_UINT64);
  841. break;
  842. case UPB_DESCRIPTOR_TYPE_INT32:
  843. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  844. case UPB_DESCRIPTOR_TYPE_SINT32:
  845. upb_fielddef_settype(f, UPB_TYPE_INT32);
  846. break;
  847. case UPB_DESCRIPTOR_TYPE_UINT32:
  848. case UPB_DESCRIPTOR_TYPE_FIXED32:
  849. upb_fielddef_settype(f, UPB_TYPE_UINT32);
  850. break;
  851. case UPB_DESCRIPTOR_TYPE_BOOL:
  852. upb_fielddef_settype(f, UPB_TYPE_BOOL);
  853. break;
  854. case UPB_DESCRIPTOR_TYPE_STRING:
  855. upb_fielddef_settype(f, UPB_TYPE_STRING);
  856. break;
  857. case UPB_DESCRIPTOR_TYPE_BYTES:
  858. upb_fielddef_settype(f, UPB_TYPE_BYTES);
  859. break;
  860. case UPB_DESCRIPTOR_TYPE_GROUP:
  861. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  862. upb_fielddef_settype(f, UPB_TYPE_MESSAGE);
  863. break;
  864. case UPB_DESCRIPTOR_TYPE_ENUM:
  865. upb_fielddef_settype(f, UPB_TYPE_ENUM);
  866. break;
  867. default: assert(false);
  868. }
  869. if (type == UPB_DESCRIPTOR_TYPE_FIXED64 ||
  870. type == UPB_DESCRIPTOR_TYPE_FIXED32 ||
  871. type == UPB_DESCRIPTOR_TYPE_SFIXED64 ||
  872. type == UPB_DESCRIPTOR_TYPE_SFIXED32) {
  873. upb_fielddef_setintfmt(f, UPB_INTFMT_FIXED);
  874. } else if (type == UPB_DESCRIPTOR_TYPE_SINT64 ||
  875. type == UPB_DESCRIPTOR_TYPE_SINT32) {
  876. upb_fielddef_setintfmt(f, UPB_INTFMT_ZIGZAG);
  877. } else {
  878. upb_fielddef_setintfmt(f, UPB_INTFMT_VARIABLE);
  879. }
  880. upb_fielddef_settagdelim(f, type == UPB_DESCRIPTOR_TYPE_GROUP);
  881. }
  882. upb_descriptortype_t upb_fielddef_descriptortype(const upb_fielddef *f) {
  883. switch (upb_fielddef_type(f)) {
  884. case UPB_TYPE_FLOAT: return UPB_DESCRIPTOR_TYPE_FLOAT;
  885. case UPB_TYPE_DOUBLE: return UPB_DESCRIPTOR_TYPE_DOUBLE;
  886. case UPB_TYPE_BOOL: return UPB_DESCRIPTOR_TYPE_BOOL;
  887. case UPB_TYPE_STRING: return UPB_DESCRIPTOR_TYPE_STRING;
  888. case UPB_TYPE_BYTES: return UPB_DESCRIPTOR_TYPE_BYTES;
  889. case UPB_TYPE_ENUM: return UPB_DESCRIPTOR_TYPE_ENUM;
  890. case UPB_TYPE_INT32:
  891. switch (upb_fielddef_intfmt(f)) {
  892. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_INT32;
  893. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_SFIXED32;
  894. case UPB_INTFMT_ZIGZAG: return UPB_DESCRIPTOR_TYPE_SINT32;
  895. }
  896. case UPB_TYPE_INT64:
  897. switch (upb_fielddef_intfmt(f)) {
  898. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_INT64;
  899. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_SFIXED64;
  900. case UPB_INTFMT_ZIGZAG: return UPB_DESCRIPTOR_TYPE_SINT64;
  901. }
  902. case UPB_TYPE_UINT32:
  903. switch (upb_fielddef_intfmt(f)) {
  904. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_UINT32;
  905. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_FIXED32;
  906. case UPB_INTFMT_ZIGZAG: return -1;
  907. }
  908. case UPB_TYPE_UINT64:
  909. switch (upb_fielddef_intfmt(f)) {
  910. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_UINT64;
  911. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_FIXED64;
  912. case UPB_INTFMT_ZIGZAG: return -1;
  913. }
  914. case UPB_TYPE_MESSAGE:
  915. return upb_fielddef_istagdelim(f) ?
  916. UPB_DESCRIPTOR_TYPE_GROUP : UPB_DESCRIPTOR_TYPE_MESSAGE;
  917. }
  918. return 0;
  919. }
  920. void upb_fielddef_setisextension(upb_fielddef *f, bool is_extension) {
  921. assert(!upb_fielddef_isfrozen(f));
  922. f->is_extension_ = is_extension;
  923. }
  924. void upb_fielddef_setlazy(upb_fielddef *f, bool lazy) {
  925. assert(!upb_fielddef_isfrozen(f));
  926. f->lazy_ = lazy;
  927. }
  928. void upb_fielddef_setpacked(upb_fielddef *f, bool packed) {
  929. assert(!upb_fielddef_isfrozen(f));
  930. f->packed_ = packed;
  931. }
  932. void upb_fielddef_setlabel(upb_fielddef *f, upb_label_t label) {
  933. assert(!upb_fielddef_isfrozen(f));
  934. assert(upb_fielddef_checklabel(label));
  935. f->label_ = label;
  936. }
  937. void upb_fielddef_setintfmt(upb_fielddef *f, upb_intfmt_t fmt) {
  938. assert(!upb_fielddef_isfrozen(f));
  939. assert(upb_fielddef_checkintfmt(fmt));
  940. f->intfmt = fmt;
  941. }
  942. void upb_fielddef_settagdelim(upb_fielddef *f, bool tag_delim) {
  943. assert(!upb_fielddef_isfrozen(f));
  944. f->tagdelim = tag_delim;
  945. f->tagdelim = tag_delim;
  946. }
  947. static bool checksetdefault(upb_fielddef *f, upb_fieldtype_t type) {
  948. if (!f->type_is_set_ || upb_fielddef_isfrozen(f) ||
  949. upb_fielddef_type(f) != type) {
  950. assert(false);
  951. return false;
  952. }
  953. if (f->default_is_string) {
  954. str_t *s = f->defaultval.bytes;
  955. assert(s || type == UPB_TYPE_ENUM);
  956. if (s) freestr(s);
  957. }
  958. f->default_is_string = false;
  959. return true;
  960. }
  961. void upb_fielddef_setdefaultint64(upb_fielddef *f, int64_t value) {
  962. if (checksetdefault(f, UPB_TYPE_INT64))
  963. f->defaultval.sint = value;
  964. }
  965. void upb_fielddef_setdefaultint32(upb_fielddef *f, int32_t value) {
  966. if ((upb_fielddef_type(f) == UPB_TYPE_ENUM &&
  967. checksetdefault(f, UPB_TYPE_ENUM)) ||
  968. checksetdefault(f, UPB_TYPE_INT32)) {
  969. f->defaultval.sint = value;
  970. }
  971. }
  972. void upb_fielddef_setdefaultuint64(upb_fielddef *f, uint64_t value) {
  973. if (checksetdefault(f, UPB_TYPE_UINT64))
  974. f->defaultval.uint = value;
  975. }
  976. void upb_fielddef_setdefaultuint32(upb_fielddef *f, uint32_t value) {
  977. if (checksetdefault(f, UPB_TYPE_UINT32))
  978. f->defaultval.uint = value;
  979. }
  980. void upb_fielddef_setdefaultbool(upb_fielddef *f, bool value) {
  981. if (checksetdefault(f, UPB_TYPE_BOOL))
  982. f->defaultval.uint = value;
  983. }
  984. void upb_fielddef_setdefaultfloat(upb_fielddef *f, float value) {
  985. if (checksetdefault(f, UPB_TYPE_FLOAT))
  986. f->defaultval.flt = value;
  987. }
  988. void upb_fielddef_setdefaultdouble(upb_fielddef *f, double value) {
  989. if (checksetdefault(f, UPB_TYPE_DOUBLE))
  990. f->defaultval.dbl = value;
  991. }
  992. bool upb_fielddef_setdefaultstr(upb_fielddef *f, const void *str, size_t len,
  993. upb_status *s) {
  994. assert(upb_fielddef_isstring(f) || f->type_ == UPB_TYPE_ENUM);
  995. if (f->type_ == UPB_TYPE_ENUM && !upb_isident(str, len, false, s))
  996. return false;
  997. if (f->default_is_string) {
  998. str_t *s = f->defaultval.bytes;
  999. assert(s || f->type_ == UPB_TYPE_ENUM);
  1000. if (s) freestr(s);
  1001. } else {
  1002. assert(f->type_ == UPB_TYPE_ENUM);
  1003. }
  1004. str_t *str2 = newstr(str, len);
  1005. f->defaultval.bytes = str2;
  1006. f->default_is_string = true;
  1007. return true;
  1008. }
  1009. void upb_fielddef_setdefaultcstr(upb_fielddef *f, const char *str,
  1010. upb_status *s) {
  1011. assert(f->type_is_set_);
  1012. upb_fielddef_setdefaultstr(f, str, str ? strlen(str) : 0, s);
  1013. }
  1014. bool upb_fielddef_enumhasdefaultint32(const upb_fielddef *f) {
  1015. assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  1016. int32_t val;
  1017. return enumdefaultint32(f, &val);
  1018. }
  1019. bool upb_fielddef_enumhasdefaultstr(const upb_fielddef *f) {
  1020. assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  1021. return enumdefaultstr(f) != NULL;
  1022. }
  1023. static bool upb_subdef_typecheck(upb_fielddef *f, const upb_def *subdef,
  1024. upb_status *s) {
  1025. if (f->type_ == UPB_TYPE_MESSAGE) {
  1026. if (upb_dyncast_msgdef(subdef)) return true;
  1027. upb_status_seterrmsg(s, "invalid subdef type for this submessage field");
  1028. return false;
  1029. } else if (f->type_ == UPB_TYPE_ENUM) {
  1030. if (upb_dyncast_enumdef(subdef)) return true;
  1031. upb_status_seterrmsg(s, "invalid subdef type for this enum field");
  1032. return false;
  1033. } else {
  1034. upb_status_seterrmsg(s, "only message and enum fields can have a subdef");
  1035. return false;
  1036. }
  1037. }
  1038. static void release_subdef(upb_fielddef *f) {
  1039. if (f->subdef_is_symbolic) {
  1040. free(f->sub.name);
  1041. } else if (f->sub.def) {
  1042. upb_unref2(f->sub.def, f);
  1043. }
  1044. }
  1045. bool upb_fielddef_setsubdef(upb_fielddef *f, const upb_def *subdef,
  1046. upb_status *s) {
  1047. assert(!upb_fielddef_isfrozen(f));
  1048. assert(upb_fielddef_hassubdef(f));
  1049. if (subdef && !upb_subdef_typecheck(f, subdef, s)) return false;
  1050. release_subdef(f);
  1051. f->sub.def = subdef;
  1052. f->subdef_is_symbolic = false;
  1053. if (f->sub.def) upb_ref2(f->sub.def, f);
  1054. return true;
  1055. }
  1056. bool upb_fielddef_setmsgsubdef(upb_fielddef *f, const upb_msgdef *subdef,
  1057. upb_status *s) {
  1058. return upb_fielddef_setsubdef(f, UPB_UPCAST(subdef), s);
  1059. }
  1060. bool upb_fielddef_setenumsubdef(upb_fielddef *f, const upb_enumdef *subdef,
  1061. upb_status *s) {
  1062. return upb_fielddef_setsubdef(f, UPB_UPCAST(subdef), s);
  1063. }
  1064. bool upb_fielddef_setsubdefname(upb_fielddef *f, const char *name,
  1065. upb_status *s) {
  1066. assert(!upb_fielddef_isfrozen(f));
  1067. if (!upb_fielddef_hassubdef(f)) {
  1068. upb_status_seterrmsg(s, "field type does not accept a subdef");
  1069. return false;
  1070. }
  1071. // TODO: validate name (upb_isident() doesn't quite work atm because this name
  1072. // may have a leading ".").
  1073. release_subdef(f);
  1074. f->sub.name = upb_strdup(name);
  1075. f->subdef_is_symbolic = true;
  1076. return true;
  1077. }
  1078. bool upb_fielddef_issubmsg(const upb_fielddef *f) {
  1079. return upb_fielddef_type(f) == UPB_TYPE_MESSAGE;
  1080. }
  1081. bool upb_fielddef_isstring(const upb_fielddef *f) {
  1082. return upb_fielddef_type(f) == UPB_TYPE_STRING ||
  1083. upb_fielddef_type(f) == UPB_TYPE_BYTES;
  1084. }
  1085. bool upb_fielddef_isseq(const upb_fielddef *f) {
  1086. return upb_fielddef_label(f) == UPB_LABEL_REPEATED;
  1087. }
  1088. bool upb_fielddef_isprimitive(const upb_fielddef *f) {
  1089. return !upb_fielddef_isstring(f) && !upb_fielddef_issubmsg(f);
  1090. }
  1091. bool upb_fielddef_ismap(const upb_fielddef *f) {
  1092. return upb_fielddef_isseq(f) && upb_fielddef_issubmsg(f) &&
  1093. upb_msgdef_mapentry(upb_fielddef_msgsubdef(f));
  1094. }
  1095. bool upb_fielddef_hassubdef(const upb_fielddef *f) {
  1096. return upb_fielddef_issubmsg(f) || upb_fielddef_type(f) == UPB_TYPE_ENUM;
  1097. }
  1098. static bool between(int32_t x, int32_t low, int32_t high) {
  1099. return x >= low && x <= high;
  1100. }
  1101. bool upb_fielddef_checklabel(int32_t label) { return between(label, 1, 3); }
  1102. bool upb_fielddef_checktype(int32_t type) { return between(type, 1, 11); }
  1103. bool upb_fielddef_checkintfmt(int32_t fmt) { return between(fmt, 1, 3); }
  1104. bool upb_fielddef_checkdescriptortype(int32_t type) {
  1105. return between(type, 1, 18);
  1106. }
  1107. /* upb_msgdef *****************************************************************/
  1108. static void visitmsg(const upb_refcounted *r, upb_refcounted_visit *visit,
  1109. void *closure) {
  1110. const upb_msgdef *m = (const upb_msgdef*)r;
  1111. upb_msg_field_iter i;
  1112. for(upb_msg_field_begin(&i, m);
  1113. !upb_msg_field_done(&i);
  1114. upb_msg_field_next(&i)) {
  1115. upb_fielddef *f = upb_msg_iter_field(&i);
  1116. visit(r, UPB_UPCAST2(f), closure);
  1117. }
  1118. upb_msg_oneof_iter o;
  1119. for(upb_msg_oneof_begin(&o, m);
  1120. !upb_msg_oneof_done(&o);
  1121. upb_msg_oneof_next(&o)) {
  1122. upb_oneofdef *f = upb_msg_iter_oneof(&o);
  1123. visit(r, UPB_UPCAST2(f), closure);
  1124. }
  1125. }
  1126. static void freemsg(upb_refcounted *r) {
  1127. upb_msgdef *m = (upb_msgdef*)r;
  1128. upb_strtable_uninit(&m->ntoo);
  1129. upb_strtable_uninit(&m->ntof);
  1130. upb_inttable_uninit(&m->itof);
  1131. upb_def_uninit(UPB_UPCAST(m));
  1132. free(m);
  1133. }
  1134. upb_msgdef *upb_msgdef_new(const void *owner) {
  1135. static const struct upb_refcounted_vtbl vtbl = {visitmsg, freemsg};
  1136. upb_msgdef *m = malloc(sizeof(*m));
  1137. if (!m) return NULL;
  1138. if (!upb_def_init(UPB_UPCAST(m), UPB_DEF_MSG, &vtbl, owner)) goto err2;
  1139. if (!upb_inttable_init(&m->itof, UPB_CTYPE_PTR)) goto err3;
  1140. if (!upb_strtable_init(&m->ntof, UPB_CTYPE_PTR)) goto err2;
  1141. if (!upb_strtable_init(&m->ntoo, UPB_CTYPE_PTR)) goto err1;
  1142. m->map_entry = false;
  1143. return m;
  1144. err1:
  1145. upb_strtable_uninit(&m->ntof);
  1146. err2:
  1147. upb_inttable_uninit(&m->itof);
  1148. err3:
  1149. free(m);
  1150. return NULL;
  1151. }
  1152. upb_msgdef *upb_msgdef_dup(const upb_msgdef *m, const void *owner) {
  1153. upb_msgdef *newm = upb_msgdef_new(owner);
  1154. if (!newm) return NULL;
  1155. bool ok = upb_def_setfullname(UPB_UPCAST(newm),
  1156. upb_def_fullname(UPB_UPCAST(m)), NULL);
  1157. newm->map_entry = m->map_entry;
  1158. UPB_ASSERT_VAR(ok, ok);
  1159. upb_msg_field_iter i;
  1160. for(upb_msg_field_begin(&i, m);
  1161. !upb_msg_field_done(&i);
  1162. upb_msg_field_next(&i)) {
  1163. upb_fielddef *f = upb_fielddef_dup(upb_msg_iter_field(&i), &f);
  1164. // Fields in oneofs are dup'd below.
  1165. if (upb_fielddef_containingoneof(f)) continue;
  1166. if (!f || !upb_msgdef_addfield(newm, f, &f, NULL)) {
  1167. upb_msgdef_unref(newm, owner);
  1168. return NULL;
  1169. }
  1170. }
  1171. upb_msg_oneof_iter o;
  1172. for(upb_msg_oneof_begin(&o, m);
  1173. !upb_msg_oneof_done(&o);
  1174. upb_msg_oneof_next(&o)) {
  1175. upb_oneofdef *f = upb_oneofdef_dup(upb_msg_iter_oneof(&o), &f);
  1176. if (!f || !upb_msgdef_addoneof(newm, f, &f, NULL)) {
  1177. upb_msgdef_unref(newm, owner);
  1178. return NULL;
  1179. }
  1180. }
  1181. return newm;
  1182. }
  1183. bool upb_msgdef_isfrozen(const upb_msgdef *m) {
  1184. return upb_def_isfrozen(UPB_UPCAST(m));
  1185. }
  1186. void upb_msgdef_ref(const upb_msgdef *m, const void *owner) {
  1187. upb_def_ref(UPB_UPCAST(m), owner);
  1188. }
  1189. void upb_msgdef_unref(const upb_msgdef *m, const void *owner) {
  1190. upb_def_unref(UPB_UPCAST(m), owner);
  1191. }
  1192. void upb_msgdef_donateref(
  1193. const upb_msgdef *m, const void *from, const void *to) {
  1194. upb_def_donateref(UPB_UPCAST(m), from, to);
  1195. }
  1196. void upb_msgdef_checkref(const upb_msgdef *m, const void *owner) {
  1197. upb_def_checkref(UPB_UPCAST(m), owner);
  1198. }
  1199. bool upb_msgdef_freeze(upb_msgdef *m, upb_status *status) {
  1200. upb_def *d = UPB_UPCAST(m);
  1201. return upb_def_freeze(&d, 1, status);
  1202. }
  1203. const char *upb_msgdef_fullname(const upb_msgdef *m) {
  1204. return upb_def_fullname(UPB_UPCAST(m));
  1205. }
  1206. bool upb_msgdef_setfullname(upb_msgdef *m, const char *fullname,
  1207. upb_status *s) {
  1208. return upb_def_setfullname(UPB_UPCAST(m), fullname, s);
  1209. }
  1210. // Helper: check that the field |f| is safe to add to msgdef |m|. Set an error
  1211. // on status |s| and return false if not.
  1212. static bool check_field_add(const upb_msgdef *m, const upb_fielddef *f,
  1213. upb_status *s) {
  1214. if (upb_fielddef_containingtype(f) != NULL) {
  1215. upb_status_seterrmsg(s, "fielddef already belongs to a message");
  1216. return false;
  1217. } else if (upb_fielddef_name(f) == NULL || upb_fielddef_number(f) == 0) {
  1218. upb_status_seterrmsg(s, "field name or number were not set");
  1219. return false;
  1220. } else if (upb_msgdef_ntofz(m, upb_fielddef_name(f)) ||
  1221. upb_msgdef_itof(m, upb_fielddef_number(f))) {
  1222. upb_status_seterrmsg(s, "duplicate field name or number for field");
  1223. return false;
  1224. }
  1225. return true;
  1226. }
  1227. static void add_field(upb_msgdef *m, upb_fielddef *f, const void *ref_donor) {
  1228. release_containingtype(f);
  1229. f->msg.def = m;
  1230. f->msg_is_symbolic = false;
  1231. upb_inttable_insert(&m->itof, upb_fielddef_number(f), upb_value_ptr(f));
  1232. upb_strtable_insert(&m->ntof, upb_fielddef_name(f), upb_value_ptr(f));
  1233. upb_ref2(f, m);
  1234. upb_ref2(m, f);
  1235. if (ref_donor) upb_fielddef_unref(f, ref_donor);
  1236. }
  1237. bool upb_msgdef_addfield(upb_msgdef *m, upb_fielddef *f, const void *ref_donor,
  1238. upb_status *s) {
  1239. // TODO: extensions need to have a separate namespace, because proto2 allows a
  1240. // top-level extension (ie. one not in any package) to have the same name as a
  1241. // field from the message.
  1242. //
  1243. // This also implies that there needs to be a separate lookup-by-name method
  1244. // for extensions. It seems desirable for iteration to return both extensions
  1245. // and non-extensions though.
  1246. //
  1247. // We also need to validate that the field number is in an extension range iff
  1248. // it is an extension.
  1249. // This method is idempotent. Check if |f| is already part of this msgdef and
  1250. // return immediately if so.
  1251. if (upb_fielddef_containingtype(f) == m) {
  1252. return true;
  1253. }
  1254. // Check constraints for all fields before performing any action.
  1255. if (!check_field_add(m, f, s)) {
  1256. return false;
  1257. } else if (upb_fielddef_containingoneof(f) != NULL) {
  1258. // Fields in a oneof can only be added by adding the oneof to the msgdef.
  1259. upb_status_seterrmsg(s, "fielddef is part of a oneof");
  1260. return false;
  1261. }
  1262. // Constraint checks ok, perform the action.
  1263. add_field(m, f, ref_donor);
  1264. return true;
  1265. }
  1266. bool upb_msgdef_addoneof(upb_msgdef *m, upb_oneofdef *o, const void *ref_donor,
  1267. upb_status *s) {
  1268. // Check various conditions that would prevent this oneof from being added.
  1269. if (upb_oneofdef_containingtype(o)) {
  1270. upb_status_seterrmsg(s, "oneofdef already belongs to a message");
  1271. return false;
  1272. } else if (upb_oneofdef_name(o) == NULL) {
  1273. upb_status_seterrmsg(s, "oneofdef name was not set");
  1274. return false;
  1275. } else if (upb_msgdef_ntooz(m, upb_oneofdef_name(o))) {
  1276. upb_status_seterrmsg(s, "duplicate oneof name");
  1277. return false;
  1278. }
  1279. // Check that all of the oneof's fields do not conflict with names or numbers
  1280. // of fields already in the message.
  1281. upb_oneof_iter it;
  1282. for (upb_oneof_begin(&it, o); !upb_oneof_done(&it); upb_oneof_next(&it)) {
  1283. const upb_fielddef *f = upb_oneof_iter_field(&it);
  1284. if (!check_field_add(m, f, s)) {
  1285. return false;
  1286. }
  1287. }
  1288. // Everything checks out -- commit now.
  1289. // Add oneof itself first.
  1290. o->parent = m;
  1291. upb_strtable_insert(&m->ntoo, upb_oneofdef_name(o), upb_value_ptr(o));
  1292. upb_ref2(o, m);
  1293. upb_ref2(m, o);
  1294. // Add each field of the oneof directly to the msgdef.
  1295. for (upb_oneof_begin(&it, o); !upb_oneof_done(&it); upb_oneof_next(&it)) {
  1296. upb_fielddef *f = upb_oneof_iter_field(&it);
  1297. add_field(m, f, NULL);
  1298. }
  1299. if (ref_donor) upb_oneofdef_unref(o, ref_donor);
  1300. return true;
  1301. }
  1302. const upb_fielddef *upb_msgdef_itof(const upb_msgdef *m, uint32_t i) {
  1303. upb_value val;
  1304. return upb_inttable_lookup32(&m->itof, i, &val) ?
  1305. upb_value_getptr(val) : NULL;
  1306. }
  1307. const upb_fielddef *upb_msgdef_ntof(const upb_msgdef *m, const char *name,
  1308. size_t len) {
  1309. upb_value val;
  1310. return upb_strtable_lookup2(&m->ntof, name, len, &val) ?
  1311. upb_value_getptr(val) : NULL;
  1312. }
  1313. const upb_oneofdef *upb_msgdef_ntoo(const upb_msgdef *m, const char *name,
  1314. size_t len) {
  1315. upb_value val;
  1316. return upb_strtable_lookup2(&m->ntoo, name, len, &val) ?
  1317. upb_value_getptr(val) : NULL;
  1318. }
  1319. int upb_msgdef_numfields(const upb_msgdef *m) {
  1320. return upb_strtable_count(&m->ntof);
  1321. }
  1322. int upb_msgdef_numoneofs(const upb_msgdef *m) {
  1323. return upb_strtable_count(&m->ntoo);
  1324. }
  1325. void upb_msgdef_setmapentry(upb_msgdef *m, bool map_entry) {
  1326. assert(!upb_msgdef_isfrozen(m));
  1327. m->map_entry = map_entry;
  1328. }
  1329. bool upb_msgdef_mapentry(const upb_msgdef *m) {
  1330. return m->map_entry;
  1331. }
  1332. void upb_msg_field_begin(upb_msg_field_iter *iter, const upb_msgdef *m) {
  1333. upb_inttable_begin(iter, &m->itof);
  1334. }
  1335. void upb_msg_field_next(upb_msg_field_iter *iter) { upb_inttable_next(iter); }
  1336. bool upb_msg_field_done(const upb_msg_field_iter *iter) {
  1337. return upb_inttable_done(iter);
  1338. }
  1339. upb_fielddef *upb_msg_iter_field(const upb_msg_field_iter *iter) {
  1340. return (upb_fielddef*)upb_value_getptr(upb_inttable_iter_value(iter));
  1341. }
  1342. void upb_msg_field_iter_setdone(upb_msg_field_iter *iter) {
  1343. upb_inttable_iter_setdone(iter);
  1344. }
  1345. void upb_msg_oneof_begin(upb_msg_oneof_iter *iter, const upb_msgdef *m) {
  1346. upb_strtable_begin(iter, &m->ntoo);
  1347. }
  1348. void upb_msg_oneof_next(upb_msg_oneof_iter *iter) { upb_strtable_next(iter); }
  1349. bool upb_msg_oneof_done(const upb_msg_oneof_iter *iter) {
  1350. return upb_strtable_done(iter);
  1351. }
  1352. upb_oneofdef *upb_msg_iter_oneof(const upb_msg_oneof_iter *iter) {
  1353. return (upb_oneofdef*)upb_value_getptr(upb_strtable_iter_value(iter));
  1354. }
  1355. void upb_msg_oneof_iter_setdone(upb_msg_oneof_iter *iter) {
  1356. upb_strtable_iter_setdone(iter);
  1357. }
  1358. /* upb_oneofdef ***************************************************************/
  1359. static void visitoneof(const upb_refcounted *r, upb_refcounted_visit *visit,
  1360. void *closure) {
  1361. const upb_oneofdef *o = (const upb_oneofdef*)r;
  1362. upb_oneof_iter i;
  1363. for (upb_oneof_begin(&i, o); !upb_oneof_done(&i); upb_oneof_next(&i)) {
  1364. const upb_fielddef *f = upb_oneof_iter_field(&i);
  1365. visit(r, UPB_UPCAST2(f), closure);
  1366. }
  1367. if (o->parent) {
  1368. visit(r, UPB_UPCAST2(o->parent), closure);
  1369. }
  1370. }
  1371. static void freeoneof(upb_refcounted *r) {
  1372. upb_oneofdef *o = (upb_oneofdef*)r;
  1373. upb_strtable_uninit(&o->ntof);
  1374. upb_inttable_uninit(&o->itof);
  1375. upb_def_uninit(UPB_UPCAST(o));
  1376. free(o);
  1377. }
  1378. upb_oneofdef *upb_oneofdef_new(const void *owner) {
  1379. static const struct upb_refcounted_vtbl vtbl = {visitoneof, freeoneof};
  1380. upb_oneofdef *o = malloc(sizeof(*o));
  1381. o->parent = NULL;
  1382. if (!o) return NULL;
  1383. if (!upb_def_init(UPB_UPCAST(o), UPB_DEF_ONEOF, &vtbl, owner)) goto err2;
  1384. if (!upb_inttable_init(&o->itof, UPB_CTYPE_PTR)) goto err2;
  1385. if (!upb_strtable_init(&o->ntof, UPB_CTYPE_PTR)) goto err1;
  1386. return o;
  1387. err1:
  1388. upb_inttable_uninit(&o->itof);
  1389. err2:
  1390. free(o);
  1391. return NULL;
  1392. }
  1393. upb_oneofdef *upb_oneofdef_dup(const upb_oneofdef *o, const void *owner) {
  1394. upb_oneofdef *newo = upb_oneofdef_new(owner);
  1395. if (!newo) return NULL;
  1396. bool ok = upb_def_setfullname(UPB_UPCAST(newo),
  1397. upb_def_fullname(UPB_UPCAST(o)), NULL);
  1398. UPB_ASSERT_VAR(ok, ok);
  1399. upb_oneof_iter i;
  1400. for (upb_oneof_begin(&i, o); !upb_oneof_done(&i); upb_oneof_next(&i)) {
  1401. upb_fielddef *f = upb_fielddef_dup(upb_oneof_iter_field(&i), &f);
  1402. if (!f || !upb_oneofdef_addfield(newo, f, &f, NULL)) {
  1403. upb_oneofdef_unref(newo, owner);
  1404. return NULL;
  1405. }
  1406. }
  1407. return newo;
  1408. }
  1409. bool upb_oneofdef_isfrozen(const upb_oneofdef *o) {
  1410. return upb_def_isfrozen(UPB_UPCAST(o));
  1411. }
  1412. void upb_oneofdef_ref(const upb_oneofdef *o, const void *owner) {
  1413. upb_def_ref(UPB_UPCAST(o), owner);
  1414. }
  1415. void upb_oneofdef_unref(const upb_oneofdef *o, const void *owner) {
  1416. upb_def_unref(UPB_UPCAST(o), owner);
  1417. }
  1418. void upb_oneofdef_donateref(const upb_oneofdef *o, const void *from,
  1419. const void *to) {
  1420. upb_def_donateref(UPB_UPCAST(o), from, to);
  1421. }
  1422. void upb_oneofdef_checkref(const upb_oneofdef *o, const void *owner) {
  1423. upb_def_checkref(UPB_UPCAST(o), owner);
  1424. }
  1425. const char *upb_oneofdef_name(const upb_oneofdef *o) {
  1426. return upb_def_fullname(UPB_UPCAST(o));
  1427. }
  1428. bool upb_oneofdef_setname(upb_oneofdef *o, const char *fullname,
  1429. upb_status *s) {
  1430. if (upb_oneofdef_containingtype(o)) {
  1431. upb_status_seterrmsg(s, "oneof already added to a message");
  1432. return false;
  1433. }
  1434. return upb_def_setfullname(UPB_UPCAST(o), fullname, s);
  1435. }
  1436. const upb_msgdef *upb_oneofdef_containingtype(const upb_oneofdef *o) {
  1437. return o->parent;
  1438. }
  1439. int upb_oneofdef_numfields(const upb_oneofdef *o) {
  1440. return upb_strtable_count(&o->ntof);
  1441. }
  1442. bool upb_oneofdef_addfield(upb_oneofdef *o, upb_fielddef *f,
  1443. const void *ref_donor,
  1444. upb_status *s) {
  1445. assert(!upb_oneofdef_isfrozen(o));
  1446. assert(!o->parent || !upb_msgdef_isfrozen(o->parent));
  1447. // This method is idempotent. Check if |f| is already part of this oneofdef
  1448. // and return immediately if so.
  1449. if (upb_fielddef_containingoneof(f) == o) {
  1450. return true;
  1451. }
  1452. // The field must have an OPTIONAL label.
  1453. if (upb_fielddef_label(f) != UPB_LABEL_OPTIONAL) {
  1454. upb_status_seterrmsg(s, "fields in oneof must have OPTIONAL label");
  1455. return false;
  1456. }
  1457. // Check that no field with this name or number exists already in the oneof.
  1458. // Also check that the field is not already part of a oneof.
  1459. if (upb_fielddef_name(f) == NULL || upb_fielddef_number(f) == 0) {
  1460. upb_status_seterrmsg(s, "field name or number were not set");
  1461. return false;
  1462. } else if (upb_oneofdef_itof(o, upb_fielddef_number(f)) ||
  1463. upb_oneofdef_ntofz(o, upb_fielddef_name(f))) {
  1464. upb_status_seterrmsg(s, "duplicate field name or number");
  1465. return false;
  1466. } else if (upb_fielddef_containingoneof(f) != NULL) {
  1467. upb_status_seterrmsg(s, "fielddef already belongs to a oneof");
  1468. return false;
  1469. }
  1470. // We allow adding a field to the oneof either if the field is not part of a
  1471. // msgdef, or if it is and we are also part of the same msgdef.
  1472. if (o->parent == NULL) {
  1473. // If we're not in a msgdef, the field cannot be either. Otherwise we would
  1474. // need to magically add this oneof to a msgdef to remain consistent, which
  1475. // is surprising behavior.
  1476. if (upb_fielddef_containingtype(f) != NULL) {
  1477. upb_status_seterrmsg(s, "fielddef already belongs to a message, but "
  1478. "oneof does not");
  1479. return false;
  1480. }
  1481. } else {
  1482. // If we're in a msgdef, the user can add fields that either aren't in any
  1483. // msgdef (in which case they're added to our msgdef) or already a part of
  1484. // our msgdef.
  1485. if (upb_fielddef_containingtype(f) != NULL &&
  1486. upb_fielddef_containingtype(f) != o->parent) {
  1487. upb_status_seterrmsg(s, "fielddef belongs to a different message "
  1488. "than oneof");
  1489. return false;
  1490. }
  1491. }
  1492. // Commit phase. First add the field to our parent msgdef, if any, because
  1493. // that may fail; then add the field to our own tables.
  1494. if (o->parent != NULL && upb_fielddef_containingtype(f) == NULL) {
  1495. if (!upb_msgdef_addfield((upb_msgdef*)o->parent, f, NULL, s)) {
  1496. return false;
  1497. }
  1498. }
  1499. release_containingtype(f);
  1500. f->oneof = o;
  1501. upb_inttable_insert(&o->itof, upb_fielddef_number(f), upb_value_ptr(f));
  1502. upb_strtable_insert(&o->ntof, upb_fielddef_name(f), upb_value_ptr(f));
  1503. upb_ref2(f, o);
  1504. upb_ref2(o, f);
  1505. if (ref_donor) upb_fielddef_unref(f, ref_donor);
  1506. return true;
  1507. }
  1508. const upb_fielddef *upb_oneofdef_ntof(const upb_oneofdef *o,
  1509. const char *name, size_t length) {
  1510. upb_value val;
  1511. return upb_strtable_lookup2(&o->ntof, name, length, &val) ?
  1512. upb_value_getptr(val) : NULL;
  1513. }
  1514. const upb_fielddef *upb_oneofdef_itof(const upb_oneofdef *o, uint32_t num) {
  1515. upb_value val;
  1516. return upb_inttable_lookup32(&o->itof, num, &val) ?
  1517. upb_value_getptr(val) : NULL;
  1518. }
  1519. void upb_oneof_begin(upb_oneof_iter *iter, const upb_oneofdef *o) {
  1520. upb_inttable_begin(iter, &o->itof);
  1521. }
  1522. void upb_oneof_next(upb_oneof_iter *iter) {
  1523. upb_inttable_next(iter);
  1524. }
  1525. bool upb_oneof_done(upb_oneof_iter *iter) {
  1526. return upb_inttable_done(iter);
  1527. }
  1528. upb_fielddef *upb_oneof_iter_field(const upb_oneof_iter *iter) {
  1529. return (upb_fielddef*)upb_value_getptr(upb_inttable_iter_value(iter));
  1530. }
  1531. void upb_oneof_iter_setdone(upb_oneof_iter *iter) {
  1532. upb_inttable_iter_setdone(iter);
  1533. }
  1534. /*
  1535. * upb - a minimalist implementation of protocol buffers.
  1536. *
  1537. * Copyright (c) 2014 Google Inc. See LICENSE for details.
  1538. * Author: Josh Haberman <jhaberman@gmail.com>
  1539. */
  1540. #include <stdlib.h>
  1541. #include <stdio.h>
  1542. #include <string.h>
  1543. typedef struct cleanup_ent {
  1544. upb_cleanup_func *cleanup;
  1545. void *ud;
  1546. struct cleanup_ent *next;
  1547. } cleanup_ent;
  1548. static void *seeded_alloc(void *ud, void *ptr, size_t oldsize, size_t size);
  1549. /* Default allocator **********************************************************/
  1550. // Just use realloc, keeping all allocated blocks in a linked list to destroy at
  1551. // the end.
  1552. typedef struct mem_block {
  1553. // List is doubly-linked, because in cases where realloc() moves an existing
  1554. // block, we need to be able to remove the old pointer from the list
  1555. // efficiently.
  1556. struct mem_block *prev, *next;
  1557. #ifndef NDEBUG
  1558. size_t size; // Doesn't include mem_block structure.
  1559. #endif
  1560. char data[];
  1561. } mem_block;
  1562. typedef struct {
  1563. mem_block *head;
  1564. } default_alloc_ud;
  1565. static void *default_alloc(void *_ud, void *ptr, size_t oldsize, size_t size) {
  1566. UPB_UNUSED(oldsize);
  1567. default_alloc_ud *ud = _ud;
  1568. mem_block *from = ptr ? (void*)((char*)ptr - sizeof(mem_block)) : NULL;
  1569. #ifndef NDEBUG
  1570. if (from) {
  1571. assert(oldsize <= from->size);
  1572. }
  1573. #endif
  1574. mem_block *block = realloc(from, size + sizeof(mem_block));
  1575. if (!block) return NULL;
  1576. #ifndef NDEBUG
  1577. block->size = size;
  1578. #endif
  1579. if (from) {
  1580. if (block != from) {
  1581. // The block was moved, so pointers in next and prev blocks must be
  1582. // updated to its new location.
  1583. if (block->next) block->next->prev = block;
  1584. if (block->prev) block->prev->next = block;
  1585. }
  1586. } else {
  1587. // Insert at head of linked list.
  1588. block->prev = NULL;
  1589. block->next = ud->head;
  1590. if (block->next) block->next->prev = block;
  1591. ud->head = block;
  1592. }
  1593. return &block->data;
  1594. }
  1595. static void default_alloc_cleanup(void *_ud) {
  1596. default_alloc_ud *ud = _ud;
  1597. mem_block *block = ud->head;
  1598. while (block) {
  1599. void *to_free = block;
  1600. block = block->next;
  1601. free(to_free);
  1602. }
  1603. }
  1604. /* Standard error functions ***************************************************/
  1605. static bool default_err(void *ud, const upb_status *status) {
  1606. UPB_UNUSED(ud);
  1607. fprintf(stderr, "upb error: %s\n", upb_status_errmsg(status));
  1608. return false;
  1609. }
  1610. static bool write_err_to(void *ud, const upb_status *status) {
  1611. upb_status *copy_to = ud;
  1612. upb_status_copy(copy_to, status);
  1613. return false;
  1614. }
  1615. /* upb_env ********************************************************************/
  1616. void upb_env_init(upb_env *e) {
  1617. e->ok_ = true;
  1618. e->bytes_allocated = 0;
  1619. e->cleanup_head = NULL;
  1620. default_alloc_ud *ud = (default_alloc_ud*)&e->default_alloc_ud;
  1621. ud->head = NULL;
  1622. // Set default functions.
  1623. upb_env_setallocfunc(e, default_alloc, ud);
  1624. upb_env_seterrorfunc(e, default_err, NULL);
  1625. }
  1626. void upb_env_uninit(upb_env *e) {
  1627. cleanup_ent *ent = e->cleanup_head;
  1628. while (ent) {
  1629. ent->cleanup(ent->ud);
  1630. ent = ent->next;
  1631. }
  1632. // Must do this after running cleanup functions, because this will delete
  1633. // the memory we store our cleanup entries in!
  1634. if (e->alloc == default_alloc) {
  1635. default_alloc_cleanup(e->alloc_ud);
  1636. }
  1637. }
  1638. UPB_FORCEINLINE void upb_env_setallocfunc(upb_env *e, upb_alloc_func *alloc,
  1639. void *ud) {
  1640. e->alloc = alloc;
  1641. e->alloc_ud = ud;
  1642. }
  1643. UPB_FORCEINLINE void upb_env_seterrorfunc(upb_env *e, upb_error_func *func,
  1644. void *ud) {
  1645. e->err = func;
  1646. e->err_ud = ud;
  1647. }
  1648. void upb_env_reporterrorsto(upb_env *e, upb_status *status) {
  1649. e->err = write_err_to;
  1650. e->err_ud = status;
  1651. }
  1652. bool upb_env_ok(const upb_env *e) {
  1653. return e->ok_;
  1654. }
  1655. bool upb_env_reporterror(upb_env *e, const upb_status *status) {
  1656. e->ok_ = false;
  1657. return e->err(e->err_ud, status);
  1658. }
  1659. bool upb_env_addcleanup(upb_env *e, upb_cleanup_func *func, void *ud) {
  1660. cleanup_ent *ent = upb_env_malloc(e, sizeof(cleanup_ent));
  1661. if (!ent) return false;
  1662. ent->cleanup = func;
  1663. ent->ud = ud;
  1664. ent->next = e->cleanup_head;
  1665. e->cleanup_head = ent;
  1666. return true;
  1667. }
  1668. void *upb_env_malloc(upb_env *e, size_t size) {
  1669. e->bytes_allocated += size;
  1670. if (e->alloc == seeded_alloc) {
  1671. // This is equivalent to the next branch, but allows inlining for a
  1672. // measurable perf benefit.
  1673. return seeded_alloc(e->alloc_ud, NULL, 0, size);
  1674. } else {
  1675. return e->alloc(e->alloc_ud, NULL, 0, size);
  1676. }
  1677. }
  1678. void *upb_env_realloc(upb_env *e, void *ptr, size_t oldsize, size_t size) {
  1679. assert(oldsize <= size);
  1680. char *ret = e->alloc(e->alloc_ud, ptr, oldsize, size);
  1681. #ifndef NDEBUG
  1682. // Overwrite non-preserved memory to ensure callers are passing the oldsize
  1683. // that they truly require.
  1684. memset(ret + oldsize, 0xff, size - oldsize);
  1685. #endif
  1686. return ret;
  1687. }
  1688. size_t upb_env_bytesallocated(const upb_env *e) {
  1689. return e->bytes_allocated;
  1690. }
  1691. /* upb_seededalloc ************************************************************/
  1692. // Be conservative and choose 16 in case anyone is using SSE.
  1693. static const size_t maxalign = 16;
  1694. static size_t align_up(size_t size) {
  1695. return ((size + maxalign - 1) / maxalign) * maxalign;
  1696. }
  1697. UPB_FORCEINLINE static void *seeded_alloc(void *ud, void *ptr, size_t oldsize,
  1698. size_t size) {
  1699. UPB_UNUSED(ptr);
  1700. upb_seededalloc *a = ud;
  1701. size = align_up(size);
  1702. assert(a->mem_limit >= a->mem_ptr);
  1703. if (oldsize == 0 && size <= (size_t)(a->mem_limit - a->mem_ptr)) {
  1704. // Fast path: we can satisfy from the initial allocation.
  1705. void *ret = a->mem_ptr;
  1706. a->mem_ptr += size;
  1707. return ret;
  1708. } else {
  1709. // Slow path: fallback to other allocator.
  1710. a->need_cleanup = true;
  1711. // Is `ptr` part of the user-provided initial block? Don't pass it to the
  1712. // default allocator if so; otherwise, it may try to realloc() the block.
  1713. char *chptr = ptr;
  1714. if (chptr >= a->mem_base && chptr < a->mem_limit) {
  1715. return a->alloc(a->alloc_ud, NULL, 0, size);
  1716. } else {
  1717. return a->alloc(a->alloc_ud, ptr, oldsize, size);
  1718. }
  1719. }
  1720. }
  1721. void upb_seededalloc_init(upb_seededalloc *a, void *mem, size_t len) {
  1722. a->mem_base = mem;
  1723. a->mem_ptr = mem;
  1724. a->mem_limit = (char*)mem + len;
  1725. a->need_cleanup = false;
  1726. a->returned_allocfunc = false;
  1727. default_alloc_ud *ud = (default_alloc_ud*)&a->default_alloc_ud;
  1728. ud->head = NULL;
  1729. upb_seededalloc_setfallbackalloc(a, default_alloc, ud);
  1730. }
  1731. void upb_seededalloc_uninit(upb_seededalloc *a) {
  1732. if (a->alloc == default_alloc && a->need_cleanup) {
  1733. default_alloc_cleanup(a->alloc_ud);
  1734. }
  1735. }
  1736. UPB_FORCEINLINE void upb_seededalloc_setfallbackalloc(upb_seededalloc *a,
  1737. upb_alloc_func *alloc,
  1738. void *ud) {
  1739. assert(!a->returned_allocfunc);
  1740. a->alloc = alloc;
  1741. a->alloc_ud = ud;
  1742. }
  1743. upb_alloc_func *upb_seededalloc_getallocfunc(upb_seededalloc *a) {
  1744. a->returned_allocfunc = true;
  1745. return seeded_alloc;
  1746. }
  1747. /*
  1748. * upb - a minimalist implementation of protocol buffers.
  1749. *
  1750. * Copyright (c) 2011-2012 Google Inc. See LICENSE for details.
  1751. * Author: Josh Haberman <jhaberman@gmail.com>
  1752. *
  1753. * TODO(haberman): it's unclear whether a lot of the consistency checks should
  1754. * assert() or return false.
  1755. */
  1756. #include <stdlib.h>
  1757. #include <string.h>
  1758. // Defined for the sole purpose of having a unique pointer value for
  1759. // UPB_NO_CLOSURE.
  1760. char _upb_noclosure;
  1761. static void freehandlers(upb_refcounted *r) {
  1762. upb_handlers *h = (upb_handlers*)r;
  1763. upb_inttable_iter i;
  1764. upb_inttable_begin(&i, &h->cleanup_);
  1765. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  1766. void *val = (void*)upb_inttable_iter_key(&i);
  1767. upb_value func_val = upb_inttable_iter_value(&i);
  1768. upb_handlerfree *func = upb_value_getfptr(func_val);
  1769. func(val);
  1770. }
  1771. upb_inttable_uninit(&h->cleanup_);
  1772. upb_msgdef_unref(h->msg, h);
  1773. free(h->sub);
  1774. free(h);
  1775. }
  1776. static void visithandlers(const upb_refcounted *r, upb_refcounted_visit *visit,
  1777. void *closure) {
  1778. const upb_handlers *h = (const upb_handlers*)r;
  1779. upb_msg_field_iter i;
  1780. for(upb_msg_field_begin(&i, h->msg);
  1781. !upb_msg_field_done(&i);
  1782. upb_msg_field_next(&i)) {
  1783. upb_fielddef *f = upb_msg_iter_field(&i);
  1784. if (!upb_fielddef_issubmsg(f)) continue;
  1785. const upb_handlers *sub = upb_handlers_getsubhandlers(h, f);
  1786. if (sub) visit(r, UPB_UPCAST(sub), closure);
  1787. }
  1788. }
  1789. static const struct upb_refcounted_vtbl vtbl = {visithandlers, freehandlers};
  1790. typedef struct {
  1791. upb_inttable tab; // maps upb_msgdef* -> upb_handlers*.
  1792. upb_handlers_callback *callback;
  1793. const void *closure;
  1794. } dfs_state;
  1795. // TODO(haberman): discard upb_handlers* objects that do not actually have any
  1796. // handlers set and cannot reach any upb_handlers* object that does. This is
  1797. // slightly tricky to do correctly.
  1798. static upb_handlers *newformsg(const upb_msgdef *m, const void *owner,
  1799. dfs_state *s) {
  1800. upb_handlers *h = upb_handlers_new(m, owner);
  1801. if (!h) return NULL;
  1802. if (!upb_inttable_insertptr(&s->tab, m, upb_value_ptr(h))) goto oom;
  1803. s->callback(s->closure, h);
  1804. // For each submessage field, get or create a handlers object and set it as
  1805. // the subhandlers.
  1806. upb_msg_field_iter i;
  1807. for(upb_msg_field_begin(&i, m);
  1808. !upb_msg_field_done(&i);
  1809. upb_msg_field_next(&i)) {
  1810. upb_fielddef *f = upb_msg_iter_field(&i);
  1811. if (!upb_fielddef_issubmsg(f)) continue;
  1812. const upb_msgdef *subdef = upb_downcast_msgdef(upb_fielddef_subdef(f));
  1813. upb_value subm_ent;
  1814. if (upb_inttable_lookupptr(&s->tab, subdef, &subm_ent)) {
  1815. upb_handlers_setsubhandlers(h, f, upb_value_getptr(subm_ent));
  1816. } else {
  1817. upb_handlers *sub_mh = newformsg(subdef, &sub_mh, s);
  1818. if (!sub_mh) goto oom;
  1819. upb_handlers_setsubhandlers(h, f, sub_mh);
  1820. upb_handlers_unref(sub_mh, &sub_mh);
  1821. }
  1822. }
  1823. return h;
  1824. oom:
  1825. upb_handlers_unref(h, owner);
  1826. return NULL;
  1827. }
  1828. // Given a selector for a STARTSUBMSG handler, resolves to a pointer to the
  1829. // subhandlers for this submessage field.
  1830. #define SUBH(h, selector) (h->sub[selector])
  1831. // The selector for a submessage field is the field index.
  1832. #define SUBH_F(h, f) SUBH(h, f->index_)
  1833. static int32_t trygetsel(upb_handlers *h, const upb_fielddef *f,
  1834. upb_handlertype_t type) {
  1835. upb_selector_t sel;
  1836. assert(!upb_handlers_isfrozen(h));
  1837. if (upb_handlers_msgdef(h) != upb_fielddef_containingtype(f)) {
  1838. upb_status_seterrf(
  1839. &h->status_, "type mismatch: field %s does not belong to message %s",
  1840. upb_fielddef_name(f), upb_msgdef_fullname(upb_handlers_msgdef(h)));
  1841. return -1;
  1842. }
  1843. if (!upb_handlers_getselector(f, type, &sel)) {
  1844. upb_status_seterrf(
  1845. &h->status_,
  1846. "type mismatch: cannot register handler type %d for field %s",
  1847. type, upb_fielddef_name(f));
  1848. return -1;
  1849. }
  1850. return sel;
  1851. }
  1852. static upb_selector_t handlers_getsel(upb_handlers *h, const upb_fielddef *f,
  1853. upb_handlertype_t type) {
  1854. int32_t sel = trygetsel(h, f, type);
  1855. assert(sel >= 0);
  1856. return sel;
  1857. }
  1858. static const void **returntype(upb_handlers *h, const upb_fielddef *f,
  1859. upb_handlertype_t type) {
  1860. return &h->table[handlers_getsel(h, f, type)].attr.return_closure_type_;
  1861. }
  1862. static bool doset(upb_handlers *h, int32_t sel, const upb_fielddef *f,
  1863. upb_handlertype_t type, upb_func *func,
  1864. upb_handlerattr *attr) {
  1865. assert(!upb_handlers_isfrozen(h));
  1866. if (sel < 0) {
  1867. upb_status_seterrmsg(&h->status_,
  1868. "incorrect handler type for this field.");
  1869. return false;
  1870. }
  1871. if (h->table[sel].func) {
  1872. upb_status_seterrmsg(&h->status_,
  1873. "cannot change handler once it has been set.");
  1874. return false;
  1875. }
  1876. upb_handlerattr set_attr = UPB_HANDLERATTR_INITIALIZER;
  1877. if (attr) {
  1878. set_attr = *attr;
  1879. }
  1880. // Check that the given closure type matches the closure type that has been
  1881. // established for this context (if any).
  1882. const void *closure_type = upb_handlerattr_closuretype(&set_attr);
  1883. const void **context_closure_type;
  1884. if (type == UPB_HANDLER_STRING) {
  1885. context_closure_type = returntype(h, f, UPB_HANDLER_STARTSTR);
  1886. } else if (f && upb_fielddef_isseq(f) &&
  1887. type != UPB_HANDLER_STARTSEQ &&
  1888. type != UPB_HANDLER_ENDSEQ) {
  1889. context_closure_type = returntype(h, f, UPB_HANDLER_STARTSEQ);
  1890. } else {
  1891. context_closure_type = &h->top_closure_type;
  1892. }
  1893. if (closure_type && *context_closure_type &&
  1894. closure_type != *context_closure_type) {
  1895. // TODO(haberman): better message for debugging.
  1896. if (f) {
  1897. upb_status_seterrf(&h->status_,
  1898. "closure type does not match for field %s",
  1899. upb_fielddef_name(f));
  1900. } else {
  1901. upb_status_seterrmsg(
  1902. &h->status_, "closure type does not match for message-level handler");
  1903. }
  1904. return false;
  1905. }
  1906. if (closure_type)
  1907. *context_closure_type = closure_type;
  1908. // If this is a STARTSEQ or STARTSTR handler, check that the returned pointer
  1909. // matches any pre-existing expectations about what type is expected.
  1910. if (type == UPB_HANDLER_STARTSEQ || type == UPB_HANDLER_STARTSTR) {
  1911. const void *return_type = upb_handlerattr_returnclosuretype(&set_attr);
  1912. const void *table_return_type =
  1913. upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  1914. if (return_type && table_return_type && return_type != table_return_type) {
  1915. upb_status_seterrmsg(&h->status_, "closure return type does not match");
  1916. return false;
  1917. }
  1918. if (table_return_type && !return_type)
  1919. upb_handlerattr_setreturnclosuretype(&set_attr, table_return_type);
  1920. }
  1921. h->table[sel].func = (upb_func*)func;
  1922. h->table[sel].attr = set_attr;
  1923. return true;
  1924. }
  1925. // Returns the effective closure type for this handler (which will propagate
  1926. // from outer frames if this frame has no START* handler). Not implemented for
  1927. // UPB_HANDLER_STRING at the moment since this is not needed. Returns NULL is
  1928. // the effective closure type is unspecified (either no handler was registered
  1929. // to specify it or the handler that was registered did not specify the closure
  1930. // type).
  1931. const void *effective_closure_type(upb_handlers *h, const upb_fielddef *f,
  1932. upb_handlertype_t type) {
  1933. assert(type != UPB_HANDLER_STRING);
  1934. const void *ret = h->top_closure_type;
  1935. upb_selector_t sel;
  1936. if (upb_fielddef_isseq(f) &&
  1937. type != UPB_HANDLER_STARTSEQ &&
  1938. type != UPB_HANDLER_ENDSEQ &&
  1939. h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSEQ)].func) {
  1940. ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  1941. }
  1942. if (type == UPB_HANDLER_STRING &&
  1943. h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSTR)].func) {
  1944. ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  1945. }
  1946. // The effective type of the submessage; not used yet.
  1947. // if (type == SUBMESSAGE &&
  1948. // h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSUBMSG)].func) {
  1949. // ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  1950. // }
  1951. return ret;
  1952. }
  1953. // Checks whether the START* handler specified by f & type is missing even
  1954. // though it is required to convert the established type of an outer frame
  1955. // ("closure_type") into the established type of an inner frame (represented in
  1956. // the return closure type of this handler's attr.
  1957. bool checkstart(upb_handlers *h, const upb_fielddef *f, upb_handlertype_t type,
  1958. upb_status *status) {
  1959. upb_selector_t sel = handlers_getsel(h, f, type);
  1960. if (h->table[sel].func) return true;
  1961. const void *closure_type = effective_closure_type(h, f, type);
  1962. const upb_handlerattr *attr = &h->table[sel].attr;
  1963. const void *return_closure_type = upb_handlerattr_returnclosuretype(attr);
  1964. if (closure_type && return_closure_type &&
  1965. closure_type != return_closure_type) {
  1966. upb_status_seterrf(status,
  1967. "expected start handler to return sub type for field %f",
  1968. upb_fielddef_name(f));
  1969. return false;
  1970. }
  1971. return true;
  1972. }
  1973. /* Public interface ***********************************************************/
  1974. bool upb_handlers_isfrozen(const upb_handlers *h) {
  1975. return upb_refcounted_isfrozen(UPB_UPCAST(h));
  1976. }
  1977. void upb_handlers_ref(const upb_handlers *h, const void *owner) {
  1978. upb_refcounted_ref(UPB_UPCAST(h), owner);
  1979. }
  1980. void upb_handlers_unref(const upb_handlers *h, const void *owner) {
  1981. upb_refcounted_unref(UPB_UPCAST(h), owner);
  1982. }
  1983. void upb_handlers_donateref(
  1984. const upb_handlers *h, const void *from, const void *to) {
  1985. upb_refcounted_donateref(UPB_UPCAST(h), from, to);
  1986. }
  1987. void upb_handlers_checkref(const upb_handlers *h, const void *owner) {
  1988. upb_refcounted_checkref(UPB_UPCAST(h), owner);
  1989. }
  1990. upb_handlers *upb_handlers_new(const upb_msgdef *md, const void *owner) {
  1991. assert(upb_msgdef_isfrozen(md));
  1992. int extra = sizeof(upb_handlers_tabent) * (md->selector_count - 1);
  1993. upb_handlers *h = calloc(sizeof(*h) + extra, 1);
  1994. if (!h) return NULL;
  1995. h->msg = md;
  1996. upb_msgdef_ref(h->msg, h);
  1997. upb_status_clear(&h->status_);
  1998. h->sub = calloc(md->submsg_field_count, sizeof(*h->sub));
  1999. if (!h->sub) goto oom;
  2000. if (!upb_refcounted_init(UPB_UPCAST(h), &vtbl, owner)) goto oom;
  2001. if (!upb_inttable_init(&h->cleanup_, UPB_CTYPE_FPTR)) goto oom;
  2002. // calloc() above initialized all handlers to NULL.
  2003. return h;
  2004. oom:
  2005. freehandlers(UPB_UPCAST(h));
  2006. return NULL;
  2007. }
  2008. const upb_handlers *upb_handlers_newfrozen(const upb_msgdef *m,
  2009. const void *owner,
  2010. upb_handlers_callback *callback,
  2011. const void *closure) {
  2012. dfs_state state;
  2013. state.callback = callback;
  2014. state.closure = closure;
  2015. if (!upb_inttable_init(&state.tab, UPB_CTYPE_PTR)) return NULL;
  2016. upb_handlers *ret = newformsg(m, owner, &state);
  2017. upb_inttable_uninit(&state.tab);
  2018. if (!ret) return NULL;
  2019. upb_refcounted *r = UPB_UPCAST(ret);
  2020. bool ok = upb_refcounted_freeze(&r, 1, NULL, UPB_MAX_HANDLER_DEPTH);
  2021. UPB_ASSERT_VAR(ok, ok);
  2022. return ret;
  2023. }
  2024. const upb_status *upb_handlers_status(upb_handlers *h) {
  2025. assert(!upb_handlers_isfrozen(h));
  2026. return &h->status_;
  2027. }
  2028. void upb_handlers_clearerr(upb_handlers *h) {
  2029. assert(!upb_handlers_isfrozen(h));
  2030. upb_status_clear(&h->status_);
  2031. }
  2032. #define SETTER(name, handlerctype, handlertype) \
  2033. bool upb_handlers_set ## name(upb_handlers *h, const upb_fielddef *f, \
  2034. handlerctype func, upb_handlerattr *attr) { \
  2035. int32_t sel = trygetsel(h, f, handlertype); \
  2036. return doset(h, sel, f, handlertype, (upb_func*)func, attr); \
  2037. }
  2038. SETTER(int32, upb_int32_handlerfunc*, UPB_HANDLER_INT32);
  2039. SETTER(int64, upb_int64_handlerfunc*, UPB_HANDLER_INT64);
  2040. SETTER(uint32, upb_uint32_handlerfunc*, UPB_HANDLER_UINT32);
  2041. SETTER(uint64, upb_uint64_handlerfunc*, UPB_HANDLER_UINT64);
  2042. SETTER(float, upb_float_handlerfunc*, UPB_HANDLER_FLOAT);
  2043. SETTER(double, upb_double_handlerfunc*, UPB_HANDLER_DOUBLE);
  2044. SETTER(bool, upb_bool_handlerfunc*, UPB_HANDLER_BOOL);
  2045. SETTER(startstr, upb_startstr_handlerfunc*, UPB_HANDLER_STARTSTR);
  2046. SETTER(string, upb_string_handlerfunc*, UPB_HANDLER_STRING);
  2047. SETTER(endstr, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSTR);
  2048. SETTER(startseq, upb_startfield_handlerfunc*, UPB_HANDLER_STARTSEQ);
  2049. SETTER(startsubmsg, upb_startfield_handlerfunc*, UPB_HANDLER_STARTSUBMSG);
  2050. SETTER(endsubmsg, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSUBMSG);
  2051. SETTER(endseq, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSEQ);
  2052. #undef SETTER
  2053. bool upb_handlers_setstartmsg(upb_handlers *h, upb_startmsg_handlerfunc *func,
  2054. upb_handlerattr *attr) {
  2055. return doset(h, UPB_STARTMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
  2056. (upb_func *)func, attr);
  2057. }
  2058. bool upb_handlers_setendmsg(upb_handlers *h, upb_endmsg_handlerfunc *func,
  2059. upb_handlerattr *attr) {
  2060. assert(!upb_handlers_isfrozen(h));
  2061. return doset(h, UPB_ENDMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
  2062. (upb_func *)func, attr);
  2063. }
  2064. bool upb_handlers_setsubhandlers(upb_handlers *h, const upb_fielddef *f,
  2065. const upb_handlers *sub) {
  2066. assert(sub);
  2067. assert(!upb_handlers_isfrozen(h));
  2068. assert(upb_fielddef_issubmsg(f));
  2069. if (SUBH_F(h, f)) return false; // Can't reset.
  2070. if (UPB_UPCAST(upb_handlers_msgdef(sub)) != upb_fielddef_subdef(f)) {
  2071. return false;
  2072. }
  2073. SUBH_F(h, f) = sub;
  2074. upb_ref2(sub, h);
  2075. return true;
  2076. }
  2077. const upb_handlers *upb_handlers_getsubhandlers(const upb_handlers *h,
  2078. const upb_fielddef *f) {
  2079. assert(upb_fielddef_issubmsg(f));
  2080. return SUBH_F(h, f);
  2081. }
  2082. bool upb_handlers_getattr(const upb_handlers *h, upb_selector_t sel,
  2083. upb_handlerattr *attr) {
  2084. if (!upb_handlers_gethandler(h, sel))
  2085. return false;
  2086. *attr = h->table[sel].attr;
  2087. return true;
  2088. }
  2089. const upb_handlers *upb_handlers_getsubhandlers_sel(const upb_handlers *h,
  2090. upb_selector_t sel) {
  2091. // STARTSUBMSG selector in sel is the field's selector base.
  2092. return SUBH(h, sel - UPB_STATIC_SELECTOR_COUNT);
  2093. }
  2094. const upb_msgdef *upb_handlers_msgdef(const upb_handlers *h) { return h->msg; }
  2095. bool upb_handlers_addcleanup(upb_handlers *h, void *p, upb_handlerfree *func) {
  2096. if (upb_inttable_lookupptr(&h->cleanup_, p, NULL)) {
  2097. return false;
  2098. }
  2099. bool ok = upb_inttable_insertptr(&h->cleanup_, p, upb_value_fptr(func));
  2100. UPB_ASSERT_VAR(ok, ok);
  2101. return true;
  2102. }
  2103. /* "Static" methods ***********************************************************/
  2104. bool upb_handlers_freeze(upb_handlers *const*handlers, int n, upb_status *s) {
  2105. // TODO: verify we have a transitive closure.
  2106. for (int i = 0; i < n; i++) {
  2107. upb_handlers *h = handlers[i];
  2108. if (!upb_ok(&h->status_)) {
  2109. upb_status_seterrf(s, "handlers for message %s had error status: %s",
  2110. upb_msgdef_fullname(upb_handlers_msgdef(h)),
  2111. upb_status_errmsg(&h->status_));
  2112. return false;
  2113. }
  2114. // Check that there are no closure mismatches due to missing Start* handlers
  2115. // or subhandlers with different type-level types.
  2116. upb_msg_field_iter j;
  2117. for(upb_msg_field_begin(&j, h->msg);
  2118. !upb_msg_field_done(&j);
  2119. upb_msg_field_next(&j)) {
  2120. const upb_fielddef *f = upb_msg_iter_field(&j);
  2121. if (upb_fielddef_isseq(f)) {
  2122. if (!checkstart(h, f, UPB_HANDLER_STARTSEQ, s))
  2123. return false;
  2124. }
  2125. if (upb_fielddef_isstring(f)) {
  2126. if (!checkstart(h, f, UPB_HANDLER_STARTSTR, s))
  2127. return false;
  2128. }
  2129. if (upb_fielddef_issubmsg(f)) {
  2130. bool hashandler = false;
  2131. if (upb_handlers_gethandler(
  2132. h, handlers_getsel(h, f, UPB_HANDLER_STARTSUBMSG)) ||
  2133. upb_handlers_gethandler(
  2134. h, handlers_getsel(h, f, UPB_HANDLER_ENDSUBMSG))) {
  2135. hashandler = true;
  2136. }
  2137. if (upb_fielddef_isseq(f) &&
  2138. (upb_handlers_gethandler(
  2139. h, handlers_getsel(h, f, UPB_HANDLER_STARTSEQ)) ||
  2140. upb_handlers_gethandler(
  2141. h, handlers_getsel(h, f, UPB_HANDLER_ENDSEQ)))) {
  2142. hashandler = true;
  2143. }
  2144. if (hashandler && !upb_handlers_getsubhandlers(h, f)) {
  2145. // For now we add an empty subhandlers in this case. It makes the
  2146. // decoder code generator simpler, because it only has to handle two
  2147. // cases (submessage has handlers or not) as opposed to three
  2148. // (submessage has handlers in enclosing message but no subhandlers).
  2149. //
  2150. // This makes parsing less efficient in the case that we want to
  2151. // notice a submessage but skip its contents (like if we're testing
  2152. // for submessage presence or counting the number of repeated
  2153. // submessages). In this case we will end up parsing the submessage
  2154. // field by field and throwing away the results for each, instead of
  2155. // skipping the whole delimited thing at once. If this is an issue we
  2156. // can revisit it, but do remember that this only arises when you have
  2157. // handlers (startseq/startsubmsg/endsubmsg/endseq) set for the
  2158. // submessage but no subhandlers. The uses cases for this are
  2159. // limited.
  2160. upb_handlers *sub = upb_handlers_new(upb_fielddef_msgsubdef(f), &sub);
  2161. upb_handlers_setsubhandlers(h, f, sub);
  2162. upb_handlers_unref(sub, &sub);
  2163. }
  2164. // TODO(haberman): check type of submessage.
  2165. // This is slightly tricky; also consider whether we should check that
  2166. // they match at setsubhandlers time.
  2167. }
  2168. }
  2169. }
  2170. if (!upb_refcounted_freeze((upb_refcounted*const*)handlers, n, s,
  2171. UPB_MAX_HANDLER_DEPTH)) {
  2172. return false;
  2173. }
  2174. return true;
  2175. }
  2176. upb_handlertype_t upb_handlers_getprimitivehandlertype(const upb_fielddef *f) {
  2177. switch (upb_fielddef_type(f)) {
  2178. case UPB_TYPE_INT32:
  2179. case UPB_TYPE_ENUM: return UPB_HANDLER_INT32;
  2180. case UPB_TYPE_INT64: return UPB_HANDLER_INT64;
  2181. case UPB_TYPE_UINT32: return UPB_HANDLER_UINT32;
  2182. case UPB_TYPE_UINT64: return UPB_HANDLER_UINT64;
  2183. case UPB_TYPE_FLOAT: return UPB_HANDLER_FLOAT;
  2184. case UPB_TYPE_DOUBLE: return UPB_HANDLER_DOUBLE;
  2185. case UPB_TYPE_BOOL: return UPB_HANDLER_BOOL;
  2186. default: assert(false); return -1; // Invalid input.
  2187. }
  2188. }
  2189. bool upb_handlers_getselector(const upb_fielddef *f, upb_handlertype_t type,
  2190. upb_selector_t *s) {
  2191. switch (type) {
  2192. case UPB_HANDLER_INT32:
  2193. case UPB_HANDLER_INT64:
  2194. case UPB_HANDLER_UINT32:
  2195. case UPB_HANDLER_UINT64:
  2196. case UPB_HANDLER_FLOAT:
  2197. case UPB_HANDLER_DOUBLE:
  2198. case UPB_HANDLER_BOOL:
  2199. if (!upb_fielddef_isprimitive(f) ||
  2200. upb_handlers_getprimitivehandlertype(f) != type)
  2201. return false;
  2202. *s = f->selector_base;
  2203. break;
  2204. case UPB_HANDLER_STRING:
  2205. if (upb_fielddef_isstring(f)) {
  2206. *s = f->selector_base;
  2207. } else if (upb_fielddef_lazy(f)) {
  2208. *s = f->selector_base + 3;
  2209. } else {
  2210. return false;
  2211. }
  2212. break;
  2213. case UPB_HANDLER_STARTSTR:
  2214. if (upb_fielddef_isstring(f) || upb_fielddef_lazy(f)) {
  2215. *s = f->selector_base + 1;
  2216. } else {
  2217. return false;
  2218. }
  2219. break;
  2220. case UPB_HANDLER_ENDSTR:
  2221. if (upb_fielddef_isstring(f) || upb_fielddef_lazy(f)) {
  2222. *s = f->selector_base + 2;
  2223. } else {
  2224. return false;
  2225. }
  2226. break;
  2227. case UPB_HANDLER_STARTSEQ:
  2228. if (!upb_fielddef_isseq(f)) return false;
  2229. *s = f->selector_base - 2;
  2230. break;
  2231. case UPB_HANDLER_ENDSEQ:
  2232. if (!upb_fielddef_isseq(f)) return false;
  2233. *s = f->selector_base - 1;
  2234. break;
  2235. case UPB_HANDLER_STARTSUBMSG:
  2236. if (!upb_fielddef_issubmsg(f)) return false;
  2237. // Selectors for STARTSUBMSG are at the beginning of the table so that the
  2238. // selector can also be used as an index into the "sub" array of
  2239. // subhandlers. The indexes for the two into these two tables are the
  2240. // same, except that in the handler table the static selectors come first.
  2241. *s = f->index_ + UPB_STATIC_SELECTOR_COUNT;
  2242. break;
  2243. case UPB_HANDLER_ENDSUBMSG:
  2244. if (!upb_fielddef_issubmsg(f)) return false;
  2245. *s = f->selector_base;
  2246. break;
  2247. }
  2248. assert((size_t)*s < upb_fielddef_containingtype(f)->selector_count);
  2249. return true;
  2250. }
  2251. uint32_t upb_handlers_selectorbaseoffset(const upb_fielddef *f) {
  2252. return upb_fielddef_isseq(f) ? 2 : 0;
  2253. }
  2254. uint32_t upb_handlers_selectorcount(const upb_fielddef *f) {
  2255. uint32_t ret = 1;
  2256. if (upb_fielddef_isseq(f)) ret += 2; // STARTSEQ/ENDSEQ
  2257. if (upb_fielddef_isstring(f)) ret += 2; // [STRING]/STARTSTR/ENDSTR
  2258. if (upb_fielddef_issubmsg(f)) {
  2259. // ENDSUBMSG (STARTSUBMSG is at table beginning)
  2260. ret += 0;
  2261. if (upb_fielddef_lazy(f)) {
  2262. // STARTSTR/ENDSTR/STRING (for lazy)
  2263. ret += 3;
  2264. }
  2265. }
  2266. return ret;
  2267. }
  2268. /* upb_handlerattr ************************************************************/
  2269. void upb_handlerattr_init(upb_handlerattr *attr) {
  2270. upb_handlerattr from = UPB_HANDLERATTR_INITIALIZER;
  2271. memcpy(attr, &from, sizeof(*attr));
  2272. }
  2273. void upb_handlerattr_uninit(upb_handlerattr *attr) {
  2274. UPB_UNUSED(attr);
  2275. }
  2276. bool upb_handlerattr_sethandlerdata(upb_handlerattr *attr, const void *hd) {
  2277. attr->handler_data_ = hd;
  2278. return true;
  2279. }
  2280. bool upb_handlerattr_setclosuretype(upb_handlerattr *attr, const void *type) {
  2281. attr->closure_type_ = type;
  2282. return true;
  2283. }
  2284. const void *upb_handlerattr_closuretype(const upb_handlerattr *attr) {
  2285. return attr->closure_type_;
  2286. }
  2287. bool upb_handlerattr_setreturnclosuretype(upb_handlerattr *attr,
  2288. const void *type) {
  2289. attr->return_closure_type_ = type;
  2290. return true;
  2291. }
  2292. const void *upb_handlerattr_returnclosuretype(const upb_handlerattr *attr) {
  2293. return attr->return_closure_type_;
  2294. }
  2295. bool upb_handlerattr_setalwaysok(upb_handlerattr *attr, bool alwaysok) {
  2296. attr->alwaysok_ = alwaysok;
  2297. return true;
  2298. }
  2299. bool upb_handlerattr_alwaysok(const upb_handlerattr *attr) {
  2300. return attr->alwaysok_;
  2301. }
  2302. /* upb_bufhandle **************************************************************/
  2303. size_t upb_bufhandle_objofs(const upb_bufhandle *h) {
  2304. return h->objofs_;
  2305. }
  2306. /* upb_byteshandler ***********************************************************/
  2307. void upb_byteshandler_init(upb_byteshandler* h) {
  2308. memset(h, 0, sizeof(*h));
  2309. }
  2310. // For when we support handlerfree callbacks.
  2311. void upb_byteshandler_uninit(upb_byteshandler* h) {
  2312. UPB_UNUSED(h);
  2313. }
  2314. bool upb_byteshandler_setstartstr(upb_byteshandler *h,
  2315. upb_startstr_handlerfunc *func, void *d) {
  2316. h->table[UPB_STARTSTR_SELECTOR].func = (upb_func*)func;
  2317. h->table[UPB_STARTSTR_SELECTOR].attr.handler_data_ = d;
  2318. return true;
  2319. }
  2320. bool upb_byteshandler_setstring(upb_byteshandler *h,
  2321. upb_string_handlerfunc *func, void *d) {
  2322. h->table[UPB_STRING_SELECTOR].func = (upb_func*)func;
  2323. h->table[UPB_STRING_SELECTOR].attr.handler_data_ = d;
  2324. return true;
  2325. }
  2326. bool upb_byteshandler_setendstr(upb_byteshandler *h,
  2327. upb_endfield_handlerfunc *func, void *d) {
  2328. h->table[UPB_ENDSTR_SELECTOR].func = (upb_func*)func;
  2329. h->table[UPB_ENDSTR_SELECTOR].attr.handler_data_ = d;
  2330. return true;
  2331. }
  2332. /*
  2333. * upb - a minimalist implementation of protocol buffers.
  2334. *
  2335. * Copyright (c) 2012 Google Inc. See LICENSE for details.
  2336. * Author: Josh Haberman <jhaberman@gmail.com>
  2337. *
  2338. * Our key invariants are:
  2339. * 1. reference cycles never span groups
  2340. * 2. for ref2(to, from), we increment to's count iff group(from) != group(to)
  2341. *
  2342. * The previous two are how we avoid leaking cycles. Other important
  2343. * invariants are:
  2344. * 3. for mutable objects "from" and "to", if there exists a ref2(to, from)
  2345. * this implies group(from) == group(to). (In practice, what we implement
  2346. * is even stronger; "from" and "to" will share a group if there has *ever*
  2347. * been a ref2(to, from), but all that is necessary for correctness is the
  2348. * weaker one).
  2349. * 4. mutable and immutable objects are never in the same group.
  2350. */
  2351. #include <setjmp.h>
  2352. #include <stdlib.h>
  2353. static void freeobj(upb_refcounted *o);
  2354. const char untracked_val;
  2355. const void *UPB_UNTRACKED_REF = &untracked_val;
  2356. /* arch-specific atomic primitives *******************************************/
  2357. #ifdef UPB_THREAD_UNSAFE //////////////////////////////////////////////////////
  2358. static void atomic_inc(uint32_t *a) { (*a)++; }
  2359. static bool atomic_dec(uint32_t *a) { return --(*a) == 0; }
  2360. #elif defined(__GNUC__) || defined(__clang__) //////////////////////////////////
  2361. static void atomic_inc(uint32_t *a) { __sync_fetch_and_add(a, 1); }
  2362. static bool atomic_dec(uint32_t *a) { return __sync_sub_and_fetch(a, 1) == 0; }
  2363. #elif defined(WIN32) ///////////////////////////////////////////////////////////
  2364. #include <Windows.h>
  2365. static void atomic_inc(upb_atomic_t *a) { InterlockedIncrement(&a->val); }
  2366. static bool atomic_dec(upb_atomic_t *a) {
  2367. return InterlockedDecrement(&a->val) == 0;
  2368. }
  2369. #else
  2370. #error Atomic primitives not defined for your platform/CPU. \
  2371. Implement them or compile with UPB_THREAD_UNSAFE.
  2372. #endif
  2373. // All static objects point to this refcount.
  2374. // It is special-cased in ref/unref below.
  2375. uint32_t static_refcount = -1;
  2376. // We can avoid atomic ops for statically-declared objects.
  2377. // This is a minor optimization but nice since we can avoid degrading under
  2378. // contention in this case.
  2379. static void refgroup(uint32_t *group) {
  2380. if (group != &static_refcount)
  2381. atomic_inc(group);
  2382. }
  2383. static bool unrefgroup(uint32_t *group) {
  2384. if (group == &static_refcount) {
  2385. return false;
  2386. } else {
  2387. return atomic_dec(group);
  2388. }
  2389. }
  2390. /* Reference tracking (debug only) ********************************************/
  2391. #ifdef UPB_DEBUG_REFS
  2392. #ifdef UPB_THREAD_UNSAFE
  2393. static void upb_lock() {}
  2394. static void upb_unlock() {}
  2395. #else
  2396. // User must define functions that lock/unlock a global mutex and link this
  2397. // file against them.
  2398. void upb_lock();
  2399. void upb_unlock();
  2400. #endif
  2401. // UPB_DEBUG_REFS mode counts on being able to malloc() memory in some
  2402. // code-paths that can normally never fail, like upb_refcounted_ref(). Since
  2403. // we have no way to propagage out-of-memory errors back to the user, and since
  2404. // these errors can only occur in UPB_DEBUG_REFS mode, we immediately fail.
  2405. #define CHECK_OOM(predicate) if (!(predicate)) { assert(predicate); exit(1); }
  2406. typedef struct {
  2407. int count; // How many refs there are (duplicates only allowed for ref2).
  2408. bool is_ref2;
  2409. } trackedref;
  2410. static trackedref *trackedref_new(bool is_ref2) {
  2411. trackedref *ret = malloc(sizeof(*ret));
  2412. CHECK_OOM(ret);
  2413. ret->count = 1;
  2414. ret->is_ref2 = is_ref2;
  2415. return ret;
  2416. }
  2417. static void track(const upb_refcounted *r, const void *owner, bool ref2) {
  2418. assert(owner);
  2419. if (owner == UPB_UNTRACKED_REF) return;
  2420. upb_lock();
  2421. upb_value v;
  2422. if (upb_inttable_lookupptr(r->refs, owner, &v)) {
  2423. trackedref *ref = upb_value_getptr(v);
  2424. // Since we allow multiple ref2's for the same to/from pair without
  2425. // allocating separate memory for each one, we lose the fine-grained
  2426. // tracking behavior we get with regular refs. Since ref2s only happen
  2427. // inside upb, we'll accept this limitation until/unless there is a really
  2428. // difficult upb-internal bug that can't be figured out without it.
  2429. assert(ref2);
  2430. assert(ref->is_ref2);
  2431. ref->count++;
  2432. } else {
  2433. trackedref *ref = trackedref_new(ref2);
  2434. bool ok = upb_inttable_insertptr(r->refs, owner, upb_value_ptr(ref));
  2435. CHECK_OOM(ok);
  2436. if (ref2) {
  2437. // We know this cast is safe when it is a ref2, because it's coming from
  2438. // another refcounted object.
  2439. const upb_refcounted *from = owner;
  2440. assert(!upb_inttable_lookupptr(from->ref2s, r, NULL));
  2441. ok = upb_inttable_insertptr(from->ref2s, r, upb_value_ptr(NULL));
  2442. CHECK_OOM(ok);
  2443. }
  2444. }
  2445. upb_unlock();
  2446. }
  2447. static void untrack(const upb_refcounted *r, const void *owner, bool ref2) {
  2448. assert(owner);
  2449. if (owner == UPB_UNTRACKED_REF) return;
  2450. upb_lock();
  2451. upb_value v;
  2452. bool found = upb_inttable_lookupptr(r->refs, owner, &v);
  2453. // This assert will fail if an owner attempts to release a ref it didn't have.
  2454. UPB_ASSERT_VAR(found, found);
  2455. trackedref *ref = upb_value_getptr(v);
  2456. assert(ref->is_ref2 == ref2);
  2457. if (--ref->count == 0) {
  2458. free(ref);
  2459. upb_inttable_removeptr(r->refs, owner, NULL);
  2460. if (ref2) {
  2461. // We know this cast is safe when it is a ref2, because it's coming from
  2462. // another refcounted object.
  2463. const upb_refcounted *from = owner;
  2464. bool removed = upb_inttable_removeptr(from->ref2s, r, NULL);
  2465. assert(removed);
  2466. }
  2467. }
  2468. upb_unlock();
  2469. }
  2470. static void checkref(const upb_refcounted *r, const void *owner, bool ref2) {
  2471. upb_lock();
  2472. upb_value v;
  2473. bool found = upb_inttable_lookupptr(r->refs, owner, &v);
  2474. UPB_ASSERT_VAR(found, found);
  2475. trackedref *ref = upb_value_getptr(v);
  2476. assert(ref->is_ref2 == ref2);
  2477. upb_unlock();
  2478. }
  2479. // Populates the given UPB_CTYPE_INT32 inttable with counts of ref2's that
  2480. // originate from the given owner.
  2481. static void getref2s(const upb_refcounted *owner, upb_inttable *tab) {
  2482. upb_lock();
  2483. upb_inttable_iter i;
  2484. upb_inttable_begin(&i, owner->ref2s);
  2485. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  2486. upb_refcounted *to = (upb_refcounted*)upb_inttable_iter_key(&i);
  2487. // To get the count we need to look in the target's table.
  2488. upb_value v;
  2489. bool found = upb_inttable_lookupptr(to->refs, owner, &v);
  2490. assert(found);
  2491. trackedref *ref = upb_value_getptr(v);
  2492. upb_value count = upb_value_int32(ref->count);
  2493. bool ok = upb_inttable_insertptr(tab, to, count);
  2494. CHECK_OOM(ok);
  2495. }
  2496. upb_unlock();
  2497. }
  2498. typedef struct {
  2499. upb_inttable ref2;
  2500. const upb_refcounted *obj;
  2501. } check_state;
  2502. static void visit_check(const upb_refcounted *obj, const upb_refcounted *subobj,
  2503. void *closure) {
  2504. check_state *s = closure;
  2505. assert(obj == s->obj);
  2506. assert(subobj);
  2507. upb_inttable *ref2 = &s->ref2;
  2508. upb_value v;
  2509. bool removed = upb_inttable_removeptr(ref2, subobj, &v);
  2510. // The following assertion will fail if the visit() function visits a subobj
  2511. // that it did not have a ref2 on, or visits the same subobj too many times.
  2512. assert(removed);
  2513. int32_t newcount = upb_value_getint32(v) - 1;
  2514. if (newcount > 0) {
  2515. upb_inttable_insert(ref2, (uintptr_t)subobj, upb_value_int32(newcount));
  2516. }
  2517. }
  2518. static void visit(const upb_refcounted *r, upb_refcounted_visit *v,
  2519. void *closure) {
  2520. // In DEBUG_REFS mode we know what existing ref2 refs there are, so we know
  2521. // exactly the set of nodes that visit() should visit. So we verify visit()'s
  2522. // correctness here.
  2523. check_state state;
  2524. state.obj = r;
  2525. bool ok = upb_inttable_init(&state.ref2, UPB_CTYPE_INT32);
  2526. CHECK_OOM(ok);
  2527. getref2s(r, &state.ref2);
  2528. // This should visit any children in the ref2 table.
  2529. if (r->vtbl->visit) r->vtbl->visit(r, visit_check, &state);
  2530. // This assertion will fail if the visit() function missed any children.
  2531. assert(upb_inttable_count(&state.ref2) == 0);
  2532. upb_inttable_uninit(&state.ref2);
  2533. if (r->vtbl->visit) r->vtbl->visit(r, v, closure);
  2534. }
  2535. static bool trackinit(upb_refcounted *r) {
  2536. r->refs = malloc(sizeof(*r->refs));
  2537. r->ref2s = malloc(sizeof(*r->ref2s));
  2538. if (!r->refs || !r->ref2s) goto err1;
  2539. if (!upb_inttable_init(r->refs, UPB_CTYPE_PTR)) goto err1;
  2540. if (!upb_inttable_init(r->ref2s, UPB_CTYPE_PTR)) goto err2;
  2541. return true;
  2542. err2:
  2543. upb_inttable_uninit(r->refs);
  2544. err1:
  2545. free(r->refs);
  2546. free(r->ref2s);
  2547. return false;
  2548. }
  2549. static void trackfree(const upb_refcounted *r) {
  2550. upb_inttable_uninit(r->refs);
  2551. upb_inttable_uninit(r->ref2s);
  2552. free(r->refs);
  2553. free(r->ref2s);
  2554. }
  2555. #else
  2556. static void track(const upb_refcounted *r, const void *owner, bool ref2) {
  2557. UPB_UNUSED(r);
  2558. UPB_UNUSED(owner);
  2559. UPB_UNUSED(ref2);
  2560. }
  2561. static void untrack(const upb_refcounted *r, const void *owner, bool ref2) {
  2562. UPB_UNUSED(r);
  2563. UPB_UNUSED(owner);
  2564. UPB_UNUSED(ref2);
  2565. }
  2566. static void checkref(const upb_refcounted *r, const void *owner, bool ref2) {
  2567. UPB_UNUSED(r);
  2568. UPB_UNUSED(owner);
  2569. UPB_UNUSED(ref2);
  2570. }
  2571. static bool trackinit(upb_refcounted *r) {
  2572. UPB_UNUSED(r);
  2573. return true;
  2574. }
  2575. static void trackfree(const upb_refcounted *r) {
  2576. UPB_UNUSED(r);
  2577. }
  2578. static void visit(const upb_refcounted *r, upb_refcounted_visit *v,
  2579. void *closure) {
  2580. if (r->vtbl->visit) r->vtbl->visit(r, v, closure);
  2581. }
  2582. #endif // UPB_DEBUG_REFS
  2583. /* freeze() *******************************************************************/
  2584. // The freeze() operation is by far the most complicated part of this scheme.
  2585. // We compute strongly-connected components and then mutate the graph such that
  2586. // we preserve the invariants documented at the top of this file. And we must
  2587. // handle out-of-memory errors gracefully (without leaving the graph
  2588. // inconsistent), which adds to the fun.
  2589. // The state used by the freeze operation (shared across many functions).
  2590. typedef struct {
  2591. int depth;
  2592. int maxdepth;
  2593. uint64_t index;
  2594. // Maps upb_refcounted* -> attributes (color, etc). attr layout varies by
  2595. // color.
  2596. upb_inttable objattr;
  2597. upb_inttable stack; // stack of upb_refcounted* for Tarjan's algorithm.
  2598. upb_inttable groups; // array of uint32_t*, malloc'd refcounts for new groups
  2599. upb_status *status;
  2600. jmp_buf err;
  2601. } tarjan;
  2602. static void release_ref2(const upb_refcounted *obj,
  2603. const upb_refcounted *subobj,
  2604. void *closure);
  2605. // Node attributes /////////////////////////////////////////////////////////////
  2606. // After our analysis phase all nodes will be either GRAY or WHITE.
  2607. typedef enum {
  2608. BLACK = 0, // Object has not been seen.
  2609. GRAY, // Object has been found via a refgroup but may not be reachable.
  2610. GREEN, // Object is reachable and is currently on the Tarjan stack.
  2611. WHITE, // Object is reachable and has been assigned a group (SCC).
  2612. } color_t;
  2613. UPB_NORETURN static void err(tarjan *t) { longjmp(t->err, 1); }
  2614. UPB_NORETURN static void oom(tarjan *t) {
  2615. upb_status_seterrmsg(t->status, "out of memory");
  2616. err(t);
  2617. }
  2618. static uint64_t trygetattr(const tarjan *t, const upb_refcounted *r) {
  2619. upb_value v;
  2620. return upb_inttable_lookupptr(&t->objattr, r, &v) ?
  2621. upb_value_getuint64(v) : 0;
  2622. }
  2623. static uint64_t getattr(const tarjan *t, const upb_refcounted *r) {
  2624. upb_value v;
  2625. bool found = upb_inttable_lookupptr(&t->objattr, r, &v);
  2626. UPB_ASSERT_VAR(found, found);
  2627. return upb_value_getuint64(v);
  2628. }
  2629. static void setattr(tarjan *t, const upb_refcounted *r, uint64_t attr) {
  2630. upb_inttable_removeptr(&t->objattr, r, NULL);
  2631. upb_inttable_insertptr(&t->objattr, r, upb_value_uint64(attr));
  2632. }
  2633. static color_t color(tarjan *t, const upb_refcounted *r) {
  2634. return trygetattr(t, r) & 0x3; // Color is always stored in the low 2 bits.
  2635. }
  2636. static void set_gray(tarjan *t, const upb_refcounted *r) {
  2637. assert(color(t, r) == BLACK);
  2638. setattr(t, r, GRAY);
  2639. }
  2640. // Pushes an obj onto the Tarjan stack and sets it to GREEN.
  2641. static void push(tarjan *t, const upb_refcounted *r) {
  2642. assert(color(t, r) == BLACK || color(t, r) == GRAY);
  2643. // This defines the attr layout for the GREEN state. "index" and "lowlink"
  2644. // get 31 bits, which is plenty (limit of 2B objects frozen at a time).
  2645. setattr(t, r, GREEN | (t->index << 2) | (t->index << 33));
  2646. if (++t->index == 0x80000000) {
  2647. upb_status_seterrmsg(t->status, "too many objects to freeze");
  2648. err(t);
  2649. }
  2650. upb_inttable_push(&t->stack, upb_value_ptr((void*)r));
  2651. }
  2652. // Pops an obj from the Tarjan stack and sets it to WHITE, with a ptr to its
  2653. // SCC group.
  2654. static upb_refcounted *pop(tarjan *t) {
  2655. upb_refcounted *r = upb_value_getptr(upb_inttable_pop(&t->stack));
  2656. assert(color(t, r) == GREEN);
  2657. // This defines the attr layout for nodes in the WHITE state.
  2658. // Top of group stack is [group, NULL]; we point at group.
  2659. setattr(t, r, WHITE | (upb_inttable_count(&t->groups) - 2) << 8);
  2660. return r;
  2661. }
  2662. static void tarjan_newgroup(tarjan *t) {
  2663. uint32_t *group = malloc(sizeof(*group));
  2664. if (!group) oom(t);
  2665. // Push group and empty group leader (we'll fill in leader later).
  2666. if (!upb_inttable_push(&t->groups, upb_value_ptr(group)) ||
  2667. !upb_inttable_push(&t->groups, upb_value_ptr(NULL))) {
  2668. free(group);
  2669. oom(t);
  2670. }
  2671. *group = 0;
  2672. }
  2673. static uint32_t idx(tarjan *t, const upb_refcounted *r) {
  2674. assert(color(t, r) == GREEN);
  2675. return (getattr(t, r) >> 2) & 0x7FFFFFFF;
  2676. }
  2677. static uint32_t lowlink(tarjan *t, const upb_refcounted *r) {
  2678. if (color(t, r) == GREEN) {
  2679. return getattr(t, r) >> 33;
  2680. } else {
  2681. return UINT32_MAX;
  2682. }
  2683. }
  2684. static void set_lowlink(tarjan *t, const upb_refcounted *r, uint32_t lowlink) {
  2685. assert(color(t, r) == GREEN);
  2686. setattr(t, r, ((uint64_t)lowlink << 33) | (getattr(t, r) & 0x1FFFFFFFF));
  2687. }
  2688. static uint32_t *group(tarjan *t, upb_refcounted *r) {
  2689. assert(color(t, r) == WHITE);
  2690. uint64_t groupnum = getattr(t, r) >> 8;
  2691. upb_value v;
  2692. bool found = upb_inttable_lookup(&t->groups, groupnum, &v);
  2693. UPB_ASSERT_VAR(found, found);
  2694. return upb_value_getptr(v);
  2695. }
  2696. // If the group leader for this object's group has not previously been set,
  2697. // the given object is assigned to be its leader.
  2698. static upb_refcounted *groupleader(tarjan *t, upb_refcounted *r) {
  2699. assert(color(t, r) == WHITE);
  2700. uint64_t leader_slot = (getattr(t, r) >> 8) + 1;
  2701. upb_value v;
  2702. bool found = upb_inttable_lookup(&t->groups, leader_slot, &v);
  2703. UPB_ASSERT_VAR(found, found);
  2704. if (upb_value_getptr(v)) {
  2705. return upb_value_getptr(v);
  2706. } else {
  2707. upb_inttable_remove(&t->groups, leader_slot, NULL);
  2708. upb_inttable_insert(&t->groups, leader_slot, upb_value_ptr(r));
  2709. return r;
  2710. }
  2711. }
  2712. // Tarjan's algorithm //////////////////////////////////////////////////////////
  2713. // See:
  2714. // http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
  2715. static void do_tarjan(const upb_refcounted *obj, tarjan *t);
  2716. static void tarjan_visit(const upb_refcounted *obj,
  2717. const upb_refcounted *subobj,
  2718. void *closure) {
  2719. tarjan *t = closure;
  2720. if (++t->depth > t->maxdepth) {
  2721. upb_status_seterrf(t->status, "graph too deep to freeze (%d)", t->maxdepth);
  2722. err(t);
  2723. } else if (subobj->is_frozen || color(t, subobj) == WHITE) {
  2724. // Do nothing: we don't want to visit or color already-frozen nodes,
  2725. // and WHITE nodes have already been assigned a SCC.
  2726. } else if (color(t, subobj) < GREEN) {
  2727. // Subdef has not yet been visited; recurse on it.
  2728. do_tarjan(subobj, t);
  2729. set_lowlink(t, obj, UPB_MIN(lowlink(t, obj), lowlink(t, subobj)));
  2730. } else if (color(t, subobj) == GREEN) {
  2731. // Subdef is in the stack and hence in the current SCC.
  2732. set_lowlink(t, obj, UPB_MIN(lowlink(t, obj), idx(t, subobj)));
  2733. }
  2734. --t->depth;
  2735. }
  2736. static void do_tarjan(const upb_refcounted *obj, tarjan *t) {
  2737. if (color(t, obj) == BLACK) {
  2738. // We haven't seen this object's group; mark the whole group GRAY.
  2739. const upb_refcounted *o = obj;
  2740. do { set_gray(t, o); } while ((o = o->next) != obj);
  2741. }
  2742. push(t, obj);
  2743. visit(obj, tarjan_visit, t);
  2744. if (lowlink(t, obj) == idx(t, obj)) {
  2745. tarjan_newgroup(t);
  2746. while (pop(t) != obj)
  2747. ;
  2748. }
  2749. }
  2750. // freeze() ////////////////////////////////////////////////////////////////////
  2751. static void crossref(const upb_refcounted *r, const upb_refcounted *subobj,
  2752. void *_t) {
  2753. tarjan *t = _t;
  2754. assert(color(t, r) > BLACK);
  2755. if (color(t, subobj) > BLACK && r->group != subobj->group) {
  2756. // Previously this ref was not reflected in subobj->group because they
  2757. // were in the same group; now that they are split a ref must be taken.
  2758. refgroup(subobj->group);
  2759. }
  2760. }
  2761. static bool freeze(upb_refcounted *const*roots, int n, upb_status *s,
  2762. int maxdepth) {
  2763. volatile bool ret = false;
  2764. // We run in two passes so that we can allocate all memory before performing
  2765. // any mutation of the input -- this allows us to leave the input unchanged
  2766. // in the case of memory allocation failure.
  2767. tarjan t;
  2768. t.index = 0;
  2769. t.depth = 0;
  2770. t.maxdepth = maxdepth;
  2771. t.status = s;
  2772. if (!upb_inttable_init(&t.objattr, UPB_CTYPE_UINT64)) goto err1;
  2773. if (!upb_inttable_init(&t.stack, UPB_CTYPE_PTR)) goto err2;
  2774. if (!upb_inttable_init(&t.groups, UPB_CTYPE_PTR)) goto err3;
  2775. if (setjmp(t.err) != 0) goto err4;
  2776. for (int i = 0; i < n; i++) {
  2777. if (color(&t, roots[i]) < GREEN) {
  2778. do_tarjan(roots[i], &t);
  2779. }
  2780. }
  2781. // If we've made it this far, no further errors are possible so it's safe to
  2782. // mutate the objects without risk of leaving them in an inconsistent state.
  2783. ret = true;
  2784. // The transformation that follows requires care. The preconditions are:
  2785. // - all objects in attr map are WHITE or GRAY, and are in mutable groups
  2786. // (groups of all mutable objs)
  2787. // - no ref2(to, from) refs have incremented count(to) if both "to" and
  2788. // "from" are in our attr map (this follows from invariants (2) and (3))
  2789. // Pass 1: we remove WHITE objects from their mutable groups, and add them to
  2790. // new groups according to the SCC's we computed. These new groups will
  2791. // consist of only frozen objects. None will be immediately collectible,
  2792. // because WHITE objects are by definition reachable from one of "roots",
  2793. // which the caller must own refs on.
  2794. upb_inttable_iter i;
  2795. upb_inttable_begin(&i, &t.objattr);
  2796. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  2797. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&i);
  2798. // Since removal from a singly-linked list requires access to the object's
  2799. // predecessor, we consider obj->next instead of obj for moving. With the
  2800. // while() loop we guarantee that we will visit every node's predecessor.
  2801. // Proof:
  2802. // 1. every node's predecessor is in our attr map.
  2803. // 2. though the loop body may change a node's predecessor, it will only
  2804. // change it to be the node we are currently operating on, so with a
  2805. // while() loop we guarantee ourselves the chance to remove each node.
  2806. while (color(&t, obj->next) == WHITE &&
  2807. group(&t, obj->next) != obj->next->group) {
  2808. // Remove from old group.
  2809. upb_refcounted *move = obj->next;
  2810. if (obj == move) {
  2811. // Removing the last object from a group.
  2812. assert(*obj->group == obj->individual_count);
  2813. free(obj->group);
  2814. } else {
  2815. obj->next = move->next;
  2816. // This may decrease to zero; we'll collect GRAY objects (if any) that
  2817. // remain in the group in the third pass.
  2818. assert(*move->group >= move->individual_count);
  2819. *move->group -= move->individual_count;
  2820. }
  2821. // Add to new group.
  2822. upb_refcounted *leader = groupleader(&t, move);
  2823. if (move == leader) {
  2824. // First object added to new group is its leader.
  2825. move->group = group(&t, move);
  2826. move->next = move;
  2827. *move->group = move->individual_count;
  2828. } else {
  2829. // Group already has at least one object in it.
  2830. assert(leader->group == group(&t, move));
  2831. move->group = group(&t, move);
  2832. move->next = leader->next;
  2833. leader->next = move;
  2834. *move->group += move->individual_count;
  2835. }
  2836. move->is_frozen = true;
  2837. }
  2838. }
  2839. // Pass 2: GRAY and WHITE objects "obj" with ref2(to, obj) references must
  2840. // increment count(to) if group(obj) != group(to) (which could now be the
  2841. // case if "to" was just frozen).
  2842. upb_inttable_begin(&i, &t.objattr);
  2843. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  2844. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&i);
  2845. visit(obj, crossref, &t);
  2846. }
  2847. // Pass 3: GRAY objects are collected if their group's refcount dropped to
  2848. // zero when we removed its white nodes. This can happen if they had only
  2849. // been kept alive by virtue of sharing a group with an object that was just
  2850. // frozen.
  2851. //
  2852. // It is important that we do this last, since the GRAY object's free()
  2853. // function could call unref2() on just-frozen objects, which will decrement
  2854. // refs that were added in pass 2.
  2855. upb_inttable_begin(&i, &t.objattr);
  2856. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  2857. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&i);
  2858. if (obj->group == NULL || *obj->group == 0) {
  2859. if (obj->group) {
  2860. // We eagerly free() the group's count (since we can't easily determine
  2861. // the group's remaining size it's the easiest way to ensure it gets
  2862. // done).
  2863. free(obj->group);
  2864. // Visit to release ref2's (done in a separate pass since release_ref2
  2865. // depends on o->group being unmodified so it can test merged()).
  2866. upb_refcounted *o = obj;
  2867. do { visit(o, release_ref2, NULL); } while ((o = o->next) != obj);
  2868. // Mark "group" fields as NULL so we know to free the objects later in
  2869. // this loop, but also don't try to delete the group twice.
  2870. o = obj;
  2871. do { o->group = NULL; } while ((o = o->next) != obj);
  2872. }
  2873. freeobj(obj);
  2874. }
  2875. }
  2876. err4:
  2877. if (!ret) {
  2878. upb_inttable_begin(&i, &t.groups);
  2879. for(; !upb_inttable_done(&i); upb_inttable_next(&i))
  2880. free(upb_value_getptr(upb_inttable_iter_value(&i)));
  2881. }
  2882. upb_inttable_uninit(&t.groups);
  2883. err3:
  2884. upb_inttable_uninit(&t.stack);
  2885. err2:
  2886. upb_inttable_uninit(&t.objattr);
  2887. err1:
  2888. return ret;
  2889. }
  2890. /* Misc internal functions ***************************************************/
  2891. static bool merged(const upb_refcounted *r, const upb_refcounted *r2) {
  2892. return r->group == r2->group;
  2893. }
  2894. static void merge(upb_refcounted *r, upb_refcounted *from) {
  2895. if (merged(r, from)) return;
  2896. *r->group += *from->group;
  2897. free(from->group);
  2898. upb_refcounted *base = from;
  2899. // Set all refcount pointers in the "from" chain to the merged refcount.
  2900. //
  2901. // TODO(haberman): this linear algorithm can result in an overall O(n^2) bound
  2902. // if the user continuously extends a group by one object. Prevent this by
  2903. // using one of the techniques in this paper:
  2904. // ftp://www.ncedc.org/outgoing/geomorph/dino/orals/p245-tarjan.pdf
  2905. do { from->group = r->group; } while ((from = from->next) != base);
  2906. // Merge the two circularly linked lists by swapping their next pointers.
  2907. upb_refcounted *tmp = r->next;
  2908. r->next = base->next;
  2909. base->next = tmp;
  2910. }
  2911. static void unref(const upb_refcounted *r);
  2912. static void release_ref2(const upb_refcounted *obj,
  2913. const upb_refcounted *subobj,
  2914. void *closure) {
  2915. UPB_UNUSED(closure);
  2916. untrack(subobj, obj, true);
  2917. if (!merged(obj, subobj)) {
  2918. assert(subobj->is_frozen);
  2919. unref(subobj);
  2920. }
  2921. }
  2922. static void unref(const upb_refcounted *r) {
  2923. if (unrefgroup(r->group)) {
  2924. free(r->group);
  2925. // In two passes, since release_ref2 needs a guarantee that any subobjs
  2926. // are alive.
  2927. const upb_refcounted *o = r;
  2928. do { visit(o, release_ref2, NULL); } while((o = o->next) != r);
  2929. o = r;
  2930. do {
  2931. const upb_refcounted *next = o->next;
  2932. assert(o->is_frozen || o->individual_count == 0);
  2933. freeobj((upb_refcounted*)o);
  2934. o = next;
  2935. } while(o != r);
  2936. }
  2937. }
  2938. static void freeobj(upb_refcounted *o) {
  2939. trackfree(o);
  2940. o->vtbl->free((upb_refcounted*)o);
  2941. }
  2942. /* Public interface ***********************************************************/
  2943. bool upb_refcounted_init(upb_refcounted *r,
  2944. const struct upb_refcounted_vtbl *vtbl,
  2945. const void *owner) {
  2946. r->next = r;
  2947. r->vtbl = vtbl;
  2948. r->individual_count = 0;
  2949. r->is_frozen = false;
  2950. r->group = malloc(sizeof(*r->group));
  2951. if (!r->group) return false;
  2952. *r->group = 0;
  2953. if (!trackinit(r)) {
  2954. free(r->group);
  2955. return false;
  2956. }
  2957. upb_refcounted_ref(r, owner);
  2958. return true;
  2959. }
  2960. bool upb_refcounted_isfrozen(const upb_refcounted *r) {
  2961. return r->is_frozen;
  2962. }
  2963. void upb_refcounted_ref(const upb_refcounted *r, const void *owner) {
  2964. track(r, owner, false);
  2965. if (!r->is_frozen)
  2966. ((upb_refcounted*)r)->individual_count++;
  2967. refgroup(r->group);
  2968. }
  2969. void upb_refcounted_unref(const upb_refcounted *r, const void *owner) {
  2970. untrack(r, owner, false);
  2971. if (!r->is_frozen)
  2972. ((upb_refcounted*)r)->individual_count--;
  2973. unref(r);
  2974. }
  2975. void upb_refcounted_ref2(const upb_refcounted *r, upb_refcounted *from) {
  2976. assert(!from->is_frozen); // Non-const pointer implies this.
  2977. track(r, from, true);
  2978. if (r->is_frozen) {
  2979. refgroup(r->group);
  2980. } else {
  2981. merge((upb_refcounted*)r, from);
  2982. }
  2983. }
  2984. void upb_refcounted_unref2(const upb_refcounted *r, upb_refcounted *from) {
  2985. assert(!from->is_frozen); // Non-const pointer implies this.
  2986. untrack(r, from, true);
  2987. if (r->is_frozen) {
  2988. unref(r);
  2989. } else {
  2990. assert(merged(r, from));
  2991. }
  2992. }
  2993. void upb_refcounted_donateref(
  2994. const upb_refcounted *r, const void *from, const void *to) {
  2995. assert(from != to);
  2996. if (to != NULL)
  2997. upb_refcounted_ref(r, to);
  2998. if (from != NULL)
  2999. upb_refcounted_unref(r, from);
  3000. }
  3001. void upb_refcounted_checkref(const upb_refcounted *r, const void *owner) {
  3002. checkref(r, owner, false);
  3003. }
  3004. bool upb_refcounted_freeze(upb_refcounted *const*roots, int n, upb_status *s,
  3005. int maxdepth) {
  3006. for (int i = 0; i < n; i++) {
  3007. assert(!roots[i]->is_frozen);
  3008. }
  3009. return freeze(roots, n, s, maxdepth);
  3010. }
  3011. /*
  3012. * upb - a minimalist implementation of protocol buffers.
  3013. *
  3014. * Copyright (c) 2013 Google Inc. See LICENSE for details.
  3015. * Author: Josh Haberman <jhaberman@gmail.com>
  3016. */
  3017. #include <stdlib.h>
  3018. // Fallback implementation if the shim is not specialized by the JIT.
  3019. #define SHIM_WRITER(type, ctype) \
  3020. bool upb_shim_set ## type (void *c, const void *hd, ctype val) { \
  3021. uint8_t *m = c; \
  3022. const upb_shim_data *d = hd; \
  3023. if (d->hasbit > 0) \
  3024. *(uint8_t*)&m[d->hasbit / 8] |= 1 << (d->hasbit % 8); \
  3025. *(ctype*)&m[d->offset] = val; \
  3026. return true; \
  3027. } \
  3028. SHIM_WRITER(double, double)
  3029. SHIM_WRITER(float, float)
  3030. SHIM_WRITER(int32, int32_t)
  3031. SHIM_WRITER(int64, int64_t)
  3032. SHIM_WRITER(uint32, uint32_t)
  3033. SHIM_WRITER(uint64, uint64_t)
  3034. SHIM_WRITER(bool, bool)
  3035. #undef SHIM_WRITER
  3036. bool upb_shim_set(upb_handlers *h, const upb_fielddef *f, size_t offset,
  3037. int32_t hasbit) {
  3038. upb_shim_data *d = malloc(sizeof(*d));
  3039. if (!d) return false;
  3040. d->offset = offset;
  3041. d->hasbit = hasbit;
  3042. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  3043. upb_handlerattr_sethandlerdata(&attr, d);
  3044. upb_handlerattr_setalwaysok(&attr, true);
  3045. upb_handlers_addcleanup(h, d, free);
  3046. #define TYPE(u, l) \
  3047. case UPB_TYPE_##u: \
  3048. ok = upb_handlers_set##l(h, f, upb_shim_set##l, &attr); break;
  3049. bool ok = false;
  3050. switch (upb_fielddef_type(f)) {
  3051. TYPE(INT64, int64);
  3052. TYPE(INT32, int32);
  3053. TYPE(ENUM, int32);
  3054. TYPE(UINT64, uint64);
  3055. TYPE(UINT32, uint32);
  3056. TYPE(DOUBLE, double);
  3057. TYPE(FLOAT, float);
  3058. TYPE(BOOL, bool);
  3059. default: assert(false); break;
  3060. }
  3061. #undef TYPE
  3062. upb_handlerattr_uninit(&attr);
  3063. return ok;
  3064. }
  3065. const upb_shim_data *upb_shim_getdata(const upb_handlers *h, upb_selector_t s,
  3066. upb_fieldtype_t *type) {
  3067. upb_func *f = upb_handlers_gethandler(h, s);
  3068. if ((upb_int64_handlerfunc*)f == upb_shim_setint64) {
  3069. *type = UPB_TYPE_INT64;
  3070. } else if ((upb_int32_handlerfunc*)f == upb_shim_setint32) {
  3071. *type = UPB_TYPE_INT32;
  3072. } else if ((upb_uint64_handlerfunc*)f == upb_shim_setuint64) {
  3073. *type = UPB_TYPE_UINT64;
  3074. } else if ((upb_uint32_handlerfunc*)f == upb_shim_setuint32) {
  3075. *type = UPB_TYPE_UINT32;
  3076. } else if ((upb_double_handlerfunc*)f == upb_shim_setdouble) {
  3077. *type = UPB_TYPE_DOUBLE;
  3078. } else if ((upb_float_handlerfunc*)f == upb_shim_setfloat) {
  3079. *type = UPB_TYPE_FLOAT;
  3080. } else if ((upb_bool_handlerfunc*)f == upb_shim_setbool) {
  3081. *type = UPB_TYPE_BOOL;
  3082. } else {
  3083. return NULL;
  3084. }
  3085. return (const upb_shim_data*)upb_handlers_gethandlerdata(h, s);
  3086. }
  3087. /*
  3088. * upb - a minimalist implementation of protocol buffers.
  3089. *
  3090. * Copyright (c) 2008-2012 Google Inc. See LICENSE for details.
  3091. * Author: Josh Haberman <jhaberman@gmail.com>
  3092. */
  3093. #include <stdlib.h>
  3094. #include <string.h>
  3095. bool upb_symtab_isfrozen(const upb_symtab *s) {
  3096. return upb_refcounted_isfrozen(UPB_UPCAST(s));
  3097. }
  3098. void upb_symtab_ref(const upb_symtab *s, const void *owner) {
  3099. upb_refcounted_ref(UPB_UPCAST(s), owner);
  3100. }
  3101. void upb_symtab_unref(const upb_symtab *s, const void *owner) {
  3102. upb_refcounted_unref(UPB_UPCAST(s), owner);
  3103. }
  3104. void upb_symtab_donateref(
  3105. const upb_symtab *s, const void *from, const void *to) {
  3106. upb_refcounted_donateref(UPB_UPCAST(s), from, to);
  3107. }
  3108. void upb_symtab_checkref(const upb_symtab *s, const void *owner) {
  3109. upb_refcounted_checkref(UPB_UPCAST(s), owner);
  3110. }
  3111. static void upb_symtab_free(upb_refcounted *r) {
  3112. upb_symtab *s = (upb_symtab*)r;
  3113. upb_strtable_iter i;
  3114. upb_strtable_begin(&i, &s->symtab);
  3115. for (; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  3116. const upb_def *def = upb_value_getptr(upb_strtable_iter_value(&i));
  3117. upb_def_unref(def, s);
  3118. }
  3119. upb_strtable_uninit(&s->symtab);
  3120. free(s);
  3121. }
  3122. upb_symtab *upb_symtab_new(const void *owner) {
  3123. static const struct upb_refcounted_vtbl vtbl = {NULL, &upb_symtab_free};
  3124. upb_symtab *s = malloc(sizeof(*s));
  3125. upb_refcounted_init(UPB_UPCAST(s), &vtbl, owner);
  3126. upb_strtable_init(&s->symtab, UPB_CTYPE_PTR);
  3127. return s;
  3128. }
  3129. void upb_symtab_freeze(upb_symtab *s) {
  3130. assert(!upb_symtab_isfrozen(s));
  3131. upb_refcounted *r = UPB_UPCAST(s);
  3132. // The symtab does not take ref2's (see refcounted.h) on the defs, because
  3133. // defs cannot refer back to the table and therefore cannot create cycles. So
  3134. // 0 will suffice for maxdepth here.
  3135. bool ok = upb_refcounted_freeze(&r, 1, NULL, 0);
  3136. UPB_ASSERT_VAR(ok, ok);
  3137. }
  3138. const upb_def *upb_symtab_lookup(const upb_symtab *s, const char *sym) {
  3139. upb_value v;
  3140. upb_def *ret = upb_strtable_lookup(&s->symtab, sym, &v) ?
  3141. upb_value_getptr(v) : NULL;
  3142. return ret;
  3143. }
  3144. const upb_msgdef *upb_symtab_lookupmsg(const upb_symtab *s, const char *sym) {
  3145. upb_value v;
  3146. upb_def *def = upb_strtable_lookup(&s->symtab, sym, &v) ?
  3147. upb_value_getptr(v) : NULL;
  3148. return def ? upb_dyncast_msgdef(def) : NULL;
  3149. }
  3150. const upb_enumdef *upb_symtab_lookupenum(const upb_symtab *s, const char *sym) {
  3151. upb_value v;
  3152. upb_def *def = upb_strtable_lookup(&s->symtab, sym, &v) ?
  3153. upb_value_getptr(v) : NULL;
  3154. return def ? upb_dyncast_enumdef(def) : NULL;
  3155. }
  3156. // Given a symbol and the base symbol inside which it is defined, find the
  3157. // symbol's definition in t.
  3158. static upb_def *upb_resolvename(const upb_strtable *t,
  3159. const char *base, const char *sym) {
  3160. if(strlen(sym) == 0) return NULL;
  3161. if(sym[0] == '.') {
  3162. // Symbols starting with '.' are absolute, so we do a single lookup.
  3163. // Slice to omit the leading '.'
  3164. upb_value v;
  3165. return upb_strtable_lookup(t, sym + 1, &v) ? upb_value_getptr(v) : NULL;
  3166. } else {
  3167. // Remove components from base until we find an entry or run out.
  3168. // TODO: This branch is totally broken, but currently not used.
  3169. (void)base;
  3170. assert(false);
  3171. return NULL;
  3172. }
  3173. }
  3174. const upb_def *upb_symtab_resolve(const upb_symtab *s, const char *base,
  3175. const char *sym) {
  3176. upb_def *ret = upb_resolvename(&s->symtab, base, sym);
  3177. return ret;
  3178. }
  3179. // Searches def and its children to find defs that have the same name as any
  3180. // def in "addtab." Returns true if any where found, and as a side-effect adds
  3181. // duplicates of these defs into addtab.
  3182. //
  3183. // We use a modified depth-first traversal that traverses each SCC (which we
  3184. // already computed) as if it were a single node. This allows us to traverse
  3185. // the possibly-cyclic graph as if it were a DAG and to dup the correct set of
  3186. // nodes with O(n) time.
  3187. static bool upb_resolve_dfs(const upb_def *def, upb_strtable *addtab,
  3188. const void *new_owner, upb_inttable *seen,
  3189. upb_status *s) {
  3190. // Memoize results of this function for efficiency (since we're traversing a
  3191. // DAG this is not needed to limit the depth of the search).
  3192. upb_value v;
  3193. if (upb_inttable_lookup(seen, (uintptr_t)def, &v))
  3194. return upb_value_getbool(v);
  3195. // Visit submessages for all messages in the SCC.
  3196. bool need_dup = false;
  3197. const upb_def *base = def;
  3198. do {
  3199. assert(upb_def_isfrozen(def));
  3200. if (def->type == UPB_DEF_FIELD) continue;
  3201. upb_value v;
  3202. if (upb_strtable_lookup(addtab, upb_def_fullname(def), &v)) {
  3203. need_dup = true;
  3204. }
  3205. // For messages, continue the recursion by visiting all subdefs.
  3206. const upb_msgdef *m = upb_dyncast_msgdef(def);
  3207. if (m) {
  3208. upb_msg_field_iter i;
  3209. for(upb_msg_field_begin(&i, m);
  3210. !upb_msg_field_done(&i);
  3211. upb_msg_field_next(&i)) {
  3212. upb_fielddef *f = upb_msg_iter_field(&i);
  3213. if (!upb_fielddef_hassubdef(f)) continue;
  3214. // |= to avoid short-circuit; we need its side-effects.
  3215. need_dup |= upb_resolve_dfs(
  3216. upb_fielddef_subdef(f), addtab, new_owner, seen, s);
  3217. if (!upb_ok(s)) return false;
  3218. }
  3219. }
  3220. } while ((def = (upb_def*)def->base.next) != base);
  3221. if (need_dup) {
  3222. // Dup any defs that don't already have entries in addtab.
  3223. def = base;
  3224. do {
  3225. if (def->type == UPB_DEF_FIELD) continue;
  3226. const char *name = upb_def_fullname(def);
  3227. if (!upb_strtable_lookup(addtab, name, NULL)) {
  3228. upb_def *newdef = upb_def_dup(def, new_owner);
  3229. if (!newdef) goto oom;
  3230. newdef->came_from_user = false;
  3231. if (!upb_strtable_insert(addtab, name, upb_value_ptr(newdef)))
  3232. goto oom;
  3233. }
  3234. } while ((def = (upb_def*)def->base.next) != base);
  3235. }
  3236. upb_inttable_insert(seen, (uintptr_t)def, upb_value_bool(need_dup));
  3237. return need_dup;
  3238. oom:
  3239. upb_status_seterrmsg(s, "out of memory");
  3240. return false;
  3241. }
  3242. // TODO(haberman): we need a lot more testing of error conditions.
  3243. // The came_from_user stuff in particular is not tested.
  3244. bool upb_symtab_add(upb_symtab *s, upb_def *const*defs, int n, void *ref_donor,
  3245. upb_status *status) {
  3246. assert(!upb_symtab_isfrozen(s));
  3247. upb_def **add_defs = NULL;
  3248. upb_strtable addtab;
  3249. if (!upb_strtable_init(&addtab, UPB_CTYPE_PTR)) {
  3250. upb_status_seterrmsg(status, "out of memory");
  3251. return false;
  3252. }
  3253. // Add new defs to our "add" set.
  3254. for (int i = 0; i < n; i++) {
  3255. upb_def *def = defs[i];
  3256. if (upb_def_isfrozen(def)) {
  3257. upb_status_seterrmsg(status, "added defs must be mutable");
  3258. goto err;
  3259. }
  3260. assert(!upb_def_isfrozen(def));
  3261. const char *fullname = upb_def_fullname(def);
  3262. if (!fullname) {
  3263. upb_status_seterrmsg(
  3264. status, "Anonymous defs cannot be added to a symtab");
  3265. goto err;
  3266. }
  3267. upb_fielddef *f = upb_dyncast_fielddef_mutable(def);
  3268. if (f) {
  3269. if (!upb_fielddef_containingtypename(f)) {
  3270. upb_status_seterrmsg(status,
  3271. "Standalone fielddefs must have a containing type "
  3272. "(extendee) name set");
  3273. goto err;
  3274. }
  3275. } else {
  3276. if (upb_strtable_lookup(&addtab, fullname, NULL)) {
  3277. upb_status_seterrf(status, "Conflicting defs named '%s'", fullname);
  3278. goto err;
  3279. }
  3280. // We need this to back out properly, because if there is a failure we
  3281. // need to donate the ref back to the caller.
  3282. def->came_from_user = true;
  3283. upb_def_donateref(def, ref_donor, s);
  3284. if (!upb_strtable_insert(&addtab, fullname, upb_value_ptr(def)))
  3285. goto oom_err;
  3286. }
  3287. }
  3288. // Add standalone fielddefs (ie. extensions) to the appropriate messages.
  3289. // If the appropriate message only exists in the existing symtab, duplicate
  3290. // it so we have a mutable copy we can add the fields to.
  3291. for (int i = 0; i < n; i++) {
  3292. upb_def *def = defs[i];
  3293. upb_fielddef *f = upb_dyncast_fielddef_mutable(def);
  3294. if (!f) continue;
  3295. const char *msgname = upb_fielddef_containingtypename(f);
  3296. // We validated this earlier in this function.
  3297. assert(msgname);
  3298. // If the extendee name is absolutely qualified, move past the initial ".".
  3299. // TODO(haberman): it is not obvious what it would mean if this was not
  3300. // absolutely qualified.
  3301. if (msgname[0] == '.') {
  3302. msgname++;
  3303. }
  3304. upb_value v;
  3305. upb_msgdef *m;
  3306. if (upb_strtable_lookup(&addtab, msgname, &v)) {
  3307. // Extendee is in the set of defs the user asked us to add.
  3308. m = upb_value_getptr(v);
  3309. } else {
  3310. // Need to find and dup the extendee from the existing symtab.
  3311. const upb_msgdef *frozen_m = upb_symtab_lookupmsg(s, msgname);
  3312. if (!frozen_m) {
  3313. upb_status_seterrf(status,
  3314. "Tried to extend message %s that does not exist "
  3315. "in this SymbolTable.",
  3316. msgname);
  3317. goto err;
  3318. }
  3319. m = upb_msgdef_dup(frozen_m, s);
  3320. if (!m) goto oom_err;
  3321. if (!upb_strtable_insert(&addtab, msgname, upb_value_ptr(m))) {
  3322. upb_msgdef_unref(m, s);
  3323. goto oom_err;
  3324. }
  3325. }
  3326. if (!upb_msgdef_addfield(m, f, ref_donor, status)) {
  3327. goto err;
  3328. }
  3329. }
  3330. // Add dups of any existing def that can reach a def with the same name as
  3331. // anything in our "add" set.
  3332. upb_inttable seen;
  3333. if (!upb_inttable_init(&seen, UPB_CTYPE_BOOL)) goto oom_err;
  3334. upb_strtable_iter i;
  3335. upb_strtable_begin(&i, &s->symtab);
  3336. for (; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  3337. upb_def *def = upb_value_getptr(upb_strtable_iter_value(&i));
  3338. upb_resolve_dfs(def, &addtab, s, &seen, status);
  3339. if (!upb_ok(status)) goto err;
  3340. }
  3341. upb_inttable_uninit(&seen);
  3342. // Now using the table, resolve symbolic references for subdefs.
  3343. upb_strtable_begin(&i, &addtab);
  3344. for (; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  3345. upb_def *def = upb_value_getptr(upb_strtable_iter_value(&i));
  3346. upb_msgdef *m = upb_dyncast_msgdef_mutable(def);
  3347. if (!m) continue;
  3348. // Type names are resolved relative to the message in which they appear.
  3349. const char *base = upb_msgdef_fullname(m);
  3350. upb_msg_field_iter j;
  3351. for(upb_msg_field_begin(&j, m);
  3352. !upb_msg_field_done(&j);
  3353. upb_msg_field_next(&j)) {
  3354. upb_fielddef *f = upb_msg_iter_field(&j);
  3355. const char *name = upb_fielddef_subdefname(f);
  3356. if (name && !upb_fielddef_subdef(f)) {
  3357. // Try the lookup in the current set of to-be-added defs first. If not
  3358. // there, try existing defs.
  3359. upb_def *subdef = upb_resolvename(&addtab, base, name);
  3360. if (subdef == NULL) {
  3361. subdef = upb_resolvename(&s->symtab, base, name);
  3362. }
  3363. if (subdef == NULL) {
  3364. upb_status_seterrf(
  3365. status, "couldn't resolve name '%s' in message '%s'", name, base);
  3366. goto err;
  3367. } else if (!upb_fielddef_setsubdef(f, subdef, status)) {
  3368. goto err;
  3369. }
  3370. }
  3371. }
  3372. }
  3373. // We need an array of the defs in addtab, for passing to upb_def_freeze.
  3374. add_defs = malloc(sizeof(void*) * upb_strtable_count(&addtab));
  3375. if (add_defs == NULL) goto oom_err;
  3376. upb_strtable_begin(&i, &addtab);
  3377. for (n = 0; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  3378. add_defs[n++] = upb_value_getptr(upb_strtable_iter_value(&i));
  3379. }
  3380. if (!upb_def_freeze(add_defs, n, status)) goto err;
  3381. // This must be delayed until all errors have been detected, since error
  3382. // recovery code uses this table to cleanup defs.
  3383. upb_strtable_uninit(&addtab);
  3384. // TODO(haberman) we don't properly handle errors after this point (like
  3385. // OOM in upb_strtable_insert() below).
  3386. for (int i = 0; i < n; i++) {
  3387. upb_def *def = add_defs[i];
  3388. const char *name = upb_def_fullname(def);
  3389. upb_value v;
  3390. if (upb_strtable_remove(&s->symtab, name, &v)) {
  3391. const upb_def *def = upb_value_getptr(v);
  3392. upb_def_unref(def, s);
  3393. }
  3394. bool success = upb_strtable_insert(&s->symtab, name, upb_value_ptr(def));
  3395. UPB_ASSERT_VAR(success, success == true);
  3396. }
  3397. free(add_defs);
  3398. return true;
  3399. oom_err:
  3400. upb_status_seterrmsg(status, "out of memory");
  3401. err: {
  3402. // For defs the user passed in, we need to donate the refs back. For defs
  3403. // we dup'd, we need to just unref them.
  3404. upb_strtable_iter i;
  3405. upb_strtable_begin(&i, &addtab);
  3406. for (; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  3407. upb_def *def = upb_value_getptr(upb_strtable_iter_value(&i));
  3408. bool came_from_user = def->came_from_user;
  3409. def->came_from_user = false;
  3410. if (came_from_user) {
  3411. upb_def_donateref(def, s, ref_donor);
  3412. } else {
  3413. upb_def_unref(def, s);
  3414. }
  3415. }
  3416. }
  3417. upb_strtable_uninit(&addtab);
  3418. free(add_defs);
  3419. assert(!upb_ok(status));
  3420. return false;
  3421. }
  3422. // Iteration.
  3423. static void advance_to_matching(upb_symtab_iter *iter) {
  3424. if (iter->type == UPB_DEF_ANY)
  3425. return;
  3426. while (!upb_strtable_done(&iter->iter) &&
  3427. iter->type != upb_symtab_iter_def(iter)->type) {
  3428. upb_strtable_next(&iter->iter);
  3429. }
  3430. }
  3431. void upb_symtab_begin(upb_symtab_iter *iter, const upb_symtab *s,
  3432. upb_deftype_t type) {
  3433. upb_strtable_begin(&iter->iter, &s->symtab);
  3434. iter->type = type;
  3435. advance_to_matching(iter);
  3436. }
  3437. void upb_symtab_next(upb_symtab_iter *iter) {
  3438. upb_strtable_next(&iter->iter);
  3439. advance_to_matching(iter);
  3440. }
  3441. bool upb_symtab_done(const upb_symtab_iter *iter) {
  3442. return upb_strtable_done(&iter->iter);
  3443. }
  3444. const upb_def *upb_symtab_iter_def(const upb_symtab_iter *iter) {
  3445. return upb_value_getptr(upb_strtable_iter_value(&iter->iter));
  3446. }
  3447. /*
  3448. * upb - a minimalist implementation of protocol buffers.
  3449. *
  3450. * Copyright (c) 2009 Google Inc. See LICENSE for details.
  3451. * Author: Josh Haberman <jhaberman@gmail.com>
  3452. *
  3453. * Implementation is heavily inspired by Lua's ltable.c.
  3454. */
  3455. #include <stdlib.h>
  3456. #include <string.h>
  3457. #define UPB_MAXARRSIZE 16 // 64k.
  3458. // From Chromium.
  3459. #define ARRAY_SIZE(x) \
  3460. ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x])))))
  3461. static const double MAX_LOAD = 0.85;
  3462. // The minimum utilization of the array part of a mixed hash/array table. This
  3463. // is a speed/memory-usage tradeoff (though it's not straightforward because of
  3464. // cache effects). The lower this is, the more memory we'll use.
  3465. static const double MIN_DENSITY = 0.1;
  3466. bool is_pow2(uint64_t v) { return v == 0 || (v & (v - 1)) == 0; }
  3467. int log2ceil(uint64_t v) {
  3468. int ret = 0;
  3469. bool pow2 = is_pow2(v);
  3470. while (v >>= 1) ret++;
  3471. ret = pow2 ? ret : ret + 1; // Ceiling.
  3472. return UPB_MIN(UPB_MAXARRSIZE, ret);
  3473. }
  3474. char *upb_strdup(const char *s) {
  3475. return upb_strdup2(s, strlen(s));
  3476. }
  3477. char *upb_strdup2(const char *s, size_t len) {
  3478. // Prevent overflow errors.
  3479. if (len == SIZE_MAX) return NULL;
  3480. // Always null-terminate, even if binary data; but don't rely on the input to
  3481. // have a null-terminating byte since it may be a raw binary buffer.
  3482. size_t n = len + 1;
  3483. char *p = malloc(n);
  3484. if (p) {
  3485. memcpy(p, s, len);
  3486. p[len] = 0;
  3487. }
  3488. return p;
  3489. }
  3490. // A type to represent the lookup key of either a strtable or an inttable.
  3491. typedef struct {
  3492. upb_tabkey key;
  3493. } lookupkey_t;
  3494. static lookupkey_t strkey2(const char *str, size_t len) {
  3495. lookupkey_t k;
  3496. k.key.s.str = (char*)str;
  3497. k.key.s.length = len;
  3498. return k;
  3499. }
  3500. static lookupkey_t intkey(uintptr_t key) {
  3501. lookupkey_t k;
  3502. k.key = upb_intkey(key);
  3503. return k;
  3504. }
  3505. typedef uint32_t hashfunc_t(upb_tabkey key);
  3506. typedef bool eqlfunc_t(upb_tabkey k1, lookupkey_t k2);
  3507. /* Base table (shared code) ***************************************************/
  3508. // For when we need to cast away const.
  3509. static upb_tabent *mutable_entries(upb_table *t) {
  3510. return (upb_tabent*)t->entries;
  3511. }
  3512. static bool isfull(upb_table *t) {
  3513. return (double)(t->count + 1) / upb_table_size(t) > MAX_LOAD;
  3514. }
  3515. static bool init(upb_table *t, upb_ctype_t ctype, uint8_t size_lg2) {
  3516. t->count = 0;
  3517. t->ctype = ctype;
  3518. t->size_lg2 = size_lg2;
  3519. t->mask = upb_table_size(t) ? upb_table_size(t) - 1 : 0;
  3520. size_t bytes = upb_table_size(t) * sizeof(upb_tabent);
  3521. if (bytes > 0) {
  3522. t->entries = malloc(bytes);
  3523. if (!t->entries) return false;
  3524. memset(mutable_entries(t), 0, bytes);
  3525. } else {
  3526. t->entries = NULL;
  3527. }
  3528. return true;
  3529. }
  3530. static void uninit(upb_table *t) { free(mutable_entries(t)); }
  3531. static upb_tabent *emptyent(upb_table *t) {
  3532. upb_tabent *e = mutable_entries(t) + upb_table_size(t);
  3533. while (1) { if (upb_tabent_isempty(--e)) return e; assert(e > t->entries); }
  3534. }
  3535. static upb_tabent *getentry_mutable(upb_table *t, uint32_t hash) {
  3536. return (upb_tabent*)upb_getentry(t, hash);
  3537. }
  3538. static const upb_tabent *findentry(const upb_table *t, lookupkey_t key,
  3539. uint32_t hash, eqlfunc_t *eql) {
  3540. if (t->size_lg2 == 0) return NULL;
  3541. const upb_tabent *e = upb_getentry(t, hash);
  3542. if (upb_tabent_isempty(e)) return NULL;
  3543. while (1) {
  3544. if (eql(e->key, key)) return e;
  3545. if ((e = e->next) == NULL) return NULL;
  3546. }
  3547. }
  3548. static upb_tabent *findentry_mutable(upb_table *t, lookupkey_t key,
  3549. uint32_t hash, eqlfunc_t *eql) {
  3550. return (upb_tabent*)findentry(t, key, hash, eql);
  3551. }
  3552. static bool lookup(const upb_table *t, lookupkey_t key, upb_value *v,
  3553. uint32_t hash, eqlfunc_t *eql) {
  3554. const upb_tabent *e = findentry(t, key, hash, eql);
  3555. if (e) {
  3556. if (v) {
  3557. _upb_value_setval(v, e->val, t->ctype);
  3558. }
  3559. return true;
  3560. } else {
  3561. return false;
  3562. }
  3563. }
  3564. // The given key must not already exist in the table.
  3565. static void insert(upb_table *t, lookupkey_t key, upb_value val,
  3566. uint32_t hash, hashfunc_t *hashfunc, eqlfunc_t *eql) {
  3567. UPB_UNUSED(eql);
  3568. assert(findentry(t, key, hash, eql) == NULL);
  3569. assert(val.ctype == t->ctype);
  3570. t->count++;
  3571. upb_tabent *mainpos_e = getentry_mutable(t, hash);
  3572. upb_tabent *our_e = mainpos_e;
  3573. if (upb_tabent_isempty(mainpos_e)) {
  3574. // Our main position is empty; use it.
  3575. our_e->next = NULL;
  3576. } else {
  3577. // Collision.
  3578. upb_tabent *new_e = emptyent(t);
  3579. // Head of collider's chain.
  3580. upb_tabent *chain = getentry_mutable(t, hashfunc(mainpos_e->key));
  3581. if (chain == mainpos_e) {
  3582. // Existing ent is in its main posisiton (it has the same hash as us, and
  3583. // is the head of our chain). Insert to new ent and append to this chain.
  3584. new_e->next = mainpos_e->next;
  3585. mainpos_e->next = new_e;
  3586. our_e = new_e;
  3587. } else {
  3588. // Existing ent is not in its main position (it is a node in some other
  3589. // chain). This implies that no existing ent in the table has our hash.
  3590. // Evict it (updating its chain) and use its ent for head of our chain.
  3591. *new_e = *mainpos_e; // copies next.
  3592. while (chain->next != mainpos_e) {
  3593. chain = (upb_tabent*)chain->next;
  3594. assert(chain);
  3595. }
  3596. chain->next = new_e;
  3597. our_e = mainpos_e;
  3598. our_e->next = NULL;
  3599. }
  3600. }
  3601. our_e->key = key.key;
  3602. our_e->val = val.val;
  3603. assert(findentry(t, key, hash, eql) == our_e);
  3604. }
  3605. static bool rm(upb_table *t, lookupkey_t key, upb_value *val,
  3606. upb_tabkey *removed, uint32_t hash, eqlfunc_t *eql) {
  3607. upb_tabent *chain = getentry_mutable(t, hash);
  3608. if (upb_tabent_isempty(chain)) return false;
  3609. if (eql(chain->key, key)) {
  3610. // Element to remove is at the head of its chain.
  3611. t->count--;
  3612. if (val) {
  3613. _upb_value_setval(val, chain->val, t->ctype);
  3614. }
  3615. if (chain->next) {
  3616. upb_tabent *move = (upb_tabent*)chain->next;
  3617. *chain = *move;
  3618. if (removed) *removed = move->key;
  3619. move->key.num = 0; // Make the slot empty.
  3620. } else {
  3621. if (removed) *removed = chain->key;
  3622. chain->key.num = 0; // Make the slot empty.
  3623. }
  3624. return true;
  3625. } else {
  3626. // Element to remove is either in a non-head position or not in the table.
  3627. while (chain->next && !eql(chain->next->key, key))
  3628. chain = (upb_tabent*)chain->next;
  3629. if (chain->next) {
  3630. // Found element to remove.
  3631. if (val) {
  3632. _upb_value_setval(val, chain->next->val, t->ctype);
  3633. }
  3634. upb_tabent *rm = (upb_tabent*)chain->next;
  3635. if (removed) *removed = rm->key;
  3636. rm->key.num = 0;
  3637. chain->next = rm->next;
  3638. t->count--;
  3639. return true;
  3640. } else {
  3641. return false;
  3642. }
  3643. }
  3644. }
  3645. static size_t next(const upb_table *t, size_t i) {
  3646. do {
  3647. if (++i >= upb_table_size(t))
  3648. return SIZE_MAX;
  3649. } while(upb_tabent_isempty(&t->entries[i]));
  3650. return i;
  3651. }
  3652. static size_t begin(const upb_table *t) {
  3653. return next(t, -1);
  3654. }
  3655. /* upb_strtable ***************************************************************/
  3656. // A simple "subclass" of upb_table that only adds a hash function for strings.
  3657. static uint32_t strhash(upb_tabkey key) {
  3658. return MurmurHash2(key.s.str, key.s.length, 0);
  3659. }
  3660. static bool streql(upb_tabkey k1, lookupkey_t k2) {
  3661. return k1.s.length == k2.key.s.length &&
  3662. memcmp(k1.s.str, k2.key.s.str, k1.s.length) == 0;
  3663. }
  3664. bool upb_strtable_init(upb_strtable *t, upb_ctype_t ctype) {
  3665. return init(&t->t, ctype, 2);
  3666. }
  3667. void upb_strtable_uninit(upb_strtable *t) {
  3668. for (size_t i = 0; i < upb_table_size(&t->t); i++)
  3669. free((void*)t->t.entries[i].key.s.str);
  3670. uninit(&t->t);
  3671. }
  3672. bool upb_strtable_resize(upb_strtable *t, size_t size_lg2) {
  3673. upb_strtable new_table;
  3674. if (!init(&new_table.t, t->t.ctype, size_lg2))
  3675. return false;
  3676. upb_strtable_iter i;
  3677. upb_strtable_begin(&i, t);
  3678. for ( ; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  3679. upb_strtable_insert2(
  3680. &new_table,
  3681. upb_strtable_iter_key(&i),
  3682. upb_strtable_iter_keylength(&i),
  3683. upb_strtable_iter_value(&i));
  3684. }
  3685. upb_strtable_uninit(t);
  3686. *t = new_table;
  3687. return true;
  3688. }
  3689. bool upb_strtable_insert2(upb_strtable *t, const char *k, size_t len,
  3690. upb_value v) {
  3691. if (isfull(&t->t)) {
  3692. // Need to resize. New table of double the size, add old elements to it.
  3693. if (!upb_strtable_resize(t, t->t.size_lg2 + 1)) {
  3694. return false;
  3695. }
  3696. }
  3697. if ((k = upb_strdup2(k, len)) == NULL) return false;
  3698. lookupkey_t key = strkey2(k, len);
  3699. uint32_t hash = MurmurHash2(key.key.s.str, key.key.s.length, 0);
  3700. insert(&t->t, key, v, hash, &strhash, &streql);
  3701. return true;
  3702. }
  3703. bool upb_strtable_lookup2(const upb_strtable *t, const char *key, size_t len,
  3704. upb_value *v) {
  3705. uint32_t hash = MurmurHash2(key, len, 0);
  3706. return lookup(&t->t, strkey2(key, len), v, hash, &streql);
  3707. }
  3708. bool upb_strtable_remove2(upb_strtable *t, const char *key, size_t len,
  3709. upb_value *val) {
  3710. uint32_t hash = MurmurHash2(key, strlen(key), 0);
  3711. upb_tabkey tabkey;
  3712. if (rm(&t->t, strkey2(key, len), val, &tabkey, hash, &streql)) {
  3713. free((void*)tabkey.s.str);
  3714. return true;
  3715. } else {
  3716. return false;
  3717. }
  3718. }
  3719. // Iteration
  3720. static const upb_tabent *str_tabent(const upb_strtable_iter *i) {
  3721. return &i->t->t.entries[i->index];
  3722. }
  3723. void upb_strtable_begin(upb_strtable_iter *i, const upb_strtable *t) {
  3724. i->t = t;
  3725. i->index = begin(&t->t);
  3726. }
  3727. void upb_strtable_next(upb_strtable_iter *i) {
  3728. i->index = next(&i->t->t, i->index);
  3729. }
  3730. bool upb_strtable_done(const upb_strtable_iter *i) {
  3731. return i->index >= upb_table_size(&i->t->t) ||
  3732. upb_tabent_isempty(str_tabent(i));
  3733. }
  3734. const char *upb_strtable_iter_key(upb_strtable_iter *i) {
  3735. assert(!upb_strtable_done(i));
  3736. return str_tabent(i)->key.s.str;
  3737. }
  3738. size_t upb_strtable_iter_keylength(upb_strtable_iter *i) {
  3739. assert(!upb_strtable_done(i));
  3740. return str_tabent(i)->key.s.length;
  3741. }
  3742. upb_value upb_strtable_iter_value(const upb_strtable_iter *i) {
  3743. assert(!upb_strtable_done(i));
  3744. return _upb_value_val(str_tabent(i)->val, i->t->t.ctype);
  3745. }
  3746. void upb_strtable_iter_setdone(upb_strtable_iter *i) {
  3747. i->index = SIZE_MAX;
  3748. }
  3749. bool upb_strtable_iter_isequal(const upb_strtable_iter *i1,
  3750. const upb_strtable_iter *i2) {
  3751. if (upb_strtable_done(i1) && upb_strtable_done(i2))
  3752. return true;
  3753. return i1->t == i2->t && i1->index == i2->index;
  3754. }
  3755. /* upb_inttable ***************************************************************/
  3756. // For inttables we use a hybrid structure where small keys are kept in an
  3757. // array and large keys are put in the hash table.
  3758. static uint32_t inthash(upb_tabkey key) { return upb_inthash(key.num); }
  3759. static bool inteql(upb_tabkey k1, lookupkey_t k2) {
  3760. return k1.num == k2.key.num;
  3761. }
  3762. static _upb_value *mutable_array(upb_inttable *t) {
  3763. return (_upb_value*)t->array;
  3764. }
  3765. static _upb_value *inttable_val(upb_inttable *t, uintptr_t key) {
  3766. if (key < t->array_size) {
  3767. return upb_arrhas(t->array[key]) ? &(mutable_array(t)[key]) : NULL;
  3768. } else {
  3769. upb_tabent *e =
  3770. findentry_mutable(&t->t, intkey(key), upb_inthash(key), &inteql);
  3771. return e ? &e->val : NULL;
  3772. }
  3773. }
  3774. static const _upb_value *inttable_val_const(const upb_inttable *t,
  3775. uintptr_t key) {
  3776. return inttable_val((upb_inttable*)t, key);
  3777. }
  3778. size_t upb_inttable_count(const upb_inttable *t) {
  3779. return t->t.count + t->array_count;
  3780. }
  3781. static void check(upb_inttable *t) {
  3782. UPB_UNUSED(t);
  3783. #if defined(UPB_DEBUG_TABLE) && !defined(NDEBUG)
  3784. // This check is very expensive (makes inserts/deletes O(N)).
  3785. size_t count = 0;
  3786. upb_inttable_iter i;
  3787. upb_inttable_begin(&i, t);
  3788. for(; !upb_inttable_done(&i); upb_inttable_next(&i), count++) {
  3789. assert(upb_inttable_lookup(t, upb_inttable_iter_key(&i), NULL));
  3790. }
  3791. assert(count == upb_inttable_count(t));
  3792. #endif
  3793. }
  3794. bool upb_inttable_sizedinit(upb_inttable *t, upb_ctype_t ctype,
  3795. size_t asize, int hsize_lg2) {
  3796. if (!init(&t->t, ctype, hsize_lg2)) return false;
  3797. // Always make the array part at least 1 long, so that we know key 0
  3798. // won't be in the hash part, which simplifies things.
  3799. t->array_size = UPB_MAX(1, asize);
  3800. t->array_count = 0;
  3801. size_t array_bytes = t->array_size * sizeof(upb_value);
  3802. t->array = malloc(array_bytes);
  3803. if (!t->array) {
  3804. uninit(&t->t);
  3805. return false;
  3806. }
  3807. memset(mutable_array(t), 0xff, array_bytes);
  3808. check(t);
  3809. return true;
  3810. }
  3811. bool upb_inttable_init(upb_inttable *t, upb_ctype_t ctype) {
  3812. return upb_inttable_sizedinit(t, ctype, 0, 4);
  3813. }
  3814. void upb_inttable_uninit(upb_inttable *t) {
  3815. uninit(&t->t);
  3816. free(mutable_array(t));
  3817. }
  3818. bool upb_inttable_insert(upb_inttable *t, uintptr_t key, upb_value val) {
  3819. assert(upb_arrhas(val.val));
  3820. if (key < t->array_size) {
  3821. assert(!upb_arrhas(t->array[key]));
  3822. t->array_count++;
  3823. mutable_array(t)[key] = val.val;
  3824. } else {
  3825. if (isfull(&t->t)) {
  3826. // Need to resize the hash part, but we re-use the array part.
  3827. upb_table new_table;
  3828. if (!init(&new_table, t->t.ctype, t->t.size_lg2 + 1))
  3829. return false;
  3830. size_t i;
  3831. for (i = begin(&t->t); i < upb_table_size(&t->t); i = next(&t->t, i)) {
  3832. const upb_tabent *e = &t->t.entries[i];
  3833. upb_value v;
  3834. _upb_value_setval(&v, e->val, t->t.ctype);
  3835. uint32_t hash = upb_inthash(e->key.num);
  3836. insert(&new_table, intkey(e->key.num), v, hash, &inthash, &inteql);
  3837. }
  3838. assert(t->t.count == new_table.count);
  3839. uninit(&t->t);
  3840. t->t = new_table;
  3841. }
  3842. insert(&t->t, intkey(key), val, upb_inthash(key), &inthash, &inteql);
  3843. }
  3844. check(t);
  3845. return true;
  3846. }
  3847. bool upb_inttable_lookup(const upb_inttable *t, uintptr_t key, upb_value *v) {
  3848. const _upb_value *table_v = inttable_val_const(t, key);
  3849. if (!table_v) return false;
  3850. if (v) _upb_value_setval(v, *table_v, t->t.ctype);
  3851. return true;
  3852. }
  3853. bool upb_inttable_replace(upb_inttable *t, uintptr_t key, upb_value val) {
  3854. _upb_value *table_v = inttable_val(t, key);
  3855. if (!table_v) return false;
  3856. *table_v = val.val;
  3857. return true;
  3858. }
  3859. bool upb_inttable_remove(upb_inttable *t, uintptr_t key, upb_value *val) {
  3860. bool success;
  3861. if (key < t->array_size) {
  3862. if (upb_arrhas(t->array[key])) {
  3863. t->array_count--;
  3864. if (val) {
  3865. _upb_value_setval(val, t->array[key], t->t.ctype);
  3866. }
  3867. _upb_value empty = UPB_ARRAY_EMPTYENT;
  3868. mutable_array(t)[key] = empty;
  3869. success = true;
  3870. } else {
  3871. success = false;
  3872. }
  3873. } else {
  3874. upb_tabkey removed;
  3875. uint32_t hash = upb_inthash(key);
  3876. success = rm(&t->t, intkey(key), val, &removed, hash, &inteql);
  3877. }
  3878. check(t);
  3879. return success;
  3880. }
  3881. bool upb_inttable_push(upb_inttable *t, upb_value val) {
  3882. return upb_inttable_insert(t, upb_inttable_count(t), val);
  3883. }
  3884. upb_value upb_inttable_pop(upb_inttable *t) {
  3885. upb_value val;
  3886. bool ok = upb_inttable_remove(t, upb_inttable_count(t) - 1, &val);
  3887. UPB_ASSERT_VAR(ok, ok);
  3888. return val;
  3889. }
  3890. bool upb_inttable_insertptr(upb_inttable *t, const void *key, upb_value val) {
  3891. return upb_inttable_insert(t, (uintptr_t)key, val);
  3892. }
  3893. bool upb_inttable_lookupptr(const upb_inttable *t, const void *key,
  3894. upb_value *v) {
  3895. return upb_inttable_lookup(t, (uintptr_t)key, v);
  3896. }
  3897. bool upb_inttable_removeptr(upb_inttable *t, const void *key, upb_value *val) {
  3898. return upb_inttable_remove(t, (uintptr_t)key, val);
  3899. }
  3900. void upb_inttable_compact(upb_inttable *t) {
  3901. // Create a power-of-two histogram of the table keys.
  3902. int counts[UPB_MAXARRSIZE + 1] = {0};
  3903. uintptr_t max_key = 0;
  3904. upb_inttable_iter i;
  3905. upb_inttable_begin(&i, t);
  3906. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  3907. uintptr_t key = upb_inttable_iter_key(&i);
  3908. if (key > max_key) {
  3909. max_key = key;
  3910. }
  3911. counts[log2ceil(key)]++;
  3912. }
  3913. size_t arr_size = 1;
  3914. int arr_count = upb_inttable_count(t);
  3915. if (upb_inttable_count(t) >= max_key * MIN_DENSITY) {
  3916. // We can put 100% of the entries in the array part.
  3917. arr_size = max_key + 1;
  3918. } else {
  3919. // Find the largest power of two that satisfies the MIN_DENSITY definition.
  3920. for (int size_lg2 = ARRAY_SIZE(counts) - 1; size_lg2 > 1; size_lg2--) {
  3921. arr_size = 1 << size_lg2;
  3922. arr_count -= counts[size_lg2];
  3923. if (arr_count >= arr_size * MIN_DENSITY) {
  3924. break;
  3925. }
  3926. }
  3927. }
  3928. // Array part must always be at least 1 entry large to catch lookups of key
  3929. // 0. Key 0 must always be in the array part because "0" in the hash part
  3930. // denotes an empty entry.
  3931. arr_size = UPB_MAX(arr_size, 1);
  3932. // Insert all elements into new, perfectly-sized table.
  3933. int hash_count = upb_inttable_count(t) - arr_count;
  3934. int hash_size = hash_count ? (hash_count / MAX_LOAD) + 1 : 0;
  3935. int hashsize_lg2 = log2ceil(hash_size);
  3936. assert(hash_count >= 0);
  3937. upb_inttable new_t;
  3938. upb_inttable_sizedinit(&new_t, t->t.ctype, arr_size, hashsize_lg2);
  3939. upb_inttable_begin(&i, t);
  3940. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  3941. uintptr_t k = upb_inttable_iter_key(&i);
  3942. upb_inttable_insert(&new_t, k, upb_inttable_iter_value(&i));
  3943. }
  3944. assert(new_t.array_size == arr_size);
  3945. assert(new_t.t.size_lg2 == hashsize_lg2);
  3946. upb_inttable_uninit(t);
  3947. *t = new_t;
  3948. }
  3949. // Iteration.
  3950. static const upb_tabent *int_tabent(const upb_inttable_iter *i) {
  3951. assert(!i->array_part);
  3952. return &i->t->t.entries[i->index];
  3953. }
  3954. static _upb_value int_arrent(const upb_inttable_iter *i) {
  3955. assert(i->array_part);
  3956. return i->t->array[i->index];
  3957. }
  3958. void upb_inttable_begin(upb_inttable_iter *i, const upb_inttable *t) {
  3959. i->t = t;
  3960. i->index = -1;
  3961. i->array_part = true;
  3962. upb_inttable_next(i);
  3963. }
  3964. void upb_inttable_next(upb_inttable_iter *iter) {
  3965. const upb_inttable *t = iter->t;
  3966. if (iter->array_part) {
  3967. while (++iter->index < t->array_size) {
  3968. if (upb_arrhas(int_arrent(iter))) {
  3969. return;
  3970. }
  3971. }
  3972. iter->array_part = false;
  3973. iter->index = begin(&t->t);
  3974. } else {
  3975. iter->index = next(&t->t, iter->index);
  3976. }
  3977. }
  3978. bool upb_inttable_done(const upb_inttable_iter *i) {
  3979. if (i->array_part) {
  3980. return i->index >= i->t->array_size ||
  3981. !upb_arrhas(int_arrent(i));
  3982. } else {
  3983. return i->index >= upb_table_size(&i->t->t) ||
  3984. upb_tabent_isempty(int_tabent(i));
  3985. }
  3986. }
  3987. uintptr_t upb_inttable_iter_key(const upb_inttable_iter *i) {
  3988. assert(!upb_inttable_done(i));
  3989. return i->array_part ? i->index : int_tabent(i)->key.num;
  3990. }
  3991. upb_value upb_inttable_iter_value(const upb_inttable_iter *i) {
  3992. assert(!upb_inttable_done(i));
  3993. return _upb_value_val(
  3994. i->array_part ? i->t->array[i->index] : int_tabent(i)->val,
  3995. i->t->t.ctype);
  3996. }
  3997. void upb_inttable_iter_setdone(upb_inttable_iter *i) {
  3998. i->index = SIZE_MAX;
  3999. i->array_part = false;
  4000. }
  4001. bool upb_inttable_iter_isequal(const upb_inttable_iter *i1,
  4002. const upb_inttable_iter *i2) {
  4003. if (upb_inttable_done(i1) && upb_inttable_done(i2))
  4004. return true;
  4005. return i1->t == i2->t && i1->index == i2->index &&
  4006. i1->array_part == i2->array_part;
  4007. }
  4008. #ifdef UPB_UNALIGNED_READS_OK
  4009. //-----------------------------------------------------------------------------
  4010. // MurmurHash2, by Austin Appleby (released as public domain).
  4011. // Reformatted and C99-ified by Joshua Haberman.
  4012. // Note - This code makes a few assumptions about how your machine behaves -
  4013. // 1. We can read a 4-byte value from any address without crashing
  4014. // 2. sizeof(int) == 4 (in upb this limitation is removed by using uint32_t
  4015. // And it has a few limitations -
  4016. // 1. It will not work incrementally.
  4017. // 2. It will not produce the same results on little-endian and big-endian
  4018. // machines.
  4019. uint32_t MurmurHash2(const void *key, size_t len, uint32_t seed) {
  4020. // 'm' and 'r' are mixing constants generated offline.
  4021. // They're not really 'magic', they just happen to work well.
  4022. const uint32_t m = 0x5bd1e995;
  4023. const int32_t r = 24;
  4024. // Initialize the hash to a 'random' value
  4025. uint32_t h = seed ^ len;
  4026. // Mix 4 bytes at a time into the hash
  4027. const uint8_t * data = (const uint8_t *)key;
  4028. while(len >= 4) {
  4029. uint32_t k = *(uint32_t *)data;
  4030. k *= m;
  4031. k ^= k >> r;
  4032. k *= m;
  4033. h *= m;
  4034. h ^= k;
  4035. data += 4;
  4036. len -= 4;
  4037. }
  4038. // Handle the last few bytes of the input array
  4039. switch(len) {
  4040. case 3: h ^= data[2] << 16;
  4041. case 2: h ^= data[1] << 8;
  4042. case 1: h ^= data[0]; h *= m;
  4043. };
  4044. // Do a few final mixes of the hash to ensure the last few
  4045. // bytes are well-incorporated.
  4046. h ^= h >> 13;
  4047. h *= m;
  4048. h ^= h >> 15;
  4049. return h;
  4050. }
  4051. #else // !UPB_UNALIGNED_READS_OK
  4052. //-----------------------------------------------------------------------------
  4053. // MurmurHashAligned2, by Austin Appleby
  4054. // Same algorithm as MurmurHash2, but only does aligned reads - should be safer
  4055. // on certain platforms.
  4056. // Performance will be lower than MurmurHash2
  4057. #define MIX(h,k,m) { k *= m; k ^= k >> r; k *= m; h *= m; h ^= k; }
  4058. uint32_t MurmurHash2(const void * key, size_t len, uint32_t seed) {
  4059. const uint32_t m = 0x5bd1e995;
  4060. const int32_t r = 24;
  4061. const uint8_t * data = (const uint8_t *)key;
  4062. uint32_t h = seed ^ len;
  4063. uint8_t align = (uintptr_t)data & 3;
  4064. if(align && (len >= 4)) {
  4065. // Pre-load the temp registers
  4066. uint32_t t = 0, d = 0;
  4067. switch(align) {
  4068. case 1: t |= data[2] << 16;
  4069. case 2: t |= data[1] << 8;
  4070. case 3: t |= data[0];
  4071. }
  4072. t <<= (8 * align);
  4073. data += 4-align;
  4074. len -= 4-align;
  4075. int32_t sl = 8 * (4-align);
  4076. int32_t sr = 8 * align;
  4077. // Mix
  4078. while(len >= 4) {
  4079. d = *(uint32_t *)data;
  4080. t = (t >> sr) | (d << sl);
  4081. uint32_t k = t;
  4082. MIX(h,k,m);
  4083. t = d;
  4084. data += 4;
  4085. len -= 4;
  4086. }
  4087. // Handle leftover data in temp registers
  4088. d = 0;
  4089. if(len >= align) {
  4090. switch(align) {
  4091. case 3: d |= data[2] << 16;
  4092. case 2: d |= data[1] << 8;
  4093. case 1: d |= data[0];
  4094. }
  4095. uint32_t k = (t >> sr) | (d << sl);
  4096. MIX(h,k,m);
  4097. data += align;
  4098. len -= align;
  4099. //----------
  4100. // Handle tail bytes
  4101. switch(len) {
  4102. case 3: h ^= data[2] << 16;
  4103. case 2: h ^= data[1] << 8;
  4104. case 1: h ^= data[0]; h *= m;
  4105. };
  4106. } else {
  4107. switch(len) {
  4108. case 3: d |= data[2] << 16;
  4109. case 2: d |= data[1] << 8;
  4110. case 1: d |= data[0];
  4111. case 0: h ^= (t >> sr) | (d << sl); h *= m;
  4112. }
  4113. }
  4114. h ^= h >> 13;
  4115. h *= m;
  4116. h ^= h >> 15;
  4117. return h;
  4118. } else {
  4119. while(len >= 4) {
  4120. uint32_t k = *(uint32_t *)data;
  4121. MIX(h,k,m);
  4122. data += 4;
  4123. len -= 4;
  4124. }
  4125. //----------
  4126. // Handle tail bytes
  4127. switch(len) {
  4128. case 3: h ^= data[2] << 16;
  4129. case 2: h ^= data[1] << 8;
  4130. case 1: h ^= data[0]; h *= m;
  4131. };
  4132. h ^= h >> 13;
  4133. h *= m;
  4134. h ^= h >> 15;
  4135. return h;
  4136. }
  4137. }
  4138. #undef MIX
  4139. #endif // UPB_UNALIGNED_READS_OK
  4140. /*
  4141. * upb - a minimalist implementation of protocol buffers.
  4142. *
  4143. * Copyright (c) 2009-2012 Google Inc. See LICENSE for details.
  4144. * Author: Josh Haberman <jhaberman@gmail.com>
  4145. */
  4146. #include <errno.h>
  4147. #include <stdarg.h>
  4148. #include <stddef.h>
  4149. #include <stdint.h>
  4150. #include <stdio.h>
  4151. #include <stdlib.h>
  4152. #include <string.h>
  4153. bool upb_dumptostderr(void *closure, const upb_status* status) {
  4154. UPB_UNUSED(closure);
  4155. fprintf(stderr, "%s\n", upb_status_errmsg(status));
  4156. return false;
  4157. }
  4158. // Guarantee null-termination and provide ellipsis truncation.
  4159. // It may be tempting to "optimize" this by initializing these final
  4160. // four bytes up-front and then being careful never to overwrite them,
  4161. // this is safer and simpler.
  4162. static void nullz(upb_status *status) {
  4163. const char *ellipsis = "...";
  4164. size_t len = strlen(ellipsis);
  4165. assert(sizeof(status->msg) > len);
  4166. memcpy(status->msg + sizeof(status->msg) - len, ellipsis, len);
  4167. }
  4168. void upb_status_clear(upb_status *status) {
  4169. if (!status) return;
  4170. status->ok_ = true;
  4171. status->code_ = 0;
  4172. status->msg[0] = '\0';
  4173. }
  4174. bool upb_ok(const upb_status *status) { return status->ok_; }
  4175. upb_errorspace *upb_status_errspace(const upb_status *status) {
  4176. return status->error_space_;
  4177. }
  4178. int upb_status_errcode(const upb_status *status) { return status->code_; }
  4179. const char *upb_status_errmsg(const upb_status *status) { return status->msg; }
  4180. void upb_status_seterrmsg(upb_status *status, const char *msg) {
  4181. if (!status) return;
  4182. status->ok_ = false;
  4183. strncpy(status->msg, msg, sizeof(status->msg));
  4184. nullz(status);
  4185. }
  4186. void upb_status_seterrf(upb_status *status, const char *fmt, ...) {
  4187. va_list args;
  4188. va_start(args, fmt);
  4189. upb_status_vseterrf(status, fmt, args);
  4190. va_end(args);
  4191. }
  4192. void upb_status_vseterrf(upb_status *status, const char *fmt, va_list args) {
  4193. if (!status) return;
  4194. status->ok_ = false;
  4195. vsnprintf(status->msg, sizeof(status->msg), fmt, args);
  4196. nullz(status);
  4197. }
  4198. void upb_status_seterrcode(upb_status *status, upb_errorspace *space,
  4199. int code) {
  4200. if (!status) return;
  4201. status->ok_ = false;
  4202. status->error_space_ = space;
  4203. status->code_ = code;
  4204. space->set_message(status, code);
  4205. }
  4206. void upb_status_copy(upb_status *to, const upb_status *from) {
  4207. if (!to) return;
  4208. *to = *from;
  4209. }
  4210. // This file was generated by upbc (the upb compiler).
  4211. // Do not edit -- your changes will be discarded when the file is
  4212. // regenerated.
  4213. static const upb_msgdef msgs[20];
  4214. static const upb_fielddef fields[81];
  4215. static const upb_enumdef enums[4];
  4216. static const upb_tabent strentries[236];
  4217. static const upb_tabent intentries[14];
  4218. static const _upb_value arrays[232];
  4219. #ifdef UPB_DEBUG_REFS
  4220. static upb_inttable reftables[212];
  4221. #endif
  4222. static const upb_msgdef msgs[20] = {
  4223. UPB_MSGDEF_INIT("google.protobuf.DescriptorProto", 27, 6, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[0], 8, 7), UPB_STRTABLE_INIT(7, 15, UPB_CTYPE_PTR, 4, &strentries[0]),&reftables[0], &reftables[1]),
  4224. UPB_MSGDEF_INIT("google.protobuf.DescriptorProto.ExtensionRange", 4, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[8], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[16]),&reftables[2], &reftables[3]),
  4225. UPB_MSGDEF_INIT("google.protobuf.EnumDescriptorProto", 11, 2, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[11], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[20]),&reftables[4], &reftables[5]),
  4226. UPB_MSGDEF_INIT("google.protobuf.EnumOptions", 7, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[0], &arrays[15], 8, 1), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[24]),&reftables[6], &reftables[7]),
  4227. UPB_MSGDEF_INIT("google.protobuf.EnumValueDescriptorProto", 8, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[23], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[28]),&reftables[8], &reftables[9]),
  4228. UPB_MSGDEF_INIT("google.protobuf.EnumValueOptions", 6, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[2], &arrays[27], 4, 0), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[32]),&reftables[10], &reftables[11]),
  4229. UPB_MSGDEF_INIT("google.protobuf.FieldDescriptorProto", 19, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[31], 9, 8), UPB_STRTABLE_INIT(8, 15, UPB_CTYPE_PTR, 4, &strentries[36]),&reftables[12], &reftables[13]),
  4230. UPB_MSGDEF_INIT("google.protobuf.FieldOptions", 14, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[4], &arrays[40], 32, 6), UPB_STRTABLE_INIT(7, 15, UPB_CTYPE_PTR, 4, &strentries[52]),&reftables[14], &reftables[15]),
  4231. UPB_MSGDEF_INIT("google.protobuf.FileDescriptorProto", 39, 6, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[72], 12, 11), UPB_STRTABLE_INIT(11, 15, UPB_CTYPE_PTR, 4, &strentries[68]),&reftables[16], &reftables[17]),
  4232. UPB_MSGDEF_INIT("google.protobuf.FileDescriptorSet", 6, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[84], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[84]),&reftables[18], &reftables[19]),
  4233. UPB_MSGDEF_INIT("google.protobuf.FileOptions", 21, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[6], &arrays[86], 64, 9), UPB_STRTABLE_INIT(10, 15, UPB_CTYPE_PTR, 4, &strentries[88]),&reftables[20], &reftables[21]),
  4234. UPB_MSGDEF_INIT("google.protobuf.MessageOptions", 8, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[8], &arrays[150], 16, 2), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[104]),&reftables[22], &reftables[23]),
  4235. UPB_MSGDEF_INIT("google.protobuf.MethodDescriptorProto", 13, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[166], 5, 4), UPB_STRTABLE_INIT(4, 7, UPB_CTYPE_PTR, 3, &strentries[108]),&reftables[24], &reftables[25]),
  4236. UPB_MSGDEF_INIT("google.protobuf.MethodOptions", 6, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[10], &arrays[171], 4, 0), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[116]),&reftables[26], &reftables[27]),
  4237. UPB_MSGDEF_INIT("google.protobuf.ServiceDescriptorProto", 11, 2, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[175], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[120]),&reftables[28], &reftables[29]),
  4238. UPB_MSGDEF_INIT("google.protobuf.ServiceOptions", 6, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[12], &arrays[179], 4, 0), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[124]),&reftables[30], &reftables[31]),
  4239. UPB_MSGDEF_INIT("google.protobuf.SourceCodeInfo", 6, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[183], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[128]),&reftables[32], &reftables[33]),
  4240. UPB_MSGDEF_INIT("google.protobuf.SourceCodeInfo.Location", 14, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[185], 5, 4), UPB_STRTABLE_INIT(4, 7, UPB_CTYPE_PTR, 3, &strentries[132]),&reftables[34], &reftables[35]),
  4241. UPB_MSGDEF_INIT("google.protobuf.UninterpretedOption", 18, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[190], 9, 7), UPB_STRTABLE_INIT(7, 15, UPB_CTYPE_PTR, 4, &strentries[140]),&reftables[36], &reftables[37]),
  4242. UPB_MSGDEF_INIT("google.protobuf.UninterpretedOption.NamePart", 6, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[199], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[156]),&reftables[38], &reftables[39]),
  4243. };
  4244. static const upb_fielddef fields[81] = {
  4245. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "aggregate_value", 8, &msgs[18], NULL, 15, 6, {0},&reftables[40], &reftables[41]),
  4246. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "allow_alias", 2, &msgs[3], NULL, 6, 1, {0},&reftables[42], &reftables[43]),
  4247. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "cc_generic_services", 16, &msgs[10], NULL, 17, 6, {0},&reftables[44], &reftables[45]),
  4248. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "ctype", 1, &msgs[7], UPB_UPCAST(&enums[2]), 6, 1, {0},&reftables[46], &reftables[47]),
  4249. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "default_value", 7, &msgs[6], NULL, 16, 7, {0},&reftables[48], &reftables[49]),
  4250. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_STRING, 0, false, false, false, false, "dependency", 3, &msgs[8], NULL, 30, 8, {0},&reftables[50], &reftables[51]),
  4251. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[7], NULL, 8, 3, {0},&reftables[52], &reftables[53]),
  4252. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_DOUBLE, 0, false, false, false, false, "double_value", 6, &msgs[18], NULL, 11, 4, {0},&reftables[54], &reftables[55]),
  4253. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "end", 2, &msgs[1], NULL, 3, 1, {0},&reftables[56], &reftables[57]),
  4254. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "enum_type", 4, &msgs[0], UPB_UPCAST(&msgs[2]), 16, 2, {0},&reftables[58], &reftables[59]),
  4255. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "enum_type", 5, &msgs[8], UPB_UPCAST(&msgs[2]), 13, 1, {0},&reftables[60], &reftables[61]),
  4256. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "experimental_map_key", 9, &msgs[7], NULL, 10, 5, {0},&reftables[62], &reftables[63]),
  4257. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "extendee", 2, &msgs[6], NULL, 7, 2, {0},&reftables[64], &reftables[65]),
  4258. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension", 7, &msgs[8], UPB_UPCAST(&msgs[6]), 19, 3, {0},&reftables[66], &reftables[67]),
  4259. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension", 6, &msgs[0], UPB_UPCAST(&msgs[6]), 22, 4, {0},&reftables[68], &reftables[69]),
  4260. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension_range", 5, &msgs[0], UPB_UPCAST(&msgs[1]), 19, 3, {0},&reftables[70], &reftables[71]),
  4261. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "field", 2, &msgs[0], UPB_UPCAST(&msgs[6]), 10, 0, {0},&reftables[72], &reftables[73]),
  4262. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "file", 1, &msgs[9], UPB_UPCAST(&msgs[8]), 5, 0, {0},&reftables[74], &reftables[75]),
  4263. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "go_package", 11, &msgs[10], NULL, 14, 5, {0},&reftables[76], &reftables[77]),
  4264. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "identifier_value", 3, &msgs[18], NULL, 6, 1, {0},&reftables[78], &reftables[79]),
  4265. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "input_type", 2, &msgs[12], NULL, 7, 2, {0},&reftables[80], &reftables[81]),
  4266. UPB_FIELDDEF_INIT(UPB_LABEL_REQUIRED, UPB_TYPE_BOOL, 0, false, false, false, false, "is_extension", 2, &msgs[19], NULL, 5, 1, {0},&reftables[82], &reftables[83]),
  4267. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_generate_equals_and_hash", 20, &msgs[10], NULL, 20, 9, {0},&reftables[84], &reftables[85]),
  4268. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_generic_services", 17, &msgs[10], NULL, 18, 7, {0},&reftables[86], &reftables[87]),
  4269. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_multiple_files", 10, &msgs[10], NULL, 13, 4, {0},&reftables[88], &reftables[89]),
  4270. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "java_outer_classname", 8, &msgs[10], NULL, 9, 2, {0},&reftables[90], &reftables[91]),
  4271. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "java_package", 1, &msgs[10], NULL, 6, 1, {0},&reftables[92], &reftables[93]),
  4272. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "label", 4, &msgs[6], UPB_UPCAST(&enums[0]), 11, 4, {0},&reftables[94], &reftables[95]),
  4273. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "lazy", 5, &msgs[7], NULL, 9, 4, {0},&reftables[96], &reftables[97]),
  4274. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "leading_comments", 3, &msgs[17], NULL, 8, 2, {0},&reftables[98], &reftables[99]),
  4275. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "location", 1, &msgs[16], UPB_UPCAST(&msgs[17]), 5, 0, {0},&reftables[100], &reftables[101]),
  4276. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "message_set_wire_format", 1, &msgs[11], NULL, 6, 1, {0},&reftables[102], &reftables[103]),
  4277. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "message_type", 4, &msgs[8], UPB_UPCAST(&msgs[0]), 10, 0, {0},&reftables[104], &reftables[105]),
  4278. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "method", 2, &msgs[14], UPB_UPCAST(&msgs[12]), 6, 0, {0},&reftables[106], &reftables[107]),
  4279. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[8], NULL, 22, 6, {0},&reftables[108], &reftables[109]),
  4280. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[14], NULL, 8, 2, {0},&reftables[110], &reftables[111]),
  4281. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "name", 2, &msgs[18], UPB_UPCAST(&msgs[19]), 5, 0, {0},&reftables[112], &reftables[113]),
  4282. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[4], NULL, 4, 1, {0},&reftables[114], &reftables[115]),
  4283. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[0], NULL, 24, 6, {0},&reftables[116], &reftables[117]),
  4284. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[12], NULL, 4, 1, {0},&reftables[118], &reftables[119]),
  4285. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[2], NULL, 8, 2, {0},&reftables[120], &reftables[121]),
  4286. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[6], NULL, 4, 1, {0},&reftables[122], &reftables[123]),
  4287. UPB_FIELDDEF_INIT(UPB_LABEL_REQUIRED, UPB_TYPE_STRING, 0, false, false, false, false, "name_part", 1, &msgs[19], NULL, 2, 0, {0},&reftables[124], &reftables[125]),
  4288. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT64, UPB_INTFMT_VARIABLE, false, false, false, false, "negative_int_value", 5, &msgs[18], NULL, 10, 3, {0},&reftables[126], &reftables[127]),
  4289. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "nested_type", 3, &msgs[0], UPB_UPCAST(&msgs[0]), 13, 1, {0},&reftables[128], &reftables[129]),
  4290. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "no_standard_descriptor_accessor", 2, &msgs[11], NULL, 7, 2, {0},&reftables[130], &reftables[131]),
  4291. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "number", 3, &msgs[6], NULL, 10, 3, {0},&reftables[132], &reftables[133]),
  4292. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "number", 2, &msgs[4], NULL, 7, 2, {0},&reftables[134], &reftables[135]),
  4293. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "optimize_for", 9, &msgs[10], UPB_UPCAST(&enums[3]), 12, 3, {0},&reftables[136], &reftables[137]),
  4294. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 7, &msgs[0], UPB_UPCAST(&msgs[11]), 23, 5, {0},&reftables[138], &reftables[139]),
  4295. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[2], UPB_UPCAST(&msgs[3]), 7, 1, {0},&reftables[140], &reftables[141]),
  4296. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 8, &msgs[6], UPB_UPCAST(&msgs[7]), 3, 0, {0},&reftables[142], &reftables[143]),
  4297. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[4], UPB_UPCAST(&msgs[5]), 3, 0, {0},&reftables[144], &reftables[145]),
  4298. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 8, &msgs[8], UPB_UPCAST(&msgs[10]), 20, 4, {0},&reftables[146], &reftables[147]),
  4299. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[14], UPB_UPCAST(&msgs[15]), 7, 1, {0},&reftables[148], &reftables[149]),
  4300. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 4, &msgs[12], UPB_UPCAST(&msgs[13]), 3, 0, {0},&reftables[150], &reftables[151]),
  4301. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "output_type", 3, &msgs[12], NULL, 10, 3, {0},&reftables[152], &reftables[153]),
  4302. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "package", 2, &msgs[8], NULL, 25, 7, {0},&reftables[154], &reftables[155]),
  4303. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "packed", 2, &msgs[7], NULL, 7, 2, {0},&reftables[156], &reftables[157]),
  4304. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, true, "path", 1, &msgs[17], NULL, 4, 0, {0},&reftables[158], &reftables[159]),
  4305. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_UINT64, UPB_INTFMT_VARIABLE, false, false, false, false, "positive_int_value", 4, &msgs[18], NULL, 9, 2, {0},&reftables[160], &reftables[161]),
  4306. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "public_dependency", 10, &msgs[8], NULL, 35, 9, {0},&reftables[162], &reftables[163]),
  4307. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "py_generic_services", 18, &msgs[10], NULL, 19, 8, {0},&reftables[164], &reftables[165]),
  4308. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "service", 6, &msgs[8], UPB_UPCAST(&msgs[14]), 16, 2, {0},&reftables[166], &reftables[167]),
  4309. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "source_code_info", 9, &msgs[8], UPB_UPCAST(&msgs[16]), 21, 5, {0},&reftables[168], &reftables[169]),
  4310. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, true, "span", 2, &msgs[17], NULL, 7, 1, {0},&reftables[170], &reftables[171]),
  4311. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "start", 1, &msgs[1], NULL, 2, 0, {0},&reftables[172], &reftables[173]),
  4312. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BYTES, 0, false, false, false, false, "string_value", 7, &msgs[18], NULL, 12, 5, {0},&reftables[174], &reftables[175]),
  4313. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "trailing_comments", 4, &msgs[17], NULL, 11, 3, {0},&reftables[176], &reftables[177]),
  4314. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "type", 5, &msgs[6], UPB_UPCAST(&enums[1]), 12, 5, {0},&reftables[178], &reftables[179]),
  4315. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "type_name", 6, &msgs[6], NULL, 13, 6, {0},&reftables[180], &reftables[181]),
  4316. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[5], UPB_UPCAST(&msgs[18]), 5, 0, {0},&reftables[182], &reftables[183]),
  4317. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[15], UPB_UPCAST(&msgs[18]), 5, 0, {0},&reftables[184], &reftables[185]),
  4318. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[3], UPB_UPCAST(&msgs[18]), 5, 0, {0},&reftables[186], &reftables[187]),
  4319. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[13], UPB_UPCAST(&msgs[18]), 5, 0, {0},&reftables[188], &reftables[189]),
  4320. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[10], UPB_UPCAST(&msgs[18]), 5, 0, {0},&reftables[190], &reftables[191]),
  4321. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[11], UPB_UPCAST(&msgs[18]), 5, 0, {0},&reftables[192], &reftables[193]),
  4322. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[7], UPB_UPCAST(&msgs[18]), 5, 0, {0},&reftables[194], &reftables[195]),
  4323. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "value", 2, &msgs[2], UPB_UPCAST(&msgs[4]), 6, 0, {0},&reftables[196], &reftables[197]),
  4324. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "weak", 10, &msgs[7], NULL, 13, 6, {0},&reftables[198], &reftables[199]),
  4325. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "weak_dependency", 11, &msgs[8], NULL, 38, 10, {0},&reftables[200], &reftables[201]),
  4326. };
  4327. static const upb_enumdef enums[4] = {
  4328. UPB_ENUMDEF_INIT("google.protobuf.FieldDescriptorProto.Label", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[160]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[202], 4, 3), 0, &reftables[202], &reftables[203]),
  4329. UPB_ENUMDEF_INIT("google.protobuf.FieldDescriptorProto.Type", UPB_STRTABLE_INIT(18, 31, UPB_CTYPE_INT32, 5, &strentries[164]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[206], 19, 18), 0, &reftables[204], &reftables[205]),
  4330. UPB_ENUMDEF_INIT("google.protobuf.FieldOptions.CType", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[196]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[225], 3, 3), 0, &reftables[206], &reftables[207]),
  4331. UPB_ENUMDEF_INIT("google.protobuf.FileOptions.OptimizeMode", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[200]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[228], 4, 3), 0, &reftables[208], &reftables[209]),
  4332. };
  4333. static const upb_tabent strentries[236] = {
  4334. {UPB_TABKEY_STR("extension"), UPB_VALUE_INIT_CONSTPTR(&fields[14]), NULL},
  4335. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4336. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4337. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[38]), NULL},
  4338. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4339. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4340. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4341. {UPB_TABKEY_STR("field"), UPB_VALUE_INIT_CONSTPTR(&fields[16]), NULL},
  4342. {UPB_TABKEY_STR("extension_range"), UPB_VALUE_INIT_CONSTPTR(&fields[15]), NULL},
  4343. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4344. {UPB_TABKEY_STR("nested_type"), UPB_VALUE_INIT_CONSTPTR(&fields[44]), NULL},
  4345. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4346. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4347. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4348. {UPB_TABKEY_STR("options"), UPB_VALUE_INIT_CONSTPTR(&fields[49]), NULL},
  4349. {UPB_TABKEY_STR("enum_type"), UPB_VALUE_INIT_CONSTPTR(&fields[9]), &strentries[14]},
  4350. {UPB_TABKEY_STR("start"), UPB_VALUE_INIT_CONSTPTR(&fields[66]), NULL},
  4351. {UPB_TABKEY_STR("end"), UPB_VALUE_INIT_CONSTPTR(&fields[8]), NULL},
  4352. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4353. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4354. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4355. {UPB_TABKEY_STR("value"), UPB_VALUE_INIT_CONSTPTR(&fields[78]), NULL},
  4356. {UPB_TABKEY_STR("options"), UPB_VALUE_INIT_CONSTPTR(&fields[50]), NULL},
  4357. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[40]), &strentries[22]},
  4358. {UPB_TABKEY_STR("uninterpreted_option"), UPB_VALUE_INIT_CONSTPTR(&fields[73]), NULL},
  4359. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4360. {UPB_TABKEY_STR("allow_alias"), UPB_VALUE_INIT_CONSTPTR(&fields[1]), NULL},
  4361. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4362. {UPB_TABKEY_STR("number"), UPB_VALUE_INIT_CONSTPTR(&fields[47]), NULL},
  4363. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4364. {UPB_TABKEY_STR("options"), UPB_VALUE_INIT_CONSTPTR(&fields[52]), NULL},
  4365. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[37]), &strentries[30]},
  4366. {UPB_TABKEY_STR("uninterpreted_option"), UPB_VALUE_INIT_CONSTPTR(&fields[71]), NULL},
  4367. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4368. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4369. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4370. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4371. {UPB_TABKEY_STR("label"), UPB_VALUE_INIT_CONSTPTR(&fields[27]), NULL},
  4372. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4373. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[41]), NULL},
  4374. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4375. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4376. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4377. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4378. {UPB_TABKEY_STR("number"), UPB_VALUE_INIT_CONSTPTR(&fields[46]), &strentries[49]},
  4379. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4380. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4381. {UPB_TABKEY_STR("type_name"), UPB_VALUE_INIT_CONSTPTR(&fields[70]), NULL},
  4382. {UPB_TABKEY_STR("extendee"), UPB_VALUE_INIT_CONSTPTR(&fields[12]), NULL},
  4383. {UPB_TABKEY_STR("type"), UPB_VALUE_INIT_CONSTPTR(&fields[69]), &strentries[48]},
  4384. {UPB_TABKEY_STR("default_value"), UPB_VALUE_INIT_CONSTPTR(&fields[4]), NULL},
  4385. {UPB_TABKEY_STR("options"), UPB_VALUE_INIT_CONSTPTR(&fields[51]), NULL},
  4386. {UPB_TABKEY_STR("experimental_map_key"), UPB_VALUE_INIT_CONSTPTR(&fields[11]), &strentries[67]},
  4387. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4388. {UPB_TABKEY_STR("weak"), UPB_VALUE_INIT_CONSTPTR(&fields[79]), NULL},
  4389. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4390. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4391. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4392. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4393. {UPB_TABKEY_STR("packed"), UPB_VALUE_INIT_CONSTPTR(&fields[58]), NULL},
  4394. {UPB_TABKEY_STR("lazy"), UPB_VALUE_INIT_CONSTPTR(&fields[28]), NULL},
  4395. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4396. {UPB_TABKEY_STR("ctype"), UPB_VALUE_INIT_CONSTPTR(&fields[3]), NULL},
  4397. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4398. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4399. {UPB_TABKEY_STR("deprecated"), UPB_VALUE_INIT_CONSTPTR(&fields[6]), NULL},
  4400. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4401. {UPB_TABKEY_STR("uninterpreted_option"), UPB_VALUE_INIT_CONSTPTR(&fields[77]), NULL},
  4402. {UPB_TABKEY_STR("extension"), UPB_VALUE_INIT_CONSTPTR(&fields[13]), NULL},
  4403. {UPB_TABKEY_STR("weak_dependency"), UPB_VALUE_INIT_CONSTPTR(&fields[80]), NULL},
  4404. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4405. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[34]), NULL},
  4406. {UPB_TABKEY_STR("service"), UPB_VALUE_INIT_CONSTPTR(&fields[63]), NULL},
  4407. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4408. {UPB_TABKEY_STR("source_code_info"), UPB_VALUE_INIT_CONSTPTR(&fields[64]), NULL},
  4409. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4410. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4411. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4412. {UPB_TABKEY_STR("dependency"), UPB_VALUE_INIT_CONSTPTR(&fields[5]), NULL},
  4413. {UPB_TABKEY_STR("message_type"), UPB_VALUE_INIT_CONSTPTR(&fields[32]), NULL},
  4414. {UPB_TABKEY_STR("package"), UPB_VALUE_INIT_CONSTPTR(&fields[57]), NULL},
  4415. {UPB_TABKEY_STR("options"), UPB_VALUE_INIT_CONSTPTR(&fields[53]), &strentries[82]},
  4416. {UPB_TABKEY_STR("enum_type"), UPB_VALUE_INIT_CONSTPTR(&fields[10]), NULL},
  4417. {UPB_TABKEY_STR("public_dependency"), UPB_VALUE_INIT_CONSTPTR(&fields[61]), &strentries[81]},
  4418. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4419. {UPB_TABKEY_STR("file"), UPB_VALUE_INIT_CONSTPTR(&fields[17]), NULL},
  4420. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4421. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4422. {UPB_TABKEY_STR("uninterpreted_option"), UPB_VALUE_INIT_CONSTPTR(&fields[75]), NULL},
  4423. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4424. {UPB_TABKEY_STR("cc_generic_services"), UPB_VALUE_INIT_CONSTPTR(&fields[2]), NULL},
  4425. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4426. {UPB_TABKEY_STR("java_multiple_files"), UPB_VALUE_INIT_CONSTPTR(&fields[24]), NULL},
  4427. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4428. {UPB_TABKEY_STR("java_generic_services"), UPB_VALUE_INIT_CONSTPTR(&fields[23]), &strentries[102]},
  4429. {UPB_TABKEY_STR("java_generate_equals_and_hash"), UPB_VALUE_INIT_CONSTPTR(&fields[22]), NULL},
  4430. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4431. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4432. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4433. {UPB_TABKEY_STR("go_package"), UPB_VALUE_INIT_CONSTPTR(&fields[18]), NULL},
  4434. {UPB_TABKEY_STR("java_package"), UPB_VALUE_INIT_CONSTPTR(&fields[26]), NULL},
  4435. {UPB_TABKEY_STR("optimize_for"), UPB_VALUE_INIT_CONSTPTR(&fields[48]), NULL},
  4436. {UPB_TABKEY_STR("py_generic_services"), UPB_VALUE_INIT_CONSTPTR(&fields[62]), NULL},
  4437. {UPB_TABKEY_STR("java_outer_classname"), UPB_VALUE_INIT_CONSTPTR(&fields[25]), NULL},
  4438. {UPB_TABKEY_STR("message_set_wire_format"), UPB_VALUE_INIT_CONSTPTR(&fields[31]), &strentries[106]},
  4439. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4440. {UPB_TABKEY_STR("uninterpreted_option"), UPB_VALUE_INIT_CONSTPTR(&fields[76]), NULL},
  4441. {UPB_TABKEY_STR("no_standard_descriptor_accessor"), UPB_VALUE_INIT_CONSTPTR(&fields[45]), NULL},
  4442. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4443. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4444. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4445. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[39]), NULL},
  4446. {UPB_TABKEY_STR("input_type"), UPB_VALUE_INIT_CONSTPTR(&fields[20]), NULL},
  4447. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4448. {UPB_TABKEY_STR("output_type"), UPB_VALUE_INIT_CONSTPTR(&fields[56]), NULL},
  4449. {UPB_TABKEY_STR("options"), UPB_VALUE_INIT_CONSTPTR(&fields[55]), NULL},
  4450. {UPB_TABKEY_STR("uninterpreted_option"), UPB_VALUE_INIT_CONSTPTR(&fields[74]), NULL},
  4451. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4452. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4453. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4454. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4455. {UPB_TABKEY_STR("options"), UPB_VALUE_INIT_CONSTPTR(&fields[54]), &strentries[122]},
  4456. {UPB_TABKEY_STR("method"), UPB_VALUE_INIT_CONSTPTR(&fields[33]), NULL},
  4457. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[35]), &strentries[121]},
  4458. {UPB_TABKEY_STR("uninterpreted_option"), UPB_VALUE_INIT_CONSTPTR(&fields[72]), NULL},
  4459. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4460. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4461. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4462. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4463. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4464. {UPB_TABKEY_STR("location"), UPB_VALUE_INIT_CONSTPTR(&fields[30]), NULL},
  4465. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4466. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4467. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4468. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4469. {UPB_TABKEY_STR("span"), UPB_VALUE_INIT_CONSTPTR(&fields[65]), &strentries[139]},
  4470. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4471. {UPB_TABKEY_STR("trailing_comments"), UPB_VALUE_INIT_CONSTPTR(&fields[68]), NULL},
  4472. {UPB_TABKEY_STR("leading_comments"), UPB_VALUE_INIT_CONSTPTR(&fields[29]), &strentries[137]},
  4473. {UPB_TABKEY_STR("path"), UPB_VALUE_INIT_CONSTPTR(&fields[59]), NULL},
  4474. {UPB_TABKEY_STR("double_value"), UPB_VALUE_INIT_CONSTPTR(&fields[7]), NULL},
  4475. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4476. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4477. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[36]), NULL},
  4478. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4479. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4480. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4481. {UPB_TABKEY_STR("negative_int_value"), UPB_VALUE_INIT_CONSTPTR(&fields[43]), NULL},
  4482. {UPB_TABKEY_STR("aggregate_value"), UPB_VALUE_INIT_CONSTPTR(&fields[0]), NULL},
  4483. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4484. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4485. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4486. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4487. {UPB_TABKEY_STR("positive_int_value"), UPB_VALUE_INIT_CONSTPTR(&fields[60]), NULL},
  4488. {UPB_TABKEY_STR("identifier_value"), UPB_VALUE_INIT_CONSTPTR(&fields[19]), NULL},
  4489. {UPB_TABKEY_STR("string_value"), UPB_VALUE_INIT_CONSTPTR(&fields[67]), &strentries[154]},
  4490. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4491. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4492. {UPB_TABKEY_STR("is_extension"), UPB_VALUE_INIT_CONSTPTR(&fields[21]), NULL},
  4493. {UPB_TABKEY_STR("name_part"), UPB_VALUE_INIT_CONSTPTR(&fields[42]), NULL},
  4494. {UPB_TABKEY_STR("LABEL_REQUIRED"), UPB_VALUE_INIT_INT32(2), &strentries[162]},
  4495. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4496. {UPB_TABKEY_STR("LABEL_REPEATED"), UPB_VALUE_INIT_INT32(3), NULL},
  4497. {UPB_TABKEY_STR("LABEL_OPTIONAL"), UPB_VALUE_INIT_INT32(1), NULL},
  4498. {UPB_TABKEY_STR("TYPE_FIXED64"), UPB_VALUE_INIT_INT32(6), NULL},
  4499. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4500. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4501. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4502. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4503. {UPB_TABKEY_STR("TYPE_STRING"), UPB_VALUE_INIT_INT32(9), NULL},
  4504. {UPB_TABKEY_STR("TYPE_FLOAT"), UPB_VALUE_INIT_INT32(2), &strentries[193]},
  4505. {UPB_TABKEY_STR("TYPE_DOUBLE"), UPB_VALUE_INIT_INT32(1), NULL},
  4506. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4507. {UPB_TABKEY_STR("TYPE_INT32"), UPB_VALUE_INIT_INT32(5), NULL},
  4508. {UPB_TABKEY_STR("TYPE_SFIXED32"), UPB_VALUE_INIT_INT32(15), NULL},
  4509. {UPB_TABKEY_STR("TYPE_FIXED32"), UPB_VALUE_INIT_INT32(7), NULL},
  4510. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4511. {UPB_TABKEY_STR("TYPE_MESSAGE"), UPB_VALUE_INIT_INT32(11), &strentries[194]},
  4512. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4513. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4514. {UPB_TABKEY_STR("TYPE_INT64"), UPB_VALUE_INIT_INT32(3), &strentries[191]},
  4515. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4516. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4517. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4518. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4519. {UPB_TABKEY_STR("TYPE_ENUM"), UPB_VALUE_INIT_INT32(14), NULL},
  4520. {UPB_TABKEY_STR("TYPE_UINT32"), UPB_VALUE_INIT_INT32(13), NULL},
  4521. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4522. {UPB_TABKEY_STR("TYPE_UINT64"), UPB_VALUE_INIT_INT32(4), &strentries[190]},
  4523. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4524. {UPB_TABKEY_STR("TYPE_SFIXED64"), UPB_VALUE_INIT_INT32(16), NULL},
  4525. {UPB_TABKEY_STR("TYPE_BYTES"), UPB_VALUE_INIT_INT32(12), NULL},
  4526. {UPB_TABKEY_STR("TYPE_SINT64"), UPB_VALUE_INIT_INT32(18), NULL},
  4527. {UPB_TABKEY_STR("TYPE_BOOL"), UPB_VALUE_INIT_INT32(8), NULL},
  4528. {UPB_TABKEY_STR("TYPE_GROUP"), UPB_VALUE_INIT_INT32(10), NULL},
  4529. {UPB_TABKEY_STR("TYPE_SINT32"), UPB_VALUE_INIT_INT32(17), NULL},
  4530. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4531. {UPB_TABKEY_STR("CORD"), UPB_VALUE_INIT_INT32(1), NULL},
  4532. {UPB_TABKEY_STR("STRING"), UPB_VALUE_INIT_INT32(0), &strentries[197]},
  4533. {UPB_TABKEY_STR("STRING_PIECE"), UPB_VALUE_INIT_INT32(2), NULL},
  4534. {UPB_TABKEY_STR("CODE_SIZE"), UPB_VALUE_INIT_INT32(2), NULL},
  4535. {UPB_TABKEY_STR("SPEED"), UPB_VALUE_INIT_INT32(1), &strentries[203]},
  4536. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4537. {UPB_TABKEY_STR("LITE_RUNTIME"), UPB_VALUE_INIT_INT32(3), NULL},
  4538. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4539. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4540. {UPB_TABKEY_STR("google.protobuf.SourceCodeInfo.Location"), UPB_VALUE_INIT_CONSTPTR(&msgs[17]), NULL},
  4541. {UPB_TABKEY_STR("google.protobuf.UninterpretedOption"), UPB_VALUE_INIT_CONSTPTR(&msgs[18]), NULL},
  4542. {UPB_TABKEY_STR("google.protobuf.FileDescriptorProto"), UPB_VALUE_INIT_CONSTPTR(&msgs[8]), NULL},
  4543. {UPB_TABKEY_STR("google.protobuf.MethodDescriptorProto"), UPB_VALUE_INIT_CONSTPTR(&msgs[12]), NULL},
  4544. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4545. {UPB_TABKEY_STR("google.protobuf.EnumValueOptions"), UPB_VALUE_INIT_CONSTPTR(&msgs[5]), NULL},
  4546. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4547. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4548. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4549. {UPB_TABKEY_STR("google.protobuf.DescriptorProto"), UPB_VALUE_INIT_CONSTPTR(&msgs[0]), &strentries[228]},
  4550. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4551. {UPB_TABKEY_STR("google.protobuf.SourceCodeInfo"), UPB_VALUE_INIT_CONSTPTR(&msgs[16]), NULL},
  4552. {UPB_TABKEY_STR("google.protobuf.FieldDescriptorProto.Type"), UPB_VALUE_INIT_CONSTPTR(&enums[1]), NULL},
  4553. {UPB_TABKEY_STR("google.protobuf.DescriptorProto.ExtensionRange"), UPB_VALUE_INIT_CONSTPTR(&msgs[1]), NULL},
  4554. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4555. {UPB_TABKEY_STR("google.protobuf.EnumValueDescriptorProto"), UPB_VALUE_INIT_CONSTPTR(&msgs[4]), NULL},
  4556. {UPB_TABKEY_STR("google.protobuf.FieldOptions"), UPB_VALUE_INIT_CONSTPTR(&msgs[7]), NULL},
  4557. {UPB_TABKEY_STR("google.protobuf.FileOptions"), UPB_VALUE_INIT_CONSTPTR(&msgs[10]), NULL},
  4558. {UPB_TABKEY_STR("google.protobuf.EnumDescriptorProto"), UPB_VALUE_INIT_CONSTPTR(&msgs[2]), &strentries[233]},
  4559. {UPB_TABKEY_STR("google.protobuf.FieldDescriptorProto.Label"), UPB_VALUE_INIT_CONSTPTR(&enums[0]), NULL},
  4560. {UPB_TABKEY_STR("google.protobuf.ServiceDescriptorProto"), UPB_VALUE_INIT_CONSTPTR(&msgs[14]), NULL},
  4561. {UPB_TABKEY_STR("google.protobuf.FieldOptions.CType"), UPB_VALUE_INIT_CONSTPTR(&enums[2]), &strentries[229]},
  4562. {UPB_TABKEY_STR("google.protobuf.FileDescriptorSet"), UPB_VALUE_INIT_CONSTPTR(&msgs[9]), &strentries[235]},
  4563. {UPB_TABKEY_STR("google.protobuf.EnumOptions"), UPB_VALUE_INIT_CONSTPTR(&msgs[3]), NULL},
  4564. {UPB_TABKEY_STR("google.protobuf.FieldDescriptorProto"), UPB_VALUE_INIT_CONSTPTR(&msgs[6]), NULL},
  4565. {UPB_TABKEY_STR("google.protobuf.FileOptions.OptimizeMode"), UPB_VALUE_INIT_CONSTPTR(&enums[3]), &strentries[221]},
  4566. {UPB_TABKEY_STR("google.protobuf.ServiceOptions"), UPB_VALUE_INIT_CONSTPTR(&msgs[15]), NULL},
  4567. {UPB_TABKEY_STR("google.protobuf.MessageOptions"), UPB_VALUE_INIT_CONSTPTR(&msgs[11]), NULL},
  4568. {UPB_TABKEY_STR("google.protobuf.MethodOptions"), UPB_VALUE_INIT_CONSTPTR(&msgs[13]), &strentries[226]},
  4569. {UPB_TABKEY_STR("google.protobuf.UninterpretedOption.NamePart"), UPB_VALUE_INIT_CONSTPTR(&msgs[19]), NULL},
  4570. };
  4571. static const upb_tabent intentries[14] = {
  4572. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4573. {UPB_TABKEY_NUM(999), UPB_VALUE_INIT_CONSTPTR(&fields[73]), NULL},
  4574. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4575. {UPB_TABKEY_NUM(999), UPB_VALUE_INIT_CONSTPTR(&fields[71]), NULL},
  4576. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4577. {UPB_TABKEY_NUM(999), UPB_VALUE_INIT_CONSTPTR(&fields[77]), NULL},
  4578. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4579. {UPB_TABKEY_NUM(999), UPB_VALUE_INIT_CONSTPTR(&fields[75]), NULL},
  4580. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4581. {UPB_TABKEY_NUM(999), UPB_VALUE_INIT_CONSTPTR(&fields[76]), NULL},
  4582. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4583. {UPB_TABKEY_NUM(999), UPB_VALUE_INIT_CONSTPTR(&fields[74]), NULL},
  4584. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4585. {UPB_TABKEY_NUM(999), UPB_VALUE_INIT_CONSTPTR(&fields[72]), NULL},
  4586. };
  4587. static const _upb_value arrays[232] = {
  4588. UPB_ARRAY_EMPTYENT,
  4589. UPB_VALUE_INIT_CONSTPTR(&fields[38]),
  4590. UPB_VALUE_INIT_CONSTPTR(&fields[16]),
  4591. UPB_VALUE_INIT_CONSTPTR(&fields[44]),
  4592. UPB_VALUE_INIT_CONSTPTR(&fields[9]),
  4593. UPB_VALUE_INIT_CONSTPTR(&fields[15]),
  4594. UPB_VALUE_INIT_CONSTPTR(&fields[14]),
  4595. UPB_VALUE_INIT_CONSTPTR(&fields[49]),
  4596. UPB_ARRAY_EMPTYENT,
  4597. UPB_VALUE_INIT_CONSTPTR(&fields[66]),
  4598. UPB_VALUE_INIT_CONSTPTR(&fields[8]),
  4599. UPB_ARRAY_EMPTYENT,
  4600. UPB_VALUE_INIT_CONSTPTR(&fields[40]),
  4601. UPB_VALUE_INIT_CONSTPTR(&fields[78]),
  4602. UPB_VALUE_INIT_CONSTPTR(&fields[50]),
  4603. UPB_ARRAY_EMPTYENT,
  4604. UPB_ARRAY_EMPTYENT,
  4605. UPB_VALUE_INIT_CONSTPTR(&fields[1]),
  4606. UPB_ARRAY_EMPTYENT,
  4607. UPB_ARRAY_EMPTYENT,
  4608. UPB_ARRAY_EMPTYENT,
  4609. UPB_ARRAY_EMPTYENT,
  4610. UPB_ARRAY_EMPTYENT,
  4611. UPB_ARRAY_EMPTYENT,
  4612. UPB_VALUE_INIT_CONSTPTR(&fields[37]),
  4613. UPB_VALUE_INIT_CONSTPTR(&fields[47]),
  4614. UPB_VALUE_INIT_CONSTPTR(&fields[52]),
  4615. UPB_ARRAY_EMPTYENT,
  4616. UPB_ARRAY_EMPTYENT,
  4617. UPB_ARRAY_EMPTYENT,
  4618. UPB_ARRAY_EMPTYENT,
  4619. UPB_ARRAY_EMPTYENT,
  4620. UPB_VALUE_INIT_CONSTPTR(&fields[41]),
  4621. UPB_VALUE_INIT_CONSTPTR(&fields[12]),
  4622. UPB_VALUE_INIT_CONSTPTR(&fields[46]),
  4623. UPB_VALUE_INIT_CONSTPTR(&fields[27]),
  4624. UPB_VALUE_INIT_CONSTPTR(&fields[69]),
  4625. UPB_VALUE_INIT_CONSTPTR(&fields[70]),
  4626. UPB_VALUE_INIT_CONSTPTR(&fields[4]),
  4627. UPB_VALUE_INIT_CONSTPTR(&fields[51]),
  4628. UPB_ARRAY_EMPTYENT,
  4629. UPB_VALUE_INIT_CONSTPTR(&fields[3]),
  4630. UPB_VALUE_INIT_CONSTPTR(&fields[58]),
  4631. UPB_VALUE_INIT_CONSTPTR(&fields[6]),
  4632. UPB_ARRAY_EMPTYENT,
  4633. UPB_VALUE_INIT_CONSTPTR(&fields[28]),
  4634. UPB_ARRAY_EMPTYENT,
  4635. UPB_ARRAY_EMPTYENT,
  4636. UPB_ARRAY_EMPTYENT,
  4637. UPB_VALUE_INIT_CONSTPTR(&fields[11]),
  4638. UPB_VALUE_INIT_CONSTPTR(&fields[79]),
  4639. UPB_ARRAY_EMPTYENT,
  4640. UPB_ARRAY_EMPTYENT,
  4641. UPB_ARRAY_EMPTYENT,
  4642. UPB_ARRAY_EMPTYENT,
  4643. UPB_ARRAY_EMPTYENT,
  4644. UPB_ARRAY_EMPTYENT,
  4645. UPB_ARRAY_EMPTYENT,
  4646. UPB_ARRAY_EMPTYENT,
  4647. UPB_ARRAY_EMPTYENT,
  4648. UPB_ARRAY_EMPTYENT,
  4649. UPB_ARRAY_EMPTYENT,
  4650. UPB_ARRAY_EMPTYENT,
  4651. UPB_ARRAY_EMPTYENT,
  4652. UPB_ARRAY_EMPTYENT,
  4653. UPB_ARRAY_EMPTYENT,
  4654. UPB_ARRAY_EMPTYENT,
  4655. UPB_ARRAY_EMPTYENT,
  4656. UPB_ARRAY_EMPTYENT,
  4657. UPB_ARRAY_EMPTYENT,
  4658. UPB_ARRAY_EMPTYENT,
  4659. UPB_ARRAY_EMPTYENT,
  4660. UPB_ARRAY_EMPTYENT,
  4661. UPB_VALUE_INIT_CONSTPTR(&fields[34]),
  4662. UPB_VALUE_INIT_CONSTPTR(&fields[57]),
  4663. UPB_VALUE_INIT_CONSTPTR(&fields[5]),
  4664. UPB_VALUE_INIT_CONSTPTR(&fields[32]),
  4665. UPB_VALUE_INIT_CONSTPTR(&fields[10]),
  4666. UPB_VALUE_INIT_CONSTPTR(&fields[63]),
  4667. UPB_VALUE_INIT_CONSTPTR(&fields[13]),
  4668. UPB_VALUE_INIT_CONSTPTR(&fields[53]),
  4669. UPB_VALUE_INIT_CONSTPTR(&fields[64]),
  4670. UPB_VALUE_INIT_CONSTPTR(&fields[61]),
  4671. UPB_VALUE_INIT_CONSTPTR(&fields[80]),
  4672. UPB_ARRAY_EMPTYENT,
  4673. UPB_VALUE_INIT_CONSTPTR(&fields[17]),
  4674. UPB_ARRAY_EMPTYENT,
  4675. UPB_VALUE_INIT_CONSTPTR(&fields[26]),
  4676. UPB_ARRAY_EMPTYENT,
  4677. UPB_ARRAY_EMPTYENT,
  4678. UPB_ARRAY_EMPTYENT,
  4679. UPB_ARRAY_EMPTYENT,
  4680. UPB_ARRAY_EMPTYENT,
  4681. UPB_ARRAY_EMPTYENT,
  4682. UPB_VALUE_INIT_CONSTPTR(&fields[25]),
  4683. UPB_VALUE_INIT_CONSTPTR(&fields[48]),
  4684. UPB_VALUE_INIT_CONSTPTR(&fields[24]),
  4685. UPB_VALUE_INIT_CONSTPTR(&fields[18]),
  4686. UPB_ARRAY_EMPTYENT,
  4687. UPB_ARRAY_EMPTYENT,
  4688. UPB_ARRAY_EMPTYENT,
  4689. UPB_ARRAY_EMPTYENT,
  4690. UPB_VALUE_INIT_CONSTPTR(&fields[2]),
  4691. UPB_VALUE_INIT_CONSTPTR(&fields[23]),
  4692. UPB_VALUE_INIT_CONSTPTR(&fields[62]),
  4693. UPB_ARRAY_EMPTYENT,
  4694. UPB_VALUE_INIT_CONSTPTR(&fields[22]),
  4695. UPB_ARRAY_EMPTYENT,
  4696. UPB_ARRAY_EMPTYENT,
  4697. UPB_ARRAY_EMPTYENT,
  4698. UPB_ARRAY_EMPTYENT,
  4699. UPB_ARRAY_EMPTYENT,
  4700. UPB_ARRAY_EMPTYENT,
  4701. UPB_ARRAY_EMPTYENT,
  4702. UPB_ARRAY_EMPTYENT,
  4703. UPB_ARRAY_EMPTYENT,
  4704. UPB_ARRAY_EMPTYENT,
  4705. UPB_ARRAY_EMPTYENT,
  4706. UPB_ARRAY_EMPTYENT,
  4707. UPB_ARRAY_EMPTYENT,
  4708. UPB_ARRAY_EMPTYENT,
  4709. UPB_ARRAY_EMPTYENT,
  4710. UPB_ARRAY_EMPTYENT,
  4711. UPB_ARRAY_EMPTYENT,
  4712. UPB_ARRAY_EMPTYENT,
  4713. UPB_ARRAY_EMPTYENT,
  4714. UPB_ARRAY_EMPTYENT,
  4715. UPB_ARRAY_EMPTYENT,
  4716. UPB_ARRAY_EMPTYENT,
  4717. UPB_ARRAY_EMPTYENT,
  4718. UPB_ARRAY_EMPTYENT,
  4719. UPB_ARRAY_EMPTYENT,
  4720. UPB_ARRAY_EMPTYENT,
  4721. UPB_ARRAY_EMPTYENT,
  4722. UPB_ARRAY_EMPTYENT,
  4723. UPB_ARRAY_EMPTYENT,
  4724. UPB_ARRAY_EMPTYENT,
  4725. UPB_ARRAY_EMPTYENT,
  4726. UPB_ARRAY_EMPTYENT,
  4727. UPB_ARRAY_EMPTYENT,
  4728. UPB_ARRAY_EMPTYENT,
  4729. UPB_ARRAY_EMPTYENT,
  4730. UPB_ARRAY_EMPTYENT,
  4731. UPB_ARRAY_EMPTYENT,
  4732. UPB_ARRAY_EMPTYENT,
  4733. UPB_ARRAY_EMPTYENT,
  4734. UPB_ARRAY_EMPTYENT,
  4735. UPB_ARRAY_EMPTYENT,
  4736. UPB_ARRAY_EMPTYENT,
  4737. UPB_ARRAY_EMPTYENT,
  4738. UPB_ARRAY_EMPTYENT,
  4739. UPB_VALUE_INIT_CONSTPTR(&fields[31]),
  4740. UPB_VALUE_INIT_CONSTPTR(&fields[45]),
  4741. UPB_ARRAY_EMPTYENT,
  4742. UPB_ARRAY_EMPTYENT,
  4743. UPB_ARRAY_EMPTYENT,
  4744. UPB_ARRAY_EMPTYENT,
  4745. UPB_ARRAY_EMPTYENT,
  4746. UPB_ARRAY_EMPTYENT,
  4747. UPB_ARRAY_EMPTYENT,
  4748. UPB_ARRAY_EMPTYENT,
  4749. UPB_ARRAY_EMPTYENT,
  4750. UPB_ARRAY_EMPTYENT,
  4751. UPB_ARRAY_EMPTYENT,
  4752. UPB_ARRAY_EMPTYENT,
  4753. UPB_ARRAY_EMPTYENT,
  4754. UPB_ARRAY_EMPTYENT,
  4755. UPB_VALUE_INIT_CONSTPTR(&fields[39]),
  4756. UPB_VALUE_INIT_CONSTPTR(&fields[20]),
  4757. UPB_VALUE_INIT_CONSTPTR(&fields[56]),
  4758. UPB_VALUE_INIT_CONSTPTR(&fields[55]),
  4759. UPB_ARRAY_EMPTYENT,
  4760. UPB_ARRAY_EMPTYENT,
  4761. UPB_ARRAY_EMPTYENT,
  4762. UPB_ARRAY_EMPTYENT,
  4763. UPB_ARRAY_EMPTYENT,
  4764. UPB_VALUE_INIT_CONSTPTR(&fields[35]),
  4765. UPB_VALUE_INIT_CONSTPTR(&fields[33]),
  4766. UPB_VALUE_INIT_CONSTPTR(&fields[54]),
  4767. UPB_ARRAY_EMPTYENT,
  4768. UPB_ARRAY_EMPTYENT,
  4769. UPB_ARRAY_EMPTYENT,
  4770. UPB_ARRAY_EMPTYENT,
  4771. UPB_ARRAY_EMPTYENT,
  4772. UPB_VALUE_INIT_CONSTPTR(&fields[30]),
  4773. UPB_ARRAY_EMPTYENT,
  4774. UPB_VALUE_INIT_CONSTPTR(&fields[59]),
  4775. UPB_VALUE_INIT_CONSTPTR(&fields[65]),
  4776. UPB_VALUE_INIT_CONSTPTR(&fields[29]),
  4777. UPB_VALUE_INIT_CONSTPTR(&fields[68]),
  4778. UPB_ARRAY_EMPTYENT,
  4779. UPB_ARRAY_EMPTYENT,
  4780. UPB_VALUE_INIT_CONSTPTR(&fields[36]),
  4781. UPB_VALUE_INIT_CONSTPTR(&fields[19]),
  4782. UPB_VALUE_INIT_CONSTPTR(&fields[60]),
  4783. UPB_VALUE_INIT_CONSTPTR(&fields[43]),
  4784. UPB_VALUE_INIT_CONSTPTR(&fields[7]),
  4785. UPB_VALUE_INIT_CONSTPTR(&fields[67]),
  4786. UPB_VALUE_INIT_CONSTPTR(&fields[0]),
  4787. UPB_ARRAY_EMPTYENT,
  4788. UPB_VALUE_INIT_CONSTPTR(&fields[42]),
  4789. UPB_VALUE_INIT_CONSTPTR(&fields[21]),
  4790. UPB_ARRAY_EMPTYENT,
  4791. UPB_VALUE_INIT_CONSTPTR("LABEL_OPTIONAL"),
  4792. UPB_VALUE_INIT_CONSTPTR("LABEL_REQUIRED"),
  4793. UPB_VALUE_INIT_CONSTPTR("LABEL_REPEATED"),
  4794. UPB_ARRAY_EMPTYENT,
  4795. UPB_VALUE_INIT_CONSTPTR("TYPE_DOUBLE"),
  4796. UPB_VALUE_INIT_CONSTPTR("TYPE_FLOAT"),
  4797. UPB_VALUE_INIT_CONSTPTR("TYPE_INT64"),
  4798. UPB_VALUE_INIT_CONSTPTR("TYPE_UINT64"),
  4799. UPB_VALUE_INIT_CONSTPTR("TYPE_INT32"),
  4800. UPB_VALUE_INIT_CONSTPTR("TYPE_FIXED64"),
  4801. UPB_VALUE_INIT_CONSTPTR("TYPE_FIXED32"),
  4802. UPB_VALUE_INIT_CONSTPTR("TYPE_BOOL"),
  4803. UPB_VALUE_INIT_CONSTPTR("TYPE_STRING"),
  4804. UPB_VALUE_INIT_CONSTPTR("TYPE_GROUP"),
  4805. UPB_VALUE_INIT_CONSTPTR("TYPE_MESSAGE"),
  4806. UPB_VALUE_INIT_CONSTPTR("TYPE_BYTES"),
  4807. UPB_VALUE_INIT_CONSTPTR("TYPE_UINT32"),
  4808. UPB_VALUE_INIT_CONSTPTR("TYPE_ENUM"),
  4809. UPB_VALUE_INIT_CONSTPTR("TYPE_SFIXED32"),
  4810. UPB_VALUE_INIT_CONSTPTR("TYPE_SFIXED64"),
  4811. UPB_VALUE_INIT_CONSTPTR("TYPE_SINT32"),
  4812. UPB_VALUE_INIT_CONSTPTR("TYPE_SINT64"),
  4813. UPB_VALUE_INIT_CONSTPTR("STRING"),
  4814. UPB_VALUE_INIT_CONSTPTR("CORD"),
  4815. UPB_VALUE_INIT_CONSTPTR("STRING_PIECE"),
  4816. UPB_ARRAY_EMPTYENT,
  4817. UPB_VALUE_INIT_CONSTPTR("SPEED"),
  4818. UPB_VALUE_INIT_CONSTPTR("CODE_SIZE"),
  4819. UPB_VALUE_INIT_CONSTPTR("LITE_RUNTIME"),
  4820. };
  4821. static const upb_symtab symtab = UPB_SYMTAB_INIT(UPB_STRTABLE_INIT(24, 31, UPB_CTYPE_PTR, 5, &strentries[204]), &reftables[210], &reftables[211]);
  4822. const upb_symtab *upbdefs_google_protobuf_descriptor(const void *owner) {
  4823. upb_symtab_ref(&symtab, owner);
  4824. return &symtab;
  4825. }
  4826. #ifdef UPB_DEBUG_REFS
  4827. static upb_inttable reftables[212] = {
  4828. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4829. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4830. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4831. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4832. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4833. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4834. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4835. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4836. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4837. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4838. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4839. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4840. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4841. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4842. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4843. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4844. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4845. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4846. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4847. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4848. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4849. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4850. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4851. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4852. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4853. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4854. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4855. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4856. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4857. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4858. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4859. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4860. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4861. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4862. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4863. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4864. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4865. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4866. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4867. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4868. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4869. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4870. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4871. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4872. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4873. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4874. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4875. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4876. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4877. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4878. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4879. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4880. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4881. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4882. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4883. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4884. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4885. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4886. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4887. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4888. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4889. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4890. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4891. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4892. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4893. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4894. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4895. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4896. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4897. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4898. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4899. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4900. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4901. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4902. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4903. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4904. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4905. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4906. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4907. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4908. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4909. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4910. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4911. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4912. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4913. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4914. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4915. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4916. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4917. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4918. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4919. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4920. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4921. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4922. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4923. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4924. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4925. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4926. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4927. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4928. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4929. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4930. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4931. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4932. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4933. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4934. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4935. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4936. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4937. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4938. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4939. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4940. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4941. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4942. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4943. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4944. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4945. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4946. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4947. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4948. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4949. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4950. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4951. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4952. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4953. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4954. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4955. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4956. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4957. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4958. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4959. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4960. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4961. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4962. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4963. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4964. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4965. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4966. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4967. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4968. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4969. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4970. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4971. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4972. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4973. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4974. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4975. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4976. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4977. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4978. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4979. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4980. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4981. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4982. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4983. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4984. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4985. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4986. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4987. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4988. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4989. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4990. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4991. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4992. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4993. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4994. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4995. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4996. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4997. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4998. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4999. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5000. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5001. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5002. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5003. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5004. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5005. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5006. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5007. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5008. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5009. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5010. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5011. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5012. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5013. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5014. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5015. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5016. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5017. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5018. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5019. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5020. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5021. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5022. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5023. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5024. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5025. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5026. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5027. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5028. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5029. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5030. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5031. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5032. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5033. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5034. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5035. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5036. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5037. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5038. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5039. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5040. };
  5041. #endif
  5042. /*
  5043. * upb - a minimalist implementation of protocol buffers.
  5044. *
  5045. * Copyright (c) 2008-2009 Google Inc. See LICENSE for details.
  5046. * Author: Josh Haberman <jhaberman@gmail.com>
  5047. *
  5048. * XXX: The routines in this file that consume a string do not currently
  5049. * support having the string span buffers. In the future, as upb_sink and
  5050. * its buffering/sharing functionality evolve there should be an easy and
  5051. * idiomatic way of correctly handling this case. For now, we accept this
  5052. * limitation since we currently only parse descriptors from single strings.
  5053. */
  5054. #include <errno.h>
  5055. #include <stdlib.h>
  5056. #include <string.h>
  5057. // upb_deflist is an internal-only dynamic array for storing a growing list of
  5058. // upb_defs.
  5059. typedef struct {
  5060. upb_def **defs;
  5061. size_t len;
  5062. size_t size;
  5063. bool owned;
  5064. } upb_deflist;
  5065. // We keep a stack of all the messages scopes we are currently in, as well as
  5066. // the top-level file scope. This is necessary to correctly qualify the
  5067. // definitions that are contained inside. "name" tracks the name of the
  5068. // message or package (a bare name -- not qualified by any enclosing scopes).
  5069. typedef struct {
  5070. char *name;
  5071. // Index of the first def that is under this scope. For msgdefs, the
  5072. // msgdef itself is at start-1.
  5073. int start;
  5074. } upb_descreader_frame;
  5075. // The maximum number of nested declarations that are allowed, ie.
  5076. // message Foo {
  5077. // message Bar {
  5078. // message Baz {
  5079. // }
  5080. // }
  5081. // }
  5082. //
  5083. // This is a resource limit that affects how big our runtime stack can grow.
  5084. // TODO: make this a runtime-settable property of the Reader instance.
  5085. #define UPB_MAX_MESSAGE_NESTING 64
  5086. struct upb_descreader {
  5087. upb_sink sink;
  5088. upb_deflist defs;
  5089. upb_descreader_frame stack[UPB_MAX_MESSAGE_NESTING];
  5090. int stack_len;
  5091. uint32_t number;
  5092. char *name;
  5093. bool saw_number;
  5094. bool saw_name;
  5095. char *default_string;
  5096. upb_fielddef *f;
  5097. };
  5098. static char *upb_strndup(const char *buf, size_t n) {
  5099. char *ret = malloc(n + 1);
  5100. if (!ret) return NULL;
  5101. memcpy(ret, buf, n);
  5102. ret[n] = '\0';
  5103. return ret;
  5104. }
  5105. // Returns a newly allocated string that joins input strings together, for
  5106. // example:
  5107. // join("Foo.Bar", "Baz") -> "Foo.Bar.Baz"
  5108. // join("", "Baz") -> "Baz"
  5109. // Caller owns a ref on the returned string.
  5110. static char *upb_join(const char *base, const char *name) {
  5111. if (!base || strlen(base) == 0) {
  5112. return upb_strdup(name);
  5113. } else {
  5114. char *ret = malloc(strlen(base) + strlen(name) + 2);
  5115. ret[0] = '\0';
  5116. strcat(ret, base);
  5117. strcat(ret, ".");
  5118. strcat(ret, name);
  5119. return ret;
  5120. }
  5121. }
  5122. /* upb_deflist ****************************************************************/
  5123. void upb_deflist_init(upb_deflist *l) {
  5124. l->size = 0;
  5125. l->defs = NULL;
  5126. l->len = 0;
  5127. l->owned = true;
  5128. }
  5129. void upb_deflist_uninit(upb_deflist *l) {
  5130. if (l->owned)
  5131. for(size_t i = 0; i < l->len; i++)
  5132. upb_def_unref(l->defs[i], l);
  5133. free(l->defs);
  5134. }
  5135. bool upb_deflist_push(upb_deflist *l, upb_def *d) {
  5136. if(++l->len >= l->size) {
  5137. size_t new_size = UPB_MAX(l->size, 4);
  5138. new_size *= 2;
  5139. l->defs = realloc(l->defs, new_size * sizeof(void *));
  5140. if (!l->defs) return false;
  5141. l->size = new_size;
  5142. }
  5143. l->defs[l->len - 1] = d;
  5144. return true;
  5145. }
  5146. void upb_deflist_donaterefs(upb_deflist *l, void *owner) {
  5147. assert(l->owned);
  5148. for (size_t i = 0; i < l->len; i++)
  5149. upb_def_donateref(l->defs[i], l, owner);
  5150. l->owned = false;
  5151. }
  5152. static upb_def *upb_deflist_last(upb_deflist *l) {
  5153. return l->defs[l->len-1];
  5154. }
  5155. // Qualify the defname for all defs starting with offset "start" with "str".
  5156. static void upb_deflist_qualify(upb_deflist *l, char *str, int32_t start) {
  5157. for (uint32_t i = start; i < l->len; i++) {
  5158. upb_def *def = l->defs[i];
  5159. char *name = upb_join(str, upb_def_fullname(def));
  5160. upb_def_setfullname(def, name, NULL);
  5161. free(name);
  5162. }
  5163. }
  5164. /* upb_descreader ************************************************************/
  5165. static upb_msgdef *upb_descreader_top(upb_descreader *r) {
  5166. assert(r->stack_len > 1);
  5167. int index = r->stack[r->stack_len-1].start - 1;
  5168. assert(index >= 0);
  5169. return upb_downcast_msgdef_mutable(r->defs.defs[index]);
  5170. }
  5171. static upb_def *upb_descreader_last(upb_descreader *r) {
  5172. return upb_deflist_last(&r->defs);
  5173. }
  5174. // Start/end handlers for FileDescriptorProto and DescriptorProto (the two
  5175. // entities that have names and can contain sub-definitions.
  5176. void upb_descreader_startcontainer(upb_descreader *r) {
  5177. upb_descreader_frame *f = &r->stack[r->stack_len++];
  5178. f->start = r->defs.len;
  5179. f->name = NULL;
  5180. }
  5181. void upb_descreader_endcontainer(upb_descreader *r) {
  5182. upb_descreader_frame *f = &r->stack[--r->stack_len];
  5183. upb_deflist_qualify(&r->defs, f->name, f->start);
  5184. free(f->name);
  5185. f->name = NULL;
  5186. }
  5187. void upb_descreader_setscopename(upb_descreader *r, char *str) {
  5188. upb_descreader_frame *f = &r->stack[r->stack_len-1];
  5189. free(f->name);
  5190. f->name = str;
  5191. }
  5192. // Handlers for google.protobuf.FileDescriptorProto.
  5193. static bool file_startmsg(void *r, const void *hd) {
  5194. UPB_UNUSED(hd);
  5195. upb_descreader_startcontainer(r);
  5196. return true;
  5197. }
  5198. static bool file_endmsg(void *closure, const void *hd, upb_status *status) {
  5199. UPB_UNUSED(hd);
  5200. UPB_UNUSED(status);
  5201. upb_descreader *r = closure;
  5202. upb_descreader_endcontainer(r);
  5203. return true;
  5204. }
  5205. static size_t file_onpackage(void *closure, const void *hd, const char *buf,
  5206. size_t n, const upb_bufhandle *handle) {
  5207. UPB_UNUSED(hd);
  5208. UPB_UNUSED(handle);
  5209. upb_descreader *r = closure;
  5210. // XXX: see comment at the top of the file.
  5211. upb_descreader_setscopename(r, upb_strndup(buf, n));
  5212. return n;
  5213. }
  5214. // Handlers for google.protobuf.EnumValueDescriptorProto.
  5215. static bool enumval_startmsg(void *closure, const void *hd) {
  5216. UPB_UNUSED(hd);
  5217. upb_descreader *r = closure;
  5218. r->saw_number = false;
  5219. r->saw_name = false;
  5220. return true;
  5221. }
  5222. static size_t enumval_onname(void *closure, const void *hd, const char *buf,
  5223. size_t n, const upb_bufhandle *handle) {
  5224. UPB_UNUSED(hd);
  5225. UPB_UNUSED(handle);
  5226. upb_descreader *r = closure;
  5227. // XXX: see comment at the top of the file.
  5228. free(r->name);
  5229. r->name = upb_strndup(buf, n);
  5230. r->saw_name = true;
  5231. return n;
  5232. }
  5233. static bool enumval_onnumber(void *closure, const void *hd, int32_t val) {
  5234. UPB_UNUSED(hd);
  5235. upb_descreader *r = closure;
  5236. r->number = val;
  5237. r->saw_number = true;
  5238. return true;
  5239. }
  5240. static bool enumval_endmsg(void *closure, const void *hd, upb_status *status) {
  5241. UPB_UNUSED(hd);
  5242. upb_descreader *r = closure;
  5243. if(!r->saw_number || !r->saw_name) {
  5244. upb_status_seterrmsg(status, "Enum value missing name or number.");
  5245. return false;
  5246. }
  5247. upb_enumdef *e = upb_downcast_enumdef_mutable(upb_descreader_last(r));
  5248. upb_enumdef_addval(e, r->name, r->number, status);
  5249. free(r->name);
  5250. r->name = NULL;
  5251. return true;
  5252. }
  5253. // Handlers for google.protobuf.EnumDescriptorProto.
  5254. static bool enum_startmsg(void *closure, const void *hd) {
  5255. UPB_UNUSED(hd);
  5256. upb_descreader *r = closure;
  5257. upb_deflist_push(&r->defs, UPB_UPCAST(upb_enumdef_new(&r->defs)));
  5258. return true;
  5259. }
  5260. static bool enum_endmsg(void *closure, const void *hd, upb_status *status) {
  5261. UPB_UNUSED(hd);
  5262. upb_descreader *r = closure;
  5263. upb_enumdef *e = upb_downcast_enumdef_mutable(upb_descreader_last(r));
  5264. if (upb_def_fullname(upb_descreader_last(r)) == NULL) {
  5265. upb_status_seterrmsg(status, "Enum had no name.");
  5266. return false;
  5267. }
  5268. if (upb_enumdef_numvals(e) == 0) {
  5269. upb_status_seterrmsg(status, "Enum had no values.");
  5270. return false;
  5271. }
  5272. return true;
  5273. }
  5274. static size_t enum_onname(void *closure, const void *hd, const char *buf,
  5275. size_t n, const upb_bufhandle *handle) {
  5276. UPB_UNUSED(hd);
  5277. UPB_UNUSED(handle);
  5278. upb_descreader *r = closure;
  5279. // XXX: see comment at the top of the file.
  5280. char *fullname = upb_strndup(buf, n);
  5281. upb_def_setfullname(upb_descreader_last(r), fullname, NULL);
  5282. free(fullname);
  5283. return n;
  5284. }
  5285. // Handlers for google.protobuf.FieldDescriptorProto
  5286. static bool field_startmsg(void *closure, const void *hd) {
  5287. UPB_UNUSED(hd);
  5288. upb_descreader *r = closure;
  5289. r->f = upb_fielddef_new(&r->defs);
  5290. free(r->default_string);
  5291. r->default_string = NULL;
  5292. // fielddefs default to packed, but descriptors default to non-packed.
  5293. upb_fielddef_setpacked(r->f, false);
  5294. return true;
  5295. }
  5296. // Converts the default value in string "str" into "d". Passes a ref on str.
  5297. // Returns true on success.
  5298. static bool parse_default(char *str, upb_fielddef *f) {
  5299. bool success = true;
  5300. char *end;
  5301. switch (upb_fielddef_type(f)) {
  5302. case UPB_TYPE_INT32: {
  5303. long val = strtol(str, &end, 0);
  5304. if (val > INT32_MAX || val < INT32_MIN || errno == ERANGE || *end)
  5305. success = false;
  5306. else
  5307. upb_fielddef_setdefaultint32(f, val);
  5308. break;
  5309. }
  5310. case UPB_TYPE_INT64: {
  5311. long long val = strtoll(str, &end, 0);
  5312. if (val > INT64_MAX || val < INT64_MIN || errno == ERANGE || *end)
  5313. success = false;
  5314. else
  5315. upb_fielddef_setdefaultint64(f, val);
  5316. break;
  5317. }
  5318. case UPB_TYPE_UINT32: {
  5319. unsigned long val = strtoul(str, &end, 0);
  5320. if (val > UINT32_MAX || errno == ERANGE || *end)
  5321. success = false;
  5322. else
  5323. upb_fielddef_setdefaultuint32(f, val);
  5324. break;
  5325. }
  5326. case UPB_TYPE_UINT64: {
  5327. unsigned long long val = strtoull(str, &end, 0);
  5328. if (val > UINT64_MAX || errno == ERANGE || *end)
  5329. success = false;
  5330. else
  5331. upb_fielddef_setdefaultuint64(f, val);
  5332. break;
  5333. }
  5334. case UPB_TYPE_DOUBLE: {
  5335. double val = strtod(str, &end);
  5336. if (errno == ERANGE || *end)
  5337. success = false;
  5338. else
  5339. upb_fielddef_setdefaultdouble(f, val);
  5340. break;
  5341. }
  5342. case UPB_TYPE_FLOAT: {
  5343. float val = strtof(str, &end);
  5344. if (errno == ERANGE || *end)
  5345. success = false;
  5346. else
  5347. upb_fielddef_setdefaultfloat(f, val);
  5348. break;
  5349. }
  5350. case UPB_TYPE_BOOL: {
  5351. if (strcmp(str, "false") == 0)
  5352. upb_fielddef_setdefaultbool(f, false);
  5353. else if (strcmp(str, "true") == 0)
  5354. upb_fielddef_setdefaultbool(f, true);
  5355. else
  5356. success = false;
  5357. break;
  5358. }
  5359. default: abort();
  5360. }
  5361. return success;
  5362. }
  5363. static bool field_endmsg(void *closure, const void *hd, upb_status *status) {
  5364. UPB_UNUSED(hd);
  5365. upb_descreader *r = closure;
  5366. upb_fielddef *f = r->f;
  5367. // TODO: verify that all required fields were present.
  5368. assert(upb_fielddef_number(f) != 0);
  5369. assert(upb_fielddef_name(f) != NULL);
  5370. assert((upb_fielddef_subdefname(f) != NULL) == upb_fielddef_hassubdef(f));
  5371. if (r->default_string) {
  5372. if (upb_fielddef_issubmsg(f)) {
  5373. upb_status_seterrmsg(status, "Submessages cannot have defaults.");
  5374. return false;
  5375. }
  5376. if (upb_fielddef_isstring(f) || upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  5377. upb_fielddef_setdefaultcstr(f, r->default_string, NULL);
  5378. } else {
  5379. if (r->default_string && !parse_default(r->default_string, f)) {
  5380. // We don't worry too much about giving a great error message since the
  5381. // compiler should have ensured this was correct.
  5382. upb_status_seterrmsg(status, "Error converting default value.");
  5383. return false;
  5384. }
  5385. }
  5386. }
  5387. return true;
  5388. }
  5389. static bool field_onlazy(void *closure, const void *hd, bool val) {
  5390. UPB_UNUSED(hd);
  5391. upb_descreader *r = closure;
  5392. upb_fielddef_setlazy(r->f, val);
  5393. return true;
  5394. }
  5395. static bool field_onpacked(void *closure, const void *hd, bool val) {
  5396. UPB_UNUSED(hd);
  5397. upb_descreader *r = closure;
  5398. upb_fielddef_setpacked(r->f, val);
  5399. return true;
  5400. }
  5401. static bool field_ontype(void *closure, const void *hd, int32_t val) {
  5402. UPB_UNUSED(hd);
  5403. upb_descreader *r = closure;
  5404. upb_fielddef_setdescriptortype(r->f, val);
  5405. return true;
  5406. }
  5407. static bool field_onlabel(void *closure, const void *hd, int32_t val) {
  5408. UPB_UNUSED(hd);
  5409. upb_descreader *r = closure;
  5410. upb_fielddef_setlabel(r->f, val);
  5411. return true;
  5412. }
  5413. static bool field_onnumber(void *closure, const void *hd, int32_t val) {
  5414. UPB_UNUSED(hd);
  5415. upb_descreader *r = closure;
  5416. bool ok = upb_fielddef_setnumber(r->f, val, NULL);
  5417. UPB_ASSERT_VAR(ok, ok);
  5418. return true;
  5419. }
  5420. static size_t field_onname(void *closure, const void *hd, const char *buf,
  5421. size_t n, const upb_bufhandle *handle) {
  5422. UPB_UNUSED(hd);
  5423. UPB_UNUSED(handle);
  5424. upb_descreader *r = closure;
  5425. // XXX: see comment at the top of the file.
  5426. char *name = upb_strndup(buf, n);
  5427. upb_fielddef_setname(r->f, name, NULL);
  5428. free(name);
  5429. return n;
  5430. }
  5431. static size_t field_ontypename(void *closure, const void *hd, const char *buf,
  5432. size_t n, const upb_bufhandle *handle) {
  5433. UPB_UNUSED(hd);
  5434. UPB_UNUSED(handle);
  5435. upb_descreader *r = closure;
  5436. // XXX: see comment at the top of the file.
  5437. char *name = upb_strndup(buf, n);
  5438. upb_fielddef_setsubdefname(r->f, name, NULL);
  5439. free(name);
  5440. return n;
  5441. }
  5442. static size_t field_onextendee(void *closure, const void *hd, const char *buf,
  5443. size_t n, const upb_bufhandle *handle) {
  5444. UPB_UNUSED(hd);
  5445. UPB_UNUSED(handle);
  5446. upb_descreader *r = closure;
  5447. // XXX: see comment at the top of the file.
  5448. char *name = upb_strndup(buf, n);
  5449. upb_fielddef_setcontainingtypename(r->f, name, NULL);
  5450. free(name);
  5451. return n;
  5452. }
  5453. static size_t field_ondefaultval(void *closure, const void *hd, const char *buf,
  5454. size_t n, const upb_bufhandle *handle) {
  5455. UPB_UNUSED(hd);
  5456. UPB_UNUSED(handle);
  5457. upb_descreader *r = closure;
  5458. // Have to convert from string to the correct type, but we might not know the
  5459. // type yet, so we save it as a string until the end of the field.
  5460. // XXX: see comment at the top of the file.
  5461. free(r->default_string);
  5462. r->default_string = upb_strndup(buf, n);
  5463. return n;
  5464. }
  5465. // Handlers for google.protobuf.DescriptorProto (representing a message).
  5466. static bool msg_startmsg(void *closure, const void *hd) {
  5467. UPB_UNUSED(hd);
  5468. upb_descreader *r = closure;
  5469. upb_deflist_push(&r->defs, UPB_UPCAST(upb_msgdef_new(&r->defs)));
  5470. upb_descreader_startcontainer(r);
  5471. return true;
  5472. }
  5473. static bool msg_endmsg(void *closure, const void *hd, upb_status *status) {
  5474. UPB_UNUSED(hd);
  5475. upb_descreader *r = closure;
  5476. upb_msgdef *m = upb_descreader_top(r);
  5477. if(!upb_def_fullname(UPB_UPCAST(m))) {
  5478. upb_status_seterrmsg(status, "Encountered message with no name.");
  5479. return false;
  5480. }
  5481. upb_descreader_endcontainer(r);
  5482. return true;
  5483. }
  5484. static size_t msg_onname(void *closure, const void *hd, const char *buf,
  5485. size_t n, const upb_bufhandle *handle) {
  5486. UPB_UNUSED(hd);
  5487. UPB_UNUSED(handle);
  5488. upb_descreader *r = closure;
  5489. upb_msgdef *m = upb_descreader_top(r);
  5490. // XXX: see comment at the top of the file.
  5491. char *name = upb_strndup(buf, n);
  5492. upb_def_setfullname(UPB_UPCAST(m), name, NULL);
  5493. upb_descreader_setscopename(r, name); // Passes ownership of name.
  5494. return n;
  5495. }
  5496. static bool msg_onendfield(void *closure, const void *hd) {
  5497. UPB_UNUSED(hd);
  5498. upb_descreader *r = closure;
  5499. upb_msgdef *m = upb_descreader_top(r);
  5500. upb_msgdef_addfield(m, r->f, &r->defs, NULL);
  5501. r->f = NULL;
  5502. return true;
  5503. }
  5504. static bool pushextension(void *closure, const void *hd) {
  5505. UPB_UNUSED(hd);
  5506. upb_descreader *r = closure;
  5507. assert(upb_fielddef_containingtypename(r->f));
  5508. upb_fielddef_setisextension(r->f, true);
  5509. upb_deflist_push(&r->defs, UPB_UPCAST(r->f));
  5510. r->f = NULL;
  5511. return true;
  5512. }
  5513. #define D(name) upbdefs_google_protobuf_ ## name(s)
  5514. static void reghandlers(const void *closure, upb_handlers *h) {
  5515. const upb_symtab *s = closure;
  5516. const upb_msgdef *m = upb_handlers_msgdef(h);
  5517. if (m == D(DescriptorProto)) {
  5518. upb_handlers_setstartmsg(h, &msg_startmsg, NULL);
  5519. upb_handlers_setendmsg(h, &msg_endmsg, NULL);
  5520. upb_handlers_setstring(h, D(DescriptorProto_name), &msg_onname, NULL);
  5521. upb_handlers_setendsubmsg(h, D(DescriptorProto_field), &msg_onendfield,
  5522. NULL);
  5523. upb_handlers_setendsubmsg(h, D(DescriptorProto_extension), &pushextension,
  5524. NULL);
  5525. } else if (m == D(FileDescriptorProto)) {
  5526. upb_handlers_setstartmsg(h, &file_startmsg, NULL);
  5527. upb_handlers_setendmsg(h, &file_endmsg, NULL);
  5528. upb_handlers_setstring(h, D(FileDescriptorProto_package), &file_onpackage,
  5529. NULL);
  5530. upb_handlers_setendsubmsg(h, D(FileDescriptorProto_extension), &pushextension,
  5531. NULL);
  5532. } else if (m == D(EnumValueDescriptorProto)) {
  5533. upb_handlers_setstartmsg(h, &enumval_startmsg, NULL);
  5534. upb_handlers_setendmsg(h, &enumval_endmsg, NULL);
  5535. upb_handlers_setstring(h, D(EnumValueDescriptorProto_name), &enumval_onname, NULL);
  5536. upb_handlers_setint32(h, D(EnumValueDescriptorProto_number), &enumval_onnumber,
  5537. NULL);
  5538. } else if (m == D(EnumDescriptorProto)) {
  5539. upb_handlers_setstartmsg(h, &enum_startmsg, NULL);
  5540. upb_handlers_setendmsg(h, &enum_endmsg, NULL);
  5541. upb_handlers_setstring(h, D(EnumDescriptorProto_name), &enum_onname, NULL);
  5542. } else if (m == D(FieldDescriptorProto)) {
  5543. upb_handlers_setstartmsg(h, &field_startmsg, NULL);
  5544. upb_handlers_setendmsg(h, &field_endmsg, NULL);
  5545. upb_handlers_setint32(h, D(FieldDescriptorProto_type), &field_ontype,
  5546. NULL);
  5547. upb_handlers_setint32(h, D(FieldDescriptorProto_label), &field_onlabel,
  5548. NULL);
  5549. upb_handlers_setint32(h, D(FieldDescriptorProto_number), &field_onnumber,
  5550. NULL);
  5551. upb_handlers_setstring(h, D(FieldDescriptorProto_name), &field_onname,
  5552. NULL);
  5553. upb_handlers_setstring(h, D(FieldDescriptorProto_type_name),
  5554. &field_ontypename, NULL);
  5555. upb_handlers_setstring(h, D(FieldDescriptorProto_extendee),
  5556. &field_onextendee, NULL);
  5557. upb_handlers_setstring(h, D(FieldDescriptorProto_default_value),
  5558. &field_ondefaultval, NULL);
  5559. } else if (m == D(FieldOptions)) {
  5560. upb_handlers_setbool(h, D(FieldOptions_lazy), &field_onlazy, NULL);
  5561. upb_handlers_setbool(h, D(FieldOptions_packed), &field_onpacked, NULL);
  5562. }
  5563. }
  5564. #undef D
  5565. void descreader_cleanup(void *_r) {
  5566. upb_descreader *r = _r;
  5567. free(r->name);
  5568. upb_deflist_uninit(&r->defs);
  5569. free(r->default_string);
  5570. while (r->stack_len > 0) {
  5571. upb_descreader_frame *f = &r->stack[--r->stack_len];
  5572. free(f->name);
  5573. }
  5574. }
  5575. /* Public API ****************************************************************/
  5576. upb_descreader *upb_descreader_create(upb_env *e, const upb_handlers *h) {
  5577. upb_descreader *r = upb_env_malloc(e, sizeof(upb_descreader));
  5578. if (!r || !upb_env_addcleanup(e, descreader_cleanup, r)) {
  5579. return NULL;
  5580. }
  5581. upb_deflist_init(&r->defs);
  5582. upb_sink_reset(upb_descreader_input(r), h, r);
  5583. r->stack_len = 0;
  5584. r->name = NULL;
  5585. r->default_string = NULL;
  5586. return r;
  5587. }
  5588. upb_def **upb_descreader_getdefs(upb_descreader *r, void *owner, int *n) {
  5589. *n = r->defs.len;
  5590. upb_deflist_donaterefs(&r->defs, owner);
  5591. return r->defs.defs;
  5592. }
  5593. upb_sink *upb_descreader_input(upb_descreader *r) {
  5594. return &r->sink;
  5595. }
  5596. const upb_handlers *upb_descreader_newhandlers(const void *owner) {
  5597. const upb_symtab *s = upbdefs_google_protobuf_descriptor(&s);
  5598. const upb_handlers *h = upb_handlers_newfrozen(
  5599. upbdefs_google_protobuf_FileDescriptorSet(s), owner, reghandlers, s);
  5600. upb_symtab_unref(s, &s);
  5601. return h;
  5602. }
  5603. /*
  5604. * upb - a minimalist implementation of protocol buffers.
  5605. *
  5606. * Copyright (c) 2013 Google Inc. See LICENSE for details.
  5607. * Author: Josh Haberman <jhaberman@gmail.com>
  5608. *
  5609. * Code to compile a upb::Handlers into bytecode for decoding a protobuf
  5610. * according to that specific schema and destination handlers.
  5611. *
  5612. * Compiling to bytecode is always the first step. If we are using the
  5613. * interpreted decoder we leave it as bytecode and interpret that. If we are
  5614. * using a JIT decoder we use a code generator to turn the bytecode into native
  5615. * code, LLVM IR, etc.
  5616. *
  5617. * Bytecode definition is in decoder.int.h.
  5618. */
  5619. #include <stdarg.h>
  5620. #ifdef UPB_DUMP_BYTECODE
  5621. #include <stdio.h>
  5622. #endif
  5623. #define MAXLABEL 5
  5624. #define EMPTYLABEL -1
  5625. /* mgroup *********************************************************************/
  5626. static void freegroup(upb_refcounted *r) {
  5627. mgroup *g = (mgroup*)r;
  5628. upb_inttable_uninit(&g->methods);
  5629. #ifdef UPB_USE_JIT_X64
  5630. upb_pbdecoder_freejit(g);
  5631. #endif
  5632. free(g->bytecode);
  5633. free(g);
  5634. }
  5635. static void visitgroup(const upb_refcounted *r, upb_refcounted_visit *visit,
  5636. void *closure) {
  5637. const mgroup *g = (const mgroup*)r;
  5638. upb_inttable_iter i;
  5639. upb_inttable_begin(&i, &g->methods);
  5640. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5641. upb_pbdecodermethod *method = upb_value_getptr(upb_inttable_iter_value(&i));
  5642. visit(r, UPB_UPCAST(method), closure);
  5643. }
  5644. }
  5645. mgroup *newgroup(const void *owner) {
  5646. mgroup *g = malloc(sizeof(*g));
  5647. static const struct upb_refcounted_vtbl vtbl = {visitgroup, freegroup};
  5648. upb_refcounted_init(UPB_UPCAST(g), &vtbl, owner);
  5649. upb_inttable_init(&g->methods, UPB_CTYPE_PTR);
  5650. g->bytecode = NULL;
  5651. g->bytecode_end = NULL;
  5652. return g;
  5653. }
  5654. /* upb_pbdecodermethod ********************************************************/
  5655. static void freemethod(upb_refcounted *r) {
  5656. upb_pbdecodermethod *method = (upb_pbdecodermethod*)r;
  5657. if (method->dest_handlers_) {
  5658. upb_handlers_unref(method->dest_handlers_, method);
  5659. }
  5660. upb_inttable_uninit(&method->dispatch);
  5661. free(method);
  5662. }
  5663. static void visitmethod(const upb_refcounted *r, upb_refcounted_visit *visit,
  5664. void *closure) {
  5665. const upb_pbdecodermethod *m = (const upb_pbdecodermethod*)r;
  5666. visit(r, m->group, closure);
  5667. }
  5668. static upb_pbdecodermethod *newmethod(const upb_handlers *dest_handlers,
  5669. mgroup *group) {
  5670. static const struct upb_refcounted_vtbl vtbl = {visitmethod, freemethod};
  5671. upb_pbdecodermethod *ret = malloc(sizeof(*ret));
  5672. upb_refcounted_init(UPB_UPCAST(ret), &vtbl, &ret);
  5673. upb_byteshandler_init(&ret->input_handler_);
  5674. // The method references the group and vice-versa, in a circular reference.
  5675. upb_ref2(ret, group);
  5676. upb_ref2(group, ret);
  5677. upb_inttable_insertptr(&group->methods, dest_handlers, upb_value_ptr(ret));
  5678. upb_refcounted_unref(UPB_UPCAST(ret), &ret);
  5679. ret->group = UPB_UPCAST(group);
  5680. ret->dest_handlers_ = dest_handlers;
  5681. ret->is_native_ = false; // If we JIT, it will update this later.
  5682. upb_inttable_init(&ret->dispatch, UPB_CTYPE_UINT64);
  5683. if (ret->dest_handlers_) {
  5684. upb_handlers_ref(ret->dest_handlers_, ret);
  5685. }
  5686. return ret;
  5687. }
  5688. void upb_pbdecodermethod_ref(const upb_pbdecodermethod *m, const void *owner) {
  5689. upb_refcounted_ref(UPB_UPCAST(m), owner);
  5690. }
  5691. void upb_pbdecodermethod_unref(const upb_pbdecodermethod *m,
  5692. const void *owner) {
  5693. upb_refcounted_unref(UPB_UPCAST(m), owner);
  5694. }
  5695. void upb_pbdecodermethod_donateref(const upb_pbdecodermethod *m,
  5696. const void *from, const void *to) {
  5697. upb_refcounted_donateref(UPB_UPCAST(m), from, to);
  5698. }
  5699. void upb_pbdecodermethod_checkref(const upb_pbdecodermethod *m,
  5700. const void *owner) {
  5701. upb_refcounted_checkref(UPB_UPCAST(m), owner);
  5702. }
  5703. const upb_handlers *upb_pbdecodermethod_desthandlers(
  5704. const upb_pbdecodermethod *m) {
  5705. return m->dest_handlers_;
  5706. }
  5707. const upb_byteshandler *upb_pbdecodermethod_inputhandler(
  5708. const upb_pbdecodermethod *m) {
  5709. return &m->input_handler_;
  5710. }
  5711. bool upb_pbdecodermethod_isnative(const upb_pbdecodermethod *m) {
  5712. return m->is_native_;
  5713. }
  5714. const upb_pbdecodermethod *upb_pbdecodermethod_new(
  5715. const upb_pbdecodermethodopts *opts, const void *owner) {
  5716. upb_pbcodecache cache;
  5717. upb_pbcodecache_init(&cache);
  5718. const upb_pbdecodermethod *ret =
  5719. upb_pbcodecache_getdecodermethod(&cache, opts);
  5720. upb_pbdecodermethod_ref(ret, owner);
  5721. upb_pbcodecache_uninit(&cache);
  5722. return ret;
  5723. }
  5724. /* bytecode compiler **********************************************************/
  5725. // Data used only at compilation time.
  5726. typedef struct {
  5727. mgroup *group;
  5728. uint32_t *pc;
  5729. int fwd_labels[MAXLABEL];
  5730. int back_labels[MAXLABEL];
  5731. // For fields marked "lazy", parse them lazily or eagerly?
  5732. bool lazy;
  5733. } compiler;
  5734. static compiler *newcompiler(mgroup *group, bool lazy) {
  5735. compiler *ret = malloc(sizeof(*ret));
  5736. ret->group = group;
  5737. ret->lazy = lazy;
  5738. for (int i = 0; i < MAXLABEL; i++) {
  5739. ret->fwd_labels[i] = EMPTYLABEL;
  5740. ret->back_labels[i] = EMPTYLABEL;
  5741. }
  5742. return ret;
  5743. }
  5744. static void freecompiler(compiler *c) {
  5745. free(c);
  5746. }
  5747. const size_t ptr_words = sizeof(void*) / sizeof(uint32_t);
  5748. // How many words an instruction is.
  5749. static int instruction_len(uint32_t instr) {
  5750. switch (getop(instr)) {
  5751. case OP_SETDISPATCH: return 1 + ptr_words;
  5752. case OP_TAGN: return 3;
  5753. case OP_SETBIGGROUPNUM: return 2;
  5754. default: return 1;
  5755. }
  5756. }
  5757. bool op_has_longofs(int32_t instruction) {
  5758. switch (getop(instruction)) {
  5759. case OP_CALL:
  5760. case OP_BRANCH:
  5761. case OP_CHECKDELIM:
  5762. return true;
  5763. // The "tag" instructions only have 8 bytes available for the jump target,
  5764. // but that is ok because these opcodes only require short jumps.
  5765. case OP_TAG1:
  5766. case OP_TAG2:
  5767. case OP_TAGN:
  5768. return false;
  5769. default:
  5770. assert(false);
  5771. return false;
  5772. }
  5773. }
  5774. static int32_t getofs(uint32_t instruction) {
  5775. if (op_has_longofs(instruction)) {
  5776. return (int32_t)instruction >> 8;
  5777. } else {
  5778. return (int8_t)(instruction >> 8);
  5779. }
  5780. }
  5781. static void setofs(uint32_t *instruction, int32_t ofs) {
  5782. if (op_has_longofs(*instruction)) {
  5783. *instruction = getop(*instruction) | ofs << 8;
  5784. } else {
  5785. *instruction = (*instruction & ~0xff00) | ((ofs & 0xff) << 8);
  5786. }
  5787. assert(getofs(*instruction) == ofs); // Would fail in cases of overflow.
  5788. }
  5789. static uint32_t pcofs(compiler *c) { return c->pc - c->group->bytecode; }
  5790. // Defines a local label at the current PC location. All previous forward
  5791. // references are updated to point to this location. The location is noted
  5792. // for any future backward references.
  5793. static void label(compiler *c, unsigned int label) {
  5794. assert(label < MAXLABEL);
  5795. int val = c->fwd_labels[label];
  5796. uint32_t *codep = (val == EMPTYLABEL) ? NULL : c->group->bytecode + val;
  5797. while (codep) {
  5798. int ofs = getofs(*codep);
  5799. setofs(codep, c->pc - codep - instruction_len(*codep));
  5800. codep = ofs ? codep + ofs : NULL;
  5801. }
  5802. c->fwd_labels[label] = EMPTYLABEL;
  5803. c->back_labels[label] = pcofs(c);
  5804. }
  5805. // Creates a reference to a numbered label; either a forward reference
  5806. // (positive arg) or backward reference (negative arg). For forward references
  5807. // the value returned now is actually a "next" pointer into a linked list of all
  5808. // instructions that use this label and will be patched later when the label is
  5809. // defined with label().
  5810. //
  5811. // The returned value is the offset that should be written into the instruction.
  5812. static int32_t labelref(compiler *c, int label) {
  5813. assert(label < MAXLABEL);
  5814. if (label == LABEL_DISPATCH) {
  5815. // No resolving required.
  5816. return 0;
  5817. } else if (label < 0) {
  5818. // Backward local label. Relative to the next instruction.
  5819. uint32_t from = (c->pc + 1) - c->group->bytecode;
  5820. return c->back_labels[-label] - from;
  5821. } else {
  5822. // Forward local label: prepend to (possibly-empty) linked list.
  5823. int *lptr = &c->fwd_labels[label];
  5824. int32_t ret = (*lptr == EMPTYLABEL) ? 0 : *lptr - pcofs(c);
  5825. *lptr = pcofs(c);
  5826. return ret;
  5827. }
  5828. }
  5829. static void put32(compiler *c, uint32_t v) {
  5830. mgroup *g = c->group;
  5831. if (c->pc == g->bytecode_end) {
  5832. int ofs = pcofs(c);
  5833. size_t oldsize = g->bytecode_end - g->bytecode;
  5834. size_t newsize = UPB_MAX(oldsize * 2, 64);
  5835. // TODO(haberman): handle OOM.
  5836. g->bytecode = realloc(g->bytecode, newsize * sizeof(uint32_t));
  5837. g->bytecode_end = g->bytecode + newsize;
  5838. c->pc = g->bytecode + ofs;
  5839. }
  5840. *c->pc++ = v;
  5841. }
  5842. static void putop(compiler *c, opcode op, ...) {
  5843. va_list ap;
  5844. va_start(ap, op);
  5845. switch (op) {
  5846. case OP_SETDISPATCH: {
  5847. uintptr_t ptr = (uintptr_t)va_arg(ap, void*);
  5848. put32(c, OP_SETDISPATCH);
  5849. put32(c, ptr);
  5850. if (sizeof(uintptr_t) > sizeof(uint32_t))
  5851. put32(c, (uint64_t)ptr >> 32);
  5852. break;
  5853. }
  5854. case OP_STARTMSG:
  5855. case OP_ENDMSG:
  5856. case OP_PUSHLENDELIM:
  5857. case OP_POP:
  5858. case OP_SETDELIM:
  5859. case OP_HALT:
  5860. case OP_RET:
  5861. case OP_DISPATCH:
  5862. put32(c, op);
  5863. break;
  5864. case OP_PARSE_DOUBLE:
  5865. case OP_PARSE_FLOAT:
  5866. case OP_PARSE_INT64:
  5867. case OP_PARSE_UINT64:
  5868. case OP_PARSE_INT32:
  5869. case OP_PARSE_FIXED64:
  5870. case OP_PARSE_FIXED32:
  5871. case OP_PARSE_BOOL:
  5872. case OP_PARSE_UINT32:
  5873. case OP_PARSE_SFIXED32:
  5874. case OP_PARSE_SFIXED64:
  5875. case OP_PARSE_SINT32:
  5876. case OP_PARSE_SINT64:
  5877. case OP_STARTSEQ:
  5878. case OP_ENDSEQ:
  5879. case OP_STARTSUBMSG:
  5880. case OP_ENDSUBMSG:
  5881. case OP_STARTSTR:
  5882. case OP_STRING:
  5883. case OP_ENDSTR:
  5884. case OP_PUSHTAGDELIM:
  5885. put32(c, op | va_arg(ap, upb_selector_t) << 8);
  5886. break;
  5887. case OP_SETBIGGROUPNUM:
  5888. put32(c, op);
  5889. put32(c, va_arg(ap, int));
  5890. break;
  5891. case OP_CALL: {
  5892. const upb_pbdecodermethod *method = va_arg(ap, upb_pbdecodermethod *);
  5893. put32(c, op | (method->code_base.ofs - (pcofs(c) + 1)) << 8);
  5894. break;
  5895. }
  5896. case OP_CHECKDELIM:
  5897. case OP_BRANCH: {
  5898. uint32_t instruction = op;
  5899. int label = va_arg(ap, int);
  5900. setofs(&instruction, labelref(c, label));
  5901. put32(c, instruction);
  5902. break;
  5903. }
  5904. case OP_TAG1:
  5905. case OP_TAG2: {
  5906. int label = va_arg(ap, int);
  5907. uint64_t tag = va_arg(ap, uint64_t);
  5908. uint32_t instruction = op | (tag << 16);
  5909. assert(tag <= 0xffff);
  5910. setofs(&instruction, labelref(c, label));
  5911. put32(c, instruction);
  5912. break;
  5913. }
  5914. case OP_TAGN: {
  5915. int label = va_arg(ap, int);
  5916. uint64_t tag = va_arg(ap, uint64_t);
  5917. uint32_t instruction = op | (upb_value_size(tag) << 16);
  5918. setofs(&instruction, labelref(c, label));
  5919. put32(c, instruction);
  5920. put32(c, tag);
  5921. put32(c, tag >> 32);
  5922. break;
  5923. }
  5924. }
  5925. va_end(ap);
  5926. }
  5927. #if defined(UPB_USE_JIT_X64) || defined(UPB_DUMP_BYTECODE)
  5928. const char *upb_pbdecoder_getopname(unsigned int op) {
  5929. #define OP(op) [OP_ ## op] = "OP_" #op
  5930. #define T(op) OP(PARSE_##op)
  5931. static const char *names[] = {
  5932. "<no opcode>",
  5933. T(DOUBLE), T(FLOAT), T(INT64), T(UINT64), T(INT32), T(FIXED64), T(FIXED32),
  5934. T(BOOL), T(UINT32), T(SFIXED32), T(SFIXED64), T(SINT32), T(SINT64),
  5935. OP(STARTMSG), OP(ENDMSG), OP(STARTSEQ), OP(ENDSEQ), OP(STARTSUBMSG),
  5936. OP(ENDSUBMSG), OP(STARTSTR), OP(STRING), OP(ENDSTR), OP(CALL), OP(RET),
  5937. OP(PUSHLENDELIM), OP(PUSHTAGDELIM), OP(SETDELIM), OP(CHECKDELIM),
  5938. OP(BRANCH), OP(TAG1), OP(TAG2), OP(TAGN), OP(SETDISPATCH), OP(POP),
  5939. OP(SETBIGGROUPNUM), OP(DISPATCH), OP(HALT),
  5940. };
  5941. return op > OP_HALT ? names[0] : names[op];
  5942. #undef OP
  5943. #undef T
  5944. }
  5945. #endif
  5946. #ifdef UPB_DUMP_BYTECODE
  5947. static void dumpbc(uint32_t *p, uint32_t *end, FILE *f) {
  5948. uint32_t *begin = p;
  5949. while (p < end) {
  5950. fprintf(f, "%p %8tx", p, p - begin);
  5951. uint32_t instr = *p++;
  5952. uint8_t op = getop(instr);
  5953. fprintf(f, " %s", upb_pbdecoder_getopname(op));
  5954. switch ((opcode)op) {
  5955. case OP_SETDISPATCH: {
  5956. const upb_inttable *dispatch;
  5957. memcpy(&dispatch, p, sizeof(void*));
  5958. p += ptr_words;
  5959. const upb_pbdecodermethod *method =
  5960. (void *)((char *)dispatch -
  5961. offsetof(upb_pbdecodermethod, dispatch));
  5962. fprintf(f, " %s", upb_msgdef_fullname(
  5963. upb_handlers_msgdef(method->dest_handlers_)));
  5964. break;
  5965. }
  5966. case OP_DISPATCH:
  5967. case OP_STARTMSG:
  5968. case OP_ENDMSG:
  5969. case OP_PUSHLENDELIM:
  5970. case OP_POP:
  5971. case OP_SETDELIM:
  5972. case OP_HALT:
  5973. case OP_RET:
  5974. break;
  5975. case OP_PARSE_DOUBLE:
  5976. case OP_PARSE_FLOAT:
  5977. case OP_PARSE_INT64:
  5978. case OP_PARSE_UINT64:
  5979. case OP_PARSE_INT32:
  5980. case OP_PARSE_FIXED64:
  5981. case OP_PARSE_FIXED32:
  5982. case OP_PARSE_BOOL:
  5983. case OP_PARSE_UINT32:
  5984. case OP_PARSE_SFIXED32:
  5985. case OP_PARSE_SFIXED64:
  5986. case OP_PARSE_SINT32:
  5987. case OP_PARSE_SINT64:
  5988. case OP_STARTSEQ:
  5989. case OP_ENDSEQ:
  5990. case OP_STARTSUBMSG:
  5991. case OP_ENDSUBMSG:
  5992. case OP_STARTSTR:
  5993. case OP_STRING:
  5994. case OP_ENDSTR:
  5995. case OP_PUSHTAGDELIM:
  5996. fprintf(f, " %d", instr >> 8);
  5997. break;
  5998. case OP_SETBIGGROUPNUM:
  5999. fprintf(f, " %d", *p++);
  6000. break;
  6001. case OP_CHECKDELIM:
  6002. case OP_CALL:
  6003. case OP_BRANCH:
  6004. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  6005. break;
  6006. case OP_TAG1:
  6007. case OP_TAG2: {
  6008. fprintf(f, " tag:0x%x", instr >> 16);
  6009. if (getofs(instr)) {
  6010. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  6011. }
  6012. break;
  6013. }
  6014. case OP_TAGN: {
  6015. uint64_t tag = *p++;
  6016. tag |= (uint64_t)*p++ << 32;
  6017. fprintf(f, " tag:0x%llx", (long long)tag);
  6018. fprintf(f, " n:%d", instr >> 16);
  6019. if (getofs(instr)) {
  6020. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  6021. }
  6022. break;
  6023. }
  6024. }
  6025. fputs("\n", f);
  6026. }
  6027. }
  6028. #endif
  6029. static uint64_t get_encoded_tag(const upb_fielddef *f, int wire_type) {
  6030. uint32_t tag = (upb_fielddef_number(f) << 3) | wire_type;
  6031. uint64_t encoded_tag = upb_vencode32(tag);
  6032. // No tag should be greater than 5 bytes.
  6033. assert(encoded_tag <= 0xffffffffff);
  6034. return encoded_tag;
  6035. }
  6036. static void putchecktag(compiler *c, const upb_fielddef *f,
  6037. int wire_type, int dest) {
  6038. uint64_t tag = get_encoded_tag(f, wire_type);
  6039. switch (upb_value_size(tag)) {
  6040. case 1:
  6041. putop(c, OP_TAG1, dest, tag);
  6042. break;
  6043. case 2:
  6044. putop(c, OP_TAG2, dest, tag);
  6045. break;
  6046. default:
  6047. putop(c, OP_TAGN, dest, tag);
  6048. break;
  6049. }
  6050. }
  6051. static upb_selector_t getsel(const upb_fielddef *f, upb_handlertype_t type) {
  6052. upb_selector_t selector;
  6053. bool ok = upb_handlers_getselector(f, type, &selector);
  6054. UPB_ASSERT_VAR(ok, ok);
  6055. return selector;
  6056. }
  6057. // Takes an existing, primary dispatch table entry and repacks it with a
  6058. // different alternate wire type. Called when we are inserting a secondary
  6059. // dispatch table entry for an alternate wire type.
  6060. static uint64_t repack(uint64_t dispatch, int new_wt2) {
  6061. uint64_t ofs;
  6062. uint8_t wt1;
  6063. uint8_t old_wt2;
  6064. upb_pbdecoder_unpackdispatch(dispatch, &ofs, &wt1, &old_wt2);
  6065. assert(old_wt2 == NO_WIRE_TYPE); // wt2 should not be set yet.
  6066. return upb_pbdecoder_packdispatch(ofs, wt1, new_wt2);
  6067. }
  6068. // Marks the current bytecode position as the dispatch target for this message,
  6069. // field, and wire type.
  6070. static void dispatchtarget(compiler *c, upb_pbdecodermethod *method,
  6071. const upb_fielddef *f, int wire_type) {
  6072. // Offset is relative to msg base.
  6073. uint64_t ofs = pcofs(c) - method->code_base.ofs;
  6074. uint32_t fn = upb_fielddef_number(f);
  6075. upb_inttable *d = &method->dispatch;
  6076. upb_value v;
  6077. if (upb_inttable_remove(d, fn, &v)) {
  6078. // TODO: prioritize based on packed setting in .proto file.
  6079. uint64_t repacked = repack(upb_value_getuint64(v), wire_type);
  6080. upb_inttable_insert(d, fn, upb_value_uint64(repacked));
  6081. upb_inttable_insert(d, fn + UPB_MAX_FIELDNUMBER, upb_value_uint64(ofs));
  6082. } else {
  6083. uint64_t val = upb_pbdecoder_packdispatch(ofs, wire_type, NO_WIRE_TYPE);
  6084. upb_inttable_insert(d, fn, upb_value_uint64(val));
  6085. }
  6086. }
  6087. static void putpush(compiler *c, const upb_fielddef *f) {
  6088. if (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE) {
  6089. putop(c, OP_PUSHLENDELIM);
  6090. } else {
  6091. uint32_t fn = upb_fielddef_number(f);
  6092. if (fn >= 1 << 24) {
  6093. putop(c, OP_PUSHTAGDELIM, 0);
  6094. putop(c, OP_SETBIGGROUPNUM, fn);
  6095. } else {
  6096. putop(c, OP_PUSHTAGDELIM, fn);
  6097. }
  6098. }
  6099. }
  6100. static upb_pbdecodermethod *find_submethod(const compiler *c,
  6101. const upb_pbdecodermethod *method,
  6102. const upb_fielddef *f) {
  6103. const upb_handlers *sub =
  6104. upb_handlers_getsubhandlers(method->dest_handlers_, f);
  6105. upb_value v;
  6106. return upb_inttable_lookupptr(&c->group->methods, sub, &v)
  6107. ? upb_value_getptr(v)
  6108. : NULL;
  6109. }
  6110. static void putsel(compiler *c, opcode op, upb_selector_t sel,
  6111. const upb_handlers *h) {
  6112. if (upb_handlers_gethandler(h, sel)) {
  6113. putop(c, op, sel);
  6114. }
  6115. }
  6116. // Puts an opcode to call a callback, but only if a callback actually exists for
  6117. // this field and handler type.
  6118. static void maybeput(compiler *c, opcode op, const upb_handlers *h,
  6119. const upb_fielddef *f, upb_handlertype_t type) {
  6120. putsel(c, op, getsel(f, type), h);
  6121. }
  6122. static bool haslazyhandlers(const upb_handlers *h, const upb_fielddef *f) {
  6123. if (!upb_fielddef_lazy(f))
  6124. return false;
  6125. return upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STARTSTR)) ||
  6126. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STRING)) ||
  6127. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_ENDSTR));
  6128. }
  6129. /* bytecode compiler code generation ******************************************/
  6130. // Symbolic names for our local labels.
  6131. #define LABEL_LOOPSTART 1 // Top of a repeated field loop.
  6132. #define LABEL_LOOPBREAK 2 // To jump out of a repeated loop
  6133. #define LABEL_FIELD 3 // Jump backward to find the most recent field.
  6134. #define LABEL_ENDMSG 4 // To reach the OP_ENDMSG instr for this msg.
  6135. // Generates bytecode to parse a single non-lazy message field.
  6136. static void generate_msgfield(compiler *c, const upb_fielddef *f,
  6137. upb_pbdecodermethod *method) {
  6138. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  6139. const upb_pbdecodermethod *sub_m = find_submethod(c, method, f);
  6140. if (!sub_m) {
  6141. // Don't emit any code for this field at all; it will be parsed as an
  6142. // unknown field.
  6143. return;
  6144. }
  6145. label(c, LABEL_FIELD);
  6146. int wire_type =
  6147. (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE)
  6148. ? UPB_WIRE_TYPE_DELIMITED
  6149. : UPB_WIRE_TYPE_START_GROUP;
  6150. if (upb_fielddef_isseq(f)) {
  6151. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  6152. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  6153. dispatchtarget(c, method, f, wire_type);
  6154. putop(c, OP_PUSHTAGDELIM, 0);
  6155. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  6156. label(c, LABEL_LOOPSTART);
  6157. putpush(c, f);
  6158. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  6159. putop(c, OP_CALL, sub_m);
  6160. putop(c, OP_POP);
  6161. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  6162. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  6163. putop(c, OP_SETDELIM);
  6164. }
  6165. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  6166. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  6167. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  6168. label(c, LABEL_LOOPBREAK);
  6169. putop(c, OP_POP);
  6170. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  6171. } else {
  6172. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  6173. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  6174. dispatchtarget(c, method, f, wire_type);
  6175. putpush(c, f);
  6176. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  6177. putop(c, OP_CALL, sub_m);
  6178. putop(c, OP_POP);
  6179. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  6180. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  6181. putop(c, OP_SETDELIM);
  6182. }
  6183. }
  6184. }
  6185. // Generates bytecode to parse a single string or lazy submessage field.
  6186. static void generate_delimfield(compiler *c, const upb_fielddef *f,
  6187. upb_pbdecodermethod *method) {
  6188. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  6189. label(c, LABEL_FIELD);
  6190. if (upb_fielddef_isseq(f)) {
  6191. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  6192. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  6193. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  6194. putop(c, OP_PUSHTAGDELIM, 0);
  6195. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  6196. label(c, LABEL_LOOPSTART);
  6197. putop(c, OP_PUSHLENDELIM);
  6198. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  6199. // Need to emit even if no handler to skip past the string.
  6200. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  6201. putop(c, OP_POP);
  6202. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  6203. putop(c, OP_SETDELIM);
  6204. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  6205. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_LOOPBREAK);
  6206. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  6207. label(c, LABEL_LOOPBREAK);
  6208. putop(c, OP_POP);
  6209. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  6210. } else {
  6211. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  6212. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  6213. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  6214. putop(c, OP_PUSHLENDELIM);
  6215. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  6216. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  6217. putop(c, OP_POP);
  6218. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  6219. putop(c, OP_SETDELIM);
  6220. }
  6221. }
  6222. // Generates bytecode to parse a single primitive field.
  6223. static void generate_primitivefield(compiler *c, const upb_fielddef *f,
  6224. upb_pbdecodermethod *method) {
  6225. label(c, LABEL_FIELD);
  6226. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  6227. upb_descriptortype_t descriptor_type = upb_fielddef_descriptortype(f);
  6228. // From a decoding perspective, ENUM is the same as INT32.
  6229. if (descriptor_type == UPB_DESCRIPTOR_TYPE_ENUM)
  6230. descriptor_type = UPB_DESCRIPTOR_TYPE_INT32;
  6231. opcode parse_type = (opcode)descriptor_type;
  6232. // TODO(haberman): generate packed or non-packed first depending on "packed"
  6233. // setting in the fielddef. This will favor (in speed) whichever was
  6234. // specified.
  6235. assert((int)parse_type >= 0 && parse_type <= OP_MAX);
  6236. upb_selector_t sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  6237. int wire_type = upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  6238. if (upb_fielddef_isseq(f)) {
  6239. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  6240. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  6241. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  6242. putop(c, OP_PUSHLENDELIM);
  6243. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); // Packed
  6244. label(c, LABEL_LOOPSTART);
  6245. putop(c, parse_type, sel);
  6246. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  6247. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  6248. dispatchtarget(c, method, f, wire_type);
  6249. putop(c, OP_PUSHTAGDELIM, 0);
  6250. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); // Non-packed
  6251. label(c, LABEL_LOOPSTART);
  6252. putop(c, parse_type, sel);
  6253. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  6254. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  6255. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  6256. label(c, LABEL_LOOPBREAK);
  6257. putop(c, OP_POP); // Packed and non-packed join.
  6258. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  6259. putop(c, OP_SETDELIM); // Could remove for non-packed by dup ENDSEQ.
  6260. } else {
  6261. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  6262. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  6263. dispatchtarget(c, method, f, wire_type);
  6264. putop(c, parse_type, sel);
  6265. }
  6266. }
  6267. // Adds bytecode for parsing the given message to the given decoderplan,
  6268. // while adding all dispatch targets to this message's dispatch table.
  6269. static void compile_method(compiler *c, upb_pbdecodermethod *method) {
  6270. assert(method);
  6271. // Clear all entries in the dispatch table.
  6272. upb_inttable_uninit(&method->dispatch);
  6273. upb_inttable_init(&method->dispatch, UPB_CTYPE_UINT64);
  6274. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  6275. const upb_msgdef *md = upb_handlers_msgdef(h);
  6276. method->code_base.ofs = pcofs(c);
  6277. putop(c, OP_SETDISPATCH, &method->dispatch);
  6278. putsel(c, OP_STARTMSG, UPB_STARTMSG_SELECTOR, h);
  6279. label(c, LABEL_FIELD);
  6280. uint32_t* start_pc = c->pc;
  6281. upb_msg_field_iter i;
  6282. for(upb_msg_field_begin(&i, md);
  6283. !upb_msg_field_done(&i);
  6284. upb_msg_field_next(&i)) {
  6285. const upb_fielddef *f = upb_msg_iter_field(&i);
  6286. upb_fieldtype_t type = upb_fielddef_type(f);
  6287. if (type == UPB_TYPE_MESSAGE && !(haslazyhandlers(h, f) && c->lazy)) {
  6288. generate_msgfield(c, f, method);
  6289. } else if (type == UPB_TYPE_STRING || type == UPB_TYPE_BYTES ||
  6290. type == UPB_TYPE_MESSAGE) {
  6291. generate_delimfield(c, f, method);
  6292. } else {
  6293. generate_primitivefield(c, f, method);
  6294. }
  6295. }
  6296. // If there were no fields, or if no handlers were defined, we need to
  6297. // generate a non-empty loop body so that we can at least dispatch for unknown
  6298. // fields and check for the end of the message.
  6299. if (c->pc == start_pc) {
  6300. // Check for end-of-message.
  6301. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  6302. // Unconditionally dispatch.
  6303. putop(c, OP_DISPATCH, 0);
  6304. }
  6305. // For now we just loop back to the last field of the message (or if none,
  6306. // the DISPATCH opcode for the message).
  6307. putop(c, OP_BRANCH, -LABEL_FIELD);
  6308. // Insert both a label and a dispatch table entry for this end-of-msg.
  6309. label(c, LABEL_ENDMSG);
  6310. upb_value val = upb_value_uint64(pcofs(c) - method->code_base.ofs);
  6311. upb_inttable_insert(&method->dispatch, DISPATCH_ENDMSG, val);
  6312. putsel(c, OP_ENDMSG, UPB_ENDMSG_SELECTOR, h);
  6313. putop(c, OP_RET);
  6314. upb_inttable_compact(&method->dispatch);
  6315. }
  6316. // Populate "methods" with new upb_pbdecodermethod objects reachable from "h".
  6317. // Returns the method for these handlers.
  6318. //
  6319. // Generates a new method for every destination handlers reachable from "h".
  6320. static void find_methods(compiler *c, const upb_handlers *h) {
  6321. upb_value v;
  6322. if (upb_inttable_lookupptr(&c->group->methods, h, &v))
  6323. return;
  6324. newmethod(h, c->group);
  6325. // Find submethods.
  6326. upb_msg_field_iter i;
  6327. const upb_msgdef *md = upb_handlers_msgdef(h);
  6328. for(upb_msg_field_begin(&i, md);
  6329. !upb_msg_field_done(&i);
  6330. upb_msg_field_next(&i)) {
  6331. const upb_fielddef *f = upb_msg_iter_field(&i);
  6332. const upb_handlers *sub_h;
  6333. if (upb_fielddef_type(f) == UPB_TYPE_MESSAGE &&
  6334. (sub_h = upb_handlers_getsubhandlers(h, f)) != NULL) {
  6335. // We only generate a decoder method for submessages with handlers.
  6336. // Others will be parsed as unknown fields.
  6337. find_methods(c, sub_h);
  6338. }
  6339. }
  6340. }
  6341. // (Re-)compile bytecode for all messages in "msgs."
  6342. // Overwrites any existing bytecode in "c".
  6343. static void compile_methods(compiler *c) {
  6344. // Start over at the beginning of the bytecode.
  6345. c->pc = c->group->bytecode;
  6346. upb_inttable_iter i;
  6347. upb_inttable_begin(&i, &c->group->methods);
  6348. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  6349. upb_pbdecodermethod *method = upb_value_getptr(upb_inttable_iter_value(&i));
  6350. compile_method(c, method);
  6351. }
  6352. }
  6353. static void set_bytecode_handlers(mgroup *g) {
  6354. upb_inttable_iter i;
  6355. upb_inttable_begin(&i, &g->methods);
  6356. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  6357. upb_pbdecodermethod *m = upb_value_getptr(upb_inttable_iter_value(&i));
  6358. m->code_base.ptr = g->bytecode + m->code_base.ofs;
  6359. upb_byteshandler *h = &m->input_handler_;
  6360. upb_byteshandler_setstartstr(h, upb_pbdecoder_startbc, m->code_base.ptr);
  6361. upb_byteshandler_setstring(h, upb_pbdecoder_decode, g);
  6362. upb_byteshandler_setendstr(h, upb_pbdecoder_end, m);
  6363. }
  6364. }
  6365. /* JIT setup. *****************************************************************/
  6366. #ifdef UPB_USE_JIT_X64
  6367. static void sethandlers(mgroup *g, bool allowjit) {
  6368. g->jit_code = NULL;
  6369. if (allowjit) {
  6370. // Compile byte-code into machine code, create handlers.
  6371. upb_pbdecoder_jit(g);
  6372. } else {
  6373. set_bytecode_handlers(g);
  6374. }
  6375. }
  6376. #else // UPB_USE_JIT_X64
  6377. static void sethandlers(mgroup *g, bool allowjit) {
  6378. // No JIT compiled in; use bytecode handlers unconditionally.
  6379. UPB_UNUSED(allowjit);
  6380. set_bytecode_handlers(g);
  6381. }
  6382. #endif // UPB_USE_JIT_X64
  6383. // TODO(haberman): allow this to be constructed for an arbitrary set of dest
  6384. // handlers and other mgroups (but verify we have a transitive closure).
  6385. const mgroup *mgroup_new(const upb_handlers *dest, bool allowjit, bool lazy,
  6386. const void *owner) {
  6387. UPB_UNUSED(allowjit);
  6388. assert(upb_handlers_isfrozen(dest));
  6389. mgroup *g = newgroup(owner);
  6390. compiler *c = newcompiler(g, lazy);
  6391. find_methods(c, dest);
  6392. // We compile in two passes:
  6393. // 1. all messages are assigned relative offsets from the beginning of the
  6394. // bytecode (saved in method->code_base).
  6395. // 2. forwards OP_CALL instructions can be correctly linked since message
  6396. // offsets have been previously assigned.
  6397. //
  6398. // Could avoid the second pass by linking OP_CALL instructions somehow.
  6399. compile_methods(c);
  6400. compile_methods(c);
  6401. g->bytecode_end = c->pc;
  6402. freecompiler(c);
  6403. #ifdef UPB_DUMP_BYTECODE
  6404. FILE *f = fopen("/tmp/upb-bytecode", "wb");
  6405. assert(f);
  6406. dumpbc(g->bytecode, g->bytecode_end, stderr);
  6407. dumpbc(g->bytecode, g->bytecode_end, f);
  6408. fclose(f);
  6409. #endif
  6410. sethandlers(g, allowjit);
  6411. return g;
  6412. }
  6413. /* upb_pbcodecache ************************************************************/
  6414. void upb_pbcodecache_init(upb_pbcodecache *c) {
  6415. upb_inttable_init(&c->groups, UPB_CTYPE_CONSTPTR);
  6416. c->allow_jit_ = true;
  6417. }
  6418. void upb_pbcodecache_uninit(upb_pbcodecache *c) {
  6419. upb_inttable_iter i;
  6420. upb_inttable_begin(&i, &c->groups);
  6421. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  6422. const mgroup *group = upb_value_getconstptr(upb_inttable_iter_value(&i));
  6423. upb_refcounted_unref(UPB_UPCAST(group), c);
  6424. }
  6425. upb_inttable_uninit(&c->groups);
  6426. }
  6427. bool upb_pbcodecache_allowjit(const upb_pbcodecache *c) {
  6428. return c->allow_jit_;
  6429. }
  6430. bool upb_pbcodecache_setallowjit(upb_pbcodecache *c, bool allow) {
  6431. if (upb_inttable_count(&c->groups) > 0)
  6432. return false;
  6433. c->allow_jit_ = allow;
  6434. return true;
  6435. }
  6436. const upb_pbdecodermethod *upb_pbcodecache_getdecodermethod(
  6437. upb_pbcodecache *c, const upb_pbdecodermethodopts *opts) {
  6438. // Right now we build a new DecoderMethod every time.
  6439. // TODO(haberman): properly cache methods by their true key.
  6440. const mgroup *g = mgroup_new(opts->handlers, c->allow_jit_, opts->lazy, c);
  6441. upb_inttable_push(&c->groups, upb_value_constptr(g));
  6442. upb_value v;
  6443. bool ok = upb_inttable_lookupptr(&g->methods, opts->handlers, &v);
  6444. UPB_ASSERT_VAR(ok, ok);
  6445. return upb_value_getptr(v);
  6446. }
  6447. /* upb_pbdecodermethodopts ****************************************************/
  6448. void upb_pbdecodermethodopts_init(upb_pbdecodermethodopts *opts,
  6449. const upb_handlers *h) {
  6450. opts->handlers = h;
  6451. opts->lazy = false;
  6452. }
  6453. void upb_pbdecodermethodopts_setlazy(upb_pbdecodermethodopts *opts, bool lazy) {
  6454. opts->lazy = lazy;
  6455. }
  6456. /*
  6457. * upb - a minimalist implementation of protocol buffers.
  6458. *
  6459. * Copyright (c) 2008-2013 Google Inc. See LICENSE for details.
  6460. * Author: Josh Haberman <jhaberman@gmail.com>
  6461. *
  6462. * This file implements a VM for the interpreted (bytecode) decoder.
  6463. *
  6464. * Bytecode must previously have been generated using the bytecode compiler in
  6465. * compile_decoder.c. This decoder then walks through the bytecode op-by-op to
  6466. * parse the input.
  6467. *
  6468. * Decoding is fully resumable; we just keep a pointer to the current bytecode
  6469. * instruction and resume from there. A fair amount of the logic here is to
  6470. * handle the fact that values can span buffer seams and we have to be able to
  6471. * be capable of suspending/resuming from any byte in the stream. This
  6472. * sometimes requires keeping a few trailing bytes from the last buffer around
  6473. * in the "residual" buffer.
  6474. */
  6475. #include <inttypes.h>
  6476. #include <stddef.h>
  6477. #ifdef UPB_DUMP_BYTECODE
  6478. #include <stdio.h>
  6479. #endif
  6480. #define CHECK_SUSPEND(x) if (!(x)) return upb_pbdecoder_suspend(d);
  6481. // Error messages that are shared between the bytecode and JIT decoders.
  6482. const char *kPbDecoderStackOverflow = "Nesting too deep.";
  6483. // Error messages shared within this file.
  6484. static const char *kUnterminatedVarint = "Unterminated varint.";
  6485. /* upb_pbdecoder **************************************************************/
  6486. static opcode halt = OP_HALT;
  6487. // Whether an op consumes any of the input buffer.
  6488. static bool consumes_input(opcode op) {
  6489. switch (op) {
  6490. case OP_SETDISPATCH:
  6491. case OP_STARTMSG:
  6492. case OP_ENDMSG:
  6493. case OP_STARTSEQ:
  6494. case OP_ENDSEQ:
  6495. case OP_STARTSUBMSG:
  6496. case OP_ENDSUBMSG:
  6497. case OP_STARTSTR:
  6498. case OP_ENDSTR:
  6499. case OP_PUSHTAGDELIM:
  6500. case OP_POP:
  6501. case OP_SETDELIM:
  6502. case OP_SETBIGGROUPNUM:
  6503. case OP_CHECKDELIM:
  6504. case OP_CALL:
  6505. case OP_RET:
  6506. case OP_BRANCH:
  6507. return false;
  6508. default:
  6509. return true;
  6510. }
  6511. }
  6512. static bool in_residual_buf(const upb_pbdecoder *d, const char *p);
  6513. // It's unfortunate that we have to micro-manage the compiler with
  6514. // UPB_FORCEINLINE and UPB_NOINLINE, especially since this tuning is necessarily
  6515. // specific to one hardware configuration. But empirically on a Core i7,
  6516. // performance increases 30-50% with these annotations. Every instance where
  6517. // these appear, gcc 4.2.1 made the wrong decision and degraded performance in
  6518. // benchmarks.
  6519. static void seterr(upb_pbdecoder *d, const char *msg) {
  6520. upb_status status = UPB_STATUS_INIT;
  6521. upb_status_seterrmsg(&status, msg);
  6522. upb_env_reporterror(d->env, &status);
  6523. }
  6524. void upb_pbdecoder_seterr(upb_pbdecoder *d, const char *msg) {
  6525. seterr(d, msg);
  6526. }
  6527. /* Buffering ******************************************************************/
  6528. // We operate on one buffer at a time, which is either the user's buffer passed
  6529. // to our "decode" callback or some residual bytes from the previous buffer.
  6530. // How many bytes can be safely read from d->ptr without reading past end-of-buf
  6531. // or past the current delimited end.
  6532. static size_t curbufleft(const upb_pbdecoder *d) {
  6533. assert(d->data_end >= d->ptr);
  6534. return d->data_end - d->ptr;
  6535. }
  6536. // Overall stream offset of d->ptr.
  6537. uint64_t offset(const upb_pbdecoder *d) {
  6538. return d->bufstart_ofs + (d->ptr - d->buf);
  6539. }
  6540. // Advances d->ptr.
  6541. static void advance(upb_pbdecoder *d, size_t len) {
  6542. assert(curbufleft(d) >= len);
  6543. d->ptr += len;
  6544. }
  6545. static bool in_buf(const char *p, const char *buf, const char *end) {
  6546. return p >= buf && p <= end;
  6547. }
  6548. static bool in_residual_buf(const upb_pbdecoder *d, const char *p) {
  6549. return in_buf(p, d->residual, d->residual_end);
  6550. }
  6551. // Calculates the delim_end value, which is affected by both the current buffer
  6552. // and the parsing stack, so must be called whenever either is updated.
  6553. static void set_delim_end(upb_pbdecoder *d) {
  6554. size_t delim_ofs = d->top->end_ofs - d->bufstart_ofs;
  6555. if (delim_ofs <= (size_t)(d->end - d->buf)) {
  6556. d->delim_end = d->buf + delim_ofs;
  6557. d->data_end = d->delim_end;
  6558. } else {
  6559. d->data_end = d->end;
  6560. d->delim_end = NULL;
  6561. }
  6562. }
  6563. static void switchtobuf(upb_pbdecoder *d, const char *buf, const char *end) {
  6564. d->ptr = buf;
  6565. d->buf = buf;
  6566. d->end = end;
  6567. set_delim_end(d);
  6568. }
  6569. static void advancetobuf(upb_pbdecoder *d, const char *buf, size_t len) {
  6570. assert(curbufleft(d) == 0);
  6571. d->bufstart_ofs += (d->end - d->buf);
  6572. switchtobuf(d, buf, buf + len);
  6573. }
  6574. static void checkpoint(upb_pbdecoder *d) {
  6575. // The assertion here is in the interests of efficiency, not correctness.
  6576. // We are trying to ensure that we don't checkpoint() more often than
  6577. // necessary.
  6578. assert(d->checkpoint != d->ptr);
  6579. d->checkpoint = d->ptr;
  6580. }
  6581. // Resumes the decoder from an initial state or from a previous suspend.
  6582. int32_t upb_pbdecoder_resume(upb_pbdecoder *d, void *p, const char *buf,
  6583. size_t size, const upb_bufhandle *handle) {
  6584. UPB_UNUSED(p); // Useless; just for the benefit of the JIT.
  6585. d->buf_param = buf;
  6586. d->size_param = size;
  6587. d->handle = handle;
  6588. if (d->residual_end > d->residual) {
  6589. // We have residual bytes from the last buffer.
  6590. assert(d->ptr == d->residual);
  6591. } else {
  6592. switchtobuf(d, buf, buf + size);
  6593. }
  6594. d->checkpoint = d->ptr;
  6595. if (d->top->groupnum < 0) {
  6596. CHECK_RETURN(upb_pbdecoder_skipunknown(d, -1, 0));
  6597. d->checkpoint = d->ptr;
  6598. }
  6599. return DECODE_OK;
  6600. }
  6601. // Suspends the decoder at the last checkpoint, without saving any residual
  6602. // bytes. If there are any unconsumed bytes, returns a short byte count.
  6603. size_t upb_pbdecoder_suspend(upb_pbdecoder *d) {
  6604. d->pc = d->last;
  6605. if (d->checkpoint == d->residual) {
  6606. // Checkpoint was in residual buf; no user bytes were consumed.
  6607. d->ptr = d->residual;
  6608. return 0;
  6609. } else {
  6610. assert(!in_residual_buf(d, d->checkpoint));
  6611. assert(d->buf == d->buf_param);
  6612. size_t consumed = d->checkpoint - d->buf;
  6613. d->bufstart_ofs += consumed;
  6614. d->residual_end = d->residual;
  6615. switchtobuf(d, d->residual, d->residual_end);
  6616. return consumed;
  6617. }
  6618. }
  6619. // Suspends the decoder at the last checkpoint, and saves any unconsumed
  6620. // bytes in our residual buffer. This is necessary if we need more user
  6621. // bytes to form a complete value, which might not be contiguous in the
  6622. // user's buffers. Always consumes all user bytes.
  6623. static size_t suspend_save(upb_pbdecoder *d) {
  6624. // We hit end-of-buffer before we could parse a full value.
  6625. // Save any unconsumed bytes (if any) to the residual buffer.
  6626. d->pc = d->last;
  6627. if (d->checkpoint == d->residual) {
  6628. // Checkpoint was in residual buf; append user byte(s) to residual buf.
  6629. assert((d->residual_end - d->residual) + d->size_param <=
  6630. sizeof(d->residual));
  6631. if (!in_residual_buf(d, d->ptr)) {
  6632. d->bufstart_ofs -= (d->residual_end - d->residual);
  6633. }
  6634. memcpy(d->residual_end, d->buf_param, d->size_param);
  6635. d->residual_end += d->size_param;
  6636. } else {
  6637. // Checkpoint was in user buf; old residual bytes not needed.
  6638. assert(!in_residual_buf(d, d->checkpoint));
  6639. d->ptr = d->checkpoint;
  6640. size_t save = curbufleft(d);
  6641. assert(save <= sizeof(d->residual));
  6642. memcpy(d->residual, d->ptr, save);
  6643. d->residual_end = d->residual + save;
  6644. d->bufstart_ofs = offset(d);
  6645. }
  6646. switchtobuf(d, d->residual, d->residual_end);
  6647. return d->size_param;
  6648. }
  6649. // Skips "bytes" bytes in the stream, which may be more than available. If we
  6650. // skip more bytes than are available, we return a long read count to the caller
  6651. // indicating how many bytes the caller should skip before passing a new buffer.
  6652. static int32_t skip(upb_pbdecoder *d, size_t bytes) {
  6653. assert(!in_residual_buf(d, d->ptr) || d->size_param == 0);
  6654. if (curbufleft(d) >= bytes) {
  6655. // Skipped data is all in current buffer.
  6656. advance(d, bytes);
  6657. return DECODE_OK;
  6658. } else {
  6659. // Skipped data extends beyond currently available buffers.
  6660. d->pc = d->last;
  6661. size_t skip = bytes - curbufleft(d);
  6662. d->bufstart_ofs += (d->end - d->buf) + skip;
  6663. d->residual_end = d->residual;
  6664. switchtobuf(d, d->residual, d->residual_end);
  6665. return d->size_param + skip;
  6666. }
  6667. }
  6668. // Copies the next "bytes" bytes into "buf" and advances the stream.
  6669. // Requires that this many bytes are available in the current buffer.
  6670. UPB_FORCEINLINE static void consumebytes(upb_pbdecoder *d, void *buf,
  6671. size_t bytes) {
  6672. assert(bytes <= curbufleft(d));
  6673. memcpy(buf, d->ptr, bytes);
  6674. advance(d, bytes);
  6675. }
  6676. // Slow path for getting the next "bytes" bytes, regardless of whether they are
  6677. // available in the current buffer or not. Returns a status code as described
  6678. // in decoder.int.h.
  6679. UPB_NOINLINE static int32_t getbytes_slow(upb_pbdecoder *d, void *buf,
  6680. size_t bytes) {
  6681. const size_t avail = curbufleft(d);
  6682. consumebytes(d, buf, avail);
  6683. bytes -= avail;
  6684. assert(bytes > 0);
  6685. if (in_residual_buf(d, d->ptr)) {
  6686. advancetobuf(d, d->buf_param, d->size_param);
  6687. }
  6688. if (curbufleft(d) >= bytes) {
  6689. consumebytes(d, (char *)buf + avail, bytes);
  6690. return DECODE_OK;
  6691. } else if (d->data_end == d->delim_end) {
  6692. seterr(d, "Submessage ended in the middle of a value or group");
  6693. return upb_pbdecoder_suspend(d);
  6694. } else {
  6695. return suspend_save(d);
  6696. }
  6697. }
  6698. // Gets the next "bytes" bytes, regardless of whether they are available in the
  6699. // current buffer or not. Returns a status code as described in decoder.int.h.
  6700. UPB_FORCEINLINE static int32_t getbytes(upb_pbdecoder *d, void *buf,
  6701. size_t bytes) {
  6702. if (curbufleft(d) >= bytes) {
  6703. // Buffer has enough data to satisfy.
  6704. consumebytes(d, buf, bytes);
  6705. return DECODE_OK;
  6706. } else {
  6707. return getbytes_slow(d, buf, bytes);
  6708. }
  6709. }
  6710. UPB_NOINLINE static size_t peekbytes_slow(upb_pbdecoder *d, void *buf,
  6711. size_t bytes) {
  6712. size_t ret = curbufleft(d);
  6713. memcpy(buf, d->ptr, ret);
  6714. if (in_residual_buf(d, d->ptr)) {
  6715. size_t copy = UPB_MIN(bytes - ret, d->size_param);
  6716. memcpy((char *)buf + ret, d->buf_param, copy);
  6717. ret += copy;
  6718. }
  6719. return ret;
  6720. }
  6721. UPB_FORCEINLINE static size_t peekbytes(upb_pbdecoder *d, void *buf,
  6722. size_t bytes) {
  6723. if (curbufleft(d) >= bytes) {
  6724. memcpy(buf, d->ptr, bytes);
  6725. return bytes;
  6726. } else {
  6727. return peekbytes_slow(d, buf, bytes);
  6728. }
  6729. }
  6730. /* Decoding of wire types *****************************************************/
  6731. // Slow path for decoding a varint from the current buffer position.
  6732. // Returns a status code as described in decoder.int.h.
  6733. UPB_NOINLINE int32_t upb_pbdecoder_decode_varint_slow(upb_pbdecoder *d,
  6734. uint64_t *u64) {
  6735. *u64 = 0;
  6736. uint8_t byte = 0x80;
  6737. int bitpos;
  6738. for(bitpos = 0; bitpos < 70 && (byte & 0x80); bitpos += 7) {
  6739. int32_t ret = getbytes(d, &byte, 1);
  6740. if (ret >= 0) return ret;
  6741. *u64 |= (uint64_t)(byte & 0x7F) << bitpos;
  6742. }
  6743. if(bitpos == 70 && (byte & 0x80)) {
  6744. seterr(d, kUnterminatedVarint);
  6745. return upb_pbdecoder_suspend(d);
  6746. }
  6747. return DECODE_OK;
  6748. }
  6749. // Decodes a varint from the current buffer position.
  6750. // Returns a status code as described in decoder.int.h.
  6751. UPB_FORCEINLINE static int32_t decode_varint(upb_pbdecoder *d, uint64_t *u64) {
  6752. if (curbufleft(d) > 0 && !(*d->ptr & 0x80)) {
  6753. *u64 = *d->ptr;
  6754. advance(d, 1);
  6755. return DECODE_OK;
  6756. } else if (curbufleft(d) >= 10) {
  6757. // Fast case.
  6758. upb_decoderet r = upb_vdecode_fast(d->ptr);
  6759. if (r.p == NULL) {
  6760. seterr(d, kUnterminatedVarint);
  6761. return upb_pbdecoder_suspend(d);
  6762. }
  6763. advance(d, r.p - d->ptr);
  6764. *u64 = r.val;
  6765. return DECODE_OK;
  6766. } else {
  6767. // Slow case -- varint spans buffer seam.
  6768. return upb_pbdecoder_decode_varint_slow(d, u64);
  6769. }
  6770. }
  6771. // Decodes a 32-bit varint from the current buffer position.
  6772. // Returns a status code as described in decoder.int.h.
  6773. UPB_FORCEINLINE static int32_t decode_v32(upb_pbdecoder *d, uint32_t *u32) {
  6774. uint64_t u64;
  6775. int32_t ret = decode_varint(d, &u64);
  6776. if (ret >= 0) return ret;
  6777. if (u64 > UINT32_MAX) {
  6778. seterr(d, "Unterminated 32-bit varint");
  6779. // TODO(haberman) guarantee that this function return is >= 0 somehow,
  6780. // so we know this path will always be treated as error by our caller.
  6781. // Right now the size_t -> int32_t can overflow and produce negative values.
  6782. *u32 = 0;
  6783. return upb_pbdecoder_suspend(d);
  6784. }
  6785. *u32 = u64;
  6786. return DECODE_OK;
  6787. }
  6788. // Decodes a fixed32 from the current buffer position.
  6789. // Returns a status code as described in decoder.int.h.
  6790. // TODO: proper byte swapping for big-endian machines.
  6791. UPB_FORCEINLINE static int32_t decode_fixed32(upb_pbdecoder *d, uint32_t *u32) {
  6792. return getbytes(d, u32, 4);
  6793. }
  6794. // Decodes a fixed64 from the current buffer position.
  6795. // Returns a status code as described in decoder.int.h.
  6796. // TODO: proper byte swapping for big-endian machines.
  6797. UPB_FORCEINLINE static int32_t decode_fixed64(upb_pbdecoder *d, uint64_t *u64) {
  6798. return getbytes(d, u64, 8);
  6799. }
  6800. // Non-static versions of the above functions.
  6801. // These are called by the JIT for fallback paths.
  6802. int32_t upb_pbdecoder_decode_f32(upb_pbdecoder *d, uint32_t *u32) {
  6803. return decode_fixed32(d, u32);
  6804. }
  6805. int32_t upb_pbdecoder_decode_f64(upb_pbdecoder *d, uint64_t *u64) {
  6806. return decode_fixed64(d, u64);
  6807. }
  6808. static double as_double(uint64_t n) { double d; memcpy(&d, &n, 8); return d; }
  6809. static float as_float(uint32_t n) { float f; memcpy(&f, &n, 4); return f; }
  6810. // Pushes a frame onto the decoder stack.
  6811. static bool decoder_push(upb_pbdecoder *d, uint64_t end) {
  6812. upb_pbdecoder_frame *fr = d->top;
  6813. if (end > fr->end_ofs) {
  6814. seterr(d, "Submessage end extends past enclosing submessage.");
  6815. return false;
  6816. } else if (fr == d->limit) {
  6817. seterr(d, kPbDecoderStackOverflow);
  6818. return false;
  6819. }
  6820. fr++;
  6821. fr->end_ofs = end;
  6822. fr->dispatch = NULL;
  6823. fr->groupnum = 0;
  6824. d->top = fr;
  6825. return true;
  6826. }
  6827. static bool pushtagdelim(upb_pbdecoder *d, uint32_t arg) {
  6828. // While we expect to see an "end" tag (either ENDGROUP or a non-sequence
  6829. // field number) prior to hitting any enclosing submessage end, pushing our
  6830. // existing delim end prevents us from continuing to parse values from a
  6831. // corrupt proto that doesn't give us an END tag in time.
  6832. if (!decoder_push(d, d->top->end_ofs))
  6833. return false;
  6834. d->top->groupnum = arg;
  6835. return true;
  6836. }
  6837. // Pops a frame from the decoder stack.
  6838. static void decoder_pop(upb_pbdecoder *d) { d->top--; }
  6839. UPB_NOINLINE int32_t upb_pbdecoder_checktag_slow(upb_pbdecoder *d,
  6840. uint64_t expected) {
  6841. uint64_t data = 0;
  6842. size_t bytes = upb_value_size(expected);
  6843. size_t read = peekbytes(d, &data, bytes);
  6844. if (read == bytes && data == expected) {
  6845. // Advance past matched bytes.
  6846. int32_t ok = getbytes(d, &data, read);
  6847. UPB_ASSERT_VAR(ok, ok < 0);
  6848. return DECODE_OK;
  6849. } else if (read < bytes && memcmp(&data, &expected, read) == 0) {
  6850. return suspend_save(d);
  6851. } else {
  6852. return DECODE_MISMATCH;
  6853. }
  6854. }
  6855. int32_t upb_pbdecoder_skipunknown(upb_pbdecoder *d, int32_t fieldnum,
  6856. uint8_t wire_type) {
  6857. if (fieldnum >= 0)
  6858. goto have_tag;
  6859. while (true) {
  6860. uint32_t tag;
  6861. CHECK_RETURN(decode_v32(d, &tag));
  6862. wire_type = tag & 0x7;
  6863. fieldnum = tag >> 3;
  6864. have_tag:
  6865. if (fieldnum == 0) {
  6866. seterr(d, "Saw invalid field number (0)");
  6867. return upb_pbdecoder_suspend(d);
  6868. }
  6869. // TODO: deliver to unknown field callback.
  6870. switch (wire_type) {
  6871. case UPB_WIRE_TYPE_32BIT:
  6872. CHECK_RETURN(skip(d, 4));
  6873. break;
  6874. case UPB_WIRE_TYPE_64BIT:
  6875. CHECK_RETURN(skip(d, 8));
  6876. break;
  6877. case UPB_WIRE_TYPE_VARINT: {
  6878. uint64_t u64;
  6879. CHECK_RETURN(decode_varint(d, &u64));
  6880. break;
  6881. }
  6882. case UPB_WIRE_TYPE_DELIMITED: {
  6883. uint32_t len;
  6884. CHECK_RETURN(decode_v32(d, &len));
  6885. CHECK_RETURN(skip(d, len));
  6886. break;
  6887. }
  6888. case UPB_WIRE_TYPE_START_GROUP:
  6889. CHECK_SUSPEND(pushtagdelim(d, -fieldnum));
  6890. break;
  6891. case UPB_WIRE_TYPE_END_GROUP:
  6892. if (fieldnum == -d->top->groupnum) {
  6893. decoder_pop(d);
  6894. } else if (fieldnum == d->top->groupnum) {
  6895. return DECODE_ENDGROUP;
  6896. } else {
  6897. seterr(d, "Unmatched ENDGROUP tag.");
  6898. return upb_pbdecoder_suspend(d);
  6899. }
  6900. break;
  6901. default:
  6902. seterr(d, "Invalid wire type");
  6903. return upb_pbdecoder_suspend(d);
  6904. }
  6905. if (d->top->groupnum >= 0) {
  6906. return DECODE_OK;
  6907. }
  6908. if (d->ptr == d->delim_end) {
  6909. seterr(d, "Enclosing submessage ended in the middle of value or group");
  6910. // Unlike most errors we notice during parsing, right now we have consumed
  6911. // all of the user's input.
  6912. //
  6913. // There are three different options for how to handle this case:
  6914. //
  6915. // 1. decode() = short count, error = set
  6916. // 2. decode() = full count, error = set
  6917. // 3. decode() = full count, error NOT set, short count and error will
  6918. // be reported on next call to decode() (or end())
  6919. //
  6920. // (1) and (3) have the advantage that they preserve the invariant that an
  6921. // error occurs iff decode() returns a short count.
  6922. //
  6923. // (2) and (3) have the advantage of reflecting the fact that all of the
  6924. // bytes were in fact parsed (and possibly delivered to the unknown field
  6925. // handler, in the future when that is supported).
  6926. //
  6927. // (3) requires extra state in the decode (a place to store the "permanent
  6928. // error" that we should return for all subsequent attempts to decode).
  6929. // But we likely want this anyway.
  6930. //
  6931. // Right now we do (1), thanks to the fact that we checkpoint *after* this
  6932. // check. (3) may be a better choice long term; unclear at the moment.
  6933. return upb_pbdecoder_suspend(d);
  6934. }
  6935. checkpoint(d);
  6936. }
  6937. }
  6938. static void goto_endmsg(upb_pbdecoder *d) {
  6939. upb_value v;
  6940. bool found = upb_inttable_lookup32(d->top->dispatch, DISPATCH_ENDMSG, &v);
  6941. UPB_ASSERT_VAR(found, found);
  6942. d->pc = d->top->base + upb_value_getuint64(v);
  6943. }
  6944. // Parses a tag and jumps to the corresponding bytecode instruction for this
  6945. // field.
  6946. //
  6947. // If the tag is unknown (or the wire type doesn't match), parses the field as
  6948. // unknown. If the tag is a valid ENDGROUP tag, jumps to the bytecode
  6949. // instruction for the end of message.
  6950. static int32_t dispatch(upb_pbdecoder *d) {
  6951. upb_inttable *dispatch = d->top->dispatch;
  6952. // Decode tag.
  6953. uint32_t tag;
  6954. CHECK_RETURN(decode_v32(d, &tag));
  6955. uint8_t wire_type = tag & 0x7;
  6956. uint32_t fieldnum = tag >> 3;
  6957. // Lookup tag. Because of packed/non-packed compatibility, we have to
  6958. // check the wire type against two possibilities.
  6959. upb_value val;
  6960. if (fieldnum != DISPATCH_ENDMSG &&
  6961. upb_inttable_lookup32(dispatch, fieldnum, &val)) {
  6962. uint64_t v = upb_value_getuint64(val);
  6963. if (wire_type == (v & 0xff)) {
  6964. d->pc = d->top->base + (v >> 16);
  6965. return DECODE_OK;
  6966. } else if (wire_type == ((v >> 8) & 0xff)) {
  6967. bool found =
  6968. upb_inttable_lookup(dispatch, fieldnum + UPB_MAX_FIELDNUMBER, &val);
  6969. UPB_ASSERT_VAR(found, found);
  6970. d->pc = d->top->base + upb_value_getuint64(val);
  6971. return DECODE_OK;
  6972. }
  6973. }
  6974. // Unknown field or ENDGROUP.
  6975. int32_t ret = upb_pbdecoder_skipunknown(d, fieldnum, wire_type);
  6976. if (ret == DECODE_ENDGROUP) {
  6977. goto_endmsg(d);
  6978. return DECODE_OK;
  6979. } else if (ret == DECODE_OK) {
  6980. // We just consumed some input, so we might now have consumed all the data
  6981. // in the delmited region. Since every opcode that can trigger dispatch is
  6982. // directly preceded by OP_CHECKDELIM, rewind to it now to re-check the
  6983. // delimited end.
  6984. d->pc = d->last - 1;
  6985. assert(getop(*d->pc) == OP_CHECKDELIM);
  6986. return DECODE_OK;
  6987. }
  6988. return ret;
  6989. }
  6990. // Callers know that the stack is more than one deep because the opcodes that
  6991. // call this only occur after PUSH operations.
  6992. upb_pbdecoder_frame *outer_frame(upb_pbdecoder *d) {
  6993. assert(d->top != d->stack);
  6994. return d->top - 1;
  6995. }
  6996. /* The main decoding loop *****************************************************/
  6997. // The main decoder VM function. Uses traditional bytecode dispatch loop with a
  6998. // switch() statement.
  6999. size_t upb_pbdecoder_decode(void *closure, const void *hd, const char *buf,
  7000. size_t size, const upb_bufhandle *handle) {
  7001. upb_pbdecoder *d = closure;
  7002. const mgroup *group = hd;
  7003. assert(buf);
  7004. int32_t result = upb_pbdecoder_resume(d, NULL, buf, size, handle);
  7005. if (result == DECODE_ENDGROUP) {
  7006. goto_endmsg(d);
  7007. }
  7008. CHECK_RETURN(result);
  7009. UPB_UNUSED(group);
  7010. #define VMCASE(op, code) \
  7011. case op: { code; if (consumes_input(op)) checkpoint(d); break; }
  7012. #define PRIMITIVE_OP(type, wt, name, convfunc, ctype) \
  7013. VMCASE(OP_PARSE_ ## type, { \
  7014. ctype val; \
  7015. CHECK_RETURN(decode_ ## wt(d, &val)); \
  7016. upb_sink_put ## name(&d->top->sink, arg, (convfunc)(val)); \
  7017. })
  7018. while(1) {
  7019. d->last = d->pc;
  7020. int32_t instruction = *d->pc++;
  7021. opcode op = getop(instruction);
  7022. uint32_t arg = instruction >> 8;
  7023. int32_t longofs = arg;
  7024. assert(d->ptr != d->residual_end);
  7025. #ifdef UPB_DUMP_BYTECODE
  7026. fprintf(stderr, "s_ofs=%d buf_ofs=%d data_rem=%d buf_rem=%d delim_rem=%d "
  7027. "%x %s (%d)\n",
  7028. (int)offset(d),
  7029. (int)(d->ptr - d->buf),
  7030. (int)(d->data_end - d->ptr),
  7031. (int)(d->end - d->ptr),
  7032. (int)((d->top->end_ofs - d->bufstart_ofs) - (d->ptr - d->buf)),
  7033. (int)(d->pc - 1 - group->bytecode),
  7034. upb_pbdecoder_getopname(op),
  7035. arg);
  7036. #endif
  7037. switch (op) {
  7038. // Technically, we are losing data if we see a 32-bit varint that is not
  7039. // properly sign-extended. We could detect this and error about the data
  7040. // loss, but proto2 does not do this, so we pass.
  7041. PRIMITIVE_OP(INT32, varint, int32, int32_t, uint64_t)
  7042. PRIMITIVE_OP(INT64, varint, int64, int64_t, uint64_t)
  7043. PRIMITIVE_OP(UINT32, varint, uint32, uint32_t, uint64_t)
  7044. PRIMITIVE_OP(UINT64, varint, uint64, uint64_t, uint64_t)
  7045. PRIMITIVE_OP(FIXED32, fixed32, uint32, uint32_t, uint32_t)
  7046. PRIMITIVE_OP(FIXED64, fixed64, uint64, uint64_t, uint64_t)
  7047. PRIMITIVE_OP(SFIXED32, fixed32, int32, int32_t, uint32_t)
  7048. PRIMITIVE_OP(SFIXED64, fixed64, int64, int64_t, uint64_t)
  7049. PRIMITIVE_OP(BOOL, varint, bool, bool, uint64_t)
  7050. PRIMITIVE_OP(DOUBLE, fixed64, double, as_double, uint64_t)
  7051. PRIMITIVE_OP(FLOAT, fixed32, float, as_float, uint32_t)
  7052. PRIMITIVE_OP(SINT32, varint, int32, upb_zzdec_32, uint64_t)
  7053. PRIMITIVE_OP(SINT64, varint, int64, upb_zzdec_64, uint64_t)
  7054. VMCASE(OP_SETDISPATCH,
  7055. d->top->base = d->pc - 1;
  7056. memcpy(&d->top->dispatch, d->pc, sizeof(void*));
  7057. d->pc += sizeof(void*) / sizeof(uint32_t);
  7058. )
  7059. VMCASE(OP_STARTMSG,
  7060. CHECK_SUSPEND(upb_sink_startmsg(&d->top->sink));
  7061. )
  7062. VMCASE(OP_ENDMSG,
  7063. CHECK_SUSPEND(upb_sink_endmsg(&d->top->sink, d->status));
  7064. )
  7065. VMCASE(OP_STARTSEQ,
  7066. upb_pbdecoder_frame *outer = outer_frame(d);
  7067. CHECK_SUSPEND(upb_sink_startseq(&outer->sink, arg, &d->top->sink));
  7068. )
  7069. VMCASE(OP_ENDSEQ,
  7070. CHECK_SUSPEND(upb_sink_endseq(&d->top->sink, arg));
  7071. )
  7072. VMCASE(OP_STARTSUBMSG,
  7073. upb_pbdecoder_frame *outer = outer_frame(d);
  7074. CHECK_SUSPEND(upb_sink_startsubmsg(&outer->sink, arg, &d->top->sink));
  7075. )
  7076. VMCASE(OP_ENDSUBMSG,
  7077. CHECK_SUSPEND(upb_sink_endsubmsg(&d->top->sink, arg));
  7078. )
  7079. VMCASE(OP_STARTSTR,
  7080. uint32_t len = d->top->end_ofs - offset(d);
  7081. upb_pbdecoder_frame *outer = outer_frame(d);
  7082. CHECK_SUSPEND(upb_sink_startstr(&outer->sink, arg, len, &d->top->sink));
  7083. if (len == 0) {
  7084. d->pc++; // Skip OP_STRING.
  7085. }
  7086. )
  7087. VMCASE(OP_STRING,
  7088. uint32_t len = curbufleft(d);
  7089. size_t n = upb_sink_putstring(&d->top->sink, arg, d->ptr, len, handle);
  7090. if (n > len) {
  7091. if (n > d->top->end_ofs - offset(d)) {
  7092. seterr(d, "Tried to skip past end of string.");
  7093. return upb_pbdecoder_suspend(d);
  7094. } else {
  7095. int32_t ret = skip(d, n);
  7096. // This shouldn't return DECODE_OK, because n > len.
  7097. assert(ret >= 0);
  7098. return ret;
  7099. }
  7100. }
  7101. advance(d, n);
  7102. if (n < len || d->delim_end == NULL) {
  7103. // We aren't finished with this string yet.
  7104. d->pc--; // Repeat OP_STRING.
  7105. if (n > 0) checkpoint(d);
  7106. return upb_pbdecoder_suspend(d);
  7107. }
  7108. )
  7109. VMCASE(OP_ENDSTR,
  7110. CHECK_SUSPEND(upb_sink_endstr(&d->top->sink, arg));
  7111. )
  7112. VMCASE(OP_PUSHTAGDELIM,
  7113. CHECK_SUSPEND(pushtagdelim(d, arg));
  7114. )
  7115. VMCASE(OP_SETBIGGROUPNUM,
  7116. d->top->groupnum = *d->pc++;
  7117. )
  7118. VMCASE(OP_POP,
  7119. assert(d->top > d->stack);
  7120. decoder_pop(d);
  7121. )
  7122. VMCASE(OP_PUSHLENDELIM,
  7123. uint32_t len;
  7124. CHECK_RETURN(decode_v32(d, &len));
  7125. CHECK_SUSPEND(decoder_push(d, offset(d) + len));
  7126. set_delim_end(d);
  7127. )
  7128. VMCASE(OP_SETDELIM,
  7129. set_delim_end(d);
  7130. )
  7131. VMCASE(OP_CHECKDELIM,
  7132. // We are guaranteed of this assert because we never allow ourselves to
  7133. // consume bytes beyond data_end, which covers delim_end when non-NULL.
  7134. assert(!(d->delim_end && d->ptr > d->delim_end));
  7135. if (d->ptr == d->delim_end)
  7136. d->pc += longofs;
  7137. )
  7138. VMCASE(OP_CALL,
  7139. d->callstack[d->call_len++] = d->pc;
  7140. d->pc += longofs;
  7141. )
  7142. VMCASE(OP_RET,
  7143. assert(d->call_len > 0);
  7144. d->pc = d->callstack[--d->call_len];
  7145. )
  7146. VMCASE(OP_BRANCH,
  7147. d->pc += longofs;
  7148. )
  7149. VMCASE(OP_TAG1,
  7150. CHECK_SUSPEND(curbufleft(d) > 0);
  7151. uint8_t expected = (arg >> 8) & 0xff;
  7152. if (*d->ptr == expected) {
  7153. advance(d, 1);
  7154. } else {
  7155. int8_t shortofs;
  7156. badtag:
  7157. shortofs = arg;
  7158. if (shortofs == LABEL_DISPATCH) {
  7159. CHECK_RETURN(dispatch(d));
  7160. } else {
  7161. d->pc += shortofs;
  7162. break; // Avoid checkpoint().
  7163. }
  7164. }
  7165. )
  7166. VMCASE(OP_TAG2,
  7167. CHECK_SUSPEND(curbufleft(d) > 0);
  7168. uint16_t expected = (arg >> 8) & 0xffff;
  7169. if (curbufleft(d) >= 2) {
  7170. uint16_t actual;
  7171. memcpy(&actual, d->ptr, 2);
  7172. if (expected == actual) {
  7173. advance(d, 2);
  7174. } else {
  7175. goto badtag;
  7176. }
  7177. } else {
  7178. int32_t result = upb_pbdecoder_checktag_slow(d, expected);
  7179. if (result == DECODE_MISMATCH) goto badtag;
  7180. if (result >= 0) return result;
  7181. }
  7182. )
  7183. VMCASE(OP_TAGN, {
  7184. uint64_t expected;
  7185. memcpy(&expected, d->pc, 8);
  7186. d->pc += 2;
  7187. int32_t result = upb_pbdecoder_checktag_slow(d, expected);
  7188. if (result == DECODE_MISMATCH) goto badtag;
  7189. if (result >= 0) return result;
  7190. })
  7191. VMCASE(OP_DISPATCH, {
  7192. CHECK_RETURN(dispatch(d));
  7193. })
  7194. VMCASE(OP_HALT, {
  7195. return size;
  7196. })
  7197. }
  7198. }
  7199. }
  7200. void *upb_pbdecoder_startbc(void *closure, const void *pc, size_t size_hint) {
  7201. upb_pbdecoder *d = closure;
  7202. UPB_UNUSED(size_hint);
  7203. d->top->end_ofs = UINT64_MAX;
  7204. d->bufstart_ofs = 0;
  7205. d->call_len = 1;
  7206. d->callstack[0] = &halt;
  7207. d->pc = pc;
  7208. return d;
  7209. }
  7210. void *upb_pbdecoder_startjit(void *closure, const void *hd, size_t size_hint) {
  7211. UPB_UNUSED(hd);
  7212. UPB_UNUSED(size_hint);
  7213. upb_pbdecoder *d = closure;
  7214. d->top->end_ofs = UINT64_MAX;
  7215. d->bufstart_ofs = 0;
  7216. d->call_len = 0;
  7217. return d;
  7218. }
  7219. bool upb_pbdecoder_end(void *closure, const void *handler_data) {
  7220. upb_pbdecoder *d = closure;
  7221. const upb_pbdecodermethod *method = handler_data;
  7222. if (d->residual_end > d->residual) {
  7223. seterr(d, "Unexpected EOF");
  7224. return false;
  7225. }
  7226. if (d->top->end_ofs != UINT64_MAX) {
  7227. seterr(d, "Unexpected EOF inside delimited string");
  7228. return false;
  7229. }
  7230. // Message ends here.
  7231. uint64_t end = offset(d);
  7232. d->top->end_ofs = end;
  7233. char dummy;
  7234. #ifdef UPB_USE_JIT_X64
  7235. const mgroup *group = (const mgroup*)method->group;
  7236. if (group->jit_code) {
  7237. if (d->top != d->stack)
  7238. d->stack->end_ofs = 0;
  7239. group->jit_code(closure, method->code_base.ptr, &dummy, 0, NULL);
  7240. } else {
  7241. #endif
  7242. d->stack->end_ofs = end;
  7243. const uint32_t *p = d->pc;
  7244. // Check the previous bytecode, but guard against beginning.
  7245. if (p != method->code_base.ptr) p--;
  7246. if (getop(*p) == OP_CHECKDELIM) {
  7247. // Rewind from OP_TAG* to OP_CHECKDELIM.
  7248. assert(getop(*d->pc) == OP_TAG1 ||
  7249. getop(*d->pc) == OP_TAG2 ||
  7250. getop(*d->pc) == OP_TAGN ||
  7251. getop(*d->pc == OP_DISPATCH));
  7252. d->pc = p;
  7253. }
  7254. upb_pbdecoder_decode(closure, handler_data, &dummy, 0, NULL);
  7255. #ifdef UPB_USE_JIT_X64
  7256. }
  7257. #endif
  7258. if (d->call_len != 0) {
  7259. seterr(d, "Unexpected EOF");
  7260. return false;
  7261. }
  7262. return true;
  7263. }
  7264. void upb_pbdecoder_reset(upb_pbdecoder *d) {
  7265. d->top = d->stack;
  7266. d->top->groupnum = 0;
  7267. d->ptr = d->residual;
  7268. d->buf = d->residual;
  7269. d->end = d->residual;
  7270. d->residual_end = d->residual;
  7271. }
  7272. static size_t stacksize(upb_pbdecoder *d, size_t entries) {
  7273. UPB_UNUSED(d);
  7274. return entries * sizeof(upb_pbdecoder_frame);
  7275. }
  7276. static size_t callstacksize(upb_pbdecoder *d, size_t entries) {
  7277. UPB_UNUSED(d);
  7278. #ifdef UPB_USE_JIT_X64
  7279. if (d->method_->is_native_) {
  7280. // Each native stack frame needs two pointers, plus we need a few frames for
  7281. // the enter/exit trampolines.
  7282. size_t ret = entries * sizeof(void*) * 2;
  7283. ret += sizeof(void*) * 10;
  7284. return ret;
  7285. }
  7286. #endif
  7287. return entries * sizeof(uint32_t*);
  7288. }
  7289. upb_pbdecoder *upb_pbdecoder_create(upb_env *e, const upb_pbdecodermethod *m,
  7290. upb_sink *sink) {
  7291. const size_t default_max_nesting = 64;
  7292. #ifndef NDEBUG
  7293. size_t size_before = upb_env_bytesallocated(e);
  7294. #endif
  7295. upb_pbdecoder *d = upb_env_malloc(e, sizeof(upb_pbdecoder));
  7296. if (!d) return NULL;
  7297. d->method_ = m;
  7298. d->callstack = upb_env_malloc(e, callstacksize(d, default_max_nesting));
  7299. d->stack = upb_env_malloc(e, stacksize(d, default_max_nesting));
  7300. if (!d->stack || !d->callstack) {
  7301. return NULL;
  7302. }
  7303. d->env = e;
  7304. d->limit = d->stack + default_max_nesting - 1;
  7305. d->stack_size = default_max_nesting;
  7306. upb_pbdecoder_reset(d);
  7307. upb_bytessink_reset(&d->input_, &m->input_handler_, d);
  7308. assert(sink);
  7309. if (d->method_->dest_handlers_) {
  7310. if (sink->handlers != d->method_->dest_handlers_)
  7311. return NULL;
  7312. }
  7313. upb_sink_reset(&d->top->sink, sink->handlers, sink->closure);
  7314. // If this fails, increase the value in decoder.h.
  7315. assert(upb_env_bytesallocated(e) - size_before <= UPB_PB_DECODER_SIZE);
  7316. return d;
  7317. }
  7318. uint64_t upb_pbdecoder_bytesparsed(const upb_pbdecoder *d) {
  7319. return offset(d);
  7320. }
  7321. const upb_pbdecodermethod *upb_pbdecoder_method(const upb_pbdecoder *d) {
  7322. return d->method_;
  7323. }
  7324. upb_bytessink *upb_pbdecoder_input(upb_pbdecoder *d) {
  7325. return &d->input_;
  7326. }
  7327. size_t upb_pbdecoder_maxnesting(const upb_pbdecoder *d) {
  7328. return d->stack_size;
  7329. }
  7330. bool upb_pbdecoder_setmaxnesting(upb_pbdecoder *d, size_t max) {
  7331. assert(d->top >= d->stack);
  7332. if (max < (size_t)(d->top - d->stack)) {
  7333. // Can't set a limit smaller than what we are currently at.
  7334. return false;
  7335. }
  7336. if (max > d->stack_size) {
  7337. // Need to reallocate stack and callstack to accommodate.
  7338. size_t old_size = stacksize(d, d->stack_size);
  7339. size_t new_size = stacksize(d, max);
  7340. void *p = upb_env_realloc(d->env, d->stack, old_size, new_size);
  7341. if (!p) {
  7342. return false;
  7343. }
  7344. d->stack = p;
  7345. old_size = callstacksize(d, d->stack_size);
  7346. new_size = callstacksize(d, max);
  7347. p = upb_env_realloc(d->env, d->callstack, old_size, new_size);
  7348. if (!p) {
  7349. return false;
  7350. }
  7351. d->callstack = p;
  7352. d->stack_size = max;
  7353. }
  7354. d->limit = d->stack + max - 1;
  7355. return true;
  7356. }
  7357. /*
  7358. * upb - a minimalist implementation of protocol buffers.
  7359. *
  7360. * Copyright (c) 2014 Google Inc. See LICENSE for details.
  7361. * Author: Josh Haberman <jhaberman@gmail.com>
  7362. *
  7363. * Since we are implementing pure handlers (ie. without any out-of-band access
  7364. * to pre-computed lengths), we have to buffer all submessages before we can
  7365. * emit even their first byte.
  7366. *
  7367. * Not knowing the size of submessages also means we can't write a perfect
  7368. * zero-copy implementation, even with buffering. Lengths are stored as
  7369. * varints, which means that we don't know how many bytes to reserve for the
  7370. * length until we know what the length is.
  7371. *
  7372. * This leaves us with three main choices:
  7373. *
  7374. * 1. buffer all submessage data in a temporary buffer, then copy it exactly
  7375. * once into the output buffer.
  7376. *
  7377. * 2. attempt to buffer data directly into the output buffer, estimating how
  7378. * many bytes each length will take. When our guesses are wrong, use
  7379. * memmove() to grow or shrink the allotted space.
  7380. *
  7381. * 3. buffer directly into the output buffer, allocating a max length
  7382. * ahead-of-time for each submessage length. If we overallocated, we waste
  7383. * space, but no memcpy() or memmove() is required. This approach requires
  7384. * defining a maximum size for submessages and rejecting submessages that
  7385. * exceed that size.
  7386. *
  7387. * (2) and (3) have the potential to have better performance, but they are more
  7388. * complicated and subtle to implement:
  7389. *
  7390. * (3) requires making an arbitrary choice of the maximum message size; it
  7391. * wastes space when submessages are shorter than this and fails
  7392. * completely when they are longer. This makes it more finicky and
  7393. * requires configuration based on the input. It also makes it impossible
  7394. * to perfectly match the output of reference encoders that always use the
  7395. * optimal amount of space for each length.
  7396. *
  7397. * (2) requires guessing the the size upfront, and if multiple lengths are
  7398. * guessed wrong the minimum required number of memmove() operations may
  7399. * be complicated to compute correctly. Implemented properly, it may have
  7400. * a useful amortized or average cost, but more investigation is required
  7401. * to determine this and what the optimal algorithm is to achieve it.
  7402. *
  7403. * (1) makes you always pay for exactly one copy, but its implementation is
  7404. * the simplest and its performance is predictable.
  7405. *
  7406. * So for now, we implement (1) only. If we wish to optimize later, we should
  7407. * be able to do it without affecting users.
  7408. *
  7409. * The strategy is to buffer the segments of data that do *not* depend on
  7410. * unknown lengths in one buffer, and keep a separate buffer of segment pointers
  7411. * and lengths. When the top-level submessage ends, we can go beginning to end,
  7412. * alternating the writing of lengths with memcpy() of the rest of the data.
  7413. * At the top level though, no buffering is required.
  7414. */
  7415. #include <stdlib.h>
  7416. // The output buffer is divided into segments; a segment is a string of data
  7417. // that is "ready to go" -- it does not need any varint lengths inserted into
  7418. // the middle. The seams between segments are where varints will be inserted
  7419. // once they are known.
  7420. //
  7421. // We also use the concept of a "run", which is a range of encoded bytes that
  7422. // occur at a single submessage level. Every segment contains one or more runs.
  7423. //
  7424. // A segment can span messages. Consider:
  7425. //
  7426. // .--Submessage lengths---------.
  7427. // | | |
  7428. // | V V
  7429. // V | |--------------- | |-----------------
  7430. // Submessages: | |-----------------------------------------------
  7431. // Top-level msg: ------------------------------------------------------------
  7432. //
  7433. // Segments: ----- ------------------- -----------------
  7434. // Runs: *---- *--------------*--- *----------------
  7435. // (* marks the start)
  7436. //
  7437. // Note that the top-level menssage is not in any segment because it does not
  7438. // have any length preceding it.
  7439. //
  7440. // A segment is only interrupted when another length needs to be inserted. So
  7441. // observe how the second segment spans both the inner submessage and part of
  7442. // the next enclosing message.
  7443. typedef struct {
  7444. uint32_t msglen; // The length to varint-encode before this segment.
  7445. uint32_t seglen; // Length of the segment.
  7446. } upb_pb_encoder_segment;
  7447. struct upb_pb_encoder {
  7448. upb_env *env;
  7449. // Our input and output.
  7450. upb_sink input_;
  7451. upb_bytessink *output_;
  7452. // The "subclosure" -- used as the inner closure as part of the bytessink
  7453. // protocol.
  7454. void *subc;
  7455. // The output buffer and limit, and our current write position. "buf"
  7456. // initially points to "initbuf", but is dynamically allocated if we need to
  7457. // grow beyond the initial size.
  7458. char *buf, *ptr, *limit;
  7459. // The beginning of the current run, or undefined if we are at the top level.
  7460. char *runbegin;
  7461. // The list of segments we are accumulating.
  7462. upb_pb_encoder_segment *segbuf, *segptr, *seglimit;
  7463. // The stack of enclosing submessages. Each entry in the stack points to the
  7464. // segment where this submessage's length is being accumulated.
  7465. int *stack, *top, *stacklimit;
  7466. // Depth of startmsg/endmsg calls.
  7467. int depth;
  7468. };
  7469. /* low-level buffering ********************************************************/
  7470. // Low-level functions for interacting with the output buffer.
  7471. // TODO(haberman): handle pushback
  7472. static void putbuf(upb_pb_encoder *e, const char *buf, size_t len) {
  7473. size_t n = upb_bytessink_putbuf(e->output_, e->subc, buf, len, NULL);
  7474. UPB_ASSERT_VAR(n, n == len);
  7475. }
  7476. static upb_pb_encoder_segment *top(upb_pb_encoder *e) {
  7477. return &e->segbuf[*e->top];
  7478. }
  7479. // Call to ensure that at least "bytes" bytes are available for writing at
  7480. // e->ptr. Returns false if the bytes could not be allocated.
  7481. static bool reserve(upb_pb_encoder *e, size_t bytes) {
  7482. if ((size_t)(e->limit - e->ptr) < bytes) {
  7483. // Grow buffer.
  7484. size_t needed = bytes + (e->ptr - e->buf);
  7485. size_t old_size = e->limit - e->buf;
  7486. size_t new_size = old_size;
  7487. while (new_size < needed) {
  7488. new_size *= 2;
  7489. }
  7490. char *new_buf = upb_env_realloc(e->env, e->buf, old_size, new_size);
  7491. if (new_buf == NULL) {
  7492. return false;
  7493. }
  7494. e->ptr = new_buf + (e->ptr - e->buf);
  7495. e->runbegin = new_buf + (e->runbegin - e->buf);
  7496. e->limit = new_buf + new_size;
  7497. e->buf = new_buf;
  7498. }
  7499. return true;
  7500. }
  7501. // Call when "bytes" bytes have been writte at e->ptr. The caller *must* have
  7502. // previously called reserve() with at least this many bytes.
  7503. static void encoder_advance(upb_pb_encoder *e, size_t bytes) {
  7504. assert((size_t)(e->limit - e->ptr) >= bytes);
  7505. e->ptr += bytes;
  7506. }
  7507. // Call when all of the bytes for a handler have been written. Flushes the
  7508. // bytes if possible and necessary, returning false if this failed.
  7509. static bool commit(upb_pb_encoder *e) {
  7510. if (!e->top) {
  7511. // We aren't inside a delimited region. Flush our accumulated bytes to
  7512. // the output.
  7513. //
  7514. // TODO(haberman): in the future we may want to delay flushing for
  7515. // efficiency reasons.
  7516. putbuf(e, e->buf, e->ptr - e->buf);
  7517. e->ptr = e->buf;
  7518. }
  7519. return true;
  7520. }
  7521. // Writes the given bytes to the buffer, handling reserve/advance.
  7522. static bool encode_bytes(upb_pb_encoder *e, const void *data, size_t len) {
  7523. if (!reserve(e, len)) {
  7524. return false;
  7525. }
  7526. memcpy(e->ptr, data, len);
  7527. encoder_advance(e, len);
  7528. return true;
  7529. }
  7530. // Finish the current run by adding the run totals to the segment and message
  7531. // length.
  7532. static void accumulate(upb_pb_encoder *e) {
  7533. assert(e->ptr >= e->runbegin);
  7534. size_t run_len = e->ptr - e->runbegin;
  7535. e->segptr->seglen += run_len;
  7536. top(e)->msglen += run_len;
  7537. e->runbegin = e->ptr;
  7538. }
  7539. // Call to indicate the start of delimited region for which the full length is
  7540. // not yet known. All data will be buffered until the length is known.
  7541. // Delimited regions may be nested; their lengths will all be tracked properly.
  7542. static bool start_delim(upb_pb_encoder *e) {
  7543. if (e->top) {
  7544. // We are already buffering, advance to the next segment and push it on the
  7545. // stack.
  7546. accumulate(e);
  7547. if (++e->top == e->stacklimit) {
  7548. // TODO(haberman): grow stack?
  7549. return false;
  7550. }
  7551. if (++e->segptr == e->seglimit) {
  7552. // Grow segment buffer.
  7553. size_t old_size =
  7554. (e->seglimit - e->segbuf) * sizeof(upb_pb_encoder_segment);
  7555. size_t new_size = old_size * 2;
  7556. upb_pb_encoder_segment *new_buf =
  7557. upb_env_realloc(e->env, e->segbuf, old_size, new_size);
  7558. if (new_buf == NULL) {
  7559. return false;
  7560. }
  7561. e->segptr = new_buf + (e->segptr - e->segbuf);
  7562. e->seglimit = new_buf + (new_size / sizeof(upb_pb_encoder_segment));
  7563. e->segbuf = new_buf;
  7564. }
  7565. } else {
  7566. // We were previously at the top level, start buffering.
  7567. e->segptr = e->segbuf;
  7568. e->top = e->stack;
  7569. e->runbegin = e->ptr;
  7570. }
  7571. *e->top = e->segptr - e->segbuf;
  7572. e->segptr->seglen = 0;
  7573. e->segptr->msglen = 0;
  7574. return true;
  7575. }
  7576. // Call to indicate the end of a delimited region. We now know the length of
  7577. // the delimited region. If we are not nested inside any other delimited
  7578. // regions, we can now emit all of the buffered data we accumulated.
  7579. static bool end_delim(upb_pb_encoder *e) {
  7580. accumulate(e);
  7581. size_t msglen = top(e)->msglen;
  7582. if (e->top == e->stack) {
  7583. // All lengths are now available, emit all buffered data.
  7584. char buf[UPB_PB_VARINT_MAX_LEN];
  7585. upb_pb_encoder_segment *s;
  7586. const char *ptr = e->buf;
  7587. for (s = e->segbuf; s <= e->segptr; s++) {
  7588. size_t lenbytes = upb_vencode64(s->msglen, buf);
  7589. putbuf(e, buf, lenbytes);
  7590. putbuf(e, ptr, s->seglen);
  7591. ptr += s->seglen;
  7592. }
  7593. e->ptr = e->buf;
  7594. e->top = NULL;
  7595. } else {
  7596. // Need to keep buffering; propagate length info into enclosing submessages.
  7597. --e->top;
  7598. top(e)->msglen += msglen + upb_varint_size(msglen);
  7599. }
  7600. return true;
  7601. }
  7602. /* tag_t **********************************************************************/
  7603. // A precomputed (pre-encoded) tag and length.
  7604. typedef struct {
  7605. uint8_t bytes;
  7606. char tag[7];
  7607. } tag_t;
  7608. // Allocates a new tag for this field, and sets it in these handlerattr.
  7609. static void new_tag(upb_handlers *h, const upb_fielddef *f, upb_wiretype_t wt,
  7610. upb_handlerattr *attr) {
  7611. uint32_t n = upb_fielddef_number(f);
  7612. tag_t *tag = malloc(sizeof(tag_t));
  7613. tag->bytes = upb_vencode64((n << 3) | wt, tag->tag);
  7614. upb_handlerattr_init(attr);
  7615. upb_handlerattr_sethandlerdata(attr, tag);
  7616. upb_handlers_addcleanup(h, tag, free);
  7617. }
  7618. static bool encode_tag(upb_pb_encoder *e, const tag_t *tag) {
  7619. return encode_bytes(e, tag->tag, tag->bytes);
  7620. }
  7621. /* encoding of wire types *****************************************************/
  7622. static bool encode_fixed64(upb_pb_encoder *e, uint64_t val) {
  7623. // TODO(haberman): byte-swap for big endian.
  7624. return encode_bytes(e, &val, sizeof(uint64_t));
  7625. }
  7626. static bool encode_fixed32(upb_pb_encoder *e, uint32_t val) {
  7627. // TODO(haberman): byte-swap for big endian.
  7628. return encode_bytes(e, &val, sizeof(uint32_t));
  7629. }
  7630. static bool encode_varint(upb_pb_encoder *e, uint64_t val) {
  7631. if (!reserve(e, UPB_PB_VARINT_MAX_LEN)) {
  7632. return false;
  7633. }
  7634. encoder_advance(e, upb_vencode64(val, e->ptr));
  7635. return true;
  7636. }
  7637. static uint64_t dbl2uint64(double d) {
  7638. uint64_t ret;
  7639. memcpy(&ret, &d, sizeof(uint64_t));
  7640. return ret;
  7641. }
  7642. static uint32_t flt2uint32(float d) {
  7643. uint32_t ret;
  7644. memcpy(&ret, &d, sizeof(uint32_t));
  7645. return ret;
  7646. }
  7647. /* encoding of proto types ****************************************************/
  7648. static bool startmsg(void *c, const void *hd) {
  7649. upb_pb_encoder *e = c;
  7650. UPB_UNUSED(hd);
  7651. if (e->depth++ == 0) {
  7652. upb_bytessink_start(e->output_, 0, &e->subc);
  7653. }
  7654. return true;
  7655. }
  7656. static bool endmsg(void *c, const void *hd, upb_status *status) {
  7657. upb_pb_encoder *e = c;
  7658. UPB_UNUSED(hd);
  7659. UPB_UNUSED(status);
  7660. if (--e->depth == 0) {
  7661. upb_bytessink_end(e->output_);
  7662. }
  7663. return true;
  7664. }
  7665. static void *encode_startdelimfield(void *c, const void *hd) {
  7666. bool ok = encode_tag(c, hd) && commit(c) && start_delim(c);
  7667. return ok ? c : UPB_BREAK;
  7668. }
  7669. static bool encode_enddelimfield(void *c, const void *hd) {
  7670. UPB_UNUSED(hd);
  7671. return end_delim(c);
  7672. }
  7673. static void *encode_startgroup(void *c, const void *hd) {
  7674. return (encode_tag(c, hd) && commit(c)) ? c : UPB_BREAK;
  7675. }
  7676. static bool encode_endgroup(void *c, const void *hd) {
  7677. return encode_tag(c, hd) && commit(c);
  7678. }
  7679. static void *encode_startstr(void *c, const void *hd, size_t size_hint) {
  7680. UPB_UNUSED(size_hint);
  7681. return encode_startdelimfield(c, hd);
  7682. }
  7683. static size_t encode_strbuf(void *c, const void *hd, const char *buf,
  7684. size_t len, const upb_bufhandle *h) {
  7685. UPB_UNUSED(hd);
  7686. UPB_UNUSED(h);
  7687. return encode_bytes(c, buf, len) ? len : 0;
  7688. }
  7689. #define T(type, ctype, convert, encode) \
  7690. static bool encode_scalar_##type(void *e, const void *hd, ctype val) { \
  7691. return encode_tag(e, hd) && encode(e, (convert)(val)) && commit(e); \
  7692. } \
  7693. static bool encode_packed_##type(void *e, const void *hd, ctype val) { \
  7694. UPB_UNUSED(hd); \
  7695. return encode(e, (convert)(val)); \
  7696. }
  7697. T(double, double, dbl2uint64, encode_fixed64)
  7698. T(float, float, flt2uint32, encode_fixed32);
  7699. T(int64, int64_t, uint64_t, encode_varint);
  7700. T(int32, int32_t, uint32_t, encode_varint);
  7701. T(fixed64, uint64_t, uint64_t, encode_fixed64);
  7702. T(fixed32, uint32_t, uint32_t, encode_fixed32);
  7703. T(bool, bool, bool, encode_varint);
  7704. T(uint32, uint32_t, uint32_t, encode_varint);
  7705. T(uint64, uint64_t, uint64_t, encode_varint);
  7706. T(enum, int32_t, uint32_t, encode_varint);
  7707. T(sfixed32, int32_t, uint32_t, encode_fixed32);
  7708. T(sfixed64, int64_t, uint64_t, encode_fixed64);
  7709. T(sint32, int32_t, upb_zzenc_32, encode_varint);
  7710. T(sint64, int64_t, upb_zzenc_64, encode_varint);
  7711. #undef T
  7712. /* code to build the handlers *************************************************/
  7713. static void newhandlers_callback(const void *closure, upb_handlers *h) {
  7714. UPB_UNUSED(closure);
  7715. upb_handlers_setstartmsg(h, startmsg, NULL);
  7716. upb_handlers_setendmsg(h, endmsg, NULL);
  7717. const upb_msgdef *m = upb_handlers_msgdef(h);
  7718. upb_msg_field_iter i;
  7719. for(upb_msg_field_begin(&i, m);
  7720. !upb_msg_field_done(&i);
  7721. upb_msg_field_next(&i)) {
  7722. const upb_fielddef *f = upb_msg_iter_field(&i);
  7723. bool packed = upb_fielddef_isseq(f) && upb_fielddef_isprimitive(f) &&
  7724. upb_fielddef_packed(f);
  7725. upb_handlerattr attr;
  7726. upb_wiretype_t wt =
  7727. packed ? UPB_WIRE_TYPE_DELIMITED
  7728. : upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  7729. // Pre-encode the tag for this field.
  7730. new_tag(h, f, wt, &attr);
  7731. if (packed) {
  7732. upb_handlers_setstartseq(h, f, encode_startdelimfield, &attr);
  7733. upb_handlers_setendseq(h, f, encode_enddelimfield, &attr);
  7734. }
  7735. #define T(upper, lower, upbtype) \
  7736. case UPB_DESCRIPTOR_TYPE_##upper: \
  7737. if (packed) { \
  7738. upb_handlers_set##upbtype(h, f, encode_packed_##lower, &attr); \
  7739. } else { \
  7740. upb_handlers_set##upbtype(h, f, encode_scalar_##lower, &attr); \
  7741. } \
  7742. break;
  7743. switch (upb_fielddef_descriptortype(f)) {
  7744. T(DOUBLE, double, double);
  7745. T(FLOAT, float, float);
  7746. T(INT64, int64, int64);
  7747. T(INT32, int32, int32);
  7748. T(FIXED64, fixed64, uint64);
  7749. T(FIXED32, fixed32, uint32);
  7750. T(BOOL, bool, bool);
  7751. T(UINT32, uint32, uint32);
  7752. T(UINT64, uint64, uint64);
  7753. T(ENUM, enum, int32);
  7754. T(SFIXED32, sfixed32, int32);
  7755. T(SFIXED64, sfixed64, int64);
  7756. T(SINT32, sint32, int32);
  7757. T(SINT64, sint64, int64);
  7758. case UPB_DESCRIPTOR_TYPE_STRING:
  7759. case UPB_DESCRIPTOR_TYPE_BYTES:
  7760. upb_handlers_setstartstr(h, f, encode_startstr, &attr);
  7761. upb_handlers_setendstr(h, f, encode_enddelimfield, &attr);
  7762. upb_handlers_setstring(h, f, encode_strbuf, &attr);
  7763. break;
  7764. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  7765. upb_handlers_setstartsubmsg(h, f, encode_startdelimfield, &attr);
  7766. upb_handlers_setendsubmsg(h, f, encode_enddelimfield, &attr);
  7767. break;
  7768. case UPB_DESCRIPTOR_TYPE_GROUP: {
  7769. // Endgroup takes a different tag (wire_type = END_GROUP).
  7770. upb_handlerattr attr2;
  7771. new_tag(h, f, UPB_WIRE_TYPE_END_GROUP, &attr2);
  7772. upb_handlers_setstartsubmsg(h, f, encode_startgroup, &attr);
  7773. upb_handlers_setendsubmsg(h, f, encode_endgroup, &attr2);
  7774. upb_handlerattr_uninit(&attr2);
  7775. break;
  7776. }
  7777. }
  7778. #undef T
  7779. upb_handlerattr_uninit(&attr);
  7780. }
  7781. }
  7782. void upb_pb_encoder_reset(upb_pb_encoder *e) {
  7783. e->segptr = NULL;
  7784. e->top = NULL;
  7785. e->depth = 0;
  7786. }
  7787. /* public API *****************************************************************/
  7788. const upb_handlers *upb_pb_encoder_newhandlers(const upb_msgdef *m,
  7789. const void *owner) {
  7790. return upb_handlers_newfrozen(m, owner, newhandlers_callback, NULL);
  7791. }
  7792. upb_pb_encoder *upb_pb_encoder_create(upb_env *env, const upb_handlers *h,
  7793. upb_bytessink *output) {
  7794. const size_t initial_bufsize = 256;
  7795. const size_t initial_segbufsize = 16;
  7796. // TODO(haberman): make this configurable.
  7797. const size_t stack_size = 64;
  7798. #ifndef NDEBUG
  7799. const size_t size_before = upb_env_bytesallocated(env);
  7800. #endif
  7801. upb_pb_encoder *e = upb_env_malloc(env, sizeof(upb_pb_encoder));
  7802. if (!e) return NULL;
  7803. e->buf = upb_env_malloc(env, initial_bufsize);
  7804. e->segbuf = upb_env_malloc(env, initial_segbufsize * sizeof(*e->segbuf));
  7805. e->stack = upb_env_malloc(env, stack_size * sizeof(*e->stack));
  7806. if (!e->buf || !e->segbuf || !e->stack) {
  7807. return NULL;
  7808. }
  7809. e->limit = e->buf + initial_bufsize;
  7810. e->seglimit = e->segbuf + initial_segbufsize;
  7811. e->stacklimit = e->stack + stack_size;
  7812. upb_pb_encoder_reset(e);
  7813. upb_sink_reset(&e->input_, h, e);
  7814. e->env = env;
  7815. e->output_ = output;
  7816. e->subc = output->closure;
  7817. e->ptr = e->buf;
  7818. // If this fails, increase the value in encoder.h.
  7819. assert(upb_env_bytesallocated(env) - size_before <= UPB_PB_ENCODER_SIZE);
  7820. return e;
  7821. }
  7822. upb_sink *upb_pb_encoder_input(upb_pb_encoder *e) { return &e->input_; }
  7823. /*
  7824. * upb - a minimalist implementation of protocol buffers.
  7825. *
  7826. * Copyright (c) 2010-2012 Google Inc. See LICENSE for details.
  7827. * Author: Josh Haberman <jhaberman@gmail.com>
  7828. */
  7829. #include <stdio.h>
  7830. #include <stdlib.h>
  7831. #include <string.h>
  7832. upb_def **upb_load_defs_from_descriptor(const char *str, size_t len, int *n,
  7833. void *owner, upb_status *status) {
  7834. // Create handlers.
  7835. const upb_handlers *reader_h = upb_descreader_newhandlers(&reader_h);
  7836. upb_pbdecodermethodopts opts;
  7837. upb_pbdecodermethodopts_init(&opts, reader_h);
  7838. const upb_pbdecodermethod *decoder_m =
  7839. upb_pbdecodermethod_new(&opts, &decoder_m);
  7840. upb_env env;
  7841. upb_env_init(&env);
  7842. upb_env_reporterrorsto(&env, status);
  7843. upb_descreader *reader = upb_descreader_create(&env, reader_h);
  7844. upb_pbdecoder *decoder =
  7845. upb_pbdecoder_create(&env, decoder_m, upb_descreader_input(reader));
  7846. // Push input data.
  7847. bool ok = upb_bufsrc_putbuf(str, len, upb_pbdecoder_input(decoder));
  7848. upb_def **ret = NULL;
  7849. if (!ok) goto cleanup;
  7850. upb_def **defs = upb_descreader_getdefs(reader, owner, n);
  7851. ret = malloc(sizeof(upb_def*) * (*n));
  7852. memcpy(ret, defs, sizeof(upb_def*) * (*n));
  7853. cleanup:
  7854. upb_env_uninit(&env);
  7855. upb_handlers_unref(reader_h, &reader_h);
  7856. upb_pbdecodermethod_unref(decoder_m, &decoder_m);
  7857. return ret;
  7858. }
  7859. bool upb_load_descriptor_into_symtab(upb_symtab *s, const char *str, size_t len,
  7860. upb_status *status) {
  7861. int n;
  7862. upb_def **defs = upb_load_defs_from_descriptor(str, len, &n, &defs, status);
  7863. if (!defs) return false;
  7864. bool success = upb_symtab_add(s, defs, n, &defs, status);
  7865. free(defs);
  7866. return success;
  7867. }
  7868. char *upb_readfile(const char *filename, size_t *len) {
  7869. FILE *f = fopen(filename, "rb");
  7870. if(!f) return NULL;
  7871. if(fseek(f, 0, SEEK_END) != 0) goto error;
  7872. long size = ftell(f);
  7873. if(size < 0) goto error;
  7874. if(fseek(f, 0, SEEK_SET) != 0) goto error;
  7875. char *buf = malloc(size + 1);
  7876. if(size && fread(buf, size, 1, f) != 1) goto error;
  7877. fclose(f);
  7878. if (len) *len = size;
  7879. return buf;
  7880. error:
  7881. fclose(f);
  7882. return NULL;
  7883. }
  7884. bool upb_load_descriptor_file_into_symtab(upb_symtab *symtab, const char *fname,
  7885. upb_status *status) {
  7886. size_t len;
  7887. char *data = upb_readfile(fname, &len);
  7888. if (!data) {
  7889. if (status) upb_status_seterrf(status, "Couldn't read file: %s", fname);
  7890. return false;
  7891. }
  7892. bool success = upb_load_descriptor_into_symtab(symtab, data, len, status);
  7893. free(data);
  7894. return success;
  7895. }
  7896. /*
  7897. * upb - a minimalist implementation of protocol buffers.
  7898. *
  7899. * Copyright (c) 2009 Google Inc. See LICENSE for details.
  7900. * Author: Josh Haberman <jhaberman@gmail.com>
  7901. *
  7902. * OPT: This is not optimized at all. It uses printf() which parses the format
  7903. * string every time, and it allocates memory for every put.
  7904. */
  7905. #include <ctype.h>
  7906. #include <float.h>
  7907. #include <inttypes.h>
  7908. #include <stdio.h>
  7909. #include <stdlib.h>
  7910. #include <string.h>
  7911. struct upb_textprinter {
  7912. upb_sink input_;
  7913. upb_bytessink *output_;
  7914. int indent_depth_;
  7915. bool single_line_;
  7916. void *subc;
  7917. };
  7918. #define CHECK(x) if ((x) < 0) goto err;
  7919. static const char *shortname(const char *longname) {
  7920. const char *last = strrchr(longname, '.');
  7921. return last ? last + 1 : longname;
  7922. }
  7923. static int indent(upb_textprinter *p) {
  7924. int i;
  7925. if (!p->single_line_)
  7926. for (i = 0; i < p->indent_depth_; i++)
  7927. upb_bytessink_putbuf(p->output_, p->subc, " ", 2, NULL);
  7928. return 0;
  7929. }
  7930. static int endfield(upb_textprinter *p) {
  7931. const char ch = (p->single_line_ ? ' ' : '\n');
  7932. upb_bytessink_putbuf(p->output_, p->subc, &ch, 1, NULL);
  7933. return 0;
  7934. }
  7935. static int putescaped(upb_textprinter *p, const char *buf, size_t len,
  7936. bool preserve_utf8) {
  7937. // Based on CEscapeInternal() from Google's protobuf release.
  7938. char dstbuf[4096], *dst = dstbuf, *dstend = dstbuf + sizeof(dstbuf);
  7939. const char *end = buf + len;
  7940. // I think hex is prettier and more useful, but proto2 uses octal; should
  7941. // investigate whether it can parse hex also.
  7942. const bool use_hex = false;
  7943. bool last_hex_escape = false; // true if last output char was \xNN
  7944. for (; buf < end; buf++) {
  7945. if (dstend - dst < 4) {
  7946. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  7947. dst = dstbuf;
  7948. }
  7949. bool is_hex_escape = false;
  7950. switch (*buf) {
  7951. case '\n': *(dst++) = '\\'; *(dst++) = 'n'; break;
  7952. case '\r': *(dst++) = '\\'; *(dst++) = 'r'; break;
  7953. case '\t': *(dst++) = '\\'; *(dst++) = 't'; break;
  7954. case '\"': *(dst++) = '\\'; *(dst++) = '\"'; break;
  7955. case '\'': *(dst++) = '\\'; *(dst++) = '\''; break;
  7956. case '\\': *(dst++) = '\\'; *(dst++) = '\\'; break;
  7957. default:
  7958. // Note that if we emit \xNN and the buf character after that is a hex
  7959. // digit then that digit must be escaped too to prevent it being
  7960. // interpreted as part of the character code by C.
  7961. if ((!preserve_utf8 || (uint8_t)*buf < 0x80) &&
  7962. (!isprint(*buf) || (last_hex_escape && isxdigit(*buf)))) {
  7963. sprintf(dst, (use_hex ? "\\x%02x" : "\\%03o"), (uint8_t)*buf);
  7964. is_hex_escape = use_hex;
  7965. dst += 4;
  7966. } else {
  7967. *(dst++) = *buf; break;
  7968. }
  7969. }
  7970. last_hex_escape = is_hex_escape;
  7971. }
  7972. // Flush remaining data.
  7973. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  7974. return 0;
  7975. }
  7976. bool putf(upb_textprinter *p, const char *fmt, ...) {
  7977. va_list args;
  7978. va_start(args, fmt);
  7979. // Run once to get the length of the string.
  7980. va_list args_copy;
  7981. va_copy(args_copy, args);
  7982. int len = vsnprintf(NULL, 0, fmt, args_copy);
  7983. va_end(args_copy);
  7984. // + 1 for NULL terminator (vsnprintf() requires it even if we don't).
  7985. char *str = malloc(len + 1);
  7986. if (!str) return false;
  7987. int written = vsnprintf(str, len + 1, fmt, args);
  7988. va_end(args);
  7989. UPB_ASSERT_VAR(written, written == len);
  7990. bool ok = upb_bytessink_putbuf(p->output_, p->subc, str, len, NULL);
  7991. free(str);
  7992. return ok;
  7993. }
  7994. /* handlers *******************************************************************/
  7995. static bool textprinter_startmsg(void *c, const void *hd) {
  7996. UPB_UNUSED(hd);
  7997. upb_textprinter *p = c;
  7998. if (p->indent_depth_ == 0) {
  7999. upb_bytessink_start(p->output_, 0, &p->subc);
  8000. }
  8001. return true;
  8002. }
  8003. static bool textprinter_endmsg(void *c, const void *hd, upb_status *s) {
  8004. UPB_UNUSED(hd);
  8005. UPB_UNUSED(s);
  8006. upb_textprinter *p = c;
  8007. if (p->indent_depth_ == 0) {
  8008. upb_bytessink_end(p->output_);
  8009. }
  8010. return true;
  8011. }
  8012. #define TYPE(name, ctype, fmt) \
  8013. static bool textprinter_put ## name(void *closure, const void *handler_data, \
  8014. ctype val) { \
  8015. upb_textprinter *p = closure; \
  8016. const upb_fielddef *f = handler_data; \
  8017. CHECK(indent(p)); \
  8018. putf(p, "%s: " fmt, upb_fielddef_name(f), val); \
  8019. CHECK(endfield(p)); \
  8020. return true; \
  8021. err: \
  8022. return false; \
  8023. }
  8024. static bool textprinter_putbool(void *closure, const void *handler_data,
  8025. bool val) {
  8026. upb_textprinter *p = closure;
  8027. const upb_fielddef *f = handler_data;
  8028. CHECK(indent(p));
  8029. putf(p, "%s: %s", upb_fielddef_name(f), val ? "true" : "false");
  8030. CHECK(endfield(p));
  8031. return true;
  8032. err:
  8033. return false;
  8034. }
  8035. #define STRINGIFY_HELPER(x) #x
  8036. #define STRINGIFY_MACROVAL(x) STRINGIFY_HELPER(x)
  8037. TYPE(int32, int32_t, "%" PRId32)
  8038. TYPE(int64, int64_t, "%" PRId64)
  8039. TYPE(uint32, uint32_t, "%" PRIu32);
  8040. TYPE(uint64, uint64_t, "%" PRIu64)
  8041. TYPE(float, float, "%." STRINGIFY_MACROVAL(FLT_DIG) "g")
  8042. TYPE(double, double, "%." STRINGIFY_MACROVAL(DBL_DIG) "g")
  8043. #undef TYPE
  8044. // Output a symbolic value from the enum if found, else just print as int32.
  8045. static bool textprinter_putenum(void *closure, const void *handler_data,
  8046. int32_t val) {
  8047. upb_textprinter *p = closure;
  8048. const upb_fielddef *f = handler_data;
  8049. const upb_enumdef *enum_def = upb_downcast_enumdef(upb_fielddef_subdef(f));
  8050. const char *label = upb_enumdef_iton(enum_def, val);
  8051. if (label) {
  8052. indent(p);
  8053. putf(p, "%s: %s", upb_fielddef_name(f), label);
  8054. endfield(p);
  8055. } else {
  8056. if (!textprinter_putint32(closure, handler_data, val))
  8057. return false;
  8058. }
  8059. return true;
  8060. }
  8061. static void *textprinter_startstr(void *closure, const void *handler_data,
  8062. size_t size_hint) {
  8063. const upb_fielddef *f = handler_data;
  8064. UPB_UNUSED(size_hint);
  8065. upb_textprinter *p = closure;
  8066. indent(p);
  8067. putf(p, "%s: \"", upb_fielddef_name(f));
  8068. return p;
  8069. }
  8070. static bool textprinter_endstr(void *closure, const void *handler_data) {
  8071. UPB_UNUSED(handler_data);
  8072. upb_textprinter *p = closure;
  8073. putf(p, "\"");
  8074. endfield(p);
  8075. return true;
  8076. }
  8077. static size_t textprinter_putstr(void *closure, const void *hd, const char *buf,
  8078. size_t len, const upb_bufhandle *handle) {
  8079. UPB_UNUSED(handle);
  8080. upb_textprinter *p = closure;
  8081. const upb_fielddef *f = hd;
  8082. CHECK(putescaped(p, buf, len, upb_fielddef_type(f) == UPB_TYPE_STRING));
  8083. return len;
  8084. err:
  8085. return 0;
  8086. }
  8087. static void *textprinter_startsubmsg(void *closure, const void *handler_data) {
  8088. upb_textprinter *p = closure;
  8089. const char *name = handler_data;
  8090. CHECK(indent(p));
  8091. putf(p, "%s {%c", name, p->single_line_ ? ' ' : '\n');
  8092. p->indent_depth_++;
  8093. return p;
  8094. err:
  8095. return UPB_BREAK;
  8096. }
  8097. static bool textprinter_endsubmsg(void *closure, const void *handler_data) {
  8098. UPB_UNUSED(handler_data);
  8099. upb_textprinter *p = closure;
  8100. p->indent_depth_--;
  8101. CHECK(indent(p));
  8102. upb_bytessink_putbuf(p->output_, p->subc, "}", 1, NULL);
  8103. CHECK(endfield(p));
  8104. return true;
  8105. err:
  8106. return false;
  8107. }
  8108. static void onmreg(const void *c, upb_handlers *h) {
  8109. UPB_UNUSED(c);
  8110. const upb_msgdef *m = upb_handlers_msgdef(h);
  8111. upb_handlers_setstartmsg(h, textprinter_startmsg, NULL);
  8112. upb_handlers_setendmsg(h, textprinter_endmsg, NULL);
  8113. upb_msg_field_iter i;
  8114. for(upb_msg_field_begin(&i, m);
  8115. !upb_msg_field_done(&i);
  8116. upb_msg_field_next(&i)) {
  8117. upb_fielddef *f = upb_msg_iter_field(&i);
  8118. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  8119. upb_handlerattr_sethandlerdata(&attr, f);
  8120. switch (upb_fielddef_type(f)) {
  8121. case UPB_TYPE_INT32:
  8122. upb_handlers_setint32(h, f, textprinter_putint32, &attr);
  8123. break;
  8124. case UPB_TYPE_INT64:
  8125. upb_handlers_setint64(h, f, textprinter_putint64, &attr);
  8126. break;
  8127. case UPB_TYPE_UINT32:
  8128. upb_handlers_setuint32(h, f, textprinter_putuint32, &attr);
  8129. break;
  8130. case UPB_TYPE_UINT64:
  8131. upb_handlers_setuint64(h, f, textprinter_putuint64, &attr);
  8132. break;
  8133. case UPB_TYPE_FLOAT:
  8134. upb_handlers_setfloat(h, f, textprinter_putfloat, &attr);
  8135. break;
  8136. case UPB_TYPE_DOUBLE:
  8137. upb_handlers_setdouble(h, f, textprinter_putdouble, &attr);
  8138. break;
  8139. case UPB_TYPE_BOOL:
  8140. upb_handlers_setbool(h, f, textprinter_putbool, &attr);
  8141. break;
  8142. case UPB_TYPE_STRING:
  8143. case UPB_TYPE_BYTES:
  8144. upb_handlers_setstartstr(h, f, textprinter_startstr, &attr);
  8145. upb_handlers_setstring(h, f, textprinter_putstr, &attr);
  8146. upb_handlers_setendstr(h, f, textprinter_endstr, &attr);
  8147. break;
  8148. case UPB_TYPE_MESSAGE: {
  8149. const char *name =
  8150. upb_fielddef_istagdelim(f)
  8151. ? shortname(upb_msgdef_fullname(upb_fielddef_msgsubdef(f)))
  8152. : upb_fielddef_name(f);
  8153. upb_handlerattr_sethandlerdata(&attr, name);
  8154. upb_handlers_setstartsubmsg(h, f, textprinter_startsubmsg, &attr);
  8155. upb_handlers_setendsubmsg(h, f, textprinter_endsubmsg, &attr);
  8156. break;
  8157. }
  8158. case UPB_TYPE_ENUM:
  8159. upb_handlers_setint32(h, f, textprinter_putenum, &attr);
  8160. break;
  8161. }
  8162. }
  8163. }
  8164. static void textprinter_reset(upb_textprinter *p, bool single_line) {
  8165. p->single_line_ = single_line;
  8166. p->indent_depth_ = 0;
  8167. }
  8168. /* Public API *****************************************************************/
  8169. upb_textprinter *upb_textprinter_create(upb_env *env, const upb_handlers *h,
  8170. upb_bytessink *output) {
  8171. upb_textprinter *p = upb_env_malloc(env, sizeof(upb_textprinter));
  8172. if (!p) return NULL;
  8173. p->output_ = output;
  8174. upb_sink_reset(&p->input_, h, p);
  8175. textprinter_reset(p, false);
  8176. return p;
  8177. }
  8178. const upb_handlers *upb_textprinter_newhandlers(const upb_msgdef *m,
  8179. const void *owner) {
  8180. return upb_handlers_newfrozen(m, owner, &onmreg, NULL);
  8181. }
  8182. upb_sink *upb_textprinter_input(upb_textprinter *p) { return &p->input_; }
  8183. void upb_textprinter_setsingleline(upb_textprinter *p, bool single_line) {
  8184. p->single_line_ = single_line;
  8185. }
  8186. /*
  8187. * upb - a minimalist implementation of protocol buffers.
  8188. *
  8189. * Copyright (c) 2011 Google Inc. See LICENSE for details.
  8190. * Author: Josh Haberman <jhaberman@gmail.com>
  8191. */
  8192. // Index is descriptor type.
  8193. const uint8_t upb_pb_native_wire_types[] = {
  8194. UPB_WIRE_TYPE_END_GROUP, // ENDGROUP
  8195. UPB_WIRE_TYPE_64BIT, // DOUBLE
  8196. UPB_WIRE_TYPE_32BIT, // FLOAT
  8197. UPB_WIRE_TYPE_VARINT, // INT64
  8198. UPB_WIRE_TYPE_VARINT, // UINT64
  8199. UPB_WIRE_TYPE_VARINT, // INT32
  8200. UPB_WIRE_TYPE_64BIT, // FIXED64
  8201. UPB_WIRE_TYPE_32BIT, // FIXED32
  8202. UPB_WIRE_TYPE_VARINT, // BOOL
  8203. UPB_WIRE_TYPE_DELIMITED, // STRING
  8204. UPB_WIRE_TYPE_START_GROUP, // GROUP
  8205. UPB_WIRE_TYPE_DELIMITED, // MESSAGE
  8206. UPB_WIRE_TYPE_DELIMITED, // BYTES
  8207. UPB_WIRE_TYPE_VARINT, // UINT32
  8208. UPB_WIRE_TYPE_VARINT, // ENUM
  8209. UPB_WIRE_TYPE_32BIT, // SFIXED32
  8210. UPB_WIRE_TYPE_64BIT, // SFIXED64
  8211. UPB_WIRE_TYPE_VARINT, // SINT32
  8212. UPB_WIRE_TYPE_VARINT, // SINT64
  8213. };
  8214. // A basic branch-based decoder, uses 32-bit values to get good performance
  8215. // on 32-bit architectures (but performs well on 64-bits also).
  8216. // This scheme comes from the original Google Protobuf implementation (proto2).
  8217. upb_decoderet upb_vdecode_max8_branch32(upb_decoderet r) {
  8218. upb_decoderet err = {NULL, 0};
  8219. const char *p = r.p;
  8220. uint32_t low = (uint32_t)r.val;
  8221. uint32_t high = 0;
  8222. uint32_t b;
  8223. b = *(p++); low |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  8224. b = *(p++); low |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  8225. b = *(p++); low |= (b & 0x7fU) << 28;
  8226. high = (b & 0x7fU) >> 4; if (!(b & 0x80)) goto done;
  8227. b = *(p++); high |= (b & 0x7fU) << 3; if (!(b & 0x80)) goto done;
  8228. b = *(p++); high |= (b & 0x7fU) << 10; if (!(b & 0x80)) goto done;
  8229. b = *(p++); high |= (b & 0x7fU) << 17; if (!(b & 0x80)) goto done;
  8230. b = *(p++); high |= (b & 0x7fU) << 24; if (!(b & 0x80)) goto done;
  8231. b = *(p++); high |= (b & 0x7fU) << 31; if (!(b & 0x80)) goto done;
  8232. return err;
  8233. done:
  8234. r.val = ((uint64_t)high << 32) | low;
  8235. r.p = p;
  8236. return r;
  8237. }
  8238. // Like the previous, but uses 64-bit values.
  8239. upb_decoderet upb_vdecode_max8_branch64(upb_decoderet r) {
  8240. const char *p = r.p;
  8241. uint64_t val = r.val;
  8242. uint64_t b;
  8243. upb_decoderet err = {NULL, 0};
  8244. b = *(p++); val |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  8245. b = *(p++); val |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  8246. b = *(p++); val |= (b & 0x7fU) << 28; if (!(b & 0x80)) goto done;
  8247. b = *(p++); val |= (b & 0x7fU) << 35; if (!(b & 0x80)) goto done;
  8248. b = *(p++); val |= (b & 0x7fU) << 42; if (!(b & 0x80)) goto done;
  8249. b = *(p++); val |= (b & 0x7fU) << 49; if (!(b & 0x80)) goto done;
  8250. b = *(p++); val |= (b & 0x7fU) << 56; if (!(b & 0x80)) goto done;
  8251. b = *(p++); val |= (b & 0x7fU) << 63; if (!(b & 0x80)) goto done;
  8252. return err;
  8253. done:
  8254. r.val = val;
  8255. r.p = p;
  8256. return r;
  8257. }
  8258. // Given an encoded varint v, returns an integer with a single bit set that
  8259. // indicates the end of the varint. Subtracting one from this value will
  8260. // yield a mask that leaves only bits that are part of the varint. Returns
  8261. // 0 if the varint is unterminated.
  8262. static uint64_t upb_get_vstopbit(uint64_t v) {
  8263. uint64_t cbits = v | 0x7f7f7f7f7f7f7f7fULL;
  8264. return ~cbits & (cbits+1);
  8265. }
  8266. // A branchless decoder. Credit to Pascal Massimino for the bit-twiddling.
  8267. upb_decoderet upb_vdecode_max8_massimino(upb_decoderet r) {
  8268. uint64_t b;
  8269. memcpy(&b, r.p, sizeof(b));
  8270. uint64_t stop_bit = upb_get_vstopbit(b);
  8271. b = (b & 0x7f7f7f7f7f7f7f7fULL) & (stop_bit - 1);
  8272. b += b & 0x007f007f007f007fULL;
  8273. b += 3 * (b & 0x0000ffff0000ffffULL);
  8274. b += 15 * (b & 0x00000000ffffffffULL);
  8275. if (stop_bit == 0) {
  8276. // Error: unterminated varint.
  8277. upb_decoderet err_r = {(void*)0, 0};
  8278. return err_r;
  8279. }
  8280. upb_decoderet my_r = {r.p + ((__builtin_ctzll(stop_bit) + 1) / 8),
  8281. r.val | (b << 7)};
  8282. return my_r;
  8283. }
  8284. // A branchless decoder. Credit to Daniel Wright for the bit-twiddling.
  8285. upb_decoderet upb_vdecode_max8_wright(upb_decoderet r) {
  8286. uint64_t b;
  8287. memcpy(&b, r.p, sizeof(b));
  8288. uint64_t stop_bit = upb_get_vstopbit(b);
  8289. b &= (stop_bit - 1);
  8290. b = ((b & 0x7f007f007f007f00ULL) >> 1) | (b & 0x007f007f007f007fULL);
  8291. b = ((b & 0xffff0000ffff0000ULL) >> 2) | (b & 0x0000ffff0000ffffULL);
  8292. b = ((b & 0xffffffff00000000ULL) >> 4) | (b & 0x00000000ffffffffULL);
  8293. if (stop_bit == 0) {
  8294. // Error: unterminated varint.
  8295. upb_decoderet err_r = {(void*)0, 0};
  8296. return err_r;
  8297. }
  8298. upb_decoderet my_r = {r.p + ((__builtin_ctzll(stop_bit) + 1) / 8),
  8299. r.val | (b << 14)};
  8300. return my_r;
  8301. }
  8302. #line 1 "upb/json/parser.rl"
  8303. /*
  8304. * upb - a minimalist implementation of protocol buffers.
  8305. *
  8306. * Copyright (c) 2014 Google Inc. See LICENSE for details.
  8307. * Author: Josh Haberman <jhaberman@gmail.com>
  8308. *
  8309. * A parser that uses the Ragel State Machine Compiler to generate
  8310. * the finite automata.
  8311. *
  8312. * Ragel only natively handles regular languages, but we can manually
  8313. * program it a bit to handle context-free languages like JSON, by using
  8314. * the "fcall" and "fret" constructs.
  8315. *
  8316. * This parser can handle the basics, but needs several things to be fleshed
  8317. * out:
  8318. *
  8319. * - handling of unicode escape sequences (including high surrogate pairs).
  8320. * - properly check and report errors for unknown fields, stack overflow,
  8321. * improper array nesting (or lack of nesting).
  8322. * - handling of base64 sequences with padding characters.
  8323. * - handling of push-back (non-success returns from sink functions).
  8324. * - handling of keys/escape-sequences/etc that span input buffers.
  8325. */
  8326. #include <stdio.h>
  8327. #include <stdint.h>
  8328. #include <assert.h>
  8329. #include <string.h>
  8330. #include <stdlib.h>
  8331. #include <errno.h>
  8332. #define UPB_JSON_MAX_DEPTH 64
  8333. typedef struct {
  8334. upb_sink sink;
  8335. // The current message in which we're parsing, and the field whose value we're
  8336. // expecting next.
  8337. const upb_msgdef *m;
  8338. const upb_fielddef *f;
  8339. // We are in a repeated-field context, ready to emit mapentries as
  8340. // submessages. This flag alters the start-of-object (open-brace) behavior to
  8341. // begin a sequence of mapentry messages rather than a single submessage.
  8342. bool is_map;
  8343. // We are in a map-entry message context. This flag is set when parsing the
  8344. // value field of a single map entry and indicates to all value-field parsers
  8345. // (subobjects, strings, numbers, and bools) that the map-entry submessage
  8346. // should end as soon as the value is parsed.
  8347. bool is_mapentry;
  8348. // If |is_map| or |is_mapentry| is true, |mapfield| refers to the parent
  8349. // message's map field that we're currently parsing. This differs from |f|
  8350. // because |f| is the field in the *current* message (i.e., the map-entry
  8351. // message itself), not the parent's field that leads to this map.
  8352. const upb_fielddef *mapfield;
  8353. } upb_jsonparser_frame;
  8354. struct upb_json_parser {
  8355. upb_env *env;
  8356. upb_byteshandler input_handler_;
  8357. upb_bytessink input_;
  8358. // Stack to track the JSON scopes we are in.
  8359. upb_jsonparser_frame stack[UPB_JSON_MAX_DEPTH];
  8360. upb_jsonparser_frame *top;
  8361. upb_jsonparser_frame *limit;
  8362. upb_status *status;
  8363. // Ragel's internal parsing stack for the parsing state machine.
  8364. int current_state;
  8365. int parser_stack[UPB_JSON_MAX_DEPTH];
  8366. int parser_top;
  8367. // The handle for the current buffer.
  8368. const upb_bufhandle *handle;
  8369. // Accumulate buffer. See details in parser.rl.
  8370. const char *accumulated;
  8371. size_t accumulated_len;
  8372. char *accumulate_buf;
  8373. size_t accumulate_buf_size;
  8374. // Multi-part text data. See details in parser.rl.
  8375. int multipart_state;
  8376. upb_selector_t string_selector;
  8377. // Input capture. See details in parser.rl.
  8378. const char *capture;
  8379. // Intermediate result of parsing a unicode escape sequence.
  8380. uint32_t digit;
  8381. };
  8382. #define PARSER_CHECK_RETURN(x) if (!(x)) return false
  8383. // Used to signal that a capture has been suspended.
  8384. static char suspend_capture;
  8385. static upb_selector_t getsel_for_handlertype(upb_json_parser *p,
  8386. upb_handlertype_t type) {
  8387. upb_selector_t sel;
  8388. bool ok = upb_handlers_getselector(p->top->f, type, &sel);
  8389. UPB_ASSERT_VAR(ok, ok);
  8390. return sel;
  8391. }
  8392. static upb_selector_t parser_getsel(upb_json_parser *p) {
  8393. return getsel_for_handlertype(
  8394. p, upb_handlers_getprimitivehandlertype(p->top->f));
  8395. }
  8396. static bool check_stack(upb_json_parser *p) {
  8397. if ((p->top + 1) == p->limit) {
  8398. upb_status_seterrmsg(p->status, "Nesting too deep");
  8399. return false;
  8400. }
  8401. return true;
  8402. }
  8403. // There are GCC/Clang built-ins for overflow checking which we could start
  8404. // using if there was any performance benefit to it.
  8405. static bool checked_add(size_t a, size_t b, size_t *c) {
  8406. if (SIZE_MAX - a < b) return false;
  8407. *c = a + b;
  8408. return true;
  8409. }
  8410. static size_t saturating_multiply(size_t a, size_t b) {
  8411. // size_t is unsigned, so this is defined behavior even on overflow.
  8412. size_t ret = a * b;
  8413. if (b != 0 && ret / b != a) {
  8414. ret = SIZE_MAX;
  8415. }
  8416. return ret;
  8417. }
  8418. /* Base64 decoding ************************************************************/
  8419. // TODO(haberman): make this streaming.
  8420. static const signed char b64table[] = {
  8421. -1, -1, -1, -1, -1, -1, -1, -1,
  8422. -1, -1, -1, -1, -1, -1, -1, -1,
  8423. -1, -1, -1, -1, -1, -1, -1, -1,
  8424. -1, -1, -1, -1, -1, -1, -1, -1,
  8425. -1, -1, -1, -1, -1, -1, -1, -1,
  8426. -1, -1, -1, 62/*+*/, -1, -1, -1, 63/*/ */,
  8427. 52/*0*/, 53/*1*/, 54/*2*/, 55/*3*/, 56/*4*/, 57/*5*/, 58/*6*/, 59/*7*/,
  8428. 60/*8*/, 61/*9*/, -1, -1, -1, -1, -1, -1,
  8429. -1, 0/*A*/, 1/*B*/, 2/*C*/, 3/*D*/, 4/*E*/, 5/*F*/, 6/*G*/,
  8430. 07/*H*/, 8/*I*/, 9/*J*/, 10/*K*/, 11/*L*/, 12/*M*/, 13/*N*/, 14/*O*/,
  8431. 15/*P*/, 16/*Q*/, 17/*R*/, 18/*S*/, 19/*T*/, 20/*U*/, 21/*V*/, 22/*W*/,
  8432. 23/*X*/, 24/*Y*/, 25/*Z*/, -1, -1, -1, -1, -1,
  8433. -1, 26/*a*/, 27/*b*/, 28/*c*/, 29/*d*/, 30/*e*/, 31/*f*/, 32/*g*/,
  8434. 33/*h*/, 34/*i*/, 35/*j*/, 36/*k*/, 37/*l*/, 38/*m*/, 39/*n*/, 40/*o*/,
  8435. 41/*p*/, 42/*q*/, 43/*r*/, 44/*s*/, 45/*t*/, 46/*u*/, 47/*v*/, 48/*w*/,
  8436. 49/*x*/, 50/*y*/, 51/*z*/, -1, -1, -1, -1, -1,
  8437. -1, -1, -1, -1, -1, -1, -1, -1,
  8438. -1, -1, -1, -1, -1, -1, -1, -1,
  8439. -1, -1, -1, -1, -1, -1, -1, -1,
  8440. -1, -1, -1, -1, -1, -1, -1, -1,
  8441. -1, -1, -1, -1, -1, -1, -1, -1,
  8442. -1, -1, -1, -1, -1, -1, -1, -1,
  8443. -1, -1, -1, -1, -1, -1, -1, -1,
  8444. -1, -1, -1, -1, -1, -1, -1, -1,
  8445. -1, -1, -1, -1, -1, -1, -1, -1,
  8446. -1, -1, -1, -1, -1, -1, -1, -1,
  8447. -1, -1, -1, -1, -1, -1, -1, -1,
  8448. -1, -1, -1, -1, -1, -1, -1, -1,
  8449. -1, -1, -1, -1, -1, -1, -1, -1,
  8450. -1, -1, -1, -1, -1, -1, -1, -1,
  8451. -1, -1, -1, -1, -1, -1, -1, -1,
  8452. -1, -1, -1, -1, -1, -1, -1, -1
  8453. };
  8454. // Returns the table value sign-extended to 32 bits. Knowing that the upper
  8455. // bits will be 1 for unrecognized characters makes it easier to check for
  8456. // this error condition later (see below).
  8457. int32_t b64lookup(unsigned char ch) { return b64table[ch]; }
  8458. // Returns true if the given character is not a valid base64 character or
  8459. // padding.
  8460. bool nonbase64(unsigned char ch) { return b64lookup(ch) == -1 && ch != '='; }
  8461. static bool base64_push(upb_json_parser *p, upb_selector_t sel, const char *ptr,
  8462. size_t len) {
  8463. const char *limit = ptr + len;
  8464. for (; ptr < limit; ptr += 4) {
  8465. if (limit - ptr < 4) {
  8466. upb_status_seterrf(p->status,
  8467. "Base64 input for bytes field not a multiple of 4: %s",
  8468. upb_fielddef_name(p->top->f));
  8469. return false;
  8470. }
  8471. uint32_t val = b64lookup(ptr[0]) << 18 |
  8472. b64lookup(ptr[1]) << 12 |
  8473. b64lookup(ptr[2]) << 6 |
  8474. b64lookup(ptr[3]);
  8475. // Test the upper bit; returns true if any of the characters returned -1.
  8476. if (val & 0x80000000) {
  8477. goto otherchar;
  8478. }
  8479. char output[3];
  8480. output[0] = val >> 16;
  8481. output[1] = (val >> 8) & 0xff;
  8482. output[2] = val & 0xff;
  8483. upb_sink_putstring(&p->top->sink, sel, output, 3, NULL);
  8484. }
  8485. return true;
  8486. otherchar:
  8487. if (nonbase64(ptr[0]) || nonbase64(ptr[1]) || nonbase64(ptr[2]) ||
  8488. nonbase64(ptr[3]) ) {
  8489. upb_status_seterrf(p->status,
  8490. "Non-base64 characters in bytes field: %s",
  8491. upb_fielddef_name(p->top->f));
  8492. return false;
  8493. } if (ptr[2] == '=') {
  8494. // Last group contains only two input bytes, one output byte.
  8495. if (ptr[0] == '=' || ptr[1] == '=' || ptr[3] != '=') {
  8496. goto badpadding;
  8497. }
  8498. uint32_t val = b64lookup(ptr[0]) << 18 |
  8499. b64lookup(ptr[1]) << 12;
  8500. assert(!(val & 0x80000000));
  8501. char output = val >> 16;
  8502. upb_sink_putstring(&p->top->sink, sel, &output, 1, NULL);
  8503. return true;
  8504. } else {
  8505. // Last group contains only three input bytes, two output bytes.
  8506. if (ptr[0] == '=' || ptr[1] == '=' || ptr[2] == '=') {
  8507. goto badpadding;
  8508. }
  8509. uint32_t val = b64lookup(ptr[0]) << 18 |
  8510. b64lookup(ptr[1]) << 12 |
  8511. b64lookup(ptr[2]) << 6;
  8512. char output[2];
  8513. output[0] = val >> 16;
  8514. output[1] = (val >> 8) & 0xff;
  8515. upb_sink_putstring(&p->top->sink, sel, output, 2, NULL);
  8516. return true;
  8517. }
  8518. badpadding:
  8519. upb_status_seterrf(p->status,
  8520. "Incorrect base64 padding for field: %s (%.*s)",
  8521. upb_fielddef_name(p->top->f),
  8522. 4, ptr);
  8523. return false;
  8524. }
  8525. /* Accumulate buffer **********************************************************/
  8526. // Functionality for accumulating a buffer.
  8527. //
  8528. // Some parts of the parser need an entire value as a contiguous string. For
  8529. // example, to look up a member name in a hash table, or to turn a string into
  8530. // a number, the relevant library routines need the input string to be in
  8531. // contiguous memory, even if the value spanned two or more buffers in the
  8532. // input. These routines handle that.
  8533. //
  8534. // In the common case we can just point to the input buffer to get this
  8535. // contiguous string and avoid any actual copy. So we optimistically begin
  8536. // this way. But there are a few cases where we must instead copy into a
  8537. // separate buffer:
  8538. //
  8539. // 1. The string was not contiguous in the input (it spanned buffers).
  8540. //
  8541. // 2. The string included escape sequences that need to be interpreted to get
  8542. // the true value in a contiguous buffer.
  8543. static void assert_accumulate_empty(upb_json_parser *p) {
  8544. UPB_UNUSED(p);
  8545. assert(p->accumulated == NULL);
  8546. assert(p->accumulated_len == 0);
  8547. }
  8548. static void accumulate_clear(upb_json_parser *p) {
  8549. p->accumulated = NULL;
  8550. p->accumulated_len = 0;
  8551. }
  8552. // Used internally by accumulate_append().
  8553. static bool accumulate_realloc(upb_json_parser *p, size_t need) {
  8554. size_t old_size = p->accumulate_buf_size;
  8555. size_t new_size = UPB_MAX(old_size, 128);
  8556. while (new_size < need) {
  8557. new_size = saturating_multiply(new_size, 2);
  8558. }
  8559. void *mem = upb_env_realloc(p->env, p->accumulate_buf, old_size, new_size);
  8560. if (!mem) {
  8561. upb_status_seterrmsg(p->status, "Out of memory allocating buffer.");
  8562. return false;
  8563. }
  8564. p->accumulate_buf = mem;
  8565. p->accumulate_buf_size = new_size;
  8566. return true;
  8567. }
  8568. // Logically appends the given data to the append buffer.
  8569. // If "can_alias" is true, we will try to avoid actually copying, but the buffer
  8570. // must be valid until the next accumulate_append() call (if any).
  8571. static bool accumulate_append(upb_json_parser *p, const char *buf, size_t len,
  8572. bool can_alias) {
  8573. if (!p->accumulated && can_alias) {
  8574. p->accumulated = buf;
  8575. p->accumulated_len = len;
  8576. return true;
  8577. }
  8578. size_t need;
  8579. if (!checked_add(p->accumulated_len, len, &need)) {
  8580. upb_status_seterrmsg(p->status, "Integer overflow.");
  8581. return false;
  8582. }
  8583. if (need > p->accumulate_buf_size && !accumulate_realloc(p, need)) {
  8584. return false;
  8585. }
  8586. if (p->accumulated != p->accumulate_buf) {
  8587. memcpy(p->accumulate_buf, p->accumulated, p->accumulated_len);
  8588. p->accumulated = p->accumulate_buf;
  8589. }
  8590. memcpy(p->accumulate_buf + p->accumulated_len, buf, len);
  8591. p->accumulated_len += len;
  8592. return true;
  8593. }
  8594. // Returns a pointer to the data accumulated since the last accumulate_clear()
  8595. // call, and writes the length to *len. This with point either to the input
  8596. // buffer or a temporary accumulate buffer.
  8597. static const char *accumulate_getptr(upb_json_parser *p, size_t *len) {
  8598. assert(p->accumulated);
  8599. *len = p->accumulated_len;
  8600. return p->accumulated;
  8601. }
  8602. /* Mult-part text data ********************************************************/
  8603. // When we have text data in the input, it can often come in multiple segments.
  8604. // For example, there may be some raw string data followed by an escape
  8605. // sequence. The two segments are processed with different logic. Also buffer
  8606. // seams in the input can cause multiple segments.
  8607. //
  8608. // As we see segments, there are two main cases for how we want to process them:
  8609. //
  8610. // 1. we want to push the captured input directly to string handlers.
  8611. //
  8612. // 2. we need to accumulate all the parts into a contiguous buffer for further
  8613. // processing (field name lookup, string->number conversion, etc).
  8614. // This is the set of states for p->multipart_state.
  8615. enum {
  8616. // We are not currently processing multipart data.
  8617. MULTIPART_INACTIVE = 0,
  8618. // We are processing multipart data by accumulating it into a contiguous
  8619. // buffer.
  8620. MULTIPART_ACCUMULATE = 1,
  8621. // We are processing multipart data by pushing each part directly to the
  8622. // current string handlers.
  8623. MULTIPART_PUSHEAGERLY = 2
  8624. };
  8625. // Start a multi-part text value where we accumulate the data for processing at
  8626. // the end.
  8627. static void multipart_startaccum(upb_json_parser *p) {
  8628. assert_accumulate_empty(p);
  8629. assert(p->multipart_state == MULTIPART_INACTIVE);
  8630. p->multipart_state = MULTIPART_ACCUMULATE;
  8631. }
  8632. // Start a multi-part text value where we immediately push text data to a string
  8633. // value with the given selector.
  8634. static void multipart_start(upb_json_parser *p, upb_selector_t sel) {
  8635. assert_accumulate_empty(p);
  8636. assert(p->multipart_state == MULTIPART_INACTIVE);
  8637. p->multipart_state = MULTIPART_PUSHEAGERLY;
  8638. p->string_selector = sel;
  8639. }
  8640. static bool multipart_text(upb_json_parser *p, const char *buf, size_t len,
  8641. bool can_alias) {
  8642. switch (p->multipart_state) {
  8643. case MULTIPART_INACTIVE:
  8644. upb_status_seterrmsg(
  8645. p->status, "Internal error: unexpected state MULTIPART_INACTIVE");
  8646. return false;
  8647. case MULTIPART_ACCUMULATE:
  8648. if (!accumulate_append(p, buf, len, can_alias)) {
  8649. return false;
  8650. }
  8651. break;
  8652. case MULTIPART_PUSHEAGERLY: {
  8653. const upb_bufhandle *handle = can_alias ? p->handle : NULL;
  8654. upb_sink_putstring(&p->top->sink, p->string_selector, buf, len, handle);
  8655. break;
  8656. }
  8657. }
  8658. return true;
  8659. }
  8660. // Note: this invalidates the accumulate buffer! Call only after reading its
  8661. // contents.
  8662. static void multipart_end(upb_json_parser *p) {
  8663. assert(p->multipart_state != MULTIPART_INACTIVE);
  8664. p->multipart_state = MULTIPART_INACTIVE;
  8665. accumulate_clear(p);
  8666. }
  8667. /* Input capture **************************************************************/
  8668. // Functionality for capturing a region of the input as text. Gracefully
  8669. // handles the case where a buffer seam occurs in the middle of the captured
  8670. // region.
  8671. static void capture_begin(upb_json_parser *p, const char *ptr) {
  8672. assert(p->multipart_state != MULTIPART_INACTIVE);
  8673. assert(p->capture == NULL);
  8674. p->capture = ptr;
  8675. }
  8676. static bool capture_end(upb_json_parser *p, const char *ptr) {
  8677. assert(p->capture);
  8678. if (multipart_text(p, p->capture, ptr - p->capture, true)) {
  8679. p->capture = NULL;
  8680. return true;
  8681. } else {
  8682. return false;
  8683. }
  8684. }
  8685. // This is called at the end of each input buffer (ie. when we have hit a
  8686. // buffer seam). If we are in the middle of capturing the input, this
  8687. // processes the unprocessed capture region.
  8688. static void capture_suspend(upb_json_parser *p, const char **ptr) {
  8689. if (!p->capture) return;
  8690. if (multipart_text(p, p->capture, *ptr - p->capture, false)) {
  8691. // We use this as a signal that we were in the middle of capturing, and
  8692. // that capturing should resume at the beginning of the next buffer.
  8693. //
  8694. // We can't use *ptr here, because we have no guarantee that this pointer
  8695. // will be valid when we resume (if the underlying memory is freed, then
  8696. // using the pointer at all, even to compare to NULL, is likely undefined
  8697. // behavior).
  8698. p->capture = &suspend_capture;
  8699. } else {
  8700. // Need to back up the pointer to the beginning of the capture, since
  8701. // we were not able to actually preserve it.
  8702. *ptr = p->capture;
  8703. }
  8704. }
  8705. static void capture_resume(upb_json_parser *p, const char *ptr) {
  8706. if (p->capture) {
  8707. assert(p->capture == &suspend_capture);
  8708. p->capture = ptr;
  8709. }
  8710. }
  8711. /* Callbacks from the parser **************************************************/
  8712. // These are the functions called directly from the parser itself.
  8713. // We define these in the same order as their declarations in the parser.
  8714. static char escape_char(char in) {
  8715. switch (in) {
  8716. case 'r': return '\r';
  8717. case 't': return '\t';
  8718. case 'n': return '\n';
  8719. case 'f': return '\f';
  8720. case 'b': return '\b';
  8721. case '/': return '/';
  8722. case '"': return '"';
  8723. case '\\': return '\\';
  8724. default:
  8725. assert(0);
  8726. return 'x';
  8727. }
  8728. }
  8729. static bool escape(upb_json_parser *p, const char *ptr) {
  8730. char ch = escape_char(*ptr);
  8731. return multipart_text(p, &ch, 1, false);
  8732. }
  8733. static void start_hex(upb_json_parser *p) {
  8734. p->digit = 0;
  8735. }
  8736. static void hexdigit(upb_json_parser *p, const char *ptr) {
  8737. char ch = *ptr;
  8738. p->digit <<= 4;
  8739. if (ch >= '0' && ch <= '9') {
  8740. p->digit += (ch - '0');
  8741. } else if (ch >= 'a' && ch <= 'f') {
  8742. p->digit += ((ch - 'a') + 10);
  8743. } else {
  8744. assert(ch >= 'A' && ch <= 'F');
  8745. p->digit += ((ch - 'A') + 10);
  8746. }
  8747. }
  8748. static bool end_hex(upb_json_parser *p) {
  8749. uint32_t codepoint = p->digit;
  8750. // emit the codepoint as UTF-8.
  8751. char utf8[3]; // support \u0000 -- \uFFFF -- need only three bytes.
  8752. int length = 0;
  8753. if (codepoint <= 0x7F) {
  8754. utf8[0] = codepoint;
  8755. length = 1;
  8756. } else if (codepoint <= 0x07FF) {
  8757. utf8[1] = (codepoint & 0x3F) | 0x80;
  8758. codepoint >>= 6;
  8759. utf8[0] = (codepoint & 0x1F) | 0xC0;
  8760. length = 2;
  8761. } else /* codepoint <= 0xFFFF */ {
  8762. utf8[2] = (codepoint & 0x3F) | 0x80;
  8763. codepoint >>= 6;
  8764. utf8[1] = (codepoint & 0x3F) | 0x80;
  8765. codepoint >>= 6;
  8766. utf8[0] = (codepoint & 0x0F) | 0xE0;
  8767. length = 3;
  8768. }
  8769. // TODO(haberman): Handle high surrogates: if codepoint is a high surrogate
  8770. // we have to wait for the next escape to get the full code point).
  8771. return multipart_text(p, utf8, length, false);
  8772. }
  8773. static void start_text(upb_json_parser *p, const char *ptr) {
  8774. capture_begin(p, ptr);
  8775. }
  8776. static bool end_text(upb_json_parser *p, const char *ptr) {
  8777. return capture_end(p, ptr);
  8778. }
  8779. static void start_number(upb_json_parser *p, const char *ptr) {
  8780. multipart_startaccum(p);
  8781. capture_begin(p, ptr);
  8782. }
  8783. static bool parse_number(upb_json_parser *p);
  8784. static bool end_number(upb_json_parser *p, const char *ptr) {
  8785. if (!capture_end(p, ptr)) {
  8786. return false;
  8787. }
  8788. return parse_number(p);
  8789. }
  8790. static bool parse_number(upb_json_parser *p) {
  8791. // strtol() and friends unfortunately do not support specifying the length of
  8792. // the input string, so we need to force a copy into a NULL-terminated buffer.
  8793. if (!multipart_text(p, "\0", 1, false)) {
  8794. return false;
  8795. }
  8796. size_t len;
  8797. const char *buf = accumulate_getptr(p, &len);
  8798. const char *myend = buf + len - 1; // One for NULL.
  8799. char *end;
  8800. switch (upb_fielddef_type(p->top->f)) {
  8801. case UPB_TYPE_ENUM:
  8802. case UPB_TYPE_INT32: {
  8803. long val = strtol(p->accumulated, &end, 0);
  8804. if (val > INT32_MAX || val < INT32_MIN || errno == ERANGE || end != myend)
  8805. goto err;
  8806. else
  8807. upb_sink_putint32(&p->top->sink, parser_getsel(p), val);
  8808. break;
  8809. }
  8810. case UPB_TYPE_INT64: {
  8811. long long val = strtoll(p->accumulated, &end, 0);
  8812. if (val > INT64_MAX || val < INT64_MIN || errno == ERANGE || end != myend)
  8813. goto err;
  8814. else
  8815. upb_sink_putint64(&p->top->sink, parser_getsel(p), val);
  8816. break;
  8817. }
  8818. case UPB_TYPE_UINT32: {
  8819. unsigned long val = strtoul(p->accumulated, &end, 0);
  8820. if (val > UINT32_MAX || errno == ERANGE || end != myend)
  8821. goto err;
  8822. else
  8823. upb_sink_putuint32(&p->top->sink, parser_getsel(p), val);
  8824. break;
  8825. }
  8826. case UPB_TYPE_UINT64: {
  8827. unsigned long long val = strtoull(p->accumulated, &end, 0);
  8828. if (val > UINT64_MAX || errno == ERANGE || end != myend)
  8829. goto err;
  8830. else
  8831. upb_sink_putuint64(&p->top->sink, parser_getsel(p), val);
  8832. break;
  8833. }
  8834. case UPB_TYPE_DOUBLE: {
  8835. double val = strtod(p->accumulated, &end);
  8836. if (errno == ERANGE || end != myend)
  8837. goto err;
  8838. else
  8839. upb_sink_putdouble(&p->top->sink, parser_getsel(p), val);
  8840. break;
  8841. }
  8842. case UPB_TYPE_FLOAT: {
  8843. float val = strtof(p->accumulated, &end);
  8844. if (errno == ERANGE || end != myend)
  8845. goto err;
  8846. else
  8847. upb_sink_putfloat(&p->top->sink, parser_getsel(p), val);
  8848. break;
  8849. }
  8850. default:
  8851. assert(false);
  8852. }
  8853. multipart_end(p);
  8854. return true;
  8855. err:
  8856. upb_status_seterrf(p->status, "error parsing number: %s", buf);
  8857. multipart_end(p);
  8858. return false;
  8859. }
  8860. static bool parser_putbool(upb_json_parser *p, bool val) {
  8861. if (upb_fielddef_type(p->top->f) != UPB_TYPE_BOOL) {
  8862. upb_status_seterrf(p->status,
  8863. "Boolean value specified for non-bool field: %s",
  8864. upb_fielddef_name(p->top->f));
  8865. return false;
  8866. }
  8867. bool ok = upb_sink_putbool(&p->top->sink, parser_getsel(p), val);
  8868. UPB_ASSERT_VAR(ok, ok);
  8869. return true;
  8870. }
  8871. static bool start_stringval(upb_json_parser *p) {
  8872. assert(p->top->f);
  8873. if (upb_fielddef_isstring(p->top->f)) {
  8874. if (!check_stack(p)) return false;
  8875. // Start a new parser frame: parser frames correspond one-to-one with
  8876. // handler frames, and string events occur in a sub-frame.
  8877. upb_jsonparser_frame *inner = p->top + 1;
  8878. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  8879. upb_sink_startstr(&p->top->sink, sel, 0, &inner->sink);
  8880. inner->m = p->top->m;
  8881. inner->f = p->top->f;
  8882. inner->is_map = false;
  8883. inner->is_mapentry = false;
  8884. p->top = inner;
  8885. if (upb_fielddef_type(p->top->f) == UPB_TYPE_STRING) {
  8886. // For STRING fields we push data directly to the handlers as it is
  8887. // parsed. We don't do this yet for BYTES fields, because our base64
  8888. // decoder is not streaming.
  8889. //
  8890. // TODO(haberman): make base64 decoding streaming also.
  8891. multipart_start(p, getsel_for_handlertype(p, UPB_HANDLER_STRING));
  8892. return true;
  8893. } else {
  8894. multipart_startaccum(p);
  8895. return true;
  8896. }
  8897. } else if (upb_fielddef_type(p->top->f) == UPB_TYPE_ENUM) {
  8898. // No need to push a frame -- symbolic enum names in quotes remain in the
  8899. // current parser frame.
  8900. //
  8901. // Enum string values must accumulate so we can look up the value in a table
  8902. // once it is complete.
  8903. multipart_startaccum(p);
  8904. return true;
  8905. } else {
  8906. upb_status_seterrf(p->status,
  8907. "String specified for non-string/non-enum field: %s",
  8908. upb_fielddef_name(p->top->f));
  8909. return false;
  8910. }
  8911. }
  8912. static bool end_stringval(upb_json_parser *p) {
  8913. bool ok = true;
  8914. switch (upb_fielddef_type(p->top->f)) {
  8915. case UPB_TYPE_BYTES:
  8916. if (!base64_push(p, getsel_for_handlertype(p, UPB_HANDLER_STRING),
  8917. p->accumulated, p->accumulated_len)) {
  8918. return false;
  8919. }
  8920. // Fall through.
  8921. case UPB_TYPE_STRING: {
  8922. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  8923. upb_sink_endstr(&p->top->sink, sel);
  8924. p->top--;
  8925. break;
  8926. }
  8927. case UPB_TYPE_ENUM: {
  8928. // Resolve enum symbolic name to integer value.
  8929. const upb_enumdef *enumdef =
  8930. (const upb_enumdef*)upb_fielddef_subdef(p->top->f);
  8931. size_t len;
  8932. const char *buf = accumulate_getptr(p, &len);
  8933. int32_t int_val = 0;
  8934. ok = upb_enumdef_ntoi(enumdef, buf, len, &int_val);
  8935. if (ok) {
  8936. upb_selector_t sel = parser_getsel(p);
  8937. upb_sink_putint32(&p->top->sink, sel, int_val);
  8938. } else {
  8939. upb_status_seterrf(p->status, "Enum value unknown: '%.*s'", len, buf);
  8940. }
  8941. break;
  8942. }
  8943. default:
  8944. assert(false);
  8945. upb_status_seterrmsg(p->status, "Internal error in JSON decoder");
  8946. ok = false;
  8947. break;
  8948. }
  8949. multipart_end(p);
  8950. return ok;
  8951. }
  8952. static void start_member(upb_json_parser *p) {
  8953. assert(!p->top->f);
  8954. multipart_startaccum(p);
  8955. }
  8956. // Helper: invoked during parse_mapentry() to emit the mapentry message's key
  8957. // field based on the current contents of the accumulate buffer.
  8958. static bool parse_mapentry_key(upb_json_parser *p) {
  8959. size_t len;
  8960. const char *buf = accumulate_getptr(p, &len);
  8961. // Emit the key field. We do a bit of ad-hoc parsing here because the
  8962. // parser state machine has already decided that this is a string field
  8963. // name, and we are reinterpreting it as some arbitrary key type. In
  8964. // particular, integer and bool keys are quoted, so we need to parse the
  8965. // quoted string contents here.
  8966. p->top->f = upb_msgdef_itof(p->top->m, UPB_MAPENTRY_KEY);
  8967. if (p->top->f == NULL) {
  8968. upb_status_seterrmsg(p->status, "mapentry message has no key");
  8969. return false;
  8970. }
  8971. switch (upb_fielddef_type(p->top->f)) {
  8972. case UPB_TYPE_INT32:
  8973. case UPB_TYPE_INT64:
  8974. case UPB_TYPE_UINT32:
  8975. case UPB_TYPE_UINT64:
  8976. // Invoke end_number. The accum buffer has the number's text already.
  8977. if (!parse_number(p)) {
  8978. return false;
  8979. }
  8980. break;
  8981. case UPB_TYPE_BOOL:
  8982. if (len == 4 && !strncmp(buf, "true", 4)) {
  8983. if (!parser_putbool(p, true)) {
  8984. return false;
  8985. }
  8986. } else if (len == 5 && !strncmp(buf, "false", 5)) {
  8987. if (!parser_putbool(p, false)) {
  8988. return false;
  8989. }
  8990. } else {
  8991. upb_status_seterrmsg(p->status,
  8992. "Map bool key not 'true' or 'false'");
  8993. return false;
  8994. }
  8995. multipart_end(p);
  8996. break;
  8997. case UPB_TYPE_STRING:
  8998. case UPB_TYPE_BYTES: {
  8999. upb_sink subsink;
  9000. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  9001. upb_sink_startstr(&p->top->sink, sel, len, &subsink);
  9002. sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
  9003. upb_sink_putstring(&subsink, sel, buf, len, NULL);
  9004. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  9005. upb_sink_endstr(&subsink, sel);
  9006. multipart_end(p);
  9007. break;
  9008. }
  9009. default:
  9010. upb_status_seterrmsg(p->status, "Invalid field type for map key");
  9011. return false;
  9012. }
  9013. return true;
  9014. }
  9015. // Helper: emit one map entry (as a submessage in the map field sequence). This
  9016. // is invoked from end_membername(), at the end of the map entry's key string,
  9017. // with the map key in the accumulate buffer. It parses the key from that
  9018. // buffer, emits the handler calls to start the mapentry submessage (setting up
  9019. // its subframe in the process), and sets up state in the subframe so that the
  9020. // value parser (invoked next) will emit the mapentry's value field and then
  9021. // end the mapentry message.
  9022. static bool handle_mapentry(upb_json_parser *p) {
  9023. // Map entry: p->top->sink is the seq frame, so we need to start a frame
  9024. // for the mapentry itself, and then set |f| in that frame so that the map
  9025. // value field is parsed, and also set a flag to end the frame after the
  9026. // map-entry value is parsed.
  9027. if (!check_stack(p)) return false;
  9028. const upb_fielddef *mapfield = p->top->mapfield;
  9029. const upb_msgdef *mapentrymsg = upb_fielddef_msgsubdef(mapfield);
  9030. upb_jsonparser_frame *inner = p->top + 1;
  9031. p->top->f = mapfield;
  9032. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
  9033. upb_sink_startsubmsg(&p->top->sink, sel, &inner->sink);
  9034. inner->m = mapentrymsg;
  9035. inner->mapfield = mapfield;
  9036. inner->is_map = false;
  9037. // Don't set this to true *yet* -- we reuse parsing handlers below to push
  9038. // the key field value to the sink, and these handlers will pop the frame
  9039. // if they see is_mapentry (when invoked by the parser state machine, they
  9040. // would have just seen the map-entry value, not key).
  9041. inner->is_mapentry = false;
  9042. p->top = inner;
  9043. // send STARTMSG in submsg frame.
  9044. upb_sink_startmsg(&p->top->sink);
  9045. parse_mapentry_key(p);
  9046. // Set up the value field to receive the map-entry value.
  9047. p->top->f = upb_msgdef_itof(p->top->m, UPB_MAPENTRY_VALUE);
  9048. p->top->is_mapentry = true; // set up to pop frame after value is parsed.
  9049. p->top->mapfield = mapfield;
  9050. if (p->top->f == NULL) {
  9051. upb_status_seterrmsg(p->status, "mapentry message has no value");
  9052. return false;
  9053. }
  9054. return true;
  9055. }
  9056. static bool end_membername(upb_json_parser *p) {
  9057. assert(!p->top->f);
  9058. if (p->top->is_map) {
  9059. return handle_mapentry(p);
  9060. } else {
  9061. size_t len;
  9062. const char *buf = accumulate_getptr(p, &len);
  9063. const upb_fielddef *f = upb_msgdef_ntof(p->top->m, buf, len);
  9064. if (!f) {
  9065. // TODO(haberman): Ignore unknown fields if requested/configured to do so.
  9066. upb_status_seterrf(p->status, "No such field: %.*s\n", (int)len, buf);
  9067. return false;
  9068. }
  9069. p->top->f = f;
  9070. multipart_end(p);
  9071. return true;
  9072. }
  9073. }
  9074. static void end_member(upb_json_parser *p) {
  9075. // If we just parsed a map-entry value, end that frame too.
  9076. if (p->top->is_mapentry) {
  9077. assert(p->top > p->stack);
  9078. // send ENDMSG on submsg.
  9079. upb_status s = UPB_STATUS_INIT;
  9080. upb_sink_endmsg(&p->top->sink, &s);
  9081. const upb_fielddef* mapfield = p->top->mapfield;
  9082. // send ENDSUBMSG in repeated-field-of-mapentries frame.
  9083. p->top--;
  9084. upb_selector_t sel;
  9085. bool ok = upb_handlers_getselector(mapfield,
  9086. UPB_HANDLER_ENDSUBMSG, &sel);
  9087. UPB_ASSERT_VAR(ok, ok);
  9088. upb_sink_endsubmsg(&p->top->sink, sel);
  9089. }
  9090. p->top->f = NULL;
  9091. }
  9092. static bool start_subobject(upb_json_parser *p) {
  9093. assert(p->top->f);
  9094. if (upb_fielddef_ismap(p->top->f)) {
  9095. // Beginning of a map. Start a new parser frame in a repeated-field
  9096. // context.
  9097. if (!check_stack(p)) return false;
  9098. upb_jsonparser_frame *inner = p->top + 1;
  9099. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
  9100. upb_sink_startseq(&p->top->sink, sel, &inner->sink);
  9101. inner->m = upb_fielddef_msgsubdef(p->top->f);
  9102. inner->mapfield = p->top->f;
  9103. inner->f = NULL;
  9104. inner->is_map = true;
  9105. inner->is_mapentry = false;
  9106. p->top = inner;
  9107. return true;
  9108. } else if (upb_fielddef_issubmsg(p->top->f)) {
  9109. // Beginning of a subobject. Start a new parser frame in the submsg
  9110. // context.
  9111. if (!check_stack(p)) return false;
  9112. upb_jsonparser_frame *inner = p->top + 1;
  9113. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
  9114. upb_sink_startsubmsg(&p->top->sink, sel, &inner->sink);
  9115. inner->m = upb_fielddef_msgsubdef(p->top->f);
  9116. inner->f = NULL;
  9117. inner->is_map = false;
  9118. inner->is_mapentry = false;
  9119. p->top = inner;
  9120. return true;
  9121. } else {
  9122. upb_status_seterrf(p->status,
  9123. "Object specified for non-message/group field: %s",
  9124. upb_fielddef_name(p->top->f));
  9125. return false;
  9126. }
  9127. }
  9128. static void end_subobject(upb_json_parser *p) {
  9129. if (p->top->is_map) {
  9130. p->top--;
  9131. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
  9132. upb_sink_endseq(&p->top->sink, sel);
  9133. } else {
  9134. p->top--;
  9135. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSUBMSG);
  9136. upb_sink_endsubmsg(&p->top->sink, sel);
  9137. }
  9138. }
  9139. static bool start_array(upb_json_parser *p) {
  9140. assert(p->top->f);
  9141. if (!upb_fielddef_isseq(p->top->f)) {
  9142. upb_status_seterrf(p->status,
  9143. "Array specified for non-repeated field: %s",
  9144. upb_fielddef_name(p->top->f));
  9145. return false;
  9146. }
  9147. if (!check_stack(p)) return false;
  9148. upb_jsonparser_frame *inner = p->top + 1;
  9149. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
  9150. upb_sink_startseq(&p->top->sink, sel, &inner->sink);
  9151. inner->m = p->top->m;
  9152. inner->f = p->top->f;
  9153. inner->is_map = false;
  9154. inner->is_mapentry = false;
  9155. p->top = inner;
  9156. return true;
  9157. }
  9158. static void end_array(upb_json_parser *p) {
  9159. assert(p->top > p->stack);
  9160. p->top--;
  9161. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
  9162. upb_sink_endseq(&p->top->sink, sel);
  9163. }
  9164. static void start_object(upb_json_parser *p) {
  9165. if (!p->top->is_map) {
  9166. upb_sink_startmsg(&p->top->sink);
  9167. }
  9168. }
  9169. static void end_object(upb_json_parser *p) {
  9170. if (!p->top->is_map) {
  9171. upb_status status;
  9172. upb_sink_endmsg(&p->top->sink, &status);
  9173. }
  9174. }
  9175. #define CHECK_RETURN_TOP(x) if (!(x)) goto error
  9176. /* The actual parser **********************************************************/
  9177. // What follows is the Ragel parser itself. The language is specified in Ragel
  9178. // and the actions call our C functions above.
  9179. //
  9180. // Ragel has an extensive set of functionality, and we use only a small part of
  9181. // it. There are many action types but we only use a few:
  9182. //
  9183. // ">" -- transition into a machine
  9184. // "%" -- transition out of a machine
  9185. // "@" -- transition into a final state of a machine.
  9186. //
  9187. // "@" transitions are tricky because a machine can transition into a final
  9188. // state repeatedly. But in some cases we know this can't happen, for example
  9189. // a string which is delimited by a final '"' can only transition into its
  9190. // final state once, when the closing '"' is seen.
  9191. #line 1151 "upb/json/parser.rl"
  9192. #line 1063 "upb/json/parser.c"
  9193. static const char _json_actions[] = {
  9194. 0, 1, 0, 1, 2, 1, 3, 1,
  9195. 5, 1, 6, 1, 7, 1, 8, 1,
  9196. 10, 1, 12, 1, 13, 1, 14, 1,
  9197. 15, 1, 16, 1, 17, 1, 21, 1,
  9198. 25, 1, 27, 2, 3, 8, 2, 4,
  9199. 5, 2, 6, 2, 2, 6, 8, 2,
  9200. 11, 9, 2, 13, 15, 2, 14, 15,
  9201. 2, 18, 1, 2, 19, 27, 2, 20,
  9202. 9, 2, 22, 27, 2, 23, 27, 2,
  9203. 24, 27, 2, 26, 27, 3, 14, 11,
  9204. 9
  9205. };
  9206. static const unsigned char _json_key_offsets[] = {
  9207. 0, 0, 4, 9, 14, 15, 19, 24,
  9208. 29, 34, 38, 42, 45, 48, 50, 54,
  9209. 58, 60, 62, 67, 69, 71, 80, 86,
  9210. 92, 98, 104, 106, 115, 116, 116, 116,
  9211. 121, 126, 131, 132, 133, 134, 135, 135,
  9212. 136, 137, 138, 138, 139, 140, 141, 141,
  9213. 146, 151, 152, 156, 161, 166, 171, 175,
  9214. 175, 178, 178, 178
  9215. };
  9216. static const char _json_trans_keys[] = {
  9217. 32, 123, 9, 13, 32, 34, 125, 9,
  9218. 13, 32, 34, 125, 9, 13, 34, 32,
  9219. 58, 9, 13, 32, 93, 125, 9, 13,
  9220. 32, 44, 125, 9, 13, 32, 44, 125,
  9221. 9, 13, 32, 34, 9, 13, 45, 48,
  9222. 49, 57, 48, 49, 57, 46, 69, 101,
  9223. 48, 57, 69, 101, 48, 57, 43, 45,
  9224. 48, 57, 48, 57, 48, 57, 46, 69,
  9225. 101, 48, 57, 34, 92, 34, 92, 34,
  9226. 47, 92, 98, 102, 110, 114, 116, 117,
  9227. 48, 57, 65, 70, 97, 102, 48, 57,
  9228. 65, 70, 97, 102, 48, 57, 65, 70,
  9229. 97, 102, 48, 57, 65, 70, 97, 102,
  9230. 34, 92, 34, 45, 91, 102, 110, 116,
  9231. 123, 48, 57, 34, 32, 93, 125, 9,
  9232. 13, 32, 44, 93, 9, 13, 32, 93,
  9233. 125, 9, 13, 97, 108, 115, 101, 117,
  9234. 108, 108, 114, 117, 101, 32, 34, 125,
  9235. 9, 13, 32, 34, 125, 9, 13, 34,
  9236. 32, 58, 9, 13, 32, 93, 125, 9,
  9237. 13, 32, 44, 125, 9, 13, 32, 44,
  9238. 125, 9, 13, 32, 34, 9, 13, 32,
  9239. 9, 13, 0
  9240. };
  9241. static const char _json_single_lengths[] = {
  9242. 0, 2, 3, 3, 1, 2, 3, 3,
  9243. 3, 2, 2, 1, 3, 0, 2, 2,
  9244. 0, 0, 3, 2, 2, 9, 0, 0,
  9245. 0, 0, 2, 7, 1, 0, 0, 3,
  9246. 3, 3, 1, 1, 1, 1, 0, 1,
  9247. 1, 1, 0, 1, 1, 1, 0, 3,
  9248. 3, 1, 2, 3, 3, 3, 2, 0,
  9249. 1, 0, 0, 0
  9250. };
  9251. static const char _json_range_lengths[] = {
  9252. 0, 1, 1, 1, 0, 1, 1, 1,
  9253. 1, 1, 1, 1, 0, 1, 1, 1,
  9254. 1, 1, 1, 0, 0, 0, 3, 3,
  9255. 3, 3, 0, 1, 0, 0, 0, 1,
  9256. 1, 1, 0, 0, 0, 0, 0, 0,
  9257. 0, 0, 0, 0, 0, 0, 0, 1,
  9258. 1, 0, 1, 1, 1, 1, 1, 0,
  9259. 1, 0, 0, 0
  9260. };
  9261. static const short _json_index_offsets[] = {
  9262. 0, 0, 4, 9, 14, 16, 20, 25,
  9263. 30, 35, 39, 43, 46, 50, 52, 56,
  9264. 60, 62, 64, 69, 72, 75, 85, 89,
  9265. 93, 97, 101, 104, 113, 115, 116, 117,
  9266. 122, 127, 132, 134, 136, 138, 140, 141,
  9267. 143, 145, 147, 148, 150, 152, 154, 155,
  9268. 160, 165, 167, 171, 176, 181, 186, 190,
  9269. 191, 194, 195, 196
  9270. };
  9271. static const char _json_indicies[] = {
  9272. 0, 2, 0, 1, 3, 4, 5, 3,
  9273. 1, 6, 7, 8, 6, 1, 9, 1,
  9274. 10, 11, 10, 1, 11, 1, 1, 11,
  9275. 12, 13, 14, 15, 13, 1, 16, 17,
  9276. 8, 16, 1, 17, 7, 17, 1, 18,
  9277. 19, 20, 1, 19, 20, 1, 22, 23,
  9278. 23, 21, 24, 1, 23, 23, 24, 21,
  9279. 25, 25, 26, 1, 26, 1, 26, 21,
  9280. 22, 23, 23, 20, 21, 28, 29, 27,
  9281. 31, 32, 30, 33, 33, 33, 33, 33,
  9282. 33, 33, 33, 34, 1, 35, 35, 35,
  9283. 1, 36, 36, 36, 1, 37, 37, 37,
  9284. 1, 38, 38, 38, 1, 40, 41, 39,
  9285. 42, 43, 44, 45, 46, 47, 48, 43,
  9286. 1, 49, 1, 50, 51, 53, 54, 1,
  9287. 53, 52, 55, 56, 54, 55, 1, 56,
  9288. 1, 1, 56, 52, 57, 1, 58, 1,
  9289. 59, 1, 60, 1, 61, 62, 1, 63,
  9290. 1, 64, 1, 65, 66, 1, 67, 1,
  9291. 68, 1, 69, 70, 71, 72, 70, 1,
  9292. 73, 74, 75, 73, 1, 76, 1, 77,
  9293. 78, 77, 1, 78, 1, 1, 78, 79,
  9294. 80, 81, 82, 80, 1, 83, 84, 75,
  9295. 83, 1, 84, 74, 84, 1, 85, 86,
  9296. 86, 1, 1, 1, 1, 0
  9297. };
  9298. static const char _json_trans_targs[] = {
  9299. 1, 0, 2, 3, 4, 56, 3, 4,
  9300. 56, 5, 5, 6, 7, 8, 9, 56,
  9301. 8, 9, 11, 12, 18, 57, 13, 15,
  9302. 14, 16, 17, 20, 58, 21, 20, 58,
  9303. 21, 19, 22, 23, 24, 25, 26, 20,
  9304. 58, 21, 28, 30, 31, 34, 39, 43,
  9305. 47, 29, 59, 59, 32, 31, 29, 32,
  9306. 33, 35, 36, 37, 38, 59, 40, 41,
  9307. 42, 59, 44, 45, 46, 59, 48, 49,
  9308. 55, 48, 49, 55, 50, 50, 51, 52,
  9309. 53, 54, 55, 53, 54, 59, 56
  9310. };
  9311. static const char _json_trans_actions[] = {
  9312. 0, 0, 0, 21, 77, 53, 0, 47,
  9313. 23, 17, 0, 0, 15, 19, 19, 50,
  9314. 0, 0, 0, 0, 0, 1, 0, 0,
  9315. 0, 0, 0, 3, 13, 0, 0, 35,
  9316. 5, 11, 0, 38, 7, 7, 7, 41,
  9317. 44, 9, 62, 56, 25, 0, 0, 0,
  9318. 31, 29, 33, 59, 15, 0, 27, 0,
  9319. 0, 0, 0, 0, 0, 68, 0, 0,
  9320. 0, 71, 0, 0, 0, 65, 21, 77,
  9321. 53, 0, 47, 23, 17, 0, 0, 15,
  9322. 19, 19, 50, 0, 0, 74, 0
  9323. };
  9324. static const int json_start = 1;
  9325. static const int json_en_number_machine = 10;
  9326. static const int json_en_string_machine = 19;
  9327. static const int json_en_value_machine = 27;
  9328. static const int json_en_main = 1;
  9329. #line 1154 "upb/json/parser.rl"
  9330. size_t parse(void *closure, const void *hd, const char *buf, size_t size,
  9331. const upb_bufhandle *handle) {
  9332. UPB_UNUSED(hd);
  9333. UPB_UNUSED(handle);
  9334. upb_json_parser *parser = closure;
  9335. parser->handle = handle;
  9336. // Variables used by Ragel's generated code.
  9337. int cs = parser->current_state;
  9338. int *stack = parser->parser_stack;
  9339. int top = parser->parser_top;
  9340. const char *p = buf;
  9341. const char *pe = buf + size;
  9342. capture_resume(parser, buf);
  9343. #line 1232 "upb/json/parser.c"
  9344. {
  9345. int _klen;
  9346. unsigned int _trans;
  9347. const char *_acts;
  9348. unsigned int _nacts;
  9349. const char *_keys;
  9350. if ( p == pe )
  9351. goto _test_eof;
  9352. if ( cs == 0 )
  9353. goto _out;
  9354. _resume:
  9355. _keys = _json_trans_keys + _json_key_offsets[cs];
  9356. _trans = _json_index_offsets[cs];
  9357. _klen = _json_single_lengths[cs];
  9358. if ( _klen > 0 ) {
  9359. const char *_lower = _keys;
  9360. const char *_mid;
  9361. const char *_upper = _keys + _klen - 1;
  9362. while (1) {
  9363. if ( _upper < _lower )
  9364. break;
  9365. _mid = _lower + ((_upper-_lower) >> 1);
  9366. if ( (*p) < *_mid )
  9367. _upper = _mid - 1;
  9368. else if ( (*p) > *_mid )
  9369. _lower = _mid + 1;
  9370. else {
  9371. _trans += (unsigned int)(_mid - _keys);
  9372. goto _match;
  9373. }
  9374. }
  9375. _keys += _klen;
  9376. _trans += _klen;
  9377. }
  9378. _klen = _json_range_lengths[cs];
  9379. if ( _klen > 0 ) {
  9380. const char *_lower = _keys;
  9381. const char *_mid;
  9382. const char *_upper = _keys + (_klen<<1) - 2;
  9383. while (1) {
  9384. if ( _upper < _lower )
  9385. break;
  9386. _mid = _lower + (((_upper-_lower) >> 1) & ~1);
  9387. if ( (*p) < _mid[0] )
  9388. _upper = _mid - 2;
  9389. else if ( (*p) > _mid[1] )
  9390. _lower = _mid + 2;
  9391. else {
  9392. _trans += (unsigned int)((_mid - _keys)>>1);
  9393. goto _match;
  9394. }
  9395. }
  9396. _trans += _klen;
  9397. }
  9398. _match:
  9399. _trans = _json_indicies[_trans];
  9400. cs = _json_trans_targs[_trans];
  9401. if ( _json_trans_actions[_trans] == 0 )
  9402. goto _again;
  9403. _acts = _json_actions + _json_trans_actions[_trans];
  9404. _nacts = (unsigned int) *_acts++;
  9405. while ( _nacts-- > 0 )
  9406. {
  9407. switch ( *_acts++ )
  9408. {
  9409. case 0:
  9410. #line 1066 "upb/json/parser.rl"
  9411. { p--; {cs = stack[--top]; goto _again;} }
  9412. break;
  9413. case 1:
  9414. #line 1067 "upb/json/parser.rl"
  9415. { p--; {stack[top++] = cs; cs = 10; goto _again;} }
  9416. break;
  9417. case 2:
  9418. #line 1071 "upb/json/parser.rl"
  9419. { start_text(parser, p); }
  9420. break;
  9421. case 3:
  9422. #line 1072 "upb/json/parser.rl"
  9423. { CHECK_RETURN_TOP(end_text(parser, p)); }
  9424. break;
  9425. case 4:
  9426. #line 1078 "upb/json/parser.rl"
  9427. { start_hex(parser); }
  9428. break;
  9429. case 5:
  9430. #line 1079 "upb/json/parser.rl"
  9431. { hexdigit(parser, p); }
  9432. break;
  9433. case 6:
  9434. #line 1080 "upb/json/parser.rl"
  9435. { CHECK_RETURN_TOP(end_hex(parser)); }
  9436. break;
  9437. case 7:
  9438. #line 1086 "upb/json/parser.rl"
  9439. { CHECK_RETURN_TOP(escape(parser, p)); }
  9440. break;
  9441. case 8:
  9442. #line 1092 "upb/json/parser.rl"
  9443. { p--; {cs = stack[--top]; goto _again;} }
  9444. break;
  9445. case 9:
  9446. #line 1095 "upb/json/parser.rl"
  9447. { {stack[top++] = cs; cs = 19; goto _again;} }
  9448. break;
  9449. case 10:
  9450. #line 1097 "upb/json/parser.rl"
  9451. { p--; {stack[top++] = cs; cs = 27; goto _again;} }
  9452. break;
  9453. case 11:
  9454. #line 1102 "upb/json/parser.rl"
  9455. { start_member(parser); }
  9456. break;
  9457. case 12:
  9458. #line 1103 "upb/json/parser.rl"
  9459. { CHECK_RETURN_TOP(end_membername(parser)); }
  9460. break;
  9461. case 13:
  9462. #line 1106 "upb/json/parser.rl"
  9463. { end_member(parser); }
  9464. break;
  9465. case 14:
  9466. #line 1112 "upb/json/parser.rl"
  9467. { start_object(parser); }
  9468. break;
  9469. case 15:
  9470. #line 1115 "upb/json/parser.rl"
  9471. { end_object(parser); }
  9472. break;
  9473. case 16:
  9474. #line 1121 "upb/json/parser.rl"
  9475. { CHECK_RETURN_TOP(start_array(parser)); }
  9476. break;
  9477. case 17:
  9478. #line 1125 "upb/json/parser.rl"
  9479. { end_array(parser); }
  9480. break;
  9481. case 18:
  9482. #line 1130 "upb/json/parser.rl"
  9483. { start_number(parser, p); }
  9484. break;
  9485. case 19:
  9486. #line 1131 "upb/json/parser.rl"
  9487. { CHECK_RETURN_TOP(end_number(parser, p)); }
  9488. break;
  9489. case 20:
  9490. #line 1133 "upb/json/parser.rl"
  9491. { CHECK_RETURN_TOP(start_stringval(parser)); }
  9492. break;
  9493. case 21:
  9494. #line 1134 "upb/json/parser.rl"
  9495. { CHECK_RETURN_TOP(end_stringval(parser)); }
  9496. break;
  9497. case 22:
  9498. #line 1136 "upb/json/parser.rl"
  9499. { CHECK_RETURN_TOP(parser_putbool(parser, true)); }
  9500. break;
  9501. case 23:
  9502. #line 1138 "upb/json/parser.rl"
  9503. { CHECK_RETURN_TOP(parser_putbool(parser, false)); }
  9504. break;
  9505. case 24:
  9506. #line 1140 "upb/json/parser.rl"
  9507. { /* null value */ }
  9508. break;
  9509. case 25:
  9510. #line 1142 "upb/json/parser.rl"
  9511. { CHECK_RETURN_TOP(start_subobject(parser)); }
  9512. break;
  9513. case 26:
  9514. #line 1143 "upb/json/parser.rl"
  9515. { end_subobject(parser); }
  9516. break;
  9517. case 27:
  9518. #line 1148 "upb/json/parser.rl"
  9519. { p--; {cs = stack[--top]; goto _again;} }
  9520. break;
  9521. #line 1418 "upb/json/parser.c"
  9522. }
  9523. }
  9524. _again:
  9525. if ( cs == 0 )
  9526. goto _out;
  9527. if ( ++p != pe )
  9528. goto _resume;
  9529. _test_eof: {}
  9530. _out: {}
  9531. }
  9532. #line 1173 "upb/json/parser.rl"
  9533. if (p != pe) {
  9534. upb_status_seterrf(parser->status, "Parse error at %s\n", p);
  9535. } else {
  9536. capture_suspend(parser, &p);
  9537. }
  9538. error:
  9539. // Save parsing state back to parser.
  9540. parser->current_state = cs;
  9541. parser->parser_top = top;
  9542. return p - buf;
  9543. }
  9544. bool end(void *closure, const void *hd) {
  9545. UPB_UNUSED(closure);
  9546. UPB_UNUSED(hd);
  9547. // Prevent compile warning on unused static constants.
  9548. UPB_UNUSED(json_start);
  9549. UPB_UNUSED(json_en_number_machine);
  9550. UPB_UNUSED(json_en_string_machine);
  9551. UPB_UNUSED(json_en_value_machine);
  9552. UPB_UNUSED(json_en_main);
  9553. return true;
  9554. }
  9555. static void json_parser_reset(upb_json_parser *p) {
  9556. p->top = p->stack;
  9557. p->top->f = NULL;
  9558. p->top->is_map = false;
  9559. p->top->is_mapentry = false;
  9560. int cs;
  9561. int top;
  9562. // Emit Ragel initialization of the parser.
  9563. #line 1470 "upb/json/parser.c"
  9564. {
  9565. cs = json_start;
  9566. top = 0;
  9567. }
  9568. #line 1211 "upb/json/parser.rl"
  9569. p->current_state = cs;
  9570. p->parser_top = top;
  9571. accumulate_clear(p);
  9572. p->multipart_state = MULTIPART_INACTIVE;
  9573. p->capture = NULL;
  9574. p->accumulated = NULL;
  9575. }
  9576. /* Public API *****************************************************************/
  9577. upb_json_parser *upb_json_parser_create(upb_env *env, upb_sink *output) {
  9578. #ifndef NDEBUG
  9579. const size_t size_before = upb_env_bytesallocated(env);
  9580. #endif
  9581. upb_json_parser *p = upb_env_malloc(env, sizeof(upb_json_parser));
  9582. if (!p) return false;
  9583. p->env = env;
  9584. p->limit = p->stack + UPB_JSON_MAX_DEPTH;
  9585. p->accumulate_buf = NULL;
  9586. p->accumulate_buf_size = 0;
  9587. upb_byteshandler_init(&p->input_handler_);
  9588. upb_byteshandler_setstring(&p->input_handler_, parse, NULL);
  9589. upb_byteshandler_setendstr(&p->input_handler_, end, NULL);
  9590. upb_bytessink_reset(&p->input_, &p->input_handler_, p);
  9591. json_parser_reset(p);
  9592. upb_sink_reset(&p->top->sink, output->handlers, output->closure);
  9593. p->top->m = upb_handlers_msgdef(output->handlers);
  9594. // If this fails, uncomment and increase the value in parser.h.
  9595. // fprintf(stderr, "%zd\n", upb_env_bytesallocated(env) - size_before);
  9596. assert(upb_env_bytesallocated(env) - size_before <= UPB_JSON_PARSER_SIZE);
  9597. return p;
  9598. }
  9599. upb_bytessink *upb_json_parser_input(upb_json_parser *p) {
  9600. return &p->input_;
  9601. }
  9602. /*
  9603. * upb - a minimalist implementation of protocol buffers.
  9604. *
  9605. * Copyright (c) 2014 Google Inc. See LICENSE for details.
  9606. * Author: Josh Haberman <jhaberman@gmail.com>
  9607. *
  9608. * This currently uses snprintf() to format primitives, and could be optimized
  9609. * further.
  9610. */
  9611. #include <stdlib.h>
  9612. #include <stdio.h>
  9613. #include <string.h>
  9614. #include <stdint.h>
  9615. struct upb_json_printer {
  9616. upb_sink input_;
  9617. // BytesSink closure.
  9618. void *subc_;
  9619. upb_bytessink *output_;
  9620. // We track the depth so that we know when to emit startstr/endstr on the
  9621. // output.
  9622. int depth_;
  9623. // Have we emitted the first element? This state is necessary to emit commas
  9624. // without leaving a trailing comma in arrays/maps. We keep this state per
  9625. // frame depth.
  9626. //
  9627. // Why max_depth * 2? UPB_MAX_HANDLER_DEPTH counts depth as nested messages.
  9628. // We count frames (contexts in which we separate elements by commas) as both
  9629. // repeated fields and messages (maps), and the worst case is a
  9630. // message->repeated field->submessage->repeated field->... nesting.
  9631. bool first_elem_[UPB_MAX_HANDLER_DEPTH * 2];
  9632. };
  9633. // StringPiece; a pointer plus a length.
  9634. typedef struct {
  9635. const char *ptr;
  9636. size_t len;
  9637. } strpc;
  9638. strpc *newstrpc(upb_handlers *h, const upb_fielddef *f) {
  9639. strpc *ret = malloc(sizeof(*ret));
  9640. ret->ptr = upb_fielddef_name(f);
  9641. ret->len = strlen(ret->ptr);
  9642. upb_handlers_addcleanup(h, ret, free);
  9643. return ret;
  9644. }
  9645. // ------------ JSON string printing: values, maps, arrays --------------------
  9646. static void print_data(
  9647. upb_json_printer *p, const char *buf, unsigned int len) {
  9648. // TODO: Will need to change if we support pushback from the sink.
  9649. size_t n = upb_bytessink_putbuf(p->output_, p->subc_, buf, len, NULL);
  9650. UPB_ASSERT_VAR(n, n == len);
  9651. }
  9652. static void print_comma(upb_json_printer *p) {
  9653. if (!p->first_elem_[p->depth_]) {
  9654. print_data(p, ",", 1);
  9655. }
  9656. p->first_elem_[p->depth_] = false;
  9657. }
  9658. // Helpers that print properly formatted elements to the JSON output stream.
  9659. // Used for escaping control chars in strings.
  9660. static const char kControlCharLimit = 0x20;
  9661. static inline bool is_json_escaped(char c) {
  9662. // See RFC 4627.
  9663. unsigned char uc = (unsigned char)c;
  9664. return uc < kControlCharLimit || uc == '"' || uc == '\\';
  9665. }
  9666. static inline char* json_nice_escape(char c) {
  9667. switch (c) {
  9668. case '"': return "\\\"";
  9669. case '\\': return "\\\\";
  9670. case '\b': return "\\b";
  9671. case '\f': return "\\f";
  9672. case '\n': return "\\n";
  9673. case '\r': return "\\r";
  9674. case '\t': return "\\t";
  9675. default: return NULL;
  9676. }
  9677. }
  9678. // Write a properly escaped string chunk. The surrounding quotes are *not*
  9679. // printed; this is so that the caller has the option of emitting the string
  9680. // content in chunks.
  9681. static void putstring(upb_json_printer *p, const char *buf, unsigned int len) {
  9682. const char* unescaped_run = NULL;
  9683. for (unsigned int i = 0; i < len; i++) {
  9684. char c = buf[i];
  9685. // Handle escaping.
  9686. if (is_json_escaped(c)) {
  9687. // Use a "nice" escape, like \n, if one exists for this character.
  9688. const char* escape = json_nice_escape(c);
  9689. // If we don't have a specific 'nice' escape code, use a \uXXXX-style
  9690. // escape.
  9691. char escape_buf[8];
  9692. if (!escape) {
  9693. unsigned char byte = (unsigned char)c;
  9694. snprintf(escape_buf, sizeof(escape_buf), "\\u%04x", (int)byte);
  9695. escape = escape_buf;
  9696. }
  9697. // N.B. that we assume that the input encoding is equal to the output
  9698. // encoding (both UTF-8 for now), so for chars >= 0x20 and != \, ", we
  9699. // can simply pass the bytes through.
  9700. // If there's a current run of unescaped chars, print that run first.
  9701. if (unescaped_run) {
  9702. print_data(p, unescaped_run, &buf[i] - unescaped_run);
  9703. unescaped_run = NULL;
  9704. }
  9705. // Then print the escape code.
  9706. print_data(p, escape, strlen(escape));
  9707. } else {
  9708. // Add to the current unescaped run of characters.
  9709. if (unescaped_run == NULL) {
  9710. unescaped_run = &buf[i];
  9711. }
  9712. }
  9713. }
  9714. // If the string ended in a run of unescaped characters, print that last run.
  9715. if (unescaped_run) {
  9716. print_data(p, unescaped_run, &buf[len] - unescaped_run);
  9717. }
  9718. }
  9719. #define CHKLENGTH(x) if (!(x)) return -1;
  9720. // Helpers that format floating point values according to our custom formats.
  9721. // Right now we use %.8g and %.17g for float/double, respectively, to match
  9722. // proto2::util::JsonFormat's defaults. May want to change this later.
  9723. static size_t fmt_double(double val, char* buf, size_t length) {
  9724. size_t n = snprintf(buf, length, "%.17g", val);
  9725. CHKLENGTH(n > 0 && n < length);
  9726. return n;
  9727. }
  9728. static size_t fmt_float(float val, char* buf, size_t length) {
  9729. size_t n = snprintf(buf, length, "%.8g", val);
  9730. CHKLENGTH(n > 0 && n < length);
  9731. return n;
  9732. }
  9733. static size_t fmt_bool(bool val, char* buf, size_t length) {
  9734. size_t n = snprintf(buf, length, "%s", (val ? "true" : "false"));
  9735. CHKLENGTH(n > 0 && n < length);
  9736. return n;
  9737. }
  9738. static size_t fmt_int64(long val, char* buf, size_t length) {
  9739. size_t n = snprintf(buf, length, "%ld", val);
  9740. CHKLENGTH(n > 0 && n < length);
  9741. return n;
  9742. }
  9743. static size_t fmt_uint64(unsigned long long val, char* buf, size_t length) {
  9744. size_t n = snprintf(buf, length, "%llu", val);
  9745. CHKLENGTH(n > 0 && n < length);
  9746. return n;
  9747. }
  9748. // Print a map key given a field name. Called by scalar field handlers and by
  9749. // startseq for repeated fields.
  9750. static bool putkey(void *closure, const void *handler_data) {
  9751. upb_json_printer *p = closure;
  9752. const strpc *key = handler_data;
  9753. print_comma(p);
  9754. print_data(p, "\"", 1);
  9755. putstring(p, key->ptr, key->len);
  9756. print_data(p, "\":", 2);
  9757. return true;
  9758. }
  9759. #define CHKFMT(val) if ((val) == (size_t)-1) return false;
  9760. #define CHK(val) if (!(val)) return false;
  9761. #define TYPE_HANDLERS(type, fmt_func) \
  9762. static bool put##type(void *closure, const void *handler_data, type val) { \
  9763. upb_json_printer *p = closure; \
  9764. UPB_UNUSED(handler_data); \
  9765. char data[64]; \
  9766. size_t length = fmt_func(val, data, sizeof(data)); \
  9767. CHKFMT(length); \
  9768. print_data(p, data, length); \
  9769. return true; \
  9770. } \
  9771. static bool scalar_##type(void *closure, const void *handler_data, \
  9772. type val) { \
  9773. CHK(putkey(closure, handler_data)); \
  9774. CHK(put##type(closure, handler_data, val)); \
  9775. return true; \
  9776. } \
  9777. static bool repeated_##type(void *closure, const void *handler_data, \
  9778. type val) { \
  9779. upb_json_printer *p = closure; \
  9780. print_comma(p); \
  9781. CHK(put##type(closure, handler_data, val)); \
  9782. return true; \
  9783. }
  9784. #define TYPE_HANDLERS_MAPKEY(type, fmt_func) \
  9785. static bool putmapkey_##type(void *closure, const void *handler_data, \
  9786. type val) { \
  9787. upb_json_printer *p = closure; \
  9788. print_data(p, "\"", 1); \
  9789. CHK(put##type(closure, handler_data, val)); \
  9790. print_data(p, "\":", 2); \
  9791. return true; \
  9792. }
  9793. TYPE_HANDLERS(double, fmt_double);
  9794. TYPE_HANDLERS(float, fmt_float);
  9795. TYPE_HANDLERS(bool, fmt_bool);
  9796. TYPE_HANDLERS(int32_t, fmt_int64);
  9797. TYPE_HANDLERS(uint32_t, fmt_int64);
  9798. TYPE_HANDLERS(int64_t, fmt_int64);
  9799. TYPE_HANDLERS(uint64_t, fmt_uint64);
  9800. // double and float are not allowed to be map keys.
  9801. TYPE_HANDLERS_MAPKEY(bool, fmt_bool);
  9802. TYPE_HANDLERS_MAPKEY(int32_t, fmt_int64);
  9803. TYPE_HANDLERS_MAPKEY(uint32_t, fmt_int64);
  9804. TYPE_HANDLERS_MAPKEY(int64_t, fmt_int64);
  9805. TYPE_HANDLERS_MAPKEY(uint64_t, fmt_uint64);
  9806. #undef TYPE_HANDLERS
  9807. #undef TYPE_HANDLERS_MAPKEY
  9808. typedef struct {
  9809. void *keyname;
  9810. const upb_enumdef *enumdef;
  9811. } EnumHandlerData;
  9812. static bool scalar_enum(void *closure, const void *handler_data,
  9813. int32_t val) {
  9814. const EnumHandlerData *hd = handler_data;
  9815. upb_json_printer *p = closure;
  9816. CHK(putkey(closure, hd->keyname));
  9817. const char *symbolic_name = upb_enumdef_iton(hd->enumdef, val);
  9818. if (symbolic_name) {
  9819. print_data(p, "\"", 1);
  9820. putstring(p, symbolic_name, strlen(symbolic_name));
  9821. print_data(p, "\"", 1);
  9822. } else {
  9823. putint32_t(closure, NULL, val);
  9824. }
  9825. return true;
  9826. }
  9827. static void print_enum_symbolic_name(upb_json_printer *p,
  9828. const upb_enumdef *def,
  9829. int32_t val) {
  9830. const char *symbolic_name = upb_enumdef_iton(def, val);
  9831. if (symbolic_name) {
  9832. print_data(p, "\"", 1);
  9833. putstring(p, symbolic_name, strlen(symbolic_name));
  9834. print_data(p, "\"", 1);
  9835. } else {
  9836. putint32_t(p, NULL, val);
  9837. }
  9838. }
  9839. static bool repeated_enum(void *closure, const void *handler_data,
  9840. int32_t val) {
  9841. const EnumHandlerData *hd = handler_data;
  9842. upb_json_printer *p = closure;
  9843. print_comma(p);
  9844. print_enum_symbolic_name(p, hd->enumdef, val);
  9845. return true;
  9846. }
  9847. static bool mapvalue_enum(void *closure, const void *handler_data,
  9848. int32_t val) {
  9849. const EnumHandlerData *hd = handler_data;
  9850. upb_json_printer *p = closure;
  9851. print_enum_symbolic_name(p, hd->enumdef, val);
  9852. return true;
  9853. }
  9854. static void *scalar_startsubmsg(void *closure, const void *handler_data) {
  9855. return putkey(closure, handler_data) ? closure : UPB_BREAK;
  9856. }
  9857. static void *repeated_startsubmsg(void *closure, const void *handler_data) {
  9858. UPB_UNUSED(handler_data);
  9859. upb_json_printer *p = closure;
  9860. print_comma(p);
  9861. return closure;
  9862. }
  9863. static void start_frame(upb_json_printer *p) {
  9864. p->depth_++;
  9865. p->first_elem_[p->depth_] = true;
  9866. print_data(p, "{", 1);
  9867. }
  9868. static void end_frame(upb_json_printer *p) {
  9869. print_data(p, "}", 1);
  9870. p->depth_--;
  9871. }
  9872. static bool printer_startmsg(void *closure, const void *handler_data) {
  9873. UPB_UNUSED(handler_data);
  9874. upb_json_printer *p = closure;
  9875. if (p->depth_ == 0) {
  9876. upb_bytessink_start(p->output_, 0, &p->subc_);
  9877. }
  9878. start_frame(p);
  9879. return true;
  9880. }
  9881. static bool printer_endmsg(void *closure, const void *handler_data, upb_status *s) {
  9882. UPB_UNUSED(handler_data);
  9883. UPB_UNUSED(s);
  9884. upb_json_printer *p = closure;
  9885. end_frame(p);
  9886. if (p->depth_ == 0) {
  9887. upb_bytessink_end(p->output_);
  9888. }
  9889. return true;
  9890. }
  9891. static void *startseq(void *closure, const void *handler_data) {
  9892. upb_json_printer *p = closure;
  9893. CHK(putkey(closure, handler_data));
  9894. p->depth_++;
  9895. p->first_elem_[p->depth_] = true;
  9896. print_data(p, "[", 1);
  9897. return closure;
  9898. }
  9899. static bool endseq(void *closure, const void *handler_data) {
  9900. UPB_UNUSED(handler_data);
  9901. upb_json_printer *p = closure;
  9902. print_data(p, "]", 1);
  9903. p->depth_--;
  9904. return true;
  9905. }
  9906. static void *startmap(void *closure, const void *handler_data) {
  9907. upb_json_printer *p = closure;
  9908. CHK(putkey(closure, handler_data));
  9909. p->depth_++;
  9910. p->first_elem_[p->depth_] = true;
  9911. print_data(p, "{", 1);
  9912. return closure;
  9913. }
  9914. static bool endmap(void *closure, const void *handler_data) {
  9915. UPB_UNUSED(handler_data);
  9916. upb_json_printer *p = closure;
  9917. print_data(p, "}", 1);
  9918. p->depth_--;
  9919. return true;
  9920. }
  9921. static size_t putstr(void *closure, const void *handler_data, const char *str,
  9922. size_t len, const upb_bufhandle *handle) {
  9923. UPB_UNUSED(handler_data);
  9924. UPB_UNUSED(handle);
  9925. upb_json_printer *p = closure;
  9926. putstring(p, str, len);
  9927. return len;
  9928. }
  9929. // This has to Base64 encode the bytes, because JSON has no "bytes" type.
  9930. static size_t putbytes(void *closure, const void *handler_data, const char *str,
  9931. size_t len, const upb_bufhandle *handle) {
  9932. UPB_UNUSED(handler_data);
  9933. UPB_UNUSED(handle);
  9934. upb_json_printer *p = closure;
  9935. // This is the regular base64, not the "web-safe" version.
  9936. static const char base64[] =
  9937. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  9938. // Base64-encode.
  9939. char data[16000];
  9940. const char *limit = data + sizeof(data);
  9941. const unsigned char *from = (const unsigned char*)str;
  9942. char *to = data;
  9943. size_t remaining = len;
  9944. while (remaining > 2) {
  9945. // TODO(haberman): handle encoded lengths > sizeof(data)
  9946. UPB_ASSERT_VAR(limit, (limit - to) >= 4);
  9947. to[0] = base64[from[0] >> 2];
  9948. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  9949. to[2] = base64[((from[1] & 0xf) << 2) | (from[2] >> 6)];
  9950. to[3] = base64[from[2] & 0x3f];
  9951. remaining -= 3;
  9952. to += 4;
  9953. from += 3;
  9954. }
  9955. switch (remaining) {
  9956. case 2:
  9957. to[0] = base64[from[0] >> 2];
  9958. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  9959. to[2] = base64[(from[1] & 0xf) << 2];
  9960. to[3] = '=';
  9961. to += 4;
  9962. from += 2;
  9963. break;
  9964. case 1:
  9965. to[0] = base64[from[0] >> 2];
  9966. to[1] = base64[((from[0] & 0x3) << 4)];
  9967. to[2] = '=';
  9968. to[3] = '=';
  9969. to += 4;
  9970. from += 1;
  9971. break;
  9972. }
  9973. size_t bytes = to - data;
  9974. print_data(p, "\"", 1);
  9975. putstring(p, data, bytes);
  9976. print_data(p, "\"", 1);
  9977. return len;
  9978. }
  9979. static void *scalar_startstr(void *closure, const void *handler_data,
  9980. size_t size_hint) {
  9981. UPB_UNUSED(handler_data);
  9982. UPB_UNUSED(size_hint);
  9983. upb_json_printer *p = closure;
  9984. CHK(putkey(closure, handler_data));
  9985. print_data(p, "\"", 1);
  9986. return p;
  9987. }
  9988. static size_t scalar_str(void *closure, const void *handler_data,
  9989. const char *str, size_t len,
  9990. const upb_bufhandle *handle) {
  9991. CHK(putstr(closure, handler_data, str, len, handle));
  9992. return len;
  9993. }
  9994. static bool scalar_endstr(void *closure, const void *handler_data) {
  9995. UPB_UNUSED(handler_data);
  9996. upb_json_printer *p = closure;
  9997. print_data(p, "\"", 1);
  9998. return true;
  9999. }
  10000. static void *repeated_startstr(void *closure, const void *handler_data,
  10001. size_t size_hint) {
  10002. UPB_UNUSED(handler_data);
  10003. UPB_UNUSED(size_hint);
  10004. upb_json_printer *p = closure;
  10005. print_comma(p);
  10006. print_data(p, "\"", 1);
  10007. return p;
  10008. }
  10009. static size_t repeated_str(void *closure, const void *handler_data,
  10010. const char *str, size_t len,
  10011. const upb_bufhandle *handle) {
  10012. CHK(putstr(closure, handler_data, str, len, handle));
  10013. return len;
  10014. }
  10015. static bool repeated_endstr(void *closure, const void *handler_data) {
  10016. UPB_UNUSED(handler_data);
  10017. upb_json_printer *p = closure;
  10018. print_data(p, "\"", 1);
  10019. return true;
  10020. }
  10021. static void *mapkeyval_startstr(void *closure, const void *handler_data,
  10022. size_t size_hint) {
  10023. UPB_UNUSED(handler_data);
  10024. UPB_UNUSED(size_hint);
  10025. upb_json_printer *p = closure;
  10026. print_data(p, "\"", 1);
  10027. return p;
  10028. }
  10029. static size_t mapkey_str(void *closure, const void *handler_data,
  10030. const char *str, size_t len,
  10031. const upb_bufhandle *handle) {
  10032. CHK(putstr(closure, handler_data, str, len, handle));
  10033. return len;
  10034. }
  10035. static bool mapkey_endstr(void *closure, const void *handler_data) {
  10036. UPB_UNUSED(handler_data);
  10037. upb_json_printer *p = closure;
  10038. print_data(p, "\":", 2);
  10039. return true;
  10040. }
  10041. static bool mapvalue_endstr(void *closure, const void *handler_data) {
  10042. UPB_UNUSED(handler_data);
  10043. upb_json_printer *p = closure;
  10044. print_data(p, "\"", 1);
  10045. return true;
  10046. }
  10047. static size_t scalar_bytes(void *closure, const void *handler_data,
  10048. const char *str, size_t len,
  10049. const upb_bufhandle *handle) {
  10050. CHK(putkey(closure, handler_data));
  10051. CHK(putbytes(closure, handler_data, str, len, handle));
  10052. return len;
  10053. }
  10054. static size_t repeated_bytes(void *closure, const void *handler_data,
  10055. const char *str, size_t len,
  10056. const upb_bufhandle *handle) {
  10057. upb_json_printer *p = closure;
  10058. print_comma(p);
  10059. CHK(putbytes(closure, handler_data, str, len, handle));
  10060. return len;
  10061. }
  10062. static size_t mapkey_bytes(void *closure, const void *handler_data,
  10063. const char *str, size_t len,
  10064. const upb_bufhandle *handle) {
  10065. upb_json_printer *p = closure;
  10066. CHK(putbytes(closure, handler_data, str, len, handle));
  10067. print_data(p, ":", 1);
  10068. return len;
  10069. }
  10070. static void set_enum_hd(upb_handlers *h,
  10071. const upb_fielddef *f,
  10072. upb_handlerattr *attr) {
  10073. EnumHandlerData *hd = malloc(sizeof(EnumHandlerData));
  10074. hd->enumdef = (const upb_enumdef *)upb_fielddef_subdef(f);
  10075. hd->keyname = newstrpc(h, f);
  10076. upb_handlers_addcleanup(h, hd, free);
  10077. upb_handlerattr_sethandlerdata(attr, hd);
  10078. }
  10079. // Set up handlers for a mapentry submessage (i.e., an individual key/value pair
  10080. // in a map).
  10081. //
  10082. // TODO: Handle missing key, missing value, out-of-order key/value, or repeated
  10083. // key or value cases properly. The right way to do this is to allocate a
  10084. // temporary structure at the start of a mapentry submessage, store key and
  10085. // value data in it as key and value handlers are called, and then print the
  10086. // key/value pair once at the end of the submessage. If we don't do this, we
  10087. // should at least detect the case and throw an error. However, so far all of
  10088. // our sources that emit mapentry messages do so canonically (with one key
  10089. // field, and then one value field), so this is not a pressing concern at the
  10090. // moment.
  10091. void printer_sethandlers_mapentry(const void *closure, upb_handlers *h) {
  10092. UPB_UNUSED(closure);
  10093. const upb_msgdef *md = upb_handlers_msgdef(h);
  10094. // A mapentry message is printed simply as '"key": value'. Rather than
  10095. // special-case key and value for every type below, we just handle both
  10096. // fields explicitly here.
  10097. const upb_fielddef* key_field = upb_msgdef_itof(md, UPB_MAPENTRY_KEY);
  10098. const upb_fielddef* value_field = upb_msgdef_itof(md, UPB_MAPENTRY_VALUE);
  10099. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  10100. switch (upb_fielddef_type(key_field)) {
  10101. case UPB_TYPE_INT32:
  10102. upb_handlers_setint32(h, key_field, putmapkey_int32_t, &empty_attr);
  10103. break;
  10104. case UPB_TYPE_INT64:
  10105. upb_handlers_setint64(h, key_field, putmapkey_int64_t, &empty_attr);
  10106. break;
  10107. case UPB_TYPE_UINT32:
  10108. upb_handlers_setuint32(h, key_field, putmapkey_uint32_t, &empty_attr);
  10109. break;
  10110. case UPB_TYPE_UINT64:
  10111. upb_handlers_setuint64(h, key_field, putmapkey_uint64_t, &empty_attr);
  10112. break;
  10113. case UPB_TYPE_BOOL:
  10114. upb_handlers_setbool(h, key_field, putmapkey_bool, &empty_attr);
  10115. break;
  10116. case UPB_TYPE_STRING:
  10117. upb_handlers_setstartstr(h, key_field, mapkeyval_startstr, &empty_attr);
  10118. upb_handlers_setstring(h, key_field, mapkey_str, &empty_attr);
  10119. upb_handlers_setendstr(h, key_field, mapkey_endstr, &empty_attr);
  10120. break;
  10121. case UPB_TYPE_BYTES:
  10122. upb_handlers_setstring(h, key_field, mapkey_bytes, &empty_attr);
  10123. break;
  10124. default:
  10125. assert(false);
  10126. break;
  10127. }
  10128. switch (upb_fielddef_type(value_field)) {
  10129. case UPB_TYPE_INT32:
  10130. upb_handlers_setint32(h, value_field, putint32_t, &empty_attr);
  10131. break;
  10132. case UPB_TYPE_INT64:
  10133. upb_handlers_setint64(h, value_field, putint64_t, &empty_attr);
  10134. break;
  10135. case UPB_TYPE_UINT32:
  10136. upb_handlers_setuint32(h, value_field, putuint32_t, &empty_attr);
  10137. break;
  10138. case UPB_TYPE_UINT64:
  10139. upb_handlers_setuint64(h, value_field, putuint64_t, &empty_attr);
  10140. break;
  10141. case UPB_TYPE_BOOL:
  10142. upb_handlers_setbool(h, value_field, putbool, &empty_attr);
  10143. break;
  10144. case UPB_TYPE_FLOAT:
  10145. upb_handlers_setfloat(h, value_field, putfloat, &empty_attr);
  10146. break;
  10147. case UPB_TYPE_DOUBLE:
  10148. upb_handlers_setdouble(h, value_field, putdouble, &empty_attr);
  10149. break;
  10150. case UPB_TYPE_STRING:
  10151. upb_handlers_setstartstr(h, value_field, mapkeyval_startstr, &empty_attr);
  10152. upb_handlers_setstring(h, value_field, putstr, &empty_attr);
  10153. upb_handlers_setendstr(h, value_field, mapvalue_endstr, &empty_attr);
  10154. break;
  10155. case UPB_TYPE_BYTES:
  10156. upb_handlers_setstring(h, value_field, putbytes, &empty_attr);
  10157. break;
  10158. case UPB_TYPE_ENUM: {
  10159. upb_handlerattr enum_attr = UPB_HANDLERATTR_INITIALIZER;
  10160. set_enum_hd(h, value_field, &enum_attr);
  10161. upb_handlers_setint32(h, value_field, mapvalue_enum, &enum_attr);
  10162. upb_handlerattr_uninit(&enum_attr);
  10163. break;
  10164. }
  10165. case UPB_TYPE_MESSAGE:
  10166. // No handler necessary -- the submsg handlers will print the message
  10167. // as appropriate.
  10168. break;
  10169. }
  10170. upb_handlerattr_uninit(&empty_attr);
  10171. }
  10172. void printer_sethandlers(const void *closure, upb_handlers *h) {
  10173. UPB_UNUSED(closure);
  10174. const upb_msgdef *md = upb_handlers_msgdef(h);
  10175. bool is_mapentry = upb_msgdef_mapentry(md);
  10176. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  10177. if (is_mapentry) {
  10178. // mapentry messages are sufficiently different that we handle them
  10179. // separately.
  10180. printer_sethandlers_mapentry(closure, h);
  10181. return;
  10182. }
  10183. upb_handlers_setstartmsg(h, printer_startmsg, &empty_attr);
  10184. upb_handlers_setendmsg(h, printer_endmsg, &empty_attr);
  10185. #define TYPE(type, name, ctype) \
  10186. case type: \
  10187. if (upb_fielddef_isseq(f)) { \
  10188. upb_handlers_set##name(h, f, repeated_##ctype, &empty_attr); \
  10189. } else { \
  10190. upb_handlers_set##name(h, f, scalar_##ctype, &name_attr); \
  10191. } \
  10192. break;
  10193. upb_msg_field_iter i;
  10194. upb_msg_field_begin(&i, md);
  10195. for(; !upb_msg_field_done(&i); upb_msg_field_next(&i)) {
  10196. const upb_fielddef *f = upb_msg_iter_field(&i);
  10197. upb_handlerattr name_attr = UPB_HANDLERATTR_INITIALIZER;
  10198. upb_handlerattr_sethandlerdata(&name_attr, newstrpc(h, f));
  10199. if (upb_fielddef_ismap(f)) {
  10200. upb_handlers_setstartseq(h, f, startmap, &name_attr);
  10201. upb_handlers_setendseq(h, f, endmap, &name_attr);
  10202. } else if (upb_fielddef_isseq(f)) {
  10203. upb_handlers_setstartseq(h, f, startseq, &name_attr);
  10204. upb_handlers_setendseq(h, f, endseq, &empty_attr);
  10205. }
  10206. switch (upb_fielddef_type(f)) {
  10207. TYPE(UPB_TYPE_FLOAT, float, float);
  10208. TYPE(UPB_TYPE_DOUBLE, double, double);
  10209. TYPE(UPB_TYPE_BOOL, bool, bool);
  10210. TYPE(UPB_TYPE_INT32, int32, int32_t);
  10211. TYPE(UPB_TYPE_UINT32, uint32, uint32_t);
  10212. TYPE(UPB_TYPE_INT64, int64, int64_t);
  10213. TYPE(UPB_TYPE_UINT64, uint64, uint64_t);
  10214. case UPB_TYPE_ENUM: {
  10215. // For now, we always emit symbolic names for enums. We may want an
  10216. // option later to control this behavior, but we will wait for a real
  10217. // need first.
  10218. upb_handlerattr enum_attr = UPB_HANDLERATTR_INITIALIZER;
  10219. set_enum_hd(h, f, &enum_attr);
  10220. if (upb_fielddef_isseq(f)) {
  10221. upb_handlers_setint32(h, f, repeated_enum, &enum_attr);
  10222. } else {
  10223. upb_handlers_setint32(h, f, scalar_enum, &enum_attr);
  10224. }
  10225. upb_handlerattr_uninit(&enum_attr);
  10226. break;
  10227. }
  10228. case UPB_TYPE_STRING:
  10229. if (upb_fielddef_isseq(f)) {
  10230. upb_handlers_setstartstr(h, f, repeated_startstr, &empty_attr);
  10231. upb_handlers_setstring(h, f, repeated_str, &empty_attr);
  10232. upb_handlers_setendstr(h, f, repeated_endstr, &empty_attr);
  10233. } else {
  10234. upb_handlers_setstartstr(h, f, scalar_startstr, &name_attr);
  10235. upb_handlers_setstring(h, f, scalar_str, &empty_attr);
  10236. upb_handlers_setendstr(h, f, scalar_endstr, &empty_attr);
  10237. }
  10238. break;
  10239. case UPB_TYPE_BYTES:
  10240. // XXX: this doesn't support strings that span buffers yet. The base64
  10241. // encoder will need to be made resumable for this to work properly.
  10242. if (upb_fielddef_isseq(f)) {
  10243. upb_handlers_setstring(h, f, repeated_bytes, &empty_attr);
  10244. } else {
  10245. upb_handlers_setstring(h, f, scalar_bytes, &name_attr);
  10246. }
  10247. break;
  10248. case UPB_TYPE_MESSAGE:
  10249. if (upb_fielddef_isseq(f)) {
  10250. upb_handlers_setstartsubmsg(h, f, repeated_startsubmsg, &name_attr);
  10251. } else {
  10252. upb_handlers_setstartsubmsg(h, f, scalar_startsubmsg, &name_attr);
  10253. }
  10254. break;
  10255. }
  10256. upb_handlerattr_uninit(&name_attr);
  10257. }
  10258. upb_handlerattr_uninit(&empty_attr);
  10259. #undef TYPE
  10260. }
  10261. static void json_printer_reset(upb_json_printer *p) {
  10262. p->depth_ = 0;
  10263. }
  10264. /* Public API *****************************************************************/
  10265. upb_json_printer *upb_json_printer_create(upb_env *e, const upb_handlers *h,
  10266. upb_bytessink *output) {
  10267. #ifndef NDEBUG
  10268. size_t size_before = upb_env_bytesallocated(e);
  10269. #endif
  10270. upb_json_printer *p = upb_env_malloc(e, sizeof(upb_json_printer));
  10271. if (!p) return NULL;
  10272. p->output_ = output;
  10273. json_printer_reset(p);
  10274. upb_sink_reset(&p->input_, h, p);
  10275. // If this fails, increase the value in printer.h.
  10276. assert(upb_env_bytesallocated(e) - size_before <= UPB_JSON_PRINTER_SIZE);
  10277. return p;
  10278. }
  10279. upb_sink *upb_json_printer_input(upb_json_printer *p) {
  10280. return &p->input_;
  10281. }
  10282. const upb_handlers *upb_json_printer_newhandlers(const upb_msgdef *md,
  10283. const void *owner) {
  10284. return upb_handlers_newfrozen(md, owner, printer_sethandlers, NULL);
  10285. }