upb.c 337 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099
  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. return true;
  178. }
  179. static bool upb_validate_enumdef(const upb_enumdef *e, upb_status *s) {
  180. if (upb_enumdef_numvals(e) == 0) {
  181. upb_status_seterrf(s, "enum %s has no members (must have at least one)",
  182. upb_enumdef_fullname(e));
  183. return false;
  184. }
  185. return true;
  186. }
  187. // All submessage fields are lower than all other fields.
  188. // Secondly, fields are increasing in order.
  189. uint32_t field_rank(const upb_fielddef *f) {
  190. uint32_t ret = upb_fielddef_number(f);
  191. const uint32_t high_bit = 1 << 30;
  192. assert(ret < high_bit);
  193. if (!upb_fielddef_issubmsg(f))
  194. ret |= high_bit;
  195. return ret;
  196. }
  197. int cmp_fields(const void *p1, const void *p2) {
  198. const upb_fielddef *f1 = *(upb_fielddef*const*)p1;
  199. const upb_fielddef *f2 = *(upb_fielddef*const*)p2;
  200. return field_rank(f1) - field_rank(f2);
  201. }
  202. static bool assign_msg_indices(upb_msgdef *m, upb_status *s) {
  203. // Sort fields. upb internally relies on UPB_TYPE_MESSAGE fields having the
  204. // lowest indexes, but we do not publicly guarantee this.
  205. int n = upb_msgdef_numfields(m);
  206. upb_fielddef **fields = malloc(n * sizeof(*fields));
  207. if (!fields) return false;
  208. upb_msg_iter j;
  209. int i;
  210. m->submsg_field_count = 0;
  211. for(i = 0, upb_msg_begin(&j, m); !upb_msg_done(&j); upb_msg_next(&j), i++) {
  212. upb_fielddef *f = upb_msg_iter_field(&j);
  213. assert(f->msg.def == m);
  214. if (!upb_validate_field(f, s)) {
  215. free(fields);
  216. return false;
  217. }
  218. if (upb_fielddef_issubmsg(f)) {
  219. m->submsg_field_count++;
  220. }
  221. fields[i] = f;
  222. }
  223. qsort(fields, n, sizeof(*fields), cmp_fields);
  224. uint32_t selector = UPB_STATIC_SELECTOR_COUNT + m->submsg_field_count;
  225. for (i = 0; i < n; i++) {
  226. upb_fielddef *f = fields[i];
  227. f->index_ = i;
  228. f->selector_base = selector + upb_handlers_selectorbaseoffset(f);
  229. selector += upb_handlers_selectorcount(f);
  230. }
  231. m->selector_count = selector;
  232. #ifndef NDEBUG
  233. // Verify that all selectors for the message are distinct.
  234. //
  235. #define TRY(type) \
  236. if (upb_handlers_getselector(f, type, &sel)) upb_inttable_insert(&t, sel, v);
  237. upb_inttable t;
  238. upb_inttable_init(&t, UPB_CTYPE_BOOL);
  239. upb_value v = upb_value_bool(true);
  240. upb_selector_t sel;
  241. upb_inttable_insert(&t, UPB_STARTMSG_SELECTOR, v);
  242. upb_inttable_insert(&t, UPB_ENDMSG_SELECTOR, v);
  243. for(upb_msg_begin(&j, m); !upb_msg_done(&j); upb_msg_next(&j)) {
  244. upb_fielddef *f = upb_msg_iter_field(&j);
  245. // These calls will assert-fail in upb_table if the value already exists.
  246. TRY(UPB_HANDLER_INT32);
  247. TRY(UPB_HANDLER_INT64)
  248. TRY(UPB_HANDLER_UINT32)
  249. TRY(UPB_HANDLER_UINT64)
  250. TRY(UPB_HANDLER_FLOAT)
  251. TRY(UPB_HANDLER_DOUBLE)
  252. TRY(UPB_HANDLER_BOOL)
  253. TRY(UPB_HANDLER_STARTSTR)
  254. TRY(UPB_HANDLER_STRING)
  255. TRY(UPB_HANDLER_ENDSTR)
  256. TRY(UPB_HANDLER_STARTSUBMSG)
  257. TRY(UPB_HANDLER_ENDSUBMSG)
  258. TRY(UPB_HANDLER_STARTSEQ)
  259. TRY(UPB_HANDLER_ENDSEQ)
  260. }
  261. upb_inttable_uninit(&t);
  262. #undef TRY
  263. #endif
  264. free(fields);
  265. return true;
  266. }
  267. bool upb_def_freeze(upb_def *const* defs, int n, upb_status *s) {
  268. upb_status_clear(s);
  269. // First perform validation, in two passes so we can check that we have a
  270. // transitive closure without needing to search.
  271. for (int i = 0; i < n; i++) {
  272. upb_def *def = defs[i];
  273. if (upb_def_isfrozen(def)) {
  274. // Could relax this requirement if it's annoying.
  275. upb_status_seterrmsg(s, "def is already frozen");
  276. goto err;
  277. } else if (def->type == UPB_DEF_FIELD) {
  278. upb_status_seterrmsg(s, "standalone fielddefs can not be frozen");
  279. goto err;
  280. } else if (def->type == UPB_DEF_ENUM) {
  281. if (!upb_validate_enumdef(upb_dyncast_enumdef(def), s)) {
  282. goto err;
  283. }
  284. } else {
  285. // Set now to detect transitive closure in the second pass.
  286. def->came_from_user = true;
  287. }
  288. }
  289. // Second pass of validation. Also assign selector bases and indexes, and
  290. // compact tables.
  291. for (int i = 0; i < n; i++) {
  292. upb_msgdef *m = upb_dyncast_msgdef_mutable(defs[i]);
  293. upb_enumdef *e = upb_dyncast_enumdef_mutable(defs[i]);
  294. if (m) {
  295. upb_inttable_compact(&m->itof);
  296. if (!assign_msg_indices(m, s)) {
  297. goto err;
  298. }
  299. } else if (e) {
  300. upb_inttable_compact(&e->iton);
  301. }
  302. }
  303. // Def graph contains FieldDefs between each MessageDef, so double the limit.
  304. int maxdepth = UPB_MAX_MESSAGE_DEPTH * 2;
  305. // Validation all passed; freeze the defs.
  306. bool ret =
  307. upb_refcounted_freeze((upb_refcounted * const *)defs, n, s, maxdepth);
  308. assert(!(s && ret != upb_ok(s)));
  309. return ret;
  310. err:
  311. for (int i = 0; i < n; i++) {
  312. defs[i]->came_from_user = false;
  313. }
  314. assert(!(s && upb_ok(s)));
  315. return false;
  316. }
  317. /* upb_enumdef ****************************************************************/
  318. static void upb_enumdef_free(upb_refcounted *r) {
  319. upb_enumdef *e = (upb_enumdef*)r;
  320. upb_inttable_iter i;
  321. upb_inttable_begin(&i, &e->iton);
  322. for( ; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  323. // To clean up the upb_strdup() from upb_enumdef_addval().
  324. free(upb_value_getcstr(upb_inttable_iter_value(&i)));
  325. }
  326. upb_strtable_uninit(&e->ntoi);
  327. upb_inttable_uninit(&e->iton);
  328. upb_def_uninit(UPB_UPCAST(e));
  329. free(e);
  330. }
  331. upb_enumdef *upb_enumdef_new(const void *owner) {
  332. static const struct upb_refcounted_vtbl vtbl = {NULL, &upb_enumdef_free};
  333. upb_enumdef *e = malloc(sizeof(*e));
  334. if (!e) return NULL;
  335. if (!upb_def_init(UPB_UPCAST(e), UPB_DEF_ENUM, &vtbl, owner)) goto err2;
  336. if (!upb_strtable_init(&e->ntoi, UPB_CTYPE_INT32)) goto err2;
  337. if (!upb_inttable_init(&e->iton, UPB_CTYPE_CSTR)) goto err1;
  338. return e;
  339. err1:
  340. upb_strtable_uninit(&e->ntoi);
  341. err2:
  342. free(e);
  343. return NULL;
  344. }
  345. upb_enumdef *upb_enumdef_dup(const upb_enumdef *e, const void *owner) {
  346. upb_enumdef *new_e = upb_enumdef_new(owner);
  347. if (!new_e) return NULL;
  348. upb_enum_iter i;
  349. for(upb_enum_begin(&i, e); !upb_enum_done(&i); upb_enum_next(&i)) {
  350. bool success = upb_enumdef_addval(
  351. new_e, upb_enum_iter_name(&i),upb_enum_iter_number(&i), NULL);
  352. if (!success) {
  353. upb_enumdef_unref(new_e, owner);
  354. return NULL;
  355. }
  356. }
  357. return new_e;
  358. }
  359. bool upb_enumdef_isfrozen(const upb_enumdef *e) {
  360. return upb_def_isfrozen(UPB_UPCAST(e));
  361. }
  362. void upb_enumdef_ref(const upb_enumdef *e, const void *owner) {
  363. upb_def_ref(UPB_UPCAST(e), owner);
  364. }
  365. void upb_enumdef_unref(const upb_enumdef *e, const void *owner) {
  366. upb_def_unref(UPB_UPCAST(e), owner);
  367. }
  368. void upb_enumdef_donateref(
  369. const upb_enumdef *e, const void *from, const void *to) {
  370. upb_def_donateref(UPB_UPCAST(e), from, to);
  371. }
  372. void upb_enumdef_checkref(const upb_enumdef *e, const void *owner) {
  373. upb_def_checkref(UPB_UPCAST(e), owner);
  374. }
  375. bool upb_enumdef_freeze(upb_enumdef *e, upb_status *status) {
  376. upb_def *d = UPB_UPCAST(e);
  377. return upb_def_freeze(&d, 1, status);
  378. }
  379. const char *upb_enumdef_fullname(const upb_enumdef *e) {
  380. return upb_def_fullname(UPB_UPCAST(e));
  381. }
  382. bool upb_enumdef_setfullname(upb_enumdef *e, const char *fullname,
  383. upb_status *s) {
  384. return upb_def_setfullname(UPB_UPCAST(e), fullname, s);
  385. }
  386. bool upb_enumdef_addval(upb_enumdef *e, const char *name, int32_t num,
  387. upb_status *status) {
  388. if (!upb_isident(name, strlen(name), false, status)) {
  389. return false;
  390. }
  391. if (upb_enumdef_ntoiz(e, name, NULL)) {
  392. upb_status_seterrf(status, "name '%s' is already defined", name);
  393. return false;
  394. }
  395. if (!upb_strtable_insert(&e->ntoi, name, upb_value_int32(num))) {
  396. upb_status_seterrmsg(status, "out of memory");
  397. return false;
  398. }
  399. if (!upb_inttable_lookup(&e->iton, num, NULL) &&
  400. !upb_inttable_insert(&e->iton, num, upb_value_cstr(upb_strdup(name)))) {
  401. upb_status_seterrmsg(status, "out of memory");
  402. upb_strtable_remove(&e->ntoi, name, NULL);
  403. return false;
  404. }
  405. if (upb_enumdef_numvals(e) == 1) {
  406. bool ok = upb_enumdef_setdefault(e, num, NULL);
  407. UPB_ASSERT_VAR(ok, ok);
  408. }
  409. return true;
  410. }
  411. int32_t upb_enumdef_default(const upb_enumdef *e) {
  412. assert(upb_enumdef_iton(e, e->defaultval));
  413. return e->defaultval;
  414. }
  415. bool upb_enumdef_setdefault(upb_enumdef *e, int32_t val, upb_status *s) {
  416. assert(!upb_enumdef_isfrozen(e));
  417. if (!upb_enumdef_iton(e, val)) {
  418. upb_status_seterrf(s, "number '%d' is not in the enum.", val);
  419. return false;
  420. }
  421. e->defaultval = val;
  422. return true;
  423. }
  424. int upb_enumdef_numvals(const upb_enumdef *e) {
  425. return upb_strtable_count(&e->ntoi);
  426. }
  427. void upb_enum_begin(upb_enum_iter *i, const upb_enumdef *e) {
  428. // We iterate over the ntoi table, to account for duplicate numbers.
  429. upb_strtable_begin(i, &e->ntoi);
  430. }
  431. void upb_enum_next(upb_enum_iter *iter) { upb_strtable_next(iter); }
  432. bool upb_enum_done(upb_enum_iter *iter) { return upb_strtable_done(iter); }
  433. bool upb_enumdef_ntoi(const upb_enumdef *def, const char *name,
  434. size_t len, int32_t *num) {
  435. upb_value v;
  436. if (!upb_strtable_lookup2(&def->ntoi, name, len, &v)) {
  437. return false;
  438. }
  439. if (num) *num = upb_value_getint32(v);
  440. return true;
  441. }
  442. const char *upb_enumdef_iton(const upb_enumdef *def, int32_t num) {
  443. upb_value v;
  444. return upb_inttable_lookup32(&def->iton, num, &v) ?
  445. upb_value_getcstr(v) : NULL;
  446. }
  447. const char *upb_enum_iter_name(upb_enum_iter *iter) {
  448. return upb_strtable_iter_key(iter);
  449. }
  450. int32_t upb_enum_iter_number(upb_enum_iter *iter) {
  451. return upb_value_getint32(upb_strtable_iter_value(iter));
  452. }
  453. /* upb_fielddef ***************************************************************/
  454. static void upb_fielddef_init_default(upb_fielddef *f);
  455. static void upb_fielddef_uninit_default(upb_fielddef *f) {
  456. if (f->type_is_set_ && f->default_is_string && f->defaultval.bytes)
  457. freestr(f->defaultval.bytes);
  458. }
  459. static void visitfield(const upb_refcounted *r, upb_refcounted_visit *visit,
  460. void *closure) {
  461. const upb_fielddef *f = (const upb_fielddef*)r;
  462. if (upb_fielddef_containingtype(f)) {
  463. visit(r, UPB_UPCAST2(upb_fielddef_containingtype(f)), closure);
  464. }
  465. if (upb_fielddef_subdef(f)) {
  466. visit(r, UPB_UPCAST(upb_fielddef_subdef(f)), closure);
  467. }
  468. }
  469. static void freefield(upb_refcounted *r) {
  470. upb_fielddef *f = (upb_fielddef*)r;
  471. upb_fielddef_uninit_default(f);
  472. if (f->subdef_is_symbolic)
  473. free(f->sub.name);
  474. upb_def_uninit(UPB_UPCAST(f));
  475. free(f);
  476. }
  477. static const char *enumdefaultstr(const upb_fielddef *f) {
  478. assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  479. const upb_enumdef *e = upb_fielddef_enumsubdef(f);
  480. if (f->default_is_string && f->defaultval.bytes) {
  481. // Default was explicitly set as a string.
  482. str_t *s = f->defaultval.bytes;
  483. return s->str;
  484. } else if (e) {
  485. if (!f->default_is_string) {
  486. // Default was explicitly set as an integer; look it up in enumdef.
  487. const char *name = upb_enumdef_iton(e, f->defaultval.sint);
  488. if (name) {
  489. return name;
  490. }
  491. } else {
  492. // Default is completely unset; pull enumdef default.
  493. if (upb_enumdef_numvals(e) > 0) {
  494. const char *name = upb_enumdef_iton(e, upb_enumdef_default(e));
  495. assert(name);
  496. return name;
  497. }
  498. }
  499. }
  500. return NULL;
  501. }
  502. static bool enumdefaultint32(const upb_fielddef *f, int32_t *val) {
  503. assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  504. const upb_enumdef *e = upb_fielddef_enumsubdef(f);
  505. if (!f->default_is_string) {
  506. // Default was explicitly set as an integer.
  507. *val = f->defaultval.sint;
  508. return true;
  509. } else if (e) {
  510. if (f->defaultval.bytes) {
  511. // Default was explicitly set as a str; try to lookup corresponding int.
  512. str_t *s = f->defaultval.bytes;
  513. if (upb_enumdef_ntoiz(e, s->str, val)) {
  514. return true;
  515. }
  516. } else {
  517. // Default is unset; try to pull in enumdef default.
  518. if (upb_enumdef_numvals(e) > 0) {
  519. *val = upb_enumdef_default(e);
  520. return true;
  521. }
  522. }
  523. }
  524. return false;
  525. }
  526. upb_fielddef *upb_fielddef_new(const void *owner) {
  527. static const struct upb_refcounted_vtbl vtbl = {visitfield, freefield};
  528. upb_fielddef *f = malloc(sizeof(*f));
  529. if (!f) return NULL;
  530. if (!upb_def_init(UPB_UPCAST(f), UPB_DEF_FIELD, &vtbl, owner)) {
  531. free(f);
  532. return NULL;
  533. }
  534. f->msg.def = NULL;
  535. f->sub.def = NULL;
  536. f->subdef_is_symbolic = false;
  537. f->msg_is_symbolic = false;
  538. f->label_ = UPB_LABEL_OPTIONAL;
  539. f->type_ = UPB_TYPE_INT32;
  540. f->number_ = 0;
  541. f->type_is_set_ = false;
  542. f->tagdelim = false;
  543. f->is_extension_ = false;
  544. f->lazy_ = false;
  545. f->packed_ = true;
  546. // For the moment we default this to UPB_INTFMT_VARIABLE, since it will work
  547. // with all integer types and is in some since more "default" since the most
  548. // normal-looking proto2 types int32/int64/uint32/uint64 use variable.
  549. //
  550. // Other options to consider:
  551. // - there is no default; users must set this manually (like type).
  552. // - default signed integers to UPB_INTFMT_ZIGZAG, since it's more likely to
  553. // be an optimal default for signed integers.
  554. f->intfmt = UPB_INTFMT_VARIABLE;
  555. return f;
  556. }
  557. upb_fielddef *upb_fielddef_dup(const upb_fielddef *f, const void *owner) {
  558. upb_fielddef *newf = upb_fielddef_new(owner);
  559. if (!newf) return NULL;
  560. upb_fielddef_settype(newf, upb_fielddef_type(f));
  561. upb_fielddef_setlabel(newf, upb_fielddef_label(f));
  562. upb_fielddef_setnumber(newf, upb_fielddef_number(f), NULL);
  563. upb_fielddef_setname(newf, upb_fielddef_name(f), NULL);
  564. if (f->default_is_string && f->defaultval.bytes) {
  565. str_t *s = f->defaultval.bytes;
  566. upb_fielddef_setdefaultstr(newf, s->str, s->len, NULL);
  567. } else {
  568. newf->default_is_string = f->default_is_string;
  569. newf->defaultval = f->defaultval;
  570. }
  571. const char *srcname;
  572. if (f->subdef_is_symbolic) {
  573. srcname = f->sub.name; // Might be NULL.
  574. } else {
  575. srcname = f->sub.def ? upb_def_fullname(f->sub.def) : NULL;
  576. }
  577. if (srcname) {
  578. char *newname = malloc(strlen(f->sub.def->fullname) + 2);
  579. if (!newname) {
  580. upb_fielddef_unref(newf, owner);
  581. return NULL;
  582. }
  583. strcpy(newname, ".");
  584. strcat(newname, f->sub.def->fullname);
  585. upb_fielddef_setsubdefname(newf, newname, NULL);
  586. free(newname);
  587. }
  588. return newf;
  589. }
  590. bool upb_fielddef_isfrozen(const upb_fielddef *f) {
  591. return upb_def_isfrozen(UPB_UPCAST(f));
  592. }
  593. void upb_fielddef_ref(const upb_fielddef *f, const void *owner) {
  594. upb_def_ref(UPB_UPCAST(f), owner);
  595. }
  596. void upb_fielddef_unref(const upb_fielddef *f, const void *owner) {
  597. upb_def_unref(UPB_UPCAST(f), owner);
  598. }
  599. void upb_fielddef_donateref(
  600. const upb_fielddef *f, const void *from, const void *to) {
  601. upb_def_donateref(UPB_UPCAST(f), from, to);
  602. }
  603. void upb_fielddef_checkref(const upb_fielddef *f, const void *owner) {
  604. upb_def_checkref(UPB_UPCAST(f), owner);
  605. }
  606. bool upb_fielddef_typeisset(const upb_fielddef *f) {
  607. return f->type_is_set_;
  608. }
  609. upb_fieldtype_t upb_fielddef_type(const upb_fielddef *f) {
  610. assert(f->type_is_set_);
  611. return f->type_;
  612. }
  613. uint32_t upb_fielddef_index(const upb_fielddef *f) {
  614. return f->index_;
  615. }
  616. upb_label_t upb_fielddef_label(const upb_fielddef *f) {
  617. return f->label_;
  618. }
  619. upb_intfmt_t upb_fielddef_intfmt(const upb_fielddef *f) {
  620. return f->intfmt;
  621. }
  622. bool upb_fielddef_istagdelim(const upb_fielddef *f) {
  623. return f->tagdelim;
  624. }
  625. uint32_t upb_fielddef_number(const upb_fielddef *f) {
  626. return f->number_;
  627. }
  628. bool upb_fielddef_isextension(const upb_fielddef *f) {
  629. return f->is_extension_;
  630. }
  631. bool upb_fielddef_lazy(const upb_fielddef *f) {
  632. return f->lazy_;
  633. }
  634. bool upb_fielddef_packed(const upb_fielddef *f) {
  635. return f->packed_;
  636. }
  637. const char *upb_fielddef_name(const upb_fielddef *f) {
  638. return upb_def_fullname(UPB_UPCAST(f));
  639. }
  640. const upb_msgdef *upb_fielddef_containingtype(const upb_fielddef *f) {
  641. return f->msg_is_symbolic ? NULL : f->msg.def;
  642. }
  643. upb_msgdef *upb_fielddef_containingtype_mutable(upb_fielddef *f) {
  644. return (upb_msgdef*)upb_fielddef_containingtype(f);
  645. }
  646. const char *upb_fielddef_containingtypename(upb_fielddef *f) {
  647. return f->msg_is_symbolic ? f->msg.name : NULL;
  648. }
  649. static void release_containingtype(upb_fielddef *f) {
  650. if (f->msg_is_symbolic) free(f->msg.name);
  651. }
  652. bool upb_fielddef_setcontainingtypename(upb_fielddef *f, const char *name,
  653. upb_status *s) {
  654. assert(!upb_fielddef_isfrozen(f));
  655. if (upb_fielddef_containingtype(f)) {
  656. upb_status_seterrmsg(s, "field has already been added to a message.");
  657. return false;
  658. }
  659. // TODO: validate name (upb_isident() doesn't quite work atm because this name
  660. // may have a leading ".").
  661. release_containingtype(f);
  662. f->msg.name = upb_strdup(name);
  663. f->msg_is_symbolic = true;
  664. return true;
  665. }
  666. bool upb_fielddef_setname(upb_fielddef *f, const char *name, upb_status *s) {
  667. return upb_def_setfullname(UPB_UPCAST(f), name, s);
  668. }
  669. static void chkdefaulttype(const upb_fielddef *f, upb_fieldtype_t type) {
  670. UPB_UNUSED(f);
  671. UPB_UNUSED(type);
  672. assert(f->type_is_set_ && upb_fielddef_type(f) == type);
  673. }
  674. int64_t upb_fielddef_defaultint64(const upb_fielddef *f) {
  675. chkdefaulttype(f, UPB_TYPE_INT64);
  676. return f->defaultval.sint;
  677. }
  678. int32_t upb_fielddef_defaultint32(const upb_fielddef *f) {
  679. if (f->type_is_set_ && upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  680. int32_t val;
  681. bool ok = enumdefaultint32(f, &val);
  682. UPB_ASSERT_VAR(ok, ok);
  683. return val;
  684. } else {
  685. chkdefaulttype(f, UPB_TYPE_INT32);
  686. return f->defaultval.sint;
  687. }
  688. }
  689. uint64_t upb_fielddef_defaultuint64(const upb_fielddef *f) {
  690. chkdefaulttype(f, UPB_TYPE_UINT64);
  691. return f->defaultval.uint;
  692. }
  693. uint32_t upb_fielddef_defaultuint32(const upb_fielddef *f) {
  694. chkdefaulttype(f, UPB_TYPE_UINT32);
  695. return f->defaultval.uint;
  696. }
  697. bool upb_fielddef_defaultbool(const upb_fielddef *f) {
  698. chkdefaulttype(f, UPB_TYPE_BOOL);
  699. return f->defaultval.uint;
  700. }
  701. float upb_fielddef_defaultfloat(const upb_fielddef *f) {
  702. chkdefaulttype(f, UPB_TYPE_FLOAT);
  703. return f->defaultval.flt;
  704. }
  705. double upb_fielddef_defaultdouble(const upb_fielddef *f) {
  706. chkdefaulttype(f, UPB_TYPE_DOUBLE);
  707. return f->defaultval.dbl;
  708. }
  709. const char *upb_fielddef_defaultstr(const upb_fielddef *f, size_t *len) {
  710. assert(f->type_is_set_);
  711. assert(upb_fielddef_type(f) == UPB_TYPE_STRING ||
  712. upb_fielddef_type(f) == UPB_TYPE_BYTES ||
  713. upb_fielddef_type(f) == UPB_TYPE_ENUM);
  714. if (upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  715. const char *ret = enumdefaultstr(f);
  716. assert(ret);
  717. // Enum defaults can't have embedded NULLs.
  718. if (len) *len = strlen(ret);
  719. return ret;
  720. }
  721. if (f->default_is_string) {
  722. str_t *str = f->defaultval.bytes;
  723. if (len) *len = str->len;
  724. return str->str;
  725. }
  726. return NULL;
  727. }
  728. static void upb_fielddef_init_default(upb_fielddef *f) {
  729. f->default_is_string = false;
  730. switch (upb_fielddef_type(f)) {
  731. case UPB_TYPE_DOUBLE: f->defaultval.dbl = 0; break;
  732. case UPB_TYPE_FLOAT: f->defaultval.flt = 0; break;
  733. case UPB_TYPE_INT32:
  734. case UPB_TYPE_INT64: f->defaultval.sint = 0; break;
  735. case UPB_TYPE_UINT64:
  736. case UPB_TYPE_UINT32:
  737. case UPB_TYPE_BOOL: f->defaultval.uint = 0; break;
  738. case UPB_TYPE_STRING:
  739. case UPB_TYPE_BYTES:
  740. f->defaultval.bytes = newstr("", 0);
  741. f->default_is_string = true;
  742. break;
  743. case UPB_TYPE_MESSAGE: break;
  744. case UPB_TYPE_ENUM:
  745. // This is our special sentinel that indicates "not set" for an enum.
  746. f->default_is_string = true;
  747. f->defaultval.bytes = NULL;
  748. break;
  749. }
  750. }
  751. const upb_def *upb_fielddef_subdef(const upb_fielddef *f) {
  752. return f->subdef_is_symbolic ? NULL : f->sub.def;
  753. }
  754. const upb_msgdef *upb_fielddef_msgsubdef(const upb_fielddef *f) {
  755. const upb_def *def = upb_fielddef_subdef(f);
  756. return def ? upb_dyncast_msgdef(def) : NULL;
  757. }
  758. const upb_enumdef *upb_fielddef_enumsubdef(const upb_fielddef *f) {
  759. const upb_def *def = upb_fielddef_subdef(f);
  760. return def ? upb_dyncast_enumdef(def) : NULL;
  761. }
  762. upb_def *upb_fielddef_subdef_mutable(upb_fielddef *f) {
  763. return (upb_def*)upb_fielddef_subdef(f);
  764. }
  765. const char *upb_fielddef_subdefname(const upb_fielddef *f) {
  766. if (f->subdef_is_symbolic) {
  767. return f->sub.name;
  768. } else if (f->sub.def) {
  769. return upb_def_fullname(f->sub.def);
  770. } else {
  771. return NULL;
  772. }
  773. }
  774. bool upb_fielddef_setnumber(upb_fielddef *f, uint32_t number, upb_status *s) {
  775. if (upb_fielddef_containingtype(f)) {
  776. upb_status_seterrmsg(
  777. s, "cannot change field number after adding to a message");
  778. return false;
  779. }
  780. if (number == 0 || number > UPB_MAX_FIELDNUMBER) {
  781. upb_status_seterrf(s, "invalid field number (%u)", number);
  782. return false;
  783. }
  784. f->number_ = number;
  785. return true;
  786. }
  787. void upb_fielddef_settype(upb_fielddef *f, upb_fieldtype_t type) {
  788. assert(!upb_fielddef_isfrozen(f));
  789. assert(upb_fielddef_checktype(type));
  790. upb_fielddef_uninit_default(f);
  791. f->type_ = type;
  792. f->type_is_set_ = true;
  793. upb_fielddef_init_default(f);
  794. }
  795. void upb_fielddef_setdescriptortype(upb_fielddef *f, int type) {
  796. assert(!upb_fielddef_isfrozen(f));
  797. switch (type) {
  798. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  799. upb_fielddef_settype(f, UPB_TYPE_DOUBLE);
  800. break;
  801. case UPB_DESCRIPTOR_TYPE_FLOAT:
  802. upb_fielddef_settype(f, UPB_TYPE_FLOAT);
  803. break;
  804. case UPB_DESCRIPTOR_TYPE_INT64:
  805. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  806. case UPB_DESCRIPTOR_TYPE_SINT64:
  807. upb_fielddef_settype(f, UPB_TYPE_INT64);
  808. break;
  809. case UPB_DESCRIPTOR_TYPE_UINT64:
  810. case UPB_DESCRIPTOR_TYPE_FIXED64:
  811. upb_fielddef_settype(f, UPB_TYPE_UINT64);
  812. break;
  813. case UPB_DESCRIPTOR_TYPE_INT32:
  814. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  815. case UPB_DESCRIPTOR_TYPE_SINT32:
  816. upb_fielddef_settype(f, UPB_TYPE_INT32);
  817. break;
  818. case UPB_DESCRIPTOR_TYPE_UINT32:
  819. case UPB_DESCRIPTOR_TYPE_FIXED32:
  820. upb_fielddef_settype(f, UPB_TYPE_UINT32);
  821. break;
  822. case UPB_DESCRIPTOR_TYPE_BOOL:
  823. upb_fielddef_settype(f, UPB_TYPE_BOOL);
  824. break;
  825. case UPB_DESCRIPTOR_TYPE_STRING:
  826. upb_fielddef_settype(f, UPB_TYPE_STRING);
  827. break;
  828. case UPB_DESCRIPTOR_TYPE_BYTES:
  829. upb_fielddef_settype(f, UPB_TYPE_BYTES);
  830. break;
  831. case UPB_DESCRIPTOR_TYPE_GROUP:
  832. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  833. upb_fielddef_settype(f, UPB_TYPE_MESSAGE);
  834. break;
  835. case UPB_DESCRIPTOR_TYPE_ENUM:
  836. upb_fielddef_settype(f, UPB_TYPE_ENUM);
  837. break;
  838. default: assert(false);
  839. }
  840. if (type == UPB_DESCRIPTOR_TYPE_FIXED64 ||
  841. type == UPB_DESCRIPTOR_TYPE_FIXED32 ||
  842. type == UPB_DESCRIPTOR_TYPE_SFIXED64 ||
  843. type == UPB_DESCRIPTOR_TYPE_SFIXED32) {
  844. upb_fielddef_setintfmt(f, UPB_INTFMT_FIXED);
  845. } else if (type == UPB_DESCRIPTOR_TYPE_SINT64 ||
  846. type == UPB_DESCRIPTOR_TYPE_SINT32) {
  847. upb_fielddef_setintfmt(f, UPB_INTFMT_ZIGZAG);
  848. } else {
  849. upb_fielddef_setintfmt(f, UPB_INTFMT_VARIABLE);
  850. }
  851. upb_fielddef_settagdelim(f, type == UPB_DESCRIPTOR_TYPE_GROUP);
  852. }
  853. upb_descriptortype_t upb_fielddef_descriptortype(const upb_fielddef *f) {
  854. switch (upb_fielddef_type(f)) {
  855. case UPB_TYPE_FLOAT: return UPB_DESCRIPTOR_TYPE_FLOAT;
  856. case UPB_TYPE_DOUBLE: return UPB_DESCRIPTOR_TYPE_DOUBLE;
  857. case UPB_TYPE_BOOL: return UPB_DESCRIPTOR_TYPE_BOOL;
  858. case UPB_TYPE_STRING: return UPB_DESCRIPTOR_TYPE_STRING;
  859. case UPB_TYPE_BYTES: return UPB_DESCRIPTOR_TYPE_BYTES;
  860. case UPB_TYPE_ENUM: return UPB_DESCRIPTOR_TYPE_ENUM;
  861. case UPB_TYPE_INT32:
  862. switch (upb_fielddef_intfmt(f)) {
  863. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_INT32;
  864. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_SFIXED32;
  865. case UPB_INTFMT_ZIGZAG: return UPB_DESCRIPTOR_TYPE_SINT32;
  866. }
  867. case UPB_TYPE_INT64:
  868. switch (upb_fielddef_intfmt(f)) {
  869. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_INT64;
  870. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_SFIXED64;
  871. case UPB_INTFMT_ZIGZAG: return UPB_DESCRIPTOR_TYPE_SINT64;
  872. }
  873. case UPB_TYPE_UINT32:
  874. switch (upb_fielddef_intfmt(f)) {
  875. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_UINT32;
  876. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_FIXED32;
  877. case UPB_INTFMT_ZIGZAG: return -1;
  878. }
  879. case UPB_TYPE_UINT64:
  880. switch (upb_fielddef_intfmt(f)) {
  881. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_UINT64;
  882. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_FIXED64;
  883. case UPB_INTFMT_ZIGZAG: return -1;
  884. }
  885. case UPB_TYPE_MESSAGE:
  886. return upb_fielddef_istagdelim(f) ?
  887. UPB_DESCRIPTOR_TYPE_GROUP : UPB_DESCRIPTOR_TYPE_MESSAGE;
  888. }
  889. return 0;
  890. }
  891. void upb_fielddef_setisextension(upb_fielddef *f, bool is_extension) {
  892. assert(!upb_fielddef_isfrozen(f));
  893. f->is_extension_ = is_extension;
  894. }
  895. void upb_fielddef_setlazy(upb_fielddef *f, bool lazy) {
  896. assert(!upb_fielddef_isfrozen(f));
  897. f->lazy_ = lazy;
  898. }
  899. void upb_fielddef_setpacked(upb_fielddef *f, bool packed) {
  900. assert(!upb_fielddef_isfrozen(f));
  901. f->packed_ = packed;
  902. }
  903. void upb_fielddef_setlabel(upb_fielddef *f, upb_label_t label) {
  904. assert(!upb_fielddef_isfrozen(f));
  905. assert(upb_fielddef_checklabel(label));
  906. f->label_ = label;
  907. }
  908. void upb_fielddef_setintfmt(upb_fielddef *f, upb_intfmt_t fmt) {
  909. assert(!upb_fielddef_isfrozen(f));
  910. assert(upb_fielddef_checkintfmt(fmt));
  911. f->intfmt = fmt;
  912. }
  913. void upb_fielddef_settagdelim(upb_fielddef *f, bool tag_delim) {
  914. assert(!upb_fielddef_isfrozen(f));
  915. f->tagdelim = tag_delim;
  916. f->tagdelim = tag_delim;
  917. }
  918. static bool checksetdefault(upb_fielddef *f, upb_fieldtype_t type) {
  919. if (!f->type_is_set_ || upb_fielddef_isfrozen(f) ||
  920. upb_fielddef_type(f) != type) {
  921. assert(false);
  922. return false;
  923. }
  924. if (f->default_is_string) {
  925. str_t *s = f->defaultval.bytes;
  926. assert(s || type == UPB_TYPE_ENUM);
  927. if (s) freestr(s);
  928. }
  929. f->default_is_string = false;
  930. return true;
  931. }
  932. void upb_fielddef_setdefaultint64(upb_fielddef *f, int64_t value) {
  933. if (checksetdefault(f, UPB_TYPE_INT64))
  934. f->defaultval.sint = value;
  935. }
  936. void upb_fielddef_setdefaultint32(upb_fielddef *f, int32_t value) {
  937. if ((upb_fielddef_type(f) == UPB_TYPE_ENUM &&
  938. checksetdefault(f, UPB_TYPE_ENUM)) ||
  939. checksetdefault(f, UPB_TYPE_INT32)) {
  940. f->defaultval.sint = value;
  941. }
  942. }
  943. void upb_fielddef_setdefaultuint64(upb_fielddef *f, uint64_t value) {
  944. if (checksetdefault(f, UPB_TYPE_UINT64))
  945. f->defaultval.uint = value;
  946. }
  947. void upb_fielddef_setdefaultuint32(upb_fielddef *f, uint32_t value) {
  948. if (checksetdefault(f, UPB_TYPE_UINT32))
  949. f->defaultval.uint = value;
  950. }
  951. void upb_fielddef_setdefaultbool(upb_fielddef *f, bool value) {
  952. if (checksetdefault(f, UPB_TYPE_BOOL))
  953. f->defaultval.uint = value;
  954. }
  955. void upb_fielddef_setdefaultfloat(upb_fielddef *f, float value) {
  956. if (checksetdefault(f, UPB_TYPE_FLOAT))
  957. f->defaultval.flt = value;
  958. }
  959. void upb_fielddef_setdefaultdouble(upb_fielddef *f, double value) {
  960. if (checksetdefault(f, UPB_TYPE_DOUBLE))
  961. f->defaultval.dbl = value;
  962. }
  963. bool upb_fielddef_setdefaultstr(upb_fielddef *f, const void *str, size_t len,
  964. upb_status *s) {
  965. assert(upb_fielddef_isstring(f) || f->type_ == UPB_TYPE_ENUM);
  966. if (f->type_ == UPB_TYPE_ENUM && !upb_isident(str, len, false, s))
  967. return false;
  968. if (f->default_is_string) {
  969. str_t *s = f->defaultval.bytes;
  970. assert(s || f->type_ == UPB_TYPE_ENUM);
  971. if (s) freestr(s);
  972. } else {
  973. assert(f->type_ == UPB_TYPE_ENUM);
  974. }
  975. str_t *str2 = newstr(str, len);
  976. f->defaultval.bytes = str2;
  977. f->default_is_string = true;
  978. return true;
  979. }
  980. void upb_fielddef_setdefaultcstr(upb_fielddef *f, const char *str,
  981. upb_status *s) {
  982. assert(f->type_is_set_);
  983. upb_fielddef_setdefaultstr(f, str, str ? strlen(str) : 0, s);
  984. }
  985. bool upb_fielddef_enumhasdefaultint32(const upb_fielddef *f) {
  986. assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  987. int32_t val;
  988. return enumdefaultint32(f, &val);
  989. }
  990. bool upb_fielddef_enumhasdefaultstr(const upb_fielddef *f) {
  991. assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  992. return enumdefaultstr(f) != NULL;
  993. }
  994. static bool upb_subdef_typecheck(upb_fielddef *f, const upb_def *subdef,
  995. upb_status *s) {
  996. if (f->type_ == UPB_TYPE_MESSAGE) {
  997. if (upb_dyncast_msgdef(subdef)) return true;
  998. upb_status_seterrmsg(s, "invalid subdef type for this submessage field");
  999. return false;
  1000. } else if (f->type_ == UPB_TYPE_ENUM) {
  1001. if (upb_dyncast_enumdef(subdef)) return true;
  1002. upb_status_seterrmsg(s, "invalid subdef type for this enum field");
  1003. return false;
  1004. } else {
  1005. upb_status_seterrmsg(s, "only message and enum fields can have a subdef");
  1006. return false;
  1007. }
  1008. }
  1009. static void release_subdef(upb_fielddef *f) {
  1010. if (f->subdef_is_symbolic) {
  1011. free(f->sub.name);
  1012. } else if (f->sub.def) {
  1013. upb_unref2(f->sub.def, f);
  1014. }
  1015. }
  1016. bool upb_fielddef_setsubdef(upb_fielddef *f, const upb_def *subdef,
  1017. upb_status *s) {
  1018. assert(!upb_fielddef_isfrozen(f));
  1019. assert(upb_fielddef_hassubdef(f));
  1020. if (subdef && !upb_subdef_typecheck(f, subdef, s)) return false;
  1021. release_subdef(f);
  1022. f->sub.def = subdef;
  1023. f->subdef_is_symbolic = false;
  1024. if (f->sub.def) upb_ref2(f->sub.def, f);
  1025. return true;
  1026. }
  1027. bool upb_fielddef_setmsgsubdef(upb_fielddef *f, const upb_msgdef *subdef,
  1028. upb_status *s) {
  1029. return upb_fielddef_setsubdef(f, UPB_UPCAST(subdef), s);
  1030. }
  1031. bool upb_fielddef_setenumsubdef(upb_fielddef *f, const upb_enumdef *subdef,
  1032. upb_status *s) {
  1033. return upb_fielddef_setsubdef(f, UPB_UPCAST(subdef), s);
  1034. }
  1035. bool upb_fielddef_setsubdefname(upb_fielddef *f, const char *name,
  1036. upb_status *s) {
  1037. assert(!upb_fielddef_isfrozen(f));
  1038. if (!upb_fielddef_hassubdef(f)) {
  1039. upb_status_seterrmsg(s, "field type does not accept a subdef");
  1040. return false;
  1041. }
  1042. // TODO: validate name (upb_isident() doesn't quite work atm because this name
  1043. // may have a leading ".").
  1044. release_subdef(f);
  1045. f->sub.name = upb_strdup(name);
  1046. f->subdef_is_symbolic = true;
  1047. return true;
  1048. }
  1049. bool upb_fielddef_issubmsg(const upb_fielddef *f) {
  1050. return upb_fielddef_type(f) == UPB_TYPE_MESSAGE;
  1051. }
  1052. bool upb_fielddef_isstring(const upb_fielddef *f) {
  1053. return upb_fielddef_type(f) == UPB_TYPE_STRING ||
  1054. upb_fielddef_type(f) == UPB_TYPE_BYTES;
  1055. }
  1056. bool upb_fielddef_isseq(const upb_fielddef *f) {
  1057. return upb_fielddef_label(f) == UPB_LABEL_REPEATED;
  1058. }
  1059. bool upb_fielddef_isprimitive(const upb_fielddef *f) {
  1060. return !upb_fielddef_isstring(f) && !upb_fielddef_issubmsg(f);
  1061. }
  1062. bool upb_fielddef_hassubdef(const upb_fielddef *f) {
  1063. return upb_fielddef_issubmsg(f) || upb_fielddef_type(f) == UPB_TYPE_ENUM;
  1064. }
  1065. static bool between(int32_t x, int32_t low, int32_t high) {
  1066. return x >= low && x <= high;
  1067. }
  1068. bool upb_fielddef_checklabel(int32_t label) { return between(label, 1, 3); }
  1069. bool upb_fielddef_checktype(int32_t type) { return between(type, 1, 11); }
  1070. bool upb_fielddef_checkintfmt(int32_t fmt) { return between(fmt, 1, 3); }
  1071. bool upb_fielddef_checkdescriptortype(int32_t type) {
  1072. return between(type, 1, 18);
  1073. }
  1074. /* upb_msgdef *****************************************************************/
  1075. static void visitmsg(const upb_refcounted *r, upb_refcounted_visit *visit,
  1076. void *closure) {
  1077. const upb_msgdef *m = (const upb_msgdef*)r;
  1078. upb_msg_iter i;
  1079. for(upb_msg_begin(&i, m); !upb_msg_done(&i); upb_msg_next(&i)) {
  1080. upb_fielddef *f = upb_msg_iter_field(&i);
  1081. visit(r, UPB_UPCAST2(f), closure);
  1082. }
  1083. }
  1084. static void freemsg(upb_refcounted *r) {
  1085. upb_msgdef *m = (upb_msgdef*)r;
  1086. upb_strtable_uninit(&m->ntof);
  1087. upb_inttable_uninit(&m->itof);
  1088. upb_def_uninit(UPB_UPCAST(m));
  1089. free(m);
  1090. }
  1091. upb_msgdef *upb_msgdef_new(const void *owner) {
  1092. static const struct upb_refcounted_vtbl vtbl = {visitmsg, freemsg};
  1093. upb_msgdef *m = malloc(sizeof(*m));
  1094. if (!m) return NULL;
  1095. if (!upb_def_init(UPB_UPCAST(m), UPB_DEF_MSG, &vtbl, owner)) goto err2;
  1096. if (!upb_inttable_init(&m->itof, UPB_CTYPE_PTR)) goto err2;
  1097. if (!upb_strtable_init(&m->ntof, UPB_CTYPE_PTR)) goto err1;
  1098. m->map_entry = false;
  1099. return m;
  1100. err1:
  1101. upb_inttable_uninit(&m->itof);
  1102. err2:
  1103. free(m);
  1104. return NULL;
  1105. }
  1106. upb_msgdef *upb_msgdef_dup(const upb_msgdef *m, const void *owner) {
  1107. upb_msgdef *newm = upb_msgdef_new(owner);
  1108. if (!newm) return NULL;
  1109. bool ok = upb_def_setfullname(UPB_UPCAST(newm),
  1110. upb_def_fullname(UPB_UPCAST(m)), NULL);
  1111. newm->map_entry = m->map_entry;
  1112. UPB_ASSERT_VAR(ok, ok);
  1113. upb_msg_iter i;
  1114. for(upb_msg_begin(&i, m); !upb_msg_done(&i); upb_msg_next(&i)) {
  1115. upb_fielddef *f = upb_fielddef_dup(upb_msg_iter_field(&i), &f);
  1116. if (!f || !upb_msgdef_addfield(newm, f, &f, NULL)) {
  1117. upb_msgdef_unref(newm, owner);
  1118. return NULL;
  1119. }
  1120. }
  1121. return newm;
  1122. }
  1123. bool upb_msgdef_isfrozen(const upb_msgdef *m) {
  1124. return upb_def_isfrozen(UPB_UPCAST(m));
  1125. }
  1126. void upb_msgdef_ref(const upb_msgdef *m, const void *owner) {
  1127. upb_def_ref(UPB_UPCAST(m), owner);
  1128. }
  1129. void upb_msgdef_unref(const upb_msgdef *m, const void *owner) {
  1130. upb_def_unref(UPB_UPCAST(m), owner);
  1131. }
  1132. void upb_msgdef_donateref(
  1133. const upb_msgdef *m, const void *from, const void *to) {
  1134. upb_def_donateref(UPB_UPCAST(m), from, to);
  1135. }
  1136. void upb_msgdef_checkref(const upb_msgdef *m, const void *owner) {
  1137. upb_def_checkref(UPB_UPCAST(m), owner);
  1138. }
  1139. bool upb_msgdef_freeze(upb_msgdef *m, upb_status *status) {
  1140. upb_def *d = UPB_UPCAST(m);
  1141. return upb_def_freeze(&d, 1, status);
  1142. }
  1143. const char *upb_msgdef_fullname(const upb_msgdef *m) {
  1144. return upb_def_fullname(UPB_UPCAST(m));
  1145. }
  1146. bool upb_msgdef_setfullname(upb_msgdef *m, const char *fullname,
  1147. upb_status *s) {
  1148. return upb_def_setfullname(UPB_UPCAST(m), fullname, s);
  1149. }
  1150. bool upb_msgdef_addfield(upb_msgdef *m, upb_fielddef *f, const void *ref_donor,
  1151. upb_status *s) {
  1152. // TODO: extensions need to have a separate namespace, because proto2 allows a
  1153. // top-level extension (ie. one not in any package) to have the same name as a
  1154. // field from the message.
  1155. //
  1156. // This also implies that there needs to be a separate lookup-by-name method
  1157. // for extensions. It seems desirable for iteration to return both extensions
  1158. // and non-extensions though.
  1159. //
  1160. // We also need to validate that the field number is in an extension range iff
  1161. // it is an extension.
  1162. // Check constraints for all fields before performing any action.
  1163. if (upb_fielddef_containingtype(f) != NULL) {
  1164. upb_status_seterrmsg(s, "fielddef already belongs to a message");
  1165. return false;
  1166. } else if (upb_fielddef_name(f) == NULL || upb_fielddef_number(f) == 0) {
  1167. upb_status_seterrmsg(s, "field name or number were not set");
  1168. return false;
  1169. } else if(upb_msgdef_itof(m, upb_fielddef_number(f)) ||
  1170. upb_msgdef_ntofz(m, upb_fielddef_name(f))) {
  1171. upb_status_seterrmsg(s, "duplicate field name or number");
  1172. return false;
  1173. }
  1174. // Constraint checks ok, perform the action.
  1175. release_containingtype(f);
  1176. f->msg.def = m;
  1177. f->msg_is_symbolic = false;
  1178. upb_inttable_insert(&m->itof, upb_fielddef_number(f), upb_value_ptr(f));
  1179. upb_strtable_insert(&m->ntof, upb_fielddef_name(f), upb_value_ptr(f));
  1180. upb_ref2(f, m);
  1181. upb_ref2(m, f);
  1182. if (ref_donor) upb_fielddef_unref(f, ref_donor);
  1183. return true;
  1184. }
  1185. const upb_fielddef *upb_msgdef_itof(const upb_msgdef *m, uint32_t i) {
  1186. upb_value val;
  1187. return upb_inttable_lookup32(&m->itof, i, &val) ?
  1188. upb_value_getptr(val) : NULL;
  1189. }
  1190. const upb_fielddef *upb_msgdef_ntof(const upb_msgdef *m, const char *name,
  1191. size_t len) {
  1192. upb_value val;
  1193. return upb_strtable_lookup2(&m->ntof, name, len, &val) ?
  1194. upb_value_getptr(val) : NULL;
  1195. }
  1196. int upb_msgdef_numfields(const upb_msgdef *m) {
  1197. return upb_strtable_count(&m->ntof);
  1198. }
  1199. void upb_msgdef_setmapentry(upb_msgdef *m, bool map_entry) {
  1200. assert(!upb_msgdef_isfrozen(m));
  1201. m->map_entry = map_entry;
  1202. }
  1203. bool upb_msgdef_mapentry(const upb_msgdef *m) {
  1204. return m->map_entry;
  1205. }
  1206. void upb_msg_begin(upb_msg_iter *iter, const upb_msgdef *m) {
  1207. upb_inttable_begin(iter, &m->itof);
  1208. }
  1209. void upb_msg_next(upb_msg_iter *iter) { upb_inttable_next(iter); }
  1210. bool upb_msg_done(const upb_msg_iter *iter) { return upb_inttable_done(iter); }
  1211. upb_fielddef *upb_msg_iter_field(const upb_msg_iter *iter) {
  1212. return (upb_fielddef*)upb_value_getptr(upb_inttable_iter_value(iter));
  1213. }
  1214. void upb_msg_iter_setdone(upb_msg_iter *iter) {
  1215. upb_inttable_iter_setdone(iter);
  1216. }
  1217. /*
  1218. * upb - a minimalist implementation of protocol buffers.
  1219. *
  1220. * Copyright (c) 2011-2012 Google Inc. See LICENSE for details.
  1221. * Author: Josh Haberman <jhaberman@gmail.com>
  1222. *
  1223. * TODO(haberman): it's unclear whether a lot of the consistency checks should
  1224. * assert() or return false.
  1225. */
  1226. #include <stdlib.h>
  1227. #include <string.h>
  1228. // Defined for the sole purpose of having a unique pointer value for
  1229. // UPB_NO_CLOSURE.
  1230. char _upb_noclosure;
  1231. static void freehandlers(upb_refcounted *r) {
  1232. upb_handlers *h = (upb_handlers*)r;
  1233. upb_inttable_iter i;
  1234. upb_inttable_begin(&i, &h->cleanup_);
  1235. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  1236. void *val = (void*)upb_inttable_iter_key(&i);
  1237. upb_value func_val = upb_inttable_iter_value(&i);
  1238. upb_handlerfree *func = upb_value_getfptr(func_val);
  1239. func(val);
  1240. }
  1241. upb_inttable_uninit(&h->cleanup_);
  1242. upb_msgdef_unref(h->msg, h);
  1243. free(h->sub);
  1244. free(h);
  1245. }
  1246. static void visithandlers(const upb_refcounted *r, upb_refcounted_visit *visit,
  1247. void *closure) {
  1248. const upb_handlers *h = (const upb_handlers*)r;
  1249. upb_msg_iter i;
  1250. for(upb_msg_begin(&i, h->msg); !upb_msg_done(&i); upb_msg_next(&i)) {
  1251. upb_fielddef *f = upb_msg_iter_field(&i);
  1252. if (!upb_fielddef_issubmsg(f)) continue;
  1253. const upb_handlers *sub = upb_handlers_getsubhandlers(h, f);
  1254. if (sub) visit(r, UPB_UPCAST(sub), closure);
  1255. }
  1256. }
  1257. static const struct upb_refcounted_vtbl vtbl = {visithandlers, freehandlers};
  1258. typedef struct {
  1259. upb_inttable tab; // maps upb_msgdef* -> upb_handlers*.
  1260. upb_handlers_callback *callback;
  1261. const void *closure;
  1262. } dfs_state;
  1263. // TODO(haberman): discard upb_handlers* objects that do not actually have any
  1264. // handlers set and cannot reach any upb_handlers* object that does. This is
  1265. // slightly tricky to do correctly.
  1266. static upb_handlers *newformsg(const upb_msgdef *m, const void *owner,
  1267. dfs_state *s) {
  1268. upb_handlers *h = upb_handlers_new(m, owner);
  1269. if (!h) return NULL;
  1270. if (!upb_inttable_insertptr(&s->tab, m, upb_value_ptr(h))) goto oom;
  1271. s->callback(s->closure, h);
  1272. // For each submessage field, get or create a handlers object and set it as
  1273. // the subhandlers.
  1274. upb_msg_iter i;
  1275. for(upb_msg_begin(&i, m); !upb_msg_done(&i); upb_msg_next(&i)) {
  1276. upb_fielddef *f = upb_msg_iter_field(&i);
  1277. if (!upb_fielddef_issubmsg(f)) continue;
  1278. const upb_msgdef *subdef = upb_downcast_msgdef(upb_fielddef_subdef(f));
  1279. upb_value subm_ent;
  1280. if (upb_inttable_lookupptr(&s->tab, subdef, &subm_ent)) {
  1281. upb_handlers_setsubhandlers(h, f, upb_value_getptr(subm_ent));
  1282. } else {
  1283. upb_handlers *sub_mh = newformsg(subdef, &sub_mh, s);
  1284. if (!sub_mh) goto oom;
  1285. upb_handlers_setsubhandlers(h, f, sub_mh);
  1286. upb_handlers_unref(sub_mh, &sub_mh);
  1287. }
  1288. }
  1289. return h;
  1290. oom:
  1291. upb_handlers_unref(h, owner);
  1292. return NULL;
  1293. }
  1294. // Given a selector for a STARTSUBMSG handler, resolves to a pointer to the
  1295. // subhandlers for this submessage field.
  1296. #define SUBH(h, selector) (h->sub[selector])
  1297. // The selector for a submessage field is the field index.
  1298. #define SUBH_F(h, f) SUBH(h, f->index_)
  1299. static int32_t trygetsel(upb_handlers *h, const upb_fielddef *f,
  1300. upb_handlertype_t type) {
  1301. upb_selector_t sel;
  1302. assert(!upb_handlers_isfrozen(h));
  1303. if (upb_handlers_msgdef(h) != upb_fielddef_containingtype(f)) {
  1304. upb_status_seterrf(
  1305. &h->status_, "type mismatch: field %s does not belong to message %s",
  1306. upb_fielddef_name(f), upb_msgdef_fullname(upb_handlers_msgdef(h)));
  1307. return -1;
  1308. }
  1309. if (!upb_handlers_getselector(f, type, &sel)) {
  1310. upb_status_seterrf(
  1311. &h->status_,
  1312. "type mismatch: cannot register handler type %d for field %s",
  1313. type, upb_fielddef_name(f));
  1314. return -1;
  1315. }
  1316. return sel;
  1317. }
  1318. static upb_selector_t handlers_getsel(upb_handlers *h, const upb_fielddef *f,
  1319. upb_handlertype_t type) {
  1320. int32_t sel = trygetsel(h, f, type);
  1321. assert(sel >= 0);
  1322. return sel;
  1323. }
  1324. static const void **returntype(upb_handlers *h, const upb_fielddef *f,
  1325. upb_handlertype_t type) {
  1326. return &h->table[handlers_getsel(h, f, type)].attr.return_closure_type_;
  1327. }
  1328. static bool doset(upb_handlers *h, int32_t sel, const upb_fielddef *f,
  1329. upb_handlertype_t type, upb_func *func,
  1330. upb_handlerattr *attr) {
  1331. assert(!upb_handlers_isfrozen(h));
  1332. if (sel < 0) {
  1333. upb_status_seterrmsg(&h->status_,
  1334. "incorrect handler type for this field.");
  1335. return false;
  1336. }
  1337. if (h->table[sel].func) {
  1338. upb_status_seterrmsg(&h->status_,
  1339. "cannot change handler once it has been set.");
  1340. return false;
  1341. }
  1342. upb_handlerattr set_attr = UPB_HANDLERATTR_INITIALIZER;
  1343. if (attr) {
  1344. set_attr = *attr;
  1345. }
  1346. // Check that the given closure type matches the closure type that has been
  1347. // established for this context (if any).
  1348. const void *closure_type = upb_handlerattr_closuretype(&set_attr);
  1349. const void **context_closure_type;
  1350. if (type == UPB_HANDLER_STRING) {
  1351. context_closure_type = returntype(h, f, UPB_HANDLER_STARTSTR);
  1352. } else if (f && upb_fielddef_isseq(f) &&
  1353. type != UPB_HANDLER_STARTSEQ &&
  1354. type != UPB_HANDLER_ENDSEQ) {
  1355. context_closure_type = returntype(h, f, UPB_HANDLER_STARTSEQ);
  1356. } else {
  1357. context_closure_type = &h->top_closure_type;
  1358. }
  1359. if (closure_type && *context_closure_type &&
  1360. closure_type != *context_closure_type) {
  1361. // TODO(haberman): better message for debugging.
  1362. upb_status_seterrmsg(&h->status_, "closure type does not match");
  1363. return false;
  1364. }
  1365. if (closure_type)
  1366. *context_closure_type = closure_type;
  1367. // If this is a STARTSEQ or STARTSTR handler, check that the returned pointer
  1368. // matches any pre-existing expectations about what type is expected.
  1369. if (type == UPB_HANDLER_STARTSEQ || type == UPB_HANDLER_STARTSTR) {
  1370. const void *return_type = upb_handlerattr_returnclosuretype(&set_attr);
  1371. const void *table_return_type =
  1372. upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  1373. if (return_type && table_return_type && return_type != table_return_type) {
  1374. upb_status_seterrmsg(&h->status_, "closure return type does not match");
  1375. return false;
  1376. }
  1377. if (table_return_type && !return_type)
  1378. upb_handlerattr_setreturnclosuretype(&set_attr, table_return_type);
  1379. }
  1380. h->table[sel].func = (upb_func*)func;
  1381. h->table[sel].attr = set_attr;
  1382. return true;
  1383. }
  1384. // Returns the effective closure type for this handler (which will propagate
  1385. // from outer frames if this frame has no START* handler). Not implemented for
  1386. // UPB_HANDLER_STRING at the moment since this is not needed. Returns NULL is
  1387. // the effective closure type is unspecified (either no handler was registered
  1388. // to specify it or the handler that was registered did not specify the closure
  1389. // type).
  1390. const void *effective_closure_type(upb_handlers *h, const upb_fielddef *f,
  1391. upb_handlertype_t type) {
  1392. assert(type != UPB_HANDLER_STRING);
  1393. const void *ret = h->top_closure_type;
  1394. upb_selector_t sel;
  1395. if (upb_fielddef_isseq(f) &&
  1396. type != UPB_HANDLER_STARTSEQ &&
  1397. type != UPB_HANDLER_ENDSEQ &&
  1398. h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSEQ)].func) {
  1399. ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  1400. }
  1401. if (type == UPB_HANDLER_STRING &&
  1402. h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSTR)].func) {
  1403. ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  1404. }
  1405. // The effective type of the submessage; not used yet.
  1406. // if (type == SUBMESSAGE &&
  1407. // h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSUBMSG)].func) {
  1408. // ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  1409. // }
  1410. return ret;
  1411. }
  1412. // Checks whether the START* handler specified by f & type is missing even
  1413. // though it is required to convert the established type of an outer frame
  1414. // ("closure_type") into the established type of an inner frame (represented in
  1415. // the return closure type of this handler's attr.
  1416. bool checkstart(upb_handlers *h, const upb_fielddef *f, upb_handlertype_t type,
  1417. upb_status *status) {
  1418. upb_selector_t sel = handlers_getsel(h, f, type);
  1419. if (h->table[sel].func) return true;
  1420. const void *closure_type = effective_closure_type(h, f, type);
  1421. const upb_handlerattr *attr = &h->table[sel].attr;
  1422. const void *return_closure_type = upb_handlerattr_returnclosuretype(attr);
  1423. if (closure_type && return_closure_type &&
  1424. closure_type != return_closure_type) {
  1425. upb_status_seterrf(status,
  1426. "expected start handler to return sub type for field %f",
  1427. upb_fielddef_name(f));
  1428. return false;
  1429. }
  1430. return true;
  1431. }
  1432. /* Public interface ***********************************************************/
  1433. bool upb_handlers_isfrozen(const upb_handlers *h) {
  1434. return upb_refcounted_isfrozen(UPB_UPCAST(h));
  1435. }
  1436. void upb_handlers_ref(const upb_handlers *h, const void *owner) {
  1437. upb_refcounted_ref(UPB_UPCAST(h), owner);
  1438. }
  1439. void upb_handlers_unref(const upb_handlers *h, const void *owner) {
  1440. upb_refcounted_unref(UPB_UPCAST(h), owner);
  1441. }
  1442. void upb_handlers_donateref(
  1443. const upb_handlers *h, const void *from, const void *to) {
  1444. upb_refcounted_donateref(UPB_UPCAST(h), from, to);
  1445. }
  1446. void upb_handlers_checkref(const upb_handlers *h, const void *owner) {
  1447. upb_refcounted_checkref(UPB_UPCAST(h), owner);
  1448. }
  1449. upb_handlers *upb_handlers_new(const upb_msgdef *md, const void *owner) {
  1450. assert(upb_msgdef_isfrozen(md));
  1451. int extra = sizeof(upb_handlers_tabent) * (md->selector_count - 1);
  1452. upb_handlers *h = calloc(sizeof(*h) + extra, 1);
  1453. if (!h) return NULL;
  1454. h->msg = md;
  1455. upb_msgdef_ref(h->msg, h);
  1456. upb_status_clear(&h->status_);
  1457. h->sub = calloc(md->submsg_field_count, sizeof(*h->sub));
  1458. if (!h->sub) goto oom;
  1459. if (!upb_refcounted_init(UPB_UPCAST(h), &vtbl, owner)) goto oom;
  1460. if (!upb_inttable_init(&h->cleanup_, UPB_CTYPE_FPTR)) goto oom;
  1461. // calloc() above initialized all handlers to NULL.
  1462. return h;
  1463. oom:
  1464. freehandlers(UPB_UPCAST(h));
  1465. return NULL;
  1466. }
  1467. const upb_handlers *upb_handlers_newfrozen(const upb_msgdef *m,
  1468. const void *owner,
  1469. upb_handlers_callback *callback,
  1470. const void *closure) {
  1471. dfs_state state;
  1472. state.callback = callback;
  1473. state.closure = closure;
  1474. if (!upb_inttable_init(&state.tab, UPB_CTYPE_PTR)) return NULL;
  1475. upb_handlers *ret = newformsg(m, owner, &state);
  1476. upb_inttable_uninit(&state.tab);
  1477. if (!ret) return NULL;
  1478. upb_refcounted *r = UPB_UPCAST(ret);
  1479. bool ok = upb_refcounted_freeze(&r, 1, NULL, UPB_MAX_HANDLER_DEPTH);
  1480. UPB_ASSERT_VAR(ok, ok);
  1481. return ret;
  1482. }
  1483. const upb_status *upb_handlers_status(upb_handlers *h) {
  1484. assert(!upb_handlers_isfrozen(h));
  1485. return &h->status_;
  1486. }
  1487. void upb_handlers_clearerr(upb_handlers *h) {
  1488. assert(!upb_handlers_isfrozen(h));
  1489. upb_status_clear(&h->status_);
  1490. }
  1491. #define SETTER(name, handlerctype, handlertype) \
  1492. bool upb_handlers_set ## name(upb_handlers *h, const upb_fielddef *f, \
  1493. handlerctype func, upb_handlerattr *attr) { \
  1494. int32_t sel = trygetsel(h, f, handlertype); \
  1495. return doset(h, sel, f, handlertype, (upb_func*)func, attr); \
  1496. }
  1497. SETTER(int32, upb_int32_handlerfunc*, UPB_HANDLER_INT32);
  1498. SETTER(int64, upb_int64_handlerfunc*, UPB_HANDLER_INT64);
  1499. SETTER(uint32, upb_uint32_handlerfunc*, UPB_HANDLER_UINT32);
  1500. SETTER(uint64, upb_uint64_handlerfunc*, UPB_HANDLER_UINT64);
  1501. SETTER(float, upb_float_handlerfunc*, UPB_HANDLER_FLOAT);
  1502. SETTER(double, upb_double_handlerfunc*, UPB_HANDLER_DOUBLE);
  1503. SETTER(bool, upb_bool_handlerfunc*, UPB_HANDLER_BOOL);
  1504. SETTER(startstr, upb_startstr_handlerfunc*, UPB_HANDLER_STARTSTR);
  1505. SETTER(string, upb_string_handlerfunc*, UPB_HANDLER_STRING);
  1506. SETTER(endstr, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSTR);
  1507. SETTER(startseq, upb_startfield_handlerfunc*, UPB_HANDLER_STARTSEQ);
  1508. SETTER(startsubmsg, upb_startfield_handlerfunc*, UPB_HANDLER_STARTSUBMSG);
  1509. SETTER(endsubmsg, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSUBMSG);
  1510. SETTER(endseq, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSEQ);
  1511. #undef SETTER
  1512. bool upb_handlers_setstartmsg(upb_handlers *h, upb_startmsg_handlerfunc *func,
  1513. upb_handlerattr *attr) {
  1514. return doset(h, UPB_STARTMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
  1515. (upb_func *)func, attr);
  1516. }
  1517. bool upb_handlers_setendmsg(upb_handlers *h, upb_endmsg_handlerfunc *func,
  1518. upb_handlerattr *attr) {
  1519. assert(!upb_handlers_isfrozen(h));
  1520. return doset(h, UPB_ENDMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
  1521. (upb_func *)func, attr);
  1522. }
  1523. bool upb_handlers_setsubhandlers(upb_handlers *h, const upb_fielddef *f,
  1524. const upb_handlers *sub) {
  1525. assert(sub);
  1526. assert(!upb_handlers_isfrozen(h));
  1527. assert(upb_fielddef_issubmsg(f));
  1528. if (SUBH_F(h, f)) return false; // Can't reset.
  1529. if (UPB_UPCAST(upb_handlers_msgdef(sub)) != upb_fielddef_subdef(f)) {
  1530. return false;
  1531. }
  1532. SUBH_F(h, f) = sub;
  1533. upb_ref2(sub, h);
  1534. return true;
  1535. }
  1536. const upb_handlers *upb_handlers_getsubhandlers(const upb_handlers *h,
  1537. const upb_fielddef *f) {
  1538. assert(upb_fielddef_issubmsg(f));
  1539. return SUBH_F(h, f);
  1540. }
  1541. bool upb_handlers_getattr(const upb_handlers *h, upb_selector_t sel,
  1542. upb_handlerattr *attr) {
  1543. if (!upb_handlers_gethandler(h, sel))
  1544. return false;
  1545. *attr = h->table[sel].attr;
  1546. return true;
  1547. }
  1548. const upb_handlers *upb_handlers_getsubhandlers_sel(const upb_handlers *h,
  1549. upb_selector_t sel) {
  1550. // STARTSUBMSG selector in sel is the field's selector base.
  1551. return SUBH(h, sel - UPB_STATIC_SELECTOR_COUNT);
  1552. }
  1553. const upb_msgdef *upb_handlers_msgdef(const upb_handlers *h) { return h->msg; }
  1554. bool upb_handlers_addcleanup(upb_handlers *h, void *p, upb_handlerfree *func) {
  1555. if (upb_inttable_lookupptr(&h->cleanup_, p, NULL)) {
  1556. return false;
  1557. }
  1558. bool ok = upb_inttable_insertptr(&h->cleanup_, p, upb_value_fptr(func));
  1559. UPB_ASSERT_VAR(ok, ok);
  1560. return true;
  1561. }
  1562. /* "Static" methods ***********************************************************/
  1563. bool upb_handlers_freeze(upb_handlers *const*handlers, int n, upb_status *s) {
  1564. // TODO: verify we have a transitive closure.
  1565. for (int i = 0; i < n; i++) {
  1566. upb_handlers *h = handlers[i];
  1567. if (!upb_ok(&h->status_)) {
  1568. upb_status_seterrf(s, "handlers for message %s had error status: %s",
  1569. upb_msgdef_fullname(upb_handlers_msgdef(h)),
  1570. upb_status_errmsg(&h->status_));
  1571. return false;
  1572. }
  1573. // Check that there are no closure mismatches due to missing Start* handlers
  1574. // or subhandlers with different type-level types.
  1575. upb_msg_iter j;
  1576. for(upb_msg_begin(&j, h->msg); !upb_msg_done(&j); upb_msg_next(&j)) {
  1577. const upb_fielddef *f = upb_msg_iter_field(&j);
  1578. if (upb_fielddef_isseq(f)) {
  1579. if (!checkstart(h, f, UPB_HANDLER_STARTSEQ, s))
  1580. return false;
  1581. }
  1582. if (upb_fielddef_isstring(f)) {
  1583. if (!checkstart(h, f, UPB_HANDLER_STARTSTR, s))
  1584. return false;
  1585. }
  1586. if (upb_fielddef_issubmsg(f)) {
  1587. bool hashandler = false;
  1588. if (upb_handlers_gethandler(
  1589. h, handlers_getsel(h, f, UPB_HANDLER_STARTSUBMSG)) ||
  1590. upb_handlers_gethandler(
  1591. h, handlers_getsel(h, f, UPB_HANDLER_ENDSUBMSG))) {
  1592. hashandler = true;
  1593. }
  1594. if (upb_fielddef_isseq(f) &&
  1595. (upb_handlers_gethandler(
  1596. h, handlers_getsel(h, f, UPB_HANDLER_STARTSEQ)) ||
  1597. upb_handlers_gethandler(
  1598. h, handlers_getsel(h, f, UPB_HANDLER_ENDSEQ)))) {
  1599. hashandler = true;
  1600. }
  1601. if (hashandler && !upb_handlers_getsubhandlers(h, f)) {
  1602. // For now we add an empty subhandlers in this case. It makes the
  1603. // decoder code generator simpler, because it only has to handle two
  1604. // cases (submessage has handlers or not) as opposed to three
  1605. // (submessage has handlers in enclosing message but no subhandlers).
  1606. //
  1607. // This makes parsing less efficient in the case that we want to
  1608. // notice a submessage but skip its contents (like if we're testing
  1609. // for submessage presence or counting the number of repeated
  1610. // submessages). In this case we will end up parsing the submessage
  1611. // field by field and throwing away the results for each, instead of
  1612. // skipping the whole delimited thing at once. If this is an issue we
  1613. // can revisit it, but do remember that this only arises when you have
  1614. // handlers (startseq/startsubmsg/endsubmsg/endseq) set for the
  1615. // submessage but no subhandlers. The uses cases for this are
  1616. // limited.
  1617. upb_handlers *sub = upb_handlers_new(upb_fielddef_msgsubdef(f), &sub);
  1618. upb_handlers_setsubhandlers(h, f, sub);
  1619. upb_handlers_unref(sub, &sub);
  1620. }
  1621. // TODO(haberman): check type of submessage.
  1622. // This is slightly tricky; also consider whether we should check that
  1623. // they match at setsubhandlers time.
  1624. }
  1625. }
  1626. }
  1627. if (!upb_refcounted_freeze((upb_refcounted*const*)handlers, n, s,
  1628. UPB_MAX_HANDLER_DEPTH)) {
  1629. return false;
  1630. }
  1631. return true;
  1632. }
  1633. upb_handlertype_t upb_handlers_getprimitivehandlertype(const upb_fielddef *f) {
  1634. switch (upb_fielddef_type(f)) {
  1635. case UPB_TYPE_INT32:
  1636. case UPB_TYPE_ENUM: return UPB_HANDLER_INT32;
  1637. case UPB_TYPE_INT64: return UPB_HANDLER_INT64;
  1638. case UPB_TYPE_UINT32: return UPB_HANDLER_UINT32;
  1639. case UPB_TYPE_UINT64: return UPB_HANDLER_UINT64;
  1640. case UPB_TYPE_FLOAT: return UPB_HANDLER_FLOAT;
  1641. case UPB_TYPE_DOUBLE: return UPB_HANDLER_DOUBLE;
  1642. case UPB_TYPE_BOOL: return UPB_HANDLER_BOOL;
  1643. default: assert(false); return -1; // Invalid input.
  1644. }
  1645. }
  1646. bool upb_handlers_getselector(const upb_fielddef *f, upb_handlertype_t type,
  1647. upb_selector_t *s) {
  1648. switch (type) {
  1649. case UPB_HANDLER_INT32:
  1650. case UPB_HANDLER_INT64:
  1651. case UPB_HANDLER_UINT32:
  1652. case UPB_HANDLER_UINT64:
  1653. case UPB_HANDLER_FLOAT:
  1654. case UPB_HANDLER_DOUBLE:
  1655. case UPB_HANDLER_BOOL:
  1656. if (!upb_fielddef_isprimitive(f) ||
  1657. upb_handlers_getprimitivehandlertype(f) != type)
  1658. return false;
  1659. *s = f->selector_base;
  1660. break;
  1661. case UPB_HANDLER_STRING:
  1662. if (upb_fielddef_isstring(f)) {
  1663. *s = f->selector_base;
  1664. } else if (upb_fielddef_lazy(f)) {
  1665. *s = f->selector_base + 3;
  1666. } else {
  1667. return false;
  1668. }
  1669. break;
  1670. case UPB_HANDLER_STARTSTR:
  1671. if (upb_fielddef_isstring(f) || upb_fielddef_lazy(f)) {
  1672. *s = f->selector_base + 1;
  1673. } else {
  1674. return false;
  1675. }
  1676. break;
  1677. case UPB_HANDLER_ENDSTR:
  1678. if (upb_fielddef_isstring(f) || upb_fielddef_lazy(f)) {
  1679. *s = f->selector_base + 2;
  1680. } else {
  1681. return false;
  1682. }
  1683. break;
  1684. case UPB_HANDLER_STARTSEQ:
  1685. if (!upb_fielddef_isseq(f)) return false;
  1686. *s = f->selector_base - 2;
  1687. break;
  1688. case UPB_HANDLER_ENDSEQ:
  1689. if (!upb_fielddef_isseq(f)) return false;
  1690. *s = f->selector_base - 1;
  1691. break;
  1692. case UPB_HANDLER_STARTSUBMSG:
  1693. if (!upb_fielddef_issubmsg(f)) return false;
  1694. // Selectors for STARTSUBMSG are at the beginning of the table so that the
  1695. // selector can also be used as an index into the "sub" array of
  1696. // subhandlers. The indexes for the two into these two tables are the
  1697. // same, except that in the handler table the static selectors come first.
  1698. *s = f->index_ + UPB_STATIC_SELECTOR_COUNT;
  1699. break;
  1700. case UPB_HANDLER_ENDSUBMSG:
  1701. if (!upb_fielddef_issubmsg(f)) return false;
  1702. *s = f->selector_base;
  1703. break;
  1704. }
  1705. assert(*s < upb_fielddef_containingtype(f)->selector_count);
  1706. return true;
  1707. }
  1708. uint32_t upb_handlers_selectorbaseoffset(const upb_fielddef *f) {
  1709. return upb_fielddef_isseq(f) ? 2 : 0;
  1710. }
  1711. uint32_t upb_handlers_selectorcount(const upb_fielddef *f) {
  1712. uint32_t ret = 1;
  1713. if (upb_fielddef_isseq(f)) ret += 2; // STARTSEQ/ENDSEQ
  1714. if (upb_fielddef_isstring(f)) ret += 2; // [STRING]/STARTSTR/ENDSTR
  1715. if (upb_fielddef_issubmsg(f)) {
  1716. // ENDSUBMSG (STARTSUBMSG is at table beginning)
  1717. ret += 0;
  1718. if (upb_fielddef_lazy(f)) {
  1719. // STARTSTR/ENDSTR/STRING (for lazy)
  1720. ret += 3;
  1721. }
  1722. }
  1723. return ret;
  1724. }
  1725. /* upb_handlerattr ************************************************************/
  1726. void upb_handlerattr_init(upb_handlerattr *attr) {
  1727. upb_handlerattr from = UPB_HANDLERATTR_INITIALIZER;
  1728. memcpy(attr, &from, sizeof(*attr));
  1729. }
  1730. void upb_handlerattr_uninit(upb_handlerattr *attr) {
  1731. UPB_UNUSED(attr);
  1732. }
  1733. bool upb_handlerattr_sethandlerdata(upb_handlerattr *attr, const void *hd) {
  1734. attr->handler_data_ = hd;
  1735. return true;
  1736. }
  1737. bool upb_handlerattr_setclosuretype(upb_handlerattr *attr, const void *type) {
  1738. attr->closure_type_ = type;
  1739. return true;
  1740. }
  1741. const void *upb_handlerattr_closuretype(const upb_handlerattr *attr) {
  1742. return attr->closure_type_;
  1743. }
  1744. bool upb_handlerattr_setreturnclosuretype(upb_handlerattr *attr,
  1745. const void *type) {
  1746. attr->return_closure_type_ = type;
  1747. return true;
  1748. }
  1749. const void *upb_handlerattr_returnclosuretype(const upb_handlerattr *attr) {
  1750. return attr->return_closure_type_;
  1751. }
  1752. bool upb_handlerattr_setalwaysok(upb_handlerattr *attr, bool alwaysok) {
  1753. attr->alwaysok_ = alwaysok;
  1754. return true;
  1755. }
  1756. bool upb_handlerattr_alwaysok(const upb_handlerattr *attr) {
  1757. return attr->alwaysok_;
  1758. }
  1759. /* upb_bufhandle **************************************************************/
  1760. size_t upb_bufhandle_objofs(const upb_bufhandle *h) {
  1761. return h->objofs_;
  1762. }
  1763. /* upb_byteshandler ***********************************************************/
  1764. void upb_byteshandler_init(upb_byteshandler* h) {
  1765. memset(h, 0, sizeof(*h));
  1766. }
  1767. // For when we support handlerfree callbacks.
  1768. void upb_byteshandler_uninit(upb_byteshandler* h) {
  1769. UPB_UNUSED(h);
  1770. }
  1771. bool upb_byteshandler_setstartstr(upb_byteshandler *h,
  1772. upb_startstr_handlerfunc *func, void *d) {
  1773. h->table[UPB_STARTSTR_SELECTOR].func = (upb_func*)func;
  1774. h->table[UPB_STARTSTR_SELECTOR].attr.handler_data_ = d;
  1775. return true;
  1776. }
  1777. bool upb_byteshandler_setstring(upb_byteshandler *h,
  1778. upb_string_handlerfunc *func, void *d) {
  1779. h->table[UPB_STRING_SELECTOR].func = (upb_func*)func;
  1780. h->table[UPB_STRING_SELECTOR].attr.handler_data_ = d;
  1781. return true;
  1782. }
  1783. bool upb_byteshandler_setendstr(upb_byteshandler *h,
  1784. upb_endfield_handlerfunc *func, void *d) {
  1785. h->table[UPB_ENDSTR_SELECTOR].func = (upb_func*)func;
  1786. h->table[UPB_ENDSTR_SELECTOR].attr.handler_data_ = d;
  1787. return true;
  1788. }
  1789. /*
  1790. * upb - a minimalist implementation of protocol buffers.
  1791. *
  1792. * Copyright (c) 2012 Google Inc. See LICENSE for details.
  1793. * Author: Josh Haberman <jhaberman@gmail.com>
  1794. *
  1795. * Our key invariants are:
  1796. * 1. reference cycles never span groups
  1797. * 2. for ref2(to, from), we increment to's count iff group(from) != group(to)
  1798. *
  1799. * The previous two are how we avoid leaking cycles. Other important
  1800. * invariants are:
  1801. * 3. for mutable objects "from" and "to", if there exists a ref2(to, from)
  1802. * this implies group(from) == group(to). (In practice, what we implement
  1803. * is even stronger; "from" and "to" will share a group if there has *ever*
  1804. * been a ref2(to, from), but all that is necessary for correctness is the
  1805. * weaker one).
  1806. * 4. mutable and immutable objects are never in the same group.
  1807. */
  1808. #include <setjmp.h>
  1809. #include <stdlib.h>
  1810. static void freeobj(upb_refcounted *o);
  1811. const char untracked_val;
  1812. const void *UPB_UNTRACKED_REF = &untracked_val;
  1813. /* arch-specific atomic primitives *******************************************/
  1814. #ifdef UPB_THREAD_UNSAFE //////////////////////////////////////////////////////
  1815. static void atomic_inc(uint32_t *a) { (*a)++; }
  1816. static bool atomic_dec(uint32_t *a) { return --(*a) == 0; }
  1817. #elif defined(__GNUC__) || defined(__clang__) //////////////////////////////////
  1818. static void atomic_inc(uint32_t *a) { __sync_fetch_and_add(a, 1); }
  1819. static bool atomic_dec(uint32_t *a) { return __sync_sub_and_fetch(a, 1) == 0; }
  1820. #elif defined(WIN32) ///////////////////////////////////////////////////////////
  1821. #include <Windows.h>
  1822. static void atomic_inc(upb_atomic_t *a) { InterlockedIncrement(&a->val); }
  1823. static bool atomic_dec(upb_atomic_t *a) {
  1824. return InterlockedDecrement(&a->val) == 0;
  1825. }
  1826. #else
  1827. #error Atomic primitives not defined for your platform/CPU. \
  1828. Implement them or compile with UPB_THREAD_UNSAFE.
  1829. #endif
  1830. // All static objects point to this refcount.
  1831. // It is special-cased in ref/unref below.
  1832. uint32_t static_refcount = -1;
  1833. // We can avoid atomic ops for statically-declared objects.
  1834. // This is a minor optimization but nice since we can avoid degrading under
  1835. // contention in this case.
  1836. static void refgroup(uint32_t *group) {
  1837. if (group != &static_refcount)
  1838. atomic_inc(group);
  1839. }
  1840. static bool unrefgroup(uint32_t *group) {
  1841. if (group == &static_refcount) {
  1842. return false;
  1843. } else {
  1844. return atomic_dec(group);
  1845. }
  1846. }
  1847. /* Reference tracking (debug only) ********************************************/
  1848. #ifdef UPB_DEBUG_REFS
  1849. #ifdef UPB_THREAD_UNSAFE
  1850. static void upb_lock() {}
  1851. static void upb_unlock() {}
  1852. #else
  1853. // User must define functions that lock/unlock a global mutex and link this
  1854. // file against them.
  1855. void upb_lock();
  1856. void upb_unlock();
  1857. #endif
  1858. // UPB_DEBUG_REFS mode counts on being able to malloc() memory in some
  1859. // code-paths that can normally never fail, like upb_refcounted_ref(). Since
  1860. // we have no way to propagage out-of-memory errors back to the user, and since
  1861. // these errors can only occur in UPB_DEBUG_REFS mode, we immediately fail.
  1862. #define CHECK_OOM(predicate) if (!(predicate)) { assert(predicate); exit(1); }
  1863. typedef struct {
  1864. int count; // How many refs there are (duplicates only allowed for ref2).
  1865. bool is_ref2;
  1866. } trackedref;
  1867. static trackedref *trackedref_new(bool is_ref2) {
  1868. trackedref *ret = malloc(sizeof(*ret));
  1869. CHECK_OOM(ret);
  1870. ret->count = 1;
  1871. ret->is_ref2 = is_ref2;
  1872. return ret;
  1873. }
  1874. static void track(const upb_refcounted *r, const void *owner, bool ref2) {
  1875. assert(owner);
  1876. if (owner == UPB_UNTRACKED_REF) return;
  1877. upb_lock();
  1878. upb_value v;
  1879. if (upb_inttable_lookupptr(r->refs, owner, &v)) {
  1880. trackedref *ref = upb_value_getptr(v);
  1881. // Since we allow multiple ref2's for the same to/from pair without
  1882. // allocating separate memory for each one, we lose the fine-grained
  1883. // tracking behavior we get with regular refs. Since ref2s only happen
  1884. // inside upb, we'll accept this limitation until/unless there is a really
  1885. // difficult upb-internal bug that can't be figured out without it.
  1886. assert(ref2);
  1887. assert(ref->is_ref2);
  1888. ref->count++;
  1889. } else {
  1890. trackedref *ref = trackedref_new(ref2);
  1891. bool ok = upb_inttable_insertptr(r->refs, owner, upb_value_ptr(ref));
  1892. CHECK_OOM(ok);
  1893. if (ref2) {
  1894. // We know this cast is safe when it is a ref2, because it's coming from
  1895. // another refcounted object.
  1896. const upb_refcounted *from = owner;
  1897. assert(!upb_inttable_lookupptr(from->ref2s, r, NULL));
  1898. ok = upb_inttable_insertptr(from->ref2s, r, upb_value_ptr(NULL));
  1899. CHECK_OOM(ok);
  1900. }
  1901. }
  1902. upb_unlock();
  1903. }
  1904. static void untrack(const upb_refcounted *r, const void *owner, bool ref2) {
  1905. assert(owner);
  1906. if (owner == UPB_UNTRACKED_REF) return;
  1907. upb_lock();
  1908. upb_value v;
  1909. bool found = upb_inttable_lookupptr(r->refs, owner, &v);
  1910. // This assert will fail if an owner attempts to release a ref it didn't have.
  1911. UPB_ASSERT_VAR(found, found);
  1912. trackedref *ref = upb_value_getptr(v);
  1913. assert(ref->is_ref2 == ref2);
  1914. if (--ref->count == 0) {
  1915. free(ref);
  1916. upb_inttable_removeptr(r->refs, owner, NULL);
  1917. if (ref2) {
  1918. // We know this cast is safe when it is a ref2, because it's coming from
  1919. // another refcounted object.
  1920. const upb_refcounted *from = owner;
  1921. bool removed = upb_inttable_removeptr(from->ref2s, r, NULL);
  1922. assert(removed);
  1923. }
  1924. }
  1925. upb_unlock();
  1926. }
  1927. static void checkref(const upb_refcounted *r, const void *owner, bool ref2) {
  1928. upb_lock();
  1929. upb_value v;
  1930. bool found = upb_inttable_lookupptr(r->refs, owner, &v);
  1931. UPB_ASSERT_VAR(found, found);
  1932. trackedref *ref = upb_value_getptr(v);
  1933. assert(ref->is_ref2 == ref2);
  1934. upb_unlock();
  1935. }
  1936. // Populates the given UPB_CTYPE_INT32 inttable with counts of ref2's that
  1937. // originate from the given owner.
  1938. static void getref2s(const upb_refcounted *owner, upb_inttable *tab) {
  1939. upb_lock();
  1940. upb_inttable_iter i;
  1941. upb_inttable_begin(&i, owner->ref2s);
  1942. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  1943. upb_refcounted *to = (upb_refcounted*)upb_inttable_iter_key(&i);
  1944. // To get the count we need to look in the target's table.
  1945. upb_value v;
  1946. bool found = upb_inttable_lookupptr(to->refs, owner, &v);
  1947. assert(found);
  1948. trackedref *ref = upb_value_getptr(v);
  1949. upb_value count = upb_value_int32(ref->count);
  1950. bool ok = upb_inttable_insertptr(tab, to, count);
  1951. CHECK_OOM(ok);
  1952. }
  1953. upb_unlock();
  1954. }
  1955. typedef struct {
  1956. upb_inttable ref2;
  1957. const upb_refcounted *obj;
  1958. } check_state;
  1959. static void visit_check(const upb_refcounted *obj, const upb_refcounted *subobj,
  1960. void *closure) {
  1961. check_state *s = closure;
  1962. assert(obj == s->obj);
  1963. assert(subobj);
  1964. upb_inttable *ref2 = &s->ref2;
  1965. upb_value v;
  1966. bool removed = upb_inttable_removeptr(ref2, subobj, &v);
  1967. // The following assertion will fail if the visit() function visits a subobj
  1968. // that it did not have a ref2 on, or visits the same subobj too many times.
  1969. assert(removed);
  1970. int32_t newcount = upb_value_getint32(v) - 1;
  1971. if (newcount > 0) {
  1972. upb_inttable_insert(ref2, (uintptr_t)subobj, upb_value_int32(newcount));
  1973. }
  1974. }
  1975. static void visit(const upb_refcounted *r, upb_refcounted_visit *v,
  1976. void *closure) {
  1977. // In DEBUG_REFS mode we know what existing ref2 refs there are, so we know
  1978. // exactly the set of nodes that visit() should visit. So we verify visit()'s
  1979. // correctness here.
  1980. check_state state;
  1981. state.obj = r;
  1982. bool ok = upb_inttable_init(&state.ref2, UPB_CTYPE_INT32);
  1983. CHECK_OOM(ok);
  1984. getref2s(r, &state.ref2);
  1985. // This should visit any children in the ref2 table.
  1986. if (r->vtbl->visit) r->vtbl->visit(r, visit_check, &state);
  1987. // This assertion will fail if the visit() function missed any children.
  1988. assert(upb_inttable_count(&state.ref2) == 0);
  1989. upb_inttable_uninit(&state.ref2);
  1990. if (r->vtbl->visit) r->vtbl->visit(r, v, closure);
  1991. }
  1992. static bool trackinit(upb_refcounted *r) {
  1993. r->refs = malloc(sizeof(*r->refs));
  1994. r->ref2s = malloc(sizeof(*r->ref2s));
  1995. if (!r->refs || !r->ref2s) goto err1;
  1996. if (!upb_inttable_init(r->refs, UPB_CTYPE_PTR)) goto err1;
  1997. if (!upb_inttable_init(r->ref2s, UPB_CTYPE_PTR)) goto err2;
  1998. return true;
  1999. err2:
  2000. upb_inttable_uninit(r->refs);
  2001. err1:
  2002. free(r->refs);
  2003. free(r->ref2s);
  2004. return false;
  2005. }
  2006. static void trackfree(const upb_refcounted *r) {
  2007. upb_inttable_uninit(r->refs);
  2008. upb_inttable_uninit(r->ref2s);
  2009. free(r->refs);
  2010. free(r->ref2s);
  2011. }
  2012. #else
  2013. static void track(const upb_refcounted *r, const void *owner, bool ref2) {
  2014. UPB_UNUSED(r);
  2015. UPB_UNUSED(owner);
  2016. UPB_UNUSED(ref2);
  2017. }
  2018. static void untrack(const upb_refcounted *r, const void *owner, bool ref2) {
  2019. UPB_UNUSED(r);
  2020. UPB_UNUSED(owner);
  2021. UPB_UNUSED(ref2);
  2022. }
  2023. static void checkref(const upb_refcounted *r, const void *owner, bool ref2) {
  2024. UPB_UNUSED(r);
  2025. UPB_UNUSED(owner);
  2026. UPB_UNUSED(ref2);
  2027. }
  2028. static bool trackinit(upb_refcounted *r) {
  2029. UPB_UNUSED(r);
  2030. return true;
  2031. }
  2032. static void trackfree(const upb_refcounted *r) {
  2033. UPB_UNUSED(r);
  2034. }
  2035. static void visit(const upb_refcounted *r, upb_refcounted_visit *v,
  2036. void *closure) {
  2037. if (r->vtbl->visit) r->vtbl->visit(r, v, closure);
  2038. }
  2039. #endif // UPB_DEBUG_REFS
  2040. /* freeze() *******************************************************************/
  2041. // The freeze() operation is by far the most complicated part of this scheme.
  2042. // We compute strongly-connected components and then mutate the graph such that
  2043. // we preserve the invariants documented at the top of this file. And we must
  2044. // handle out-of-memory errors gracefully (without leaving the graph
  2045. // inconsistent), which adds to the fun.
  2046. // The state used by the freeze operation (shared across many functions).
  2047. typedef struct {
  2048. int depth;
  2049. int maxdepth;
  2050. uint64_t index;
  2051. // Maps upb_refcounted* -> attributes (color, etc). attr layout varies by
  2052. // color.
  2053. upb_inttable objattr;
  2054. upb_inttable stack; // stack of upb_refcounted* for Tarjan's algorithm.
  2055. upb_inttable groups; // array of uint32_t*, malloc'd refcounts for new groups
  2056. upb_status *status;
  2057. jmp_buf err;
  2058. } tarjan;
  2059. static void release_ref2(const upb_refcounted *obj,
  2060. const upb_refcounted *subobj,
  2061. void *closure);
  2062. // Node attributes /////////////////////////////////////////////////////////////
  2063. // After our analysis phase all nodes will be either GRAY or WHITE.
  2064. typedef enum {
  2065. BLACK = 0, // Object has not been seen.
  2066. GRAY, // Object has been found via a refgroup but may not be reachable.
  2067. GREEN, // Object is reachable and is currently on the Tarjan stack.
  2068. WHITE, // Object is reachable and has been assigned a group (SCC).
  2069. } color_t;
  2070. UPB_NORETURN static void err(tarjan *t) { longjmp(t->err, 1); }
  2071. UPB_NORETURN static void oom(tarjan *t) {
  2072. upb_status_seterrmsg(t->status, "out of memory");
  2073. err(t);
  2074. }
  2075. static uint64_t trygetattr(const tarjan *t, const upb_refcounted *r) {
  2076. upb_value v;
  2077. return upb_inttable_lookupptr(&t->objattr, r, &v) ?
  2078. upb_value_getuint64(v) : 0;
  2079. }
  2080. static uint64_t getattr(const tarjan *t, const upb_refcounted *r) {
  2081. upb_value v;
  2082. bool found = upb_inttable_lookupptr(&t->objattr, r, &v);
  2083. UPB_ASSERT_VAR(found, found);
  2084. return upb_value_getuint64(v);
  2085. }
  2086. static void setattr(tarjan *t, const upb_refcounted *r, uint64_t attr) {
  2087. upb_inttable_removeptr(&t->objattr, r, NULL);
  2088. upb_inttable_insertptr(&t->objattr, r, upb_value_uint64(attr));
  2089. }
  2090. static color_t color(tarjan *t, const upb_refcounted *r) {
  2091. return trygetattr(t, r) & 0x3; // Color is always stored in the low 2 bits.
  2092. }
  2093. static void set_gray(tarjan *t, const upb_refcounted *r) {
  2094. assert(color(t, r) == BLACK);
  2095. setattr(t, r, GRAY);
  2096. }
  2097. // Pushes an obj onto the Tarjan stack and sets it to GREEN.
  2098. static void push(tarjan *t, const upb_refcounted *r) {
  2099. assert(color(t, r) == BLACK || color(t, r) == GRAY);
  2100. // This defines the attr layout for the GREEN state. "index" and "lowlink"
  2101. // get 31 bits, which is plenty (limit of 2B objects frozen at a time).
  2102. setattr(t, r, GREEN | (t->index << 2) | (t->index << 33));
  2103. if (++t->index == 0x80000000) {
  2104. upb_status_seterrmsg(t->status, "too many objects to freeze");
  2105. err(t);
  2106. }
  2107. upb_inttable_push(&t->stack, upb_value_ptr((void*)r));
  2108. }
  2109. // Pops an obj from the Tarjan stack and sets it to WHITE, with a ptr to its
  2110. // SCC group.
  2111. static upb_refcounted *pop(tarjan *t) {
  2112. upb_refcounted *r = upb_value_getptr(upb_inttable_pop(&t->stack));
  2113. assert(color(t, r) == GREEN);
  2114. // This defines the attr layout for nodes in the WHITE state.
  2115. // Top of group stack is [group, NULL]; we point at group.
  2116. setattr(t, r, WHITE | (upb_inttable_count(&t->groups) - 2) << 8);
  2117. return r;
  2118. }
  2119. static void tarjan_newgroup(tarjan *t) {
  2120. uint32_t *group = malloc(sizeof(*group));
  2121. if (!group) oom(t);
  2122. // Push group and empty group leader (we'll fill in leader later).
  2123. if (!upb_inttable_push(&t->groups, upb_value_ptr(group)) ||
  2124. !upb_inttable_push(&t->groups, upb_value_ptr(NULL))) {
  2125. free(group);
  2126. oom(t);
  2127. }
  2128. *group = 0;
  2129. }
  2130. static uint32_t idx(tarjan *t, const upb_refcounted *r) {
  2131. assert(color(t, r) == GREEN);
  2132. return (getattr(t, r) >> 2) & 0x7FFFFFFF;
  2133. }
  2134. static uint32_t lowlink(tarjan *t, const upb_refcounted *r) {
  2135. if (color(t, r) == GREEN) {
  2136. return getattr(t, r) >> 33;
  2137. } else {
  2138. return UINT32_MAX;
  2139. }
  2140. }
  2141. static void set_lowlink(tarjan *t, const upb_refcounted *r, uint32_t lowlink) {
  2142. assert(color(t, r) == GREEN);
  2143. setattr(t, r, ((uint64_t)lowlink << 33) | (getattr(t, r) & 0x1FFFFFFFF));
  2144. }
  2145. static uint32_t *group(tarjan *t, upb_refcounted *r) {
  2146. assert(color(t, r) == WHITE);
  2147. uint64_t groupnum = getattr(t, r) >> 8;
  2148. upb_value v;
  2149. bool found = upb_inttable_lookup(&t->groups, groupnum, &v);
  2150. UPB_ASSERT_VAR(found, found);
  2151. return upb_value_getptr(v);
  2152. }
  2153. // If the group leader for this object's group has not previously been set,
  2154. // the given object is assigned to be its leader.
  2155. static upb_refcounted *groupleader(tarjan *t, upb_refcounted *r) {
  2156. assert(color(t, r) == WHITE);
  2157. uint64_t leader_slot = (getattr(t, r) >> 8) + 1;
  2158. upb_value v;
  2159. bool found = upb_inttable_lookup(&t->groups, leader_slot, &v);
  2160. UPB_ASSERT_VAR(found, found);
  2161. if (upb_value_getptr(v)) {
  2162. return upb_value_getptr(v);
  2163. } else {
  2164. upb_inttable_remove(&t->groups, leader_slot, NULL);
  2165. upb_inttable_insert(&t->groups, leader_slot, upb_value_ptr(r));
  2166. return r;
  2167. }
  2168. }
  2169. // Tarjan's algorithm //////////////////////////////////////////////////////////
  2170. // See:
  2171. // http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
  2172. static void do_tarjan(const upb_refcounted *obj, tarjan *t);
  2173. static void tarjan_visit(const upb_refcounted *obj,
  2174. const upb_refcounted *subobj,
  2175. void *closure) {
  2176. tarjan *t = closure;
  2177. if (++t->depth > t->maxdepth) {
  2178. upb_status_seterrf(t->status, "graph too deep to freeze (%d)", t->maxdepth);
  2179. err(t);
  2180. } else if (subobj->is_frozen || color(t, subobj) == WHITE) {
  2181. // Do nothing: we don't want to visit or color already-frozen nodes,
  2182. // and WHITE nodes have already been assigned a SCC.
  2183. } else if (color(t, subobj) < GREEN) {
  2184. // Subdef has not yet been visited; recurse on it.
  2185. do_tarjan(subobj, t);
  2186. set_lowlink(t, obj, UPB_MIN(lowlink(t, obj), lowlink(t, subobj)));
  2187. } else if (color(t, subobj) == GREEN) {
  2188. // Subdef is in the stack and hence in the current SCC.
  2189. set_lowlink(t, obj, UPB_MIN(lowlink(t, obj), idx(t, subobj)));
  2190. }
  2191. --t->depth;
  2192. }
  2193. static void do_tarjan(const upb_refcounted *obj, tarjan *t) {
  2194. if (color(t, obj) == BLACK) {
  2195. // We haven't seen this object's group; mark the whole group GRAY.
  2196. const upb_refcounted *o = obj;
  2197. do { set_gray(t, o); } while ((o = o->next) != obj);
  2198. }
  2199. push(t, obj);
  2200. visit(obj, tarjan_visit, t);
  2201. if (lowlink(t, obj) == idx(t, obj)) {
  2202. tarjan_newgroup(t);
  2203. while (pop(t) != obj)
  2204. ;
  2205. }
  2206. }
  2207. // freeze() ////////////////////////////////////////////////////////////////////
  2208. static void crossref(const upb_refcounted *r, const upb_refcounted *subobj,
  2209. void *_t) {
  2210. tarjan *t = _t;
  2211. assert(color(t, r) > BLACK);
  2212. if (color(t, subobj) > BLACK && r->group != subobj->group) {
  2213. // Previously this ref was not reflected in subobj->group because they
  2214. // were in the same group; now that they are split a ref must be taken.
  2215. refgroup(subobj->group);
  2216. }
  2217. }
  2218. static bool freeze(upb_refcounted *const*roots, int n, upb_status *s,
  2219. int maxdepth) {
  2220. volatile bool ret = false;
  2221. // We run in two passes so that we can allocate all memory before performing
  2222. // any mutation of the input -- this allows us to leave the input unchanged
  2223. // in the case of memory allocation failure.
  2224. tarjan t;
  2225. t.index = 0;
  2226. t.depth = 0;
  2227. t.maxdepth = maxdepth;
  2228. t.status = s;
  2229. if (!upb_inttable_init(&t.objattr, UPB_CTYPE_UINT64)) goto err1;
  2230. if (!upb_inttable_init(&t.stack, UPB_CTYPE_PTR)) goto err2;
  2231. if (!upb_inttable_init(&t.groups, UPB_CTYPE_PTR)) goto err3;
  2232. if (setjmp(t.err) != 0) goto err4;
  2233. for (int i = 0; i < n; i++) {
  2234. if (color(&t, roots[i]) < GREEN) {
  2235. do_tarjan(roots[i], &t);
  2236. }
  2237. }
  2238. // If we've made it this far, no further errors are possible so it's safe to
  2239. // mutate the objects without risk of leaving them in an inconsistent state.
  2240. ret = true;
  2241. // The transformation that follows requires care. The preconditions are:
  2242. // - all objects in attr map are WHITE or GRAY, and are in mutable groups
  2243. // (groups of all mutable objs)
  2244. // - no ref2(to, from) refs have incremented count(to) if both "to" and
  2245. // "from" are in our attr map (this follows from invariants (2) and (3))
  2246. // Pass 1: we remove WHITE objects from their mutable groups, and add them to
  2247. // new groups according to the SCC's we computed. These new groups will
  2248. // consist of only frozen objects. None will be immediately collectible,
  2249. // because WHITE objects are by definition reachable from one of "roots",
  2250. // which the caller must own refs on.
  2251. upb_inttable_iter i;
  2252. upb_inttable_begin(&i, &t.objattr);
  2253. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  2254. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&i);
  2255. // Since removal from a singly-linked list requires access to the object's
  2256. // predecessor, we consider obj->next instead of obj for moving. With the
  2257. // while() loop we guarantee that we will visit every node's predecessor.
  2258. // Proof:
  2259. // 1. every node's predecessor is in our attr map.
  2260. // 2. though the loop body may change a node's predecessor, it will only
  2261. // change it to be the node we are currently operating on, so with a
  2262. // while() loop we guarantee ourselves the chance to remove each node.
  2263. while (color(&t, obj->next) == WHITE &&
  2264. group(&t, obj->next) != obj->next->group) {
  2265. // Remove from old group.
  2266. upb_refcounted *move = obj->next;
  2267. if (obj == move) {
  2268. // Removing the last object from a group.
  2269. assert(*obj->group == obj->individual_count);
  2270. free(obj->group);
  2271. } else {
  2272. obj->next = move->next;
  2273. // This may decrease to zero; we'll collect GRAY objects (if any) that
  2274. // remain in the group in the third pass.
  2275. assert(*move->group >= move->individual_count);
  2276. *move->group -= move->individual_count;
  2277. }
  2278. // Add to new group.
  2279. upb_refcounted *leader = groupleader(&t, move);
  2280. if (move == leader) {
  2281. // First object added to new group is its leader.
  2282. move->group = group(&t, move);
  2283. move->next = move;
  2284. *move->group = move->individual_count;
  2285. } else {
  2286. // Group already has at least one object in it.
  2287. assert(leader->group == group(&t, move));
  2288. move->group = group(&t, move);
  2289. move->next = leader->next;
  2290. leader->next = move;
  2291. *move->group += move->individual_count;
  2292. }
  2293. move->is_frozen = true;
  2294. }
  2295. }
  2296. // Pass 2: GRAY and WHITE objects "obj" with ref2(to, obj) references must
  2297. // increment count(to) if group(obj) != group(to) (which could now be the
  2298. // case if "to" was just frozen).
  2299. upb_inttable_begin(&i, &t.objattr);
  2300. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  2301. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&i);
  2302. visit(obj, crossref, &t);
  2303. }
  2304. // Pass 3: GRAY objects are collected if their group's refcount dropped to
  2305. // zero when we removed its white nodes. This can happen if they had only
  2306. // been kept alive by virtue of sharing a group with an object that was just
  2307. // frozen.
  2308. //
  2309. // It is important that we do this last, since the GRAY object's free()
  2310. // function could call unref2() on just-frozen objects, which will decrement
  2311. // refs that were added in pass 2.
  2312. upb_inttable_begin(&i, &t.objattr);
  2313. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  2314. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&i);
  2315. if (obj->group == NULL || *obj->group == 0) {
  2316. if (obj->group) {
  2317. // We eagerly free() the group's count (since we can't easily determine
  2318. // the group's remaining size it's the easiest way to ensure it gets
  2319. // done).
  2320. free(obj->group);
  2321. // Visit to release ref2's (done in a separate pass since release_ref2
  2322. // depends on o->group being unmodified so it can test merged()).
  2323. upb_refcounted *o = obj;
  2324. do { visit(o, release_ref2, NULL); } while ((o = o->next) != obj);
  2325. // Mark "group" fields as NULL so we know to free the objects later in
  2326. // this loop, but also don't try to delete the group twice.
  2327. o = obj;
  2328. do { o->group = NULL; } while ((o = o->next) != obj);
  2329. }
  2330. freeobj(obj);
  2331. }
  2332. }
  2333. err4:
  2334. if (!ret) {
  2335. upb_inttable_begin(&i, &t.groups);
  2336. for(; !upb_inttable_done(&i); upb_inttable_next(&i))
  2337. free(upb_value_getptr(upb_inttable_iter_value(&i)));
  2338. }
  2339. upb_inttable_uninit(&t.groups);
  2340. err3:
  2341. upb_inttable_uninit(&t.stack);
  2342. err2:
  2343. upb_inttable_uninit(&t.objattr);
  2344. err1:
  2345. return ret;
  2346. }
  2347. /* Misc internal functions ***************************************************/
  2348. static bool merged(const upb_refcounted *r, const upb_refcounted *r2) {
  2349. return r->group == r2->group;
  2350. }
  2351. static void merge(upb_refcounted *r, upb_refcounted *from) {
  2352. if (merged(r, from)) return;
  2353. *r->group += *from->group;
  2354. free(from->group);
  2355. upb_refcounted *base = from;
  2356. // Set all refcount pointers in the "from" chain to the merged refcount.
  2357. //
  2358. // TODO(haberman): this linear algorithm can result in an overall O(n^2) bound
  2359. // if the user continuously extends a group by one object. Prevent this by
  2360. // using one of the techniques in this paper:
  2361. // ftp://www.ncedc.org/outgoing/geomorph/dino/orals/p245-tarjan.pdf
  2362. do { from->group = r->group; } while ((from = from->next) != base);
  2363. // Merge the two circularly linked lists by swapping their next pointers.
  2364. upb_refcounted *tmp = r->next;
  2365. r->next = base->next;
  2366. base->next = tmp;
  2367. }
  2368. static void unref(const upb_refcounted *r);
  2369. static void release_ref2(const upb_refcounted *obj,
  2370. const upb_refcounted *subobj,
  2371. void *closure) {
  2372. UPB_UNUSED(closure);
  2373. untrack(subobj, obj, true);
  2374. if (!merged(obj, subobj)) {
  2375. assert(subobj->is_frozen);
  2376. unref(subobj);
  2377. }
  2378. }
  2379. static void unref(const upb_refcounted *r) {
  2380. if (unrefgroup(r->group)) {
  2381. free(r->group);
  2382. // In two passes, since release_ref2 needs a guarantee that any subobjs
  2383. // are alive.
  2384. const upb_refcounted *o = r;
  2385. do { visit(o, release_ref2, NULL); } while((o = o->next) != r);
  2386. o = r;
  2387. do {
  2388. const upb_refcounted *next = o->next;
  2389. assert(o->is_frozen || o->individual_count == 0);
  2390. freeobj((upb_refcounted*)o);
  2391. o = next;
  2392. } while(o != r);
  2393. }
  2394. }
  2395. static void freeobj(upb_refcounted *o) {
  2396. trackfree(o);
  2397. o->vtbl->free((upb_refcounted*)o);
  2398. }
  2399. /* Public interface ***********************************************************/
  2400. bool upb_refcounted_init(upb_refcounted *r,
  2401. const struct upb_refcounted_vtbl *vtbl,
  2402. const void *owner) {
  2403. r->next = r;
  2404. r->vtbl = vtbl;
  2405. r->individual_count = 0;
  2406. r->is_frozen = false;
  2407. r->group = malloc(sizeof(*r->group));
  2408. if (!r->group) return false;
  2409. *r->group = 0;
  2410. if (!trackinit(r)) {
  2411. free(r->group);
  2412. return false;
  2413. }
  2414. upb_refcounted_ref(r, owner);
  2415. return true;
  2416. }
  2417. bool upb_refcounted_isfrozen(const upb_refcounted *r) {
  2418. return r->is_frozen;
  2419. }
  2420. void upb_refcounted_ref(const upb_refcounted *r, const void *owner) {
  2421. track(r, owner, false);
  2422. if (!r->is_frozen)
  2423. ((upb_refcounted*)r)->individual_count++;
  2424. refgroup(r->group);
  2425. }
  2426. void upb_refcounted_unref(const upb_refcounted *r, const void *owner) {
  2427. untrack(r, owner, false);
  2428. if (!r->is_frozen)
  2429. ((upb_refcounted*)r)->individual_count--;
  2430. unref(r);
  2431. }
  2432. void upb_refcounted_ref2(const upb_refcounted *r, upb_refcounted *from) {
  2433. assert(!from->is_frozen); // Non-const pointer implies this.
  2434. track(r, from, true);
  2435. if (r->is_frozen) {
  2436. refgroup(r->group);
  2437. } else {
  2438. merge((upb_refcounted*)r, from);
  2439. }
  2440. }
  2441. void upb_refcounted_unref2(const upb_refcounted *r, upb_refcounted *from) {
  2442. assert(!from->is_frozen); // Non-const pointer implies this.
  2443. untrack(r, from, true);
  2444. if (r->is_frozen) {
  2445. unref(r);
  2446. } else {
  2447. assert(merged(r, from));
  2448. }
  2449. }
  2450. void upb_refcounted_donateref(
  2451. const upb_refcounted *r, const void *from, const void *to) {
  2452. assert(from != to);
  2453. if (to != NULL)
  2454. upb_refcounted_ref(r, to);
  2455. if (from != NULL)
  2456. upb_refcounted_unref(r, from);
  2457. }
  2458. void upb_refcounted_checkref(const upb_refcounted *r, const void *owner) {
  2459. checkref(r, owner, false);
  2460. }
  2461. bool upb_refcounted_freeze(upb_refcounted *const*roots, int n, upb_status *s,
  2462. int maxdepth) {
  2463. for (int i = 0; i < n; i++) {
  2464. assert(!roots[i]->is_frozen);
  2465. }
  2466. return freeze(roots, n, s, maxdepth);
  2467. }
  2468. /*
  2469. * upb - a minimalist implementation of protocol buffers.
  2470. *
  2471. * Copyright (c) 2013 Google Inc. See LICENSE for details.
  2472. * Author: Josh Haberman <jhaberman@gmail.com>
  2473. */
  2474. #include <stdlib.h>
  2475. // Fallback implementation if the shim is not specialized by the JIT.
  2476. #define SHIM_WRITER(type, ctype) \
  2477. bool upb_shim_set ## type (void *c, const void *hd, ctype val) { \
  2478. uint8_t *m = c; \
  2479. const upb_shim_data *d = hd; \
  2480. if (d->hasbit > 0) \
  2481. *(uint8_t*)&m[d->hasbit / 8] |= 1 << (d->hasbit % 8); \
  2482. *(ctype*)&m[d->offset] = val; \
  2483. return true; \
  2484. } \
  2485. SHIM_WRITER(double, double)
  2486. SHIM_WRITER(float, float)
  2487. SHIM_WRITER(int32, int32_t)
  2488. SHIM_WRITER(int64, int64_t)
  2489. SHIM_WRITER(uint32, uint32_t)
  2490. SHIM_WRITER(uint64, uint64_t)
  2491. SHIM_WRITER(bool, bool)
  2492. #undef SHIM_WRITER
  2493. bool upb_shim_set(upb_handlers *h, const upb_fielddef *f, size_t offset,
  2494. int32_t hasbit) {
  2495. upb_shim_data *d = malloc(sizeof(*d));
  2496. if (!d) return false;
  2497. d->offset = offset;
  2498. d->hasbit = hasbit;
  2499. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  2500. upb_handlerattr_sethandlerdata(&attr, d);
  2501. upb_handlerattr_setalwaysok(&attr, true);
  2502. upb_handlers_addcleanup(h, d, free);
  2503. #define TYPE(u, l) \
  2504. case UPB_TYPE_##u: \
  2505. ok = upb_handlers_set##l(h, f, upb_shim_set##l, &attr); break;
  2506. bool ok = false;
  2507. switch (upb_fielddef_type(f)) {
  2508. TYPE(INT64, int64);
  2509. TYPE(INT32, int32);
  2510. TYPE(ENUM, int32);
  2511. TYPE(UINT64, uint64);
  2512. TYPE(UINT32, uint32);
  2513. TYPE(DOUBLE, double);
  2514. TYPE(FLOAT, float);
  2515. TYPE(BOOL, bool);
  2516. default: assert(false); break;
  2517. }
  2518. #undef TYPE
  2519. upb_handlerattr_uninit(&attr);
  2520. return ok;
  2521. }
  2522. const upb_shim_data *upb_shim_getdata(const upb_handlers *h, upb_selector_t s,
  2523. upb_fieldtype_t *type) {
  2524. upb_func *f = upb_handlers_gethandler(h, s);
  2525. if ((upb_int64_handlerfunc*)f == upb_shim_setint64) {
  2526. *type = UPB_TYPE_INT64;
  2527. } else if ((upb_int32_handlerfunc*)f == upb_shim_setint32) {
  2528. *type = UPB_TYPE_INT32;
  2529. } else if ((upb_uint64_handlerfunc*)f == upb_shim_setuint64) {
  2530. *type = UPB_TYPE_UINT64;
  2531. } else if ((upb_uint32_handlerfunc*)f == upb_shim_setuint32) {
  2532. *type = UPB_TYPE_UINT32;
  2533. } else if ((upb_double_handlerfunc*)f == upb_shim_setdouble) {
  2534. *type = UPB_TYPE_DOUBLE;
  2535. } else if ((upb_float_handlerfunc*)f == upb_shim_setfloat) {
  2536. *type = UPB_TYPE_FLOAT;
  2537. } else if ((upb_bool_handlerfunc*)f == upb_shim_setbool) {
  2538. *type = UPB_TYPE_BOOL;
  2539. } else {
  2540. return NULL;
  2541. }
  2542. return (const upb_shim_data*)upb_handlers_gethandlerdata(h, s);
  2543. }
  2544. /*
  2545. * upb - a minimalist implementation of protocol buffers.
  2546. *
  2547. * Copyright (c) 2008-2012 Google Inc. See LICENSE for details.
  2548. * Author: Josh Haberman <jhaberman@gmail.com>
  2549. */
  2550. #include <stdlib.h>
  2551. #include <string.h>
  2552. bool upb_symtab_isfrozen(const upb_symtab *s) {
  2553. return upb_refcounted_isfrozen(UPB_UPCAST(s));
  2554. }
  2555. void upb_symtab_ref(const upb_symtab *s, const void *owner) {
  2556. upb_refcounted_ref(UPB_UPCAST(s), owner);
  2557. }
  2558. void upb_symtab_unref(const upb_symtab *s, const void *owner) {
  2559. upb_refcounted_unref(UPB_UPCAST(s), owner);
  2560. }
  2561. void upb_symtab_donateref(
  2562. const upb_symtab *s, const void *from, const void *to) {
  2563. upb_refcounted_donateref(UPB_UPCAST(s), from, to);
  2564. }
  2565. void upb_symtab_checkref(const upb_symtab *s, const void *owner) {
  2566. upb_refcounted_checkref(UPB_UPCAST(s), owner);
  2567. }
  2568. static void upb_symtab_free(upb_refcounted *r) {
  2569. upb_symtab *s = (upb_symtab*)r;
  2570. upb_strtable_iter i;
  2571. upb_strtable_begin(&i, &s->symtab);
  2572. for (; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  2573. const upb_def *def = upb_value_getptr(upb_strtable_iter_value(&i));
  2574. upb_def_unref(def, s);
  2575. }
  2576. upb_strtable_uninit(&s->symtab);
  2577. free(s);
  2578. }
  2579. upb_symtab *upb_symtab_new(const void *owner) {
  2580. static const struct upb_refcounted_vtbl vtbl = {NULL, &upb_symtab_free};
  2581. upb_symtab *s = malloc(sizeof(*s));
  2582. upb_refcounted_init(UPB_UPCAST(s), &vtbl, owner);
  2583. upb_strtable_init(&s->symtab, UPB_CTYPE_PTR);
  2584. return s;
  2585. }
  2586. void upb_symtab_freeze(upb_symtab *s) {
  2587. assert(!upb_symtab_isfrozen(s));
  2588. upb_refcounted *r = UPB_UPCAST(s);
  2589. // The symtab does not take ref2's (see refcounted.h) on the defs, because
  2590. // defs cannot refer back to the table and therefore cannot create cycles. So
  2591. // 0 will suffice for maxdepth here.
  2592. bool ok = upb_refcounted_freeze(&r, 1, NULL, 0);
  2593. UPB_ASSERT_VAR(ok, ok);
  2594. }
  2595. const upb_def *upb_symtab_lookup(const upb_symtab *s, const char *sym) {
  2596. upb_value v;
  2597. upb_def *ret = upb_strtable_lookup(&s->symtab, sym, &v) ?
  2598. upb_value_getptr(v) : NULL;
  2599. return ret;
  2600. }
  2601. const upb_msgdef *upb_symtab_lookupmsg(const upb_symtab *s, const char *sym) {
  2602. upb_value v;
  2603. upb_def *def = upb_strtable_lookup(&s->symtab, sym, &v) ?
  2604. upb_value_getptr(v) : NULL;
  2605. return def ? upb_dyncast_msgdef(def) : NULL;
  2606. }
  2607. const upb_enumdef *upb_symtab_lookupenum(const upb_symtab *s, const char *sym) {
  2608. upb_value v;
  2609. upb_def *def = upb_strtable_lookup(&s->symtab, sym, &v) ?
  2610. upb_value_getptr(v) : NULL;
  2611. return def ? upb_dyncast_enumdef(def) : NULL;
  2612. }
  2613. // Given a symbol and the base symbol inside which it is defined, find the
  2614. // symbol's definition in t.
  2615. static upb_def *upb_resolvename(const upb_strtable *t,
  2616. const char *base, const char *sym) {
  2617. if(strlen(sym) == 0) return NULL;
  2618. if(sym[0] == '.') {
  2619. // Symbols starting with '.' are absolute, so we do a single lookup.
  2620. // Slice to omit the leading '.'
  2621. upb_value v;
  2622. return upb_strtable_lookup(t, sym + 1, &v) ? upb_value_getptr(v) : NULL;
  2623. } else {
  2624. // Remove components from base until we find an entry or run out.
  2625. // TODO: This branch is totally broken, but currently not used.
  2626. (void)base;
  2627. assert(false);
  2628. return NULL;
  2629. }
  2630. }
  2631. const upb_def *upb_symtab_resolve(const upb_symtab *s, const char *base,
  2632. const char *sym) {
  2633. upb_def *ret = upb_resolvename(&s->symtab, base, sym);
  2634. return ret;
  2635. }
  2636. // Searches def and its children to find defs that have the same name as any
  2637. // def in "addtab." Returns true if any where found, and as a side-effect adds
  2638. // duplicates of these defs into addtab.
  2639. //
  2640. // We use a modified depth-first traversal that traverses each SCC (which we
  2641. // already computed) as if it were a single node. This allows us to traverse
  2642. // the possibly-cyclic graph as if it were a DAG and to dup the correct set of
  2643. // nodes with O(n) time.
  2644. static bool upb_resolve_dfs(const upb_def *def, upb_strtable *addtab,
  2645. const void *new_owner, upb_inttable *seen,
  2646. upb_status *s) {
  2647. // Memoize results of this function for efficiency (since we're traversing a
  2648. // DAG this is not needed to limit the depth of the search).
  2649. upb_value v;
  2650. if (upb_inttable_lookup(seen, (uintptr_t)def, &v))
  2651. return upb_value_getbool(v);
  2652. // Visit submessages for all messages in the SCC.
  2653. bool need_dup = false;
  2654. const upb_def *base = def;
  2655. do {
  2656. assert(upb_def_isfrozen(def));
  2657. if (def->type == UPB_DEF_FIELD) continue;
  2658. upb_value v;
  2659. if (upb_strtable_lookup(addtab, upb_def_fullname(def), &v)) {
  2660. need_dup = true;
  2661. }
  2662. // For messages, continue the recursion by visiting all subdefs.
  2663. const upb_msgdef *m = upb_dyncast_msgdef(def);
  2664. if (m) {
  2665. upb_msg_iter i;
  2666. for(upb_msg_begin(&i, m); !upb_msg_done(&i); upb_msg_next(&i)) {
  2667. upb_fielddef *f = upb_msg_iter_field(&i);
  2668. if (!upb_fielddef_hassubdef(f)) continue;
  2669. // |= to avoid short-circuit; we need its side-effects.
  2670. need_dup |= upb_resolve_dfs(
  2671. upb_fielddef_subdef(f), addtab, new_owner, seen, s);
  2672. if (!upb_ok(s)) return false;
  2673. }
  2674. }
  2675. } while ((def = (upb_def*)def->base.next) != base);
  2676. if (need_dup) {
  2677. // Dup any defs that don't already have entries in addtab.
  2678. def = base;
  2679. do {
  2680. if (def->type == UPB_DEF_FIELD) continue;
  2681. const char *name = upb_def_fullname(def);
  2682. if (!upb_strtable_lookup(addtab, name, NULL)) {
  2683. upb_def *newdef = upb_def_dup(def, new_owner);
  2684. if (!newdef) goto oom;
  2685. newdef->came_from_user = false;
  2686. if (!upb_strtable_insert(addtab, name, upb_value_ptr(newdef)))
  2687. goto oom;
  2688. }
  2689. } while ((def = (upb_def*)def->base.next) != base);
  2690. }
  2691. upb_inttable_insert(seen, (uintptr_t)def, upb_value_bool(need_dup));
  2692. return need_dup;
  2693. oom:
  2694. upb_status_seterrmsg(s, "out of memory");
  2695. return false;
  2696. }
  2697. // TODO(haberman): we need a lot more testing of error conditions.
  2698. // The came_from_user stuff in particular is not tested.
  2699. bool upb_symtab_add(upb_symtab *s, upb_def *const*defs, int n, void *ref_donor,
  2700. upb_status *status) {
  2701. assert(!upb_symtab_isfrozen(s));
  2702. upb_def **add_defs = NULL;
  2703. upb_strtable addtab;
  2704. if (!upb_strtable_init(&addtab, UPB_CTYPE_PTR)) {
  2705. upb_status_seterrmsg(status, "out of memory");
  2706. return false;
  2707. }
  2708. // Add new defs to our "add" set.
  2709. for (int i = 0; i < n; i++) {
  2710. upb_def *def = defs[i];
  2711. if (upb_def_isfrozen(def)) {
  2712. upb_status_seterrmsg(status, "added defs must be mutable");
  2713. goto err;
  2714. }
  2715. assert(!upb_def_isfrozen(def));
  2716. const char *fullname = upb_def_fullname(def);
  2717. if (!fullname) {
  2718. upb_status_seterrmsg(
  2719. status, "Anonymous defs cannot be added to a symtab");
  2720. goto err;
  2721. }
  2722. upb_fielddef *f = upb_dyncast_fielddef_mutable(def);
  2723. if (f) {
  2724. if (!upb_fielddef_containingtypename(f)) {
  2725. upb_status_seterrmsg(status,
  2726. "Standalone fielddefs must have a containing type "
  2727. "(extendee) name set");
  2728. goto err;
  2729. }
  2730. } else {
  2731. if (upb_strtable_lookup(&addtab, fullname, NULL)) {
  2732. upb_status_seterrf(status, "Conflicting defs named '%s'", fullname);
  2733. goto err;
  2734. }
  2735. // We need this to back out properly, because if there is a failure we
  2736. // need to donate the ref back to the caller.
  2737. def->came_from_user = true;
  2738. upb_def_donateref(def, ref_donor, s);
  2739. if (!upb_strtable_insert(&addtab, fullname, upb_value_ptr(def)))
  2740. goto oom_err;
  2741. }
  2742. }
  2743. // Add standalone fielddefs (ie. extensions) to the appropriate messages.
  2744. // If the appropriate message only exists in the existing symtab, duplicate
  2745. // it so we have a mutable copy we can add the fields to.
  2746. for (int i = 0; i < n; i++) {
  2747. upb_def *def = defs[i];
  2748. upb_fielddef *f = upb_dyncast_fielddef_mutable(def);
  2749. if (!f) continue;
  2750. const char *msgname = upb_fielddef_containingtypename(f);
  2751. // We validated this earlier in this function.
  2752. assert(msgname);
  2753. // If the extendee name is absolutely qualified, move past the initial ".".
  2754. // TODO(haberman): it is not obvious what it would mean if this was not
  2755. // absolutely qualified.
  2756. if (msgname[0] == '.') {
  2757. msgname++;
  2758. }
  2759. upb_value v;
  2760. upb_msgdef *m;
  2761. if (upb_strtable_lookup(&addtab, msgname, &v)) {
  2762. // Extendee is in the set of defs the user asked us to add.
  2763. m = upb_value_getptr(v);
  2764. } else {
  2765. // Need to find and dup the extendee from the existing symtab.
  2766. const upb_msgdef *frozen_m = upb_symtab_lookupmsg(s, msgname);
  2767. if (!frozen_m) {
  2768. upb_status_seterrf(status,
  2769. "Tried to extend message %s that does not exist "
  2770. "in this SymbolTable.",
  2771. msgname);
  2772. goto err;
  2773. }
  2774. m = upb_msgdef_dup(frozen_m, s);
  2775. if (!m) goto oom_err;
  2776. if (!upb_strtable_insert(&addtab, msgname, upb_value_ptr(m))) {
  2777. upb_msgdef_unref(m, s);
  2778. goto oom_err;
  2779. }
  2780. }
  2781. if (!upb_msgdef_addfield(m, f, ref_donor, status)) {
  2782. goto err;
  2783. }
  2784. }
  2785. // Add dups of any existing def that can reach a def with the same name as
  2786. // anything in our "add" set.
  2787. upb_inttable seen;
  2788. if (!upb_inttable_init(&seen, UPB_CTYPE_BOOL)) goto oom_err;
  2789. upb_strtable_iter i;
  2790. upb_strtable_begin(&i, &s->symtab);
  2791. for (; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  2792. upb_def *def = upb_value_getptr(upb_strtable_iter_value(&i));
  2793. upb_resolve_dfs(def, &addtab, s, &seen, status);
  2794. if (!upb_ok(status)) goto err;
  2795. }
  2796. upb_inttable_uninit(&seen);
  2797. // Now using the table, resolve symbolic references for subdefs.
  2798. upb_strtable_begin(&i, &addtab);
  2799. for (; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  2800. upb_def *def = upb_value_getptr(upb_strtable_iter_value(&i));
  2801. upb_msgdef *m = upb_dyncast_msgdef_mutable(def);
  2802. if (!m) continue;
  2803. // Type names are resolved relative to the message in which they appear.
  2804. const char *base = upb_msgdef_fullname(m);
  2805. upb_msg_iter j;
  2806. for(upb_msg_begin(&j, m); !upb_msg_done(&j); upb_msg_next(&j)) {
  2807. upb_fielddef *f = upb_msg_iter_field(&j);
  2808. const char *name = upb_fielddef_subdefname(f);
  2809. if (name && !upb_fielddef_subdef(f)) {
  2810. // Try the lookup in the current set of to-be-added defs first. If not
  2811. // there, try existing defs.
  2812. upb_def *subdef = upb_resolvename(&addtab, base, name);
  2813. if (subdef == NULL) {
  2814. subdef = upb_resolvename(&s->symtab, base, name);
  2815. }
  2816. if (subdef == NULL) {
  2817. upb_status_seterrf(
  2818. status, "couldn't resolve name '%s' in message '%s'", name, base);
  2819. goto err;
  2820. } else if (!upb_fielddef_setsubdef(f, subdef, status)) {
  2821. goto err;
  2822. }
  2823. }
  2824. }
  2825. }
  2826. // We need an array of the defs in addtab, for passing to upb_def_freeze.
  2827. add_defs = malloc(sizeof(void*) * upb_strtable_count(&addtab));
  2828. if (add_defs == NULL) goto oom_err;
  2829. upb_strtable_begin(&i, &addtab);
  2830. for (n = 0; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  2831. add_defs[n++] = upb_value_getptr(upb_strtable_iter_value(&i));
  2832. }
  2833. if (!upb_def_freeze(add_defs, n, status)) goto err;
  2834. // This must be delayed until all errors have been detected, since error
  2835. // recovery code uses this table to cleanup defs.
  2836. upb_strtable_uninit(&addtab);
  2837. // TODO(haberman) we don't properly handle errors after this point (like
  2838. // OOM in upb_strtable_insert() below).
  2839. for (int i = 0; i < n; i++) {
  2840. upb_def *def = add_defs[i];
  2841. const char *name = upb_def_fullname(def);
  2842. upb_value v;
  2843. if (upb_strtable_remove(&s->symtab, name, &v)) {
  2844. const upb_def *def = upb_value_getptr(v);
  2845. upb_def_unref(def, s);
  2846. }
  2847. bool success = upb_strtable_insert(&s->symtab, name, upb_value_ptr(def));
  2848. UPB_ASSERT_VAR(success, success == true);
  2849. }
  2850. free(add_defs);
  2851. return true;
  2852. oom_err:
  2853. upb_status_seterrmsg(status, "out of memory");
  2854. err: {
  2855. // For defs the user passed in, we need to donate the refs back. For defs
  2856. // we dup'd, we need to just unref them.
  2857. upb_strtable_iter i;
  2858. upb_strtable_begin(&i, &addtab);
  2859. for (; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  2860. upb_def *def = upb_value_getptr(upb_strtable_iter_value(&i));
  2861. bool came_from_user = def->came_from_user;
  2862. def->came_from_user = false;
  2863. if (came_from_user) {
  2864. upb_def_donateref(def, s, ref_donor);
  2865. } else {
  2866. upb_def_unref(def, s);
  2867. }
  2868. }
  2869. }
  2870. upb_strtable_uninit(&addtab);
  2871. free(add_defs);
  2872. assert(!upb_ok(status));
  2873. return false;
  2874. }
  2875. // Iteration.
  2876. static void advance_to_matching(upb_symtab_iter *iter) {
  2877. if (iter->type == UPB_DEF_ANY)
  2878. return;
  2879. while (!upb_strtable_done(&iter->iter) &&
  2880. iter->type != upb_symtab_iter_def(iter)->type) {
  2881. upb_strtable_next(&iter->iter);
  2882. }
  2883. }
  2884. void upb_symtab_begin(upb_symtab_iter *iter, const upb_symtab *s,
  2885. upb_deftype_t type) {
  2886. upb_strtable_begin(&iter->iter, &s->symtab);
  2887. iter->type = type;
  2888. advance_to_matching(iter);
  2889. }
  2890. void upb_symtab_next(upb_symtab_iter *iter) {
  2891. upb_strtable_next(&iter->iter);
  2892. advance_to_matching(iter);
  2893. }
  2894. bool upb_symtab_done(const upb_symtab_iter *iter) {
  2895. return upb_strtable_done(&iter->iter);
  2896. }
  2897. const upb_def *upb_symtab_iter_def(const upb_symtab_iter *iter) {
  2898. return upb_value_getptr(upb_strtable_iter_value(&iter->iter));
  2899. }
  2900. /*
  2901. * upb - a minimalist implementation of protocol buffers.
  2902. *
  2903. * Copyright (c) 2009 Google Inc. See LICENSE for details.
  2904. * Author: Josh Haberman <jhaberman@gmail.com>
  2905. *
  2906. * Implementation is heavily inspired by Lua's ltable.c.
  2907. */
  2908. #include <stdlib.h>
  2909. #include <string.h>
  2910. #define UPB_MAXARRSIZE 16 // 64k.
  2911. // From Chromium.
  2912. #define ARRAY_SIZE(x) \
  2913. ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x])))))
  2914. static const double MAX_LOAD = 0.85;
  2915. // The minimum utilization of the array part of a mixed hash/array table. This
  2916. // is a speed/memory-usage tradeoff (though it's not straightforward because of
  2917. // cache effects). The lower this is, the more memory we'll use.
  2918. static const double MIN_DENSITY = 0.1;
  2919. bool is_pow2(uint64_t v) { return v == 0 || (v & (v - 1)) == 0; }
  2920. int log2ceil(uint64_t v) {
  2921. int ret = 0;
  2922. bool pow2 = is_pow2(v);
  2923. while (v >>= 1) ret++;
  2924. ret = pow2 ? ret : ret + 1; // Ceiling.
  2925. return UPB_MIN(UPB_MAXARRSIZE, ret);
  2926. }
  2927. char *upb_strdup(const char *s) {
  2928. return upb_strdup2(s, strlen(s));
  2929. }
  2930. char *upb_strdup2(const char *s, size_t len) {
  2931. // Always null-terminate, even if binary data; but don't rely on the input to
  2932. // have a null-terminating byte since it may be a raw binary buffer.
  2933. size_t n = len + 1;
  2934. char *p = malloc(n);
  2935. if (p) {
  2936. memcpy(p, s, len);
  2937. p[len] = 0;
  2938. }
  2939. return p;
  2940. }
  2941. // A type to represent the lookup key of either a strtable or an inttable.
  2942. typedef struct {
  2943. upb_tabkey key;
  2944. } lookupkey_t;
  2945. static lookupkey_t strkey2(const char *str, size_t len) {
  2946. lookupkey_t k;
  2947. k.key.s.str = (char*)str;
  2948. k.key.s.length = len;
  2949. return k;
  2950. }
  2951. static lookupkey_t intkey(uintptr_t key) {
  2952. lookupkey_t k;
  2953. k.key = upb_intkey(key);
  2954. return k;
  2955. }
  2956. typedef uint32_t hashfunc_t(upb_tabkey key);
  2957. typedef bool eqlfunc_t(upb_tabkey k1, lookupkey_t k2);
  2958. /* Base table (shared code) ***************************************************/
  2959. // For when we need to cast away const.
  2960. static upb_tabent *mutable_entries(upb_table *t) {
  2961. return (upb_tabent*)t->entries;
  2962. }
  2963. static bool isfull(upb_table *t) {
  2964. return (double)(t->count + 1) / upb_table_size(t) > MAX_LOAD;
  2965. }
  2966. static bool init(upb_table *t, upb_ctype_t ctype, uint8_t size_lg2) {
  2967. t->count = 0;
  2968. t->ctype = ctype;
  2969. t->size_lg2 = size_lg2;
  2970. t->mask = upb_table_size(t) ? upb_table_size(t) - 1 : 0;
  2971. size_t bytes = upb_table_size(t) * sizeof(upb_tabent);
  2972. if (bytes > 0) {
  2973. t->entries = malloc(bytes);
  2974. if (!t->entries) return false;
  2975. memset(mutable_entries(t), 0, bytes);
  2976. } else {
  2977. t->entries = NULL;
  2978. }
  2979. return true;
  2980. }
  2981. static void uninit(upb_table *t) { free(mutable_entries(t)); }
  2982. static upb_tabent *emptyent(upb_table *t) {
  2983. upb_tabent *e = mutable_entries(t) + upb_table_size(t);
  2984. while (1) { if (upb_tabent_isempty(--e)) return e; assert(e > t->entries); }
  2985. }
  2986. static upb_tabent *getentry_mutable(upb_table *t, uint32_t hash) {
  2987. return (upb_tabent*)upb_getentry(t, hash);
  2988. }
  2989. static const upb_tabent *findentry(const upb_table *t, lookupkey_t key,
  2990. uint32_t hash, eqlfunc_t *eql) {
  2991. if (t->size_lg2 == 0) return NULL;
  2992. const upb_tabent *e = upb_getentry(t, hash);
  2993. if (upb_tabent_isempty(e)) return NULL;
  2994. while (1) {
  2995. if (eql(e->key, key)) return e;
  2996. if ((e = e->next) == NULL) return NULL;
  2997. }
  2998. }
  2999. static upb_tabent *findentry_mutable(upb_table *t, lookupkey_t key,
  3000. uint32_t hash, eqlfunc_t *eql) {
  3001. return (upb_tabent*)findentry(t, key, hash, eql);
  3002. }
  3003. static bool lookup(const upb_table *t, lookupkey_t key, upb_value *v,
  3004. uint32_t hash, eqlfunc_t *eql) {
  3005. const upb_tabent *e = findentry(t, key, hash, eql);
  3006. if (e) {
  3007. if (v) {
  3008. _upb_value_setval(v, e->val, t->ctype);
  3009. }
  3010. return true;
  3011. } else {
  3012. return false;
  3013. }
  3014. }
  3015. // The given key must not already exist in the table.
  3016. static void insert(upb_table *t, lookupkey_t key, upb_value val,
  3017. uint32_t hash, hashfunc_t *hashfunc, eqlfunc_t *eql) {
  3018. UPB_UNUSED(eql);
  3019. assert(findentry(t, key, hash, eql) == NULL);
  3020. assert(val.ctype == t->ctype);
  3021. t->count++;
  3022. upb_tabent *mainpos_e = getentry_mutable(t, hash);
  3023. upb_tabent *our_e = mainpos_e;
  3024. if (upb_tabent_isempty(mainpos_e)) {
  3025. // Our main position is empty; use it.
  3026. our_e->next = NULL;
  3027. } else {
  3028. // Collision.
  3029. upb_tabent *new_e = emptyent(t);
  3030. // Head of collider's chain.
  3031. upb_tabent *chain = getentry_mutable(t, hashfunc(mainpos_e->key));
  3032. if (chain == mainpos_e) {
  3033. // Existing ent is in its main posisiton (it has the same hash as us, and
  3034. // is the head of our chain). Insert to new ent and append to this chain.
  3035. new_e->next = mainpos_e->next;
  3036. mainpos_e->next = new_e;
  3037. our_e = new_e;
  3038. } else {
  3039. // Existing ent is not in its main position (it is a node in some other
  3040. // chain). This implies that no existing ent in the table has our hash.
  3041. // Evict it (updating its chain) and use its ent for head of our chain.
  3042. *new_e = *mainpos_e; // copies next.
  3043. while (chain->next != mainpos_e) {
  3044. chain = (upb_tabent*)chain->next;
  3045. assert(chain);
  3046. }
  3047. chain->next = new_e;
  3048. our_e = mainpos_e;
  3049. our_e->next = NULL;
  3050. }
  3051. }
  3052. our_e->key = key.key;
  3053. our_e->val = val.val;
  3054. assert(findentry(t, key, hash, eql) == our_e);
  3055. }
  3056. static bool rm(upb_table *t, lookupkey_t key, upb_value *val,
  3057. upb_tabkey *removed, uint32_t hash, eqlfunc_t *eql) {
  3058. upb_tabent *chain = getentry_mutable(t, hash);
  3059. if (upb_tabent_isempty(chain)) return false;
  3060. if (eql(chain->key, key)) {
  3061. // Element to remove is at the head of its chain.
  3062. t->count--;
  3063. if (val) {
  3064. _upb_value_setval(val, chain->val, t->ctype);
  3065. }
  3066. if (chain->next) {
  3067. upb_tabent *move = (upb_tabent*)chain->next;
  3068. *chain = *move;
  3069. if (removed) *removed = move->key;
  3070. move->key.num = 0; // Make the slot empty.
  3071. } else {
  3072. if (removed) *removed = chain->key;
  3073. chain->key.num = 0; // Make the slot empty.
  3074. }
  3075. return true;
  3076. } else {
  3077. // Element to remove is either in a non-head position or not in the table.
  3078. while (chain->next && !eql(chain->next->key, key))
  3079. chain = (upb_tabent*)chain->next;
  3080. if (chain->next) {
  3081. // Found element to remove.
  3082. if (val) {
  3083. _upb_value_setval(val, chain->next->val, t->ctype);
  3084. }
  3085. upb_tabent *rm = (upb_tabent*)chain->next;
  3086. if (removed) *removed = rm->key;
  3087. rm->key.num = 0;
  3088. chain->next = rm->next;
  3089. t->count--;
  3090. return true;
  3091. } else {
  3092. return false;
  3093. }
  3094. }
  3095. }
  3096. static size_t next(const upb_table *t, size_t i) {
  3097. do {
  3098. if (++i >= upb_table_size(t))
  3099. return SIZE_MAX;
  3100. } while(upb_tabent_isempty(&t->entries[i]));
  3101. return i;
  3102. }
  3103. static size_t begin(const upb_table *t) {
  3104. return next(t, -1);
  3105. }
  3106. /* upb_strtable ***************************************************************/
  3107. // A simple "subclass" of upb_table that only adds a hash function for strings.
  3108. static uint32_t strhash(upb_tabkey key) {
  3109. return MurmurHash2(key.s.str, key.s.length, 0);
  3110. }
  3111. static bool streql(upb_tabkey k1, lookupkey_t k2) {
  3112. return k1.s.length == k2.key.s.length &&
  3113. memcmp(k1.s.str, k2.key.s.str, k1.s.length) == 0;
  3114. }
  3115. bool upb_strtable_init(upb_strtable *t, upb_ctype_t ctype) {
  3116. return init(&t->t, ctype, 2);
  3117. }
  3118. void upb_strtable_uninit(upb_strtable *t) {
  3119. for (size_t i = 0; i < upb_table_size(&t->t); i++)
  3120. free((void*)t->t.entries[i].key.s.str);
  3121. uninit(&t->t);
  3122. }
  3123. bool upb_strtable_resize(upb_strtable *t, size_t size_lg2) {
  3124. upb_strtable new_table;
  3125. if (!init(&new_table.t, t->t.ctype, size_lg2))
  3126. return false;
  3127. upb_strtable_iter i;
  3128. upb_strtable_begin(&i, t);
  3129. for ( ; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  3130. upb_strtable_insert2(
  3131. &new_table,
  3132. upb_strtable_iter_key(&i),
  3133. upb_strtable_iter_keylength(&i),
  3134. upb_strtable_iter_value(&i));
  3135. }
  3136. upb_strtable_uninit(t);
  3137. *t = new_table;
  3138. return true;
  3139. }
  3140. bool upb_strtable_insert2(upb_strtable *t, const char *k, size_t len,
  3141. upb_value v) {
  3142. if (isfull(&t->t)) {
  3143. // Need to resize. New table of double the size, add old elements to it.
  3144. if (!upb_strtable_resize(t, t->t.size_lg2 + 1)) {
  3145. return false;
  3146. }
  3147. }
  3148. if ((k = upb_strdup2(k, len)) == NULL) return false;
  3149. lookupkey_t key = strkey2(k, len);
  3150. uint32_t hash = MurmurHash2(key.key.s.str, key.key.s.length, 0);
  3151. insert(&t->t, key, v, hash, &strhash, &streql);
  3152. return true;
  3153. }
  3154. bool upb_strtable_lookup2(const upb_strtable *t, const char *key, size_t len,
  3155. upb_value *v) {
  3156. uint32_t hash = MurmurHash2(key, len, 0);
  3157. return lookup(&t->t, strkey2(key, len), v, hash, &streql);
  3158. }
  3159. bool upb_strtable_remove2(upb_strtable *t, const char *key, size_t len,
  3160. upb_value *val) {
  3161. uint32_t hash = MurmurHash2(key, strlen(key), 0);
  3162. upb_tabkey tabkey;
  3163. if (rm(&t->t, strkey2(key, len), val, &tabkey, hash, &streql)) {
  3164. free((void*)tabkey.s.str);
  3165. return true;
  3166. } else {
  3167. return false;
  3168. }
  3169. }
  3170. // Iteration
  3171. static const upb_tabent *str_tabent(const upb_strtable_iter *i) {
  3172. return &i->t->t.entries[i->index];
  3173. }
  3174. void upb_strtable_begin(upb_strtable_iter *i, const upb_strtable *t) {
  3175. i->t = t;
  3176. i->index = begin(&t->t);
  3177. }
  3178. void upb_strtable_next(upb_strtable_iter *i) {
  3179. i->index = next(&i->t->t, i->index);
  3180. }
  3181. bool upb_strtable_done(const upb_strtable_iter *i) {
  3182. return i->index >= upb_table_size(&i->t->t) ||
  3183. upb_tabent_isempty(str_tabent(i));
  3184. }
  3185. const char *upb_strtable_iter_key(upb_strtable_iter *i) {
  3186. assert(!upb_strtable_done(i));
  3187. return str_tabent(i)->key.s.str;
  3188. }
  3189. size_t upb_strtable_iter_keylength(upb_strtable_iter *i) {
  3190. assert(!upb_strtable_done(i));
  3191. return str_tabent(i)->key.s.length;
  3192. }
  3193. upb_value upb_strtable_iter_value(const upb_strtable_iter *i) {
  3194. assert(!upb_strtable_done(i));
  3195. return _upb_value_val(str_tabent(i)->val, i->t->t.ctype);
  3196. }
  3197. void upb_strtable_iter_setdone(upb_strtable_iter *i) {
  3198. i->index = SIZE_MAX;
  3199. }
  3200. bool upb_strtable_iter_isequal(const upb_strtable_iter *i1,
  3201. const upb_strtable_iter *i2) {
  3202. if (upb_strtable_done(i1) && upb_strtable_done(i2))
  3203. return true;
  3204. return i1->t == i2->t && i1->index == i2->index;
  3205. }
  3206. /* upb_inttable ***************************************************************/
  3207. // For inttables we use a hybrid structure where small keys are kept in an
  3208. // array and large keys are put in the hash table.
  3209. static uint32_t inthash(upb_tabkey key) { return upb_inthash(key.num); }
  3210. static bool inteql(upb_tabkey k1, lookupkey_t k2) {
  3211. return k1.num == k2.key.num;
  3212. }
  3213. static _upb_value *mutable_array(upb_inttable *t) {
  3214. return (_upb_value*)t->array;
  3215. }
  3216. static _upb_value *inttable_val(upb_inttable *t, uintptr_t key) {
  3217. if (key < t->array_size) {
  3218. return upb_arrhas(t->array[key]) ? &(mutable_array(t)[key]) : NULL;
  3219. } else {
  3220. upb_tabent *e =
  3221. findentry_mutable(&t->t, intkey(key), upb_inthash(key), &inteql);
  3222. return e ? &e->val : NULL;
  3223. }
  3224. }
  3225. static const _upb_value *inttable_val_const(const upb_inttable *t,
  3226. uintptr_t key) {
  3227. return inttable_val((upb_inttable*)t, key);
  3228. }
  3229. size_t upb_inttable_count(const upb_inttable *t) {
  3230. return t->t.count + t->array_count;
  3231. }
  3232. static void check(upb_inttable *t) {
  3233. UPB_UNUSED(t);
  3234. #if defined(UPB_DEBUG_TABLE) && !defined(NDEBUG)
  3235. // This check is very expensive (makes inserts/deletes O(N)).
  3236. size_t count = 0;
  3237. upb_inttable_iter i;
  3238. upb_inttable_begin(&i, t);
  3239. for(; !upb_inttable_done(&i); upb_inttable_next(&i), count++) {
  3240. assert(upb_inttable_lookup(t, upb_inttable_iter_key(&i), NULL));
  3241. }
  3242. assert(count == upb_inttable_count(t));
  3243. #endif
  3244. }
  3245. bool upb_inttable_sizedinit(upb_inttable *t, upb_ctype_t ctype,
  3246. size_t asize, int hsize_lg2) {
  3247. if (!init(&t->t, ctype, hsize_lg2)) return false;
  3248. // Always make the array part at least 1 long, so that we know key 0
  3249. // won't be in the hash part, which simplifies things.
  3250. t->array_size = UPB_MAX(1, asize);
  3251. t->array_count = 0;
  3252. size_t array_bytes = t->array_size * sizeof(upb_value);
  3253. t->array = malloc(array_bytes);
  3254. if (!t->array) {
  3255. uninit(&t->t);
  3256. return false;
  3257. }
  3258. memset(mutable_array(t), 0xff, array_bytes);
  3259. check(t);
  3260. return true;
  3261. }
  3262. bool upb_inttable_init(upb_inttable *t, upb_ctype_t ctype) {
  3263. return upb_inttable_sizedinit(t, ctype, 0, 4);
  3264. }
  3265. void upb_inttable_uninit(upb_inttable *t) {
  3266. uninit(&t->t);
  3267. free(mutable_array(t));
  3268. }
  3269. bool upb_inttable_insert(upb_inttable *t, uintptr_t key, upb_value val) {
  3270. assert(upb_arrhas(val.val));
  3271. if (key < t->array_size) {
  3272. assert(!upb_arrhas(t->array[key]));
  3273. t->array_count++;
  3274. mutable_array(t)[key] = val.val;
  3275. } else {
  3276. if (isfull(&t->t)) {
  3277. // Need to resize the hash part, but we re-use the array part.
  3278. upb_table new_table;
  3279. if (!init(&new_table, t->t.ctype, t->t.size_lg2 + 1))
  3280. return false;
  3281. size_t i;
  3282. for (i = begin(&t->t); i < upb_table_size(&t->t); i = next(&t->t, i)) {
  3283. const upb_tabent *e = &t->t.entries[i];
  3284. upb_value v;
  3285. _upb_value_setval(&v, e->val, t->t.ctype);
  3286. uint32_t hash = upb_inthash(e->key.num);
  3287. insert(&new_table, intkey(e->key.num), v, hash, &inthash, &inteql);
  3288. }
  3289. assert(t->t.count == new_table.count);
  3290. uninit(&t->t);
  3291. t->t = new_table;
  3292. }
  3293. insert(&t->t, intkey(key), val, upb_inthash(key), &inthash, &inteql);
  3294. }
  3295. check(t);
  3296. return true;
  3297. }
  3298. bool upb_inttable_lookup(const upb_inttable *t, uintptr_t key, upb_value *v) {
  3299. const _upb_value *table_v = inttable_val_const(t, key);
  3300. if (!table_v) return false;
  3301. if (v) _upb_value_setval(v, *table_v, t->t.ctype);
  3302. return true;
  3303. }
  3304. bool upb_inttable_replace(upb_inttable *t, uintptr_t key, upb_value val) {
  3305. _upb_value *table_v = inttable_val(t, key);
  3306. if (!table_v) return false;
  3307. *table_v = val.val;
  3308. return true;
  3309. }
  3310. bool upb_inttable_remove(upb_inttable *t, uintptr_t key, upb_value *val) {
  3311. bool success;
  3312. if (key < t->array_size) {
  3313. if (upb_arrhas(t->array[key])) {
  3314. t->array_count--;
  3315. if (val) {
  3316. _upb_value_setval(val, t->array[key], t->t.ctype);
  3317. }
  3318. _upb_value empty = UPB_ARRAY_EMPTYENT;
  3319. mutable_array(t)[key] = empty;
  3320. success = true;
  3321. } else {
  3322. success = false;
  3323. }
  3324. } else {
  3325. upb_tabkey removed;
  3326. uint32_t hash = upb_inthash(key);
  3327. success = rm(&t->t, intkey(key), val, &removed, hash, &inteql);
  3328. }
  3329. check(t);
  3330. return success;
  3331. }
  3332. bool upb_inttable_push(upb_inttable *t, upb_value val) {
  3333. return upb_inttable_insert(t, upb_inttable_count(t), val);
  3334. }
  3335. upb_value upb_inttable_pop(upb_inttable *t) {
  3336. upb_value val;
  3337. bool ok = upb_inttable_remove(t, upb_inttable_count(t) - 1, &val);
  3338. UPB_ASSERT_VAR(ok, ok);
  3339. return val;
  3340. }
  3341. bool upb_inttable_insertptr(upb_inttable *t, const void *key, upb_value val) {
  3342. return upb_inttable_insert(t, (uintptr_t)key, val);
  3343. }
  3344. bool upb_inttable_lookupptr(const upb_inttable *t, const void *key,
  3345. upb_value *v) {
  3346. return upb_inttable_lookup(t, (uintptr_t)key, v);
  3347. }
  3348. bool upb_inttable_removeptr(upb_inttable *t, const void *key, upb_value *val) {
  3349. return upb_inttable_remove(t, (uintptr_t)key, val);
  3350. }
  3351. void upb_inttable_compact(upb_inttable *t) {
  3352. // Create a power-of-two histogram of the table keys.
  3353. int counts[UPB_MAXARRSIZE + 1] = {0};
  3354. uintptr_t max_key = 0;
  3355. upb_inttable_iter i;
  3356. upb_inttable_begin(&i, t);
  3357. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  3358. uintptr_t key = upb_inttable_iter_key(&i);
  3359. if (key > max_key) {
  3360. max_key = key;
  3361. }
  3362. counts[log2ceil(key)]++;
  3363. }
  3364. int arr_size;
  3365. int arr_count = upb_inttable_count(t);
  3366. if (upb_inttable_count(t) >= max_key * MIN_DENSITY) {
  3367. // We can put 100% of the entries in the array part.
  3368. arr_size = max_key + 1;
  3369. } else {
  3370. // Find the largest power of two that satisfies the MIN_DENSITY definition.
  3371. for (int size_lg2 = ARRAY_SIZE(counts) - 1; size_lg2 > 1; size_lg2--) {
  3372. arr_size = 1 << size_lg2;
  3373. arr_count -= counts[size_lg2];
  3374. if (arr_count >= arr_size * MIN_DENSITY) {
  3375. break;
  3376. }
  3377. }
  3378. }
  3379. // Array part must always be at least 1 entry large to catch lookups of key
  3380. // 0. Key 0 must always be in the array part because "0" in the hash part
  3381. // denotes an empty entry.
  3382. arr_size = UPB_MAX(arr_size, 1);
  3383. // Insert all elements into new, perfectly-sized table.
  3384. int hash_count = upb_inttable_count(t) - arr_count;
  3385. int hash_size = hash_count ? (hash_count / MAX_LOAD) + 1 : 0;
  3386. int hashsize_lg2 = log2ceil(hash_size);
  3387. assert(hash_count >= 0);
  3388. upb_inttable new_t;
  3389. upb_inttable_sizedinit(&new_t, t->t.ctype, arr_size, hashsize_lg2);
  3390. upb_inttable_begin(&i, t);
  3391. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  3392. uintptr_t k = upb_inttable_iter_key(&i);
  3393. upb_inttable_insert(&new_t, k, upb_inttable_iter_value(&i));
  3394. }
  3395. assert(new_t.array_size == arr_size);
  3396. assert(new_t.t.size_lg2 == hashsize_lg2);
  3397. upb_inttable_uninit(t);
  3398. *t = new_t;
  3399. }
  3400. // Iteration.
  3401. static const upb_tabent *int_tabent(const upb_inttable_iter *i) {
  3402. assert(!i->array_part);
  3403. return &i->t->t.entries[i->index];
  3404. }
  3405. static _upb_value int_arrent(const upb_inttable_iter *i) {
  3406. assert(i->array_part);
  3407. return i->t->array[i->index];
  3408. }
  3409. void upb_inttable_begin(upb_inttable_iter *i, const upb_inttable *t) {
  3410. i->t = t;
  3411. i->index = -1;
  3412. i->array_part = true;
  3413. upb_inttable_next(i);
  3414. }
  3415. void upb_inttable_next(upb_inttable_iter *iter) {
  3416. const upb_inttable *t = iter->t;
  3417. if (iter->array_part) {
  3418. while (++iter->index < t->array_size) {
  3419. if (upb_arrhas(int_arrent(iter))) {
  3420. return;
  3421. }
  3422. }
  3423. iter->array_part = false;
  3424. iter->index = begin(&t->t);
  3425. } else {
  3426. iter->index = next(&t->t, iter->index);
  3427. }
  3428. }
  3429. bool upb_inttable_done(const upb_inttable_iter *i) {
  3430. if (i->array_part) {
  3431. return i->index >= i->t->array_size ||
  3432. !upb_arrhas(int_arrent(i));
  3433. } else {
  3434. return i->index >= upb_table_size(&i->t->t) ||
  3435. upb_tabent_isempty(int_tabent(i));
  3436. }
  3437. }
  3438. uintptr_t upb_inttable_iter_key(const upb_inttable_iter *i) {
  3439. assert(!upb_inttable_done(i));
  3440. return i->array_part ? i->index : int_tabent(i)->key.num;
  3441. }
  3442. upb_value upb_inttable_iter_value(const upb_inttable_iter *i) {
  3443. assert(!upb_inttable_done(i));
  3444. return _upb_value_val(
  3445. i->array_part ? i->t->array[i->index] : int_tabent(i)->val,
  3446. i->t->t.ctype);
  3447. }
  3448. void upb_inttable_iter_setdone(upb_inttable_iter *i) {
  3449. i->index = SIZE_MAX;
  3450. i->array_part = false;
  3451. }
  3452. bool upb_inttable_iter_isequal(const upb_inttable_iter *i1,
  3453. const upb_inttable_iter *i2) {
  3454. if (upb_inttable_done(i1) && upb_inttable_done(i2))
  3455. return true;
  3456. return i1->t == i2->t && i1->index == i2->index &&
  3457. i1->array_part == i2->array_part;
  3458. }
  3459. #ifdef UPB_UNALIGNED_READS_OK
  3460. //-----------------------------------------------------------------------------
  3461. // MurmurHash2, by Austin Appleby (released as public domain).
  3462. // Reformatted and C99-ified by Joshua Haberman.
  3463. // Note - This code makes a few assumptions about how your machine behaves -
  3464. // 1. We can read a 4-byte value from any address without crashing
  3465. // 2. sizeof(int) == 4 (in upb this limitation is removed by using uint32_t
  3466. // And it has a few limitations -
  3467. // 1. It will not work incrementally.
  3468. // 2. It will not produce the same results on little-endian and big-endian
  3469. // machines.
  3470. uint32_t MurmurHash2(const void *key, size_t len, uint32_t seed) {
  3471. // 'm' and 'r' are mixing constants generated offline.
  3472. // They're not really 'magic', they just happen to work well.
  3473. const uint32_t m = 0x5bd1e995;
  3474. const int32_t r = 24;
  3475. // Initialize the hash to a 'random' value
  3476. uint32_t h = seed ^ len;
  3477. // Mix 4 bytes at a time into the hash
  3478. const uint8_t * data = (const uint8_t *)key;
  3479. while(len >= 4) {
  3480. uint32_t k = *(uint32_t *)data;
  3481. k *= m;
  3482. k ^= k >> r;
  3483. k *= m;
  3484. h *= m;
  3485. h ^= k;
  3486. data += 4;
  3487. len -= 4;
  3488. }
  3489. // Handle the last few bytes of the input array
  3490. switch(len) {
  3491. case 3: h ^= data[2] << 16;
  3492. case 2: h ^= data[1] << 8;
  3493. case 1: h ^= data[0]; h *= m;
  3494. };
  3495. // Do a few final mixes of the hash to ensure the last few
  3496. // bytes are well-incorporated.
  3497. h ^= h >> 13;
  3498. h *= m;
  3499. h ^= h >> 15;
  3500. return h;
  3501. }
  3502. #else // !UPB_UNALIGNED_READS_OK
  3503. //-----------------------------------------------------------------------------
  3504. // MurmurHashAligned2, by Austin Appleby
  3505. // Same algorithm as MurmurHash2, but only does aligned reads - should be safer
  3506. // on certain platforms.
  3507. // Performance will be lower than MurmurHash2
  3508. #define MIX(h,k,m) { k *= m; k ^= k >> r; k *= m; h *= m; h ^= k; }
  3509. uint32_t MurmurHash2(const void * key, size_t len, uint32_t seed) {
  3510. const uint32_t m = 0x5bd1e995;
  3511. const int32_t r = 24;
  3512. const uint8_t * data = (const uint8_t *)key;
  3513. uint32_t h = seed ^ len;
  3514. uint8_t align = (uintptr_t)data & 3;
  3515. if(align && (len >= 4)) {
  3516. // Pre-load the temp registers
  3517. uint32_t t = 0, d = 0;
  3518. switch(align) {
  3519. case 1: t |= data[2] << 16;
  3520. case 2: t |= data[1] << 8;
  3521. case 3: t |= data[0];
  3522. }
  3523. t <<= (8 * align);
  3524. data += 4-align;
  3525. len -= 4-align;
  3526. int32_t sl = 8 * (4-align);
  3527. int32_t sr = 8 * align;
  3528. // Mix
  3529. while(len >= 4) {
  3530. d = *(uint32_t *)data;
  3531. t = (t >> sr) | (d << sl);
  3532. uint32_t k = t;
  3533. MIX(h,k,m);
  3534. t = d;
  3535. data += 4;
  3536. len -= 4;
  3537. }
  3538. // Handle leftover data in temp registers
  3539. d = 0;
  3540. if(len >= align) {
  3541. switch(align) {
  3542. case 3: d |= data[2] << 16;
  3543. case 2: d |= data[1] << 8;
  3544. case 1: d |= data[0];
  3545. }
  3546. uint32_t k = (t >> sr) | (d << sl);
  3547. MIX(h,k,m);
  3548. data += align;
  3549. len -= align;
  3550. //----------
  3551. // Handle tail bytes
  3552. switch(len) {
  3553. case 3: h ^= data[2] << 16;
  3554. case 2: h ^= data[1] << 8;
  3555. case 1: h ^= data[0]; h *= m;
  3556. };
  3557. } else {
  3558. switch(len) {
  3559. case 3: d |= data[2] << 16;
  3560. case 2: d |= data[1] << 8;
  3561. case 1: d |= data[0];
  3562. case 0: h ^= (t >> sr) | (d << sl); h *= m;
  3563. }
  3564. }
  3565. h ^= h >> 13;
  3566. h *= m;
  3567. h ^= h >> 15;
  3568. return h;
  3569. } else {
  3570. while(len >= 4) {
  3571. uint32_t k = *(uint32_t *)data;
  3572. MIX(h,k,m);
  3573. data += 4;
  3574. len -= 4;
  3575. }
  3576. //----------
  3577. // Handle tail bytes
  3578. switch(len) {
  3579. case 3: h ^= data[2] << 16;
  3580. case 2: h ^= data[1] << 8;
  3581. case 1: h ^= data[0]; h *= m;
  3582. };
  3583. h ^= h >> 13;
  3584. h *= m;
  3585. h ^= h >> 15;
  3586. return h;
  3587. }
  3588. }
  3589. #undef MIX
  3590. #endif // UPB_UNALIGNED_READS_OK
  3591. /*
  3592. * upb - a minimalist implementation of protocol buffers.
  3593. *
  3594. * Copyright (c) 2009-2012 Google Inc. See LICENSE for details.
  3595. * Author: Josh Haberman <jhaberman@gmail.com>
  3596. */
  3597. #include <errno.h>
  3598. #include <stdarg.h>
  3599. #include <stddef.h>
  3600. #include <stdint.h>
  3601. #include <stdio.h>
  3602. #include <stdlib.h>
  3603. #include <string.h>
  3604. bool upb_dumptostderr(void *closure, const upb_status* status) {
  3605. UPB_UNUSED(closure);
  3606. fprintf(stderr, "%s\n", upb_status_errmsg(status));
  3607. return false;
  3608. }
  3609. // Guarantee null-termination and provide ellipsis truncation.
  3610. // It may be tempting to "optimize" this by initializing these final
  3611. // four bytes up-front and then being careful never to overwrite them,
  3612. // this is safer and simpler.
  3613. static void nullz(upb_status *status) {
  3614. const char *ellipsis = "...";
  3615. size_t len = strlen(ellipsis);
  3616. assert(sizeof(status->msg) > len);
  3617. memcpy(status->msg + sizeof(status->msg) - len, ellipsis, len);
  3618. }
  3619. void upb_status_clear(upb_status *status) {
  3620. upb_status blank = UPB_STATUS_INIT;
  3621. upb_status_copy(status, &blank);
  3622. }
  3623. bool upb_ok(const upb_status *status) { return status->ok_; }
  3624. upb_errorspace *upb_status_errspace(const upb_status *status) {
  3625. return status->error_space_;
  3626. }
  3627. int upb_status_errcode(const upb_status *status) { return status->code_; }
  3628. const char *upb_status_errmsg(const upb_status *status) { return status->msg; }
  3629. void upb_status_seterrmsg(upb_status *status, const char *msg) {
  3630. if (!status) return;
  3631. status->ok_ = false;
  3632. strncpy(status->msg, msg, sizeof(status->msg));
  3633. nullz(status);
  3634. }
  3635. void upb_status_seterrf(upb_status *status, const char *fmt, ...) {
  3636. va_list args;
  3637. va_start(args, fmt);
  3638. upb_status_vseterrf(status, fmt, args);
  3639. va_end(args);
  3640. }
  3641. void upb_status_vseterrf(upb_status *status, const char *fmt, va_list args) {
  3642. if (!status) return;
  3643. status->ok_ = false;
  3644. vsnprintf(status->msg, sizeof(status->msg), fmt, args);
  3645. nullz(status);
  3646. }
  3647. void upb_status_seterrcode(upb_status *status, upb_errorspace *space,
  3648. int code) {
  3649. if (!status) return;
  3650. status->ok_ = false;
  3651. status->error_space_ = space;
  3652. status->code_ = code;
  3653. space->set_message(status, code);
  3654. }
  3655. void upb_status_copy(upb_status *to, const upb_status *from) {
  3656. if (!to) return;
  3657. *to = *from;
  3658. }
  3659. // This file was generated by upbc (the upb compiler).
  3660. // Do not edit -- your changes will be discarded when the file is
  3661. // regenerated.
  3662. static const upb_msgdef msgs[20];
  3663. static const upb_fielddef fields[81];
  3664. static const upb_enumdef enums[4];
  3665. static const upb_tabent strentries[236];
  3666. static const upb_tabent intentries[14];
  3667. static const _upb_value arrays[232];
  3668. #ifdef UPB_DEBUG_REFS
  3669. static upb_inttable reftables[212];
  3670. #endif
  3671. static const upb_msgdef msgs[20] = {
  3672. 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]),
  3673. 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]),
  3674. 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]),
  3675. 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]),
  3676. 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]),
  3677. 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]),
  3678. 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]),
  3679. 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]),
  3680. 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]),
  3681. 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]),
  3682. 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]),
  3683. 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]),
  3684. 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]),
  3685. 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]),
  3686. 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]),
  3687. 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]),
  3688. 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]),
  3689. 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]),
  3690. 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]),
  3691. 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]),
  3692. };
  3693. static const upb_fielddef fields[81] = {
  3694. 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]),
  3695. 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]),
  3696. 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]),
  3697. 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]),
  3698. 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]),
  3699. 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]),
  3700. 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]),
  3701. 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]),
  3702. 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]),
  3703. 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]),
  3704. 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]),
  3705. 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]),
  3706. 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]),
  3707. 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]),
  3708. 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]),
  3709. 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]),
  3710. 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]),
  3711. 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]),
  3712. 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]),
  3713. 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]),
  3714. 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]),
  3715. 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]),
  3716. 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]),
  3717. 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]),
  3718. 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]),
  3719. 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]),
  3720. 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]),
  3721. 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]),
  3722. 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]),
  3723. 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]),
  3724. 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]),
  3725. 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]),
  3726. 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]),
  3727. 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]),
  3728. 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]),
  3729. 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]),
  3730. 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]),
  3731. 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]),
  3732. 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]),
  3733. 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]),
  3734. 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]),
  3735. 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]),
  3736. 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]),
  3737. 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]),
  3738. 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]),
  3739. 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]),
  3740. 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]),
  3741. 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]),
  3742. 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]),
  3743. 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]),
  3744. 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]),
  3745. 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]),
  3746. 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]),
  3747. 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]),
  3748. 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]),
  3749. 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]),
  3750. 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]),
  3751. 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]),
  3752. 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]),
  3753. 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]),
  3754. 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]),
  3755. 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]),
  3756. 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]),
  3757. 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]),
  3758. 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]),
  3759. 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]),
  3760. 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]),
  3761. 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]),
  3762. 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]),
  3763. 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]),
  3764. 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]),
  3765. 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]),
  3766. 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]),
  3767. 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]),
  3768. 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]),
  3769. 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]),
  3770. 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]),
  3771. 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]),
  3772. 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]),
  3773. 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]),
  3774. 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]),
  3775. };
  3776. static const upb_enumdef enums[4] = {
  3777. 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]),
  3778. 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]),
  3779. 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]),
  3780. 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]),
  3781. };
  3782. static const upb_tabent strentries[236] = {
  3783. {UPB_TABKEY_STR("extension"), UPB_VALUE_INIT_CONSTPTR(&fields[14]), NULL},
  3784. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3785. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3786. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[38]), NULL},
  3787. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3788. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3789. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3790. {UPB_TABKEY_STR("field"), UPB_VALUE_INIT_CONSTPTR(&fields[16]), NULL},
  3791. {UPB_TABKEY_STR("extension_range"), UPB_VALUE_INIT_CONSTPTR(&fields[15]), NULL},
  3792. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3793. {UPB_TABKEY_STR("nested_type"), UPB_VALUE_INIT_CONSTPTR(&fields[44]), NULL},
  3794. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3795. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3796. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3797. {UPB_TABKEY_STR("options"), UPB_VALUE_INIT_CONSTPTR(&fields[49]), NULL},
  3798. {UPB_TABKEY_STR("enum_type"), UPB_VALUE_INIT_CONSTPTR(&fields[9]), &strentries[14]},
  3799. {UPB_TABKEY_STR("start"), UPB_VALUE_INIT_CONSTPTR(&fields[66]), NULL},
  3800. {UPB_TABKEY_STR("end"), UPB_VALUE_INIT_CONSTPTR(&fields[8]), NULL},
  3801. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3802. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3803. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3804. {UPB_TABKEY_STR("value"), UPB_VALUE_INIT_CONSTPTR(&fields[78]), NULL},
  3805. {UPB_TABKEY_STR("options"), UPB_VALUE_INIT_CONSTPTR(&fields[50]), NULL},
  3806. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[40]), &strentries[22]},
  3807. {UPB_TABKEY_STR("uninterpreted_option"), UPB_VALUE_INIT_CONSTPTR(&fields[73]), NULL},
  3808. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3809. {UPB_TABKEY_STR("allow_alias"), UPB_VALUE_INIT_CONSTPTR(&fields[1]), NULL},
  3810. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3811. {UPB_TABKEY_STR("number"), UPB_VALUE_INIT_CONSTPTR(&fields[47]), NULL},
  3812. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3813. {UPB_TABKEY_STR("options"), UPB_VALUE_INIT_CONSTPTR(&fields[52]), NULL},
  3814. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[37]), &strentries[30]},
  3815. {UPB_TABKEY_STR("uninterpreted_option"), UPB_VALUE_INIT_CONSTPTR(&fields[71]), NULL},
  3816. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3817. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3818. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3819. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3820. {UPB_TABKEY_STR("label"), UPB_VALUE_INIT_CONSTPTR(&fields[27]), NULL},
  3821. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3822. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[41]), NULL},
  3823. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3824. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3825. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3826. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3827. {UPB_TABKEY_STR("number"), UPB_VALUE_INIT_CONSTPTR(&fields[46]), &strentries[49]},
  3828. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3829. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3830. {UPB_TABKEY_STR("type_name"), UPB_VALUE_INIT_CONSTPTR(&fields[70]), NULL},
  3831. {UPB_TABKEY_STR("extendee"), UPB_VALUE_INIT_CONSTPTR(&fields[12]), NULL},
  3832. {UPB_TABKEY_STR("type"), UPB_VALUE_INIT_CONSTPTR(&fields[69]), &strentries[48]},
  3833. {UPB_TABKEY_STR("default_value"), UPB_VALUE_INIT_CONSTPTR(&fields[4]), NULL},
  3834. {UPB_TABKEY_STR("options"), UPB_VALUE_INIT_CONSTPTR(&fields[51]), NULL},
  3835. {UPB_TABKEY_STR("experimental_map_key"), UPB_VALUE_INIT_CONSTPTR(&fields[11]), &strentries[67]},
  3836. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3837. {UPB_TABKEY_STR("weak"), UPB_VALUE_INIT_CONSTPTR(&fields[79]), NULL},
  3838. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3839. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3840. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3841. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3842. {UPB_TABKEY_STR("packed"), UPB_VALUE_INIT_CONSTPTR(&fields[58]), NULL},
  3843. {UPB_TABKEY_STR("lazy"), UPB_VALUE_INIT_CONSTPTR(&fields[28]), NULL},
  3844. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3845. {UPB_TABKEY_STR("ctype"), UPB_VALUE_INIT_CONSTPTR(&fields[3]), NULL},
  3846. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3847. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3848. {UPB_TABKEY_STR("deprecated"), UPB_VALUE_INIT_CONSTPTR(&fields[6]), NULL},
  3849. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3850. {UPB_TABKEY_STR("uninterpreted_option"), UPB_VALUE_INIT_CONSTPTR(&fields[77]), NULL},
  3851. {UPB_TABKEY_STR("extension"), UPB_VALUE_INIT_CONSTPTR(&fields[13]), NULL},
  3852. {UPB_TABKEY_STR("weak_dependency"), UPB_VALUE_INIT_CONSTPTR(&fields[80]), NULL},
  3853. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3854. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[34]), NULL},
  3855. {UPB_TABKEY_STR("service"), UPB_VALUE_INIT_CONSTPTR(&fields[63]), NULL},
  3856. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3857. {UPB_TABKEY_STR("source_code_info"), UPB_VALUE_INIT_CONSTPTR(&fields[64]), NULL},
  3858. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3859. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3860. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3861. {UPB_TABKEY_STR("dependency"), UPB_VALUE_INIT_CONSTPTR(&fields[5]), NULL},
  3862. {UPB_TABKEY_STR("message_type"), UPB_VALUE_INIT_CONSTPTR(&fields[32]), NULL},
  3863. {UPB_TABKEY_STR("package"), UPB_VALUE_INIT_CONSTPTR(&fields[57]), NULL},
  3864. {UPB_TABKEY_STR("options"), UPB_VALUE_INIT_CONSTPTR(&fields[53]), &strentries[82]},
  3865. {UPB_TABKEY_STR("enum_type"), UPB_VALUE_INIT_CONSTPTR(&fields[10]), NULL},
  3866. {UPB_TABKEY_STR("public_dependency"), UPB_VALUE_INIT_CONSTPTR(&fields[61]), &strentries[81]},
  3867. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3868. {UPB_TABKEY_STR("file"), UPB_VALUE_INIT_CONSTPTR(&fields[17]), NULL},
  3869. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3870. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3871. {UPB_TABKEY_STR("uninterpreted_option"), UPB_VALUE_INIT_CONSTPTR(&fields[75]), NULL},
  3872. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3873. {UPB_TABKEY_STR("cc_generic_services"), UPB_VALUE_INIT_CONSTPTR(&fields[2]), NULL},
  3874. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3875. {UPB_TABKEY_STR("java_multiple_files"), UPB_VALUE_INIT_CONSTPTR(&fields[24]), NULL},
  3876. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3877. {UPB_TABKEY_STR("java_generic_services"), UPB_VALUE_INIT_CONSTPTR(&fields[23]), &strentries[102]},
  3878. {UPB_TABKEY_STR("java_generate_equals_and_hash"), UPB_VALUE_INIT_CONSTPTR(&fields[22]), NULL},
  3879. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3880. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3881. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3882. {UPB_TABKEY_STR("go_package"), UPB_VALUE_INIT_CONSTPTR(&fields[18]), NULL},
  3883. {UPB_TABKEY_STR("java_package"), UPB_VALUE_INIT_CONSTPTR(&fields[26]), NULL},
  3884. {UPB_TABKEY_STR("optimize_for"), UPB_VALUE_INIT_CONSTPTR(&fields[48]), NULL},
  3885. {UPB_TABKEY_STR("py_generic_services"), UPB_VALUE_INIT_CONSTPTR(&fields[62]), NULL},
  3886. {UPB_TABKEY_STR("java_outer_classname"), UPB_VALUE_INIT_CONSTPTR(&fields[25]), NULL},
  3887. {UPB_TABKEY_STR("message_set_wire_format"), UPB_VALUE_INIT_CONSTPTR(&fields[31]), &strentries[106]},
  3888. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3889. {UPB_TABKEY_STR("uninterpreted_option"), UPB_VALUE_INIT_CONSTPTR(&fields[76]), NULL},
  3890. {UPB_TABKEY_STR("no_standard_descriptor_accessor"), UPB_VALUE_INIT_CONSTPTR(&fields[45]), NULL},
  3891. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3892. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3893. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3894. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[39]), NULL},
  3895. {UPB_TABKEY_STR("input_type"), UPB_VALUE_INIT_CONSTPTR(&fields[20]), NULL},
  3896. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3897. {UPB_TABKEY_STR("output_type"), UPB_VALUE_INIT_CONSTPTR(&fields[56]), NULL},
  3898. {UPB_TABKEY_STR("options"), UPB_VALUE_INIT_CONSTPTR(&fields[55]), NULL},
  3899. {UPB_TABKEY_STR("uninterpreted_option"), UPB_VALUE_INIT_CONSTPTR(&fields[74]), NULL},
  3900. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3901. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3902. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3903. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3904. {UPB_TABKEY_STR("options"), UPB_VALUE_INIT_CONSTPTR(&fields[54]), &strentries[122]},
  3905. {UPB_TABKEY_STR("method"), UPB_VALUE_INIT_CONSTPTR(&fields[33]), NULL},
  3906. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[35]), &strentries[121]},
  3907. {UPB_TABKEY_STR("uninterpreted_option"), UPB_VALUE_INIT_CONSTPTR(&fields[72]), NULL},
  3908. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3909. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3910. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3911. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3912. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3913. {UPB_TABKEY_STR("location"), UPB_VALUE_INIT_CONSTPTR(&fields[30]), NULL},
  3914. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3915. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3916. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3917. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3918. {UPB_TABKEY_STR("span"), UPB_VALUE_INIT_CONSTPTR(&fields[65]), &strentries[139]},
  3919. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3920. {UPB_TABKEY_STR("trailing_comments"), UPB_VALUE_INIT_CONSTPTR(&fields[68]), NULL},
  3921. {UPB_TABKEY_STR("leading_comments"), UPB_VALUE_INIT_CONSTPTR(&fields[29]), &strentries[137]},
  3922. {UPB_TABKEY_STR("path"), UPB_VALUE_INIT_CONSTPTR(&fields[59]), NULL},
  3923. {UPB_TABKEY_STR("double_value"), UPB_VALUE_INIT_CONSTPTR(&fields[7]), NULL},
  3924. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3925. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3926. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[36]), NULL},
  3927. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3928. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3929. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3930. {UPB_TABKEY_STR("negative_int_value"), UPB_VALUE_INIT_CONSTPTR(&fields[43]), NULL},
  3931. {UPB_TABKEY_STR("aggregate_value"), UPB_VALUE_INIT_CONSTPTR(&fields[0]), NULL},
  3932. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3933. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3934. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3935. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3936. {UPB_TABKEY_STR("positive_int_value"), UPB_VALUE_INIT_CONSTPTR(&fields[60]), NULL},
  3937. {UPB_TABKEY_STR("identifier_value"), UPB_VALUE_INIT_CONSTPTR(&fields[19]), NULL},
  3938. {UPB_TABKEY_STR("string_value"), UPB_VALUE_INIT_CONSTPTR(&fields[67]), &strentries[154]},
  3939. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3940. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3941. {UPB_TABKEY_STR("is_extension"), UPB_VALUE_INIT_CONSTPTR(&fields[21]), NULL},
  3942. {UPB_TABKEY_STR("name_part"), UPB_VALUE_INIT_CONSTPTR(&fields[42]), NULL},
  3943. {UPB_TABKEY_STR("LABEL_REQUIRED"), UPB_VALUE_INIT_INT32(2), &strentries[162]},
  3944. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3945. {UPB_TABKEY_STR("LABEL_REPEATED"), UPB_VALUE_INIT_INT32(3), NULL},
  3946. {UPB_TABKEY_STR("LABEL_OPTIONAL"), UPB_VALUE_INIT_INT32(1), NULL},
  3947. {UPB_TABKEY_STR("TYPE_FIXED64"), UPB_VALUE_INIT_INT32(6), NULL},
  3948. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3949. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3950. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3951. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3952. {UPB_TABKEY_STR("TYPE_STRING"), UPB_VALUE_INIT_INT32(9), NULL},
  3953. {UPB_TABKEY_STR("TYPE_FLOAT"), UPB_VALUE_INIT_INT32(2), &strentries[193]},
  3954. {UPB_TABKEY_STR("TYPE_DOUBLE"), UPB_VALUE_INIT_INT32(1), NULL},
  3955. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3956. {UPB_TABKEY_STR("TYPE_INT32"), UPB_VALUE_INIT_INT32(5), NULL},
  3957. {UPB_TABKEY_STR("TYPE_SFIXED32"), UPB_VALUE_INIT_INT32(15), NULL},
  3958. {UPB_TABKEY_STR("TYPE_FIXED32"), UPB_VALUE_INIT_INT32(7), NULL},
  3959. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3960. {UPB_TABKEY_STR("TYPE_MESSAGE"), UPB_VALUE_INIT_INT32(11), &strentries[194]},
  3961. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3962. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3963. {UPB_TABKEY_STR("TYPE_INT64"), UPB_VALUE_INIT_INT32(3), &strentries[191]},
  3964. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3965. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3966. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3967. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3968. {UPB_TABKEY_STR("TYPE_ENUM"), UPB_VALUE_INIT_INT32(14), NULL},
  3969. {UPB_TABKEY_STR("TYPE_UINT32"), UPB_VALUE_INIT_INT32(13), NULL},
  3970. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3971. {UPB_TABKEY_STR("TYPE_UINT64"), UPB_VALUE_INIT_INT32(4), &strentries[190]},
  3972. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3973. {UPB_TABKEY_STR("TYPE_SFIXED64"), UPB_VALUE_INIT_INT32(16), NULL},
  3974. {UPB_TABKEY_STR("TYPE_BYTES"), UPB_VALUE_INIT_INT32(12), NULL},
  3975. {UPB_TABKEY_STR("TYPE_SINT64"), UPB_VALUE_INIT_INT32(18), NULL},
  3976. {UPB_TABKEY_STR("TYPE_BOOL"), UPB_VALUE_INIT_INT32(8), NULL},
  3977. {UPB_TABKEY_STR("TYPE_GROUP"), UPB_VALUE_INIT_INT32(10), NULL},
  3978. {UPB_TABKEY_STR("TYPE_SINT32"), UPB_VALUE_INIT_INT32(17), NULL},
  3979. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3980. {UPB_TABKEY_STR("CORD"), UPB_VALUE_INIT_INT32(1), NULL},
  3981. {UPB_TABKEY_STR("STRING"), UPB_VALUE_INIT_INT32(0), &strentries[197]},
  3982. {UPB_TABKEY_STR("STRING_PIECE"), UPB_VALUE_INIT_INT32(2), NULL},
  3983. {UPB_TABKEY_STR("CODE_SIZE"), UPB_VALUE_INIT_INT32(2), NULL},
  3984. {UPB_TABKEY_STR("SPEED"), UPB_VALUE_INIT_INT32(1), &strentries[203]},
  3985. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3986. {UPB_TABKEY_STR("LITE_RUNTIME"), UPB_VALUE_INIT_INT32(3), NULL},
  3987. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3988. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3989. {UPB_TABKEY_STR("google.protobuf.SourceCodeInfo.Location"), UPB_VALUE_INIT_CONSTPTR(&msgs[17]), NULL},
  3990. {UPB_TABKEY_STR("google.protobuf.UninterpretedOption"), UPB_VALUE_INIT_CONSTPTR(&msgs[18]), NULL},
  3991. {UPB_TABKEY_STR("google.protobuf.FileDescriptorProto"), UPB_VALUE_INIT_CONSTPTR(&msgs[8]), NULL},
  3992. {UPB_TABKEY_STR("google.protobuf.MethodDescriptorProto"), UPB_VALUE_INIT_CONSTPTR(&msgs[12]), NULL},
  3993. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3994. {UPB_TABKEY_STR("google.protobuf.EnumValueOptions"), UPB_VALUE_INIT_CONSTPTR(&msgs[5]), NULL},
  3995. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3996. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3997. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3998. {UPB_TABKEY_STR("google.protobuf.DescriptorProto"), UPB_VALUE_INIT_CONSTPTR(&msgs[0]), &strentries[228]},
  3999. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4000. {UPB_TABKEY_STR("google.protobuf.SourceCodeInfo"), UPB_VALUE_INIT_CONSTPTR(&msgs[16]), NULL},
  4001. {UPB_TABKEY_STR("google.protobuf.FieldDescriptorProto.Type"), UPB_VALUE_INIT_CONSTPTR(&enums[1]), NULL},
  4002. {UPB_TABKEY_STR("google.protobuf.DescriptorProto.ExtensionRange"), UPB_VALUE_INIT_CONSTPTR(&msgs[1]), NULL},
  4003. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4004. {UPB_TABKEY_STR("google.protobuf.EnumValueDescriptorProto"), UPB_VALUE_INIT_CONSTPTR(&msgs[4]), NULL},
  4005. {UPB_TABKEY_STR("google.protobuf.FieldOptions"), UPB_VALUE_INIT_CONSTPTR(&msgs[7]), NULL},
  4006. {UPB_TABKEY_STR("google.protobuf.FileOptions"), UPB_VALUE_INIT_CONSTPTR(&msgs[10]), NULL},
  4007. {UPB_TABKEY_STR("google.protobuf.EnumDescriptorProto"), UPB_VALUE_INIT_CONSTPTR(&msgs[2]), &strentries[233]},
  4008. {UPB_TABKEY_STR("google.protobuf.FieldDescriptorProto.Label"), UPB_VALUE_INIT_CONSTPTR(&enums[0]), NULL},
  4009. {UPB_TABKEY_STR("google.protobuf.ServiceDescriptorProto"), UPB_VALUE_INIT_CONSTPTR(&msgs[14]), NULL},
  4010. {UPB_TABKEY_STR("google.protobuf.FieldOptions.CType"), UPB_VALUE_INIT_CONSTPTR(&enums[2]), &strentries[229]},
  4011. {UPB_TABKEY_STR("google.protobuf.FileDescriptorSet"), UPB_VALUE_INIT_CONSTPTR(&msgs[9]), &strentries[235]},
  4012. {UPB_TABKEY_STR("google.protobuf.EnumOptions"), UPB_VALUE_INIT_CONSTPTR(&msgs[3]), NULL},
  4013. {UPB_TABKEY_STR("google.protobuf.FieldDescriptorProto"), UPB_VALUE_INIT_CONSTPTR(&msgs[6]), NULL},
  4014. {UPB_TABKEY_STR("google.protobuf.FileOptions.OptimizeMode"), UPB_VALUE_INIT_CONSTPTR(&enums[3]), &strentries[221]},
  4015. {UPB_TABKEY_STR("google.protobuf.ServiceOptions"), UPB_VALUE_INIT_CONSTPTR(&msgs[15]), NULL},
  4016. {UPB_TABKEY_STR("google.protobuf.MessageOptions"), UPB_VALUE_INIT_CONSTPTR(&msgs[11]), NULL},
  4017. {UPB_TABKEY_STR("google.protobuf.MethodOptions"), UPB_VALUE_INIT_CONSTPTR(&msgs[13]), &strentries[226]},
  4018. {UPB_TABKEY_STR("google.protobuf.UninterpretedOption.NamePart"), UPB_VALUE_INIT_CONSTPTR(&msgs[19]), NULL},
  4019. };
  4020. static const upb_tabent intentries[14] = {
  4021. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4022. {UPB_TABKEY_NUM(999), UPB_VALUE_INIT_CONSTPTR(&fields[73]), NULL},
  4023. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4024. {UPB_TABKEY_NUM(999), UPB_VALUE_INIT_CONSTPTR(&fields[71]), NULL},
  4025. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4026. {UPB_TABKEY_NUM(999), UPB_VALUE_INIT_CONSTPTR(&fields[77]), NULL},
  4027. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4028. {UPB_TABKEY_NUM(999), UPB_VALUE_INIT_CONSTPTR(&fields[75]), NULL},
  4029. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4030. {UPB_TABKEY_NUM(999), UPB_VALUE_INIT_CONSTPTR(&fields[76]), NULL},
  4031. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4032. {UPB_TABKEY_NUM(999), UPB_VALUE_INIT_CONSTPTR(&fields[74]), NULL},
  4033. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4034. {UPB_TABKEY_NUM(999), UPB_VALUE_INIT_CONSTPTR(&fields[72]), NULL},
  4035. };
  4036. static const _upb_value arrays[232] = {
  4037. UPB_ARRAY_EMPTYENT,
  4038. UPB_VALUE_INIT_CONSTPTR(&fields[38]),
  4039. UPB_VALUE_INIT_CONSTPTR(&fields[16]),
  4040. UPB_VALUE_INIT_CONSTPTR(&fields[44]),
  4041. UPB_VALUE_INIT_CONSTPTR(&fields[9]),
  4042. UPB_VALUE_INIT_CONSTPTR(&fields[15]),
  4043. UPB_VALUE_INIT_CONSTPTR(&fields[14]),
  4044. UPB_VALUE_INIT_CONSTPTR(&fields[49]),
  4045. UPB_ARRAY_EMPTYENT,
  4046. UPB_VALUE_INIT_CONSTPTR(&fields[66]),
  4047. UPB_VALUE_INIT_CONSTPTR(&fields[8]),
  4048. UPB_ARRAY_EMPTYENT,
  4049. UPB_VALUE_INIT_CONSTPTR(&fields[40]),
  4050. UPB_VALUE_INIT_CONSTPTR(&fields[78]),
  4051. UPB_VALUE_INIT_CONSTPTR(&fields[50]),
  4052. UPB_ARRAY_EMPTYENT,
  4053. UPB_ARRAY_EMPTYENT,
  4054. UPB_VALUE_INIT_CONSTPTR(&fields[1]),
  4055. UPB_ARRAY_EMPTYENT,
  4056. UPB_ARRAY_EMPTYENT,
  4057. UPB_ARRAY_EMPTYENT,
  4058. UPB_ARRAY_EMPTYENT,
  4059. UPB_ARRAY_EMPTYENT,
  4060. UPB_ARRAY_EMPTYENT,
  4061. UPB_VALUE_INIT_CONSTPTR(&fields[37]),
  4062. UPB_VALUE_INIT_CONSTPTR(&fields[47]),
  4063. UPB_VALUE_INIT_CONSTPTR(&fields[52]),
  4064. UPB_ARRAY_EMPTYENT,
  4065. UPB_ARRAY_EMPTYENT,
  4066. UPB_ARRAY_EMPTYENT,
  4067. UPB_ARRAY_EMPTYENT,
  4068. UPB_ARRAY_EMPTYENT,
  4069. UPB_VALUE_INIT_CONSTPTR(&fields[41]),
  4070. UPB_VALUE_INIT_CONSTPTR(&fields[12]),
  4071. UPB_VALUE_INIT_CONSTPTR(&fields[46]),
  4072. UPB_VALUE_INIT_CONSTPTR(&fields[27]),
  4073. UPB_VALUE_INIT_CONSTPTR(&fields[69]),
  4074. UPB_VALUE_INIT_CONSTPTR(&fields[70]),
  4075. UPB_VALUE_INIT_CONSTPTR(&fields[4]),
  4076. UPB_VALUE_INIT_CONSTPTR(&fields[51]),
  4077. UPB_ARRAY_EMPTYENT,
  4078. UPB_VALUE_INIT_CONSTPTR(&fields[3]),
  4079. UPB_VALUE_INIT_CONSTPTR(&fields[58]),
  4080. UPB_VALUE_INIT_CONSTPTR(&fields[6]),
  4081. UPB_ARRAY_EMPTYENT,
  4082. UPB_VALUE_INIT_CONSTPTR(&fields[28]),
  4083. UPB_ARRAY_EMPTYENT,
  4084. UPB_ARRAY_EMPTYENT,
  4085. UPB_ARRAY_EMPTYENT,
  4086. UPB_VALUE_INIT_CONSTPTR(&fields[11]),
  4087. UPB_VALUE_INIT_CONSTPTR(&fields[79]),
  4088. UPB_ARRAY_EMPTYENT,
  4089. UPB_ARRAY_EMPTYENT,
  4090. UPB_ARRAY_EMPTYENT,
  4091. UPB_ARRAY_EMPTYENT,
  4092. UPB_ARRAY_EMPTYENT,
  4093. UPB_ARRAY_EMPTYENT,
  4094. UPB_ARRAY_EMPTYENT,
  4095. UPB_ARRAY_EMPTYENT,
  4096. UPB_ARRAY_EMPTYENT,
  4097. UPB_ARRAY_EMPTYENT,
  4098. UPB_ARRAY_EMPTYENT,
  4099. UPB_ARRAY_EMPTYENT,
  4100. UPB_ARRAY_EMPTYENT,
  4101. UPB_ARRAY_EMPTYENT,
  4102. UPB_ARRAY_EMPTYENT,
  4103. UPB_ARRAY_EMPTYENT,
  4104. UPB_ARRAY_EMPTYENT,
  4105. UPB_ARRAY_EMPTYENT,
  4106. UPB_ARRAY_EMPTYENT,
  4107. UPB_ARRAY_EMPTYENT,
  4108. UPB_ARRAY_EMPTYENT,
  4109. UPB_ARRAY_EMPTYENT,
  4110. UPB_VALUE_INIT_CONSTPTR(&fields[34]),
  4111. UPB_VALUE_INIT_CONSTPTR(&fields[57]),
  4112. UPB_VALUE_INIT_CONSTPTR(&fields[5]),
  4113. UPB_VALUE_INIT_CONSTPTR(&fields[32]),
  4114. UPB_VALUE_INIT_CONSTPTR(&fields[10]),
  4115. UPB_VALUE_INIT_CONSTPTR(&fields[63]),
  4116. UPB_VALUE_INIT_CONSTPTR(&fields[13]),
  4117. UPB_VALUE_INIT_CONSTPTR(&fields[53]),
  4118. UPB_VALUE_INIT_CONSTPTR(&fields[64]),
  4119. UPB_VALUE_INIT_CONSTPTR(&fields[61]),
  4120. UPB_VALUE_INIT_CONSTPTR(&fields[80]),
  4121. UPB_ARRAY_EMPTYENT,
  4122. UPB_VALUE_INIT_CONSTPTR(&fields[17]),
  4123. UPB_ARRAY_EMPTYENT,
  4124. UPB_VALUE_INIT_CONSTPTR(&fields[26]),
  4125. UPB_ARRAY_EMPTYENT,
  4126. UPB_ARRAY_EMPTYENT,
  4127. UPB_ARRAY_EMPTYENT,
  4128. UPB_ARRAY_EMPTYENT,
  4129. UPB_ARRAY_EMPTYENT,
  4130. UPB_ARRAY_EMPTYENT,
  4131. UPB_VALUE_INIT_CONSTPTR(&fields[25]),
  4132. UPB_VALUE_INIT_CONSTPTR(&fields[48]),
  4133. UPB_VALUE_INIT_CONSTPTR(&fields[24]),
  4134. UPB_VALUE_INIT_CONSTPTR(&fields[18]),
  4135. UPB_ARRAY_EMPTYENT,
  4136. UPB_ARRAY_EMPTYENT,
  4137. UPB_ARRAY_EMPTYENT,
  4138. UPB_ARRAY_EMPTYENT,
  4139. UPB_VALUE_INIT_CONSTPTR(&fields[2]),
  4140. UPB_VALUE_INIT_CONSTPTR(&fields[23]),
  4141. UPB_VALUE_INIT_CONSTPTR(&fields[62]),
  4142. UPB_ARRAY_EMPTYENT,
  4143. UPB_VALUE_INIT_CONSTPTR(&fields[22]),
  4144. UPB_ARRAY_EMPTYENT,
  4145. UPB_ARRAY_EMPTYENT,
  4146. UPB_ARRAY_EMPTYENT,
  4147. UPB_ARRAY_EMPTYENT,
  4148. UPB_ARRAY_EMPTYENT,
  4149. UPB_ARRAY_EMPTYENT,
  4150. UPB_ARRAY_EMPTYENT,
  4151. UPB_ARRAY_EMPTYENT,
  4152. UPB_ARRAY_EMPTYENT,
  4153. UPB_ARRAY_EMPTYENT,
  4154. UPB_ARRAY_EMPTYENT,
  4155. UPB_ARRAY_EMPTYENT,
  4156. UPB_ARRAY_EMPTYENT,
  4157. UPB_ARRAY_EMPTYENT,
  4158. UPB_ARRAY_EMPTYENT,
  4159. UPB_ARRAY_EMPTYENT,
  4160. UPB_ARRAY_EMPTYENT,
  4161. UPB_ARRAY_EMPTYENT,
  4162. UPB_ARRAY_EMPTYENT,
  4163. UPB_ARRAY_EMPTYENT,
  4164. UPB_ARRAY_EMPTYENT,
  4165. UPB_ARRAY_EMPTYENT,
  4166. UPB_ARRAY_EMPTYENT,
  4167. UPB_ARRAY_EMPTYENT,
  4168. UPB_ARRAY_EMPTYENT,
  4169. UPB_ARRAY_EMPTYENT,
  4170. UPB_ARRAY_EMPTYENT,
  4171. UPB_ARRAY_EMPTYENT,
  4172. UPB_ARRAY_EMPTYENT,
  4173. UPB_ARRAY_EMPTYENT,
  4174. UPB_ARRAY_EMPTYENT,
  4175. UPB_ARRAY_EMPTYENT,
  4176. UPB_ARRAY_EMPTYENT,
  4177. UPB_ARRAY_EMPTYENT,
  4178. UPB_ARRAY_EMPTYENT,
  4179. UPB_ARRAY_EMPTYENT,
  4180. UPB_ARRAY_EMPTYENT,
  4181. UPB_ARRAY_EMPTYENT,
  4182. UPB_ARRAY_EMPTYENT,
  4183. UPB_ARRAY_EMPTYENT,
  4184. UPB_ARRAY_EMPTYENT,
  4185. UPB_ARRAY_EMPTYENT,
  4186. UPB_ARRAY_EMPTYENT,
  4187. UPB_ARRAY_EMPTYENT,
  4188. UPB_VALUE_INIT_CONSTPTR(&fields[31]),
  4189. UPB_VALUE_INIT_CONSTPTR(&fields[45]),
  4190. UPB_ARRAY_EMPTYENT,
  4191. UPB_ARRAY_EMPTYENT,
  4192. UPB_ARRAY_EMPTYENT,
  4193. UPB_ARRAY_EMPTYENT,
  4194. UPB_ARRAY_EMPTYENT,
  4195. UPB_ARRAY_EMPTYENT,
  4196. UPB_ARRAY_EMPTYENT,
  4197. UPB_ARRAY_EMPTYENT,
  4198. UPB_ARRAY_EMPTYENT,
  4199. UPB_ARRAY_EMPTYENT,
  4200. UPB_ARRAY_EMPTYENT,
  4201. UPB_ARRAY_EMPTYENT,
  4202. UPB_ARRAY_EMPTYENT,
  4203. UPB_ARRAY_EMPTYENT,
  4204. UPB_VALUE_INIT_CONSTPTR(&fields[39]),
  4205. UPB_VALUE_INIT_CONSTPTR(&fields[20]),
  4206. UPB_VALUE_INIT_CONSTPTR(&fields[56]),
  4207. UPB_VALUE_INIT_CONSTPTR(&fields[55]),
  4208. UPB_ARRAY_EMPTYENT,
  4209. UPB_ARRAY_EMPTYENT,
  4210. UPB_ARRAY_EMPTYENT,
  4211. UPB_ARRAY_EMPTYENT,
  4212. UPB_ARRAY_EMPTYENT,
  4213. UPB_VALUE_INIT_CONSTPTR(&fields[35]),
  4214. UPB_VALUE_INIT_CONSTPTR(&fields[33]),
  4215. UPB_VALUE_INIT_CONSTPTR(&fields[54]),
  4216. UPB_ARRAY_EMPTYENT,
  4217. UPB_ARRAY_EMPTYENT,
  4218. UPB_ARRAY_EMPTYENT,
  4219. UPB_ARRAY_EMPTYENT,
  4220. UPB_ARRAY_EMPTYENT,
  4221. UPB_VALUE_INIT_CONSTPTR(&fields[30]),
  4222. UPB_ARRAY_EMPTYENT,
  4223. UPB_VALUE_INIT_CONSTPTR(&fields[59]),
  4224. UPB_VALUE_INIT_CONSTPTR(&fields[65]),
  4225. UPB_VALUE_INIT_CONSTPTR(&fields[29]),
  4226. UPB_VALUE_INIT_CONSTPTR(&fields[68]),
  4227. UPB_ARRAY_EMPTYENT,
  4228. UPB_ARRAY_EMPTYENT,
  4229. UPB_VALUE_INIT_CONSTPTR(&fields[36]),
  4230. UPB_VALUE_INIT_CONSTPTR(&fields[19]),
  4231. UPB_VALUE_INIT_CONSTPTR(&fields[60]),
  4232. UPB_VALUE_INIT_CONSTPTR(&fields[43]),
  4233. UPB_VALUE_INIT_CONSTPTR(&fields[7]),
  4234. UPB_VALUE_INIT_CONSTPTR(&fields[67]),
  4235. UPB_VALUE_INIT_CONSTPTR(&fields[0]),
  4236. UPB_ARRAY_EMPTYENT,
  4237. UPB_VALUE_INIT_CONSTPTR(&fields[42]),
  4238. UPB_VALUE_INIT_CONSTPTR(&fields[21]),
  4239. UPB_ARRAY_EMPTYENT,
  4240. UPB_VALUE_INIT_CONSTPTR("LABEL_OPTIONAL"),
  4241. UPB_VALUE_INIT_CONSTPTR("LABEL_REQUIRED"),
  4242. UPB_VALUE_INIT_CONSTPTR("LABEL_REPEATED"),
  4243. UPB_ARRAY_EMPTYENT,
  4244. UPB_VALUE_INIT_CONSTPTR("TYPE_DOUBLE"),
  4245. UPB_VALUE_INIT_CONSTPTR("TYPE_FLOAT"),
  4246. UPB_VALUE_INIT_CONSTPTR("TYPE_INT64"),
  4247. UPB_VALUE_INIT_CONSTPTR("TYPE_UINT64"),
  4248. UPB_VALUE_INIT_CONSTPTR("TYPE_INT32"),
  4249. UPB_VALUE_INIT_CONSTPTR("TYPE_FIXED64"),
  4250. UPB_VALUE_INIT_CONSTPTR("TYPE_FIXED32"),
  4251. UPB_VALUE_INIT_CONSTPTR("TYPE_BOOL"),
  4252. UPB_VALUE_INIT_CONSTPTR("TYPE_STRING"),
  4253. UPB_VALUE_INIT_CONSTPTR("TYPE_GROUP"),
  4254. UPB_VALUE_INIT_CONSTPTR("TYPE_MESSAGE"),
  4255. UPB_VALUE_INIT_CONSTPTR("TYPE_BYTES"),
  4256. UPB_VALUE_INIT_CONSTPTR("TYPE_UINT32"),
  4257. UPB_VALUE_INIT_CONSTPTR("TYPE_ENUM"),
  4258. UPB_VALUE_INIT_CONSTPTR("TYPE_SFIXED32"),
  4259. UPB_VALUE_INIT_CONSTPTR("TYPE_SFIXED64"),
  4260. UPB_VALUE_INIT_CONSTPTR("TYPE_SINT32"),
  4261. UPB_VALUE_INIT_CONSTPTR("TYPE_SINT64"),
  4262. UPB_VALUE_INIT_CONSTPTR("STRING"),
  4263. UPB_VALUE_INIT_CONSTPTR("CORD"),
  4264. UPB_VALUE_INIT_CONSTPTR("STRING_PIECE"),
  4265. UPB_ARRAY_EMPTYENT,
  4266. UPB_VALUE_INIT_CONSTPTR("SPEED"),
  4267. UPB_VALUE_INIT_CONSTPTR("CODE_SIZE"),
  4268. UPB_VALUE_INIT_CONSTPTR("LITE_RUNTIME"),
  4269. };
  4270. static const upb_symtab symtab = UPB_SYMTAB_INIT(UPB_STRTABLE_INIT(24, 31, UPB_CTYPE_PTR, 5, &strentries[204]), &reftables[210], &reftables[211]);
  4271. const upb_symtab *upbdefs_google_protobuf_descriptor(const void *owner) {
  4272. upb_symtab_ref(&symtab, owner);
  4273. return &symtab;
  4274. }
  4275. #ifdef UPB_DEBUG_REFS
  4276. static upb_inttable reftables[212] = {
  4277. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4278. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4279. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4280. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4281. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4282. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4283. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4284. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4285. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4286. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4287. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4288. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4289. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4290. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4291. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4292. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4293. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4294. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4295. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4296. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4297. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4298. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4299. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4300. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4301. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4302. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4303. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4304. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4305. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4306. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4307. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4308. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4309. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4310. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4311. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4312. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4313. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4314. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4315. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4316. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4317. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4318. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4319. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4320. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4321. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4322. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4323. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4324. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4325. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4326. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4327. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4328. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4329. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4330. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4331. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4332. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4333. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4334. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4335. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4336. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4337. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4338. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4339. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4340. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4341. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4342. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4343. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4344. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4345. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4346. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4347. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4348. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4349. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4350. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4351. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4352. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4353. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4354. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4355. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4356. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4357. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4358. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4359. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4360. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4361. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4362. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4363. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4364. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4365. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4366. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4367. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4368. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4369. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4370. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4371. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4372. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4373. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4374. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4375. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4376. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4377. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4378. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4379. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4380. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4381. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4382. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4383. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4384. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4385. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4386. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4387. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4388. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4389. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4390. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4391. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4392. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4393. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4394. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4395. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4396. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4397. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4398. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4399. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4400. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4401. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4402. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4403. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4404. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4405. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4406. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4407. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4408. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4409. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4410. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4411. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4412. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4413. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4414. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4415. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4416. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4417. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4418. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4419. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4420. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4421. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4422. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4423. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4424. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4425. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4426. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4427. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4428. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4429. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4430. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4431. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4432. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4433. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4434. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4435. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4436. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4437. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4438. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4439. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4440. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4441. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4442. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4443. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4444. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4445. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4446. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4447. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4448. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4449. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4450. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4451. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4452. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4453. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4454. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4455. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4456. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4457. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4458. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4459. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4460. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4461. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4462. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4463. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4464. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4465. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4466. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4467. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4468. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4469. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4470. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4471. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4472. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4473. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4474. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4475. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4476. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4477. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4478. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4479. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4480. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4481. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4482. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4483. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4484. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4485. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4486. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4487. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4488. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4489. };
  4490. #endif
  4491. /*
  4492. * upb - a minimalist implementation of protocol buffers.
  4493. *
  4494. * Copyright (c) 2008-2009 Google Inc. See LICENSE for details.
  4495. * Author: Josh Haberman <jhaberman@gmail.com>
  4496. *
  4497. * XXX: The routines in this file that consume a string do not currently
  4498. * support having the string span buffers. In the future, as upb_sink and
  4499. * its buffering/sharing functionality evolve there should be an easy and
  4500. * idiomatic way of correctly handling this case. For now, we accept this
  4501. * limitation since we currently only parse descriptors from single strings.
  4502. */
  4503. #include <errno.h>
  4504. #include <stdlib.h>
  4505. #include <string.h>
  4506. static char *upb_strndup(const char *buf, size_t n) {
  4507. char *ret = malloc(n + 1);
  4508. if (!ret) return NULL;
  4509. memcpy(ret, buf, n);
  4510. ret[n] = '\0';
  4511. return ret;
  4512. }
  4513. // Returns a newly allocated string that joins input strings together, for
  4514. // example:
  4515. // join("Foo.Bar", "Baz") -> "Foo.Bar.Baz"
  4516. // join("", "Baz") -> "Baz"
  4517. // Caller owns a ref on the returned string.
  4518. static char *upb_join(const char *base, const char *name) {
  4519. if (!base || strlen(base) == 0) {
  4520. return upb_strdup(name);
  4521. } else {
  4522. char *ret = malloc(strlen(base) + strlen(name) + 2);
  4523. ret[0] = '\0';
  4524. strcat(ret, base);
  4525. strcat(ret, ".");
  4526. strcat(ret, name);
  4527. return ret;
  4528. }
  4529. }
  4530. /* upb_deflist ****************************************************************/
  4531. void upb_deflist_init(upb_deflist *l) {
  4532. l->size = 0;
  4533. l->defs = NULL;
  4534. l->len = 0;
  4535. l->owned = true;
  4536. }
  4537. void upb_deflist_uninit(upb_deflist *l) {
  4538. if (l->owned)
  4539. for(size_t i = 0; i < l->len; i++)
  4540. upb_def_unref(l->defs[i], l);
  4541. free(l->defs);
  4542. }
  4543. bool upb_deflist_push(upb_deflist *l, upb_def *d) {
  4544. if(++l->len >= l->size) {
  4545. size_t new_size = UPB_MAX(l->size, 4);
  4546. new_size *= 2;
  4547. l->defs = realloc(l->defs, new_size * sizeof(void *));
  4548. if (!l->defs) return false;
  4549. l->size = new_size;
  4550. }
  4551. l->defs[l->len - 1] = d;
  4552. return true;
  4553. }
  4554. void upb_deflist_donaterefs(upb_deflist *l, void *owner) {
  4555. assert(l->owned);
  4556. for (size_t i = 0; i < l->len; i++)
  4557. upb_def_donateref(l->defs[i], l, owner);
  4558. l->owned = false;
  4559. }
  4560. static upb_def *upb_deflist_last(upb_deflist *l) {
  4561. return l->defs[l->len-1];
  4562. }
  4563. // Qualify the defname for all defs starting with offset "start" with "str".
  4564. static void upb_deflist_qualify(upb_deflist *l, char *str, int32_t start) {
  4565. for (uint32_t i = start; i < l->len; i++) {
  4566. upb_def *def = l->defs[i];
  4567. char *name = upb_join(str, upb_def_fullname(def));
  4568. upb_def_setfullname(def, name, NULL);
  4569. free(name);
  4570. }
  4571. }
  4572. /* upb_descreader ************************************************************/
  4573. void upb_descreader_init(upb_descreader *r, const upb_handlers *handlers,
  4574. upb_status *status) {
  4575. UPB_UNUSED(status);
  4576. upb_deflist_init(&r->defs);
  4577. upb_sink_reset(upb_descreader_input(r), handlers, r);
  4578. r->stack_len = 0;
  4579. r->name = NULL;
  4580. r->default_string = NULL;
  4581. }
  4582. void upb_descreader_uninit(upb_descreader *r) {
  4583. free(r->name);
  4584. upb_deflist_uninit(&r->defs);
  4585. free(r->default_string);
  4586. while (r->stack_len > 0) {
  4587. upb_descreader_frame *f = &r->stack[--r->stack_len];
  4588. free(f->name);
  4589. }
  4590. }
  4591. upb_def **upb_descreader_getdefs(upb_descreader *r, void *owner, int *n) {
  4592. *n = r->defs.len;
  4593. upb_deflist_donaterefs(&r->defs, owner);
  4594. return r->defs.defs;
  4595. }
  4596. upb_sink *upb_descreader_input(upb_descreader *r) {
  4597. return &r->sink;
  4598. }
  4599. static upb_msgdef *upb_descreader_top(upb_descreader *r) {
  4600. assert(r->stack_len > 1);
  4601. int index = r->stack[r->stack_len-1].start - 1;
  4602. assert(index >= 0);
  4603. return upb_downcast_msgdef_mutable(r->defs.defs[index]);
  4604. }
  4605. static upb_def *upb_descreader_last(upb_descreader *r) {
  4606. return upb_deflist_last(&r->defs);
  4607. }
  4608. // Start/end handlers for FileDescriptorProto and DescriptorProto (the two
  4609. // entities that have names and can contain sub-definitions.
  4610. void upb_descreader_startcontainer(upb_descreader *r) {
  4611. upb_descreader_frame *f = &r->stack[r->stack_len++];
  4612. f->start = r->defs.len;
  4613. f->name = NULL;
  4614. }
  4615. void upb_descreader_endcontainer(upb_descreader *r) {
  4616. upb_descreader_frame *f = &r->stack[--r->stack_len];
  4617. upb_deflist_qualify(&r->defs, f->name, f->start);
  4618. free(f->name);
  4619. f->name = NULL;
  4620. }
  4621. void upb_descreader_setscopename(upb_descreader *r, char *str) {
  4622. upb_descreader_frame *f = &r->stack[r->stack_len-1];
  4623. free(f->name);
  4624. f->name = str;
  4625. }
  4626. // Handlers for google.protobuf.FileDescriptorProto.
  4627. static bool file_startmsg(void *r, const void *hd) {
  4628. UPB_UNUSED(hd);
  4629. upb_descreader_startcontainer(r);
  4630. return true;
  4631. }
  4632. static bool file_endmsg(void *closure, const void *hd, upb_status *status) {
  4633. UPB_UNUSED(hd);
  4634. UPB_UNUSED(status);
  4635. upb_descreader *r = closure;
  4636. upb_descreader_endcontainer(r);
  4637. return true;
  4638. }
  4639. static size_t file_onpackage(void *closure, const void *hd, const char *buf,
  4640. size_t n, const upb_bufhandle *handle) {
  4641. UPB_UNUSED(hd);
  4642. UPB_UNUSED(handle);
  4643. upb_descreader *r = closure;
  4644. // XXX: see comment at the top of the file.
  4645. upb_descreader_setscopename(r, upb_strndup(buf, n));
  4646. return n;
  4647. }
  4648. // Handlers for google.protobuf.EnumValueDescriptorProto.
  4649. static bool enumval_startmsg(void *closure, const void *hd) {
  4650. UPB_UNUSED(hd);
  4651. upb_descreader *r = closure;
  4652. r->saw_number = false;
  4653. r->saw_name = false;
  4654. return true;
  4655. }
  4656. static size_t enumval_onname(void *closure, const void *hd, const char *buf,
  4657. size_t n, const upb_bufhandle *handle) {
  4658. UPB_UNUSED(hd);
  4659. UPB_UNUSED(handle);
  4660. upb_descreader *r = closure;
  4661. // XXX: see comment at the top of the file.
  4662. free(r->name);
  4663. r->name = upb_strndup(buf, n);
  4664. r->saw_name = true;
  4665. return n;
  4666. }
  4667. static bool enumval_onnumber(void *closure, const void *hd, int32_t val) {
  4668. UPB_UNUSED(hd);
  4669. upb_descreader *r = closure;
  4670. r->number = val;
  4671. r->saw_number = true;
  4672. return true;
  4673. }
  4674. static bool enumval_endmsg(void *closure, const void *hd, upb_status *status) {
  4675. UPB_UNUSED(hd);
  4676. upb_descreader *r = closure;
  4677. if(!r->saw_number || !r->saw_name) {
  4678. upb_status_seterrmsg(status, "Enum value missing name or number.");
  4679. return false;
  4680. }
  4681. upb_enumdef *e = upb_downcast_enumdef_mutable(upb_descreader_last(r));
  4682. upb_enumdef_addval(e, r->name, r->number, status);
  4683. free(r->name);
  4684. r->name = NULL;
  4685. return true;
  4686. }
  4687. // Handlers for google.protobuf.EnumDescriptorProto.
  4688. static bool enum_startmsg(void *closure, const void *hd) {
  4689. UPB_UNUSED(hd);
  4690. upb_descreader *r = closure;
  4691. upb_deflist_push(&r->defs, UPB_UPCAST(upb_enumdef_new(&r->defs)));
  4692. return true;
  4693. }
  4694. static bool enum_endmsg(void *closure, const void *hd, upb_status *status) {
  4695. UPB_UNUSED(hd);
  4696. upb_descreader *r = closure;
  4697. upb_enumdef *e = upb_downcast_enumdef_mutable(upb_descreader_last(r));
  4698. if (upb_def_fullname(upb_descreader_last(r)) == NULL) {
  4699. upb_status_seterrmsg(status, "Enum had no name.");
  4700. return false;
  4701. }
  4702. if (upb_enumdef_numvals(e) == 0) {
  4703. upb_status_seterrmsg(status, "Enum had no values.");
  4704. return false;
  4705. }
  4706. return true;
  4707. }
  4708. static size_t enum_onname(void *closure, const void *hd, const char *buf,
  4709. size_t n, const upb_bufhandle *handle) {
  4710. UPB_UNUSED(hd);
  4711. UPB_UNUSED(handle);
  4712. upb_descreader *r = closure;
  4713. // XXX: see comment at the top of the file.
  4714. char *fullname = upb_strndup(buf, n);
  4715. upb_def_setfullname(upb_descreader_last(r), fullname, NULL);
  4716. free(fullname);
  4717. return n;
  4718. }
  4719. // Handlers for google.protobuf.FieldDescriptorProto
  4720. static bool field_startmsg(void *closure, const void *hd) {
  4721. UPB_UNUSED(hd);
  4722. upb_descreader *r = closure;
  4723. r->f = upb_fielddef_new(&r->defs);
  4724. free(r->default_string);
  4725. r->default_string = NULL;
  4726. // fielddefs default to packed, but descriptors default to non-packed.
  4727. upb_fielddef_setpacked(r->f, false);
  4728. return true;
  4729. }
  4730. // Converts the default value in string "str" into "d". Passes a ref on str.
  4731. // Returns true on success.
  4732. static bool parse_default(char *str, upb_fielddef *f) {
  4733. bool success = true;
  4734. char *end;
  4735. switch (upb_fielddef_type(f)) {
  4736. case UPB_TYPE_INT32: {
  4737. long val = strtol(str, &end, 0);
  4738. if (val > INT32_MAX || val < INT32_MIN || errno == ERANGE || *end)
  4739. success = false;
  4740. else
  4741. upb_fielddef_setdefaultint32(f, val);
  4742. break;
  4743. }
  4744. case UPB_TYPE_INT64: {
  4745. long long val = strtoll(str, &end, 0);
  4746. if (val > INT64_MAX || val < INT64_MIN || errno == ERANGE || *end)
  4747. success = false;
  4748. else
  4749. upb_fielddef_setdefaultint64(f, val);
  4750. break;
  4751. }
  4752. case UPB_TYPE_UINT32: {
  4753. long val = strtoul(str, &end, 0);
  4754. if (val > UINT32_MAX || errno == ERANGE || *end)
  4755. success = false;
  4756. else
  4757. upb_fielddef_setdefaultuint32(f, val);
  4758. break;
  4759. }
  4760. case UPB_TYPE_UINT64: {
  4761. unsigned long long val = strtoull(str, &end, 0);
  4762. if (val > UINT64_MAX || errno == ERANGE || *end)
  4763. success = false;
  4764. else
  4765. upb_fielddef_setdefaultuint64(f, val);
  4766. break;
  4767. }
  4768. case UPB_TYPE_DOUBLE: {
  4769. double val = strtod(str, &end);
  4770. if (errno == ERANGE || *end)
  4771. success = false;
  4772. else
  4773. upb_fielddef_setdefaultdouble(f, val);
  4774. break;
  4775. }
  4776. case UPB_TYPE_FLOAT: {
  4777. float val = strtof(str, &end);
  4778. if (errno == ERANGE || *end)
  4779. success = false;
  4780. else
  4781. upb_fielddef_setdefaultfloat(f, val);
  4782. break;
  4783. }
  4784. case UPB_TYPE_BOOL: {
  4785. if (strcmp(str, "false") == 0)
  4786. upb_fielddef_setdefaultbool(f, false);
  4787. else if (strcmp(str, "true") == 0)
  4788. upb_fielddef_setdefaultbool(f, true);
  4789. else
  4790. success = false;
  4791. break;
  4792. }
  4793. default: abort();
  4794. }
  4795. return success;
  4796. }
  4797. static bool field_endmsg(void *closure, const void *hd, upb_status *status) {
  4798. UPB_UNUSED(hd);
  4799. upb_descreader *r = closure;
  4800. upb_fielddef *f = r->f;
  4801. // TODO: verify that all required fields were present.
  4802. assert(upb_fielddef_number(f) != 0);
  4803. assert(upb_fielddef_name(f) != NULL);
  4804. assert((upb_fielddef_subdefname(f) != NULL) == upb_fielddef_hassubdef(f));
  4805. if (r->default_string) {
  4806. if (upb_fielddef_issubmsg(f)) {
  4807. upb_status_seterrmsg(status, "Submessages cannot have defaults.");
  4808. return false;
  4809. }
  4810. if (upb_fielddef_isstring(f) || upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  4811. upb_fielddef_setdefaultcstr(f, r->default_string, NULL);
  4812. } else {
  4813. if (r->default_string && !parse_default(r->default_string, f)) {
  4814. // We don't worry too much about giving a great error message since the
  4815. // compiler should have ensured this was correct.
  4816. upb_status_seterrmsg(status, "Error converting default value.");
  4817. return false;
  4818. }
  4819. }
  4820. }
  4821. return true;
  4822. }
  4823. static bool field_onlazy(void *closure, const void *hd, bool val) {
  4824. UPB_UNUSED(hd);
  4825. upb_descreader *r = closure;
  4826. upb_fielddef_setlazy(r->f, val);
  4827. return true;
  4828. }
  4829. static bool field_onpacked(void *closure, const void *hd, bool val) {
  4830. UPB_UNUSED(hd);
  4831. upb_descreader *r = closure;
  4832. upb_fielddef_setpacked(r->f, val);
  4833. return true;
  4834. }
  4835. static bool field_ontype(void *closure, const void *hd, int32_t val) {
  4836. UPB_UNUSED(hd);
  4837. upb_descreader *r = closure;
  4838. upb_fielddef_setdescriptortype(r->f, val);
  4839. return true;
  4840. }
  4841. static bool field_onlabel(void *closure, const void *hd, int32_t val) {
  4842. UPB_UNUSED(hd);
  4843. upb_descreader *r = closure;
  4844. upb_fielddef_setlabel(r->f, val);
  4845. return true;
  4846. }
  4847. static bool field_onnumber(void *closure, const void *hd, int32_t val) {
  4848. UPB_UNUSED(hd);
  4849. upb_descreader *r = closure;
  4850. bool ok = upb_fielddef_setnumber(r->f, val, NULL);
  4851. UPB_ASSERT_VAR(ok, ok);
  4852. return true;
  4853. }
  4854. static size_t field_onname(void *closure, const void *hd, const char *buf,
  4855. size_t n, const upb_bufhandle *handle) {
  4856. UPB_UNUSED(hd);
  4857. UPB_UNUSED(handle);
  4858. upb_descreader *r = closure;
  4859. // XXX: see comment at the top of the file.
  4860. char *name = upb_strndup(buf, n);
  4861. upb_fielddef_setname(r->f, name, NULL);
  4862. free(name);
  4863. return n;
  4864. }
  4865. static size_t field_ontypename(void *closure, const void *hd, const char *buf,
  4866. size_t n, const upb_bufhandle *handle) {
  4867. UPB_UNUSED(hd);
  4868. UPB_UNUSED(handle);
  4869. upb_descreader *r = closure;
  4870. // XXX: see comment at the top of the file.
  4871. char *name = upb_strndup(buf, n);
  4872. upb_fielddef_setsubdefname(r->f, name, NULL);
  4873. free(name);
  4874. return n;
  4875. }
  4876. static size_t field_onextendee(void *closure, const void *hd, const char *buf,
  4877. size_t n, const upb_bufhandle *handle) {
  4878. UPB_UNUSED(hd);
  4879. UPB_UNUSED(handle);
  4880. upb_descreader *r = closure;
  4881. // XXX: see comment at the top of the file.
  4882. char *name = upb_strndup(buf, n);
  4883. upb_fielddef_setcontainingtypename(r->f, name, NULL);
  4884. free(name);
  4885. return n;
  4886. }
  4887. static size_t field_ondefaultval(void *closure, const void *hd, const char *buf,
  4888. size_t n, const upb_bufhandle *handle) {
  4889. UPB_UNUSED(hd);
  4890. UPB_UNUSED(handle);
  4891. upb_descreader *r = closure;
  4892. // Have to convert from string to the correct type, but we might not know the
  4893. // type yet, so we save it as a string until the end of the field.
  4894. // XXX: see comment at the top of the file.
  4895. free(r->default_string);
  4896. r->default_string = upb_strndup(buf, n);
  4897. return n;
  4898. }
  4899. // Handlers for google.protobuf.DescriptorProto (representing a message).
  4900. static bool msg_startmsg(void *closure, const void *hd) {
  4901. UPB_UNUSED(hd);
  4902. upb_descreader *r = closure;
  4903. upb_deflist_push(&r->defs, UPB_UPCAST(upb_msgdef_new(&r->defs)));
  4904. upb_descreader_startcontainer(r);
  4905. return true;
  4906. }
  4907. static bool msg_endmsg(void *closure, const void *hd, upb_status *status) {
  4908. UPB_UNUSED(hd);
  4909. upb_descreader *r = closure;
  4910. upb_msgdef *m = upb_descreader_top(r);
  4911. if(!upb_def_fullname(UPB_UPCAST(m))) {
  4912. upb_status_seterrmsg(status, "Encountered message with no name.");
  4913. return false;
  4914. }
  4915. upb_descreader_endcontainer(r);
  4916. return true;
  4917. }
  4918. static size_t msg_onname(void *closure, const void *hd, const char *buf,
  4919. size_t n, const upb_bufhandle *handle) {
  4920. UPB_UNUSED(hd);
  4921. UPB_UNUSED(handle);
  4922. upb_descreader *r = closure;
  4923. upb_msgdef *m = upb_descreader_top(r);
  4924. // XXX: see comment at the top of the file.
  4925. char *name = upb_strndup(buf, n);
  4926. upb_def_setfullname(UPB_UPCAST(m), name, NULL);
  4927. upb_descreader_setscopename(r, name); // Passes ownership of name.
  4928. return n;
  4929. }
  4930. static bool msg_onendfield(void *closure, const void *hd) {
  4931. UPB_UNUSED(hd);
  4932. upb_descreader *r = closure;
  4933. upb_msgdef *m = upb_descreader_top(r);
  4934. upb_msgdef_addfield(m, r->f, &r->defs, NULL);
  4935. r->f = NULL;
  4936. return true;
  4937. }
  4938. static bool pushextension(void *closure, const void *hd) {
  4939. UPB_UNUSED(hd);
  4940. upb_descreader *r = closure;
  4941. assert(upb_fielddef_containingtypename(r->f));
  4942. upb_fielddef_setisextension(r->f, true);
  4943. upb_deflist_push(&r->defs, UPB_UPCAST(r->f));
  4944. r->f = NULL;
  4945. return true;
  4946. }
  4947. #define D(name) upbdefs_google_protobuf_ ## name(s)
  4948. static void reghandlers(const void *closure, upb_handlers *h) {
  4949. const upb_symtab *s = closure;
  4950. const upb_msgdef *m = upb_handlers_msgdef(h);
  4951. if (m == D(DescriptorProto)) {
  4952. upb_handlers_setstartmsg(h, &msg_startmsg, NULL);
  4953. upb_handlers_setendmsg(h, &msg_endmsg, NULL);
  4954. upb_handlers_setstring(h, D(DescriptorProto_name), &msg_onname, NULL);
  4955. upb_handlers_setendsubmsg(h, D(DescriptorProto_field), &msg_onendfield,
  4956. NULL);
  4957. upb_handlers_setendsubmsg(h, D(DescriptorProto_extension), &pushextension,
  4958. NULL);
  4959. } else if (m == D(FileDescriptorProto)) {
  4960. upb_handlers_setstartmsg(h, &file_startmsg, NULL);
  4961. upb_handlers_setendmsg(h, &file_endmsg, NULL);
  4962. upb_handlers_setstring(h, D(FileDescriptorProto_package), &file_onpackage,
  4963. NULL);
  4964. upb_handlers_setendsubmsg(h, D(FileDescriptorProto_extension), &pushextension,
  4965. NULL);
  4966. } else if (m == D(EnumValueDescriptorProto)) {
  4967. upb_handlers_setstartmsg(h, &enumval_startmsg, NULL);
  4968. upb_handlers_setendmsg(h, &enumval_endmsg, NULL);
  4969. upb_handlers_setstring(h, D(EnumValueDescriptorProto_name), &enumval_onname, NULL);
  4970. upb_handlers_setint32(h, D(EnumValueDescriptorProto_number), &enumval_onnumber,
  4971. NULL);
  4972. } else if (m == D(EnumDescriptorProto)) {
  4973. upb_handlers_setstartmsg(h, &enum_startmsg, NULL);
  4974. upb_handlers_setendmsg(h, &enum_endmsg, NULL);
  4975. upb_handlers_setstring(h, D(EnumDescriptorProto_name), &enum_onname, NULL);
  4976. } else if (m == D(FieldDescriptorProto)) {
  4977. upb_handlers_setstartmsg(h, &field_startmsg, NULL);
  4978. upb_handlers_setendmsg(h, &field_endmsg, NULL);
  4979. upb_handlers_setint32(h, D(FieldDescriptorProto_type), &field_ontype,
  4980. NULL);
  4981. upb_handlers_setint32(h, D(FieldDescriptorProto_label), &field_onlabel,
  4982. NULL);
  4983. upb_handlers_setint32(h, D(FieldDescriptorProto_number), &field_onnumber,
  4984. NULL);
  4985. upb_handlers_setstring(h, D(FieldDescriptorProto_name), &field_onname,
  4986. NULL);
  4987. upb_handlers_setstring(h, D(FieldDescriptorProto_type_name),
  4988. &field_ontypename, NULL);
  4989. upb_handlers_setstring(h, D(FieldDescriptorProto_extendee),
  4990. &field_onextendee, NULL);
  4991. upb_handlers_setstring(h, D(FieldDescriptorProto_default_value),
  4992. &field_ondefaultval, NULL);
  4993. } else if (m == D(FieldOptions)) {
  4994. upb_handlers_setbool(h, D(FieldOptions_lazy), &field_onlazy, NULL);
  4995. upb_handlers_setbool(h, D(FieldOptions_packed), &field_onpacked, NULL);
  4996. }
  4997. }
  4998. #undef D
  4999. const upb_handlers *upb_descreader_newhandlers(const void *owner) {
  5000. const upb_symtab *s = upbdefs_google_protobuf_descriptor(&s);
  5001. const upb_handlers *h = upb_handlers_newfrozen(
  5002. upbdefs_google_protobuf_FileDescriptorSet(s), owner, reghandlers, s);
  5003. upb_symtab_unref(s, &s);
  5004. return h;
  5005. }
  5006. /*
  5007. * upb - a minimalist implementation of protocol buffers.
  5008. *
  5009. * Copyright (c) 2013 Google Inc. See LICENSE for details.
  5010. * Author: Josh Haberman <jhaberman@gmail.com>
  5011. *
  5012. * Code to compile a upb::Handlers into bytecode for decoding a protobuf
  5013. * according to that specific schema and destination handlers.
  5014. *
  5015. * Compiling to bytecode is always the first step. If we are using the
  5016. * interpreted decoder we leave it as bytecode and interpret that. If we are
  5017. * using a JIT decoder we use a code generator to turn the bytecode into native
  5018. * code, LLVM IR, etc.
  5019. *
  5020. * Bytecode definition is in decoder.int.h.
  5021. */
  5022. #include <stdarg.h>
  5023. #ifdef UPB_DUMP_BYTECODE
  5024. #include <stdio.h>
  5025. #endif
  5026. #define MAXLABEL 5
  5027. #define EMPTYLABEL -1
  5028. /* mgroup *********************************************************************/
  5029. static void freegroup(upb_refcounted *r) {
  5030. mgroup *g = (mgroup*)r;
  5031. upb_inttable_uninit(&g->methods);
  5032. #ifdef UPB_USE_JIT_X64
  5033. upb_pbdecoder_freejit(g);
  5034. #endif
  5035. free(g->bytecode);
  5036. free(g);
  5037. }
  5038. static void visitgroup(const upb_refcounted *r, upb_refcounted_visit *visit,
  5039. void *closure) {
  5040. const mgroup *g = (const mgroup*)r;
  5041. upb_inttable_iter i;
  5042. upb_inttable_begin(&i, &g->methods);
  5043. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5044. upb_pbdecodermethod *method = upb_value_getptr(upb_inttable_iter_value(&i));
  5045. visit(r, UPB_UPCAST(method), closure);
  5046. }
  5047. }
  5048. mgroup *newgroup(const void *owner) {
  5049. mgroup *g = malloc(sizeof(*g));
  5050. static const struct upb_refcounted_vtbl vtbl = {visitgroup, freegroup};
  5051. upb_refcounted_init(UPB_UPCAST(g), &vtbl, owner);
  5052. upb_inttable_init(&g->methods, UPB_CTYPE_PTR);
  5053. g->bytecode = NULL;
  5054. g->bytecode_end = NULL;
  5055. return g;
  5056. }
  5057. /* upb_pbdecodermethod ********************************************************/
  5058. static void freemethod(upb_refcounted *r) {
  5059. upb_pbdecodermethod *method = (upb_pbdecodermethod*)r;
  5060. upb_byteshandler_uninit(&method->input_handler_);
  5061. if (method->dest_handlers_) {
  5062. upb_handlers_unref(method->dest_handlers_, method);
  5063. }
  5064. upb_inttable_uninit(&method->dispatch);
  5065. free(method);
  5066. }
  5067. static void visitmethod(const upb_refcounted *r, upb_refcounted_visit *visit,
  5068. void *closure) {
  5069. const upb_pbdecodermethod *m = (const upb_pbdecodermethod*)r;
  5070. visit(r, m->group, closure);
  5071. }
  5072. static upb_pbdecodermethod *newmethod(const upb_handlers *dest_handlers,
  5073. mgroup *group) {
  5074. static const struct upb_refcounted_vtbl vtbl = {visitmethod, freemethod};
  5075. upb_pbdecodermethod *ret = malloc(sizeof(*ret));
  5076. upb_refcounted_init(UPB_UPCAST(ret), &vtbl, &ret);
  5077. upb_byteshandler_init(&ret->input_handler_);
  5078. // The method references the group and vice-versa, in a circular reference.
  5079. upb_ref2(ret, group);
  5080. upb_ref2(group, ret);
  5081. upb_inttable_insertptr(&group->methods, dest_handlers, upb_value_ptr(ret));
  5082. upb_refcounted_unref(UPB_UPCAST(ret), &ret);
  5083. ret->group = UPB_UPCAST(group);
  5084. ret->dest_handlers_ = dest_handlers;
  5085. ret->is_native_ = false; // If we JIT, it will update this later.
  5086. upb_inttable_init(&ret->dispatch, UPB_CTYPE_UINT64);
  5087. if (ret->dest_handlers_) {
  5088. upb_handlers_ref(ret->dest_handlers_, ret);
  5089. }
  5090. return ret;
  5091. }
  5092. void upb_pbdecodermethod_ref(const upb_pbdecodermethod *m, const void *owner) {
  5093. upb_refcounted_ref(UPB_UPCAST(m), owner);
  5094. }
  5095. void upb_pbdecodermethod_unref(const upb_pbdecodermethod *m,
  5096. const void *owner) {
  5097. upb_refcounted_unref(UPB_UPCAST(m), owner);
  5098. }
  5099. void upb_pbdecodermethod_donateref(const upb_pbdecodermethod *m,
  5100. const void *from, const void *to) {
  5101. upb_refcounted_donateref(UPB_UPCAST(m), from, to);
  5102. }
  5103. void upb_pbdecodermethod_checkref(const upb_pbdecodermethod *m,
  5104. const void *owner) {
  5105. upb_refcounted_checkref(UPB_UPCAST(m), owner);
  5106. }
  5107. const upb_handlers *upb_pbdecodermethod_desthandlers(
  5108. const upb_pbdecodermethod *m) {
  5109. return m->dest_handlers_;
  5110. }
  5111. const upb_byteshandler *upb_pbdecodermethod_inputhandler(
  5112. const upb_pbdecodermethod *m) {
  5113. return &m->input_handler_;
  5114. }
  5115. bool upb_pbdecodermethod_isnative(const upb_pbdecodermethod *m) {
  5116. return m->is_native_;
  5117. }
  5118. const upb_pbdecodermethod *upb_pbdecodermethod_new(
  5119. const upb_pbdecodermethodopts *opts, const void *owner) {
  5120. upb_pbcodecache cache;
  5121. upb_pbcodecache_init(&cache);
  5122. const upb_pbdecodermethod *ret =
  5123. upb_pbcodecache_getdecodermethod(&cache, opts);
  5124. upb_pbdecodermethod_ref(ret, owner);
  5125. upb_pbcodecache_uninit(&cache);
  5126. return ret;
  5127. }
  5128. /* bytecode compiler **********************************************************/
  5129. // Data used only at compilation time.
  5130. typedef struct {
  5131. mgroup *group;
  5132. uint32_t *pc;
  5133. int fwd_labels[MAXLABEL];
  5134. int back_labels[MAXLABEL];
  5135. // For fields marked "lazy", parse them lazily or eagerly?
  5136. bool lazy;
  5137. } compiler;
  5138. static compiler *newcompiler(mgroup *group, bool lazy) {
  5139. compiler *ret = malloc(sizeof(*ret));
  5140. ret->group = group;
  5141. ret->lazy = lazy;
  5142. for (int i = 0; i < MAXLABEL; i++) {
  5143. ret->fwd_labels[i] = EMPTYLABEL;
  5144. ret->back_labels[i] = EMPTYLABEL;
  5145. }
  5146. return ret;
  5147. }
  5148. static void freecompiler(compiler *c) {
  5149. free(c);
  5150. }
  5151. const size_t ptr_words = sizeof(void*) / sizeof(uint32_t);
  5152. // How many words an instruction is.
  5153. static int instruction_len(uint32_t instr) {
  5154. switch (getop(instr)) {
  5155. case OP_SETDISPATCH: return 1 + ptr_words;
  5156. case OP_TAGN: return 3;
  5157. case OP_SETBIGGROUPNUM: return 2;
  5158. default: return 1;
  5159. }
  5160. }
  5161. bool op_has_longofs(int32_t instruction) {
  5162. switch (getop(instruction)) {
  5163. case OP_CALL:
  5164. case OP_BRANCH:
  5165. case OP_CHECKDELIM:
  5166. return true;
  5167. // The "tag" instructions only have 8 bytes available for the jump target,
  5168. // but that is ok because these opcodes only require short jumps.
  5169. case OP_TAG1:
  5170. case OP_TAG2:
  5171. case OP_TAGN:
  5172. return false;
  5173. default:
  5174. assert(false);
  5175. return false;
  5176. }
  5177. }
  5178. static int32_t getofs(uint32_t instruction) {
  5179. if (op_has_longofs(instruction)) {
  5180. return (int32_t)instruction >> 8;
  5181. } else {
  5182. return (int8_t)(instruction >> 8);
  5183. }
  5184. }
  5185. static void setofs(uint32_t *instruction, int32_t ofs) {
  5186. if (op_has_longofs(*instruction)) {
  5187. *instruction = getop(*instruction) | ofs << 8;
  5188. } else {
  5189. *instruction = (*instruction & ~0xff00) | ((ofs & 0xff) << 8);
  5190. }
  5191. assert(getofs(*instruction) == ofs); // Would fail in cases of overflow.
  5192. }
  5193. static uint32_t pcofs(compiler *c) { return c->pc - c->group->bytecode; }
  5194. // Defines a local label at the current PC location. All previous forward
  5195. // references are updated to point to this location. The location is noted
  5196. // for any future backward references.
  5197. static void label(compiler *c, unsigned int label) {
  5198. assert(label < MAXLABEL);
  5199. int val = c->fwd_labels[label];
  5200. uint32_t *codep = (val == EMPTYLABEL) ? NULL : c->group->bytecode + val;
  5201. while (codep) {
  5202. int ofs = getofs(*codep);
  5203. setofs(codep, c->pc - codep - instruction_len(*codep));
  5204. codep = ofs ? codep + ofs : NULL;
  5205. }
  5206. c->fwd_labels[label] = EMPTYLABEL;
  5207. c->back_labels[label] = pcofs(c);
  5208. }
  5209. // Creates a reference to a numbered label; either a forward reference
  5210. // (positive arg) or backward reference (negative arg). For forward references
  5211. // the value returned now is actually a "next" pointer into a linked list of all
  5212. // instructions that use this label and will be patched later when the label is
  5213. // defined with label().
  5214. //
  5215. // The returned value is the offset that should be written into the instruction.
  5216. static int32_t labelref(compiler *c, int label) {
  5217. assert(label < MAXLABEL);
  5218. if (label == LABEL_DISPATCH) {
  5219. // No resolving required.
  5220. return 0;
  5221. } else if (label < 0) {
  5222. // Backward local label. Relative to the next instruction.
  5223. uint32_t from = (c->pc + 1) - c->group->bytecode;
  5224. return c->back_labels[-label] - from;
  5225. } else {
  5226. // Forward local label: prepend to (possibly-empty) linked list.
  5227. int *lptr = &c->fwd_labels[label];
  5228. int32_t ret = (*lptr == EMPTYLABEL) ? 0 : *lptr - pcofs(c);
  5229. *lptr = pcofs(c);
  5230. return ret;
  5231. }
  5232. }
  5233. static void put32(compiler *c, uint32_t v) {
  5234. mgroup *g = c->group;
  5235. if (c->pc == g->bytecode_end) {
  5236. int ofs = pcofs(c);
  5237. size_t oldsize = g->bytecode_end - g->bytecode;
  5238. size_t newsize = UPB_MAX(oldsize * 2, 64);
  5239. // TODO(haberman): handle OOM.
  5240. g->bytecode = realloc(g->bytecode, newsize * sizeof(uint32_t));
  5241. g->bytecode_end = g->bytecode + newsize;
  5242. c->pc = g->bytecode + ofs;
  5243. }
  5244. *c->pc++ = v;
  5245. }
  5246. static void putop(compiler *c, opcode op, ...) {
  5247. va_list ap;
  5248. va_start(ap, op);
  5249. switch (op) {
  5250. case OP_SETDISPATCH: {
  5251. uintptr_t ptr = (uintptr_t)va_arg(ap, void*);
  5252. put32(c, OP_SETDISPATCH);
  5253. put32(c, ptr);
  5254. if (sizeof(uintptr_t) > sizeof(uint32_t))
  5255. put32(c, (uint64_t)ptr >> 32);
  5256. break;
  5257. }
  5258. case OP_STARTMSG:
  5259. case OP_ENDMSG:
  5260. case OP_PUSHLENDELIM:
  5261. case OP_POP:
  5262. case OP_SETDELIM:
  5263. case OP_HALT:
  5264. case OP_RET:
  5265. put32(c, op);
  5266. break;
  5267. case OP_PARSE_DOUBLE:
  5268. case OP_PARSE_FLOAT:
  5269. case OP_PARSE_INT64:
  5270. case OP_PARSE_UINT64:
  5271. case OP_PARSE_INT32:
  5272. case OP_PARSE_FIXED64:
  5273. case OP_PARSE_FIXED32:
  5274. case OP_PARSE_BOOL:
  5275. case OP_PARSE_UINT32:
  5276. case OP_PARSE_SFIXED32:
  5277. case OP_PARSE_SFIXED64:
  5278. case OP_PARSE_SINT32:
  5279. case OP_PARSE_SINT64:
  5280. case OP_STARTSEQ:
  5281. case OP_ENDSEQ:
  5282. case OP_STARTSUBMSG:
  5283. case OP_ENDSUBMSG:
  5284. case OP_STARTSTR:
  5285. case OP_STRING:
  5286. case OP_ENDSTR:
  5287. case OP_PUSHTAGDELIM:
  5288. put32(c, op | va_arg(ap, upb_selector_t) << 8);
  5289. break;
  5290. case OP_SETBIGGROUPNUM:
  5291. put32(c, op);
  5292. put32(c, va_arg(ap, int));
  5293. break;
  5294. case OP_CALL: {
  5295. const upb_pbdecodermethod *method = va_arg(ap, upb_pbdecodermethod *);
  5296. put32(c, op | (method->code_base.ofs - (pcofs(c) + 1)) << 8);
  5297. break;
  5298. }
  5299. case OP_CHECKDELIM:
  5300. case OP_BRANCH: {
  5301. uint32_t instruction = op;
  5302. int label = va_arg(ap, int);
  5303. setofs(&instruction, labelref(c, label));
  5304. put32(c, instruction);
  5305. break;
  5306. }
  5307. case OP_TAG1:
  5308. case OP_TAG2: {
  5309. int label = va_arg(ap, int);
  5310. uint64_t tag = va_arg(ap, uint64_t);
  5311. uint32_t instruction = op | (tag << 16);
  5312. assert(tag <= 0xffff);
  5313. setofs(&instruction, labelref(c, label));
  5314. put32(c, instruction);
  5315. break;
  5316. }
  5317. case OP_TAGN: {
  5318. int label = va_arg(ap, int);
  5319. uint64_t tag = va_arg(ap, uint64_t);
  5320. uint32_t instruction = op | (upb_value_size(tag) << 16);
  5321. setofs(&instruction, labelref(c, label));
  5322. put32(c, instruction);
  5323. put32(c, tag);
  5324. put32(c, tag >> 32);
  5325. break;
  5326. }
  5327. }
  5328. va_end(ap);
  5329. }
  5330. #if defined(UPB_USE_JIT_X64) || defined(UPB_DUMP_BYTECODE)
  5331. const char *upb_pbdecoder_getopname(unsigned int op) {
  5332. #define OP(op) [OP_ ## op] = "OP_" #op
  5333. #define T(op) OP(PARSE_##op)
  5334. static const char *names[] = {
  5335. "<no opcode>",
  5336. T(DOUBLE), T(FLOAT), T(INT64), T(UINT64), T(INT32), T(FIXED64), T(FIXED32),
  5337. T(BOOL), T(UINT32), T(SFIXED32), T(SFIXED64), T(SINT32), T(SINT64),
  5338. OP(STARTMSG), OP(ENDMSG), OP(STARTSEQ), OP(ENDSEQ), OP(STARTSUBMSG),
  5339. OP(ENDSUBMSG), OP(STARTSTR), OP(STRING), OP(ENDSTR), OP(CALL), OP(RET),
  5340. OP(PUSHLENDELIM), OP(PUSHTAGDELIM), OP(SETDELIM), OP(CHECKDELIM),
  5341. OP(BRANCH), OP(TAG1), OP(TAG2), OP(TAGN), OP(SETDISPATCH), OP(POP),
  5342. OP(SETBIGGROUPNUM), OP(HALT),
  5343. };
  5344. return op > OP_HALT ? names[0] : names[op];
  5345. #undef OP
  5346. #undef T
  5347. }
  5348. #endif
  5349. #ifdef UPB_DUMP_BYTECODE
  5350. static void dumpbc(uint32_t *p, uint32_t *end, FILE *f) {
  5351. uint32_t *begin = p;
  5352. while (p < end) {
  5353. fprintf(f, "%p %8tx", p, p - begin);
  5354. uint32_t instr = *p++;
  5355. uint8_t op = getop(instr);
  5356. fprintf(f, " %s", upb_pbdecoder_getopname(op));
  5357. switch ((opcode)op) {
  5358. case OP_SETDISPATCH: {
  5359. const upb_inttable *dispatch;
  5360. memcpy(&dispatch, p, sizeof(void*));
  5361. p += ptr_words;
  5362. const upb_pbdecodermethod *method =
  5363. (void *)((char *)dispatch -
  5364. offsetof(upb_pbdecodermethod, dispatch));
  5365. fprintf(f, " %s", upb_msgdef_fullname(
  5366. upb_handlers_msgdef(method->dest_handlers_)));
  5367. break;
  5368. }
  5369. case OP_STARTMSG:
  5370. case OP_ENDMSG:
  5371. case OP_PUSHLENDELIM:
  5372. case OP_POP:
  5373. case OP_SETDELIM:
  5374. case OP_HALT:
  5375. case OP_RET:
  5376. break;
  5377. case OP_PARSE_DOUBLE:
  5378. case OP_PARSE_FLOAT:
  5379. case OP_PARSE_INT64:
  5380. case OP_PARSE_UINT64:
  5381. case OP_PARSE_INT32:
  5382. case OP_PARSE_FIXED64:
  5383. case OP_PARSE_FIXED32:
  5384. case OP_PARSE_BOOL:
  5385. case OP_PARSE_UINT32:
  5386. case OP_PARSE_SFIXED32:
  5387. case OP_PARSE_SFIXED64:
  5388. case OP_PARSE_SINT32:
  5389. case OP_PARSE_SINT64:
  5390. case OP_STARTSEQ:
  5391. case OP_ENDSEQ:
  5392. case OP_STARTSUBMSG:
  5393. case OP_ENDSUBMSG:
  5394. case OP_STARTSTR:
  5395. case OP_STRING:
  5396. case OP_ENDSTR:
  5397. case OP_PUSHTAGDELIM:
  5398. fprintf(f, " %d", instr >> 8);
  5399. break;
  5400. case OP_SETBIGGROUPNUM:
  5401. fprintf(f, " %d", *p++);
  5402. break;
  5403. case OP_CHECKDELIM:
  5404. case OP_CALL:
  5405. case OP_BRANCH:
  5406. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  5407. break;
  5408. case OP_TAG1:
  5409. case OP_TAG2: {
  5410. fprintf(f, " tag:0x%x", instr >> 16);
  5411. if (getofs(instr)) {
  5412. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  5413. }
  5414. break;
  5415. }
  5416. case OP_TAGN: {
  5417. uint64_t tag = *p++;
  5418. tag |= (uint64_t)*p++ << 32;
  5419. fprintf(f, " tag:0x%llx", (long long)tag);
  5420. fprintf(f, " n:%d", instr >> 16);
  5421. if (getofs(instr)) {
  5422. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  5423. }
  5424. break;
  5425. }
  5426. }
  5427. fputs("\n", f);
  5428. }
  5429. }
  5430. #endif
  5431. static uint64_t get_encoded_tag(const upb_fielddef *f, int wire_type) {
  5432. uint32_t tag = (upb_fielddef_number(f) << 3) | wire_type;
  5433. uint64_t encoded_tag = upb_vencode32(tag);
  5434. // No tag should be greater than 5 bytes.
  5435. assert(encoded_tag <= 0xffffffffff);
  5436. return encoded_tag;
  5437. }
  5438. static void putchecktag(compiler *c, const upb_fielddef *f,
  5439. int wire_type, int dest) {
  5440. uint64_t tag = get_encoded_tag(f, wire_type);
  5441. switch (upb_value_size(tag)) {
  5442. case 1:
  5443. putop(c, OP_TAG1, dest, tag);
  5444. break;
  5445. case 2:
  5446. putop(c, OP_TAG2, dest, tag);
  5447. break;
  5448. default:
  5449. putop(c, OP_TAGN, dest, tag);
  5450. break;
  5451. }
  5452. }
  5453. static upb_selector_t getsel(const upb_fielddef *f, upb_handlertype_t type) {
  5454. upb_selector_t selector;
  5455. bool ok = upb_handlers_getselector(f, type, &selector);
  5456. UPB_ASSERT_VAR(ok, ok);
  5457. return selector;
  5458. }
  5459. // Takes an existing, primary dispatch table entry and repacks it with a
  5460. // different alternate wire type. Called when we are inserting a secondary
  5461. // dispatch table entry for an alternate wire type.
  5462. static uint64_t repack(uint64_t dispatch, int new_wt2) {
  5463. uint64_t ofs;
  5464. uint8_t wt1;
  5465. uint8_t old_wt2;
  5466. upb_pbdecoder_unpackdispatch(dispatch, &ofs, &wt1, &old_wt2);
  5467. assert(old_wt2 == NO_WIRE_TYPE); // wt2 should not be set yet.
  5468. return upb_pbdecoder_packdispatch(ofs, wt1, new_wt2);
  5469. }
  5470. // Marks the current bytecode position as the dispatch target for this message,
  5471. // field, and wire type.
  5472. static void dispatchtarget(compiler *c, upb_pbdecodermethod *method,
  5473. const upb_fielddef *f, int wire_type) {
  5474. // Offset is relative to msg base.
  5475. uint64_t ofs = pcofs(c) - method->code_base.ofs;
  5476. uint32_t fn = upb_fielddef_number(f);
  5477. upb_inttable *d = &method->dispatch;
  5478. upb_value v;
  5479. if (upb_inttable_remove(d, fn, &v)) {
  5480. // TODO: prioritize based on packed setting in .proto file.
  5481. uint64_t repacked = repack(upb_value_getuint64(v), wire_type);
  5482. upb_inttable_insert(d, fn, upb_value_uint64(repacked));
  5483. upb_inttable_insert(d, fn + UPB_MAX_FIELDNUMBER, upb_value_uint64(ofs));
  5484. } else {
  5485. uint64_t val = upb_pbdecoder_packdispatch(ofs, wire_type, NO_WIRE_TYPE);
  5486. upb_inttable_insert(d, fn, upb_value_uint64(val));
  5487. }
  5488. }
  5489. static void putpush(compiler *c, const upb_fielddef *f) {
  5490. if (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE) {
  5491. putop(c, OP_PUSHLENDELIM);
  5492. } else {
  5493. uint32_t fn = upb_fielddef_number(f);
  5494. if (fn >= 1 << 24) {
  5495. putop(c, OP_PUSHTAGDELIM, 0);
  5496. putop(c, OP_SETBIGGROUPNUM, fn);
  5497. } else {
  5498. putop(c, OP_PUSHTAGDELIM, fn);
  5499. }
  5500. }
  5501. }
  5502. static upb_pbdecodermethod *find_submethod(const compiler *c,
  5503. const upb_pbdecodermethod *method,
  5504. const upb_fielddef *f) {
  5505. const upb_handlers *sub =
  5506. upb_handlers_getsubhandlers(method->dest_handlers_, f);
  5507. upb_value v;
  5508. return upb_inttable_lookupptr(&c->group->methods, sub, &v)
  5509. ? upb_value_getptr(v)
  5510. : NULL;
  5511. }
  5512. static void putsel(compiler *c, opcode op, upb_selector_t sel,
  5513. const upb_handlers *h) {
  5514. if (upb_handlers_gethandler(h, sel)) {
  5515. putop(c, op, sel);
  5516. }
  5517. }
  5518. // Puts an opcode to call a callback, but only if a callback actually exists for
  5519. // this field and handler type.
  5520. static void maybeput(compiler *c, opcode op, const upb_handlers *h,
  5521. const upb_fielddef *f, upb_handlertype_t type) {
  5522. putsel(c, op, getsel(f, type), h);
  5523. }
  5524. static bool haslazyhandlers(const upb_handlers *h, const upb_fielddef *f) {
  5525. if (!upb_fielddef_lazy(f))
  5526. return false;
  5527. return upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STARTSTR)) ||
  5528. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STRING)) ||
  5529. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_ENDSTR));
  5530. }
  5531. /* bytecode compiler code generation ******************************************/
  5532. // Symbolic names for our local labels.
  5533. #define LABEL_LOOPSTART 1 // Top of a repeated field loop.
  5534. #define LABEL_LOOPBREAK 2 // To jump out of a repeated loop
  5535. #define LABEL_FIELD 3 // Jump backward to find the most recent field.
  5536. #define LABEL_ENDMSG 4 // To reach the OP_ENDMSG instr for this msg.
  5537. // Generates bytecode to parse a single non-lazy message field.
  5538. static void generate_msgfield(compiler *c, const upb_fielddef *f,
  5539. upb_pbdecodermethod *method) {
  5540. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  5541. const upb_pbdecodermethod *sub_m = find_submethod(c, method, f);
  5542. if (!sub_m) {
  5543. // Don't emit any code for this field at all; it will be parsed as an
  5544. // unknown field.
  5545. return;
  5546. }
  5547. label(c, LABEL_FIELD);
  5548. int wire_type =
  5549. (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE)
  5550. ? UPB_WIRE_TYPE_DELIMITED
  5551. : UPB_WIRE_TYPE_START_GROUP;
  5552. if (upb_fielddef_isseq(f)) {
  5553. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5554. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  5555. dispatchtarget(c, method, f, wire_type);
  5556. putop(c, OP_PUSHTAGDELIM, 0);
  5557. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  5558. label(c, LABEL_LOOPSTART);
  5559. putpush(c, f);
  5560. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  5561. putop(c, OP_CALL, sub_m);
  5562. putop(c, OP_POP);
  5563. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  5564. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  5565. putop(c, OP_SETDELIM);
  5566. }
  5567. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5568. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  5569. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5570. label(c, LABEL_LOOPBREAK);
  5571. putop(c, OP_POP);
  5572. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  5573. } else {
  5574. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5575. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  5576. dispatchtarget(c, method, f, wire_type);
  5577. putpush(c, f);
  5578. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  5579. putop(c, OP_CALL, sub_m);
  5580. putop(c, OP_POP);
  5581. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  5582. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  5583. putop(c, OP_SETDELIM);
  5584. }
  5585. }
  5586. }
  5587. // Generates bytecode to parse a single string or lazy submessage field.
  5588. static void generate_delimfield(compiler *c, const upb_fielddef *f,
  5589. upb_pbdecodermethod *method) {
  5590. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  5591. label(c, LABEL_FIELD);
  5592. if (upb_fielddef_isseq(f)) {
  5593. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5594. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  5595. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  5596. putop(c, OP_PUSHTAGDELIM, 0);
  5597. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  5598. label(c, LABEL_LOOPSTART);
  5599. putop(c, OP_PUSHLENDELIM);
  5600. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  5601. // Need to emit even if no handler to skip past the string.
  5602. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  5603. putop(c, OP_POP);
  5604. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  5605. putop(c, OP_SETDELIM);
  5606. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5607. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_LOOPBREAK);
  5608. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5609. label(c, LABEL_LOOPBREAK);
  5610. putop(c, OP_POP);
  5611. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  5612. } else {
  5613. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5614. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  5615. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  5616. putop(c, OP_PUSHLENDELIM);
  5617. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  5618. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  5619. putop(c, OP_POP);
  5620. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  5621. putop(c, OP_SETDELIM);
  5622. }
  5623. }
  5624. // Generates bytecode to parse a single primitive field.
  5625. static void generate_primitivefield(compiler *c, const upb_fielddef *f,
  5626. upb_pbdecodermethod *method) {
  5627. label(c, LABEL_FIELD);
  5628. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  5629. upb_descriptortype_t descriptor_type = upb_fielddef_descriptortype(f);
  5630. // From a decoding perspective, ENUM is the same as INT32.
  5631. if (descriptor_type == UPB_DESCRIPTOR_TYPE_ENUM)
  5632. descriptor_type = UPB_DESCRIPTOR_TYPE_INT32;
  5633. opcode parse_type = (opcode)descriptor_type;
  5634. // TODO(haberman): generate packed or non-packed first depending on "packed"
  5635. // setting in the fielddef. This will favor (in speed) whichever was
  5636. // specified.
  5637. assert((int)parse_type >= 0 && parse_type <= OP_MAX);
  5638. upb_selector_t sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  5639. int wire_type = upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  5640. if (upb_fielddef_isseq(f)) {
  5641. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5642. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  5643. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  5644. putop(c, OP_PUSHLENDELIM);
  5645. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); // Packed
  5646. label(c, LABEL_LOOPSTART);
  5647. putop(c, parse_type, sel);
  5648. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5649. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5650. dispatchtarget(c, method, f, wire_type);
  5651. putop(c, OP_PUSHTAGDELIM, 0);
  5652. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); // Non-packed
  5653. label(c, LABEL_LOOPSTART);
  5654. putop(c, parse_type, sel);
  5655. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5656. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  5657. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5658. label(c, LABEL_LOOPBREAK);
  5659. putop(c, OP_POP); // Packed and non-packed join.
  5660. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  5661. putop(c, OP_SETDELIM); // Could remove for non-packed by dup ENDSEQ.
  5662. } else {
  5663. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5664. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  5665. dispatchtarget(c, method, f, wire_type);
  5666. putop(c, parse_type, sel);
  5667. }
  5668. }
  5669. // Adds bytecode for parsing the given message to the given decoderplan,
  5670. // while adding all dispatch targets to this message's dispatch table.
  5671. static void compile_method(compiler *c, upb_pbdecodermethod *method) {
  5672. assert(method);
  5673. // Clear all entries in the dispatch table.
  5674. upb_inttable_uninit(&method->dispatch);
  5675. upb_inttable_init(&method->dispatch, UPB_CTYPE_UINT64);
  5676. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  5677. const upb_msgdef *md = upb_handlers_msgdef(h);
  5678. method->code_base.ofs = pcofs(c);
  5679. putop(c, OP_SETDISPATCH, &method->dispatch);
  5680. putsel(c, OP_STARTMSG, UPB_STARTMSG_SELECTOR, h);
  5681. label(c, LABEL_FIELD);
  5682. upb_msg_iter i;
  5683. for(upb_msg_begin(&i, md); !upb_msg_done(&i); upb_msg_next(&i)) {
  5684. const upb_fielddef *f = upb_msg_iter_field(&i);
  5685. upb_fieldtype_t type = upb_fielddef_type(f);
  5686. if (type == UPB_TYPE_MESSAGE && !(haslazyhandlers(h, f) && c->lazy)) {
  5687. generate_msgfield(c, f, method);
  5688. } else if (type == UPB_TYPE_STRING || type == UPB_TYPE_BYTES ||
  5689. type == UPB_TYPE_MESSAGE) {
  5690. generate_delimfield(c, f, method);
  5691. } else {
  5692. generate_primitivefield(c, f, method);
  5693. }
  5694. }
  5695. // For now we just loop back to the last field of the message (or if none,
  5696. // the DISPATCH opcode for the message.
  5697. putop(c, OP_BRANCH, -LABEL_FIELD);
  5698. // Insert both a label and a dispatch table entry for this end-of-msg.
  5699. label(c, LABEL_ENDMSG);
  5700. upb_value val = upb_value_uint64(pcofs(c) - method->code_base.ofs);
  5701. upb_inttable_insert(&method->dispatch, DISPATCH_ENDMSG, val);
  5702. putsel(c, OP_ENDMSG, UPB_ENDMSG_SELECTOR, h);
  5703. putop(c, OP_RET);
  5704. upb_inttable_compact(&method->dispatch);
  5705. }
  5706. // Populate "methods" with new upb_pbdecodermethod objects reachable from "h".
  5707. // Returns the method for these handlers.
  5708. //
  5709. // Generates a new method for every destination handlers reachable from "h".
  5710. static void find_methods(compiler *c, const upb_handlers *h) {
  5711. upb_value v;
  5712. if (upb_inttable_lookupptr(&c->group->methods, h, &v))
  5713. return;
  5714. newmethod(h, c->group);
  5715. // Find submethods.
  5716. upb_msg_iter i;
  5717. const upb_msgdef *md = upb_handlers_msgdef(h);
  5718. for(upb_msg_begin(&i, md); !upb_msg_done(&i); upb_msg_next(&i)) {
  5719. const upb_fielddef *f = upb_msg_iter_field(&i);
  5720. const upb_handlers *sub_h;
  5721. if (upb_fielddef_type(f) == UPB_TYPE_MESSAGE &&
  5722. (sub_h = upb_handlers_getsubhandlers(h, f)) != NULL) {
  5723. // We only generate a decoder method for submessages with handlers.
  5724. // Others will be parsed as unknown fields.
  5725. find_methods(c, sub_h);
  5726. }
  5727. }
  5728. }
  5729. // (Re-)compile bytecode for all messages in "msgs."
  5730. // Overwrites any existing bytecode in "c".
  5731. static void compile_methods(compiler *c) {
  5732. // Start over at the beginning of the bytecode.
  5733. c->pc = c->group->bytecode;
  5734. upb_inttable_iter i;
  5735. upb_inttable_begin(&i, &c->group->methods);
  5736. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5737. upb_pbdecodermethod *method = upb_value_getptr(upb_inttable_iter_value(&i));
  5738. compile_method(c, method);
  5739. }
  5740. }
  5741. static void set_bytecode_handlers(mgroup *g) {
  5742. upb_inttable_iter i;
  5743. upb_inttable_begin(&i, &g->methods);
  5744. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5745. upb_pbdecodermethod *m = upb_value_getptr(upb_inttable_iter_value(&i));
  5746. m->code_base.ptr = g->bytecode + m->code_base.ofs;
  5747. upb_byteshandler *h = &m->input_handler_;
  5748. upb_byteshandler_setstartstr(h, upb_pbdecoder_startbc, m->code_base.ptr);
  5749. upb_byteshandler_setstring(h, upb_pbdecoder_decode, g);
  5750. upb_byteshandler_setendstr(h, upb_pbdecoder_end, m);
  5751. }
  5752. }
  5753. /* JIT setup. ******************************************************************/
  5754. #ifdef UPB_USE_JIT_X64
  5755. static void sethandlers(mgroup *g, bool allowjit) {
  5756. g->jit_code = NULL;
  5757. if (allowjit) {
  5758. // Compile byte-code into machine code, create handlers.
  5759. upb_pbdecoder_jit(g);
  5760. } else {
  5761. set_bytecode_handlers(g);
  5762. }
  5763. }
  5764. #else // UPB_USE_JIT_X64
  5765. static void sethandlers(mgroup *g, bool allowjit) {
  5766. // No JIT compiled in; use bytecode handlers unconditionally.
  5767. UPB_UNUSED(allowjit);
  5768. set_bytecode_handlers(g);
  5769. }
  5770. #endif // UPB_USE_JIT_X64
  5771. // TODO(haberman): allow this to be constructed for an arbitrary set of dest
  5772. // handlers and other mgroups (but verify we have a transitive closure).
  5773. const mgroup *mgroup_new(const upb_handlers *dest, bool allowjit, bool lazy,
  5774. const void *owner) {
  5775. UPB_UNUSED(allowjit);
  5776. assert(upb_handlers_isfrozen(dest));
  5777. mgroup *g = newgroup(owner);
  5778. compiler *c = newcompiler(g, lazy);
  5779. find_methods(c, dest);
  5780. // We compile in two passes:
  5781. // 1. all messages are assigned relative offsets from the beginning of the
  5782. // bytecode (saved in method->code_base).
  5783. // 2. forwards OP_CALL instructions can be correctly linked since message
  5784. // offsets have been previously assigned.
  5785. //
  5786. // Could avoid the second pass by linking OP_CALL instructions somehow.
  5787. compile_methods(c);
  5788. compile_methods(c);
  5789. g->bytecode_end = c->pc;
  5790. freecompiler(c);
  5791. #ifdef UPB_DUMP_BYTECODE
  5792. FILE *f = fopen("/tmp/upb-bytecode", "wb");
  5793. assert(f);
  5794. dumpbc(g->bytecode, g->bytecode_end, stderr);
  5795. dumpbc(g->bytecode, g->bytecode_end, f);
  5796. fclose(f);
  5797. #endif
  5798. sethandlers(g, allowjit);
  5799. return g;
  5800. }
  5801. /* upb_pbcodecache ************************************************************/
  5802. void upb_pbcodecache_init(upb_pbcodecache *c) {
  5803. upb_inttable_init(&c->groups, UPB_CTYPE_CONSTPTR);
  5804. c->allow_jit_ = true;
  5805. }
  5806. void upb_pbcodecache_uninit(upb_pbcodecache *c) {
  5807. upb_inttable_iter i;
  5808. upb_inttable_begin(&i, &c->groups);
  5809. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5810. const mgroup *group = upb_value_getconstptr(upb_inttable_iter_value(&i));
  5811. upb_refcounted_unref(UPB_UPCAST(group), c);
  5812. }
  5813. upb_inttable_uninit(&c->groups);
  5814. }
  5815. bool upb_pbcodecache_allowjit(const upb_pbcodecache *c) {
  5816. return c->allow_jit_;
  5817. }
  5818. bool upb_pbcodecache_setallowjit(upb_pbcodecache *c, bool allow) {
  5819. if (upb_inttable_count(&c->groups) > 0)
  5820. return false;
  5821. c->allow_jit_ = allow;
  5822. return true;
  5823. }
  5824. const upb_pbdecodermethod *upb_pbcodecache_getdecodermethod(
  5825. upb_pbcodecache *c, const upb_pbdecodermethodopts *opts) {
  5826. // Right now we build a new DecoderMethod every time.
  5827. // TODO(haberman): properly cache methods by their true key.
  5828. const mgroup *g = mgroup_new(opts->handlers, c->allow_jit_, opts->lazy, c);
  5829. upb_inttable_push(&c->groups, upb_value_constptr(g));
  5830. upb_value v;
  5831. bool ok = upb_inttable_lookupptr(&g->methods, opts->handlers, &v);
  5832. UPB_ASSERT_VAR(ok, ok);
  5833. return upb_value_getptr(v);
  5834. }
  5835. /* upb_pbdecodermethodopts ****************************************************/
  5836. void upb_pbdecodermethodopts_init(upb_pbdecodermethodopts *opts,
  5837. const upb_handlers *h) {
  5838. opts->handlers = h;
  5839. opts->lazy = false;
  5840. }
  5841. void upb_pbdecodermethodopts_setlazy(upb_pbdecodermethodopts *opts, bool lazy) {
  5842. opts->lazy = lazy;
  5843. }
  5844. /*
  5845. * upb - a minimalist implementation of protocol buffers.
  5846. *
  5847. * Copyright (c) 2008-2013 Google Inc. See LICENSE for details.
  5848. * Author: Josh Haberman <jhaberman@gmail.com>
  5849. *
  5850. * This file implements a VM for the interpreted (bytecode) decoder.
  5851. *
  5852. * Bytecode must previously have been generated using the bytecode compiler in
  5853. * compile_decoder.c. This decoder then walks through the bytecode op-by-op to
  5854. * parse the input.
  5855. *
  5856. * Decoding is fully resumable; we just keep a pointer to the current bytecode
  5857. * instruction and resume from there. A fair amount of the logic here is to
  5858. * handle the fact that values can span buffer seams and we have to be able to
  5859. * be capable of suspending/resuming from any byte in the stream. This
  5860. * sometimes requires keeping a few trailing bytes from the last buffer around
  5861. * in the "residual" buffer.
  5862. */
  5863. #include <inttypes.h>
  5864. #include <setjmp.h>
  5865. #include <stdarg.h>
  5866. #include <stddef.h>
  5867. #include <stdlib.h>
  5868. #ifdef UPB_DUMP_BYTECODE
  5869. #include <stdio.h>
  5870. #endif
  5871. #define CHECK_SUSPEND(x) if (!(x)) return upb_pbdecoder_suspend(d);
  5872. // Error messages that are shared between the bytecode and JIT decoders.
  5873. const char *kPbDecoderStackOverflow = "Nesting too deep.";
  5874. // Error messages shared within this file.
  5875. static const char *kUnterminatedVarint = "Unterminated varint.";
  5876. /* upb_pbdecoder **************************************************************/
  5877. static opcode halt = OP_HALT;
  5878. // Whether an op consumes any of the input buffer.
  5879. static bool consumes_input(opcode op) {
  5880. switch (op) {
  5881. case OP_SETDISPATCH:
  5882. case OP_STARTMSG:
  5883. case OP_ENDMSG:
  5884. case OP_STARTSEQ:
  5885. case OP_ENDSEQ:
  5886. case OP_STARTSUBMSG:
  5887. case OP_ENDSUBMSG:
  5888. case OP_STARTSTR:
  5889. case OP_ENDSTR:
  5890. case OP_PUSHTAGDELIM:
  5891. case OP_POP:
  5892. case OP_SETDELIM:
  5893. case OP_SETBIGGROUPNUM:
  5894. case OP_CHECKDELIM:
  5895. case OP_CALL:
  5896. case OP_RET:
  5897. case OP_BRANCH:
  5898. return false;
  5899. default:
  5900. return true;
  5901. }
  5902. }
  5903. static bool in_residual_buf(const upb_pbdecoder *d, const char *p);
  5904. // It's unfortunate that we have to micro-manage the compiler this way,
  5905. // especially since this tuning is necessarily specific to one hardware
  5906. // configuration. But emperically on a Core i7, performance increases 30-50%
  5907. // with these annotations. Every instance where these appear, gcc 4.2.1 made
  5908. // the wrong decision and degraded performance in benchmarks.
  5909. #define FORCEINLINE static inline __attribute__((always_inline))
  5910. #define NOINLINE __attribute__((noinline))
  5911. static void seterr(upb_pbdecoder *d, const char *msg) {
  5912. // TODO(haberman): encapsulate this access to pipeline->status, but not sure
  5913. // exactly what that interface should look like.
  5914. upb_status_seterrmsg(d->status, msg);
  5915. }
  5916. void upb_pbdecoder_seterr(upb_pbdecoder *d, const char *msg) {
  5917. seterr(d, msg);
  5918. }
  5919. /* Buffering ******************************************************************/
  5920. // We operate on one buffer at a time, which is either the user's buffer passed
  5921. // to our "decode" callback or some residual bytes from the previous buffer.
  5922. // How many bytes can be safely read from d->ptr without reading past end-of-buf
  5923. // or past the current delimited end.
  5924. static size_t curbufleft(const upb_pbdecoder *d) {
  5925. assert(d->data_end >= d->ptr);
  5926. return d->data_end - d->ptr;
  5927. }
  5928. // Overall stream offset of d->ptr.
  5929. uint64_t offset(const upb_pbdecoder *d) {
  5930. return d->bufstart_ofs + (d->ptr - d->buf);
  5931. }
  5932. // Advances d->ptr.
  5933. static void advance(upb_pbdecoder *d, size_t len) {
  5934. assert(curbufleft(d) >= len);
  5935. d->ptr += len;
  5936. }
  5937. static bool in_buf(const char *p, const char *buf, const char *end) {
  5938. return p >= buf && p <= end;
  5939. }
  5940. static bool in_residual_buf(const upb_pbdecoder *d, const char *p) {
  5941. return in_buf(p, d->residual, d->residual_end);
  5942. }
  5943. // Calculates the delim_end value, which is affected by both the current buffer
  5944. // and the parsing stack, so must be called whenever either is updated.
  5945. static void set_delim_end(upb_pbdecoder *d) {
  5946. size_t delim_ofs = d->top->end_ofs - d->bufstart_ofs;
  5947. if (delim_ofs <= (d->end - d->buf)) {
  5948. d->delim_end = d->buf + delim_ofs;
  5949. d->data_end = d->delim_end;
  5950. } else {
  5951. d->data_end = d->end;
  5952. d->delim_end = NULL;
  5953. }
  5954. }
  5955. static void switchtobuf(upb_pbdecoder *d, const char *buf, const char *end) {
  5956. d->ptr = buf;
  5957. d->buf = buf;
  5958. d->end = end;
  5959. set_delim_end(d);
  5960. }
  5961. static void advancetobuf(upb_pbdecoder *d, const char *buf, size_t len) {
  5962. assert(curbufleft(d) == 0);
  5963. d->bufstart_ofs += (d->end - d->buf);
  5964. switchtobuf(d, buf, buf + len);
  5965. }
  5966. static void checkpoint(upb_pbdecoder *d) {
  5967. // The assertion here is in the interests of efficiency, not correctness.
  5968. // We are trying to ensure that we don't checkpoint() more often than
  5969. // necessary.
  5970. assert(d->checkpoint != d->ptr);
  5971. d->checkpoint = d->ptr;
  5972. }
  5973. // Resumes the decoder from an initial state or from a previous suspend.
  5974. int32_t upb_pbdecoder_resume(upb_pbdecoder *d, void *p, const char *buf,
  5975. size_t size, const upb_bufhandle *handle) {
  5976. UPB_UNUSED(p); // Useless; just for the benefit of the JIT.
  5977. d->buf_param = buf;
  5978. d->size_param = size;
  5979. d->handle = handle;
  5980. if (d->residual_end > d->residual) {
  5981. // We have residual bytes from the last buffer.
  5982. assert(d->ptr == d->residual);
  5983. } else {
  5984. switchtobuf(d, buf, buf + size);
  5985. }
  5986. d->checkpoint = d->ptr;
  5987. if (d->top->groupnum < 0) {
  5988. CHECK_RETURN(upb_pbdecoder_skipunknown(d, -1, 0));
  5989. d->checkpoint = d->ptr;
  5990. }
  5991. return DECODE_OK;
  5992. }
  5993. // Suspends the decoder at the last checkpoint, without saving any residual
  5994. // bytes. If there are any unconsumed bytes, returns a short byte count.
  5995. size_t upb_pbdecoder_suspend(upb_pbdecoder *d) {
  5996. d->pc = d->last;
  5997. if (d->checkpoint == d->residual) {
  5998. // Checkpoint was in residual buf; no user bytes were consumed.
  5999. d->ptr = d->residual;
  6000. return 0;
  6001. } else {
  6002. assert(!in_residual_buf(d, d->checkpoint));
  6003. assert(d->buf == d->buf_param);
  6004. size_t consumed = d->checkpoint - d->buf;
  6005. d->bufstart_ofs += consumed;
  6006. d->residual_end = d->residual;
  6007. switchtobuf(d, d->residual, d->residual_end);
  6008. return consumed;
  6009. }
  6010. }
  6011. // Suspends the decoder at the last checkpoint, and saves any unconsumed
  6012. // bytes in our residual buffer. This is necessary if we need more user
  6013. // bytes to form a complete value, which might not be contiguous in the
  6014. // user's buffers. Always consumes all user bytes.
  6015. static size_t suspend_save(upb_pbdecoder *d) {
  6016. // We hit end-of-buffer before we could parse a full value.
  6017. // Save any unconsumed bytes (if any) to the residual buffer.
  6018. d->pc = d->last;
  6019. if (d->checkpoint == d->residual) {
  6020. // Checkpoint was in residual buf; append user byte(s) to residual buf.
  6021. assert((d->residual_end - d->residual) + d->size_param <=
  6022. sizeof(d->residual));
  6023. if (!in_residual_buf(d, d->ptr)) {
  6024. d->bufstart_ofs -= (d->residual_end - d->residual);
  6025. }
  6026. memcpy(d->residual_end, d->buf_param, d->size_param);
  6027. d->residual_end += d->size_param;
  6028. } else {
  6029. // Checkpoint was in user buf; old residual bytes not needed.
  6030. assert(!in_residual_buf(d, d->checkpoint));
  6031. d->ptr = d->checkpoint;
  6032. size_t save = curbufleft(d);
  6033. assert(save <= sizeof(d->residual));
  6034. memcpy(d->residual, d->ptr, save);
  6035. d->residual_end = d->residual + save;
  6036. d->bufstart_ofs = offset(d);
  6037. }
  6038. switchtobuf(d, d->residual, d->residual_end);
  6039. return d->size_param;
  6040. }
  6041. // Skips "bytes" bytes in the stream, which may be more than available. If we
  6042. // skip more bytes than are available, we return a long read count to the caller
  6043. // indicating how many bytes the caller should skip before passing a new buffer.
  6044. static int32_t skip(upb_pbdecoder *d, size_t bytes) {
  6045. assert(!in_residual_buf(d, d->ptr) || d->size_param == 0);
  6046. if (curbufleft(d) >= bytes) {
  6047. // Skipped data is all in current buffer.
  6048. advance(d, bytes);
  6049. return DECODE_OK;
  6050. } else {
  6051. // Skipped data extends beyond currently available buffers.
  6052. d->pc = d->last;
  6053. size_t skip = bytes - curbufleft(d);
  6054. d->bufstart_ofs += (d->end - d->buf) + skip;
  6055. d->residual_end = d->residual;
  6056. switchtobuf(d, d->residual, d->residual_end);
  6057. return d->size_param + skip;
  6058. }
  6059. }
  6060. // Copies the next "bytes" bytes into "buf" and advances the stream.
  6061. // Requires that this many bytes are available in the current buffer.
  6062. FORCEINLINE void consumebytes(upb_pbdecoder *d, void *buf, size_t bytes) {
  6063. assert(bytes <= curbufleft(d));
  6064. memcpy(buf, d->ptr, bytes);
  6065. advance(d, bytes);
  6066. }
  6067. // Slow path for getting the next "bytes" bytes, regardless of whether they are
  6068. // available in the current buffer or not. Returns a status code as described
  6069. // in decoder.int.h.
  6070. static NOINLINE int32_t getbytes_slow(upb_pbdecoder *d, void *buf,
  6071. size_t bytes) {
  6072. const size_t avail = curbufleft(d);
  6073. consumebytes(d, buf, avail);
  6074. bytes -= avail;
  6075. assert(bytes > 0);
  6076. if (in_residual_buf(d, d->ptr)) {
  6077. advancetobuf(d, d->buf_param, d->size_param);
  6078. }
  6079. if (curbufleft(d) >= bytes) {
  6080. consumebytes(d, buf + avail, bytes);
  6081. return DECODE_OK;
  6082. } else if (d->data_end == d->delim_end) {
  6083. seterr(d, "Submessage ended in the middle of a value or group");
  6084. return upb_pbdecoder_suspend(d);
  6085. } else {
  6086. return suspend_save(d);
  6087. }
  6088. }
  6089. // Gets the next "bytes" bytes, regardless of whether they are available in the
  6090. // current buffer or not. Returns a status code as described in decoder.int.h.
  6091. FORCEINLINE int32_t getbytes(upb_pbdecoder *d, void *buf, size_t bytes) {
  6092. if (curbufleft(d) >= bytes) {
  6093. // Buffer has enough data to satisfy.
  6094. consumebytes(d, buf, bytes);
  6095. return DECODE_OK;
  6096. } else {
  6097. return getbytes_slow(d, buf, bytes);
  6098. }
  6099. }
  6100. static NOINLINE size_t peekbytes_slow(upb_pbdecoder *d, void *buf,
  6101. size_t bytes) {
  6102. size_t ret = curbufleft(d);
  6103. memcpy(buf, d->ptr, ret);
  6104. if (in_residual_buf(d, d->ptr)) {
  6105. size_t copy = UPB_MIN(bytes - ret, d->size_param);
  6106. memcpy(buf + ret, d->buf_param, copy);
  6107. ret += copy;
  6108. }
  6109. return ret;
  6110. }
  6111. FORCEINLINE size_t peekbytes(upb_pbdecoder *d, void *buf, size_t bytes) {
  6112. if (curbufleft(d) >= bytes) {
  6113. memcpy(buf, d->ptr, bytes);
  6114. return bytes;
  6115. } else {
  6116. return peekbytes_slow(d, buf, bytes);
  6117. }
  6118. }
  6119. /* Decoding of wire types *****************************************************/
  6120. // Slow path for decoding a varint from the current buffer position.
  6121. // Returns a status code as described in decoder.int.h.
  6122. NOINLINE int32_t upb_pbdecoder_decode_varint_slow(upb_pbdecoder *d,
  6123. uint64_t *u64) {
  6124. *u64 = 0;
  6125. uint8_t byte = 0x80;
  6126. int bitpos;
  6127. for(bitpos = 0; bitpos < 70 && (byte & 0x80); bitpos += 7) {
  6128. int32_t ret = getbytes(d, &byte, 1);
  6129. if (ret >= 0) return ret;
  6130. *u64 |= (uint64_t)(byte & 0x7F) << bitpos;
  6131. }
  6132. if(bitpos == 70 && (byte & 0x80)) {
  6133. seterr(d, kUnterminatedVarint);
  6134. return upb_pbdecoder_suspend(d);
  6135. }
  6136. return DECODE_OK;
  6137. }
  6138. // Decodes a varint from the current buffer position.
  6139. // Returns a status code as described in decoder.int.h.
  6140. FORCEINLINE int32_t decode_varint(upb_pbdecoder *d, uint64_t *u64) {
  6141. if (curbufleft(d) > 0 && !(*d->ptr & 0x80)) {
  6142. *u64 = *d->ptr;
  6143. advance(d, 1);
  6144. return DECODE_OK;
  6145. } else if (curbufleft(d) >= 10) {
  6146. // Fast case.
  6147. upb_decoderet r = upb_vdecode_fast(d->ptr);
  6148. if (r.p == NULL) {
  6149. seterr(d, kUnterminatedVarint);
  6150. return upb_pbdecoder_suspend(d);
  6151. }
  6152. advance(d, r.p - d->ptr);
  6153. *u64 = r.val;
  6154. return DECODE_OK;
  6155. } else {
  6156. // Slow case -- varint spans buffer seam.
  6157. return upb_pbdecoder_decode_varint_slow(d, u64);
  6158. }
  6159. }
  6160. // Decodes a 32-bit varint from the current buffer position.
  6161. // Returns a status code as described in decoder.int.h.
  6162. FORCEINLINE int32_t decode_v32(upb_pbdecoder *d, uint32_t *u32) {
  6163. uint64_t u64;
  6164. int32_t ret = decode_varint(d, &u64);
  6165. if (ret >= 0) return ret;
  6166. if (u64 > UINT32_MAX) {
  6167. seterr(d, "Unterminated 32-bit varint");
  6168. // TODO(haberman) guarantee that this function return is >= 0 somehow,
  6169. // so we know this path will always be treated as error by our caller.
  6170. // Right now the size_t -> int32_t can overflow and produce negative values.
  6171. *u32 = 0;
  6172. return upb_pbdecoder_suspend(d);
  6173. }
  6174. *u32 = u64;
  6175. return DECODE_OK;
  6176. }
  6177. // Decodes a fixed32 from the current buffer position.
  6178. // Returns a status code as described in decoder.int.h.
  6179. // TODO: proper byte swapping for big-endian machines.
  6180. FORCEINLINE int32_t decode_fixed32(upb_pbdecoder *d, uint32_t *u32) {
  6181. return getbytes(d, u32, 4);
  6182. }
  6183. // Decodes a fixed64 from the current buffer position.
  6184. // Returns a status code as described in decoder.int.h.
  6185. // TODO: proper byte swapping for big-endian machines.
  6186. FORCEINLINE int32_t decode_fixed64(upb_pbdecoder *d, uint64_t *u64) {
  6187. return getbytes(d, u64, 8);
  6188. }
  6189. // Non-static versions of the above functions.
  6190. // These are called by the JIT for fallback paths.
  6191. int32_t upb_pbdecoder_decode_f32(upb_pbdecoder *d, uint32_t *u32) {
  6192. return decode_fixed32(d, u32);
  6193. }
  6194. int32_t upb_pbdecoder_decode_f64(upb_pbdecoder *d, uint64_t *u64) {
  6195. return decode_fixed64(d, u64);
  6196. }
  6197. static double as_double(uint64_t n) { double d; memcpy(&d, &n, 8); return d; }
  6198. static float as_float(uint32_t n) { float f; memcpy(&f, &n, 4); return f; }
  6199. // Pushes a frame onto the decoder stack.
  6200. static bool decoder_push(upb_pbdecoder *d, uint64_t end) {
  6201. upb_pbdecoder_frame *fr = d->top;
  6202. if (end > fr->end_ofs) {
  6203. seterr(d, "Submessage end extends past enclosing submessage.");
  6204. return false;
  6205. } else if ((fr + 1) == d->limit) {
  6206. seterr(d, kPbDecoderStackOverflow);
  6207. return false;
  6208. }
  6209. fr++;
  6210. fr->end_ofs = end;
  6211. fr->dispatch = NULL;
  6212. fr->groupnum = 0;
  6213. d->top = fr;
  6214. return true;
  6215. }
  6216. static bool pushtagdelim(upb_pbdecoder *d, uint32_t arg) {
  6217. // While we expect to see an "end" tag (either ENDGROUP or a non-sequence
  6218. // field number) prior to hitting any enclosing submessage end, pushing our
  6219. // existing delim end prevents us from continuing to parse values from a
  6220. // corrupt proto that doesn't give us an END tag in time.
  6221. if (!decoder_push(d, d->top->end_ofs))
  6222. return false;
  6223. d->top->groupnum = arg;
  6224. return true;
  6225. }
  6226. // Pops a frame from the decoder stack.
  6227. static void decoder_pop(upb_pbdecoder *d) { d->top--; }
  6228. NOINLINE int32_t upb_pbdecoder_checktag_slow(upb_pbdecoder *d,
  6229. uint64_t expected) {
  6230. uint64_t data = 0;
  6231. size_t bytes = upb_value_size(expected);
  6232. size_t read = peekbytes(d, &data, bytes);
  6233. if (read == bytes && data == expected) {
  6234. // Advance past matched bytes.
  6235. int32_t ok = getbytes(d, &data, read);
  6236. UPB_ASSERT_VAR(ok, ok < 0);
  6237. return DECODE_OK;
  6238. } else if (read < bytes && memcmp(&data, &expected, read) == 0) {
  6239. return suspend_save(d);
  6240. } else {
  6241. return DECODE_MISMATCH;
  6242. }
  6243. }
  6244. int32_t upb_pbdecoder_skipunknown(upb_pbdecoder *d, int32_t fieldnum,
  6245. uint8_t wire_type) {
  6246. if (fieldnum >= 0)
  6247. goto have_tag;
  6248. while (true) {
  6249. uint32_t tag;
  6250. CHECK_RETURN(decode_v32(d, &tag));
  6251. wire_type = tag & 0x7;
  6252. fieldnum = tag >> 3;
  6253. have_tag:
  6254. if (fieldnum == 0) {
  6255. seterr(d, "Saw invalid field number (0)");
  6256. return upb_pbdecoder_suspend(d);
  6257. }
  6258. // TODO: deliver to unknown field callback.
  6259. switch (wire_type) {
  6260. case UPB_WIRE_TYPE_32BIT:
  6261. CHECK_RETURN(skip(d, 4));
  6262. break;
  6263. case UPB_WIRE_TYPE_64BIT:
  6264. CHECK_RETURN(skip(d, 8));
  6265. break;
  6266. case UPB_WIRE_TYPE_VARINT: {
  6267. uint64_t u64;
  6268. CHECK_RETURN(decode_varint(d, &u64));
  6269. break;
  6270. }
  6271. case UPB_WIRE_TYPE_DELIMITED: {
  6272. uint32_t len;
  6273. CHECK_RETURN(decode_v32(d, &len));
  6274. CHECK_RETURN(skip(d, len));
  6275. break;
  6276. }
  6277. case UPB_WIRE_TYPE_START_GROUP:
  6278. CHECK_SUSPEND(pushtagdelim(d, -fieldnum));
  6279. break;
  6280. case UPB_WIRE_TYPE_END_GROUP:
  6281. if (fieldnum == -d->top->groupnum) {
  6282. decoder_pop(d);
  6283. } else if (fieldnum == d->top->groupnum) {
  6284. return DECODE_ENDGROUP;
  6285. } else {
  6286. seterr(d, "Unmatched ENDGROUP tag.");
  6287. return upb_pbdecoder_suspend(d);
  6288. }
  6289. break;
  6290. default:
  6291. seterr(d, "Invalid wire type");
  6292. return upb_pbdecoder_suspend(d);
  6293. }
  6294. if (d->top->groupnum >= 0) {
  6295. return DECODE_OK;
  6296. }
  6297. if (d->ptr == d->delim_end) {
  6298. seterr(d, "Enclosing submessage ended in the middle of value or group");
  6299. // Unlike most errors we notice during parsing, right now we have consumed
  6300. // all of the user's input.
  6301. //
  6302. // There are three different options for how to handle this case:
  6303. //
  6304. // 1. decode() = short count, error = set
  6305. // 2. decode() = full count, error = set
  6306. // 3. decode() = full count, error NOT set, short count and error will
  6307. // be reported on next call to decode() (or end())
  6308. //
  6309. // (1) and (3) have the advantage that they preserve the invariant that an
  6310. // error occurs iff decode() returns a short count.
  6311. //
  6312. // (2) and (3) have the advantage of reflecting the fact that all of the
  6313. // bytes were in fact parsed (and possibly delivered to the unknown field
  6314. // handler, in the future when that is supported).
  6315. //
  6316. // (3) requires extra state in the decode (a place to store the "permanent
  6317. // error" that we should return for all subsequent attempts to decode).
  6318. // But we likely want this anyway.
  6319. //
  6320. // Right now we do (1), thanks to the fact that we checkpoint *after* this
  6321. // check. (3) may be a better choice long term; unclear at the moment.
  6322. return upb_pbdecoder_suspend(d);
  6323. }
  6324. checkpoint(d);
  6325. }
  6326. }
  6327. static void goto_endmsg(upb_pbdecoder *d) {
  6328. upb_value v;
  6329. bool found = upb_inttable_lookup32(d->top->dispatch, DISPATCH_ENDMSG, &v);
  6330. UPB_ASSERT_VAR(found, found);
  6331. d->pc = d->top->base + upb_value_getuint64(v);
  6332. }
  6333. // Parses a tag and jumps to the corresponding bytecode instruction for this
  6334. // field.
  6335. //
  6336. // If the tag is unknown (or the wire type doesn't match), parses the field as
  6337. // unknown. If the tag is a valid ENDGROUP tag, jumps to the bytecode
  6338. // instruction for the end of message.
  6339. static int32_t dispatch(upb_pbdecoder *d) {
  6340. upb_inttable *dispatch = d->top->dispatch;
  6341. // Decode tag.
  6342. uint32_t tag;
  6343. CHECK_RETURN(decode_v32(d, &tag));
  6344. uint8_t wire_type = tag & 0x7;
  6345. uint32_t fieldnum = tag >> 3;
  6346. // Lookup tag. Because of packed/non-packed compatibility, we have to
  6347. // check the wire type against two possibilities.
  6348. upb_value val;
  6349. if (fieldnum != DISPATCH_ENDMSG &&
  6350. upb_inttable_lookup32(dispatch, fieldnum, &val)) {
  6351. uint64_t v = upb_value_getuint64(val);
  6352. if (wire_type == (v & 0xff)) {
  6353. d->pc = d->top->base + (v >> 16);
  6354. return DECODE_OK;
  6355. } else if (wire_type == ((v >> 8) & 0xff)) {
  6356. bool found =
  6357. upb_inttable_lookup(dispatch, fieldnum + UPB_MAX_FIELDNUMBER, &val);
  6358. UPB_ASSERT_VAR(found, found);
  6359. d->pc = d->top->base + upb_value_getuint64(val);
  6360. return DECODE_OK;
  6361. }
  6362. }
  6363. // Unknown field or ENDGROUP.
  6364. int32_t ret = upb_pbdecoder_skipunknown(d, fieldnum, wire_type);
  6365. if (ret == DECODE_ENDGROUP) {
  6366. goto_endmsg(d);
  6367. return DECODE_OK;
  6368. } else {
  6369. d->pc = d->last - 1; // Rewind to CHECKDELIM.
  6370. return ret;
  6371. }
  6372. }
  6373. // Callers know that the stack is more than one deep because the opcodes that
  6374. // call this only occur after PUSH operations.
  6375. upb_pbdecoder_frame *outer_frame(upb_pbdecoder *d) {
  6376. assert(d->top != d->stack);
  6377. return d->top - 1;
  6378. }
  6379. /* The main decoding loop *****************************************************/
  6380. // The main decoder VM function. Uses traditional bytecode dispatch loop with a
  6381. // switch() statement.
  6382. size_t upb_pbdecoder_decode(void *closure, const void *hd, const char *buf,
  6383. size_t size, const upb_bufhandle *handle) {
  6384. upb_pbdecoder *d = closure;
  6385. const mgroup *group = hd;
  6386. assert(buf);
  6387. int32_t result = upb_pbdecoder_resume(d, NULL, buf, size, handle);
  6388. if (result == DECODE_ENDGROUP) {
  6389. goto_endmsg(d);
  6390. }
  6391. CHECK_RETURN(result);
  6392. UPB_UNUSED(group);
  6393. #define VMCASE(op, code) \
  6394. case op: { code; if (consumes_input(op)) checkpoint(d); break; }
  6395. #define PRIMITIVE_OP(type, wt, name, convfunc, ctype) \
  6396. VMCASE(OP_PARSE_ ## type, { \
  6397. ctype val; \
  6398. CHECK_RETURN(decode_ ## wt(d, &val)); \
  6399. upb_sink_put ## name(&d->top->sink, arg, (convfunc)(val)); \
  6400. })
  6401. while(1) {
  6402. d->last = d->pc;
  6403. int32_t instruction = *d->pc++;
  6404. opcode op = getop(instruction);
  6405. uint32_t arg = instruction >> 8;
  6406. int32_t longofs = arg;
  6407. assert(d->ptr != d->residual_end);
  6408. #ifdef UPB_DUMP_BYTECODE
  6409. fprintf(stderr, "s_ofs=%d buf_ofs=%d data_rem=%d buf_rem=%d delim_rem=%d "
  6410. "%x %s (%d)\n",
  6411. (int)offset(d),
  6412. (int)(d->ptr - d->buf),
  6413. (int)(d->data_end - d->ptr),
  6414. (int)(d->end - d->ptr),
  6415. (int)((d->top->end_ofs - d->bufstart_ofs) - (d->ptr - d->buf)),
  6416. (int)(d->pc - 1 - group->bytecode),
  6417. upb_pbdecoder_getopname(op),
  6418. arg);
  6419. #endif
  6420. switch (op) {
  6421. // Technically, we are losing data if we see a 32-bit varint that is not
  6422. // properly sign-extended. We could detect this and error about the data
  6423. // loss, but proto2 does not do this, so we pass.
  6424. PRIMITIVE_OP(INT32, varint, int32, int32_t, uint64_t)
  6425. PRIMITIVE_OP(INT64, varint, int64, int64_t, uint64_t)
  6426. PRIMITIVE_OP(UINT32, varint, uint32, uint32_t, uint64_t)
  6427. PRIMITIVE_OP(UINT64, varint, uint64, uint64_t, uint64_t)
  6428. PRIMITIVE_OP(FIXED32, fixed32, uint32, uint32_t, uint32_t)
  6429. PRIMITIVE_OP(FIXED64, fixed64, uint64, uint64_t, uint64_t)
  6430. PRIMITIVE_OP(SFIXED32, fixed32, int32, int32_t, uint32_t)
  6431. PRIMITIVE_OP(SFIXED64, fixed64, int64, int64_t, uint64_t)
  6432. PRIMITIVE_OP(BOOL, varint, bool, bool, uint64_t)
  6433. PRIMITIVE_OP(DOUBLE, fixed64, double, as_double, uint64_t)
  6434. PRIMITIVE_OP(FLOAT, fixed32, float, as_float, uint32_t)
  6435. PRIMITIVE_OP(SINT32, varint, int32, upb_zzdec_32, uint64_t)
  6436. PRIMITIVE_OP(SINT64, varint, int64, upb_zzdec_64, uint64_t)
  6437. VMCASE(OP_SETDISPATCH,
  6438. d->top->base = d->pc - 1;
  6439. memcpy(&d->top->dispatch, d->pc, sizeof(void*));
  6440. d->pc += sizeof(void*) / sizeof(uint32_t);
  6441. )
  6442. VMCASE(OP_STARTMSG,
  6443. CHECK_SUSPEND(upb_sink_startmsg(&d->top->sink));
  6444. )
  6445. VMCASE(OP_ENDMSG,
  6446. CHECK_SUSPEND(upb_sink_endmsg(&d->top->sink, d->status));
  6447. )
  6448. VMCASE(OP_STARTSEQ,
  6449. upb_pbdecoder_frame *outer = outer_frame(d);
  6450. CHECK_SUSPEND(upb_sink_startseq(&outer->sink, arg, &d->top->sink));
  6451. )
  6452. VMCASE(OP_ENDSEQ,
  6453. CHECK_SUSPEND(upb_sink_endseq(&d->top->sink, arg));
  6454. )
  6455. VMCASE(OP_STARTSUBMSG,
  6456. upb_pbdecoder_frame *outer = outer_frame(d);
  6457. CHECK_SUSPEND(upb_sink_startsubmsg(&outer->sink, arg, &d->top->sink));
  6458. )
  6459. VMCASE(OP_ENDSUBMSG,
  6460. CHECK_SUSPEND(upb_sink_endsubmsg(&d->top->sink, arg));
  6461. )
  6462. VMCASE(OP_STARTSTR,
  6463. uint32_t len = d->top->end_ofs - offset(d);
  6464. upb_pbdecoder_frame *outer = outer_frame(d);
  6465. CHECK_SUSPEND(upb_sink_startstr(&outer->sink, arg, len, &d->top->sink));
  6466. if (len == 0) {
  6467. d->pc++; // Skip OP_STRING.
  6468. }
  6469. )
  6470. VMCASE(OP_STRING,
  6471. uint32_t len = curbufleft(d);
  6472. size_t n = upb_sink_putstring(&d->top->sink, arg, d->ptr, len, handle);
  6473. if (n > len) {
  6474. if (n > d->top->end_ofs - offset(d)) {
  6475. seterr(d, "Tried to skip past end of string.");
  6476. return upb_pbdecoder_suspend(d);
  6477. } else {
  6478. int32_t ret = skip(d, n);
  6479. // This shouldn't return DECODE_OK, because n > len.
  6480. assert(ret >= 0);
  6481. return ret;
  6482. }
  6483. }
  6484. advance(d, n);
  6485. if (n < len || d->delim_end == NULL) {
  6486. // We aren't finished with this string yet.
  6487. d->pc--; // Repeat OP_STRING.
  6488. if (n > 0) checkpoint(d);
  6489. return upb_pbdecoder_suspend(d);
  6490. }
  6491. )
  6492. VMCASE(OP_ENDSTR,
  6493. CHECK_SUSPEND(upb_sink_endstr(&d->top->sink, arg));
  6494. )
  6495. VMCASE(OP_PUSHTAGDELIM,
  6496. CHECK_SUSPEND(pushtagdelim(d, arg));
  6497. )
  6498. VMCASE(OP_SETBIGGROUPNUM,
  6499. d->top->groupnum = *d->pc++;
  6500. )
  6501. VMCASE(OP_POP,
  6502. assert(d->top > d->stack);
  6503. decoder_pop(d);
  6504. )
  6505. VMCASE(OP_PUSHLENDELIM,
  6506. uint32_t len;
  6507. CHECK_RETURN(decode_v32(d, &len));
  6508. CHECK_SUSPEND(decoder_push(d, offset(d) + len));
  6509. set_delim_end(d);
  6510. )
  6511. VMCASE(OP_SETDELIM,
  6512. set_delim_end(d);
  6513. )
  6514. VMCASE(OP_CHECKDELIM,
  6515. // We are guaranteed of this assert because we never allow ourselves to
  6516. // consume bytes beyond data_end, which covers delim_end when non-NULL.
  6517. assert(!(d->delim_end && d->ptr > d->delim_end));
  6518. if (d->ptr == d->delim_end)
  6519. d->pc += longofs;
  6520. )
  6521. VMCASE(OP_CALL,
  6522. d->callstack[d->call_len++] = d->pc;
  6523. d->pc += longofs;
  6524. )
  6525. VMCASE(OP_RET,
  6526. assert(d->call_len > 0);
  6527. d->pc = d->callstack[--d->call_len];
  6528. )
  6529. VMCASE(OP_BRANCH,
  6530. d->pc += longofs;
  6531. )
  6532. VMCASE(OP_TAG1,
  6533. CHECK_SUSPEND(curbufleft(d) > 0);
  6534. uint8_t expected = (arg >> 8) & 0xff;
  6535. if (*d->ptr == expected) {
  6536. advance(d, 1);
  6537. } else {
  6538. int8_t shortofs;
  6539. badtag:
  6540. shortofs = arg;
  6541. if (shortofs == LABEL_DISPATCH) {
  6542. CHECK_RETURN(dispatch(d));
  6543. } else {
  6544. d->pc += shortofs;
  6545. break; // Avoid checkpoint().
  6546. }
  6547. }
  6548. )
  6549. VMCASE(OP_TAG2,
  6550. CHECK_SUSPEND(curbufleft(d) > 0);
  6551. uint16_t expected = (arg >> 8) & 0xffff;
  6552. if (curbufleft(d) >= 2) {
  6553. uint16_t actual;
  6554. memcpy(&actual, d->ptr, 2);
  6555. if (expected == actual) {
  6556. advance(d, 2);
  6557. } else {
  6558. goto badtag;
  6559. }
  6560. } else {
  6561. int32_t result = upb_pbdecoder_checktag_slow(d, expected);
  6562. if (result == DECODE_MISMATCH) goto badtag;
  6563. if (result >= 0) return result;
  6564. }
  6565. )
  6566. VMCASE(OP_TAGN, {
  6567. uint64_t expected;
  6568. memcpy(&expected, d->pc, 8);
  6569. d->pc += 2;
  6570. int32_t result = upb_pbdecoder_checktag_slow(d, expected);
  6571. if (result == DECODE_MISMATCH) goto badtag;
  6572. if (result >= 0) return result;
  6573. })
  6574. VMCASE(OP_HALT, {
  6575. return size;
  6576. })
  6577. }
  6578. }
  6579. }
  6580. void *upb_pbdecoder_startbc(void *closure, const void *pc, size_t size_hint) {
  6581. upb_pbdecoder *d = closure;
  6582. UPB_UNUSED(size_hint);
  6583. d->call_len = 1;
  6584. d->pc = pc;
  6585. return d;
  6586. }
  6587. void *upb_pbdecoder_startjit(void *closure, const void *hd, size_t size_hint) {
  6588. UPB_UNUSED(hd);
  6589. UPB_UNUSED(size_hint);
  6590. upb_pbdecoder *d = closure;
  6591. d->call_len = 0;
  6592. return d;
  6593. }
  6594. bool upb_pbdecoder_end(void *closure, const void *handler_data) {
  6595. upb_pbdecoder *d = closure;
  6596. const upb_pbdecodermethod *method = handler_data;
  6597. if (d->residual_end > d->residual) {
  6598. seterr(d, "Unexpected EOF");
  6599. return false;
  6600. }
  6601. if (d->top->end_ofs != UINT64_MAX) {
  6602. seterr(d, "Unexpected EOF inside delimited string");
  6603. return false;
  6604. }
  6605. // Message ends here.
  6606. uint64_t end = offset(d);
  6607. d->top->end_ofs = end;
  6608. char dummy;
  6609. #ifdef UPB_USE_JIT_X64
  6610. const mgroup *group = (const mgroup*)method->group;
  6611. if (group->jit_code) {
  6612. if (d->top != d->stack)
  6613. d->stack->end_ofs = 0;
  6614. group->jit_code(closure, method->code_base.ptr, &dummy, 0, NULL);
  6615. } else {
  6616. #endif
  6617. d->stack->end_ofs = end;
  6618. const uint32_t *p = d->pc;
  6619. // Check the previous bytecode, but guard against beginning.
  6620. if (p != method->code_base.ptr) p--;
  6621. if (getop(*p) == OP_CHECKDELIM) {
  6622. // Rewind from OP_TAG* to OP_CHECKDELIM.
  6623. assert(getop(*d->pc) == OP_TAG1 ||
  6624. getop(*d->pc) == OP_TAG2 ||
  6625. getop(*d->pc) == OP_TAGN);
  6626. d->pc = p;
  6627. }
  6628. upb_pbdecoder_decode(closure, handler_data, &dummy, 0, NULL);
  6629. #ifdef UPB_USE_JIT_X64
  6630. }
  6631. #endif
  6632. if (d->call_len != 0) {
  6633. seterr(d, "Unexpected EOF");
  6634. return false;
  6635. }
  6636. return true;
  6637. }
  6638. void upb_pbdecoder_init(upb_pbdecoder *d, const upb_pbdecodermethod *m,
  6639. upb_status *s) {
  6640. d->limit = &d->stack[UPB_DECODER_MAX_NESTING];
  6641. upb_bytessink_reset(&d->input_, &m->input_handler_, d);
  6642. d->method_ = m;
  6643. d->callstack[0] = &halt;
  6644. d->status = s;
  6645. upb_pbdecoder_reset(d);
  6646. }
  6647. void upb_pbdecoder_reset(upb_pbdecoder *d) {
  6648. d->top = d->stack;
  6649. d->top->end_ofs = UINT64_MAX;
  6650. d->top->groupnum = 0;
  6651. d->bufstart_ofs = 0;
  6652. d->ptr = d->residual;
  6653. d->buf = d->residual;
  6654. d->end = d->residual;
  6655. d->residual_end = d->residual;
  6656. d->call_len = 1;
  6657. }
  6658. uint64_t upb_pbdecoder_bytesparsed(const upb_pbdecoder *d) {
  6659. return offset(d);
  6660. }
  6661. // Not currently required, but to support outgrowing the static stack we need
  6662. // this.
  6663. void upb_pbdecoder_uninit(upb_pbdecoder *d) {
  6664. UPB_UNUSED(d);
  6665. }
  6666. const upb_pbdecodermethod *upb_pbdecoder_method(const upb_pbdecoder *d) {
  6667. return d->method_;
  6668. }
  6669. bool upb_pbdecoder_resetoutput(upb_pbdecoder *d, upb_sink* sink) {
  6670. // TODO(haberman): do we need to test whether the decoder is already on the
  6671. // stack (like calling this from within a callback)? Should we support
  6672. // rebinding the output at all?
  6673. assert(sink);
  6674. if (d->method_->dest_handlers_) {
  6675. if (sink->handlers != d->method_->dest_handlers_)
  6676. return false;
  6677. }
  6678. upb_sink_reset(&d->top->sink, sink->handlers, sink->closure);
  6679. return true;
  6680. }
  6681. upb_bytessink *upb_pbdecoder_input(upb_pbdecoder *d) {
  6682. return &d->input_;
  6683. }
  6684. /*
  6685. * upb - a minimalist implementation of protocol buffers.
  6686. *
  6687. * Copyright (c) 2014 Google Inc. See LICENSE for details.
  6688. * Author: Josh Haberman <jhaberman@gmail.com>
  6689. *
  6690. * Since we are implementing pure handlers (ie. without any out-of-band access
  6691. * to pre-computed lengths), we have to buffer all submessages before we can
  6692. * emit even their first byte.
  6693. *
  6694. * Not knowing the size of submessages also means we can't write a perfect
  6695. * zero-copy implementation, even with buffering. Lengths are stored as
  6696. * varints, which means that we don't know how many bytes to reserve for the
  6697. * length until we know what the length is.
  6698. *
  6699. * This leaves us with three main choices:
  6700. *
  6701. * 1. buffer all submessage data in a temporary buffer, then copy it exactly
  6702. * once into the output buffer.
  6703. *
  6704. * 2. attempt to buffer data directly into the output buffer, estimating how
  6705. * many bytes each length will take. When our guesses are wrong, use
  6706. * memmove() to grow or shrink the allotted space.
  6707. *
  6708. * 3. buffer directly into the output buffer, allocating a max length
  6709. * ahead-of-time for each submessage length. If we overallocated, we waste
  6710. * space, but no memcpy() or memmove() is required. This approach requires
  6711. * defining a maximum size for submessages and rejecting submessages that
  6712. * exceed that size.
  6713. *
  6714. * (2) and (3) have the potential to have better performance, but they are more
  6715. * complicated and subtle to implement:
  6716. *
  6717. * (3) requires making an arbitrary choice of the maximum message size; it
  6718. * wastes space when submessages are shorter than this and fails
  6719. * completely when they are longer. This makes it more finicky and
  6720. * requires configuration based on the input. It also makes it impossible
  6721. * to perfectly match the output of reference encoders that always use the
  6722. * optimal amount of space for each length.
  6723. *
  6724. * (2) requires guessing the the size upfront, and if multiple lengths are
  6725. * guessed wrong the minimum required number of memmove() operations may
  6726. * be complicated to compute correctly. Implemented properly, it may have
  6727. * a useful amortized or average cost, but more investigation is required
  6728. * to determine this and what the optimal algorithm is to achieve it.
  6729. *
  6730. * (1) makes you always pay for exactly one copy, but its implementation is
  6731. * the simplest and its performance is predictable.
  6732. *
  6733. * So for now, we implement (1) only. If we wish to optimize later, we should
  6734. * be able to do it without affecting users.
  6735. *
  6736. * The strategy is to buffer the segments of data that do *not* depend on
  6737. * unknown lengths in one buffer, and keep a separate buffer of segment pointers
  6738. * and lengths. When the top-level submessage ends, we can go beginning to end,
  6739. * alternating the writing of lengths with memcpy() of the rest of the data.
  6740. * At the top level though, no buffering is required.
  6741. */
  6742. #include <stdlib.h>
  6743. /* low-level buffering ********************************************************/
  6744. // Low-level functions for interacting with the output buffer.
  6745. // TODO(haberman): handle pushback
  6746. static void putbuf(upb_pb_encoder *e, const char *buf, size_t len) {
  6747. size_t n = upb_bytessink_putbuf(e->output_, e->subc, buf, len, NULL);
  6748. UPB_ASSERT_VAR(n, n == len);
  6749. }
  6750. static upb_pb_encoder_segment *top(upb_pb_encoder *e) {
  6751. return &e->segbuf[*e->top];
  6752. }
  6753. // Call to ensure that at least "bytes" bytes are available for writing at
  6754. // e->ptr. Returns false if the bytes could not be allocated.
  6755. static bool reserve(upb_pb_encoder *e, size_t bytes) {
  6756. if ((e->limit - e->ptr) < bytes) {
  6757. size_t needed = bytes + (e->ptr - e->buf);
  6758. size_t old_size = e->limit - e->buf;
  6759. size_t new_size = old_size;
  6760. while (new_size < needed) {
  6761. new_size *= 2;
  6762. }
  6763. char *realloc_from = (e->buf == e->initbuf) ? NULL : e->buf;
  6764. char *new_buf = realloc(realloc_from, new_size);
  6765. if (new_buf == NULL) {
  6766. return false;
  6767. }
  6768. if (realloc_from == NULL) {
  6769. memcpy(new_buf, e->initbuf, old_size);
  6770. }
  6771. e->ptr = new_buf + (e->ptr - e->buf);
  6772. e->runbegin = new_buf + (e->runbegin - e->buf);
  6773. e->limit = new_buf + new_size;
  6774. e->buf = new_buf;
  6775. }
  6776. return true;
  6777. }
  6778. // Call when "bytes" bytes have been writte at e->ptr. The caller *must* have
  6779. // previously called reserve() with at least this many bytes.
  6780. static void encoder_advance(upb_pb_encoder *e, size_t bytes) {
  6781. assert((e->limit - e->ptr) >= bytes);
  6782. e->ptr += bytes;
  6783. }
  6784. // Call when all of the bytes for a handler have been written. Flushes the
  6785. // bytes if possible and necessary, returning false if this failed.
  6786. static bool commit(upb_pb_encoder *e) {
  6787. if (!e->top) {
  6788. // We aren't inside a delimited region. Flush our accumulated bytes to
  6789. // the output.
  6790. //
  6791. // TODO(haberman): in the future we may want to delay flushing for
  6792. // efficiency reasons.
  6793. putbuf(e, e->buf, e->ptr - e->buf);
  6794. e->ptr = e->buf;
  6795. }
  6796. return true;
  6797. }
  6798. // Writes the given bytes to the buffer, handling reserve/advance.
  6799. static bool encode_bytes(upb_pb_encoder *e, const void *data, size_t len) {
  6800. if (!reserve(e, len)) {
  6801. return false;
  6802. }
  6803. memcpy(e->ptr, data, len);
  6804. encoder_advance(e, len);
  6805. return true;
  6806. }
  6807. // Finish the current run by adding the run totals to the segment and message
  6808. // length.
  6809. static void accumulate(upb_pb_encoder *e) {
  6810. assert(e->ptr >= e->runbegin);
  6811. size_t run_len = e->ptr - e->runbegin;
  6812. e->segptr->seglen += run_len;
  6813. top(e)->msglen += run_len;
  6814. e->runbegin = e->ptr;
  6815. }
  6816. // Call to indicate the start of delimited region for which the full length is
  6817. // not yet known. All data will be buffered until the length is known.
  6818. // Delimited regions may be nested; their lengths will all be tracked properly.
  6819. static bool start_delim(upb_pb_encoder *e) {
  6820. if (e->top) {
  6821. // We are already buffering, advance to the next segment and push it on the
  6822. // stack.
  6823. accumulate(e);
  6824. if (++e->top == e->stacklimit) {
  6825. // TODO(haberman): grow stack?
  6826. return false;
  6827. }
  6828. if (++e->segptr == e->seglimit) {
  6829. upb_pb_encoder_segment *realloc_from =
  6830. (e->segbuf == e->seginitbuf) ? NULL : e->segbuf;
  6831. size_t old_size =
  6832. (e->seglimit - e->segbuf) * sizeof(upb_pb_encoder_segment);
  6833. size_t new_size = old_size * 2;
  6834. upb_pb_encoder_segment *new_buf = realloc(realloc_from, new_size);
  6835. if (new_buf == NULL) {
  6836. return false;
  6837. }
  6838. if (realloc_from == NULL) {
  6839. memcpy(new_buf, e->seginitbuf, old_size);
  6840. }
  6841. e->segptr = new_buf + (e->segptr - e->segbuf);
  6842. e->seglimit = new_buf + (new_size / sizeof(upb_pb_encoder_segment));
  6843. e->segbuf = new_buf;
  6844. }
  6845. } else {
  6846. // We were previously at the top level, start buffering.
  6847. e->segptr = e->segbuf;
  6848. e->top = e->stack;
  6849. e->runbegin = e->ptr;
  6850. }
  6851. *e->top = e->segptr - e->segbuf;
  6852. e->segptr->seglen = 0;
  6853. e->segptr->msglen = 0;
  6854. return true;
  6855. }
  6856. // Call to indicate the end of a delimited region. We now know the length of
  6857. // the delimited region. If we are not nested inside any other delimited
  6858. // regions, we can now emit all of the buffered data we accumulated.
  6859. static bool end_delim(upb_pb_encoder *e) {
  6860. accumulate(e);
  6861. size_t msglen = top(e)->msglen;
  6862. if (e->top == e->stack) {
  6863. // All lengths are now available, emit all buffered data.
  6864. char buf[UPB_PB_VARINT_MAX_LEN];
  6865. upb_pb_encoder_segment *s;
  6866. const char *ptr = e->buf;
  6867. for (s = e->segbuf; s <= e->segptr; s++) {
  6868. size_t lenbytes = upb_vencode64(s->msglen, buf);
  6869. putbuf(e, buf, lenbytes);
  6870. putbuf(e, ptr, s->seglen);
  6871. ptr += s->seglen;
  6872. }
  6873. e->ptr = e->buf;
  6874. e->top = NULL;
  6875. } else {
  6876. // Need to keep buffering; propagate length info into enclosing submessages.
  6877. --e->top;
  6878. top(e)->msglen += msglen + upb_varint_size(msglen);
  6879. }
  6880. return true;
  6881. }
  6882. /* tag_t **********************************************************************/
  6883. // A precomputed (pre-encoded) tag and length.
  6884. typedef struct {
  6885. uint8_t bytes;
  6886. char tag[7];
  6887. } tag_t;
  6888. // Allocates a new tag for this field, and sets it in these handlerattr.
  6889. static void new_tag(upb_handlers *h, const upb_fielddef *f, upb_wiretype_t wt,
  6890. upb_handlerattr *attr) {
  6891. uint32_t n = upb_fielddef_number(f);
  6892. tag_t *tag = malloc(sizeof(tag_t));
  6893. tag->bytes = upb_vencode64((n << 3) | wt, tag->tag);
  6894. upb_handlerattr_init(attr);
  6895. upb_handlerattr_sethandlerdata(attr, tag);
  6896. upb_handlers_addcleanup(h, tag, free);
  6897. }
  6898. static bool encode_tag(upb_pb_encoder *e, const tag_t *tag) {
  6899. return encode_bytes(e, tag->tag, tag->bytes);
  6900. }
  6901. /* encoding of wire types *****************************************************/
  6902. static bool encode_fixed64(upb_pb_encoder *e, uint64_t val) {
  6903. // TODO(haberman): byte-swap for big endian.
  6904. return encode_bytes(e, &val, sizeof(uint64_t));
  6905. }
  6906. static bool encode_fixed32(upb_pb_encoder *e, uint32_t val) {
  6907. // TODO(haberman): byte-swap for big endian.
  6908. return encode_bytes(e, &val, sizeof(uint32_t));
  6909. }
  6910. static bool encode_varint(upb_pb_encoder *e, uint64_t val) {
  6911. if (!reserve(e, UPB_PB_VARINT_MAX_LEN)) {
  6912. return false;
  6913. }
  6914. encoder_advance(e, upb_vencode64(val, e->ptr));
  6915. return true;
  6916. }
  6917. static uint64_t dbl2uint64(double d) {
  6918. uint64_t ret;
  6919. memcpy(&ret, &d, sizeof(uint64_t));
  6920. return ret;
  6921. }
  6922. static uint32_t flt2uint32(float d) {
  6923. uint32_t ret;
  6924. memcpy(&ret, &d, sizeof(uint32_t));
  6925. return ret;
  6926. }
  6927. /* encoding of proto types ****************************************************/
  6928. static bool startmsg(void *c, const void *hd) {
  6929. upb_pb_encoder *e = c;
  6930. UPB_UNUSED(hd);
  6931. if (e->depth++ == 0) {
  6932. upb_bytessink_start(e->output_, 0, &e->subc);
  6933. }
  6934. return true;
  6935. }
  6936. static bool endmsg(void *c, const void *hd, upb_status *status) {
  6937. upb_pb_encoder *e = c;
  6938. UPB_UNUSED(hd);
  6939. UPB_UNUSED(status);
  6940. if (--e->depth == 0) {
  6941. upb_bytessink_end(e->output_);
  6942. }
  6943. return true;
  6944. }
  6945. static void *encode_startdelimfield(void *c, const void *hd) {
  6946. bool ok = encode_tag(c, hd) && commit(c) && start_delim(c);
  6947. return ok ? c : UPB_BREAK;
  6948. }
  6949. static bool encode_enddelimfield(void *c, const void *hd) {
  6950. UPB_UNUSED(hd);
  6951. return end_delim(c);
  6952. }
  6953. static void *encode_startgroup(void *c, const void *hd) {
  6954. return (encode_tag(c, hd) && commit(c)) ? c : UPB_BREAK;
  6955. }
  6956. static bool encode_endgroup(void *c, const void *hd) {
  6957. return encode_tag(c, hd) && commit(c);
  6958. }
  6959. static void *encode_startstr(void *c, const void *hd, size_t size_hint) {
  6960. UPB_UNUSED(size_hint);
  6961. return encode_startdelimfield(c, hd);
  6962. }
  6963. static size_t encode_strbuf(void *c, const void *hd, const char *buf,
  6964. size_t len, const upb_bufhandle *h) {
  6965. UPB_UNUSED(hd);
  6966. UPB_UNUSED(h);
  6967. return encode_bytes(c, buf, len) ? len : 0;
  6968. }
  6969. #define T(type, ctype, convert, encode) \
  6970. static bool encode_scalar_##type(void *e, const void *hd, ctype val) { \
  6971. return encode_tag(e, hd) && encode(e, (convert)(val)) && commit(e); \
  6972. } \
  6973. static bool encode_packed_##type(void *e, const void *hd, ctype val) { \
  6974. UPB_UNUSED(hd); \
  6975. return encode(e, (convert)(val)); \
  6976. }
  6977. T(double, double, dbl2uint64, encode_fixed64)
  6978. T(float, float, flt2uint32, encode_fixed32);
  6979. T(int64, int64_t, uint64_t, encode_varint);
  6980. T(int32, int32_t, uint32_t, encode_varint);
  6981. T(fixed64, uint64_t, uint64_t, encode_fixed64);
  6982. T(fixed32, uint32_t, uint32_t, encode_fixed32);
  6983. T(bool, bool, bool, encode_varint);
  6984. T(uint32, uint32_t, uint32_t, encode_varint);
  6985. T(uint64, uint64_t, uint64_t, encode_varint);
  6986. T(enum, int32_t, uint32_t, encode_varint);
  6987. T(sfixed32, int32_t, uint32_t, encode_fixed32);
  6988. T(sfixed64, int64_t, uint64_t, encode_fixed64);
  6989. T(sint32, int32_t, upb_zzenc_32, encode_varint);
  6990. T(sint64, int64_t, upb_zzenc_64, encode_varint);
  6991. #undef T
  6992. /* code to build the handlers *************************************************/
  6993. static void newhandlers_callback(const void *closure, upb_handlers *h) {
  6994. UPB_UNUSED(closure);
  6995. upb_handlers_setstartmsg(h, startmsg, NULL);
  6996. upb_handlers_setendmsg(h, endmsg, NULL);
  6997. const upb_msgdef *m = upb_handlers_msgdef(h);
  6998. upb_msg_iter i;
  6999. for(upb_msg_begin(&i, m); !upb_msg_done(&i); upb_msg_next(&i)) {
  7000. const upb_fielddef *f = upb_msg_iter_field(&i);
  7001. bool packed = upb_fielddef_isseq(f) && upb_fielddef_isprimitive(f) &&
  7002. upb_fielddef_packed(f);
  7003. upb_handlerattr attr;
  7004. upb_wiretype_t wt =
  7005. packed ? UPB_WIRE_TYPE_DELIMITED
  7006. : upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  7007. // Pre-encode the tag for this field.
  7008. new_tag(h, f, wt, &attr);
  7009. if (packed) {
  7010. upb_handlers_setstartseq(h, f, encode_startdelimfield, &attr);
  7011. upb_handlers_setendseq(h, f, encode_enddelimfield, &attr);
  7012. }
  7013. #define T(upper, lower, upbtype) \
  7014. case UPB_DESCRIPTOR_TYPE_##upper: \
  7015. if (packed) { \
  7016. upb_handlers_set##upbtype(h, f, encode_packed_##lower, &attr); \
  7017. } else { \
  7018. upb_handlers_set##upbtype(h, f, encode_scalar_##lower, &attr); \
  7019. } \
  7020. break;
  7021. switch (upb_fielddef_descriptortype(f)) {
  7022. T(DOUBLE, double, double);
  7023. T(FLOAT, float, float);
  7024. T(INT64, int64, int64);
  7025. T(INT32, int32, int32);
  7026. T(FIXED64, fixed64, uint64);
  7027. T(FIXED32, fixed32, uint32);
  7028. T(BOOL, bool, bool);
  7029. T(UINT32, uint32, uint32);
  7030. T(UINT64, uint64, uint64);
  7031. T(ENUM, enum, int32);
  7032. T(SFIXED32, sfixed32, int32);
  7033. T(SFIXED64, sfixed64, int64);
  7034. T(SINT32, sint32, int32);
  7035. T(SINT64, sint64, int64);
  7036. case UPB_DESCRIPTOR_TYPE_STRING:
  7037. case UPB_DESCRIPTOR_TYPE_BYTES:
  7038. upb_handlers_setstartstr(h, f, encode_startstr, &attr);
  7039. upb_handlers_setendstr(h, f, encode_enddelimfield, &attr);
  7040. upb_handlers_setstring(h, f, encode_strbuf, &attr);
  7041. break;
  7042. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  7043. upb_handlers_setstartsubmsg(h, f, encode_startdelimfield, &attr);
  7044. upb_handlers_setendsubmsg(h, f, encode_enddelimfield, &attr);
  7045. break;
  7046. case UPB_DESCRIPTOR_TYPE_GROUP: {
  7047. // Endgroup takes a different tag (wire_type = END_GROUP).
  7048. upb_handlerattr attr2;
  7049. new_tag(h, f, UPB_WIRE_TYPE_END_GROUP, &attr2);
  7050. upb_handlers_setstartsubmsg(h, f, encode_startgroup, &attr);
  7051. upb_handlers_setendsubmsg(h, f, encode_endgroup, &attr2);
  7052. upb_handlerattr_uninit(&attr2);
  7053. break;
  7054. }
  7055. }
  7056. #undef T
  7057. upb_handlerattr_uninit(&attr);
  7058. }
  7059. }
  7060. /* public API *****************************************************************/
  7061. const upb_handlers *upb_pb_encoder_newhandlers(const upb_msgdef *m,
  7062. const void *owner) {
  7063. return upb_handlers_newfrozen(m, owner, newhandlers_callback, NULL);
  7064. }
  7065. #define ARRAYSIZE(x) (sizeof(x) / sizeof(x[0]))
  7066. void upb_pb_encoder_init(upb_pb_encoder *e, const upb_handlers *h) {
  7067. e->output_ = NULL;
  7068. e->subc = NULL;
  7069. e->buf = e->initbuf;
  7070. e->ptr = e->buf;
  7071. e->limit = e->buf + ARRAYSIZE(e->initbuf);
  7072. e->segbuf = e->seginitbuf;
  7073. e->seglimit = e->segbuf + ARRAYSIZE(e->seginitbuf);
  7074. e->stacklimit = e->stack + ARRAYSIZE(e->stack);
  7075. upb_sink_reset(&e->input_, h, e);
  7076. }
  7077. void upb_pb_encoder_uninit(upb_pb_encoder *e) {
  7078. if (e->buf != e->initbuf) {
  7079. free(e->buf);
  7080. }
  7081. if (e->segbuf != e->seginitbuf) {
  7082. free(e->segbuf);
  7083. }
  7084. }
  7085. void upb_pb_encoder_resetoutput(upb_pb_encoder *e, upb_bytessink *output) {
  7086. upb_pb_encoder_reset(e);
  7087. e->output_ = output;
  7088. e->subc = output->closure;
  7089. }
  7090. void upb_pb_encoder_reset(upb_pb_encoder *e) {
  7091. e->segptr = NULL;
  7092. e->top = NULL;
  7093. e->depth = 0;
  7094. }
  7095. upb_sink *upb_pb_encoder_input(upb_pb_encoder *e) { return &e->input_; }
  7096. /*
  7097. * upb - a minimalist implementation of protocol buffers.
  7098. *
  7099. * Copyright (c) 2010-2012 Google Inc. See LICENSE for details.
  7100. * Author: Josh Haberman <jhaberman@gmail.com>
  7101. */
  7102. #include <stdio.h>
  7103. #include <stdlib.h>
  7104. #include <string.h>
  7105. upb_def **upb_load_defs_from_descriptor(const char *str, size_t len, int *n,
  7106. void *owner, upb_status *status) {
  7107. // Create handlers.
  7108. const upb_handlers *reader_h = upb_descreader_newhandlers(&reader_h);
  7109. upb_pbdecodermethodopts opts;
  7110. upb_pbdecodermethodopts_init(&opts, reader_h);
  7111. const upb_pbdecodermethod *decoder_m =
  7112. upb_pbdecodermethod_new(&opts, &decoder_m);
  7113. upb_pbdecoder decoder;
  7114. upb_descreader reader;
  7115. upb_pbdecoder_init(&decoder, decoder_m, status);
  7116. upb_descreader_init(&reader, reader_h, status);
  7117. upb_pbdecoder_resetoutput(&decoder, upb_descreader_input(&reader));
  7118. // Push input data.
  7119. bool ok = upb_bufsrc_putbuf(str, len, upb_pbdecoder_input(&decoder));
  7120. upb_def **ret = NULL;
  7121. if (!ok) goto cleanup;
  7122. upb_def **defs = upb_descreader_getdefs(&reader, owner, n);
  7123. ret = malloc(sizeof(upb_def*) * (*n));
  7124. memcpy(ret, defs, sizeof(upb_def*) * (*n));
  7125. cleanup:
  7126. upb_pbdecoder_uninit(&decoder);
  7127. upb_descreader_uninit(&reader);
  7128. upb_handlers_unref(reader_h, &reader_h);
  7129. upb_pbdecodermethod_unref(decoder_m, &decoder_m);
  7130. return ret;
  7131. }
  7132. bool upb_load_descriptor_into_symtab(upb_symtab *s, const char *str, size_t len,
  7133. upb_status *status) {
  7134. int n;
  7135. upb_def **defs = upb_load_defs_from_descriptor(str, len, &n, &defs, status);
  7136. if (!defs) return false;
  7137. bool success = upb_symtab_add(s, defs, n, &defs, status);
  7138. free(defs);
  7139. return success;
  7140. }
  7141. char *upb_readfile(const char *filename, size_t *len) {
  7142. FILE *f = fopen(filename, "rb");
  7143. if(!f) return NULL;
  7144. if(fseek(f, 0, SEEK_END) != 0) goto error;
  7145. long size = ftell(f);
  7146. if(size < 0) goto error;
  7147. if(fseek(f, 0, SEEK_SET) != 0) goto error;
  7148. char *buf = malloc(size + 1);
  7149. if(size && fread(buf, size, 1, f) != 1) goto error;
  7150. fclose(f);
  7151. if (len) *len = size;
  7152. return buf;
  7153. error:
  7154. fclose(f);
  7155. return NULL;
  7156. }
  7157. bool upb_load_descriptor_file_into_symtab(upb_symtab *symtab, const char *fname,
  7158. upb_status *status) {
  7159. size_t len;
  7160. char *data = upb_readfile(fname, &len);
  7161. if (!data) {
  7162. if (status) upb_status_seterrf(status, "Couldn't read file: %s", fname);
  7163. return false;
  7164. }
  7165. bool success = upb_load_descriptor_into_symtab(symtab, data, len, status);
  7166. free(data);
  7167. return success;
  7168. }
  7169. /*
  7170. * upb - a minimalist implementation of protocol buffers.
  7171. *
  7172. * Copyright (c) 2009 Google Inc. See LICENSE for details.
  7173. * Author: Josh Haberman <jhaberman@gmail.com>
  7174. *
  7175. * OPT: This is not optimized at all. It uses printf() which parses the format
  7176. * string every time, and it allocates memory for every put.
  7177. */
  7178. #include <ctype.h>
  7179. #include <float.h>
  7180. #include <inttypes.h>
  7181. #include <stdio.h>
  7182. #include <stdlib.h>
  7183. #include <string.h>
  7184. #define CHECK(x) if ((x) < 0) goto err;
  7185. static const char *shortname(const char *longname) {
  7186. const char *last = strrchr(longname, '.');
  7187. return last ? last + 1 : longname;
  7188. }
  7189. static int indent(upb_textprinter *p) {
  7190. int i;
  7191. if (!p->single_line_)
  7192. for (i = 0; i < p->indent_depth_; i++)
  7193. upb_bytessink_putbuf(p->output_, p->subc, " ", 2, NULL);
  7194. return 0;
  7195. }
  7196. static int endfield(upb_textprinter *p) {
  7197. const char ch = (p->single_line_ ? ' ' : '\n');
  7198. upb_bytessink_putbuf(p->output_, p->subc, &ch, 1, NULL);
  7199. return 0;
  7200. }
  7201. static int putescaped(upb_textprinter *p, const char *buf, size_t len,
  7202. bool preserve_utf8) {
  7203. // Based on CEscapeInternal() from Google's protobuf release.
  7204. char dstbuf[4096], *dst = dstbuf, *dstend = dstbuf + sizeof(dstbuf);
  7205. const char *end = buf + len;
  7206. // I think hex is prettier and more useful, but proto2 uses octal; should
  7207. // investigate whether it can parse hex also.
  7208. const bool use_hex = false;
  7209. bool last_hex_escape = false; // true if last output char was \xNN
  7210. for (; buf < end; buf++) {
  7211. if (dstend - dst < 4) {
  7212. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  7213. dst = dstbuf;
  7214. }
  7215. bool is_hex_escape = false;
  7216. switch (*buf) {
  7217. case '\n': *(dst++) = '\\'; *(dst++) = 'n'; break;
  7218. case '\r': *(dst++) = '\\'; *(dst++) = 'r'; break;
  7219. case '\t': *(dst++) = '\\'; *(dst++) = 't'; break;
  7220. case '\"': *(dst++) = '\\'; *(dst++) = '\"'; break;
  7221. case '\'': *(dst++) = '\\'; *(dst++) = '\''; break;
  7222. case '\\': *(dst++) = '\\'; *(dst++) = '\\'; break;
  7223. default:
  7224. // Note that if we emit \xNN and the buf character after that is a hex
  7225. // digit then that digit must be escaped too to prevent it being
  7226. // interpreted as part of the character code by C.
  7227. if ((!preserve_utf8 || (uint8_t)*buf < 0x80) &&
  7228. (!isprint(*buf) || (last_hex_escape && isxdigit(*buf)))) {
  7229. sprintf(dst, (use_hex ? "\\x%02x" : "\\%03o"), (uint8_t)*buf);
  7230. is_hex_escape = use_hex;
  7231. dst += 4;
  7232. } else {
  7233. *(dst++) = *buf; break;
  7234. }
  7235. }
  7236. last_hex_escape = is_hex_escape;
  7237. }
  7238. // Flush remaining data.
  7239. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  7240. return 0;
  7241. }
  7242. bool putf(upb_textprinter *p, const char *fmt, ...) {
  7243. va_list args;
  7244. va_start(args, fmt);
  7245. // Run once to get the length of the string.
  7246. va_list args_copy;
  7247. va_copy(args_copy, args);
  7248. int len = vsnprintf(NULL, 0, fmt, args_copy);
  7249. va_end(args_copy);
  7250. // + 1 for NULL terminator (vsnprintf() requires it even if we don't).
  7251. char *str = malloc(len + 1);
  7252. if (!str) return false;
  7253. int written = vsnprintf(str, len + 1, fmt, args);
  7254. va_end(args);
  7255. UPB_ASSERT_VAR(written, written == len);
  7256. bool ok = upb_bytessink_putbuf(p->output_, p->subc, str, len, NULL);
  7257. free(str);
  7258. return ok;
  7259. }
  7260. /* handlers *******************************************************************/
  7261. static bool textprinter_startmsg(void *c, const void *hd) {
  7262. UPB_UNUSED(hd);
  7263. upb_textprinter *p = c;
  7264. if (p->indent_depth_ == 0) {
  7265. upb_bytessink_start(p->output_, 0, &p->subc);
  7266. }
  7267. return true;
  7268. }
  7269. static bool textprinter_endmsg(void *c, const void *hd, upb_status *s) {
  7270. UPB_UNUSED(hd);
  7271. UPB_UNUSED(s);
  7272. upb_textprinter *p = c;
  7273. if (p->indent_depth_ == 0) {
  7274. upb_bytessink_end(p->output_);
  7275. }
  7276. return true;
  7277. }
  7278. #define TYPE(name, ctype, fmt) \
  7279. static bool textprinter_put ## name(void *closure, const void *handler_data, \
  7280. ctype val) { \
  7281. upb_textprinter *p = closure; \
  7282. const upb_fielddef *f = handler_data; \
  7283. CHECK(indent(p)); \
  7284. putf(p, "%s: " fmt, upb_fielddef_name(f), val); \
  7285. CHECK(endfield(p)); \
  7286. return true; \
  7287. err: \
  7288. return false; \
  7289. }
  7290. static bool textprinter_putbool(void *closure, const void *handler_data,
  7291. bool val) {
  7292. upb_textprinter *p = closure;
  7293. const upb_fielddef *f = handler_data;
  7294. CHECK(indent(p));
  7295. putf(p, "%s: %s", upb_fielddef_name(f), val ? "true" : "false");
  7296. CHECK(endfield(p));
  7297. return true;
  7298. err:
  7299. return false;
  7300. }
  7301. #define STRINGIFY_HELPER(x) #x
  7302. #define STRINGIFY_MACROVAL(x) STRINGIFY_HELPER(x)
  7303. TYPE(int32, int32_t, "%" PRId32)
  7304. TYPE(int64, int64_t, "%" PRId64)
  7305. TYPE(uint32, uint32_t, "%" PRIu32);
  7306. TYPE(uint64, uint64_t, "%" PRIu64)
  7307. TYPE(float, float, "%." STRINGIFY_MACROVAL(FLT_DIG) "g")
  7308. TYPE(double, double, "%." STRINGIFY_MACROVAL(DBL_DIG) "g")
  7309. #undef TYPE
  7310. // Output a symbolic value from the enum if found, else just print as int32.
  7311. static bool textprinter_putenum(void *closure, const void *handler_data,
  7312. int32_t val) {
  7313. upb_textprinter *p = closure;
  7314. const upb_fielddef *f = handler_data;
  7315. const upb_enumdef *enum_def = upb_downcast_enumdef(upb_fielddef_subdef(f));
  7316. const char *label = upb_enumdef_iton(enum_def, val);
  7317. if (label) {
  7318. indent(p);
  7319. putf(p, "%s: %s", upb_fielddef_name(f), label);
  7320. endfield(p);
  7321. } else {
  7322. if (!textprinter_putint32(closure, handler_data, val))
  7323. return false;
  7324. }
  7325. return true;
  7326. }
  7327. static void *textprinter_startstr(void *closure, const void *handler_data,
  7328. size_t size_hint) {
  7329. const upb_fielddef *f = handler_data;
  7330. UPB_UNUSED(size_hint);
  7331. upb_textprinter *p = closure;
  7332. indent(p);
  7333. putf(p, "%s: \"", upb_fielddef_name(f));
  7334. return p;
  7335. }
  7336. static bool textprinter_endstr(void *closure, const void *handler_data) {
  7337. UPB_UNUSED(handler_data);
  7338. upb_textprinter *p = closure;
  7339. putf(p, "\"");
  7340. endfield(p);
  7341. return true;
  7342. }
  7343. static size_t textprinter_putstr(void *closure, const void *hd, const char *buf,
  7344. size_t len, const upb_bufhandle *handle) {
  7345. UPB_UNUSED(handle);
  7346. upb_textprinter *p = closure;
  7347. const upb_fielddef *f = hd;
  7348. CHECK(putescaped(p, buf, len, upb_fielddef_type(f) == UPB_TYPE_STRING));
  7349. return len;
  7350. err:
  7351. return 0;
  7352. }
  7353. static void *textprinter_startsubmsg(void *closure, const void *handler_data) {
  7354. upb_textprinter *p = closure;
  7355. const char *name = handler_data;
  7356. CHECK(indent(p));
  7357. putf(p, "%s {%c", name, p->single_line_ ? ' ' : '\n');
  7358. p->indent_depth_++;
  7359. return p;
  7360. err:
  7361. return UPB_BREAK;
  7362. }
  7363. static bool textprinter_endsubmsg(void *closure, const void *handler_data) {
  7364. UPB_UNUSED(handler_data);
  7365. upb_textprinter *p = closure;
  7366. p->indent_depth_--;
  7367. CHECK(indent(p));
  7368. upb_bytessink_putbuf(p->output_, p->subc, "}", 1, NULL);
  7369. CHECK(endfield(p));
  7370. return true;
  7371. err:
  7372. return false;
  7373. }
  7374. /* Public API *****************************************************************/
  7375. void upb_textprinter_init(upb_textprinter *p, const upb_handlers *h) {
  7376. p->single_line_ = false;
  7377. p->indent_depth_ = 0;
  7378. upb_sink_reset(&p->input_, h, p);
  7379. }
  7380. void upb_textprinter_uninit(upb_textprinter *p) {
  7381. UPB_UNUSED(p);
  7382. }
  7383. void upb_textprinter_reset(upb_textprinter *p, bool single_line) {
  7384. p->single_line_ = single_line;
  7385. p->indent_depth_ = 0;
  7386. }
  7387. static void onmreg(const void *c, upb_handlers *h) {
  7388. UPB_UNUSED(c);
  7389. const upb_msgdef *m = upb_handlers_msgdef(h);
  7390. upb_handlers_setstartmsg(h, textprinter_startmsg, NULL);
  7391. upb_handlers_setendmsg(h, textprinter_endmsg, NULL);
  7392. upb_msg_iter i;
  7393. for(upb_msg_begin(&i, m); !upb_msg_done(&i); upb_msg_next(&i)) {
  7394. upb_fielddef *f = upb_msg_iter_field(&i);
  7395. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  7396. upb_handlerattr_sethandlerdata(&attr, f);
  7397. switch (upb_fielddef_type(f)) {
  7398. case UPB_TYPE_INT32:
  7399. upb_handlers_setint32(h, f, textprinter_putint32, &attr);
  7400. break;
  7401. case UPB_TYPE_INT64:
  7402. upb_handlers_setint64(h, f, textprinter_putint64, &attr);
  7403. break;
  7404. case UPB_TYPE_UINT32:
  7405. upb_handlers_setuint32(h, f, textprinter_putuint32, &attr);
  7406. break;
  7407. case UPB_TYPE_UINT64:
  7408. upb_handlers_setuint64(h, f, textprinter_putuint64, &attr);
  7409. break;
  7410. case UPB_TYPE_FLOAT:
  7411. upb_handlers_setfloat(h, f, textprinter_putfloat, &attr);
  7412. break;
  7413. case UPB_TYPE_DOUBLE:
  7414. upb_handlers_setdouble(h, f, textprinter_putdouble, &attr);
  7415. break;
  7416. case UPB_TYPE_BOOL:
  7417. upb_handlers_setbool(h, f, textprinter_putbool, &attr);
  7418. break;
  7419. case UPB_TYPE_STRING:
  7420. case UPB_TYPE_BYTES:
  7421. upb_handlers_setstartstr(h, f, textprinter_startstr, &attr);
  7422. upb_handlers_setstring(h, f, textprinter_putstr, &attr);
  7423. upb_handlers_setendstr(h, f, textprinter_endstr, &attr);
  7424. break;
  7425. case UPB_TYPE_MESSAGE: {
  7426. const char *name =
  7427. upb_fielddef_istagdelim(f)
  7428. ? shortname(upb_msgdef_fullname(upb_fielddef_msgsubdef(f)))
  7429. : upb_fielddef_name(f);
  7430. upb_handlerattr_sethandlerdata(&attr, name);
  7431. upb_handlers_setstartsubmsg(h, f, textprinter_startsubmsg, &attr);
  7432. upb_handlers_setendsubmsg(h, f, textprinter_endsubmsg, &attr);
  7433. break;
  7434. }
  7435. case UPB_TYPE_ENUM:
  7436. upb_handlers_setint32(h, f, textprinter_putenum, &attr);
  7437. break;
  7438. }
  7439. }
  7440. }
  7441. const upb_handlers *upb_textprinter_newhandlers(const upb_msgdef *m,
  7442. const void *owner) {
  7443. return upb_handlers_newfrozen(m, owner, &onmreg, NULL);
  7444. }
  7445. upb_sink *upb_textprinter_input(upb_textprinter *p) { return &p->input_; }
  7446. bool upb_textprinter_resetoutput(upb_textprinter *p, upb_bytessink *output) {
  7447. p->output_ = output;
  7448. return true;
  7449. }
  7450. void upb_textprinter_setsingleline(upb_textprinter *p, bool single_line) {
  7451. p->single_line_ = single_line;
  7452. }
  7453. /*
  7454. * upb - a minimalist implementation of protocol buffers.
  7455. *
  7456. * Copyright (c) 2011 Google Inc. See LICENSE for details.
  7457. * Author: Josh Haberman <jhaberman@gmail.com>
  7458. */
  7459. // Index is descriptor type.
  7460. const uint8_t upb_pb_native_wire_types[] = {
  7461. UPB_WIRE_TYPE_END_GROUP, // ENDGROUP
  7462. UPB_WIRE_TYPE_64BIT, // DOUBLE
  7463. UPB_WIRE_TYPE_32BIT, // FLOAT
  7464. UPB_WIRE_TYPE_VARINT, // INT64
  7465. UPB_WIRE_TYPE_VARINT, // UINT64
  7466. UPB_WIRE_TYPE_VARINT, // INT32
  7467. UPB_WIRE_TYPE_64BIT, // FIXED64
  7468. UPB_WIRE_TYPE_32BIT, // FIXED32
  7469. UPB_WIRE_TYPE_VARINT, // BOOL
  7470. UPB_WIRE_TYPE_DELIMITED, // STRING
  7471. UPB_WIRE_TYPE_START_GROUP, // GROUP
  7472. UPB_WIRE_TYPE_DELIMITED, // MESSAGE
  7473. UPB_WIRE_TYPE_DELIMITED, // BYTES
  7474. UPB_WIRE_TYPE_VARINT, // UINT32
  7475. UPB_WIRE_TYPE_VARINT, // ENUM
  7476. UPB_WIRE_TYPE_32BIT, // SFIXED32
  7477. UPB_WIRE_TYPE_64BIT, // SFIXED64
  7478. UPB_WIRE_TYPE_VARINT, // SINT32
  7479. UPB_WIRE_TYPE_VARINT, // SINT64
  7480. };
  7481. // A basic branch-based decoder, uses 32-bit values to get good performance
  7482. // on 32-bit architectures (but performs well on 64-bits also).
  7483. // This scheme comes from the original Google Protobuf implementation (proto2).
  7484. upb_decoderet upb_vdecode_max8_branch32(upb_decoderet r) {
  7485. upb_decoderet err = {NULL, 0};
  7486. const char *p = r.p;
  7487. uint32_t low = (uint32_t)r.val;
  7488. uint32_t high = 0;
  7489. uint32_t b;
  7490. b = *(p++); low |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  7491. b = *(p++); low |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  7492. b = *(p++); low |= (b & 0x7fU) << 28;
  7493. high = (b & 0x7fU) >> 4; if (!(b & 0x80)) goto done;
  7494. b = *(p++); high |= (b & 0x7fU) << 3; if (!(b & 0x80)) goto done;
  7495. b = *(p++); high |= (b & 0x7fU) << 10; if (!(b & 0x80)) goto done;
  7496. b = *(p++); high |= (b & 0x7fU) << 17; if (!(b & 0x80)) goto done;
  7497. b = *(p++); high |= (b & 0x7fU) << 24; if (!(b & 0x80)) goto done;
  7498. b = *(p++); high |= (b & 0x7fU) << 31; if (!(b & 0x80)) goto done;
  7499. return err;
  7500. done:
  7501. r.val = ((uint64_t)high << 32) | low;
  7502. r.p = p;
  7503. return r;
  7504. }
  7505. // Like the previous, but uses 64-bit values.
  7506. upb_decoderet upb_vdecode_max8_branch64(upb_decoderet r) {
  7507. const char *p = r.p;
  7508. uint64_t val = r.val;
  7509. uint64_t b;
  7510. upb_decoderet err = {NULL, 0};
  7511. b = *(p++); val |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  7512. b = *(p++); val |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  7513. b = *(p++); val |= (b & 0x7fU) << 28; if (!(b & 0x80)) goto done;
  7514. b = *(p++); val |= (b & 0x7fU) << 35; if (!(b & 0x80)) goto done;
  7515. b = *(p++); val |= (b & 0x7fU) << 42; if (!(b & 0x80)) goto done;
  7516. b = *(p++); val |= (b & 0x7fU) << 49; if (!(b & 0x80)) goto done;
  7517. b = *(p++); val |= (b & 0x7fU) << 56; if (!(b & 0x80)) goto done;
  7518. b = *(p++); val |= (b & 0x7fU) << 63; if (!(b & 0x80)) goto done;
  7519. return err;
  7520. done:
  7521. r.val = val;
  7522. r.p = p;
  7523. return r;
  7524. }
  7525. // Given an encoded varint v, returns an integer with a single bit set that
  7526. // indicates the end of the varint. Subtracting one from this value will
  7527. // yield a mask that leaves only bits that are part of the varint. Returns
  7528. // 0 if the varint is unterminated.
  7529. static uint64_t upb_get_vstopbit(uint64_t v) {
  7530. uint64_t cbits = v | 0x7f7f7f7f7f7f7f7fULL;
  7531. return ~cbits & (cbits+1);
  7532. }
  7533. // A branchless decoder. Credit to Pascal Massimino for the bit-twiddling.
  7534. upb_decoderet upb_vdecode_max8_massimino(upb_decoderet r) {
  7535. uint64_t b;
  7536. memcpy(&b, r.p, sizeof(b));
  7537. uint64_t stop_bit = upb_get_vstopbit(b);
  7538. b = (b & 0x7f7f7f7f7f7f7f7fULL) & (stop_bit - 1);
  7539. b += b & 0x007f007f007f007fULL;
  7540. b += 3 * (b & 0x0000ffff0000ffffULL);
  7541. b += 15 * (b & 0x00000000ffffffffULL);
  7542. if (stop_bit == 0) {
  7543. // Error: unterminated varint.
  7544. upb_decoderet err_r = {(void*)0, 0};
  7545. return err_r;
  7546. }
  7547. upb_decoderet my_r = {r.p + ((__builtin_ctzll(stop_bit) + 1) / 8),
  7548. r.val | (b << 7)};
  7549. return my_r;
  7550. }
  7551. // A branchless decoder. Credit to Daniel Wright for the bit-twiddling.
  7552. upb_decoderet upb_vdecode_max8_wright(upb_decoderet r) {
  7553. uint64_t b;
  7554. memcpy(&b, r.p, sizeof(b));
  7555. uint64_t stop_bit = upb_get_vstopbit(b);
  7556. b &= (stop_bit - 1);
  7557. b = ((b & 0x7f007f007f007f00ULL) >> 1) | (b & 0x007f007f007f007fULL);
  7558. b = ((b & 0xffff0000ffff0000ULL) >> 2) | (b & 0x0000ffff0000ffffULL);
  7559. b = ((b & 0xffffffff00000000ULL) >> 4) | (b & 0x00000000ffffffffULL);
  7560. if (stop_bit == 0) {
  7561. // Error: unterminated varint.
  7562. upb_decoderet err_r = {(void*)0, 0};
  7563. return err_r;
  7564. }
  7565. upb_decoderet my_r = {r.p + ((__builtin_ctzll(stop_bit) + 1) / 8),
  7566. r.val | (b << 14)};
  7567. return my_r;
  7568. }
  7569. #line 1 "upb/json/parser.rl"
  7570. /*
  7571. * upb - a minimalist implementation of protocol buffers.
  7572. *
  7573. * Copyright (c) 2014 Google Inc. See LICENSE for details.
  7574. * Author: Josh Haberman <jhaberman@gmail.com>
  7575. *
  7576. * A parser that uses the Ragel State Machine Compiler to generate
  7577. * the finite automata.
  7578. *
  7579. * Ragel only natively handles regular languages, but we can manually
  7580. * program it a bit to handle context-free languages like JSON, by using
  7581. * the "fcall" and "fret" constructs.
  7582. *
  7583. * This parser can handle the basics, but needs several things to be fleshed
  7584. * out:
  7585. *
  7586. * - handling of unicode escape sequences (including high surrogate pairs).
  7587. * - properly check and report errors for unknown fields, stack overflow,
  7588. * improper array nesting (or lack of nesting).
  7589. * - handling of base64 sequences with padding characters.
  7590. * - handling of push-back (non-success returns from sink functions).
  7591. * - handling of keys/escape-sequences/etc that span input buffers.
  7592. */
  7593. #include <stdio.h>
  7594. #include <stdint.h>
  7595. #include <assert.h>
  7596. #include <string.h>
  7597. #include <stdlib.h>
  7598. #include <errno.h>
  7599. #define PARSER_CHECK_RETURN(x) if (!(x)) return false
  7600. static upb_selector_t getsel_for_handlertype(upb_json_parser *p,
  7601. upb_handlertype_t type) {
  7602. upb_selector_t sel;
  7603. bool ok = upb_handlers_getselector(p->top->f, type, &sel);
  7604. UPB_ASSERT_VAR(ok, ok);
  7605. return sel;
  7606. }
  7607. static upb_selector_t parser_getsel(upb_json_parser *p) {
  7608. return getsel_for_handlertype(
  7609. p, upb_handlers_getprimitivehandlertype(p->top->f));
  7610. }
  7611. static void start_member(upb_json_parser *p) {
  7612. assert(!p->top->f);
  7613. assert(!p->accumulated);
  7614. p->accumulated_len = 0;
  7615. }
  7616. static bool end_member(upb_json_parser *p) {
  7617. // TODO(haberman): support keys that span buffers or have escape sequences.
  7618. assert(!p->top->f);
  7619. assert(p->accumulated);
  7620. const upb_fielddef *f =
  7621. upb_msgdef_ntof(p->top->m, p->accumulated, p->accumulated_len);
  7622. if (!f) {
  7623. // TODO(haberman): Ignore unknown fields if requested/configured to do so.
  7624. upb_status_seterrf(p->status, "No such field: %.*s\n",
  7625. (int)p->accumulated_len, p->accumulated);
  7626. return false;
  7627. }
  7628. p->top->f = f;
  7629. p->accumulated = NULL;
  7630. return true;
  7631. }
  7632. static void start_object(upb_json_parser *p) {
  7633. upb_sink_startmsg(&p->top->sink);
  7634. }
  7635. static void end_object(upb_json_parser *p) {
  7636. upb_status status;
  7637. upb_sink_endmsg(&p->top->sink, &status);
  7638. }
  7639. static bool check_stack(upb_json_parser *p) {
  7640. if ((p->top + 1) == p->limit) {
  7641. upb_status_seterrmsg(p->status, "Nesting too deep");
  7642. return false;
  7643. }
  7644. return true;
  7645. }
  7646. static bool start_subobject(upb_json_parser *p) {
  7647. assert(p->top->f);
  7648. if (!upb_fielddef_issubmsg(p->top->f)) {
  7649. upb_status_seterrf(p->status,
  7650. "Object specified for non-message/group field: %s",
  7651. upb_fielddef_name(p->top->f));
  7652. return false;
  7653. }
  7654. if (!check_stack(p)) return false;
  7655. upb_jsonparser_frame *inner = p->top + 1;
  7656. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
  7657. upb_sink_startsubmsg(&p->top->sink, sel, &inner->sink);
  7658. inner->m = upb_fielddef_msgsubdef(p->top->f);
  7659. inner->f = NULL;
  7660. p->top = inner;
  7661. return true;
  7662. }
  7663. static void end_subobject(upb_json_parser *p) {
  7664. p->top--;
  7665. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSUBMSG);
  7666. upb_sink_endsubmsg(&p->top->sink, sel);
  7667. }
  7668. static bool start_array(upb_json_parser *p) {
  7669. assert(p->top->f);
  7670. if (!upb_fielddef_isseq(p->top->f)) {
  7671. upb_status_seterrf(p->status,
  7672. "Array specified for non-repeated field: %s",
  7673. upb_fielddef_name(p->top->f));
  7674. return false;
  7675. }
  7676. if (!check_stack(p)) return false;
  7677. upb_jsonparser_frame *inner = p->top + 1;
  7678. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
  7679. upb_sink_startseq(&p->top->sink, sel, &inner->sink);
  7680. inner->m = p->top->m;
  7681. inner->f = p->top->f;
  7682. p->top = inner;
  7683. return true;
  7684. }
  7685. static void end_array(upb_json_parser *p) {
  7686. assert(p->top > p->stack);
  7687. p->top--;
  7688. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
  7689. upb_sink_endseq(&p->top->sink, sel);
  7690. }
  7691. static void clear_member(upb_json_parser *p) { p->top->f = NULL; }
  7692. static bool parser_putbool(upb_json_parser *p, bool val) {
  7693. if (upb_fielddef_type(p->top->f) != UPB_TYPE_BOOL) {
  7694. upb_status_seterrf(p->status,
  7695. "Boolean value specified for non-bool field: %s",
  7696. upb_fielddef_name(p->top->f));
  7697. return false;
  7698. }
  7699. bool ok = upb_sink_putbool(&p->top->sink, parser_getsel(p), val);
  7700. UPB_ASSERT_VAR(ok, ok);
  7701. return true;
  7702. }
  7703. static void start_text(upb_json_parser *p, const char *ptr) {
  7704. p->text_begin = ptr;
  7705. }
  7706. static const signed char b64table[] = {
  7707. -1, -1, -1, -1, -1, -1, -1, -1,
  7708. -1, -1, -1, -1, -1, -1, -1, -1,
  7709. -1, -1, -1, -1, -1, -1, -1, -1,
  7710. -1, -1, -1, -1, -1, -1, -1, -1,
  7711. -1, -1, -1, -1, -1, -1, -1, -1,
  7712. -1, -1, -1, 62/*+*/, -1, -1, -1, 63/*/ */,
  7713. 52/*0*/, 53/*1*/, 54/*2*/, 55/*3*/, 56/*4*/, 57/*5*/, 58/*6*/, 59/*7*/,
  7714. 60/*8*/, 61/*9*/, -1, -1, -1, -1, -1, -1,
  7715. -1, 0/*A*/, 1/*B*/, 2/*C*/, 3/*D*/, 4/*E*/, 5/*F*/, 6/*G*/,
  7716. 07/*H*/, 8/*I*/, 9/*J*/, 10/*K*/, 11/*L*/, 12/*M*/, 13/*N*/, 14/*O*/,
  7717. 15/*P*/, 16/*Q*/, 17/*R*/, 18/*S*/, 19/*T*/, 20/*U*/, 21/*V*/, 22/*W*/,
  7718. 23/*X*/, 24/*Y*/, 25/*Z*/, -1, -1, -1, -1, -1,
  7719. -1, 26/*a*/, 27/*b*/, 28/*c*/, 29/*d*/, 30/*e*/, 31/*f*/, 32/*g*/,
  7720. 33/*h*/, 34/*i*/, 35/*j*/, 36/*k*/, 37/*l*/, 38/*m*/, 39/*n*/, 40/*o*/,
  7721. 41/*p*/, 42/*q*/, 43/*r*/, 44/*s*/, 45/*t*/, 46/*u*/, 47/*v*/, 48/*w*/,
  7722. 49/*x*/, 50/*y*/, 51/*z*/, -1, -1, -1, -1, -1,
  7723. -1, -1, -1, -1, -1, -1, -1, -1,
  7724. -1, -1, -1, -1, -1, -1, -1, -1,
  7725. -1, -1, -1, -1, -1, -1, -1, -1,
  7726. -1, -1, -1, -1, -1, -1, -1, -1,
  7727. -1, -1, -1, -1, -1, -1, -1, -1,
  7728. -1, -1, -1, -1, -1, -1, -1, -1,
  7729. -1, -1, -1, -1, -1, -1, -1, -1,
  7730. -1, -1, -1, -1, -1, -1, -1, -1,
  7731. -1, -1, -1, -1, -1, -1, -1, -1,
  7732. -1, -1, -1, -1, -1, -1, -1, -1,
  7733. -1, -1, -1, -1, -1, -1, -1, -1,
  7734. -1, -1, -1, -1, -1, -1, -1, -1,
  7735. -1, -1, -1, -1, -1, -1, -1, -1,
  7736. -1, -1, -1, -1, -1, -1, -1, -1,
  7737. -1, -1, -1, -1, -1, -1, -1, -1,
  7738. -1, -1, -1, -1, -1, -1, -1, -1
  7739. };
  7740. // Returns the table value sign-extended to 32 bits. Knowing that the upper
  7741. // bits will be 1 for unrecognized characters makes it easier to check for
  7742. // this error condition later (see below).
  7743. int32_t b64lookup(unsigned char ch) { return b64table[ch]; }
  7744. // Returns true if the given character is not a valid base64 character or
  7745. // padding.
  7746. bool nonbase64(unsigned char ch) { return b64lookup(ch) == -1 && ch != '='; }
  7747. static bool base64_push(upb_json_parser *p, upb_selector_t sel, const char *ptr,
  7748. size_t len) {
  7749. const char *limit = ptr + len;
  7750. for (; ptr < limit; ptr += 4) {
  7751. if (limit - ptr < 4) {
  7752. upb_status_seterrf(p->status,
  7753. "Base64 input for bytes field not a multiple of 4: %s",
  7754. upb_fielddef_name(p->top->f));
  7755. return false;
  7756. }
  7757. uint32_t val = b64lookup(ptr[0]) << 18 |
  7758. b64lookup(ptr[1]) << 12 |
  7759. b64lookup(ptr[2]) << 6 |
  7760. b64lookup(ptr[3]);
  7761. // Test the upper bit; returns true if any of the characters returned -1.
  7762. if (val & 0x80000000) {
  7763. goto otherchar;
  7764. }
  7765. char output[3];
  7766. output[0] = val >> 16;
  7767. output[1] = (val >> 8) & 0xff;
  7768. output[2] = val & 0xff;
  7769. upb_sink_putstring(&p->top->sink, sel, output, 3, NULL);
  7770. }
  7771. return true;
  7772. otherchar:
  7773. if (nonbase64(ptr[0]) || nonbase64(ptr[1]) || nonbase64(ptr[2]) ||
  7774. nonbase64(ptr[3]) ) {
  7775. upb_status_seterrf(p->status,
  7776. "Non-base64 characters in bytes field: %s",
  7777. upb_fielddef_name(p->top->f));
  7778. return false;
  7779. } if (ptr[2] == '=') {
  7780. // Last group contains only two input bytes, one output byte.
  7781. if (ptr[0] == '=' || ptr[1] == '=' || ptr[3] != '=') {
  7782. goto badpadding;
  7783. }
  7784. uint32_t val = b64lookup(ptr[0]) << 18 |
  7785. b64lookup(ptr[1]) << 12;
  7786. assert(!(val & 0x80000000));
  7787. char output = val >> 16;
  7788. upb_sink_putstring(&p->top->sink, sel, &output, 1, NULL);
  7789. return true;
  7790. } else {
  7791. // Last group contains only three input bytes, two output bytes.
  7792. if (ptr[0] == '=' || ptr[1] == '=' || ptr[2] == '=') {
  7793. goto badpadding;
  7794. }
  7795. uint32_t val = b64lookup(ptr[0]) << 18 |
  7796. b64lookup(ptr[1]) << 12 |
  7797. b64lookup(ptr[2]) << 6;
  7798. char output[2];
  7799. output[0] = val >> 16;
  7800. output[1] = (val >> 8) & 0xff;
  7801. upb_sink_putstring(&p->top->sink, sel, output, 2, NULL);
  7802. return true;
  7803. }
  7804. badpadding:
  7805. upb_status_seterrf(p->status,
  7806. "Incorrect base64 padding for field: %s (%.*s)",
  7807. upb_fielddef_name(p->top->f),
  7808. 4, ptr);
  7809. return false;
  7810. }
  7811. static bool end_text(upb_json_parser *p, const char *ptr, bool is_num) {
  7812. assert(!p->accumulated); // TODO: handle this case.
  7813. p->accumulated = p->text_begin;
  7814. p->accumulated_len = ptr - p->text_begin;
  7815. if (p->top->f && upb_fielddef_isstring(p->top->f)) {
  7816. // This is a string field (as opposed to a member name).
  7817. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
  7818. if (upb_fielddef_type(p->top->f) == UPB_TYPE_BYTES) {
  7819. PARSER_CHECK_RETURN(base64_push(p, sel, p->accumulated,
  7820. p->accumulated_len));
  7821. } else {
  7822. upb_sink_putstring(&p->top->sink, sel, p->accumulated, p->accumulated_len, NULL);
  7823. }
  7824. p->accumulated = NULL;
  7825. } else if (p->top->f &&
  7826. upb_fielddef_type(p->top->f) == UPB_TYPE_ENUM &&
  7827. !is_num) {
  7828. // Enum case: resolve enum symbolic name to integer value.
  7829. const upb_enumdef *enumdef =
  7830. (const upb_enumdef*)upb_fielddef_subdef(p->top->f);
  7831. int32_t int_val = 0;
  7832. if (upb_enumdef_ntoi(enumdef, p->accumulated, p->accumulated_len,
  7833. &int_val)) {
  7834. upb_selector_t sel = parser_getsel(p);
  7835. upb_sink_putint32(&p->top->sink, sel, int_val);
  7836. } else {
  7837. upb_status_seterrmsg(p->status, "Enum value name unknown");
  7838. return false;
  7839. }
  7840. p->accumulated = NULL;
  7841. }
  7842. return true;
  7843. }
  7844. static bool start_stringval(upb_json_parser *p) {
  7845. assert(p->top->f);
  7846. if (upb_fielddef_isstring(p->top->f)) {
  7847. if (!check_stack(p)) return false;
  7848. // Start a new parser frame: parser frames correspond one-to-one with
  7849. // handler frames, and string events occur in a sub-frame.
  7850. upb_jsonparser_frame *inner = p->top + 1;
  7851. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  7852. upb_sink_startstr(&p->top->sink, sel, 0, &inner->sink);
  7853. inner->m = p->top->m;
  7854. inner->f = p->top->f;
  7855. p->top = inner;
  7856. return true;
  7857. } else if (upb_fielddef_type(p->top->f) == UPB_TYPE_ENUM) {
  7858. // Do nothing -- symbolic enum names in quotes remain in the
  7859. // current parser frame.
  7860. return true;
  7861. } else {
  7862. upb_status_seterrf(p->status,
  7863. "String specified for non-string/non-enum field: %s",
  7864. upb_fielddef_name(p->top->f));
  7865. return false;
  7866. }
  7867. }
  7868. static void end_stringval(upb_json_parser *p) {
  7869. if (upb_fielddef_isstring(p->top->f)) {
  7870. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  7871. upb_sink_endstr(&p->top->sink, sel);
  7872. p->top--;
  7873. }
  7874. }
  7875. static void start_number(upb_json_parser *p, const char *ptr) {
  7876. start_text(p, ptr);
  7877. assert(p->accumulated == NULL);
  7878. }
  7879. static void end_number(upb_json_parser *p, const char *ptr) {
  7880. end_text(p, ptr, true);
  7881. const char *myend = p->accumulated + p->accumulated_len;
  7882. char *end;
  7883. switch (upb_fielddef_type(p->top->f)) {
  7884. case UPB_TYPE_ENUM:
  7885. case UPB_TYPE_INT32: {
  7886. long val = strtol(p->accumulated, &end, 0);
  7887. if (val > INT32_MAX || val < INT32_MIN || errno == ERANGE || end != myend)
  7888. assert(false);
  7889. else
  7890. upb_sink_putint32(&p->top->sink, parser_getsel(p), val);
  7891. break;
  7892. }
  7893. case UPB_TYPE_INT64: {
  7894. long long val = strtoll(p->accumulated, &end, 0);
  7895. if (val > INT64_MAX || val < INT64_MIN || errno == ERANGE || end != myend)
  7896. assert(false);
  7897. else
  7898. upb_sink_putint64(&p->top->sink, parser_getsel(p), val);
  7899. break;
  7900. }
  7901. case UPB_TYPE_UINT32: {
  7902. unsigned long val = strtoul(p->accumulated, &end, 0);
  7903. if (val > UINT32_MAX || errno == ERANGE || end != myend)
  7904. assert(false);
  7905. else
  7906. upb_sink_putuint32(&p->top->sink, parser_getsel(p), val);
  7907. break;
  7908. }
  7909. case UPB_TYPE_UINT64: {
  7910. unsigned long long val = strtoull(p->accumulated, &end, 0);
  7911. if (val > UINT64_MAX || errno == ERANGE || end != myend)
  7912. assert(false);
  7913. else
  7914. upb_sink_putuint64(&p->top->sink, parser_getsel(p), val);
  7915. break;
  7916. }
  7917. case UPB_TYPE_DOUBLE: {
  7918. double val = strtod(p->accumulated, &end);
  7919. if (errno == ERANGE || end != myend)
  7920. assert(false);
  7921. else
  7922. upb_sink_putdouble(&p->top->sink, parser_getsel(p), val);
  7923. break;
  7924. }
  7925. case UPB_TYPE_FLOAT: {
  7926. float val = strtof(p->accumulated, &end);
  7927. if (errno == ERANGE || end != myend)
  7928. assert(false);
  7929. else
  7930. upb_sink_putfloat(&p->top->sink, parser_getsel(p), val);
  7931. break;
  7932. }
  7933. default:
  7934. assert(false);
  7935. }
  7936. p->accumulated = NULL;
  7937. }
  7938. static char escape_char(char in) {
  7939. switch (in) {
  7940. case 'r': return '\r';
  7941. case 't': return '\t';
  7942. case 'n': return '\n';
  7943. case 'f': return '\f';
  7944. case 'b': return '\b';
  7945. case '/': return '/';
  7946. case '"': return '"';
  7947. case '\\': return '\\';
  7948. default:
  7949. assert(0);
  7950. return 'x';
  7951. }
  7952. }
  7953. static void escape(upb_json_parser *p, const char *ptr) {
  7954. char ch = escape_char(*ptr);
  7955. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
  7956. upb_sink_putstring(&p->top->sink, sel, &ch, 1, NULL);
  7957. }
  7958. static uint8_t hexdigit(char ch) {
  7959. if (ch >= '0' && ch <= '9') {
  7960. return ch - '0';
  7961. } else if (ch >= 'a' && ch <= 'f') {
  7962. return ch - 'a' + 10;
  7963. } else {
  7964. assert(ch >= 'A' && ch <= 'F');
  7965. return ch - 'A' + 10;
  7966. }
  7967. }
  7968. static void start_hex(upb_json_parser *p, const char *ptr) {
  7969. start_text(p, ptr);
  7970. }
  7971. static void hex(upb_json_parser *p, const char *end) {
  7972. const char *start = p->text_begin;
  7973. UPB_ASSERT_VAR(end, end - start == 4);
  7974. uint16_t codepoint =
  7975. (hexdigit(start[0]) << 12) |
  7976. (hexdigit(start[1]) << 8) |
  7977. (hexdigit(start[2]) << 4) |
  7978. hexdigit(start[3]);
  7979. // emit the codepoint as UTF-8.
  7980. char utf8[3]; // support \u0000 -- \uFFFF -- need only three bytes.
  7981. int length = 0;
  7982. if (codepoint <= 0x7F) {
  7983. utf8[0] = codepoint;
  7984. length = 1;
  7985. } else if (codepoint <= 0x07FF) {
  7986. utf8[1] = (codepoint & 0x3F) | 0x80;
  7987. codepoint >>= 6;
  7988. utf8[0] = (codepoint & 0x1F) | 0xC0;
  7989. length = 2;
  7990. } else /* codepoint <= 0xFFFF */ {
  7991. utf8[2] = (codepoint & 0x3F) | 0x80;
  7992. codepoint >>= 6;
  7993. utf8[1] = (codepoint & 0x3F) | 0x80;
  7994. codepoint >>= 6;
  7995. utf8[0] = (codepoint & 0x0F) | 0xE0;
  7996. length = 3;
  7997. }
  7998. // TODO(haberman): Handle high surrogates: if codepoint is a high surrogate
  7999. // we have to wait for the next escape to get the full code point).
  8000. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
  8001. upb_sink_putstring(&p->top->sink, sel, utf8, length, NULL);
  8002. }
  8003. #define CHECK_RETURN_TOP(x) if (!(x)) goto error
  8004. // What follows is the Ragel parser itself. The language is specified in Ragel
  8005. // and the actions call our C functions above.
  8006. #line 596 "upb/json/parser.rl"
  8007. #line 514 "upb/json/parser.c"
  8008. static const char _json_actions[] = {
  8009. 0, 1, 0, 1, 2, 1, 3, 1,
  8010. 4, 1, 5, 1, 6, 1, 7, 1,
  8011. 9, 1, 11, 1, 12, 1, 13, 1,
  8012. 14, 1, 15, 1, 16, 1, 24, 1,
  8013. 26, 2, 3, 7, 2, 5, 2, 2,
  8014. 5, 7, 2, 10, 8, 2, 12, 14,
  8015. 2, 13, 14, 2, 17, 1, 2, 18,
  8016. 26, 2, 19, 8, 2, 20, 26, 2,
  8017. 21, 26, 2, 22, 26, 2, 23, 26,
  8018. 2, 25, 26, 3, 13, 10, 8
  8019. };
  8020. static const unsigned char _json_key_offsets[] = {
  8021. 0, 0, 4, 9, 14, 18, 22, 27,
  8022. 32, 37, 41, 45, 48, 51, 53, 57,
  8023. 61, 63, 65, 70, 72, 74, 83, 89,
  8024. 95, 101, 107, 109, 118, 118, 118, 123,
  8025. 128, 133, 133, 134, 135, 136, 137, 137,
  8026. 138, 139, 140, 140, 141, 142, 143, 143,
  8027. 148, 153, 157, 161, 166, 171, 176, 180,
  8028. 180, 183, 183, 183
  8029. };
  8030. static const char _json_trans_keys[] = {
  8031. 32, 123, 9, 13, 32, 34, 125, 9,
  8032. 13, 32, 34, 125, 9, 13, 32, 58,
  8033. 9, 13, 32, 58, 9, 13, 32, 93,
  8034. 125, 9, 13, 32, 44, 125, 9, 13,
  8035. 32, 44, 125, 9, 13, 32, 34, 9,
  8036. 13, 45, 48, 49, 57, 48, 49, 57,
  8037. 46, 69, 101, 48, 57, 69, 101, 48,
  8038. 57, 43, 45, 48, 57, 48, 57, 48,
  8039. 57, 46, 69, 101, 48, 57, 34, 92,
  8040. 34, 92, 34, 47, 92, 98, 102, 110,
  8041. 114, 116, 117, 48, 57, 65, 70, 97,
  8042. 102, 48, 57, 65, 70, 97, 102, 48,
  8043. 57, 65, 70, 97, 102, 48, 57, 65,
  8044. 70, 97, 102, 34, 92, 34, 45, 91,
  8045. 102, 110, 116, 123, 48, 57, 32, 93,
  8046. 125, 9, 13, 32, 44, 93, 9, 13,
  8047. 32, 93, 125, 9, 13, 97, 108, 115,
  8048. 101, 117, 108, 108, 114, 117, 101, 32,
  8049. 34, 125, 9, 13, 32, 34, 125, 9,
  8050. 13, 32, 58, 9, 13, 32, 58, 9,
  8051. 13, 32, 93, 125, 9, 13, 32, 44,
  8052. 125, 9, 13, 32, 44, 125, 9, 13,
  8053. 32, 34, 9, 13, 32, 9, 13, 0
  8054. };
  8055. static const char _json_single_lengths[] = {
  8056. 0, 2, 3, 3, 2, 2, 3, 3,
  8057. 3, 2, 2, 1, 3, 0, 2, 2,
  8058. 0, 0, 3, 2, 2, 9, 0, 0,
  8059. 0, 0, 2, 7, 0, 0, 3, 3,
  8060. 3, 0, 1, 1, 1, 1, 0, 1,
  8061. 1, 1, 0, 1, 1, 1, 0, 3,
  8062. 3, 2, 2, 3, 3, 3, 2, 0,
  8063. 1, 0, 0, 0
  8064. };
  8065. static const char _json_range_lengths[] = {
  8066. 0, 1, 1, 1, 1, 1, 1, 1,
  8067. 1, 1, 1, 1, 0, 1, 1, 1,
  8068. 1, 1, 1, 0, 0, 0, 3, 3,
  8069. 3, 3, 0, 1, 0, 0, 1, 1,
  8070. 1, 0, 0, 0, 0, 0, 0, 0,
  8071. 0, 0, 0, 0, 0, 0, 0, 1,
  8072. 1, 1, 1, 1, 1, 1, 1, 0,
  8073. 1, 0, 0, 0
  8074. };
  8075. static const short _json_index_offsets[] = {
  8076. 0, 0, 4, 9, 14, 18, 22, 27,
  8077. 32, 37, 41, 45, 48, 52, 54, 58,
  8078. 62, 64, 66, 71, 74, 77, 87, 91,
  8079. 95, 99, 103, 106, 115, 116, 117, 122,
  8080. 127, 132, 133, 135, 137, 139, 141, 142,
  8081. 144, 146, 148, 149, 151, 153, 155, 156,
  8082. 161, 166, 170, 174, 179, 184, 189, 193,
  8083. 194, 197, 198, 199
  8084. };
  8085. static const char _json_indicies[] = {
  8086. 0, 2, 0, 1, 3, 4, 5, 3,
  8087. 1, 6, 7, 8, 6, 1, 9, 10,
  8088. 9, 1, 11, 12, 11, 1, 12, 1,
  8089. 1, 12, 13, 14, 15, 16, 14, 1,
  8090. 17, 18, 8, 17, 1, 18, 7, 18,
  8091. 1, 19, 20, 21, 1, 20, 21, 1,
  8092. 23, 24, 24, 22, 25, 1, 24, 24,
  8093. 25, 22, 26, 26, 27, 1, 27, 1,
  8094. 27, 22, 23, 24, 24, 21, 22, 29,
  8095. 30, 28, 32, 33, 31, 34, 34, 34,
  8096. 34, 34, 34, 34, 34, 35, 1, 36,
  8097. 36, 36, 1, 37, 37, 37, 1, 38,
  8098. 38, 38, 1, 39, 39, 39, 1, 41,
  8099. 42, 40, 43, 44, 45, 46, 47, 48,
  8100. 49, 44, 1, 50, 51, 53, 54, 1,
  8101. 53, 52, 55, 56, 54, 55, 1, 56,
  8102. 1, 1, 56, 52, 57, 58, 1, 59,
  8103. 1, 60, 1, 61, 1, 62, 63, 1,
  8104. 64, 1, 65, 1, 66, 67, 1, 68,
  8105. 1, 69, 1, 70, 71, 72, 73, 71,
  8106. 1, 74, 75, 76, 74, 1, 77, 78,
  8107. 77, 1, 79, 80, 79, 1, 80, 1,
  8108. 1, 80, 81, 82, 83, 84, 82, 1,
  8109. 85, 86, 76, 85, 1, 86, 75, 86,
  8110. 1, 87, 88, 88, 1, 1, 1, 1,
  8111. 0
  8112. };
  8113. static const char _json_trans_targs[] = {
  8114. 1, 0, 2, 3, 4, 56, 3, 4,
  8115. 56, 5, 6, 5, 6, 7, 8, 9,
  8116. 56, 8, 9, 11, 12, 18, 57, 13,
  8117. 15, 14, 16, 17, 20, 58, 21, 20,
  8118. 58, 21, 19, 22, 23, 24, 25, 26,
  8119. 20, 58, 21, 28, 29, 30, 34, 39,
  8120. 43, 47, 59, 59, 31, 30, 33, 31,
  8121. 32, 59, 35, 36, 37, 38, 59, 40,
  8122. 41, 42, 59, 44, 45, 46, 59, 48,
  8123. 49, 55, 48, 49, 55, 50, 51, 50,
  8124. 51, 52, 53, 54, 55, 53, 54, 59,
  8125. 56
  8126. };
  8127. static const char _json_trans_actions[] = {
  8128. 0, 0, 0, 21, 75, 48, 0, 42,
  8129. 23, 17, 17, 0, 0, 15, 19, 19,
  8130. 45, 0, 0, 0, 0, 0, 1, 0,
  8131. 0, 0, 0, 0, 3, 13, 0, 0,
  8132. 33, 5, 11, 0, 7, 0, 0, 0,
  8133. 36, 39, 9, 57, 51, 25, 0, 0,
  8134. 0, 29, 60, 54, 15, 0, 27, 0,
  8135. 0, 31, 0, 0, 0, 0, 66, 0,
  8136. 0, 0, 69, 0, 0, 0, 63, 21,
  8137. 75, 48, 0, 42, 23, 17, 17, 0,
  8138. 0, 15, 19, 19, 45, 0, 0, 72,
  8139. 0
  8140. };
  8141. static const int json_start = 1;
  8142. static const int json_first_final = 56;
  8143. static const int json_error = 0;
  8144. static const int json_en_number_machine = 10;
  8145. static const int json_en_string_machine = 19;
  8146. static const int json_en_value_machine = 27;
  8147. static const int json_en_main = 1;
  8148. #line 599 "upb/json/parser.rl"
  8149. size_t parse(void *closure, const void *hd, const char *buf, size_t size,
  8150. const upb_bufhandle *handle) {
  8151. UPB_UNUSED(hd);
  8152. UPB_UNUSED(handle);
  8153. upb_json_parser *parser = closure;
  8154. // Variables used by Ragel's generated code.
  8155. int cs = parser->current_state;
  8156. int *stack = parser->parser_stack;
  8157. int top = parser->parser_top;
  8158. const char *p = buf;
  8159. const char *pe = buf + size;
  8160. #line 684 "upb/json/parser.c"
  8161. {
  8162. int _klen;
  8163. unsigned int _trans;
  8164. const char *_acts;
  8165. unsigned int _nacts;
  8166. const char *_keys;
  8167. if ( p == pe )
  8168. goto _test_eof;
  8169. if ( cs == 0 )
  8170. goto _out;
  8171. _resume:
  8172. _keys = _json_trans_keys + _json_key_offsets[cs];
  8173. _trans = _json_index_offsets[cs];
  8174. _klen = _json_single_lengths[cs];
  8175. if ( _klen > 0 ) {
  8176. const char *_lower = _keys;
  8177. const char *_mid;
  8178. const char *_upper = _keys + _klen - 1;
  8179. while (1) {
  8180. if ( _upper < _lower )
  8181. break;
  8182. _mid = _lower + ((_upper-_lower) >> 1);
  8183. if ( (*p) < *_mid )
  8184. _upper = _mid - 1;
  8185. else if ( (*p) > *_mid )
  8186. _lower = _mid + 1;
  8187. else {
  8188. _trans += (unsigned int)(_mid - _keys);
  8189. goto _match;
  8190. }
  8191. }
  8192. _keys += _klen;
  8193. _trans += _klen;
  8194. }
  8195. _klen = _json_range_lengths[cs];
  8196. if ( _klen > 0 ) {
  8197. const char *_lower = _keys;
  8198. const char *_mid;
  8199. const char *_upper = _keys + (_klen<<1) - 2;
  8200. while (1) {
  8201. if ( _upper < _lower )
  8202. break;
  8203. _mid = _lower + (((_upper-_lower) >> 1) & ~1);
  8204. if ( (*p) < _mid[0] )
  8205. _upper = _mid - 2;
  8206. else if ( (*p) > _mid[1] )
  8207. _lower = _mid + 2;
  8208. else {
  8209. _trans += (unsigned int)((_mid - _keys)>>1);
  8210. goto _match;
  8211. }
  8212. }
  8213. _trans += _klen;
  8214. }
  8215. _match:
  8216. _trans = _json_indicies[_trans];
  8217. cs = _json_trans_targs[_trans];
  8218. if ( _json_trans_actions[_trans] == 0 )
  8219. goto _again;
  8220. _acts = _json_actions + _json_trans_actions[_trans];
  8221. _nacts = (unsigned int) *_acts++;
  8222. while ( _nacts-- > 0 )
  8223. {
  8224. switch ( *_acts++ )
  8225. {
  8226. case 0:
  8227. #line 517 "upb/json/parser.rl"
  8228. { p--; {cs = stack[--top]; goto _again;} }
  8229. break;
  8230. case 1:
  8231. #line 518 "upb/json/parser.rl"
  8232. { p--; {stack[top++] = cs; cs = 10; goto _again;} }
  8233. break;
  8234. case 2:
  8235. #line 522 "upb/json/parser.rl"
  8236. { start_text(parser, p); }
  8237. break;
  8238. case 3:
  8239. #line 523 "upb/json/parser.rl"
  8240. { CHECK_RETURN_TOP(end_text(parser, p, false)); }
  8241. break;
  8242. case 4:
  8243. #line 529 "upb/json/parser.rl"
  8244. { start_hex(parser, p); }
  8245. break;
  8246. case 5:
  8247. #line 530 "upb/json/parser.rl"
  8248. { hex(parser, p); }
  8249. break;
  8250. case 6:
  8251. #line 536 "upb/json/parser.rl"
  8252. { escape(parser, p); }
  8253. break;
  8254. case 7:
  8255. #line 539 "upb/json/parser.rl"
  8256. { {cs = stack[--top]; goto _again;} }
  8257. break;
  8258. case 8:
  8259. #line 540 "upb/json/parser.rl"
  8260. { {stack[top++] = cs; cs = 19; goto _again;} }
  8261. break;
  8262. case 9:
  8263. #line 542 "upb/json/parser.rl"
  8264. { p--; {stack[top++] = cs; cs = 27; goto _again;} }
  8265. break;
  8266. case 10:
  8267. #line 547 "upb/json/parser.rl"
  8268. { start_member(parser); }
  8269. break;
  8270. case 11:
  8271. #line 548 "upb/json/parser.rl"
  8272. { CHECK_RETURN_TOP(end_member(parser)); }
  8273. break;
  8274. case 12:
  8275. #line 551 "upb/json/parser.rl"
  8276. { clear_member(parser); }
  8277. break;
  8278. case 13:
  8279. #line 557 "upb/json/parser.rl"
  8280. { start_object(parser); }
  8281. break;
  8282. case 14:
  8283. #line 560 "upb/json/parser.rl"
  8284. { end_object(parser); }
  8285. break;
  8286. case 15:
  8287. #line 566 "upb/json/parser.rl"
  8288. { CHECK_RETURN_TOP(start_array(parser)); }
  8289. break;
  8290. case 16:
  8291. #line 570 "upb/json/parser.rl"
  8292. { end_array(parser); }
  8293. break;
  8294. case 17:
  8295. #line 575 "upb/json/parser.rl"
  8296. { start_number(parser, p); }
  8297. break;
  8298. case 18:
  8299. #line 576 "upb/json/parser.rl"
  8300. { end_number(parser, p); }
  8301. break;
  8302. case 19:
  8303. #line 578 "upb/json/parser.rl"
  8304. { CHECK_RETURN_TOP(start_stringval(parser)); }
  8305. break;
  8306. case 20:
  8307. #line 579 "upb/json/parser.rl"
  8308. { end_stringval(parser); }
  8309. break;
  8310. case 21:
  8311. #line 581 "upb/json/parser.rl"
  8312. { CHECK_RETURN_TOP(parser_putbool(parser, true)); }
  8313. break;
  8314. case 22:
  8315. #line 583 "upb/json/parser.rl"
  8316. { CHECK_RETURN_TOP(parser_putbool(parser, false)); }
  8317. break;
  8318. case 23:
  8319. #line 585 "upb/json/parser.rl"
  8320. { /* null value */ }
  8321. break;
  8322. case 24:
  8323. #line 587 "upb/json/parser.rl"
  8324. { CHECK_RETURN_TOP(start_subobject(parser)); }
  8325. break;
  8326. case 25:
  8327. #line 588 "upb/json/parser.rl"
  8328. { end_subobject(parser); }
  8329. break;
  8330. case 26:
  8331. #line 593 "upb/json/parser.rl"
  8332. { p--; {cs = stack[--top]; goto _again;} }
  8333. break;
  8334. #line 866 "upb/json/parser.c"
  8335. }
  8336. }
  8337. _again:
  8338. if ( cs == 0 )
  8339. goto _out;
  8340. if ( ++p != pe )
  8341. goto _resume;
  8342. _test_eof: {}
  8343. _out: {}
  8344. }
  8345. #line 615 "upb/json/parser.rl"
  8346. if (p != pe) {
  8347. upb_status_seterrf(parser->status, "Parse error at %s\n", p);
  8348. }
  8349. error:
  8350. // Save parsing state back to parser.
  8351. parser->current_state = cs;
  8352. parser->parser_top = top;
  8353. return p - buf;
  8354. }
  8355. bool end(void *closure, const void *hd) {
  8356. UPB_UNUSED(closure);
  8357. UPB_UNUSED(hd);
  8358. return true;
  8359. }
  8360. void upb_json_parser_init(upb_json_parser *p, upb_status *status) {
  8361. p->limit = p->stack + UPB_JSON_MAX_DEPTH;
  8362. upb_byteshandler_init(&p->input_handler_);
  8363. upb_byteshandler_setstring(&p->input_handler_, parse, NULL);
  8364. upb_byteshandler_setendstr(&p->input_handler_, end, NULL);
  8365. upb_bytessink_reset(&p->input_, &p->input_handler_, p);
  8366. p->status = status;
  8367. }
  8368. void upb_json_parser_uninit(upb_json_parser *p) {
  8369. upb_byteshandler_uninit(&p->input_handler_);
  8370. }
  8371. void upb_json_parser_reset(upb_json_parser *p) {
  8372. p->top = p->stack;
  8373. p->top->f = NULL;
  8374. int cs;
  8375. int top;
  8376. // Emit Ragel initialization of the parser.
  8377. #line 920 "upb/json/parser.c"
  8378. {
  8379. cs = json_start;
  8380. top = 0;
  8381. }
  8382. #line 655 "upb/json/parser.rl"
  8383. p->current_state = cs;
  8384. p->parser_top = top;
  8385. p->text_begin = NULL;
  8386. p->accumulated = NULL;
  8387. p->accumulated_len = 0;
  8388. }
  8389. void upb_json_parser_resetoutput(upb_json_parser *p, upb_sink *sink) {
  8390. upb_json_parser_reset(p);
  8391. upb_sink_reset(&p->top->sink, sink->handlers, sink->closure);
  8392. p->top->m = upb_handlers_msgdef(sink->handlers);
  8393. p->accumulated = NULL;
  8394. }
  8395. upb_bytessink *upb_json_parser_input(upb_json_parser *p) {
  8396. return &p->input_;
  8397. }
  8398. /*
  8399. * upb - a minimalist implementation of protocol buffers.
  8400. *
  8401. * Copyright (c) 2014 Google Inc. See LICENSE for details.
  8402. * Author: Josh Haberman <jhaberman@gmail.com>
  8403. *
  8404. * This currently uses snprintf() to format primitives, and could be optimized
  8405. * further.
  8406. */
  8407. #include <stdlib.h>
  8408. #include <stdio.h>
  8409. #include <string.h>
  8410. #include <stdint.h>
  8411. // StringPiece; a pointer plus a length.
  8412. typedef struct {
  8413. const char *ptr;
  8414. size_t len;
  8415. } strpc;
  8416. strpc *newstrpc(upb_handlers *h, const upb_fielddef *f) {
  8417. strpc *ret = malloc(sizeof(*ret));
  8418. ret->ptr = upb_fielddef_name(f);
  8419. ret->len = strlen(ret->ptr);
  8420. upb_handlers_addcleanup(h, ret, free);
  8421. return ret;
  8422. }
  8423. // ------------ JSON string printing: values, maps, arrays --------------------
  8424. static void print_data(
  8425. upb_json_printer *p, const char *buf, unsigned int len) {
  8426. // TODO: Will need to change if we support pushback from the sink.
  8427. size_t n = upb_bytessink_putbuf(p->output_, p->subc_, buf, len, NULL);
  8428. UPB_ASSERT_VAR(n, n == len);
  8429. }
  8430. static void print_comma(upb_json_printer *p) {
  8431. if (!p->first_elem_[p->depth_]) {
  8432. print_data(p, ",", 1);
  8433. }
  8434. p->first_elem_[p->depth_] = false;
  8435. }
  8436. // Helpers that print properly formatted elements to the JSON output stream.
  8437. // Used for escaping control chars in strings.
  8438. static const char kControlCharLimit = 0x20;
  8439. static inline bool is_json_escaped(char c) {
  8440. // See RFC 4627.
  8441. unsigned char uc = (unsigned char)c;
  8442. return uc < kControlCharLimit || uc == '"' || uc == '\\';
  8443. }
  8444. static inline char* json_nice_escape(char c) {
  8445. switch (c) {
  8446. case '"': return "\\\"";
  8447. case '\\': return "\\\\";
  8448. case '\b': return "\\b";
  8449. case '\f': return "\\f";
  8450. case '\n': return "\\n";
  8451. case '\r': return "\\r";
  8452. case '\t': return "\\t";
  8453. default: return NULL;
  8454. }
  8455. }
  8456. // Write a properly escaped string chunk. The surrounding quotes are *not*
  8457. // printed; this is so that the caller has the option of emitting the string
  8458. // content in chunks.
  8459. static void putstring(upb_json_printer *p, const char *buf, unsigned int len) {
  8460. const char* unescaped_run = NULL;
  8461. for (unsigned int i = 0; i < len; i++) {
  8462. char c = buf[i];
  8463. // Handle escaping.
  8464. if (is_json_escaped(c)) {
  8465. // Use a "nice" escape, like \n, if one exists for this character.
  8466. const char* escape = json_nice_escape(c);
  8467. // If we don't have a specific 'nice' escape code, use a \uXXXX-style
  8468. // escape.
  8469. char escape_buf[8];
  8470. if (!escape) {
  8471. unsigned char byte = (unsigned char)c;
  8472. snprintf(escape_buf, sizeof(escape_buf), "\\u%04x", (int)byte);
  8473. escape = escape_buf;
  8474. }
  8475. // N.B. that we assume that the input encoding is equal to the output
  8476. // encoding (both UTF-8 for now), so for chars >= 0x20 and != \, ", we
  8477. // can simply pass the bytes through.
  8478. // If there's a current run of unescaped chars, print that run first.
  8479. if (unescaped_run) {
  8480. print_data(p, unescaped_run, &buf[i] - unescaped_run);
  8481. unescaped_run = NULL;
  8482. }
  8483. // Then print the escape code.
  8484. print_data(p, escape, strlen(escape));
  8485. } else {
  8486. // Add to the current unescaped run of characters.
  8487. if (unescaped_run == NULL) {
  8488. unescaped_run = &buf[i];
  8489. }
  8490. }
  8491. }
  8492. // If the string ended in a run of unescaped characters, print that last run.
  8493. if (unescaped_run) {
  8494. print_data(p, unescaped_run, &buf[len] - unescaped_run);
  8495. }
  8496. }
  8497. #define CHKLENGTH(x) if (!(x)) return -1;
  8498. // Helpers that format floating point values according to our custom formats.
  8499. // Right now we use %.8g and %.17g for float/double, respectively, to match
  8500. // proto2::util::JsonFormat's defaults. May want to change this later.
  8501. static size_t fmt_double(double val, char* buf, size_t length) {
  8502. size_t n = snprintf(buf, length, "%.17g", val);
  8503. CHKLENGTH(n > 0 && n < length);
  8504. return n;
  8505. }
  8506. static size_t fmt_float(float val, char* buf, size_t length) {
  8507. size_t n = snprintf(buf, length, "%.8g", val);
  8508. CHKLENGTH(n > 0 && n < length);
  8509. return n;
  8510. }
  8511. static size_t fmt_bool(bool val, char* buf, size_t length) {
  8512. size_t n = snprintf(buf, length, "%s", (val ? "true" : "false"));
  8513. CHKLENGTH(n > 0 && n < length);
  8514. return n;
  8515. }
  8516. static size_t fmt_int64(long val, char* buf, size_t length) {
  8517. size_t n = snprintf(buf, length, "%ld", val);
  8518. CHKLENGTH(n > 0 && n < length);
  8519. return n;
  8520. }
  8521. static size_t fmt_uint64(unsigned long long val, char* buf, size_t length) {
  8522. size_t n = snprintf(buf, length, "%llu", val);
  8523. CHKLENGTH(n > 0 && n < length);
  8524. return n;
  8525. }
  8526. // Print a map key given a field name. Called by scalar field handlers and by
  8527. // startseq for repeated fields.
  8528. static bool putkey(void *closure, const void *handler_data) {
  8529. upb_json_printer *p = closure;
  8530. const strpc *key = handler_data;
  8531. print_comma(p);
  8532. print_data(p, "\"", 1);
  8533. putstring(p, key->ptr, key->len);
  8534. print_data(p, "\":", 2);
  8535. return true;
  8536. }
  8537. #define CHKFMT(val) if ((val) == -1) return false;
  8538. #define CHK(val) if (!(val)) return false;
  8539. #define TYPE_HANDLERS(type, fmt_func) \
  8540. static bool put##type(void *closure, const void *handler_data, type val) { \
  8541. upb_json_printer *p = closure; \
  8542. UPB_UNUSED(handler_data); \
  8543. char data[64]; \
  8544. size_t length = fmt_func(val, data, sizeof(data)); \
  8545. CHKFMT(length); \
  8546. print_data(p, data, length); \
  8547. return true; \
  8548. } \
  8549. static bool scalar_##type(void *closure, const void *handler_data, \
  8550. type val) { \
  8551. CHK(putkey(closure, handler_data)); \
  8552. CHK(put##type(closure, handler_data, val)); \
  8553. return true; \
  8554. } \
  8555. static bool repeated_##type(void *closure, const void *handler_data, \
  8556. type val) { \
  8557. upb_json_printer *p = closure; \
  8558. print_comma(p); \
  8559. CHK(put##type(closure, handler_data, val)); \
  8560. return true; \
  8561. }
  8562. TYPE_HANDLERS(double, fmt_double);
  8563. TYPE_HANDLERS(float, fmt_float);
  8564. TYPE_HANDLERS(bool, fmt_bool);
  8565. TYPE_HANDLERS(int32_t, fmt_int64);
  8566. TYPE_HANDLERS(uint32_t, fmt_int64);
  8567. TYPE_HANDLERS(int64_t, fmt_int64);
  8568. TYPE_HANDLERS(uint64_t, fmt_uint64);
  8569. #undef TYPE_HANDLERS
  8570. typedef struct {
  8571. void *keyname;
  8572. const upb_enumdef *enumdef;
  8573. } EnumHandlerData;
  8574. static bool scalar_enum(void *closure, const void *handler_data,
  8575. int32_t val) {
  8576. const EnumHandlerData *hd = handler_data;
  8577. upb_json_printer *p = closure;
  8578. CHK(putkey(closure, hd->keyname));
  8579. const char *symbolic_name = upb_enumdef_iton(hd->enumdef, val);
  8580. if (symbolic_name) {
  8581. print_data(p, "\"", 1);
  8582. putstring(p, symbolic_name, strlen(symbolic_name));
  8583. print_data(p, "\"", 1);
  8584. } else {
  8585. putint32_t(closure, NULL, val);
  8586. }
  8587. return true;
  8588. }
  8589. static bool repeated_enum(void *closure, const void *handler_data,
  8590. int32_t val) {
  8591. const EnumHandlerData *hd = handler_data;
  8592. upb_json_printer *p = closure;
  8593. print_comma(p);
  8594. const char *symbolic_name = upb_enumdef_iton(hd->enumdef, val);
  8595. if (symbolic_name) {
  8596. print_data(p, "\"", 1);
  8597. putstring(p, symbolic_name, strlen(symbolic_name));
  8598. print_data(p, "\"", 1);
  8599. } else {
  8600. putint32_t(closure, NULL, val);
  8601. }
  8602. return true;
  8603. }
  8604. static void *scalar_startsubmsg(void *closure, const void *handler_data) {
  8605. return putkey(closure, handler_data) ? closure : UPB_BREAK;
  8606. }
  8607. static void *repeated_startsubmsg(void *closure, const void *handler_data) {
  8608. UPB_UNUSED(handler_data);
  8609. upb_json_printer *p = closure;
  8610. print_comma(p);
  8611. return closure;
  8612. }
  8613. static bool startmap(void *closure, const void *handler_data) {
  8614. UPB_UNUSED(handler_data);
  8615. upb_json_printer *p = closure;
  8616. if (p->depth_++ == 0) {
  8617. upb_bytessink_start(p->output_, 0, &p->subc_);
  8618. }
  8619. p->first_elem_[p->depth_] = true;
  8620. print_data(p, "{", 1);
  8621. return true;
  8622. }
  8623. static bool endmap(void *closure, const void *handler_data, upb_status *s) {
  8624. UPB_UNUSED(handler_data);
  8625. UPB_UNUSED(s);
  8626. upb_json_printer *p = closure;
  8627. if (--p->depth_ == 0) {
  8628. upb_bytessink_end(p->output_);
  8629. }
  8630. print_data(p, "}", 1);
  8631. return true;
  8632. }
  8633. static void *startseq(void *closure, const void *handler_data) {
  8634. upb_json_printer *p = closure;
  8635. CHK(putkey(closure, handler_data));
  8636. p->depth_++;
  8637. p->first_elem_[p->depth_] = true;
  8638. print_data(p, "[", 1);
  8639. return closure;
  8640. }
  8641. static bool endseq(void *closure, const void *handler_data) {
  8642. UPB_UNUSED(handler_data);
  8643. upb_json_printer *p = closure;
  8644. print_data(p, "]", 1);
  8645. p->depth_--;
  8646. return true;
  8647. }
  8648. static size_t putstr(void *closure, const void *handler_data, const char *str,
  8649. size_t len, const upb_bufhandle *handle) {
  8650. UPB_UNUSED(handler_data);
  8651. UPB_UNUSED(handle);
  8652. upb_json_printer *p = closure;
  8653. putstring(p, str, len);
  8654. return len;
  8655. }
  8656. // This has to Base64 encode the bytes, because JSON has no "bytes" type.
  8657. static size_t putbytes(void *closure, const void *handler_data, const char *str,
  8658. size_t len, const upb_bufhandle *handle) {
  8659. UPB_UNUSED(handler_data);
  8660. UPB_UNUSED(handle);
  8661. upb_json_printer *p = closure;
  8662. // This is the regular base64, not the "web-safe" version.
  8663. static const char base64[] =
  8664. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  8665. // Base64-encode.
  8666. char data[16000];
  8667. const char *limit = data + sizeof(data);
  8668. const unsigned char *from = (const unsigned char*)str;
  8669. char *to = data;
  8670. size_t remaining = len;
  8671. while (remaining > 2) {
  8672. // TODO(haberman): handle encoded lengths > sizeof(data)
  8673. UPB_ASSERT_VAR(limit, (limit - to) >= 4);
  8674. to[0] = base64[from[0] >> 2];
  8675. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  8676. to[2] = base64[((from[1] & 0xf) << 2) | (from[2] >> 6)];
  8677. to[3] = base64[from[2] & 0x3f];
  8678. remaining -= 3;
  8679. to += 4;
  8680. from += 3;
  8681. }
  8682. switch (remaining) {
  8683. case 2:
  8684. to[0] = base64[from[0] >> 2];
  8685. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  8686. to[2] = base64[(from[1] & 0xf) << 2];
  8687. to[3] = '=';
  8688. to += 4;
  8689. from += 2;
  8690. break;
  8691. case 1:
  8692. to[0] = base64[from[0] >> 2];
  8693. to[1] = base64[((from[0] & 0x3) << 4)];
  8694. to[2] = '=';
  8695. to[3] = '=';
  8696. to += 4;
  8697. from += 1;
  8698. break;
  8699. }
  8700. size_t bytes = to - data;
  8701. print_data(p, "\"", 1);
  8702. putstring(p, data, bytes);
  8703. print_data(p, "\"", 1);
  8704. return len;
  8705. }
  8706. static void *scalar_startstr(void *closure, const void *handler_data,
  8707. size_t size_hint) {
  8708. UPB_UNUSED(handler_data);
  8709. UPB_UNUSED(size_hint);
  8710. upb_json_printer *p = closure;
  8711. CHK(putkey(closure, handler_data));
  8712. print_data(p, "\"", 1);
  8713. return p;
  8714. }
  8715. static size_t scalar_str(void *closure, const void *handler_data,
  8716. const char *str, size_t len,
  8717. const upb_bufhandle *handle) {
  8718. CHK(putstr(closure, handler_data, str, len, handle));
  8719. return len;
  8720. }
  8721. static bool scalar_endstr(void *closure, const void *handler_data) {
  8722. UPB_UNUSED(handler_data);
  8723. upb_json_printer *p = closure;
  8724. print_data(p, "\"", 1);
  8725. return true;
  8726. }
  8727. static void *repeated_startstr(void *closure, const void *handler_data,
  8728. size_t size_hint) {
  8729. UPB_UNUSED(handler_data);
  8730. UPB_UNUSED(size_hint);
  8731. upb_json_printer *p = closure;
  8732. print_comma(p);
  8733. print_data(p, "\"", 1);
  8734. return p;
  8735. }
  8736. static size_t repeated_str(void *closure, const void *handler_data,
  8737. const char *str, size_t len,
  8738. const upb_bufhandle *handle) {
  8739. CHK(putstr(closure, handler_data, str, len, handle));
  8740. return len;
  8741. }
  8742. static bool repeated_endstr(void *closure, const void *handler_data) {
  8743. UPB_UNUSED(handler_data);
  8744. upb_json_printer *p = closure;
  8745. print_data(p, "\"", 1);
  8746. return true;
  8747. }
  8748. static size_t scalar_bytes(void *closure, const void *handler_data,
  8749. const char *str, size_t len,
  8750. const upb_bufhandle *handle) {
  8751. CHK(putkey(closure, handler_data));
  8752. CHK(putbytes(closure, handler_data, str, len, handle));
  8753. return len;
  8754. }
  8755. static size_t repeated_bytes(void *closure, const void *handler_data,
  8756. const char *str, size_t len,
  8757. const upb_bufhandle *handle) {
  8758. upb_json_printer *p = closure;
  8759. print_comma(p);
  8760. CHK(putbytes(closure, handler_data, str, len, handle));
  8761. return len;
  8762. }
  8763. void printer_sethandlers(const void *closure, upb_handlers *h) {
  8764. UPB_UNUSED(closure);
  8765. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  8766. upb_handlers_setstartmsg(h, startmap, &empty_attr);
  8767. upb_handlers_setendmsg(h, endmap, &empty_attr);
  8768. #define TYPE(type, name, ctype) \
  8769. case type: \
  8770. if (upb_fielddef_isseq(f)) { \
  8771. upb_handlers_set##name(h, f, repeated_##ctype, &empty_attr); \
  8772. } else { \
  8773. upb_handlers_set##name(h, f, scalar_##ctype, &name_attr); \
  8774. } \
  8775. break;
  8776. upb_msg_iter i;
  8777. upb_msg_begin(&i, upb_handlers_msgdef(h));
  8778. for(; !upb_msg_done(&i); upb_msg_next(&i)) {
  8779. const upb_fielddef *f = upb_msg_iter_field(&i);
  8780. upb_handlerattr name_attr = UPB_HANDLERATTR_INITIALIZER;
  8781. upb_handlerattr_sethandlerdata(&name_attr, newstrpc(h, f));
  8782. if (upb_fielddef_isseq(f)) {
  8783. upb_handlers_setstartseq(h, f, startseq, &name_attr);
  8784. upb_handlers_setendseq(h, f, endseq, &empty_attr);
  8785. }
  8786. switch (upb_fielddef_type(f)) {
  8787. TYPE(UPB_TYPE_FLOAT, float, float);
  8788. TYPE(UPB_TYPE_DOUBLE, double, double);
  8789. TYPE(UPB_TYPE_BOOL, bool, bool);
  8790. TYPE(UPB_TYPE_INT32, int32, int32_t);
  8791. TYPE(UPB_TYPE_UINT32, uint32, uint32_t);
  8792. TYPE(UPB_TYPE_INT64, int64, int64_t);
  8793. TYPE(UPB_TYPE_UINT64, uint64, uint64_t);
  8794. case UPB_TYPE_ENUM: {
  8795. // For now, we always emit symbolic names for enums. We may want an
  8796. // option later to control this behavior, but we will wait for a real
  8797. // need first.
  8798. EnumHandlerData *hd = malloc(sizeof(EnumHandlerData));
  8799. hd->enumdef = (const upb_enumdef *)upb_fielddef_subdef(f);
  8800. hd->keyname = newstrpc(h, f);
  8801. upb_handlers_addcleanup(h, hd, free);
  8802. upb_handlerattr enum_attr = UPB_HANDLERATTR_INITIALIZER;
  8803. upb_handlerattr_sethandlerdata(&enum_attr, hd);
  8804. if (upb_fielddef_isseq(f)) {
  8805. upb_handlers_setint32(h, f, repeated_enum, &enum_attr);
  8806. } else {
  8807. upb_handlers_setint32(h, f, scalar_enum, &enum_attr);
  8808. }
  8809. upb_handlerattr_uninit(&enum_attr);
  8810. break;
  8811. }
  8812. case UPB_TYPE_STRING:
  8813. if (upb_fielddef_isseq(f)) {
  8814. upb_handlers_setstartstr(h, f, repeated_startstr, &empty_attr);
  8815. upb_handlers_setstring(h, f, repeated_str, &empty_attr);
  8816. upb_handlers_setendstr(h, f, repeated_endstr, &empty_attr);
  8817. } else {
  8818. upb_handlers_setstartstr(h, f, scalar_startstr, &name_attr);
  8819. upb_handlers_setstring(h, f, scalar_str, &empty_attr);
  8820. upb_handlers_setendstr(h, f, scalar_endstr, &empty_attr);
  8821. }
  8822. break;
  8823. case UPB_TYPE_BYTES:
  8824. // XXX: this doesn't support strings that span buffers yet. The base64
  8825. // encoder will need to be made resumable for this to work properly.
  8826. if (upb_fielddef_isseq(f)) {
  8827. upb_handlers_setstring(h, f, repeated_bytes, &empty_attr);
  8828. } else {
  8829. upb_handlers_setstring(h, f, scalar_bytes, &name_attr);
  8830. }
  8831. break;
  8832. case UPB_TYPE_MESSAGE:
  8833. if (upb_fielddef_isseq(f)) {
  8834. upb_handlers_setstartsubmsg(h, f, repeated_startsubmsg, &name_attr);
  8835. } else {
  8836. upb_handlers_setstartsubmsg(h, f, scalar_startsubmsg, &name_attr);
  8837. }
  8838. break;
  8839. }
  8840. upb_handlerattr_uninit(&name_attr);
  8841. }
  8842. upb_handlerattr_uninit(&empty_attr);
  8843. #undef TYPE
  8844. }
  8845. /* Public API *****************************************************************/
  8846. void upb_json_printer_init(upb_json_printer *p, const upb_handlers *h) {
  8847. p->output_ = NULL;
  8848. p->depth_ = 0;
  8849. upb_sink_reset(&p->input_, h, p);
  8850. }
  8851. void upb_json_printer_uninit(upb_json_printer *p) {
  8852. UPB_UNUSED(p);
  8853. }
  8854. void upb_json_printer_reset(upb_json_printer *p) {
  8855. p->depth_ = 0;
  8856. }
  8857. void upb_json_printer_resetoutput(upb_json_printer *p, upb_bytessink *output) {
  8858. upb_json_printer_reset(p);
  8859. p->output_ = output;
  8860. }
  8861. upb_sink *upb_json_printer_input(upb_json_printer *p) {
  8862. return &p->input_;
  8863. }
  8864. const upb_handlers *upb_json_printer_newhandlers(const upb_msgdef *md,
  8865. const void *owner) {
  8866. return upb_handlers_newfrozen(md, owner, printer_sethandlers, NULL);
  8867. }