upb.c 347 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435
  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. // Prevent overflow errors.
  2932. if (len == SIZE_MAX) return NULL;
  2933. // Always null-terminate, even if binary data; but don't rely on the input to
  2934. // have a null-terminating byte since it may be a raw binary buffer.
  2935. size_t n = len + 1;
  2936. char *p = malloc(n);
  2937. if (p) {
  2938. memcpy(p, s, len);
  2939. p[len] = 0;
  2940. }
  2941. return p;
  2942. }
  2943. // A type to represent the lookup key of either a strtable or an inttable.
  2944. typedef struct {
  2945. upb_tabkey key;
  2946. } lookupkey_t;
  2947. static lookupkey_t strkey2(const char *str, size_t len) {
  2948. lookupkey_t k;
  2949. k.key.s.str = (char*)str;
  2950. k.key.s.length = len;
  2951. return k;
  2952. }
  2953. static lookupkey_t intkey(uintptr_t key) {
  2954. lookupkey_t k;
  2955. k.key = upb_intkey(key);
  2956. return k;
  2957. }
  2958. typedef uint32_t hashfunc_t(upb_tabkey key);
  2959. typedef bool eqlfunc_t(upb_tabkey k1, lookupkey_t k2);
  2960. /* Base table (shared code) ***************************************************/
  2961. // For when we need to cast away const.
  2962. static upb_tabent *mutable_entries(upb_table *t) {
  2963. return (upb_tabent*)t->entries;
  2964. }
  2965. static bool isfull(upb_table *t) {
  2966. return (double)(t->count + 1) / upb_table_size(t) > MAX_LOAD;
  2967. }
  2968. static bool init(upb_table *t, upb_ctype_t ctype, uint8_t size_lg2) {
  2969. t->count = 0;
  2970. t->ctype = ctype;
  2971. t->size_lg2 = size_lg2;
  2972. t->mask = upb_table_size(t) ? upb_table_size(t) - 1 : 0;
  2973. size_t bytes = upb_table_size(t) * sizeof(upb_tabent);
  2974. if (bytes > 0) {
  2975. t->entries = malloc(bytes);
  2976. if (!t->entries) return false;
  2977. memset(mutable_entries(t), 0, bytes);
  2978. } else {
  2979. t->entries = NULL;
  2980. }
  2981. return true;
  2982. }
  2983. static void uninit(upb_table *t) { free(mutable_entries(t)); }
  2984. static upb_tabent *emptyent(upb_table *t) {
  2985. upb_tabent *e = mutable_entries(t) + upb_table_size(t);
  2986. while (1) { if (upb_tabent_isempty(--e)) return e; assert(e > t->entries); }
  2987. }
  2988. static upb_tabent *getentry_mutable(upb_table *t, uint32_t hash) {
  2989. return (upb_tabent*)upb_getentry(t, hash);
  2990. }
  2991. static const upb_tabent *findentry(const upb_table *t, lookupkey_t key,
  2992. uint32_t hash, eqlfunc_t *eql) {
  2993. if (t->size_lg2 == 0) return NULL;
  2994. const upb_tabent *e = upb_getentry(t, hash);
  2995. if (upb_tabent_isempty(e)) return NULL;
  2996. while (1) {
  2997. if (eql(e->key, key)) return e;
  2998. if ((e = e->next) == NULL) return NULL;
  2999. }
  3000. }
  3001. static upb_tabent *findentry_mutable(upb_table *t, lookupkey_t key,
  3002. uint32_t hash, eqlfunc_t *eql) {
  3003. return (upb_tabent*)findentry(t, key, hash, eql);
  3004. }
  3005. static bool lookup(const upb_table *t, lookupkey_t key, upb_value *v,
  3006. uint32_t hash, eqlfunc_t *eql) {
  3007. const upb_tabent *e = findentry(t, key, hash, eql);
  3008. if (e) {
  3009. if (v) {
  3010. _upb_value_setval(v, e->val, t->ctype);
  3011. }
  3012. return true;
  3013. } else {
  3014. return false;
  3015. }
  3016. }
  3017. // The given key must not already exist in the table.
  3018. static void insert(upb_table *t, lookupkey_t key, upb_value val,
  3019. uint32_t hash, hashfunc_t *hashfunc, eqlfunc_t *eql) {
  3020. UPB_UNUSED(eql);
  3021. assert(findentry(t, key, hash, eql) == NULL);
  3022. assert(val.ctype == t->ctype);
  3023. t->count++;
  3024. upb_tabent *mainpos_e = getentry_mutable(t, hash);
  3025. upb_tabent *our_e = mainpos_e;
  3026. if (upb_tabent_isempty(mainpos_e)) {
  3027. // Our main position is empty; use it.
  3028. our_e->next = NULL;
  3029. } else {
  3030. // Collision.
  3031. upb_tabent *new_e = emptyent(t);
  3032. // Head of collider's chain.
  3033. upb_tabent *chain = getentry_mutable(t, hashfunc(mainpos_e->key));
  3034. if (chain == mainpos_e) {
  3035. // Existing ent is in its main posisiton (it has the same hash as us, and
  3036. // is the head of our chain). Insert to new ent and append to this chain.
  3037. new_e->next = mainpos_e->next;
  3038. mainpos_e->next = new_e;
  3039. our_e = new_e;
  3040. } else {
  3041. // Existing ent is not in its main position (it is a node in some other
  3042. // chain). This implies that no existing ent in the table has our hash.
  3043. // Evict it (updating its chain) and use its ent for head of our chain.
  3044. *new_e = *mainpos_e; // copies next.
  3045. while (chain->next != mainpos_e) {
  3046. chain = (upb_tabent*)chain->next;
  3047. assert(chain);
  3048. }
  3049. chain->next = new_e;
  3050. our_e = mainpos_e;
  3051. our_e->next = NULL;
  3052. }
  3053. }
  3054. our_e->key = key.key;
  3055. our_e->val = val.val;
  3056. assert(findentry(t, key, hash, eql) == our_e);
  3057. }
  3058. static bool rm(upb_table *t, lookupkey_t key, upb_value *val,
  3059. upb_tabkey *removed, uint32_t hash, eqlfunc_t *eql) {
  3060. upb_tabent *chain = getentry_mutable(t, hash);
  3061. if (upb_tabent_isempty(chain)) return false;
  3062. if (eql(chain->key, key)) {
  3063. // Element to remove is at the head of its chain.
  3064. t->count--;
  3065. if (val) {
  3066. _upb_value_setval(val, chain->val, t->ctype);
  3067. }
  3068. if (chain->next) {
  3069. upb_tabent *move = (upb_tabent*)chain->next;
  3070. *chain = *move;
  3071. if (removed) *removed = move->key;
  3072. move->key.num = 0; // Make the slot empty.
  3073. } else {
  3074. if (removed) *removed = chain->key;
  3075. chain->key.num = 0; // Make the slot empty.
  3076. }
  3077. return true;
  3078. } else {
  3079. // Element to remove is either in a non-head position or not in the table.
  3080. while (chain->next && !eql(chain->next->key, key))
  3081. chain = (upb_tabent*)chain->next;
  3082. if (chain->next) {
  3083. // Found element to remove.
  3084. if (val) {
  3085. _upb_value_setval(val, chain->next->val, t->ctype);
  3086. }
  3087. upb_tabent *rm = (upb_tabent*)chain->next;
  3088. if (removed) *removed = rm->key;
  3089. rm->key.num = 0;
  3090. chain->next = rm->next;
  3091. t->count--;
  3092. return true;
  3093. } else {
  3094. return false;
  3095. }
  3096. }
  3097. }
  3098. static size_t next(const upb_table *t, size_t i) {
  3099. do {
  3100. if (++i >= upb_table_size(t))
  3101. return SIZE_MAX;
  3102. } while(upb_tabent_isempty(&t->entries[i]));
  3103. return i;
  3104. }
  3105. static size_t begin(const upb_table *t) {
  3106. return next(t, -1);
  3107. }
  3108. /* upb_strtable ***************************************************************/
  3109. // A simple "subclass" of upb_table that only adds a hash function for strings.
  3110. static uint32_t strhash(upb_tabkey key) {
  3111. return MurmurHash2(key.s.str, key.s.length, 0);
  3112. }
  3113. static bool streql(upb_tabkey k1, lookupkey_t k2) {
  3114. return k1.s.length == k2.key.s.length &&
  3115. memcmp(k1.s.str, k2.key.s.str, k1.s.length) == 0;
  3116. }
  3117. bool upb_strtable_init(upb_strtable *t, upb_ctype_t ctype) {
  3118. return init(&t->t, ctype, 2);
  3119. }
  3120. void upb_strtable_uninit(upb_strtable *t) {
  3121. for (size_t i = 0; i < upb_table_size(&t->t); i++)
  3122. free((void*)t->t.entries[i].key.s.str);
  3123. uninit(&t->t);
  3124. }
  3125. bool upb_strtable_resize(upb_strtable *t, size_t size_lg2) {
  3126. upb_strtable new_table;
  3127. if (!init(&new_table.t, t->t.ctype, size_lg2))
  3128. return false;
  3129. upb_strtable_iter i;
  3130. upb_strtable_begin(&i, t);
  3131. for ( ; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  3132. upb_strtable_insert2(
  3133. &new_table,
  3134. upb_strtable_iter_key(&i),
  3135. upb_strtable_iter_keylength(&i),
  3136. upb_strtable_iter_value(&i));
  3137. }
  3138. upb_strtable_uninit(t);
  3139. *t = new_table;
  3140. return true;
  3141. }
  3142. bool upb_strtable_insert2(upb_strtable *t, const char *k, size_t len,
  3143. upb_value v) {
  3144. if (isfull(&t->t)) {
  3145. // Need to resize. New table of double the size, add old elements to it.
  3146. if (!upb_strtable_resize(t, t->t.size_lg2 + 1)) {
  3147. return false;
  3148. }
  3149. }
  3150. if ((k = upb_strdup2(k, len)) == NULL) return false;
  3151. lookupkey_t key = strkey2(k, len);
  3152. uint32_t hash = MurmurHash2(key.key.s.str, key.key.s.length, 0);
  3153. insert(&t->t, key, v, hash, &strhash, &streql);
  3154. return true;
  3155. }
  3156. bool upb_strtable_lookup2(const upb_strtable *t, const char *key, size_t len,
  3157. upb_value *v) {
  3158. uint32_t hash = MurmurHash2(key, len, 0);
  3159. return lookup(&t->t, strkey2(key, len), v, hash, &streql);
  3160. }
  3161. bool upb_strtable_remove2(upb_strtable *t, const char *key, size_t len,
  3162. upb_value *val) {
  3163. uint32_t hash = MurmurHash2(key, strlen(key), 0);
  3164. upb_tabkey tabkey;
  3165. if (rm(&t->t, strkey2(key, len), val, &tabkey, hash, &streql)) {
  3166. free((void*)tabkey.s.str);
  3167. return true;
  3168. } else {
  3169. return false;
  3170. }
  3171. }
  3172. // Iteration
  3173. static const upb_tabent *str_tabent(const upb_strtable_iter *i) {
  3174. return &i->t->t.entries[i->index];
  3175. }
  3176. void upb_strtable_begin(upb_strtable_iter *i, const upb_strtable *t) {
  3177. i->t = t;
  3178. i->index = begin(&t->t);
  3179. }
  3180. void upb_strtable_next(upb_strtable_iter *i) {
  3181. i->index = next(&i->t->t, i->index);
  3182. }
  3183. bool upb_strtable_done(const upb_strtable_iter *i) {
  3184. return i->index >= upb_table_size(&i->t->t) ||
  3185. upb_tabent_isempty(str_tabent(i));
  3186. }
  3187. const char *upb_strtable_iter_key(upb_strtable_iter *i) {
  3188. assert(!upb_strtable_done(i));
  3189. return str_tabent(i)->key.s.str;
  3190. }
  3191. size_t upb_strtable_iter_keylength(upb_strtable_iter *i) {
  3192. assert(!upb_strtable_done(i));
  3193. return str_tabent(i)->key.s.length;
  3194. }
  3195. upb_value upb_strtable_iter_value(const upb_strtable_iter *i) {
  3196. assert(!upb_strtable_done(i));
  3197. return _upb_value_val(str_tabent(i)->val, i->t->t.ctype);
  3198. }
  3199. void upb_strtable_iter_setdone(upb_strtable_iter *i) {
  3200. i->index = SIZE_MAX;
  3201. }
  3202. bool upb_strtable_iter_isequal(const upb_strtable_iter *i1,
  3203. const upb_strtable_iter *i2) {
  3204. if (upb_strtable_done(i1) && upb_strtable_done(i2))
  3205. return true;
  3206. return i1->t == i2->t && i1->index == i2->index;
  3207. }
  3208. /* upb_inttable ***************************************************************/
  3209. // For inttables we use a hybrid structure where small keys are kept in an
  3210. // array and large keys are put in the hash table.
  3211. static uint32_t inthash(upb_tabkey key) { return upb_inthash(key.num); }
  3212. static bool inteql(upb_tabkey k1, lookupkey_t k2) {
  3213. return k1.num == k2.key.num;
  3214. }
  3215. static _upb_value *mutable_array(upb_inttable *t) {
  3216. return (_upb_value*)t->array;
  3217. }
  3218. static _upb_value *inttable_val(upb_inttable *t, uintptr_t key) {
  3219. if (key < t->array_size) {
  3220. return upb_arrhas(t->array[key]) ? &(mutable_array(t)[key]) : NULL;
  3221. } else {
  3222. upb_tabent *e =
  3223. findentry_mutable(&t->t, intkey(key), upb_inthash(key), &inteql);
  3224. return e ? &e->val : NULL;
  3225. }
  3226. }
  3227. static const _upb_value *inttable_val_const(const upb_inttable *t,
  3228. uintptr_t key) {
  3229. return inttable_val((upb_inttable*)t, key);
  3230. }
  3231. size_t upb_inttable_count(const upb_inttable *t) {
  3232. return t->t.count + t->array_count;
  3233. }
  3234. static void check(upb_inttable *t) {
  3235. UPB_UNUSED(t);
  3236. #if defined(UPB_DEBUG_TABLE) && !defined(NDEBUG)
  3237. // This check is very expensive (makes inserts/deletes O(N)).
  3238. size_t count = 0;
  3239. upb_inttable_iter i;
  3240. upb_inttable_begin(&i, t);
  3241. for(; !upb_inttable_done(&i); upb_inttable_next(&i), count++) {
  3242. assert(upb_inttable_lookup(t, upb_inttable_iter_key(&i), NULL));
  3243. }
  3244. assert(count == upb_inttable_count(t));
  3245. #endif
  3246. }
  3247. bool upb_inttable_sizedinit(upb_inttable *t, upb_ctype_t ctype,
  3248. size_t asize, int hsize_lg2) {
  3249. if (!init(&t->t, ctype, hsize_lg2)) return false;
  3250. // Always make the array part at least 1 long, so that we know key 0
  3251. // won't be in the hash part, which simplifies things.
  3252. t->array_size = UPB_MAX(1, asize);
  3253. t->array_count = 0;
  3254. size_t array_bytes = t->array_size * sizeof(upb_value);
  3255. t->array = malloc(array_bytes);
  3256. if (!t->array) {
  3257. uninit(&t->t);
  3258. return false;
  3259. }
  3260. memset(mutable_array(t), 0xff, array_bytes);
  3261. check(t);
  3262. return true;
  3263. }
  3264. bool upb_inttable_init(upb_inttable *t, upb_ctype_t ctype) {
  3265. return upb_inttable_sizedinit(t, ctype, 0, 4);
  3266. }
  3267. void upb_inttable_uninit(upb_inttable *t) {
  3268. uninit(&t->t);
  3269. free(mutable_array(t));
  3270. }
  3271. bool upb_inttable_insert(upb_inttable *t, uintptr_t key, upb_value val) {
  3272. assert(upb_arrhas(val.val));
  3273. if (key < t->array_size) {
  3274. assert(!upb_arrhas(t->array[key]));
  3275. t->array_count++;
  3276. mutable_array(t)[key] = val.val;
  3277. } else {
  3278. if (isfull(&t->t)) {
  3279. // Need to resize the hash part, but we re-use the array part.
  3280. upb_table new_table;
  3281. if (!init(&new_table, t->t.ctype, t->t.size_lg2 + 1))
  3282. return false;
  3283. size_t i;
  3284. for (i = begin(&t->t); i < upb_table_size(&t->t); i = next(&t->t, i)) {
  3285. const upb_tabent *e = &t->t.entries[i];
  3286. upb_value v;
  3287. _upb_value_setval(&v, e->val, t->t.ctype);
  3288. uint32_t hash = upb_inthash(e->key.num);
  3289. insert(&new_table, intkey(e->key.num), v, hash, &inthash, &inteql);
  3290. }
  3291. assert(t->t.count == new_table.count);
  3292. uninit(&t->t);
  3293. t->t = new_table;
  3294. }
  3295. insert(&t->t, intkey(key), val, upb_inthash(key), &inthash, &inteql);
  3296. }
  3297. check(t);
  3298. return true;
  3299. }
  3300. bool upb_inttable_lookup(const upb_inttable *t, uintptr_t key, upb_value *v) {
  3301. const _upb_value *table_v = inttable_val_const(t, key);
  3302. if (!table_v) return false;
  3303. if (v) _upb_value_setval(v, *table_v, t->t.ctype);
  3304. return true;
  3305. }
  3306. bool upb_inttable_replace(upb_inttable *t, uintptr_t key, upb_value val) {
  3307. _upb_value *table_v = inttable_val(t, key);
  3308. if (!table_v) return false;
  3309. *table_v = val.val;
  3310. return true;
  3311. }
  3312. bool upb_inttable_remove(upb_inttable *t, uintptr_t key, upb_value *val) {
  3313. bool success;
  3314. if (key < t->array_size) {
  3315. if (upb_arrhas(t->array[key])) {
  3316. t->array_count--;
  3317. if (val) {
  3318. _upb_value_setval(val, t->array[key], t->t.ctype);
  3319. }
  3320. _upb_value empty = UPB_ARRAY_EMPTYENT;
  3321. mutable_array(t)[key] = empty;
  3322. success = true;
  3323. } else {
  3324. success = false;
  3325. }
  3326. } else {
  3327. upb_tabkey removed;
  3328. uint32_t hash = upb_inthash(key);
  3329. success = rm(&t->t, intkey(key), val, &removed, hash, &inteql);
  3330. }
  3331. check(t);
  3332. return success;
  3333. }
  3334. bool upb_inttable_push(upb_inttable *t, upb_value val) {
  3335. return upb_inttable_insert(t, upb_inttable_count(t), val);
  3336. }
  3337. upb_value upb_inttable_pop(upb_inttable *t) {
  3338. upb_value val;
  3339. bool ok = upb_inttable_remove(t, upb_inttable_count(t) - 1, &val);
  3340. UPB_ASSERT_VAR(ok, ok);
  3341. return val;
  3342. }
  3343. bool upb_inttable_insertptr(upb_inttable *t, const void *key, upb_value val) {
  3344. return upb_inttable_insert(t, (uintptr_t)key, val);
  3345. }
  3346. bool upb_inttable_lookupptr(const upb_inttable *t, const void *key,
  3347. upb_value *v) {
  3348. return upb_inttable_lookup(t, (uintptr_t)key, v);
  3349. }
  3350. bool upb_inttable_removeptr(upb_inttable *t, const void *key, upb_value *val) {
  3351. return upb_inttable_remove(t, (uintptr_t)key, val);
  3352. }
  3353. void upb_inttable_compact(upb_inttable *t) {
  3354. // Create a power-of-two histogram of the table keys.
  3355. int counts[UPB_MAXARRSIZE + 1] = {0};
  3356. uintptr_t max_key = 0;
  3357. upb_inttable_iter i;
  3358. upb_inttable_begin(&i, t);
  3359. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  3360. uintptr_t key = upb_inttable_iter_key(&i);
  3361. if (key > max_key) {
  3362. max_key = key;
  3363. }
  3364. counts[log2ceil(key)]++;
  3365. }
  3366. int arr_size;
  3367. int arr_count = upb_inttable_count(t);
  3368. if (upb_inttable_count(t) >= max_key * MIN_DENSITY) {
  3369. // We can put 100% of the entries in the array part.
  3370. arr_size = max_key + 1;
  3371. } else {
  3372. // Find the largest power of two that satisfies the MIN_DENSITY definition.
  3373. for (int size_lg2 = ARRAY_SIZE(counts) - 1; size_lg2 > 1; size_lg2--) {
  3374. arr_size = 1 << size_lg2;
  3375. arr_count -= counts[size_lg2];
  3376. if (arr_count >= arr_size * MIN_DENSITY) {
  3377. break;
  3378. }
  3379. }
  3380. }
  3381. // Array part must always be at least 1 entry large to catch lookups of key
  3382. // 0. Key 0 must always be in the array part because "0" in the hash part
  3383. // denotes an empty entry.
  3384. arr_size = UPB_MAX(arr_size, 1);
  3385. // Insert all elements into new, perfectly-sized table.
  3386. int hash_count = upb_inttable_count(t) - arr_count;
  3387. int hash_size = hash_count ? (hash_count / MAX_LOAD) + 1 : 0;
  3388. int hashsize_lg2 = log2ceil(hash_size);
  3389. assert(hash_count >= 0);
  3390. upb_inttable new_t;
  3391. upb_inttable_sizedinit(&new_t, t->t.ctype, arr_size, hashsize_lg2);
  3392. upb_inttable_begin(&i, t);
  3393. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  3394. uintptr_t k = upb_inttable_iter_key(&i);
  3395. upb_inttable_insert(&new_t, k, upb_inttable_iter_value(&i));
  3396. }
  3397. assert(new_t.array_size == arr_size);
  3398. assert(new_t.t.size_lg2 == hashsize_lg2);
  3399. upb_inttable_uninit(t);
  3400. *t = new_t;
  3401. }
  3402. // Iteration.
  3403. static const upb_tabent *int_tabent(const upb_inttable_iter *i) {
  3404. assert(!i->array_part);
  3405. return &i->t->t.entries[i->index];
  3406. }
  3407. static _upb_value int_arrent(const upb_inttable_iter *i) {
  3408. assert(i->array_part);
  3409. return i->t->array[i->index];
  3410. }
  3411. void upb_inttable_begin(upb_inttable_iter *i, const upb_inttable *t) {
  3412. i->t = t;
  3413. i->index = -1;
  3414. i->array_part = true;
  3415. upb_inttable_next(i);
  3416. }
  3417. void upb_inttable_next(upb_inttable_iter *iter) {
  3418. const upb_inttable *t = iter->t;
  3419. if (iter->array_part) {
  3420. while (++iter->index < t->array_size) {
  3421. if (upb_arrhas(int_arrent(iter))) {
  3422. return;
  3423. }
  3424. }
  3425. iter->array_part = false;
  3426. iter->index = begin(&t->t);
  3427. } else {
  3428. iter->index = next(&t->t, iter->index);
  3429. }
  3430. }
  3431. bool upb_inttable_done(const upb_inttable_iter *i) {
  3432. if (i->array_part) {
  3433. return i->index >= i->t->array_size ||
  3434. !upb_arrhas(int_arrent(i));
  3435. } else {
  3436. return i->index >= upb_table_size(&i->t->t) ||
  3437. upb_tabent_isempty(int_tabent(i));
  3438. }
  3439. }
  3440. uintptr_t upb_inttable_iter_key(const upb_inttable_iter *i) {
  3441. assert(!upb_inttable_done(i));
  3442. return i->array_part ? i->index : int_tabent(i)->key.num;
  3443. }
  3444. upb_value upb_inttable_iter_value(const upb_inttable_iter *i) {
  3445. assert(!upb_inttable_done(i));
  3446. return _upb_value_val(
  3447. i->array_part ? i->t->array[i->index] : int_tabent(i)->val,
  3448. i->t->t.ctype);
  3449. }
  3450. void upb_inttable_iter_setdone(upb_inttable_iter *i) {
  3451. i->index = SIZE_MAX;
  3452. i->array_part = false;
  3453. }
  3454. bool upb_inttable_iter_isequal(const upb_inttable_iter *i1,
  3455. const upb_inttable_iter *i2) {
  3456. if (upb_inttable_done(i1) && upb_inttable_done(i2))
  3457. return true;
  3458. return i1->t == i2->t && i1->index == i2->index &&
  3459. i1->array_part == i2->array_part;
  3460. }
  3461. #ifdef UPB_UNALIGNED_READS_OK
  3462. //-----------------------------------------------------------------------------
  3463. // MurmurHash2, by Austin Appleby (released as public domain).
  3464. // Reformatted and C99-ified by Joshua Haberman.
  3465. // Note - This code makes a few assumptions about how your machine behaves -
  3466. // 1. We can read a 4-byte value from any address without crashing
  3467. // 2. sizeof(int) == 4 (in upb this limitation is removed by using uint32_t
  3468. // And it has a few limitations -
  3469. // 1. It will not work incrementally.
  3470. // 2. It will not produce the same results on little-endian and big-endian
  3471. // machines.
  3472. uint32_t MurmurHash2(const void *key, size_t len, uint32_t seed) {
  3473. // 'm' and 'r' are mixing constants generated offline.
  3474. // They're not really 'magic', they just happen to work well.
  3475. const uint32_t m = 0x5bd1e995;
  3476. const int32_t r = 24;
  3477. // Initialize the hash to a 'random' value
  3478. uint32_t h = seed ^ len;
  3479. // Mix 4 bytes at a time into the hash
  3480. const uint8_t * data = (const uint8_t *)key;
  3481. while(len >= 4) {
  3482. uint32_t k = *(uint32_t *)data;
  3483. k *= m;
  3484. k ^= k >> r;
  3485. k *= m;
  3486. h *= m;
  3487. h ^= k;
  3488. data += 4;
  3489. len -= 4;
  3490. }
  3491. // Handle the last few bytes of the input array
  3492. switch(len) {
  3493. case 3: h ^= data[2] << 16;
  3494. case 2: h ^= data[1] << 8;
  3495. case 1: h ^= data[0]; h *= m;
  3496. };
  3497. // Do a few final mixes of the hash to ensure the last few
  3498. // bytes are well-incorporated.
  3499. h ^= h >> 13;
  3500. h *= m;
  3501. h ^= h >> 15;
  3502. return h;
  3503. }
  3504. #else // !UPB_UNALIGNED_READS_OK
  3505. //-----------------------------------------------------------------------------
  3506. // MurmurHashAligned2, by Austin Appleby
  3507. // Same algorithm as MurmurHash2, but only does aligned reads - should be safer
  3508. // on certain platforms.
  3509. // Performance will be lower than MurmurHash2
  3510. #define MIX(h,k,m) { k *= m; k ^= k >> r; k *= m; h *= m; h ^= k; }
  3511. uint32_t MurmurHash2(const void * key, size_t len, uint32_t seed) {
  3512. const uint32_t m = 0x5bd1e995;
  3513. const int32_t r = 24;
  3514. const uint8_t * data = (const uint8_t *)key;
  3515. uint32_t h = seed ^ len;
  3516. uint8_t align = (uintptr_t)data & 3;
  3517. if(align && (len >= 4)) {
  3518. // Pre-load the temp registers
  3519. uint32_t t = 0, d = 0;
  3520. switch(align) {
  3521. case 1: t |= data[2] << 16;
  3522. case 2: t |= data[1] << 8;
  3523. case 3: t |= data[0];
  3524. }
  3525. t <<= (8 * align);
  3526. data += 4-align;
  3527. len -= 4-align;
  3528. int32_t sl = 8 * (4-align);
  3529. int32_t sr = 8 * align;
  3530. // Mix
  3531. while(len >= 4) {
  3532. d = *(uint32_t *)data;
  3533. t = (t >> sr) | (d << sl);
  3534. uint32_t k = t;
  3535. MIX(h,k,m);
  3536. t = d;
  3537. data += 4;
  3538. len -= 4;
  3539. }
  3540. // Handle leftover data in temp registers
  3541. d = 0;
  3542. if(len >= align) {
  3543. switch(align) {
  3544. case 3: d |= data[2] << 16;
  3545. case 2: d |= data[1] << 8;
  3546. case 1: d |= data[0];
  3547. }
  3548. uint32_t k = (t >> sr) | (d << sl);
  3549. MIX(h,k,m);
  3550. data += align;
  3551. len -= align;
  3552. //----------
  3553. // Handle tail bytes
  3554. switch(len) {
  3555. case 3: h ^= data[2] << 16;
  3556. case 2: h ^= data[1] << 8;
  3557. case 1: h ^= data[0]; h *= m;
  3558. };
  3559. } else {
  3560. switch(len) {
  3561. case 3: d |= data[2] << 16;
  3562. case 2: d |= data[1] << 8;
  3563. case 1: d |= data[0];
  3564. case 0: h ^= (t >> sr) | (d << sl); h *= m;
  3565. }
  3566. }
  3567. h ^= h >> 13;
  3568. h *= m;
  3569. h ^= h >> 15;
  3570. return h;
  3571. } else {
  3572. while(len >= 4) {
  3573. uint32_t k = *(uint32_t *)data;
  3574. MIX(h,k,m);
  3575. data += 4;
  3576. len -= 4;
  3577. }
  3578. //----------
  3579. // Handle tail bytes
  3580. switch(len) {
  3581. case 3: h ^= data[2] << 16;
  3582. case 2: h ^= data[1] << 8;
  3583. case 1: h ^= data[0]; h *= m;
  3584. };
  3585. h ^= h >> 13;
  3586. h *= m;
  3587. h ^= h >> 15;
  3588. return h;
  3589. }
  3590. }
  3591. #undef MIX
  3592. #endif // UPB_UNALIGNED_READS_OK
  3593. /*
  3594. * upb - a minimalist implementation of protocol buffers.
  3595. *
  3596. * Copyright (c) 2009-2012 Google Inc. See LICENSE for details.
  3597. * Author: Josh Haberman <jhaberman@gmail.com>
  3598. */
  3599. #include <errno.h>
  3600. #include <stdarg.h>
  3601. #include <stddef.h>
  3602. #include <stdint.h>
  3603. #include <stdio.h>
  3604. #include <stdlib.h>
  3605. #include <string.h>
  3606. bool upb_dumptostderr(void *closure, const upb_status* status) {
  3607. UPB_UNUSED(closure);
  3608. fprintf(stderr, "%s\n", upb_status_errmsg(status));
  3609. return false;
  3610. }
  3611. // Guarantee null-termination and provide ellipsis truncation.
  3612. // It may be tempting to "optimize" this by initializing these final
  3613. // four bytes up-front and then being careful never to overwrite them,
  3614. // this is safer and simpler.
  3615. static void nullz(upb_status *status) {
  3616. const char *ellipsis = "...";
  3617. size_t len = strlen(ellipsis);
  3618. assert(sizeof(status->msg) > len);
  3619. memcpy(status->msg + sizeof(status->msg) - len, ellipsis, len);
  3620. }
  3621. void upb_status_clear(upb_status *status) {
  3622. if (!status) return;
  3623. status->ok_ = true;
  3624. status->code_ = 0;
  3625. status->msg[0] = '\0';
  3626. }
  3627. bool upb_ok(const upb_status *status) { return status->ok_; }
  3628. upb_errorspace *upb_status_errspace(const upb_status *status) {
  3629. return status->error_space_;
  3630. }
  3631. int upb_status_errcode(const upb_status *status) { return status->code_; }
  3632. const char *upb_status_errmsg(const upb_status *status) { return status->msg; }
  3633. void upb_status_seterrmsg(upb_status *status, const char *msg) {
  3634. if (!status) return;
  3635. status->ok_ = false;
  3636. strncpy(status->msg, msg, sizeof(status->msg));
  3637. nullz(status);
  3638. }
  3639. void upb_status_seterrf(upb_status *status, const char *fmt, ...) {
  3640. va_list args;
  3641. va_start(args, fmt);
  3642. upb_status_vseterrf(status, fmt, args);
  3643. va_end(args);
  3644. }
  3645. void upb_status_vseterrf(upb_status *status, const char *fmt, va_list args) {
  3646. if (!status) return;
  3647. status->ok_ = false;
  3648. vsnprintf(status->msg, sizeof(status->msg), fmt, args);
  3649. nullz(status);
  3650. }
  3651. void upb_status_seterrcode(upb_status *status, upb_errorspace *space,
  3652. int code) {
  3653. if (!status) return;
  3654. status->ok_ = false;
  3655. status->error_space_ = space;
  3656. status->code_ = code;
  3657. space->set_message(status, code);
  3658. }
  3659. void upb_status_copy(upb_status *to, const upb_status *from) {
  3660. if (!to) return;
  3661. *to = *from;
  3662. }
  3663. // This file was generated by upbc (the upb compiler).
  3664. // Do not edit -- your changes will be discarded when the file is
  3665. // regenerated.
  3666. static const upb_msgdef msgs[20];
  3667. static const upb_fielddef fields[81];
  3668. static const upb_enumdef enums[4];
  3669. static const upb_tabent strentries[236];
  3670. static const upb_tabent intentries[14];
  3671. static const _upb_value arrays[232];
  3672. #ifdef UPB_DEBUG_REFS
  3673. static upb_inttable reftables[212];
  3674. #endif
  3675. static const upb_msgdef msgs[20] = {
  3676. 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]),
  3677. 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]),
  3678. 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]),
  3679. 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]),
  3680. 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]),
  3681. 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]),
  3682. 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]),
  3683. 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]),
  3684. 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]),
  3685. 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]),
  3686. 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]),
  3687. 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]),
  3688. 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]),
  3689. 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]),
  3690. 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]),
  3691. 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]),
  3692. 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]),
  3693. 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]),
  3694. 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]),
  3695. 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]),
  3696. };
  3697. static const upb_fielddef fields[81] = {
  3698. 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]),
  3699. 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]),
  3700. 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]),
  3701. 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]),
  3702. 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]),
  3703. 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]),
  3704. 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]),
  3705. 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]),
  3706. 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]),
  3707. 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]),
  3708. 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]),
  3709. 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]),
  3710. 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]),
  3711. 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]),
  3712. 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]),
  3713. 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]),
  3714. 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]),
  3715. 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]),
  3716. 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]),
  3717. 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]),
  3718. 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]),
  3719. 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]),
  3720. 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]),
  3721. 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]),
  3722. 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]),
  3723. 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]),
  3724. 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]),
  3725. 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]),
  3726. 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]),
  3727. 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]),
  3728. 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]),
  3729. 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]),
  3730. 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]),
  3731. 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]),
  3732. 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]),
  3733. 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]),
  3734. 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]),
  3735. 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]),
  3736. 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]),
  3737. 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]),
  3738. 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]),
  3739. 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]),
  3740. 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]),
  3741. 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]),
  3742. 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]),
  3743. 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]),
  3744. 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]),
  3745. 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]),
  3746. 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]),
  3747. 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]),
  3748. 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]),
  3749. 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]),
  3750. 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]),
  3751. 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]),
  3752. 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]),
  3753. 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]),
  3754. 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]),
  3755. 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]),
  3756. 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]),
  3757. 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]),
  3758. 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]),
  3759. 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]),
  3760. 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]),
  3761. 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]),
  3762. 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]),
  3763. 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]),
  3764. 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]),
  3765. 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]),
  3766. 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]),
  3767. 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]),
  3768. 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]),
  3769. 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]),
  3770. 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]),
  3771. 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]),
  3772. 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]),
  3773. 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]),
  3774. 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]),
  3775. 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]),
  3776. 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]),
  3777. 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]),
  3778. 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]),
  3779. };
  3780. static const upb_enumdef enums[4] = {
  3781. 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]),
  3782. 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]),
  3783. 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]),
  3784. 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]),
  3785. };
  3786. static const upb_tabent strentries[236] = {
  3787. {UPB_TABKEY_STR("extension"), UPB_VALUE_INIT_CONSTPTR(&fields[14]), NULL},
  3788. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3789. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3790. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[38]), NULL},
  3791. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3792. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3793. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3794. {UPB_TABKEY_STR("field"), UPB_VALUE_INIT_CONSTPTR(&fields[16]), NULL},
  3795. {UPB_TABKEY_STR("extension_range"), UPB_VALUE_INIT_CONSTPTR(&fields[15]), NULL},
  3796. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3797. {UPB_TABKEY_STR("nested_type"), UPB_VALUE_INIT_CONSTPTR(&fields[44]), NULL},
  3798. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3799. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3800. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3801. {UPB_TABKEY_STR("options"), UPB_VALUE_INIT_CONSTPTR(&fields[49]), NULL},
  3802. {UPB_TABKEY_STR("enum_type"), UPB_VALUE_INIT_CONSTPTR(&fields[9]), &strentries[14]},
  3803. {UPB_TABKEY_STR("start"), UPB_VALUE_INIT_CONSTPTR(&fields[66]), NULL},
  3804. {UPB_TABKEY_STR("end"), UPB_VALUE_INIT_CONSTPTR(&fields[8]), NULL},
  3805. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3806. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3807. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3808. {UPB_TABKEY_STR("value"), UPB_VALUE_INIT_CONSTPTR(&fields[78]), NULL},
  3809. {UPB_TABKEY_STR("options"), UPB_VALUE_INIT_CONSTPTR(&fields[50]), NULL},
  3810. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[40]), &strentries[22]},
  3811. {UPB_TABKEY_STR("uninterpreted_option"), UPB_VALUE_INIT_CONSTPTR(&fields[73]), NULL},
  3812. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3813. {UPB_TABKEY_STR("allow_alias"), UPB_VALUE_INIT_CONSTPTR(&fields[1]), NULL},
  3814. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3815. {UPB_TABKEY_STR("number"), UPB_VALUE_INIT_CONSTPTR(&fields[47]), NULL},
  3816. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3817. {UPB_TABKEY_STR("options"), UPB_VALUE_INIT_CONSTPTR(&fields[52]), NULL},
  3818. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[37]), &strentries[30]},
  3819. {UPB_TABKEY_STR("uninterpreted_option"), UPB_VALUE_INIT_CONSTPTR(&fields[71]), NULL},
  3820. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3821. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3822. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3823. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3824. {UPB_TABKEY_STR("label"), UPB_VALUE_INIT_CONSTPTR(&fields[27]), NULL},
  3825. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3826. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[41]), NULL},
  3827. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3828. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3829. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3830. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3831. {UPB_TABKEY_STR("number"), UPB_VALUE_INIT_CONSTPTR(&fields[46]), &strentries[49]},
  3832. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3833. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3834. {UPB_TABKEY_STR("type_name"), UPB_VALUE_INIT_CONSTPTR(&fields[70]), NULL},
  3835. {UPB_TABKEY_STR("extendee"), UPB_VALUE_INIT_CONSTPTR(&fields[12]), NULL},
  3836. {UPB_TABKEY_STR("type"), UPB_VALUE_INIT_CONSTPTR(&fields[69]), &strentries[48]},
  3837. {UPB_TABKEY_STR("default_value"), UPB_VALUE_INIT_CONSTPTR(&fields[4]), NULL},
  3838. {UPB_TABKEY_STR("options"), UPB_VALUE_INIT_CONSTPTR(&fields[51]), NULL},
  3839. {UPB_TABKEY_STR("experimental_map_key"), UPB_VALUE_INIT_CONSTPTR(&fields[11]), &strentries[67]},
  3840. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3841. {UPB_TABKEY_STR("weak"), UPB_VALUE_INIT_CONSTPTR(&fields[79]), NULL},
  3842. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3843. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3844. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3845. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3846. {UPB_TABKEY_STR("packed"), UPB_VALUE_INIT_CONSTPTR(&fields[58]), NULL},
  3847. {UPB_TABKEY_STR("lazy"), UPB_VALUE_INIT_CONSTPTR(&fields[28]), NULL},
  3848. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3849. {UPB_TABKEY_STR("ctype"), UPB_VALUE_INIT_CONSTPTR(&fields[3]), NULL},
  3850. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3851. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3852. {UPB_TABKEY_STR("deprecated"), UPB_VALUE_INIT_CONSTPTR(&fields[6]), NULL},
  3853. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3854. {UPB_TABKEY_STR("uninterpreted_option"), UPB_VALUE_INIT_CONSTPTR(&fields[77]), NULL},
  3855. {UPB_TABKEY_STR("extension"), UPB_VALUE_INIT_CONSTPTR(&fields[13]), NULL},
  3856. {UPB_TABKEY_STR("weak_dependency"), UPB_VALUE_INIT_CONSTPTR(&fields[80]), NULL},
  3857. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3858. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[34]), NULL},
  3859. {UPB_TABKEY_STR("service"), UPB_VALUE_INIT_CONSTPTR(&fields[63]), NULL},
  3860. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3861. {UPB_TABKEY_STR("source_code_info"), UPB_VALUE_INIT_CONSTPTR(&fields[64]), NULL},
  3862. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3863. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3864. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3865. {UPB_TABKEY_STR("dependency"), UPB_VALUE_INIT_CONSTPTR(&fields[5]), NULL},
  3866. {UPB_TABKEY_STR("message_type"), UPB_VALUE_INIT_CONSTPTR(&fields[32]), NULL},
  3867. {UPB_TABKEY_STR("package"), UPB_VALUE_INIT_CONSTPTR(&fields[57]), NULL},
  3868. {UPB_TABKEY_STR("options"), UPB_VALUE_INIT_CONSTPTR(&fields[53]), &strentries[82]},
  3869. {UPB_TABKEY_STR("enum_type"), UPB_VALUE_INIT_CONSTPTR(&fields[10]), NULL},
  3870. {UPB_TABKEY_STR("public_dependency"), UPB_VALUE_INIT_CONSTPTR(&fields[61]), &strentries[81]},
  3871. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3872. {UPB_TABKEY_STR("file"), UPB_VALUE_INIT_CONSTPTR(&fields[17]), NULL},
  3873. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3874. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3875. {UPB_TABKEY_STR("uninterpreted_option"), UPB_VALUE_INIT_CONSTPTR(&fields[75]), NULL},
  3876. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3877. {UPB_TABKEY_STR("cc_generic_services"), UPB_VALUE_INIT_CONSTPTR(&fields[2]), NULL},
  3878. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3879. {UPB_TABKEY_STR("java_multiple_files"), UPB_VALUE_INIT_CONSTPTR(&fields[24]), NULL},
  3880. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3881. {UPB_TABKEY_STR("java_generic_services"), UPB_VALUE_INIT_CONSTPTR(&fields[23]), &strentries[102]},
  3882. {UPB_TABKEY_STR("java_generate_equals_and_hash"), UPB_VALUE_INIT_CONSTPTR(&fields[22]), NULL},
  3883. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3884. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3885. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3886. {UPB_TABKEY_STR("go_package"), UPB_VALUE_INIT_CONSTPTR(&fields[18]), NULL},
  3887. {UPB_TABKEY_STR("java_package"), UPB_VALUE_INIT_CONSTPTR(&fields[26]), NULL},
  3888. {UPB_TABKEY_STR("optimize_for"), UPB_VALUE_INIT_CONSTPTR(&fields[48]), NULL},
  3889. {UPB_TABKEY_STR("py_generic_services"), UPB_VALUE_INIT_CONSTPTR(&fields[62]), NULL},
  3890. {UPB_TABKEY_STR("java_outer_classname"), UPB_VALUE_INIT_CONSTPTR(&fields[25]), NULL},
  3891. {UPB_TABKEY_STR("message_set_wire_format"), UPB_VALUE_INIT_CONSTPTR(&fields[31]), &strentries[106]},
  3892. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3893. {UPB_TABKEY_STR("uninterpreted_option"), UPB_VALUE_INIT_CONSTPTR(&fields[76]), NULL},
  3894. {UPB_TABKEY_STR("no_standard_descriptor_accessor"), UPB_VALUE_INIT_CONSTPTR(&fields[45]), NULL},
  3895. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3896. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3897. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3898. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[39]), NULL},
  3899. {UPB_TABKEY_STR("input_type"), UPB_VALUE_INIT_CONSTPTR(&fields[20]), NULL},
  3900. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3901. {UPB_TABKEY_STR("output_type"), UPB_VALUE_INIT_CONSTPTR(&fields[56]), NULL},
  3902. {UPB_TABKEY_STR("options"), UPB_VALUE_INIT_CONSTPTR(&fields[55]), NULL},
  3903. {UPB_TABKEY_STR("uninterpreted_option"), UPB_VALUE_INIT_CONSTPTR(&fields[74]), NULL},
  3904. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3905. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3906. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3907. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3908. {UPB_TABKEY_STR("options"), UPB_VALUE_INIT_CONSTPTR(&fields[54]), &strentries[122]},
  3909. {UPB_TABKEY_STR("method"), UPB_VALUE_INIT_CONSTPTR(&fields[33]), NULL},
  3910. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[35]), &strentries[121]},
  3911. {UPB_TABKEY_STR("uninterpreted_option"), UPB_VALUE_INIT_CONSTPTR(&fields[72]), NULL},
  3912. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3913. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, 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_STR("location"), UPB_VALUE_INIT_CONSTPTR(&fields[30]), NULL},
  3918. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3919. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3920. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3921. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3922. {UPB_TABKEY_STR("span"), UPB_VALUE_INIT_CONSTPTR(&fields[65]), &strentries[139]},
  3923. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3924. {UPB_TABKEY_STR("trailing_comments"), UPB_VALUE_INIT_CONSTPTR(&fields[68]), NULL},
  3925. {UPB_TABKEY_STR("leading_comments"), UPB_VALUE_INIT_CONSTPTR(&fields[29]), &strentries[137]},
  3926. {UPB_TABKEY_STR("path"), UPB_VALUE_INIT_CONSTPTR(&fields[59]), NULL},
  3927. {UPB_TABKEY_STR("double_value"), UPB_VALUE_INIT_CONSTPTR(&fields[7]), NULL},
  3928. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3929. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3930. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[36]), NULL},
  3931. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3932. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3933. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3934. {UPB_TABKEY_STR("negative_int_value"), UPB_VALUE_INIT_CONSTPTR(&fields[43]), NULL},
  3935. {UPB_TABKEY_STR("aggregate_value"), UPB_VALUE_INIT_CONSTPTR(&fields[0]), NULL},
  3936. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3937. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3938. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3939. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3940. {UPB_TABKEY_STR("positive_int_value"), UPB_VALUE_INIT_CONSTPTR(&fields[60]), NULL},
  3941. {UPB_TABKEY_STR("identifier_value"), UPB_VALUE_INIT_CONSTPTR(&fields[19]), NULL},
  3942. {UPB_TABKEY_STR("string_value"), UPB_VALUE_INIT_CONSTPTR(&fields[67]), &strentries[154]},
  3943. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3944. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3945. {UPB_TABKEY_STR("is_extension"), UPB_VALUE_INIT_CONSTPTR(&fields[21]), NULL},
  3946. {UPB_TABKEY_STR("name_part"), UPB_VALUE_INIT_CONSTPTR(&fields[42]), NULL},
  3947. {UPB_TABKEY_STR("LABEL_REQUIRED"), UPB_VALUE_INIT_INT32(2), &strentries[162]},
  3948. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3949. {UPB_TABKEY_STR("LABEL_REPEATED"), UPB_VALUE_INIT_INT32(3), NULL},
  3950. {UPB_TABKEY_STR("LABEL_OPTIONAL"), UPB_VALUE_INIT_INT32(1), NULL},
  3951. {UPB_TABKEY_STR("TYPE_FIXED64"), UPB_VALUE_INIT_INT32(6), NULL},
  3952. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3953. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3954. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3955. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3956. {UPB_TABKEY_STR("TYPE_STRING"), UPB_VALUE_INIT_INT32(9), NULL},
  3957. {UPB_TABKEY_STR("TYPE_FLOAT"), UPB_VALUE_INIT_INT32(2), &strentries[193]},
  3958. {UPB_TABKEY_STR("TYPE_DOUBLE"), UPB_VALUE_INIT_INT32(1), NULL},
  3959. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3960. {UPB_TABKEY_STR("TYPE_INT32"), UPB_VALUE_INIT_INT32(5), NULL},
  3961. {UPB_TABKEY_STR("TYPE_SFIXED32"), UPB_VALUE_INIT_INT32(15), NULL},
  3962. {UPB_TABKEY_STR("TYPE_FIXED32"), UPB_VALUE_INIT_INT32(7), NULL},
  3963. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3964. {UPB_TABKEY_STR("TYPE_MESSAGE"), UPB_VALUE_INIT_INT32(11), &strentries[194]},
  3965. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3966. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3967. {UPB_TABKEY_STR("TYPE_INT64"), UPB_VALUE_INIT_INT32(3), &strentries[191]},
  3968. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3969. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3970. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3971. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3972. {UPB_TABKEY_STR("TYPE_ENUM"), UPB_VALUE_INIT_INT32(14), NULL},
  3973. {UPB_TABKEY_STR("TYPE_UINT32"), UPB_VALUE_INIT_INT32(13), NULL},
  3974. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3975. {UPB_TABKEY_STR("TYPE_UINT64"), UPB_VALUE_INIT_INT32(4), &strentries[190]},
  3976. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3977. {UPB_TABKEY_STR("TYPE_SFIXED64"), UPB_VALUE_INIT_INT32(16), NULL},
  3978. {UPB_TABKEY_STR("TYPE_BYTES"), UPB_VALUE_INIT_INT32(12), NULL},
  3979. {UPB_TABKEY_STR("TYPE_SINT64"), UPB_VALUE_INIT_INT32(18), NULL},
  3980. {UPB_TABKEY_STR("TYPE_BOOL"), UPB_VALUE_INIT_INT32(8), NULL},
  3981. {UPB_TABKEY_STR("TYPE_GROUP"), UPB_VALUE_INIT_INT32(10), NULL},
  3982. {UPB_TABKEY_STR("TYPE_SINT32"), UPB_VALUE_INIT_INT32(17), NULL},
  3983. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3984. {UPB_TABKEY_STR("CORD"), UPB_VALUE_INIT_INT32(1), NULL},
  3985. {UPB_TABKEY_STR("STRING"), UPB_VALUE_INIT_INT32(0), &strentries[197]},
  3986. {UPB_TABKEY_STR("STRING_PIECE"), UPB_VALUE_INIT_INT32(2), NULL},
  3987. {UPB_TABKEY_STR("CODE_SIZE"), UPB_VALUE_INIT_INT32(2), NULL},
  3988. {UPB_TABKEY_STR("SPEED"), UPB_VALUE_INIT_INT32(1), &strentries[203]},
  3989. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3990. {UPB_TABKEY_STR("LITE_RUNTIME"), UPB_VALUE_INIT_INT32(3), NULL},
  3991. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3992. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3993. {UPB_TABKEY_STR("google.protobuf.SourceCodeInfo.Location"), UPB_VALUE_INIT_CONSTPTR(&msgs[17]), NULL},
  3994. {UPB_TABKEY_STR("google.protobuf.UninterpretedOption"), UPB_VALUE_INIT_CONSTPTR(&msgs[18]), NULL},
  3995. {UPB_TABKEY_STR("google.protobuf.FileDescriptorProto"), UPB_VALUE_INIT_CONSTPTR(&msgs[8]), NULL},
  3996. {UPB_TABKEY_STR("google.protobuf.MethodDescriptorProto"), UPB_VALUE_INIT_CONSTPTR(&msgs[12]), NULL},
  3997. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3998. {UPB_TABKEY_STR("google.protobuf.EnumValueOptions"), UPB_VALUE_INIT_CONSTPTR(&msgs[5]), NULL},
  3999. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4000. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4001. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4002. {UPB_TABKEY_STR("google.protobuf.DescriptorProto"), UPB_VALUE_INIT_CONSTPTR(&msgs[0]), &strentries[228]},
  4003. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4004. {UPB_TABKEY_STR("google.protobuf.SourceCodeInfo"), UPB_VALUE_INIT_CONSTPTR(&msgs[16]), NULL},
  4005. {UPB_TABKEY_STR("google.protobuf.FieldDescriptorProto.Type"), UPB_VALUE_INIT_CONSTPTR(&enums[1]), NULL},
  4006. {UPB_TABKEY_STR("google.protobuf.DescriptorProto.ExtensionRange"), UPB_VALUE_INIT_CONSTPTR(&msgs[1]), NULL},
  4007. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4008. {UPB_TABKEY_STR("google.protobuf.EnumValueDescriptorProto"), UPB_VALUE_INIT_CONSTPTR(&msgs[4]), NULL},
  4009. {UPB_TABKEY_STR("google.protobuf.FieldOptions"), UPB_VALUE_INIT_CONSTPTR(&msgs[7]), NULL},
  4010. {UPB_TABKEY_STR("google.protobuf.FileOptions"), UPB_VALUE_INIT_CONSTPTR(&msgs[10]), NULL},
  4011. {UPB_TABKEY_STR("google.protobuf.EnumDescriptorProto"), UPB_VALUE_INIT_CONSTPTR(&msgs[2]), &strentries[233]},
  4012. {UPB_TABKEY_STR("google.protobuf.FieldDescriptorProto.Label"), UPB_VALUE_INIT_CONSTPTR(&enums[0]), NULL},
  4013. {UPB_TABKEY_STR("google.protobuf.ServiceDescriptorProto"), UPB_VALUE_INIT_CONSTPTR(&msgs[14]), NULL},
  4014. {UPB_TABKEY_STR("google.protobuf.FieldOptions.CType"), UPB_VALUE_INIT_CONSTPTR(&enums[2]), &strentries[229]},
  4015. {UPB_TABKEY_STR("google.protobuf.FileDescriptorSet"), UPB_VALUE_INIT_CONSTPTR(&msgs[9]), &strentries[235]},
  4016. {UPB_TABKEY_STR("google.protobuf.EnumOptions"), UPB_VALUE_INIT_CONSTPTR(&msgs[3]), NULL},
  4017. {UPB_TABKEY_STR("google.protobuf.FieldDescriptorProto"), UPB_VALUE_INIT_CONSTPTR(&msgs[6]), NULL},
  4018. {UPB_TABKEY_STR("google.protobuf.FileOptions.OptimizeMode"), UPB_VALUE_INIT_CONSTPTR(&enums[3]), &strentries[221]},
  4019. {UPB_TABKEY_STR("google.protobuf.ServiceOptions"), UPB_VALUE_INIT_CONSTPTR(&msgs[15]), NULL},
  4020. {UPB_TABKEY_STR("google.protobuf.MessageOptions"), UPB_VALUE_INIT_CONSTPTR(&msgs[11]), NULL},
  4021. {UPB_TABKEY_STR("google.protobuf.MethodOptions"), UPB_VALUE_INIT_CONSTPTR(&msgs[13]), &strentries[226]},
  4022. {UPB_TABKEY_STR("google.protobuf.UninterpretedOption.NamePart"), UPB_VALUE_INIT_CONSTPTR(&msgs[19]), NULL},
  4023. };
  4024. static const upb_tabent intentries[14] = {
  4025. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4026. {UPB_TABKEY_NUM(999), UPB_VALUE_INIT_CONSTPTR(&fields[73]), NULL},
  4027. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4028. {UPB_TABKEY_NUM(999), UPB_VALUE_INIT_CONSTPTR(&fields[71]), NULL},
  4029. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4030. {UPB_TABKEY_NUM(999), UPB_VALUE_INIT_CONSTPTR(&fields[77]), NULL},
  4031. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4032. {UPB_TABKEY_NUM(999), UPB_VALUE_INIT_CONSTPTR(&fields[75]), NULL},
  4033. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4034. {UPB_TABKEY_NUM(999), UPB_VALUE_INIT_CONSTPTR(&fields[76]), NULL},
  4035. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4036. {UPB_TABKEY_NUM(999), UPB_VALUE_INIT_CONSTPTR(&fields[74]), NULL},
  4037. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4038. {UPB_TABKEY_NUM(999), UPB_VALUE_INIT_CONSTPTR(&fields[72]), NULL},
  4039. };
  4040. static const _upb_value arrays[232] = {
  4041. UPB_ARRAY_EMPTYENT,
  4042. UPB_VALUE_INIT_CONSTPTR(&fields[38]),
  4043. UPB_VALUE_INIT_CONSTPTR(&fields[16]),
  4044. UPB_VALUE_INIT_CONSTPTR(&fields[44]),
  4045. UPB_VALUE_INIT_CONSTPTR(&fields[9]),
  4046. UPB_VALUE_INIT_CONSTPTR(&fields[15]),
  4047. UPB_VALUE_INIT_CONSTPTR(&fields[14]),
  4048. UPB_VALUE_INIT_CONSTPTR(&fields[49]),
  4049. UPB_ARRAY_EMPTYENT,
  4050. UPB_VALUE_INIT_CONSTPTR(&fields[66]),
  4051. UPB_VALUE_INIT_CONSTPTR(&fields[8]),
  4052. UPB_ARRAY_EMPTYENT,
  4053. UPB_VALUE_INIT_CONSTPTR(&fields[40]),
  4054. UPB_VALUE_INIT_CONSTPTR(&fields[78]),
  4055. UPB_VALUE_INIT_CONSTPTR(&fields[50]),
  4056. UPB_ARRAY_EMPTYENT,
  4057. UPB_ARRAY_EMPTYENT,
  4058. UPB_VALUE_INIT_CONSTPTR(&fields[1]),
  4059. UPB_ARRAY_EMPTYENT,
  4060. UPB_ARRAY_EMPTYENT,
  4061. UPB_ARRAY_EMPTYENT,
  4062. UPB_ARRAY_EMPTYENT,
  4063. UPB_ARRAY_EMPTYENT,
  4064. UPB_ARRAY_EMPTYENT,
  4065. UPB_VALUE_INIT_CONSTPTR(&fields[37]),
  4066. UPB_VALUE_INIT_CONSTPTR(&fields[47]),
  4067. UPB_VALUE_INIT_CONSTPTR(&fields[52]),
  4068. UPB_ARRAY_EMPTYENT,
  4069. UPB_ARRAY_EMPTYENT,
  4070. UPB_ARRAY_EMPTYENT,
  4071. UPB_ARRAY_EMPTYENT,
  4072. UPB_ARRAY_EMPTYENT,
  4073. UPB_VALUE_INIT_CONSTPTR(&fields[41]),
  4074. UPB_VALUE_INIT_CONSTPTR(&fields[12]),
  4075. UPB_VALUE_INIT_CONSTPTR(&fields[46]),
  4076. UPB_VALUE_INIT_CONSTPTR(&fields[27]),
  4077. UPB_VALUE_INIT_CONSTPTR(&fields[69]),
  4078. UPB_VALUE_INIT_CONSTPTR(&fields[70]),
  4079. UPB_VALUE_INIT_CONSTPTR(&fields[4]),
  4080. UPB_VALUE_INIT_CONSTPTR(&fields[51]),
  4081. UPB_ARRAY_EMPTYENT,
  4082. UPB_VALUE_INIT_CONSTPTR(&fields[3]),
  4083. UPB_VALUE_INIT_CONSTPTR(&fields[58]),
  4084. UPB_VALUE_INIT_CONSTPTR(&fields[6]),
  4085. UPB_ARRAY_EMPTYENT,
  4086. UPB_VALUE_INIT_CONSTPTR(&fields[28]),
  4087. UPB_ARRAY_EMPTYENT,
  4088. UPB_ARRAY_EMPTYENT,
  4089. UPB_ARRAY_EMPTYENT,
  4090. UPB_VALUE_INIT_CONSTPTR(&fields[11]),
  4091. UPB_VALUE_INIT_CONSTPTR(&fields[79]),
  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_ARRAY_EMPTYENT,
  4111. UPB_ARRAY_EMPTYENT,
  4112. UPB_ARRAY_EMPTYENT,
  4113. UPB_ARRAY_EMPTYENT,
  4114. UPB_VALUE_INIT_CONSTPTR(&fields[34]),
  4115. UPB_VALUE_INIT_CONSTPTR(&fields[57]),
  4116. UPB_VALUE_INIT_CONSTPTR(&fields[5]),
  4117. UPB_VALUE_INIT_CONSTPTR(&fields[32]),
  4118. UPB_VALUE_INIT_CONSTPTR(&fields[10]),
  4119. UPB_VALUE_INIT_CONSTPTR(&fields[63]),
  4120. UPB_VALUE_INIT_CONSTPTR(&fields[13]),
  4121. UPB_VALUE_INIT_CONSTPTR(&fields[53]),
  4122. UPB_VALUE_INIT_CONSTPTR(&fields[64]),
  4123. UPB_VALUE_INIT_CONSTPTR(&fields[61]),
  4124. UPB_VALUE_INIT_CONSTPTR(&fields[80]),
  4125. UPB_ARRAY_EMPTYENT,
  4126. UPB_VALUE_INIT_CONSTPTR(&fields[17]),
  4127. UPB_ARRAY_EMPTYENT,
  4128. UPB_VALUE_INIT_CONSTPTR(&fields[26]),
  4129. UPB_ARRAY_EMPTYENT,
  4130. UPB_ARRAY_EMPTYENT,
  4131. UPB_ARRAY_EMPTYENT,
  4132. UPB_ARRAY_EMPTYENT,
  4133. UPB_ARRAY_EMPTYENT,
  4134. UPB_ARRAY_EMPTYENT,
  4135. UPB_VALUE_INIT_CONSTPTR(&fields[25]),
  4136. UPB_VALUE_INIT_CONSTPTR(&fields[48]),
  4137. UPB_VALUE_INIT_CONSTPTR(&fields[24]),
  4138. UPB_VALUE_INIT_CONSTPTR(&fields[18]),
  4139. UPB_ARRAY_EMPTYENT,
  4140. UPB_ARRAY_EMPTYENT,
  4141. UPB_ARRAY_EMPTYENT,
  4142. UPB_ARRAY_EMPTYENT,
  4143. UPB_VALUE_INIT_CONSTPTR(&fields[2]),
  4144. UPB_VALUE_INIT_CONSTPTR(&fields[23]),
  4145. UPB_VALUE_INIT_CONSTPTR(&fields[62]),
  4146. UPB_ARRAY_EMPTYENT,
  4147. UPB_VALUE_INIT_CONSTPTR(&fields[22]),
  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_ARRAY_EMPTYENT,
  4189. UPB_ARRAY_EMPTYENT,
  4190. UPB_ARRAY_EMPTYENT,
  4191. UPB_ARRAY_EMPTYENT,
  4192. UPB_VALUE_INIT_CONSTPTR(&fields[31]),
  4193. UPB_VALUE_INIT_CONSTPTR(&fields[45]),
  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_ARRAY_EMPTYENT,
  4205. UPB_ARRAY_EMPTYENT,
  4206. UPB_ARRAY_EMPTYENT,
  4207. UPB_ARRAY_EMPTYENT,
  4208. UPB_VALUE_INIT_CONSTPTR(&fields[39]),
  4209. UPB_VALUE_INIT_CONSTPTR(&fields[20]),
  4210. UPB_VALUE_INIT_CONSTPTR(&fields[56]),
  4211. UPB_VALUE_INIT_CONSTPTR(&fields[55]),
  4212. UPB_ARRAY_EMPTYENT,
  4213. UPB_ARRAY_EMPTYENT,
  4214. UPB_ARRAY_EMPTYENT,
  4215. UPB_ARRAY_EMPTYENT,
  4216. UPB_ARRAY_EMPTYENT,
  4217. UPB_VALUE_INIT_CONSTPTR(&fields[35]),
  4218. UPB_VALUE_INIT_CONSTPTR(&fields[33]),
  4219. UPB_VALUE_INIT_CONSTPTR(&fields[54]),
  4220. UPB_ARRAY_EMPTYENT,
  4221. UPB_ARRAY_EMPTYENT,
  4222. UPB_ARRAY_EMPTYENT,
  4223. UPB_ARRAY_EMPTYENT,
  4224. UPB_ARRAY_EMPTYENT,
  4225. UPB_VALUE_INIT_CONSTPTR(&fields[30]),
  4226. UPB_ARRAY_EMPTYENT,
  4227. UPB_VALUE_INIT_CONSTPTR(&fields[59]),
  4228. UPB_VALUE_INIT_CONSTPTR(&fields[65]),
  4229. UPB_VALUE_INIT_CONSTPTR(&fields[29]),
  4230. UPB_VALUE_INIT_CONSTPTR(&fields[68]),
  4231. UPB_ARRAY_EMPTYENT,
  4232. UPB_ARRAY_EMPTYENT,
  4233. UPB_VALUE_INIT_CONSTPTR(&fields[36]),
  4234. UPB_VALUE_INIT_CONSTPTR(&fields[19]),
  4235. UPB_VALUE_INIT_CONSTPTR(&fields[60]),
  4236. UPB_VALUE_INIT_CONSTPTR(&fields[43]),
  4237. UPB_VALUE_INIT_CONSTPTR(&fields[7]),
  4238. UPB_VALUE_INIT_CONSTPTR(&fields[67]),
  4239. UPB_VALUE_INIT_CONSTPTR(&fields[0]),
  4240. UPB_ARRAY_EMPTYENT,
  4241. UPB_VALUE_INIT_CONSTPTR(&fields[42]),
  4242. UPB_VALUE_INIT_CONSTPTR(&fields[21]),
  4243. UPB_ARRAY_EMPTYENT,
  4244. UPB_VALUE_INIT_CONSTPTR("LABEL_OPTIONAL"),
  4245. UPB_VALUE_INIT_CONSTPTR("LABEL_REQUIRED"),
  4246. UPB_VALUE_INIT_CONSTPTR("LABEL_REPEATED"),
  4247. UPB_ARRAY_EMPTYENT,
  4248. UPB_VALUE_INIT_CONSTPTR("TYPE_DOUBLE"),
  4249. UPB_VALUE_INIT_CONSTPTR("TYPE_FLOAT"),
  4250. UPB_VALUE_INIT_CONSTPTR("TYPE_INT64"),
  4251. UPB_VALUE_INIT_CONSTPTR("TYPE_UINT64"),
  4252. UPB_VALUE_INIT_CONSTPTR("TYPE_INT32"),
  4253. UPB_VALUE_INIT_CONSTPTR("TYPE_FIXED64"),
  4254. UPB_VALUE_INIT_CONSTPTR("TYPE_FIXED32"),
  4255. UPB_VALUE_INIT_CONSTPTR("TYPE_BOOL"),
  4256. UPB_VALUE_INIT_CONSTPTR("TYPE_STRING"),
  4257. UPB_VALUE_INIT_CONSTPTR("TYPE_GROUP"),
  4258. UPB_VALUE_INIT_CONSTPTR("TYPE_MESSAGE"),
  4259. UPB_VALUE_INIT_CONSTPTR("TYPE_BYTES"),
  4260. UPB_VALUE_INIT_CONSTPTR("TYPE_UINT32"),
  4261. UPB_VALUE_INIT_CONSTPTR("TYPE_ENUM"),
  4262. UPB_VALUE_INIT_CONSTPTR("TYPE_SFIXED32"),
  4263. UPB_VALUE_INIT_CONSTPTR("TYPE_SFIXED64"),
  4264. UPB_VALUE_INIT_CONSTPTR("TYPE_SINT32"),
  4265. UPB_VALUE_INIT_CONSTPTR("TYPE_SINT64"),
  4266. UPB_VALUE_INIT_CONSTPTR("STRING"),
  4267. UPB_VALUE_INIT_CONSTPTR("CORD"),
  4268. UPB_VALUE_INIT_CONSTPTR("STRING_PIECE"),
  4269. UPB_ARRAY_EMPTYENT,
  4270. UPB_VALUE_INIT_CONSTPTR("SPEED"),
  4271. UPB_VALUE_INIT_CONSTPTR("CODE_SIZE"),
  4272. UPB_VALUE_INIT_CONSTPTR("LITE_RUNTIME"),
  4273. };
  4274. static const upb_symtab symtab = UPB_SYMTAB_INIT(UPB_STRTABLE_INIT(24, 31, UPB_CTYPE_PTR, 5, &strentries[204]), &reftables[210], &reftables[211]);
  4275. const upb_symtab *upbdefs_google_protobuf_descriptor(const void *owner) {
  4276. upb_symtab_ref(&symtab, owner);
  4277. return &symtab;
  4278. }
  4279. #ifdef UPB_DEBUG_REFS
  4280. static upb_inttable reftables[212] = {
  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. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4490. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4491. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4492. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4493. };
  4494. #endif
  4495. /*
  4496. * upb - a minimalist implementation of protocol buffers.
  4497. *
  4498. * Copyright (c) 2008-2009 Google Inc. See LICENSE for details.
  4499. * Author: Josh Haberman <jhaberman@gmail.com>
  4500. *
  4501. * XXX: The routines in this file that consume a string do not currently
  4502. * support having the string span buffers. In the future, as upb_sink and
  4503. * its buffering/sharing functionality evolve there should be an easy and
  4504. * idiomatic way of correctly handling this case. For now, we accept this
  4505. * limitation since we currently only parse descriptors from single strings.
  4506. */
  4507. #include <errno.h>
  4508. #include <stdlib.h>
  4509. #include <string.h>
  4510. static char *upb_strndup(const char *buf, size_t n) {
  4511. char *ret = malloc(n + 1);
  4512. if (!ret) return NULL;
  4513. memcpy(ret, buf, n);
  4514. ret[n] = '\0';
  4515. return ret;
  4516. }
  4517. // Returns a newly allocated string that joins input strings together, for
  4518. // example:
  4519. // join("Foo.Bar", "Baz") -> "Foo.Bar.Baz"
  4520. // join("", "Baz") -> "Baz"
  4521. // Caller owns a ref on the returned string.
  4522. static char *upb_join(const char *base, const char *name) {
  4523. if (!base || strlen(base) == 0) {
  4524. return upb_strdup(name);
  4525. } else {
  4526. char *ret = malloc(strlen(base) + strlen(name) + 2);
  4527. ret[0] = '\0';
  4528. strcat(ret, base);
  4529. strcat(ret, ".");
  4530. strcat(ret, name);
  4531. return ret;
  4532. }
  4533. }
  4534. /* upb_deflist ****************************************************************/
  4535. void upb_deflist_init(upb_deflist *l) {
  4536. l->size = 0;
  4537. l->defs = NULL;
  4538. l->len = 0;
  4539. l->owned = true;
  4540. }
  4541. void upb_deflist_uninit(upb_deflist *l) {
  4542. if (l->owned)
  4543. for(size_t i = 0; i < l->len; i++)
  4544. upb_def_unref(l->defs[i], l);
  4545. free(l->defs);
  4546. }
  4547. bool upb_deflist_push(upb_deflist *l, upb_def *d) {
  4548. if(++l->len >= l->size) {
  4549. size_t new_size = UPB_MAX(l->size, 4);
  4550. new_size *= 2;
  4551. l->defs = realloc(l->defs, new_size * sizeof(void *));
  4552. if (!l->defs) return false;
  4553. l->size = new_size;
  4554. }
  4555. l->defs[l->len - 1] = d;
  4556. return true;
  4557. }
  4558. void upb_deflist_donaterefs(upb_deflist *l, void *owner) {
  4559. assert(l->owned);
  4560. for (size_t i = 0; i < l->len; i++)
  4561. upb_def_donateref(l->defs[i], l, owner);
  4562. l->owned = false;
  4563. }
  4564. static upb_def *upb_deflist_last(upb_deflist *l) {
  4565. return l->defs[l->len-1];
  4566. }
  4567. // Qualify the defname for all defs starting with offset "start" with "str".
  4568. static void upb_deflist_qualify(upb_deflist *l, char *str, int32_t start) {
  4569. for (uint32_t i = start; i < l->len; i++) {
  4570. upb_def *def = l->defs[i];
  4571. char *name = upb_join(str, upb_def_fullname(def));
  4572. upb_def_setfullname(def, name, NULL);
  4573. free(name);
  4574. }
  4575. }
  4576. /* upb_descreader ************************************************************/
  4577. void upb_descreader_init(upb_descreader *r, const upb_handlers *handlers,
  4578. upb_status *status) {
  4579. UPB_UNUSED(status);
  4580. upb_deflist_init(&r->defs);
  4581. upb_sink_reset(upb_descreader_input(r), handlers, r);
  4582. r->stack_len = 0;
  4583. r->name = NULL;
  4584. r->default_string = NULL;
  4585. }
  4586. void upb_descreader_uninit(upb_descreader *r) {
  4587. free(r->name);
  4588. upb_deflist_uninit(&r->defs);
  4589. free(r->default_string);
  4590. while (r->stack_len > 0) {
  4591. upb_descreader_frame *f = &r->stack[--r->stack_len];
  4592. free(f->name);
  4593. }
  4594. }
  4595. upb_def **upb_descreader_getdefs(upb_descreader *r, void *owner, int *n) {
  4596. *n = r->defs.len;
  4597. upb_deflist_donaterefs(&r->defs, owner);
  4598. return r->defs.defs;
  4599. }
  4600. upb_sink *upb_descreader_input(upb_descreader *r) {
  4601. return &r->sink;
  4602. }
  4603. static upb_msgdef *upb_descreader_top(upb_descreader *r) {
  4604. assert(r->stack_len > 1);
  4605. int index = r->stack[r->stack_len-1].start - 1;
  4606. assert(index >= 0);
  4607. return upb_downcast_msgdef_mutable(r->defs.defs[index]);
  4608. }
  4609. static upb_def *upb_descreader_last(upb_descreader *r) {
  4610. return upb_deflist_last(&r->defs);
  4611. }
  4612. // Start/end handlers for FileDescriptorProto and DescriptorProto (the two
  4613. // entities that have names and can contain sub-definitions.
  4614. void upb_descreader_startcontainer(upb_descreader *r) {
  4615. upb_descreader_frame *f = &r->stack[r->stack_len++];
  4616. f->start = r->defs.len;
  4617. f->name = NULL;
  4618. }
  4619. void upb_descreader_endcontainer(upb_descreader *r) {
  4620. upb_descreader_frame *f = &r->stack[--r->stack_len];
  4621. upb_deflist_qualify(&r->defs, f->name, f->start);
  4622. free(f->name);
  4623. f->name = NULL;
  4624. }
  4625. void upb_descreader_setscopename(upb_descreader *r, char *str) {
  4626. upb_descreader_frame *f = &r->stack[r->stack_len-1];
  4627. free(f->name);
  4628. f->name = str;
  4629. }
  4630. // Handlers for google.protobuf.FileDescriptorProto.
  4631. static bool file_startmsg(void *r, const void *hd) {
  4632. UPB_UNUSED(hd);
  4633. upb_descreader_startcontainer(r);
  4634. return true;
  4635. }
  4636. static bool file_endmsg(void *closure, const void *hd, upb_status *status) {
  4637. UPB_UNUSED(hd);
  4638. UPB_UNUSED(status);
  4639. upb_descreader *r = closure;
  4640. upb_descreader_endcontainer(r);
  4641. return true;
  4642. }
  4643. static size_t file_onpackage(void *closure, const void *hd, const char *buf,
  4644. size_t n, const upb_bufhandle *handle) {
  4645. UPB_UNUSED(hd);
  4646. UPB_UNUSED(handle);
  4647. upb_descreader *r = closure;
  4648. // XXX: see comment at the top of the file.
  4649. upb_descreader_setscopename(r, upb_strndup(buf, n));
  4650. return n;
  4651. }
  4652. // Handlers for google.protobuf.EnumValueDescriptorProto.
  4653. static bool enumval_startmsg(void *closure, const void *hd) {
  4654. UPB_UNUSED(hd);
  4655. upb_descreader *r = closure;
  4656. r->saw_number = false;
  4657. r->saw_name = false;
  4658. return true;
  4659. }
  4660. static size_t enumval_onname(void *closure, const void *hd, const char *buf,
  4661. size_t n, const upb_bufhandle *handle) {
  4662. UPB_UNUSED(hd);
  4663. UPB_UNUSED(handle);
  4664. upb_descreader *r = closure;
  4665. // XXX: see comment at the top of the file.
  4666. free(r->name);
  4667. r->name = upb_strndup(buf, n);
  4668. r->saw_name = true;
  4669. return n;
  4670. }
  4671. static bool enumval_onnumber(void *closure, const void *hd, int32_t val) {
  4672. UPB_UNUSED(hd);
  4673. upb_descreader *r = closure;
  4674. r->number = val;
  4675. r->saw_number = true;
  4676. return true;
  4677. }
  4678. static bool enumval_endmsg(void *closure, const void *hd, upb_status *status) {
  4679. UPB_UNUSED(hd);
  4680. upb_descreader *r = closure;
  4681. if(!r->saw_number || !r->saw_name) {
  4682. upb_status_seterrmsg(status, "Enum value missing name or number.");
  4683. return false;
  4684. }
  4685. upb_enumdef *e = upb_downcast_enumdef_mutable(upb_descreader_last(r));
  4686. upb_enumdef_addval(e, r->name, r->number, status);
  4687. free(r->name);
  4688. r->name = NULL;
  4689. return true;
  4690. }
  4691. // Handlers for google.protobuf.EnumDescriptorProto.
  4692. static bool enum_startmsg(void *closure, const void *hd) {
  4693. UPB_UNUSED(hd);
  4694. upb_descreader *r = closure;
  4695. upb_deflist_push(&r->defs, UPB_UPCAST(upb_enumdef_new(&r->defs)));
  4696. return true;
  4697. }
  4698. static bool enum_endmsg(void *closure, const void *hd, upb_status *status) {
  4699. UPB_UNUSED(hd);
  4700. upb_descreader *r = closure;
  4701. upb_enumdef *e = upb_downcast_enumdef_mutable(upb_descreader_last(r));
  4702. if (upb_def_fullname(upb_descreader_last(r)) == NULL) {
  4703. upb_status_seterrmsg(status, "Enum had no name.");
  4704. return false;
  4705. }
  4706. if (upb_enumdef_numvals(e) == 0) {
  4707. upb_status_seterrmsg(status, "Enum had no values.");
  4708. return false;
  4709. }
  4710. return true;
  4711. }
  4712. static size_t enum_onname(void *closure, const void *hd, const char *buf,
  4713. size_t n, const upb_bufhandle *handle) {
  4714. UPB_UNUSED(hd);
  4715. UPB_UNUSED(handle);
  4716. upb_descreader *r = closure;
  4717. // XXX: see comment at the top of the file.
  4718. char *fullname = upb_strndup(buf, n);
  4719. upb_def_setfullname(upb_descreader_last(r), fullname, NULL);
  4720. free(fullname);
  4721. return n;
  4722. }
  4723. // Handlers for google.protobuf.FieldDescriptorProto
  4724. static bool field_startmsg(void *closure, const void *hd) {
  4725. UPB_UNUSED(hd);
  4726. upb_descreader *r = closure;
  4727. r->f = upb_fielddef_new(&r->defs);
  4728. free(r->default_string);
  4729. r->default_string = NULL;
  4730. // fielddefs default to packed, but descriptors default to non-packed.
  4731. upb_fielddef_setpacked(r->f, false);
  4732. return true;
  4733. }
  4734. // Converts the default value in string "str" into "d". Passes a ref on str.
  4735. // Returns true on success.
  4736. static bool parse_default(char *str, upb_fielddef *f) {
  4737. bool success = true;
  4738. char *end;
  4739. switch (upb_fielddef_type(f)) {
  4740. case UPB_TYPE_INT32: {
  4741. long val = strtol(str, &end, 0);
  4742. if (val > INT32_MAX || val < INT32_MIN || errno == ERANGE || *end)
  4743. success = false;
  4744. else
  4745. upb_fielddef_setdefaultint32(f, val);
  4746. break;
  4747. }
  4748. case UPB_TYPE_INT64: {
  4749. long long val = strtoll(str, &end, 0);
  4750. if (val > INT64_MAX || val < INT64_MIN || errno == ERANGE || *end)
  4751. success = false;
  4752. else
  4753. upb_fielddef_setdefaultint64(f, val);
  4754. break;
  4755. }
  4756. case UPB_TYPE_UINT32: {
  4757. long val = strtoul(str, &end, 0);
  4758. if (val > UINT32_MAX || errno == ERANGE || *end)
  4759. success = false;
  4760. else
  4761. upb_fielddef_setdefaultuint32(f, val);
  4762. break;
  4763. }
  4764. case UPB_TYPE_UINT64: {
  4765. unsigned long long val = strtoull(str, &end, 0);
  4766. if (val > UINT64_MAX || errno == ERANGE || *end)
  4767. success = false;
  4768. else
  4769. upb_fielddef_setdefaultuint64(f, val);
  4770. break;
  4771. }
  4772. case UPB_TYPE_DOUBLE: {
  4773. double val = strtod(str, &end);
  4774. if (errno == ERANGE || *end)
  4775. success = false;
  4776. else
  4777. upb_fielddef_setdefaultdouble(f, val);
  4778. break;
  4779. }
  4780. case UPB_TYPE_FLOAT: {
  4781. float val = strtof(str, &end);
  4782. if (errno == ERANGE || *end)
  4783. success = false;
  4784. else
  4785. upb_fielddef_setdefaultfloat(f, val);
  4786. break;
  4787. }
  4788. case UPB_TYPE_BOOL: {
  4789. if (strcmp(str, "false") == 0)
  4790. upb_fielddef_setdefaultbool(f, false);
  4791. else if (strcmp(str, "true") == 0)
  4792. upb_fielddef_setdefaultbool(f, true);
  4793. else
  4794. success = false;
  4795. break;
  4796. }
  4797. default: abort();
  4798. }
  4799. return success;
  4800. }
  4801. static bool field_endmsg(void *closure, const void *hd, upb_status *status) {
  4802. UPB_UNUSED(hd);
  4803. upb_descreader *r = closure;
  4804. upb_fielddef *f = r->f;
  4805. // TODO: verify that all required fields were present.
  4806. assert(upb_fielddef_number(f) != 0);
  4807. assert(upb_fielddef_name(f) != NULL);
  4808. assert((upb_fielddef_subdefname(f) != NULL) == upb_fielddef_hassubdef(f));
  4809. if (r->default_string) {
  4810. if (upb_fielddef_issubmsg(f)) {
  4811. upb_status_seterrmsg(status, "Submessages cannot have defaults.");
  4812. return false;
  4813. }
  4814. if (upb_fielddef_isstring(f) || upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  4815. upb_fielddef_setdefaultcstr(f, r->default_string, NULL);
  4816. } else {
  4817. if (r->default_string && !parse_default(r->default_string, f)) {
  4818. // We don't worry too much about giving a great error message since the
  4819. // compiler should have ensured this was correct.
  4820. upb_status_seterrmsg(status, "Error converting default value.");
  4821. return false;
  4822. }
  4823. }
  4824. }
  4825. return true;
  4826. }
  4827. static bool field_onlazy(void *closure, const void *hd, bool val) {
  4828. UPB_UNUSED(hd);
  4829. upb_descreader *r = closure;
  4830. upb_fielddef_setlazy(r->f, val);
  4831. return true;
  4832. }
  4833. static bool field_onpacked(void *closure, const void *hd, bool val) {
  4834. UPB_UNUSED(hd);
  4835. upb_descreader *r = closure;
  4836. upb_fielddef_setpacked(r->f, val);
  4837. return true;
  4838. }
  4839. static bool field_ontype(void *closure, const void *hd, int32_t val) {
  4840. UPB_UNUSED(hd);
  4841. upb_descreader *r = closure;
  4842. upb_fielddef_setdescriptortype(r->f, val);
  4843. return true;
  4844. }
  4845. static bool field_onlabel(void *closure, const void *hd, int32_t val) {
  4846. UPB_UNUSED(hd);
  4847. upb_descreader *r = closure;
  4848. upb_fielddef_setlabel(r->f, val);
  4849. return true;
  4850. }
  4851. static bool field_onnumber(void *closure, const void *hd, int32_t val) {
  4852. UPB_UNUSED(hd);
  4853. upb_descreader *r = closure;
  4854. bool ok = upb_fielddef_setnumber(r->f, val, NULL);
  4855. UPB_ASSERT_VAR(ok, ok);
  4856. return true;
  4857. }
  4858. static size_t field_onname(void *closure, const void *hd, const char *buf,
  4859. size_t n, const upb_bufhandle *handle) {
  4860. UPB_UNUSED(hd);
  4861. UPB_UNUSED(handle);
  4862. upb_descreader *r = closure;
  4863. // XXX: see comment at the top of the file.
  4864. char *name = upb_strndup(buf, n);
  4865. upb_fielddef_setname(r->f, name, NULL);
  4866. free(name);
  4867. return n;
  4868. }
  4869. static size_t field_ontypename(void *closure, const void *hd, const char *buf,
  4870. size_t n, const upb_bufhandle *handle) {
  4871. UPB_UNUSED(hd);
  4872. UPB_UNUSED(handle);
  4873. upb_descreader *r = closure;
  4874. // XXX: see comment at the top of the file.
  4875. char *name = upb_strndup(buf, n);
  4876. upb_fielddef_setsubdefname(r->f, name, NULL);
  4877. free(name);
  4878. return n;
  4879. }
  4880. static size_t field_onextendee(void *closure, const void *hd, const char *buf,
  4881. size_t n, const upb_bufhandle *handle) {
  4882. UPB_UNUSED(hd);
  4883. UPB_UNUSED(handle);
  4884. upb_descreader *r = closure;
  4885. // XXX: see comment at the top of the file.
  4886. char *name = upb_strndup(buf, n);
  4887. upb_fielddef_setcontainingtypename(r->f, name, NULL);
  4888. free(name);
  4889. return n;
  4890. }
  4891. static size_t field_ondefaultval(void *closure, const void *hd, const char *buf,
  4892. size_t n, const upb_bufhandle *handle) {
  4893. UPB_UNUSED(hd);
  4894. UPB_UNUSED(handle);
  4895. upb_descreader *r = closure;
  4896. // Have to convert from string to the correct type, but we might not know the
  4897. // type yet, so we save it as a string until the end of the field.
  4898. // XXX: see comment at the top of the file.
  4899. free(r->default_string);
  4900. r->default_string = upb_strndup(buf, n);
  4901. return n;
  4902. }
  4903. // Handlers for google.protobuf.DescriptorProto (representing a message).
  4904. static bool msg_startmsg(void *closure, const void *hd) {
  4905. UPB_UNUSED(hd);
  4906. upb_descreader *r = closure;
  4907. upb_deflist_push(&r->defs, UPB_UPCAST(upb_msgdef_new(&r->defs)));
  4908. upb_descreader_startcontainer(r);
  4909. return true;
  4910. }
  4911. static bool msg_endmsg(void *closure, const void *hd, upb_status *status) {
  4912. UPB_UNUSED(hd);
  4913. upb_descreader *r = closure;
  4914. upb_msgdef *m = upb_descreader_top(r);
  4915. if(!upb_def_fullname(UPB_UPCAST(m))) {
  4916. upb_status_seterrmsg(status, "Encountered message with no name.");
  4917. return false;
  4918. }
  4919. upb_descreader_endcontainer(r);
  4920. return true;
  4921. }
  4922. static size_t msg_onname(void *closure, const void *hd, const char *buf,
  4923. size_t n, const upb_bufhandle *handle) {
  4924. UPB_UNUSED(hd);
  4925. UPB_UNUSED(handle);
  4926. upb_descreader *r = closure;
  4927. upb_msgdef *m = upb_descreader_top(r);
  4928. // XXX: see comment at the top of the file.
  4929. char *name = upb_strndup(buf, n);
  4930. upb_def_setfullname(UPB_UPCAST(m), name, NULL);
  4931. upb_descreader_setscopename(r, name); // Passes ownership of name.
  4932. return n;
  4933. }
  4934. static bool msg_onendfield(void *closure, const void *hd) {
  4935. UPB_UNUSED(hd);
  4936. upb_descreader *r = closure;
  4937. upb_msgdef *m = upb_descreader_top(r);
  4938. upb_msgdef_addfield(m, r->f, &r->defs, NULL);
  4939. r->f = NULL;
  4940. return true;
  4941. }
  4942. static bool pushextension(void *closure, const void *hd) {
  4943. UPB_UNUSED(hd);
  4944. upb_descreader *r = closure;
  4945. assert(upb_fielddef_containingtypename(r->f));
  4946. upb_fielddef_setisextension(r->f, true);
  4947. upb_deflist_push(&r->defs, UPB_UPCAST(r->f));
  4948. r->f = NULL;
  4949. return true;
  4950. }
  4951. #define D(name) upbdefs_google_protobuf_ ## name(s)
  4952. static void reghandlers(const void *closure, upb_handlers *h) {
  4953. const upb_symtab *s = closure;
  4954. const upb_msgdef *m = upb_handlers_msgdef(h);
  4955. if (m == D(DescriptorProto)) {
  4956. upb_handlers_setstartmsg(h, &msg_startmsg, NULL);
  4957. upb_handlers_setendmsg(h, &msg_endmsg, NULL);
  4958. upb_handlers_setstring(h, D(DescriptorProto_name), &msg_onname, NULL);
  4959. upb_handlers_setendsubmsg(h, D(DescriptorProto_field), &msg_onendfield,
  4960. NULL);
  4961. upb_handlers_setendsubmsg(h, D(DescriptorProto_extension), &pushextension,
  4962. NULL);
  4963. } else if (m == D(FileDescriptorProto)) {
  4964. upb_handlers_setstartmsg(h, &file_startmsg, NULL);
  4965. upb_handlers_setendmsg(h, &file_endmsg, NULL);
  4966. upb_handlers_setstring(h, D(FileDescriptorProto_package), &file_onpackage,
  4967. NULL);
  4968. upb_handlers_setendsubmsg(h, D(FileDescriptorProto_extension), &pushextension,
  4969. NULL);
  4970. } else if (m == D(EnumValueDescriptorProto)) {
  4971. upb_handlers_setstartmsg(h, &enumval_startmsg, NULL);
  4972. upb_handlers_setendmsg(h, &enumval_endmsg, NULL);
  4973. upb_handlers_setstring(h, D(EnumValueDescriptorProto_name), &enumval_onname, NULL);
  4974. upb_handlers_setint32(h, D(EnumValueDescriptorProto_number), &enumval_onnumber,
  4975. NULL);
  4976. } else if (m == D(EnumDescriptorProto)) {
  4977. upb_handlers_setstartmsg(h, &enum_startmsg, NULL);
  4978. upb_handlers_setendmsg(h, &enum_endmsg, NULL);
  4979. upb_handlers_setstring(h, D(EnumDescriptorProto_name), &enum_onname, NULL);
  4980. } else if (m == D(FieldDescriptorProto)) {
  4981. upb_handlers_setstartmsg(h, &field_startmsg, NULL);
  4982. upb_handlers_setendmsg(h, &field_endmsg, NULL);
  4983. upb_handlers_setint32(h, D(FieldDescriptorProto_type), &field_ontype,
  4984. NULL);
  4985. upb_handlers_setint32(h, D(FieldDescriptorProto_label), &field_onlabel,
  4986. NULL);
  4987. upb_handlers_setint32(h, D(FieldDescriptorProto_number), &field_onnumber,
  4988. NULL);
  4989. upb_handlers_setstring(h, D(FieldDescriptorProto_name), &field_onname,
  4990. NULL);
  4991. upb_handlers_setstring(h, D(FieldDescriptorProto_type_name),
  4992. &field_ontypename, NULL);
  4993. upb_handlers_setstring(h, D(FieldDescriptorProto_extendee),
  4994. &field_onextendee, NULL);
  4995. upb_handlers_setstring(h, D(FieldDescriptorProto_default_value),
  4996. &field_ondefaultval, NULL);
  4997. } else if (m == D(FieldOptions)) {
  4998. upb_handlers_setbool(h, D(FieldOptions_lazy), &field_onlazy, NULL);
  4999. upb_handlers_setbool(h, D(FieldOptions_packed), &field_onpacked, NULL);
  5000. }
  5001. }
  5002. #undef D
  5003. const upb_handlers *upb_descreader_newhandlers(const void *owner) {
  5004. const upb_symtab *s = upbdefs_google_protobuf_descriptor(&s);
  5005. const upb_handlers *h = upb_handlers_newfrozen(
  5006. upbdefs_google_protobuf_FileDescriptorSet(s), owner, reghandlers, s);
  5007. upb_symtab_unref(s, &s);
  5008. return h;
  5009. }
  5010. /*
  5011. * upb - a minimalist implementation of protocol buffers.
  5012. *
  5013. * Copyright (c) 2013 Google Inc. See LICENSE for details.
  5014. * Author: Josh Haberman <jhaberman@gmail.com>
  5015. *
  5016. * Code to compile a upb::Handlers into bytecode for decoding a protobuf
  5017. * according to that specific schema and destination handlers.
  5018. *
  5019. * Compiling to bytecode is always the first step. If we are using the
  5020. * interpreted decoder we leave it as bytecode and interpret that. If we are
  5021. * using a JIT decoder we use a code generator to turn the bytecode into native
  5022. * code, LLVM IR, etc.
  5023. *
  5024. * Bytecode definition is in decoder.int.h.
  5025. */
  5026. #include <stdarg.h>
  5027. #ifdef UPB_DUMP_BYTECODE
  5028. #include <stdio.h>
  5029. #endif
  5030. #define MAXLABEL 5
  5031. #define EMPTYLABEL -1
  5032. /* mgroup *********************************************************************/
  5033. static void freegroup(upb_refcounted *r) {
  5034. mgroup *g = (mgroup*)r;
  5035. upb_inttable_uninit(&g->methods);
  5036. #ifdef UPB_USE_JIT_X64
  5037. upb_pbdecoder_freejit(g);
  5038. #endif
  5039. free(g->bytecode);
  5040. free(g);
  5041. }
  5042. static void visitgroup(const upb_refcounted *r, upb_refcounted_visit *visit,
  5043. void *closure) {
  5044. const mgroup *g = (const mgroup*)r;
  5045. upb_inttable_iter i;
  5046. upb_inttable_begin(&i, &g->methods);
  5047. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5048. upb_pbdecodermethod *method = upb_value_getptr(upb_inttable_iter_value(&i));
  5049. visit(r, UPB_UPCAST(method), closure);
  5050. }
  5051. }
  5052. mgroup *newgroup(const void *owner) {
  5053. mgroup *g = malloc(sizeof(*g));
  5054. static const struct upb_refcounted_vtbl vtbl = {visitgroup, freegroup};
  5055. upb_refcounted_init(UPB_UPCAST(g), &vtbl, owner);
  5056. upb_inttable_init(&g->methods, UPB_CTYPE_PTR);
  5057. g->bytecode = NULL;
  5058. g->bytecode_end = NULL;
  5059. return g;
  5060. }
  5061. /* upb_pbdecodermethod ********************************************************/
  5062. static void freemethod(upb_refcounted *r) {
  5063. upb_pbdecodermethod *method = (upb_pbdecodermethod*)r;
  5064. upb_byteshandler_uninit(&method->input_handler_);
  5065. if (method->dest_handlers_) {
  5066. upb_handlers_unref(method->dest_handlers_, method);
  5067. }
  5068. upb_inttable_uninit(&method->dispatch);
  5069. free(method);
  5070. }
  5071. static void visitmethod(const upb_refcounted *r, upb_refcounted_visit *visit,
  5072. void *closure) {
  5073. const upb_pbdecodermethod *m = (const upb_pbdecodermethod*)r;
  5074. visit(r, m->group, closure);
  5075. }
  5076. static upb_pbdecodermethod *newmethod(const upb_handlers *dest_handlers,
  5077. mgroup *group) {
  5078. static const struct upb_refcounted_vtbl vtbl = {visitmethod, freemethod};
  5079. upb_pbdecodermethod *ret = malloc(sizeof(*ret));
  5080. upb_refcounted_init(UPB_UPCAST(ret), &vtbl, &ret);
  5081. upb_byteshandler_init(&ret->input_handler_);
  5082. // The method references the group and vice-versa, in a circular reference.
  5083. upb_ref2(ret, group);
  5084. upb_ref2(group, ret);
  5085. upb_inttable_insertptr(&group->methods, dest_handlers, upb_value_ptr(ret));
  5086. upb_refcounted_unref(UPB_UPCAST(ret), &ret);
  5087. ret->group = UPB_UPCAST(group);
  5088. ret->dest_handlers_ = dest_handlers;
  5089. ret->is_native_ = false; // If we JIT, it will update this later.
  5090. upb_inttable_init(&ret->dispatch, UPB_CTYPE_UINT64);
  5091. if (ret->dest_handlers_) {
  5092. upb_handlers_ref(ret->dest_handlers_, ret);
  5093. }
  5094. return ret;
  5095. }
  5096. void upb_pbdecodermethod_ref(const upb_pbdecodermethod *m, const void *owner) {
  5097. upb_refcounted_ref(UPB_UPCAST(m), owner);
  5098. }
  5099. void upb_pbdecodermethod_unref(const upb_pbdecodermethod *m,
  5100. const void *owner) {
  5101. upb_refcounted_unref(UPB_UPCAST(m), owner);
  5102. }
  5103. void upb_pbdecodermethod_donateref(const upb_pbdecodermethod *m,
  5104. const void *from, const void *to) {
  5105. upb_refcounted_donateref(UPB_UPCAST(m), from, to);
  5106. }
  5107. void upb_pbdecodermethod_checkref(const upb_pbdecodermethod *m,
  5108. const void *owner) {
  5109. upb_refcounted_checkref(UPB_UPCAST(m), owner);
  5110. }
  5111. const upb_handlers *upb_pbdecodermethod_desthandlers(
  5112. const upb_pbdecodermethod *m) {
  5113. return m->dest_handlers_;
  5114. }
  5115. const upb_byteshandler *upb_pbdecodermethod_inputhandler(
  5116. const upb_pbdecodermethod *m) {
  5117. return &m->input_handler_;
  5118. }
  5119. bool upb_pbdecodermethod_isnative(const upb_pbdecodermethod *m) {
  5120. return m->is_native_;
  5121. }
  5122. const upb_pbdecodermethod *upb_pbdecodermethod_new(
  5123. const upb_pbdecodermethodopts *opts, const void *owner) {
  5124. upb_pbcodecache cache;
  5125. upb_pbcodecache_init(&cache);
  5126. const upb_pbdecodermethod *ret =
  5127. upb_pbcodecache_getdecodermethod(&cache, opts);
  5128. upb_pbdecodermethod_ref(ret, owner);
  5129. upb_pbcodecache_uninit(&cache);
  5130. return ret;
  5131. }
  5132. /* bytecode compiler **********************************************************/
  5133. // Data used only at compilation time.
  5134. typedef struct {
  5135. mgroup *group;
  5136. uint32_t *pc;
  5137. int fwd_labels[MAXLABEL];
  5138. int back_labels[MAXLABEL];
  5139. // For fields marked "lazy", parse them lazily or eagerly?
  5140. bool lazy;
  5141. } compiler;
  5142. static compiler *newcompiler(mgroup *group, bool lazy) {
  5143. compiler *ret = malloc(sizeof(*ret));
  5144. ret->group = group;
  5145. ret->lazy = lazy;
  5146. for (int i = 0; i < MAXLABEL; i++) {
  5147. ret->fwd_labels[i] = EMPTYLABEL;
  5148. ret->back_labels[i] = EMPTYLABEL;
  5149. }
  5150. return ret;
  5151. }
  5152. static void freecompiler(compiler *c) {
  5153. free(c);
  5154. }
  5155. const size_t ptr_words = sizeof(void*) / sizeof(uint32_t);
  5156. // How many words an instruction is.
  5157. static int instruction_len(uint32_t instr) {
  5158. switch (getop(instr)) {
  5159. case OP_SETDISPATCH: return 1 + ptr_words;
  5160. case OP_TAGN: return 3;
  5161. case OP_SETBIGGROUPNUM: return 2;
  5162. default: return 1;
  5163. }
  5164. }
  5165. bool op_has_longofs(int32_t instruction) {
  5166. switch (getop(instruction)) {
  5167. case OP_CALL:
  5168. case OP_BRANCH:
  5169. case OP_CHECKDELIM:
  5170. return true;
  5171. // The "tag" instructions only have 8 bytes available for the jump target,
  5172. // but that is ok because these opcodes only require short jumps.
  5173. case OP_TAG1:
  5174. case OP_TAG2:
  5175. case OP_TAGN:
  5176. return false;
  5177. default:
  5178. assert(false);
  5179. return false;
  5180. }
  5181. }
  5182. static int32_t getofs(uint32_t instruction) {
  5183. if (op_has_longofs(instruction)) {
  5184. return (int32_t)instruction >> 8;
  5185. } else {
  5186. return (int8_t)(instruction >> 8);
  5187. }
  5188. }
  5189. static void setofs(uint32_t *instruction, int32_t ofs) {
  5190. if (op_has_longofs(*instruction)) {
  5191. *instruction = getop(*instruction) | ofs << 8;
  5192. } else {
  5193. *instruction = (*instruction & ~0xff00) | ((ofs & 0xff) << 8);
  5194. }
  5195. assert(getofs(*instruction) == ofs); // Would fail in cases of overflow.
  5196. }
  5197. static uint32_t pcofs(compiler *c) { return c->pc - c->group->bytecode; }
  5198. // Defines a local label at the current PC location. All previous forward
  5199. // references are updated to point to this location. The location is noted
  5200. // for any future backward references.
  5201. static void label(compiler *c, unsigned int label) {
  5202. assert(label < MAXLABEL);
  5203. int val = c->fwd_labels[label];
  5204. uint32_t *codep = (val == EMPTYLABEL) ? NULL : c->group->bytecode + val;
  5205. while (codep) {
  5206. int ofs = getofs(*codep);
  5207. setofs(codep, c->pc - codep - instruction_len(*codep));
  5208. codep = ofs ? codep + ofs : NULL;
  5209. }
  5210. c->fwd_labels[label] = EMPTYLABEL;
  5211. c->back_labels[label] = pcofs(c);
  5212. }
  5213. // Creates a reference to a numbered label; either a forward reference
  5214. // (positive arg) or backward reference (negative arg). For forward references
  5215. // the value returned now is actually a "next" pointer into a linked list of all
  5216. // instructions that use this label and will be patched later when the label is
  5217. // defined with label().
  5218. //
  5219. // The returned value is the offset that should be written into the instruction.
  5220. static int32_t labelref(compiler *c, int label) {
  5221. assert(label < MAXLABEL);
  5222. if (label == LABEL_DISPATCH) {
  5223. // No resolving required.
  5224. return 0;
  5225. } else if (label < 0) {
  5226. // Backward local label. Relative to the next instruction.
  5227. uint32_t from = (c->pc + 1) - c->group->bytecode;
  5228. return c->back_labels[-label] - from;
  5229. } else {
  5230. // Forward local label: prepend to (possibly-empty) linked list.
  5231. int *lptr = &c->fwd_labels[label];
  5232. int32_t ret = (*lptr == EMPTYLABEL) ? 0 : *lptr - pcofs(c);
  5233. *lptr = pcofs(c);
  5234. return ret;
  5235. }
  5236. }
  5237. static void put32(compiler *c, uint32_t v) {
  5238. mgroup *g = c->group;
  5239. if (c->pc == g->bytecode_end) {
  5240. int ofs = pcofs(c);
  5241. size_t oldsize = g->bytecode_end - g->bytecode;
  5242. size_t newsize = UPB_MAX(oldsize * 2, 64);
  5243. // TODO(haberman): handle OOM.
  5244. g->bytecode = realloc(g->bytecode, newsize * sizeof(uint32_t));
  5245. g->bytecode_end = g->bytecode + newsize;
  5246. c->pc = g->bytecode + ofs;
  5247. }
  5248. *c->pc++ = v;
  5249. }
  5250. static void putop(compiler *c, opcode op, ...) {
  5251. va_list ap;
  5252. va_start(ap, op);
  5253. switch (op) {
  5254. case OP_SETDISPATCH: {
  5255. uintptr_t ptr = (uintptr_t)va_arg(ap, void*);
  5256. put32(c, OP_SETDISPATCH);
  5257. put32(c, ptr);
  5258. if (sizeof(uintptr_t) > sizeof(uint32_t))
  5259. put32(c, (uint64_t)ptr >> 32);
  5260. break;
  5261. }
  5262. case OP_STARTMSG:
  5263. case OP_ENDMSG:
  5264. case OP_PUSHLENDELIM:
  5265. case OP_POP:
  5266. case OP_SETDELIM:
  5267. case OP_HALT:
  5268. case OP_RET:
  5269. case OP_DISPATCH:
  5270. put32(c, op);
  5271. break;
  5272. case OP_PARSE_DOUBLE:
  5273. case OP_PARSE_FLOAT:
  5274. case OP_PARSE_INT64:
  5275. case OP_PARSE_UINT64:
  5276. case OP_PARSE_INT32:
  5277. case OP_PARSE_FIXED64:
  5278. case OP_PARSE_FIXED32:
  5279. case OP_PARSE_BOOL:
  5280. case OP_PARSE_UINT32:
  5281. case OP_PARSE_SFIXED32:
  5282. case OP_PARSE_SFIXED64:
  5283. case OP_PARSE_SINT32:
  5284. case OP_PARSE_SINT64:
  5285. case OP_STARTSEQ:
  5286. case OP_ENDSEQ:
  5287. case OP_STARTSUBMSG:
  5288. case OP_ENDSUBMSG:
  5289. case OP_STARTSTR:
  5290. case OP_STRING:
  5291. case OP_ENDSTR:
  5292. case OP_PUSHTAGDELIM:
  5293. put32(c, op | va_arg(ap, upb_selector_t) << 8);
  5294. break;
  5295. case OP_SETBIGGROUPNUM:
  5296. put32(c, op);
  5297. put32(c, va_arg(ap, int));
  5298. break;
  5299. case OP_CALL: {
  5300. const upb_pbdecodermethod *method = va_arg(ap, upb_pbdecodermethod *);
  5301. put32(c, op | (method->code_base.ofs - (pcofs(c) + 1)) << 8);
  5302. break;
  5303. }
  5304. case OP_CHECKDELIM:
  5305. case OP_BRANCH: {
  5306. uint32_t instruction = op;
  5307. int label = va_arg(ap, int);
  5308. setofs(&instruction, labelref(c, label));
  5309. put32(c, instruction);
  5310. break;
  5311. }
  5312. case OP_TAG1:
  5313. case OP_TAG2: {
  5314. int label = va_arg(ap, int);
  5315. uint64_t tag = va_arg(ap, uint64_t);
  5316. uint32_t instruction = op | (tag << 16);
  5317. assert(tag <= 0xffff);
  5318. setofs(&instruction, labelref(c, label));
  5319. put32(c, instruction);
  5320. break;
  5321. }
  5322. case OP_TAGN: {
  5323. int label = va_arg(ap, int);
  5324. uint64_t tag = va_arg(ap, uint64_t);
  5325. uint32_t instruction = op | (upb_value_size(tag) << 16);
  5326. setofs(&instruction, labelref(c, label));
  5327. put32(c, instruction);
  5328. put32(c, tag);
  5329. put32(c, tag >> 32);
  5330. break;
  5331. }
  5332. }
  5333. va_end(ap);
  5334. }
  5335. #if defined(UPB_USE_JIT_X64) || defined(UPB_DUMP_BYTECODE)
  5336. const char *upb_pbdecoder_getopname(unsigned int op) {
  5337. #define OP(op) [OP_ ## op] = "OP_" #op
  5338. #define T(op) OP(PARSE_##op)
  5339. static const char *names[] = {
  5340. "<no opcode>",
  5341. T(DOUBLE), T(FLOAT), T(INT64), T(UINT64), T(INT32), T(FIXED64), T(FIXED32),
  5342. T(BOOL), T(UINT32), T(SFIXED32), T(SFIXED64), T(SINT32), T(SINT64),
  5343. OP(STARTMSG), OP(ENDMSG), OP(STARTSEQ), OP(ENDSEQ), OP(STARTSUBMSG),
  5344. OP(ENDSUBMSG), OP(STARTSTR), OP(STRING), OP(ENDSTR), OP(CALL), OP(RET),
  5345. OP(PUSHLENDELIM), OP(PUSHTAGDELIM), OP(SETDELIM), OP(CHECKDELIM),
  5346. OP(BRANCH), OP(TAG1), OP(TAG2), OP(TAGN), OP(SETDISPATCH), OP(POP),
  5347. OP(SETBIGGROUPNUM), OP(DISPATCH), OP(HALT),
  5348. };
  5349. return op > OP_HALT ? names[0] : names[op];
  5350. #undef OP
  5351. #undef T
  5352. }
  5353. #endif
  5354. #ifdef UPB_DUMP_BYTECODE
  5355. static void dumpbc(uint32_t *p, uint32_t *end, FILE *f) {
  5356. uint32_t *begin = p;
  5357. while (p < end) {
  5358. fprintf(f, "%p %8tx", p, p - begin);
  5359. uint32_t instr = *p++;
  5360. uint8_t op = getop(instr);
  5361. fprintf(f, " %s", upb_pbdecoder_getopname(op));
  5362. switch ((opcode)op) {
  5363. case OP_SETDISPATCH: {
  5364. const upb_inttable *dispatch;
  5365. memcpy(&dispatch, p, sizeof(void*));
  5366. p += ptr_words;
  5367. const upb_pbdecodermethod *method =
  5368. (void *)((char *)dispatch -
  5369. offsetof(upb_pbdecodermethod, dispatch));
  5370. fprintf(f, " %s", upb_msgdef_fullname(
  5371. upb_handlers_msgdef(method->dest_handlers_)));
  5372. break;
  5373. }
  5374. case OP_DISPATCH:
  5375. case OP_STARTMSG:
  5376. case OP_ENDMSG:
  5377. case OP_PUSHLENDELIM:
  5378. case OP_POP:
  5379. case OP_SETDELIM:
  5380. case OP_HALT:
  5381. case OP_RET:
  5382. break;
  5383. case OP_PARSE_DOUBLE:
  5384. case OP_PARSE_FLOAT:
  5385. case OP_PARSE_INT64:
  5386. case OP_PARSE_UINT64:
  5387. case OP_PARSE_INT32:
  5388. case OP_PARSE_FIXED64:
  5389. case OP_PARSE_FIXED32:
  5390. case OP_PARSE_BOOL:
  5391. case OP_PARSE_UINT32:
  5392. case OP_PARSE_SFIXED32:
  5393. case OP_PARSE_SFIXED64:
  5394. case OP_PARSE_SINT32:
  5395. case OP_PARSE_SINT64:
  5396. case OP_STARTSEQ:
  5397. case OP_ENDSEQ:
  5398. case OP_STARTSUBMSG:
  5399. case OP_ENDSUBMSG:
  5400. case OP_STARTSTR:
  5401. case OP_STRING:
  5402. case OP_ENDSTR:
  5403. case OP_PUSHTAGDELIM:
  5404. fprintf(f, " %d", instr >> 8);
  5405. break;
  5406. case OP_SETBIGGROUPNUM:
  5407. fprintf(f, " %d", *p++);
  5408. break;
  5409. case OP_CHECKDELIM:
  5410. case OP_CALL:
  5411. case OP_BRANCH:
  5412. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  5413. break;
  5414. case OP_TAG1:
  5415. case OP_TAG2: {
  5416. fprintf(f, " tag:0x%x", instr >> 16);
  5417. if (getofs(instr)) {
  5418. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  5419. }
  5420. break;
  5421. }
  5422. case OP_TAGN: {
  5423. uint64_t tag = *p++;
  5424. tag |= (uint64_t)*p++ << 32;
  5425. fprintf(f, " tag:0x%llx", (long long)tag);
  5426. fprintf(f, " n:%d", instr >> 16);
  5427. if (getofs(instr)) {
  5428. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  5429. }
  5430. break;
  5431. }
  5432. }
  5433. fputs("\n", f);
  5434. }
  5435. }
  5436. #endif
  5437. static uint64_t get_encoded_tag(const upb_fielddef *f, int wire_type) {
  5438. uint32_t tag = (upb_fielddef_number(f) << 3) | wire_type;
  5439. uint64_t encoded_tag = upb_vencode32(tag);
  5440. // No tag should be greater than 5 bytes.
  5441. assert(encoded_tag <= 0xffffffffff);
  5442. return encoded_tag;
  5443. }
  5444. static void putchecktag(compiler *c, const upb_fielddef *f,
  5445. int wire_type, int dest) {
  5446. uint64_t tag = get_encoded_tag(f, wire_type);
  5447. switch (upb_value_size(tag)) {
  5448. case 1:
  5449. putop(c, OP_TAG1, dest, tag);
  5450. break;
  5451. case 2:
  5452. putop(c, OP_TAG2, dest, tag);
  5453. break;
  5454. default:
  5455. putop(c, OP_TAGN, dest, tag);
  5456. break;
  5457. }
  5458. }
  5459. static upb_selector_t getsel(const upb_fielddef *f, upb_handlertype_t type) {
  5460. upb_selector_t selector;
  5461. bool ok = upb_handlers_getselector(f, type, &selector);
  5462. UPB_ASSERT_VAR(ok, ok);
  5463. return selector;
  5464. }
  5465. // Takes an existing, primary dispatch table entry and repacks it with a
  5466. // different alternate wire type. Called when we are inserting a secondary
  5467. // dispatch table entry for an alternate wire type.
  5468. static uint64_t repack(uint64_t dispatch, int new_wt2) {
  5469. uint64_t ofs;
  5470. uint8_t wt1;
  5471. uint8_t old_wt2;
  5472. upb_pbdecoder_unpackdispatch(dispatch, &ofs, &wt1, &old_wt2);
  5473. assert(old_wt2 == NO_WIRE_TYPE); // wt2 should not be set yet.
  5474. return upb_pbdecoder_packdispatch(ofs, wt1, new_wt2);
  5475. }
  5476. // Marks the current bytecode position as the dispatch target for this message,
  5477. // field, and wire type.
  5478. static void dispatchtarget(compiler *c, upb_pbdecodermethod *method,
  5479. const upb_fielddef *f, int wire_type) {
  5480. // Offset is relative to msg base.
  5481. uint64_t ofs = pcofs(c) - method->code_base.ofs;
  5482. uint32_t fn = upb_fielddef_number(f);
  5483. upb_inttable *d = &method->dispatch;
  5484. upb_value v;
  5485. if (upb_inttable_remove(d, fn, &v)) {
  5486. // TODO: prioritize based on packed setting in .proto file.
  5487. uint64_t repacked = repack(upb_value_getuint64(v), wire_type);
  5488. upb_inttable_insert(d, fn, upb_value_uint64(repacked));
  5489. upb_inttable_insert(d, fn + UPB_MAX_FIELDNUMBER, upb_value_uint64(ofs));
  5490. } else {
  5491. uint64_t val = upb_pbdecoder_packdispatch(ofs, wire_type, NO_WIRE_TYPE);
  5492. upb_inttable_insert(d, fn, upb_value_uint64(val));
  5493. }
  5494. }
  5495. static void putpush(compiler *c, const upb_fielddef *f) {
  5496. if (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE) {
  5497. putop(c, OP_PUSHLENDELIM);
  5498. } else {
  5499. uint32_t fn = upb_fielddef_number(f);
  5500. if (fn >= 1 << 24) {
  5501. putop(c, OP_PUSHTAGDELIM, 0);
  5502. putop(c, OP_SETBIGGROUPNUM, fn);
  5503. } else {
  5504. putop(c, OP_PUSHTAGDELIM, fn);
  5505. }
  5506. }
  5507. }
  5508. static upb_pbdecodermethod *find_submethod(const compiler *c,
  5509. const upb_pbdecodermethod *method,
  5510. const upb_fielddef *f) {
  5511. const upb_handlers *sub =
  5512. upb_handlers_getsubhandlers(method->dest_handlers_, f);
  5513. upb_value v;
  5514. return upb_inttable_lookupptr(&c->group->methods, sub, &v)
  5515. ? upb_value_getptr(v)
  5516. : NULL;
  5517. }
  5518. static void putsel(compiler *c, opcode op, upb_selector_t sel,
  5519. const upb_handlers *h) {
  5520. if (upb_handlers_gethandler(h, sel)) {
  5521. putop(c, op, sel);
  5522. }
  5523. }
  5524. // Puts an opcode to call a callback, but only if a callback actually exists for
  5525. // this field and handler type.
  5526. static void maybeput(compiler *c, opcode op, const upb_handlers *h,
  5527. const upb_fielddef *f, upb_handlertype_t type) {
  5528. putsel(c, op, getsel(f, type), h);
  5529. }
  5530. static bool haslazyhandlers(const upb_handlers *h, const upb_fielddef *f) {
  5531. if (!upb_fielddef_lazy(f))
  5532. return false;
  5533. return upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STARTSTR)) ||
  5534. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STRING)) ||
  5535. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_ENDSTR));
  5536. }
  5537. /* bytecode compiler code generation ******************************************/
  5538. // Symbolic names for our local labels.
  5539. #define LABEL_LOOPSTART 1 // Top of a repeated field loop.
  5540. #define LABEL_LOOPBREAK 2 // To jump out of a repeated loop
  5541. #define LABEL_FIELD 3 // Jump backward to find the most recent field.
  5542. #define LABEL_ENDMSG 4 // To reach the OP_ENDMSG instr for this msg.
  5543. // Generates bytecode to parse a single non-lazy message field.
  5544. static void generate_msgfield(compiler *c, const upb_fielddef *f,
  5545. upb_pbdecodermethod *method) {
  5546. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  5547. const upb_pbdecodermethod *sub_m = find_submethod(c, method, f);
  5548. if (!sub_m) {
  5549. // Don't emit any code for this field at all; it will be parsed as an
  5550. // unknown field.
  5551. return;
  5552. }
  5553. label(c, LABEL_FIELD);
  5554. int wire_type =
  5555. (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE)
  5556. ? UPB_WIRE_TYPE_DELIMITED
  5557. : UPB_WIRE_TYPE_START_GROUP;
  5558. if (upb_fielddef_isseq(f)) {
  5559. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5560. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  5561. dispatchtarget(c, method, f, wire_type);
  5562. putop(c, OP_PUSHTAGDELIM, 0);
  5563. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  5564. label(c, LABEL_LOOPSTART);
  5565. putpush(c, f);
  5566. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  5567. putop(c, OP_CALL, sub_m);
  5568. putop(c, OP_POP);
  5569. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  5570. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  5571. putop(c, OP_SETDELIM);
  5572. }
  5573. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5574. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  5575. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5576. label(c, LABEL_LOOPBREAK);
  5577. putop(c, OP_POP);
  5578. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  5579. } else {
  5580. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5581. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  5582. dispatchtarget(c, method, f, wire_type);
  5583. putpush(c, f);
  5584. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  5585. putop(c, OP_CALL, sub_m);
  5586. putop(c, OP_POP);
  5587. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  5588. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  5589. putop(c, OP_SETDELIM);
  5590. }
  5591. }
  5592. }
  5593. // Generates bytecode to parse a single string or lazy submessage field.
  5594. static void generate_delimfield(compiler *c, const upb_fielddef *f,
  5595. upb_pbdecodermethod *method) {
  5596. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  5597. label(c, LABEL_FIELD);
  5598. if (upb_fielddef_isseq(f)) {
  5599. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5600. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  5601. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  5602. putop(c, OP_PUSHTAGDELIM, 0);
  5603. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  5604. label(c, LABEL_LOOPSTART);
  5605. putop(c, OP_PUSHLENDELIM);
  5606. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  5607. // Need to emit even if no handler to skip past the string.
  5608. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  5609. putop(c, OP_POP);
  5610. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  5611. putop(c, OP_SETDELIM);
  5612. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5613. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_LOOPBREAK);
  5614. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5615. label(c, LABEL_LOOPBREAK);
  5616. putop(c, OP_POP);
  5617. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  5618. } else {
  5619. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5620. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  5621. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  5622. putop(c, OP_PUSHLENDELIM);
  5623. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  5624. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  5625. putop(c, OP_POP);
  5626. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  5627. putop(c, OP_SETDELIM);
  5628. }
  5629. }
  5630. // Generates bytecode to parse a single primitive field.
  5631. static void generate_primitivefield(compiler *c, const upb_fielddef *f,
  5632. upb_pbdecodermethod *method) {
  5633. label(c, LABEL_FIELD);
  5634. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  5635. upb_descriptortype_t descriptor_type = upb_fielddef_descriptortype(f);
  5636. // From a decoding perspective, ENUM is the same as INT32.
  5637. if (descriptor_type == UPB_DESCRIPTOR_TYPE_ENUM)
  5638. descriptor_type = UPB_DESCRIPTOR_TYPE_INT32;
  5639. opcode parse_type = (opcode)descriptor_type;
  5640. // TODO(haberman): generate packed or non-packed first depending on "packed"
  5641. // setting in the fielddef. This will favor (in speed) whichever was
  5642. // specified.
  5643. assert((int)parse_type >= 0 && parse_type <= OP_MAX);
  5644. upb_selector_t sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  5645. int wire_type = upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  5646. if (upb_fielddef_isseq(f)) {
  5647. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5648. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  5649. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  5650. putop(c, OP_PUSHLENDELIM);
  5651. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); // Packed
  5652. label(c, LABEL_LOOPSTART);
  5653. putop(c, parse_type, sel);
  5654. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5655. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5656. dispatchtarget(c, method, f, wire_type);
  5657. putop(c, OP_PUSHTAGDELIM, 0);
  5658. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); // Non-packed
  5659. label(c, LABEL_LOOPSTART);
  5660. putop(c, parse_type, sel);
  5661. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5662. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  5663. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5664. label(c, LABEL_LOOPBREAK);
  5665. putop(c, OP_POP); // Packed and non-packed join.
  5666. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  5667. putop(c, OP_SETDELIM); // Could remove for non-packed by dup ENDSEQ.
  5668. } else {
  5669. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5670. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  5671. dispatchtarget(c, method, f, wire_type);
  5672. putop(c, parse_type, sel);
  5673. }
  5674. }
  5675. // Adds bytecode for parsing the given message to the given decoderplan,
  5676. // while adding all dispatch targets to this message's dispatch table.
  5677. static void compile_method(compiler *c, upb_pbdecodermethod *method) {
  5678. assert(method);
  5679. // Clear all entries in the dispatch table.
  5680. upb_inttable_uninit(&method->dispatch);
  5681. upb_inttable_init(&method->dispatch, UPB_CTYPE_UINT64);
  5682. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  5683. const upb_msgdef *md = upb_handlers_msgdef(h);
  5684. method->code_base.ofs = pcofs(c);
  5685. putop(c, OP_SETDISPATCH, &method->dispatch);
  5686. putsel(c, OP_STARTMSG, UPB_STARTMSG_SELECTOR, h);
  5687. label(c, LABEL_FIELD);
  5688. uint32_t* start_pc = c->pc;
  5689. upb_msg_iter i;
  5690. for(upb_msg_begin(&i, md); !upb_msg_done(&i); upb_msg_next(&i)) {
  5691. const upb_fielddef *f = upb_msg_iter_field(&i);
  5692. upb_fieldtype_t type = upb_fielddef_type(f);
  5693. if (type == UPB_TYPE_MESSAGE && !(haslazyhandlers(h, f) && c->lazy)) {
  5694. generate_msgfield(c, f, method);
  5695. } else if (type == UPB_TYPE_STRING || type == UPB_TYPE_BYTES ||
  5696. type == UPB_TYPE_MESSAGE) {
  5697. generate_delimfield(c, f, method);
  5698. } else {
  5699. generate_primitivefield(c, f, method);
  5700. }
  5701. }
  5702. // If there were no fields, or if no handlers were defined, we need to
  5703. // generate a non-empty loop body so that we can at least dispatch for unknown
  5704. // fields and check for the end of the message.
  5705. if (c->pc == start_pc) {
  5706. // Check for end-of-message.
  5707. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5708. // Unconditionally dispatch.
  5709. putop(c, OP_DISPATCH, 0);
  5710. }
  5711. // For now we just loop back to the last field of the message (or if none,
  5712. // the DISPATCH opcode for the message).
  5713. putop(c, OP_BRANCH, -LABEL_FIELD);
  5714. // Insert both a label and a dispatch table entry for this end-of-msg.
  5715. label(c, LABEL_ENDMSG);
  5716. upb_value val = upb_value_uint64(pcofs(c) - method->code_base.ofs);
  5717. upb_inttable_insert(&method->dispatch, DISPATCH_ENDMSG, val);
  5718. putsel(c, OP_ENDMSG, UPB_ENDMSG_SELECTOR, h);
  5719. putop(c, OP_RET);
  5720. upb_inttable_compact(&method->dispatch);
  5721. }
  5722. // Populate "methods" with new upb_pbdecodermethod objects reachable from "h".
  5723. // Returns the method for these handlers.
  5724. //
  5725. // Generates a new method for every destination handlers reachable from "h".
  5726. static void find_methods(compiler *c, const upb_handlers *h) {
  5727. upb_value v;
  5728. if (upb_inttable_lookupptr(&c->group->methods, h, &v))
  5729. return;
  5730. newmethod(h, c->group);
  5731. // Find submethods.
  5732. upb_msg_iter i;
  5733. const upb_msgdef *md = upb_handlers_msgdef(h);
  5734. for(upb_msg_begin(&i, md); !upb_msg_done(&i); upb_msg_next(&i)) {
  5735. const upb_fielddef *f = upb_msg_iter_field(&i);
  5736. const upb_handlers *sub_h;
  5737. if (upb_fielddef_type(f) == UPB_TYPE_MESSAGE &&
  5738. (sub_h = upb_handlers_getsubhandlers(h, f)) != NULL) {
  5739. // We only generate a decoder method for submessages with handlers.
  5740. // Others will be parsed as unknown fields.
  5741. find_methods(c, sub_h);
  5742. }
  5743. }
  5744. }
  5745. // (Re-)compile bytecode for all messages in "msgs."
  5746. // Overwrites any existing bytecode in "c".
  5747. static void compile_methods(compiler *c) {
  5748. // Start over at the beginning of the bytecode.
  5749. c->pc = c->group->bytecode;
  5750. upb_inttable_iter i;
  5751. upb_inttable_begin(&i, &c->group->methods);
  5752. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5753. upb_pbdecodermethod *method = upb_value_getptr(upb_inttable_iter_value(&i));
  5754. compile_method(c, method);
  5755. }
  5756. }
  5757. static void set_bytecode_handlers(mgroup *g) {
  5758. upb_inttable_iter i;
  5759. upb_inttable_begin(&i, &g->methods);
  5760. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5761. upb_pbdecodermethod *m = upb_value_getptr(upb_inttable_iter_value(&i));
  5762. m->code_base.ptr = g->bytecode + m->code_base.ofs;
  5763. upb_byteshandler *h = &m->input_handler_;
  5764. upb_byteshandler_setstartstr(h, upb_pbdecoder_startbc, m->code_base.ptr);
  5765. upb_byteshandler_setstring(h, upb_pbdecoder_decode, g);
  5766. upb_byteshandler_setendstr(h, upb_pbdecoder_end, m);
  5767. }
  5768. }
  5769. /* JIT setup. ******************************************************************/
  5770. #ifdef UPB_USE_JIT_X64
  5771. static void sethandlers(mgroup *g, bool allowjit) {
  5772. g->jit_code = NULL;
  5773. if (allowjit) {
  5774. // Compile byte-code into machine code, create handlers.
  5775. upb_pbdecoder_jit(g);
  5776. } else {
  5777. set_bytecode_handlers(g);
  5778. }
  5779. }
  5780. #else // UPB_USE_JIT_X64
  5781. static void sethandlers(mgroup *g, bool allowjit) {
  5782. // No JIT compiled in; use bytecode handlers unconditionally.
  5783. UPB_UNUSED(allowjit);
  5784. set_bytecode_handlers(g);
  5785. }
  5786. #endif // UPB_USE_JIT_X64
  5787. // TODO(haberman): allow this to be constructed for an arbitrary set of dest
  5788. // handlers and other mgroups (but verify we have a transitive closure).
  5789. const mgroup *mgroup_new(const upb_handlers *dest, bool allowjit, bool lazy,
  5790. const void *owner) {
  5791. UPB_UNUSED(allowjit);
  5792. assert(upb_handlers_isfrozen(dest));
  5793. mgroup *g = newgroup(owner);
  5794. compiler *c = newcompiler(g, lazy);
  5795. find_methods(c, dest);
  5796. // We compile in two passes:
  5797. // 1. all messages are assigned relative offsets from the beginning of the
  5798. // bytecode (saved in method->code_base).
  5799. // 2. forwards OP_CALL instructions can be correctly linked since message
  5800. // offsets have been previously assigned.
  5801. //
  5802. // Could avoid the second pass by linking OP_CALL instructions somehow.
  5803. compile_methods(c);
  5804. compile_methods(c);
  5805. g->bytecode_end = c->pc;
  5806. freecompiler(c);
  5807. #ifdef UPB_DUMP_BYTECODE
  5808. FILE *f = fopen("/tmp/upb-bytecode", "wb");
  5809. assert(f);
  5810. dumpbc(g->bytecode, g->bytecode_end, stderr);
  5811. dumpbc(g->bytecode, g->bytecode_end, f);
  5812. fclose(f);
  5813. #endif
  5814. sethandlers(g, allowjit);
  5815. return g;
  5816. }
  5817. /* upb_pbcodecache ************************************************************/
  5818. void upb_pbcodecache_init(upb_pbcodecache *c) {
  5819. upb_inttable_init(&c->groups, UPB_CTYPE_CONSTPTR);
  5820. c->allow_jit_ = true;
  5821. }
  5822. void upb_pbcodecache_uninit(upb_pbcodecache *c) {
  5823. upb_inttable_iter i;
  5824. upb_inttable_begin(&i, &c->groups);
  5825. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5826. const mgroup *group = upb_value_getconstptr(upb_inttable_iter_value(&i));
  5827. upb_refcounted_unref(UPB_UPCAST(group), c);
  5828. }
  5829. upb_inttable_uninit(&c->groups);
  5830. }
  5831. bool upb_pbcodecache_allowjit(const upb_pbcodecache *c) {
  5832. return c->allow_jit_;
  5833. }
  5834. bool upb_pbcodecache_setallowjit(upb_pbcodecache *c, bool allow) {
  5835. if (upb_inttable_count(&c->groups) > 0)
  5836. return false;
  5837. c->allow_jit_ = allow;
  5838. return true;
  5839. }
  5840. const upb_pbdecodermethod *upb_pbcodecache_getdecodermethod(
  5841. upb_pbcodecache *c, const upb_pbdecodermethodopts *opts) {
  5842. // Right now we build a new DecoderMethod every time.
  5843. // TODO(haberman): properly cache methods by their true key.
  5844. const mgroup *g = mgroup_new(opts->handlers, c->allow_jit_, opts->lazy, c);
  5845. upb_inttable_push(&c->groups, upb_value_constptr(g));
  5846. upb_value v;
  5847. bool ok = upb_inttable_lookupptr(&g->methods, opts->handlers, &v);
  5848. UPB_ASSERT_VAR(ok, ok);
  5849. return upb_value_getptr(v);
  5850. }
  5851. /* upb_pbdecodermethodopts ****************************************************/
  5852. void upb_pbdecodermethodopts_init(upb_pbdecodermethodopts *opts,
  5853. const upb_handlers *h) {
  5854. opts->handlers = h;
  5855. opts->lazy = false;
  5856. }
  5857. void upb_pbdecodermethodopts_setlazy(upb_pbdecodermethodopts *opts, bool lazy) {
  5858. opts->lazy = lazy;
  5859. }
  5860. /*
  5861. * upb - a minimalist implementation of protocol buffers.
  5862. *
  5863. * Copyright (c) 2008-2013 Google Inc. See LICENSE for details.
  5864. * Author: Josh Haberman <jhaberman@gmail.com>
  5865. *
  5866. * This file implements a VM for the interpreted (bytecode) decoder.
  5867. *
  5868. * Bytecode must previously have been generated using the bytecode compiler in
  5869. * compile_decoder.c. This decoder then walks through the bytecode op-by-op to
  5870. * parse the input.
  5871. *
  5872. * Decoding is fully resumable; we just keep a pointer to the current bytecode
  5873. * instruction and resume from there. A fair amount of the logic here is to
  5874. * handle the fact that values can span buffer seams and we have to be able to
  5875. * be capable of suspending/resuming from any byte in the stream. This
  5876. * sometimes requires keeping a few trailing bytes from the last buffer around
  5877. * in the "residual" buffer.
  5878. */
  5879. #include <inttypes.h>
  5880. #include <setjmp.h>
  5881. #include <stdarg.h>
  5882. #include <stddef.h>
  5883. #include <stdlib.h>
  5884. #ifdef UPB_DUMP_BYTECODE
  5885. #include <stdio.h>
  5886. #endif
  5887. #define CHECK_SUSPEND(x) if (!(x)) return upb_pbdecoder_suspend(d);
  5888. // Error messages that are shared between the bytecode and JIT decoders.
  5889. const char *kPbDecoderStackOverflow = "Nesting too deep.";
  5890. // Error messages shared within this file.
  5891. static const char *kUnterminatedVarint = "Unterminated varint.";
  5892. /* upb_pbdecoder **************************************************************/
  5893. static opcode halt = OP_HALT;
  5894. // Whether an op consumes any of the input buffer.
  5895. static bool consumes_input(opcode op) {
  5896. switch (op) {
  5897. case OP_SETDISPATCH:
  5898. case OP_STARTMSG:
  5899. case OP_ENDMSG:
  5900. case OP_STARTSEQ:
  5901. case OP_ENDSEQ:
  5902. case OP_STARTSUBMSG:
  5903. case OP_ENDSUBMSG:
  5904. case OP_STARTSTR:
  5905. case OP_ENDSTR:
  5906. case OP_PUSHTAGDELIM:
  5907. case OP_POP:
  5908. case OP_SETDELIM:
  5909. case OP_SETBIGGROUPNUM:
  5910. case OP_CHECKDELIM:
  5911. case OP_CALL:
  5912. case OP_RET:
  5913. case OP_BRANCH:
  5914. return false;
  5915. default:
  5916. return true;
  5917. }
  5918. }
  5919. static bool in_residual_buf(const upb_pbdecoder *d, const char *p);
  5920. // It's unfortunate that we have to micro-manage the compiler this way,
  5921. // especially since this tuning is necessarily specific to one hardware
  5922. // configuration. But emperically on a Core i7, performance increases 30-50%
  5923. // with these annotations. Every instance where these appear, gcc 4.2.1 made
  5924. // the wrong decision and degraded performance in benchmarks.
  5925. #define FORCEINLINE static inline __attribute__((always_inline))
  5926. #define NOINLINE __attribute__((noinline))
  5927. static void seterr(upb_pbdecoder *d, const char *msg) {
  5928. // TODO(haberman): encapsulate this access to pipeline->status, but not sure
  5929. // exactly what that interface should look like.
  5930. upb_status_seterrmsg(d->status, msg);
  5931. }
  5932. void upb_pbdecoder_seterr(upb_pbdecoder *d, const char *msg) {
  5933. seterr(d, msg);
  5934. }
  5935. /* Buffering ******************************************************************/
  5936. // We operate on one buffer at a time, which is either the user's buffer passed
  5937. // to our "decode" callback or some residual bytes from the previous buffer.
  5938. // How many bytes can be safely read from d->ptr without reading past end-of-buf
  5939. // or past the current delimited end.
  5940. static size_t curbufleft(const upb_pbdecoder *d) {
  5941. assert(d->data_end >= d->ptr);
  5942. return d->data_end - d->ptr;
  5943. }
  5944. // Overall stream offset of d->ptr.
  5945. uint64_t offset(const upb_pbdecoder *d) {
  5946. return d->bufstart_ofs + (d->ptr - d->buf);
  5947. }
  5948. // Advances d->ptr.
  5949. static void advance(upb_pbdecoder *d, size_t len) {
  5950. assert(curbufleft(d) >= len);
  5951. d->ptr += len;
  5952. }
  5953. static bool in_buf(const char *p, const char *buf, const char *end) {
  5954. return p >= buf && p <= end;
  5955. }
  5956. static bool in_residual_buf(const upb_pbdecoder *d, const char *p) {
  5957. return in_buf(p, d->residual, d->residual_end);
  5958. }
  5959. // Calculates the delim_end value, which is affected by both the current buffer
  5960. // and the parsing stack, so must be called whenever either is updated.
  5961. static void set_delim_end(upb_pbdecoder *d) {
  5962. size_t delim_ofs = d->top->end_ofs - d->bufstart_ofs;
  5963. if (delim_ofs <= (d->end - d->buf)) {
  5964. d->delim_end = d->buf + delim_ofs;
  5965. d->data_end = d->delim_end;
  5966. } else {
  5967. d->data_end = d->end;
  5968. d->delim_end = NULL;
  5969. }
  5970. }
  5971. static void switchtobuf(upb_pbdecoder *d, const char *buf, const char *end) {
  5972. d->ptr = buf;
  5973. d->buf = buf;
  5974. d->end = end;
  5975. set_delim_end(d);
  5976. }
  5977. static void advancetobuf(upb_pbdecoder *d, const char *buf, size_t len) {
  5978. assert(curbufleft(d) == 0);
  5979. d->bufstart_ofs += (d->end - d->buf);
  5980. switchtobuf(d, buf, buf + len);
  5981. }
  5982. static void checkpoint(upb_pbdecoder *d) {
  5983. // The assertion here is in the interests of efficiency, not correctness.
  5984. // We are trying to ensure that we don't checkpoint() more often than
  5985. // necessary.
  5986. assert(d->checkpoint != d->ptr);
  5987. d->checkpoint = d->ptr;
  5988. }
  5989. // Resumes the decoder from an initial state or from a previous suspend.
  5990. int32_t upb_pbdecoder_resume(upb_pbdecoder *d, void *p, const char *buf,
  5991. size_t size, const upb_bufhandle *handle) {
  5992. UPB_UNUSED(p); // Useless; just for the benefit of the JIT.
  5993. d->buf_param = buf;
  5994. d->size_param = size;
  5995. d->handle = handle;
  5996. if (d->residual_end > d->residual) {
  5997. // We have residual bytes from the last buffer.
  5998. assert(d->ptr == d->residual);
  5999. } else {
  6000. switchtobuf(d, buf, buf + size);
  6001. }
  6002. d->checkpoint = d->ptr;
  6003. if (d->top->groupnum < 0) {
  6004. CHECK_RETURN(upb_pbdecoder_skipunknown(d, -1, 0));
  6005. d->checkpoint = d->ptr;
  6006. }
  6007. return DECODE_OK;
  6008. }
  6009. // Suspends the decoder at the last checkpoint, without saving any residual
  6010. // bytes. If there are any unconsumed bytes, returns a short byte count.
  6011. size_t upb_pbdecoder_suspend(upb_pbdecoder *d) {
  6012. d->pc = d->last;
  6013. if (d->checkpoint == d->residual) {
  6014. // Checkpoint was in residual buf; no user bytes were consumed.
  6015. d->ptr = d->residual;
  6016. return 0;
  6017. } else {
  6018. assert(!in_residual_buf(d, d->checkpoint));
  6019. assert(d->buf == d->buf_param);
  6020. size_t consumed = d->checkpoint - d->buf;
  6021. d->bufstart_ofs += consumed;
  6022. d->residual_end = d->residual;
  6023. switchtobuf(d, d->residual, d->residual_end);
  6024. return consumed;
  6025. }
  6026. }
  6027. // Suspends the decoder at the last checkpoint, and saves any unconsumed
  6028. // bytes in our residual buffer. This is necessary if we need more user
  6029. // bytes to form a complete value, which might not be contiguous in the
  6030. // user's buffers. Always consumes all user bytes.
  6031. static size_t suspend_save(upb_pbdecoder *d) {
  6032. // We hit end-of-buffer before we could parse a full value.
  6033. // Save any unconsumed bytes (if any) to the residual buffer.
  6034. d->pc = d->last;
  6035. if (d->checkpoint == d->residual) {
  6036. // Checkpoint was in residual buf; append user byte(s) to residual buf.
  6037. assert((d->residual_end - d->residual) + d->size_param <=
  6038. sizeof(d->residual));
  6039. if (!in_residual_buf(d, d->ptr)) {
  6040. d->bufstart_ofs -= (d->residual_end - d->residual);
  6041. }
  6042. memcpy(d->residual_end, d->buf_param, d->size_param);
  6043. d->residual_end += d->size_param;
  6044. } else {
  6045. // Checkpoint was in user buf; old residual bytes not needed.
  6046. assert(!in_residual_buf(d, d->checkpoint));
  6047. d->ptr = d->checkpoint;
  6048. size_t save = curbufleft(d);
  6049. assert(save <= sizeof(d->residual));
  6050. memcpy(d->residual, d->ptr, save);
  6051. d->residual_end = d->residual + save;
  6052. d->bufstart_ofs = offset(d);
  6053. }
  6054. switchtobuf(d, d->residual, d->residual_end);
  6055. return d->size_param;
  6056. }
  6057. // Skips "bytes" bytes in the stream, which may be more than available. If we
  6058. // skip more bytes than are available, we return a long read count to the caller
  6059. // indicating how many bytes the caller should skip before passing a new buffer.
  6060. static int32_t skip(upb_pbdecoder *d, size_t bytes) {
  6061. assert(!in_residual_buf(d, d->ptr) || d->size_param == 0);
  6062. if (curbufleft(d) >= bytes) {
  6063. // Skipped data is all in current buffer.
  6064. advance(d, bytes);
  6065. return DECODE_OK;
  6066. } else {
  6067. // Skipped data extends beyond currently available buffers.
  6068. d->pc = d->last;
  6069. size_t skip = bytes - curbufleft(d);
  6070. d->bufstart_ofs += (d->end - d->buf) + skip;
  6071. d->residual_end = d->residual;
  6072. switchtobuf(d, d->residual, d->residual_end);
  6073. return d->size_param + skip;
  6074. }
  6075. }
  6076. // Copies the next "bytes" bytes into "buf" and advances the stream.
  6077. // Requires that this many bytes are available in the current buffer.
  6078. FORCEINLINE void consumebytes(upb_pbdecoder *d, void *buf, size_t bytes) {
  6079. assert(bytes <= curbufleft(d));
  6080. memcpy(buf, d->ptr, bytes);
  6081. advance(d, bytes);
  6082. }
  6083. // Slow path for getting the next "bytes" bytes, regardless of whether they are
  6084. // available in the current buffer or not. Returns a status code as described
  6085. // in decoder.int.h.
  6086. static NOINLINE int32_t getbytes_slow(upb_pbdecoder *d, void *buf,
  6087. size_t bytes) {
  6088. const size_t avail = curbufleft(d);
  6089. consumebytes(d, buf, avail);
  6090. bytes -= avail;
  6091. assert(bytes > 0);
  6092. if (in_residual_buf(d, d->ptr)) {
  6093. advancetobuf(d, d->buf_param, d->size_param);
  6094. }
  6095. if (curbufleft(d) >= bytes) {
  6096. consumebytes(d, buf + avail, bytes);
  6097. return DECODE_OK;
  6098. } else if (d->data_end == d->delim_end) {
  6099. seterr(d, "Submessage ended in the middle of a value or group");
  6100. return upb_pbdecoder_suspend(d);
  6101. } else {
  6102. return suspend_save(d);
  6103. }
  6104. }
  6105. // Gets the next "bytes" bytes, regardless of whether they are available in the
  6106. // current buffer or not. Returns a status code as described in decoder.int.h.
  6107. FORCEINLINE int32_t getbytes(upb_pbdecoder *d, void *buf, size_t bytes) {
  6108. if (curbufleft(d) >= bytes) {
  6109. // Buffer has enough data to satisfy.
  6110. consumebytes(d, buf, bytes);
  6111. return DECODE_OK;
  6112. } else {
  6113. return getbytes_slow(d, buf, bytes);
  6114. }
  6115. }
  6116. static NOINLINE size_t peekbytes_slow(upb_pbdecoder *d, void *buf,
  6117. size_t bytes) {
  6118. size_t ret = curbufleft(d);
  6119. memcpy(buf, d->ptr, ret);
  6120. if (in_residual_buf(d, d->ptr)) {
  6121. size_t copy = UPB_MIN(bytes - ret, d->size_param);
  6122. memcpy(buf + ret, d->buf_param, copy);
  6123. ret += copy;
  6124. }
  6125. return ret;
  6126. }
  6127. FORCEINLINE size_t peekbytes(upb_pbdecoder *d, void *buf, size_t bytes) {
  6128. if (curbufleft(d) >= bytes) {
  6129. memcpy(buf, d->ptr, bytes);
  6130. return bytes;
  6131. } else {
  6132. return peekbytes_slow(d, buf, bytes);
  6133. }
  6134. }
  6135. /* Decoding of wire types *****************************************************/
  6136. // Slow path for decoding a varint from the current buffer position.
  6137. // Returns a status code as described in decoder.int.h.
  6138. NOINLINE int32_t upb_pbdecoder_decode_varint_slow(upb_pbdecoder *d,
  6139. uint64_t *u64) {
  6140. *u64 = 0;
  6141. uint8_t byte = 0x80;
  6142. int bitpos;
  6143. for(bitpos = 0; bitpos < 70 && (byte & 0x80); bitpos += 7) {
  6144. int32_t ret = getbytes(d, &byte, 1);
  6145. if (ret >= 0) return ret;
  6146. *u64 |= (uint64_t)(byte & 0x7F) << bitpos;
  6147. }
  6148. if(bitpos == 70 && (byte & 0x80)) {
  6149. seterr(d, kUnterminatedVarint);
  6150. return upb_pbdecoder_suspend(d);
  6151. }
  6152. return DECODE_OK;
  6153. }
  6154. // Decodes a varint from the current buffer position.
  6155. // Returns a status code as described in decoder.int.h.
  6156. FORCEINLINE int32_t decode_varint(upb_pbdecoder *d, uint64_t *u64) {
  6157. if (curbufleft(d) > 0 && !(*d->ptr & 0x80)) {
  6158. *u64 = *d->ptr;
  6159. advance(d, 1);
  6160. return DECODE_OK;
  6161. } else if (curbufleft(d) >= 10) {
  6162. // Fast case.
  6163. upb_decoderet r = upb_vdecode_fast(d->ptr);
  6164. if (r.p == NULL) {
  6165. seterr(d, kUnterminatedVarint);
  6166. return upb_pbdecoder_suspend(d);
  6167. }
  6168. advance(d, r.p - d->ptr);
  6169. *u64 = r.val;
  6170. return DECODE_OK;
  6171. } else {
  6172. // Slow case -- varint spans buffer seam.
  6173. return upb_pbdecoder_decode_varint_slow(d, u64);
  6174. }
  6175. }
  6176. // Decodes a 32-bit varint from the current buffer position.
  6177. // Returns a status code as described in decoder.int.h.
  6178. FORCEINLINE int32_t decode_v32(upb_pbdecoder *d, uint32_t *u32) {
  6179. uint64_t u64;
  6180. int32_t ret = decode_varint(d, &u64);
  6181. if (ret >= 0) return ret;
  6182. if (u64 > UINT32_MAX) {
  6183. seterr(d, "Unterminated 32-bit varint");
  6184. // TODO(haberman) guarantee that this function return is >= 0 somehow,
  6185. // so we know this path will always be treated as error by our caller.
  6186. // Right now the size_t -> int32_t can overflow and produce negative values.
  6187. *u32 = 0;
  6188. return upb_pbdecoder_suspend(d);
  6189. }
  6190. *u32 = u64;
  6191. return DECODE_OK;
  6192. }
  6193. // Decodes a fixed32 from the current buffer position.
  6194. // Returns a status code as described in decoder.int.h.
  6195. // TODO: proper byte swapping for big-endian machines.
  6196. FORCEINLINE int32_t decode_fixed32(upb_pbdecoder *d, uint32_t *u32) {
  6197. return getbytes(d, u32, 4);
  6198. }
  6199. // Decodes a fixed64 from the current buffer position.
  6200. // Returns a status code as described in decoder.int.h.
  6201. // TODO: proper byte swapping for big-endian machines.
  6202. FORCEINLINE int32_t decode_fixed64(upb_pbdecoder *d, uint64_t *u64) {
  6203. return getbytes(d, u64, 8);
  6204. }
  6205. // Non-static versions of the above functions.
  6206. // These are called by the JIT for fallback paths.
  6207. int32_t upb_pbdecoder_decode_f32(upb_pbdecoder *d, uint32_t *u32) {
  6208. return decode_fixed32(d, u32);
  6209. }
  6210. int32_t upb_pbdecoder_decode_f64(upb_pbdecoder *d, uint64_t *u64) {
  6211. return decode_fixed64(d, u64);
  6212. }
  6213. static double as_double(uint64_t n) { double d; memcpy(&d, &n, 8); return d; }
  6214. static float as_float(uint32_t n) { float f; memcpy(&f, &n, 4); return f; }
  6215. // Pushes a frame onto the decoder stack.
  6216. static bool decoder_push(upb_pbdecoder *d, uint64_t end) {
  6217. upb_pbdecoder_frame *fr = d->top;
  6218. if (end > fr->end_ofs) {
  6219. seterr(d, "Submessage end extends past enclosing submessage.");
  6220. return false;
  6221. } else if ((fr + 1) == d->limit) {
  6222. seterr(d, kPbDecoderStackOverflow);
  6223. return false;
  6224. }
  6225. fr++;
  6226. fr->end_ofs = end;
  6227. fr->dispatch = NULL;
  6228. fr->groupnum = 0;
  6229. d->top = fr;
  6230. return true;
  6231. }
  6232. static bool pushtagdelim(upb_pbdecoder *d, uint32_t arg) {
  6233. // While we expect to see an "end" tag (either ENDGROUP or a non-sequence
  6234. // field number) prior to hitting any enclosing submessage end, pushing our
  6235. // existing delim end prevents us from continuing to parse values from a
  6236. // corrupt proto that doesn't give us an END tag in time.
  6237. if (!decoder_push(d, d->top->end_ofs))
  6238. return false;
  6239. d->top->groupnum = arg;
  6240. return true;
  6241. }
  6242. // Pops a frame from the decoder stack.
  6243. static void decoder_pop(upb_pbdecoder *d) { d->top--; }
  6244. NOINLINE int32_t upb_pbdecoder_checktag_slow(upb_pbdecoder *d,
  6245. uint64_t expected) {
  6246. uint64_t data = 0;
  6247. size_t bytes = upb_value_size(expected);
  6248. size_t read = peekbytes(d, &data, bytes);
  6249. if (read == bytes && data == expected) {
  6250. // Advance past matched bytes.
  6251. int32_t ok = getbytes(d, &data, read);
  6252. UPB_ASSERT_VAR(ok, ok < 0);
  6253. return DECODE_OK;
  6254. } else if (read < bytes && memcmp(&data, &expected, read) == 0) {
  6255. return suspend_save(d);
  6256. } else {
  6257. return DECODE_MISMATCH;
  6258. }
  6259. }
  6260. int32_t upb_pbdecoder_skipunknown(upb_pbdecoder *d, int32_t fieldnum,
  6261. uint8_t wire_type) {
  6262. if (fieldnum >= 0)
  6263. goto have_tag;
  6264. while (true) {
  6265. uint32_t tag;
  6266. CHECK_RETURN(decode_v32(d, &tag));
  6267. wire_type = tag & 0x7;
  6268. fieldnum = tag >> 3;
  6269. have_tag:
  6270. if (fieldnum == 0) {
  6271. seterr(d, "Saw invalid field number (0)");
  6272. return upb_pbdecoder_suspend(d);
  6273. }
  6274. // TODO: deliver to unknown field callback.
  6275. switch (wire_type) {
  6276. case UPB_WIRE_TYPE_32BIT:
  6277. CHECK_RETURN(skip(d, 4));
  6278. break;
  6279. case UPB_WIRE_TYPE_64BIT:
  6280. CHECK_RETURN(skip(d, 8));
  6281. break;
  6282. case UPB_WIRE_TYPE_VARINT: {
  6283. uint64_t u64;
  6284. CHECK_RETURN(decode_varint(d, &u64));
  6285. break;
  6286. }
  6287. case UPB_WIRE_TYPE_DELIMITED: {
  6288. uint32_t len;
  6289. CHECK_RETURN(decode_v32(d, &len));
  6290. CHECK_RETURN(skip(d, len));
  6291. break;
  6292. }
  6293. case UPB_WIRE_TYPE_START_GROUP:
  6294. CHECK_SUSPEND(pushtagdelim(d, -fieldnum));
  6295. break;
  6296. case UPB_WIRE_TYPE_END_GROUP:
  6297. if (fieldnum == -d->top->groupnum) {
  6298. decoder_pop(d);
  6299. } else if (fieldnum == d->top->groupnum) {
  6300. return DECODE_ENDGROUP;
  6301. } else {
  6302. seterr(d, "Unmatched ENDGROUP tag.");
  6303. return upb_pbdecoder_suspend(d);
  6304. }
  6305. break;
  6306. default:
  6307. seterr(d, "Invalid wire type");
  6308. return upb_pbdecoder_suspend(d);
  6309. }
  6310. if (d->top->groupnum >= 0) {
  6311. return DECODE_OK;
  6312. }
  6313. if (d->ptr == d->delim_end) {
  6314. seterr(d, "Enclosing submessage ended in the middle of value or group");
  6315. // Unlike most errors we notice during parsing, right now we have consumed
  6316. // all of the user's input.
  6317. //
  6318. // There are three different options for how to handle this case:
  6319. //
  6320. // 1. decode() = short count, error = set
  6321. // 2. decode() = full count, error = set
  6322. // 3. decode() = full count, error NOT set, short count and error will
  6323. // be reported on next call to decode() (or end())
  6324. //
  6325. // (1) and (3) have the advantage that they preserve the invariant that an
  6326. // error occurs iff decode() returns a short count.
  6327. //
  6328. // (2) and (3) have the advantage of reflecting the fact that all of the
  6329. // bytes were in fact parsed (and possibly delivered to the unknown field
  6330. // handler, in the future when that is supported).
  6331. //
  6332. // (3) requires extra state in the decode (a place to store the "permanent
  6333. // error" that we should return for all subsequent attempts to decode).
  6334. // But we likely want this anyway.
  6335. //
  6336. // Right now we do (1), thanks to the fact that we checkpoint *after* this
  6337. // check. (3) may be a better choice long term; unclear at the moment.
  6338. return upb_pbdecoder_suspend(d);
  6339. }
  6340. checkpoint(d);
  6341. }
  6342. }
  6343. static void goto_endmsg(upb_pbdecoder *d) {
  6344. upb_value v;
  6345. bool found = upb_inttable_lookup32(d->top->dispatch, DISPATCH_ENDMSG, &v);
  6346. UPB_ASSERT_VAR(found, found);
  6347. d->pc = d->top->base + upb_value_getuint64(v);
  6348. }
  6349. // Parses a tag and jumps to the corresponding bytecode instruction for this
  6350. // field.
  6351. //
  6352. // If the tag is unknown (or the wire type doesn't match), parses the field as
  6353. // unknown. If the tag is a valid ENDGROUP tag, jumps to the bytecode
  6354. // instruction for the end of message.
  6355. static int32_t dispatch(upb_pbdecoder *d) {
  6356. upb_inttable *dispatch = d->top->dispatch;
  6357. // Decode tag.
  6358. uint32_t tag;
  6359. CHECK_RETURN(decode_v32(d, &tag));
  6360. uint8_t wire_type = tag & 0x7;
  6361. uint32_t fieldnum = tag >> 3;
  6362. // Lookup tag. Because of packed/non-packed compatibility, we have to
  6363. // check the wire type against two possibilities.
  6364. upb_value val;
  6365. if (fieldnum != DISPATCH_ENDMSG &&
  6366. upb_inttable_lookup32(dispatch, fieldnum, &val)) {
  6367. uint64_t v = upb_value_getuint64(val);
  6368. if (wire_type == (v & 0xff)) {
  6369. d->pc = d->top->base + (v >> 16);
  6370. return DECODE_OK;
  6371. } else if (wire_type == ((v >> 8) & 0xff)) {
  6372. bool found =
  6373. upb_inttable_lookup(dispatch, fieldnum + UPB_MAX_FIELDNUMBER, &val);
  6374. UPB_ASSERT_VAR(found, found);
  6375. d->pc = d->top->base + upb_value_getuint64(val);
  6376. return DECODE_OK;
  6377. }
  6378. }
  6379. // Unknown field or ENDGROUP.
  6380. int32_t ret = upb_pbdecoder_skipunknown(d, fieldnum, wire_type);
  6381. if (ret == DECODE_ENDGROUP) {
  6382. goto_endmsg(d);
  6383. return DECODE_OK;
  6384. } else {
  6385. d->pc = d->last - 1; // Rewind to CHECKDELIM.
  6386. return ret;
  6387. }
  6388. }
  6389. // Callers know that the stack is more than one deep because the opcodes that
  6390. // call this only occur after PUSH operations.
  6391. upb_pbdecoder_frame *outer_frame(upb_pbdecoder *d) {
  6392. assert(d->top != d->stack);
  6393. return d->top - 1;
  6394. }
  6395. /* The main decoding loop *****************************************************/
  6396. // The main decoder VM function. Uses traditional bytecode dispatch loop with a
  6397. // switch() statement.
  6398. size_t upb_pbdecoder_decode(void *closure, const void *hd, const char *buf,
  6399. size_t size, const upb_bufhandle *handle) {
  6400. upb_pbdecoder *d = closure;
  6401. const mgroup *group = hd;
  6402. assert(buf);
  6403. int32_t result = upb_pbdecoder_resume(d, NULL, buf, size, handle);
  6404. if (result == DECODE_ENDGROUP) {
  6405. goto_endmsg(d);
  6406. }
  6407. CHECK_RETURN(result);
  6408. UPB_UNUSED(group);
  6409. #define VMCASE(op, code) \
  6410. case op: { code; if (consumes_input(op)) checkpoint(d); break; }
  6411. #define PRIMITIVE_OP(type, wt, name, convfunc, ctype) \
  6412. VMCASE(OP_PARSE_ ## type, { \
  6413. ctype val; \
  6414. CHECK_RETURN(decode_ ## wt(d, &val)); \
  6415. upb_sink_put ## name(&d->top->sink, arg, (convfunc)(val)); \
  6416. })
  6417. while(1) {
  6418. d->last = d->pc;
  6419. int32_t instruction = *d->pc++;
  6420. opcode op = getop(instruction);
  6421. uint32_t arg = instruction >> 8;
  6422. int32_t longofs = arg;
  6423. assert(d->ptr != d->residual_end);
  6424. #ifdef UPB_DUMP_BYTECODE
  6425. fprintf(stderr, "s_ofs=%d buf_ofs=%d data_rem=%d buf_rem=%d delim_rem=%d "
  6426. "%x %s (%d)\n",
  6427. (int)offset(d),
  6428. (int)(d->ptr - d->buf),
  6429. (int)(d->data_end - d->ptr),
  6430. (int)(d->end - d->ptr),
  6431. (int)((d->top->end_ofs - d->bufstart_ofs) - (d->ptr - d->buf)),
  6432. (int)(d->pc - 1 - group->bytecode),
  6433. upb_pbdecoder_getopname(op),
  6434. arg);
  6435. #endif
  6436. switch (op) {
  6437. // Technically, we are losing data if we see a 32-bit varint that is not
  6438. // properly sign-extended. We could detect this and error about the data
  6439. // loss, but proto2 does not do this, so we pass.
  6440. PRIMITIVE_OP(INT32, varint, int32, int32_t, uint64_t)
  6441. PRIMITIVE_OP(INT64, varint, int64, int64_t, uint64_t)
  6442. PRIMITIVE_OP(UINT32, varint, uint32, uint32_t, uint64_t)
  6443. PRIMITIVE_OP(UINT64, varint, uint64, uint64_t, uint64_t)
  6444. PRIMITIVE_OP(FIXED32, fixed32, uint32, uint32_t, uint32_t)
  6445. PRIMITIVE_OP(FIXED64, fixed64, uint64, uint64_t, uint64_t)
  6446. PRIMITIVE_OP(SFIXED32, fixed32, int32, int32_t, uint32_t)
  6447. PRIMITIVE_OP(SFIXED64, fixed64, int64, int64_t, uint64_t)
  6448. PRIMITIVE_OP(BOOL, varint, bool, bool, uint64_t)
  6449. PRIMITIVE_OP(DOUBLE, fixed64, double, as_double, uint64_t)
  6450. PRIMITIVE_OP(FLOAT, fixed32, float, as_float, uint32_t)
  6451. PRIMITIVE_OP(SINT32, varint, int32, upb_zzdec_32, uint64_t)
  6452. PRIMITIVE_OP(SINT64, varint, int64, upb_zzdec_64, uint64_t)
  6453. VMCASE(OP_SETDISPATCH,
  6454. d->top->base = d->pc - 1;
  6455. memcpy(&d->top->dispatch, d->pc, sizeof(void*));
  6456. d->pc += sizeof(void*) / sizeof(uint32_t);
  6457. )
  6458. VMCASE(OP_STARTMSG,
  6459. CHECK_SUSPEND(upb_sink_startmsg(&d->top->sink));
  6460. )
  6461. VMCASE(OP_ENDMSG,
  6462. CHECK_SUSPEND(upb_sink_endmsg(&d->top->sink, d->status));
  6463. )
  6464. VMCASE(OP_STARTSEQ,
  6465. upb_pbdecoder_frame *outer = outer_frame(d);
  6466. CHECK_SUSPEND(upb_sink_startseq(&outer->sink, arg, &d->top->sink));
  6467. )
  6468. VMCASE(OP_ENDSEQ,
  6469. CHECK_SUSPEND(upb_sink_endseq(&d->top->sink, arg));
  6470. )
  6471. VMCASE(OP_STARTSUBMSG,
  6472. upb_pbdecoder_frame *outer = outer_frame(d);
  6473. CHECK_SUSPEND(upb_sink_startsubmsg(&outer->sink, arg, &d->top->sink));
  6474. )
  6475. VMCASE(OP_ENDSUBMSG,
  6476. CHECK_SUSPEND(upb_sink_endsubmsg(&d->top->sink, arg));
  6477. )
  6478. VMCASE(OP_STARTSTR,
  6479. uint32_t len = d->top->end_ofs - offset(d);
  6480. upb_pbdecoder_frame *outer = outer_frame(d);
  6481. CHECK_SUSPEND(upb_sink_startstr(&outer->sink, arg, len, &d->top->sink));
  6482. if (len == 0) {
  6483. d->pc++; // Skip OP_STRING.
  6484. }
  6485. )
  6486. VMCASE(OP_STRING,
  6487. uint32_t len = curbufleft(d);
  6488. size_t n = upb_sink_putstring(&d->top->sink, arg, d->ptr, len, handle);
  6489. if (n > len) {
  6490. if (n > d->top->end_ofs - offset(d)) {
  6491. seterr(d, "Tried to skip past end of string.");
  6492. return upb_pbdecoder_suspend(d);
  6493. } else {
  6494. int32_t ret = skip(d, n);
  6495. // This shouldn't return DECODE_OK, because n > len.
  6496. assert(ret >= 0);
  6497. return ret;
  6498. }
  6499. }
  6500. advance(d, n);
  6501. if (n < len || d->delim_end == NULL) {
  6502. // We aren't finished with this string yet.
  6503. d->pc--; // Repeat OP_STRING.
  6504. if (n > 0) checkpoint(d);
  6505. return upb_pbdecoder_suspend(d);
  6506. }
  6507. )
  6508. VMCASE(OP_ENDSTR,
  6509. CHECK_SUSPEND(upb_sink_endstr(&d->top->sink, arg));
  6510. )
  6511. VMCASE(OP_PUSHTAGDELIM,
  6512. CHECK_SUSPEND(pushtagdelim(d, arg));
  6513. )
  6514. VMCASE(OP_SETBIGGROUPNUM,
  6515. d->top->groupnum = *d->pc++;
  6516. )
  6517. VMCASE(OP_POP,
  6518. assert(d->top > d->stack);
  6519. decoder_pop(d);
  6520. )
  6521. VMCASE(OP_PUSHLENDELIM,
  6522. uint32_t len;
  6523. CHECK_RETURN(decode_v32(d, &len));
  6524. CHECK_SUSPEND(decoder_push(d, offset(d) + len));
  6525. set_delim_end(d);
  6526. )
  6527. VMCASE(OP_SETDELIM,
  6528. set_delim_end(d);
  6529. )
  6530. VMCASE(OP_CHECKDELIM,
  6531. // We are guaranteed of this assert because we never allow ourselves to
  6532. // consume bytes beyond data_end, which covers delim_end when non-NULL.
  6533. assert(!(d->delim_end && d->ptr > d->delim_end));
  6534. if (d->ptr == d->delim_end)
  6535. d->pc += longofs;
  6536. )
  6537. VMCASE(OP_CALL,
  6538. d->callstack[d->call_len++] = d->pc;
  6539. d->pc += longofs;
  6540. )
  6541. VMCASE(OP_RET,
  6542. assert(d->call_len > 0);
  6543. d->pc = d->callstack[--d->call_len];
  6544. )
  6545. VMCASE(OP_BRANCH,
  6546. d->pc += longofs;
  6547. )
  6548. VMCASE(OP_TAG1,
  6549. CHECK_SUSPEND(curbufleft(d) > 0);
  6550. uint8_t expected = (arg >> 8) & 0xff;
  6551. if (*d->ptr == expected) {
  6552. advance(d, 1);
  6553. } else {
  6554. int8_t shortofs;
  6555. badtag:
  6556. shortofs = arg;
  6557. if (shortofs == LABEL_DISPATCH) {
  6558. CHECK_RETURN(dispatch(d));
  6559. } else {
  6560. d->pc += shortofs;
  6561. break; // Avoid checkpoint().
  6562. }
  6563. }
  6564. )
  6565. VMCASE(OP_TAG2,
  6566. CHECK_SUSPEND(curbufleft(d) > 0);
  6567. uint16_t expected = (arg >> 8) & 0xffff;
  6568. if (curbufleft(d) >= 2) {
  6569. uint16_t actual;
  6570. memcpy(&actual, d->ptr, 2);
  6571. if (expected == actual) {
  6572. advance(d, 2);
  6573. } else {
  6574. goto badtag;
  6575. }
  6576. } else {
  6577. int32_t result = upb_pbdecoder_checktag_slow(d, expected);
  6578. if (result == DECODE_MISMATCH) goto badtag;
  6579. if (result >= 0) return result;
  6580. }
  6581. )
  6582. VMCASE(OP_TAGN, {
  6583. uint64_t expected;
  6584. memcpy(&expected, d->pc, 8);
  6585. d->pc += 2;
  6586. int32_t result = upb_pbdecoder_checktag_slow(d, expected);
  6587. if (result == DECODE_MISMATCH) goto badtag;
  6588. if (result >= 0) return result;
  6589. })
  6590. VMCASE(OP_DISPATCH, {
  6591. CHECK_RETURN(dispatch(d));
  6592. })
  6593. VMCASE(OP_HALT, {
  6594. return size;
  6595. })
  6596. }
  6597. }
  6598. }
  6599. void *upb_pbdecoder_startbc(void *closure, const void *pc, size_t size_hint) {
  6600. upb_pbdecoder *d = closure;
  6601. UPB_UNUSED(size_hint);
  6602. d->call_len = 1;
  6603. d->pc = pc;
  6604. return d;
  6605. }
  6606. void *upb_pbdecoder_startjit(void *closure, const void *hd, size_t size_hint) {
  6607. UPB_UNUSED(hd);
  6608. UPB_UNUSED(size_hint);
  6609. upb_pbdecoder *d = closure;
  6610. d->call_len = 0;
  6611. return d;
  6612. }
  6613. bool upb_pbdecoder_end(void *closure, const void *handler_data) {
  6614. upb_pbdecoder *d = closure;
  6615. const upb_pbdecodermethod *method = handler_data;
  6616. if (d->residual_end > d->residual) {
  6617. seterr(d, "Unexpected EOF");
  6618. return false;
  6619. }
  6620. if (d->top->end_ofs != UINT64_MAX) {
  6621. seterr(d, "Unexpected EOF inside delimited string");
  6622. return false;
  6623. }
  6624. // Message ends here.
  6625. uint64_t end = offset(d);
  6626. d->top->end_ofs = end;
  6627. char dummy;
  6628. #ifdef UPB_USE_JIT_X64
  6629. const mgroup *group = (const mgroup*)method->group;
  6630. if (group->jit_code) {
  6631. if (d->top != d->stack)
  6632. d->stack->end_ofs = 0;
  6633. group->jit_code(closure, method->code_base.ptr, &dummy, 0, NULL);
  6634. } else {
  6635. #endif
  6636. d->stack->end_ofs = end;
  6637. const uint32_t *p = d->pc;
  6638. // Check the previous bytecode, but guard against beginning.
  6639. if (p != method->code_base.ptr) p--;
  6640. if (getop(*p) == OP_CHECKDELIM) {
  6641. // Rewind from OP_TAG* to OP_CHECKDELIM.
  6642. assert(getop(*d->pc) == OP_TAG1 ||
  6643. getop(*d->pc) == OP_TAG2 ||
  6644. getop(*d->pc) == OP_TAGN ||
  6645. getop(*d->pc == OP_DISPATCH));
  6646. d->pc = p;
  6647. }
  6648. upb_pbdecoder_decode(closure, handler_data, &dummy, 0, NULL);
  6649. #ifdef UPB_USE_JIT_X64
  6650. }
  6651. #endif
  6652. if (d->call_len != 0) {
  6653. seterr(d, "Unexpected EOF");
  6654. return false;
  6655. }
  6656. return true;
  6657. }
  6658. void upb_pbdecoder_init(upb_pbdecoder *d, const upb_pbdecodermethod *m,
  6659. upb_status *s) {
  6660. d->limit = &d->stack[UPB_DECODER_MAX_NESTING];
  6661. upb_bytessink_reset(&d->input_, &m->input_handler_, d);
  6662. d->method_ = m;
  6663. d->callstack[0] = &halt;
  6664. d->status = s;
  6665. upb_pbdecoder_reset(d);
  6666. }
  6667. void upb_pbdecoder_reset(upb_pbdecoder *d) {
  6668. d->top = d->stack;
  6669. d->top->end_ofs = UINT64_MAX;
  6670. d->top->groupnum = 0;
  6671. d->bufstart_ofs = 0;
  6672. d->ptr = d->residual;
  6673. d->buf = d->residual;
  6674. d->end = d->residual;
  6675. d->residual_end = d->residual;
  6676. d->call_len = 1;
  6677. }
  6678. uint64_t upb_pbdecoder_bytesparsed(const upb_pbdecoder *d) {
  6679. return offset(d);
  6680. }
  6681. // Not currently required, but to support outgrowing the static stack we need
  6682. // this.
  6683. void upb_pbdecoder_uninit(upb_pbdecoder *d) {
  6684. UPB_UNUSED(d);
  6685. }
  6686. const upb_pbdecodermethod *upb_pbdecoder_method(const upb_pbdecoder *d) {
  6687. return d->method_;
  6688. }
  6689. bool upb_pbdecoder_resetoutput(upb_pbdecoder *d, upb_sink* sink) {
  6690. // TODO(haberman): do we need to test whether the decoder is already on the
  6691. // stack (like calling this from within a callback)? Should we support
  6692. // rebinding the output at all?
  6693. assert(sink);
  6694. if (d->method_->dest_handlers_) {
  6695. if (sink->handlers != d->method_->dest_handlers_)
  6696. return false;
  6697. }
  6698. upb_sink_reset(&d->top->sink, sink->handlers, sink->closure);
  6699. return true;
  6700. }
  6701. upb_bytessink *upb_pbdecoder_input(upb_pbdecoder *d) {
  6702. return &d->input_;
  6703. }
  6704. /*
  6705. * upb - a minimalist implementation of protocol buffers.
  6706. *
  6707. * Copyright (c) 2014 Google Inc. See LICENSE for details.
  6708. * Author: Josh Haberman <jhaberman@gmail.com>
  6709. *
  6710. * Since we are implementing pure handlers (ie. without any out-of-band access
  6711. * to pre-computed lengths), we have to buffer all submessages before we can
  6712. * emit even their first byte.
  6713. *
  6714. * Not knowing the size of submessages also means we can't write a perfect
  6715. * zero-copy implementation, even with buffering. Lengths are stored as
  6716. * varints, which means that we don't know how many bytes to reserve for the
  6717. * length until we know what the length is.
  6718. *
  6719. * This leaves us with three main choices:
  6720. *
  6721. * 1. buffer all submessage data in a temporary buffer, then copy it exactly
  6722. * once into the output buffer.
  6723. *
  6724. * 2. attempt to buffer data directly into the output buffer, estimating how
  6725. * many bytes each length will take. When our guesses are wrong, use
  6726. * memmove() to grow or shrink the allotted space.
  6727. *
  6728. * 3. buffer directly into the output buffer, allocating a max length
  6729. * ahead-of-time for each submessage length. If we overallocated, we waste
  6730. * space, but no memcpy() or memmove() is required. This approach requires
  6731. * defining a maximum size for submessages and rejecting submessages that
  6732. * exceed that size.
  6733. *
  6734. * (2) and (3) have the potential to have better performance, but they are more
  6735. * complicated and subtle to implement:
  6736. *
  6737. * (3) requires making an arbitrary choice of the maximum message size; it
  6738. * wastes space when submessages are shorter than this and fails
  6739. * completely when they are longer. This makes it more finicky and
  6740. * requires configuration based on the input. It also makes it impossible
  6741. * to perfectly match the output of reference encoders that always use the
  6742. * optimal amount of space for each length.
  6743. *
  6744. * (2) requires guessing the the size upfront, and if multiple lengths are
  6745. * guessed wrong the minimum required number of memmove() operations may
  6746. * be complicated to compute correctly. Implemented properly, it may have
  6747. * a useful amortized or average cost, but more investigation is required
  6748. * to determine this and what the optimal algorithm is to achieve it.
  6749. *
  6750. * (1) makes you always pay for exactly one copy, but its implementation is
  6751. * the simplest and its performance is predictable.
  6752. *
  6753. * So for now, we implement (1) only. If we wish to optimize later, we should
  6754. * be able to do it without affecting users.
  6755. *
  6756. * The strategy is to buffer the segments of data that do *not* depend on
  6757. * unknown lengths in one buffer, and keep a separate buffer of segment pointers
  6758. * and lengths. When the top-level submessage ends, we can go beginning to end,
  6759. * alternating the writing of lengths with memcpy() of the rest of the data.
  6760. * At the top level though, no buffering is required.
  6761. */
  6762. #include <stdlib.h>
  6763. /* low-level buffering ********************************************************/
  6764. // Low-level functions for interacting with the output buffer.
  6765. // TODO(haberman): handle pushback
  6766. static void putbuf(upb_pb_encoder *e, const char *buf, size_t len) {
  6767. size_t n = upb_bytessink_putbuf(e->output_, e->subc, buf, len, NULL);
  6768. UPB_ASSERT_VAR(n, n == len);
  6769. }
  6770. static upb_pb_encoder_segment *top(upb_pb_encoder *e) {
  6771. return &e->segbuf[*e->top];
  6772. }
  6773. // Call to ensure that at least "bytes" bytes are available for writing at
  6774. // e->ptr. Returns false if the bytes could not be allocated.
  6775. static bool reserve(upb_pb_encoder *e, size_t bytes) {
  6776. if ((e->limit - e->ptr) < bytes) {
  6777. size_t needed = bytes + (e->ptr - e->buf);
  6778. size_t old_size = e->limit - e->buf;
  6779. size_t new_size = old_size;
  6780. while (new_size < needed) {
  6781. new_size *= 2;
  6782. }
  6783. char *realloc_from = (e->buf == e->initbuf) ? NULL : e->buf;
  6784. char *new_buf = realloc(realloc_from, new_size);
  6785. if (new_buf == NULL) {
  6786. return false;
  6787. }
  6788. if (realloc_from == NULL) {
  6789. memcpy(new_buf, e->initbuf, old_size);
  6790. }
  6791. e->ptr = new_buf + (e->ptr - e->buf);
  6792. e->runbegin = new_buf + (e->runbegin - e->buf);
  6793. e->limit = new_buf + new_size;
  6794. e->buf = new_buf;
  6795. }
  6796. return true;
  6797. }
  6798. // Call when "bytes" bytes have been writte at e->ptr. The caller *must* have
  6799. // previously called reserve() with at least this many bytes.
  6800. static void encoder_advance(upb_pb_encoder *e, size_t bytes) {
  6801. assert((e->limit - e->ptr) >= bytes);
  6802. e->ptr += bytes;
  6803. }
  6804. // Call when all of the bytes for a handler have been written. Flushes the
  6805. // bytes if possible and necessary, returning false if this failed.
  6806. static bool commit(upb_pb_encoder *e) {
  6807. if (!e->top) {
  6808. // We aren't inside a delimited region. Flush our accumulated bytes to
  6809. // the output.
  6810. //
  6811. // TODO(haberman): in the future we may want to delay flushing for
  6812. // efficiency reasons.
  6813. putbuf(e, e->buf, e->ptr - e->buf);
  6814. e->ptr = e->buf;
  6815. }
  6816. return true;
  6817. }
  6818. // Writes the given bytes to the buffer, handling reserve/advance.
  6819. static bool encode_bytes(upb_pb_encoder *e, const void *data, size_t len) {
  6820. if (!reserve(e, len)) {
  6821. return false;
  6822. }
  6823. memcpy(e->ptr, data, len);
  6824. encoder_advance(e, len);
  6825. return true;
  6826. }
  6827. // Finish the current run by adding the run totals to the segment and message
  6828. // length.
  6829. static void accumulate(upb_pb_encoder *e) {
  6830. assert(e->ptr >= e->runbegin);
  6831. size_t run_len = e->ptr - e->runbegin;
  6832. e->segptr->seglen += run_len;
  6833. top(e)->msglen += run_len;
  6834. e->runbegin = e->ptr;
  6835. }
  6836. // Call to indicate the start of delimited region for which the full length is
  6837. // not yet known. All data will be buffered until the length is known.
  6838. // Delimited regions may be nested; their lengths will all be tracked properly.
  6839. static bool start_delim(upb_pb_encoder *e) {
  6840. if (e->top) {
  6841. // We are already buffering, advance to the next segment and push it on the
  6842. // stack.
  6843. accumulate(e);
  6844. if (++e->top == e->stacklimit) {
  6845. // TODO(haberman): grow stack?
  6846. return false;
  6847. }
  6848. if (++e->segptr == e->seglimit) {
  6849. upb_pb_encoder_segment *realloc_from =
  6850. (e->segbuf == e->seginitbuf) ? NULL : e->segbuf;
  6851. size_t old_size =
  6852. (e->seglimit - e->segbuf) * sizeof(upb_pb_encoder_segment);
  6853. size_t new_size = old_size * 2;
  6854. upb_pb_encoder_segment *new_buf = realloc(realloc_from, new_size);
  6855. if (new_buf == NULL) {
  6856. return false;
  6857. }
  6858. if (realloc_from == NULL) {
  6859. memcpy(new_buf, e->seginitbuf, old_size);
  6860. }
  6861. e->segptr = new_buf + (e->segptr - e->segbuf);
  6862. e->seglimit = new_buf + (new_size / sizeof(upb_pb_encoder_segment));
  6863. e->segbuf = new_buf;
  6864. }
  6865. } else {
  6866. // We were previously at the top level, start buffering.
  6867. e->segptr = e->segbuf;
  6868. e->top = e->stack;
  6869. e->runbegin = e->ptr;
  6870. }
  6871. *e->top = e->segptr - e->segbuf;
  6872. e->segptr->seglen = 0;
  6873. e->segptr->msglen = 0;
  6874. return true;
  6875. }
  6876. // Call to indicate the end of a delimited region. We now know the length of
  6877. // the delimited region. If we are not nested inside any other delimited
  6878. // regions, we can now emit all of the buffered data we accumulated.
  6879. static bool end_delim(upb_pb_encoder *e) {
  6880. accumulate(e);
  6881. size_t msglen = top(e)->msglen;
  6882. if (e->top == e->stack) {
  6883. // All lengths are now available, emit all buffered data.
  6884. char buf[UPB_PB_VARINT_MAX_LEN];
  6885. upb_pb_encoder_segment *s;
  6886. const char *ptr = e->buf;
  6887. for (s = e->segbuf; s <= e->segptr; s++) {
  6888. size_t lenbytes = upb_vencode64(s->msglen, buf);
  6889. putbuf(e, buf, lenbytes);
  6890. putbuf(e, ptr, s->seglen);
  6891. ptr += s->seglen;
  6892. }
  6893. e->ptr = e->buf;
  6894. e->top = NULL;
  6895. } else {
  6896. // Need to keep buffering; propagate length info into enclosing submessages.
  6897. --e->top;
  6898. top(e)->msglen += msglen + upb_varint_size(msglen);
  6899. }
  6900. return true;
  6901. }
  6902. /* tag_t **********************************************************************/
  6903. // A precomputed (pre-encoded) tag and length.
  6904. typedef struct {
  6905. uint8_t bytes;
  6906. char tag[7];
  6907. } tag_t;
  6908. // Allocates a new tag for this field, and sets it in these handlerattr.
  6909. static void new_tag(upb_handlers *h, const upb_fielddef *f, upb_wiretype_t wt,
  6910. upb_handlerattr *attr) {
  6911. uint32_t n = upb_fielddef_number(f);
  6912. tag_t *tag = malloc(sizeof(tag_t));
  6913. tag->bytes = upb_vencode64((n << 3) | wt, tag->tag);
  6914. upb_handlerattr_init(attr);
  6915. upb_handlerattr_sethandlerdata(attr, tag);
  6916. upb_handlers_addcleanup(h, tag, free);
  6917. }
  6918. static bool encode_tag(upb_pb_encoder *e, const tag_t *tag) {
  6919. return encode_bytes(e, tag->tag, tag->bytes);
  6920. }
  6921. /* encoding of wire types *****************************************************/
  6922. static bool encode_fixed64(upb_pb_encoder *e, uint64_t val) {
  6923. // TODO(haberman): byte-swap for big endian.
  6924. return encode_bytes(e, &val, sizeof(uint64_t));
  6925. }
  6926. static bool encode_fixed32(upb_pb_encoder *e, uint32_t val) {
  6927. // TODO(haberman): byte-swap for big endian.
  6928. return encode_bytes(e, &val, sizeof(uint32_t));
  6929. }
  6930. static bool encode_varint(upb_pb_encoder *e, uint64_t val) {
  6931. if (!reserve(e, UPB_PB_VARINT_MAX_LEN)) {
  6932. return false;
  6933. }
  6934. encoder_advance(e, upb_vencode64(val, e->ptr));
  6935. return true;
  6936. }
  6937. static uint64_t dbl2uint64(double d) {
  6938. uint64_t ret;
  6939. memcpy(&ret, &d, sizeof(uint64_t));
  6940. return ret;
  6941. }
  6942. static uint32_t flt2uint32(float d) {
  6943. uint32_t ret;
  6944. memcpy(&ret, &d, sizeof(uint32_t));
  6945. return ret;
  6946. }
  6947. /* encoding of proto types ****************************************************/
  6948. static bool startmsg(void *c, const void *hd) {
  6949. upb_pb_encoder *e = c;
  6950. UPB_UNUSED(hd);
  6951. if (e->depth++ == 0) {
  6952. upb_bytessink_start(e->output_, 0, &e->subc);
  6953. }
  6954. return true;
  6955. }
  6956. static bool endmsg(void *c, const void *hd, upb_status *status) {
  6957. upb_pb_encoder *e = c;
  6958. UPB_UNUSED(hd);
  6959. UPB_UNUSED(status);
  6960. if (--e->depth == 0) {
  6961. upb_bytessink_end(e->output_);
  6962. }
  6963. return true;
  6964. }
  6965. static void *encode_startdelimfield(void *c, const void *hd) {
  6966. bool ok = encode_tag(c, hd) && commit(c) && start_delim(c);
  6967. return ok ? c : UPB_BREAK;
  6968. }
  6969. static bool encode_enddelimfield(void *c, const void *hd) {
  6970. UPB_UNUSED(hd);
  6971. return end_delim(c);
  6972. }
  6973. static void *encode_startgroup(void *c, const void *hd) {
  6974. return (encode_tag(c, hd) && commit(c)) ? c : UPB_BREAK;
  6975. }
  6976. static bool encode_endgroup(void *c, const void *hd) {
  6977. return encode_tag(c, hd) && commit(c);
  6978. }
  6979. static void *encode_startstr(void *c, const void *hd, size_t size_hint) {
  6980. UPB_UNUSED(size_hint);
  6981. return encode_startdelimfield(c, hd);
  6982. }
  6983. static size_t encode_strbuf(void *c, const void *hd, const char *buf,
  6984. size_t len, const upb_bufhandle *h) {
  6985. UPB_UNUSED(hd);
  6986. UPB_UNUSED(h);
  6987. return encode_bytes(c, buf, len) ? len : 0;
  6988. }
  6989. #define T(type, ctype, convert, encode) \
  6990. static bool encode_scalar_##type(void *e, const void *hd, ctype val) { \
  6991. return encode_tag(e, hd) && encode(e, (convert)(val)) && commit(e); \
  6992. } \
  6993. static bool encode_packed_##type(void *e, const void *hd, ctype val) { \
  6994. UPB_UNUSED(hd); \
  6995. return encode(e, (convert)(val)); \
  6996. }
  6997. T(double, double, dbl2uint64, encode_fixed64)
  6998. T(float, float, flt2uint32, encode_fixed32);
  6999. T(int64, int64_t, uint64_t, encode_varint);
  7000. T(int32, int32_t, uint32_t, encode_varint);
  7001. T(fixed64, uint64_t, uint64_t, encode_fixed64);
  7002. T(fixed32, uint32_t, uint32_t, encode_fixed32);
  7003. T(bool, bool, bool, encode_varint);
  7004. T(uint32, uint32_t, uint32_t, encode_varint);
  7005. T(uint64, uint64_t, uint64_t, encode_varint);
  7006. T(enum, int32_t, uint32_t, encode_varint);
  7007. T(sfixed32, int32_t, uint32_t, encode_fixed32);
  7008. T(sfixed64, int64_t, uint64_t, encode_fixed64);
  7009. T(sint32, int32_t, upb_zzenc_32, encode_varint);
  7010. T(sint64, int64_t, upb_zzenc_64, encode_varint);
  7011. #undef T
  7012. /* code to build the handlers *************************************************/
  7013. static void newhandlers_callback(const void *closure, upb_handlers *h) {
  7014. UPB_UNUSED(closure);
  7015. upb_handlers_setstartmsg(h, startmsg, NULL);
  7016. upb_handlers_setendmsg(h, endmsg, NULL);
  7017. const upb_msgdef *m = upb_handlers_msgdef(h);
  7018. upb_msg_iter i;
  7019. for(upb_msg_begin(&i, m); !upb_msg_done(&i); upb_msg_next(&i)) {
  7020. const upb_fielddef *f = upb_msg_iter_field(&i);
  7021. bool packed = upb_fielddef_isseq(f) && upb_fielddef_isprimitive(f) &&
  7022. upb_fielddef_packed(f);
  7023. upb_handlerattr attr;
  7024. upb_wiretype_t wt =
  7025. packed ? UPB_WIRE_TYPE_DELIMITED
  7026. : upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  7027. // Pre-encode the tag for this field.
  7028. new_tag(h, f, wt, &attr);
  7029. if (packed) {
  7030. upb_handlers_setstartseq(h, f, encode_startdelimfield, &attr);
  7031. upb_handlers_setendseq(h, f, encode_enddelimfield, &attr);
  7032. }
  7033. #define T(upper, lower, upbtype) \
  7034. case UPB_DESCRIPTOR_TYPE_##upper: \
  7035. if (packed) { \
  7036. upb_handlers_set##upbtype(h, f, encode_packed_##lower, &attr); \
  7037. } else { \
  7038. upb_handlers_set##upbtype(h, f, encode_scalar_##lower, &attr); \
  7039. } \
  7040. break;
  7041. switch (upb_fielddef_descriptortype(f)) {
  7042. T(DOUBLE, double, double);
  7043. T(FLOAT, float, float);
  7044. T(INT64, int64, int64);
  7045. T(INT32, int32, int32);
  7046. T(FIXED64, fixed64, uint64);
  7047. T(FIXED32, fixed32, uint32);
  7048. T(BOOL, bool, bool);
  7049. T(UINT32, uint32, uint32);
  7050. T(UINT64, uint64, uint64);
  7051. T(ENUM, enum, int32);
  7052. T(SFIXED32, sfixed32, int32);
  7053. T(SFIXED64, sfixed64, int64);
  7054. T(SINT32, sint32, int32);
  7055. T(SINT64, sint64, int64);
  7056. case UPB_DESCRIPTOR_TYPE_STRING:
  7057. case UPB_DESCRIPTOR_TYPE_BYTES:
  7058. upb_handlers_setstartstr(h, f, encode_startstr, &attr);
  7059. upb_handlers_setendstr(h, f, encode_enddelimfield, &attr);
  7060. upb_handlers_setstring(h, f, encode_strbuf, &attr);
  7061. break;
  7062. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  7063. upb_handlers_setstartsubmsg(h, f, encode_startdelimfield, &attr);
  7064. upb_handlers_setendsubmsg(h, f, encode_enddelimfield, &attr);
  7065. break;
  7066. case UPB_DESCRIPTOR_TYPE_GROUP: {
  7067. // Endgroup takes a different tag (wire_type = END_GROUP).
  7068. upb_handlerattr attr2;
  7069. new_tag(h, f, UPB_WIRE_TYPE_END_GROUP, &attr2);
  7070. upb_handlers_setstartsubmsg(h, f, encode_startgroup, &attr);
  7071. upb_handlers_setendsubmsg(h, f, encode_endgroup, &attr2);
  7072. upb_handlerattr_uninit(&attr2);
  7073. break;
  7074. }
  7075. }
  7076. #undef T
  7077. upb_handlerattr_uninit(&attr);
  7078. }
  7079. }
  7080. /* public API *****************************************************************/
  7081. const upb_handlers *upb_pb_encoder_newhandlers(const upb_msgdef *m,
  7082. const void *owner) {
  7083. return upb_handlers_newfrozen(m, owner, newhandlers_callback, NULL);
  7084. }
  7085. #define ARRAYSIZE(x) (sizeof(x) / sizeof(x[0]))
  7086. void upb_pb_encoder_init(upb_pb_encoder *e, const upb_handlers *h) {
  7087. e->output_ = NULL;
  7088. e->subc = NULL;
  7089. e->buf = e->initbuf;
  7090. e->ptr = e->buf;
  7091. e->limit = e->buf + ARRAYSIZE(e->initbuf);
  7092. e->segbuf = e->seginitbuf;
  7093. e->seglimit = e->segbuf + ARRAYSIZE(e->seginitbuf);
  7094. e->stacklimit = e->stack + ARRAYSIZE(e->stack);
  7095. upb_sink_reset(&e->input_, h, e);
  7096. }
  7097. void upb_pb_encoder_uninit(upb_pb_encoder *e) {
  7098. if (e->buf != e->initbuf) {
  7099. free(e->buf);
  7100. }
  7101. if (e->segbuf != e->seginitbuf) {
  7102. free(e->segbuf);
  7103. }
  7104. }
  7105. void upb_pb_encoder_resetoutput(upb_pb_encoder *e, upb_bytessink *output) {
  7106. upb_pb_encoder_reset(e);
  7107. e->output_ = output;
  7108. e->subc = output->closure;
  7109. }
  7110. void upb_pb_encoder_reset(upb_pb_encoder *e) {
  7111. e->segptr = NULL;
  7112. e->top = NULL;
  7113. e->depth = 0;
  7114. }
  7115. upb_sink *upb_pb_encoder_input(upb_pb_encoder *e) { return &e->input_; }
  7116. /*
  7117. * upb - a minimalist implementation of protocol buffers.
  7118. *
  7119. * Copyright (c) 2010-2012 Google Inc. See LICENSE for details.
  7120. * Author: Josh Haberman <jhaberman@gmail.com>
  7121. */
  7122. #include <stdio.h>
  7123. #include <stdlib.h>
  7124. #include <string.h>
  7125. upb_def **upb_load_defs_from_descriptor(const char *str, size_t len, int *n,
  7126. void *owner, upb_status *status) {
  7127. // Create handlers.
  7128. const upb_handlers *reader_h = upb_descreader_newhandlers(&reader_h);
  7129. upb_pbdecodermethodopts opts;
  7130. upb_pbdecodermethodopts_init(&opts, reader_h);
  7131. const upb_pbdecodermethod *decoder_m =
  7132. upb_pbdecodermethod_new(&opts, &decoder_m);
  7133. upb_pbdecoder decoder;
  7134. upb_descreader reader;
  7135. upb_pbdecoder_init(&decoder, decoder_m, status);
  7136. upb_descreader_init(&reader, reader_h, status);
  7137. upb_pbdecoder_resetoutput(&decoder, upb_descreader_input(&reader));
  7138. // Push input data.
  7139. bool ok = upb_bufsrc_putbuf(str, len, upb_pbdecoder_input(&decoder));
  7140. upb_def **ret = NULL;
  7141. if (!ok) goto cleanup;
  7142. upb_def **defs = upb_descreader_getdefs(&reader, owner, n);
  7143. ret = malloc(sizeof(upb_def*) * (*n));
  7144. memcpy(ret, defs, sizeof(upb_def*) * (*n));
  7145. cleanup:
  7146. upb_pbdecoder_uninit(&decoder);
  7147. upb_descreader_uninit(&reader);
  7148. upb_handlers_unref(reader_h, &reader_h);
  7149. upb_pbdecodermethod_unref(decoder_m, &decoder_m);
  7150. return ret;
  7151. }
  7152. bool upb_load_descriptor_into_symtab(upb_symtab *s, const char *str, size_t len,
  7153. upb_status *status) {
  7154. int n;
  7155. upb_def **defs = upb_load_defs_from_descriptor(str, len, &n, &defs, status);
  7156. if (!defs) return false;
  7157. bool success = upb_symtab_add(s, defs, n, &defs, status);
  7158. free(defs);
  7159. return success;
  7160. }
  7161. char *upb_readfile(const char *filename, size_t *len) {
  7162. FILE *f = fopen(filename, "rb");
  7163. if(!f) return NULL;
  7164. if(fseek(f, 0, SEEK_END) != 0) goto error;
  7165. long size = ftell(f);
  7166. if(size < 0) goto error;
  7167. if(fseek(f, 0, SEEK_SET) != 0) goto error;
  7168. char *buf = malloc(size + 1);
  7169. if(size && fread(buf, size, 1, f) != 1) goto error;
  7170. fclose(f);
  7171. if (len) *len = size;
  7172. return buf;
  7173. error:
  7174. fclose(f);
  7175. return NULL;
  7176. }
  7177. bool upb_load_descriptor_file_into_symtab(upb_symtab *symtab, const char *fname,
  7178. upb_status *status) {
  7179. size_t len;
  7180. char *data = upb_readfile(fname, &len);
  7181. if (!data) {
  7182. if (status) upb_status_seterrf(status, "Couldn't read file: %s", fname);
  7183. return false;
  7184. }
  7185. bool success = upb_load_descriptor_into_symtab(symtab, data, len, status);
  7186. free(data);
  7187. return success;
  7188. }
  7189. /*
  7190. * upb - a minimalist implementation of protocol buffers.
  7191. *
  7192. * Copyright (c) 2009 Google Inc. See LICENSE for details.
  7193. * Author: Josh Haberman <jhaberman@gmail.com>
  7194. *
  7195. * OPT: This is not optimized at all. It uses printf() which parses the format
  7196. * string every time, and it allocates memory for every put.
  7197. */
  7198. #include <ctype.h>
  7199. #include <float.h>
  7200. #include <inttypes.h>
  7201. #include <stdio.h>
  7202. #include <stdlib.h>
  7203. #include <string.h>
  7204. #define CHECK(x) if ((x) < 0) goto err;
  7205. static const char *shortname(const char *longname) {
  7206. const char *last = strrchr(longname, '.');
  7207. return last ? last + 1 : longname;
  7208. }
  7209. static int indent(upb_textprinter *p) {
  7210. int i;
  7211. if (!p->single_line_)
  7212. for (i = 0; i < p->indent_depth_; i++)
  7213. upb_bytessink_putbuf(p->output_, p->subc, " ", 2, NULL);
  7214. return 0;
  7215. }
  7216. static int endfield(upb_textprinter *p) {
  7217. const char ch = (p->single_line_ ? ' ' : '\n');
  7218. upb_bytessink_putbuf(p->output_, p->subc, &ch, 1, NULL);
  7219. return 0;
  7220. }
  7221. static int putescaped(upb_textprinter *p, const char *buf, size_t len,
  7222. bool preserve_utf8) {
  7223. // Based on CEscapeInternal() from Google's protobuf release.
  7224. char dstbuf[4096], *dst = dstbuf, *dstend = dstbuf + sizeof(dstbuf);
  7225. const char *end = buf + len;
  7226. // I think hex is prettier and more useful, but proto2 uses octal; should
  7227. // investigate whether it can parse hex also.
  7228. const bool use_hex = false;
  7229. bool last_hex_escape = false; // true if last output char was \xNN
  7230. for (; buf < end; buf++) {
  7231. if (dstend - dst < 4) {
  7232. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  7233. dst = dstbuf;
  7234. }
  7235. bool is_hex_escape = false;
  7236. switch (*buf) {
  7237. case '\n': *(dst++) = '\\'; *(dst++) = 'n'; break;
  7238. case '\r': *(dst++) = '\\'; *(dst++) = 'r'; break;
  7239. case '\t': *(dst++) = '\\'; *(dst++) = 't'; break;
  7240. case '\"': *(dst++) = '\\'; *(dst++) = '\"'; break;
  7241. case '\'': *(dst++) = '\\'; *(dst++) = '\''; break;
  7242. case '\\': *(dst++) = '\\'; *(dst++) = '\\'; break;
  7243. default:
  7244. // Note that if we emit \xNN and the buf character after that is a hex
  7245. // digit then that digit must be escaped too to prevent it being
  7246. // interpreted as part of the character code by C.
  7247. if ((!preserve_utf8 || (uint8_t)*buf < 0x80) &&
  7248. (!isprint(*buf) || (last_hex_escape && isxdigit(*buf)))) {
  7249. sprintf(dst, (use_hex ? "\\x%02x" : "\\%03o"), (uint8_t)*buf);
  7250. is_hex_escape = use_hex;
  7251. dst += 4;
  7252. } else {
  7253. *(dst++) = *buf; break;
  7254. }
  7255. }
  7256. last_hex_escape = is_hex_escape;
  7257. }
  7258. // Flush remaining data.
  7259. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  7260. return 0;
  7261. }
  7262. bool putf(upb_textprinter *p, const char *fmt, ...) {
  7263. va_list args;
  7264. va_start(args, fmt);
  7265. // Run once to get the length of the string.
  7266. va_list args_copy;
  7267. va_copy(args_copy, args);
  7268. int len = vsnprintf(NULL, 0, fmt, args_copy);
  7269. va_end(args_copy);
  7270. // + 1 for NULL terminator (vsnprintf() requires it even if we don't).
  7271. char *str = malloc(len + 1);
  7272. if (!str) return false;
  7273. int written = vsnprintf(str, len + 1, fmt, args);
  7274. va_end(args);
  7275. UPB_ASSERT_VAR(written, written == len);
  7276. bool ok = upb_bytessink_putbuf(p->output_, p->subc, str, len, NULL);
  7277. free(str);
  7278. return ok;
  7279. }
  7280. /* handlers *******************************************************************/
  7281. static bool textprinter_startmsg(void *c, const void *hd) {
  7282. UPB_UNUSED(hd);
  7283. upb_textprinter *p = c;
  7284. if (p->indent_depth_ == 0) {
  7285. upb_bytessink_start(p->output_, 0, &p->subc);
  7286. }
  7287. return true;
  7288. }
  7289. static bool textprinter_endmsg(void *c, const void *hd, upb_status *s) {
  7290. UPB_UNUSED(hd);
  7291. UPB_UNUSED(s);
  7292. upb_textprinter *p = c;
  7293. if (p->indent_depth_ == 0) {
  7294. upb_bytessink_end(p->output_);
  7295. }
  7296. return true;
  7297. }
  7298. #define TYPE(name, ctype, fmt) \
  7299. static bool textprinter_put ## name(void *closure, const void *handler_data, \
  7300. ctype val) { \
  7301. upb_textprinter *p = closure; \
  7302. const upb_fielddef *f = handler_data; \
  7303. CHECK(indent(p)); \
  7304. putf(p, "%s: " fmt, upb_fielddef_name(f), val); \
  7305. CHECK(endfield(p)); \
  7306. return true; \
  7307. err: \
  7308. return false; \
  7309. }
  7310. static bool textprinter_putbool(void *closure, const void *handler_data,
  7311. bool val) {
  7312. upb_textprinter *p = closure;
  7313. const upb_fielddef *f = handler_data;
  7314. CHECK(indent(p));
  7315. putf(p, "%s: %s", upb_fielddef_name(f), val ? "true" : "false");
  7316. CHECK(endfield(p));
  7317. return true;
  7318. err:
  7319. return false;
  7320. }
  7321. #define STRINGIFY_HELPER(x) #x
  7322. #define STRINGIFY_MACROVAL(x) STRINGIFY_HELPER(x)
  7323. TYPE(int32, int32_t, "%" PRId32)
  7324. TYPE(int64, int64_t, "%" PRId64)
  7325. TYPE(uint32, uint32_t, "%" PRIu32);
  7326. TYPE(uint64, uint64_t, "%" PRIu64)
  7327. TYPE(float, float, "%." STRINGIFY_MACROVAL(FLT_DIG) "g")
  7328. TYPE(double, double, "%." STRINGIFY_MACROVAL(DBL_DIG) "g")
  7329. #undef TYPE
  7330. // Output a symbolic value from the enum if found, else just print as int32.
  7331. static bool textprinter_putenum(void *closure, const void *handler_data,
  7332. int32_t val) {
  7333. upb_textprinter *p = closure;
  7334. const upb_fielddef *f = handler_data;
  7335. const upb_enumdef *enum_def = upb_downcast_enumdef(upb_fielddef_subdef(f));
  7336. const char *label = upb_enumdef_iton(enum_def, val);
  7337. if (label) {
  7338. indent(p);
  7339. putf(p, "%s: %s", upb_fielddef_name(f), label);
  7340. endfield(p);
  7341. } else {
  7342. if (!textprinter_putint32(closure, handler_data, val))
  7343. return false;
  7344. }
  7345. return true;
  7346. }
  7347. static void *textprinter_startstr(void *closure, const void *handler_data,
  7348. size_t size_hint) {
  7349. const upb_fielddef *f = handler_data;
  7350. UPB_UNUSED(size_hint);
  7351. upb_textprinter *p = closure;
  7352. indent(p);
  7353. putf(p, "%s: \"", upb_fielddef_name(f));
  7354. return p;
  7355. }
  7356. static bool textprinter_endstr(void *closure, const void *handler_data) {
  7357. UPB_UNUSED(handler_data);
  7358. upb_textprinter *p = closure;
  7359. putf(p, "\"");
  7360. endfield(p);
  7361. return true;
  7362. }
  7363. static size_t textprinter_putstr(void *closure, const void *hd, const char *buf,
  7364. size_t len, const upb_bufhandle *handle) {
  7365. UPB_UNUSED(handle);
  7366. upb_textprinter *p = closure;
  7367. const upb_fielddef *f = hd;
  7368. CHECK(putescaped(p, buf, len, upb_fielddef_type(f) == UPB_TYPE_STRING));
  7369. return len;
  7370. err:
  7371. return 0;
  7372. }
  7373. static void *textprinter_startsubmsg(void *closure, const void *handler_data) {
  7374. upb_textprinter *p = closure;
  7375. const char *name = handler_data;
  7376. CHECK(indent(p));
  7377. putf(p, "%s {%c", name, p->single_line_ ? ' ' : '\n');
  7378. p->indent_depth_++;
  7379. return p;
  7380. err:
  7381. return UPB_BREAK;
  7382. }
  7383. static bool textprinter_endsubmsg(void *closure, const void *handler_data) {
  7384. UPB_UNUSED(handler_data);
  7385. upb_textprinter *p = closure;
  7386. p->indent_depth_--;
  7387. CHECK(indent(p));
  7388. upb_bytessink_putbuf(p->output_, p->subc, "}", 1, NULL);
  7389. CHECK(endfield(p));
  7390. return true;
  7391. err:
  7392. return false;
  7393. }
  7394. /* Public API *****************************************************************/
  7395. void upb_textprinter_init(upb_textprinter *p, const upb_handlers *h) {
  7396. p->single_line_ = false;
  7397. p->indent_depth_ = 0;
  7398. upb_sink_reset(&p->input_, h, p);
  7399. }
  7400. void upb_textprinter_uninit(upb_textprinter *p) {
  7401. UPB_UNUSED(p);
  7402. }
  7403. void upb_textprinter_reset(upb_textprinter *p, bool single_line) {
  7404. p->single_line_ = single_line;
  7405. p->indent_depth_ = 0;
  7406. }
  7407. static void onmreg(const void *c, upb_handlers *h) {
  7408. UPB_UNUSED(c);
  7409. const upb_msgdef *m = upb_handlers_msgdef(h);
  7410. upb_handlers_setstartmsg(h, textprinter_startmsg, NULL);
  7411. upb_handlers_setendmsg(h, textprinter_endmsg, NULL);
  7412. upb_msg_iter i;
  7413. for(upb_msg_begin(&i, m); !upb_msg_done(&i); upb_msg_next(&i)) {
  7414. upb_fielddef *f = upb_msg_iter_field(&i);
  7415. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  7416. upb_handlerattr_sethandlerdata(&attr, f);
  7417. switch (upb_fielddef_type(f)) {
  7418. case UPB_TYPE_INT32:
  7419. upb_handlers_setint32(h, f, textprinter_putint32, &attr);
  7420. break;
  7421. case UPB_TYPE_INT64:
  7422. upb_handlers_setint64(h, f, textprinter_putint64, &attr);
  7423. break;
  7424. case UPB_TYPE_UINT32:
  7425. upb_handlers_setuint32(h, f, textprinter_putuint32, &attr);
  7426. break;
  7427. case UPB_TYPE_UINT64:
  7428. upb_handlers_setuint64(h, f, textprinter_putuint64, &attr);
  7429. break;
  7430. case UPB_TYPE_FLOAT:
  7431. upb_handlers_setfloat(h, f, textprinter_putfloat, &attr);
  7432. break;
  7433. case UPB_TYPE_DOUBLE:
  7434. upb_handlers_setdouble(h, f, textprinter_putdouble, &attr);
  7435. break;
  7436. case UPB_TYPE_BOOL:
  7437. upb_handlers_setbool(h, f, textprinter_putbool, &attr);
  7438. break;
  7439. case UPB_TYPE_STRING:
  7440. case UPB_TYPE_BYTES:
  7441. upb_handlers_setstartstr(h, f, textprinter_startstr, &attr);
  7442. upb_handlers_setstring(h, f, textprinter_putstr, &attr);
  7443. upb_handlers_setendstr(h, f, textprinter_endstr, &attr);
  7444. break;
  7445. case UPB_TYPE_MESSAGE: {
  7446. const char *name =
  7447. upb_fielddef_istagdelim(f)
  7448. ? shortname(upb_msgdef_fullname(upb_fielddef_msgsubdef(f)))
  7449. : upb_fielddef_name(f);
  7450. upb_handlerattr_sethandlerdata(&attr, name);
  7451. upb_handlers_setstartsubmsg(h, f, textprinter_startsubmsg, &attr);
  7452. upb_handlers_setendsubmsg(h, f, textprinter_endsubmsg, &attr);
  7453. break;
  7454. }
  7455. case UPB_TYPE_ENUM:
  7456. upb_handlers_setint32(h, f, textprinter_putenum, &attr);
  7457. break;
  7458. }
  7459. }
  7460. }
  7461. const upb_handlers *upb_textprinter_newhandlers(const upb_msgdef *m,
  7462. const void *owner) {
  7463. return upb_handlers_newfrozen(m, owner, &onmreg, NULL);
  7464. }
  7465. upb_sink *upb_textprinter_input(upb_textprinter *p) { return &p->input_; }
  7466. bool upb_textprinter_resetoutput(upb_textprinter *p, upb_bytessink *output) {
  7467. p->output_ = output;
  7468. return true;
  7469. }
  7470. void upb_textprinter_setsingleline(upb_textprinter *p, bool single_line) {
  7471. p->single_line_ = single_line;
  7472. }
  7473. /*
  7474. * upb - a minimalist implementation of protocol buffers.
  7475. *
  7476. * Copyright (c) 2011 Google Inc. See LICENSE for details.
  7477. * Author: Josh Haberman <jhaberman@gmail.com>
  7478. */
  7479. // Index is descriptor type.
  7480. const uint8_t upb_pb_native_wire_types[] = {
  7481. UPB_WIRE_TYPE_END_GROUP, // ENDGROUP
  7482. UPB_WIRE_TYPE_64BIT, // DOUBLE
  7483. UPB_WIRE_TYPE_32BIT, // FLOAT
  7484. UPB_WIRE_TYPE_VARINT, // INT64
  7485. UPB_WIRE_TYPE_VARINT, // UINT64
  7486. UPB_WIRE_TYPE_VARINT, // INT32
  7487. UPB_WIRE_TYPE_64BIT, // FIXED64
  7488. UPB_WIRE_TYPE_32BIT, // FIXED32
  7489. UPB_WIRE_TYPE_VARINT, // BOOL
  7490. UPB_WIRE_TYPE_DELIMITED, // STRING
  7491. UPB_WIRE_TYPE_START_GROUP, // GROUP
  7492. UPB_WIRE_TYPE_DELIMITED, // MESSAGE
  7493. UPB_WIRE_TYPE_DELIMITED, // BYTES
  7494. UPB_WIRE_TYPE_VARINT, // UINT32
  7495. UPB_WIRE_TYPE_VARINT, // ENUM
  7496. UPB_WIRE_TYPE_32BIT, // SFIXED32
  7497. UPB_WIRE_TYPE_64BIT, // SFIXED64
  7498. UPB_WIRE_TYPE_VARINT, // SINT32
  7499. UPB_WIRE_TYPE_VARINT, // SINT64
  7500. };
  7501. // A basic branch-based decoder, uses 32-bit values to get good performance
  7502. // on 32-bit architectures (but performs well on 64-bits also).
  7503. // This scheme comes from the original Google Protobuf implementation (proto2).
  7504. upb_decoderet upb_vdecode_max8_branch32(upb_decoderet r) {
  7505. upb_decoderet err = {NULL, 0};
  7506. const char *p = r.p;
  7507. uint32_t low = (uint32_t)r.val;
  7508. uint32_t high = 0;
  7509. uint32_t b;
  7510. b = *(p++); low |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  7511. b = *(p++); low |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  7512. b = *(p++); low |= (b & 0x7fU) << 28;
  7513. high = (b & 0x7fU) >> 4; if (!(b & 0x80)) goto done;
  7514. b = *(p++); high |= (b & 0x7fU) << 3; if (!(b & 0x80)) goto done;
  7515. b = *(p++); high |= (b & 0x7fU) << 10; if (!(b & 0x80)) goto done;
  7516. b = *(p++); high |= (b & 0x7fU) << 17; if (!(b & 0x80)) goto done;
  7517. b = *(p++); high |= (b & 0x7fU) << 24; if (!(b & 0x80)) goto done;
  7518. b = *(p++); high |= (b & 0x7fU) << 31; if (!(b & 0x80)) goto done;
  7519. return err;
  7520. done:
  7521. r.val = ((uint64_t)high << 32) | low;
  7522. r.p = p;
  7523. return r;
  7524. }
  7525. // Like the previous, but uses 64-bit values.
  7526. upb_decoderet upb_vdecode_max8_branch64(upb_decoderet r) {
  7527. const char *p = r.p;
  7528. uint64_t val = r.val;
  7529. uint64_t b;
  7530. upb_decoderet err = {NULL, 0};
  7531. b = *(p++); val |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  7532. b = *(p++); val |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  7533. b = *(p++); val |= (b & 0x7fU) << 28; if (!(b & 0x80)) goto done;
  7534. b = *(p++); val |= (b & 0x7fU) << 35; if (!(b & 0x80)) goto done;
  7535. b = *(p++); val |= (b & 0x7fU) << 42; if (!(b & 0x80)) goto done;
  7536. b = *(p++); val |= (b & 0x7fU) << 49; if (!(b & 0x80)) goto done;
  7537. b = *(p++); val |= (b & 0x7fU) << 56; if (!(b & 0x80)) goto done;
  7538. b = *(p++); val |= (b & 0x7fU) << 63; if (!(b & 0x80)) goto done;
  7539. return err;
  7540. done:
  7541. r.val = val;
  7542. r.p = p;
  7543. return r;
  7544. }
  7545. // Given an encoded varint v, returns an integer with a single bit set that
  7546. // indicates the end of the varint. Subtracting one from this value will
  7547. // yield a mask that leaves only bits that are part of the varint. Returns
  7548. // 0 if the varint is unterminated.
  7549. static uint64_t upb_get_vstopbit(uint64_t v) {
  7550. uint64_t cbits = v | 0x7f7f7f7f7f7f7f7fULL;
  7551. return ~cbits & (cbits+1);
  7552. }
  7553. // A branchless decoder. Credit to Pascal Massimino for the bit-twiddling.
  7554. upb_decoderet upb_vdecode_max8_massimino(upb_decoderet r) {
  7555. uint64_t b;
  7556. memcpy(&b, r.p, sizeof(b));
  7557. uint64_t stop_bit = upb_get_vstopbit(b);
  7558. b = (b & 0x7f7f7f7f7f7f7f7fULL) & (stop_bit - 1);
  7559. b += b & 0x007f007f007f007fULL;
  7560. b += 3 * (b & 0x0000ffff0000ffffULL);
  7561. b += 15 * (b & 0x00000000ffffffffULL);
  7562. if (stop_bit == 0) {
  7563. // Error: unterminated varint.
  7564. upb_decoderet err_r = {(void*)0, 0};
  7565. return err_r;
  7566. }
  7567. upb_decoderet my_r = {r.p + ((__builtin_ctzll(stop_bit) + 1) / 8),
  7568. r.val | (b << 7)};
  7569. return my_r;
  7570. }
  7571. // A branchless decoder. Credit to Daniel Wright for the bit-twiddling.
  7572. upb_decoderet upb_vdecode_max8_wright(upb_decoderet r) {
  7573. uint64_t b;
  7574. memcpy(&b, r.p, sizeof(b));
  7575. uint64_t stop_bit = upb_get_vstopbit(b);
  7576. b &= (stop_bit - 1);
  7577. b = ((b & 0x7f007f007f007f00ULL) >> 1) | (b & 0x007f007f007f007fULL);
  7578. b = ((b & 0xffff0000ffff0000ULL) >> 2) | (b & 0x0000ffff0000ffffULL);
  7579. b = ((b & 0xffffffff00000000ULL) >> 4) | (b & 0x00000000ffffffffULL);
  7580. if (stop_bit == 0) {
  7581. // Error: unterminated varint.
  7582. upb_decoderet err_r = {(void*)0, 0};
  7583. return err_r;
  7584. }
  7585. upb_decoderet my_r = {r.p + ((__builtin_ctzll(stop_bit) + 1) / 8),
  7586. r.val | (b << 14)};
  7587. return my_r;
  7588. }
  7589. #line 1 "upb/json/parser.rl"
  7590. /*
  7591. * upb - a minimalist implementation of protocol buffers.
  7592. *
  7593. * Copyright (c) 2014 Google Inc. See LICENSE for details.
  7594. * Author: Josh Haberman <jhaberman@gmail.com>
  7595. *
  7596. * A parser that uses the Ragel State Machine Compiler to generate
  7597. * the finite automata.
  7598. *
  7599. * Ragel only natively handles regular languages, but we can manually
  7600. * program it a bit to handle context-free languages like JSON, by using
  7601. * the "fcall" and "fret" constructs.
  7602. *
  7603. * This parser can handle the basics, but needs several things to be fleshed
  7604. * out:
  7605. *
  7606. * - handling of unicode escape sequences (including high surrogate pairs).
  7607. * - properly check and report errors for unknown fields, stack overflow,
  7608. * improper array nesting (or lack of nesting).
  7609. * - handling of base64 sequences with padding characters.
  7610. * - handling of push-back (non-success returns from sink functions).
  7611. * - handling of keys/escape-sequences/etc that span input buffers.
  7612. */
  7613. #include <stdio.h>
  7614. #include <stdint.h>
  7615. #include <assert.h>
  7616. #include <string.h>
  7617. #include <stdlib.h>
  7618. #include <errno.h>
  7619. #define PARSER_CHECK_RETURN(x) if (!(x)) return false
  7620. // Used to signal that a capture has been suspended.
  7621. static char suspend_capture;
  7622. static upb_selector_t getsel_for_handlertype(upb_json_parser *p,
  7623. upb_handlertype_t type) {
  7624. upb_selector_t sel;
  7625. bool ok = upb_handlers_getselector(p->top->f, type, &sel);
  7626. UPB_ASSERT_VAR(ok, ok);
  7627. return sel;
  7628. }
  7629. static upb_selector_t parser_getsel(upb_json_parser *p) {
  7630. return getsel_for_handlertype(
  7631. p, upb_handlers_getprimitivehandlertype(p->top->f));
  7632. }
  7633. static bool check_stack(upb_json_parser *p) {
  7634. if ((p->top + 1) == p->limit) {
  7635. upb_status_seterrmsg(p->status, "Nesting too deep");
  7636. return false;
  7637. }
  7638. return true;
  7639. }
  7640. // There are GCC/Clang built-ins for overflow checking which we could start
  7641. // using if there was any performance benefit to it.
  7642. static bool checked_add(size_t a, size_t b, size_t *c) {
  7643. if (SIZE_MAX - a < b) return false;
  7644. *c = a + b;
  7645. return true;
  7646. }
  7647. static size_t saturating_multiply(size_t a, size_t b) {
  7648. // size_t is unsigned, so this is defined behavior even on overflow.
  7649. size_t ret = a * b;
  7650. if (b != 0 && ret / b != a) {
  7651. ret = SIZE_MAX;
  7652. }
  7653. return ret;
  7654. }
  7655. /* Base64 decoding ************************************************************/
  7656. // TODO(haberman): make this streaming.
  7657. static const signed char b64table[] = {
  7658. -1, -1, -1, -1, -1, -1, -1, -1,
  7659. -1, -1, -1, -1, -1, -1, -1, -1,
  7660. -1, -1, -1, -1, -1, -1, -1, -1,
  7661. -1, -1, -1, -1, -1, -1, -1, -1,
  7662. -1, -1, -1, -1, -1, -1, -1, -1,
  7663. -1, -1, -1, 62/*+*/, -1, -1, -1, 63/*/ */,
  7664. 52/*0*/, 53/*1*/, 54/*2*/, 55/*3*/, 56/*4*/, 57/*5*/, 58/*6*/, 59/*7*/,
  7665. 60/*8*/, 61/*9*/, -1, -1, -1, -1, -1, -1,
  7666. -1, 0/*A*/, 1/*B*/, 2/*C*/, 3/*D*/, 4/*E*/, 5/*F*/, 6/*G*/,
  7667. 07/*H*/, 8/*I*/, 9/*J*/, 10/*K*/, 11/*L*/, 12/*M*/, 13/*N*/, 14/*O*/,
  7668. 15/*P*/, 16/*Q*/, 17/*R*/, 18/*S*/, 19/*T*/, 20/*U*/, 21/*V*/, 22/*W*/,
  7669. 23/*X*/, 24/*Y*/, 25/*Z*/, -1, -1, -1, -1, -1,
  7670. -1, 26/*a*/, 27/*b*/, 28/*c*/, 29/*d*/, 30/*e*/, 31/*f*/, 32/*g*/,
  7671. 33/*h*/, 34/*i*/, 35/*j*/, 36/*k*/, 37/*l*/, 38/*m*/, 39/*n*/, 40/*o*/,
  7672. 41/*p*/, 42/*q*/, 43/*r*/, 44/*s*/, 45/*t*/, 46/*u*/, 47/*v*/, 48/*w*/,
  7673. 49/*x*/, 50/*y*/, 51/*z*/, -1, -1, -1, -1, -1,
  7674. -1, -1, -1, -1, -1, -1, -1, -1,
  7675. -1, -1, -1, -1, -1, -1, -1, -1,
  7676. -1, -1, -1, -1, -1, -1, -1, -1,
  7677. -1, -1, -1, -1, -1, -1, -1, -1,
  7678. -1, -1, -1, -1, -1, -1, -1, -1,
  7679. -1, -1, -1, -1, -1, -1, -1, -1,
  7680. -1, -1, -1, -1, -1, -1, -1, -1,
  7681. -1, -1, -1, -1, -1, -1, -1, -1,
  7682. -1, -1, -1, -1, -1, -1, -1, -1,
  7683. -1, -1, -1, -1, -1, -1, -1, -1,
  7684. -1, -1, -1, -1, -1, -1, -1, -1,
  7685. -1, -1, -1, -1, -1, -1, -1, -1,
  7686. -1, -1, -1, -1, -1, -1, -1, -1,
  7687. -1, -1, -1, -1, -1, -1, -1, -1,
  7688. -1, -1, -1, -1, -1, -1, -1, -1,
  7689. -1, -1, -1, -1, -1, -1, -1, -1
  7690. };
  7691. // Returns the table value sign-extended to 32 bits. Knowing that the upper
  7692. // bits will be 1 for unrecognized characters makes it easier to check for
  7693. // this error condition later (see below).
  7694. int32_t b64lookup(unsigned char ch) { return b64table[ch]; }
  7695. // Returns true if the given character is not a valid base64 character or
  7696. // padding.
  7697. bool nonbase64(unsigned char ch) { return b64lookup(ch) == -1 && ch != '='; }
  7698. static bool base64_push(upb_json_parser *p, upb_selector_t sel, const char *ptr,
  7699. size_t len) {
  7700. const char *limit = ptr + len;
  7701. for (; ptr < limit; ptr += 4) {
  7702. if (limit - ptr < 4) {
  7703. upb_status_seterrf(p->status,
  7704. "Base64 input for bytes field not a multiple of 4: %s",
  7705. upb_fielddef_name(p->top->f));
  7706. return false;
  7707. }
  7708. uint32_t val = b64lookup(ptr[0]) << 18 |
  7709. b64lookup(ptr[1]) << 12 |
  7710. b64lookup(ptr[2]) << 6 |
  7711. b64lookup(ptr[3]);
  7712. // Test the upper bit; returns true if any of the characters returned -1.
  7713. if (val & 0x80000000) {
  7714. goto otherchar;
  7715. }
  7716. char output[3];
  7717. output[0] = val >> 16;
  7718. output[1] = (val >> 8) & 0xff;
  7719. output[2] = val & 0xff;
  7720. upb_sink_putstring(&p->top->sink, sel, output, 3, NULL);
  7721. }
  7722. return true;
  7723. otherchar:
  7724. if (nonbase64(ptr[0]) || nonbase64(ptr[1]) || nonbase64(ptr[2]) ||
  7725. nonbase64(ptr[3]) ) {
  7726. upb_status_seterrf(p->status,
  7727. "Non-base64 characters in bytes field: %s",
  7728. upb_fielddef_name(p->top->f));
  7729. return false;
  7730. } if (ptr[2] == '=') {
  7731. // Last group contains only two input bytes, one output byte.
  7732. if (ptr[0] == '=' || ptr[1] == '=' || ptr[3] != '=') {
  7733. goto badpadding;
  7734. }
  7735. uint32_t val = b64lookup(ptr[0]) << 18 |
  7736. b64lookup(ptr[1]) << 12;
  7737. assert(!(val & 0x80000000));
  7738. char output = val >> 16;
  7739. upb_sink_putstring(&p->top->sink, sel, &output, 1, NULL);
  7740. return true;
  7741. } else {
  7742. // Last group contains only three input bytes, two output bytes.
  7743. if (ptr[0] == '=' || ptr[1] == '=' || ptr[2] == '=') {
  7744. goto badpadding;
  7745. }
  7746. uint32_t val = b64lookup(ptr[0]) << 18 |
  7747. b64lookup(ptr[1]) << 12 |
  7748. b64lookup(ptr[2]) << 6;
  7749. char output[2];
  7750. output[0] = val >> 16;
  7751. output[1] = (val >> 8) & 0xff;
  7752. upb_sink_putstring(&p->top->sink, sel, output, 2, NULL);
  7753. return true;
  7754. }
  7755. badpadding:
  7756. upb_status_seterrf(p->status,
  7757. "Incorrect base64 padding for field: %s (%.*s)",
  7758. upb_fielddef_name(p->top->f),
  7759. 4, ptr);
  7760. return false;
  7761. }
  7762. /* Accumulate buffer **********************************************************/
  7763. // Functionality for accumulating a buffer.
  7764. //
  7765. // Some parts of the parser need an entire value as a contiguous string. For
  7766. // example, to look up a member name in a hash table, or to turn a string into
  7767. // a number, the relevant library routines need the input string to be in
  7768. // contiguous memory, even if the value spanned two or more buffers in the
  7769. // input. These routines handle that.
  7770. //
  7771. // In the common case we can just point to the input buffer to get this
  7772. // contiguous string and avoid any actual copy. So we optimistically begin
  7773. // this way. But there are a few cases where we must instead copy into a
  7774. // separate buffer:
  7775. //
  7776. // 1. The string was not contiguous in the input (it spanned buffers).
  7777. //
  7778. // 2. The string included escape sequences that need to be interpreted to get
  7779. // the true value in a contiguous buffer.
  7780. static void assert_accumulate_empty(upb_json_parser *p) {
  7781. assert(p->accumulated == NULL);
  7782. assert(p->accumulated_len == 0);
  7783. }
  7784. static void accumulate_clear(upb_json_parser *p) {
  7785. p->accumulated = NULL;
  7786. p->accumulated_len = 0;
  7787. }
  7788. // Used internally by accumulate_append().
  7789. static bool accumulate_realloc(upb_json_parser *p, size_t need) {
  7790. size_t new_size = UPB_MAX(p->accumulate_buf_size, 128);
  7791. while (new_size < need) {
  7792. new_size = saturating_multiply(new_size, 2);
  7793. }
  7794. void *mem = realloc(p->accumulate_buf, new_size);
  7795. if (!mem) {
  7796. upb_status_seterrmsg(p->status, "Out of memory allocating buffer.");
  7797. return false;
  7798. }
  7799. p->accumulate_buf = mem;
  7800. p->accumulate_buf_size = new_size;
  7801. return true;
  7802. }
  7803. // Logically appends the given data to the append buffer.
  7804. // If "can_alias" is true, we will try to avoid actually copying, but the buffer
  7805. // must be valid until the next accumulate_append() call (if any).
  7806. static bool accumulate_append(upb_json_parser *p, const char *buf, size_t len,
  7807. bool can_alias) {
  7808. if (!p->accumulated && can_alias) {
  7809. p->accumulated = buf;
  7810. p->accumulated_len = len;
  7811. return true;
  7812. }
  7813. size_t need;
  7814. if (!checked_add(p->accumulated_len, len, &need)) {
  7815. upb_status_seterrmsg(p->status, "Integer overflow.");
  7816. return false;
  7817. }
  7818. if (need > p->accumulate_buf_size && !accumulate_realloc(p, need)) {
  7819. return false;
  7820. }
  7821. if (p->accumulated != p->accumulate_buf) {
  7822. memcpy(p->accumulate_buf, p->accumulated, p->accumulated_len);
  7823. p->accumulated = p->accumulate_buf;
  7824. }
  7825. memcpy(p->accumulate_buf + p->accumulated_len, buf, len);
  7826. p->accumulated_len += len;
  7827. return true;
  7828. }
  7829. // Returns a pointer to the data accumulated since the last accumulate_clear()
  7830. // call, and writes the length to *len. This with point either to the input
  7831. // buffer or a temporary accumulate buffer.
  7832. static const char *accumulate_getptr(upb_json_parser *p, size_t *len) {
  7833. assert(p->accumulated);
  7834. *len = p->accumulated_len;
  7835. return p->accumulated;
  7836. }
  7837. /* Mult-part text data ********************************************************/
  7838. // When we have text data in the input, it can often come in multiple segments.
  7839. // For example, there may be some raw string data followed by an escape
  7840. // sequence. The two segments are processed with different logic. Also buffer
  7841. // seams in the input can cause multiple segments.
  7842. //
  7843. // As we see segments, there are two main cases for how we want to process them:
  7844. //
  7845. // 1. we want to push the captured input directly to string handlers.
  7846. //
  7847. // 2. we need to accumulate all the parts into a contiguous buffer for further
  7848. // processing (field name lookup, string->number conversion, etc).
  7849. // This is the set of states for p->multipart_state.
  7850. enum {
  7851. // We are not currently processing multipart data.
  7852. MULTIPART_INACTIVE = 0,
  7853. // We are processing multipart data by accumulating it into a contiguous
  7854. // buffer.
  7855. MULTIPART_ACCUMULATE = 1,
  7856. // We are processing multipart data by pushing each part directly to the
  7857. // current string handlers.
  7858. MULTIPART_PUSHEAGERLY = 2
  7859. };
  7860. // Start a multi-part text value where we accumulate the data for processing at
  7861. // the end.
  7862. static void multipart_startaccum(upb_json_parser *p) {
  7863. assert_accumulate_empty(p);
  7864. assert(p->multipart_state == MULTIPART_INACTIVE);
  7865. p->multipart_state = MULTIPART_ACCUMULATE;
  7866. }
  7867. // Start a multi-part text value where we immediately push text data to a string
  7868. // value with the given selector.
  7869. static void multipart_start(upb_json_parser *p, upb_selector_t sel) {
  7870. assert_accumulate_empty(p);
  7871. assert(p->multipart_state == MULTIPART_INACTIVE);
  7872. p->multipart_state = MULTIPART_PUSHEAGERLY;
  7873. p->string_selector = sel;
  7874. }
  7875. static bool multipart_text(upb_json_parser *p, const char *buf, size_t len,
  7876. bool can_alias) {
  7877. switch (p->multipart_state) {
  7878. case MULTIPART_INACTIVE:
  7879. upb_status_seterrmsg(
  7880. p->status, "Internal error: unexpected state MULTIPART_INACTIVE");
  7881. return false;
  7882. case MULTIPART_ACCUMULATE:
  7883. if (!accumulate_append(p, buf, len, can_alias)) {
  7884. return false;
  7885. }
  7886. break;
  7887. case MULTIPART_PUSHEAGERLY: {
  7888. const upb_bufhandle *handle = can_alias ? p->handle : NULL;
  7889. upb_sink_putstring(&p->top->sink, p->string_selector, buf, len, handle);
  7890. break;
  7891. }
  7892. }
  7893. return true;
  7894. }
  7895. // Note: this invalidates the accumulate buffer! Call only after reading its
  7896. // contents.
  7897. static void multipart_end(upb_json_parser *p) {
  7898. assert(p->multipart_state != MULTIPART_INACTIVE);
  7899. p->multipart_state = MULTIPART_INACTIVE;
  7900. accumulate_clear(p);
  7901. }
  7902. /* Input capture **************************************************************/
  7903. // Functionality for capturing a region of the input as text. Gracefully
  7904. // handles the case where a buffer seam occurs in the middle of the captured
  7905. // region.
  7906. static void capture_begin(upb_json_parser *p, const char *ptr) {
  7907. assert(p->multipart_state != MULTIPART_INACTIVE);
  7908. assert(p->capture == NULL);
  7909. p->capture = ptr;
  7910. }
  7911. static bool capture_end(upb_json_parser *p, const char *ptr) {
  7912. assert(p->capture);
  7913. if (multipart_text(p, p->capture, ptr - p->capture, true)) {
  7914. p->capture = NULL;
  7915. return true;
  7916. } else {
  7917. return false;
  7918. }
  7919. }
  7920. // This is called at the end of each input buffer (ie. when we have hit a
  7921. // buffer seam). If we are in the middle of capturing the input, this
  7922. // processes the unprocessed capture region.
  7923. static void capture_suspend(upb_json_parser *p, const char **ptr) {
  7924. if (!p->capture) return;
  7925. if (multipart_text(p, p->capture, *ptr - p->capture, false)) {
  7926. // We use this as a signal that we were in the middle of capturing, and
  7927. // that capturing should resume at the beginning of the next buffer.
  7928. //
  7929. // We can't use *ptr here, because we have no guarantee that this pointer
  7930. // will be valid when we resume (if the underlying memory is freed, then
  7931. // using the pointer at all, even to compare to NULL, is likely undefined
  7932. // behavior).
  7933. p->capture = &suspend_capture;
  7934. } else {
  7935. // Need to back up the pointer to the beginning of the capture, since
  7936. // we were not able to actually preserve it.
  7937. *ptr = p->capture;
  7938. }
  7939. }
  7940. static void capture_resume(upb_json_parser *p, const char *ptr) {
  7941. if (p->capture) {
  7942. assert(p->capture == &suspend_capture);
  7943. p->capture = ptr;
  7944. }
  7945. }
  7946. /* Callbacks from the parser **************************************************/
  7947. // These are the functions called directly from the parser itself.
  7948. // We define these in the same order as their declarations in the parser.
  7949. static char escape_char(char in) {
  7950. switch (in) {
  7951. case 'r': return '\r';
  7952. case 't': return '\t';
  7953. case 'n': return '\n';
  7954. case 'f': return '\f';
  7955. case 'b': return '\b';
  7956. case '/': return '/';
  7957. case '"': return '"';
  7958. case '\\': return '\\';
  7959. default:
  7960. assert(0);
  7961. return 'x';
  7962. }
  7963. }
  7964. static bool escape(upb_json_parser *p, const char *ptr) {
  7965. char ch = escape_char(*ptr);
  7966. return multipart_text(p, &ch, 1, false);
  7967. }
  7968. static void start_hex(upb_json_parser *p) {
  7969. p->digit = 0;
  7970. }
  7971. static void hexdigit(upb_json_parser *p, const char *ptr) {
  7972. char ch = *ptr;
  7973. p->digit <<= 4;
  7974. if (ch >= '0' && ch <= '9') {
  7975. p->digit += (ch - '0');
  7976. } else if (ch >= 'a' && ch <= 'f') {
  7977. p->digit += ((ch - 'a') + 10);
  7978. } else {
  7979. assert(ch >= 'A' && ch <= 'F');
  7980. p->digit += ((ch - 'A') + 10);
  7981. }
  7982. }
  7983. static bool end_hex(upb_json_parser *p) {
  7984. uint32_t codepoint = p->digit;
  7985. // emit the codepoint as UTF-8.
  7986. char utf8[3]; // support \u0000 -- \uFFFF -- need only three bytes.
  7987. int length = 0;
  7988. if (codepoint <= 0x7F) {
  7989. utf8[0] = codepoint;
  7990. length = 1;
  7991. } else if (codepoint <= 0x07FF) {
  7992. utf8[1] = (codepoint & 0x3F) | 0x80;
  7993. codepoint >>= 6;
  7994. utf8[0] = (codepoint & 0x1F) | 0xC0;
  7995. length = 2;
  7996. } else /* codepoint <= 0xFFFF */ {
  7997. utf8[2] = (codepoint & 0x3F) | 0x80;
  7998. codepoint >>= 6;
  7999. utf8[1] = (codepoint & 0x3F) | 0x80;
  8000. codepoint >>= 6;
  8001. utf8[0] = (codepoint & 0x0F) | 0xE0;
  8002. length = 3;
  8003. }
  8004. // TODO(haberman): Handle high surrogates: if codepoint is a high surrogate
  8005. // we have to wait for the next escape to get the full code point).
  8006. return multipart_text(p, utf8, length, false);
  8007. }
  8008. static void start_text(upb_json_parser *p, const char *ptr) {
  8009. capture_begin(p, ptr);
  8010. }
  8011. static bool end_text(upb_json_parser *p, const char *ptr) {
  8012. return capture_end(p, ptr);
  8013. }
  8014. static void start_number(upb_json_parser *p, const char *ptr) {
  8015. multipart_startaccum(p);
  8016. capture_begin(p, ptr);
  8017. }
  8018. static bool end_number(upb_json_parser *p, const char *ptr) {
  8019. if (!capture_end(p, ptr)) {
  8020. return false;
  8021. }
  8022. // strtol() and friends unfortunately do not support specifying the length of
  8023. // the input string, so we need to force a copy into a NULL-terminated buffer.
  8024. if (!multipart_text(p, "\0", 1, false)) {
  8025. return false;
  8026. }
  8027. size_t len;
  8028. const char *buf = accumulate_getptr(p, &len);
  8029. const char *myend = buf + len - 1; // One for NULL.
  8030. char *end;
  8031. switch (upb_fielddef_type(p->top->f)) {
  8032. case UPB_TYPE_ENUM:
  8033. case UPB_TYPE_INT32: {
  8034. long val = strtol(p->accumulated, &end, 0);
  8035. if (val > INT32_MAX || val < INT32_MIN || errno == ERANGE || end != myend)
  8036. goto err;
  8037. else
  8038. upb_sink_putint32(&p->top->sink, parser_getsel(p), val);
  8039. break;
  8040. }
  8041. case UPB_TYPE_INT64: {
  8042. long long val = strtoll(p->accumulated, &end, 0);
  8043. if (val > INT64_MAX || val < INT64_MIN || errno == ERANGE || end != myend)
  8044. goto err;
  8045. else
  8046. upb_sink_putint64(&p->top->sink, parser_getsel(p), val);
  8047. break;
  8048. }
  8049. case UPB_TYPE_UINT32: {
  8050. unsigned long val = strtoul(p->accumulated, &end, 0);
  8051. if (val > UINT32_MAX || errno == ERANGE || end != myend)
  8052. goto err;
  8053. else
  8054. upb_sink_putuint32(&p->top->sink, parser_getsel(p), val);
  8055. break;
  8056. }
  8057. case UPB_TYPE_UINT64: {
  8058. unsigned long long val = strtoull(p->accumulated, &end, 0);
  8059. if (val > UINT64_MAX || errno == ERANGE || end != myend)
  8060. goto err;
  8061. else
  8062. upb_sink_putuint64(&p->top->sink, parser_getsel(p), val);
  8063. break;
  8064. }
  8065. case UPB_TYPE_DOUBLE: {
  8066. double val = strtod(p->accumulated, &end);
  8067. if (errno == ERANGE || end != myend)
  8068. goto err;
  8069. else
  8070. upb_sink_putdouble(&p->top->sink, parser_getsel(p), val);
  8071. break;
  8072. }
  8073. case UPB_TYPE_FLOAT: {
  8074. float val = strtof(p->accumulated, &end);
  8075. if (errno == ERANGE || end != myend)
  8076. goto err;
  8077. else
  8078. upb_sink_putfloat(&p->top->sink, parser_getsel(p), val);
  8079. break;
  8080. }
  8081. default:
  8082. assert(false);
  8083. }
  8084. multipart_end(p);
  8085. return true;
  8086. err:
  8087. upb_status_seterrf(p->status, "error parsing number: %s", buf);
  8088. multipart_end(p);
  8089. return false;
  8090. }
  8091. static bool parser_putbool(upb_json_parser *p, bool val) {
  8092. if (upb_fielddef_type(p->top->f) != UPB_TYPE_BOOL) {
  8093. upb_status_seterrf(p->status,
  8094. "Boolean value specified for non-bool field: %s",
  8095. upb_fielddef_name(p->top->f));
  8096. return false;
  8097. }
  8098. bool ok = upb_sink_putbool(&p->top->sink, parser_getsel(p), val);
  8099. UPB_ASSERT_VAR(ok, ok);
  8100. return true;
  8101. }
  8102. static bool start_stringval(upb_json_parser *p) {
  8103. assert(p->top->f);
  8104. if (upb_fielddef_isstring(p->top->f)) {
  8105. if (!check_stack(p)) return false;
  8106. // Start a new parser frame: parser frames correspond one-to-one with
  8107. // handler frames, and string events occur in a sub-frame.
  8108. upb_jsonparser_frame *inner = p->top + 1;
  8109. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  8110. upb_sink_startstr(&p->top->sink, sel, 0, &inner->sink);
  8111. inner->m = p->top->m;
  8112. inner->f = p->top->f;
  8113. p->top = inner;
  8114. if (upb_fielddef_type(p->top->f) == UPB_TYPE_STRING) {
  8115. // For STRING fields we push data directly to the handlers as it is
  8116. // parsed. We don't do this yet for BYTES fields, because our base64
  8117. // decoder is not streaming.
  8118. //
  8119. // TODO(haberman): make base64 decoding streaming also.
  8120. multipart_start(p, getsel_for_handlertype(p, UPB_HANDLER_STRING));
  8121. return true;
  8122. } else {
  8123. multipart_startaccum(p);
  8124. return true;
  8125. }
  8126. } else if (upb_fielddef_type(p->top->f) == UPB_TYPE_ENUM) {
  8127. // No need to push a frame -- symbolic enum names in quotes remain in the
  8128. // current parser frame.
  8129. //
  8130. // Enum string values must accumulate so we can look up the value in a table
  8131. // once it is complete.
  8132. multipart_startaccum(p);
  8133. return true;
  8134. } else {
  8135. upb_status_seterrf(p->status,
  8136. "String specified for non-string/non-enum field: %s",
  8137. upb_fielddef_name(p->top->f));
  8138. return false;
  8139. }
  8140. }
  8141. static bool end_stringval(upb_json_parser *p) {
  8142. bool ok = true;
  8143. switch (upb_fielddef_type(p->top->f)) {
  8144. case UPB_TYPE_BYTES:
  8145. if (!base64_push(p, getsel_for_handlertype(p, UPB_HANDLER_STRING),
  8146. p->accumulated, p->accumulated_len)) {
  8147. return false;
  8148. }
  8149. // Fall through.
  8150. case UPB_TYPE_STRING: {
  8151. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  8152. upb_sink_endstr(&p->top->sink, sel);
  8153. p->top--;
  8154. break;
  8155. }
  8156. case UPB_TYPE_ENUM: {
  8157. // Resolve enum symbolic name to integer value.
  8158. const upb_enumdef *enumdef =
  8159. (const upb_enumdef*)upb_fielddef_subdef(p->top->f);
  8160. size_t len;
  8161. const char *buf = accumulate_getptr(p, &len);
  8162. int32_t int_val = 0;
  8163. ok = upb_enumdef_ntoi(enumdef, buf, len, &int_val);
  8164. if (ok) {
  8165. upb_selector_t sel = parser_getsel(p);
  8166. upb_sink_putint32(&p->top->sink, sel, int_val);
  8167. } else {
  8168. upb_status_seterrf(p->status, "Enum value unknown: '%.*s'", len, buf);
  8169. }
  8170. break;
  8171. }
  8172. default:
  8173. assert(false);
  8174. upb_status_seterrmsg(p->status, "Internal error in JSON decoder");
  8175. ok = false;
  8176. break;
  8177. }
  8178. multipart_end(p);
  8179. return ok;
  8180. }
  8181. static void start_member(upb_json_parser *p) {
  8182. assert(!p->top->f);
  8183. multipart_startaccum(p);
  8184. }
  8185. static bool end_member(upb_json_parser *p) {
  8186. assert(!p->top->f);
  8187. size_t len;
  8188. const char *buf = accumulate_getptr(p, &len);
  8189. const upb_fielddef *f = upb_msgdef_ntof(p->top->m, buf, len);
  8190. if (!f) {
  8191. // TODO(haberman): Ignore unknown fields if requested/configured to do so.
  8192. upb_status_seterrf(p->status, "No such field: %.*s\n", (int)len, buf);
  8193. return false;
  8194. }
  8195. p->top->f = f;
  8196. multipart_end(p);
  8197. return true;
  8198. }
  8199. static void clear_member(upb_json_parser *p) { p->top->f = NULL; }
  8200. static bool start_subobject(upb_json_parser *p) {
  8201. assert(p->top->f);
  8202. if (!upb_fielddef_issubmsg(p->top->f)) {
  8203. upb_status_seterrf(p->status,
  8204. "Object specified for non-message/group field: %s",
  8205. upb_fielddef_name(p->top->f));
  8206. return false;
  8207. }
  8208. if (!check_stack(p)) return false;
  8209. upb_jsonparser_frame *inner = p->top + 1;
  8210. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
  8211. upb_sink_startsubmsg(&p->top->sink, sel, &inner->sink);
  8212. inner->m = upb_fielddef_msgsubdef(p->top->f);
  8213. inner->f = NULL;
  8214. p->top = inner;
  8215. return true;
  8216. }
  8217. static void end_subobject(upb_json_parser *p) {
  8218. p->top--;
  8219. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSUBMSG);
  8220. upb_sink_endsubmsg(&p->top->sink, sel);
  8221. }
  8222. static bool start_array(upb_json_parser *p) {
  8223. assert(p->top->f);
  8224. if (!upb_fielddef_isseq(p->top->f)) {
  8225. upb_status_seterrf(p->status,
  8226. "Array specified for non-repeated field: %s",
  8227. upb_fielddef_name(p->top->f));
  8228. return false;
  8229. }
  8230. if (!check_stack(p)) return false;
  8231. upb_jsonparser_frame *inner = p->top + 1;
  8232. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
  8233. upb_sink_startseq(&p->top->sink, sel, &inner->sink);
  8234. inner->m = p->top->m;
  8235. inner->f = p->top->f;
  8236. p->top = inner;
  8237. return true;
  8238. }
  8239. static void end_array(upb_json_parser *p) {
  8240. assert(p->top > p->stack);
  8241. p->top--;
  8242. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
  8243. upb_sink_endseq(&p->top->sink, sel);
  8244. }
  8245. static void start_object(upb_json_parser *p) {
  8246. upb_sink_startmsg(&p->top->sink);
  8247. }
  8248. static void end_object(upb_json_parser *p) {
  8249. upb_status status;
  8250. upb_sink_endmsg(&p->top->sink, &status);
  8251. }
  8252. #define CHECK_RETURN_TOP(x) if (!(x)) goto error
  8253. /* The actual parser **********************************************************/
  8254. // What follows is the Ragel parser itself. The language is specified in Ragel
  8255. // and the actions call our C functions above.
  8256. //
  8257. // Ragel has an extensive set of functionality, and we use only a small part of
  8258. // it. There are many action types but we only use a few:
  8259. //
  8260. // ">" -- transition into a machine
  8261. // "%" -- transition out of a machine
  8262. // "@" -- transition into a final state of a machine.
  8263. //
  8264. // "@" transitions are tricky because a machine can transition into a final
  8265. // state repeatedly. But in some cases we know this can't happen, for example
  8266. // a string which is delimited by a final '"' can only transition into its
  8267. // final state once, when the closing '"' is seen.
  8268. #line 904 "upb/json/parser.rl"
  8269. #line 816 "upb/json/parser.c"
  8270. static const char _json_actions[] = {
  8271. 0, 1, 0, 1, 2, 1, 3, 1,
  8272. 5, 1, 6, 1, 7, 1, 8, 1,
  8273. 10, 1, 12, 1, 13, 1, 14, 1,
  8274. 15, 1, 16, 1, 17, 1, 21, 1,
  8275. 25, 1, 27, 2, 3, 8, 2, 4,
  8276. 5, 2, 6, 2, 2, 6, 8, 2,
  8277. 11, 9, 2, 13, 15, 2, 14, 15,
  8278. 2, 18, 1, 2, 19, 27, 2, 20,
  8279. 9, 2, 22, 27, 2, 23, 27, 2,
  8280. 24, 27, 2, 26, 27, 3, 14, 11,
  8281. 9
  8282. };
  8283. static const unsigned char _json_key_offsets[] = {
  8284. 0, 0, 4, 9, 14, 15, 19, 24,
  8285. 29, 34, 38, 42, 45, 48, 50, 54,
  8286. 58, 60, 62, 67, 69, 71, 80, 86,
  8287. 92, 98, 104, 106, 115, 116, 116, 116,
  8288. 121, 126, 131, 132, 133, 134, 135, 135,
  8289. 136, 137, 138, 138, 139, 140, 141, 141,
  8290. 146, 151, 152, 156, 161, 166, 171, 175,
  8291. 175, 178, 178, 178
  8292. };
  8293. static const char _json_trans_keys[] = {
  8294. 32, 123, 9, 13, 32, 34, 125, 9,
  8295. 13, 32, 34, 125, 9, 13, 34, 32,
  8296. 58, 9, 13, 32, 93, 125, 9, 13,
  8297. 32, 44, 125, 9, 13, 32, 44, 125,
  8298. 9, 13, 32, 34, 9, 13, 45, 48,
  8299. 49, 57, 48, 49, 57, 46, 69, 101,
  8300. 48, 57, 69, 101, 48, 57, 43, 45,
  8301. 48, 57, 48, 57, 48, 57, 46, 69,
  8302. 101, 48, 57, 34, 92, 34, 92, 34,
  8303. 47, 92, 98, 102, 110, 114, 116, 117,
  8304. 48, 57, 65, 70, 97, 102, 48, 57,
  8305. 65, 70, 97, 102, 48, 57, 65, 70,
  8306. 97, 102, 48, 57, 65, 70, 97, 102,
  8307. 34, 92, 34, 45, 91, 102, 110, 116,
  8308. 123, 48, 57, 34, 32, 93, 125, 9,
  8309. 13, 32, 44, 93, 9, 13, 32, 93,
  8310. 125, 9, 13, 97, 108, 115, 101, 117,
  8311. 108, 108, 114, 117, 101, 32, 34, 125,
  8312. 9, 13, 32, 34, 125, 9, 13, 34,
  8313. 32, 58, 9, 13, 32, 93, 125, 9,
  8314. 13, 32, 44, 125, 9, 13, 32, 44,
  8315. 125, 9, 13, 32, 34, 9, 13, 32,
  8316. 9, 13, 0
  8317. };
  8318. static const char _json_single_lengths[] = {
  8319. 0, 2, 3, 3, 1, 2, 3, 3,
  8320. 3, 2, 2, 1, 3, 0, 2, 2,
  8321. 0, 0, 3, 2, 2, 9, 0, 0,
  8322. 0, 0, 2, 7, 1, 0, 0, 3,
  8323. 3, 3, 1, 1, 1, 1, 0, 1,
  8324. 1, 1, 0, 1, 1, 1, 0, 3,
  8325. 3, 1, 2, 3, 3, 3, 2, 0,
  8326. 1, 0, 0, 0
  8327. };
  8328. static const char _json_range_lengths[] = {
  8329. 0, 1, 1, 1, 0, 1, 1, 1,
  8330. 1, 1, 1, 1, 0, 1, 1, 1,
  8331. 1, 1, 1, 0, 0, 0, 3, 3,
  8332. 3, 3, 0, 1, 0, 0, 0, 1,
  8333. 1, 1, 0, 0, 0, 0, 0, 0,
  8334. 0, 0, 0, 0, 0, 0, 0, 1,
  8335. 1, 0, 1, 1, 1, 1, 1, 0,
  8336. 1, 0, 0, 0
  8337. };
  8338. static const short _json_index_offsets[] = {
  8339. 0, 0, 4, 9, 14, 16, 20, 25,
  8340. 30, 35, 39, 43, 46, 50, 52, 56,
  8341. 60, 62, 64, 69, 72, 75, 85, 89,
  8342. 93, 97, 101, 104, 113, 115, 116, 117,
  8343. 122, 127, 132, 134, 136, 138, 140, 141,
  8344. 143, 145, 147, 148, 150, 152, 154, 155,
  8345. 160, 165, 167, 171, 176, 181, 186, 190,
  8346. 191, 194, 195, 196
  8347. };
  8348. static const char _json_indicies[] = {
  8349. 0, 2, 0, 1, 3, 4, 5, 3,
  8350. 1, 6, 7, 8, 6, 1, 9, 1,
  8351. 10, 11, 10, 1, 11, 1, 1, 11,
  8352. 12, 13, 14, 15, 13, 1, 16, 17,
  8353. 8, 16, 1, 17, 7, 17, 1, 18,
  8354. 19, 20, 1, 19, 20, 1, 22, 23,
  8355. 23, 21, 24, 1, 23, 23, 24, 21,
  8356. 25, 25, 26, 1, 26, 1, 26, 21,
  8357. 22, 23, 23, 20, 21, 28, 29, 27,
  8358. 31, 32, 30, 33, 33, 33, 33, 33,
  8359. 33, 33, 33, 34, 1, 35, 35, 35,
  8360. 1, 36, 36, 36, 1, 37, 37, 37,
  8361. 1, 38, 38, 38, 1, 40, 41, 39,
  8362. 42, 43, 44, 45, 46, 47, 48, 43,
  8363. 1, 49, 1, 50, 51, 53, 54, 1,
  8364. 53, 52, 55, 56, 54, 55, 1, 56,
  8365. 1, 1, 56, 52, 57, 1, 58, 1,
  8366. 59, 1, 60, 1, 61, 62, 1, 63,
  8367. 1, 64, 1, 65, 66, 1, 67, 1,
  8368. 68, 1, 69, 70, 71, 72, 70, 1,
  8369. 73, 74, 75, 73, 1, 76, 1, 77,
  8370. 78, 77, 1, 78, 1, 1, 78, 79,
  8371. 80, 81, 82, 80, 1, 83, 84, 75,
  8372. 83, 1, 84, 74, 84, 1, 85, 86,
  8373. 86, 1, 1, 1, 1, 0
  8374. };
  8375. static const char _json_trans_targs[] = {
  8376. 1, 0, 2, 3, 4, 56, 3, 4,
  8377. 56, 5, 5, 6, 7, 8, 9, 56,
  8378. 8, 9, 11, 12, 18, 57, 13, 15,
  8379. 14, 16, 17, 20, 58, 21, 20, 58,
  8380. 21, 19, 22, 23, 24, 25, 26, 20,
  8381. 58, 21, 28, 30, 31, 34, 39, 43,
  8382. 47, 29, 59, 59, 32, 31, 29, 32,
  8383. 33, 35, 36, 37, 38, 59, 40, 41,
  8384. 42, 59, 44, 45, 46, 59, 48, 49,
  8385. 55, 48, 49, 55, 50, 50, 51, 52,
  8386. 53, 54, 55, 53, 54, 59, 56
  8387. };
  8388. static const char _json_trans_actions[] = {
  8389. 0, 0, 0, 21, 77, 53, 0, 47,
  8390. 23, 17, 0, 0, 15, 19, 19, 50,
  8391. 0, 0, 0, 0, 0, 1, 0, 0,
  8392. 0, 0, 0, 3, 13, 0, 0, 35,
  8393. 5, 11, 0, 38, 7, 7, 7, 41,
  8394. 44, 9, 62, 56, 25, 0, 0, 0,
  8395. 31, 29, 33, 59, 15, 0, 27, 0,
  8396. 0, 0, 0, 0, 0, 68, 0, 0,
  8397. 0, 71, 0, 0, 0, 65, 21, 77,
  8398. 53, 0, 47, 23, 17, 0, 0, 15,
  8399. 19, 19, 50, 0, 0, 74, 0
  8400. };
  8401. static const int json_start = 1;
  8402. static const int json_first_final = 56;
  8403. static const int json_error = 0;
  8404. static const int json_en_number_machine = 10;
  8405. static const int json_en_string_machine = 19;
  8406. static const int json_en_value_machine = 27;
  8407. static const int json_en_main = 1;
  8408. #line 907 "upb/json/parser.rl"
  8409. size_t parse(void *closure, const void *hd, const char *buf, size_t size,
  8410. const upb_bufhandle *handle) {
  8411. UPB_UNUSED(hd);
  8412. UPB_UNUSED(handle);
  8413. upb_json_parser *parser = closure;
  8414. parser->handle = handle;
  8415. // Variables used by Ragel's generated code.
  8416. int cs = parser->current_state;
  8417. int *stack = parser->parser_stack;
  8418. int top = parser->parser_top;
  8419. const char *p = buf;
  8420. const char *pe = buf + size;
  8421. capture_resume(parser, buf);
  8422. #line 987 "upb/json/parser.c"
  8423. {
  8424. int _klen;
  8425. unsigned int _trans;
  8426. const char *_acts;
  8427. unsigned int _nacts;
  8428. const char *_keys;
  8429. if ( p == pe )
  8430. goto _test_eof;
  8431. if ( cs == 0 )
  8432. goto _out;
  8433. _resume:
  8434. _keys = _json_trans_keys + _json_key_offsets[cs];
  8435. _trans = _json_index_offsets[cs];
  8436. _klen = _json_single_lengths[cs];
  8437. if ( _klen > 0 ) {
  8438. const char *_lower = _keys;
  8439. const char *_mid;
  8440. const char *_upper = _keys + _klen - 1;
  8441. while (1) {
  8442. if ( _upper < _lower )
  8443. break;
  8444. _mid = _lower + ((_upper-_lower) >> 1);
  8445. if ( (*p) < *_mid )
  8446. _upper = _mid - 1;
  8447. else if ( (*p) > *_mid )
  8448. _lower = _mid + 1;
  8449. else {
  8450. _trans += (unsigned int)(_mid - _keys);
  8451. goto _match;
  8452. }
  8453. }
  8454. _keys += _klen;
  8455. _trans += _klen;
  8456. }
  8457. _klen = _json_range_lengths[cs];
  8458. if ( _klen > 0 ) {
  8459. const char *_lower = _keys;
  8460. const char *_mid;
  8461. const char *_upper = _keys + (_klen<<1) - 2;
  8462. while (1) {
  8463. if ( _upper < _lower )
  8464. break;
  8465. _mid = _lower + (((_upper-_lower) >> 1) & ~1);
  8466. if ( (*p) < _mid[0] )
  8467. _upper = _mid - 2;
  8468. else if ( (*p) > _mid[1] )
  8469. _lower = _mid + 2;
  8470. else {
  8471. _trans += (unsigned int)((_mid - _keys)>>1);
  8472. goto _match;
  8473. }
  8474. }
  8475. _trans += _klen;
  8476. }
  8477. _match:
  8478. _trans = _json_indicies[_trans];
  8479. cs = _json_trans_targs[_trans];
  8480. if ( _json_trans_actions[_trans] == 0 )
  8481. goto _again;
  8482. _acts = _json_actions + _json_trans_actions[_trans];
  8483. _nacts = (unsigned int) *_acts++;
  8484. while ( _nacts-- > 0 )
  8485. {
  8486. switch ( *_acts++ )
  8487. {
  8488. case 0:
  8489. #line 819 "upb/json/parser.rl"
  8490. { p--; {cs = stack[--top]; goto _again;} }
  8491. break;
  8492. case 1:
  8493. #line 820 "upb/json/parser.rl"
  8494. { p--; {stack[top++] = cs; cs = 10; goto _again;} }
  8495. break;
  8496. case 2:
  8497. #line 824 "upb/json/parser.rl"
  8498. { start_text(parser, p); }
  8499. break;
  8500. case 3:
  8501. #line 825 "upb/json/parser.rl"
  8502. { CHECK_RETURN_TOP(end_text(parser, p)); }
  8503. break;
  8504. case 4:
  8505. #line 831 "upb/json/parser.rl"
  8506. { start_hex(parser); }
  8507. break;
  8508. case 5:
  8509. #line 832 "upb/json/parser.rl"
  8510. { hexdigit(parser, p); }
  8511. break;
  8512. case 6:
  8513. #line 833 "upb/json/parser.rl"
  8514. { CHECK_RETURN_TOP(end_hex(parser)); }
  8515. break;
  8516. case 7:
  8517. #line 839 "upb/json/parser.rl"
  8518. { CHECK_RETURN_TOP(escape(parser, p)); }
  8519. break;
  8520. case 8:
  8521. #line 845 "upb/json/parser.rl"
  8522. { p--; {cs = stack[--top]; goto _again;} }
  8523. break;
  8524. case 9:
  8525. #line 848 "upb/json/parser.rl"
  8526. { {stack[top++] = cs; cs = 19; goto _again;} }
  8527. break;
  8528. case 10:
  8529. #line 850 "upb/json/parser.rl"
  8530. { p--; {stack[top++] = cs; cs = 27; goto _again;} }
  8531. break;
  8532. case 11:
  8533. #line 855 "upb/json/parser.rl"
  8534. { start_member(parser); }
  8535. break;
  8536. case 12:
  8537. #line 856 "upb/json/parser.rl"
  8538. { CHECK_RETURN_TOP(end_member(parser)); }
  8539. break;
  8540. case 13:
  8541. #line 859 "upb/json/parser.rl"
  8542. { clear_member(parser); }
  8543. break;
  8544. case 14:
  8545. #line 865 "upb/json/parser.rl"
  8546. { start_object(parser); }
  8547. break;
  8548. case 15:
  8549. #line 868 "upb/json/parser.rl"
  8550. { end_object(parser); }
  8551. break;
  8552. case 16:
  8553. #line 874 "upb/json/parser.rl"
  8554. { CHECK_RETURN_TOP(start_array(parser)); }
  8555. break;
  8556. case 17:
  8557. #line 878 "upb/json/parser.rl"
  8558. { end_array(parser); }
  8559. break;
  8560. case 18:
  8561. #line 883 "upb/json/parser.rl"
  8562. { start_number(parser, p); }
  8563. break;
  8564. case 19:
  8565. #line 884 "upb/json/parser.rl"
  8566. { CHECK_RETURN_TOP(end_number(parser, p)); }
  8567. break;
  8568. case 20:
  8569. #line 886 "upb/json/parser.rl"
  8570. { CHECK_RETURN_TOP(start_stringval(parser)); }
  8571. break;
  8572. case 21:
  8573. #line 887 "upb/json/parser.rl"
  8574. { CHECK_RETURN_TOP(end_stringval(parser)); }
  8575. break;
  8576. case 22:
  8577. #line 889 "upb/json/parser.rl"
  8578. { CHECK_RETURN_TOP(parser_putbool(parser, true)); }
  8579. break;
  8580. case 23:
  8581. #line 891 "upb/json/parser.rl"
  8582. { CHECK_RETURN_TOP(parser_putbool(parser, false)); }
  8583. break;
  8584. case 24:
  8585. #line 893 "upb/json/parser.rl"
  8586. { /* null value */ }
  8587. break;
  8588. case 25:
  8589. #line 895 "upb/json/parser.rl"
  8590. { CHECK_RETURN_TOP(start_subobject(parser)); }
  8591. break;
  8592. case 26:
  8593. #line 896 "upb/json/parser.rl"
  8594. { end_subobject(parser); }
  8595. break;
  8596. case 27:
  8597. #line 901 "upb/json/parser.rl"
  8598. { p--; {cs = stack[--top]; goto _again;} }
  8599. break;
  8600. #line 1173 "upb/json/parser.c"
  8601. }
  8602. }
  8603. _again:
  8604. if ( cs == 0 )
  8605. goto _out;
  8606. if ( ++p != pe )
  8607. goto _resume;
  8608. _test_eof: {}
  8609. _out: {}
  8610. }
  8611. #line 926 "upb/json/parser.rl"
  8612. if (p != pe) {
  8613. upb_status_seterrf(parser->status, "Parse error at %s\n", p);
  8614. } else {
  8615. capture_suspend(parser, &p);
  8616. }
  8617. error:
  8618. // Save parsing state back to parser.
  8619. parser->current_state = cs;
  8620. parser->parser_top = top;
  8621. return p - buf;
  8622. }
  8623. bool end(void *closure, const void *hd) {
  8624. UPB_UNUSED(closure);
  8625. UPB_UNUSED(hd);
  8626. return true;
  8627. }
  8628. /* Public API *****************************************************************/
  8629. void upb_json_parser_init(upb_json_parser *p, upb_status *status) {
  8630. p->limit = p->stack + UPB_JSON_MAX_DEPTH;
  8631. p->accumulate_buf = NULL;
  8632. p->accumulate_buf_size = 0;
  8633. upb_byteshandler_init(&p->input_handler_);
  8634. upb_byteshandler_setstring(&p->input_handler_, parse, NULL);
  8635. upb_byteshandler_setendstr(&p->input_handler_, end, NULL);
  8636. upb_bytessink_reset(&p->input_, &p->input_handler_, p);
  8637. p->status = status;
  8638. }
  8639. void upb_json_parser_uninit(upb_json_parser *p) {
  8640. upb_byteshandler_uninit(&p->input_handler_);
  8641. free(p->accumulate_buf);
  8642. }
  8643. void upb_json_parser_reset(upb_json_parser *p) {
  8644. p->top = p->stack;
  8645. p->top->f = NULL;
  8646. int cs;
  8647. int top;
  8648. // Emit Ragel initialization of the parser.
  8649. #line 1235 "upb/json/parser.c"
  8650. {
  8651. cs = json_start;
  8652. top = 0;
  8653. }
  8654. #line 974 "upb/json/parser.rl"
  8655. p->current_state = cs;
  8656. p->parser_top = top;
  8657. accumulate_clear(p);
  8658. p->multipart_state = MULTIPART_INACTIVE;
  8659. p->capture = NULL;
  8660. }
  8661. void upb_json_parser_resetoutput(upb_json_parser *p, upb_sink *sink) {
  8662. upb_json_parser_reset(p);
  8663. upb_sink_reset(&p->top->sink, sink->handlers, sink->closure);
  8664. p->top->m = upb_handlers_msgdef(sink->handlers);
  8665. p->accumulated = NULL;
  8666. }
  8667. upb_bytessink *upb_json_parser_input(upb_json_parser *p) {
  8668. return &p->input_;
  8669. }
  8670. /*
  8671. * upb - a minimalist implementation of protocol buffers.
  8672. *
  8673. * Copyright (c) 2014 Google Inc. See LICENSE for details.
  8674. * Author: Josh Haberman <jhaberman@gmail.com>
  8675. *
  8676. * This currently uses snprintf() to format primitives, and could be optimized
  8677. * further.
  8678. */
  8679. #include <stdlib.h>
  8680. #include <stdio.h>
  8681. #include <string.h>
  8682. #include <stdint.h>
  8683. // StringPiece; a pointer plus a length.
  8684. typedef struct {
  8685. const char *ptr;
  8686. size_t len;
  8687. } strpc;
  8688. strpc *newstrpc(upb_handlers *h, const upb_fielddef *f) {
  8689. strpc *ret = malloc(sizeof(*ret));
  8690. ret->ptr = upb_fielddef_name(f);
  8691. ret->len = strlen(ret->ptr);
  8692. upb_handlers_addcleanup(h, ret, free);
  8693. return ret;
  8694. }
  8695. // ------------ JSON string printing: values, maps, arrays --------------------
  8696. static void print_data(
  8697. upb_json_printer *p, const char *buf, unsigned int len) {
  8698. // TODO: Will need to change if we support pushback from the sink.
  8699. size_t n = upb_bytessink_putbuf(p->output_, p->subc_, buf, len, NULL);
  8700. UPB_ASSERT_VAR(n, n == len);
  8701. }
  8702. static void print_comma(upb_json_printer *p) {
  8703. if (!p->first_elem_[p->depth_]) {
  8704. print_data(p, ",", 1);
  8705. }
  8706. p->first_elem_[p->depth_] = false;
  8707. }
  8708. // Helpers that print properly formatted elements to the JSON output stream.
  8709. // Used for escaping control chars in strings.
  8710. static const char kControlCharLimit = 0x20;
  8711. static inline bool is_json_escaped(char c) {
  8712. // See RFC 4627.
  8713. unsigned char uc = (unsigned char)c;
  8714. return uc < kControlCharLimit || uc == '"' || uc == '\\';
  8715. }
  8716. static inline char* json_nice_escape(char c) {
  8717. switch (c) {
  8718. case '"': return "\\\"";
  8719. case '\\': return "\\\\";
  8720. case '\b': return "\\b";
  8721. case '\f': return "\\f";
  8722. case '\n': return "\\n";
  8723. case '\r': return "\\r";
  8724. case '\t': return "\\t";
  8725. default: return NULL;
  8726. }
  8727. }
  8728. // Write a properly escaped string chunk. The surrounding quotes are *not*
  8729. // printed; this is so that the caller has the option of emitting the string
  8730. // content in chunks.
  8731. static void putstring(upb_json_printer *p, const char *buf, unsigned int len) {
  8732. const char* unescaped_run = NULL;
  8733. for (unsigned int i = 0; i < len; i++) {
  8734. char c = buf[i];
  8735. // Handle escaping.
  8736. if (is_json_escaped(c)) {
  8737. // Use a "nice" escape, like \n, if one exists for this character.
  8738. const char* escape = json_nice_escape(c);
  8739. // If we don't have a specific 'nice' escape code, use a \uXXXX-style
  8740. // escape.
  8741. char escape_buf[8];
  8742. if (!escape) {
  8743. unsigned char byte = (unsigned char)c;
  8744. snprintf(escape_buf, sizeof(escape_buf), "\\u%04x", (int)byte);
  8745. escape = escape_buf;
  8746. }
  8747. // N.B. that we assume that the input encoding is equal to the output
  8748. // encoding (both UTF-8 for now), so for chars >= 0x20 and != \, ", we
  8749. // can simply pass the bytes through.
  8750. // If there's a current run of unescaped chars, print that run first.
  8751. if (unescaped_run) {
  8752. print_data(p, unescaped_run, &buf[i] - unescaped_run);
  8753. unescaped_run = NULL;
  8754. }
  8755. // Then print the escape code.
  8756. print_data(p, escape, strlen(escape));
  8757. } else {
  8758. // Add to the current unescaped run of characters.
  8759. if (unescaped_run == NULL) {
  8760. unescaped_run = &buf[i];
  8761. }
  8762. }
  8763. }
  8764. // If the string ended in a run of unescaped characters, print that last run.
  8765. if (unescaped_run) {
  8766. print_data(p, unescaped_run, &buf[len] - unescaped_run);
  8767. }
  8768. }
  8769. #define CHKLENGTH(x) if (!(x)) return -1;
  8770. // Helpers that format floating point values according to our custom formats.
  8771. // Right now we use %.8g and %.17g for float/double, respectively, to match
  8772. // proto2::util::JsonFormat's defaults. May want to change this later.
  8773. static size_t fmt_double(double val, char* buf, size_t length) {
  8774. size_t n = snprintf(buf, length, "%.17g", val);
  8775. CHKLENGTH(n > 0 && n < length);
  8776. return n;
  8777. }
  8778. static size_t fmt_float(float val, char* buf, size_t length) {
  8779. size_t n = snprintf(buf, length, "%.8g", val);
  8780. CHKLENGTH(n > 0 && n < length);
  8781. return n;
  8782. }
  8783. static size_t fmt_bool(bool val, char* buf, size_t length) {
  8784. size_t n = snprintf(buf, length, "%s", (val ? "true" : "false"));
  8785. CHKLENGTH(n > 0 && n < length);
  8786. return n;
  8787. }
  8788. static size_t fmt_int64(long val, char* buf, size_t length) {
  8789. size_t n = snprintf(buf, length, "%ld", val);
  8790. CHKLENGTH(n > 0 && n < length);
  8791. return n;
  8792. }
  8793. static size_t fmt_uint64(unsigned long long val, char* buf, size_t length) {
  8794. size_t n = snprintf(buf, length, "%llu", val);
  8795. CHKLENGTH(n > 0 && n < length);
  8796. return n;
  8797. }
  8798. // Print a map key given a field name. Called by scalar field handlers and by
  8799. // startseq for repeated fields.
  8800. static bool putkey(void *closure, const void *handler_data) {
  8801. upb_json_printer *p = closure;
  8802. const strpc *key = handler_data;
  8803. print_comma(p);
  8804. print_data(p, "\"", 1);
  8805. putstring(p, key->ptr, key->len);
  8806. print_data(p, "\":", 2);
  8807. return true;
  8808. }
  8809. #define CHKFMT(val) if ((val) == -1) return false;
  8810. #define CHK(val) if (!(val)) return false;
  8811. #define TYPE_HANDLERS(type, fmt_func) \
  8812. static bool put##type(void *closure, const void *handler_data, type val) { \
  8813. upb_json_printer *p = closure; \
  8814. UPB_UNUSED(handler_data); \
  8815. char data[64]; \
  8816. size_t length = fmt_func(val, data, sizeof(data)); \
  8817. CHKFMT(length); \
  8818. print_data(p, data, length); \
  8819. return true; \
  8820. } \
  8821. static bool scalar_##type(void *closure, const void *handler_data, \
  8822. type val) { \
  8823. CHK(putkey(closure, handler_data)); \
  8824. CHK(put##type(closure, handler_data, val)); \
  8825. return true; \
  8826. } \
  8827. static bool repeated_##type(void *closure, const void *handler_data, \
  8828. type val) { \
  8829. upb_json_printer *p = closure; \
  8830. print_comma(p); \
  8831. CHK(put##type(closure, handler_data, val)); \
  8832. return true; \
  8833. }
  8834. TYPE_HANDLERS(double, fmt_double);
  8835. TYPE_HANDLERS(float, fmt_float);
  8836. TYPE_HANDLERS(bool, fmt_bool);
  8837. TYPE_HANDLERS(int32_t, fmt_int64);
  8838. TYPE_HANDLERS(uint32_t, fmt_int64);
  8839. TYPE_HANDLERS(int64_t, fmt_int64);
  8840. TYPE_HANDLERS(uint64_t, fmt_uint64);
  8841. #undef TYPE_HANDLERS
  8842. typedef struct {
  8843. void *keyname;
  8844. const upb_enumdef *enumdef;
  8845. } EnumHandlerData;
  8846. static bool scalar_enum(void *closure, const void *handler_data,
  8847. int32_t val) {
  8848. const EnumHandlerData *hd = handler_data;
  8849. upb_json_printer *p = closure;
  8850. CHK(putkey(closure, hd->keyname));
  8851. const char *symbolic_name = upb_enumdef_iton(hd->enumdef, val);
  8852. if (symbolic_name) {
  8853. print_data(p, "\"", 1);
  8854. putstring(p, symbolic_name, strlen(symbolic_name));
  8855. print_data(p, "\"", 1);
  8856. } else {
  8857. putint32_t(closure, NULL, val);
  8858. }
  8859. return true;
  8860. }
  8861. static bool repeated_enum(void *closure, const void *handler_data,
  8862. int32_t val) {
  8863. const EnumHandlerData *hd = handler_data;
  8864. upb_json_printer *p = closure;
  8865. print_comma(p);
  8866. const char *symbolic_name = upb_enumdef_iton(hd->enumdef, val);
  8867. if (symbolic_name) {
  8868. print_data(p, "\"", 1);
  8869. putstring(p, symbolic_name, strlen(symbolic_name));
  8870. print_data(p, "\"", 1);
  8871. } else {
  8872. putint32_t(closure, NULL, val);
  8873. }
  8874. return true;
  8875. }
  8876. static void *scalar_startsubmsg(void *closure, const void *handler_data) {
  8877. return putkey(closure, handler_data) ? closure : UPB_BREAK;
  8878. }
  8879. static void *repeated_startsubmsg(void *closure, const void *handler_data) {
  8880. UPB_UNUSED(handler_data);
  8881. upb_json_printer *p = closure;
  8882. print_comma(p);
  8883. return closure;
  8884. }
  8885. static bool startmap(void *closure, const void *handler_data) {
  8886. UPB_UNUSED(handler_data);
  8887. upb_json_printer *p = closure;
  8888. if (p->depth_++ == 0) {
  8889. upb_bytessink_start(p->output_, 0, &p->subc_);
  8890. }
  8891. p->first_elem_[p->depth_] = true;
  8892. print_data(p, "{", 1);
  8893. return true;
  8894. }
  8895. static bool endmap(void *closure, const void *handler_data, upb_status *s) {
  8896. UPB_UNUSED(handler_data);
  8897. UPB_UNUSED(s);
  8898. upb_json_printer *p = closure;
  8899. if (--p->depth_ == 0) {
  8900. upb_bytessink_end(p->output_);
  8901. }
  8902. print_data(p, "}", 1);
  8903. return true;
  8904. }
  8905. static void *startseq(void *closure, const void *handler_data) {
  8906. upb_json_printer *p = closure;
  8907. CHK(putkey(closure, handler_data));
  8908. p->depth_++;
  8909. p->first_elem_[p->depth_] = true;
  8910. print_data(p, "[", 1);
  8911. return closure;
  8912. }
  8913. static bool endseq(void *closure, const void *handler_data) {
  8914. UPB_UNUSED(handler_data);
  8915. upb_json_printer *p = closure;
  8916. print_data(p, "]", 1);
  8917. p->depth_--;
  8918. return true;
  8919. }
  8920. static size_t putstr(void *closure, const void *handler_data, const char *str,
  8921. size_t len, const upb_bufhandle *handle) {
  8922. UPB_UNUSED(handler_data);
  8923. UPB_UNUSED(handle);
  8924. upb_json_printer *p = closure;
  8925. putstring(p, str, len);
  8926. return len;
  8927. }
  8928. // This has to Base64 encode the bytes, because JSON has no "bytes" type.
  8929. static size_t putbytes(void *closure, const void *handler_data, const char *str,
  8930. size_t len, const upb_bufhandle *handle) {
  8931. UPB_UNUSED(handler_data);
  8932. UPB_UNUSED(handle);
  8933. upb_json_printer *p = closure;
  8934. // This is the regular base64, not the "web-safe" version.
  8935. static const char base64[] =
  8936. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  8937. // Base64-encode.
  8938. char data[16000];
  8939. const char *limit = data + sizeof(data);
  8940. const unsigned char *from = (const unsigned char*)str;
  8941. char *to = data;
  8942. size_t remaining = len;
  8943. while (remaining > 2) {
  8944. // TODO(haberman): handle encoded lengths > sizeof(data)
  8945. UPB_ASSERT_VAR(limit, (limit - to) >= 4);
  8946. to[0] = base64[from[0] >> 2];
  8947. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  8948. to[2] = base64[((from[1] & 0xf) << 2) | (from[2] >> 6)];
  8949. to[3] = base64[from[2] & 0x3f];
  8950. remaining -= 3;
  8951. to += 4;
  8952. from += 3;
  8953. }
  8954. switch (remaining) {
  8955. case 2:
  8956. to[0] = base64[from[0] >> 2];
  8957. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  8958. to[2] = base64[(from[1] & 0xf) << 2];
  8959. to[3] = '=';
  8960. to += 4;
  8961. from += 2;
  8962. break;
  8963. case 1:
  8964. to[0] = base64[from[0] >> 2];
  8965. to[1] = base64[((from[0] & 0x3) << 4)];
  8966. to[2] = '=';
  8967. to[3] = '=';
  8968. to += 4;
  8969. from += 1;
  8970. break;
  8971. }
  8972. size_t bytes = to - data;
  8973. print_data(p, "\"", 1);
  8974. putstring(p, data, bytes);
  8975. print_data(p, "\"", 1);
  8976. return len;
  8977. }
  8978. static void *scalar_startstr(void *closure, const void *handler_data,
  8979. size_t size_hint) {
  8980. UPB_UNUSED(handler_data);
  8981. UPB_UNUSED(size_hint);
  8982. upb_json_printer *p = closure;
  8983. CHK(putkey(closure, handler_data));
  8984. print_data(p, "\"", 1);
  8985. return p;
  8986. }
  8987. static size_t scalar_str(void *closure, const void *handler_data,
  8988. const char *str, size_t len,
  8989. const upb_bufhandle *handle) {
  8990. CHK(putstr(closure, handler_data, str, len, handle));
  8991. return len;
  8992. }
  8993. static bool scalar_endstr(void *closure, const void *handler_data) {
  8994. UPB_UNUSED(handler_data);
  8995. upb_json_printer *p = closure;
  8996. print_data(p, "\"", 1);
  8997. return true;
  8998. }
  8999. static void *repeated_startstr(void *closure, const void *handler_data,
  9000. size_t size_hint) {
  9001. UPB_UNUSED(handler_data);
  9002. UPB_UNUSED(size_hint);
  9003. upb_json_printer *p = closure;
  9004. print_comma(p);
  9005. print_data(p, "\"", 1);
  9006. return p;
  9007. }
  9008. static size_t repeated_str(void *closure, const void *handler_data,
  9009. const char *str, size_t len,
  9010. const upb_bufhandle *handle) {
  9011. CHK(putstr(closure, handler_data, str, len, handle));
  9012. return len;
  9013. }
  9014. static bool repeated_endstr(void *closure, const void *handler_data) {
  9015. UPB_UNUSED(handler_data);
  9016. upb_json_printer *p = closure;
  9017. print_data(p, "\"", 1);
  9018. return true;
  9019. }
  9020. static size_t scalar_bytes(void *closure, const void *handler_data,
  9021. const char *str, size_t len,
  9022. const upb_bufhandle *handle) {
  9023. CHK(putkey(closure, handler_data));
  9024. CHK(putbytes(closure, handler_data, str, len, handle));
  9025. return len;
  9026. }
  9027. static size_t repeated_bytes(void *closure, const void *handler_data,
  9028. const char *str, size_t len,
  9029. const upb_bufhandle *handle) {
  9030. upb_json_printer *p = closure;
  9031. print_comma(p);
  9032. CHK(putbytes(closure, handler_data, str, len, handle));
  9033. return len;
  9034. }
  9035. void printer_sethandlers(const void *closure, upb_handlers *h) {
  9036. UPB_UNUSED(closure);
  9037. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  9038. upb_handlers_setstartmsg(h, startmap, &empty_attr);
  9039. upb_handlers_setendmsg(h, endmap, &empty_attr);
  9040. #define TYPE(type, name, ctype) \
  9041. case type: \
  9042. if (upb_fielddef_isseq(f)) { \
  9043. upb_handlers_set##name(h, f, repeated_##ctype, &empty_attr); \
  9044. } else { \
  9045. upb_handlers_set##name(h, f, scalar_##ctype, &name_attr); \
  9046. } \
  9047. break;
  9048. upb_msg_iter i;
  9049. upb_msg_begin(&i, upb_handlers_msgdef(h));
  9050. for(; !upb_msg_done(&i); upb_msg_next(&i)) {
  9051. const upb_fielddef *f = upb_msg_iter_field(&i);
  9052. upb_handlerattr name_attr = UPB_HANDLERATTR_INITIALIZER;
  9053. upb_handlerattr_sethandlerdata(&name_attr, newstrpc(h, f));
  9054. if (upb_fielddef_isseq(f)) {
  9055. upb_handlers_setstartseq(h, f, startseq, &name_attr);
  9056. upb_handlers_setendseq(h, f, endseq, &empty_attr);
  9057. }
  9058. switch (upb_fielddef_type(f)) {
  9059. TYPE(UPB_TYPE_FLOAT, float, float);
  9060. TYPE(UPB_TYPE_DOUBLE, double, double);
  9061. TYPE(UPB_TYPE_BOOL, bool, bool);
  9062. TYPE(UPB_TYPE_INT32, int32, int32_t);
  9063. TYPE(UPB_TYPE_UINT32, uint32, uint32_t);
  9064. TYPE(UPB_TYPE_INT64, int64, int64_t);
  9065. TYPE(UPB_TYPE_UINT64, uint64, uint64_t);
  9066. case UPB_TYPE_ENUM: {
  9067. // For now, we always emit symbolic names for enums. We may want an
  9068. // option later to control this behavior, but we will wait for a real
  9069. // need first.
  9070. EnumHandlerData *hd = malloc(sizeof(EnumHandlerData));
  9071. hd->enumdef = (const upb_enumdef *)upb_fielddef_subdef(f);
  9072. hd->keyname = newstrpc(h, f);
  9073. upb_handlers_addcleanup(h, hd, free);
  9074. upb_handlerattr enum_attr = UPB_HANDLERATTR_INITIALIZER;
  9075. upb_handlerattr_sethandlerdata(&enum_attr, hd);
  9076. if (upb_fielddef_isseq(f)) {
  9077. upb_handlers_setint32(h, f, repeated_enum, &enum_attr);
  9078. } else {
  9079. upb_handlers_setint32(h, f, scalar_enum, &enum_attr);
  9080. }
  9081. upb_handlerattr_uninit(&enum_attr);
  9082. break;
  9083. }
  9084. case UPB_TYPE_STRING:
  9085. if (upb_fielddef_isseq(f)) {
  9086. upb_handlers_setstartstr(h, f, repeated_startstr, &empty_attr);
  9087. upb_handlers_setstring(h, f, repeated_str, &empty_attr);
  9088. upb_handlers_setendstr(h, f, repeated_endstr, &empty_attr);
  9089. } else {
  9090. upb_handlers_setstartstr(h, f, scalar_startstr, &name_attr);
  9091. upb_handlers_setstring(h, f, scalar_str, &empty_attr);
  9092. upb_handlers_setendstr(h, f, scalar_endstr, &empty_attr);
  9093. }
  9094. break;
  9095. case UPB_TYPE_BYTES:
  9096. // XXX: this doesn't support strings that span buffers yet. The base64
  9097. // encoder will need to be made resumable for this to work properly.
  9098. if (upb_fielddef_isseq(f)) {
  9099. upb_handlers_setstring(h, f, repeated_bytes, &empty_attr);
  9100. } else {
  9101. upb_handlers_setstring(h, f, scalar_bytes, &name_attr);
  9102. }
  9103. break;
  9104. case UPB_TYPE_MESSAGE:
  9105. if (upb_fielddef_isseq(f)) {
  9106. upb_handlers_setstartsubmsg(h, f, repeated_startsubmsg, &name_attr);
  9107. } else {
  9108. upb_handlers_setstartsubmsg(h, f, scalar_startsubmsg, &name_attr);
  9109. }
  9110. break;
  9111. }
  9112. upb_handlerattr_uninit(&name_attr);
  9113. }
  9114. upb_handlerattr_uninit(&empty_attr);
  9115. #undef TYPE
  9116. }
  9117. /* Public API *****************************************************************/
  9118. void upb_json_printer_init(upb_json_printer *p, const upb_handlers *h) {
  9119. p->output_ = NULL;
  9120. p->depth_ = 0;
  9121. upb_sink_reset(&p->input_, h, p);
  9122. }
  9123. void upb_json_printer_uninit(upb_json_printer *p) {
  9124. UPB_UNUSED(p);
  9125. }
  9126. void upb_json_printer_reset(upb_json_printer *p) {
  9127. p->depth_ = 0;
  9128. }
  9129. void upb_json_printer_resetoutput(upb_json_printer *p, upb_bytessink *output) {
  9130. upb_json_printer_reset(p);
  9131. p->output_ = output;
  9132. }
  9133. upb_sink *upb_json_printer_input(upb_json_printer *p) {
  9134. return &p->input_;
  9135. }
  9136. const upb_handlers *upb_json_printer_newhandlers(const upb_msgdef *md,
  9137. const void *owner) {
  9138. return upb_handlers_newfrozen(md, owner, printer_sethandlers, NULL);
  9139. }