upb.c 559 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480
  1. /* Amalgamated source file */
  2. #define _XOPEN_SOURCE 700
  3. #include "upb.h"
  4. #if UINTPTR_MAX == 0xffffffff
  5. #define UPB_SIZE(size32, size64) size32
  6. #else
  7. #define UPB_SIZE(size32, size64) size64
  8. #endif
  9. #define UPB_FIELD_AT(msg, fieldtype, offset) \
  10. *(fieldtype*)((const char*)(msg) + offset)
  11. #define UPB_READ_ONEOF(msg, fieldtype, offset, case_offset, case_val, default) \
  12. UPB_FIELD_AT(msg, int, case_offset) == case_val \
  13. ? UPB_FIELD_AT(msg, fieldtype, offset) \
  14. : default
  15. #define UPB_WRITE_ONEOF(msg, fieldtype, offset, value, case_offset, case_val) \
  16. UPB_FIELD_AT(msg, int, case_offset) = case_val; \
  17. UPB_FIELD_AT(msg, fieldtype, offset) = value;
  18. /* This file was generated by upbc (the upb compiler) from the input
  19. * file:
  20. *
  21. * google/protobuf/descriptor.proto
  22. *
  23. * Do not edit -- your changes will be discarded when the file is
  24. * regenerated. */
  25. #include <stddef.h>
  26. static const upb_msglayout *const google_protobuf_FileDescriptorSet_submsgs[1] = {
  27. &google_protobuf_FileDescriptorProto_msginit,
  28. };
  29. static const upb_msglayout_field google_protobuf_FileDescriptorSet__fields[1] = {
  30. {1, UPB_SIZE(0, 0), 0, 0, 11, 3},
  31. };
  32. const upb_msglayout google_protobuf_FileDescriptorSet_msginit = {
  33. &google_protobuf_FileDescriptorSet_submsgs[0],
  34. &google_protobuf_FileDescriptorSet__fields[0],
  35. UPB_SIZE(4, 8), 1, false,
  36. };
  37. static const upb_msglayout *const google_protobuf_FileDescriptorProto_submsgs[6] = {
  38. &google_protobuf_DescriptorProto_msginit,
  39. &google_protobuf_EnumDescriptorProto_msginit,
  40. &google_protobuf_FieldDescriptorProto_msginit,
  41. &google_protobuf_FileOptions_msginit,
  42. &google_protobuf_ServiceDescriptorProto_msginit,
  43. &google_protobuf_SourceCodeInfo_msginit,
  44. };
  45. static const upb_msglayout_field google_protobuf_FileDescriptorProto__fields[12] = {
  46. {1, UPB_SIZE(4, 8), 1, 0, 9, 1},
  47. {2, UPB_SIZE(12, 24), 2, 0, 9, 1},
  48. {3, UPB_SIZE(36, 72), 0, 0, 9, 3},
  49. {4, UPB_SIZE(40, 80), 0, 0, 11, 3},
  50. {5, UPB_SIZE(44, 88), 0, 1, 11, 3},
  51. {6, UPB_SIZE(48, 96), 0, 4, 11, 3},
  52. {7, UPB_SIZE(52, 104), 0, 2, 11, 3},
  53. {8, UPB_SIZE(28, 56), 4, 3, 11, 1},
  54. {9, UPB_SIZE(32, 64), 5, 5, 11, 1},
  55. {10, UPB_SIZE(56, 112), 0, 0, 5, 3},
  56. {11, UPB_SIZE(60, 120), 0, 0, 5, 3},
  57. {12, UPB_SIZE(20, 40), 3, 0, 9, 1},
  58. };
  59. const upb_msglayout google_protobuf_FileDescriptorProto_msginit = {
  60. &google_protobuf_FileDescriptorProto_submsgs[0],
  61. &google_protobuf_FileDescriptorProto__fields[0],
  62. UPB_SIZE(64, 128), 12, false,
  63. };
  64. static const upb_msglayout *const google_protobuf_DescriptorProto_submsgs[8] = {
  65. &google_protobuf_DescriptorProto_msginit,
  66. &google_protobuf_DescriptorProto_ExtensionRange_msginit,
  67. &google_protobuf_DescriptorProto_ReservedRange_msginit,
  68. &google_protobuf_EnumDescriptorProto_msginit,
  69. &google_protobuf_FieldDescriptorProto_msginit,
  70. &google_protobuf_MessageOptions_msginit,
  71. &google_protobuf_OneofDescriptorProto_msginit,
  72. };
  73. static const upb_msglayout_field google_protobuf_DescriptorProto__fields[10] = {
  74. {1, UPB_SIZE(4, 8), 1, 0, 9, 1},
  75. {2, UPB_SIZE(16, 32), 0, 4, 11, 3},
  76. {3, UPB_SIZE(20, 40), 0, 0, 11, 3},
  77. {4, UPB_SIZE(24, 48), 0, 3, 11, 3},
  78. {5, UPB_SIZE(28, 56), 0, 1, 11, 3},
  79. {6, UPB_SIZE(32, 64), 0, 4, 11, 3},
  80. {7, UPB_SIZE(12, 24), 2, 5, 11, 1},
  81. {8, UPB_SIZE(36, 72), 0, 6, 11, 3},
  82. {9, UPB_SIZE(40, 80), 0, 2, 11, 3},
  83. {10, UPB_SIZE(44, 88), 0, 0, 9, 3},
  84. };
  85. const upb_msglayout google_protobuf_DescriptorProto_msginit = {
  86. &google_protobuf_DescriptorProto_submsgs[0],
  87. &google_protobuf_DescriptorProto__fields[0],
  88. UPB_SIZE(48, 96), 10, false,
  89. };
  90. static const upb_msglayout *const google_protobuf_DescriptorProto_ExtensionRange_submsgs[1] = {
  91. &google_protobuf_ExtensionRangeOptions_msginit,
  92. };
  93. static const upb_msglayout_field google_protobuf_DescriptorProto_ExtensionRange__fields[3] = {
  94. {1, UPB_SIZE(4, 4), 1, 0, 5, 1},
  95. {2, UPB_SIZE(8, 8), 2, 0, 5, 1},
  96. {3, UPB_SIZE(12, 16), 3, 0, 11, 1},
  97. };
  98. const upb_msglayout google_protobuf_DescriptorProto_ExtensionRange_msginit = {
  99. &google_protobuf_DescriptorProto_ExtensionRange_submsgs[0],
  100. &google_protobuf_DescriptorProto_ExtensionRange__fields[0],
  101. UPB_SIZE(16, 24), 3, false,
  102. };
  103. static const upb_msglayout_field google_protobuf_DescriptorProto_ReservedRange__fields[2] = {
  104. {1, UPB_SIZE(4, 4), 1, 0, 5, 1},
  105. {2, UPB_SIZE(8, 8), 2, 0, 5, 1},
  106. };
  107. const upb_msglayout google_protobuf_DescriptorProto_ReservedRange_msginit = {
  108. NULL,
  109. &google_protobuf_DescriptorProto_ReservedRange__fields[0],
  110. UPB_SIZE(12, 12), 2, false,
  111. };
  112. static const upb_msglayout *const google_protobuf_ExtensionRangeOptions_submsgs[1] = {
  113. &google_protobuf_UninterpretedOption_msginit,
  114. };
  115. static const upb_msglayout_field google_protobuf_ExtensionRangeOptions__fields[1] = {
  116. {999, UPB_SIZE(0, 0), 0, 0, 11, 3},
  117. };
  118. const upb_msglayout google_protobuf_ExtensionRangeOptions_msginit = {
  119. &google_protobuf_ExtensionRangeOptions_submsgs[0],
  120. &google_protobuf_ExtensionRangeOptions__fields[0],
  121. UPB_SIZE(4, 8), 1, false,
  122. };
  123. static const upb_msglayout *const google_protobuf_FieldDescriptorProto_submsgs[1] = {
  124. &google_protobuf_FieldOptions_msginit,
  125. };
  126. static const upb_msglayout_field google_protobuf_FieldDescriptorProto__fields[10] = {
  127. {1, UPB_SIZE(32, 32), 5, 0, 9, 1},
  128. {2, UPB_SIZE(40, 48), 6, 0, 9, 1},
  129. {3, UPB_SIZE(24, 24), 3, 0, 5, 1},
  130. {4, UPB_SIZE(8, 8), 1, 0, 14, 1},
  131. {5, UPB_SIZE(16, 16), 2, 0, 14, 1},
  132. {6, UPB_SIZE(48, 64), 7, 0, 9, 1},
  133. {7, UPB_SIZE(56, 80), 8, 0, 9, 1},
  134. {8, UPB_SIZE(72, 112), 10, 0, 11, 1},
  135. {9, UPB_SIZE(28, 28), 4, 0, 5, 1},
  136. {10, UPB_SIZE(64, 96), 9, 0, 9, 1},
  137. };
  138. const upb_msglayout google_protobuf_FieldDescriptorProto_msginit = {
  139. &google_protobuf_FieldDescriptorProto_submsgs[0],
  140. &google_protobuf_FieldDescriptorProto__fields[0],
  141. UPB_SIZE(80, 128), 10, false,
  142. };
  143. static const upb_msglayout *const google_protobuf_OneofDescriptorProto_submsgs[1] = {
  144. &google_protobuf_OneofOptions_msginit,
  145. };
  146. static const upb_msglayout_field google_protobuf_OneofDescriptorProto__fields[2] = {
  147. {1, UPB_SIZE(4, 8), 1, 0, 9, 1},
  148. {2, UPB_SIZE(12, 24), 2, 0, 11, 1},
  149. };
  150. const upb_msglayout google_protobuf_OneofDescriptorProto_msginit = {
  151. &google_protobuf_OneofDescriptorProto_submsgs[0],
  152. &google_protobuf_OneofDescriptorProto__fields[0],
  153. UPB_SIZE(16, 32), 2, false,
  154. };
  155. static const upb_msglayout *const google_protobuf_EnumDescriptorProto_submsgs[3] = {
  156. &google_protobuf_EnumDescriptorProto_EnumReservedRange_msginit,
  157. &google_protobuf_EnumOptions_msginit,
  158. &google_protobuf_EnumValueDescriptorProto_msginit,
  159. };
  160. static const upb_msglayout_field google_protobuf_EnumDescriptorProto__fields[5] = {
  161. {1, UPB_SIZE(4, 8), 1, 0, 9, 1},
  162. {2, UPB_SIZE(16, 32), 0, 2, 11, 3},
  163. {3, UPB_SIZE(12, 24), 2, 1, 11, 1},
  164. {4, UPB_SIZE(20, 40), 0, 0, 11, 3},
  165. {5, UPB_SIZE(24, 48), 0, 0, 9, 3},
  166. };
  167. const upb_msglayout google_protobuf_EnumDescriptorProto_msginit = {
  168. &google_protobuf_EnumDescriptorProto_submsgs[0],
  169. &google_protobuf_EnumDescriptorProto__fields[0],
  170. UPB_SIZE(32, 64), 5, false,
  171. };
  172. static const upb_msglayout_field google_protobuf_EnumDescriptorProto_EnumReservedRange__fields[2] = {
  173. {1, UPB_SIZE(4, 4), 1, 0, 5, 1},
  174. {2, UPB_SIZE(8, 8), 2, 0, 5, 1},
  175. };
  176. const upb_msglayout google_protobuf_EnumDescriptorProto_EnumReservedRange_msginit = {
  177. NULL,
  178. &google_protobuf_EnumDescriptorProto_EnumReservedRange__fields[0],
  179. UPB_SIZE(12, 12), 2, false,
  180. };
  181. static const upb_msglayout *const google_protobuf_EnumValueDescriptorProto_submsgs[1] = {
  182. &google_protobuf_EnumValueOptions_msginit,
  183. };
  184. static const upb_msglayout_field google_protobuf_EnumValueDescriptorProto__fields[3] = {
  185. {1, UPB_SIZE(8, 8), 2, 0, 9, 1},
  186. {2, UPB_SIZE(4, 4), 1, 0, 5, 1},
  187. {3, UPB_SIZE(16, 24), 3, 0, 11, 1},
  188. };
  189. const upb_msglayout google_protobuf_EnumValueDescriptorProto_msginit = {
  190. &google_protobuf_EnumValueDescriptorProto_submsgs[0],
  191. &google_protobuf_EnumValueDescriptorProto__fields[0],
  192. UPB_SIZE(24, 32), 3, false,
  193. };
  194. static const upb_msglayout *const google_protobuf_ServiceDescriptorProto_submsgs[2] = {
  195. &google_protobuf_MethodDescriptorProto_msginit,
  196. &google_protobuf_ServiceOptions_msginit,
  197. };
  198. static const upb_msglayout_field google_protobuf_ServiceDescriptorProto__fields[3] = {
  199. {1, UPB_SIZE(4, 8), 1, 0, 9, 1},
  200. {2, UPB_SIZE(16, 32), 0, 0, 11, 3},
  201. {3, UPB_SIZE(12, 24), 2, 1, 11, 1},
  202. };
  203. const upb_msglayout google_protobuf_ServiceDescriptorProto_msginit = {
  204. &google_protobuf_ServiceDescriptorProto_submsgs[0],
  205. &google_protobuf_ServiceDescriptorProto__fields[0],
  206. UPB_SIZE(24, 48), 3, false,
  207. };
  208. static const upb_msglayout *const google_protobuf_MethodDescriptorProto_submsgs[1] = {
  209. &google_protobuf_MethodOptions_msginit,
  210. };
  211. static const upb_msglayout_field google_protobuf_MethodDescriptorProto__fields[6] = {
  212. {1, UPB_SIZE(4, 8), 3, 0, 9, 1},
  213. {2, UPB_SIZE(12, 24), 4, 0, 9, 1},
  214. {3, UPB_SIZE(20, 40), 5, 0, 9, 1},
  215. {4, UPB_SIZE(28, 56), 6, 0, 11, 1},
  216. {5, UPB_SIZE(1, 1), 1, 0, 8, 1},
  217. {6, UPB_SIZE(2, 2), 2, 0, 8, 1},
  218. };
  219. const upb_msglayout google_protobuf_MethodDescriptorProto_msginit = {
  220. &google_protobuf_MethodDescriptorProto_submsgs[0],
  221. &google_protobuf_MethodDescriptorProto__fields[0],
  222. UPB_SIZE(32, 64), 6, false,
  223. };
  224. static const upb_msglayout *const google_protobuf_FileOptions_submsgs[1] = {
  225. &google_protobuf_UninterpretedOption_msginit,
  226. };
  227. static const upb_msglayout_field google_protobuf_FileOptions__fields[19] = {
  228. {1, UPB_SIZE(28, 32), 11, 0, 9, 1},
  229. {8, UPB_SIZE(36, 48), 12, 0, 9, 1},
  230. {9, UPB_SIZE(8, 8), 1, 0, 14, 1},
  231. {10, UPB_SIZE(16, 16), 2, 0, 8, 1},
  232. {11, UPB_SIZE(44, 64), 13, 0, 9, 1},
  233. {16, UPB_SIZE(17, 17), 3, 0, 8, 1},
  234. {17, UPB_SIZE(18, 18), 4, 0, 8, 1},
  235. {18, UPB_SIZE(19, 19), 5, 0, 8, 1},
  236. {20, UPB_SIZE(20, 20), 6, 0, 8, 1},
  237. {23, UPB_SIZE(21, 21), 7, 0, 8, 1},
  238. {27, UPB_SIZE(22, 22), 8, 0, 8, 1},
  239. {31, UPB_SIZE(23, 23), 9, 0, 8, 1},
  240. {36, UPB_SIZE(52, 80), 14, 0, 9, 1},
  241. {37, UPB_SIZE(60, 96), 15, 0, 9, 1},
  242. {39, UPB_SIZE(68, 112), 16, 0, 9, 1},
  243. {40, UPB_SIZE(76, 128), 17, 0, 9, 1},
  244. {41, UPB_SIZE(84, 144), 18, 0, 9, 1},
  245. {42, UPB_SIZE(24, 24), 10, 0, 8, 1},
  246. {999, UPB_SIZE(92, 160), 0, 0, 11, 3},
  247. };
  248. const upb_msglayout google_protobuf_FileOptions_msginit = {
  249. &google_protobuf_FileOptions_submsgs[0],
  250. &google_protobuf_FileOptions__fields[0],
  251. UPB_SIZE(96, 176), 19, false,
  252. };
  253. static const upb_msglayout *const google_protobuf_MessageOptions_submsgs[1] = {
  254. &google_protobuf_UninterpretedOption_msginit,
  255. };
  256. static const upb_msglayout_field google_protobuf_MessageOptions__fields[5] = {
  257. {1, UPB_SIZE(1, 1), 1, 0, 8, 1},
  258. {2, UPB_SIZE(2, 2), 2, 0, 8, 1},
  259. {3, UPB_SIZE(3, 3), 3, 0, 8, 1},
  260. {7, UPB_SIZE(4, 4), 4, 0, 8, 1},
  261. {999, UPB_SIZE(8, 8), 0, 0, 11, 3},
  262. };
  263. const upb_msglayout google_protobuf_MessageOptions_msginit = {
  264. &google_protobuf_MessageOptions_submsgs[0],
  265. &google_protobuf_MessageOptions__fields[0],
  266. UPB_SIZE(12, 16), 5, false,
  267. };
  268. static const upb_msglayout *const google_protobuf_FieldOptions_submsgs[1] = {
  269. &google_protobuf_UninterpretedOption_msginit,
  270. };
  271. static const upb_msglayout_field google_protobuf_FieldOptions__fields[7] = {
  272. {1, UPB_SIZE(8, 8), 1, 0, 14, 1},
  273. {2, UPB_SIZE(24, 24), 3, 0, 8, 1},
  274. {3, UPB_SIZE(25, 25), 4, 0, 8, 1},
  275. {5, UPB_SIZE(26, 26), 5, 0, 8, 1},
  276. {6, UPB_SIZE(16, 16), 2, 0, 14, 1},
  277. {10, UPB_SIZE(27, 27), 6, 0, 8, 1},
  278. {999, UPB_SIZE(28, 32), 0, 0, 11, 3},
  279. };
  280. const upb_msglayout google_protobuf_FieldOptions_msginit = {
  281. &google_protobuf_FieldOptions_submsgs[0],
  282. &google_protobuf_FieldOptions__fields[0],
  283. UPB_SIZE(32, 40), 7, false,
  284. };
  285. static const upb_msglayout *const google_protobuf_OneofOptions_submsgs[1] = {
  286. &google_protobuf_UninterpretedOption_msginit,
  287. };
  288. static const upb_msglayout_field google_protobuf_OneofOptions__fields[1] = {
  289. {999, UPB_SIZE(0, 0), 0, 0, 11, 3},
  290. };
  291. const upb_msglayout google_protobuf_OneofOptions_msginit = {
  292. &google_protobuf_OneofOptions_submsgs[0],
  293. &google_protobuf_OneofOptions__fields[0],
  294. UPB_SIZE(4, 8), 1, false,
  295. };
  296. static const upb_msglayout *const google_protobuf_EnumOptions_submsgs[1] = {
  297. &google_protobuf_UninterpretedOption_msginit,
  298. };
  299. static const upb_msglayout_field google_protobuf_EnumOptions__fields[3] = {
  300. {2, UPB_SIZE(1, 1), 1, 0, 8, 1},
  301. {3, UPB_SIZE(2, 2), 2, 0, 8, 1},
  302. {999, UPB_SIZE(4, 8), 0, 0, 11, 3},
  303. };
  304. const upb_msglayout google_protobuf_EnumOptions_msginit = {
  305. &google_protobuf_EnumOptions_submsgs[0],
  306. &google_protobuf_EnumOptions__fields[0],
  307. UPB_SIZE(8, 16), 3, false,
  308. };
  309. static const upb_msglayout *const google_protobuf_EnumValueOptions_submsgs[1] = {
  310. &google_protobuf_UninterpretedOption_msginit,
  311. };
  312. static const upb_msglayout_field google_protobuf_EnumValueOptions__fields[2] = {
  313. {1, UPB_SIZE(1, 1), 1, 0, 8, 1},
  314. {999, UPB_SIZE(4, 8), 0, 0, 11, 3},
  315. };
  316. const upb_msglayout google_protobuf_EnumValueOptions_msginit = {
  317. &google_protobuf_EnumValueOptions_submsgs[0],
  318. &google_protobuf_EnumValueOptions__fields[0],
  319. UPB_SIZE(8, 16), 2, false,
  320. };
  321. static const upb_msglayout *const google_protobuf_ServiceOptions_submsgs[1] = {
  322. &google_protobuf_UninterpretedOption_msginit,
  323. };
  324. static const upb_msglayout_field google_protobuf_ServiceOptions__fields[2] = {
  325. {33, UPB_SIZE(1, 1), 1, 0, 8, 1},
  326. {999, UPB_SIZE(4, 8), 0, 0, 11, 3},
  327. };
  328. const upb_msglayout google_protobuf_ServiceOptions_msginit = {
  329. &google_protobuf_ServiceOptions_submsgs[0],
  330. &google_protobuf_ServiceOptions__fields[0],
  331. UPB_SIZE(8, 16), 2, false,
  332. };
  333. static const upb_msglayout *const google_protobuf_MethodOptions_submsgs[1] = {
  334. &google_protobuf_UninterpretedOption_msginit,
  335. };
  336. static const upb_msglayout_field google_protobuf_MethodOptions__fields[3] = {
  337. {33, UPB_SIZE(16, 16), 2, 0, 8, 1},
  338. {34, UPB_SIZE(8, 8), 1, 0, 14, 1},
  339. {999, UPB_SIZE(20, 24), 0, 0, 11, 3},
  340. };
  341. const upb_msglayout google_protobuf_MethodOptions_msginit = {
  342. &google_protobuf_MethodOptions_submsgs[0],
  343. &google_protobuf_MethodOptions__fields[0],
  344. UPB_SIZE(24, 32), 3, false,
  345. };
  346. static const upb_msglayout *const google_protobuf_UninterpretedOption_submsgs[1] = {
  347. &google_protobuf_UninterpretedOption_NamePart_msginit,
  348. };
  349. static const upb_msglayout_field google_protobuf_UninterpretedOption__fields[7] = {
  350. {2, UPB_SIZE(56, 80), 0, 0, 11, 3},
  351. {3, UPB_SIZE(32, 32), 4, 0, 9, 1},
  352. {4, UPB_SIZE(8, 8), 1, 0, 4, 1},
  353. {5, UPB_SIZE(16, 16), 2, 0, 3, 1},
  354. {6, UPB_SIZE(24, 24), 3, 0, 1, 1},
  355. {7, UPB_SIZE(40, 48), 5, 0, 12, 1},
  356. {8, UPB_SIZE(48, 64), 6, 0, 9, 1},
  357. };
  358. const upb_msglayout google_protobuf_UninterpretedOption_msginit = {
  359. &google_protobuf_UninterpretedOption_submsgs[0],
  360. &google_protobuf_UninterpretedOption__fields[0],
  361. UPB_SIZE(64, 96), 7, false,
  362. };
  363. static const upb_msglayout_field google_protobuf_UninterpretedOption_NamePart__fields[2] = {
  364. {1, UPB_SIZE(4, 8), 2, 0, 9, 2},
  365. {2, UPB_SIZE(1, 1), 1, 0, 8, 2},
  366. };
  367. const upb_msglayout google_protobuf_UninterpretedOption_NamePart_msginit = {
  368. NULL,
  369. &google_protobuf_UninterpretedOption_NamePart__fields[0],
  370. UPB_SIZE(16, 32), 2, false,
  371. };
  372. static const upb_msglayout *const google_protobuf_SourceCodeInfo_submsgs[1] = {
  373. &google_protobuf_SourceCodeInfo_Location_msginit,
  374. };
  375. static const upb_msglayout_field google_protobuf_SourceCodeInfo__fields[1] = {
  376. {1, UPB_SIZE(0, 0), 0, 0, 11, 3},
  377. };
  378. const upb_msglayout google_protobuf_SourceCodeInfo_msginit = {
  379. &google_protobuf_SourceCodeInfo_submsgs[0],
  380. &google_protobuf_SourceCodeInfo__fields[0],
  381. UPB_SIZE(4, 8), 1, false,
  382. };
  383. static const upb_msglayout_field google_protobuf_SourceCodeInfo_Location__fields[5] = {
  384. {1, UPB_SIZE(20, 40), 0, 0, 5, 3},
  385. {2, UPB_SIZE(24, 48), 0, 0, 5, 3},
  386. {3, UPB_SIZE(4, 8), 1, 0, 9, 1},
  387. {4, UPB_SIZE(12, 24), 2, 0, 9, 1},
  388. {6, UPB_SIZE(28, 56), 0, 0, 9, 3},
  389. };
  390. const upb_msglayout google_protobuf_SourceCodeInfo_Location_msginit = {
  391. NULL,
  392. &google_protobuf_SourceCodeInfo_Location__fields[0],
  393. UPB_SIZE(32, 64), 5, false,
  394. };
  395. static const upb_msglayout *const google_protobuf_GeneratedCodeInfo_submsgs[1] = {
  396. &google_protobuf_GeneratedCodeInfo_Annotation_msginit,
  397. };
  398. static const upb_msglayout_field google_protobuf_GeneratedCodeInfo__fields[1] = {
  399. {1, UPB_SIZE(0, 0), 0, 0, 11, 3},
  400. };
  401. const upb_msglayout google_protobuf_GeneratedCodeInfo_msginit = {
  402. &google_protobuf_GeneratedCodeInfo_submsgs[0],
  403. &google_protobuf_GeneratedCodeInfo__fields[0],
  404. UPB_SIZE(4, 8), 1, false,
  405. };
  406. static const upb_msglayout_field google_protobuf_GeneratedCodeInfo_Annotation__fields[4] = {
  407. {1, UPB_SIZE(20, 32), 0, 0, 5, 3},
  408. {2, UPB_SIZE(12, 16), 3, 0, 9, 1},
  409. {3, UPB_SIZE(4, 4), 1, 0, 5, 1},
  410. {4, UPB_SIZE(8, 8), 2, 0, 5, 1},
  411. };
  412. const upb_msglayout google_protobuf_GeneratedCodeInfo_Annotation_msginit = {
  413. NULL,
  414. &google_protobuf_GeneratedCodeInfo_Annotation__fields[0],
  415. UPB_SIZE(24, 48), 4, false,
  416. };
  417. /* Maps descriptor type -> upb field type. */
  418. const uint8_t upb_desctype_to_fieldtype[] = {
  419. UPB_WIRE_TYPE_END_GROUP, /* ENDGROUP */
  420. UPB_TYPE_DOUBLE, /* DOUBLE */
  421. UPB_TYPE_FLOAT, /* FLOAT */
  422. UPB_TYPE_INT64, /* INT64 */
  423. UPB_TYPE_UINT64, /* UINT64 */
  424. UPB_TYPE_INT32, /* INT32 */
  425. UPB_TYPE_UINT64, /* FIXED64 */
  426. UPB_TYPE_UINT32, /* FIXED32 */
  427. UPB_TYPE_BOOL, /* BOOL */
  428. UPB_TYPE_STRING, /* STRING */
  429. UPB_TYPE_MESSAGE, /* GROUP */
  430. UPB_TYPE_MESSAGE, /* MESSAGE */
  431. UPB_TYPE_BYTES, /* BYTES */
  432. UPB_TYPE_UINT32, /* UINT32 */
  433. UPB_TYPE_ENUM, /* ENUM */
  434. UPB_TYPE_INT32, /* SFIXED32 */
  435. UPB_TYPE_INT64, /* SFIXED64 */
  436. UPB_TYPE_INT32, /* SINT32 */
  437. UPB_TYPE_INT64, /* SINT64 */
  438. };
  439. /* Data pertaining to the parse. */
  440. typedef struct {
  441. /* Current decoding pointer. Points to the beginning of a field until we
  442. * have finished decoding the whole field. */
  443. const char *ptr;
  444. } upb_decstate;
  445. /* Data pertaining to a single message frame. */
  446. typedef struct {
  447. const char *limit;
  448. int32_t group_number; /* 0 if we are not parsing a group. */
  449. /* These members are unset for an unknown group frame. */
  450. char *msg;
  451. const upb_msglayout *m;
  452. } upb_decframe;
  453. #define CHK(x) if (!(x)) { return false; }
  454. static bool upb_skip_unknowngroup(upb_decstate *d, int field_number,
  455. const char *limit);
  456. static bool upb_decode_message(upb_decstate *d, const char *limit,
  457. int group_number, char *msg,
  458. const upb_msglayout *l);
  459. static bool upb_decode_varint(const char **ptr, const char *limit,
  460. uint64_t *val) {
  461. uint8_t byte;
  462. int bitpos = 0;
  463. const char *p = *ptr;
  464. *val = 0;
  465. do {
  466. CHK(bitpos < 70 && p < limit);
  467. byte = *p;
  468. *val |= (uint64_t)(byte & 0x7F) << bitpos;
  469. p++;
  470. bitpos += 7;
  471. } while (byte & 0x80);
  472. *ptr = p;
  473. return true;
  474. }
  475. static bool upb_decode_varint32(const char **ptr, const char *limit,
  476. uint32_t *val) {
  477. uint64_t u64;
  478. CHK(upb_decode_varint(ptr, limit, &u64) && u64 <= UINT32_MAX);
  479. *val = u64;
  480. return true;
  481. }
  482. static bool upb_decode_64bit(const char **ptr, const char *limit,
  483. uint64_t *val) {
  484. CHK(limit - *ptr >= 8);
  485. memcpy(val, *ptr, 8);
  486. *ptr += 8;
  487. return true;
  488. }
  489. static bool upb_decode_32bit(const char **ptr, const char *limit,
  490. uint32_t *val) {
  491. CHK(limit - *ptr >= 4);
  492. memcpy(val, *ptr, 4);
  493. *ptr += 4;
  494. return true;
  495. }
  496. static bool upb_decode_tag(const char **ptr, const char *limit,
  497. int *field_number, int *wire_type) {
  498. uint32_t tag = 0;
  499. CHK(upb_decode_varint32(ptr, limit, &tag));
  500. *field_number = tag >> 3;
  501. *wire_type = tag & 7;
  502. return true;
  503. }
  504. static int32_t upb_zzdecode_32(uint32_t n) {
  505. return (n >> 1) ^ -(int32_t)(n & 1);
  506. }
  507. static int64_t upb_zzdecode_64(uint64_t n) {
  508. return (n >> 1) ^ -(int64_t)(n & 1);
  509. }
  510. static bool upb_decode_string(const char **ptr, const char *limit,
  511. upb_strview *val) {
  512. uint32_t len;
  513. CHK(upb_decode_varint32(ptr, limit, &len) &&
  514. len < INT32_MAX &&
  515. limit - *ptr >= (int32_t)len);
  516. *val = upb_strview_make(*ptr, len);
  517. *ptr += len;
  518. return true;
  519. }
  520. static void upb_set32(void *msg, size_t ofs, uint32_t val) {
  521. memcpy((char*)msg + ofs, &val, sizeof(val));
  522. }
  523. static bool upb_append_unknown(upb_decstate *d, upb_decframe *frame,
  524. const char *start) {
  525. upb_msg_addunknown(frame->msg, start, d->ptr - start);
  526. return true;
  527. }
  528. static bool upb_skip_unknownfielddata(upb_decstate *d, upb_decframe *frame,
  529. int field_number, int wire_type) {
  530. switch (wire_type) {
  531. case UPB_WIRE_TYPE_VARINT: {
  532. uint64_t val;
  533. return upb_decode_varint(&d->ptr, frame->limit, &val);
  534. }
  535. case UPB_WIRE_TYPE_32BIT: {
  536. uint32_t val;
  537. return upb_decode_32bit(&d->ptr, frame->limit, &val);
  538. }
  539. case UPB_WIRE_TYPE_64BIT: {
  540. uint64_t val;
  541. return upb_decode_64bit(&d->ptr, frame->limit, &val);
  542. }
  543. case UPB_WIRE_TYPE_DELIMITED: {
  544. upb_strview val;
  545. return upb_decode_string(&d->ptr, frame->limit, &val);
  546. }
  547. case UPB_WIRE_TYPE_START_GROUP:
  548. return upb_skip_unknowngroup(d, field_number, frame->limit);
  549. case UPB_WIRE_TYPE_END_GROUP:
  550. CHK(field_number == frame->group_number);
  551. frame->limit = d->ptr;
  552. return true;
  553. }
  554. return false;
  555. }
  556. static bool upb_array_grow(upb_array *arr, size_t elements) {
  557. size_t needed = arr->len + elements;
  558. size_t new_size = UPB_MAX(arr->size, 8);
  559. size_t new_bytes;
  560. size_t old_bytes;
  561. void *new_data;
  562. upb_alloc *alloc = upb_arena_alloc(arr->arena);
  563. while (new_size < needed) {
  564. new_size *= 2;
  565. }
  566. old_bytes = arr->len * arr->element_size;
  567. new_bytes = new_size * arr->element_size;
  568. new_data = upb_realloc(alloc, arr->data, old_bytes, new_bytes);
  569. CHK(new_data);
  570. arr->data = new_data;
  571. arr->size = new_size;
  572. return true;
  573. }
  574. static void *upb_array_reserve(upb_array *arr, size_t elements) {
  575. if (arr->size - arr->len < elements) {
  576. CHK(upb_array_grow(arr, elements));
  577. }
  578. return (char*)arr->data + (arr->len * arr->element_size);
  579. }
  580. static void *upb_array_add(upb_array *arr, size_t elements) {
  581. void *ret = upb_array_reserve(arr, elements);
  582. arr->len += elements;
  583. return ret;
  584. }
  585. static upb_array *upb_getarr(upb_decframe *frame,
  586. const upb_msglayout_field *field) {
  587. UPB_ASSERT(field->label == UPB_LABEL_REPEATED);
  588. return *(upb_array**)&frame->msg[field->offset];
  589. }
  590. static upb_array *upb_getorcreatearr(upb_decframe *frame,
  591. const upb_msglayout_field *field) {
  592. upb_array *arr = upb_getarr(frame, field);
  593. if (!arr) {
  594. upb_fieldtype_t type = upb_desctype_to_fieldtype[field->descriptortype];
  595. arr = upb_array_new(type, upb_msg_arena(frame->msg));
  596. if (!arr) {
  597. return NULL;
  598. }
  599. *(upb_array**)&frame->msg[field->offset] = arr;
  600. }
  601. return arr;
  602. }
  603. static void upb_sethasbit(upb_decframe *frame,
  604. const upb_msglayout_field *field) {
  605. int32_t hasbit = field->presence;
  606. UPB_ASSERT(field->presence > 0);
  607. frame->msg[hasbit / 8] |= (1 << (hasbit % 8));
  608. }
  609. static void upb_setoneofcase(upb_decframe *frame,
  610. const upb_msglayout_field *field) {
  611. UPB_ASSERT(field->presence < 0);
  612. upb_set32(frame->msg, ~field->presence, field->number);
  613. }
  614. static char *upb_decode_prepareslot(upb_decframe *frame,
  615. const upb_msglayout_field *field) {
  616. char *field_mem = frame->msg + field->offset;
  617. upb_array *arr;
  618. if (field->label == UPB_LABEL_REPEATED) {
  619. arr = upb_getorcreatearr(frame, field);
  620. field_mem = upb_array_reserve(arr, 1);
  621. }
  622. return field_mem;
  623. }
  624. static void upb_decode_setpresent(upb_decframe *frame,
  625. const upb_msglayout_field *field) {
  626. if (field->label == UPB_LABEL_REPEATED) {
  627. upb_array *arr = upb_getarr(frame, field);
  628. UPB_ASSERT(arr->len < arr->size);
  629. arr->len++;
  630. } else if (field->presence < 0) {
  631. upb_setoneofcase(frame, field);
  632. } else if (field->presence > 0) {
  633. upb_sethasbit(frame, field);
  634. }
  635. }
  636. static bool upb_decode_submsg(upb_decstate *d, upb_decframe *frame,
  637. const char *limit,
  638. const upb_msglayout_field *field,
  639. int group_number) {
  640. char *submsg_slot = upb_decode_prepareslot(frame, field);
  641. char *submsg = *(void **)submsg_slot;
  642. const upb_msglayout *subm;
  643. subm = frame->m->submsgs[field->submsg_index];
  644. UPB_ASSERT(subm);
  645. if (!submsg) {
  646. submsg = upb_msg_new(subm, upb_msg_arena(frame->msg));
  647. CHK(submsg);
  648. *(void**)submsg_slot = submsg;
  649. }
  650. upb_decode_message(d, limit, group_number, submsg, subm);
  651. return true;
  652. }
  653. static bool upb_decode_varintfield(upb_decstate *d, upb_decframe *frame,
  654. const char *field_start,
  655. const upb_msglayout_field *field) {
  656. uint64_t val;
  657. void *field_mem;
  658. field_mem = upb_decode_prepareslot(frame, field);
  659. CHK(field_mem);
  660. CHK(upb_decode_varint(&d->ptr, frame->limit, &val));
  661. switch ((upb_descriptortype_t)field->descriptortype) {
  662. case UPB_DESCRIPTOR_TYPE_INT64:
  663. case UPB_DESCRIPTOR_TYPE_UINT64:
  664. memcpy(field_mem, &val, sizeof(val));
  665. break;
  666. case UPB_DESCRIPTOR_TYPE_INT32:
  667. case UPB_DESCRIPTOR_TYPE_UINT32:
  668. case UPB_DESCRIPTOR_TYPE_ENUM: {
  669. uint32_t val32 = val;
  670. memcpy(field_mem, &val32, sizeof(val32));
  671. break;
  672. }
  673. case UPB_DESCRIPTOR_TYPE_BOOL: {
  674. bool valbool = val != 0;
  675. memcpy(field_mem, &valbool, sizeof(valbool));
  676. break;
  677. }
  678. case UPB_DESCRIPTOR_TYPE_SINT32: {
  679. int32_t decoded = upb_zzdecode_32(val);
  680. memcpy(field_mem, &decoded, sizeof(decoded));
  681. break;
  682. }
  683. case UPB_DESCRIPTOR_TYPE_SINT64: {
  684. int64_t decoded = upb_zzdecode_64(val);
  685. memcpy(field_mem, &decoded, sizeof(decoded));
  686. break;
  687. }
  688. default:
  689. return upb_append_unknown(d, frame, field_start);
  690. }
  691. upb_decode_setpresent(frame, field);
  692. return true;
  693. }
  694. static bool upb_decode_64bitfield(upb_decstate *d, upb_decframe *frame,
  695. const char *field_start,
  696. const upb_msglayout_field *field) {
  697. void *field_mem;
  698. uint64_t val;
  699. field_mem = upb_decode_prepareslot(frame, field);
  700. CHK(field_mem);
  701. CHK(upb_decode_64bit(&d->ptr, frame->limit, &val));
  702. switch ((upb_descriptortype_t)field->descriptortype) {
  703. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  704. case UPB_DESCRIPTOR_TYPE_FIXED64:
  705. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  706. memcpy(field_mem, &val, sizeof(val));
  707. break;
  708. default:
  709. return upb_append_unknown(d, frame, field_start);
  710. }
  711. upb_decode_setpresent(frame, field);
  712. return true;
  713. }
  714. static bool upb_decode_32bitfield(upb_decstate *d, upb_decframe *frame,
  715. const char *field_start,
  716. const upb_msglayout_field *field) {
  717. void *field_mem;
  718. uint32_t val;
  719. field_mem = upb_decode_prepareslot(frame, field);
  720. CHK(field_mem);
  721. CHK(upb_decode_32bit(&d->ptr, frame->limit, &val));
  722. switch ((upb_descriptortype_t)field->descriptortype) {
  723. case UPB_DESCRIPTOR_TYPE_FLOAT:
  724. case UPB_DESCRIPTOR_TYPE_FIXED32:
  725. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  726. memcpy(field_mem, &val, sizeof(val));
  727. break;
  728. default:
  729. return upb_append_unknown(d, frame, field_start);
  730. }
  731. upb_decode_setpresent(frame, field);
  732. return true;
  733. }
  734. static bool upb_decode_fixedpacked(upb_array *arr, upb_strview data,
  735. int elem_size) {
  736. int elements = data.size / elem_size;
  737. void *field_mem;
  738. CHK((size_t)(elements * elem_size) == data.size);
  739. field_mem = upb_array_add(arr, elements);
  740. CHK(field_mem);
  741. memcpy(field_mem, data.data, data.size);
  742. return true;
  743. }
  744. static bool upb_decode_toarray(upb_decstate *d, upb_decframe *frame,
  745. const char *field_start,
  746. const upb_msglayout_field *field,
  747. upb_strview val) {
  748. upb_array *arr = upb_getorcreatearr(frame, field);
  749. #define VARINT_CASE(ctype, decode) { \
  750. const char *ptr = val.data; \
  751. const char *limit = ptr + val.size; \
  752. while (ptr < limit) { \
  753. uint64_t val; \
  754. void *field_mem; \
  755. ctype decoded; \
  756. CHK(upb_decode_varint(&ptr, limit, &val)); \
  757. decoded = (decode)(val); \
  758. field_mem = upb_array_add(arr, 1); \
  759. CHK(field_mem); \
  760. memcpy(field_mem, &decoded, sizeof(ctype)); \
  761. } \
  762. return true; \
  763. }
  764. switch ((upb_descriptortype_t)field->descriptortype) {
  765. case UPB_DESCRIPTOR_TYPE_STRING:
  766. case UPB_DESCRIPTOR_TYPE_BYTES: {
  767. void *field_mem = upb_array_add(arr, 1);
  768. CHK(field_mem);
  769. memcpy(field_mem, &val, sizeof(val));
  770. return true;
  771. }
  772. case UPB_DESCRIPTOR_TYPE_FLOAT:
  773. case UPB_DESCRIPTOR_TYPE_FIXED32:
  774. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  775. return upb_decode_fixedpacked(arr, val, sizeof(int32_t));
  776. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  777. case UPB_DESCRIPTOR_TYPE_FIXED64:
  778. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  779. return upb_decode_fixedpacked(arr, val, sizeof(int64_t));
  780. case UPB_DESCRIPTOR_TYPE_INT32:
  781. case UPB_DESCRIPTOR_TYPE_UINT32:
  782. case UPB_DESCRIPTOR_TYPE_ENUM:
  783. /* TODO: proto2 enum field that isn't in the enum. */
  784. VARINT_CASE(uint32_t, uint32_t);
  785. case UPB_DESCRIPTOR_TYPE_INT64:
  786. case UPB_DESCRIPTOR_TYPE_UINT64:
  787. VARINT_CASE(uint64_t, uint64_t);
  788. case UPB_DESCRIPTOR_TYPE_BOOL:
  789. VARINT_CASE(bool, bool);
  790. case UPB_DESCRIPTOR_TYPE_SINT32:
  791. VARINT_CASE(int32_t, upb_zzdecode_32);
  792. case UPB_DESCRIPTOR_TYPE_SINT64:
  793. VARINT_CASE(int64_t, upb_zzdecode_64);
  794. case UPB_DESCRIPTOR_TYPE_MESSAGE: {
  795. const upb_msglayout *subm;
  796. char *submsg;
  797. void *field_mem;
  798. CHK(val.size <= (size_t)(frame->limit - val.data));
  799. d->ptr -= val.size;
  800. /* Create elemente message. */
  801. subm = frame->m->submsgs[field->submsg_index];
  802. UPB_ASSERT(subm);
  803. submsg = upb_msg_new(subm, upb_msg_arena(frame->msg));
  804. CHK(submsg);
  805. field_mem = upb_array_add(arr, 1);
  806. CHK(field_mem);
  807. *(void**)field_mem = submsg;
  808. return upb_decode_message(
  809. d, val.data + val.size, frame->group_number, submsg, subm);
  810. }
  811. case UPB_DESCRIPTOR_TYPE_GROUP:
  812. return upb_append_unknown(d, frame, field_start);
  813. }
  814. #undef VARINT_CASE
  815. UPB_UNREACHABLE();
  816. }
  817. static bool upb_decode_delimitedfield(upb_decstate *d, upb_decframe *frame,
  818. const char *field_start,
  819. const upb_msglayout_field *field) {
  820. upb_strview val;
  821. CHK(upb_decode_string(&d->ptr, frame->limit, &val));
  822. if (field->label == UPB_LABEL_REPEATED) {
  823. return upb_decode_toarray(d, frame, field_start, field, val);
  824. } else {
  825. switch ((upb_descriptortype_t)field->descriptortype) {
  826. case UPB_DESCRIPTOR_TYPE_STRING:
  827. case UPB_DESCRIPTOR_TYPE_BYTES: {
  828. void *field_mem = upb_decode_prepareslot(frame, field);
  829. CHK(field_mem);
  830. memcpy(field_mem, &val, sizeof(val));
  831. break;
  832. }
  833. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  834. CHK(val.size <= (size_t)(frame->limit - val.data));
  835. d->ptr -= val.size;
  836. CHK(upb_decode_submsg(d, frame, val.data + val.size, field, 0));
  837. break;
  838. default:
  839. /* TODO(haberman): should we accept the last element of a packed? */
  840. return upb_append_unknown(d, frame, field_start);
  841. }
  842. upb_decode_setpresent(frame, field);
  843. return true;
  844. }
  845. }
  846. static const upb_msglayout_field *upb_find_field(const upb_msglayout *l,
  847. uint32_t field_number) {
  848. /* Lots of optimization opportunities here. */
  849. int i;
  850. for (i = 0; i < l->field_count; i++) {
  851. if (l->fields[i].number == field_number) {
  852. return &l->fields[i];
  853. }
  854. }
  855. return NULL; /* Unknown field. */
  856. }
  857. static bool upb_decode_field(upb_decstate *d, upb_decframe *frame) {
  858. int field_number;
  859. int wire_type;
  860. const char *field_start = d->ptr;
  861. const upb_msglayout_field *field;
  862. CHK(upb_decode_tag(&d->ptr, frame->limit, &field_number, &wire_type));
  863. field = upb_find_field(frame->m, field_number);
  864. if (field) {
  865. switch (wire_type) {
  866. case UPB_WIRE_TYPE_VARINT:
  867. return upb_decode_varintfield(d, frame, field_start, field);
  868. case UPB_WIRE_TYPE_32BIT:
  869. return upb_decode_32bitfield(d, frame, field_start, field);
  870. case UPB_WIRE_TYPE_64BIT:
  871. return upb_decode_64bitfield(d, frame, field_start, field);
  872. case UPB_WIRE_TYPE_DELIMITED:
  873. return upb_decode_delimitedfield(d, frame, field_start, field);
  874. case UPB_WIRE_TYPE_START_GROUP:
  875. CHK(field->descriptortype == UPB_DESCRIPTOR_TYPE_GROUP);
  876. return upb_decode_submsg(d, frame, frame->limit, field, field_number);
  877. case UPB_WIRE_TYPE_END_GROUP:
  878. CHK(frame->group_number == field_number)
  879. frame->limit = d->ptr;
  880. return true;
  881. default:
  882. return false;
  883. }
  884. } else {
  885. CHK(field_number != 0);
  886. CHK(upb_skip_unknownfielddata(d, frame, field_number, wire_type));
  887. CHK(upb_append_unknown(d, frame, field_start));
  888. return true;
  889. }
  890. }
  891. static bool upb_skip_unknowngroup(upb_decstate *d, int field_number,
  892. const char *limit) {
  893. upb_decframe frame;
  894. frame.msg = NULL;
  895. frame.m = NULL;
  896. frame.group_number = field_number;
  897. frame.limit = limit;
  898. while (d->ptr < frame.limit) {
  899. int wire_type;
  900. int field_number;
  901. CHK(upb_decode_tag(&d->ptr, frame.limit, &field_number, &wire_type));
  902. CHK(upb_skip_unknownfielddata(d, &frame, field_number, wire_type));
  903. }
  904. return true;
  905. }
  906. static bool upb_decode_message(upb_decstate *d, const char *limit,
  907. int group_number, char *msg,
  908. const upb_msglayout *l) {
  909. upb_decframe frame;
  910. frame.group_number = group_number;
  911. frame.limit = limit;
  912. frame.msg = msg;
  913. frame.m = l;
  914. while (d->ptr < frame.limit) {
  915. CHK(upb_decode_field(d, &frame));
  916. }
  917. return true;
  918. }
  919. bool upb_decode(upb_strview buf, void *msg, const upb_msglayout *l) {
  920. upb_decstate state;
  921. state.ptr = buf.data;
  922. return upb_decode_message(&state, buf.data + buf.size, 0, msg, l);
  923. }
  924. #undef CHK
  925. #include <ctype.h>
  926. #include <stdlib.h>
  927. #include <string.h>
  928. typedef struct {
  929. size_t len;
  930. char str[1]; /* Null-terminated string data follows. */
  931. } str_t;
  932. static str_t *newstr(const char *data, size_t len) {
  933. str_t *ret = upb_gmalloc(sizeof(*ret) + len);
  934. if (!ret) return NULL;
  935. ret->len = len;
  936. memcpy(ret->str, data, len);
  937. ret->str[len] = '\0';
  938. return ret;
  939. }
  940. static void freestr(str_t *s) { upb_gfree(s); }
  941. /* isalpha() etc. from <ctype.h> are locale-dependent, which we don't want. */
  942. static bool upb_isbetween(char c, char low, char high) {
  943. return c >= low && c <= high;
  944. }
  945. static bool upb_isletter(char c) {
  946. return upb_isbetween(c, 'A', 'Z') || upb_isbetween(c, 'a', 'z') || c == '_';
  947. }
  948. static bool upb_isalphanum(char c) {
  949. return upb_isletter(c) || upb_isbetween(c, '0', '9');
  950. }
  951. static bool upb_isident(const char *str, size_t len, bool full, upb_status *s) {
  952. bool start = true;
  953. size_t i;
  954. for (i = 0; i < len; i++) {
  955. char c = str[i];
  956. if (c == '.') {
  957. if (start || !full) {
  958. upb_status_seterrf(s, "invalid name: unexpected '.' (%s)", str);
  959. return false;
  960. }
  961. start = true;
  962. } else if (start) {
  963. if (!upb_isletter(c)) {
  964. upb_status_seterrf(
  965. s, "invalid name: path components must start with a letter (%s)",
  966. str);
  967. return false;
  968. }
  969. start = false;
  970. } else {
  971. if (!upb_isalphanum(c)) {
  972. upb_status_seterrf(s, "invalid name: non-alphanumeric character (%s)",
  973. str);
  974. return false;
  975. }
  976. }
  977. }
  978. return !start;
  979. }
  980. static bool upb_isoneof(const upb_refcounted *def) {
  981. return def->vtbl == &upb_oneofdef_vtbl;
  982. }
  983. static bool upb_isfield(const upb_refcounted *def) {
  984. return def->vtbl == &upb_fielddef_vtbl;
  985. }
  986. static const upb_oneofdef *upb_trygetoneof(const upb_refcounted *def) {
  987. return upb_isoneof(def) ? (const upb_oneofdef*)def : NULL;
  988. }
  989. static const upb_fielddef *upb_trygetfield(const upb_refcounted *def) {
  990. return upb_isfield(def) ? (const upb_fielddef*)def : NULL;
  991. }
  992. /* upb_def ********************************************************************/
  993. upb_deftype_t upb_def_type(const upb_def *d) { return d->type; }
  994. const char *upb_def_fullname(const upb_def *d) { return d->fullname; }
  995. const char *upb_def_name(const upb_def *d) {
  996. const char *p;
  997. if (d->fullname == NULL) {
  998. return NULL;
  999. } else if ((p = strrchr(d->fullname, '.')) == NULL) {
  1000. /* No '.' in the name, return the full string. */
  1001. return d->fullname;
  1002. } else {
  1003. /* Return one past the last '.'. */
  1004. return p + 1;
  1005. }
  1006. }
  1007. bool upb_def_setfullname(upb_def *def, const char *fullname, upb_status *s) {
  1008. UPB_ASSERT(!upb_def_isfrozen(def));
  1009. if (!upb_isident(fullname, strlen(fullname), true, s)) {
  1010. return false;
  1011. }
  1012. fullname = upb_gstrdup(fullname);
  1013. if (!fullname) {
  1014. upb_upberr_setoom(s);
  1015. return false;
  1016. }
  1017. upb_gfree((void*)def->fullname);
  1018. def->fullname = fullname;
  1019. return true;
  1020. }
  1021. const upb_filedef *upb_def_file(const upb_def *d) { return d->file; }
  1022. static bool upb_def_init(upb_def *def, upb_deftype_t type,
  1023. const struct upb_refcounted_vtbl *vtbl,
  1024. const void *owner) {
  1025. if (!upb_refcounted_init(upb_def_upcast_mutable(def), vtbl, owner)) return false;
  1026. def->type = type;
  1027. def->fullname = NULL;
  1028. def->came_from_user = false;
  1029. def->file = NULL;
  1030. return true;
  1031. }
  1032. static void upb_def_uninit(upb_def *def) {
  1033. upb_gfree((void*)def->fullname);
  1034. }
  1035. static const char *msgdef_name(const upb_msgdef *m) {
  1036. const char *name = upb_def_fullname(upb_msgdef_upcast(m));
  1037. return name ? name : "(anonymous)";
  1038. }
  1039. static bool upb_validate_field(upb_fielddef *f, upb_status *s) {
  1040. if (upb_fielddef_name(f) == NULL || upb_fielddef_number(f) == 0) {
  1041. upb_status_seterrmsg(s, "fielddef must have name and number set");
  1042. return false;
  1043. }
  1044. if (!f->type_is_set_) {
  1045. upb_status_seterrmsg(s, "fielddef type was not initialized");
  1046. return false;
  1047. }
  1048. if (upb_fielddef_lazy(f) &&
  1049. upb_fielddef_descriptortype(f) != UPB_DESCRIPTOR_TYPE_MESSAGE) {
  1050. upb_status_seterrmsg(s,
  1051. "only length-delimited submessage fields may be lazy");
  1052. return false;
  1053. }
  1054. if (upb_fielddef_hassubdef(f)) {
  1055. const upb_def *subdef;
  1056. if (f->subdef_is_symbolic) {
  1057. upb_status_seterrf(s, "field '%s.%s' has not been resolved",
  1058. msgdef_name(f->msg.def), upb_fielddef_name(f));
  1059. return false;
  1060. }
  1061. subdef = upb_fielddef_subdef(f);
  1062. if (subdef == NULL) {
  1063. upb_status_seterrf(s, "field %s.%s is missing required subdef",
  1064. msgdef_name(f->msg.def), upb_fielddef_name(f));
  1065. return false;
  1066. }
  1067. if (!upb_def_isfrozen(subdef) && !subdef->came_from_user) {
  1068. upb_status_seterrf(s,
  1069. "subdef of field %s.%s is not frozen or being frozen",
  1070. msgdef_name(f->msg.def), upb_fielddef_name(f));
  1071. return false;
  1072. }
  1073. }
  1074. if (upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  1075. bool has_default_name = upb_fielddef_enumhasdefaultstr(f);
  1076. bool has_default_number = upb_fielddef_enumhasdefaultint32(f);
  1077. /* Previously verified by upb_validate_enumdef(). */
  1078. UPB_ASSERT(upb_enumdef_numvals(upb_fielddef_enumsubdef(f)) > 0);
  1079. /* We've already validated that we have an associated enumdef and that it
  1080. * has at least one member, so at least one of these should be true.
  1081. * Because if the user didn't set anything, we'll pick up the enum's
  1082. * default, but if the user *did* set something we should at least pick up
  1083. * the one they set (int32 or string). */
  1084. UPB_ASSERT(has_default_name || has_default_number);
  1085. if (!has_default_name) {
  1086. upb_status_seterrf(s,
  1087. "enum default for field %s.%s (%d) is not in the enum",
  1088. msgdef_name(f->msg.def), upb_fielddef_name(f),
  1089. upb_fielddef_defaultint32(f));
  1090. return false;
  1091. }
  1092. if (!has_default_number) {
  1093. upb_status_seterrf(s,
  1094. "enum default for field %s.%s (%s) is not in the enum",
  1095. msgdef_name(f->msg.def), upb_fielddef_name(f),
  1096. upb_fielddef_defaultstr(f, NULL));
  1097. return false;
  1098. }
  1099. /* Lift the effective numeric default into the field's default slot, in case
  1100. * we were only getting it "by reference" from the enumdef. */
  1101. upb_fielddef_setdefaultint32(f, upb_fielddef_defaultint32(f));
  1102. }
  1103. /* Ensure that MapEntry submessages only appear as repeated fields, not
  1104. * optional/required (singular) fields. */
  1105. if (upb_fielddef_type(f) == UPB_TYPE_MESSAGE &&
  1106. upb_fielddef_msgsubdef(f) != NULL) {
  1107. const upb_msgdef *subdef = upb_fielddef_msgsubdef(f);
  1108. if (upb_msgdef_mapentry(subdef) && !upb_fielddef_isseq(f)) {
  1109. upb_status_seterrf(s,
  1110. "Field %s refers to mapentry message but is not "
  1111. "a repeated field",
  1112. upb_fielddef_name(f) ? upb_fielddef_name(f) :
  1113. "(unnamed)");
  1114. return false;
  1115. }
  1116. }
  1117. return true;
  1118. }
  1119. static bool upb_validate_enumdef(const upb_enumdef *e, upb_status *s) {
  1120. if (upb_enumdef_numvals(e) == 0) {
  1121. upb_status_seterrf(s, "enum %s has no members (must have at least one)",
  1122. upb_enumdef_fullname(e));
  1123. return false;
  1124. }
  1125. return true;
  1126. }
  1127. /* All submessage fields are lower than all other fields.
  1128. * Secondly, fields are increasing in order. */
  1129. uint32_t field_rank(const upb_fielddef *f) {
  1130. uint32_t ret = upb_fielddef_number(f);
  1131. const uint32_t high_bit = 1 << 30;
  1132. UPB_ASSERT(ret < high_bit);
  1133. if (!upb_fielddef_issubmsg(f))
  1134. ret |= high_bit;
  1135. return ret;
  1136. }
  1137. int cmp_fields(const void *p1, const void *p2) {
  1138. const upb_fielddef *f1 = *(upb_fielddef*const*)p1;
  1139. const upb_fielddef *f2 = *(upb_fielddef*const*)p2;
  1140. return field_rank(f1) - field_rank(f2);
  1141. }
  1142. static bool assign_msg_indices(upb_msgdef *m, upb_status *s) {
  1143. /* Sort fields. upb internally relies on UPB_TYPE_MESSAGE fields having the
  1144. * lowest indexes, but we do not publicly guarantee this. */
  1145. upb_msg_field_iter j;
  1146. upb_msg_oneof_iter k;
  1147. int i;
  1148. uint32_t selector;
  1149. int n = upb_msgdef_numfields(m);
  1150. upb_fielddef **fields;
  1151. if (n == 0) {
  1152. m->selector_count = UPB_STATIC_SELECTOR_COUNT;
  1153. m->submsg_field_count = 0;
  1154. return true;
  1155. }
  1156. fields = upb_gmalloc(n * sizeof(*fields));
  1157. if (!fields) {
  1158. upb_upberr_setoom(s);
  1159. return false;
  1160. }
  1161. m->submsg_field_count = 0;
  1162. for(i = 0, upb_msg_field_begin(&j, m);
  1163. !upb_msg_field_done(&j);
  1164. upb_msg_field_next(&j), i++) {
  1165. upb_fielddef *f = upb_msg_iter_field(&j);
  1166. UPB_ASSERT(f->msg.def == m);
  1167. if (!upb_validate_field(f, s)) {
  1168. upb_gfree(fields);
  1169. return false;
  1170. }
  1171. if (upb_fielddef_issubmsg(f)) {
  1172. m->submsg_field_count++;
  1173. }
  1174. fields[i] = f;
  1175. }
  1176. qsort(fields, n, sizeof(*fields), cmp_fields);
  1177. selector = UPB_STATIC_SELECTOR_COUNT + m->submsg_field_count;
  1178. for (i = 0; i < n; i++) {
  1179. upb_fielddef *f = fields[i];
  1180. f->index_ = i;
  1181. f->selector_base = selector + upb_handlers_selectorbaseoffset(f);
  1182. selector += upb_handlers_selectorcount(f);
  1183. }
  1184. m->selector_count = selector;
  1185. #ifndef NDEBUG
  1186. {
  1187. /* Verify that all selectors for the message are distinct. */
  1188. #define TRY(type) \
  1189. if (upb_handlers_getselector(f, type, &sel)) upb_inttable_insert(&t, sel, v);
  1190. upb_inttable t;
  1191. upb_value v;
  1192. upb_selector_t sel;
  1193. upb_inttable_init(&t, UPB_CTYPE_BOOL);
  1194. v = upb_value_bool(true);
  1195. upb_inttable_insert(&t, UPB_STARTMSG_SELECTOR, v);
  1196. upb_inttable_insert(&t, UPB_ENDMSG_SELECTOR, v);
  1197. upb_inttable_insert(&t, UPB_UNKNOWN_SELECTOR, v);
  1198. for(upb_msg_field_begin(&j, m);
  1199. !upb_msg_field_done(&j);
  1200. upb_msg_field_next(&j)) {
  1201. upb_fielddef *f = upb_msg_iter_field(&j);
  1202. /* These calls will assert-fail in upb_table if the value already
  1203. * exists. */
  1204. TRY(UPB_HANDLER_INT32);
  1205. TRY(UPB_HANDLER_INT64)
  1206. TRY(UPB_HANDLER_UINT32)
  1207. TRY(UPB_HANDLER_UINT64)
  1208. TRY(UPB_HANDLER_FLOAT)
  1209. TRY(UPB_HANDLER_DOUBLE)
  1210. TRY(UPB_HANDLER_BOOL)
  1211. TRY(UPB_HANDLER_STARTSTR)
  1212. TRY(UPB_HANDLER_STRING)
  1213. TRY(UPB_HANDLER_ENDSTR)
  1214. TRY(UPB_HANDLER_STARTSUBMSG)
  1215. TRY(UPB_HANDLER_ENDSUBMSG)
  1216. TRY(UPB_HANDLER_STARTSEQ)
  1217. TRY(UPB_HANDLER_ENDSEQ)
  1218. }
  1219. upb_inttable_uninit(&t);
  1220. }
  1221. #undef TRY
  1222. #endif
  1223. for(upb_msg_oneof_begin(&k, m), i = 0;
  1224. !upb_msg_oneof_done(&k);
  1225. upb_msg_oneof_next(&k), i++) {
  1226. upb_oneofdef *o = upb_msg_iter_oneof(&k);
  1227. o->index = i;
  1228. }
  1229. upb_gfree(fields);
  1230. return true;
  1231. }
  1232. static void assign_msg_wellknowntype(upb_msgdef *m) {
  1233. const char *name = upb_msgdef_fullname(m);
  1234. if (name == NULL) {
  1235. m->well_known_type = UPB_WELLKNOWN_UNSPECIFIED;
  1236. return;
  1237. }
  1238. if (!strcmp(name, "google.protobuf.Any")) {
  1239. m->well_known_type = UPB_WELLKNOWN_ANY;
  1240. } else if (!strcmp(name, "google.protobuf.FieldMask")) {
  1241. m->well_known_type = UPB_WELLKNOWN_FIELDMASK;
  1242. } else if (!strcmp(name, "google.protobuf.Duration")) {
  1243. m->well_known_type = UPB_WELLKNOWN_DURATION;
  1244. } else if (!strcmp(name, "google.protobuf.Timestamp")) {
  1245. m->well_known_type = UPB_WELLKNOWN_TIMESTAMP;
  1246. } else if (!strcmp(name, "google.protobuf.DoubleValue")) {
  1247. m->well_known_type = UPB_WELLKNOWN_DOUBLEVALUE;
  1248. } else if (!strcmp(name, "google.protobuf.FloatValue")) {
  1249. m->well_known_type = UPB_WELLKNOWN_FLOATVALUE;
  1250. } else if (!strcmp(name, "google.protobuf.Int64Value")) {
  1251. m->well_known_type = UPB_WELLKNOWN_INT64VALUE;
  1252. } else if (!strcmp(name, "google.protobuf.UInt64Value")) {
  1253. m->well_known_type = UPB_WELLKNOWN_UINT64VALUE;
  1254. } else if (!strcmp(name, "google.protobuf.Int32Value")) {
  1255. m->well_known_type = UPB_WELLKNOWN_INT32VALUE;
  1256. } else if (!strcmp(name, "google.protobuf.UInt32Value")) {
  1257. m->well_known_type = UPB_WELLKNOWN_UINT32VALUE;
  1258. } else if (!strcmp(name, "google.protobuf.BoolValue")) {
  1259. m->well_known_type = UPB_WELLKNOWN_BOOLVALUE;
  1260. } else if (!strcmp(name, "google.protobuf.StringValue")) {
  1261. m->well_known_type = UPB_WELLKNOWN_STRINGVALUE;
  1262. } else if (!strcmp(name, "google.protobuf.BytesValue")) {
  1263. m->well_known_type = UPB_WELLKNOWN_BYTESVALUE;
  1264. } else if (!strcmp(name, "google.protobuf.Value")) {
  1265. m->well_known_type = UPB_WELLKNOWN_VALUE;
  1266. } else if (!strcmp(name, "google.protobuf.ListValue")) {
  1267. m->well_known_type = UPB_WELLKNOWN_LISTVALUE;
  1268. } else if (!strcmp(name, "google.protobuf.Struct")) {
  1269. m->well_known_type = UPB_WELLKNOWN_STRUCT;
  1270. } else {
  1271. m->well_known_type = UPB_WELLKNOWN_UNSPECIFIED;
  1272. }
  1273. }
  1274. bool _upb_def_validate(upb_def *const*defs, size_t n, upb_status *s) {
  1275. size_t i;
  1276. /* First perform validation, in two passes so we can check that we have a
  1277. * transitive closure without needing to search. */
  1278. for (i = 0; i < n; i++) {
  1279. upb_def *def = defs[i];
  1280. if (upb_def_isfrozen(def)) {
  1281. /* Could relax this requirement if it's annoying. */
  1282. upb_status_seterrmsg(s, "def is already frozen");
  1283. goto err;
  1284. } else if (def->type == UPB_DEF_FIELD) {
  1285. upb_status_seterrmsg(s, "standalone fielddefs can not be frozen");
  1286. goto err;
  1287. } else {
  1288. /* Set now to detect transitive closure in the second pass. */
  1289. def->came_from_user = true;
  1290. if (def->type == UPB_DEF_ENUM &&
  1291. !upb_validate_enumdef(upb_dyncast_enumdef(def), s)) {
  1292. goto err;
  1293. }
  1294. }
  1295. }
  1296. /* Second pass of validation. Also assign selector bases and indexes, and
  1297. * compact tables. */
  1298. for (i = 0; i < n; i++) {
  1299. upb_def *def = defs[i];
  1300. upb_msgdef *m = upb_dyncast_msgdef_mutable(def);
  1301. upb_enumdef *e = upb_dyncast_enumdef_mutable(def);
  1302. if (m) {
  1303. upb_inttable_compact(&m->itof);
  1304. if (!assign_msg_indices(m, s)) {
  1305. goto err;
  1306. }
  1307. assign_msg_wellknowntype(m);
  1308. /* m->well_known_type = UPB_WELLKNOWN_UNSPECIFIED; */
  1309. } else if (e) {
  1310. upb_inttable_compact(&e->iton);
  1311. }
  1312. }
  1313. return true;
  1314. err:
  1315. for (i = 0; i < n; i++) {
  1316. upb_def *def = defs[i];
  1317. def->came_from_user = false;
  1318. }
  1319. UPB_ASSERT(!(s && upb_ok(s)));
  1320. return false;
  1321. }
  1322. bool upb_def_freeze(upb_def *const* defs, size_t n, upb_status *s) {
  1323. /* Def graph contains FieldDefs between each MessageDef, so double the
  1324. * limit. */
  1325. const size_t maxdepth = UPB_MAX_MESSAGE_DEPTH * 2;
  1326. if (!_upb_def_validate(defs, n, s)) {
  1327. return false;
  1328. }
  1329. /* Validation all passed; freeze the objects. */
  1330. return upb_refcounted_freeze((upb_refcounted *const*)defs, n, s, maxdepth);
  1331. }
  1332. /* upb_enumdef ****************************************************************/
  1333. static void visitenum(const upb_refcounted *r, upb_refcounted_visit *visit,
  1334. void *closure) {
  1335. const upb_enumdef *e = (const upb_enumdef*)r;
  1336. const upb_def *def = upb_enumdef_upcast(e);
  1337. if (upb_def_file(def)) {
  1338. visit(r, upb_filedef_upcast(upb_def_file(def)), closure);
  1339. }
  1340. }
  1341. static void freeenum(upb_refcounted *r) {
  1342. upb_enumdef *e = (upb_enumdef*)r;
  1343. upb_inttable_iter i;
  1344. upb_inttable_begin(&i, &e->iton);
  1345. for( ; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  1346. /* To clean up the upb_gstrdup() from upb_enumdef_addval(). */
  1347. upb_gfree(upb_value_getcstr(upb_inttable_iter_value(&i)));
  1348. }
  1349. upb_strtable_uninit(&e->ntoi);
  1350. upb_inttable_uninit(&e->iton);
  1351. upb_def_uninit(upb_enumdef_upcast_mutable(e));
  1352. upb_gfree(e);
  1353. }
  1354. const struct upb_refcounted_vtbl upb_enumdef_vtbl = {&visitenum, &freeenum};
  1355. upb_enumdef *upb_enumdef_new(const void *owner) {
  1356. upb_enumdef *e = upb_gmalloc(sizeof(*e));
  1357. if (!e) return NULL;
  1358. if (!upb_def_init(upb_enumdef_upcast_mutable(e), UPB_DEF_ENUM,
  1359. &upb_enumdef_vtbl, owner)) {
  1360. goto err2;
  1361. }
  1362. if (!upb_strtable_init(&e->ntoi, UPB_CTYPE_INT32)) goto err2;
  1363. if (!upb_inttable_init(&e->iton, UPB_CTYPE_CSTR)) goto err1;
  1364. return e;
  1365. err1:
  1366. upb_strtable_uninit(&e->ntoi);
  1367. err2:
  1368. upb_gfree(e);
  1369. return NULL;
  1370. }
  1371. bool upb_enumdef_freeze(upb_enumdef *e, upb_status *status) {
  1372. upb_def *d = upb_enumdef_upcast_mutable(e);
  1373. return upb_def_freeze(&d, 1, status);
  1374. }
  1375. const char *upb_enumdef_fullname(const upb_enumdef *e) {
  1376. return upb_def_fullname(upb_enumdef_upcast(e));
  1377. }
  1378. const char *upb_enumdef_name(const upb_enumdef *e) {
  1379. return upb_def_name(upb_enumdef_upcast(e));
  1380. }
  1381. bool upb_enumdef_setfullname(upb_enumdef *e, const char *fullname,
  1382. upb_status *s) {
  1383. return upb_def_setfullname(upb_enumdef_upcast_mutable(e), fullname, s);
  1384. }
  1385. bool upb_enumdef_addval(upb_enumdef *e, const char *name, int32_t num,
  1386. upb_status *status) {
  1387. char *name2;
  1388. if (!upb_isident(name, strlen(name), false, status)) {
  1389. return false;
  1390. }
  1391. if (upb_enumdef_ntoiz(e, name, NULL)) {
  1392. upb_status_seterrf(status, "name '%s' is already defined", name);
  1393. return false;
  1394. }
  1395. if (!upb_strtable_insert(&e->ntoi, name, upb_value_int32(num))) {
  1396. upb_status_seterrmsg(status, "out of memory");
  1397. return false;
  1398. }
  1399. if (!upb_inttable_lookup(&e->iton, num, NULL)) {
  1400. name2 = upb_gstrdup(name);
  1401. if (!name2 || !upb_inttable_insert(&e->iton, num, upb_value_cstr(name2))) {
  1402. upb_status_seterrmsg(status, "out of memory");
  1403. upb_strtable_remove(&e->ntoi, name, NULL);
  1404. return false;
  1405. }
  1406. }
  1407. if (upb_enumdef_numvals(e) == 1) {
  1408. bool ok = upb_enumdef_setdefault(e, num, NULL);
  1409. UPB_ASSERT(ok);
  1410. }
  1411. return true;
  1412. }
  1413. int32_t upb_enumdef_default(const upb_enumdef *e) {
  1414. UPB_ASSERT(upb_enumdef_iton(e, e->defaultval));
  1415. return e->defaultval;
  1416. }
  1417. bool upb_enumdef_setdefault(upb_enumdef *e, int32_t val, upb_status *s) {
  1418. UPB_ASSERT(!upb_enumdef_isfrozen(e));
  1419. if (!upb_enumdef_iton(e, val)) {
  1420. upb_status_seterrf(s, "number '%d' is not in the enum.", val);
  1421. return false;
  1422. }
  1423. e->defaultval = val;
  1424. return true;
  1425. }
  1426. int upb_enumdef_numvals(const upb_enumdef *e) {
  1427. return upb_strtable_count(&e->ntoi);
  1428. }
  1429. void upb_enum_begin(upb_enum_iter *i, const upb_enumdef *e) {
  1430. /* We iterate over the ntoi table, to account for duplicate numbers. */
  1431. upb_strtable_begin(i, &e->ntoi);
  1432. }
  1433. void upb_enum_next(upb_enum_iter *iter) { upb_strtable_next(iter); }
  1434. bool upb_enum_done(upb_enum_iter *iter) { return upb_strtable_done(iter); }
  1435. bool upb_enumdef_ntoi(const upb_enumdef *def, const char *name,
  1436. size_t len, int32_t *num) {
  1437. upb_value v;
  1438. if (!upb_strtable_lookup2(&def->ntoi, name, len, &v)) {
  1439. return false;
  1440. }
  1441. if (num) *num = upb_value_getint32(v);
  1442. return true;
  1443. }
  1444. const char *upb_enumdef_iton(const upb_enumdef *def, int32_t num) {
  1445. upb_value v;
  1446. return upb_inttable_lookup32(&def->iton, num, &v) ?
  1447. upb_value_getcstr(v) : NULL;
  1448. }
  1449. const char *upb_enum_iter_name(upb_enum_iter *iter) {
  1450. return upb_strtable_iter_key(iter);
  1451. }
  1452. int32_t upb_enum_iter_number(upb_enum_iter *iter) {
  1453. return upb_value_getint32(upb_strtable_iter_value(iter));
  1454. }
  1455. /* upb_fielddef ***************************************************************/
  1456. static void upb_fielddef_init_default(upb_fielddef *f);
  1457. static void upb_fielddef_uninit_default(upb_fielddef *f) {
  1458. if (f->type_is_set_ && f->default_is_string && f->defaultval.bytes)
  1459. freestr(f->defaultval.bytes);
  1460. }
  1461. const char *upb_fielddef_fullname(const upb_fielddef *e) {
  1462. return upb_def_fullname(upb_fielddef_upcast(e));
  1463. }
  1464. static void visitfield(const upb_refcounted *r, upb_refcounted_visit *visit,
  1465. void *closure) {
  1466. const upb_fielddef *f = (const upb_fielddef*)r;
  1467. const upb_def *def = upb_fielddef_upcast(f);
  1468. if (upb_fielddef_containingtype(f)) {
  1469. visit(r, upb_msgdef_upcast2(upb_fielddef_containingtype(f)), closure);
  1470. }
  1471. if (upb_fielddef_containingoneof(f)) {
  1472. visit(r, upb_oneofdef_upcast(upb_fielddef_containingoneof(f)), closure);
  1473. }
  1474. if (upb_fielddef_subdef(f)) {
  1475. visit(r, upb_def_upcast(upb_fielddef_subdef(f)), closure);
  1476. }
  1477. if (upb_def_file(def)) {
  1478. visit(r, upb_filedef_upcast(upb_def_file(def)), closure);
  1479. }
  1480. }
  1481. static void freefield(upb_refcounted *r) {
  1482. upb_fielddef *f = (upb_fielddef*)r;
  1483. upb_fielddef_uninit_default(f);
  1484. if (f->subdef_is_symbolic)
  1485. upb_gfree(f->sub.name);
  1486. if (f->msg_is_symbolic)
  1487. upb_gfree(f->msg.name);
  1488. upb_def_uninit(upb_fielddef_upcast_mutable(f));
  1489. upb_gfree(f);
  1490. }
  1491. static const char *enumdefaultstr(const upb_fielddef *f) {
  1492. const upb_enumdef *e;
  1493. UPB_ASSERT(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  1494. e = upb_fielddef_enumsubdef(f);
  1495. if (f->default_is_string && f->defaultval.bytes) {
  1496. /* Default was explicitly set as a string. */
  1497. str_t *s = f->defaultval.bytes;
  1498. return s->str;
  1499. } else if (e) {
  1500. if (!f->default_is_string) {
  1501. /* Default was explicitly set as an integer; look it up in enumdef. */
  1502. const char *name = upb_enumdef_iton(e, f->defaultval.sint);
  1503. if (name) {
  1504. return name;
  1505. }
  1506. } else {
  1507. /* Default is completely unset; pull enumdef default. */
  1508. if (upb_enumdef_numvals(e) > 0) {
  1509. const char *name = upb_enumdef_iton(e, upb_enumdef_default(e));
  1510. UPB_ASSERT(name);
  1511. return name;
  1512. }
  1513. }
  1514. }
  1515. return NULL;
  1516. }
  1517. static bool enumdefaultint32(const upb_fielddef *f, int32_t *val) {
  1518. const upb_enumdef *e;
  1519. UPB_ASSERT(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  1520. e = upb_fielddef_enumsubdef(f);
  1521. if (!f->default_is_string) {
  1522. /* Default was explicitly set as an integer. */
  1523. *val = f->defaultval.sint;
  1524. return true;
  1525. } else if (e) {
  1526. if (f->defaultval.bytes) {
  1527. /* Default was explicitly set as a str; try to lookup corresponding int. */
  1528. str_t *s = f->defaultval.bytes;
  1529. if (upb_enumdef_ntoiz(e, s->str, val)) {
  1530. return true;
  1531. }
  1532. } else {
  1533. /* Default is unset; try to pull in enumdef default. */
  1534. if (upb_enumdef_numvals(e) > 0) {
  1535. *val = upb_enumdef_default(e);
  1536. return true;
  1537. }
  1538. }
  1539. }
  1540. return false;
  1541. }
  1542. const struct upb_refcounted_vtbl upb_fielddef_vtbl = {visitfield, freefield};
  1543. upb_fielddef *upb_fielddef_new(const void *o) {
  1544. upb_fielddef *f = upb_gmalloc(sizeof(*f));
  1545. if (!f) return NULL;
  1546. if (!upb_def_init(upb_fielddef_upcast_mutable(f), UPB_DEF_FIELD,
  1547. &upb_fielddef_vtbl, o)) {
  1548. upb_gfree(f);
  1549. return NULL;
  1550. }
  1551. f->msg.def = NULL;
  1552. f->sub.def = NULL;
  1553. f->oneof = NULL;
  1554. f->subdef_is_symbolic = false;
  1555. f->msg_is_symbolic = false;
  1556. f->label_ = UPB_LABEL_OPTIONAL;
  1557. f->type_ = UPB_TYPE_INT32;
  1558. f->number_ = 0;
  1559. f->type_is_set_ = false;
  1560. f->tagdelim = false;
  1561. f->is_extension_ = false;
  1562. f->lazy_ = false;
  1563. f->packed_ = true;
  1564. /* For the moment we default this to UPB_INTFMT_VARIABLE, since it will work
  1565. * with all integer types and is in some since more "default" since the most
  1566. * normal-looking proto2 types int32/int64/uint32/uint64 use variable.
  1567. *
  1568. * Other options to consider:
  1569. * - there is no default; users must set this manually (like type).
  1570. * - default signed integers to UPB_INTFMT_ZIGZAG, since it's more likely to
  1571. * be an optimal default for signed integers. */
  1572. f->intfmt = UPB_INTFMT_VARIABLE;
  1573. return f;
  1574. }
  1575. bool upb_fielddef_typeisset(const upb_fielddef *f) {
  1576. return f->type_is_set_;
  1577. }
  1578. upb_fieldtype_t upb_fielddef_type(const upb_fielddef *f) {
  1579. UPB_ASSERT(f->type_is_set_);
  1580. return f->type_;
  1581. }
  1582. uint32_t upb_fielddef_index(const upb_fielddef *f) {
  1583. return f->index_;
  1584. }
  1585. upb_label_t upb_fielddef_label(const upb_fielddef *f) {
  1586. return f->label_;
  1587. }
  1588. upb_intfmt_t upb_fielddef_intfmt(const upb_fielddef *f) {
  1589. return f->intfmt;
  1590. }
  1591. bool upb_fielddef_istagdelim(const upb_fielddef *f) {
  1592. return f->tagdelim;
  1593. }
  1594. uint32_t upb_fielddef_number(const upb_fielddef *f) {
  1595. return f->number_;
  1596. }
  1597. bool upb_fielddef_isextension(const upb_fielddef *f) {
  1598. return f->is_extension_;
  1599. }
  1600. bool upb_fielddef_lazy(const upb_fielddef *f) {
  1601. return f->lazy_;
  1602. }
  1603. bool upb_fielddef_packed(const upb_fielddef *f) {
  1604. return f->packed_;
  1605. }
  1606. const char *upb_fielddef_name(const upb_fielddef *f) {
  1607. return upb_def_fullname(upb_fielddef_upcast(f));
  1608. }
  1609. size_t upb_fielddef_getjsonname(const upb_fielddef *f, char *buf, size_t len) {
  1610. const char *name = upb_fielddef_name(f);
  1611. size_t src, dst = 0;
  1612. bool ucase_next = false;
  1613. #define WRITE(byte) \
  1614. ++dst; \
  1615. if (dst < len) buf[dst - 1] = byte; \
  1616. else if (dst == len) buf[dst - 1] = '\0'
  1617. if (!name) {
  1618. WRITE('\0');
  1619. return 0;
  1620. }
  1621. /* Implement the transformation as described in the spec:
  1622. * 1. upper case all letters after an underscore.
  1623. * 2. remove all underscores.
  1624. */
  1625. for (src = 0; name[src]; src++) {
  1626. if (name[src] == '_') {
  1627. ucase_next = true;
  1628. continue;
  1629. }
  1630. if (ucase_next) {
  1631. WRITE(toupper(name[src]));
  1632. ucase_next = false;
  1633. } else {
  1634. WRITE(name[src]);
  1635. }
  1636. }
  1637. WRITE('\0');
  1638. return dst;
  1639. #undef WRITE
  1640. }
  1641. const upb_msgdef *upb_fielddef_containingtype(const upb_fielddef *f) {
  1642. return f->msg_is_symbolic ? NULL : f->msg.def;
  1643. }
  1644. const upb_oneofdef *upb_fielddef_containingoneof(const upb_fielddef *f) {
  1645. return f->oneof;
  1646. }
  1647. upb_msgdef *upb_fielddef_containingtype_mutable(upb_fielddef *f) {
  1648. return (upb_msgdef*)upb_fielddef_containingtype(f);
  1649. }
  1650. const char *upb_fielddef_containingtypename(upb_fielddef *f) {
  1651. return f->msg_is_symbolic ? f->msg.name : NULL;
  1652. }
  1653. static void release_containingtype(upb_fielddef *f) {
  1654. if (f->msg_is_symbolic) upb_gfree(f->msg.name);
  1655. }
  1656. bool upb_fielddef_setcontainingtypename(upb_fielddef *f, const char *name,
  1657. upb_status *s) {
  1658. char *name_copy;
  1659. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  1660. if (upb_fielddef_containingtype(f)) {
  1661. upb_status_seterrmsg(s, "field has already been added to a message.");
  1662. return false;
  1663. }
  1664. /* TODO: validate name (upb_isident() doesn't quite work atm because this name
  1665. * may have a leading "."). */
  1666. name_copy = upb_gstrdup(name);
  1667. if (!name_copy) {
  1668. upb_upberr_setoom(s);
  1669. return false;
  1670. }
  1671. release_containingtype(f);
  1672. f->msg.name = name_copy;
  1673. f->msg_is_symbolic = true;
  1674. return true;
  1675. }
  1676. bool upb_fielddef_setname(upb_fielddef *f, const char *name, upb_status *s) {
  1677. if (upb_fielddef_containingtype(f) || upb_fielddef_containingoneof(f)) {
  1678. upb_status_seterrmsg(s, "Already added to message or oneof");
  1679. return false;
  1680. }
  1681. return upb_def_setfullname(upb_fielddef_upcast_mutable(f), name, s);
  1682. }
  1683. static void chkdefaulttype(const upb_fielddef *f, upb_fieldtype_t type) {
  1684. UPB_UNUSED(f);
  1685. UPB_UNUSED(type);
  1686. UPB_ASSERT(f->type_is_set_ && upb_fielddef_type(f) == type);
  1687. }
  1688. int64_t upb_fielddef_defaultint64(const upb_fielddef *f) {
  1689. chkdefaulttype(f, UPB_TYPE_INT64);
  1690. return f->defaultval.sint;
  1691. }
  1692. int32_t upb_fielddef_defaultint32(const upb_fielddef *f) {
  1693. if (f->type_is_set_ && upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  1694. int32_t val;
  1695. bool ok = enumdefaultint32(f, &val);
  1696. UPB_ASSERT(ok);
  1697. return val;
  1698. } else {
  1699. chkdefaulttype(f, UPB_TYPE_INT32);
  1700. return f->defaultval.sint;
  1701. }
  1702. }
  1703. uint64_t upb_fielddef_defaultuint64(const upb_fielddef *f) {
  1704. chkdefaulttype(f, UPB_TYPE_UINT64);
  1705. return f->defaultval.uint;
  1706. }
  1707. uint32_t upb_fielddef_defaultuint32(const upb_fielddef *f) {
  1708. chkdefaulttype(f, UPB_TYPE_UINT32);
  1709. return f->defaultval.uint;
  1710. }
  1711. bool upb_fielddef_defaultbool(const upb_fielddef *f) {
  1712. chkdefaulttype(f, UPB_TYPE_BOOL);
  1713. return f->defaultval.uint;
  1714. }
  1715. float upb_fielddef_defaultfloat(const upb_fielddef *f) {
  1716. chkdefaulttype(f, UPB_TYPE_FLOAT);
  1717. return f->defaultval.flt;
  1718. }
  1719. double upb_fielddef_defaultdouble(const upb_fielddef *f) {
  1720. chkdefaulttype(f, UPB_TYPE_DOUBLE);
  1721. return f->defaultval.dbl;
  1722. }
  1723. const char *upb_fielddef_defaultstr(const upb_fielddef *f, size_t *len) {
  1724. UPB_ASSERT(f->type_is_set_);
  1725. UPB_ASSERT(upb_fielddef_type(f) == UPB_TYPE_STRING ||
  1726. upb_fielddef_type(f) == UPB_TYPE_BYTES ||
  1727. upb_fielddef_type(f) == UPB_TYPE_ENUM);
  1728. if (upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  1729. const char *ret = enumdefaultstr(f);
  1730. UPB_ASSERT(ret);
  1731. /* Enum defaults can't have embedded NULLs. */
  1732. if (len) *len = strlen(ret);
  1733. return ret;
  1734. }
  1735. if (f->default_is_string) {
  1736. str_t *str = f->defaultval.bytes;
  1737. if (len) *len = str->len;
  1738. return str->str;
  1739. }
  1740. return NULL;
  1741. }
  1742. static void upb_fielddef_init_default(upb_fielddef *f) {
  1743. f->default_is_string = false;
  1744. switch (upb_fielddef_type(f)) {
  1745. case UPB_TYPE_DOUBLE: f->defaultval.dbl = 0; break;
  1746. case UPB_TYPE_FLOAT: f->defaultval.flt = 0; break;
  1747. case UPB_TYPE_INT32:
  1748. case UPB_TYPE_INT64: f->defaultval.sint = 0; break;
  1749. case UPB_TYPE_UINT64:
  1750. case UPB_TYPE_UINT32:
  1751. case UPB_TYPE_BOOL: f->defaultval.uint = 0; break;
  1752. case UPB_TYPE_STRING:
  1753. case UPB_TYPE_BYTES:
  1754. f->defaultval.bytes = newstr("", 0);
  1755. f->default_is_string = true;
  1756. break;
  1757. case UPB_TYPE_MESSAGE: break;
  1758. case UPB_TYPE_ENUM:
  1759. /* This is our special sentinel that indicates "not set" for an enum. */
  1760. f->default_is_string = true;
  1761. f->defaultval.bytes = NULL;
  1762. break;
  1763. }
  1764. }
  1765. const upb_def *upb_fielddef_subdef(const upb_fielddef *f) {
  1766. return f->subdef_is_symbolic ? NULL : f->sub.def;
  1767. }
  1768. const upb_msgdef *upb_fielddef_msgsubdef(const upb_fielddef *f) {
  1769. const upb_def *def = upb_fielddef_subdef(f);
  1770. return def ? upb_dyncast_msgdef(def) : NULL;
  1771. }
  1772. const upb_enumdef *upb_fielddef_enumsubdef(const upb_fielddef *f) {
  1773. const upb_def *def = upb_fielddef_subdef(f);
  1774. return def ? upb_dyncast_enumdef(def) : NULL;
  1775. }
  1776. upb_def *upb_fielddef_subdef_mutable(upb_fielddef *f) {
  1777. return (upb_def*)upb_fielddef_subdef(f);
  1778. }
  1779. const char *upb_fielddef_subdefname(const upb_fielddef *f) {
  1780. if (f->subdef_is_symbolic) {
  1781. return f->sub.name;
  1782. } else if (f->sub.def) {
  1783. return upb_def_fullname(f->sub.def);
  1784. } else {
  1785. return NULL;
  1786. }
  1787. }
  1788. bool upb_fielddef_setnumber(upb_fielddef *f, uint32_t number, upb_status *s) {
  1789. if (upb_fielddef_containingtype(f)) {
  1790. upb_status_seterrmsg(
  1791. s, "cannot change field number after adding to a message");
  1792. return false;
  1793. }
  1794. if (number == 0) {
  1795. upb_status_seterrf(s, "invalid field number (%u)", number);
  1796. return false;
  1797. }
  1798. f->number_ = number;
  1799. return true;
  1800. }
  1801. void upb_fielddef_settype(upb_fielddef *f, upb_fieldtype_t type) {
  1802. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  1803. UPB_ASSERT(upb_fielddef_checktype(type));
  1804. upb_fielddef_uninit_default(f);
  1805. f->type_ = type;
  1806. f->type_is_set_ = true;
  1807. upb_fielddef_init_default(f);
  1808. }
  1809. void upb_fielddef_setdescriptortype(upb_fielddef *f, int type) {
  1810. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  1811. switch (type) {
  1812. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  1813. upb_fielddef_settype(f, UPB_TYPE_DOUBLE);
  1814. break;
  1815. case UPB_DESCRIPTOR_TYPE_FLOAT:
  1816. upb_fielddef_settype(f, UPB_TYPE_FLOAT);
  1817. break;
  1818. case UPB_DESCRIPTOR_TYPE_INT64:
  1819. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  1820. case UPB_DESCRIPTOR_TYPE_SINT64:
  1821. upb_fielddef_settype(f, UPB_TYPE_INT64);
  1822. break;
  1823. case UPB_DESCRIPTOR_TYPE_UINT64:
  1824. case UPB_DESCRIPTOR_TYPE_FIXED64:
  1825. upb_fielddef_settype(f, UPB_TYPE_UINT64);
  1826. break;
  1827. case UPB_DESCRIPTOR_TYPE_INT32:
  1828. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  1829. case UPB_DESCRIPTOR_TYPE_SINT32:
  1830. upb_fielddef_settype(f, UPB_TYPE_INT32);
  1831. break;
  1832. case UPB_DESCRIPTOR_TYPE_UINT32:
  1833. case UPB_DESCRIPTOR_TYPE_FIXED32:
  1834. upb_fielddef_settype(f, UPB_TYPE_UINT32);
  1835. break;
  1836. case UPB_DESCRIPTOR_TYPE_BOOL:
  1837. upb_fielddef_settype(f, UPB_TYPE_BOOL);
  1838. break;
  1839. case UPB_DESCRIPTOR_TYPE_STRING:
  1840. upb_fielddef_settype(f, UPB_TYPE_STRING);
  1841. break;
  1842. case UPB_DESCRIPTOR_TYPE_BYTES:
  1843. upb_fielddef_settype(f, UPB_TYPE_BYTES);
  1844. break;
  1845. case UPB_DESCRIPTOR_TYPE_GROUP:
  1846. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  1847. upb_fielddef_settype(f, UPB_TYPE_MESSAGE);
  1848. break;
  1849. case UPB_DESCRIPTOR_TYPE_ENUM:
  1850. upb_fielddef_settype(f, UPB_TYPE_ENUM);
  1851. break;
  1852. default: UPB_ASSERT(false);
  1853. }
  1854. if (type == UPB_DESCRIPTOR_TYPE_FIXED64 ||
  1855. type == UPB_DESCRIPTOR_TYPE_FIXED32 ||
  1856. type == UPB_DESCRIPTOR_TYPE_SFIXED64 ||
  1857. type == UPB_DESCRIPTOR_TYPE_SFIXED32) {
  1858. upb_fielddef_setintfmt(f, UPB_INTFMT_FIXED);
  1859. } else if (type == UPB_DESCRIPTOR_TYPE_SINT64 ||
  1860. type == UPB_DESCRIPTOR_TYPE_SINT32) {
  1861. upb_fielddef_setintfmt(f, UPB_INTFMT_ZIGZAG);
  1862. } else {
  1863. upb_fielddef_setintfmt(f, UPB_INTFMT_VARIABLE);
  1864. }
  1865. upb_fielddef_settagdelim(f, type == UPB_DESCRIPTOR_TYPE_GROUP);
  1866. }
  1867. upb_descriptortype_t upb_fielddef_descriptortype(const upb_fielddef *f) {
  1868. switch (upb_fielddef_type(f)) {
  1869. case UPB_TYPE_FLOAT: return UPB_DESCRIPTOR_TYPE_FLOAT;
  1870. case UPB_TYPE_DOUBLE: return UPB_DESCRIPTOR_TYPE_DOUBLE;
  1871. case UPB_TYPE_BOOL: return UPB_DESCRIPTOR_TYPE_BOOL;
  1872. case UPB_TYPE_STRING: return UPB_DESCRIPTOR_TYPE_STRING;
  1873. case UPB_TYPE_BYTES: return UPB_DESCRIPTOR_TYPE_BYTES;
  1874. case UPB_TYPE_ENUM: return UPB_DESCRIPTOR_TYPE_ENUM;
  1875. case UPB_TYPE_INT32:
  1876. switch (upb_fielddef_intfmt(f)) {
  1877. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_INT32;
  1878. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_SFIXED32;
  1879. case UPB_INTFMT_ZIGZAG: return UPB_DESCRIPTOR_TYPE_SINT32;
  1880. }
  1881. case UPB_TYPE_INT64:
  1882. switch (upb_fielddef_intfmt(f)) {
  1883. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_INT64;
  1884. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_SFIXED64;
  1885. case UPB_INTFMT_ZIGZAG: return UPB_DESCRIPTOR_TYPE_SINT64;
  1886. }
  1887. case UPB_TYPE_UINT32:
  1888. switch (upb_fielddef_intfmt(f)) {
  1889. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_UINT32;
  1890. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_FIXED32;
  1891. case UPB_INTFMT_ZIGZAG: return -1;
  1892. }
  1893. case UPB_TYPE_UINT64:
  1894. switch (upb_fielddef_intfmt(f)) {
  1895. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_UINT64;
  1896. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_FIXED64;
  1897. case UPB_INTFMT_ZIGZAG: return -1;
  1898. }
  1899. case UPB_TYPE_MESSAGE:
  1900. return upb_fielddef_istagdelim(f) ?
  1901. UPB_DESCRIPTOR_TYPE_GROUP : UPB_DESCRIPTOR_TYPE_MESSAGE;
  1902. }
  1903. return 0;
  1904. }
  1905. void upb_fielddef_setisextension(upb_fielddef *f, bool is_extension) {
  1906. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  1907. f->is_extension_ = is_extension;
  1908. }
  1909. void upb_fielddef_setlazy(upb_fielddef *f, bool lazy) {
  1910. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  1911. f->lazy_ = lazy;
  1912. }
  1913. void upb_fielddef_setpacked(upb_fielddef *f, bool packed) {
  1914. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  1915. f->packed_ = packed;
  1916. }
  1917. void upb_fielddef_setlabel(upb_fielddef *f, upb_label_t label) {
  1918. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  1919. UPB_ASSERT(upb_fielddef_checklabel(label));
  1920. f->label_ = label;
  1921. }
  1922. void upb_fielddef_setintfmt(upb_fielddef *f, upb_intfmt_t fmt) {
  1923. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  1924. UPB_ASSERT(upb_fielddef_checkintfmt(fmt));
  1925. f->intfmt = fmt;
  1926. }
  1927. void upb_fielddef_settagdelim(upb_fielddef *f, bool tag_delim) {
  1928. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  1929. f->tagdelim = tag_delim;
  1930. f->tagdelim = tag_delim;
  1931. }
  1932. static bool checksetdefault(upb_fielddef *f, upb_fieldtype_t type) {
  1933. if (!f->type_is_set_ || upb_fielddef_isfrozen(f) ||
  1934. upb_fielddef_type(f) != type) {
  1935. UPB_ASSERT(false);
  1936. return false;
  1937. }
  1938. if (f->default_is_string) {
  1939. str_t *s = f->defaultval.bytes;
  1940. UPB_ASSERT(s || type == UPB_TYPE_ENUM);
  1941. if (s) freestr(s);
  1942. }
  1943. f->default_is_string = false;
  1944. return true;
  1945. }
  1946. void upb_fielddef_setdefaultint64(upb_fielddef *f, int64_t value) {
  1947. if (checksetdefault(f, UPB_TYPE_INT64))
  1948. f->defaultval.sint = value;
  1949. }
  1950. void upb_fielddef_setdefaultint32(upb_fielddef *f, int32_t value) {
  1951. if ((upb_fielddef_type(f) == UPB_TYPE_ENUM &&
  1952. checksetdefault(f, UPB_TYPE_ENUM)) ||
  1953. checksetdefault(f, UPB_TYPE_INT32)) {
  1954. f->defaultval.sint = value;
  1955. }
  1956. }
  1957. void upb_fielddef_setdefaultuint64(upb_fielddef *f, uint64_t value) {
  1958. if (checksetdefault(f, UPB_TYPE_UINT64))
  1959. f->defaultval.uint = value;
  1960. }
  1961. void upb_fielddef_setdefaultuint32(upb_fielddef *f, uint32_t value) {
  1962. if (checksetdefault(f, UPB_TYPE_UINT32))
  1963. f->defaultval.uint = value;
  1964. }
  1965. void upb_fielddef_setdefaultbool(upb_fielddef *f, bool value) {
  1966. if (checksetdefault(f, UPB_TYPE_BOOL))
  1967. f->defaultval.uint = value;
  1968. }
  1969. void upb_fielddef_setdefaultfloat(upb_fielddef *f, float value) {
  1970. if (checksetdefault(f, UPB_TYPE_FLOAT))
  1971. f->defaultval.flt = value;
  1972. }
  1973. void upb_fielddef_setdefaultdouble(upb_fielddef *f, double value) {
  1974. if (checksetdefault(f, UPB_TYPE_DOUBLE))
  1975. f->defaultval.dbl = value;
  1976. }
  1977. bool upb_fielddef_setdefaultstr(upb_fielddef *f, const void *str, size_t len,
  1978. upb_status *s) {
  1979. str_t *str2;
  1980. UPB_ASSERT(upb_fielddef_isstring(f) || f->type_ == UPB_TYPE_ENUM);
  1981. if (f->type_ == UPB_TYPE_ENUM && !upb_isident(str, len, false, s))
  1982. return false;
  1983. if (f->default_is_string) {
  1984. str_t *s = f->defaultval.bytes;
  1985. UPB_ASSERT(s || f->type_ == UPB_TYPE_ENUM);
  1986. if (s) freestr(s);
  1987. } else {
  1988. UPB_ASSERT(f->type_ == UPB_TYPE_ENUM);
  1989. }
  1990. str2 = newstr(str, len);
  1991. f->defaultval.bytes = str2;
  1992. f->default_is_string = true;
  1993. return true;
  1994. }
  1995. void upb_fielddef_setdefaultcstr(upb_fielddef *f, const char *str,
  1996. upb_status *s) {
  1997. UPB_ASSERT(f->type_is_set_);
  1998. upb_fielddef_setdefaultstr(f, str, str ? strlen(str) : 0, s);
  1999. }
  2000. bool upb_fielddef_enumhasdefaultint32(const upb_fielddef *f) {
  2001. int32_t val;
  2002. UPB_ASSERT(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  2003. return enumdefaultint32(f, &val);
  2004. }
  2005. bool upb_fielddef_enumhasdefaultstr(const upb_fielddef *f) {
  2006. UPB_ASSERT(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  2007. return enumdefaultstr(f) != NULL;
  2008. }
  2009. static bool upb_subdef_typecheck(upb_fielddef *f, const upb_def *subdef,
  2010. upb_status *s) {
  2011. if (f->type_ == UPB_TYPE_MESSAGE) {
  2012. if (upb_dyncast_msgdef(subdef)) return true;
  2013. upb_status_seterrmsg(s, "invalid subdef type for this submessage field");
  2014. return false;
  2015. } else if (f->type_ == UPB_TYPE_ENUM) {
  2016. if (upb_dyncast_enumdef(subdef)) return true;
  2017. upb_status_seterrmsg(s, "invalid subdef type for this enum field");
  2018. return false;
  2019. } else {
  2020. upb_status_seterrmsg(s, "only message and enum fields can have a subdef");
  2021. return false;
  2022. }
  2023. }
  2024. static void release_subdef(upb_fielddef *f) {
  2025. if (f->subdef_is_symbolic) {
  2026. upb_gfree(f->sub.name);
  2027. } else if (f->sub.def) {
  2028. upb_unref2(f->sub.def, f);
  2029. }
  2030. }
  2031. bool upb_fielddef_setsubdef(upb_fielddef *f, const upb_def *subdef,
  2032. upb_status *s) {
  2033. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  2034. UPB_ASSERT(upb_fielddef_hassubdef(f));
  2035. if (subdef && !upb_subdef_typecheck(f, subdef, s)) return false;
  2036. release_subdef(f);
  2037. f->sub.def = subdef;
  2038. f->subdef_is_symbolic = false;
  2039. if (f->sub.def) upb_ref2(f->sub.def, f);
  2040. return true;
  2041. }
  2042. bool upb_fielddef_setmsgsubdef(upb_fielddef *f, const upb_msgdef *subdef,
  2043. upb_status *s) {
  2044. return upb_fielddef_setsubdef(f, upb_msgdef_upcast(subdef), s);
  2045. }
  2046. bool upb_fielddef_setenumsubdef(upb_fielddef *f, const upb_enumdef *subdef,
  2047. upb_status *s) {
  2048. return upb_fielddef_setsubdef(f, upb_enumdef_upcast(subdef), s);
  2049. }
  2050. bool upb_fielddef_setsubdefname(upb_fielddef *f, const char *name,
  2051. upb_status *s) {
  2052. char *name_copy;
  2053. UPB_ASSERT(!upb_fielddef_isfrozen(f));
  2054. if (!upb_fielddef_hassubdef(f)) {
  2055. upb_status_seterrmsg(s, "field type does not accept a subdef");
  2056. return false;
  2057. }
  2058. name_copy = upb_gstrdup(name);
  2059. if (!name_copy) {
  2060. upb_upberr_setoom(s);
  2061. return false;
  2062. }
  2063. /* TODO: validate name (upb_isident() doesn't quite work atm because this name
  2064. * may have a leading "."). */
  2065. release_subdef(f);
  2066. f->sub.name = name_copy;
  2067. f->subdef_is_symbolic = true;
  2068. return true;
  2069. }
  2070. bool upb_fielddef_issubmsg(const upb_fielddef *f) {
  2071. return upb_fielddef_type(f) == UPB_TYPE_MESSAGE;
  2072. }
  2073. bool upb_fielddef_isstring(const upb_fielddef *f) {
  2074. return upb_fielddef_type(f) == UPB_TYPE_STRING ||
  2075. upb_fielddef_type(f) == UPB_TYPE_BYTES;
  2076. }
  2077. bool upb_fielddef_isseq(const upb_fielddef *f) {
  2078. return upb_fielddef_label(f) == UPB_LABEL_REPEATED;
  2079. }
  2080. bool upb_fielddef_isprimitive(const upb_fielddef *f) {
  2081. return !upb_fielddef_isstring(f) && !upb_fielddef_issubmsg(f);
  2082. }
  2083. bool upb_fielddef_ismap(const upb_fielddef *f) {
  2084. return upb_fielddef_isseq(f) && upb_fielddef_issubmsg(f) &&
  2085. upb_msgdef_mapentry(upb_fielddef_msgsubdef(f));
  2086. }
  2087. bool upb_fielddef_haspresence(const upb_fielddef *f) {
  2088. if (upb_fielddef_isseq(f)) return false;
  2089. if (upb_fielddef_issubmsg(f)) return true;
  2090. /* Primitive field: return true unless there is a message that specifies
  2091. * presence should not exist. */
  2092. if (f->msg_is_symbolic || !f->msg.def) return true;
  2093. return f->msg.def->syntax == UPB_SYNTAX_PROTO2;
  2094. }
  2095. bool upb_fielddef_hassubdef(const upb_fielddef *f) {
  2096. return upb_fielddef_issubmsg(f) || upb_fielddef_type(f) == UPB_TYPE_ENUM;
  2097. }
  2098. static bool between(int32_t x, int32_t low, int32_t high) {
  2099. return x >= low && x <= high;
  2100. }
  2101. bool upb_fielddef_checklabel(int32_t label) { return between(label, 1, 3); }
  2102. bool upb_fielddef_checktype(int32_t type) { return between(type, 1, 11); }
  2103. bool upb_fielddef_checkintfmt(int32_t fmt) { return between(fmt, 1, 3); }
  2104. bool upb_fielddef_checkdescriptortype(int32_t type) {
  2105. return between(type, 1, 18);
  2106. }
  2107. /* upb_msgdef *****************************************************************/
  2108. static void visitmsg(const upb_refcounted *r, upb_refcounted_visit *visit,
  2109. void *closure) {
  2110. upb_msg_oneof_iter o;
  2111. const upb_msgdef *m = (const upb_msgdef*)r;
  2112. const upb_def *def = upb_msgdef_upcast(m);
  2113. upb_msg_field_iter i;
  2114. for(upb_msg_field_begin(&i, m);
  2115. !upb_msg_field_done(&i);
  2116. upb_msg_field_next(&i)) {
  2117. upb_fielddef *f = upb_msg_iter_field(&i);
  2118. visit(r, upb_fielddef_upcast2(f), closure);
  2119. }
  2120. for(upb_msg_oneof_begin(&o, m);
  2121. !upb_msg_oneof_done(&o);
  2122. upb_msg_oneof_next(&o)) {
  2123. upb_oneofdef *f = upb_msg_iter_oneof(&o);
  2124. visit(r, upb_oneofdef_upcast(f), closure);
  2125. }
  2126. if (upb_def_file(def)) {
  2127. visit(r, upb_filedef_upcast(upb_def_file(def)), closure);
  2128. }
  2129. }
  2130. static void freemsg(upb_refcounted *r) {
  2131. upb_msgdef *m = (upb_msgdef*)r;
  2132. upb_strtable_uninit(&m->ntof);
  2133. upb_inttable_uninit(&m->itof);
  2134. upb_def_uninit(upb_msgdef_upcast_mutable(m));
  2135. upb_gfree(m);
  2136. }
  2137. const struct upb_refcounted_vtbl upb_msgdef_vtbl = {visitmsg, freemsg};
  2138. upb_msgdef *upb_msgdef_new(const void *owner) {
  2139. upb_msgdef *m = upb_gmalloc(sizeof(*m));
  2140. if (!m) return NULL;
  2141. if (!upb_def_init(upb_msgdef_upcast_mutable(m), UPB_DEF_MSG, &upb_msgdef_vtbl,
  2142. owner)) {
  2143. goto err2;
  2144. }
  2145. if (!upb_inttable_init(&m->itof, UPB_CTYPE_PTR)) goto err2;
  2146. if (!upb_strtable_init(&m->ntof, UPB_CTYPE_PTR)) goto err1;
  2147. m->map_entry = false;
  2148. m->syntax = UPB_SYNTAX_PROTO2;
  2149. return m;
  2150. err1:
  2151. upb_inttable_uninit(&m->itof);
  2152. err2:
  2153. upb_gfree(m);
  2154. return NULL;
  2155. }
  2156. bool upb_msgdef_freeze(upb_msgdef *m, upb_status *status) {
  2157. upb_def *d = upb_msgdef_upcast_mutable(m);
  2158. return upb_def_freeze(&d, 1, status);
  2159. }
  2160. const char *upb_msgdef_fullname(const upb_msgdef *m) {
  2161. return upb_def_fullname(upb_msgdef_upcast(m));
  2162. }
  2163. const char *upb_msgdef_name(const upb_msgdef *m) {
  2164. return upb_def_name(upb_msgdef_upcast(m));
  2165. }
  2166. bool upb_msgdef_setfullname(upb_msgdef *m, const char *fullname,
  2167. upb_status *s) {
  2168. return upb_def_setfullname(upb_msgdef_upcast_mutable(m), fullname, s);
  2169. }
  2170. bool upb_msgdef_setsyntax(upb_msgdef *m, upb_syntax_t syntax) {
  2171. if (syntax != UPB_SYNTAX_PROTO2 && syntax != UPB_SYNTAX_PROTO3) {
  2172. return false;
  2173. }
  2174. m->syntax = syntax;
  2175. return true;
  2176. }
  2177. upb_syntax_t upb_msgdef_syntax(const upb_msgdef *m) {
  2178. return m->syntax;
  2179. }
  2180. /* Helper: check that the field |f| is safe to add to msgdef |m|. Set an error
  2181. * on status |s| and return false if not. */
  2182. static bool check_field_add(const upb_msgdef *m, const upb_fielddef *f,
  2183. upb_status *s) {
  2184. if (upb_fielddef_containingtype(f) != NULL) {
  2185. upb_status_seterrmsg(s, "fielddef already belongs to a message");
  2186. return false;
  2187. } else if (upb_fielddef_name(f) == NULL || upb_fielddef_number(f) == 0) {
  2188. upb_status_seterrmsg(s, "field name or number were not set");
  2189. return false;
  2190. } else if (upb_msgdef_itof(m, upb_fielddef_number(f))) {
  2191. upb_status_seterrmsg(s, "duplicate field number");
  2192. return false;
  2193. } else if (upb_strtable_lookup(&m->ntof, upb_fielddef_name(f), NULL)) {
  2194. upb_status_seterrmsg(s, "name conflicts with existing field or oneof");
  2195. return false;
  2196. }
  2197. return true;
  2198. }
  2199. static void add_field(upb_msgdef *m, upb_fielddef *f, const void *ref_donor) {
  2200. release_containingtype(f);
  2201. f->msg.def = m;
  2202. f->msg_is_symbolic = false;
  2203. upb_inttable_insert(&m->itof, upb_fielddef_number(f), upb_value_ptr(f));
  2204. upb_strtable_insert(&m->ntof, upb_fielddef_name(f), upb_value_ptr(f));
  2205. upb_ref2(f, m);
  2206. upb_ref2(m, f);
  2207. if (ref_donor) upb_fielddef_unref(f, ref_donor);
  2208. }
  2209. bool upb_msgdef_addfield(upb_msgdef *m, upb_fielddef *f, const void *ref_donor,
  2210. upb_status *s) {
  2211. /* TODO: extensions need to have a separate namespace, because proto2 allows a
  2212. * top-level extension (ie. one not in any package) to have the same name as a
  2213. * field from the message.
  2214. *
  2215. * This also implies that there needs to be a separate lookup-by-name method
  2216. * for extensions. It seems desirable for iteration to return both extensions
  2217. * and non-extensions though.
  2218. *
  2219. * We also need to validate that the field number is in an extension range iff
  2220. * it is an extension.
  2221. *
  2222. * This method is idempotent. Check if |f| is already part of this msgdef and
  2223. * return immediately if so. */
  2224. if (upb_fielddef_containingtype(f) == m) {
  2225. if (ref_donor) upb_fielddef_unref(f, ref_donor);
  2226. return true;
  2227. }
  2228. /* Check constraints for all fields before performing any action. */
  2229. if (!check_field_add(m, f, s)) {
  2230. return false;
  2231. } else if (upb_fielddef_containingoneof(f) != NULL) {
  2232. /* Fields in a oneof can only be added by adding the oneof to the msgdef. */
  2233. upb_status_seterrmsg(s, "fielddef is part of a oneof");
  2234. return false;
  2235. }
  2236. /* Constraint checks ok, perform the action. */
  2237. add_field(m, f, ref_donor);
  2238. return true;
  2239. }
  2240. bool upb_msgdef_addoneof(upb_msgdef *m, upb_oneofdef *o, const void *ref_donor,
  2241. upb_status *s) {
  2242. upb_oneof_iter it;
  2243. /* Check various conditions that would prevent this oneof from being added. */
  2244. if (upb_oneofdef_containingtype(o)) {
  2245. upb_status_seterrmsg(s, "oneofdef already belongs to a message");
  2246. return false;
  2247. } else if (upb_oneofdef_name(o) == NULL) {
  2248. upb_status_seterrmsg(s, "oneofdef name was not set");
  2249. return false;
  2250. } else if (upb_strtable_lookup(&m->ntof, upb_oneofdef_name(o), NULL)) {
  2251. upb_status_seterrmsg(s, "name conflicts with existing field or oneof");
  2252. return false;
  2253. }
  2254. /* Check that all of the oneof's fields do not conflict with names or numbers
  2255. * of fields already in the message. */
  2256. for (upb_oneof_begin(&it, o); !upb_oneof_done(&it); upb_oneof_next(&it)) {
  2257. const upb_fielddef *f = upb_oneof_iter_field(&it);
  2258. if (!check_field_add(m, f, s)) {
  2259. return false;
  2260. }
  2261. }
  2262. /* Everything checks out -- commit now. */
  2263. /* Add oneof itself first. */
  2264. o->parent = m;
  2265. upb_strtable_insert(&m->ntof, upb_oneofdef_name(o), upb_value_ptr(o));
  2266. upb_ref2(o, m);
  2267. upb_ref2(m, o);
  2268. /* Add each field of the oneof directly to the msgdef. */
  2269. for (upb_oneof_begin(&it, o); !upb_oneof_done(&it); upb_oneof_next(&it)) {
  2270. upb_fielddef *f = upb_oneof_iter_field(&it);
  2271. add_field(m, f, NULL);
  2272. }
  2273. if (ref_donor) upb_oneofdef_unref(o, ref_donor);
  2274. return true;
  2275. }
  2276. const upb_fielddef *upb_msgdef_itof(const upb_msgdef *m, uint32_t i) {
  2277. upb_value val;
  2278. return upb_inttable_lookup32(&m->itof, i, &val) ?
  2279. upb_value_getptr(val) : NULL;
  2280. }
  2281. const upb_fielddef *upb_msgdef_ntof(const upb_msgdef *m, const char *name,
  2282. size_t len) {
  2283. upb_value val;
  2284. if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
  2285. return NULL;
  2286. }
  2287. return upb_trygetfield(upb_value_getptr(val));
  2288. }
  2289. const upb_oneofdef *upb_msgdef_ntoo(const upb_msgdef *m, const char *name,
  2290. size_t len) {
  2291. upb_value val;
  2292. if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
  2293. return NULL;
  2294. }
  2295. return upb_trygetoneof(upb_value_getptr(val));
  2296. }
  2297. bool upb_msgdef_lookupname(const upb_msgdef *m, const char *name, size_t len,
  2298. const upb_fielddef **f, const upb_oneofdef **o) {
  2299. upb_value val;
  2300. if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
  2301. return false;
  2302. }
  2303. *o = upb_trygetoneof(upb_value_getptr(val));
  2304. *f = upb_trygetfield(upb_value_getptr(val));
  2305. UPB_ASSERT((*o != NULL) ^ (*f != NULL)); /* Exactly one of the two should be set. */
  2306. return true;
  2307. }
  2308. int upb_msgdef_numfields(const upb_msgdef *m) {
  2309. /* The number table contains only fields. */
  2310. return upb_inttable_count(&m->itof);
  2311. }
  2312. int upb_msgdef_numoneofs(const upb_msgdef *m) {
  2313. /* The name table includes oneofs, and the number table does not. */
  2314. return upb_strtable_count(&m->ntof) - upb_inttable_count(&m->itof);
  2315. }
  2316. void upb_msgdef_setmapentry(upb_msgdef *m, bool map_entry) {
  2317. UPB_ASSERT(!upb_msgdef_isfrozen(m));
  2318. m->map_entry = map_entry;
  2319. }
  2320. bool upb_msgdef_mapentry(const upb_msgdef *m) {
  2321. return m->map_entry;
  2322. }
  2323. upb_wellknowntype_t upb_msgdef_wellknowntype(const upb_msgdef *m) {
  2324. return m->well_known_type;
  2325. }
  2326. bool upb_msgdef_isnumberwrapper(const upb_msgdef *m) {
  2327. upb_wellknowntype_t type = upb_msgdef_wellknowntype(m);
  2328. return type >= UPB_WELLKNOWN_DOUBLEVALUE &&
  2329. type <= UPB_WELLKNOWN_UINT32VALUE;
  2330. }
  2331. void upb_msg_field_begin(upb_msg_field_iter *iter, const upb_msgdef *m) {
  2332. upb_inttable_begin(iter, &m->itof);
  2333. }
  2334. void upb_msg_field_next(upb_msg_field_iter *iter) { upb_inttable_next(iter); }
  2335. bool upb_msg_field_done(const upb_msg_field_iter *iter) {
  2336. return upb_inttable_done(iter);
  2337. }
  2338. upb_fielddef *upb_msg_iter_field(const upb_msg_field_iter *iter) {
  2339. return (upb_fielddef*)upb_value_getptr(upb_inttable_iter_value(iter));
  2340. }
  2341. void upb_msg_field_iter_setdone(upb_msg_field_iter *iter) {
  2342. upb_inttable_iter_setdone(iter);
  2343. }
  2344. void upb_msg_oneof_begin(upb_msg_oneof_iter *iter, const upb_msgdef *m) {
  2345. upb_strtable_begin(iter, &m->ntof);
  2346. /* We need to skip past any initial fields. */
  2347. while (!upb_strtable_done(iter) &&
  2348. !upb_isoneof(upb_value_getptr(upb_strtable_iter_value(iter)))) {
  2349. upb_strtable_next(iter);
  2350. }
  2351. }
  2352. void upb_msg_oneof_next(upb_msg_oneof_iter *iter) {
  2353. /* We need to skip past fields to return only oneofs. */
  2354. do {
  2355. upb_strtable_next(iter);
  2356. } while (!upb_strtable_done(iter) &&
  2357. !upb_isoneof(upb_value_getptr(upb_strtable_iter_value(iter))));
  2358. }
  2359. bool upb_msg_oneof_done(const upb_msg_oneof_iter *iter) {
  2360. return upb_strtable_done(iter);
  2361. }
  2362. upb_oneofdef *upb_msg_iter_oneof(const upb_msg_oneof_iter *iter) {
  2363. return (upb_oneofdef*)upb_value_getptr(upb_strtable_iter_value(iter));
  2364. }
  2365. void upb_msg_oneof_iter_setdone(upb_msg_oneof_iter *iter) {
  2366. upb_strtable_iter_setdone(iter);
  2367. }
  2368. /* upb_oneofdef ***************************************************************/
  2369. static void visitoneof(const upb_refcounted *r, upb_refcounted_visit *visit,
  2370. void *closure) {
  2371. const upb_oneofdef *o = (const upb_oneofdef*)r;
  2372. upb_oneof_iter i;
  2373. for (upb_oneof_begin(&i, o); !upb_oneof_done(&i); upb_oneof_next(&i)) {
  2374. const upb_fielddef *f = upb_oneof_iter_field(&i);
  2375. visit(r, upb_fielddef_upcast2(f), closure);
  2376. }
  2377. if (o->parent) {
  2378. visit(r, upb_msgdef_upcast2(o->parent), closure);
  2379. }
  2380. }
  2381. static void freeoneof(upb_refcounted *r) {
  2382. upb_oneofdef *o = (upb_oneofdef*)r;
  2383. upb_strtable_uninit(&o->ntof);
  2384. upb_inttable_uninit(&o->itof);
  2385. upb_gfree((void*)o->name);
  2386. upb_gfree(o);
  2387. }
  2388. const struct upb_refcounted_vtbl upb_oneofdef_vtbl = {visitoneof, freeoneof};
  2389. upb_oneofdef *upb_oneofdef_new(const void *owner) {
  2390. upb_oneofdef *o = upb_gmalloc(sizeof(*o));
  2391. if (!o) {
  2392. return NULL;
  2393. }
  2394. o->parent = NULL;
  2395. o->name = NULL;
  2396. if (!upb_refcounted_init(upb_oneofdef_upcast_mutable(o), &upb_oneofdef_vtbl,
  2397. owner)) {
  2398. goto err2;
  2399. }
  2400. if (!upb_inttable_init(&o->itof, UPB_CTYPE_PTR)) goto err2;
  2401. if (!upb_strtable_init(&o->ntof, UPB_CTYPE_PTR)) goto err1;
  2402. return o;
  2403. err1:
  2404. upb_inttable_uninit(&o->itof);
  2405. err2:
  2406. upb_gfree(o);
  2407. return NULL;
  2408. }
  2409. const char *upb_oneofdef_name(const upb_oneofdef *o) { return o->name; }
  2410. bool upb_oneofdef_setname(upb_oneofdef *o, const char *name, upb_status *s) {
  2411. UPB_ASSERT(!upb_oneofdef_isfrozen(o));
  2412. if (upb_oneofdef_containingtype(o)) {
  2413. upb_status_seterrmsg(s, "oneof already added to a message");
  2414. return false;
  2415. }
  2416. if (!upb_isident(name, strlen(name), true, s)) {
  2417. return false;
  2418. }
  2419. name = upb_gstrdup(name);
  2420. if (!name) {
  2421. upb_status_seterrmsg(s, "One of memory");
  2422. return false;
  2423. }
  2424. upb_gfree((void*)o->name);
  2425. o->name = name;
  2426. return true;
  2427. }
  2428. const upb_msgdef *upb_oneofdef_containingtype(const upb_oneofdef *o) {
  2429. return o->parent;
  2430. }
  2431. int upb_oneofdef_numfields(const upb_oneofdef *o) {
  2432. return upb_strtable_count(&o->ntof);
  2433. }
  2434. uint32_t upb_oneofdef_index(const upb_oneofdef *o) {
  2435. return o->index;
  2436. }
  2437. bool upb_oneofdef_addfield(upb_oneofdef *o, upb_fielddef *f,
  2438. const void *ref_donor,
  2439. upb_status *s) {
  2440. UPB_ASSERT(!upb_oneofdef_isfrozen(o));
  2441. UPB_ASSERT(!o->parent || !upb_msgdef_isfrozen(o->parent));
  2442. /* This method is idempotent. Check if |f| is already part of this oneofdef
  2443. * and return immediately if so. */
  2444. if (upb_fielddef_containingoneof(f) == o) {
  2445. return true;
  2446. }
  2447. /* The field must have an OPTIONAL label. */
  2448. if (upb_fielddef_label(f) != UPB_LABEL_OPTIONAL) {
  2449. upb_status_seterrmsg(s, "fields in oneof must have OPTIONAL label");
  2450. return false;
  2451. }
  2452. /* Check that no field with this name or number exists already in the oneof.
  2453. * Also check that the field is not already part of a oneof. */
  2454. if (upb_fielddef_name(f) == NULL || upb_fielddef_number(f) == 0) {
  2455. upb_status_seterrmsg(s, "field name or number were not set");
  2456. return false;
  2457. } else if (upb_oneofdef_itof(o, upb_fielddef_number(f)) ||
  2458. upb_oneofdef_ntofz(o, upb_fielddef_name(f))) {
  2459. upb_status_seterrmsg(s, "duplicate field name or number");
  2460. return false;
  2461. } else if (upb_fielddef_containingoneof(f) != NULL) {
  2462. upb_status_seterrmsg(s, "fielddef already belongs to a oneof");
  2463. return false;
  2464. }
  2465. /* We allow adding a field to the oneof either if the field is not part of a
  2466. * msgdef, or if it is and we are also part of the same msgdef. */
  2467. if (o->parent == NULL) {
  2468. /* If we're not in a msgdef, the field cannot be either. Otherwise we would
  2469. * need to magically add this oneof to a msgdef to remain consistent, which
  2470. * is surprising behavior. */
  2471. if (upb_fielddef_containingtype(f) != NULL) {
  2472. upb_status_seterrmsg(s, "fielddef already belongs to a message, but "
  2473. "oneof does not");
  2474. return false;
  2475. }
  2476. } else {
  2477. /* If we're in a msgdef, the user can add fields that either aren't in any
  2478. * msgdef (in which case they're added to our msgdef) or already a part of
  2479. * our msgdef. */
  2480. if (upb_fielddef_containingtype(f) != NULL &&
  2481. upb_fielddef_containingtype(f) != o->parent) {
  2482. upb_status_seterrmsg(s, "fielddef belongs to a different message "
  2483. "than oneof");
  2484. return false;
  2485. }
  2486. }
  2487. /* Commit phase. First add the field to our parent msgdef, if any, because
  2488. * that may fail; then add the field to our own tables. */
  2489. if (o->parent != NULL && upb_fielddef_containingtype(f) == NULL) {
  2490. if (!upb_msgdef_addfield((upb_msgdef*)o->parent, f, NULL, s)) {
  2491. return false;
  2492. }
  2493. }
  2494. release_containingtype(f);
  2495. f->oneof = o;
  2496. upb_inttable_insert(&o->itof, upb_fielddef_number(f), upb_value_ptr(f));
  2497. upb_strtable_insert(&o->ntof, upb_fielddef_name(f), upb_value_ptr(f));
  2498. upb_ref2(f, o);
  2499. upb_ref2(o, f);
  2500. if (ref_donor) upb_fielddef_unref(f, ref_donor);
  2501. return true;
  2502. }
  2503. const upb_fielddef *upb_oneofdef_ntof(const upb_oneofdef *o,
  2504. const char *name, size_t length) {
  2505. upb_value val;
  2506. return upb_strtable_lookup2(&o->ntof, name, length, &val) ?
  2507. upb_value_getptr(val) : NULL;
  2508. }
  2509. const upb_fielddef *upb_oneofdef_itof(const upb_oneofdef *o, uint32_t num) {
  2510. upb_value val;
  2511. return upb_inttable_lookup32(&o->itof, num, &val) ?
  2512. upb_value_getptr(val) : NULL;
  2513. }
  2514. void upb_oneof_begin(upb_oneof_iter *iter, const upb_oneofdef *o) {
  2515. upb_inttable_begin(iter, &o->itof);
  2516. }
  2517. void upb_oneof_next(upb_oneof_iter *iter) {
  2518. upb_inttable_next(iter);
  2519. }
  2520. bool upb_oneof_done(upb_oneof_iter *iter) {
  2521. return upb_inttable_done(iter);
  2522. }
  2523. upb_fielddef *upb_oneof_iter_field(const upb_oneof_iter *iter) {
  2524. return (upb_fielddef*)upb_value_getptr(upb_inttable_iter_value(iter));
  2525. }
  2526. void upb_oneof_iter_setdone(upb_oneof_iter *iter) {
  2527. upb_inttable_iter_setdone(iter);
  2528. }
  2529. /* upb_filedef ****************************************************************/
  2530. static void visitfiledef(const upb_refcounted *r, upb_refcounted_visit *visit,
  2531. void *closure) {
  2532. const upb_filedef *f = (const upb_filedef*)r;
  2533. size_t i;
  2534. for(i = 0; i < upb_filedef_defcount(f); i++) {
  2535. visit(r, upb_def_upcast(upb_filedef_def(f, i)), closure);
  2536. }
  2537. }
  2538. static void freefiledef(upb_refcounted *r) {
  2539. upb_filedef *f = (upb_filedef*)r;
  2540. size_t i;
  2541. for(i = 0; i < upb_filedef_depcount(f); i++) {
  2542. upb_filedef_unref(upb_filedef_dep(f, i), f);
  2543. }
  2544. upb_inttable_uninit(&f->defs);
  2545. upb_inttable_uninit(&f->deps);
  2546. upb_gfree((void*)f->name);
  2547. upb_gfree((void*)f->package);
  2548. upb_gfree((void*)f->phpprefix);
  2549. upb_gfree((void*)f->phpnamespace);
  2550. upb_gfree(f);
  2551. }
  2552. const struct upb_refcounted_vtbl upb_filedef_vtbl = {visitfiledef, freefiledef};
  2553. upb_filedef *upb_filedef_new(const void *owner) {
  2554. upb_filedef *f = upb_gmalloc(sizeof(*f));
  2555. if (!f) {
  2556. return NULL;
  2557. }
  2558. f->package = NULL;
  2559. f->name = NULL;
  2560. f->phpprefix = NULL;
  2561. f->phpnamespace = NULL;
  2562. f->syntax = UPB_SYNTAX_PROTO2;
  2563. if (!upb_refcounted_init(upb_filedef_upcast_mutable(f), &upb_filedef_vtbl,
  2564. owner)) {
  2565. goto err;
  2566. }
  2567. if (!upb_inttable_init(&f->defs, UPB_CTYPE_CONSTPTR)) {
  2568. goto err;
  2569. }
  2570. if (!upb_inttable_init(&f->deps, UPB_CTYPE_CONSTPTR)) {
  2571. goto err2;
  2572. }
  2573. return f;
  2574. err2:
  2575. upb_inttable_uninit(&f->defs);
  2576. err:
  2577. upb_gfree(f);
  2578. return NULL;
  2579. }
  2580. const char *upb_filedef_name(const upb_filedef *f) {
  2581. return f->name;
  2582. }
  2583. const char *upb_filedef_package(const upb_filedef *f) {
  2584. return f->package;
  2585. }
  2586. const char *upb_filedef_phpprefix(const upb_filedef *f) {
  2587. return f->phpprefix;
  2588. }
  2589. const char *upb_filedef_phpnamespace(const upb_filedef *f) {
  2590. return f->phpnamespace;
  2591. }
  2592. upb_syntax_t upb_filedef_syntax(const upb_filedef *f) {
  2593. return f->syntax;
  2594. }
  2595. size_t upb_filedef_defcount(const upb_filedef *f) {
  2596. return upb_inttable_count(&f->defs);
  2597. }
  2598. size_t upb_filedef_depcount(const upb_filedef *f) {
  2599. return upb_inttable_count(&f->deps);
  2600. }
  2601. const upb_def *upb_filedef_def(const upb_filedef *f, size_t i) {
  2602. upb_value v;
  2603. if (upb_inttable_lookup32(&f->defs, i, &v)) {
  2604. return upb_value_getconstptr(v);
  2605. } else {
  2606. return NULL;
  2607. }
  2608. }
  2609. const upb_filedef *upb_filedef_dep(const upb_filedef *f, size_t i) {
  2610. upb_value v;
  2611. if (upb_inttable_lookup32(&f->deps, i, &v)) {
  2612. return upb_value_getconstptr(v);
  2613. } else {
  2614. return NULL;
  2615. }
  2616. }
  2617. bool upb_filedef_setname(upb_filedef *f, const char *name, upb_status *s) {
  2618. name = upb_gstrdup(name);
  2619. if (!name) {
  2620. upb_upberr_setoom(s);
  2621. return false;
  2622. }
  2623. upb_gfree((void*)f->name);
  2624. f->name = name;
  2625. return true;
  2626. }
  2627. bool upb_filedef_setpackage(upb_filedef *f, const char *package,
  2628. upb_status *s) {
  2629. if (!upb_isident(package, strlen(package), true, s)) return false;
  2630. package = upb_gstrdup(package);
  2631. if (!package) {
  2632. upb_upberr_setoom(s);
  2633. return false;
  2634. }
  2635. upb_gfree((void*)f->package);
  2636. f->package = package;
  2637. return true;
  2638. }
  2639. bool upb_filedef_setphpprefix(upb_filedef *f, const char *phpprefix,
  2640. upb_status *s) {
  2641. phpprefix = upb_gstrdup(phpprefix);
  2642. if (!phpprefix) {
  2643. upb_upberr_setoom(s);
  2644. return false;
  2645. }
  2646. upb_gfree((void*)f->phpprefix);
  2647. f->phpprefix = phpprefix;
  2648. return true;
  2649. }
  2650. bool upb_filedef_setphpnamespace(upb_filedef *f, const char *phpnamespace,
  2651. upb_status *s) {
  2652. phpnamespace = upb_gstrdup(phpnamespace);
  2653. if (!phpnamespace) {
  2654. upb_upberr_setoom(s);
  2655. return false;
  2656. }
  2657. upb_gfree((void*)f->phpnamespace);
  2658. f->phpnamespace = phpnamespace;
  2659. return true;
  2660. }
  2661. bool upb_filedef_setsyntax(upb_filedef *f, upb_syntax_t syntax,
  2662. upb_status *s) {
  2663. UPB_UNUSED(s);
  2664. if (syntax != UPB_SYNTAX_PROTO2 &&
  2665. syntax != UPB_SYNTAX_PROTO3) {
  2666. upb_status_seterrmsg(s, "Unknown syntax value.");
  2667. return false;
  2668. }
  2669. f->syntax = syntax;
  2670. {
  2671. /* Set all messages in this file to match. */
  2672. size_t i;
  2673. for (i = 0; i < upb_filedef_defcount(f); i++) {
  2674. /* Casting const away is safe since all defs in mutable filedef must
  2675. * also be mutable. */
  2676. upb_def *def = (upb_def*)upb_filedef_def(f, i);
  2677. upb_msgdef *m = upb_dyncast_msgdef_mutable(def);
  2678. if (m) {
  2679. m->syntax = syntax;
  2680. }
  2681. }
  2682. }
  2683. return true;
  2684. }
  2685. bool upb_filedef_adddef(upb_filedef *f, upb_def *def, const void *ref_donor,
  2686. upb_status *s) {
  2687. if (def->file) {
  2688. upb_status_seterrmsg(s, "Def is already part of another filedef.");
  2689. return false;
  2690. }
  2691. if (upb_inttable_push(&f->defs, upb_value_constptr(def))) {
  2692. def->file = f;
  2693. upb_ref2(def, f);
  2694. upb_ref2(f, def);
  2695. if (ref_donor) upb_def_unref(def, ref_donor);
  2696. if (def->type == UPB_DEF_MSG) {
  2697. upb_downcast_msgdef_mutable(def)->syntax = f->syntax;
  2698. }
  2699. return true;
  2700. } else {
  2701. upb_upberr_setoom(s);
  2702. return false;
  2703. }
  2704. }
  2705. bool upb_filedef_adddep(upb_filedef *f, const upb_filedef *dep) {
  2706. if (upb_inttable_push(&f->deps, upb_value_constptr(dep))) {
  2707. /* Regular ref instead of ref2 because files can't form cycles. */
  2708. upb_filedef_ref(dep, f);
  2709. return true;
  2710. } else {
  2711. return false;
  2712. }
  2713. }
  2714. void upb_symtab_free(upb_symtab *s) {
  2715. upb_strtable_iter i;
  2716. upb_strtable_begin(&i, &s->symtab);
  2717. for (; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  2718. const upb_def *def = upb_value_getptr(upb_strtable_iter_value(&i));
  2719. upb_def_unref(def, s);
  2720. }
  2721. upb_strtable_uninit(&s->symtab);
  2722. upb_gfree(s);
  2723. }
  2724. upb_symtab *upb_symtab_new() {
  2725. upb_symtab *s = upb_gmalloc(sizeof(*s));
  2726. if (!s) {
  2727. return NULL;
  2728. }
  2729. upb_strtable_init(&s->symtab, UPB_CTYPE_PTR);
  2730. return s;
  2731. }
  2732. const upb_def *upb_symtab_lookup(const upb_symtab *s, const char *sym) {
  2733. upb_value v;
  2734. upb_def *ret = upb_strtable_lookup(&s->symtab, sym, &v) ?
  2735. upb_value_getptr(v) : NULL;
  2736. return ret;
  2737. }
  2738. const upb_msgdef *upb_symtab_lookupmsg(const upb_symtab *s, const char *sym) {
  2739. upb_value v;
  2740. upb_def *def = upb_strtable_lookup(&s->symtab, sym, &v) ?
  2741. upb_value_getptr(v) : NULL;
  2742. return def ? upb_dyncast_msgdef(def) : NULL;
  2743. }
  2744. const upb_msgdef *upb_symtab_lookupmsg2(const upb_symtab *s, const char *sym,
  2745. size_t len) {
  2746. upb_value v;
  2747. upb_def *def = upb_strtable_lookup2(&s->symtab, sym, len, &v) ?
  2748. upb_value_getptr(v) : NULL;
  2749. return def ? upb_dyncast_msgdef(def) : NULL;
  2750. }
  2751. const upb_enumdef *upb_symtab_lookupenum(const upb_symtab *s, const char *sym) {
  2752. upb_value v;
  2753. upb_def *def = upb_strtable_lookup(&s->symtab, sym, &v) ?
  2754. upb_value_getptr(v) : NULL;
  2755. return def ? upb_dyncast_enumdef(def) : NULL;
  2756. }
  2757. /* Given a symbol and the base symbol inside which it is defined, find the
  2758. * symbol's definition in t. */
  2759. static upb_def *upb_resolvename(const upb_strtable *t,
  2760. const char *base, const char *sym) {
  2761. if(strlen(sym) == 0) return NULL;
  2762. if(sym[0] == '.') {
  2763. /* Symbols starting with '.' are absolute, so we do a single lookup.
  2764. * Slice to omit the leading '.' */
  2765. upb_value v;
  2766. return upb_strtable_lookup(t, sym + 1, &v) ? upb_value_getptr(v) : NULL;
  2767. } else {
  2768. /* Remove components from base until we find an entry or run out.
  2769. * TODO: This branch is totally broken, but currently not used. */
  2770. (void)base;
  2771. UPB_ASSERT(false);
  2772. return NULL;
  2773. }
  2774. }
  2775. const upb_def *upb_symtab_resolve(const upb_symtab *s, const char *base,
  2776. const char *sym) {
  2777. upb_def *ret = upb_resolvename(&s->symtab, base, sym);
  2778. return ret;
  2779. }
  2780. /* TODO(haberman): we need a lot more testing of error conditions. */
  2781. static bool symtab_add(upb_symtab *s, upb_def *const*defs, size_t n,
  2782. void *ref_donor, upb_refcounted *freeze_also,
  2783. upb_status *status) {
  2784. size_t i;
  2785. size_t add_n;
  2786. size_t freeze_n;
  2787. upb_strtable_iter iter;
  2788. upb_refcounted **add_objs = NULL;
  2789. upb_def **add_defs = NULL;
  2790. size_t add_objs_size;
  2791. upb_strtable addtab;
  2792. if (n == 0 && !freeze_also) {
  2793. return true;
  2794. }
  2795. if (!upb_strtable_init(&addtab, UPB_CTYPE_PTR)) {
  2796. upb_status_seterrmsg(status, "out of memory");
  2797. return false;
  2798. }
  2799. /* Add new defs to our "add" set. */
  2800. for (i = 0; i < n; i++) {
  2801. upb_def *def = defs[i];
  2802. const char *fullname;
  2803. upb_fielddef *f;
  2804. if (upb_def_isfrozen(def)) {
  2805. upb_status_seterrmsg(status, "added defs must be mutable");
  2806. goto err;
  2807. }
  2808. UPB_ASSERT(!upb_def_isfrozen(def));
  2809. fullname = upb_def_fullname(def);
  2810. if (!fullname) {
  2811. upb_status_seterrmsg(
  2812. status, "Anonymous defs cannot be added to a symtab");
  2813. goto err;
  2814. }
  2815. f = upb_dyncast_fielddef_mutable(def);
  2816. if (f) {
  2817. if (!upb_fielddef_containingtypename(f)) {
  2818. upb_status_seterrmsg(status,
  2819. "Standalone fielddefs must have a containing type "
  2820. "(extendee) name set");
  2821. goto err;
  2822. }
  2823. } else {
  2824. if (upb_strtable_lookup(&addtab, fullname, NULL)) {
  2825. upb_status_seterrf(status, "Conflicting defs named '%s'", fullname);
  2826. goto err;
  2827. }
  2828. if (upb_strtable_lookup(&s->symtab, fullname, NULL)) {
  2829. upb_status_seterrf(status, "Symtab already has a def named '%s'",
  2830. fullname);
  2831. goto err;
  2832. }
  2833. if (!upb_strtable_insert(&addtab, fullname, upb_value_ptr(def)))
  2834. goto oom_err;
  2835. upb_def_donateref(def, ref_donor, s);
  2836. }
  2837. if (upb_dyncast_fielddef_mutable(def)) {
  2838. /* TODO(haberman): allow adding extensions attached to files. */
  2839. upb_status_seterrf(status, "Can't add extensions to symtab.\n");
  2840. goto err;
  2841. }
  2842. }
  2843. /* Now using the table, resolve symbolic references for subdefs. */
  2844. upb_strtable_begin(&iter, &addtab);
  2845. for (; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
  2846. const char *base;
  2847. upb_def *def = upb_value_getptr(upb_strtable_iter_value(&iter));
  2848. upb_msgdef *m = upb_dyncast_msgdef_mutable(def);
  2849. upb_msg_field_iter j;
  2850. if (!m) continue;
  2851. /* Type names are resolved relative to the message in which they appear. */
  2852. base = upb_msgdef_fullname(m);
  2853. for(upb_msg_field_begin(&j, m);
  2854. !upb_msg_field_done(&j);
  2855. upb_msg_field_next(&j)) {
  2856. upb_fielddef *f = upb_msg_iter_field(&j);
  2857. const char *name = upb_fielddef_subdefname(f);
  2858. if (name && !upb_fielddef_subdef(f)) {
  2859. /* Try the lookup in the current set of to-be-added defs first. If not
  2860. * there, try existing defs. */
  2861. upb_def *subdef = upb_resolvename(&addtab, base, name);
  2862. if (subdef == NULL) {
  2863. subdef = upb_resolvename(&s->symtab, base, name);
  2864. }
  2865. if (subdef == NULL) {
  2866. upb_status_seterrf(
  2867. status, "couldn't resolve name '%s' in message '%s'", name, base);
  2868. goto err;
  2869. } else if (!upb_fielddef_setsubdef(f, subdef, status)) {
  2870. goto err;
  2871. }
  2872. }
  2873. }
  2874. }
  2875. /* We need an array of the defs in addtab, for passing to
  2876. * upb_refcounted_freeze(). */
  2877. add_objs_size = upb_strtable_count(&addtab);
  2878. if (freeze_also) {
  2879. add_objs_size++;
  2880. }
  2881. add_defs = upb_gmalloc(sizeof(void*) * add_objs_size);
  2882. if (add_defs == NULL) goto oom_err;
  2883. upb_strtable_begin(&iter, &addtab);
  2884. for (add_n = 0; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
  2885. add_defs[add_n++] = upb_value_getptr(upb_strtable_iter_value(&iter));
  2886. }
  2887. /* Validate defs. */
  2888. if (!_upb_def_validate(add_defs, add_n, status)) {
  2889. goto err;
  2890. }
  2891. /* Cheat a little and give the array a new type.
  2892. * This is probably undefined behavior, but this code will be deleted soon. */
  2893. add_objs = (upb_refcounted**)add_defs;
  2894. freeze_n = add_n;
  2895. if (freeze_also) {
  2896. add_objs[freeze_n++] = freeze_also;
  2897. }
  2898. if (!upb_refcounted_freeze(add_objs, freeze_n, status,
  2899. UPB_MAX_MESSAGE_DEPTH * 2)) {
  2900. goto err;
  2901. }
  2902. /* This must be delayed until all errors have been detected, since error
  2903. * recovery code uses this table to cleanup defs. */
  2904. upb_strtable_uninit(&addtab);
  2905. /* TODO(haberman) we don't properly handle errors after this point (like
  2906. * OOM in upb_strtable_insert() below). */
  2907. for (i = 0; i < add_n; i++) {
  2908. upb_def *def = (upb_def*)add_objs[i];
  2909. const char *name = upb_def_fullname(def);
  2910. bool success;
  2911. success = upb_strtable_insert(&s->symtab, name, upb_value_ptr(def));
  2912. UPB_ASSERT(success);
  2913. }
  2914. upb_gfree(add_defs);
  2915. return true;
  2916. oom_err:
  2917. upb_status_seterrmsg(status, "out of memory");
  2918. err: {
  2919. /* We need to donate the refs back. */
  2920. upb_strtable_begin(&iter, &addtab);
  2921. for (; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
  2922. upb_def *def = upb_value_getptr(upb_strtable_iter_value(&iter));
  2923. upb_def_donateref(def, s, ref_donor);
  2924. }
  2925. }
  2926. upb_strtable_uninit(&addtab);
  2927. upb_gfree(add_defs);
  2928. UPB_ASSERT(!upb_ok(status));
  2929. return false;
  2930. }
  2931. bool upb_symtab_add(upb_symtab *s, upb_def *const*defs, size_t n,
  2932. void *ref_donor, upb_status *status) {
  2933. return symtab_add(s, defs, n, ref_donor, NULL, status);
  2934. }
  2935. bool upb_symtab_addfile(upb_symtab *s, upb_filedef *file, upb_status *status) {
  2936. size_t n;
  2937. size_t i;
  2938. upb_def **defs;
  2939. bool ret;
  2940. n = upb_filedef_defcount(file);
  2941. if (n == 0) {
  2942. return true;
  2943. }
  2944. defs = upb_gmalloc(sizeof(*defs) * n);
  2945. if (defs == NULL) {
  2946. upb_status_seterrmsg(status, "Out of memory");
  2947. return false;
  2948. }
  2949. for (i = 0; i < n; i++) {
  2950. defs[i] = upb_filedef_mutabledef(file, i);
  2951. }
  2952. ret = symtab_add(s, defs, n, NULL, upb_filedef_upcast_mutable(file), status);
  2953. upb_gfree(defs);
  2954. return ret;
  2955. }
  2956. /* Iteration. */
  2957. static void advance_to_matching(upb_symtab_iter *iter) {
  2958. if (iter->type == UPB_DEF_ANY)
  2959. return;
  2960. while (!upb_strtable_done(&iter->iter) &&
  2961. iter->type != upb_symtab_iter_def(iter)->type) {
  2962. upb_strtable_next(&iter->iter);
  2963. }
  2964. }
  2965. void upb_symtab_begin(upb_symtab_iter *iter, const upb_symtab *s,
  2966. upb_deftype_t type) {
  2967. upb_strtable_begin(&iter->iter, &s->symtab);
  2968. iter->type = type;
  2969. advance_to_matching(iter);
  2970. }
  2971. void upb_symtab_next(upb_symtab_iter *iter) {
  2972. upb_strtable_next(&iter->iter);
  2973. advance_to_matching(iter);
  2974. }
  2975. bool upb_symtab_done(const upb_symtab_iter *iter) {
  2976. return upb_strtable_done(&iter->iter);
  2977. }
  2978. const upb_def *upb_symtab_iter_def(const upb_symtab_iter *iter) {
  2979. return upb_value_getptr(upb_strtable_iter_value(&iter->iter));
  2980. }
  2981. /* We encode backwards, to avoid pre-computing lengths (one-pass encode). */
  2982. #define UPB_PB_VARINT_MAX_LEN 10
  2983. #define CHK(x) do { if (!(x)) { return false; } } while(0)
  2984. /* Maps descriptor type -> upb field type. */
  2985. static const uint8_t upb_desctype_to_fieldtype2[] = {
  2986. UPB_WIRE_TYPE_END_GROUP, /* ENDGROUP */
  2987. UPB_TYPE_DOUBLE, /* DOUBLE */
  2988. UPB_TYPE_FLOAT, /* FLOAT */
  2989. UPB_TYPE_INT64, /* INT64 */
  2990. UPB_TYPE_UINT64, /* UINT64 */
  2991. UPB_TYPE_INT32, /* INT32 */
  2992. UPB_TYPE_UINT64, /* FIXED64 */
  2993. UPB_TYPE_UINT32, /* FIXED32 */
  2994. UPB_TYPE_BOOL, /* BOOL */
  2995. UPB_TYPE_STRING, /* STRING */
  2996. UPB_TYPE_MESSAGE, /* GROUP */
  2997. UPB_TYPE_MESSAGE, /* MESSAGE */
  2998. UPB_TYPE_BYTES, /* BYTES */
  2999. UPB_TYPE_UINT32, /* UINT32 */
  3000. UPB_TYPE_ENUM, /* ENUM */
  3001. UPB_TYPE_INT32, /* SFIXED32 */
  3002. UPB_TYPE_INT64, /* SFIXED64 */
  3003. UPB_TYPE_INT32, /* SINT32 */
  3004. UPB_TYPE_INT64, /* SINT64 */
  3005. };
  3006. static size_t upb_encode_varint(uint64_t val, char *buf) {
  3007. size_t i;
  3008. if (val < 128) { buf[0] = val; return 1; }
  3009. i = 0;
  3010. while (val) {
  3011. uint8_t byte = val & 0x7fU;
  3012. val >>= 7;
  3013. if (val) byte |= 0x80U;
  3014. buf[i++] = byte;
  3015. }
  3016. return i;
  3017. }
  3018. static uint32_t upb_zzencode_32(int32_t n) { return (n << 1) ^ (n >> 31); }
  3019. static uint64_t upb_zzencode_64(int64_t n) { return (n << 1) ^ (n >> 63); }
  3020. typedef struct {
  3021. upb_alloc *alloc;
  3022. char *buf, *ptr, *limit;
  3023. } upb_encstate;
  3024. static size_t upb_roundup_pow2(size_t bytes) {
  3025. size_t ret = 128;
  3026. while (ret < bytes) {
  3027. ret *= 2;
  3028. }
  3029. return ret;
  3030. }
  3031. static bool upb_encode_growbuffer(upb_encstate *e, size_t bytes) {
  3032. size_t old_size = e->limit - e->buf;
  3033. size_t new_size = upb_roundup_pow2(bytes + (e->limit - e->ptr));
  3034. char *new_buf = upb_realloc(e->alloc, e->buf, old_size, new_size);
  3035. CHK(new_buf);
  3036. /* We want previous data at the end, realloc() put it at the beginning. */
  3037. memmove(new_buf + new_size - old_size, e->buf, old_size);
  3038. e->ptr = new_buf + new_size - (e->limit - e->ptr);
  3039. e->limit = new_buf + new_size;
  3040. e->buf = new_buf;
  3041. return true;
  3042. }
  3043. /* Call to ensure that at least "bytes" bytes are available for writing at
  3044. * e->ptr. Returns false if the bytes could not be allocated. */
  3045. static bool upb_encode_reserve(upb_encstate *e, size_t bytes) {
  3046. CHK(UPB_LIKELY((size_t)(e->ptr - e->buf) >= bytes) ||
  3047. upb_encode_growbuffer(e, bytes));
  3048. e->ptr -= bytes;
  3049. return true;
  3050. }
  3051. /* Writes the given bytes to the buffer, handling reserve/advance. */
  3052. static bool upb_put_bytes(upb_encstate *e, const void *data, size_t len) {
  3053. CHK(upb_encode_reserve(e, len));
  3054. memcpy(e->ptr, data, len);
  3055. return true;
  3056. }
  3057. static bool upb_put_fixed64(upb_encstate *e, uint64_t val) {
  3058. /* TODO(haberman): byte-swap for big endian. */
  3059. return upb_put_bytes(e, &val, sizeof(uint64_t));
  3060. }
  3061. static bool upb_put_fixed32(upb_encstate *e, uint32_t val) {
  3062. /* TODO(haberman): byte-swap for big endian. */
  3063. return upb_put_bytes(e, &val, sizeof(uint32_t));
  3064. }
  3065. static bool upb_put_varint(upb_encstate *e, uint64_t val) {
  3066. size_t len;
  3067. char *start;
  3068. CHK(upb_encode_reserve(e, UPB_PB_VARINT_MAX_LEN));
  3069. len = upb_encode_varint(val, e->ptr);
  3070. start = e->ptr + UPB_PB_VARINT_MAX_LEN - len;
  3071. memmove(start, e->ptr, len);
  3072. e->ptr = start;
  3073. return true;
  3074. }
  3075. static bool upb_put_double(upb_encstate *e, double d) {
  3076. uint64_t u64;
  3077. UPB_ASSERT(sizeof(double) == sizeof(uint64_t));
  3078. memcpy(&u64, &d, sizeof(uint64_t));
  3079. return upb_put_fixed64(e, u64);
  3080. }
  3081. static bool upb_put_float(upb_encstate *e, float d) {
  3082. uint32_t u32;
  3083. UPB_ASSERT(sizeof(float) == sizeof(uint32_t));
  3084. memcpy(&u32, &d, sizeof(uint32_t));
  3085. return upb_put_fixed32(e, u32);
  3086. }
  3087. static uint32_t upb_readcase(const char *msg, const upb_msglayout_field *f) {
  3088. uint32_t ret;
  3089. uint32_t offset = ~f->presence;
  3090. memcpy(&ret, msg + offset, sizeof(ret));
  3091. return ret;
  3092. }
  3093. static bool upb_readhasbit(const char *msg, const upb_msglayout_field *f) {
  3094. uint32_t hasbit = f->presence;
  3095. UPB_ASSERT(f->presence > 0);
  3096. return msg[hasbit / 8] & (1 << (hasbit % 8));
  3097. }
  3098. static bool upb_put_tag(upb_encstate *e, int field_number, int wire_type) {
  3099. return upb_put_varint(e, (field_number << 3) | wire_type);
  3100. }
  3101. static bool upb_put_fixedarray(upb_encstate *e, const upb_array *arr,
  3102. size_t size) {
  3103. size_t bytes = arr->len * size;
  3104. return upb_put_bytes(e, arr->data, bytes) && upb_put_varint(e, bytes);
  3105. }
  3106. bool upb_encode_message(upb_encstate *e, const char *msg,
  3107. const upb_msglayout *m, size_t *size);
  3108. static bool upb_encode_array(upb_encstate *e, const char *field_mem,
  3109. const upb_msglayout *m,
  3110. const upb_msglayout_field *f) {
  3111. const upb_array *arr = *(const upb_array**)field_mem;
  3112. if (arr == NULL || arr->len == 0) {
  3113. return true;
  3114. }
  3115. UPB_ASSERT(arr->type == upb_desctype_to_fieldtype2[f->descriptortype]);
  3116. #define VARINT_CASE(ctype, encode) { \
  3117. ctype *start = arr->data; \
  3118. ctype *ptr = start + arr->len; \
  3119. size_t pre_len = e->limit - e->ptr; \
  3120. do { \
  3121. ptr--; \
  3122. CHK(upb_put_varint(e, encode)); \
  3123. } while (ptr != start); \
  3124. CHK(upb_put_varint(e, e->limit - e->ptr - pre_len)); \
  3125. } \
  3126. break; \
  3127. do { ; } while(0)
  3128. switch (f->descriptortype) {
  3129. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  3130. CHK(upb_put_fixedarray(e, arr, sizeof(double)));
  3131. break;
  3132. case UPB_DESCRIPTOR_TYPE_FLOAT:
  3133. CHK(upb_put_fixedarray(e, arr, sizeof(float)));
  3134. break;
  3135. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  3136. case UPB_DESCRIPTOR_TYPE_FIXED64:
  3137. CHK(upb_put_fixedarray(e, arr, sizeof(uint64_t)));
  3138. break;
  3139. case UPB_DESCRIPTOR_TYPE_FIXED32:
  3140. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  3141. CHK(upb_put_fixedarray(e, arr, sizeof(uint32_t)));
  3142. break;
  3143. case UPB_DESCRIPTOR_TYPE_INT64:
  3144. case UPB_DESCRIPTOR_TYPE_UINT64:
  3145. VARINT_CASE(uint64_t, *ptr);
  3146. case UPB_DESCRIPTOR_TYPE_UINT32:
  3147. VARINT_CASE(uint32_t, *ptr);
  3148. case UPB_DESCRIPTOR_TYPE_INT32:
  3149. case UPB_DESCRIPTOR_TYPE_ENUM:
  3150. VARINT_CASE(int32_t, (int64_t)*ptr);
  3151. case UPB_DESCRIPTOR_TYPE_BOOL:
  3152. VARINT_CASE(bool, *ptr);
  3153. case UPB_DESCRIPTOR_TYPE_SINT32:
  3154. VARINT_CASE(int32_t, upb_zzencode_32(*ptr));
  3155. case UPB_DESCRIPTOR_TYPE_SINT64:
  3156. VARINT_CASE(int64_t, upb_zzencode_64(*ptr));
  3157. case UPB_DESCRIPTOR_TYPE_STRING:
  3158. case UPB_DESCRIPTOR_TYPE_BYTES: {
  3159. upb_strview *start = arr->data;
  3160. upb_strview *ptr = start + arr->len;
  3161. do {
  3162. ptr--;
  3163. CHK(upb_put_bytes(e, ptr->data, ptr->size) &&
  3164. upb_put_varint(e, ptr->size) &&
  3165. upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
  3166. } while (ptr != start);
  3167. return true;
  3168. }
  3169. case UPB_DESCRIPTOR_TYPE_GROUP: {
  3170. void **start = arr->data;
  3171. void **ptr = start + arr->len;
  3172. const upb_msglayout *subm = m->submsgs[f->submsg_index];
  3173. do {
  3174. size_t size;
  3175. ptr--;
  3176. CHK(upb_put_tag(e, f->number, UPB_WIRE_TYPE_END_GROUP) &&
  3177. upb_encode_message(e, *ptr, subm, &size) &&
  3178. upb_put_tag(e, f->number, UPB_WIRE_TYPE_START_GROUP));
  3179. } while (ptr != start);
  3180. return true;
  3181. }
  3182. case UPB_DESCRIPTOR_TYPE_MESSAGE: {
  3183. void **start = arr->data;
  3184. void **ptr = start + arr->len;
  3185. const upb_msglayout *subm = m->submsgs[f->submsg_index];
  3186. do {
  3187. size_t size;
  3188. ptr--;
  3189. CHK(upb_encode_message(e, *ptr, subm, &size) &&
  3190. upb_put_varint(e, size) &&
  3191. upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
  3192. } while (ptr != start);
  3193. return true;
  3194. }
  3195. }
  3196. #undef VARINT_CASE
  3197. /* We encode all primitive arrays as packed, regardless of what was specified
  3198. * in the .proto file. Could special case 1-sized arrays. */
  3199. CHK(upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
  3200. return true;
  3201. }
  3202. static bool upb_encode_scalarfield(upb_encstate *e, const char *field_mem,
  3203. const upb_msglayout *m,
  3204. const upb_msglayout_field *f,
  3205. bool skip_zero_value) {
  3206. #define CASE(ctype, type, wire_type, encodeval) do { \
  3207. ctype val = *(ctype*)field_mem; \
  3208. if (skip_zero_value && val == 0) { \
  3209. return true; \
  3210. } \
  3211. return upb_put_ ## type(e, encodeval) && \
  3212. upb_put_tag(e, f->number, wire_type); \
  3213. } while(0)
  3214. switch (f->descriptortype) {
  3215. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  3216. CASE(double, double, UPB_WIRE_TYPE_64BIT, val);
  3217. case UPB_DESCRIPTOR_TYPE_FLOAT:
  3218. CASE(float, float, UPB_WIRE_TYPE_32BIT, val);
  3219. case UPB_DESCRIPTOR_TYPE_INT64:
  3220. case UPB_DESCRIPTOR_TYPE_UINT64:
  3221. CASE(uint64_t, varint, UPB_WIRE_TYPE_VARINT, val);
  3222. case UPB_DESCRIPTOR_TYPE_UINT32:
  3223. CASE(uint32_t, varint, UPB_WIRE_TYPE_VARINT, val);
  3224. case UPB_DESCRIPTOR_TYPE_INT32:
  3225. case UPB_DESCRIPTOR_TYPE_ENUM:
  3226. CASE(int32_t, varint, UPB_WIRE_TYPE_VARINT, (int64_t)val);
  3227. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  3228. case UPB_DESCRIPTOR_TYPE_FIXED64:
  3229. CASE(uint64_t, fixed64, UPB_WIRE_TYPE_64BIT, val);
  3230. case UPB_DESCRIPTOR_TYPE_FIXED32:
  3231. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  3232. CASE(uint32_t, fixed32, UPB_WIRE_TYPE_32BIT, val);
  3233. case UPB_DESCRIPTOR_TYPE_BOOL:
  3234. CASE(bool, varint, UPB_WIRE_TYPE_VARINT, val);
  3235. case UPB_DESCRIPTOR_TYPE_SINT32:
  3236. CASE(int32_t, varint, UPB_WIRE_TYPE_VARINT, upb_zzencode_32(val));
  3237. case UPB_DESCRIPTOR_TYPE_SINT64:
  3238. CASE(int64_t, varint, UPB_WIRE_TYPE_VARINT, upb_zzencode_64(val));
  3239. case UPB_DESCRIPTOR_TYPE_STRING:
  3240. case UPB_DESCRIPTOR_TYPE_BYTES: {
  3241. upb_strview view = *(upb_strview*)field_mem;
  3242. if (skip_zero_value && view.size == 0) {
  3243. return true;
  3244. }
  3245. return upb_put_bytes(e, view.data, view.size) &&
  3246. upb_put_varint(e, view.size) &&
  3247. upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED);
  3248. }
  3249. case UPB_DESCRIPTOR_TYPE_GROUP: {
  3250. size_t size;
  3251. void *submsg = *(void **)field_mem;
  3252. const upb_msglayout *subm = m->submsgs[f->submsg_index];
  3253. if (submsg == NULL) {
  3254. return true;
  3255. }
  3256. return upb_put_tag(e, f->number, UPB_WIRE_TYPE_END_GROUP) &&
  3257. upb_encode_message(e, submsg, subm, &size) &&
  3258. upb_put_tag(e, f->number, UPB_WIRE_TYPE_START_GROUP);
  3259. }
  3260. case UPB_DESCRIPTOR_TYPE_MESSAGE: {
  3261. size_t size;
  3262. void *submsg = *(void **)field_mem;
  3263. const upb_msglayout *subm = m->submsgs[f->submsg_index];
  3264. if (submsg == NULL) {
  3265. return true;
  3266. }
  3267. return upb_encode_message(e, submsg, subm, &size) &&
  3268. upb_put_varint(e, size) &&
  3269. upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED);
  3270. }
  3271. }
  3272. #undef CASE
  3273. UPB_UNREACHABLE();
  3274. }
  3275. bool upb_encode_message(upb_encstate *e, const char *msg,
  3276. const upb_msglayout *m, size_t *size) {
  3277. int i;
  3278. size_t pre_len = e->limit - e->ptr;
  3279. const char *unknown;
  3280. size_t unknown_size;
  3281. for (i = m->field_count - 1; i >= 0; i--) {
  3282. const upb_msglayout_field *f = &m->fields[i];
  3283. if (f->label == UPB_LABEL_REPEATED) {
  3284. CHK(upb_encode_array(e, msg + f->offset, m, f));
  3285. } else {
  3286. bool skip_empty = false;
  3287. if (f->presence == 0) {
  3288. /* Proto3 presence. */
  3289. skip_empty = true;
  3290. } else if (f->presence > 0) {
  3291. /* Proto2 presence: hasbit. */
  3292. if (!upb_readhasbit(msg, f)) {
  3293. continue;
  3294. }
  3295. } else {
  3296. /* Field is in a oneof. */
  3297. if (upb_readcase(msg, f) != f->number) {
  3298. continue;
  3299. }
  3300. }
  3301. CHK(upb_encode_scalarfield(e, msg + f->offset, m, f, skip_empty));
  3302. }
  3303. }
  3304. unknown = upb_msg_getunknown(msg, &unknown_size);
  3305. if (unknown) {
  3306. upb_put_bytes(e, unknown, unknown_size);
  3307. }
  3308. *size = (e->limit - e->ptr) - pre_len;
  3309. return true;
  3310. }
  3311. char *upb_encode(const void *msg, const upb_msglayout *m, upb_arena *arena,
  3312. size_t *size) {
  3313. upb_encstate e;
  3314. e.alloc = upb_arena_alloc(arena);
  3315. e.buf = NULL;
  3316. e.limit = NULL;
  3317. e.ptr = NULL;
  3318. if (!upb_encode_message(&e, msg, m, size)) {
  3319. *size = 0;
  3320. return NULL;
  3321. }
  3322. *size = e.limit - e.ptr;
  3323. if (*size == 0) {
  3324. static char ch;
  3325. return &ch;
  3326. } else {
  3327. UPB_ASSERT(e.ptr);
  3328. return e.ptr;
  3329. }
  3330. }
  3331. #undef CHK
  3332. /*
  3333. ** TODO(haberman): it's unclear whether a lot of the consistency checks should
  3334. ** UPB_ASSERT() or return false.
  3335. */
  3336. #include <string.h>
  3337. static void *upb_calloc(size_t size) {
  3338. void *mem = upb_gmalloc(size);
  3339. if (mem) {
  3340. memset(mem, 0, size);
  3341. }
  3342. return mem;
  3343. }
  3344. /* Defined for the sole purpose of having a unique pointer value for
  3345. * UPB_NO_CLOSURE. */
  3346. char _upb_noclosure;
  3347. static void freehandlers(upb_refcounted *r) {
  3348. upb_handlers *h = (upb_handlers*)r;
  3349. upb_inttable_iter i;
  3350. upb_inttable_begin(&i, &h->cleanup_);
  3351. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  3352. void *val = (void*)upb_inttable_iter_key(&i);
  3353. upb_value func_val = upb_inttable_iter_value(&i);
  3354. upb_handlerfree *func = upb_value_getfptr(func_val);
  3355. func(val);
  3356. }
  3357. upb_inttable_uninit(&h->cleanup_);
  3358. upb_msgdef_unref(h->msg, h);
  3359. upb_gfree(h->sub);
  3360. upb_gfree(h);
  3361. }
  3362. static void visithandlers(const upb_refcounted *r, upb_refcounted_visit *visit,
  3363. void *closure) {
  3364. const upb_handlers *h = (const upb_handlers*)r;
  3365. upb_msg_field_iter i;
  3366. for(upb_msg_field_begin(&i, h->msg);
  3367. !upb_msg_field_done(&i);
  3368. upb_msg_field_next(&i)) {
  3369. upb_fielddef *f = upb_msg_iter_field(&i);
  3370. const upb_handlers *sub;
  3371. if (!upb_fielddef_issubmsg(f)) continue;
  3372. sub = upb_handlers_getsubhandlers(h, f);
  3373. if (sub) visit(r, upb_handlers_upcast(sub), closure);
  3374. }
  3375. }
  3376. static const struct upb_refcounted_vtbl vtbl = {visithandlers, freehandlers};
  3377. typedef struct {
  3378. upb_inttable tab; /* maps upb_msgdef* -> upb_handlers*. */
  3379. upb_handlers_callback *callback;
  3380. const void *closure;
  3381. } dfs_state;
  3382. /* TODO(haberman): discard upb_handlers* objects that do not actually have any
  3383. * handlers set and cannot reach any upb_handlers* object that does. This is
  3384. * slightly tricky to do correctly. */
  3385. static upb_handlers *newformsg(const upb_msgdef *m, const void *owner,
  3386. dfs_state *s) {
  3387. upb_msg_field_iter i;
  3388. upb_handlers *h = upb_handlers_new(m, owner);
  3389. if (!h) return NULL;
  3390. if (!upb_inttable_insertptr(&s->tab, m, upb_value_ptr(h))) goto oom;
  3391. s->callback(s->closure, h);
  3392. /* For each submessage field, get or create a handlers object and set it as
  3393. * the subhandlers. */
  3394. for(upb_msg_field_begin(&i, m);
  3395. !upb_msg_field_done(&i);
  3396. upb_msg_field_next(&i)) {
  3397. upb_fielddef *f = upb_msg_iter_field(&i);
  3398. const upb_msgdef *subdef;
  3399. upb_value subm_ent;
  3400. if (!upb_fielddef_issubmsg(f)) continue;
  3401. subdef = upb_downcast_msgdef(upb_fielddef_subdef(f));
  3402. if (upb_inttable_lookupptr(&s->tab, subdef, &subm_ent)) {
  3403. upb_handlers_setsubhandlers(h, f, upb_value_getptr(subm_ent));
  3404. } else {
  3405. upb_handlers *sub_mh = newformsg(subdef, &sub_mh, s);
  3406. if (!sub_mh) goto oom;
  3407. upb_handlers_setsubhandlers(h, f, sub_mh);
  3408. upb_handlers_unref(sub_mh, &sub_mh);
  3409. }
  3410. }
  3411. return h;
  3412. oom:
  3413. upb_handlers_unref(h, owner);
  3414. return NULL;
  3415. }
  3416. /* Given a selector for a STARTSUBMSG handler, resolves to a pointer to the
  3417. * subhandlers for this submessage field. */
  3418. #define SUBH(h, selector) (h->sub[selector])
  3419. /* The selector for a submessage field is the field index. */
  3420. #define SUBH_F(h, f) SUBH(h, f->index_)
  3421. static int32_t trygetsel(upb_handlers *h, const upb_fielddef *f,
  3422. upb_handlertype_t type) {
  3423. upb_selector_t sel;
  3424. UPB_ASSERT(!upb_handlers_isfrozen(h));
  3425. if (upb_handlers_msgdef(h) != upb_fielddef_containingtype(f)) {
  3426. upb_status_seterrf(
  3427. &h->status_, "type mismatch: field %s does not belong to message %s",
  3428. upb_fielddef_name(f), upb_msgdef_fullname(upb_handlers_msgdef(h)));
  3429. return -1;
  3430. }
  3431. if (!upb_handlers_getselector(f, type, &sel)) {
  3432. upb_status_seterrf(
  3433. &h->status_,
  3434. "type mismatch: cannot register handler type %d for field %s",
  3435. type, upb_fielddef_name(f));
  3436. return -1;
  3437. }
  3438. return sel;
  3439. }
  3440. static upb_selector_t handlers_getsel(upb_handlers *h, const upb_fielddef *f,
  3441. upb_handlertype_t type) {
  3442. int32_t sel = trygetsel(h, f, type);
  3443. UPB_ASSERT(sel >= 0);
  3444. return sel;
  3445. }
  3446. static const void **returntype(upb_handlers *h, const upb_fielddef *f,
  3447. upb_handlertype_t type) {
  3448. return &h->table[handlers_getsel(h, f, type)].attr.return_closure_type_;
  3449. }
  3450. static bool doset(upb_handlers *h, int32_t sel, const upb_fielddef *f,
  3451. upb_handlertype_t type, upb_func *func,
  3452. upb_handlerattr *attr) {
  3453. upb_handlerattr set_attr = UPB_HANDLERATTR_INITIALIZER;
  3454. const void *closure_type;
  3455. const void **context_closure_type;
  3456. UPB_ASSERT(!upb_handlers_isfrozen(h));
  3457. if (sel < 0) {
  3458. upb_status_seterrmsg(&h->status_,
  3459. "incorrect handler type for this field.");
  3460. return false;
  3461. }
  3462. if (h->table[sel].func) {
  3463. upb_status_seterrmsg(&h->status_,
  3464. "cannot change handler once it has been set.");
  3465. return false;
  3466. }
  3467. if (attr) {
  3468. set_attr = *attr;
  3469. }
  3470. /* Check that the given closure type matches the closure type that has been
  3471. * established for this context (if any). */
  3472. closure_type = upb_handlerattr_closuretype(&set_attr);
  3473. if (type == UPB_HANDLER_STRING) {
  3474. context_closure_type = returntype(h, f, UPB_HANDLER_STARTSTR);
  3475. } else if (f && upb_fielddef_isseq(f) &&
  3476. type != UPB_HANDLER_STARTSEQ &&
  3477. type != UPB_HANDLER_ENDSEQ) {
  3478. context_closure_type = returntype(h, f, UPB_HANDLER_STARTSEQ);
  3479. } else {
  3480. context_closure_type = &h->top_closure_type;
  3481. }
  3482. if (closure_type && *context_closure_type &&
  3483. closure_type != *context_closure_type) {
  3484. /* TODO(haberman): better message for debugging. */
  3485. if (f) {
  3486. upb_status_seterrf(&h->status_,
  3487. "closure type does not match for field %s",
  3488. upb_fielddef_name(f));
  3489. } else {
  3490. upb_status_seterrmsg(
  3491. &h->status_, "closure type does not match for message-level handler");
  3492. }
  3493. return false;
  3494. }
  3495. if (closure_type)
  3496. *context_closure_type = closure_type;
  3497. /* If this is a STARTSEQ or STARTSTR handler, check that the returned pointer
  3498. * matches any pre-existing expectations about what type is expected. */
  3499. if (type == UPB_HANDLER_STARTSEQ || type == UPB_HANDLER_STARTSTR) {
  3500. const void *return_type = upb_handlerattr_returnclosuretype(&set_attr);
  3501. const void *table_return_type =
  3502. upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  3503. if (return_type && table_return_type && return_type != table_return_type) {
  3504. upb_status_seterrmsg(&h->status_, "closure return type does not match");
  3505. return false;
  3506. }
  3507. if (table_return_type && !return_type)
  3508. upb_handlerattr_setreturnclosuretype(&set_attr, table_return_type);
  3509. }
  3510. h->table[sel].func = (upb_func*)func;
  3511. h->table[sel].attr = set_attr;
  3512. return true;
  3513. }
  3514. /* Returns the effective closure type for this handler (which will propagate
  3515. * from outer frames if this frame has no START* handler). Not implemented for
  3516. * UPB_HANDLER_STRING at the moment since this is not needed. Returns NULL is
  3517. * the effective closure type is unspecified (either no handler was registered
  3518. * to specify it or the handler that was registered did not specify the closure
  3519. * type). */
  3520. const void *effective_closure_type(upb_handlers *h, const upb_fielddef *f,
  3521. upb_handlertype_t type) {
  3522. const void *ret;
  3523. upb_selector_t sel;
  3524. UPB_ASSERT(type != UPB_HANDLER_STRING);
  3525. ret = h->top_closure_type;
  3526. if (upb_fielddef_isseq(f) &&
  3527. type != UPB_HANDLER_STARTSEQ &&
  3528. type != UPB_HANDLER_ENDSEQ &&
  3529. h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSEQ)].func) {
  3530. ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  3531. }
  3532. if (type == UPB_HANDLER_STRING &&
  3533. h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSTR)].func) {
  3534. ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  3535. }
  3536. /* The effective type of the submessage; not used yet.
  3537. * if (type == SUBMESSAGE &&
  3538. * h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSUBMSG)].func) {
  3539. * ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  3540. * } */
  3541. return ret;
  3542. }
  3543. /* Checks whether the START* handler specified by f & type is missing even
  3544. * though it is required to convert the established type of an outer frame
  3545. * ("closure_type") into the established type of an inner frame (represented in
  3546. * the return closure type of this handler's attr. */
  3547. bool checkstart(upb_handlers *h, const upb_fielddef *f, upb_handlertype_t type,
  3548. upb_status *status) {
  3549. const void *closure_type;
  3550. const upb_handlerattr *attr;
  3551. const void *return_closure_type;
  3552. upb_selector_t sel = handlers_getsel(h, f, type);
  3553. if (h->table[sel].func) return true;
  3554. closure_type = effective_closure_type(h, f, type);
  3555. attr = &h->table[sel].attr;
  3556. return_closure_type = upb_handlerattr_returnclosuretype(attr);
  3557. if (closure_type && return_closure_type &&
  3558. closure_type != return_closure_type) {
  3559. upb_status_seterrf(status,
  3560. "expected start handler to return sub type for field %f",
  3561. upb_fielddef_name(f));
  3562. return false;
  3563. }
  3564. return true;
  3565. }
  3566. /* Public interface ***********************************************************/
  3567. upb_handlers *upb_handlers_new(const upb_msgdef *md, const void *owner) {
  3568. int extra;
  3569. upb_handlers *h;
  3570. UPB_ASSERT(upb_msgdef_isfrozen(md));
  3571. extra = sizeof(upb_handlers_tabent) * (md->selector_count - 1);
  3572. h = upb_calloc(sizeof(*h) + extra);
  3573. if (!h) return NULL;
  3574. h->msg = md;
  3575. upb_msgdef_ref(h->msg, h);
  3576. upb_status_clear(&h->status_);
  3577. if (md->submsg_field_count > 0) {
  3578. h->sub = upb_calloc(md->submsg_field_count * sizeof(*h->sub));
  3579. if (!h->sub) goto oom;
  3580. } else {
  3581. h->sub = 0;
  3582. }
  3583. if (!upb_refcounted_init(upb_handlers_upcast_mutable(h), &vtbl, owner))
  3584. goto oom;
  3585. if (!upb_inttable_init(&h->cleanup_, UPB_CTYPE_FPTR)) goto oom;
  3586. /* calloc() above initialized all handlers to NULL. */
  3587. return h;
  3588. oom:
  3589. freehandlers(upb_handlers_upcast_mutable(h));
  3590. return NULL;
  3591. }
  3592. const upb_handlers *upb_handlers_newfrozen(const upb_msgdef *m,
  3593. const void *owner,
  3594. upb_handlers_callback *callback,
  3595. const void *closure) {
  3596. dfs_state state;
  3597. upb_handlers *ret;
  3598. bool ok;
  3599. upb_refcounted *r;
  3600. state.callback = callback;
  3601. state.closure = closure;
  3602. if (!upb_inttable_init(&state.tab, UPB_CTYPE_PTR)) return NULL;
  3603. ret = newformsg(m, owner, &state);
  3604. upb_inttable_uninit(&state.tab);
  3605. if (!ret) return NULL;
  3606. r = upb_handlers_upcast_mutable(ret);
  3607. ok = upb_refcounted_freeze(&r, 1, NULL, UPB_MAX_HANDLER_DEPTH);
  3608. UPB_ASSERT(ok);
  3609. return ret;
  3610. }
  3611. const upb_status *upb_handlers_status(upb_handlers *h) {
  3612. UPB_ASSERT(!upb_handlers_isfrozen(h));
  3613. return &h->status_;
  3614. }
  3615. void upb_handlers_clearerr(upb_handlers *h) {
  3616. UPB_ASSERT(!upb_handlers_isfrozen(h));
  3617. upb_status_clear(&h->status_);
  3618. }
  3619. #define SETTER(name, handlerctype, handlertype) \
  3620. bool upb_handlers_set ## name(upb_handlers *h, const upb_fielddef *f, \
  3621. handlerctype func, upb_handlerattr *attr) { \
  3622. int32_t sel = trygetsel(h, f, handlertype); \
  3623. return doset(h, sel, f, handlertype, (upb_func*)func, attr); \
  3624. }
  3625. SETTER(int32, upb_int32_handlerfunc*, UPB_HANDLER_INT32)
  3626. SETTER(int64, upb_int64_handlerfunc*, UPB_HANDLER_INT64)
  3627. SETTER(uint32, upb_uint32_handlerfunc*, UPB_HANDLER_UINT32)
  3628. SETTER(uint64, upb_uint64_handlerfunc*, UPB_HANDLER_UINT64)
  3629. SETTER(float, upb_float_handlerfunc*, UPB_HANDLER_FLOAT)
  3630. SETTER(double, upb_double_handlerfunc*, UPB_HANDLER_DOUBLE)
  3631. SETTER(bool, upb_bool_handlerfunc*, UPB_HANDLER_BOOL)
  3632. SETTER(startstr, upb_startstr_handlerfunc*, UPB_HANDLER_STARTSTR)
  3633. SETTER(string, upb_string_handlerfunc*, UPB_HANDLER_STRING)
  3634. SETTER(endstr, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSTR)
  3635. SETTER(startseq, upb_startfield_handlerfunc*, UPB_HANDLER_STARTSEQ)
  3636. SETTER(startsubmsg, upb_startfield_handlerfunc*, UPB_HANDLER_STARTSUBMSG)
  3637. SETTER(endsubmsg, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSUBMSG)
  3638. SETTER(endseq, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSEQ)
  3639. #undef SETTER
  3640. bool upb_handlers_setunknown(upb_handlers *h, upb_unknown_handlerfunc *func,
  3641. upb_handlerattr *attr) {
  3642. return doset(h, UPB_UNKNOWN_SELECTOR, NULL, UPB_HANDLER_INT32,
  3643. (upb_func *)func, attr);
  3644. }
  3645. bool upb_handlers_setstartmsg(upb_handlers *h, upb_startmsg_handlerfunc *func,
  3646. upb_handlerattr *attr) {
  3647. return doset(h, UPB_STARTMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
  3648. (upb_func *)func, attr);
  3649. }
  3650. bool upb_handlers_setendmsg(upb_handlers *h, upb_endmsg_handlerfunc *func,
  3651. upb_handlerattr *attr) {
  3652. UPB_ASSERT(!upb_handlers_isfrozen(h));
  3653. return doset(h, UPB_ENDMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
  3654. (upb_func *)func, attr);
  3655. }
  3656. bool upb_handlers_setsubhandlers(upb_handlers *h, const upb_fielddef *f,
  3657. const upb_handlers *sub) {
  3658. UPB_ASSERT(sub);
  3659. UPB_ASSERT(!upb_handlers_isfrozen(h));
  3660. UPB_ASSERT(upb_fielddef_issubmsg(f));
  3661. if (SUBH_F(h, f)) return false; /* Can't reset. */
  3662. if (upb_msgdef_upcast(upb_handlers_msgdef(sub)) != upb_fielddef_subdef(f)) {
  3663. return false;
  3664. }
  3665. SUBH_F(h, f) = sub;
  3666. upb_ref2(sub, h);
  3667. return true;
  3668. }
  3669. const upb_handlers *upb_handlers_getsubhandlers(const upb_handlers *h,
  3670. const upb_fielddef *f) {
  3671. UPB_ASSERT(upb_fielddef_issubmsg(f));
  3672. return SUBH_F(h, f);
  3673. }
  3674. bool upb_handlers_getattr(const upb_handlers *h, upb_selector_t sel,
  3675. upb_handlerattr *attr) {
  3676. if (!upb_handlers_gethandler(h, sel))
  3677. return false;
  3678. *attr = h->table[sel].attr;
  3679. return true;
  3680. }
  3681. const upb_handlers *upb_handlers_getsubhandlers_sel(const upb_handlers *h,
  3682. upb_selector_t sel) {
  3683. /* STARTSUBMSG selector in sel is the field's selector base. */
  3684. return SUBH(h, sel - UPB_STATIC_SELECTOR_COUNT);
  3685. }
  3686. const upb_msgdef *upb_handlers_msgdef(const upb_handlers *h) { return h->msg; }
  3687. bool upb_handlers_addcleanup(upb_handlers *h, void *p, upb_handlerfree *func) {
  3688. bool ok;
  3689. if (upb_inttable_lookupptr(&h->cleanup_, p, NULL)) {
  3690. return false;
  3691. }
  3692. ok = upb_inttable_insertptr(&h->cleanup_, p, upb_value_fptr(func));
  3693. UPB_ASSERT(ok);
  3694. return true;
  3695. }
  3696. /* "Static" methods ***********************************************************/
  3697. bool upb_handlers_freeze(upb_handlers *const*handlers, int n, upb_status *s) {
  3698. /* TODO: verify we have a transitive closure. */
  3699. int i;
  3700. for (i = 0; i < n; i++) {
  3701. upb_msg_field_iter j;
  3702. upb_handlers *h = handlers[i];
  3703. if (!upb_ok(&h->status_)) {
  3704. upb_status_seterrf(s, "handlers for message %s had error status: %s",
  3705. upb_msgdef_fullname(upb_handlers_msgdef(h)),
  3706. upb_status_errmsg(&h->status_));
  3707. return false;
  3708. }
  3709. /* Check that there are no closure mismatches due to missing Start* handlers
  3710. * or subhandlers with different type-level types. */
  3711. for(upb_msg_field_begin(&j, h->msg);
  3712. !upb_msg_field_done(&j);
  3713. upb_msg_field_next(&j)) {
  3714. const upb_fielddef *f = upb_msg_iter_field(&j);
  3715. if (upb_fielddef_isseq(f)) {
  3716. if (!checkstart(h, f, UPB_HANDLER_STARTSEQ, s))
  3717. return false;
  3718. }
  3719. if (upb_fielddef_isstring(f)) {
  3720. if (!checkstart(h, f, UPB_HANDLER_STARTSTR, s))
  3721. return false;
  3722. }
  3723. if (upb_fielddef_issubmsg(f)) {
  3724. bool hashandler = false;
  3725. if (upb_handlers_gethandler(
  3726. h, handlers_getsel(h, f, UPB_HANDLER_STARTSUBMSG)) ||
  3727. upb_handlers_gethandler(
  3728. h, handlers_getsel(h, f, UPB_HANDLER_ENDSUBMSG))) {
  3729. hashandler = true;
  3730. }
  3731. if (upb_fielddef_isseq(f) &&
  3732. (upb_handlers_gethandler(
  3733. h, handlers_getsel(h, f, UPB_HANDLER_STARTSEQ)) ||
  3734. upb_handlers_gethandler(
  3735. h, handlers_getsel(h, f, UPB_HANDLER_ENDSEQ)))) {
  3736. hashandler = true;
  3737. }
  3738. if (hashandler && !upb_handlers_getsubhandlers(h, f)) {
  3739. /* For now we add an empty subhandlers in this case. It makes the
  3740. * decoder code generator simpler, because it only has to handle two
  3741. * cases (submessage has handlers or not) as opposed to three
  3742. * (submessage has handlers in enclosing message but no subhandlers).
  3743. *
  3744. * This makes parsing less efficient in the case that we want to
  3745. * notice a submessage but skip its contents (like if we're testing
  3746. * for submessage presence or counting the number of repeated
  3747. * submessages). In this case we will end up parsing the submessage
  3748. * field by field and throwing away the results for each, instead of
  3749. * skipping the whole delimited thing at once. If this is an issue we
  3750. * can revisit it, but do remember that this only arises when you have
  3751. * handlers (startseq/startsubmsg/endsubmsg/endseq) set for the
  3752. * submessage but no subhandlers. The uses cases for this are
  3753. * limited. */
  3754. upb_handlers *sub = upb_handlers_new(upb_fielddef_msgsubdef(f), &sub);
  3755. upb_handlers_setsubhandlers(h, f, sub);
  3756. upb_handlers_unref(sub, &sub);
  3757. }
  3758. /* TODO(haberman): check type of submessage.
  3759. * This is slightly tricky; also consider whether we should check that
  3760. * they match at setsubhandlers time. */
  3761. }
  3762. }
  3763. }
  3764. if (!upb_refcounted_freeze((upb_refcounted*const*)handlers, n, s,
  3765. UPB_MAX_HANDLER_DEPTH)) {
  3766. return false;
  3767. }
  3768. return true;
  3769. }
  3770. upb_handlertype_t upb_handlers_getprimitivehandlertype(const upb_fielddef *f) {
  3771. switch (upb_fielddef_type(f)) {
  3772. case UPB_TYPE_INT32:
  3773. case UPB_TYPE_ENUM: return UPB_HANDLER_INT32;
  3774. case UPB_TYPE_INT64: return UPB_HANDLER_INT64;
  3775. case UPB_TYPE_UINT32: return UPB_HANDLER_UINT32;
  3776. case UPB_TYPE_UINT64: return UPB_HANDLER_UINT64;
  3777. case UPB_TYPE_FLOAT: return UPB_HANDLER_FLOAT;
  3778. case UPB_TYPE_DOUBLE: return UPB_HANDLER_DOUBLE;
  3779. case UPB_TYPE_BOOL: return UPB_HANDLER_BOOL;
  3780. default: UPB_ASSERT(false); return -1; /* Invalid input. */
  3781. }
  3782. }
  3783. bool upb_handlers_getselector(const upb_fielddef *f, upb_handlertype_t type,
  3784. upb_selector_t *s) {
  3785. switch (type) {
  3786. case UPB_HANDLER_INT32:
  3787. case UPB_HANDLER_INT64:
  3788. case UPB_HANDLER_UINT32:
  3789. case UPB_HANDLER_UINT64:
  3790. case UPB_HANDLER_FLOAT:
  3791. case UPB_HANDLER_DOUBLE:
  3792. case UPB_HANDLER_BOOL:
  3793. if (!upb_fielddef_isprimitive(f) ||
  3794. upb_handlers_getprimitivehandlertype(f) != type)
  3795. return false;
  3796. *s = f->selector_base;
  3797. break;
  3798. case UPB_HANDLER_STRING:
  3799. if (upb_fielddef_isstring(f)) {
  3800. *s = f->selector_base;
  3801. } else if (upb_fielddef_lazy(f)) {
  3802. *s = f->selector_base + 3;
  3803. } else {
  3804. return false;
  3805. }
  3806. break;
  3807. case UPB_HANDLER_STARTSTR:
  3808. if (upb_fielddef_isstring(f) || upb_fielddef_lazy(f)) {
  3809. *s = f->selector_base + 1;
  3810. } else {
  3811. return false;
  3812. }
  3813. break;
  3814. case UPB_HANDLER_ENDSTR:
  3815. if (upb_fielddef_isstring(f) || upb_fielddef_lazy(f)) {
  3816. *s = f->selector_base + 2;
  3817. } else {
  3818. return false;
  3819. }
  3820. break;
  3821. case UPB_HANDLER_STARTSEQ:
  3822. if (!upb_fielddef_isseq(f)) return false;
  3823. *s = f->selector_base - 2;
  3824. break;
  3825. case UPB_HANDLER_ENDSEQ:
  3826. if (!upb_fielddef_isseq(f)) return false;
  3827. *s = f->selector_base - 1;
  3828. break;
  3829. case UPB_HANDLER_STARTSUBMSG:
  3830. if (!upb_fielddef_issubmsg(f)) return false;
  3831. /* Selectors for STARTSUBMSG are at the beginning of the table so that the
  3832. * selector can also be used as an index into the "sub" array of
  3833. * subhandlers. The indexes for the two into these two tables are the
  3834. * same, except that in the handler table the static selectors come first. */
  3835. *s = f->index_ + UPB_STATIC_SELECTOR_COUNT;
  3836. break;
  3837. case UPB_HANDLER_ENDSUBMSG:
  3838. if (!upb_fielddef_issubmsg(f)) return false;
  3839. *s = f->selector_base;
  3840. break;
  3841. }
  3842. UPB_ASSERT((size_t)*s < upb_fielddef_containingtype(f)->selector_count);
  3843. return true;
  3844. }
  3845. uint32_t upb_handlers_selectorbaseoffset(const upb_fielddef *f) {
  3846. return upb_fielddef_isseq(f) ? 2 : 0;
  3847. }
  3848. uint32_t upb_handlers_selectorcount(const upb_fielddef *f) {
  3849. uint32_t ret = 1;
  3850. if (upb_fielddef_isseq(f)) ret += 2; /* STARTSEQ/ENDSEQ */
  3851. if (upb_fielddef_isstring(f)) ret += 2; /* [STRING]/STARTSTR/ENDSTR */
  3852. if (upb_fielddef_issubmsg(f)) {
  3853. /* ENDSUBMSG (STARTSUBMSG is at table beginning) */
  3854. ret += 0;
  3855. if (upb_fielddef_lazy(f)) {
  3856. /* STARTSTR/ENDSTR/STRING (for lazy) */
  3857. ret += 3;
  3858. }
  3859. }
  3860. return ret;
  3861. }
  3862. /* upb_handlerattr ************************************************************/
  3863. void upb_handlerattr_init(upb_handlerattr *attr) {
  3864. upb_handlerattr from = UPB_HANDLERATTR_INITIALIZER;
  3865. memcpy(attr, &from, sizeof(*attr));
  3866. }
  3867. void upb_handlerattr_uninit(upb_handlerattr *attr) {
  3868. UPB_UNUSED(attr);
  3869. }
  3870. bool upb_handlerattr_sethandlerdata(upb_handlerattr *attr, const void *hd) {
  3871. attr->handler_data_ = hd;
  3872. return true;
  3873. }
  3874. bool upb_handlerattr_setclosuretype(upb_handlerattr *attr, const void *type) {
  3875. attr->closure_type_ = type;
  3876. return true;
  3877. }
  3878. const void *upb_handlerattr_closuretype(const upb_handlerattr *attr) {
  3879. return attr->closure_type_;
  3880. }
  3881. bool upb_handlerattr_setreturnclosuretype(upb_handlerattr *attr,
  3882. const void *type) {
  3883. attr->return_closure_type_ = type;
  3884. return true;
  3885. }
  3886. const void *upb_handlerattr_returnclosuretype(const upb_handlerattr *attr) {
  3887. return attr->return_closure_type_;
  3888. }
  3889. bool upb_handlerattr_setalwaysok(upb_handlerattr *attr, bool alwaysok) {
  3890. attr->alwaysok_ = alwaysok;
  3891. return true;
  3892. }
  3893. bool upb_handlerattr_alwaysok(const upb_handlerattr *attr) {
  3894. return attr->alwaysok_;
  3895. }
  3896. /* upb_bufhandle **************************************************************/
  3897. size_t upb_bufhandle_objofs(const upb_bufhandle *h) {
  3898. return h->objofs_;
  3899. }
  3900. /* upb_byteshandler ***********************************************************/
  3901. void upb_byteshandler_init(upb_byteshandler* h) {
  3902. memset(h, 0, sizeof(*h));
  3903. }
  3904. /* For when we support handlerfree callbacks. */
  3905. void upb_byteshandler_uninit(upb_byteshandler* h) {
  3906. UPB_UNUSED(h);
  3907. }
  3908. bool upb_byteshandler_setstartstr(upb_byteshandler *h,
  3909. upb_startstr_handlerfunc *func, void *d) {
  3910. h->table[UPB_STARTSTR_SELECTOR].func = (upb_func*)func;
  3911. h->table[UPB_STARTSTR_SELECTOR].attr.handler_data_ = d;
  3912. return true;
  3913. }
  3914. bool upb_byteshandler_setstring(upb_byteshandler *h,
  3915. upb_string_handlerfunc *func, void *d) {
  3916. h->table[UPB_STRING_SELECTOR].func = (upb_func*)func;
  3917. h->table[UPB_STRING_SELECTOR].attr.handler_data_ = d;
  3918. return true;
  3919. }
  3920. bool upb_byteshandler_setendstr(upb_byteshandler *h,
  3921. upb_endfield_handlerfunc *func, void *d) {
  3922. h->table[UPB_ENDSTR_SELECTOR].func = (upb_func*)func;
  3923. h->table[UPB_ENDSTR_SELECTOR].attr.handler_data_ = d;
  3924. return true;
  3925. }
  3926. /** Handlers for upb_msg ******************************************************/
  3927. typedef struct {
  3928. size_t offset;
  3929. int32_t hasbit;
  3930. } upb_msg_handlerdata;
  3931. /* Fallback implementation if the handler is not specialized by the producer. */
  3932. #define MSG_WRITER(type, ctype) \
  3933. bool upb_msg_set ## type (void *c, const void *hd, ctype val) { \
  3934. uint8_t *m = c; \
  3935. const upb_msg_handlerdata *d = hd; \
  3936. if (d->hasbit > 0) \
  3937. *(uint8_t*)&m[d->hasbit / 8] |= 1 << (d->hasbit % 8); \
  3938. *(ctype*)&m[d->offset] = val; \
  3939. return true; \
  3940. } \
  3941. MSG_WRITER(double, double)
  3942. MSG_WRITER(float, float)
  3943. MSG_WRITER(int32, int32_t)
  3944. MSG_WRITER(int64, int64_t)
  3945. MSG_WRITER(uint32, uint32_t)
  3946. MSG_WRITER(uint64, uint64_t)
  3947. MSG_WRITER(bool, bool)
  3948. bool upb_msg_setscalarhandler(upb_handlers *h, const upb_fielddef *f,
  3949. size_t offset, int32_t hasbit) {
  3950. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  3951. bool ok;
  3952. upb_msg_handlerdata *d = upb_gmalloc(sizeof(*d));
  3953. if (!d) return false;
  3954. d->offset = offset;
  3955. d->hasbit = hasbit;
  3956. upb_handlerattr_sethandlerdata(&attr, d);
  3957. upb_handlerattr_setalwaysok(&attr, true);
  3958. upb_handlers_addcleanup(h, d, upb_gfree);
  3959. #define TYPE(u, l) \
  3960. case UPB_TYPE_##u: \
  3961. ok = upb_handlers_set##l(h, f, upb_msg_set##l, &attr); break;
  3962. ok = false;
  3963. switch (upb_fielddef_type(f)) {
  3964. TYPE(INT64, int64);
  3965. TYPE(INT32, int32);
  3966. TYPE(ENUM, int32);
  3967. TYPE(UINT64, uint64);
  3968. TYPE(UINT32, uint32);
  3969. TYPE(DOUBLE, double);
  3970. TYPE(FLOAT, float);
  3971. TYPE(BOOL, bool);
  3972. default: UPB_ASSERT(false); break;
  3973. }
  3974. #undef TYPE
  3975. upb_handlerattr_uninit(&attr);
  3976. return ok;
  3977. }
  3978. bool upb_msg_getscalarhandlerdata(const upb_handlers *h,
  3979. upb_selector_t s,
  3980. upb_fieldtype_t *type,
  3981. size_t *offset,
  3982. int32_t *hasbit) {
  3983. const upb_msg_handlerdata *d;
  3984. upb_func *f = upb_handlers_gethandler(h, s);
  3985. if ((upb_int64_handlerfunc*)f == upb_msg_setint64) {
  3986. *type = UPB_TYPE_INT64;
  3987. } else if ((upb_int32_handlerfunc*)f == upb_msg_setint32) {
  3988. *type = UPB_TYPE_INT32;
  3989. } else if ((upb_uint64_handlerfunc*)f == upb_msg_setuint64) {
  3990. *type = UPB_TYPE_UINT64;
  3991. } else if ((upb_uint32_handlerfunc*)f == upb_msg_setuint32) {
  3992. *type = UPB_TYPE_UINT32;
  3993. } else if ((upb_double_handlerfunc*)f == upb_msg_setdouble) {
  3994. *type = UPB_TYPE_DOUBLE;
  3995. } else if ((upb_float_handlerfunc*)f == upb_msg_setfloat) {
  3996. *type = UPB_TYPE_FLOAT;
  3997. } else if ((upb_bool_handlerfunc*)f == upb_msg_setbool) {
  3998. *type = UPB_TYPE_BOOL;
  3999. } else {
  4000. return false;
  4001. }
  4002. d = upb_handlers_gethandlerdata(h, s);
  4003. *offset = d->offset;
  4004. *hasbit = d->hasbit;
  4005. return true;
  4006. }
  4007. bool upb_fieldtype_mapkeyok(upb_fieldtype_t type) {
  4008. return type == UPB_TYPE_BOOL || type == UPB_TYPE_INT32 ||
  4009. type == UPB_TYPE_UINT32 || type == UPB_TYPE_INT64 ||
  4010. type == UPB_TYPE_UINT64 || type == UPB_TYPE_STRING;
  4011. }
  4012. #define PTR_AT(msg, ofs, type) (type*)((char*)msg + ofs)
  4013. #define VOIDPTR_AT(msg, ofs) PTR_AT(msg, ofs, void)
  4014. #define ENCODE_MAX_NESTING 64
  4015. #define CHECK_TRUE(x) if (!(x)) { return false; }
  4016. /** upb_msgval ****************************************************************/
  4017. #define upb_alignof(t) offsetof(struct { char c; t x; }, x)
  4018. /* These functions will generate real memcpy() calls on ARM sadly, because
  4019. * the compiler assumes they might not be aligned. */
  4020. static upb_msgval upb_msgval_read(const void *p, size_t ofs,
  4021. uint8_t size) {
  4022. upb_msgval val;
  4023. p = (char*)p + ofs;
  4024. memcpy(&val, p, size);
  4025. return val;
  4026. }
  4027. static void upb_msgval_write(void *p, size_t ofs, upb_msgval val,
  4028. uint8_t size) {
  4029. p = (char*)p + ofs;
  4030. memcpy(p, &val, size);
  4031. }
  4032. static size_t upb_msgval_sizeof(upb_fieldtype_t type) {
  4033. switch (type) {
  4034. case UPB_TYPE_DOUBLE:
  4035. case UPB_TYPE_INT64:
  4036. case UPB_TYPE_UINT64:
  4037. return 8;
  4038. case UPB_TYPE_ENUM:
  4039. case UPB_TYPE_INT32:
  4040. case UPB_TYPE_UINT32:
  4041. case UPB_TYPE_FLOAT:
  4042. return 4;
  4043. case UPB_TYPE_BOOL:
  4044. return 1;
  4045. case UPB_TYPE_MESSAGE:
  4046. return sizeof(void*);
  4047. case UPB_TYPE_BYTES:
  4048. case UPB_TYPE_STRING:
  4049. return sizeof(upb_strview);
  4050. }
  4051. UPB_UNREACHABLE();
  4052. }
  4053. static uint8_t upb_msg_fieldsize(const upb_msglayout_field *field) {
  4054. if (field->label == UPB_LABEL_REPEATED) {
  4055. return sizeof(void*);
  4056. } else {
  4057. return upb_msgval_sizeof(upb_desctype_to_fieldtype[field->descriptortype]);
  4058. }
  4059. }
  4060. /* TODO(haberman): this is broken right now because upb_msgval can contain
  4061. * a char* / size_t pair, which is too big for a upb_value. To fix this
  4062. * we'll probably need to dynamically allocate a upb_msgval and store a
  4063. * pointer to that in the tables for extensions/maps. */
  4064. static upb_value upb_toval(upb_msgval val) {
  4065. upb_value ret;
  4066. UPB_UNUSED(val);
  4067. memset(&ret, 0, sizeof(upb_value)); /* XXX */
  4068. return ret;
  4069. }
  4070. static upb_msgval upb_msgval_fromval(upb_value val) {
  4071. upb_msgval ret;
  4072. UPB_UNUSED(val);
  4073. memset(&ret, 0, sizeof(upb_msgval)); /* XXX */
  4074. return ret;
  4075. }
  4076. static upb_ctype_t upb_fieldtotabtype(upb_fieldtype_t type) {
  4077. switch (type) {
  4078. case UPB_TYPE_FLOAT: return UPB_CTYPE_FLOAT;
  4079. case UPB_TYPE_DOUBLE: return UPB_CTYPE_DOUBLE;
  4080. case UPB_TYPE_BOOL: return UPB_CTYPE_BOOL;
  4081. case UPB_TYPE_BYTES:
  4082. case UPB_TYPE_MESSAGE:
  4083. case UPB_TYPE_STRING: return UPB_CTYPE_CONSTPTR;
  4084. case UPB_TYPE_ENUM:
  4085. case UPB_TYPE_INT32: return UPB_CTYPE_INT32;
  4086. case UPB_TYPE_UINT32: return UPB_CTYPE_UINT32;
  4087. case UPB_TYPE_INT64: return UPB_CTYPE_INT64;
  4088. case UPB_TYPE_UINT64: return UPB_CTYPE_UINT64;
  4089. default: UPB_ASSERT(false); return 0;
  4090. }
  4091. }
  4092. /** upb_msg *******************************************************************/
  4093. /* If we always read/write as a consistent type to each address, this shouldn't
  4094. * violate aliasing.
  4095. */
  4096. #define DEREF(msg, ofs, type) *PTR_AT(msg, ofs, type)
  4097. /* Internal members of a upb_msg. We can change this without breaking binary
  4098. * compatibility. We put these before the user's data. The user's upb_msg*
  4099. * points after the upb_msg_internal. */
  4100. /* Used when a message is not extendable. */
  4101. typedef struct {
  4102. /* TODO(haberman): use pointer tagging so we we are slim when known unknown
  4103. * fields are not present. */
  4104. upb_arena *arena;
  4105. char *unknown;
  4106. size_t unknown_len;
  4107. size_t unknown_size;
  4108. } upb_msg_internal;
  4109. /* Used when a message is extendable. */
  4110. typedef struct {
  4111. upb_inttable *extdict;
  4112. upb_msg_internal base;
  4113. } upb_msg_internal_withext;
  4114. static int upb_msg_internalsize(const upb_msglayout *l) {
  4115. return sizeof(upb_msg_internal) - l->extendable * sizeof(void *);
  4116. }
  4117. static upb_msg_internal *upb_msg_getinternal(upb_msg *msg) {
  4118. return VOIDPTR_AT(msg, -sizeof(upb_msg_internal));
  4119. }
  4120. static const upb_msg_internal *upb_msg_getinternal_const(const upb_msg *msg) {
  4121. return VOIDPTR_AT(msg, -sizeof(upb_msg_internal));
  4122. }
  4123. static upb_msg_internal_withext *upb_msg_getinternalwithext(
  4124. upb_msg *msg, const upb_msglayout *l) {
  4125. UPB_ASSERT(l->extendable);
  4126. return VOIDPTR_AT(msg, -sizeof(upb_msg_internal_withext));
  4127. }
  4128. void upb_msg_addunknown(upb_msg *msg, const char *data, size_t len) {
  4129. upb_msg_internal* in = upb_msg_getinternal(msg);
  4130. if (len > in->unknown_size - in->unknown_len) {
  4131. upb_alloc *alloc = upb_arena_alloc(in->arena);
  4132. size_t need = in->unknown_size + len;
  4133. size_t newsize = UPB_MAX(in->unknown_size * 2, need);
  4134. in->unknown = upb_realloc(alloc, in->unknown, in->unknown_size, newsize);
  4135. in->unknown_size = newsize;
  4136. }
  4137. memcpy(in->unknown + in->unknown_len, data, len);
  4138. in->unknown_len += len;
  4139. }
  4140. const char *upb_msg_getunknown(const upb_msg *msg, size_t *len) {
  4141. const upb_msg_internal* in = upb_msg_getinternal_const(msg);
  4142. *len = in->unknown_len;
  4143. return in->unknown;
  4144. }
  4145. static const upb_msglayout_field *upb_msg_checkfield(int field_index,
  4146. const upb_msglayout *l) {
  4147. UPB_ASSERT(field_index >= 0 && field_index < l->field_count);
  4148. return &l->fields[field_index];
  4149. }
  4150. static bool upb_msg_inoneof(const upb_msglayout_field *field) {
  4151. return field->presence < 0;
  4152. }
  4153. static uint32_t *upb_msg_oneofcase(const upb_msg *msg, int field_index,
  4154. const upb_msglayout *l) {
  4155. const upb_msglayout_field *field = upb_msg_checkfield(field_index, l);
  4156. UPB_ASSERT(upb_msg_inoneof(field));
  4157. return PTR_AT(msg, ~field->presence, uint32_t);
  4158. }
  4159. static size_t upb_msg_sizeof(const upb_msglayout *l) {
  4160. return l->size + upb_msg_internalsize(l);
  4161. }
  4162. upb_msg *upb_msg_new(const upb_msglayout *l, upb_arena *a) {
  4163. upb_alloc *alloc = upb_arena_alloc(a);
  4164. void *mem = upb_malloc(alloc, upb_msg_sizeof(l));
  4165. upb_msg_internal *in;
  4166. upb_msg *msg;
  4167. if (!mem) {
  4168. return NULL;
  4169. }
  4170. msg = VOIDPTR_AT(mem, upb_msg_internalsize(l));
  4171. /* Initialize normal members. */
  4172. memset(msg, 0, l->size);
  4173. /* Initialize internal members. */
  4174. in = upb_msg_getinternal(msg);
  4175. in->arena = a;
  4176. in->unknown = NULL;
  4177. in->unknown_len = 0;
  4178. in->unknown_size = 0;
  4179. if (l->extendable) {
  4180. upb_msg_getinternalwithext(msg, l)->extdict = NULL;
  4181. }
  4182. return msg;
  4183. }
  4184. upb_arena *upb_msg_arena(const upb_msg *msg) {
  4185. return upb_msg_getinternal_const(msg)->arena;
  4186. }
  4187. bool upb_msg_has(const upb_msg *msg,
  4188. int field_index,
  4189. const upb_msglayout *l) {
  4190. const upb_msglayout_field *field = upb_msg_checkfield(field_index, l);
  4191. UPB_ASSERT(field->presence);
  4192. if (upb_msg_inoneof(field)) {
  4193. /* Oneofs are set when the oneof number is set to this field. */
  4194. return *upb_msg_oneofcase(msg, field_index, l) == field->number;
  4195. } else {
  4196. /* Other fields are set when their hasbit is set. */
  4197. uint32_t hasbit = field->presence;
  4198. return DEREF(msg, hasbit / 8, char) | (1 << (hasbit % 8));
  4199. }
  4200. }
  4201. upb_msgval upb_msg_get(const upb_msg *msg, int field_index,
  4202. const upb_msglayout *l) {
  4203. const upb_msglayout_field *field = upb_msg_checkfield(field_index, l);
  4204. int size = upb_msg_fieldsize(field);
  4205. return upb_msgval_read(msg, field->offset, size);
  4206. }
  4207. void upb_msg_set(upb_msg *msg, int field_index, upb_msgval val,
  4208. const upb_msglayout *l) {
  4209. const upb_msglayout_field *field = upb_msg_checkfield(field_index, l);
  4210. int size = upb_msg_fieldsize(field);
  4211. upb_msgval_write(msg, field->offset, val, size);
  4212. }
  4213. /** upb_array *****************************************************************/
  4214. #define DEREF_ARR(arr, i, type) ((type*)arr->data)[i]
  4215. upb_array *upb_array_new(upb_fieldtype_t type, upb_arena *a) {
  4216. upb_alloc *alloc = upb_arena_alloc(a);
  4217. upb_array *ret = upb_malloc(alloc, sizeof(upb_array));
  4218. if (!ret) {
  4219. return NULL;
  4220. }
  4221. ret->type = type;
  4222. ret->data = NULL;
  4223. ret->len = 0;
  4224. ret->size = 0;
  4225. ret->element_size = upb_msgval_sizeof(type);
  4226. ret->arena = a;
  4227. return ret;
  4228. }
  4229. size_t upb_array_size(const upb_array *arr) {
  4230. return arr->len;
  4231. }
  4232. upb_fieldtype_t upb_array_type(const upb_array *arr) {
  4233. return arr->type;
  4234. }
  4235. upb_msgval upb_array_get(const upb_array *arr, size_t i) {
  4236. UPB_ASSERT(i < arr->len);
  4237. return upb_msgval_read(arr->data, i * arr->element_size, arr->element_size);
  4238. }
  4239. bool upb_array_set(upb_array *arr, size_t i, upb_msgval val) {
  4240. UPB_ASSERT(i <= arr->len);
  4241. if (i == arr->len) {
  4242. /* Extending the array. */
  4243. if (i == arr->size) {
  4244. /* Need to reallocate. */
  4245. size_t new_size = UPB_MAX(arr->size * 2, 8);
  4246. size_t new_bytes = new_size * arr->element_size;
  4247. size_t old_bytes = arr->size * arr->element_size;
  4248. upb_alloc *alloc = upb_arena_alloc(arr->arena);
  4249. upb_msgval *new_data =
  4250. upb_realloc(alloc, arr->data, old_bytes, new_bytes);
  4251. if (!new_data) {
  4252. return false;
  4253. }
  4254. arr->data = new_data;
  4255. arr->size = new_size;
  4256. }
  4257. arr->len = i + 1;
  4258. }
  4259. upb_msgval_write(arr->data, i * arr->element_size, val, arr->element_size);
  4260. return true;
  4261. }
  4262. /** upb_map *******************************************************************/
  4263. struct upb_map {
  4264. upb_fieldtype_t key_type;
  4265. upb_fieldtype_t val_type;
  4266. /* We may want to optimize this to use inttable where possible, for greater
  4267. * efficiency and lower memory footprint. */
  4268. upb_strtable strtab;
  4269. upb_arena *arena;
  4270. };
  4271. static void upb_map_tokey(upb_fieldtype_t type, upb_msgval *key,
  4272. const char **out_key, size_t *out_len) {
  4273. switch (type) {
  4274. case UPB_TYPE_STRING:
  4275. /* Point to string data of the input key. */
  4276. *out_key = key->str.data;
  4277. *out_len = key->str.size;
  4278. return;
  4279. case UPB_TYPE_BOOL:
  4280. case UPB_TYPE_INT32:
  4281. case UPB_TYPE_UINT32:
  4282. case UPB_TYPE_INT64:
  4283. case UPB_TYPE_UINT64:
  4284. /* Point to the key itself. XXX: big-endian. */
  4285. *out_key = (const char*)key;
  4286. *out_len = upb_msgval_sizeof(type);
  4287. return;
  4288. case UPB_TYPE_BYTES:
  4289. case UPB_TYPE_DOUBLE:
  4290. case UPB_TYPE_ENUM:
  4291. case UPB_TYPE_FLOAT:
  4292. case UPB_TYPE_MESSAGE:
  4293. break; /* Cannot be a map key. */
  4294. }
  4295. UPB_UNREACHABLE();
  4296. }
  4297. static upb_msgval upb_map_fromkey(upb_fieldtype_t type, const char *key,
  4298. size_t len) {
  4299. switch (type) {
  4300. case UPB_TYPE_STRING:
  4301. return upb_msgval_makestr(key, len);
  4302. case UPB_TYPE_BOOL:
  4303. case UPB_TYPE_INT32:
  4304. case UPB_TYPE_UINT32:
  4305. case UPB_TYPE_INT64:
  4306. case UPB_TYPE_UINT64:
  4307. return upb_msgval_read(key, 0, upb_msgval_sizeof(type));
  4308. case UPB_TYPE_BYTES:
  4309. case UPB_TYPE_DOUBLE:
  4310. case UPB_TYPE_ENUM:
  4311. case UPB_TYPE_FLOAT:
  4312. case UPB_TYPE_MESSAGE:
  4313. break; /* Cannot be a map key. */
  4314. }
  4315. UPB_UNREACHABLE();
  4316. }
  4317. upb_map *upb_map_new(upb_fieldtype_t ktype, upb_fieldtype_t vtype,
  4318. upb_arena *a) {
  4319. upb_ctype_t vtabtype = upb_fieldtotabtype(vtype);
  4320. upb_alloc *alloc = upb_arena_alloc(a);
  4321. upb_map *map = upb_malloc(alloc, sizeof(upb_map));
  4322. if (!map) {
  4323. return NULL;
  4324. }
  4325. UPB_ASSERT(upb_fieldtype_mapkeyok(ktype));
  4326. map->key_type = ktype;
  4327. map->val_type = vtype;
  4328. map->arena = a;
  4329. if (!upb_strtable_init2(&map->strtab, vtabtype, alloc)) {
  4330. return NULL;
  4331. }
  4332. return map;
  4333. }
  4334. size_t upb_map_size(const upb_map *map) {
  4335. return upb_strtable_count(&map->strtab);
  4336. }
  4337. upb_fieldtype_t upb_map_keytype(const upb_map *map) {
  4338. return map->key_type;
  4339. }
  4340. upb_fieldtype_t upb_map_valuetype(const upb_map *map) {
  4341. return map->val_type;
  4342. }
  4343. bool upb_map_get(const upb_map *map, upb_msgval key, upb_msgval *val) {
  4344. upb_value tabval;
  4345. const char *key_str;
  4346. size_t key_len;
  4347. bool ret;
  4348. upb_map_tokey(map->key_type, &key, &key_str, &key_len);
  4349. ret = upb_strtable_lookup2(&map->strtab, key_str, key_len, &tabval);
  4350. if (ret) {
  4351. memcpy(val, &tabval, sizeof(tabval));
  4352. }
  4353. return ret;
  4354. }
  4355. bool upb_map_set(upb_map *map, upb_msgval key, upb_msgval val,
  4356. upb_msgval *removed) {
  4357. const char *key_str;
  4358. size_t key_len;
  4359. upb_value tabval = upb_toval(val);
  4360. upb_value removedtabval;
  4361. upb_alloc *a = upb_arena_alloc(map->arena);
  4362. upb_map_tokey(map->key_type, &key, &key_str, &key_len);
  4363. /* TODO(haberman): add overwrite operation to minimize number of lookups. */
  4364. if (upb_strtable_lookup2(&map->strtab, key_str, key_len, NULL)) {
  4365. upb_strtable_remove3(&map->strtab, key_str, key_len, &removedtabval, a);
  4366. memcpy(&removed, &removedtabval, sizeof(removed));
  4367. }
  4368. return upb_strtable_insert3(&map->strtab, key_str, key_len, tabval, a);
  4369. }
  4370. bool upb_map_del(upb_map *map, upb_msgval key) {
  4371. const char *key_str;
  4372. size_t key_len;
  4373. upb_alloc *a = upb_arena_alloc(map->arena);
  4374. upb_map_tokey(map->key_type, &key, &key_str, &key_len);
  4375. return upb_strtable_remove3(&map->strtab, key_str, key_len, NULL, a);
  4376. }
  4377. /** upb_mapiter ***************************************************************/
  4378. struct upb_mapiter {
  4379. upb_strtable_iter iter;
  4380. upb_fieldtype_t key_type;
  4381. };
  4382. size_t upb_mapiter_sizeof() {
  4383. return sizeof(upb_mapiter);
  4384. }
  4385. void upb_mapiter_begin(upb_mapiter *i, const upb_map *map) {
  4386. upb_strtable_begin(&i->iter, &map->strtab);
  4387. i->key_type = map->key_type;
  4388. }
  4389. upb_mapiter *upb_mapiter_new(const upb_map *t, upb_alloc *a) {
  4390. upb_mapiter *ret = upb_malloc(a, upb_mapiter_sizeof());
  4391. if (!ret) {
  4392. return NULL;
  4393. }
  4394. upb_mapiter_begin(ret, t);
  4395. return ret;
  4396. }
  4397. void upb_mapiter_free(upb_mapiter *i, upb_alloc *a) {
  4398. upb_free(a, i);
  4399. }
  4400. void upb_mapiter_next(upb_mapiter *i) {
  4401. upb_strtable_next(&i->iter);
  4402. }
  4403. bool upb_mapiter_done(const upb_mapiter *i) {
  4404. return upb_strtable_done(&i->iter);
  4405. }
  4406. upb_msgval upb_mapiter_key(const upb_mapiter *i) {
  4407. return upb_map_fromkey(i->key_type, upb_strtable_iter_key(&i->iter),
  4408. upb_strtable_iter_keylength(&i->iter));
  4409. }
  4410. upb_msgval upb_mapiter_value(const upb_mapiter *i) {
  4411. return upb_msgval_fromval(upb_strtable_iter_value(&i->iter));
  4412. }
  4413. void upb_mapiter_setdone(upb_mapiter *i) {
  4414. upb_strtable_iter_setdone(&i->iter);
  4415. }
  4416. bool upb_mapiter_isequal(const upb_mapiter *i1, const upb_mapiter *i2) {
  4417. return upb_strtable_iter_isequal(&i1->iter, &i2->iter);
  4418. }
  4419. static bool is_power_of_two(size_t val) {
  4420. return (val & (val - 1)) == 0;
  4421. }
  4422. /* Align up to the given power of 2. */
  4423. static size_t align_up(size_t val, size_t align) {
  4424. UPB_ASSERT(is_power_of_two(align));
  4425. return (val + align - 1) & ~(align - 1);
  4426. }
  4427. static size_t div_round_up(size_t n, size_t d) {
  4428. return (n + d - 1) / d;
  4429. }
  4430. static size_t upb_msgval_sizeof2(upb_fieldtype_t type) {
  4431. switch (type) {
  4432. case UPB_TYPE_DOUBLE:
  4433. case UPB_TYPE_INT64:
  4434. case UPB_TYPE_UINT64:
  4435. return 8;
  4436. case UPB_TYPE_ENUM:
  4437. case UPB_TYPE_INT32:
  4438. case UPB_TYPE_UINT32:
  4439. case UPB_TYPE_FLOAT:
  4440. return 4;
  4441. case UPB_TYPE_BOOL:
  4442. return 1;
  4443. case UPB_TYPE_MESSAGE:
  4444. return sizeof(void*);
  4445. case UPB_TYPE_BYTES:
  4446. case UPB_TYPE_STRING:
  4447. return sizeof(upb_strview);
  4448. }
  4449. UPB_UNREACHABLE();
  4450. }
  4451. static uint8_t upb_msg_fielddefsize(const upb_fielddef *f) {
  4452. if (upb_fielddef_isseq(f)) {
  4453. return sizeof(void*);
  4454. } else {
  4455. return upb_msgval_sizeof2(upb_fielddef_type(f));
  4456. }
  4457. }
  4458. /** upb_msglayout *************************************************************/
  4459. static void upb_msglayout_free(upb_msglayout *l) {
  4460. upb_gfree(l);
  4461. }
  4462. static size_t upb_msglayout_place(upb_msglayout *l, size_t size) {
  4463. size_t ret;
  4464. l->size = align_up(l->size, size);
  4465. ret = l->size;
  4466. l->size += size;
  4467. return ret;
  4468. }
  4469. static bool upb_msglayout_init(const upb_msgdef *m,
  4470. upb_msglayout *l,
  4471. upb_msgfactory *factory) {
  4472. upb_msg_field_iter it;
  4473. upb_msg_oneof_iter oit;
  4474. size_t hasbit;
  4475. size_t submsg_count = 0;
  4476. const upb_msglayout **submsgs;
  4477. upb_msglayout_field *fields;
  4478. for (upb_msg_field_begin(&it, m);
  4479. !upb_msg_field_done(&it);
  4480. upb_msg_field_next(&it)) {
  4481. const upb_fielddef* f = upb_msg_iter_field(&it);
  4482. if (upb_fielddef_issubmsg(f)) {
  4483. submsg_count++;
  4484. }
  4485. }
  4486. memset(l, 0, sizeof(*l));
  4487. fields = upb_gmalloc(upb_msgdef_numfields(m) * sizeof(*fields));
  4488. submsgs = upb_gmalloc(submsg_count * sizeof(*submsgs));
  4489. if ((!fields && upb_msgdef_numfields(m)) ||
  4490. (!submsgs && submsg_count)) {
  4491. /* OOM. */
  4492. upb_gfree(fields);
  4493. upb_gfree(submsgs);
  4494. return false;
  4495. }
  4496. l->field_count = upb_msgdef_numfields(m);
  4497. l->fields = fields;
  4498. l->submsgs = submsgs;
  4499. /* Allocate data offsets in three stages:
  4500. *
  4501. * 1. hasbits.
  4502. * 2. regular fields.
  4503. * 3. oneof fields.
  4504. *
  4505. * OPT: There is a lot of room for optimization here to minimize the size.
  4506. */
  4507. /* Allocate hasbits and set basic field attributes. */
  4508. submsg_count = 0;
  4509. for (upb_msg_field_begin(&it, m), hasbit = 0;
  4510. !upb_msg_field_done(&it);
  4511. upb_msg_field_next(&it)) {
  4512. const upb_fielddef* f = upb_msg_iter_field(&it);
  4513. upb_msglayout_field *field = &fields[upb_fielddef_index(f)];
  4514. field->number = upb_fielddef_number(f);
  4515. field->descriptortype = upb_fielddef_descriptortype(f);
  4516. field->label = upb_fielddef_label(f);
  4517. if (upb_fielddef_issubmsg(f)) {
  4518. const upb_msglayout *sub_layout =
  4519. upb_msgfactory_getlayout(factory, upb_fielddef_msgsubdef(f));
  4520. field->submsg_index = submsg_count++;
  4521. submsgs[field->submsg_index] = sub_layout;
  4522. }
  4523. if (upb_fielddef_haspresence(f) && !upb_fielddef_containingoneof(f)) {
  4524. field->presence = (hasbit++);
  4525. } else {
  4526. field->presence = 0;
  4527. }
  4528. }
  4529. /* Account for space used by hasbits. */
  4530. l->size = div_round_up(hasbit, 8);
  4531. /* Allocate non-oneof fields. */
  4532. for (upb_msg_field_begin(&it, m); !upb_msg_field_done(&it);
  4533. upb_msg_field_next(&it)) {
  4534. const upb_fielddef* f = upb_msg_iter_field(&it);
  4535. size_t field_size = upb_msg_fielddefsize(f);
  4536. size_t index = upb_fielddef_index(f);
  4537. if (upb_fielddef_containingoneof(f)) {
  4538. /* Oneofs are handled separately below. */
  4539. continue;
  4540. }
  4541. fields[index].offset = upb_msglayout_place(l, field_size);
  4542. }
  4543. /* Allocate oneof fields. Each oneof field consists of a uint32 for the case
  4544. * and space for the actual data. */
  4545. for (upb_msg_oneof_begin(&oit, m); !upb_msg_oneof_done(&oit);
  4546. upb_msg_oneof_next(&oit)) {
  4547. const upb_oneofdef* o = upb_msg_iter_oneof(&oit);
  4548. upb_oneof_iter fit;
  4549. size_t case_size = sizeof(uint32_t); /* Could potentially optimize this. */
  4550. size_t field_size = 0;
  4551. uint32_t case_offset;
  4552. uint32_t data_offset;
  4553. /* Calculate field size: the max of all field sizes. */
  4554. for (upb_oneof_begin(&fit, o);
  4555. !upb_oneof_done(&fit);
  4556. upb_oneof_next(&fit)) {
  4557. const upb_fielddef* f = upb_oneof_iter_field(&fit);
  4558. field_size = UPB_MAX(field_size, upb_msg_fielddefsize(f));
  4559. }
  4560. /* Align and allocate case offset. */
  4561. case_offset = upb_msglayout_place(l, case_size);
  4562. data_offset = upb_msglayout_place(l, field_size);
  4563. for (upb_oneof_begin(&fit, o);
  4564. !upb_oneof_done(&fit);
  4565. upb_oneof_next(&fit)) {
  4566. const upb_fielddef* f = upb_oneof_iter_field(&fit);
  4567. fields[upb_fielddef_index(f)].offset = data_offset;
  4568. fields[upb_fielddef_index(f)].presence = ~case_offset;
  4569. }
  4570. }
  4571. /* Size of the entire structure should be a multiple of its greatest
  4572. * alignment. TODO: track overall alignment for real? */
  4573. l->size = align_up(l->size, 8);
  4574. return true;
  4575. }
  4576. /** upb_msgfactory ************************************************************/
  4577. struct upb_msgfactory {
  4578. const upb_symtab *symtab; /* We own a ref. */
  4579. upb_inttable layouts;
  4580. upb_inttable mergehandlers;
  4581. };
  4582. upb_msgfactory *upb_msgfactory_new(const upb_symtab *symtab) {
  4583. upb_msgfactory *ret = upb_gmalloc(sizeof(*ret));
  4584. ret->symtab = symtab;
  4585. upb_inttable_init(&ret->layouts, UPB_CTYPE_PTR);
  4586. upb_inttable_init(&ret->mergehandlers, UPB_CTYPE_CONSTPTR);
  4587. return ret;
  4588. }
  4589. void upb_msgfactory_free(upb_msgfactory *f) {
  4590. upb_inttable_iter i;
  4591. upb_inttable_begin(&i, &f->layouts);
  4592. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  4593. upb_msglayout *l = upb_value_getptr(upb_inttable_iter_value(&i));
  4594. upb_msglayout_free(l);
  4595. }
  4596. upb_inttable_begin(&i, &f->mergehandlers);
  4597. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  4598. const upb_handlers *h = upb_value_getconstptr(upb_inttable_iter_value(&i));
  4599. upb_handlers_unref(h, f);
  4600. }
  4601. upb_inttable_uninit(&f->layouts);
  4602. upb_inttable_uninit(&f->mergehandlers);
  4603. upb_gfree(f);
  4604. }
  4605. const upb_symtab *upb_msgfactory_symtab(const upb_msgfactory *f) {
  4606. return f->symtab;
  4607. }
  4608. const upb_msglayout *upb_msgfactory_getlayout(upb_msgfactory *f,
  4609. const upb_msgdef *m) {
  4610. upb_value v;
  4611. UPB_ASSERT(upb_symtab_lookupmsg(f->symtab, upb_msgdef_fullname(m)) == m);
  4612. UPB_ASSERT(!upb_msgdef_mapentry(m));
  4613. if (upb_inttable_lookupptr(&f->layouts, m, &v)) {
  4614. UPB_ASSERT(upb_value_getptr(v));
  4615. return upb_value_getptr(v);
  4616. } else {
  4617. /* In case of circular dependency, layout has to be inserted first. */
  4618. upb_msglayout *l = upb_gmalloc(sizeof(*l));
  4619. upb_msgfactory *mutable_f = (void*)f;
  4620. upb_inttable_insertptr(&mutable_f->layouts, m, upb_value_ptr(l));
  4621. UPB_ASSERT(l);
  4622. if (!upb_msglayout_init(m, l, f)) {
  4623. upb_msglayout_free(l);
  4624. }
  4625. return l;
  4626. }
  4627. }
  4628. #if UINTPTR_MAX == 0xffffffff
  4629. #define UPB_SIZE(size32, size64) size32
  4630. #else
  4631. #define UPB_SIZE(size32, size64) size64
  4632. #endif
  4633. #define UPB_FIELD_AT(msg, fieldtype, offset) \
  4634. *(fieldtype*)((const char*)(msg) + offset)
  4635. #define UPB_READ_ONEOF(msg, fieldtype, offset, case_offset, case_val, default) \
  4636. UPB_FIELD_AT(msg, int, case_offset) == case_val \
  4637. ? UPB_FIELD_AT(msg, fieldtype, offset) \
  4638. : default
  4639. #define UPB_WRITE_ONEOF(msg, fieldtype, offset, value, case_offset, case_val) \
  4640. UPB_FIELD_AT(msg, int, case_offset) = case_val; \
  4641. UPB_FIELD_AT(msg, fieldtype, offset) = value;
  4642. #undef UPB_SIZE
  4643. #undef UPB_FIELD_AT
  4644. #undef UPB_READ_ONEOF
  4645. #undef UPB_WRITE_ONEOF
  4646. /*
  4647. ** upb::RefCounted Implementation
  4648. **
  4649. ** Our key invariants are:
  4650. ** 1. reference cycles never span groups
  4651. ** 2. for ref2(to, from), we increment to's count iff group(from) != group(to)
  4652. **
  4653. ** The previous two are how we avoid leaking cycles. Other important
  4654. ** invariants are:
  4655. ** 3. for mutable objects "from" and "to", if there exists a ref2(to, from)
  4656. ** this implies group(from) == group(to). (In practice, what we implement
  4657. ** is even stronger; "from" and "to" will share a group if there has *ever*
  4658. ** been a ref2(to, from), but all that is necessary for correctness is the
  4659. ** weaker one).
  4660. ** 4. mutable and immutable objects are never in the same group.
  4661. */
  4662. #include <setjmp.h>
  4663. static void freeobj(upb_refcounted *o);
  4664. const char untracked_val;
  4665. const void *UPB_UNTRACKED_REF = &untracked_val;
  4666. /* arch-specific atomic primitives *******************************************/
  4667. #ifdef UPB_THREAD_UNSAFE /*---------------------------------------------------*/
  4668. static void atomic_inc(uint32_t *a) { (*a)++; }
  4669. static bool atomic_dec(uint32_t *a) { return --(*a) == 0; }
  4670. #elif defined(__GNUC__) || defined(__clang__) /*------------------------------*/
  4671. static void atomic_inc(uint32_t *a) { __sync_fetch_and_add(a, 1); }
  4672. static bool atomic_dec(uint32_t *a) { return __sync_sub_and_fetch(a, 1) == 0; }
  4673. #elif defined(WIN32) /*-------------------------------------------------------*/
  4674. #include <Windows.h>
  4675. static void atomic_inc(upb_atomic_t *a) { InterlockedIncrement(&a->val); }
  4676. static bool atomic_dec(upb_atomic_t *a) {
  4677. return InterlockedDecrement(&a->val) == 0;
  4678. }
  4679. #else
  4680. #error Atomic primitives not defined for your platform/CPU. \
  4681. Implement them or compile with UPB_THREAD_UNSAFE.
  4682. #endif
  4683. /* All static objects point to this refcount.
  4684. * It is special-cased in ref/unref below. */
  4685. uint32_t static_refcount = -1;
  4686. /* We can avoid atomic ops for statically-declared objects.
  4687. * This is a minor optimization but nice since we can avoid degrading under
  4688. * contention in this case. */
  4689. static void refgroup(uint32_t *group) {
  4690. if (group != &static_refcount)
  4691. atomic_inc(group);
  4692. }
  4693. static bool unrefgroup(uint32_t *group) {
  4694. if (group == &static_refcount) {
  4695. return false;
  4696. } else {
  4697. return atomic_dec(group);
  4698. }
  4699. }
  4700. /* Reference tracking (debug only) ********************************************/
  4701. #ifdef UPB_DEBUG_REFS
  4702. #ifdef UPB_THREAD_UNSAFE
  4703. static void upb_lock() {}
  4704. static void upb_unlock() {}
  4705. #else
  4706. /* User must define functions that lock/unlock a global mutex and link this
  4707. * file against them. */
  4708. void upb_lock();
  4709. void upb_unlock();
  4710. #endif
  4711. /* UPB_DEBUG_REFS mode counts on being able to malloc() memory in some
  4712. * code-paths that can normally never fail, like upb_refcounted_ref(). Since
  4713. * we have no way to propagage out-of-memory errors back to the user, and since
  4714. * these errors can only occur in UPB_DEBUG_REFS mode, we use an allocator that
  4715. * immediately aborts on failure (avoiding the global allocator, which might
  4716. * inject failures). */
  4717. #include <stdlib.h>
  4718. static void *upb_debugrefs_allocfunc(upb_alloc *alloc, void *ptr,
  4719. size_t oldsize, size_t size) {
  4720. UPB_UNUSED(alloc);
  4721. UPB_UNUSED(oldsize);
  4722. if (size == 0) {
  4723. free(ptr);
  4724. return NULL;
  4725. } else {
  4726. void *ret = realloc(ptr, size);
  4727. if (!ret) {
  4728. abort();
  4729. }
  4730. return ret;
  4731. }
  4732. }
  4733. upb_alloc upb_alloc_debugrefs = {&upb_debugrefs_allocfunc};
  4734. typedef struct {
  4735. int count; /* How many refs there are (duplicates only allowed for ref2). */
  4736. bool is_ref2;
  4737. } trackedref;
  4738. static trackedref *trackedref_new(bool is_ref2) {
  4739. trackedref *ret = upb_malloc(&upb_alloc_debugrefs, sizeof(*ret));
  4740. ret->count = 1;
  4741. ret->is_ref2 = is_ref2;
  4742. return ret;
  4743. }
  4744. static void track(const upb_refcounted *r, const void *owner, bool ref2) {
  4745. upb_value v;
  4746. UPB_ASSERT(owner);
  4747. if (owner == UPB_UNTRACKED_REF) return;
  4748. upb_lock();
  4749. if (upb_inttable_lookupptr(r->refs, owner, &v)) {
  4750. trackedref *ref = upb_value_getptr(v);
  4751. /* Since we allow multiple ref2's for the same to/from pair without
  4752. * allocating separate memory for each one, we lose the fine-grained
  4753. * tracking behavior we get with regular refs. Since ref2s only happen
  4754. * inside upb, we'll accept this limitation until/unless there is a really
  4755. * difficult upb-internal bug that can't be figured out without it. */
  4756. UPB_ASSERT(ref2);
  4757. UPB_ASSERT(ref->is_ref2);
  4758. ref->count++;
  4759. } else {
  4760. trackedref *ref = trackedref_new(ref2);
  4761. upb_inttable_insertptr2(r->refs, owner, upb_value_ptr(ref),
  4762. &upb_alloc_debugrefs);
  4763. if (ref2) {
  4764. /* We know this cast is safe when it is a ref2, because it's coming from
  4765. * another refcounted object. */
  4766. const upb_refcounted *from = owner;
  4767. UPB_ASSERT(!upb_inttable_lookupptr(from->ref2s, r, NULL));
  4768. upb_inttable_insertptr2(from->ref2s, r, upb_value_ptr(NULL),
  4769. &upb_alloc_debugrefs);
  4770. }
  4771. }
  4772. upb_unlock();
  4773. }
  4774. static void untrack(const upb_refcounted *r, const void *owner, bool ref2) {
  4775. upb_value v;
  4776. bool found;
  4777. trackedref *ref;
  4778. UPB_ASSERT(owner);
  4779. if (owner == UPB_UNTRACKED_REF) return;
  4780. upb_lock();
  4781. found = upb_inttable_lookupptr(r->refs, owner, &v);
  4782. /* This assert will fail if an owner attempts to release a ref it didn't have. */
  4783. UPB_ASSERT(found);
  4784. ref = upb_value_getptr(v);
  4785. UPB_ASSERT(ref->is_ref2 == ref2);
  4786. if (--ref->count == 0) {
  4787. free(ref);
  4788. upb_inttable_removeptr(r->refs, owner, NULL);
  4789. if (ref2) {
  4790. /* We know this cast is safe when it is a ref2, because it's coming from
  4791. * another refcounted object. */
  4792. const upb_refcounted *from = owner;
  4793. bool removed = upb_inttable_removeptr(from->ref2s, r, NULL);
  4794. UPB_ASSERT(removed);
  4795. }
  4796. }
  4797. upb_unlock();
  4798. }
  4799. static void checkref(const upb_refcounted *r, const void *owner, bool ref2) {
  4800. upb_value v;
  4801. bool found;
  4802. trackedref *ref;
  4803. upb_lock();
  4804. found = upb_inttable_lookupptr(r->refs, owner, &v);
  4805. UPB_ASSERT(found);
  4806. ref = upb_value_getptr(v);
  4807. UPB_ASSERT(ref->is_ref2 == ref2);
  4808. upb_unlock();
  4809. }
  4810. /* Populates the given UPB_CTYPE_INT32 inttable with counts of ref2's that
  4811. * originate from the given owner. */
  4812. static void getref2s(const upb_refcounted *owner, upb_inttable *tab) {
  4813. upb_inttable_iter i;
  4814. upb_lock();
  4815. upb_inttable_begin(&i, owner->ref2s);
  4816. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  4817. upb_value v;
  4818. upb_value count;
  4819. trackedref *ref;
  4820. bool found;
  4821. upb_refcounted *to = (upb_refcounted*)upb_inttable_iter_key(&i);
  4822. /* To get the count we need to look in the target's table. */
  4823. found = upb_inttable_lookupptr(to->refs, owner, &v);
  4824. UPB_ASSERT(found);
  4825. ref = upb_value_getptr(v);
  4826. count = upb_value_int32(ref->count);
  4827. upb_inttable_insertptr2(tab, to, count, &upb_alloc_debugrefs);
  4828. }
  4829. upb_unlock();
  4830. }
  4831. typedef struct {
  4832. upb_inttable ref2;
  4833. const upb_refcounted *obj;
  4834. } check_state;
  4835. static void visit_check(const upb_refcounted *obj, const upb_refcounted *subobj,
  4836. void *closure) {
  4837. check_state *s = closure;
  4838. upb_inttable *ref2 = &s->ref2;
  4839. upb_value v;
  4840. bool removed;
  4841. int32_t newcount;
  4842. UPB_ASSERT(obj == s->obj);
  4843. UPB_ASSERT(subobj);
  4844. removed = upb_inttable_removeptr(ref2, subobj, &v);
  4845. /* The following assertion will fail if the visit() function visits a subobj
  4846. * that it did not have a ref2 on, or visits the same subobj too many times. */
  4847. UPB_ASSERT(removed);
  4848. newcount = upb_value_getint32(v) - 1;
  4849. if (newcount > 0) {
  4850. upb_inttable_insert2(ref2, (uintptr_t)subobj, upb_value_int32(newcount),
  4851. &upb_alloc_debugrefs);
  4852. }
  4853. }
  4854. static void visit(const upb_refcounted *r, upb_refcounted_visit *v,
  4855. void *closure) {
  4856. /* In DEBUG_REFS mode we know what existing ref2 refs there are, so we know
  4857. * exactly the set of nodes that visit() should visit. So we verify visit()'s
  4858. * correctness here. */
  4859. check_state state;
  4860. state.obj = r;
  4861. upb_inttable_init2(&state.ref2, UPB_CTYPE_INT32, &upb_alloc_debugrefs);
  4862. getref2s(r, &state.ref2);
  4863. /* This should visit any children in the ref2 table. */
  4864. if (r->vtbl->visit) r->vtbl->visit(r, visit_check, &state);
  4865. /* This assertion will fail if the visit() function missed any children. */
  4866. UPB_ASSERT(upb_inttable_count(&state.ref2) == 0);
  4867. upb_inttable_uninit2(&state.ref2, &upb_alloc_debugrefs);
  4868. if (r->vtbl->visit) r->vtbl->visit(r, v, closure);
  4869. }
  4870. static void trackinit(upb_refcounted *r) {
  4871. r->refs = upb_malloc(&upb_alloc_debugrefs, sizeof(*r->refs));
  4872. r->ref2s = upb_malloc(&upb_alloc_debugrefs, sizeof(*r->ref2s));
  4873. upb_inttable_init2(r->refs, UPB_CTYPE_PTR, &upb_alloc_debugrefs);
  4874. upb_inttable_init2(r->ref2s, UPB_CTYPE_PTR, &upb_alloc_debugrefs);
  4875. }
  4876. static void trackfree(const upb_refcounted *r) {
  4877. upb_inttable_uninit2(r->refs, &upb_alloc_debugrefs);
  4878. upb_inttable_uninit2(r->ref2s, &upb_alloc_debugrefs);
  4879. upb_free(&upb_alloc_debugrefs, r->refs);
  4880. upb_free(&upb_alloc_debugrefs, r->ref2s);
  4881. }
  4882. #else
  4883. static void track(const upb_refcounted *r, const void *owner, bool ref2) {
  4884. UPB_UNUSED(r);
  4885. UPB_UNUSED(owner);
  4886. UPB_UNUSED(ref2);
  4887. }
  4888. static void untrack(const upb_refcounted *r, const void *owner, bool ref2) {
  4889. UPB_UNUSED(r);
  4890. UPB_UNUSED(owner);
  4891. UPB_UNUSED(ref2);
  4892. }
  4893. static void checkref(const upb_refcounted *r, const void *owner, bool ref2) {
  4894. UPB_UNUSED(r);
  4895. UPB_UNUSED(owner);
  4896. UPB_UNUSED(ref2);
  4897. }
  4898. static void trackinit(upb_refcounted *r) {
  4899. UPB_UNUSED(r);
  4900. }
  4901. static void trackfree(const upb_refcounted *r) {
  4902. UPB_UNUSED(r);
  4903. }
  4904. static void visit(const upb_refcounted *r, upb_refcounted_visit *v,
  4905. void *closure) {
  4906. if (r->vtbl->visit) r->vtbl->visit(r, v, closure);
  4907. }
  4908. #endif /* UPB_DEBUG_REFS */
  4909. /* freeze() *******************************************************************/
  4910. /* The freeze() operation is by far the most complicated part of this scheme.
  4911. * We compute strongly-connected components and then mutate the graph such that
  4912. * we preserve the invariants documented at the top of this file. And we must
  4913. * handle out-of-memory errors gracefully (without leaving the graph
  4914. * inconsistent), which adds to the fun. */
  4915. /* The state used by the freeze operation (shared across many functions). */
  4916. typedef struct {
  4917. int depth;
  4918. int maxdepth;
  4919. uint64_t index;
  4920. /* Maps upb_refcounted* -> attributes (color, etc). attr layout varies by
  4921. * color. */
  4922. upb_inttable objattr;
  4923. upb_inttable stack; /* stack of upb_refcounted* for Tarjan's algorithm. */
  4924. upb_inttable groups; /* array of uint32_t*, malloc'd refcounts for new groups */
  4925. upb_status *status;
  4926. jmp_buf err;
  4927. } tarjan;
  4928. static void release_ref2(const upb_refcounted *obj,
  4929. const upb_refcounted *subobj,
  4930. void *closure);
  4931. /* Node attributes -----------------------------------------------------------*/
  4932. /* After our analysis phase all nodes will be either GRAY or WHITE. */
  4933. typedef enum {
  4934. BLACK = 0, /* Object has not been seen. */
  4935. GRAY, /* Object has been found via a refgroup but may not be reachable. */
  4936. GREEN, /* Object is reachable and is currently on the Tarjan stack. */
  4937. WHITE /* Object is reachable and has been assigned a group (SCC). */
  4938. } color_t;
  4939. UPB_NORETURN static void err(tarjan *t) { longjmp(t->err, 1); }
  4940. UPB_NORETURN static void oom(tarjan *t) {
  4941. upb_status_seterrmsg(t->status, "out of memory");
  4942. err(t);
  4943. }
  4944. static uint64_t trygetattr(const tarjan *t, const upb_refcounted *r) {
  4945. upb_value v;
  4946. return upb_inttable_lookupptr(&t->objattr, r, &v) ?
  4947. upb_value_getuint64(v) : 0;
  4948. }
  4949. static uint64_t getattr(const tarjan *t, const upb_refcounted *r) {
  4950. upb_value v;
  4951. bool found = upb_inttable_lookupptr(&t->objattr, r, &v);
  4952. UPB_ASSERT(found);
  4953. return upb_value_getuint64(v);
  4954. }
  4955. static void setattr(tarjan *t, const upb_refcounted *r, uint64_t attr) {
  4956. upb_inttable_removeptr(&t->objattr, r, NULL);
  4957. upb_inttable_insertptr(&t->objattr, r, upb_value_uint64(attr));
  4958. }
  4959. static color_t color(tarjan *t, const upb_refcounted *r) {
  4960. return trygetattr(t, r) & 0x3; /* Color is always stored in the low 2 bits. */
  4961. }
  4962. static void set_gray(tarjan *t, const upb_refcounted *r) {
  4963. UPB_ASSERT(color(t, r) == BLACK);
  4964. setattr(t, r, GRAY);
  4965. }
  4966. /* Pushes an obj onto the Tarjan stack and sets it to GREEN. */
  4967. static void push(tarjan *t, const upb_refcounted *r) {
  4968. UPB_ASSERT(color(t, r) == BLACK || color(t, r) == GRAY);
  4969. /* This defines the attr layout for the GREEN state. "index" and "lowlink"
  4970. * get 31 bits, which is plenty (limit of 2B objects frozen at a time). */
  4971. setattr(t, r, GREEN | (t->index << 2) | (t->index << 33));
  4972. if (++t->index == 0x80000000) {
  4973. upb_status_seterrmsg(t->status, "too many objects to freeze");
  4974. err(t);
  4975. }
  4976. upb_inttable_push(&t->stack, upb_value_ptr((void*)r));
  4977. }
  4978. /* Pops an obj from the Tarjan stack and sets it to WHITE, with a ptr to its
  4979. * SCC group. */
  4980. static upb_refcounted *pop(tarjan *t) {
  4981. upb_refcounted *r = upb_value_getptr(upb_inttable_pop(&t->stack));
  4982. UPB_ASSERT(color(t, r) == GREEN);
  4983. /* This defines the attr layout for nodes in the WHITE state.
  4984. * Top of group stack is [group, NULL]; we point at group. */
  4985. setattr(t, r, WHITE | (upb_inttable_count(&t->groups) - 2) << 8);
  4986. return r;
  4987. }
  4988. static void tarjan_newgroup(tarjan *t) {
  4989. uint32_t *group = upb_gmalloc(sizeof(*group));
  4990. if (!group) oom(t);
  4991. /* Push group and empty group leader (we'll fill in leader later). */
  4992. if (!upb_inttable_push(&t->groups, upb_value_ptr(group)) ||
  4993. !upb_inttable_push(&t->groups, upb_value_ptr(NULL))) {
  4994. upb_gfree(group);
  4995. oom(t);
  4996. }
  4997. *group = 0;
  4998. }
  4999. static uint32_t idx(tarjan *t, const upb_refcounted *r) {
  5000. UPB_ASSERT(color(t, r) == GREEN);
  5001. return (getattr(t, r) >> 2) & 0x7FFFFFFF;
  5002. }
  5003. static uint32_t lowlink(tarjan *t, const upb_refcounted *r) {
  5004. if (color(t, r) == GREEN) {
  5005. return getattr(t, r) >> 33;
  5006. } else {
  5007. return UINT32_MAX;
  5008. }
  5009. }
  5010. static void set_lowlink(tarjan *t, const upb_refcounted *r, uint32_t lowlink) {
  5011. UPB_ASSERT(color(t, r) == GREEN);
  5012. setattr(t, r, ((uint64_t)lowlink << 33) | (getattr(t, r) & 0x1FFFFFFFF));
  5013. }
  5014. static uint32_t *group(tarjan *t, upb_refcounted *r) {
  5015. uint64_t groupnum;
  5016. upb_value v;
  5017. bool found;
  5018. UPB_ASSERT(color(t, r) == WHITE);
  5019. groupnum = getattr(t, r) >> 8;
  5020. found = upb_inttable_lookup(&t->groups, groupnum, &v);
  5021. UPB_ASSERT(found);
  5022. return upb_value_getptr(v);
  5023. }
  5024. /* If the group leader for this object's group has not previously been set,
  5025. * the given object is assigned to be its leader. */
  5026. static upb_refcounted *groupleader(tarjan *t, upb_refcounted *r) {
  5027. uint64_t leader_slot;
  5028. upb_value v;
  5029. bool found;
  5030. UPB_ASSERT(color(t, r) == WHITE);
  5031. leader_slot = (getattr(t, r) >> 8) + 1;
  5032. found = upb_inttable_lookup(&t->groups, leader_slot, &v);
  5033. UPB_ASSERT(found);
  5034. if (upb_value_getptr(v)) {
  5035. return upb_value_getptr(v);
  5036. } else {
  5037. upb_inttable_remove(&t->groups, leader_slot, NULL);
  5038. upb_inttable_insert(&t->groups, leader_slot, upb_value_ptr(r));
  5039. return r;
  5040. }
  5041. }
  5042. /* Tarjan's algorithm --------------------------------------------------------*/
  5043. /* See:
  5044. * http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm */
  5045. static void do_tarjan(const upb_refcounted *obj, tarjan *t);
  5046. static void tarjan_visit(const upb_refcounted *obj,
  5047. const upb_refcounted *subobj,
  5048. void *closure) {
  5049. tarjan *t = closure;
  5050. if (++t->depth > t->maxdepth) {
  5051. upb_status_seterrf(t->status, "graph too deep to freeze (%d)", t->maxdepth);
  5052. err(t);
  5053. } else if (subobj->is_frozen || color(t, subobj) == WHITE) {
  5054. /* Do nothing: we don't want to visit or color already-frozen nodes,
  5055. * and WHITE nodes have already been assigned a SCC. */
  5056. } else if (color(t, subobj) < GREEN) {
  5057. /* Subdef has not yet been visited; recurse on it. */
  5058. do_tarjan(subobj, t);
  5059. set_lowlink(t, obj, UPB_MIN(lowlink(t, obj), lowlink(t, subobj)));
  5060. } else if (color(t, subobj) == GREEN) {
  5061. /* Subdef is in the stack and hence in the current SCC. */
  5062. set_lowlink(t, obj, UPB_MIN(lowlink(t, obj), idx(t, subobj)));
  5063. }
  5064. --t->depth;
  5065. }
  5066. static void do_tarjan(const upb_refcounted *obj, tarjan *t) {
  5067. if (color(t, obj) == BLACK) {
  5068. /* We haven't seen this object's group; mark the whole group GRAY. */
  5069. const upb_refcounted *o = obj;
  5070. do { set_gray(t, o); } while ((o = o->next) != obj);
  5071. }
  5072. push(t, obj);
  5073. visit(obj, tarjan_visit, t);
  5074. if (lowlink(t, obj) == idx(t, obj)) {
  5075. tarjan_newgroup(t);
  5076. while (pop(t) != obj)
  5077. ;
  5078. }
  5079. }
  5080. /* freeze() ------------------------------------------------------------------*/
  5081. static void crossref(const upb_refcounted *r, const upb_refcounted *subobj,
  5082. void *_t) {
  5083. tarjan *t = _t;
  5084. UPB_ASSERT(color(t, r) > BLACK);
  5085. if (color(t, subobj) > BLACK && r->group != subobj->group) {
  5086. /* Previously this ref was not reflected in subobj->group because they
  5087. * were in the same group; now that they are split a ref must be taken. */
  5088. refgroup(subobj->group);
  5089. }
  5090. }
  5091. static bool freeze(upb_refcounted *const*roots, int n, upb_status *s,
  5092. int maxdepth) {
  5093. volatile bool ret = false;
  5094. int i;
  5095. upb_inttable_iter iter;
  5096. /* We run in two passes so that we can allocate all memory before performing
  5097. * any mutation of the input -- this allows us to leave the input unchanged
  5098. * in the case of memory allocation failure. */
  5099. tarjan t;
  5100. t.index = 0;
  5101. t.depth = 0;
  5102. t.maxdepth = maxdepth;
  5103. t.status = s;
  5104. if (!upb_inttable_init(&t.objattr, UPB_CTYPE_UINT64)) goto err1;
  5105. if (!upb_inttable_init(&t.stack, UPB_CTYPE_PTR)) goto err2;
  5106. if (!upb_inttable_init(&t.groups, UPB_CTYPE_PTR)) goto err3;
  5107. if (setjmp(t.err) != 0) goto err4;
  5108. for (i = 0; i < n; i++) {
  5109. if (color(&t, roots[i]) < GREEN) {
  5110. do_tarjan(roots[i], &t);
  5111. }
  5112. }
  5113. /* If we've made it this far, no further errors are possible so it's safe to
  5114. * mutate the objects without risk of leaving them in an inconsistent state. */
  5115. ret = true;
  5116. /* The transformation that follows requires care. The preconditions are:
  5117. * - all objects in attr map are WHITE or GRAY, and are in mutable groups
  5118. * (groups of all mutable objs)
  5119. * - no ref2(to, from) refs have incremented count(to) if both "to" and
  5120. * "from" are in our attr map (this follows from invariants (2) and (3)) */
  5121. /* Pass 1: we remove WHITE objects from their mutable groups, and add them to
  5122. * new groups according to the SCC's we computed. These new groups will
  5123. * consist of only frozen objects. None will be immediately collectible,
  5124. * because WHITE objects are by definition reachable from one of "roots",
  5125. * which the caller must own refs on. */
  5126. upb_inttable_begin(&iter, &t.objattr);
  5127. for(; !upb_inttable_done(&iter); upb_inttable_next(&iter)) {
  5128. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&iter);
  5129. /* Since removal from a singly-linked list requires access to the object's
  5130. * predecessor, we consider obj->next instead of obj for moving. With the
  5131. * while() loop we guarantee that we will visit every node's predecessor.
  5132. * Proof:
  5133. * 1. every node's predecessor is in our attr map.
  5134. * 2. though the loop body may change a node's predecessor, it will only
  5135. * change it to be the node we are currently operating on, so with a
  5136. * while() loop we guarantee ourselves the chance to remove each node. */
  5137. while (color(&t, obj->next) == WHITE &&
  5138. group(&t, obj->next) != obj->next->group) {
  5139. upb_refcounted *leader;
  5140. /* Remove from old group. */
  5141. upb_refcounted *move = obj->next;
  5142. if (obj == move) {
  5143. /* Removing the last object from a group. */
  5144. UPB_ASSERT(*obj->group == obj->individual_count);
  5145. upb_gfree(obj->group);
  5146. } else {
  5147. obj->next = move->next;
  5148. /* This may decrease to zero; we'll collect GRAY objects (if any) that
  5149. * remain in the group in the third pass. */
  5150. UPB_ASSERT(*move->group >= move->individual_count);
  5151. *move->group -= move->individual_count;
  5152. }
  5153. /* Add to new group. */
  5154. leader = groupleader(&t, move);
  5155. if (move == leader) {
  5156. /* First object added to new group is its leader. */
  5157. move->group = group(&t, move);
  5158. move->next = move;
  5159. *move->group = move->individual_count;
  5160. } else {
  5161. /* Group already has at least one object in it. */
  5162. UPB_ASSERT(leader->group == group(&t, move));
  5163. move->group = group(&t, move);
  5164. move->next = leader->next;
  5165. leader->next = move;
  5166. *move->group += move->individual_count;
  5167. }
  5168. move->is_frozen = true;
  5169. }
  5170. }
  5171. /* Pass 2: GRAY and WHITE objects "obj" with ref2(to, obj) references must
  5172. * increment count(to) if group(obj) != group(to) (which could now be the
  5173. * case if "to" was just frozen). */
  5174. upb_inttable_begin(&iter, &t.objattr);
  5175. for(; !upb_inttable_done(&iter); upb_inttable_next(&iter)) {
  5176. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&iter);
  5177. visit(obj, crossref, &t);
  5178. }
  5179. /* Pass 3: GRAY objects are collected if their group's refcount dropped to
  5180. * zero when we removed its white nodes. This can happen if they had only
  5181. * been kept alive by virtue of sharing a group with an object that was just
  5182. * frozen.
  5183. *
  5184. * It is important that we do this last, since the GRAY object's free()
  5185. * function could call unref2() on just-frozen objects, which will decrement
  5186. * refs that were added in pass 2. */
  5187. upb_inttable_begin(&iter, &t.objattr);
  5188. for(; !upb_inttable_done(&iter); upb_inttable_next(&iter)) {
  5189. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&iter);
  5190. if (obj->group == NULL || *obj->group == 0) {
  5191. if (obj->group) {
  5192. upb_refcounted *o;
  5193. /* We eagerly free() the group's count (since we can't easily determine
  5194. * the group's remaining size it's the easiest way to ensure it gets
  5195. * done). */
  5196. upb_gfree(obj->group);
  5197. /* Visit to release ref2's (done in a separate pass since release_ref2
  5198. * depends on o->group being unmodified so it can test merged()). */
  5199. o = obj;
  5200. do { visit(o, release_ref2, NULL); } while ((o = o->next) != obj);
  5201. /* Mark "group" fields as NULL so we know to free the objects later in
  5202. * this loop, but also don't try to delete the group twice. */
  5203. o = obj;
  5204. do { o->group = NULL; } while ((o = o->next) != obj);
  5205. }
  5206. freeobj(obj);
  5207. }
  5208. }
  5209. err4:
  5210. if (!ret) {
  5211. upb_inttable_begin(&iter, &t.groups);
  5212. for(; !upb_inttable_done(&iter); upb_inttable_next(&iter))
  5213. upb_gfree(upb_value_getptr(upb_inttable_iter_value(&iter)));
  5214. }
  5215. upb_inttable_uninit(&t.groups);
  5216. err3:
  5217. upb_inttable_uninit(&t.stack);
  5218. err2:
  5219. upb_inttable_uninit(&t.objattr);
  5220. err1:
  5221. return ret;
  5222. }
  5223. /* Misc internal functions ***************************************************/
  5224. static bool merged(const upb_refcounted *r, const upb_refcounted *r2) {
  5225. return r->group == r2->group;
  5226. }
  5227. static void merge(upb_refcounted *r, upb_refcounted *from) {
  5228. upb_refcounted *base;
  5229. upb_refcounted *tmp;
  5230. if (merged(r, from)) return;
  5231. *r->group += *from->group;
  5232. upb_gfree(from->group);
  5233. base = from;
  5234. /* Set all refcount pointers in the "from" chain to the merged refcount.
  5235. *
  5236. * TODO(haberman): this linear algorithm can result in an overall O(n^2) bound
  5237. * if the user continuously extends a group by one object. Prevent this by
  5238. * using one of the techniques in this paper:
  5239. * http://bioinfo.ict.ac.cn/~dbu/AlgorithmCourses/Lectures/Union-Find-Tarjan.pdf */
  5240. do { from->group = r->group; } while ((from = from->next) != base);
  5241. /* Merge the two circularly linked lists by swapping their next pointers. */
  5242. tmp = r->next;
  5243. r->next = base->next;
  5244. base->next = tmp;
  5245. }
  5246. static void unref(const upb_refcounted *r);
  5247. static void release_ref2(const upb_refcounted *obj,
  5248. const upb_refcounted *subobj,
  5249. void *closure) {
  5250. UPB_UNUSED(closure);
  5251. untrack(subobj, obj, true);
  5252. if (!merged(obj, subobj)) {
  5253. UPB_ASSERT(subobj->is_frozen);
  5254. unref(subobj);
  5255. }
  5256. }
  5257. static void unref(const upb_refcounted *r) {
  5258. if (unrefgroup(r->group)) {
  5259. const upb_refcounted *o;
  5260. upb_gfree(r->group);
  5261. /* In two passes, since release_ref2 needs a guarantee that any subobjs
  5262. * are alive. */
  5263. o = r;
  5264. do { visit(o, release_ref2, NULL); } while((o = o->next) != r);
  5265. o = r;
  5266. do {
  5267. const upb_refcounted *next = o->next;
  5268. UPB_ASSERT(o->is_frozen || o->individual_count == 0);
  5269. freeobj((upb_refcounted*)o);
  5270. o = next;
  5271. } while(o != r);
  5272. }
  5273. }
  5274. static void freeobj(upb_refcounted *o) {
  5275. trackfree(o);
  5276. o->vtbl->free((upb_refcounted*)o);
  5277. }
  5278. /* Public interface ***********************************************************/
  5279. bool upb_refcounted_init(upb_refcounted *r,
  5280. const struct upb_refcounted_vtbl *vtbl,
  5281. const void *owner) {
  5282. #ifndef NDEBUG
  5283. /* Endianness check. This is unrelated to upb_refcounted, it's just a
  5284. * convenient place to put the check that we can be assured will run for
  5285. * basically every program using upb. */
  5286. const int x = 1;
  5287. #ifdef UPB_BIG_ENDIAN
  5288. UPB_ASSERT(*(char*)&x != 1);
  5289. #else
  5290. UPB_ASSERT(*(char*)&x == 1);
  5291. #endif
  5292. #endif
  5293. r->next = r;
  5294. r->vtbl = vtbl;
  5295. r->individual_count = 0;
  5296. r->is_frozen = false;
  5297. r->group = upb_gmalloc(sizeof(*r->group));
  5298. if (!r->group) return false;
  5299. *r->group = 0;
  5300. trackinit(r);
  5301. upb_refcounted_ref(r, owner);
  5302. return true;
  5303. }
  5304. bool upb_refcounted_isfrozen(const upb_refcounted *r) {
  5305. return r->is_frozen;
  5306. }
  5307. void upb_refcounted_ref(const upb_refcounted *r, const void *owner) {
  5308. track(r, owner, false);
  5309. if (!r->is_frozen)
  5310. ((upb_refcounted*)r)->individual_count++;
  5311. refgroup(r->group);
  5312. }
  5313. void upb_refcounted_unref(const upb_refcounted *r, const void *owner) {
  5314. untrack(r, owner, false);
  5315. if (!r->is_frozen)
  5316. ((upb_refcounted*)r)->individual_count--;
  5317. unref(r);
  5318. }
  5319. void upb_refcounted_ref2(const upb_refcounted *r, upb_refcounted *from) {
  5320. UPB_ASSERT(!from->is_frozen); /* Non-const pointer implies this. */
  5321. track(r, from, true);
  5322. if (r->is_frozen) {
  5323. refgroup(r->group);
  5324. } else {
  5325. merge((upb_refcounted*)r, from);
  5326. }
  5327. }
  5328. void upb_refcounted_unref2(const upb_refcounted *r, upb_refcounted *from) {
  5329. UPB_ASSERT(!from->is_frozen); /* Non-const pointer implies this. */
  5330. untrack(r, from, true);
  5331. if (r->is_frozen) {
  5332. unref(r);
  5333. } else {
  5334. UPB_ASSERT(merged(r, from));
  5335. }
  5336. }
  5337. void upb_refcounted_donateref(
  5338. const upb_refcounted *r, const void *from, const void *to) {
  5339. UPB_ASSERT(from != to);
  5340. if (to != NULL)
  5341. upb_refcounted_ref(r, to);
  5342. if (from != NULL)
  5343. upb_refcounted_unref(r, from);
  5344. }
  5345. void upb_refcounted_checkref(const upb_refcounted *r, const void *owner) {
  5346. checkref(r, owner, false);
  5347. }
  5348. bool upb_refcounted_freeze(upb_refcounted *const*roots, int n, upb_status *s,
  5349. int maxdepth) {
  5350. int i;
  5351. bool ret;
  5352. for (i = 0; i < n; i++) {
  5353. UPB_ASSERT(!roots[i]->is_frozen);
  5354. }
  5355. ret = freeze(roots, n, s, maxdepth);
  5356. UPB_ASSERT(!s || ret == upb_ok(s));
  5357. return ret;
  5358. }
  5359. bool upb_bufsrc_putbuf(const char *buf, size_t len, upb_bytessink *sink) {
  5360. void *subc;
  5361. bool ret;
  5362. upb_bufhandle handle;
  5363. upb_bufhandle_init(&handle);
  5364. upb_bufhandle_setbuf(&handle, buf, 0);
  5365. ret = upb_bytessink_start(sink, len, &subc);
  5366. if (ret && len != 0) {
  5367. ret = (upb_bytessink_putbuf(sink, subc, buf, len, &handle) >= len);
  5368. }
  5369. if (ret) {
  5370. ret = upb_bytessink_end(sink);
  5371. }
  5372. upb_bufhandle_uninit(&handle);
  5373. return ret;
  5374. }
  5375. struct upb_bufsink {
  5376. upb_byteshandler handler;
  5377. upb_bytessink sink;
  5378. upb_env *env;
  5379. char *ptr;
  5380. size_t len, size;
  5381. };
  5382. static void *upb_bufsink_start(void *_sink, const void *hd, size_t size_hint) {
  5383. upb_bufsink *sink = _sink;
  5384. UPB_UNUSED(hd);
  5385. UPB_UNUSED(size_hint);
  5386. sink->len = 0;
  5387. return sink;
  5388. }
  5389. static size_t upb_bufsink_string(void *_sink, const void *hd, const char *ptr,
  5390. size_t len, const upb_bufhandle *handle) {
  5391. upb_bufsink *sink = _sink;
  5392. size_t new_size = sink->size;
  5393. UPB_ASSERT(new_size > 0);
  5394. UPB_UNUSED(hd);
  5395. UPB_UNUSED(handle);
  5396. while (sink->len + len > new_size) {
  5397. new_size *= 2;
  5398. }
  5399. if (new_size != sink->size) {
  5400. sink->ptr = upb_env_realloc(sink->env, sink->ptr, sink->size, new_size);
  5401. sink->size = new_size;
  5402. }
  5403. memcpy(sink->ptr + sink->len, ptr, len);
  5404. sink->len += len;
  5405. return len;
  5406. }
  5407. upb_bufsink *upb_bufsink_new(upb_env *env) {
  5408. upb_bufsink *sink = upb_env_malloc(env, sizeof(upb_bufsink));
  5409. upb_byteshandler_init(&sink->handler);
  5410. upb_byteshandler_setstartstr(&sink->handler, upb_bufsink_start, NULL);
  5411. upb_byteshandler_setstring(&sink->handler, upb_bufsink_string, NULL);
  5412. upb_bytessink_reset(&sink->sink, &sink->handler, sink);
  5413. sink->env = env;
  5414. sink->size = 32;
  5415. sink->ptr = upb_env_malloc(env, sink->size);
  5416. sink->len = 0;
  5417. return sink;
  5418. }
  5419. void upb_bufsink_free(upb_bufsink *sink) {
  5420. upb_env_free(sink->env, sink->ptr);
  5421. upb_env_free(sink->env, sink);
  5422. }
  5423. upb_bytessink *upb_bufsink_sink(upb_bufsink *sink) {
  5424. return &sink->sink;
  5425. }
  5426. const char *upb_bufsink_getdata(const upb_bufsink *sink, size_t *len) {
  5427. *len = sink->len;
  5428. return sink->ptr;
  5429. }
  5430. /*
  5431. ** upb_table Implementation
  5432. **
  5433. ** Implementation is heavily inspired by Lua's ltable.c.
  5434. */
  5435. #include <string.h>
  5436. #define UPB_MAXARRSIZE 16 /* 64k. */
  5437. /* From Chromium. */
  5438. #define ARRAY_SIZE(x) \
  5439. ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x])))))
  5440. static void upb_check_alloc(upb_table *t, upb_alloc *a) {
  5441. UPB_UNUSED(t);
  5442. UPB_UNUSED(a);
  5443. UPB_ASSERT_DEBUGVAR(t->alloc == a);
  5444. }
  5445. static const double MAX_LOAD = 0.85;
  5446. /* The minimum utilization of the array part of a mixed hash/array table. This
  5447. * is a speed/memory-usage tradeoff (though it's not straightforward because of
  5448. * cache effects). The lower this is, the more memory we'll use. */
  5449. static const double MIN_DENSITY = 0.1;
  5450. bool is_pow2(uint64_t v) { return v == 0 || (v & (v - 1)) == 0; }
  5451. int log2ceil(uint64_t v) {
  5452. int ret = 0;
  5453. bool pow2 = is_pow2(v);
  5454. while (v >>= 1) ret++;
  5455. ret = pow2 ? ret : ret + 1; /* Ceiling. */
  5456. return UPB_MIN(UPB_MAXARRSIZE, ret);
  5457. }
  5458. char *upb_strdup(const char *s, upb_alloc *a) {
  5459. return upb_strdup2(s, strlen(s), a);
  5460. }
  5461. char *upb_strdup2(const char *s, size_t len, upb_alloc *a) {
  5462. size_t n;
  5463. char *p;
  5464. /* Prevent overflow errors. */
  5465. if (len == SIZE_MAX) return NULL;
  5466. /* Always null-terminate, even if binary data; but don't rely on the input to
  5467. * have a null-terminating byte since it may be a raw binary buffer. */
  5468. n = len + 1;
  5469. p = upb_malloc(a, n);
  5470. if (p) {
  5471. memcpy(p, s, len);
  5472. p[len] = 0;
  5473. }
  5474. return p;
  5475. }
  5476. /* A type to represent the lookup key of either a strtable or an inttable. */
  5477. typedef union {
  5478. uintptr_t num;
  5479. struct {
  5480. const char *str;
  5481. size_t len;
  5482. } str;
  5483. } lookupkey_t;
  5484. static lookupkey_t strkey2(const char *str, size_t len) {
  5485. lookupkey_t k;
  5486. k.str.str = str;
  5487. k.str.len = len;
  5488. return k;
  5489. }
  5490. static lookupkey_t intkey(uintptr_t key) {
  5491. lookupkey_t k;
  5492. k.num = key;
  5493. return k;
  5494. }
  5495. typedef uint32_t hashfunc_t(upb_tabkey key);
  5496. typedef bool eqlfunc_t(upb_tabkey k1, lookupkey_t k2);
  5497. /* Base table (shared code) ***************************************************/
  5498. /* For when we need to cast away const. */
  5499. static upb_tabent *mutable_entries(upb_table *t) {
  5500. return (upb_tabent*)t->entries;
  5501. }
  5502. static bool isfull(upb_table *t) {
  5503. if (upb_table_size(t) == 0) {
  5504. return true;
  5505. } else {
  5506. return ((double)(t->count + 1) / upb_table_size(t)) > MAX_LOAD;
  5507. }
  5508. }
  5509. static bool init(upb_table *t, upb_ctype_t ctype, uint8_t size_lg2,
  5510. upb_alloc *a) {
  5511. size_t bytes;
  5512. t->count = 0;
  5513. t->ctype = ctype;
  5514. t->size_lg2 = size_lg2;
  5515. t->mask = upb_table_size(t) ? upb_table_size(t) - 1 : 0;
  5516. #ifndef NDEBUG
  5517. t->alloc = a;
  5518. #endif
  5519. bytes = upb_table_size(t) * sizeof(upb_tabent);
  5520. if (bytes > 0) {
  5521. t->entries = upb_malloc(a, bytes);
  5522. if (!t->entries) return false;
  5523. memset(mutable_entries(t), 0, bytes);
  5524. } else {
  5525. t->entries = NULL;
  5526. }
  5527. return true;
  5528. }
  5529. static void uninit(upb_table *t, upb_alloc *a) {
  5530. upb_check_alloc(t, a);
  5531. upb_free(a, mutable_entries(t));
  5532. }
  5533. static upb_tabent *emptyent(upb_table *t) {
  5534. upb_tabent *e = mutable_entries(t) + upb_table_size(t);
  5535. while (1) { if (upb_tabent_isempty(--e)) return e; UPB_ASSERT(e > t->entries); }
  5536. }
  5537. static upb_tabent *getentry_mutable(upb_table *t, uint32_t hash) {
  5538. return (upb_tabent*)upb_getentry(t, hash);
  5539. }
  5540. static const upb_tabent *findentry(const upb_table *t, lookupkey_t key,
  5541. uint32_t hash, eqlfunc_t *eql) {
  5542. const upb_tabent *e;
  5543. if (t->size_lg2 == 0) return NULL;
  5544. e = upb_getentry(t, hash);
  5545. if (upb_tabent_isempty(e)) return NULL;
  5546. while (1) {
  5547. if (eql(e->key, key)) return e;
  5548. if ((e = e->next) == NULL) return NULL;
  5549. }
  5550. }
  5551. static upb_tabent *findentry_mutable(upb_table *t, lookupkey_t key,
  5552. uint32_t hash, eqlfunc_t *eql) {
  5553. return (upb_tabent*)findentry(t, key, hash, eql);
  5554. }
  5555. static bool lookup(const upb_table *t, lookupkey_t key, upb_value *v,
  5556. uint32_t hash, eqlfunc_t *eql) {
  5557. const upb_tabent *e = findentry(t, key, hash, eql);
  5558. if (e) {
  5559. if (v) {
  5560. _upb_value_setval(v, e->val.val, t->ctype);
  5561. }
  5562. return true;
  5563. } else {
  5564. return false;
  5565. }
  5566. }
  5567. /* The given key must not already exist in the table. */
  5568. static void insert(upb_table *t, lookupkey_t key, upb_tabkey tabkey,
  5569. upb_value val, uint32_t hash,
  5570. hashfunc_t *hashfunc, eqlfunc_t *eql) {
  5571. upb_tabent *mainpos_e;
  5572. upb_tabent *our_e;
  5573. UPB_ASSERT(findentry(t, key, hash, eql) == NULL);
  5574. UPB_ASSERT_DEBUGVAR(val.ctype == t->ctype);
  5575. t->count++;
  5576. mainpos_e = getentry_mutable(t, hash);
  5577. our_e = mainpos_e;
  5578. if (upb_tabent_isempty(mainpos_e)) {
  5579. /* Our main position is empty; use it. */
  5580. our_e->next = NULL;
  5581. } else {
  5582. /* Collision. */
  5583. upb_tabent *new_e = emptyent(t);
  5584. /* Head of collider's chain. */
  5585. upb_tabent *chain = getentry_mutable(t, hashfunc(mainpos_e->key));
  5586. if (chain == mainpos_e) {
  5587. /* Existing ent is in its main posisiton (it has the same hash as us, and
  5588. * is the head of our chain). Insert to new ent and append to this chain. */
  5589. new_e->next = mainpos_e->next;
  5590. mainpos_e->next = new_e;
  5591. our_e = new_e;
  5592. } else {
  5593. /* Existing ent is not in its main position (it is a node in some other
  5594. * chain). This implies that no existing ent in the table has our hash.
  5595. * Evict it (updating its chain) and use its ent for head of our chain. */
  5596. *new_e = *mainpos_e; /* copies next. */
  5597. while (chain->next != mainpos_e) {
  5598. chain = (upb_tabent*)chain->next;
  5599. UPB_ASSERT(chain);
  5600. }
  5601. chain->next = new_e;
  5602. our_e = mainpos_e;
  5603. our_e->next = NULL;
  5604. }
  5605. }
  5606. our_e->key = tabkey;
  5607. our_e->val.val = val.val;
  5608. UPB_ASSERT(findentry(t, key, hash, eql) == our_e);
  5609. }
  5610. static bool rm(upb_table *t, lookupkey_t key, upb_value *val,
  5611. upb_tabkey *removed, uint32_t hash, eqlfunc_t *eql) {
  5612. upb_tabent *chain = getentry_mutable(t, hash);
  5613. if (upb_tabent_isempty(chain)) return false;
  5614. if (eql(chain->key, key)) {
  5615. /* Element to remove is at the head of its chain. */
  5616. t->count--;
  5617. if (val) _upb_value_setval(val, chain->val.val, t->ctype);
  5618. if (removed) *removed = chain->key;
  5619. if (chain->next) {
  5620. upb_tabent *move = (upb_tabent*)chain->next;
  5621. *chain = *move;
  5622. move->key = 0; /* Make the slot empty. */
  5623. } else {
  5624. chain->key = 0; /* Make the slot empty. */
  5625. }
  5626. return true;
  5627. } else {
  5628. /* Element to remove is either in a non-head position or not in the
  5629. * table. */
  5630. while (chain->next && !eql(chain->next->key, key)) {
  5631. chain = (upb_tabent*)chain->next;
  5632. }
  5633. if (chain->next) {
  5634. /* Found element to remove. */
  5635. upb_tabent *rm = (upb_tabent*)chain->next;
  5636. t->count--;
  5637. if (val) _upb_value_setval(val, chain->next->val.val, t->ctype);
  5638. if (removed) *removed = rm->key;
  5639. rm->key = 0; /* Make the slot empty. */
  5640. chain->next = rm->next;
  5641. return true;
  5642. } else {
  5643. /* Element to remove is not in the table. */
  5644. return false;
  5645. }
  5646. }
  5647. }
  5648. static size_t next(const upb_table *t, size_t i) {
  5649. do {
  5650. if (++i >= upb_table_size(t))
  5651. return SIZE_MAX;
  5652. } while(upb_tabent_isempty(&t->entries[i]));
  5653. return i;
  5654. }
  5655. static size_t begin(const upb_table *t) {
  5656. return next(t, -1);
  5657. }
  5658. /* upb_strtable ***************************************************************/
  5659. /* A simple "subclass" of upb_table that only adds a hash function for strings. */
  5660. static upb_tabkey strcopy(lookupkey_t k2, upb_alloc *a) {
  5661. uint32_t len = (uint32_t) k2.str.len;
  5662. char *str = upb_malloc(a, k2.str.len + sizeof(uint32_t) + 1);
  5663. if (str == NULL) return 0;
  5664. memcpy(str, &len, sizeof(uint32_t));
  5665. memcpy(str + sizeof(uint32_t), k2.str.str, k2.str.len + 1);
  5666. return (uintptr_t)str;
  5667. }
  5668. static uint32_t strhash(upb_tabkey key) {
  5669. uint32_t len;
  5670. char *str = upb_tabstr(key, &len);
  5671. return MurmurHash2(str, len, 0);
  5672. }
  5673. static bool streql(upb_tabkey k1, lookupkey_t k2) {
  5674. uint32_t len;
  5675. char *str = upb_tabstr(k1, &len);
  5676. return len == k2.str.len && memcmp(str, k2.str.str, len) == 0;
  5677. }
  5678. bool upb_strtable_init2(upb_strtable *t, upb_ctype_t ctype, upb_alloc *a) {
  5679. return init(&t->t, ctype, 2, a);
  5680. }
  5681. void upb_strtable_uninit2(upb_strtable *t, upb_alloc *a) {
  5682. size_t i;
  5683. for (i = 0; i < upb_table_size(&t->t); i++)
  5684. upb_free(a, (void*)t->t.entries[i].key);
  5685. uninit(&t->t, a);
  5686. }
  5687. bool upb_strtable_resize(upb_strtable *t, size_t size_lg2, upb_alloc *a) {
  5688. upb_strtable new_table;
  5689. upb_strtable_iter i;
  5690. upb_check_alloc(&t->t, a);
  5691. if (!init(&new_table.t, t->t.ctype, size_lg2, a))
  5692. return false;
  5693. upb_strtable_begin(&i, t);
  5694. for ( ; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  5695. upb_strtable_insert3(
  5696. &new_table,
  5697. upb_strtable_iter_key(&i),
  5698. upb_strtable_iter_keylength(&i),
  5699. upb_strtable_iter_value(&i),
  5700. a);
  5701. }
  5702. upb_strtable_uninit2(t, a);
  5703. *t = new_table;
  5704. return true;
  5705. }
  5706. bool upb_strtable_insert3(upb_strtable *t, const char *k, size_t len,
  5707. upb_value v, upb_alloc *a) {
  5708. lookupkey_t key;
  5709. upb_tabkey tabkey;
  5710. uint32_t hash;
  5711. upb_check_alloc(&t->t, a);
  5712. if (isfull(&t->t)) {
  5713. /* Need to resize. New table of double the size, add old elements to it. */
  5714. if (!upb_strtable_resize(t, t->t.size_lg2 + 1, a)) {
  5715. return false;
  5716. }
  5717. }
  5718. key = strkey2(k, len);
  5719. tabkey = strcopy(key, a);
  5720. if (tabkey == 0) return false;
  5721. hash = MurmurHash2(key.str.str, key.str.len, 0);
  5722. insert(&t->t, key, tabkey, v, hash, &strhash, &streql);
  5723. return true;
  5724. }
  5725. bool upb_strtable_lookup2(const upb_strtable *t, const char *key, size_t len,
  5726. upb_value *v) {
  5727. uint32_t hash = MurmurHash2(key, len, 0);
  5728. return lookup(&t->t, strkey2(key, len), v, hash, &streql);
  5729. }
  5730. bool upb_strtable_remove3(upb_strtable *t, const char *key, size_t len,
  5731. upb_value *val, upb_alloc *alloc) {
  5732. uint32_t hash = MurmurHash2(key, len, 0);
  5733. upb_tabkey tabkey;
  5734. if (rm(&t->t, strkey2(key, len), val, &tabkey, hash, &streql)) {
  5735. upb_free(alloc, (void*)tabkey);
  5736. return true;
  5737. } else {
  5738. return false;
  5739. }
  5740. }
  5741. /* Iteration */
  5742. static const upb_tabent *str_tabent(const upb_strtable_iter *i) {
  5743. return &i->t->t.entries[i->index];
  5744. }
  5745. void upb_strtable_begin(upb_strtable_iter *i, const upb_strtable *t) {
  5746. i->t = t;
  5747. i->index = begin(&t->t);
  5748. }
  5749. void upb_strtable_next(upb_strtable_iter *i) {
  5750. i->index = next(&i->t->t, i->index);
  5751. }
  5752. bool upb_strtable_done(const upb_strtable_iter *i) {
  5753. return i->index >= upb_table_size(&i->t->t) ||
  5754. upb_tabent_isempty(str_tabent(i));
  5755. }
  5756. const char *upb_strtable_iter_key(const upb_strtable_iter *i) {
  5757. UPB_ASSERT(!upb_strtable_done(i));
  5758. return upb_tabstr(str_tabent(i)->key, NULL);
  5759. }
  5760. size_t upb_strtable_iter_keylength(const upb_strtable_iter *i) {
  5761. uint32_t len;
  5762. UPB_ASSERT(!upb_strtable_done(i));
  5763. upb_tabstr(str_tabent(i)->key, &len);
  5764. return len;
  5765. }
  5766. upb_value upb_strtable_iter_value(const upb_strtable_iter *i) {
  5767. UPB_ASSERT(!upb_strtable_done(i));
  5768. return _upb_value_val(str_tabent(i)->val.val, i->t->t.ctype);
  5769. }
  5770. void upb_strtable_iter_setdone(upb_strtable_iter *i) {
  5771. i->index = SIZE_MAX;
  5772. }
  5773. bool upb_strtable_iter_isequal(const upb_strtable_iter *i1,
  5774. const upb_strtable_iter *i2) {
  5775. if (upb_strtable_done(i1) && upb_strtable_done(i2))
  5776. return true;
  5777. return i1->t == i2->t && i1->index == i2->index;
  5778. }
  5779. /* upb_inttable ***************************************************************/
  5780. /* For inttables we use a hybrid structure where small keys are kept in an
  5781. * array and large keys are put in the hash table. */
  5782. static uint32_t inthash(upb_tabkey key) { return upb_inthash(key); }
  5783. static bool inteql(upb_tabkey k1, lookupkey_t k2) {
  5784. return k1 == k2.num;
  5785. }
  5786. static upb_tabval *mutable_array(upb_inttable *t) {
  5787. return (upb_tabval*)t->array;
  5788. }
  5789. static upb_tabval *inttable_val(upb_inttable *t, uintptr_t key) {
  5790. if (key < t->array_size) {
  5791. return upb_arrhas(t->array[key]) ? &(mutable_array(t)[key]) : NULL;
  5792. } else {
  5793. upb_tabent *e =
  5794. findentry_mutable(&t->t, intkey(key), upb_inthash(key), &inteql);
  5795. return e ? &e->val : NULL;
  5796. }
  5797. }
  5798. static const upb_tabval *inttable_val_const(const upb_inttable *t,
  5799. uintptr_t key) {
  5800. return inttable_val((upb_inttable*)t, key);
  5801. }
  5802. size_t upb_inttable_count(const upb_inttable *t) {
  5803. return t->t.count + t->array_count;
  5804. }
  5805. static void check(upb_inttable *t) {
  5806. UPB_UNUSED(t);
  5807. #if defined(UPB_DEBUG_TABLE) && !defined(NDEBUG)
  5808. {
  5809. /* This check is very expensive (makes inserts/deletes O(N)). */
  5810. size_t count = 0;
  5811. upb_inttable_iter i;
  5812. upb_inttable_begin(&i, t);
  5813. for(; !upb_inttable_done(&i); upb_inttable_next(&i), count++) {
  5814. UPB_ASSERT(upb_inttable_lookup(t, upb_inttable_iter_key(&i), NULL));
  5815. }
  5816. UPB_ASSERT(count == upb_inttable_count(t));
  5817. }
  5818. #endif
  5819. }
  5820. bool upb_inttable_sizedinit(upb_inttable *t, upb_ctype_t ctype,
  5821. size_t asize, int hsize_lg2, upb_alloc *a) {
  5822. size_t array_bytes;
  5823. if (!init(&t->t, ctype, hsize_lg2, a)) return false;
  5824. /* Always make the array part at least 1 long, so that we know key 0
  5825. * won't be in the hash part, which simplifies things. */
  5826. t->array_size = UPB_MAX(1, asize);
  5827. t->array_count = 0;
  5828. array_bytes = t->array_size * sizeof(upb_value);
  5829. t->array = upb_malloc(a, array_bytes);
  5830. if (!t->array) {
  5831. uninit(&t->t, a);
  5832. return false;
  5833. }
  5834. memset(mutable_array(t), 0xff, array_bytes);
  5835. check(t);
  5836. return true;
  5837. }
  5838. bool upb_inttable_init2(upb_inttable *t, upb_ctype_t ctype, upb_alloc *a) {
  5839. return upb_inttable_sizedinit(t, ctype, 0, 4, a);
  5840. }
  5841. void upb_inttable_uninit2(upb_inttable *t, upb_alloc *a) {
  5842. uninit(&t->t, a);
  5843. upb_free(a, mutable_array(t));
  5844. }
  5845. bool upb_inttable_insert2(upb_inttable *t, uintptr_t key, upb_value val,
  5846. upb_alloc *a) {
  5847. upb_tabval tabval;
  5848. tabval.val = val.val;
  5849. UPB_ASSERT(upb_arrhas(tabval)); /* This will reject (uint64_t)-1. Fix this. */
  5850. upb_check_alloc(&t->t, a);
  5851. if (key < t->array_size) {
  5852. UPB_ASSERT(!upb_arrhas(t->array[key]));
  5853. t->array_count++;
  5854. mutable_array(t)[key].val = val.val;
  5855. } else {
  5856. if (isfull(&t->t)) {
  5857. /* Need to resize the hash part, but we re-use the array part. */
  5858. size_t i;
  5859. upb_table new_table;
  5860. if (!init(&new_table, t->t.ctype, t->t.size_lg2 + 1, a)) {
  5861. return false;
  5862. }
  5863. for (i = begin(&t->t); i < upb_table_size(&t->t); i = next(&t->t, i)) {
  5864. const upb_tabent *e = &t->t.entries[i];
  5865. uint32_t hash;
  5866. upb_value v;
  5867. _upb_value_setval(&v, e->val.val, t->t.ctype);
  5868. hash = upb_inthash(e->key);
  5869. insert(&new_table, intkey(e->key), e->key, v, hash, &inthash, &inteql);
  5870. }
  5871. UPB_ASSERT(t->t.count == new_table.count);
  5872. uninit(&t->t, a);
  5873. t->t = new_table;
  5874. }
  5875. insert(&t->t, intkey(key), key, val, upb_inthash(key), &inthash, &inteql);
  5876. }
  5877. check(t);
  5878. return true;
  5879. }
  5880. bool upb_inttable_lookup(const upb_inttable *t, uintptr_t key, upb_value *v) {
  5881. const upb_tabval *table_v = inttable_val_const(t, key);
  5882. if (!table_v) return false;
  5883. if (v) _upb_value_setval(v, table_v->val, t->t.ctype);
  5884. return true;
  5885. }
  5886. bool upb_inttable_replace(upb_inttable *t, uintptr_t key, upb_value val) {
  5887. upb_tabval *table_v = inttable_val(t, key);
  5888. if (!table_v) return false;
  5889. table_v->val = val.val;
  5890. return true;
  5891. }
  5892. bool upb_inttable_remove(upb_inttable *t, uintptr_t key, upb_value *val) {
  5893. bool success;
  5894. if (key < t->array_size) {
  5895. if (upb_arrhas(t->array[key])) {
  5896. upb_tabval empty = UPB_TABVALUE_EMPTY_INIT;
  5897. t->array_count--;
  5898. if (val) {
  5899. _upb_value_setval(val, t->array[key].val, t->t.ctype);
  5900. }
  5901. mutable_array(t)[key] = empty;
  5902. success = true;
  5903. } else {
  5904. success = false;
  5905. }
  5906. } else {
  5907. success = rm(&t->t, intkey(key), val, NULL, upb_inthash(key), &inteql);
  5908. }
  5909. check(t);
  5910. return success;
  5911. }
  5912. bool upb_inttable_push2(upb_inttable *t, upb_value val, upb_alloc *a) {
  5913. upb_check_alloc(&t->t, a);
  5914. return upb_inttable_insert2(t, upb_inttable_count(t), val, a);
  5915. }
  5916. upb_value upb_inttable_pop(upb_inttable *t) {
  5917. upb_value val;
  5918. bool ok = upb_inttable_remove(t, upb_inttable_count(t) - 1, &val);
  5919. UPB_ASSERT(ok);
  5920. return val;
  5921. }
  5922. bool upb_inttable_insertptr2(upb_inttable *t, const void *key, upb_value val,
  5923. upb_alloc *a) {
  5924. upb_check_alloc(&t->t, a);
  5925. return upb_inttable_insert2(t, (uintptr_t)key, val, a);
  5926. }
  5927. bool upb_inttable_lookupptr(const upb_inttable *t, const void *key,
  5928. upb_value *v) {
  5929. return upb_inttable_lookup(t, (uintptr_t)key, v);
  5930. }
  5931. bool upb_inttable_removeptr(upb_inttable *t, const void *key, upb_value *val) {
  5932. return upb_inttable_remove(t, (uintptr_t)key, val);
  5933. }
  5934. void upb_inttable_compact2(upb_inttable *t, upb_alloc *a) {
  5935. /* A power-of-two histogram of the table keys. */
  5936. size_t counts[UPB_MAXARRSIZE + 1] = {0};
  5937. /* The max key in each bucket. */
  5938. uintptr_t max[UPB_MAXARRSIZE + 1] = {0};
  5939. upb_inttable_iter i;
  5940. size_t arr_count;
  5941. int size_lg2;
  5942. upb_inttable new_t;
  5943. upb_check_alloc(&t->t, a);
  5944. upb_inttable_begin(&i, t);
  5945. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5946. uintptr_t key = upb_inttable_iter_key(&i);
  5947. int bucket = log2ceil(key);
  5948. max[bucket] = UPB_MAX(max[bucket], key);
  5949. counts[bucket]++;
  5950. }
  5951. /* Find the largest power of two that satisfies the MIN_DENSITY
  5952. * definition (while actually having some keys). */
  5953. arr_count = upb_inttable_count(t);
  5954. for (size_lg2 = ARRAY_SIZE(counts) - 1; size_lg2 > 0; size_lg2--) {
  5955. if (counts[size_lg2] == 0) {
  5956. /* We can halve again without losing any entries. */
  5957. continue;
  5958. } else if (arr_count >= (1 << size_lg2) * MIN_DENSITY) {
  5959. break;
  5960. }
  5961. arr_count -= counts[size_lg2];
  5962. }
  5963. UPB_ASSERT(arr_count <= upb_inttable_count(t));
  5964. {
  5965. /* Insert all elements into new, perfectly-sized table. */
  5966. size_t arr_size = max[size_lg2] + 1; /* +1 so arr[max] will fit. */
  5967. size_t hash_count = upb_inttable_count(t) - arr_count;
  5968. size_t hash_size = hash_count ? (hash_count / MAX_LOAD) + 1 : 0;
  5969. size_t hashsize_lg2 = log2ceil(hash_size);
  5970. upb_inttable_sizedinit(&new_t, t->t.ctype, arr_size, hashsize_lg2, a);
  5971. upb_inttable_begin(&i, t);
  5972. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5973. uintptr_t k = upb_inttable_iter_key(&i);
  5974. upb_inttable_insert2(&new_t, k, upb_inttable_iter_value(&i), a);
  5975. }
  5976. UPB_ASSERT(new_t.array_size == arr_size);
  5977. UPB_ASSERT(new_t.t.size_lg2 == hashsize_lg2);
  5978. }
  5979. upb_inttable_uninit2(t, a);
  5980. *t = new_t;
  5981. }
  5982. /* Iteration. */
  5983. static const upb_tabent *int_tabent(const upb_inttable_iter *i) {
  5984. UPB_ASSERT(!i->array_part);
  5985. return &i->t->t.entries[i->index];
  5986. }
  5987. static upb_tabval int_arrent(const upb_inttable_iter *i) {
  5988. UPB_ASSERT(i->array_part);
  5989. return i->t->array[i->index];
  5990. }
  5991. void upb_inttable_begin(upb_inttable_iter *i, const upb_inttable *t) {
  5992. i->t = t;
  5993. i->index = -1;
  5994. i->array_part = true;
  5995. upb_inttable_next(i);
  5996. }
  5997. void upb_inttable_next(upb_inttable_iter *iter) {
  5998. const upb_inttable *t = iter->t;
  5999. if (iter->array_part) {
  6000. while (++iter->index < t->array_size) {
  6001. if (upb_arrhas(int_arrent(iter))) {
  6002. return;
  6003. }
  6004. }
  6005. iter->array_part = false;
  6006. iter->index = begin(&t->t);
  6007. } else {
  6008. iter->index = next(&t->t, iter->index);
  6009. }
  6010. }
  6011. bool upb_inttable_done(const upb_inttable_iter *i) {
  6012. if (i->array_part) {
  6013. return i->index >= i->t->array_size ||
  6014. !upb_arrhas(int_arrent(i));
  6015. } else {
  6016. return i->index >= upb_table_size(&i->t->t) ||
  6017. upb_tabent_isempty(int_tabent(i));
  6018. }
  6019. }
  6020. uintptr_t upb_inttable_iter_key(const upb_inttable_iter *i) {
  6021. UPB_ASSERT(!upb_inttable_done(i));
  6022. return i->array_part ? i->index : int_tabent(i)->key;
  6023. }
  6024. upb_value upb_inttable_iter_value(const upb_inttable_iter *i) {
  6025. UPB_ASSERT(!upb_inttable_done(i));
  6026. return _upb_value_val(
  6027. i->array_part ? i->t->array[i->index].val : int_tabent(i)->val.val,
  6028. i->t->t.ctype);
  6029. }
  6030. void upb_inttable_iter_setdone(upb_inttable_iter *i) {
  6031. i->index = SIZE_MAX;
  6032. i->array_part = false;
  6033. }
  6034. bool upb_inttable_iter_isequal(const upb_inttable_iter *i1,
  6035. const upb_inttable_iter *i2) {
  6036. if (upb_inttable_done(i1) && upb_inttable_done(i2))
  6037. return true;
  6038. return i1->t == i2->t && i1->index == i2->index &&
  6039. i1->array_part == i2->array_part;
  6040. }
  6041. #ifdef UPB_UNALIGNED_READS_OK
  6042. /* -----------------------------------------------------------------------------
  6043. * MurmurHash2, by Austin Appleby (released as public domain).
  6044. * Reformatted and C99-ified by Joshua Haberman.
  6045. * Note - This code makes a few assumptions about how your machine behaves -
  6046. * 1. We can read a 4-byte value from any address without crashing
  6047. * 2. sizeof(int) == 4 (in upb this limitation is removed by using uint32_t
  6048. * And it has a few limitations -
  6049. * 1. It will not work incrementally.
  6050. * 2. It will not produce the same results on little-endian and big-endian
  6051. * machines. */
  6052. uint32_t MurmurHash2(const void *key, size_t len, uint32_t seed) {
  6053. /* 'm' and 'r' are mixing constants generated offline.
  6054. * They're not really 'magic', they just happen to work well. */
  6055. const uint32_t m = 0x5bd1e995;
  6056. const int32_t r = 24;
  6057. /* Initialize the hash to a 'random' value */
  6058. uint32_t h = seed ^ len;
  6059. /* Mix 4 bytes at a time into the hash */
  6060. const uint8_t * data = (const uint8_t *)key;
  6061. while(len >= 4) {
  6062. uint32_t k = *(uint32_t *)data;
  6063. k *= m;
  6064. k ^= k >> r;
  6065. k *= m;
  6066. h *= m;
  6067. h ^= k;
  6068. data += 4;
  6069. len -= 4;
  6070. }
  6071. /* Handle the last few bytes of the input array */
  6072. switch(len) {
  6073. case 3: h ^= data[2] << 16;
  6074. case 2: h ^= data[1] << 8;
  6075. case 1: h ^= data[0]; h *= m;
  6076. };
  6077. /* Do a few final mixes of the hash to ensure the last few
  6078. * bytes are well-incorporated. */
  6079. h ^= h >> 13;
  6080. h *= m;
  6081. h ^= h >> 15;
  6082. return h;
  6083. }
  6084. #else /* !UPB_UNALIGNED_READS_OK */
  6085. /* -----------------------------------------------------------------------------
  6086. * MurmurHashAligned2, by Austin Appleby
  6087. * Same algorithm as MurmurHash2, but only does aligned reads - should be safer
  6088. * on certain platforms.
  6089. * Performance will be lower than MurmurHash2 */
  6090. #define MIX(h,k,m) { k *= m; k ^= k >> r; k *= m; h *= m; h ^= k; }
  6091. uint32_t MurmurHash2(const void * key, size_t len, uint32_t seed) {
  6092. const uint32_t m = 0x5bd1e995;
  6093. const int32_t r = 24;
  6094. const uint8_t * data = (const uint8_t *)key;
  6095. uint32_t h = seed ^ len;
  6096. uint8_t align = (uintptr_t)data & 3;
  6097. if(align && (len >= 4)) {
  6098. /* Pre-load the temp registers */
  6099. uint32_t t = 0, d = 0;
  6100. int32_t sl;
  6101. int32_t sr;
  6102. switch(align) {
  6103. case 1: t |= data[2] << 16;
  6104. case 2: t |= data[1] << 8;
  6105. case 3: t |= data[0];
  6106. }
  6107. t <<= (8 * align);
  6108. data += 4-align;
  6109. len -= 4-align;
  6110. sl = 8 * (4-align);
  6111. sr = 8 * align;
  6112. /* Mix */
  6113. while(len >= 4) {
  6114. uint32_t k;
  6115. d = *(uint32_t *)data;
  6116. t = (t >> sr) | (d << sl);
  6117. k = t;
  6118. MIX(h,k,m);
  6119. t = d;
  6120. data += 4;
  6121. len -= 4;
  6122. }
  6123. /* Handle leftover data in temp registers */
  6124. d = 0;
  6125. if(len >= align) {
  6126. uint32_t k;
  6127. switch(align) {
  6128. case 3: d |= data[2] << 16;
  6129. case 2: d |= data[1] << 8;
  6130. case 1: d |= data[0];
  6131. }
  6132. k = (t >> sr) | (d << sl);
  6133. MIX(h,k,m);
  6134. data += align;
  6135. len -= align;
  6136. /* ----------
  6137. * Handle tail bytes */
  6138. switch(len) {
  6139. case 3: h ^= data[2] << 16;
  6140. case 2: h ^= data[1] << 8;
  6141. case 1: h ^= data[0]; h *= m;
  6142. };
  6143. } else {
  6144. switch(len) {
  6145. case 3: d |= data[2] << 16;
  6146. case 2: d |= data[1] << 8;
  6147. case 1: d |= data[0];
  6148. case 0: h ^= (t >> sr) | (d << sl); h *= m;
  6149. }
  6150. }
  6151. h ^= h >> 13;
  6152. h *= m;
  6153. h ^= h >> 15;
  6154. return h;
  6155. } else {
  6156. while(len >= 4) {
  6157. uint32_t k = *(uint32_t *)data;
  6158. MIX(h,k,m);
  6159. data += 4;
  6160. len -= 4;
  6161. }
  6162. /* ----------
  6163. * Handle tail bytes */
  6164. switch(len) {
  6165. case 3: h ^= data[2] << 16;
  6166. case 2: h ^= data[1] << 8;
  6167. case 1: h ^= data[0]; h *= m;
  6168. };
  6169. h ^= h >> 13;
  6170. h *= m;
  6171. h ^= h >> 15;
  6172. return h;
  6173. }
  6174. }
  6175. #undef MIX
  6176. #endif /* UPB_UNALIGNED_READS_OK */
  6177. #include <errno.h>
  6178. #include <stdarg.h>
  6179. #include <stddef.h>
  6180. #include <stdint.h>
  6181. #include <stdio.h>
  6182. #include <stdlib.h>
  6183. #include <string.h>
  6184. bool upb_dumptostderr(void *closure, const upb_status* status) {
  6185. UPB_UNUSED(closure);
  6186. fprintf(stderr, "%s\n", upb_status_errmsg(status));
  6187. return false;
  6188. }
  6189. /* Guarantee null-termination and provide ellipsis truncation.
  6190. * It may be tempting to "optimize" this by initializing these final
  6191. * four bytes up-front and then being careful never to overwrite them,
  6192. * this is safer and simpler. */
  6193. static void nullz(upb_status *status) {
  6194. const char *ellipsis = "...";
  6195. size_t len = strlen(ellipsis);
  6196. UPB_ASSERT(sizeof(status->msg) > len);
  6197. memcpy(status->msg + sizeof(status->msg) - len, ellipsis, len);
  6198. }
  6199. /* upb_upberr *****************************************************************/
  6200. upb_errorspace upb_upberr = {"upb error"};
  6201. void upb_upberr_setoom(upb_status *status) {
  6202. status->error_space_ = &upb_upberr;
  6203. upb_status_seterrmsg(status, "Out of memory");
  6204. }
  6205. /* upb_status *****************************************************************/
  6206. void upb_status_clear(upb_status *status) {
  6207. if (!status) return;
  6208. status->ok_ = true;
  6209. status->code_ = 0;
  6210. status->msg[0] = '\0';
  6211. }
  6212. bool upb_ok(const upb_status *status) { return status->ok_; }
  6213. upb_errorspace *upb_status_errspace(const upb_status *status) {
  6214. return status->error_space_;
  6215. }
  6216. int upb_status_errcode(const upb_status *status) { return status->code_; }
  6217. const char *upb_status_errmsg(const upb_status *status) { return status->msg; }
  6218. void upb_status_seterrmsg(upb_status *status, const char *msg) {
  6219. if (!status) return;
  6220. status->ok_ = false;
  6221. strncpy(status->msg, msg, sizeof(status->msg));
  6222. nullz(status);
  6223. }
  6224. void upb_status_seterrf(upb_status *status, const char *fmt, ...) {
  6225. va_list args;
  6226. va_start(args, fmt);
  6227. upb_status_vseterrf(status, fmt, args);
  6228. va_end(args);
  6229. }
  6230. void upb_status_vseterrf(upb_status *status, const char *fmt, va_list args) {
  6231. if (!status) return;
  6232. status->ok_ = false;
  6233. _upb_vsnprintf(status->msg, sizeof(status->msg), fmt, args);
  6234. nullz(status);
  6235. }
  6236. void upb_status_copy(upb_status *to, const upb_status *from) {
  6237. if (!to) return;
  6238. *to = *from;
  6239. }
  6240. /* upb_alloc ******************************************************************/
  6241. static void *upb_global_allocfunc(upb_alloc *alloc, void *ptr, size_t oldsize,
  6242. size_t size) {
  6243. UPB_UNUSED(alloc);
  6244. UPB_UNUSED(oldsize);
  6245. if (size == 0) {
  6246. free(ptr);
  6247. return NULL;
  6248. } else {
  6249. return realloc(ptr, size);
  6250. }
  6251. }
  6252. upb_alloc upb_alloc_global = {&upb_global_allocfunc};
  6253. /* upb_arena ******************************************************************/
  6254. /* Be conservative and choose 16 in case anyone is using SSE. */
  6255. static const size_t maxalign = 16;
  6256. static size_t align_up_max(size_t size) {
  6257. return ((size + maxalign - 1) / maxalign) * maxalign;
  6258. }
  6259. typedef struct mem_block {
  6260. struct mem_block *next;
  6261. size_t size;
  6262. size_t used;
  6263. bool owned;
  6264. /* Data follows. */
  6265. } mem_block;
  6266. typedef struct cleanup_ent {
  6267. struct cleanup_ent *next;
  6268. upb_cleanup_func *cleanup;
  6269. void *ud;
  6270. } cleanup_ent;
  6271. static void upb_arena_addblock(upb_arena *a, void *ptr, size_t size,
  6272. bool owned) {
  6273. mem_block *block = ptr;
  6274. block->next = a->block_head;
  6275. block->size = size;
  6276. block->used = align_up_max(sizeof(mem_block));
  6277. block->owned = owned;
  6278. a->block_head = block;
  6279. /* TODO(haberman): ASAN poison. */
  6280. }
  6281. static mem_block *upb_arena_allocblock(upb_arena *a, size_t size) {
  6282. size_t block_size = UPB_MAX(size, a->next_block_size) + sizeof(mem_block);
  6283. mem_block *block = upb_malloc(a->block_alloc, block_size);
  6284. if (!block) {
  6285. return NULL;
  6286. }
  6287. upb_arena_addblock(a, block, block_size, true);
  6288. a->next_block_size = UPB_MIN(block_size * 2, a->max_block_size);
  6289. return block;
  6290. }
  6291. static void *upb_arena_doalloc(upb_alloc *alloc, void *ptr, size_t oldsize,
  6292. size_t size) {
  6293. upb_arena *a = (upb_arena*)alloc; /* upb_alloc is initial member. */
  6294. mem_block *block = a->block_head;
  6295. void *ret;
  6296. if (size == 0) {
  6297. return NULL; /* We are an arena, don't need individual frees. */
  6298. }
  6299. size = align_up_max(size);
  6300. /* TODO(haberman): special-case if this is a realloc of the last alloc? */
  6301. if (!block || block->size - block->used < size) {
  6302. /* Slow path: have to allocate a new block. */
  6303. block = upb_arena_allocblock(a, size);
  6304. if (!block) {
  6305. return NULL; /* Out of memory. */
  6306. }
  6307. }
  6308. ret = (char*)block + block->used;
  6309. block->used += size;
  6310. if (oldsize > 0) {
  6311. memcpy(ret, ptr, oldsize); /* Preserve existing data. */
  6312. }
  6313. /* TODO(haberman): ASAN unpoison. */
  6314. a->bytes_allocated += size;
  6315. return ret;
  6316. }
  6317. /* Public Arena API ***********************************************************/
  6318. void upb_arena_init(upb_arena *a) {
  6319. a->alloc.func = &upb_arena_doalloc;
  6320. a->block_alloc = &upb_alloc_global;
  6321. a->bytes_allocated = 0;
  6322. a->next_block_size = 256;
  6323. a->max_block_size = 16384;
  6324. a->cleanup_head = NULL;
  6325. a->block_head = NULL;
  6326. }
  6327. void upb_arena_init2(upb_arena *a, void *mem, size_t size, upb_alloc *alloc) {
  6328. upb_arena_init(a);
  6329. if (size > sizeof(mem_block)) {
  6330. upb_arena_addblock(a, mem, size, false);
  6331. }
  6332. if (alloc) {
  6333. a->block_alloc = alloc;
  6334. }
  6335. }
  6336. void upb_arena_uninit(upb_arena *a) {
  6337. cleanup_ent *ent = a->cleanup_head;
  6338. mem_block *block = a->block_head;
  6339. while (ent) {
  6340. ent->cleanup(ent->ud);
  6341. ent = ent->next;
  6342. }
  6343. /* Must do this after running cleanup functions, because this will delete
  6344. * the memory we store our cleanup entries in! */
  6345. while (block) {
  6346. mem_block *next = block->next;
  6347. if (block->owned) {
  6348. upb_free(a->block_alloc, block);
  6349. }
  6350. block = next;
  6351. }
  6352. /* Protect against multiple-uninit. */
  6353. a->cleanup_head = NULL;
  6354. a->block_head = NULL;
  6355. }
  6356. bool upb_arena_addcleanup(upb_arena *a, upb_cleanup_func *func, void *ud) {
  6357. cleanup_ent *ent = upb_malloc(&a->alloc, sizeof(cleanup_ent));
  6358. if (!ent) {
  6359. return false; /* Out of memory. */
  6360. }
  6361. ent->cleanup = func;
  6362. ent->ud = ud;
  6363. ent->next = a->cleanup_head;
  6364. a->cleanup_head = ent;
  6365. return true;
  6366. }
  6367. size_t upb_arena_bytesallocated(const upb_arena *a) {
  6368. return a->bytes_allocated;
  6369. }
  6370. /* Standard error functions ***************************************************/
  6371. static bool default_err(void *ud, const upb_status *status) {
  6372. UPB_UNUSED(ud);
  6373. UPB_UNUSED(status);
  6374. return false;
  6375. }
  6376. static bool write_err_to(void *ud, const upb_status *status) {
  6377. upb_status *copy_to = ud;
  6378. upb_status_copy(copy_to, status);
  6379. return false;
  6380. }
  6381. /* upb_env ********************************************************************/
  6382. void upb_env_initonly(upb_env *e) {
  6383. e->ok_ = true;
  6384. e->error_func_ = &default_err;
  6385. e->error_ud_ = NULL;
  6386. }
  6387. void upb_env_init(upb_env *e) {
  6388. upb_arena_init(&e->arena_);
  6389. upb_env_initonly(e);
  6390. }
  6391. void upb_env_init2(upb_env *e, void *mem, size_t n, upb_alloc *alloc) {
  6392. upb_arena_init2(&e->arena_, mem, n, alloc);
  6393. upb_env_initonly(e);
  6394. }
  6395. void upb_env_uninit(upb_env *e) {
  6396. upb_arena_uninit(&e->arena_);
  6397. }
  6398. void upb_env_seterrorfunc(upb_env *e, upb_error_func *func, void *ud) {
  6399. e->error_func_ = func;
  6400. e->error_ud_ = ud;
  6401. }
  6402. void upb_env_reporterrorsto(upb_env *e, upb_status *s) {
  6403. e->error_func_ = &write_err_to;
  6404. e->error_ud_ = s;
  6405. }
  6406. bool upb_env_reporterror(upb_env *e, const upb_status *status) {
  6407. e->ok_ = false;
  6408. return e->error_func_(e->error_ud_, status);
  6409. }
  6410. void *upb_env_malloc(upb_env *e, size_t size) {
  6411. return upb_malloc(&e->arena_.alloc, size);
  6412. }
  6413. void *upb_env_realloc(upb_env *e, void *ptr, size_t oldsize, size_t size) {
  6414. return upb_realloc(&e->arena_.alloc, ptr, oldsize, size);
  6415. }
  6416. void upb_env_free(upb_env *e, void *ptr) {
  6417. upb_free(&e->arena_.alloc, ptr);
  6418. }
  6419. bool upb_env_addcleanup(upb_env *e, upb_cleanup_func *func, void *ud) {
  6420. return upb_arena_addcleanup(&e->arena_, func, ud);
  6421. }
  6422. size_t upb_env_bytesallocated(const upb_env *e) {
  6423. return upb_arena_bytesallocated(&e->arena_);
  6424. }
  6425. /* This file was generated by upbc (the upb compiler) from the input
  6426. * file:
  6427. *
  6428. * upb/descriptor/descriptor.proto
  6429. *
  6430. * Do not edit -- your changes will be discarded when the file is
  6431. * regenerated. */
  6432. static const upb_msgdef msgs[22];
  6433. static const upb_fielddef fields[107];
  6434. static const upb_enumdef enums[5];
  6435. static const upb_tabent strentries[236];
  6436. static const upb_tabent intentries[18];
  6437. static const upb_tabval arrays[187];
  6438. #ifdef UPB_DEBUG_REFS
  6439. static upb_inttable reftables[268];
  6440. #endif
  6441. static const upb_msgdef msgs[22] = {
  6442. UPB_MSGDEF_INIT("google.protobuf.DescriptorProto", 41, 8, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[0], 11, 10), UPB_STRTABLE_INIT(10, 15, UPB_CTYPE_PTR, 4, &strentries[0]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[0], &reftables[1]),
  6443. UPB_MSGDEF_INIT("google.protobuf.DescriptorProto.ExtensionRange", 5, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[11], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[16]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[2], &reftables[3]),
  6444. UPB_MSGDEF_INIT("google.protobuf.DescriptorProto.ReservedRange", 5, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[14], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[20]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[4], &reftables[5]),
  6445. UPB_MSGDEF_INIT("google.protobuf.EnumDescriptorProto", 12, 2, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[17], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[24]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[6], &reftables[7]),
  6446. UPB_MSGDEF_INIT("google.protobuf.EnumOptions", 9, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[0], &arrays[21], 4, 2), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[28]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[8], &reftables[9]),
  6447. UPB_MSGDEF_INIT("google.protobuf.EnumValueDescriptorProto", 9, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[25], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[32]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[10], &reftables[11]),
  6448. UPB_MSGDEF_INIT("google.protobuf.EnumValueOptions", 8, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[2], &arrays[29], 2, 1), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[36]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[12], &reftables[13]),
  6449. UPB_MSGDEF_INIT("google.protobuf.FieldDescriptorProto", 24, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[31], 11, 10), UPB_STRTABLE_INIT(10, 15, UPB_CTYPE_PTR, 4, &strentries[40]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[14], &reftables[15]),
  6450. UPB_MSGDEF_INIT("google.protobuf.FieldOptions", 13, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[4], &arrays[42], 11, 6), UPB_STRTABLE_INIT(7, 15, UPB_CTYPE_PTR, 4, &strentries[56]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[16], &reftables[17]),
  6451. UPB_MSGDEF_INIT("google.protobuf.FileDescriptorProto", 43, 6, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[53], 13, 12), UPB_STRTABLE_INIT(12, 15, UPB_CTYPE_PTR, 4, &strentries[72]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[18], &reftables[19]),
  6452. UPB_MSGDEF_INIT("google.protobuf.FileDescriptorSet", 7, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[66], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[88]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[20], &reftables[21]),
  6453. UPB_MSGDEF_INIT("google.protobuf.FileOptions", 38, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[6], &arrays[68], 42, 17), UPB_STRTABLE_INIT(18, 31, UPB_CTYPE_PTR, 5, &strentries[92]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[22], &reftables[23]),
  6454. UPB_MSGDEF_INIT("google.protobuf.MessageOptions", 11, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[8], &arrays[110], 8, 4), UPB_STRTABLE_INIT(5, 7, UPB_CTYPE_PTR, 3, &strentries[124]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[24], &reftables[25]),
  6455. UPB_MSGDEF_INIT("google.protobuf.MethodDescriptorProto", 16, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[118], 7, 6), UPB_STRTABLE_INIT(6, 7, UPB_CTYPE_PTR, 3, &strentries[132]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[26], &reftables[27]),
  6456. UPB_MSGDEF_INIT("google.protobuf.MethodOptions", 8, 1, UPB_INTTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &intentries[10], &arrays[125], 1, 0), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[140]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[28], &reftables[29]),
  6457. UPB_MSGDEF_INIT("google.protobuf.OneofDescriptorProto", 6, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[126], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[144]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[30], &reftables[31]),
  6458. UPB_MSGDEF_INIT("google.protobuf.ServiceDescriptorProto", 12, 2, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[128], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[148]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[32], &reftables[33]),
  6459. UPB_MSGDEF_INIT("google.protobuf.ServiceOptions", 8, 1, UPB_INTTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &intentries[14], &arrays[132], 1, 0), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[152]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[34], &reftables[35]),
  6460. UPB_MSGDEF_INIT("google.protobuf.SourceCodeInfo", 7, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[133], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[156]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[36], &reftables[37]),
  6461. UPB_MSGDEF_INIT("google.protobuf.SourceCodeInfo.Location", 20, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[135], 7, 5), UPB_STRTABLE_INIT(5, 7, UPB_CTYPE_PTR, 3, &strentries[160]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[38], &reftables[39]),
  6462. UPB_MSGDEF_INIT("google.protobuf.UninterpretedOption", 19, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[142], 9, 7), UPB_STRTABLE_INIT(7, 15, UPB_CTYPE_PTR, 4, &strentries[168]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[40], &reftables[41]),
  6463. UPB_MSGDEF_INIT("google.protobuf.UninterpretedOption.NamePart", 7, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[151], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[184]), false, UPB_SYNTAX_PROTO2, UPB_WELLKNOWN_UNSPECIFIED, &reftables[42], &reftables[43]),
  6464. };
  6465. static const upb_fielddef fields[107] = {
  6466. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "aggregate_value", 8, &msgs[20], NULL, 16, 6, {0},&reftables[44], &reftables[45]),
  6467. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "allow_alias", 2, &msgs[4], NULL, 7, 1, {0},&reftables[46], &reftables[47]),
  6468. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "cc_enable_arenas", 31, &msgs[11], NULL, 24, 12, {0},&reftables[48], &reftables[49]),
  6469. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "cc_generic_services", 16, &msgs[11], NULL, 18, 6, {0},&reftables[50], &reftables[51]),
  6470. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "client_streaming", 5, &msgs[13], NULL, 14, 4, {0},&reftables[52], &reftables[53]),
  6471. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "csharp_namespace", 37, &msgs[11], NULL, 28, 14, {0},&reftables[54], &reftables[55]),
  6472. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "ctype", 1, &msgs[8], (const upb_def*)(&enums[2]), 7, 1, {0},&reftables[56], &reftables[57]),
  6473. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "default_value", 7, &msgs[7], NULL, 17, 7, {0},&reftables[58], &reftables[59]),
  6474. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_STRING, 0, false, false, false, false, "dependency", 3, &msgs[9], NULL, 31, 8, {0},&reftables[60], &reftables[61]),
  6475. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[8], NULL, 9, 3, {0},&reftables[62], &reftables[63]),
  6476. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 33, &msgs[14], NULL, 7, 1, {0},&reftables[64], &reftables[65]),
  6477. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[12], NULL, 9, 3, {0},&reftables[66], &reftables[67]),
  6478. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 23, &msgs[11], NULL, 22, 10, {0},&reftables[68], &reftables[69]),
  6479. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 1, &msgs[6], NULL, 7, 1, {0},&reftables[70], &reftables[71]),
  6480. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[4], NULL, 8, 2, {0},&reftables[72], &reftables[73]),
  6481. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 33, &msgs[17], NULL, 7, 1, {0},&reftables[74], &reftables[75]),
  6482. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_DOUBLE, 0, false, false, false, false, "double_value", 6, &msgs[20], NULL, 12, 4, {0},&reftables[76], &reftables[77]),
  6483. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "end", 2, &msgs[2], NULL, 4, 1, {0},&reftables[78], &reftables[79]),
  6484. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "end", 2, &msgs[1], NULL, 4, 1, {0},&reftables[80], &reftables[81]),
  6485. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "enum_type", 5, &msgs[9], (const upb_def*)(&msgs[3]), 14, 1, {0},&reftables[82], &reftables[83]),
  6486. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "enum_type", 4, &msgs[0], (const upb_def*)(&msgs[3]), 19, 2, {0},&reftables[84], &reftables[85]),
  6487. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "extendee", 2, &msgs[7], NULL, 8, 2, {0},&reftables[86], &reftables[87]),
  6488. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension", 6, &msgs[0], (const upb_def*)(&msgs[7]), 25, 4, {0},&reftables[88], &reftables[89]),
  6489. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension", 7, &msgs[9], (const upb_def*)(&msgs[7]), 20, 3, {0},&reftables[90], &reftables[91]),
  6490. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension_range", 5, &msgs[0], (const upb_def*)(&msgs[1]), 22, 3, {0},&reftables[92], &reftables[93]),
  6491. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "field", 2, &msgs[0], (const upb_def*)(&msgs[7]), 13, 0, {0},&reftables[94], &reftables[95]),
  6492. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "file", 1, &msgs[10], (const upb_def*)(&msgs[9]), 6, 0, {0},&reftables[96], &reftables[97]),
  6493. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "go_package", 11, &msgs[11], NULL, 15, 5, {0},&reftables[98], &reftables[99]),
  6494. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "identifier_value", 3, &msgs[20], NULL, 7, 1, {0},&reftables[100], &reftables[101]),
  6495. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "input_type", 2, &msgs[13], NULL, 8, 2, {0},&reftables[102], &reftables[103]),
  6496. UPB_FIELDDEF_INIT(UPB_LABEL_REQUIRED, UPB_TYPE_BOOL, 0, false, false, false, false, "is_extension", 2, &msgs[21], NULL, 6, 1, {0},&reftables[104], &reftables[105]),
  6497. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_generate_equals_and_hash", 20, &msgs[11], NULL, 21, 9, {0},&reftables[106], &reftables[107]),
  6498. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_generic_services", 17, &msgs[11], NULL, 19, 7, {0},&reftables[108], &reftables[109]),
  6499. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_multiple_files", 10, &msgs[11], NULL, 14, 4, {0},&reftables[110], &reftables[111]),
  6500. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "java_outer_classname", 8, &msgs[11], NULL, 10, 2, {0},&reftables[112], &reftables[113]),
  6501. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "java_package", 1, &msgs[11], NULL, 7, 1, {0},&reftables[114], &reftables[115]),
  6502. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_string_check_utf8", 27, &msgs[11], NULL, 23, 11, {0},&reftables[116], &reftables[117]),
  6503. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "javanano_use_deprecated_package", 38, &msgs[11], NULL, 31, 15, {0},&reftables[118], &reftables[119]),
  6504. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "json_name", 10, &msgs[7], NULL, 21, 9, {0},&reftables[120], &reftables[121]),
  6505. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "jstype", 6, &msgs[8], (const upb_def*)(&enums[3]), 11, 5, {0},&reftables[122], &reftables[123]),
  6506. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "label", 4, &msgs[7], (const upb_def*)(&enums[0]), 12, 4, {0},&reftables[124], &reftables[125]),
  6507. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "lazy", 5, &msgs[8], NULL, 10, 4, {0},&reftables[126], &reftables[127]),
  6508. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "leading_comments", 3, &msgs[19], NULL, 9, 2, {0},&reftables[128], &reftables[129]),
  6509. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_STRING, 0, false, false, false, false, "leading_detached_comments", 6, &msgs[19], NULL, 17, 4, {0},&reftables[130], &reftables[131]),
  6510. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "location", 1, &msgs[18], (const upb_def*)(&msgs[19]), 6, 0, {0},&reftables[132], &reftables[133]),
  6511. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "map_entry", 7, &msgs[12], NULL, 10, 4, {0},&reftables[134], &reftables[135]),
  6512. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "message_set_wire_format", 1, &msgs[12], NULL, 7, 1, {0},&reftables[136], &reftables[137]),
  6513. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "message_type", 4, &msgs[9], (const upb_def*)(&msgs[0]), 11, 0, {0},&reftables[138], &reftables[139]),
  6514. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "method", 2, &msgs[16], (const upb_def*)(&msgs[13]), 7, 0, {0},&reftables[140], &reftables[141]),
  6515. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "name", 2, &msgs[20], (const upb_def*)(&msgs[21]), 6, 0, {0},&reftables[142], &reftables[143]),
  6516. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[5], NULL, 5, 1, {0},&reftables[144], &reftables[145]),
  6517. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[9], NULL, 23, 6, {0},&reftables[146], &reftables[147]),
  6518. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[3], NULL, 9, 2, {0},&reftables[148], &reftables[149]),
  6519. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[16], NULL, 9, 2, {0},&reftables[150], &reftables[151]),
  6520. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[15], NULL, 3, 0, {0},&reftables[152], &reftables[153]),
  6521. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[13], NULL, 5, 1, {0},&reftables[154], &reftables[155]),
  6522. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[7], NULL, 5, 1, {0},&reftables[156], &reftables[157]),
  6523. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[0], NULL, 33, 8, {0},&reftables[158], &reftables[159]),
  6524. UPB_FIELDDEF_INIT(UPB_LABEL_REQUIRED, UPB_TYPE_STRING, 0, false, false, false, false, "name_part", 1, &msgs[21], NULL, 3, 0, {0},&reftables[160], &reftables[161]),
  6525. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT64, UPB_INTFMT_VARIABLE, false, false, false, false, "negative_int_value", 5, &msgs[20], NULL, 11, 3, {0},&reftables[162], &reftables[163]),
  6526. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "nested_type", 3, &msgs[0], (const upb_def*)(&msgs[0]), 16, 1, {0},&reftables[164], &reftables[165]),
  6527. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "no_standard_descriptor_accessor", 2, &msgs[12], NULL, 8, 2, {0},&reftables[166], &reftables[167]),
  6528. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "number", 3, &msgs[7], NULL, 11, 3, {0},&reftables[168], &reftables[169]),
  6529. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "number", 2, &msgs[5], NULL, 8, 2, {0},&reftables[170], &reftables[171]),
  6530. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "objc_class_prefix", 36, &msgs[11], NULL, 25, 13, {0},&reftables[172], &reftables[173]),
  6531. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "oneof_decl", 8, &msgs[0], (const upb_def*)(&msgs[15]), 29, 6, {0},&reftables[174], &reftables[175]),
  6532. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "oneof_index", 9, &msgs[7], NULL, 20, 8, {0},&reftables[176], &reftables[177]),
  6533. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "optimize_for", 9, &msgs[11], (const upb_def*)(&enums[4]), 13, 3, {0},&reftables[178], &reftables[179]),
  6534. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 7, &msgs[0], (const upb_def*)(&msgs[12]), 26, 5, {0},&reftables[180], &reftables[181]),
  6535. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 8, &msgs[9], (const upb_def*)(&msgs[11]), 21, 4, {0},&reftables[182], &reftables[183]),
  6536. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 8, &msgs[7], (const upb_def*)(&msgs[8]), 4, 0, {0},&reftables[184], &reftables[185]),
  6537. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 4, &msgs[13], (const upb_def*)(&msgs[14]), 4, 0, {0},&reftables[186], &reftables[187]),
  6538. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[16], (const upb_def*)(&msgs[17]), 8, 1, {0},&reftables[188], &reftables[189]),
  6539. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[3], (const upb_def*)(&msgs[4]), 8, 1, {0},&reftables[190], &reftables[191]),
  6540. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[5], (const upb_def*)(&msgs[6]), 4, 0, {0},&reftables[192], &reftables[193]),
  6541. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "output_type", 3, &msgs[13], NULL, 11, 3, {0},&reftables[194], &reftables[195]),
  6542. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "package", 2, &msgs[9], NULL, 26, 7, {0},&reftables[196], &reftables[197]),
  6543. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "packed", 2, &msgs[8], NULL, 8, 2, {0},&reftables[198], &reftables[199]),
  6544. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, true, "path", 1, &msgs[19], NULL, 5, 0, {0},&reftables[200], &reftables[201]),
  6545. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "php_class_prefix", 40, &msgs[11], NULL, 32, 16, {0},&reftables[202], &reftables[203]),
  6546. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "php_namespace", 41, &msgs[11], NULL, 35, 17, {0},&reftables[204], &reftables[205]),
  6547. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_UINT64, UPB_INTFMT_VARIABLE, false, false, false, false, "positive_int_value", 4, &msgs[20], NULL, 10, 2, {0},&reftables[206], &reftables[207]),
  6548. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "public_dependency", 10, &msgs[9], NULL, 36, 9, {0},&reftables[208], &reftables[209]),
  6549. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "py_generic_services", 18, &msgs[11], NULL, 20, 8, {0},&reftables[210], &reftables[211]),
  6550. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_STRING, 0, false, false, false, false, "reserved_name", 10, &msgs[0], NULL, 38, 9, {0},&reftables[212], &reftables[213]),
  6551. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "reserved_range", 9, &msgs[0], (const upb_def*)(&msgs[2]), 32, 7, {0},&reftables[214], &reftables[215]),
  6552. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "server_streaming", 6, &msgs[13], NULL, 15, 5, {0},&reftables[216], &reftables[217]),
  6553. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "service", 6, &msgs[9], (const upb_def*)(&msgs[16]), 17, 2, {0},&reftables[218], &reftables[219]),
  6554. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "source_code_info", 9, &msgs[9], (const upb_def*)(&msgs[18]), 22, 5, {0},&reftables[220], &reftables[221]),
  6555. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, true, "span", 2, &msgs[19], NULL, 8, 1, {0},&reftables[222], &reftables[223]),
  6556. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "start", 1, &msgs[2], NULL, 3, 0, {0},&reftables[224], &reftables[225]),
  6557. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "start", 1, &msgs[1], NULL, 3, 0, {0},&reftables[226], &reftables[227]),
  6558. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BYTES, 0, false, false, false, false, "string_value", 7, &msgs[20], NULL, 13, 5, {0},&reftables[228], &reftables[229]),
  6559. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "syntax", 12, &msgs[9], NULL, 40, 11, {0},&reftables[230], &reftables[231]),
  6560. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "trailing_comments", 4, &msgs[19], NULL, 12, 3, {0},&reftables[232], &reftables[233]),
  6561. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "type", 5, &msgs[7], (const upb_def*)(&enums[1]), 13, 5, {0},&reftables[234], &reftables[235]),
  6562. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "type_name", 6, &msgs[7], NULL, 14, 6, {0},&reftables[236], &reftables[237]),
  6563. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[12], (const upb_def*)(&msgs[20]), 6, 0, {0},&reftables[238], &reftables[239]),
  6564. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[17], (const upb_def*)(&msgs[20]), 6, 0, {0},&reftables[240], &reftables[241]),
  6565. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[11], (const upb_def*)(&msgs[20]), 6, 0, {0},&reftables[242], &reftables[243]),
  6566. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[14], (const upb_def*)(&msgs[20]), 6, 0, {0},&reftables[244], &reftables[245]),
  6567. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[8], (const upb_def*)(&msgs[20]), 6, 0, {0},&reftables[246], &reftables[247]),
  6568. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[6], (const upb_def*)(&msgs[20]), 6, 0, {0},&reftables[248], &reftables[249]),
  6569. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[4], (const upb_def*)(&msgs[20]), 6, 0, {0},&reftables[250], &reftables[251]),
  6570. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "value", 2, &msgs[3], (const upb_def*)(&msgs[5]), 7, 0, {0},&reftables[252], &reftables[253]),
  6571. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "weak", 10, &msgs[8], NULL, 12, 6, {0},&reftables[254], &reftables[255]),
  6572. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "weak_dependency", 11, &msgs[9], NULL, 39, 10, {0},&reftables[256], &reftables[257]),
  6573. };
  6574. static const upb_enumdef enums[5] = {
  6575. UPB_ENUMDEF_INIT("google.protobuf.FieldDescriptorProto.Label", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[188]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[154], 4, 3), 0, &reftables[258], &reftables[259]),
  6576. UPB_ENUMDEF_INIT("google.protobuf.FieldDescriptorProto.Type", UPB_STRTABLE_INIT(18, 31, UPB_CTYPE_INT32, 5, &strentries[192]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[158], 19, 18), 0, &reftables[260], &reftables[261]),
  6577. UPB_ENUMDEF_INIT("google.protobuf.FieldOptions.CType", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[224]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[177], 3, 3), 0, &reftables[262], &reftables[263]),
  6578. UPB_ENUMDEF_INIT("google.protobuf.FieldOptions.JSType", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[228]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[180], 3, 3), 0, &reftables[264], &reftables[265]),
  6579. UPB_ENUMDEF_INIT("google.protobuf.FileOptions.OptimizeMode", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[232]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[183], 4, 3), 0, &reftables[266], &reftables[267]),
  6580. };
  6581. static const upb_tabent strentries[236] = {
  6582. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "extension"), UPB_TABVALUE_PTR_INIT(&fields[22]), NULL},
  6583. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6584. {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "reserved_name"), UPB_TABVALUE_PTR_INIT(&fields[84]), NULL},
  6585. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[57]), NULL},
  6586. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6587. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6588. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6589. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "field"), UPB_TABVALUE_PTR_INIT(&fields[25]), &strentries[12]},
  6590. {UPB_TABKEY_STR("\017", "\000", "\000", "\000", "extension_range"), UPB_TABVALUE_PTR_INIT(&fields[24]), &strentries[14]},
  6591. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6592. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "nested_type"), UPB_TABVALUE_PTR_INIT(&fields[60]), NULL},
  6593. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6594. {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "reserved_range"), UPB_TABVALUE_PTR_INIT(&fields[85]), NULL},
  6595. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[68]), NULL},
  6596. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "oneof_decl"), UPB_TABVALUE_PTR_INIT(&fields[65]), NULL},
  6597. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "enum_type"), UPB_TABVALUE_PTR_INIT(&fields[20]), &strentries[13]},
  6598. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "start"), UPB_TABVALUE_PTR_INIT(&fields[91]), NULL},
  6599. {UPB_TABKEY_STR("\003", "\000", "\000", "\000", "end"), UPB_TABVALUE_PTR_INIT(&fields[18]), NULL},
  6600. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6601. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6602. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "start"), UPB_TABVALUE_PTR_INIT(&fields[90]), NULL},
  6603. {UPB_TABKEY_STR("\003", "\000", "\000", "\000", "end"), UPB_TABVALUE_PTR_INIT(&fields[17]), NULL},
  6604. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6605. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6606. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6607. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "value"), UPB_TABVALUE_PTR_INIT(&fields[104]), NULL},
  6608. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[73]), NULL},
  6609. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[52]), &strentries[26]},
  6610. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[103]), NULL},
  6611. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[14]), NULL},
  6612. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "allow_alias"), UPB_TABVALUE_PTR_INIT(&fields[1]), NULL},
  6613. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6614. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "number"), UPB_TABVALUE_PTR_INIT(&fields[63]), NULL},
  6615. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6616. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[74]), NULL},
  6617. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[50]), &strentries[34]},
  6618. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[102]), NULL},
  6619. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[13]), NULL},
  6620. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6621. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6622. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "oneof_index"), UPB_TABVALUE_PTR_INIT(&fields[66]), NULL},
  6623. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "label"), UPB_TABVALUE_PTR_INIT(&fields[40]), NULL},
  6624. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6625. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[56]), NULL},
  6626. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6627. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6628. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6629. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6630. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "number"), UPB_TABVALUE_PTR_INIT(&fields[62]), &strentries[53]},
  6631. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6632. {UPB_TABKEY_STR("\010", "\000", "\000", "\000", "extendee"), UPB_TABVALUE_PTR_INIT(&fields[21]), NULL},
  6633. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "type_name"), UPB_TABVALUE_PTR_INIT(&fields[96]), NULL},
  6634. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "json_name"), UPB_TABVALUE_PTR_INIT(&fields[38]), NULL},
  6635. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "type"), UPB_TABVALUE_PTR_INIT(&fields[95]), &strentries[50]},
  6636. {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "default_value"), UPB_TABVALUE_PTR_INIT(&fields[7]), NULL},
  6637. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[70]), NULL},
  6638. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[101]), NULL},
  6639. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6640. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "weak"), UPB_TABVALUE_PTR_INIT(&fields[105]), NULL},
  6641. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6642. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6643. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6644. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6645. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "packed"), UPB_TABVALUE_PTR_INIT(&fields[77]), NULL},
  6646. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "lazy"), UPB_TABVALUE_PTR_INIT(&fields[41]), NULL},
  6647. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6648. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "ctype"), UPB_TABVALUE_PTR_INIT(&fields[6]), NULL},
  6649. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6650. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "jstype"), UPB_TABVALUE_PTR_INIT(&fields[39]), NULL},
  6651. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[9]), NULL},
  6652. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6653. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6654. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "extension"), UPB_TABVALUE_PTR_INIT(&fields[23]), NULL},
  6655. {UPB_TABKEY_STR("\017", "\000", "\000", "\000", "weak_dependency"), UPB_TABVALUE_PTR_INIT(&fields[106]), NULL},
  6656. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6657. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[51]), NULL},
  6658. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "service"), UPB_TABVALUE_PTR_INIT(&fields[87]), NULL},
  6659. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6660. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "source_code_info"), UPB_TABVALUE_PTR_INIT(&fields[88]), NULL},
  6661. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6662. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6663. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "syntax"), UPB_TABVALUE_PTR_INIT(&fields[93]), NULL},
  6664. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "dependency"), UPB_TABVALUE_PTR_INIT(&fields[8]), NULL},
  6665. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "message_type"), UPB_TABVALUE_PTR_INIT(&fields[47]), NULL},
  6666. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "package"), UPB_TABVALUE_PTR_INIT(&fields[76]), NULL},
  6667. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[69]), &strentries[86]},
  6668. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "enum_type"), UPB_TABVALUE_PTR_INIT(&fields[19]), NULL},
  6669. {UPB_TABKEY_STR("\021", "\000", "\000", "\000", "public_dependency"), UPB_TABVALUE_PTR_INIT(&fields[82]), &strentries[85]},
  6670. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6671. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "file"), UPB_TABVALUE_PTR_INIT(&fields[26]), NULL},
  6672. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6673. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6674. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6675. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6676. {UPB_TABKEY_STR("\023", "\000", "\000", "\000", "cc_generic_services"), UPB_TABVALUE_PTR_INIT(&fields[3]), NULL},
  6677. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "csharp_namespace"), UPB_TABVALUE_PTR_INIT(&fields[5]), &strentries[116]},
  6678. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6679. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6680. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6681. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6682. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6683. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6684. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6685. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "go_package"), UPB_TABVALUE_PTR_INIT(&fields[27]), NULL},
  6686. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "java_package"), UPB_TABVALUE_PTR_INIT(&fields[35]), &strentries[120]},
  6687. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6688. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6689. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "java_outer_classname"), UPB_TABVALUE_PTR_INIT(&fields[34]), NULL},
  6690. {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "php_namespace"), UPB_TABVALUE_PTR_INIT(&fields[80]), &strentries[113]},
  6691. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6692. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6693. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6694. {UPB_TABKEY_STR("\023", "\000", "\000", "\000", "java_multiple_files"), UPB_TABVALUE_PTR_INIT(&fields[33]), &strentries[117]},
  6695. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[99]), NULL},
  6696. {UPB_TABKEY_STR("\025", "\000", "\000", "\000", "java_generic_services"), UPB_TABVALUE_PTR_INIT(&fields[32]), &strentries[118]},
  6697. {UPB_TABKEY_STR("\035", "\000", "\000", "\000", "java_generate_equals_and_hash"), UPB_TABVALUE_PTR_INIT(&fields[31]), NULL},
  6698. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "php_class_prefix"), UPB_TABVALUE_PTR_INIT(&fields[79]), NULL},
  6699. {UPB_TABKEY_STR("\037", "\000", "\000", "\000", "javanano_use_deprecated_package"), UPB_TABVALUE_PTR_INIT(&fields[37]), &strentries[123]},
  6700. {UPB_TABKEY_STR("\023", "\000", "\000", "\000", "py_generic_services"), UPB_TABVALUE_PTR_INIT(&fields[83]), NULL},
  6701. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "optimize_for"), UPB_TABVALUE_PTR_INIT(&fields[67]), NULL},
  6702. {UPB_TABKEY_STR("\026", "\000", "\000", "\000", "java_string_check_utf8"), UPB_TABVALUE_PTR_INIT(&fields[36]), NULL},
  6703. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[12]), &strentries[119]},
  6704. {UPB_TABKEY_STR("\021", "\000", "\000", "\000", "objc_class_prefix"), UPB_TABVALUE_PTR_INIT(&fields[64]), NULL},
  6705. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "cc_enable_arenas"), UPB_TABVALUE_PTR_INIT(&fields[2]), NULL},
  6706. {UPB_TABKEY_STR("\027", "\000", "\000", "\000", "message_set_wire_format"), UPB_TABVALUE_PTR_INIT(&fields[46]), &strentries[128]},
  6707. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6708. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6709. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6710. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[97]), NULL},
  6711. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[11]), NULL},
  6712. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "map_entry"), UPB_TABVALUE_PTR_INIT(&fields[45]), NULL},
  6713. {UPB_TABKEY_STR("\037", "\000", "\000", "\000", "no_standard_descriptor_accessor"), UPB_TABVALUE_PTR_INIT(&fields[61]), NULL},
  6714. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6715. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "client_streaming"), UPB_TABVALUE_PTR_INIT(&fields[4]), NULL},
  6716. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "server_streaming"), UPB_TABVALUE_PTR_INIT(&fields[86]), NULL},
  6717. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[55]), NULL},
  6718. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "input_type"), UPB_TABVALUE_PTR_INIT(&fields[29]), NULL},
  6719. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6720. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "output_type"), UPB_TABVALUE_PTR_INIT(&fields[75]), NULL},
  6721. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[71]), NULL},
  6722. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[100]), NULL},
  6723. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[10]), NULL},
  6724. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6725. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6726. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6727. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6728. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6729. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[54]), NULL},
  6730. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6731. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[72]), &strentries[150]},
  6732. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "method"), UPB_TABVALUE_PTR_INIT(&fields[48]), NULL},
  6733. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[53]), &strentries[149]},
  6734. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[98]), NULL},
  6735. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[15]), NULL},
  6736. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6737. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6738. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6739. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6740. {UPB_TABKEY_STR("\010", "\000", "\000", "\000", "location"), UPB_TABVALUE_PTR_INIT(&fields[44]), NULL},
  6741. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6742. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6743. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6744. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6745. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "span"), UPB_TABVALUE_PTR_INIT(&fields[89]), &strentries[167]},
  6746. {UPB_TABKEY_STR("\031", "\000", "\000", "\000", "leading_detached_comments"), UPB_TABVALUE_PTR_INIT(&fields[43]), &strentries[165]},
  6747. {UPB_TABKEY_STR("\021", "\000", "\000", "\000", "trailing_comments"), UPB_TABVALUE_PTR_INIT(&fields[94]), NULL},
  6748. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "leading_comments"), UPB_TABVALUE_PTR_INIT(&fields[42]), &strentries[164]},
  6749. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "path"), UPB_TABVALUE_PTR_INIT(&fields[78]), NULL},
  6750. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "double_value"), UPB_TABVALUE_PTR_INIT(&fields[16]), NULL},
  6751. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6752. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6753. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[49]), NULL},
  6754. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6755. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6756. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6757. {UPB_TABKEY_STR("\022", "\000", "\000", "\000", "negative_int_value"), UPB_TABVALUE_PTR_INIT(&fields[59]), NULL},
  6758. {UPB_TABKEY_STR("\017", "\000", "\000", "\000", "aggregate_value"), UPB_TABVALUE_PTR_INIT(&fields[0]), NULL},
  6759. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6760. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6761. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6762. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6763. {UPB_TABKEY_STR("\022", "\000", "\000", "\000", "positive_int_value"), UPB_TABVALUE_PTR_INIT(&fields[81]), NULL},
  6764. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "identifier_value"), UPB_TABVALUE_PTR_INIT(&fields[28]), NULL},
  6765. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "string_value"), UPB_TABVALUE_PTR_INIT(&fields[92]), &strentries[182]},
  6766. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6767. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6768. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "is_extension"), UPB_TABVALUE_PTR_INIT(&fields[30]), NULL},
  6769. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "name_part"), UPB_TABVALUE_PTR_INIT(&fields[58]), NULL},
  6770. {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "LABEL_REQUIRED"), UPB_TABVALUE_INT_INIT(2), &strentries[190]},
  6771. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6772. {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "LABEL_REPEATED"), UPB_TABVALUE_INT_INIT(3), NULL},
  6773. {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "LABEL_OPTIONAL"), UPB_TABVALUE_INT_INIT(1), NULL},
  6774. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "TYPE_FIXED64"), UPB_TABVALUE_INT_INIT(6), NULL},
  6775. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6776. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6777. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6778. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6779. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_STRING"), UPB_TABVALUE_INT_INIT(9), NULL},
  6780. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_FLOAT"), UPB_TABVALUE_INT_INIT(2), &strentries[221]},
  6781. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_DOUBLE"), UPB_TABVALUE_INT_INIT(1), NULL},
  6782. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6783. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_INT32"), UPB_TABVALUE_INT_INIT(5), NULL},
  6784. {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "TYPE_SFIXED32"), UPB_TABVALUE_INT_INIT(15), NULL},
  6785. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "TYPE_FIXED32"), UPB_TABVALUE_INT_INIT(7), NULL},
  6786. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6787. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "TYPE_MESSAGE"), UPB_TABVALUE_INT_INIT(11), &strentries[222]},
  6788. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6789. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6790. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_INT64"), UPB_TABVALUE_INT_INIT(3), &strentries[219]},
  6791. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6792. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6793. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6794. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6795. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "TYPE_ENUM"), UPB_TABVALUE_INT_INIT(14), NULL},
  6796. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_UINT32"), UPB_TABVALUE_INT_INIT(13), NULL},
  6797. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6798. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_UINT64"), UPB_TABVALUE_INT_INIT(4), &strentries[218]},
  6799. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6800. {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "TYPE_SFIXED64"), UPB_TABVALUE_INT_INIT(16), NULL},
  6801. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_BYTES"), UPB_TABVALUE_INT_INIT(12), NULL},
  6802. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_SINT64"), UPB_TABVALUE_INT_INIT(18), NULL},
  6803. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "TYPE_BOOL"), UPB_TABVALUE_INT_INIT(8), NULL},
  6804. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_GROUP"), UPB_TABVALUE_INT_INIT(10), NULL},
  6805. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_SINT32"), UPB_TABVALUE_INT_INIT(17), NULL},
  6806. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6807. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "CORD"), UPB_TABVALUE_INT_INIT(1), NULL},
  6808. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "STRING"), UPB_TABVALUE_INT_INIT(0), &strentries[225]},
  6809. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "STRING_PIECE"), UPB_TABVALUE_INT_INIT(2), NULL},
  6810. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6811. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "JS_NORMAL"), UPB_TABVALUE_INT_INIT(0), NULL},
  6812. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "JS_NUMBER"), UPB_TABVALUE_INT_INIT(2), NULL},
  6813. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "JS_STRING"), UPB_TABVALUE_INT_INIT(1), NULL},
  6814. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "CODE_SIZE"), UPB_TABVALUE_INT_INIT(2), NULL},
  6815. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "SPEED"), UPB_TABVALUE_INT_INIT(1), &strentries[235]},
  6816. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6817. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "LITE_RUNTIME"), UPB_TABVALUE_INT_INIT(3), NULL},
  6818. };
  6819. static const upb_tabent intentries[18] = {
  6820. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6821. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[103]), NULL},
  6822. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6823. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[102]), NULL},
  6824. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6825. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[101]), NULL},
  6826. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6827. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[99]), NULL},
  6828. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6829. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[97]), NULL},
  6830. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6831. {UPB_TABKEY_NUM(33), UPB_TABVALUE_PTR_INIT(&fields[10]), NULL},
  6832. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6833. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[100]), NULL},
  6834. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6835. {UPB_TABKEY_NUM(33), UPB_TABVALUE_PTR_INIT(&fields[15]), NULL},
  6836. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  6837. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[98]), NULL},
  6838. };
  6839. static const upb_tabval arrays[187] = {
  6840. UPB_TABVALUE_EMPTY_INIT,
  6841. UPB_TABVALUE_PTR_INIT(&fields[57]),
  6842. UPB_TABVALUE_PTR_INIT(&fields[25]),
  6843. UPB_TABVALUE_PTR_INIT(&fields[60]),
  6844. UPB_TABVALUE_PTR_INIT(&fields[20]),
  6845. UPB_TABVALUE_PTR_INIT(&fields[24]),
  6846. UPB_TABVALUE_PTR_INIT(&fields[22]),
  6847. UPB_TABVALUE_PTR_INIT(&fields[68]),
  6848. UPB_TABVALUE_PTR_INIT(&fields[65]),
  6849. UPB_TABVALUE_PTR_INIT(&fields[85]),
  6850. UPB_TABVALUE_PTR_INIT(&fields[84]),
  6851. UPB_TABVALUE_EMPTY_INIT,
  6852. UPB_TABVALUE_PTR_INIT(&fields[91]),
  6853. UPB_TABVALUE_PTR_INIT(&fields[18]),
  6854. UPB_TABVALUE_EMPTY_INIT,
  6855. UPB_TABVALUE_PTR_INIT(&fields[90]),
  6856. UPB_TABVALUE_PTR_INIT(&fields[17]),
  6857. UPB_TABVALUE_EMPTY_INIT,
  6858. UPB_TABVALUE_PTR_INIT(&fields[52]),
  6859. UPB_TABVALUE_PTR_INIT(&fields[104]),
  6860. UPB_TABVALUE_PTR_INIT(&fields[73]),
  6861. UPB_TABVALUE_EMPTY_INIT,
  6862. UPB_TABVALUE_EMPTY_INIT,
  6863. UPB_TABVALUE_PTR_INIT(&fields[1]),
  6864. UPB_TABVALUE_PTR_INIT(&fields[14]),
  6865. UPB_TABVALUE_EMPTY_INIT,
  6866. UPB_TABVALUE_PTR_INIT(&fields[50]),
  6867. UPB_TABVALUE_PTR_INIT(&fields[63]),
  6868. UPB_TABVALUE_PTR_INIT(&fields[74]),
  6869. UPB_TABVALUE_EMPTY_INIT,
  6870. UPB_TABVALUE_PTR_INIT(&fields[13]),
  6871. UPB_TABVALUE_EMPTY_INIT,
  6872. UPB_TABVALUE_PTR_INIT(&fields[56]),
  6873. UPB_TABVALUE_PTR_INIT(&fields[21]),
  6874. UPB_TABVALUE_PTR_INIT(&fields[62]),
  6875. UPB_TABVALUE_PTR_INIT(&fields[40]),
  6876. UPB_TABVALUE_PTR_INIT(&fields[95]),
  6877. UPB_TABVALUE_PTR_INIT(&fields[96]),
  6878. UPB_TABVALUE_PTR_INIT(&fields[7]),
  6879. UPB_TABVALUE_PTR_INIT(&fields[70]),
  6880. UPB_TABVALUE_PTR_INIT(&fields[66]),
  6881. UPB_TABVALUE_PTR_INIT(&fields[38]),
  6882. UPB_TABVALUE_EMPTY_INIT,
  6883. UPB_TABVALUE_PTR_INIT(&fields[6]),
  6884. UPB_TABVALUE_PTR_INIT(&fields[77]),
  6885. UPB_TABVALUE_PTR_INIT(&fields[9]),
  6886. UPB_TABVALUE_EMPTY_INIT,
  6887. UPB_TABVALUE_PTR_INIT(&fields[41]),
  6888. UPB_TABVALUE_PTR_INIT(&fields[39]),
  6889. UPB_TABVALUE_EMPTY_INIT,
  6890. UPB_TABVALUE_EMPTY_INIT,
  6891. UPB_TABVALUE_EMPTY_INIT,
  6892. UPB_TABVALUE_PTR_INIT(&fields[105]),
  6893. UPB_TABVALUE_EMPTY_INIT,
  6894. UPB_TABVALUE_PTR_INIT(&fields[51]),
  6895. UPB_TABVALUE_PTR_INIT(&fields[76]),
  6896. UPB_TABVALUE_PTR_INIT(&fields[8]),
  6897. UPB_TABVALUE_PTR_INIT(&fields[47]),
  6898. UPB_TABVALUE_PTR_INIT(&fields[19]),
  6899. UPB_TABVALUE_PTR_INIT(&fields[87]),
  6900. UPB_TABVALUE_PTR_INIT(&fields[23]),
  6901. UPB_TABVALUE_PTR_INIT(&fields[69]),
  6902. UPB_TABVALUE_PTR_INIT(&fields[88]),
  6903. UPB_TABVALUE_PTR_INIT(&fields[82]),
  6904. UPB_TABVALUE_PTR_INIT(&fields[106]),
  6905. UPB_TABVALUE_PTR_INIT(&fields[93]),
  6906. UPB_TABVALUE_EMPTY_INIT,
  6907. UPB_TABVALUE_PTR_INIT(&fields[26]),
  6908. UPB_TABVALUE_EMPTY_INIT,
  6909. UPB_TABVALUE_PTR_INIT(&fields[35]),
  6910. UPB_TABVALUE_EMPTY_INIT,
  6911. UPB_TABVALUE_EMPTY_INIT,
  6912. UPB_TABVALUE_EMPTY_INIT,
  6913. UPB_TABVALUE_EMPTY_INIT,
  6914. UPB_TABVALUE_EMPTY_INIT,
  6915. UPB_TABVALUE_EMPTY_INIT,
  6916. UPB_TABVALUE_PTR_INIT(&fields[34]),
  6917. UPB_TABVALUE_PTR_INIT(&fields[67]),
  6918. UPB_TABVALUE_PTR_INIT(&fields[33]),
  6919. UPB_TABVALUE_PTR_INIT(&fields[27]),
  6920. UPB_TABVALUE_EMPTY_INIT,
  6921. UPB_TABVALUE_EMPTY_INIT,
  6922. UPB_TABVALUE_EMPTY_INIT,
  6923. UPB_TABVALUE_EMPTY_INIT,
  6924. UPB_TABVALUE_PTR_INIT(&fields[3]),
  6925. UPB_TABVALUE_PTR_INIT(&fields[32]),
  6926. UPB_TABVALUE_PTR_INIT(&fields[83]),
  6927. UPB_TABVALUE_EMPTY_INIT,
  6928. UPB_TABVALUE_PTR_INIT(&fields[31]),
  6929. UPB_TABVALUE_EMPTY_INIT,
  6930. UPB_TABVALUE_EMPTY_INIT,
  6931. UPB_TABVALUE_PTR_INIT(&fields[12]),
  6932. UPB_TABVALUE_EMPTY_INIT,
  6933. UPB_TABVALUE_EMPTY_INIT,
  6934. UPB_TABVALUE_EMPTY_INIT,
  6935. UPB_TABVALUE_PTR_INIT(&fields[36]),
  6936. UPB_TABVALUE_EMPTY_INIT,
  6937. UPB_TABVALUE_EMPTY_INIT,
  6938. UPB_TABVALUE_EMPTY_INIT,
  6939. UPB_TABVALUE_PTR_INIT(&fields[2]),
  6940. UPB_TABVALUE_EMPTY_INIT,
  6941. UPB_TABVALUE_EMPTY_INIT,
  6942. UPB_TABVALUE_EMPTY_INIT,
  6943. UPB_TABVALUE_EMPTY_INIT,
  6944. UPB_TABVALUE_PTR_INIT(&fields[64]),
  6945. UPB_TABVALUE_PTR_INIT(&fields[5]),
  6946. UPB_TABVALUE_PTR_INIT(&fields[37]),
  6947. UPB_TABVALUE_EMPTY_INIT,
  6948. UPB_TABVALUE_PTR_INIT(&fields[79]),
  6949. UPB_TABVALUE_PTR_INIT(&fields[80]),
  6950. UPB_TABVALUE_EMPTY_INIT,
  6951. UPB_TABVALUE_PTR_INIT(&fields[46]),
  6952. UPB_TABVALUE_PTR_INIT(&fields[61]),
  6953. UPB_TABVALUE_PTR_INIT(&fields[11]),
  6954. UPB_TABVALUE_EMPTY_INIT,
  6955. UPB_TABVALUE_EMPTY_INIT,
  6956. UPB_TABVALUE_EMPTY_INIT,
  6957. UPB_TABVALUE_PTR_INIT(&fields[45]),
  6958. UPB_TABVALUE_EMPTY_INIT,
  6959. UPB_TABVALUE_PTR_INIT(&fields[55]),
  6960. UPB_TABVALUE_PTR_INIT(&fields[29]),
  6961. UPB_TABVALUE_PTR_INIT(&fields[75]),
  6962. UPB_TABVALUE_PTR_INIT(&fields[71]),
  6963. UPB_TABVALUE_PTR_INIT(&fields[4]),
  6964. UPB_TABVALUE_PTR_INIT(&fields[86]),
  6965. UPB_TABVALUE_EMPTY_INIT,
  6966. UPB_TABVALUE_EMPTY_INIT,
  6967. UPB_TABVALUE_PTR_INIT(&fields[54]),
  6968. UPB_TABVALUE_EMPTY_INIT,
  6969. UPB_TABVALUE_PTR_INIT(&fields[53]),
  6970. UPB_TABVALUE_PTR_INIT(&fields[48]),
  6971. UPB_TABVALUE_PTR_INIT(&fields[72]),
  6972. UPB_TABVALUE_EMPTY_INIT,
  6973. UPB_TABVALUE_EMPTY_INIT,
  6974. UPB_TABVALUE_PTR_INIT(&fields[44]),
  6975. UPB_TABVALUE_EMPTY_INIT,
  6976. UPB_TABVALUE_PTR_INIT(&fields[78]),
  6977. UPB_TABVALUE_PTR_INIT(&fields[89]),
  6978. UPB_TABVALUE_PTR_INIT(&fields[42]),
  6979. UPB_TABVALUE_PTR_INIT(&fields[94]),
  6980. UPB_TABVALUE_EMPTY_INIT,
  6981. UPB_TABVALUE_PTR_INIT(&fields[43]),
  6982. UPB_TABVALUE_EMPTY_INIT,
  6983. UPB_TABVALUE_EMPTY_INIT,
  6984. UPB_TABVALUE_PTR_INIT(&fields[49]),
  6985. UPB_TABVALUE_PTR_INIT(&fields[28]),
  6986. UPB_TABVALUE_PTR_INIT(&fields[81]),
  6987. UPB_TABVALUE_PTR_INIT(&fields[59]),
  6988. UPB_TABVALUE_PTR_INIT(&fields[16]),
  6989. UPB_TABVALUE_PTR_INIT(&fields[92]),
  6990. UPB_TABVALUE_PTR_INIT(&fields[0]),
  6991. UPB_TABVALUE_EMPTY_INIT,
  6992. UPB_TABVALUE_PTR_INIT(&fields[58]),
  6993. UPB_TABVALUE_PTR_INIT(&fields[30]),
  6994. UPB_TABVALUE_EMPTY_INIT,
  6995. UPB_TABVALUE_PTR_INIT("LABEL_OPTIONAL"),
  6996. UPB_TABVALUE_PTR_INIT("LABEL_REQUIRED"),
  6997. UPB_TABVALUE_PTR_INIT("LABEL_REPEATED"),
  6998. UPB_TABVALUE_EMPTY_INIT,
  6999. UPB_TABVALUE_PTR_INIT("TYPE_DOUBLE"),
  7000. UPB_TABVALUE_PTR_INIT("TYPE_FLOAT"),
  7001. UPB_TABVALUE_PTR_INIT("TYPE_INT64"),
  7002. UPB_TABVALUE_PTR_INIT("TYPE_UINT64"),
  7003. UPB_TABVALUE_PTR_INIT("TYPE_INT32"),
  7004. UPB_TABVALUE_PTR_INIT("TYPE_FIXED64"),
  7005. UPB_TABVALUE_PTR_INIT("TYPE_FIXED32"),
  7006. UPB_TABVALUE_PTR_INIT("TYPE_BOOL"),
  7007. UPB_TABVALUE_PTR_INIT("TYPE_STRING"),
  7008. UPB_TABVALUE_PTR_INIT("TYPE_GROUP"),
  7009. UPB_TABVALUE_PTR_INIT("TYPE_MESSAGE"),
  7010. UPB_TABVALUE_PTR_INIT("TYPE_BYTES"),
  7011. UPB_TABVALUE_PTR_INIT("TYPE_UINT32"),
  7012. UPB_TABVALUE_PTR_INIT("TYPE_ENUM"),
  7013. UPB_TABVALUE_PTR_INIT("TYPE_SFIXED32"),
  7014. UPB_TABVALUE_PTR_INIT("TYPE_SFIXED64"),
  7015. UPB_TABVALUE_PTR_INIT("TYPE_SINT32"),
  7016. UPB_TABVALUE_PTR_INIT("TYPE_SINT64"),
  7017. UPB_TABVALUE_PTR_INIT("STRING"),
  7018. UPB_TABVALUE_PTR_INIT("CORD"),
  7019. UPB_TABVALUE_PTR_INIT("STRING_PIECE"),
  7020. UPB_TABVALUE_PTR_INIT("JS_NORMAL"),
  7021. UPB_TABVALUE_PTR_INIT("JS_STRING"),
  7022. UPB_TABVALUE_PTR_INIT("JS_NUMBER"),
  7023. UPB_TABVALUE_EMPTY_INIT,
  7024. UPB_TABVALUE_PTR_INIT("SPEED"),
  7025. UPB_TABVALUE_PTR_INIT("CODE_SIZE"),
  7026. UPB_TABVALUE_PTR_INIT("LITE_RUNTIME"),
  7027. };
  7028. #ifdef UPB_DEBUG_REFS
  7029. static upb_inttable reftables[268] = {
  7030. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7031. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7032. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7033. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7034. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7035. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7036. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7037. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7038. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7039. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7040. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7041. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7042. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7043. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7044. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7045. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7046. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7047. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7048. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7049. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7050. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7051. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7052. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7053. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7054. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7055. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7056. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7057. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7058. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7059. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7060. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7061. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7062. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7063. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7064. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7065. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7066. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7067. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7068. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7069. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7070. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7071. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7072. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7073. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7074. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7075. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7076. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7077. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7078. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7079. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7080. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7081. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7082. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7083. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7084. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7085. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7086. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7087. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7088. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7089. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7090. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7091. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7092. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7093. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7094. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7095. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7096. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7097. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7098. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7099. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7100. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7101. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7102. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7103. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7104. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7105. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7106. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7107. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7108. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7109. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7110. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7111. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7112. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7113. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7114. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7115. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7116. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7117. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7118. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7119. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7120. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7121. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7122. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7123. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7124. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7125. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7126. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7127. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7128. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7129. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7130. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7131. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7132. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7133. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7134. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7135. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7136. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7137. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7138. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7139. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7140. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7141. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7142. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7143. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7144. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7145. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7146. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7147. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7148. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7149. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7150. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7151. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7152. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7153. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7154. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7155. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7156. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7157. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7158. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7159. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7160. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7161. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7162. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7163. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7164. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7165. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7166. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7167. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7168. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7169. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7170. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7171. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7172. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7173. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7174. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7175. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7176. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7177. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7178. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7179. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7180. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7181. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7182. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7183. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7184. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7185. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7186. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7187. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7188. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7189. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7190. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7191. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7192. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7193. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7194. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7195. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7196. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7197. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7198. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7199. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7200. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7201. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7202. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7203. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7204. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7205. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7206. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7207. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7208. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7209. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7210. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7211. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7212. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7213. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7214. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7215. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7216. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7217. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7218. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7219. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7220. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7221. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7222. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7223. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7224. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7225. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7226. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7227. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7228. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7229. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7230. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7231. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7232. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7233. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7234. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7235. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7236. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7237. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7238. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7239. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7240. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7241. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7242. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7243. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7244. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7245. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7246. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7247. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7248. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7249. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7250. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7251. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7252. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7253. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7254. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7255. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7256. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7257. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7258. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7259. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7260. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7261. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7262. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7263. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7264. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7265. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7266. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7267. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7268. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7269. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7270. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7271. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7272. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7273. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7274. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7275. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7276. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7277. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7278. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7279. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7280. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7281. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7282. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7283. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7284. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7285. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7286. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7287. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7288. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7289. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7290. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7291. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7292. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7293. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7294. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7295. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7296. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7297. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  7298. };
  7299. #endif
  7300. static const upb_msgdef *refm(const upb_msgdef *m, const void *owner) {
  7301. upb_msgdef_ref(m, owner);
  7302. return m;
  7303. }
  7304. static const upb_enumdef *refe(const upb_enumdef *e, const void *owner) {
  7305. upb_enumdef_ref(e, owner);
  7306. return e;
  7307. }
  7308. /* Public API. */
  7309. const upb_msgdef *upbdefs_google_protobuf_DescriptorProto_get(const void *owner) { return refm(&msgs[0], owner); }
  7310. const upb_msgdef *upbdefs_google_protobuf_DescriptorProto_ExtensionRange_get(const void *owner) { return refm(&msgs[1], owner); }
  7311. const upb_msgdef *upbdefs_google_protobuf_DescriptorProto_ReservedRange_get(const void *owner) { return refm(&msgs[2], owner); }
  7312. const upb_msgdef *upbdefs_google_protobuf_EnumDescriptorProto_get(const void *owner) { return refm(&msgs[3], owner); }
  7313. const upb_msgdef *upbdefs_google_protobuf_EnumOptions_get(const void *owner) { return refm(&msgs[4], owner); }
  7314. const upb_msgdef *upbdefs_google_protobuf_EnumValueDescriptorProto_get(const void *owner) { return refm(&msgs[5], owner); }
  7315. const upb_msgdef *upbdefs_google_protobuf_EnumValueOptions_get(const void *owner) { return refm(&msgs[6], owner); }
  7316. const upb_msgdef *upbdefs_google_protobuf_FieldDescriptorProto_get(const void *owner) { return refm(&msgs[7], owner); }
  7317. const upb_msgdef *upbdefs_google_protobuf_FieldOptions_get(const void *owner) { return refm(&msgs[8], owner); }
  7318. const upb_msgdef *upbdefs_google_protobuf_FileDescriptorProto_get(const void *owner) { return refm(&msgs[9], owner); }
  7319. const upb_msgdef *upbdefs_google_protobuf_FileDescriptorSet_get(const void *owner) { return refm(&msgs[10], owner); }
  7320. const upb_msgdef *upbdefs_google_protobuf_FileOptions_get(const void *owner) { return refm(&msgs[11], owner); }
  7321. const upb_msgdef *upbdefs_google_protobuf_MessageOptions_get(const void *owner) { return refm(&msgs[12], owner); }
  7322. const upb_msgdef *upbdefs_google_protobuf_MethodDescriptorProto_get(const void *owner) { return refm(&msgs[13], owner); }
  7323. const upb_msgdef *upbdefs_google_protobuf_MethodOptions_get(const void *owner) { return refm(&msgs[14], owner); }
  7324. const upb_msgdef *upbdefs_google_protobuf_OneofDescriptorProto_get(const void *owner) { return refm(&msgs[15], owner); }
  7325. const upb_msgdef *upbdefs_google_protobuf_ServiceDescriptorProto_get(const void *owner) { return refm(&msgs[16], owner); }
  7326. const upb_msgdef *upbdefs_google_protobuf_ServiceOptions_get(const void *owner) { return refm(&msgs[17], owner); }
  7327. const upb_msgdef *upbdefs_google_protobuf_SourceCodeInfo_get(const void *owner) { return refm(&msgs[18], owner); }
  7328. const upb_msgdef *upbdefs_google_protobuf_SourceCodeInfo_Location_get(const void *owner) { return refm(&msgs[19], owner); }
  7329. const upb_msgdef *upbdefs_google_protobuf_UninterpretedOption_get(const void *owner) { return refm(&msgs[20], owner); }
  7330. const upb_msgdef *upbdefs_google_protobuf_UninterpretedOption_NamePart_get(const void *owner) { return refm(&msgs[21], owner); }
  7331. const upb_enumdef *upbdefs_google_protobuf_FieldDescriptorProto_Label_get(const void *owner) { return refe(&enums[0], owner); }
  7332. const upb_enumdef *upbdefs_google_protobuf_FieldDescriptorProto_Type_get(const void *owner) { return refe(&enums[1], owner); }
  7333. const upb_enumdef *upbdefs_google_protobuf_FieldOptions_CType_get(const void *owner) { return refe(&enums[2], owner); }
  7334. const upb_enumdef *upbdefs_google_protobuf_FieldOptions_JSType_get(const void *owner) { return refe(&enums[3], owner); }
  7335. const upb_enumdef *upbdefs_google_protobuf_FileOptions_OptimizeMode_get(const void *owner) { return refe(&enums[4], owner); }
  7336. /*
  7337. ** XXX: The routines in this file that consume a string do not currently
  7338. ** support having the string span buffers. In the future, as upb_sink and
  7339. ** its buffering/sharing functionality evolve there should be an easy and
  7340. ** idiomatic way of correctly handling this case. For now, we accept this
  7341. ** limitation since we currently only parse descriptors from single strings.
  7342. */
  7343. #include <errno.h>
  7344. #include <stdlib.h>
  7345. #include <string.h>
  7346. /* Compares a NULL-terminated string with a non-NULL-terminated string. */
  7347. static bool upb_streq(const char *str, const char *buf, size_t n) {
  7348. return strlen(str) == n && memcmp(str, buf, n) == 0;
  7349. }
  7350. /* We keep a stack of all the messages scopes we are currently in, as well as
  7351. * the top-level file scope. This is necessary to correctly qualify the
  7352. * definitions that are contained inside. "name" tracks the name of the
  7353. * message or package (a bare name -- not qualified by any enclosing scopes). */
  7354. typedef struct {
  7355. char *name;
  7356. /* Index of the first def that is under this scope. For msgdefs, the
  7357. * msgdef itself is at start-1. */
  7358. int start;
  7359. uint32_t oneof_start;
  7360. uint32_t oneof_index;
  7361. } upb_descreader_frame;
  7362. /* The maximum number of nested declarations that are allowed, ie.
  7363. * message Foo {
  7364. * message Bar {
  7365. * message Baz {
  7366. * }
  7367. * }
  7368. * }
  7369. *
  7370. * This is a resource limit that affects how big our runtime stack can grow.
  7371. * TODO: make this a runtime-settable property of the Reader instance. */
  7372. #define UPB_MAX_MESSAGE_NESTING 64
  7373. struct upb_descreader {
  7374. upb_sink sink;
  7375. upb_inttable files;
  7376. upb_strtable files_by_name;
  7377. upb_filedef *file; /* The last file in files. */
  7378. upb_descreader_frame stack[UPB_MAX_MESSAGE_NESTING];
  7379. int stack_len;
  7380. upb_inttable oneofs;
  7381. uint32_t number;
  7382. char *name;
  7383. bool saw_number;
  7384. bool saw_name;
  7385. char *default_string;
  7386. upb_fielddef *f;
  7387. };
  7388. static char *upb_gstrndup(const char *buf, size_t n) {
  7389. char *ret = upb_gmalloc(n + 1);
  7390. if (!ret) return NULL;
  7391. memcpy(ret, buf, n);
  7392. ret[n] = '\0';
  7393. return ret;
  7394. }
  7395. /* Returns a newly allocated string that joins input strings together, for
  7396. * example:
  7397. * join("Foo.Bar", "Baz") -> "Foo.Bar.Baz"
  7398. * join("", "Baz") -> "Baz"
  7399. * Caller owns a ref on the returned string. */
  7400. static char *upb_join(const char *base, const char *name) {
  7401. if (!base || strlen(base) == 0) {
  7402. return upb_gstrdup(name);
  7403. } else {
  7404. char *ret = upb_gmalloc(strlen(base) + strlen(name) + 2);
  7405. if (!ret) {
  7406. return NULL;
  7407. }
  7408. ret[0] = '\0';
  7409. strcat(ret, base);
  7410. strcat(ret, ".");
  7411. strcat(ret, name);
  7412. return ret;
  7413. }
  7414. }
  7415. /* Qualify the defname for all defs starting with offset "start" with "str". */
  7416. static bool upb_descreader_qualify(upb_filedef *f, char *str, int32_t start) {
  7417. size_t i;
  7418. for (i = start; i < upb_filedef_defcount(f); i++) {
  7419. upb_def *def = upb_filedef_mutabledef(f, i);
  7420. char *name = upb_join(str, upb_def_fullname(def));
  7421. if (!name) {
  7422. /* Need better logic here; at this point we've qualified some names but
  7423. * not others. */
  7424. return false;
  7425. }
  7426. upb_def_setfullname(def, name, NULL);
  7427. upb_gfree(name);
  7428. }
  7429. return true;
  7430. }
  7431. /* upb_descreader ************************************************************/
  7432. static upb_msgdef *upb_descreader_top(upb_descreader *r) {
  7433. int index;
  7434. UPB_ASSERT(r->stack_len > 1);
  7435. index = r->stack[r->stack_len-1].start - 1;
  7436. UPB_ASSERT(index >= 0);
  7437. return upb_downcast_msgdef_mutable(upb_filedef_mutabledef(r->file, index));
  7438. }
  7439. static upb_def *upb_descreader_last(upb_descreader *r) {
  7440. return upb_filedef_mutabledef(r->file, upb_filedef_defcount(r->file) - 1);
  7441. }
  7442. /* Start/end handlers for FileDescriptorProto and DescriptorProto (the two
  7443. * entities that have names and can contain sub-definitions. */
  7444. void upb_descreader_startcontainer(upb_descreader *r) {
  7445. upb_descreader_frame *f = &r->stack[r->stack_len++];
  7446. f->start = upb_filedef_defcount(r->file);
  7447. f->oneof_start = upb_inttable_count(&r->oneofs);
  7448. f->oneof_index = 0;
  7449. f->name = NULL;
  7450. }
  7451. bool upb_descreader_endcontainer(upb_descreader *r) {
  7452. upb_descreader_frame *f = &r->stack[r->stack_len - 1];
  7453. while (upb_inttable_count(&r->oneofs) > f->oneof_start) {
  7454. upb_oneofdef *o = upb_value_getptr(upb_inttable_pop(&r->oneofs));
  7455. bool ok = upb_msgdef_addoneof(upb_descreader_top(r), o, &r->oneofs, NULL);
  7456. UPB_ASSERT(ok);
  7457. }
  7458. if (!upb_descreader_qualify(r->file, f->name, f->start)) {
  7459. return false;
  7460. }
  7461. upb_gfree(f->name);
  7462. f->name = NULL;
  7463. r->stack_len--;
  7464. return true;
  7465. }
  7466. void upb_descreader_setscopename(upb_descreader *r, char *str) {
  7467. upb_descreader_frame *f = &r->stack[r->stack_len-1];
  7468. upb_gfree(f->name);
  7469. f->name = str;
  7470. }
  7471. static upb_oneofdef *upb_descreader_getoneof(upb_descreader *r,
  7472. uint32_t index) {
  7473. bool found;
  7474. upb_value val;
  7475. upb_descreader_frame *f = &r->stack[r->stack_len-1];
  7476. /* DescriptorProto messages can be nested, so we will see the nested messages
  7477. * between when we see the FieldDescriptorProto and the OneofDescriptorProto.
  7478. * We need to preserve the oneofs in between these two things. */
  7479. index += f->oneof_start;
  7480. while (upb_inttable_count(&r->oneofs) <= index) {
  7481. upb_inttable_push(&r->oneofs, upb_value_ptr(upb_oneofdef_new(&r->oneofs)));
  7482. }
  7483. found = upb_inttable_lookup(&r->oneofs, index, &val);
  7484. UPB_ASSERT(found);
  7485. return upb_value_getptr(val);
  7486. }
  7487. /** Handlers for google.protobuf.FileDescriptorSet. ***************************/
  7488. static void *fileset_startfile(void *closure, const void *hd) {
  7489. upb_descreader *r = closure;
  7490. UPB_UNUSED(hd);
  7491. r->file = upb_filedef_new(&r->files);
  7492. upb_inttable_push(&r->files, upb_value_ptr(r->file));
  7493. return r;
  7494. }
  7495. /** Handlers for google.protobuf.FileDescriptorProto. *************************/
  7496. static bool file_start(void *closure, const void *hd) {
  7497. upb_descreader *r = closure;
  7498. UPB_UNUSED(hd);
  7499. upb_descreader_startcontainer(r);
  7500. return true;
  7501. }
  7502. static bool file_end(void *closure, const void *hd, upb_status *status) {
  7503. upb_descreader *r = closure;
  7504. UPB_UNUSED(hd);
  7505. UPB_UNUSED(status);
  7506. return upb_descreader_endcontainer(r);
  7507. }
  7508. static size_t file_onname(void *closure, const void *hd, const char *buf,
  7509. size_t n, const upb_bufhandle *handle) {
  7510. upb_descreader *r = closure;
  7511. char *name;
  7512. bool ok;
  7513. UPB_UNUSED(hd);
  7514. UPB_UNUSED(handle);
  7515. name = upb_gstrndup(buf, n);
  7516. upb_strtable_insert(&r->files_by_name, name, upb_value_ptr(r->file));
  7517. /* XXX: see comment at the top of the file. */
  7518. ok = upb_filedef_setname(r->file, name, NULL);
  7519. upb_gfree(name);
  7520. UPB_ASSERT(ok);
  7521. return n;
  7522. }
  7523. static size_t file_onpackage(void *closure, const void *hd, const char *buf,
  7524. size_t n, const upb_bufhandle *handle) {
  7525. upb_descreader *r = closure;
  7526. char *package;
  7527. bool ok;
  7528. UPB_UNUSED(hd);
  7529. UPB_UNUSED(handle);
  7530. package = upb_gstrndup(buf, n);
  7531. /* XXX: see comment at the top of the file. */
  7532. upb_descreader_setscopename(r, package);
  7533. ok = upb_filedef_setpackage(r->file, package, NULL);
  7534. UPB_ASSERT(ok);
  7535. return n;
  7536. }
  7537. static void *file_startphpnamespace(void *closure, const void *hd,
  7538. size_t size_hint) {
  7539. upb_descreader *r = closure;
  7540. bool ok;
  7541. UPB_UNUSED(hd);
  7542. UPB_UNUSED(size_hint);
  7543. ok = upb_filedef_setphpnamespace(r->file, "", NULL);
  7544. UPB_ASSERT(ok);
  7545. return closure;
  7546. }
  7547. static size_t file_onphpnamespace(void *closure, const void *hd,
  7548. const char *buf, size_t n,
  7549. const upb_bufhandle *handle) {
  7550. upb_descreader *r = closure;
  7551. char *php_namespace;
  7552. bool ok;
  7553. UPB_UNUSED(hd);
  7554. UPB_UNUSED(handle);
  7555. php_namespace = upb_gstrndup(buf, n);
  7556. ok = upb_filedef_setphpnamespace(r->file, php_namespace, NULL);
  7557. upb_gfree(php_namespace);
  7558. UPB_ASSERT(ok);
  7559. return n;
  7560. }
  7561. static size_t file_onphpprefix(void *closure, const void *hd, const char *buf,
  7562. size_t n, const upb_bufhandle *handle) {
  7563. upb_descreader *r = closure;
  7564. char *prefix;
  7565. bool ok;
  7566. UPB_UNUSED(hd);
  7567. UPB_UNUSED(handle);
  7568. prefix = upb_gstrndup(buf, n);
  7569. ok = upb_filedef_setphpprefix(r->file, prefix, NULL);
  7570. upb_gfree(prefix);
  7571. UPB_ASSERT(ok);
  7572. return n;
  7573. }
  7574. static size_t file_onsyntax(void *closure, const void *hd, const char *buf,
  7575. size_t n, const upb_bufhandle *handle) {
  7576. upb_descreader *r = closure;
  7577. bool ok;
  7578. UPB_UNUSED(hd);
  7579. UPB_UNUSED(handle);
  7580. /* XXX: see comment at the top of the file. */
  7581. if (upb_streq("proto2", buf, n)) {
  7582. ok = upb_filedef_setsyntax(r->file, UPB_SYNTAX_PROTO2, NULL);
  7583. } else if (upb_streq("proto3", buf, n)) {
  7584. ok = upb_filedef_setsyntax(r->file, UPB_SYNTAX_PROTO3, NULL);
  7585. } else {
  7586. ok = false;
  7587. }
  7588. UPB_ASSERT(ok);
  7589. return n;
  7590. }
  7591. static void *file_startmsg(void *closure, const void *hd) {
  7592. upb_descreader *r = closure;
  7593. upb_msgdef *m = upb_msgdef_new(&m);
  7594. bool ok = upb_filedef_addmsg(r->file, m, &m, NULL);
  7595. UPB_UNUSED(hd);
  7596. UPB_ASSERT(ok);
  7597. return r;
  7598. }
  7599. static void *file_startenum(void *closure, const void *hd) {
  7600. upb_descreader *r = closure;
  7601. upb_enumdef *e = upb_enumdef_new(&e);
  7602. bool ok = upb_filedef_addenum(r->file, e, &e, NULL);
  7603. UPB_UNUSED(hd);
  7604. UPB_ASSERT(ok);
  7605. return r;
  7606. }
  7607. static void *file_startext(void *closure, const void *hd) {
  7608. upb_descreader *r = closure;
  7609. r->f = upb_fielddef_new(r);
  7610. UPB_UNUSED(hd);
  7611. return r;
  7612. }
  7613. static bool file_endext(void *closure, const void *hd) {
  7614. /* The current symtab code can't handle extensions, so we just discard
  7615. * them for now. */
  7616. upb_descreader *r = closure;
  7617. upb_fielddef_unref(r->f, r);
  7618. UPB_UNUSED(hd);
  7619. r->f = NULL;
  7620. return true;
  7621. }
  7622. static size_t file_ondep(void *closure, const void *hd, const char *buf,
  7623. size_t n, const upb_bufhandle *handle) {
  7624. upb_descreader *r = closure;
  7625. upb_value val;
  7626. if (upb_strtable_lookup2(&r->files_by_name, buf, n, &val)) {
  7627. upb_filedef_adddep(r->file, upb_value_getptr(val));
  7628. }
  7629. UPB_UNUSED(hd);
  7630. UPB_UNUSED(handle);
  7631. return n;
  7632. }
  7633. /** Handlers for google.protobuf.EnumValueDescriptorProto. *********************/
  7634. static bool enumval_startmsg(void *closure, const void *hd) {
  7635. upb_descreader *r = closure;
  7636. UPB_UNUSED(hd);
  7637. r->saw_number = false;
  7638. r->saw_name = false;
  7639. return true;
  7640. }
  7641. static size_t enumval_onname(void *closure, const void *hd, const char *buf,
  7642. size_t n, const upb_bufhandle *handle) {
  7643. upb_descreader *r = closure;
  7644. UPB_UNUSED(hd);
  7645. UPB_UNUSED(handle);
  7646. /* XXX: see comment at the top of the file. */
  7647. upb_gfree(r->name);
  7648. r->name = upb_gstrndup(buf, n);
  7649. r->saw_name = true;
  7650. return n;
  7651. }
  7652. static bool enumval_onnumber(void *closure, const void *hd, int32_t val) {
  7653. upb_descreader *r = closure;
  7654. UPB_UNUSED(hd);
  7655. r->number = val;
  7656. r->saw_number = true;
  7657. return true;
  7658. }
  7659. static bool enumval_endmsg(void *closure, const void *hd, upb_status *status) {
  7660. upb_descreader *r = closure;
  7661. upb_enumdef *e;
  7662. UPB_UNUSED(hd);
  7663. if(!r->saw_number || !r->saw_name) {
  7664. upb_status_seterrmsg(status, "Enum value missing name or number.");
  7665. return false;
  7666. }
  7667. e = upb_downcast_enumdef_mutable(upb_descreader_last(r));
  7668. upb_enumdef_addval(e, r->name, r->number, status);
  7669. upb_gfree(r->name);
  7670. r->name = NULL;
  7671. return true;
  7672. }
  7673. /** Handlers for google.protobuf.EnumDescriptorProto. *************************/
  7674. static bool enum_endmsg(void *closure, const void *hd, upb_status *status) {
  7675. upb_descreader *r = closure;
  7676. upb_enumdef *e;
  7677. UPB_UNUSED(hd);
  7678. e = upb_downcast_enumdef_mutable(upb_descreader_last(r));
  7679. if (upb_def_fullname(upb_descreader_last(r)) == NULL) {
  7680. upb_status_seterrmsg(status, "Enum had no name.");
  7681. return false;
  7682. }
  7683. if (upb_enumdef_numvals(e) == 0) {
  7684. upb_status_seterrmsg(status, "Enum had no values.");
  7685. return false;
  7686. }
  7687. return true;
  7688. }
  7689. static size_t enum_onname(void *closure, const void *hd, const char *buf,
  7690. size_t n, const upb_bufhandle *handle) {
  7691. upb_descreader *r = closure;
  7692. char *fullname = upb_gstrndup(buf, n);
  7693. UPB_UNUSED(hd);
  7694. UPB_UNUSED(handle);
  7695. /* XXX: see comment at the top of the file. */
  7696. upb_def_setfullname(upb_descreader_last(r), fullname, NULL);
  7697. upb_gfree(fullname);
  7698. return n;
  7699. }
  7700. /** Handlers for google.protobuf.FieldDescriptorProto *************************/
  7701. static bool field_startmsg(void *closure, const void *hd) {
  7702. upb_descreader *r = closure;
  7703. UPB_UNUSED(hd);
  7704. UPB_ASSERT(r->f);
  7705. upb_gfree(r->default_string);
  7706. r->default_string = NULL;
  7707. /* fielddefs default to packed, but descriptors default to non-packed. */
  7708. upb_fielddef_setpacked(r->f, false);
  7709. return true;
  7710. }
  7711. /* Converts the default value in string "str" into "d". Passes a ref on str.
  7712. * Returns true on success. */
  7713. static bool parse_default(char *str, upb_fielddef *f) {
  7714. bool success = true;
  7715. char *end;
  7716. switch (upb_fielddef_type(f)) {
  7717. case UPB_TYPE_INT32: {
  7718. long val = strtol(str, &end, 0);
  7719. if (val > INT32_MAX || val < INT32_MIN || errno == ERANGE || *end)
  7720. success = false;
  7721. else
  7722. upb_fielddef_setdefaultint32(f, val);
  7723. break;
  7724. }
  7725. case UPB_TYPE_INT64: {
  7726. /* XXX: Need to write our own strtoll, since it's not available in c89. */
  7727. long long val = strtol(str, &end, 0);
  7728. if (val > INT64_MAX || val < INT64_MIN || errno == ERANGE || *end)
  7729. success = false;
  7730. else
  7731. upb_fielddef_setdefaultint64(f, val);
  7732. break;
  7733. }
  7734. case UPB_TYPE_UINT32: {
  7735. unsigned long val = strtoul(str, &end, 0);
  7736. if (val > UINT32_MAX || errno == ERANGE || *end)
  7737. success = false;
  7738. else
  7739. upb_fielddef_setdefaultuint32(f, val);
  7740. break;
  7741. }
  7742. case UPB_TYPE_UINT64: {
  7743. /* XXX: Need to write our own strtoull, since it's not available in c89. */
  7744. unsigned long long val = strtoul(str, &end, 0);
  7745. if (val > UINT64_MAX || errno == ERANGE || *end)
  7746. success = false;
  7747. else
  7748. upb_fielddef_setdefaultuint64(f, val);
  7749. break;
  7750. }
  7751. case UPB_TYPE_DOUBLE: {
  7752. double val = strtod(str, &end);
  7753. if (errno == ERANGE || *end)
  7754. success = false;
  7755. else
  7756. upb_fielddef_setdefaultdouble(f, val);
  7757. break;
  7758. }
  7759. case UPB_TYPE_FLOAT: {
  7760. /* XXX: Need to write our own strtof, since it's not available in c89. */
  7761. float val = strtod(str, &end);
  7762. if (errno == ERANGE || *end)
  7763. success = false;
  7764. else
  7765. upb_fielddef_setdefaultfloat(f, val);
  7766. break;
  7767. }
  7768. case UPB_TYPE_BOOL: {
  7769. if (strcmp(str, "false") == 0)
  7770. upb_fielddef_setdefaultbool(f, false);
  7771. else if (strcmp(str, "true") == 0)
  7772. upb_fielddef_setdefaultbool(f, true);
  7773. else
  7774. success = false;
  7775. break;
  7776. }
  7777. default: abort();
  7778. }
  7779. return success;
  7780. }
  7781. static bool field_endmsg(void *closure, const void *hd, upb_status *status) {
  7782. upb_descreader *r = closure;
  7783. upb_fielddef *f = r->f;
  7784. UPB_UNUSED(hd);
  7785. /* TODO: verify that all required fields were present. */
  7786. UPB_ASSERT(upb_fielddef_number(f) != 0);
  7787. UPB_ASSERT(upb_fielddef_name(f) != NULL);
  7788. UPB_ASSERT((upb_fielddef_subdefname(f) != NULL) == upb_fielddef_hassubdef(f));
  7789. if (r->default_string) {
  7790. if (upb_fielddef_issubmsg(f)) {
  7791. upb_status_seterrmsg(status, "Submessages cannot have defaults.");
  7792. return false;
  7793. }
  7794. if (upb_fielddef_isstring(f) || upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  7795. upb_fielddef_setdefaultcstr(f, r->default_string, NULL);
  7796. } else {
  7797. if (r->default_string && !parse_default(r->default_string, f)) {
  7798. /* We don't worry too much about giving a great error message since the
  7799. * compiler should have ensured this was correct. */
  7800. upb_status_seterrmsg(status, "Error converting default value.");
  7801. return false;
  7802. }
  7803. }
  7804. }
  7805. return true;
  7806. }
  7807. static bool field_onlazy(void *closure, const void *hd, bool val) {
  7808. upb_descreader *r = closure;
  7809. UPB_UNUSED(hd);
  7810. upb_fielddef_setlazy(r->f, val);
  7811. return true;
  7812. }
  7813. static bool field_onpacked(void *closure, const void *hd, bool val) {
  7814. upb_descreader *r = closure;
  7815. UPB_UNUSED(hd);
  7816. upb_fielddef_setpacked(r->f, val);
  7817. return true;
  7818. }
  7819. static bool field_ontype(void *closure, const void *hd, int32_t val) {
  7820. upb_descreader *r = closure;
  7821. UPB_UNUSED(hd);
  7822. upb_fielddef_setdescriptortype(r->f, val);
  7823. return true;
  7824. }
  7825. static bool field_onlabel(void *closure, const void *hd, int32_t val) {
  7826. upb_descreader *r = closure;
  7827. UPB_UNUSED(hd);
  7828. upb_fielddef_setlabel(r->f, val);
  7829. return true;
  7830. }
  7831. static bool field_onnumber(void *closure, const void *hd, int32_t val) {
  7832. upb_descreader *r = closure;
  7833. bool ok;
  7834. UPB_UNUSED(hd);
  7835. ok = upb_fielddef_setnumber(r->f, val, NULL);
  7836. UPB_ASSERT(ok);
  7837. return true;
  7838. }
  7839. static size_t field_onname(void *closure, const void *hd, const char *buf,
  7840. size_t n, const upb_bufhandle *handle) {
  7841. upb_descreader *r = closure;
  7842. char *name = upb_gstrndup(buf, n);
  7843. UPB_UNUSED(hd);
  7844. UPB_UNUSED(handle);
  7845. /* XXX: see comment at the top of the file. */
  7846. upb_fielddef_setname(r->f, name, NULL);
  7847. upb_gfree(name);
  7848. return n;
  7849. }
  7850. static size_t field_ontypename(void *closure, const void *hd, const char *buf,
  7851. size_t n, const upb_bufhandle *handle) {
  7852. upb_descreader *r = closure;
  7853. char *name = upb_gstrndup(buf, n);
  7854. UPB_UNUSED(hd);
  7855. UPB_UNUSED(handle);
  7856. /* XXX: see comment at the top of the file. */
  7857. upb_fielddef_setsubdefname(r->f, name, NULL);
  7858. upb_gfree(name);
  7859. return n;
  7860. }
  7861. static size_t field_onextendee(void *closure, const void *hd, const char *buf,
  7862. size_t n, const upb_bufhandle *handle) {
  7863. upb_descreader *r = closure;
  7864. char *name = upb_gstrndup(buf, n);
  7865. UPB_UNUSED(hd);
  7866. UPB_UNUSED(handle);
  7867. /* XXX: see comment at the top of the file. */
  7868. upb_fielddef_setcontainingtypename(r->f, name, NULL);
  7869. upb_gfree(name);
  7870. return n;
  7871. }
  7872. static size_t field_ondefaultval(void *closure, const void *hd, const char *buf,
  7873. size_t n, const upb_bufhandle *handle) {
  7874. upb_descreader *r = closure;
  7875. UPB_UNUSED(hd);
  7876. UPB_UNUSED(handle);
  7877. /* Have to convert from string to the correct type, but we might not know the
  7878. * type yet, so we save it as a string until the end of the field.
  7879. * XXX: see comment at the top of the file. */
  7880. upb_gfree(r->default_string);
  7881. r->default_string = upb_gstrndup(buf, n);
  7882. return n;
  7883. }
  7884. static bool field_ononeofindex(void *closure, const void *hd, int32_t index) {
  7885. upb_descreader *r = closure;
  7886. upb_oneofdef *o = upb_descreader_getoneof(r, index);
  7887. bool ok = upb_oneofdef_addfield(o, r->f, &r->f, NULL);
  7888. UPB_UNUSED(hd);
  7889. UPB_ASSERT(ok);
  7890. return true;
  7891. }
  7892. /** Handlers for google.protobuf.OneofDescriptorProto. ************************/
  7893. static size_t oneof_name(void *closure, const void *hd, const char *buf,
  7894. size_t n, const upb_bufhandle *handle) {
  7895. upb_descreader *r = closure;
  7896. upb_descreader_frame *f = &r->stack[r->stack_len-1];
  7897. upb_oneofdef *o = upb_descreader_getoneof(r, f->oneof_index++);
  7898. char *name_null_terminated = upb_gstrndup(buf, n);
  7899. bool ok = upb_oneofdef_setname(o, name_null_terminated, NULL);
  7900. UPB_UNUSED(hd);
  7901. UPB_UNUSED(handle);
  7902. UPB_ASSERT(ok);
  7903. free(name_null_terminated);
  7904. return n;
  7905. }
  7906. /** Handlers for google.protobuf.DescriptorProto ******************************/
  7907. static bool msg_start(void *closure, const void *hd) {
  7908. upb_descreader *r = closure;
  7909. UPB_UNUSED(hd);
  7910. upb_descreader_startcontainer(r);
  7911. return true;
  7912. }
  7913. static bool msg_end(void *closure, const void *hd, upb_status *status) {
  7914. upb_descreader *r = closure;
  7915. upb_msgdef *m = upb_descreader_top(r);
  7916. UPB_UNUSED(hd);
  7917. if(!upb_def_fullname(upb_msgdef_upcast_mutable(m))) {
  7918. upb_status_seterrmsg(status, "Encountered message with no name.");
  7919. return false;
  7920. }
  7921. return upb_descreader_endcontainer(r);
  7922. }
  7923. static size_t msg_name(void *closure, const void *hd, const char *buf,
  7924. size_t n, const upb_bufhandle *handle) {
  7925. upb_descreader *r = closure;
  7926. upb_msgdef *m = upb_descreader_top(r);
  7927. /* XXX: see comment at the top of the file. */
  7928. char *name = upb_gstrndup(buf, n);
  7929. UPB_UNUSED(hd);
  7930. UPB_UNUSED(handle);
  7931. upb_def_setfullname(upb_msgdef_upcast_mutable(m), name, NULL);
  7932. upb_descreader_setscopename(r, name); /* Passes ownership of name. */
  7933. return n;
  7934. }
  7935. static void *msg_startmsg(void *closure, const void *hd) {
  7936. upb_descreader *r = closure;
  7937. upb_msgdef *m = upb_msgdef_new(&m);
  7938. bool ok = upb_filedef_addmsg(r->file, m, &m, NULL);
  7939. UPB_UNUSED(hd);
  7940. UPB_ASSERT(ok);
  7941. return r;
  7942. }
  7943. static void *msg_startext(void *closure, const void *hd) {
  7944. upb_descreader *r = closure;
  7945. r->f = upb_fielddef_new(r);
  7946. UPB_UNUSED(hd);
  7947. return r;
  7948. }
  7949. static bool msg_endext(void *closure, const void *hd) {
  7950. /* The current symtab code can't handle extensions, so we just discard
  7951. * them for now. */
  7952. upb_descreader *r = closure;
  7953. upb_fielddef_unref(r->f, r);
  7954. UPB_UNUSED(hd);
  7955. r->f = NULL;
  7956. return true;
  7957. }
  7958. static void *msg_startfield(void *closure, const void *hd) {
  7959. upb_descreader *r = closure;
  7960. r->f = upb_fielddef_new(&r->f);
  7961. /* We can't add the new field to the message until its name/number are
  7962. * filled in. */
  7963. UPB_UNUSED(hd);
  7964. return r;
  7965. }
  7966. static bool msg_endfield(void *closure, const void *hd) {
  7967. upb_descreader *r = closure;
  7968. upb_msgdef *m = upb_descreader_top(r);
  7969. bool ok;
  7970. UPB_UNUSED(hd);
  7971. /* Oneof fields are added to the msgdef through their oneof, so don't need to
  7972. * be added here. */
  7973. if (upb_fielddef_containingoneof(r->f) == NULL) {
  7974. ok = upb_msgdef_addfield(m, r->f, &r->f, NULL);
  7975. UPB_ASSERT(ok);
  7976. }
  7977. r->f = NULL;
  7978. return true;
  7979. }
  7980. static bool msg_onmapentry(void *closure, const void *hd, bool mapentry) {
  7981. upb_descreader *r = closure;
  7982. upb_msgdef *m = upb_descreader_top(r);
  7983. UPB_UNUSED(hd);
  7984. upb_msgdef_setmapentry(m, mapentry);
  7985. r->f = NULL;
  7986. return true;
  7987. }
  7988. /** Code to register handlers *************************************************/
  7989. #define F(msg, field) upbdefs_google_protobuf_ ## msg ## _f_ ## field(m)
  7990. static void reghandlers(const void *closure, upb_handlers *h) {
  7991. const upb_msgdef *m = upb_handlers_msgdef(h);
  7992. UPB_UNUSED(closure);
  7993. if (upbdefs_google_protobuf_FileDescriptorSet_is(m)) {
  7994. upb_handlers_setstartsubmsg(h, F(FileDescriptorSet, file),
  7995. &fileset_startfile, NULL);
  7996. } else if (upbdefs_google_protobuf_DescriptorProto_is(m)) {
  7997. upb_handlers_setstartmsg(h, &msg_start, NULL);
  7998. upb_handlers_setendmsg(h, &msg_end, NULL);
  7999. upb_handlers_setstring(h, F(DescriptorProto, name), &msg_name, NULL);
  8000. upb_handlers_setstartsubmsg(h, F(DescriptorProto, extension), &msg_startext,
  8001. NULL);
  8002. upb_handlers_setendsubmsg(h, F(DescriptorProto, extension), &msg_endext,
  8003. NULL);
  8004. upb_handlers_setstartsubmsg(h, F(DescriptorProto, nested_type),
  8005. &msg_startmsg, NULL);
  8006. upb_handlers_setstartsubmsg(h, F(DescriptorProto, field),
  8007. &msg_startfield, NULL);
  8008. upb_handlers_setendsubmsg(h, F(DescriptorProto, field),
  8009. &msg_endfield, NULL);
  8010. upb_handlers_setstartsubmsg(h, F(DescriptorProto, enum_type),
  8011. &file_startenum, NULL);
  8012. } else if (upbdefs_google_protobuf_FileDescriptorProto_is(m)) {
  8013. upb_handlers_setstartmsg(h, &file_start, NULL);
  8014. upb_handlers_setendmsg(h, &file_end, NULL);
  8015. upb_handlers_setstring(h, F(FileDescriptorProto, name), &file_onname,
  8016. NULL);
  8017. upb_handlers_setstring(h, F(FileDescriptorProto, package), &file_onpackage,
  8018. NULL);
  8019. upb_handlers_setstring(h, F(FileDescriptorProto, syntax), &file_onsyntax,
  8020. NULL);
  8021. upb_handlers_setstartsubmsg(h, F(FileDescriptorProto, message_type),
  8022. &file_startmsg, NULL);
  8023. upb_handlers_setstartsubmsg(h, F(FileDescriptorProto, enum_type),
  8024. &file_startenum, NULL);
  8025. upb_handlers_setstartsubmsg(h, F(FileDescriptorProto, extension),
  8026. &file_startext, NULL);
  8027. upb_handlers_setendsubmsg(h, F(FileDescriptorProto, extension),
  8028. &file_endext, NULL);
  8029. upb_handlers_setstring(h, F(FileDescriptorProto, dependency),
  8030. &file_ondep, NULL);
  8031. } else if (upbdefs_google_protobuf_EnumValueDescriptorProto_is(m)) {
  8032. upb_handlers_setstartmsg(h, &enumval_startmsg, NULL);
  8033. upb_handlers_setendmsg(h, &enumval_endmsg, NULL);
  8034. upb_handlers_setstring(h, F(EnumValueDescriptorProto, name), &enumval_onname, NULL);
  8035. upb_handlers_setint32(h, F(EnumValueDescriptorProto, number), &enumval_onnumber,
  8036. NULL);
  8037. } else if (upbdefs_google_protobuf_EnumDescriptorProto_is(m)) {
  8038. upb_handlers_setendmsg(h, &enum_endmsg, NULL);
  8039. upb_handlers_setstring(h, F(EnumDescriptorProto, name), &enum_onname, NULL);
  8040. } else if (upbdefs_google_protobuf_FieldDescriptorProto_is(m)) {
  8041. upb_handlers_setstartmsg(h, &field_startmsg, NULL);
  8042. upb_handlers_setendmsg(h, &field_endmsg, NULL);
  8043. upb_handlers_setint32(h, F(FieldDescriptorProto, type), &field_ontype,
  8044. NULL);
  8045. upb_handlers_setint32(h, F(FieldDescriptorProto, label), &field_onlabel,
  8046. NULL);
  8047. upb_handlers_setint32(h, F(FieldDescriptorProto, number), &field_onnumber,
  8048. NULL);
  8049. upb_handlers_setstring(h, F(FieldDescriptorProto, name), &field_onname,
  8050. NULL);
  8051. upb_handlers_setstring(h, F(FieldDescriptorProto, type_name),
  8052. &field_ontypename, NULL);
  8053. upb_handlers_setstring(h, F(FieldDescriptorProto, extendee),
  8054. &field_onextendee, NULL);
  8055. upb_handlers_setstring(h, F(FieldDescriptorProto, default_value),
  8056. &field_ondefaultval, NULL);
  8057. upb_handlers_setint32(h, F(FieldDescriptorProto, oneof_index),
  8058. &field_ononeofindex, NULL);
  8059. } else if (upbdefs_google_protobuf_OneofDescriptorProto_is(m)) {
  8060. upb_handlers_setstring(h, F(OneofDescriptorProto, name), &oneof_name, NULL);
  8061. } else if (upbdefs_google_protobuf_FieldOptions_is(m)) {
  8062. upb_handlers_setbool(h, F(FieldOptions, lazy), &field_onlazy, NULL);
  8063. upb_handlers_setbool(h, F(FieldOptions, packed), &field_onpacked, NULL);
  8064. } else if (upbdefs_google_protobuf_MessageOptions_is(m)) {
  8065. upb_handlers_setbool(h, F(MessageOptions, map_entry), &msg_onmapentry, NULL);
  8066. } else if (upbdefs_google_protobuf_FileOptions_is(m)) {
  8067. upb_handlers_setstring(h, F(FileOptions, php_class_prefix),
  8068. &file_onphpprefix, NULL);
  8069. upb_handlers_setstartstr(h, F(FileOptions, php_namespace),
  8070. &file_startphpnamespace, NULL);
  8071. upb_handlers_setstring(h, F(FileOptions, php_namespace),
  8072. &file_onphpnamespace, NULL);
  8073. }
  8074. UPB_ASSERT(upb_ok(upb_handlers_status(h)));
  8075. }
  8076. #undef F
  8077. void descreader_cleanup(void *_r) {
  8078. upb_descreader *r = _r;
  8079. size_t i;
  8080. for (i = 0; i < upb_descreader_filecount(r); i++) {
  8081. upb_filedef_unref(upb_descreader_file(r, i), &r->files);
  8082. }
  8083. upb_gfree(r->name);
  8084. upb_inttable_uninit(&r->files);
  8085. upb_strtable_uninit(&r->files_by_name);
  8086. upb_inttable_uninit(&r->oneofs);
  8087. upb_gfree(r->default_string);
  8088. while (r->stack_len > 0) {
  8089. upb_descreader_frame *f = &r->stack[--r->stack_len];
  8090. upb_gfree(f->name);
  8091. }
  8092. }
  8093. /* Public API ****************************************************************/
  8094. upb_descreader *upb_descreader_create(upb_env *e, const upb_handlers *h) {
  8095. upb_descreader *r = upb_env_malloc(e, sizeof(upb_descreader));
  8096. if (!r || !upb_env_addcleanup(e, descreader_cleanup, r)) {
  8097. return NULL;
  8098. }
  8099. upb_inttable_init(&r->files, UPB_CTYPE_PTR);
  8100. upb_strtable_init(&r->files_by_name, UPB_CTYPE_PTR);
  8101. upb_inttable_init(&r->oneofs, UPB_CTYPE_PTR);
  8102. upb_sink_reset(upb_descreader_input(r), h, r);
  8103. r->stack_len = 0;
  8104. r->name = NULL;
  8105. r->default_string = NULL;
  8106. return r;
  8107. }
  8108. size_t upb_descreader_filecount(const upb_descreader *r) {
  8109. return upb_inttable_count(&r->files);
  8110. }
  8111. upb_filedef *upb_descreader_file(const upb_descreader *r, size_t i) {
  8112. upb_value v;
  8113. if (upb_inttable_lookup(&r->files, i, &v)) {
  8114. return upb_value_getptr(v);
  8115. } else {
  8116. return NULL;
  8117. }
  8118. }
  8119. upb_sink *upb_descreader_input(upb_descreader *r) {
  8120. return &r->sink;
  8121. }
  8122. const upb_handlers *upb_descreader_newhandlers(const void *owner) {
  8123. const upb_msgdef *m = upbdefs_google_protobuf_FileDescriptorSet_get(&m);
  8124. const upb_handlers *h = upb_handlers_newfrozen(m, owner, reghandlers, NULL);
  8125. upb_msgdef_unref(m, &m);
  8126. return h;
  8127. }
  8128. /*
  8129. ** protobuf decoder bytecode compiler
  8130. **
  8131. ** Code to compile a upb::Handlers into bytecode for decoding a protobuf
  8132. ** according to that specific schema and destination handlers.
  8133. **
  8134. ** Compiling to bytecode is always the first step. If we are using the
  8135. ** interpreted decoder we leave it as bytecode and interpret that. If we are
  8136. ** using a JIT decoder we use a code generator to turn the bytecode into native
  8137. ** code, LLVM IR, etc.
  8138. **
  8139. ** Bytecode definition is in decoder.int.h.
  8140. */
  8141. #include <stdarg.h>
  8142. #ifdef UPB_DUMP_BYTECODE
  8143. #include <stdio.h>
  8144. #endif
  8145. #define MAXLABEL 5
  8146. #define EMPTYLABEL -1
  8147. /* mgroup *********************************************************************/
  8148. static void freegroup(upb_refcounted *r) {
  8149. mgroup *g = (mgroup*)r;
  8150. upb_inttable_uninit(&g->methods);
  8151. #ifdef UPB_USE_JIT_X64
  8152. upb_pbdecoder_freejit(g);
  8153. #endif
  8154. upb_gfree(g->bytecode);
  8155. upb_gfree(g);
  8156. }
  8157. static void visitgroup(const upb_refcounted *r, upb_refcounted_visit *visit,
  8158. void *closure) {
  8159. const mgroup *g = (const mgroup*)r;
  8160. upb_inttable_iter i;
  8161. upb_inttable_begin(&i, &g->methods);
  8162. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  8163. upb_pbdecodermethod *method = upb_value_getptr(upb_inttable_iter_value(&i));
  8164. visit(r, upb_pbdecodermethod_upcast(method), closure);
  8165. }
  8166. }
  8167. mgroup *newgroup(const void *owner) {
  8168. mgroup *g = upb_gmalloc(sizeof(*g));
  8169. static const struct upb_refcounted_vtbl vtbl = {visitgroup, freegroup};
  8170. upb_refcounted_init(mgroup_upcast_mutable(g), &vtbl, owner);
  8171. upb_inttable_init(&g->methods, UPB_CTYPE_PTR);
  8172. g->bytecode = NULL;
  8173. g->bytecode_end = NULL;
  8174. return g;
  8175. }
  8176. /* upb_pbdecodermethod ********************************************************/
  8177. static void freemethod(upb_refcounted *r) {
  8178. upb_pbdecodermethod *method = (upb_pbdecodermethod*)r;
  8179. if (method->dest_handlers_) {
  8180. upb_handlers_unref(method->dest_handlers_, method);
  8181. }
  8182. upb_inttable_uninit(&method->dispatch);
  8183. upb_gfree(method);
  8184. }
  8185. static void visitmethod(const upb_refcounted *r, upb_refcounted_visit *visit,
  8186. void *closure) {
  8187. const upb_pbdecodermethod *m = (const upb_pbdecodermethod*)r;
  8188. visit(r, m->group, closure);
  8189. }
  8190. static upb_pbdecodermethod *newmethod(const upb_handlers *dest_handlers,
  8191. mgroup *group) {
  8192. static const struct upb_refcounted_vtbl vtbl = {visitmethod, freemethod};
  8193. upb_pbdecodermethod *ret = upb_gmalloc(sizeof(*ret));
  8194. upb_refcounted_init(upb_pbdecodermethod_upcast_mutable(ret), &vtbl, &ret);
  8195. upb_byteshandler_init(&ret->input_handler_);
  8196. /* The method references the group and vice-versa, in a circular reference. */
  8197. upb_ref2(ret, group);
  8198. upb_ref2(group, ret);
  8199. upb_inttable_insertptr(&group->methods, dest_handlers, upb_value_ptr(ret));
  8200. upb_pbdecodermethod_unref(ret, &ret);
  8201. ret->group = mgroup_upcast_mutable(group);
  8202. ret->dest_handlers_ = dest_handlers;
  8203. ret->is_native_ = false; /* If we JIT, it will update this later. */
  8204. upb_inttable_init(&ret->dispatch, UPB_CTYPE_UINT64);
  8205. if (ret->dest_handlers_) {
  8206. upb_handlers_ref(ret->dest_handlers_, ret);
  8207. }
  8208. return ret;
  8209. }
  8210. const upb_handlers *upb_pbdecodermethod_desthandlers(
  8211. const upb_pbdecodermethod *m) {
  8212. return m->dest_handlers_;
  8213. }
  8214. const upb_byteshandler *upb_pbdecodermethod_inputhandler(
  8215. const upb_pbdecodermethod *m) {
  8216. return &m->input_handler_;
  8217. }
  8218. bool upb_pbdecodermethod_isnative(const upb_pbdecodermethod *m) {
  8219. return m->is_native_;
  8220. }
  8221. const upb_pbdecodermethod *upb_pbdecodermethod_new(
  8222. const upb_pbdecodermethodopts *opts, const void *owner) {
  8223. const upb_pbdecodermethod *ret;
  8224. upb_pbcodecache cache;
  8225. upb_pbcodecache_init(&cache);
  8226. ret = upb_pbcodecache_getdecodermethod(&cache, opts);
  8227. upb_pbdecodermethod_ref(ret, owner);
  8228. upb_pbcodecache_uninit(&cache);
  8229. return ret;
  8230. }
  8231. /* bytecode compiler **********************************************************/
  8232. /* Data used only at compilation time. */
  8233. typedef struct {
  8234. mgroup *group;
  8235. uint32_t *pc;
  8236. int fwd_labels[MAXLABEL];
  8237. int back_labels[MAXLABEL];
  8238. /* For fields marked "lazy", parse them lazily or eagerly? */
  8239. bool lazy;
  8240. } compiler;
  8241. static compiler *newcompiler(mgroup *group, bool lazy) {
  8242. compiler *ret = upb_gmalloc(sizeof(*ret));
  8243. int i;
  8244. ret->group = group;
  8245. ret->lazy = lazy;
  8246. for (i = 0; i < MAXLABEL; i++) {
  8247. ret->fwd_labels[i] = EMPTYLABEL;
  8248. ret->back_labels[i] = EMPTYLABEL;
  8249. }
  8250. return ret;
  8251. }
  8252. static void freecompiler(compiler *c) {
  8253. upb_gfree(c);
  8254. }
  8255. const size_t ptr_words = sizeof(void*) / sizeof(uint32_t);
  8256. /* How many words an instruction is. */
  8257. static int instruction_len(uint32_t instr) {
  8258. switch (getop(instr)) {
  8259. case OP_SETDISPATCH: return 1 + ptr_words;
  8260. case OP_TAGN: return 3;
  8261. case OP_SETBIGGROUPNUM: return 2;
  8262. default: return 1;
  8263. }
  8264. }
  8265. bool op_has_longofs(int32_t instruction) {
  8266. switch (getop(instruction)) {
  8267. case OP_CALL:
  8268. case OP_BRANCH:
  8269. case OP_CHECKDELIM:
  8270. return true;
  8271. /* The "tag" instructions only have 8 bytes available for the jump target,
  8272. * but that is ok because these opcodes only require short jumps. */
  8273. case OP_TAG1:
  8274. case OP_TAG2:
  8275. case OP_TAGN:
  8276. return false;
  8277. default:
  8278. UPB_ASSERT(false);
  8279. return false;
  8280. }
  8281. }
  8282. static int32_t getofs(uint32_t instruction) {
  8283. if (op_has_longofs(instruction)) {
  8284. return (int32_t)instruction >> 8;
  8285. } else {
  8286. return (int8_t)(instruction >> 8);
  8287. }
  8288. }
  8289. static void setofs(uint32_t *instruction, int32_t ofs) {
  8290. if (op_has_longofs(*instruction)) {
  8291. *instruction = getop(*instruction) | ofs << 8;
  8292. } else {
  8293. *instruction = (*instruction & ~0xff00) | ((ofs & 0xff) << 8);
  8294. }
  8295. UPB_ASSERT(getofs(*instruction) == ofs); /* Would fail in cases of overflow. */
  8296. }
  8297. static uint32_t pcofs(compiler *c) { return c->pc - c->group->bytecode; }
  8298. /* Defines a local label at the current PC location. All previous forward
  8299. * references are updated to point to this location. The location is noted
  8300. * for any future backward references. */
  8301. static void label(compiler *c, unsigned int label) {
  8302. int val;
  8303. uint32_t *codep;
  8304. UPB_ASSERT(label < MAXLABEL);
  8305. val = c->fwd_labels[label];
  8306. codep = (val == EMPTYLABEL) ? NULL : c->group->bytecode + val;
  8307. while (codep) {
  8308. int ofs = getofs(*codep);
  8309. setofs(codep, c->pc - codep - instruction_len(*codep));
  8310. codep = ofs ? codep + ofs : NULL;
  8311. }
  8312. c->fwd_labels[label] = EMPTYLABEL;
  8313. c->back_labels[label] = pcofs(c);
  8314. }
  8315. /* Creates a reference to a numbered label; either a forward reference
  8316. * (positive arg) or backward reference (negative arg). For forward references
  8317. * the value returned now is actually a "next" pointer into a linked list of all
  8318. * instructions that use this label and will be patched later when the label is
  8319. * defined with label().
  8320. *
  8321. * The returned value is the offset that should be written into the instruction.
  8322. */
  8323. static int32_t labelref(compiler *c, int label) {
  8324. UPB_ASSERT(label < MAXLABEL);
  8325. if (label == LABEL_DISPATCH) {
  8326. /* No resolving required. */
  8327. return 0;
  8328. } else if (label < 0) {
  8329. /* Backward local label. Relative to the next instruction. */
  8330. uint32_t from = (c->pc + 1) - c->group->bytecode;
  8331. return c->back_labels[-label] - from;
  8332. } else {
  8333. /* Forward local label: prepend to (possibly-empty) linked list. */
  8334. int *lptr = &c->fwd_labels[label];
  8335. int32_t ret = (*lptr == EMPTYLABEL) ? 0 : *lptr - pcofs(c);
  8336. *lptr = pcofs(c);
  8337. return ret;
  8338. }
  8339. }
  8340. static void put32(compiler *c, uint32_t v) {
  8341. mgroup *g = c->group;
  8342. if (c->pc == g->bytecode_end) {
  8343. int ofs = pcofs(c);
  8344. size_t oldsize = g->bytecode_end - g->bytecode;
  8345. size_t newsize = UPB_MAX(oldsize * 2, 64);
  8346. /* TODO(haberman): handle OOM. */
  8347. g->bytecode = upb_grealloc(g->bytecode, oldsize * sizeof(uint32_t),
  8348. newsize * sizeof(uint32_t));
  8349. g->bytecode_end = g->bytecode + newsize;
  8350. c->pc = g->bytecode + ofs;
  8351. }
  8352. *c->pc++ = v;
  8353. }
  8354. static void putop(compiler *c, int op, ...) {
  8355. va_list ap;
  8356. va_start(ap, op);
  8357. switch (op) {
  8358. case OP_SETDISPATCH: {
  8359. uintptr_t ptr = (uintptr_t)va_arg(ap, void*);
  8360. put32(c, OP_SETDISPATCH);
  8361. put32(c, ptr);
  8362. if (sizeof(uintptr_t) > sizeof(uint32_t))
  8363. put32(c, (uint64_t)ptr >> 32);
  8364. break;
  8365. }
  8366. case OP_STARTMSG:
  8367. case OP_ENDMSG:
  8368. case OP_PUSHLENDELIM:
  8369. case OP_POP:
  8370. case OP_SETDELIM:
  8371. case OP_HALT:
  8372. case OP_RET:
  8373. case OP_DISPATCH:
  8374. put32(c, op);
  8375. break;
  8376. case OP_PARSE_DOUBLE:
  8377. case OP_PARSE_FLOAT:
  8378. case OP_PARSE_INT64:
  8379. case OP_PARSE_UINT64:
  8380. case OP_PARSE_INT32:
  8381. case OP_PARSE_FIXED64:
  8382. case OP_PARSE_FIXED32:
  8383. case OP_PARSE_BOOL:
  8384. case OP_PARSE_UINT32:
  8385. case OP_PARSE_SFIXED32:
  8386. case OP_PARSE_SFIXED64:
  8387. case OP_PARSE_SINT32:
  8388. case OP_PARSE_SINT64:
  8389. case OP_STARTSEQ:
  8390. case OP_ENDSEQ:
  8391. case OP_STARTSUBMSG:
  8392. case OP_ENDSUBMSG:
  8393. case OP_STARTSTR:
  8394. case OP_STRING:
  8395. case OP_ENDSTR:
  8396. case OP_PUSHTAGDELIM:
  8397. put32(c, op | va_arg(ap, upb_selector_t) << 8);
  8398. break;
  8399. case OP_SETBIGGROUPNUM:
  8400. put32(c, op);
  8401. put32(c, va_arg(ap, int));
  8402. break;
  8403. case OP_CALL: {
  8404. const upb_pbdecodermethod *method = va_arg(ap, upb_pbdecodermethod *);
  8405. put32(c, op | (method->code_base.ofs - (pcofs(c) + 1)) << 8);
  8406. break;
  8407. }
  8408. case OP_CHECKDELIM:
  8409. case OP_BRANCH: {
  8410. uint32_t instruction = op;
  8411. int label = va_arg(ap, int);
  8412. setofs(&instruction, labelref(c, label));
  8413. put32(c, instruction);
  8414. break;
  8415. }
  8416. case OP_TAG1:
  8417. case OP_TAG2: {
  8418. int label = va_arg(ap, int);
  8419. uint64_t tag = va_arg(ap, uint64_t);
  8420. uint32_t instruction = op | (tag << 16);
  8421. UPB_ASSERT(tag <= 0xffff);
  8422. setofs(&instruction, labelref(c, label));
  8423. put32(c, instruction);
  8424. break;
  8425. }
  8426. case OP_TAGN: {
  8427. int label = va_arg(ap, int);
  8428. uint64_t tag = va_arg(ap, uint64_t);
  8429. uint32_t instruction = op | (upb_value_size(tag) << 16);
  8430. setofs(&instruction, labelref(c, label));
  8431. put32(c, instruction);
  8432. put32(c, tag);
  8433. put32(c, tag >> 32);
  8434. break;
  8435. }
  8436. }
  8437. va_end(ap);
  8438. }
  8439. #if defined(UPB_USE_JIT_X64) || defined(UPB_DUMP_BYTECODE)
  8440. const char *upb_pbdecoder_getopname(unsigned int op) {
  8441. #define QUOTE(x) #x
  8442. #define EXPAND_AND_QUOTE(x) QUOTE(x)
  8443. #define OPNAME(x) OP_##x
  8444. #define OP(x) case OPNAME(x): return EXPAND_AND_QUOTE(OPNAME(x));
  8445. #define T(x) OP(PARSE_##x)
  8446. /* Keep in sync with list in decoder.int.h. */
  8447. switch ((opcode)op) {
  8448. T(DOUBLE) T(FLOAT) T(INT64) T(UINT64) T(INT32) T(FIXED64) T(FIXED32)
  8449. T(BOOL) T(UINT32) T(SFIXED32) T(SFIXED64) T(SINT32) T(SINT64)
  8450. OP(STARTMSG) OP(ENDMSG) OP(STARTSEQ) OP(ENDSEQ) OP(STARTSUBMSG)
  8451. OP(ENDSUBMSG) OP(STARTSTR) OP(STRING) OP(ENDSTR) OP(CALL) OP(RET)
  8452. OP(PUSHLENDELIM) OP(PUSHTAGDELIM) OP(SETDELIM) OP(CHECKDELIM)
  8453. OP(BRANCH) OP(TAG1) OP(TAG2) OP(TAGN) OP(SETDISPATCH) OP(POP)
  8454. OP(SETBIGGROUPNUM) OP(DISPATCH) OP(HALT)
  8455. }
  8456. return "<unknown op>";
  8457. #undef OP
  8458. #undef T
  8459. }
  8460. #endif
  8461. #ifdef UPB_DUMP_BYTECODE
  8462. static void dumpbc(uint32_t *p, uint32_t *end, FILE *f) {
  8463. uint32_t *begin = p;
  8464. while (p < end) {
  8465. fprintf(f, "%p %8tx", p, p - begin);
  8466. uint32_t instr = *p++;
  8467. uint8_t op = getop(instr);
  8468. fprintf(f, " %s", upb_pbdecoder_getopname(op));
  8469. switch ((opcode)op) {
  8470. case OP_SETDISPATCH: {
  8471. const upb_inttable *dispatch;
  8472. memcpy(&dispatch, p, sizeof(void*));
  8473. p += ptr_words;
  8474. const upb_pbdecodermethod *method =
  8475. (void *)((char *)dispatch -
  8476. offsetof(upb_pbdecodermethod, dispatch));
  8477. fprintf(f, " %s", upb_msgdef_fullname(
  8478. upb_handlers_msgdef(method->dest_handlers_)));
  8479. break;
  8480. }
  8481. case OP_DISPATCH:
  8482. case OP_STARTMSG:
  8483. case OP_ENDMSG:
  8484. case OP_PUSHLENDELIM:
  8485. case OP_POP:
  8486. case OP_SETDELIM:
  8487. case OP_HALT:
  8488. case OP_RET:
  8489. break;
  8490. case OP_PARSE_DOUBLE:
  8491. case OP_PARSE_FLOAT:
  8492. case OP_PARSE_INT64:
  8493. case OP_PARSE_UINT64:
  8494. case OP_PARSE_INT32:
  8495. case OP_PARSE_FIXED64:
  8496. case OP_PARSE_FIXED32:
  8497. case OP_PARSE_BOOL:
  8498. case OP_PARSE_UINT32:
  8499. case OP_PARSE_SFIXED32:
  8500. case OP_PARSE_SFIXED64:
  8501. case OP_PARSE_SINT32:
  8502. case OP_PARSE_SINT64:
  8503. case OP_STARTSEQ:
  8504. case OP_ENDSEQ:
  8505. case OP_STARTSUBMSG:
  8506. case OP_ENDSUBMSG:
  8507. case OP_STARTSTR:
  8508. case OP_STRING:
  8509. case OP_ENDSTR:
  8510. case OP_PUSHTAGDELIM:
  8511. fprintf(f, " %d", instr >> 8);
  8512. break;
  8513. case OP_SETBIGGROUPNUM:
  8514. fprintf(f, " %d", *p++);
  8515. break;
  8516. case OP_CHECKDELIM:
  8517. case OP_CALL:
  8518. case OP_BRANCH:
  8519. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  8520. break;
  8521. case OP_TAG1:
  8522. case OP_TAG2: {
  8523. fprintf(f, " tag:0x%x", instr >> 16);
  8524. if (getofs(instr)) {
  8525. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  8526. }
  8527. break;
  8528. }
  8529. case OP_TAGN: {
  8530. uint64_t tag = *p++;
  8531. tag |= (uint64_t)*p++ << 32;
  8532. fprintf(f, " tag:0x%llx", (long long)tag);
  8533. fprintf(f, " n:%d", instr >> 16);
  8534. if (getofs(instr)) {
  8535. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  8536. }
  8537. break;
  8538. }
  8539. }
  8540. fputs("\n", f);
  8541. }
  8542. }
  8543. #endif
  8544. static uint64_t get_encoded_tag(const upb_fielddef *f, int wire_type) {
  8545. uint32_t tag = (upb_fielddef_number(f) << 3) | wire_type;
  8546. uint64_t encoded_tag = upb_vencode32(tag);
  8547. /* No tag should be greater than 5 bytes. */
  8548. UPB_ASSERT(encoded_tag <= 0xffffffffff);
  8549. return encoded_tag;
  8550. }
  8551. static void putchecktag(compiler *c, const upb_fielddef *f,
  8552. int wire_type, int dest) {
  8553. uint64_t tag = get_encoded_tag(f, wire_type);
  8554. switch (upb_value_size(tag)) {
  8555. case 1:
  8556. putop(c, OP_TAG1, dest, tag);
  8557. break;
  8558. case 2:
  8559. putop(c, OP_TAG2, dest, tag);
  8560. break;
  8561. default:
  8562. putop(c, OP_TAGN, dest, tag);
  8563. break;
  8564. }
  8565. }
  8566. static upb_selector_t getsel(const upb_fielddef *f, upb_handlertype_t type) {
  8567. upb_selector_t selector;
  8568. bool ok = upb_handlers_getselector(f, type, &selector);
  8569. UPB_ASSERT(ok);
  8570. return selector;
  8571. }
  8572. /* Takes an existing, primary dispatch table entry and repacks it with a
  8573. * different alternate wire type. Called when we are inserting a secondary
  8574. * dispatch table entry for an alternate wire type. */
  8575. static uint64_t repack(uint64_t dispatch, int new_wt2) {
  8576. uint64_t ofs;
  8577. uint8_t wt1;
  8578. uint8_t old_wt2;
  8579. upb_pbdecoder_unpackdispatch(dispatch, &ofs, &wt1, &old_wt2);
  8580. UPB_ASSERT(old_wt2 == NO_WIRE_TYPE); /* wt2 should not be set yet. */
  8581. return upb_pbdecoder_packdispatch(ofs, wt1, new_wt2);
  8582. }
  8583. /* Marks the current bytecode position as the dispatch target for this message,
  8584. * field, and wire type. */
  8585. static void dispatchtarget(compiler *c, upb_pbdecodermethod *method,
  8586. const upb_fielddef *f, int wire_type) {
  8587. /* Offset is relative to msg base. */
  8588. uint64_t ofs = pcofs(c) - method->code_base.ofs;
  8589. uint32_t fn = upb_fielddef_number(f);
  8590. upb_inttable *d = &method->dispatch;
  8591. upb_value v;
  8592. if (upb_inttable_remove(d, fn, &v)) {
  8593. /* TODO: prioritize based on packed setting in .proto file. */
  8594. uint64_t repacked = repack(upb_value_getuint64(v), wire_type);
  8595. upb_inttable_insert(d, fn, upb_value_uint64(repacked));
  8596. upb_inttable_insert(d, fn + UPB_MAX_FIELDNUMBER, upb_value_uint64(ofs));
  8597. } else {
  8598. uint64_t val = upb_pbdecoder_packdispatch(ofs, wire_type, NO_WIRE_TYPE);
  8599. upb_inttable_insert(d, fn, upb_value_uint64(val));
  8600. }
  8601. }
  8602. static void putpush(compiler *c, const upb_fielddef *f) {
  8603. if (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE) {
  8604. putop(c, OP_PUSHLENDELIM);
  8605. } else {
  8606. uint32_t fn = upb_fielddef_number(f);
  8607. if (fn >= 1 << 24) {
  8608. putop(c, OP_PUSHTAGDELIM, 0);
  8609. putop(c, OP_SETBIGGROUPNUM, fn);
  8610. } else {
  8611. putop(c, OP_PUSHTAGDELIM, fn);
  8612. }
  8613. }
  8614. }
  8615. static upb_pbdecodermethod *find_submethod(const compiler *c,
  8616. const upb_pbdecodermethod *method,
  8617. const upb_fielddef *f) {
  8618. const upb_handlers *sub =
  8619. upb_handlers_getsubhandlers(method->dest_handlers_, f);
  8620. upb_value v;
  8621. return upb_inttable_lookupptr(&c->group->methods, sub, &v)
  8622. ? upb_value_getptr(v)
  8623. : NULL;
  8624. }
  8625. static void putsel(compiler *c, opcode op, upb_selector_t sel,
  8626. const upb_handlers *h) {
  8627. if (upb_handlers_gethandler(h, sel)) {
  8628. putop(c, op, sel);
  8629. }
  8630. }
  8631. /* Puts an opcode to call a callback, but only if a callback actually exists for
  8632. * this field and handler type. */
  8633. static void maybeput(compiler *c, opcode op, const upb_handlers *h,
  8634. const upb_fielddef *f, upb_handlertype_t type) {
  8635. putsel(c, op, getsel(f, type), h);
  8636. }
  8637. static bool haslazyhandlers(const upb_handlers *h, const upb_fielddef *f) {
  8638. if (!upb_fielddef_lazy(f))
  8639. return false;
  8640. return upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STARTSTR)) ||
  8641. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STRING)) ||
  8642. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_ENDSTR));
  8643. }
  8644. /* bytecode compiler code generation ******************************************/
  8645. /* Symbolic names for our local labels. */
  8646. #define LABEL_LOOPSTART 1 /* Top of a repeated field loop. */
  8647. #define LABEL_LOOPBREAK 2 /* To jump out of a repeated loop */
  8648. #define LABEL_FIELD 3 /* Jump backward to find the most recent field. */
  8649. #define LABEL_ENDMSG 4 /* To reach the OP_ENDMSG instr for this msg. */
  8650. /* Generates bytecode to parse a single non-lazy message field. */
  8651. static void generate_msgfield(compiler *c, const upb_fielddef *f,
  8652. upb_pbdecodermethod *method) {
  8653. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  8654. const upb_pbdecodermethod *sub_m = find_submethod(c, method, f);
  8655. int wire_type;
  8656. if (!sub_m) {
  8657. /* Don't emit any code for this field at all; it will be parsed as an
  8658. * unknown field.
  8659. *
  8660. * TODO(haberman): we should change this to parse it as a string field
  8661. * instead. It will probably be faster, but more importantly, once we
  8662. * start vending unknown fields, a field shouldn't be treated as unknown
  8663. * just because it doesn't have subhandlers registered. */
  8664. return;
  8665. }
  8666. label(c, LABEL_FIELD);
  8667. wire_type =
  8668. (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE)
  8669. ? UPB_WIRE_TYPE_DELIMITED
  8670. : UPB_WIRE_TYPE_START_GROUP;
  8671. if (upb_fielddef_isseq(f)) {
  8672. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  8673. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  8674. dispatchtarget(c, method, f, wire_type);
  8675. putop(c, OP_PUSHTAGDELIM, 0);
  8676. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  8677. label(c, LABEL_LOOPSTART);
  8678. putpush(c, f);
  8679. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  8680. putop(c, OP_CALL, sub_m);
  8681. putop(c, OP_POP);
  8682. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  8683. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  8684. putop(c, OP_SETDELIM);
  8685. }
  8686. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  8687. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  8688. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  8689. label(c, LABEL_LOOPBREAK);
  8690. putop(c, OP_POP);
  8691. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  8692. } else {
  8693. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  8694. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  8695. dispatchtarget(c, method, f, wire_type);
  8696. putpush(c, f);
  8697. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  8698. putop(c, OP_CALL, sub_m);
  8699. putop(c, OP_POP);
  8700. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  8701. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  8702. putop(c, OP_SETDELIM);
  8703. }
  8704. }
  8705. }
  8706. /* Generates bytecode to parse a single string or lazy submessage field. */
  8707. static void generate_delimfield(compiler *c, const upb_fielddef *f,
  8708. upb_pbdecodermethod *method) {
  8709. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  8710. label(c, LABEL_FIELD);
  8711. if (upb_fielddef_isseq(f)) {
  8712. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  8713. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  8714. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  8715. putop(c, OP_PUSHTAGDELIM, 0);
  8716. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  8717. label(c, LABEL_LOOPSTART);
  8718. putop(c, OP_PUSHLENDELIM);
  8719. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  8720. /* Need to emit even if no handler to skip past the string. */
  8721. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  8722. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  8723. putop(c, OP_POP);
  8724. putop(c, OP_SETDELIM);
  8725. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  8726. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_LOOPBREAK);
  8727. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  8728. label(c, LABEL_LOOPBREAK);
  8729. putop(c, OP_POP);
  8730. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  8731. } else {
  8732. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  8733. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  8734. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  8735. putop(c, OP_PUSHLENDELIM);
  8736. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  8737. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  8738. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  8739. putop(c, OP_POP);
  8740. putop(c, OP_SETDELIM);
  8741. }
  8742. }
  8743. /* Generates bytecode to parse a single primitive field. */
  8744. static void generate_primitivefield(compiler *c, const upb_fielddef *f,
  8745. upb_pbdecodermethod *method) {
  8746. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  8747. upb_descriptortype_t descriptor_type = upb_fielddef_descriptortype(f);
  8748. opcode parse_type;
  8749. upb_selector_t sel;
  8750. int wire_type;
  8751. label(c, LABEL_FIELD);
  8752. /* From a decoding perspective, ENUM is the same as INT32. */
  8753. if (descriptor_type == UPB_DESCRIPTOR_TYPE_ENUM)
  8754. descriptor_type = UPB_DESCRIPTOR_TYPE_INT32;
  8755. parse_type = (opcode)descriptor_type;
  8756. /* TODO(haberman): generate packed or non-packed first depending on "packed"
  8757. * setting in the fielddef. This will favor (in speed) whichever was
  8758. * specified. */
  8759. UPB_ASSERT((int)parse_type >= 0 && parse_type <= OP_MAX);
  8760. sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  8761. wire_type = upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  8762. if (upb_fielddef_isseq(f)) {
  8763. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  8764. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  8765. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  8766. putop(c, OP_PUSHLENDELIM);
  8767. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); /* Packed */
  8768. label(c, LABEL_LOOPSTART);
  8769. putop(c, parse_type, sel);
  8770. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  8771. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  8772. dispatchtarget(c, method, f, wire_type);
  8773. putop(c, OP_PUSHTAGDELIM, 0);
  8774. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); /* Non-packed */
  8775. label(c, LABEL_LOOPSTART);
  8776. putop(c, parse_type, sel);
  8777. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  8778. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  8779. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  8780. label(c, LABEL_LOOPBREAK);
  8781. putop(c, OP_POP); /* Packed and non-packed join. */
  8782. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  8783. putop(c, OP_SETDELIM); /* Could remove for non-packed by dup ENDSEQ. */
  8784. } else {
  8785. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  8786. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  8787. dispatchtarget(c, method, f, wire_type);
  8788. putop(c, parse_type, sel);
  8789. }
  8790. }
  8791. /* Adds bytecode for parsing the given message to the given decoderplan,
  8792. * while adding all dispatch targets to this message's dispatch table. */
  8793. static void compile_method(compiler *c, upb_pbdecodermethod *method) {
  8794. const upb_handlers *h;
  8795. const upb_msgdef *md;
  8796. uint32_t* start_pc;
  8797. upb_msg_field_iter i;
  8798. upb_value val;
  8799. UPB_ASSERT(method);
  8800. /* Clear all entries in the dispatch table. */
  8801. upb_inttable_uninit(&method->dispatch);
  8802. upb_inttable_init(&method->dispatch, UPB_CTYPE_UINT64);
  8803. h = upb_pbdecodermethod_desthandlers(method);
  8804. md = upb_handlers_msgdef(h);
  8805. method->code_base.ofs = pcofs(c);
  8806. putop(c, OP_SETDISPATCH, &method->dispatch);
  8807. putsel(c, OP_STARTMSG, UPB_STARTMSG_SELECTOR, h);
  8808. label(c, LABEL_FIELD);
  8809. start_pc = c->pc;
  8810. for(upb_msg_field_begin(&i, md);
  8811. !upb_msg_field_done(&i);
  8812. upb_msg_field_next(&i)) {
  8813. const upb_fielddef *f = upb_msg_iter_field(&i);
  8814. upb_fieldtype_t type = upb_fielddef_type(f);
  8815. if (type == UPB_TYPE_MESSAGE && !(haslazyhandlers(h, f) && c->lazy)) {
  8816. generate_msgfield(c, f, method);
  8817. } else if (type == UPB_TYPE_STRING || type == UPB_TYPE_BYTES ||
  8818. type == UPB_TYPE_MESSAGE) {
  8819. generate_delimfield(c, f, method);
  8820. } else {
  8821. generate_primitivefield(c, f, method);
  8822. }
  8823. }
  8824. /* If there were no fields, or if no handlers were defined, we need to
  8825. * generate a non-empty loop body so that we can at least dispatch for unknown
  8826. * fields and check for the end of the message. */
  8827. if (c->pc == start_pc) {
  8828. /* Check for end-of-message. */
  8829. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  8830. /* Unconditionally dispatch. */
  8831. putop(c, OP_DISPATCH, 0);
  8832. }
  8833. /* For now we just loop back to the last field of the message (or if none,
  8834. * the DISPATCH opcode for the message). */
  8835. putop(c, OP_BRANCH, -LABEL_FIELD);
  8836. /* Insert both a label and a dispatch table entry for this end-of-msg. */
  8837. label(c, LABEL_ENDMSG);
  8838. val = upb_value_uint64(pcofs(c) - method->code_base.ofs);
  8839. upb_inttable_insert(&method->dispatch, DISPATCH_ENDMSG, val);
  8840. putsel(c, OP_ENDMSG, UPB_ENDMSG_SELECTOR, h);
  8841. putop(c, OP_RET);
  8842. upb_inttable_compact(&method->dispatch);
  8843. }
  8844. /* Populate "methods" with new upb_pbdecodermethod objects reachable from "h".
  8845. * Returns the method for these handlers.
  8846. *
  8847. * Generates a new method for every destination handlers reachable from "h". */
  8848. static void find_methods(compiler *c, const upb_handlers *h) {
  8849. upb_value v;
  8850. upb_msg_field_iter i;
  8851. const upb_msgdef *md;
  8852. if (upb_inttable_lookupptr(&c->group->methods, h, &v))
  8853. return;
  8854. newmethod(h, c->group);
  8855. /* Find submethods. */
  8856. md = upb_handlers_msgdef(h);
  8857. for(upb_msg_field_begin(&i, md);
  8858. !upb_msg_field_done(&i);
  8859. upb_msg_field_next(&i)) {
  8860. const upb_fielddef *f = upb_msg_iter_field(&i);
  8861. const upb_handlers *sub_h;
  8862. if (upb_fielddef_type(f) == UPB_TYPE_MESSAGE &&
  8863. (sub_h = upb_handlers_getsubhandlers(h, f)) != NULL) {
  8864. /* We only generate a decoder method for submessages with handlers.
  8865. * Others will be parsed as unknown fields. */
  8866. find_methods(c, sub_h);
  8867. }
  8868. }
  8869. }
  8870. /* (Re-)compile bytecode for all messages in "msgs."
  8871. * Overwrites any existing bytecode in "c". */
  8872. static void compile_methods(compiler *c) {
  8873. upb_inttable_iter i;
  8874. /* Start over at the beginning of the bytecode. */
  8875. c->pc = c->group->bytecode;
  8876. upb_inttable_begin(&i, &c->group->methods);
  8877. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  8878. upb_pbdecodermethod *method = upb_value_getptr(upb_inttable_iter_value(&i));
  8879. compile_method(c, method);
  8880. }
  8881. }
  8882. static void set_bytecode_handlers(mgroup *g) {
  8883. upb_inttable_iter i;
  8884. upb_inttable_begin(&i, &g->methods);
  8885. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  8886. upb_pbdecodermethod *m = upb_value_getptr(upb_inttable_iter_value(&i));
  8887. upb_byteshandler *h = &m->input_handler_;
  8888. m->code_base.ptr = g->bytecode + m->code_base.ofs;
  8889. upb_byteshandler_setstartstr(h, upb_pbdecoder_startbc, m->code_base.ptr);
  8890. upb_byteshandler_setstring(h, upb_pbdecoder_decode, g);
  8891. upb_byteshandler_setendstr(h, upb_pbdecoder_end, m);
  8892. }
  8893. }
  8894. /* JIT setup. *****************************************************************/
  8895. #ifdef UPB_USE_JIT_X64
  8896. static void sethandlers(mgroup *g, bool allowjit) {
  8897. g->jit_code = NULL;
  8898. if (allowjit) {
  8899. /* Compile byte-code into machine code, create handlers. */
  8900. upb_pbdecoder_jit(g);
  8901. } else {
  8902. set_bytecode_handlers(g);
  8903. }
  8904. }
  8905. #else /* UPB_USE_JIT_X64 */
  8906. static void sethandlers(mgroup *g, bool allowjit) {
  8907. /* No JIT compiled in; use bytecode handlers unconditionally. */
  8908. UPB_UNUSED(allowjit);
  8909. set_bytecode_handlers(g);
  8910. }
  8911. #endif /* UPB_USE_JIT_X64 */
  8912. /* TODO(haberman): allow this to be constructed for an arbitrary set of dest
  8913. * handlers and other mgroups (but verify we have a transitive closure). */
  8914. const mgroup *mgroup_new(const upb_handlers *dest, bool allowjit, bool lazy,
  8915. const void *owner) {
  8916. mgroup *g;
  8917. compiler *c;
  8918. UPB_UNUSED(allowjit);
  8919. UPB_ASSERT(upb_handlers_isfrozen(dest));
  8920. g = newgroup(owner);
  8921. c = newcompiler(g, lazy);
  8922. find_methods(c, dest);
  8923. /* We compile in two passes:
  8924. * 1. all messages are assigned relative offsets from the beginning of the
  8925. * bytecode (saved in method->code_base).
  8926. * 2. forwards OP_CALL instructions can be correctly linked since message
  8927. * offsets have been previously assigned.
  8928. *
  8929. * Could avoid the second pass by linking OP_CALL instructions somehow. */
  8930. compile_methods(c);
  8931. compile_methods(c);
  8932. g->bytecode_end = c->pc;
  8933. freecompiler(c);
  8934. #ifdef UPB_DUMP_BYTECODE
  8935. {
  8936. FILE *f = fopen("/tmp/upb-bytecode", "w");
  8937. UPB_ASSERT(f);
  8938. dumpbc(g->bytecode, g->bytecode_end, stderr);
  8939. dumpbc(g->bytecode, g->bytecode_end, f);
  8940. fclose(f);
  8941. f = fopen("/tmp/upb-bytecode.bin", "wb");
  8942. UPB_ASSERT(f);
  8943. fwrite(g->bytecode, 1, g->bytecode_end - g->bytecode, f);
  8944. fclose(f);
  8945. }
  8946. #endif
  8947. sethandlers(g, allowjit);
  8948. return g;
  8949. }
  8950. /* upb_pbcodecache ************************************************************/
  8951. void upb_pbcodecache_init(upb_pbcodecache *c) {
  8952. upb_inttable_init(&c->groups, UPB_CTYPE_CONSTPTR);
  8953. c->allow_jit_ = true;
  8954. }
  8955. void upb_pbcodecache_uninit(upb_pbcodecache *c) {
  8956. upb_inttable_iter i;
  8957. upb_inttable_begin(&i, &c->groups);
  8958. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  8959. const mgroup *group = upb_value_getconstptr(upb_inttable_iter_value(&i));
  8960. mgroup_unref(group, c);
  8961. }
  8962. upb_inttable_uninit(&c->groups);
  8963. }
  8964. bool upb_pbcodecache_allowjit(const upb_pbcodecache *c) {
  8965. return c->allow_jit_;
  8966. }
  8967. bool upb_pbcodecache_setallowjit(upb_pbcodecache *c, bool allow) {
  8968. if (upb_inttable_count(&c->groups) > 0)
  8969. return false;
  8970. c->allow_jit_ = allow;
  8971. return true;
  8972. }
  8973. const upb_pbdecodermethod *upb_pbcodecache_getdecodermethod(
  8974. upb_pbcodecache *c, const upb_pbdecodermethodopts *opts) {
  8975. upb_value v;
  8976. bool ok;
  8977. /* Right now we build a new DecoderMethod every time.
  8978. * TODO(haberman): properly cache methods by their true key. */
  8979. const mgroup *g = mgroup_new(opts->handlers, c->allow_jit_, opts->lazy, c);
  8980. upb_inttable_push(&c->groups, upb_value_constptr(g));
  8981. ok = upb_inttable_lookupptr(&g->methods, opts->handlers, &v);
  8982. UPB_ASSERT(ok);
  8983. return upb_value_getptr(v);
  8984. }
  8985. /* upb_pbdecodermethodopts ****************************************************/
  8986. void upb_pbdecodermethodopts_init(upb_pbdecodermethodopts *opts,
  8987. const upb_handlers *h) {
  8988. opts->handlers = h;
  8989. opts->lazy = false;
  8990. }
  8991. void upb_pbdecodermethodopts_setlazy(upb_pbdecodermethodopts *opts, bool lazy) {
  8992. opts->lazy = lazy;
  8993. }
  8994. /*
  8995. ** upb::Decoder (Bytecode Decoder VM)
  8996. **
  8997. ** Bytecode must previously have been generated using the bytecode compiler in
  8998. ** compile_decoder.c. This decoder then walks through the bytecode op-by-op to
  8999. ** parse the input.
  9000. **
  9001. ** Decoding is fully resumable; we just keep a pointer to the current bytecode
  9002. ** instruction and resume from there. A fair amount of the logic here is to
  9003. ** handle the fact that values can span buffer seams and we have to be able to
  9004. ** be capable of suspending/resuming from any byte in the stream. This
  9005. ** sometimes requires keeping a few trailing bytes from the last buffer around
  9006. ** in the "residual" buffer.
  9007. */
  9008. #include <inttypes.h>
  9009. #include <stddef.h>
  9010. #ifdef UPB_DUMP_BYTECODE
  9011. #include <stdio.h>
  9012. #endif
  9013. #define CHECK_SUSPEND(x) if (!(x)) return upb_pbdecoder_suspend(d);
  9014. /* Error messages that are shared between the bytecode and JIT decoders. */
  9015. const char *kPbDecoderStackOverflow = "Nesting too deep.";
  9016. const char *kPbDecoderSubmessageTooLong =
  9017. "Submessage end extends past enclosing submessage.";
  9018. /* Error messages shared within this file. */
  9019. static const char *kUnterminatedVarint = "Unterminated varint.";
  9020. /* upb_pbdecoder **************************************************************/
  9021. static opcode halt = OP_HALT;
  9022. /* A dummy character we can point to when the user passes us a NULL buffer.
  9023. * We need this because in C (NULL + 0) and (NULL - NULL) are undefined
  9024. * behavior, which would invalidate functions like curbufleft(). */
  9025. static const char dummy_char;
  9026. /* Whether an op consumes any of the input buffer. */
  9027. static bool consumes_input(opcode op) {
  9028. switch (op) {
  9029. case OP_SETDISPATCH:
  9030. case OP_STARTMSG:
  9031. case OP_ENDMSG:
  9032. case OP_STARTSEQ:
  9033. case OP_ENDSEQ:
  9034. case OP_STARTSUBMSG:
  9035. case OP_ENDSUBMSG:
  9036. case OP_STARTSTR:
  9037. case OP_ENDSTR:
  9038. case OP_PUSHTAGDELIM:
  9039. case OP_POP:
  9040. case OP_SETDELIM:
  9041. case OP_SETBIGGROUPNUM:
  9042. case OP_CHECKDELIM:
  9043. case OP_CALL:
  9044. case OP_RET:
  9045. case OP_BRANCH:
  9046. return false;
  9047. default:
  9048. return true;
  9049. }
  9050. }
  9051. static size_t stacksize(upb_pbdecoder *d, size_t entries) {
  9052. UPB_UNUSED(d);
  9053. return entries * sizeof(upb_pbdecoder_frame);
  9054. }
  9055. static size_t callstacksize(upb_pbdecoder *d, size_t entries) {
  9056. UPB_UNUSED(d);
  9057. #ifdef UPB_USE_JIT_X64
  9058. if (d->method_->is_native_) {
  9059. /* Each native stack frame needs two pointers, plus we need a few frames for
  9060. * the enter/exit trampolines. */
  9061. size_t ret = entries * sizeof(void*) * 2;
  9062. ret += sizeof(void*) * 10;
  9063. return ret;
  9064. }
  9065. #endif
  9066. return entries * sizeof(uint32_t*);
  9067. }
  9068. static bool in_residual_buf(const upb_pbdecoder *d, const char *p);
  9069. /* It's unfortunate that we have to micro-manage the compiler with
  9070. * UPB_FORCEINLINE and UPB_NOINLINE, especially since this tuning is necessarily
  9071. * specific to one hardware configuration. But empirically on a Core i7,
  9072. * performance increases 30-50% with these annotations. Every instance where
  9073. * these appear, gcc 4.2.1 made the wrong decision and degraded performance in
  9074. * benchmarks. */
  9075. static void seterr(upb_pbdecoder *d, const char *msg) {
  9076. upb_status status = UPB_STATUS_INIT;
  9077. upb_status_seterrmsg(&status, msg);
  9078. upb_env_reporterror(d->env, &status);
  9079. }
  9080. void upb_pbdecoder_seterr(upb_pbdecoder *d, const char *msg) {
  9081. seterr(d, msg);
  9082. }
  9083. /* Buffering ******************************************************************/
  9084. /* We operate on one buffer at a time, which is either the user's buffer passed
  9085. * to our "decode" callback or some residual bytes from the previous buffer. */
  9086. /* How many bytes can be safely read from d->ptr without reading past end-of-buf
  9087. * or past the current delimited end. */
  9088. static size_t curbufleft(const upb_pbdecoder *d) {
  9089. UPB_ASSERT(d->data_end >= d->ptr);
  9090. return d->data_end - d->ptr;
  9091. }
  9092. /* How many bytes are available before end-of-buffer. */
  9093. static size_t bufleft(const upb_pbdecoder *d) {
  9094. return d->end - d->ptr;
  9095. }
  9096. /* Overall stream offset of d->ptr. */
  9097. uint64_t offset(const upb_pbdecoder *d) {
  9098. return d->bufstart_ofs + (d->ptr - d->buf);
  9099. }
  9100. /* How many bytes are available before the end of this delimited region. */
  9101. size_t delim_remaining(const upb_pbdecoder *d) {
  9102. return d->top->end_ofs - offset(d);
  9103. }
  9104. /* Advances d->ptr. */
  9105. static void advance(upb_pbdecoder *d, size_t len) {
  9106. UPB_ASSERT(curbufleft(d) >= len);
  9107. d->ptr += len;
  9108. }
  9109. static bool in_buf(const char *p, const char *buf, const char *end) {
  9110. return p >= buf && p <= end;
  9111. }
  9112. static bool in_residual_buf(const upb_pbdecoder *d, const char *p) {
  9113. return in_buf(p, d->residual, d->residual_end);
  9114. }
  9115. /* Calculates the delim_end value, which is affected by both the current buffer
  9116. * and the parsing stack, so must be called whenever either is updated. */
  9117. static void set_delim_end(upb_pbdecoder *d) {
  9118. size_t delim_ofs = d->top->end_ofs - d->bufstart_ofs;
  9119. if (delim_ofs <= (size_t)(d->end - d->buf)) {
  9120. d->delim_end = d->buf + delim_ofs;
  9121. d->data_end = d->delim_end;
  9122. } else {
  9123. d->data_end = d->end;
  9124. d->delim_end = NULL;
  9125. }
  9126. }
  9127. static void switchtobuf(upb_pbdecoder *d, const char *buf, const char *end) {
  9128. d->ptr = buf;
  9129. d->buf = buf;
  9130. d->end = end;
  9131. set_delim_end(d);
  9132. }
  9133. static void advancetobuf(upb_pbdecoder *d, const char *buf, size_t len) {
  9134. UPB_ASSERT(curbufleft(d) == 0);
  9135. d->bufstart_ofs += (d->end - d->buf);
  9136. switchtobuf(d, buf, buf + len);
  9137. }
  9138. static void checkpoint(upb_pbdecoder *d) {
  9139. /* The assertion here is in the interests of efficiency, not correctness.
  9140. * We are trying to ensure that we don't checkpoint() more often than
  9141. * necessary. */
  9142. UPB_ASSERT(d->checkpoint != d->ptr);
  9143. d->checkpoint = d->ptr;
  9144. }
  9145. /* Skips "bytes" bytes in the stream, which may be more than available. If we
  9146. * skip more bytes than are available, we return a long read count to the caller
  9147. * indicating how many bytes can be skipped over before passing actual data
  9148. * again. Skipped bytes can pass a NULL buffer and the decoder guarantees they
  9149. * won't actually be read.
  9150. */
  9151. static int32_t skip(upb_pbdecoder *d, size_t bytes) {
  9152. UPB_ASSERT(!in_residual_buf(d, d->ptr) || d->size_param == 0);
  9153. UPB_ASSERT(d->skip == 0);
  9154. if (bytes > delim_remaining(d)) {
  9155. seterr(d, "Skipped value extended beyond enclosing submessage.");
  9156. return upb_pbdecoder_suspend(d);
  9157. } else if (bufleft(d) >= bytes) {
  9158. /* Skipped data is all in current buffer, and more is still available. */
  9159. advance(d, bytes);
  9160. d->skip = 0;
  9161. return DECODE_OK;
  9162. } else {
  9163. /* Skipped data extends beyond currently available buffers. */
  9164. d->pc = d->last;
  9165. d->skip = bytes - curbufleft(d);
  9166. d->bufstart_ofs += (d->end - d->buf);
  9167. d->residual_end = d->residual;
  9168. switchtobuf(d, d->residual, d->residual_end);
  9169. return d->size_param + d->skip;
  9170. }
  9171. }
  9172. /* Resumes the decoder from an initial state or from a previous suspend. */
  9173. int32_t upb_pbdecoder_resume(upb_pbdecoder *d, void *p, const char *buf,
  9174. size_t size, const upb_bufhandle *handle) {
  9175. UPB_UNUSED(p); /* Useless; just for the benefit of the JIT. */
  9176. /* d->skip and d->residual_end could probably elegantly be represented
  9177. * as a single variable, to more easily represent this invariant. */
  9178. UPB_ASSERT(!(d->skip && d->residual_end > d->residual));
  9179. /* We need to remember the original size_param, so that the value we return
  9180. * is relative to it, even if we do some skipping first. */
  9181. d->size_param = size;
  9182. d->handle = handle;
  9183. /* Have to handle this case specially (ie. not with skip()) because the user
  9184. * is allowed to pass a NULL buffer here, which won't allow us to safely
  9185. * calculate a d->end or use our normal functions like curbufleft(). */
  9186. if (d->skip && d->skip >= size) {
  9187. d->skip -= size;
  9188. d->bufstart_ofs += size;
  9189. buf = &dummy_char;
  9190. size = 0;
  9191. /* We can't just return now, because we might need to execute some ops
  9192. * like CHECKDELIM, which could call some callbacks and pop the stack. */
  9193. }
  9194. /* We need to pretend that this was the actual buffer param, since some of the
  9195. * calculations assume that d->ptr/d->buf is relative to this. */
  9196. d->buf_param = buf;
  9197. if (!buf) {
  9198. /* NULL buf is ok if its entire span is covered by the "skip" above, but
  9199. * by this point we know that "skip" doesn't cover the buffer. */
  9200. seterr(d, "Passed NULL buffer over non-skippable region.");
  9201. return upb_pbdecoder_suspend(d);
  9202. }
  9203. if (d->residual_end > d->residual) {
  9204. /* We have residual bytes from the last buffer. */
  9205. UPB_ASSERT(d->ptr == d->residual);
  9206. } else {
  9207. switchtobuf(d, buf, buf + size);
  9208. }
  9209. d->checkpoint = d->ptr;
  9210. /* Handle skips that don't cover the whole buffer (as above). */
  9211. if (d->skip) {
  9212. size_t skip_bytes = d->skip;
  9213. d->skip = 0;
  9214. CHECK_RETURN(skip(d, skip_bytes));
  9215. checkpoint(d);
  9216. }
  9217. /* If we're inside an unknown group, continue to parse unknown values. */
  9218. if (d->top->groupnum < 0) {
  9219. CHECK_RETURN(upb_pbdecoder_skipunknown(d, -1, 0));
  9220. checkpoint(d);
  9221. }
  9222. return DECODE_OK;
  9223. }
  9224. /* Suspends the decoder at the last checkpoint, without saving any residual
  9225. * bytes. If there are any unconsumed bytes, returns a short byte count. */
  9226. size_t upb_pbdecoder_suspend(upb_pbdecoder *d) {
  9227. d->pc = d->last;
  9228. if (d->checkpoint == d->residual) {
  9229. /* Checkpoint was in residual buf; no user bytes were consumed. */
  9230. d->ptr = d->residual;
  9231. return 0;
  9232. } else {
  9233. size_t ret = d->size_param - (d->end - d->checkpoint);
  9234. UPB_ASSERT(!in_residual_buf(d, d->checkpoint));
  9235. UPB_ASSERT(d->buf == d->buf_param || d->buf == &dummy_char);
  9236. d->bufstart_ofs += (d->checkpoint - d->buf);
  9237. d->residual_end = d->residual;
  9238. switchtobuf(d, d->residual, d->residual_end);
  9239. return ret;
  9240. }
  9241. }
  9242. /* Suspends the decoder at the last checkpoint, and saves any unconsumed
  9243. * bytes in our residual buffer. This is necessary if we need more user
  9244. * bytes to form a complete value, which might not be contiguous in the
  9245. * user's buffers. Always consumes all user bytes. */
  9246. static size_t suspend_save(upb_pbdecoder *d) {
  9247. /* We hit end-of-buffer before we could parse a full value.
  9248. * Save any unconsumed bytes (if any) to the residual buffer. */
  9249. d->pc = d->last;
  9250. if (d->checkpoint == d->residual) {
  9251. /* Checkpoint was in residual buf; append user byte(s) to residual buf. */
  9252. UPB_ASSERT((d->residual_end - d->residual) + d->size_param <=
  9253. sizeof(d->residual));
  9254. if (!in_residual_buf(d, d->ptr)) {
  9255. d->bufstart_ofs -= (d->residual_end - d->residual);
  9256. }
  9257. memcpy(d->residual_end, d->buf_param, d->size_param);
  9258. d->residual_end += d->size_param;
  9259. } else {
  9260. /* Checkpoint was in user buf; old residual bytes not needed. */
  9261. size_t save;
  9262. UPB_ASSERT(!in_residual_buf(d, d->checkpoint));
  9263. d->ptr = d->checkpoint;
  9264. save = curbufleft(d);
  9265. UPB_ASSERT(save <= sizeof(d->residual));
  9266. memcpy(d->residual, d->ptr, save);
  9267. d->residual_end = d->residual + save;
  9268. d->bufstart_ofs = offset(d);
  9269. }
  9270. switchtobuf(d, d->residual, d->residual_end);
  9271. return d->size_param;
  9272. }
  9273. /* Copies the next "bytes" bytes into "buf" and advances the stream.
  9274. * Requires that this many bytes are available in the current buffer. */
  9275. UPB_FORCEINLINE static void consumebytes(upb_pbdecoder *d, void *buf,
  9276. size_t bytes) {
  9277. UPB_ASSERT(bytes <= curbufleft(d));
  9278. memcpy(buf, d->ptr, bytes);
  9279. advance(d, bytes);
  9280. }
  9281. /* Slow path for getting the next "bytes" bytes, regardless of whether they are
  9282. * available in the current buffer or not. Returns a status code as described
  9283. * in decoder.int.h. */
  9284. UPB_NOINLINE static int32_t getbytes_slow(upb_pbdecoder *d, void *buf,
  9285. size_t bytes) {
  9286. const size_t avail = curbufleft(d);
  9287. consumebytes(d, buf, avail);
  9288. bytes -= avail;
  9289. UPB_ASSERT(bytes > 0);
  9290. if (in_residual_buf(d, d->ptr)) {
  9291. advancetobuf(d, d->buf_param, d->size_param);
  9292. }
  9293. if (curbufleft(d) >= bytes) {
  9294. consumebytes(d, (char *)buf + avail, bytes);
  9295. return DECODE_OK;
  9296. } else if (d->data_end == d->delim_end) {
  9297. seterr(d, "Submessage ended in the middle of a value or group");
  9298. return upb_pbdecoder_suspend(d);
  9299. } else {
  9300. return suspend_save(d);
  9301. }
  9302. }
  9303. /* Gets the next "bytes" bytes, regardless of whether they are available in the
  9304. * current buffer or not. Returns a status code as described in decoder.int.h.
  9305. */
  9306. UPB_FORCEINLINE static int32_t getbytes(upb_pbdecoder *d, void *buf,
  9307. size_t bytes) {
  9308. if (curbufleft(d) >= bytes) {
  9309. /* Buffer has enough data to satisfy. */
  9310. consumebytes(d, buf, bytes);
  9311. return DECODE_OK;
  9312. } else {
  9313. return getbytes_slow(d, buf, bytes);
  9314. }
  9315. }
  9316. UPB_NOINLINE static size_t peekbytes_slow(upb_pbdecoder *d, void *buf,
  9317. size_t bytes) {
  9318. size_t ret = curbufleft(d);
  9319. memcpy(buf, d->ptr, ret);
  9320. if (in_residual_buf(d, d->ptr)) {
  9321. size_t copy = UPB_MIN(bytes - ret, d->size_param);
  9322. memcpy((char *)buf + ret, d->buf_param, copy);
  9323. ret += copy;
  9324. }
  9325. return ret;
  9326. }
  9327. UPB_FORCEINLINE static size_t peekbytes(upb_pbdecoder *d, void *buf,
  9328. size_t bytes) {
  9329. if (curbufleft(d) >= bytes) {
  9330. memcpy(buf, d->ptr, bytes);
  9331. return bytes;
  9332. } else {
  9333. return peekbytes_slow(d, buf, bytes);
  9334. }
  9335. }
  9336. /* Decoding of wire types *****************************************************/
  9337. /* Slow path for decoding a varint from the current buffer position.
  9338. * Returns a status code as described in decoder.int.h. */
  9339. UPB_NOINLINE int32_t upb_pbdecoder_decode_varint_slow(upb_pbdecoder *d,
  9340. uint64_t *u64) {
  9341. uint8_t byte = 0x80;
  9342. int bitpos;
  9343. *u64 = 0;
  9344. for(bitpos = 0; bitpos < 70 && (byte & 0x80); bitpos += 7) {
  9345. CHECK_RETURN(getbytes(d, &byte, 1));
  9346. *u64 |= (uint64_t)(byte & 0x7F) << bitpos;
  9347. }
  9348. if(bitpos == 70 && (byte & 0x80)) {
  9349. seterr(d, kUnterminatedVarint);
  9350. return upb_pbdecoder_suspend(d);
  9351. }
  9352. return DECODE_OK;
  9353. }
  9354. /* Decodes a varint from the current buffer position.
  9355. * Returns a status code as described in decoder.int.h. */
  9356. UPB_FORCEINLINE static int32_t decode_varint(upb_pbdecoder *d, uint64_t *u64) {
  9357. if (curbufleft(d) > 0 && !(*d->ptr & 0x80)) {
  9358. *u64 = *d->ptr;
  9359. advance(d, 1);
  9360. return DECODE_OK;
  9361. } else if (curbufleft(d) >= 10) {
  9362. /* Fast case. */
  9363. upb_decoderet r = upb_vdecode_fast(d->ptr);
  9364. if (r.p == NULL) {
  9365. seterr(d, kUnterminatedVarint);
  9366. return upb_pbdecoder_suspend(d);
  9367. }
  9368. advance(d, r.p - d->ptr);
  9369. *u64 = r.val;
  9370. return DECODE_OK;
  9371. } else {
  9372. /* Slow case -- varint spans buffer seam. */
  9373. return upb_pbdecoder_decode_varint_slow(d, u64);
  9374. }
  9375. }
  9376. /* Decodes a 32-bit varint from the current buffer position.
  9377. * Returns a status code as described in decoder.int.h. */
  9378. UPB_FORCEINLINE static int32_t decode_v32(upb_pbdecoder *d, uint32_t *u32) {
  9379. uint64_t u64;
  9380. int32_t ret = decode_varint(d, &u64);
  9381. if (ret >= 0) return ret;
  9382. if (u64 > UINT32_MAX) {
  9383. seterr(d, "Unterminated 32-bit varint");
  9384. /* TODO(haberman) guarantee that this function return is >= 0 somehow,
  9385. * so we know this path will always be treated as error by our caller.
  9386. * Right now the size_t -> int32_t can overflow and produce negative values.
  9387. */
  9388. *u32 = 0;
  9389. return upb_pbdecoder_suspend(d);
  9390. }
  9391. *u32 = u64;
  9392. return DECODE_OK;
  9393. }
  9394. /* Decodes a fixed32 from the current buffer position.
  9395. * Returns a status code as described in decoder.int.h.
  9396. * TODO: proper byte swapping for big-endian machines. */
  9397. UPB_FORCEINLINE static int32_t decode_fixed32(upb_pbdecoder *d, uint32_t *u32) {
  9398. return getbytes(d, u32, 4);
  9399. }
  9400. /* Decodes a fixed64 from the current buffer position.
  9401. * Returns a status code as described in decoder.int.h.
  9402. * TODO: proper byte swapping for big-endian machines. */
  9403. UPB_FORCEINLINE static int32_t decode_fixed64(upb_pbdecoder *d, uint64_t *u64) {
  9404. return getbytes(d, u64, 8);
  9405. }
  9406. /* Non-static versions of the above functions.
  9407. * These are called by the JIT for fallback paths. */
  9408. int32_t upb_pbdecoder_decode_f32(upb_pbdecoder *d, uint32_t *u32) {
  9409. return decode_fixed32(d, u32);
  9410. }
  9411. int32_t upb_pbdecoder_decode_f64(upb_pbdecoder *d, uint64_t *u64) {
  9412. return decode_fixed64(d, u64);
  9413. }
  9414. static double as_double(uint64_t n) { double d; memcpy(&d, &n, 8); return d; }
  9415. static float as_float(uint32_t n) { float f; memcpy(&f, &n, 4); return f; }
  9416. /* Pushes a frame onto the decoder stack. */
  9417. static bool decoder_push(upb_pbdecoder *d, uint64_t end) {
  9418. upb_pbdecoder_frame *fr = d->top;
  9419. if (end > fr->end_ofs) {
  9420. seterr(d, kPbDecoderSubmessageTooLong);
  9421. return false;
  9422. } else if (fr == d->limit) {
  9423. seterr(d, kPbDecoderStackOverflow);
  9424. return false;
  9425. }
  9426. fr++;
  9427. fr->end_ofs = end;
  9428. fr->dispatch = NULL;
  9429. fr->groupnum = 0;
  9430. d->top = fr;
  9431. return true;
  9432. }
  9433. static bool pushtagdelim(upb_pbdecoder *d, uint32_t arg) {
  9434. /* While we expect to see an "end" tag (either ENDGROUP or a non-sequence
  9435. * field number) prior to hitting any enclosing submessage end, pushing our
  9436. * existing delim end prevents us from continuing to parse values from a
  9437. * corrupt proto that doesn't give us an END tag in time. */
  9438. if (!decoder_push(d, d->top->end_ofs))
  9439. return false;
  9440. d->top->groupnum = arg;
  9441. return true;
  9442. }
  9443. /* Pops a frame from the decoder stack. */
  9444. static void decoder_pop(upb_pbdecoder *d) { d->top--; }
  9445. UPB_NOINLINE int32_t upb_pbdecoder_checktag_slow(upb_pbdecoder *d,
  9446. uint64_t expected) {
  9447. uint64_t data = 0;
  9448. size_t bytes = upb_value_size(expected);
  9449. size_t read = peekbytes(d, &data, bytes);
  9450. if (read == bytes && data == expected) {
  9451. /* Advance past matched bytes. */
  9452. int32_t ok = getbytes(d, &data, read);
  9453. UPB_ASSERT(ok < 0);
  9454. return DECODE_OK;
  9455. } else if (read < bytes && memcmp(&data, &expected, read) == 0) {
  9456. return suspend_save(d);
  9457. } else {
  9458. return DECODE_MISMATCH;
  9459. }
  9460. }
  9461. int32_t upb_pbdecoder_skipunknown(upb_pbdecoder *d, int32_t fieldnum,
  9462. uint8_t wire_type) {
  9463. if (fieldnum >= 0)
  9464. goto have_tag;
  9465. while (true) {
  9466. uint32_t tag;
  9467. CHECK_RETURN(decode_v32(d, &tag));
  9468. wire_type = tag & 0x7;
  9469. fieldnum = tag >> 3;
  9470. have_tag:
  9471. if (fieldnum == 0) {
  9472. seterr(d, "Saw invalid field number (0)");
  9473. return upb_pbdecoder_suspend(d);
  9474. }
  9475. switch (wire_type) {
  9476. case UPB_WIRE_TYPE_32BIT:
  9477. CHECK_RETURN(skip(d, 4));
  9478. break;
  9479. case UPB_WIRE_TYPE_64BIT:
  9480. CHECK_RETURN(skip(d, 8));
  9481. break;
  9482. case UPB_WIRE_TYPE_VARINT: {
  9483. uint64_t u64;
  9484. CHECK_RETURN(decode_varint(d, &u64));
  9485. break;
  9486. }
  9487. case UPB_WIRE_TYPE_DELIMITED: {
  9488. uint32_t len;
  9489. CHECK_RETURN(decode_v32(d, &len));
  9490. CHECK_RETURN(skip(d, len));
  9491. break;
  9492. }
  9493. case UPB_WIRE_TYPE_START_GROUP:
  9494. CHECK_SUSPEND(pushtagdelim(d, -fieldnum));
  9495. break;
  9496. case UPB_WIRE_TYPE_END_GROUP:
  9497. if (fieldnum == -d->top->groupnum) {
  9498. decoder_pop(d);
  9499. } else if (fieldnum == d->top->groupnum) {
  9500. return DECODE_ENDGROUP;
  9501. } else {
  9502. seterr(d, "Unmatched ENDGROUP tag.");
  9503. return upb_pbdecoder_suspend(d);
  9504. }
  9505. break;
  9506. default:
  9507. seterr(d, "Invalid wire type");
  9508. return upb_pbdecoder_suspend(d);
  9509. }
  9510. if (d->top->groupnum >= 0) {
  9511. /* TODO: More code needed for handling unknown groups. */
  9512. upb_sink_putunknown(&d->top->sink, d->checkpoint, d->ptr - d->checkpoint);
  9513. return DECODE_OK;
  9514. }
  9515. /* Unknown group -- continue looping over unknown fields. */
  9516. checkpoint(d);
  9517. }
  9518. }
  9519. static void goto_endmsg(upb_pbdecoder *d) {
  9520. upb_value v;
  9521. bool found = upb_inttable_lookup32(d->top->dispatch, DISPATCH_ENDMSG, &v);
  9522. UPB_ASSERT(found);
  9523. d->pc = d->top->base + upb_value_getuint64(v);
  9524. }
  9525. /* Parses a tag and jumps to the corresponding bytecode instruction for this
  9526. * field.
  9527. *
  9528. * If the tag is unknown (or the wire type doesn't match), parses the field as
  9529. * unknown. If the tag is a valid ENDGROUP tag, jumps to the bytecode
  9530. * instruction for the end of message. */
  9531. static int32_t dispatch(upb_pbdecoder *d) {
  9532. upb_inttable *dispatch = d->top->dispatch;
  9533. uint32_t tag;
  9534. uint8_t wire_type;
  9535. uint32_t fieldnum;
  9536. upb_value val;
  9537. int32_t retval;
  9538. /* Decode tag. */
  9539. CHECK_RETURN(decode_v32(d, &tag));
  9540. wire_type = tag & 0x7;
  9541. fieldnum = tag >> 3;
  9542. /* Lookup tag. Because of packed/non-packed compatibility, we have to
  9543. * check the wire type against two possibilities. */
  9544. if (fieldnum != DISPATCH_ENDMSG &&
  9545. upb_inttable_lookup32(dispatch, fieldnum, &val)) {
  9546. uint64_t v = upb_value_getuint64(val);
  9547. if (wire_type == (v & 0xff)) {
  9548. d->pc = d->top->base + (v >> 16);
  9549. return DECODE_OK;
  9550. } else if (wire_type == ((v >> 8) & 0xff)) {
  9551. bool found =
  9552. upb_inttable_lookup(dispatch, fieldnum + UPB_MAX_FIELDNUMBER, &val);
  9553. UPB_ASSERT(found);
  9554. d->pc = d->top->base + upb_value_getuint64(val);
  9555. return DECODE_OK;
  9556. }
  9557. }
  9558. /* We have some unknown fields (or ENDGROUP) to parse. The DISPATCH or TAG
  9559. * bytecode that triggered this is preceded by a CHECKDELIM bytecode which
  9560. * we need to back up to, so that when we're done skipping unknown data we
  9561. * can re-check the delimited end. */
  9562. d->last--; /* Necessary if we get suspended */
  9563. d->pc = d->last;
  9564. UPB_ASSERT(getop(*d->last) == OP_CHECKDELIM);
  9565. /* Unknown field or ENDGROUP. */
  9566. retval = upb_pbdecoder_skipunknown(d, fieldnum, wire_type);
  9567. CHECK_RETURN(retval);
  9568. if (retval == DECODE_ENDGROUP) {
  9569. goto_endmsg(d);
  9570. return DECODE_OK;
  9571. }
  9572. return DECODE_OK;
  9573. }
  9574. /* Callers know that the stack is more than one deep because the opcodes that
  9575. * call this only occur after PUSH operations. */
  9576. upb_pbdecoder_frame *outer_frame(upb_pbdecoder *d) {
  9577. UPB_ASSERT(d->top != d->stack);
  9578. return d->top - 1;
  9579. }
  9580. /* The main decoding loop *****************************************************/
  9581. /* The main decoder VM function. Uses traditional bytecode dispatch loop with a
  9582. * switch() statement. */
  9583. size_t run_decoder_vm(upb_pbdecoder *d, const mgroup *group,
  9584. const upb_bufhandle* handle) {
  9585. #define VMCASE(op, code) \
  9586. case op: { code; if (consumes_input(op)) checkpoint(d); break; }
  9587. #define PRIMITIVE_OP(type, wt, name, convfunc, ctype) \
  9588. VMCASE(OP_PARSE_ ## type, { \
  9589. ctype val; \
  9590. CHECK_RETURN(decode_ ## wt(d, &val)); \
  9591. upb_sink_put ## name(&d->top->sink, arg, (convfunc)(val)); \
  9592. })
  9593. while(1) {
  9594. int32_t instruction;
  9595. opcode op;
  9596. uint32_t arg;
  9597. int32_t longofs;
  9598. d->last = d->pc;
  9599. instruction = *d->pc++;
  9600. op = getop(instruction);
  9601. arg = instruction >> 8;
  9602. longofs = arg;
  9603. UPB_ASSERT(d->ptr != d->residual_end);
  9604. UPB_UNUSED(group);
  9605. #ifdef UPB_DUMP_BYTECODE
  9606. fprintf(stderr, "s_ofs=%d buf_ofs=%d data_rem=%d buf_rem=%d delim_rem=%d "
  9607. "%x %s (%d)\n",
  9608. (int)offset(d),
  9609. (int)(d->ptr - d->buf),
  9610. (int)(d->data_end - d->ptr),
  9611. (int)(d->end - d->ptr),
  9612. (int)((d->top->end_ofs - d->bufstart_ofs) - (d->ptr - d->buf)),
  9613. (int)(d->pc - 1 - group->bytecode),
  9614. upb_pbdecoder_getopname(op),
  9615. arg);
  9616. #endif
  9617. switch (op) {
  9618. /* Technically, we are losing data if we see a 32-bit varint that is not
  9619. * properly sign-extended. We could detect this and error about the data
  9620. * loss, but proto2 does not do this, so we pass. */
  9621. PRIMITIVE_OP(INT32, varint, int32, int32_t, uint64_t)
  9622. PRIMITIVE_OP(INT64, varint, int64, int64_t, uint64_t)
  9623. PRIMITIVE_OP(UINT32, varint, uint32, uint32_t, uint64_t)
  9624. PRIMITIVE_OP(UINT64, varint, uint64, uint64_t, uint64_t)
  9625. PRIMITIVE_OP(FIXED32, fixed32, uint32, uint32_t, uint32_t)
  9626. PRIMITIVE_OP(FIXED64, fixed64, uint64, uint64_t, uint64_t)
  9627. PRIMITIVE_OP(SFIXED32, fixed32, int32, int32_t, uint32_t)
  9628. PRIMITIVE_OP(SFIXED64, fixed64, int64, int64_t, uint64_t)
  9629. PRIMITIVE_OP(BOOL, varint, bool, bool, uint64_t)
  9630. PRIMITIVE_OP(DOUBLE, fixed64, double, as_double, uint64_t)
  9631. PRIMITIVE_OP(FLOAT, fixed32, float, as_float, uint32_t)
  9632. PRIMITIVE_OP(SINT32, varint, int32, upb_zzdec_32, uint64_t)
  9633. PRIMITIVE_OP(SINT64, varint, int64, upb_zzdec_64, uint64_t)
  9634. VMCASE(OP_SETDISPATCH,
  9635. d->top->base = d->pc - 1;
  9636. memcpy(&d->top->dispatch, d->pc, sizeof(void*));
  9637. d->pc += sizeof(void*) / sizeof(uint32_t);
  9638. )
  9639. VMCASE(OP_STARTMSG,
  9640. CHECK_SUSPEND(upb_sink_startmsg(&d->top->sink));
  9641. )
  9642. VMCASE(OP_ENDMSG,
  9643. CHECK_SUSPEND(upb_sink_endmsg(&d->top->sink, d->status));
  9644. )
  9645. VMCASE(OP_STARTSEQ,
  9646. upb_pbdecoder_frame *outer = outer_frame(d);
  9647. CHECK_SUSPEND(upb_sink_startseq(&outer->sink, arg, &d->top->sink));
  9648. )
  9649. VMCASE(OP_ENDSEQ,
  9650. CHECK_SUSPEND(upb_sink_endseq(&d->top->sink, arg));
  9651. )
  9652. VMCASE(OP_STARTSUBMSG,
  9653. upb_pbdecoder_frame *outer = outer_frame(d);
  9654. CHECK_SUSPEND(upb_sink_startsubmsg(&outer->sink, arg, &d->top->sink));
  9655. )
  9656. VMCASE(OP_ENDSUBMSG,
  9657. CHECK_SUSPEND(upb_sink_endsubmsg(&d->top->sink, arg));
  9658. )
  9659. VMCASE(OP_STARTSTR,
  9660. uint32_t len = delim_remaining(d);
  9661. upb_pbdecoder_frame *outer = outer_frame(d);
  9662. CHECK_SUSPEND(upb_sink_startstr(&outer->sink, arg, len, &d->top->sink));
  9663. if (len == 0) {
  9664. d->pc++; /* Skip OP_STRING. */
  9665. }
  9666. )
  9667. VMCASE(OP_STRING,
  9668. uint32_t len = curbufleft(d);
  9669. size_t n = upb_sink_putstring(&d->top->sink, arg, d->ptr, len, handle);
  9670. if (n > len) {
  9671. if (n > delim_remaining(d)) {
  9672. seterr(d, "Tried to skip past end of string.");
  9673. return upb_pbdecoder_suspend(d);
  9674. } else {
  9675. int32_t ret = skip(d, n);
  9676. /* This shouldn't return DECODE_OK, because n > len. */
  9677. UPB_ASSERT(ret >= 0);
  9678. return ret;
  9679. }
  9680. }
  9681. advance(d, n);
  9682. if (n < len || d->delim_end == NULL) {
  9683. /* We aren't finished with this string yet. */
  9684. d->pc--; /* Repeat OP_STRING. */
  9685. if (n > 0) checkpoint(d);
  9686. return upb_pbdecoder_suspend(d);
  9687. }
  9688. )
  9689. VMCASE(OP_ENDSTR,
  9690. CHECK_SUSPEND(upb_sink_endstr(&d->top->sink, arg));
  9691. )
  9692. VMCASE(OP_PUSHTAGDELIM,
  9693. CHECK_SUSPEND(pushtagdelim(d, arg));
  9694. )
  9695. VMCASE(OP_SETBIGGROUPNUM,
  9696. d->top->groupnum = *d->pc++;
  9697. )
  9698. VMCASE(OP_POP,
  9699. UPB_ASSERT(d->top > d->stack);
  9700. decoder_pop(d);
  9701. )
  9702. VMCASE(OP_PUSHLENDELIM,
  9703. uint32_t len;
  9704. CHECK_RETURN(decode_v32(d, &len));
  9705. CHECK_SUSPEND(decoder_push(d, offset(d) + len));
  9706. set_delim_end(d);
  9707. )
  9708. VMCASE(OP_SETDELIM,
  9709. set_delim_end(d);
  9710. )
  9711. VMCASE(OP_CHECKDELIM,
  9712. /* We are guaranteed of this assert because we never allow ourselves to
  9713. * consume bytes beyond data_end, which covers delim_end when non-NULL.
  9714. */
  9715. UPB_ASSERT(!(d->delim_end && d->ptr > d->delim_end));
  9716. if (d->ptr == d->delim_end)
  9717. d->pc += longofs;
  9718. )
  9719. VMCASE(OP_CALL,
  9720. d->callstack[d->call_len++] = d->pc;
  9721. d->pc += longofs;
  9722. )
  9723. VMCASE(OP_RET,
  9724. UPB_ASSERT(d->call_len > 0);
  9725. d->pc = d->callstack[--d->call_len];
  9726. )
  9727. VMCASE(OP_BRANCH,
  9728. d->pc += longofs;
  9729. )
  9730. VMCASE(OP_TAG1,
  9731. uint8_t expected;
  9732. CHECK_SUSPEND(curbufleft(d) > 0);
  9733. expected = (arg >> 8) & 0xff;
  9734. if (*d->ptr == expected) {
  9735. advance(d, 1);
  9736. } else {
  9737. int8_t shortofs;
  9738. badtag:
  9739. shortofs = arg;
  9740. if (shortofs == LABEL_DISPATCH) {
  9741. CHECK_RETURN(dispatch(d));
  9742. } else {
  9743. d->pc += shortofs;
  9744. break; /* Avoid checkpoint(). */
  9745. }
  9746. }
  9747. )
  9748. VMCASE(OP_TAG2,
  9749. uint16_t expected;
  9750. CHECK_SUSPEND(curbufleft(d) > 0);
  9751. expected = (arg >> 8) & 0xffff;
  9752. if (curbufleft(d) >= 2) {
  9753. uint16_t actual;
  9754. memcpy(&actual, d->ptr, 2);
  9755. if (expected == actual) {
  9756. advance(d, 2);
  9757. } else {
  9758. goto badtag;
  9759. }
  9760. } else {
  9761. int32_t result = upb_pbdecoder_checktag_slow(d, expected);
  9762. if (result == DECODE_MISMATCH) goto badtag;
  9763. if (result >= 0) return result;
  9764. }
  9765. )
  9766. VMCASE(OP_TAGN, {
  9767. uint64_t expected;
  9768. int32_t result;
  9769. memcpy(&expected, d->pc, 8);
  9770. d->pc += 2;
  9771. result = upb_pbdecoder_checktag_slow(d, expected);
  9772. if (result == DECODE_MISMATCH) goto badtag;
  9773. if (result >= 0) return result;
  9774. })
  9775. VMCASE(OP_DISPATCH, {
  9776. CHECK_RETURN(dispatch(d));
  9777. })
  9778. VMCASE(OP_HALT, {
  9779. return d->size_param;
  9780. })
  9781. }
  9782. }
  9783. }
  9784. /* BytesHandler handlers ******************************************************/
  9785. void *upb_pbdecoder_startbc(void *closure, const void *pc, size_t size_hint) {
  9786. upb_pbdecoder *d = closure;
  9787. UPB_UNUSED(size_hint);
  9788. d->top->end_ofs = UINT64_MAX;
  9789. d->bufstart_ofs = 0;
  9790. d->call_len = 1;
  9791. d->callstack[0] = &halt;
  9792. d->pc = pc;
  9793. d->skip = 0;
  9794. return d;
  9795. }
  9796. void *upb_pbdecoder_startjit(void *closure, const void *hd, size_t size_hint) {
  9797. upb_pbdecoder *d = closure;
  9798. UPB_UNUSED(hd);
  9799. UPB_UNUSED(size_hint);
  9800. d->top->end_ofs = UINT64_MAX;
  9801. d->bufstart_ofs = 0;
  9802. d->call_len = 0;
  9803. d->skip = 0;
  9804. return d;
  9805. }
  9806. bool upb_pbdecoder_end(void *closure, const void *handler_data) {
  9807. upb_pbdecoder *d = closure;
  9808. const upb_pbdecodermethod *method = handler_data;
  9809. uint64_t end;
  9810. char dummy;
  9811. if (d->residual_end > d->residual) {
  9812. seterr(d, "Unexpected EOF: decoder still has buffered unparsed data");
  9813. return false;
  9814. }
  9815. if (d->skip) {
  9816. seterr(d, "Unexpected EOF inside skipped data");
  9817. return false;
  9818. }
  9819. if (d->top->end_ofs != UINT64_MAX) {
  9820. seterr(d, "Unexpected EOF inside delimited string");
  9821. return false;
  9822. }
  9823. /* The user's end() call indicates that the message ends here. */
  9824. end = offset(d);
  9825. d->top->end_ofs = end;
  9826. #ifdef UPB_USE_JIT_X64
  9827. if (method->is_native_) {
  9828. const mgroup *group = (const mgroup*)method->group;
  9829. if (d->top != d->stack)
  9830. d->stack->end_ofs = 0;
  9831. group->jit_code(closure, method->code_base.ptr, &dummy, 0, NULL);
  9832. } else
  9833. #endif
  9834. {
  9835. const uint32_t *p = d->pc;
  9836. d->stack->end_ofs = end;
  9837. /* Check the previous bytecode, but guard against beginning. */
  9838. if (p != method->code_base.ptr) p--;
  9839. if (getop(*p) == OP_CHECKDELIM) {
  9840. /* Rewind from OP_TAG* to OP_CHECKDELIM. */
  9841. UPB_ASSERT(getop(*d->pc) == OP_TAG1 ||
  9842. getop(*d->pc) == OP_TAG2 ||
  9843. getop(*d->pc) == OP_TAGN ||
  9844. getop(*d->pc) == OP_DISPATCH);
  9845. d->pc = p;
  9846. }
  9847. upb_pbdecoder_decode(closure, handler_data, &dummy, 0, NULL);
  9848. }
  9849. if (d->call_len != 0) {
  9850. seterr(d, "Unexpected EOF inside submessage or group");
  9851. return false;
  9852. }
  9853. return true;
  9854. }
  9855. size_t upb_pbdecoder_decode(void *decoder, const void *group, const char *buf,
  9856. size_t size, const upb_bufhandle *handle) {
  9857. int32_t result = upb_pbdecoder_resume(decoder, NULL, buf, size, handle);
  9858. if (result == DECODE_ENDGROUP) goto_endmsg(decoder);
  9859. CHECK_RETURN(result);
  9860. return run_decoder_vm(decoder, group, handle);
  9861. }
  9862. /* Public API *****************************************************************/
  9863. void upb_pbdecoder_reset(upb_pbdecoder *d) {
  9864. d->top = d->stack;
  9865. d->top->groupnum = 0;
  9866. d->ptr = d->residual;
  9867. d->buf = d->residual;
  9868. d->end = d->residual;
  9869. d->residual_end = d->residual;
  9870. }
  9871. upb_pbdecoder *upb_pbdecoder_create(upb_env *e, const upb_pbdecodermethod *m,
  9872. upb_sink *sink) {
  9873. const size_t default_max_nesting = 64;
  9874. #ifndef NDEBUG
  9875. size_t size_before = upb_env_bytesallocated(e);
  9876. #endif
  9877. upb_pbdecoder *d = upb_env_malloc(e, sizeof(upb_pbdecoder));
  9878. if (!d) return NULL;
  9879. d->method_ = m;
  9880. d->callstack = upb_env_malloc(e, callstacksize(d, default_max_nesting));
  9881. d->stack = upb_env_malloc(e, stacksize(d, default_max_nesting));
  9882. if (!d->stack || !d->callstack) {
  9883. return NULL;
  9884. }
  9885. d->env = e;
  9886. d->limit = d->stack + default_max_nesting - 1;
  9887. d->stack_size = default_max_nesting;
  9888. d->status = NULL;
  9889. upb_pbdecoder_reset(d);
  9890. upb_bytessink_reset(&d->input_, &m->input_handler_, d);
  9891. UPB_ASSERT(sink);
  9892. if (d->method_->dest_handlers_) {
  9893. if (sink->handlers != d->method_->dest_handlers_)
  9894. return NULL;
  9895. }
  9896. upb_sink_reset(&d->top->sink, sink->handlers, sink->closure);
  9897. /* If this fails, increase the value in decoder.h. */
  9898. UPB_ASSERT_DEBUGVAR(upb_env_bytesallocated(e) - size_before <=
  9899. UPB_PB_DECODER_SIZE);
  9900. return d;
  9901. }
  9902. uint64_t upb_pbdecoder_bytesparsed(const upb_pbdecoder *d) {
  9903. return offset(d);
  9904. }
  9905. const upb_pbdecodermethod *upb_pbdecoder_method(const upb_pbdecoder *d) {
  9906. return d->method_;
  9907. }
  9908. upb_bytessink *upb_pbdecoder_input(upb_pbdecoder *d) {
  9909. return &d->input_;
  9910. }
  9911. size_t upb_pbdecoder_maxnesting(const upb_pbdecoder *d) {
  9912. return d->stack_size;
  9913. }
  9914. bool upb_pbdecoder_setmaxnesting(upb_pbdecoder *d, size_t max) {
  9915. UPB_ASSERT(d->top >= d->stack);
  9916. if (max < (size_t)(d->top - d->stack)) {
  9917. /* Can't set a limit smaller than what we are currently at. */
  9918. return false;
  9919. }
  9920. if (max > d->stack_size) {
  9921. /* Need to reallocate stack and callstack to accommodate. */
  9922. size_t old_size = stacksize(d, d->stack_size);
  9923. size_t new_size = stacksize(d, max);
  9924. void *p = upb_env_realloc(d->env, d->stack, old_size, new_size);
  9925. if (!p) {
  9926. return false;
  9927. }
  9928. d->stack = p;
  9929. old_size = callstacksize(d, d->stack_size);
  9930. new_size = callstacksize(d, max);
  9931. p = upb_env_realloc(d->env, d->callstack, old_size, new_size);
  9932. if (!p) {
  9933. return false;
  9934. }
  9935. d->callstack = p;
  9936. d->stack_size = max;
  9937. }
  9938. d->limit = d->stack + max - 1;
  9939. return true;
  9940. }
  9941. /*
  9942. ** upb::Encoder
  9943. **
  9944. ** Since we are implementing pure handlers (ie. without any out-of-band access
  9945. ** to pre-computed lengths), we have to buffer all submessages before we can
  9946. ** emit even their first byte.
  9947. **
  9948. ** Not knowing the size of submessages also means we can't write a perfect
  9949. ** zero-copy implementation, even with buffering. Lengths are stored as
  9950. ** varints, which means that we don't know how many bytes to reserve for the
  9951. ** length until we know what the length is.
  9952. **
  9953. ** This leaves us with three main choices:
  9954. **
  9955. ** 1. buffer all submessage data in a temporary buffer, then copy it exactly
  9956. ** once into the output buffer.
  9957. **
  9958. ** 2. attempt to buffer data directly into the output buffer, estimating how
  9959. ** many bytes each length will take. When our guesses are wrong, use
  9960. ** memmove() to grow or shrink the allotted space.
  9961. **
  9962. ** 3. buffer directly into the output buffer, allocating a max length
  9963. ** ahead-of-time for each submessage length. If we overallocated, we waste
  9964. ** space, but no memcpy() or memmove() is required. This approach requires
  9965. ** defining a maximum size for submessages and rejecting submessages that
  9966. ** exceed that size.
  9967. **
  9968. ** (2) and (3) have the potential to have better performance, but they are more
  9969. ** complicated and subtle to implement:
  9970. **
  9971. ** (3) requires making an arbitrary choice of the maximum message size; it
  9972. ** wastes space when submessages are shorter than this and fails
  9973. ** completely when they are longer. This makes it more finicky and
  9974. ** requires configuration based on the input. It also makes it impossible
  9975. ** to perfectly match the output of reference encoders that always use the
  9976. ** optimal amount of space for each length.
  9977. **
  9978. ** (2) requires guessing the the size upfront, and if multiple lengths are
  9979. ** guessed wrong the minimum required number of memmove() operations may
  9980. ** be complicated to compute correctly. Implemented properly, it may have
  9981. ** a useful amortized or average cost, but more investigation is required
  9982. ** to determine this and what the optimal algorithm is to achieve it.
  9983. **
  9984. ** (1) makes you always pay for exactly one copy, but its implementation is
  9985. ** the simplest and its performance is predictable.
  9986. **
  9987. ** So for now, we implement (1) only. If we wish to optimize later, we should
  9988. ** be able to do it without affecting users.
  9989. **
  9990. ** The strategy is to buffer the segments of data that do *not* depend on
  9991. ** unknown lengths in one buffer, and keep a separate buffer of segment pointers
  9992. ** and lengths. When the top-level submessage ends, we can go beginning to end,
  9993. ** alternating the writing of lengths with memcpy() of the rest of the data.
  9994. ** At the top level though, no buffering is required.
  9995. */
  9996. /* The output buffer is divided into segments; a segment is a string of data
  9997. * that is "ready to go" -- it does not need any varint lengths inserted into
  9998. * the middle. The seams between segments are where varints will be inserted
  9999. * once they are known.
  10000. *
  10001. * We also use the concept of a "run", which is a range of encoded bytes that
  10002. * occur at a single submessage level. Every segment contains one or more runs.
  10003. *
  10004. * A segment can span messages. Consider:
  10005. *
  10006. * .--Submessage lengths---------.
  10007. * | | |
  10008. * | V V
  10009. * V | |--------------- | |-----------------
  10010. * Submessages: | |-----------------------------------------------
  10011. * Top-level msg: ------------------------------------------------------------
  10012. *
  10013. * Segments: ----- ------------------- -----------------
  10014. * Runs: *---- *--------------*--- *----------------
  10015. * (* marks the start)
  10016. *
  10017. * Note that the top-level menssage is not in any segment because it does not
  10018. * have any length preceding it.
  10019. *
  10020. * A segment is only interrupted when another length needs to be inserted. So
  10021. * observe how the second segment spans both the inner submessage and part of
  10022. * the next enclosing message. */
  10023. typedef struct {
  10024. uint32_t msglen; /* The length to varint-encode before this segment. */
  10025. uint32_t seglen; /* Length of the segment. */
  10026. } upb_pb_encoder_segment;
  10027. struct upb_pb_encoder {
  10028. upb_env *env;
  10029. /* Our input and output. */
  10030. upb_sink input_;
  10031. upb_bytessink *output_;
  10032. /* The "subclosure" -- used as the inner closure as part of the bytessink
  10033. * protocol. */
  10034. void *subc;
  10035. /* The output buffer and limit, and our current write position. "buf"
  10036. * initially points to "initbuf", but is dynamically allocated if we need to
  10037. * grow beyond the initial size. */
  10038. char *buf, *ptr, *limit;
  10039. /* The beginning of the current run, or undefined if we are at the top
  10040. * level. */
  10041. char *runbegin;
  10042. /* The list of segments we are accumulating. */
  10043. upb_pb_encoder_segment *segbuf, *segptr, *seglimit;
  10044. /* The stack of enclosing submessages. Each entry in the stack points to the
  10045. * segment where this submessage's length is being accumulated. */
  10046. int *stack, *top, *stacklimit;
  10047. /* Depth of startmsg/endmsg calls. */
  10048. int depth;
  10049. };
  10050. /* low-level buffering ********************************************************/
  10051. /* Low-level functions for interacting with the output buffer. */
  10052. /* TODO(haberman): handle pushback */
  10053. static void putbuf(upb_pb_encoder *e, const char *buf, size_t len) {
  10054. size_t n = upb_bytessink_putbuf(e->output_, e->subc, buf, len, NULL);
  10055. UPB_ASSERT(n == len);
  10056. }
  10057. static upb_pb_encoder_segment *top(upb_pb_encoder *e) {
  10058. return &e->segbuf[*e->top];
  10059. }
  10060. /* Call to ensure that at least "bytes" bytes are available for writing at
  10061. * e->ptr. Returns false if the bytes could not be allocated. */
  10062. static bool reserve(upb_pb_encoder *e, size_t bytes) {
  10063. if ((size_t)(e->limit - e->ptr) < bytes) {
  10064. /* Grow buffer. */
  10065. char *new_buf;
  10066. size_t needed = bytes + (e->ptr - e->buf);
  10067. size_t old_size = e->limit - e->buf;
  10068. size_t new_size = old_size;
  10069. while (new_size < needed) {
  10070. new_size *= 2;
  10071. }
  10072. new_buf = upb_env_realloc(e->env, e->buf, old_size, new_size);
  10073. if (new_buf == NULL) {
  10074. return false;
  10075. }
  10076. e->ptr = new_buf + (e->ptr - e->buf);
  10077. e->runbegin = new_buf + (e->runbegin - e->buf);
  10078. e->limit = new_buf + new_size;
  10079. e->buf = new_buf;
  10080. }
  10081. return true;
  10082. }
  10083. /* Call when "bytes" bytes have been writte at e->ptr. The caller *must* have
  10084. * previously called reserve() with at least this many bytes. */
  10085. static void encoder_advance(upb_pb_encoder *e, size_t bytes) {
  10086. UPB_ASSERT((size_t)(e->limit - e->ptr) >= bytes);
  10087. e->ptr += bytes;
  10088. }
  10089. /* Call when all of the bytes for a handler have been written. Flushes the
  10090. * bytes if possible and necessary, returning false if this failed. */
  10091. static bool commit(upb_pb_encoder *e) {
  10092. if (!e->top) {
  10093. /* We aren't inside a delimited region. Flush our accumulated bytes to
  10094. * the output.
  10095. *
  10096. * TODO(haberman): in the future we may want to delay flushing for
  10097. * efficiency reasons. */
  10098. putbuf(e, e->buf, e->ptr - e->buf);
  10099. e->ptr = e->buf;
  10100. }
  10101. return true;
  10102. }
  10103. /* Writes the given bytes to the buffer, handling reserve/advance. */
  10104. static bool encode_bytes(upb_pb_encoder *e, const void *data, size_t len) {
  10105. if (!reserve(e, len)) {
  10106. return false;
  10107. }
  10108. memcpy(e->ptr, data, len);
  10109. encoder_advance(e, len);
  10110. return true;
  10111. }
  10112. /* Finish the current run by adding the run totals to the segment and message
  10113. * length. */
  10114. static void accumulate(upb_pb_encoder *e) {
  10115. size_t run_len;
  10116. UPB_ASSERT(e->ptr >= e->runbegin);
  10117. run_len = e->ptr - e->runbegin;
  10118. e->segptr->seglen += run_len;
  10119. top(e)->msglen += run_len;
  10120. e->runbegin = e->ptr;
  10121. }
  10122. /* Call to indicate the start of delimited region for which the full length is
  10123. * not yet known. All data will be buffered until the length is known.
  10124. * Delimited regions may be nested; their lengths will all be tracked properly. */
  10125. static bool start_delim(upb_pb_encoder *e) {
  10126. if (e->top) {
  10127. /* We are already buffering, advance to the next segment and push it on the
  10128. * stack. */
  10129. accumulate(e);
  10130. if (++e->top == e->stacklimit) {
  10131. /* TODO(haberman): grow stack? */
  10132. return false;
  10133. }
  10134. if (++e->segptr == e->seglimit) {
  10135. /* Grow segment buffer. */
  10136. size_t old_size =
  10137. (e->seglimit - e->segbuf) * sizeof(upb_pb_encoder_segment);
  10138. size_t new_size = old_size * 2;
  10139. upb_pb_encoder_segment *new_buf =
  10140. upb_env_realloc(e->env, e->segbuf, old_size, new_size);
  10141. if (new_buf == NULL) {
  10142. return false;
  10143. }
  10144. e->segptr = new_buf + (e->segptr - e->segbuf);
  10145. e->seglimit = new_buf + (new_size / sizeof(upb_pb_encoder_segment));
  10146. e->segbuf = new_buf;
  10147. }
  10148. } else {
  10149. /* We were previously at the top level, start buffering. */
  10150. e->segptr = e->segbuf;
  10151. e->top = e->stack;
  10152. e->runbegin = e->ptr;
  10153. }
  10154. *e->top = e->segptr - e->segbuf;
  10155. e->segptr->seglen = 0;
  10156. e->segptr->msglen = 0;
  10157. return true;
  10158. }
  10159. /* Call to indicate the end of a delimited region. We now know the length of
  10160. * the delimited region. If we are not nested inside any other delimited
  10161. * regions, we can now emit all of the buffered data we accumulated. */
  10162. static bool end_delim(upb_pb_encoder *e) {
  10163. size_t msglen;
  10164. accumulate(e);
  10165. msglen = top(e)->msglen;
  10166. if (e->top == e->stack) {
  10167. /* All lengths are now available, emit all buffered data. */
  10168. char buf[UPB_PB_VARINT_MAX_LEN];
  10169. upb_pb_encoder_segment *s;
  10170. const char *ptr = e->buf;
  10171. for (s = e->segbuf; s <= e->segptr; s++) {
  10172. size_t lenbytes = upb_vencode64(s->msglen, buf);
  10173. putbuf(e, buf, lenbytes);
  10174. putbuf(e, ptr, s->seglen);
  10175. ptr += s->seglen;
  10176. }
  10177. e->ptr = e->buf;
  10178. e->top = NULL;
  10179. } else {
  10180. /* Need to keep buffering; propagate length info into enclosing
  10181. * submessages. */
  10182. --e->top;
  10183. top(e)->msglen += msglen + upb_varint_size(msglen);
  10184. }
  10185. return true;
  10186. }
  10187. /* tag_t **********************************************************************/
  10188. /* A precomputed (pre-encoded) tag and length. */
  10189. typedef struct {
  10190. uint8_t bytes;
  10191. char tag[7];
  10192. } tag_t;
  10193. /* Allocates a new tag for this field, and sets it in these handlerattr. */
  10194. static void new_tag(upb_handlers *h, const upb_fielddef *f, upb_wiretype_t wt,
  10195. upb_handlerattr *attr) {
  10196. uint32_t n = upb_fielddef_number(f);
  10197. tag_t *tag = upb_gmalloc(sizeof(tag_t));
  10198. tag->bytes = upb_vencode64((n << 3) | wt, tag->tag);
  10199. upb_handlerattr_init(attr);
  10200. upb_handlerattr_sethandlerdata(attr, tag);
  10201. upb_handlers_addcleanup(h, tag, upb_gfree);
  10202. }
  10203. static bool encode_tag(upb_pb_encoder *e, const tag_t *tag) {
  10204. return encode_bytes(e, tag->tag, tag->bytes);
  10205. }
  10206. /* encoding of wire types *****************************************************/
  10207. static bool encode_fixed64(upb_pb_encoder *e, uint64_t val) {
  10208. /* TODO(haberman): byte-swap for big endian. */
  10209. return encode_bytes(e, &val, sizeof(uint64_t));
  10210. }
  10211. static bool encode_fixed32(upb_pb_encoder *e, uint32_t val) {
  10212. /* TODO(haberman): byte-swap for big endian. */
  10213. return encode_bytes(e, &val, sizeof(uint32_t));
  10214. }
  10215. static bool encode_varint(upb_pb_encoder *e, uint64_t val) {
  10216. if (!reserve(e, UPB_PB_VARINT_MAX_LEN)) {
  10217. return false;
  10218. }
  10219. encoder_advance(e, upb_vencode64(val, e->ptr));
  10220. return true;
  10221. }
  10222. static uint64_t dbl2uint64(double d) {
  10223. uint64_t ret;
  10224. memcpy(&ret, &d, sizeof(uint64_t));
  10225. return ret;
  10226. }
  10227. static uint32_t flt2uint32(float d) {
  10228. uint32_t ret;
  10229. memcpy(&ret, &d, sizeof(uint32_t));
  10230. return ret;
  10231. }
  10232. /* encoding of proto types ****************************************************/
  10233. static bool startmsg(void *c, const void *hd) {
  10234. upb_pb_encoder *e = c;
  10235. UPB_UNUSED(hd);
  10236. if (e->depth++ == 0) {
  10237. upb_bytessink_start(e->output_, 0, &e->subc);
  10238. }
  10239. return true;
  10240. }
  10241. static bool endmsg(void *c, const void *hd, upb_status *status) {
  10242. upb_pb_encoder *e = c;
  10243. UPB_UNUSED(hd);
  10244. UPB_UNUSED(status);
  10245. if (--e->depth == 0) {
  10246. upb_bytessink_end(e->output_);
  10247. }
  10248. return true;
  10249. }
  10250. static void *encode_startdelimfield(void *c, const void *hd) {
  10251. bool ok = encode_tag(c, hd) && commit(c) && start_delim(c);
  10252. return ok ? c : UPB_BREAK;
  10253. }
  10254. static bool encode_unknown(void *c, const void *hd, const char *buf,
  10255. size_t len) {
  10256. UPB_UNUSED(hd);
  10257. return encode_bytes(c, buf, len) && commit(c);
  10258. }
  10259. static bool encode_enddelimfield(void *c, const void *hd) {
  10260. UPB_UNUSED(hd);
  10261. return end_delim(c);
  10262. }
  10263. static void *encode_startgroup(void *c, const void *hd) {
  10264. return (encode_tag(c, hd) && commit(c)) ? c : UPB_BREAK;
  10265. }
  10266. static bool encode_endgroup(void *c, const void *hd) {
  10267. return encode_tag(c, hd) && commit(c);
  10268. }
  10269. static void *encode_startstr(void *c, const void *hd, size_t size_hint) {
  10270. UPB_UNUSED(size_hint);
  10271. return encode_startdelimfield(c, hd);
  10272. }
  10273. static size_t encode_strbuf(void *c, const void *hd, const char *buf,
  10274. size_t len, const upb_bufhandle *h) {
  10275. UPB_UNUSED(hd);
  10276. UPB_UNUSED(h);
  10277. return encode_bytes(c, buf, len) ? len : 0;
  10278. }
  10279. #define T(type, ctype, convert, encode) \
  10280. static bool encode_scalar_##type(void *e, const void *hd, ctype val) { \
  10281. return encode_tag(e, hd) && encode(e, (convert)(val)) && commit(e); \
  10282. } \
  10283. static bool encode_packed_##type(void *e, const void *hd, ctype val) { \
  10284. UPB_UNUSED(hd); \
  10285. return encode(e, (convert)(val)); \
  10286. }
  10287. T(double, double, dbl2uint64, encode_fixed64)
  10288. T(float, float, flt2uint32, encode_fixed32)
  10289. T(int64, int64_t, uint64_t, encode_varint)
  10290. T(int32, int32_t, int64_t, encode_varint)
  10291. T(fixed64, uint64_t, uint64_t, encode_fixed64)
  10292. T(fixed32, uint32_t, uint32_t, encode_fixed32)
  10293. T(bool, bool, bool, encode_varint)
  10294. T(uint32, uint32_t, uint32_t, encode_varint)
  10295. T(uint64, uint64_t, uint64_t, encode_varint)
  10296. T(enum, int32_t, uint32_t, encode_varint)
  10297. T(sfixed32, int32_t, uint32_t, encode_fixed32)
  10298. T(sfixed64, int64_t, uint64_t, encode_fixed64)
  10299. T(sint32, int32_t, upb_zzenc_32, encode_varint)
  10300. T(sint64, int64_t, upb_zzenc_64, encode_varint)
  10301. #undef T
  10302. /* code to build the handlers *************************************************/
  10303. static void newhandlers_callback(const void *closure, upb_handlers *h) {
  10304. const upb_msgdef *m;
  10305. upb_msg_field_iter i;
  10306. UPB_UNUSED(closure);
  10307. upb_handlers_setstartmsg(h, startmsg, NULL);
  10308. upb_handlers_setendmsg(h, endmsg, NULL);
  10309. upb_handlers_setunknown(h, encode_unknown, NULL);
  10310. m = upb_handlers_msgdef(h);
  10311. for(upb_msg_field_begin(&i, m);
  10312. !upb_msg_field_done(&i);
  10313. upb_msg_field_next(&i)) {
  10314. const upb_fielddef *f = upb_msg_iter_field(&i);
  10315. bool packed = upb_fielddef_isseq(f) && upb_fielddef_isprimitive(f) &&
  10316. upb_fielddef_packed(f);
  10317. upb_handlerattr attr;
  10318. upb_wiretype_t wt =
  10319. packed ? UPB_WIRE_TYPE_DELIMITED
  10320. : upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  10321. /* Pre-encode the tag for this field. */
  10322. new_tag(h, f, wt, &attr);
  10323. if (packed) {
  10324. upb_handlers_setstartseq(h, f, encode_startdelimfield, &attr);
  10325. upb_handlers_setendseq(h, f, encode_enddelimfield, &attr);
  10326. }
  10327. #define T(upper, lower, upbtype) \
  10328. case UPB_DESCRIPTOR_TYPE_##upper: \
  10329. if (packed) { \
  10330. upb_handlers_set##upbtype(h, f, encode_packed_##lower, &attr); \
  10331. } else { \
  10332. upb_handlers_set##upbtype(h, f, encode_scalar_##lower, &attr); \
  10333. } \
  10334. break;
  10335. switch (upb_fielddef_descriptortype(f)) {
  10336. T(DOUBLE, double, double);
  10337. T(FLOAT, float, float);
  10338. T(INT64, int64, int64);
  10339. T(INT32, int32, int32);
  10340. T(FIXED64, fixed64, uint64);
  10341. T(FIXED32, fixed32, uint32);
  10342. T(BOOL, bool, bool);
  10343. T(UINT32, uint32, uint32);
  10344. T(UINT64, uint64, uint64);
  10345. T(ENUM, enum, int32);
  10346. T(SFIXED32, sfixed32, int32);
  10347. T(SFIXED64, sfixed64, int64);
  10348. T(SINT32, sint32, int32);
  10349. T(SINT64, sint64, int64);
  10350. case UPB_DESCRIPTOR_TYPE_STRING:
  10351. case UPB_DESCRIPTOR_TYPE_BYTES:
  10352. upb_handlers_setstartstr(h, f, encode_startstr, &attr);
  10353. upb_handlers_setendstr(h, f, encode_enddelimfield, &attr);
  10354. upb_handlers_setstring(h, f, encode_strbuf, &attr);
  10355. break;
  10356. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  10357. upb_handlers_setstartsubmsg(h, f, encode_startdelimfield, &attr);
  10358. upb_handlers_setendsubmsg(h, f, encode_enddelimfield, &attr);
  10359. break;
  10360. case UPB_DESCRIPTOR_TYPE_GROUP: {
  10361. /* Endgroup takes a different tag (wire_type = END_GROUP). */
  10362. upb_handlerattr attr2;
  10363. new_tag(h, f, UPB_WIRE_TYPE_END_GROUP, &attr2);
  10364. upb_handlers_setstartsubmsg(h, f, encode_startgroup, &attr);
  10365. upb_handlers_setendsubmsg(h, f, encode_endgroup, &attr2);
  10366. upb_handlerattr_uninit(&attr2);
  10367. break;
  10368. }
  10369. }
  10370. #undef T
  10371. upb_handlerattr_uninit(&attr);
  10372. }
  10373. }
  10374. void upb_pb_encoder_reset(upb_pb_encoder *e) {
  10375. e->segptr = NULL;
  10376. e->top = NULL;
  10377. e->depth = 0;
  10378. }
  10379. /* public API *****************************************************************/
  10380. const upb_handlers *upb_pb_encoder_newhandlers(const upb_msgdef *m,
  10381. const void *owner) {
  10382. return upb_handlers_newfrozen(m, owner, newhandlers_callback, NULL);
  10383. }
  10384. upb_pb_encoder *upb_pb_encoder_create(upb_env *env, const upb_handlers *h,
  10385. upb_bytessink *output) {
  10386. const size_t initial_bufsize = 256;
  10387. const size_t initial_segbufsize = 16;
  10388. /* TODO(haberman): make this configurable. */
  10389. const size_t stack_size = 64;
  10390. #ifndef NDEBUG
  10391. const size_t size_before = upb_env_bytesallocated(env);
  10392. #endif
  10393. upb_pb_encoder *e = upb_env_malloc(env, sizeof(upb_pb_encoder));
  10394. if (!e) return NULL;
  10395. e->buf = upb_env_malloc(env, initial_bufsize);
  10396. e->segbuf = upb_env_malloc(env, initial_segbufsize * sizeof(*e->segbuf));
  10397. e->stack = upb_env_malloc(env, stack_size * sizeof(*e->stack));
  10398. if (!e->buf || !e->segbuf || !e->stack) {
  10399. return NULL;
  10400. }
  10401. e->limit = e->buf + initial_bufsize;
  10402. e->seglimit = e->segbuf + initial_segbufsize;
  10403. e->stacklimit = e->stack + stack_size;
  10404. upb_pb_encoder_reset(e);
  10405. upb_sink_reset(&e->input_, h, e);
  10406. e->env = env;
  10407. e->output_ = output;
  10408. e->subc = output->closure;
  10409. e->ptr = e->buf;
  10410. /* If this fails, increase the value in encoder.h. */
  10411. UPB_ASSERT_DEBUGVAR(upb_env_bytesallocated(env) - size_before <=
  10412. UPB_PB_ENCODER_SIZE);
  10413. return e;
  10414. }
  10415. upb_sink *upb_pb_encoder_input(upb_pb_encoder *e) { return &e->input_; }
  10416. upb_filedef **upb_loaddescriptor(const char *buf, size_t n, const void *owner,
  10417. upb_status *status) {
  10418. /* Create handlers. */
  10419. const upb_pbdecodermethod *decoder_m;
  10420. const upb_handlers *reader_h = upb_descreader_newhandlers(&reader_h);
  10421. upb_env env;
  10422. upb_pbdecodermethodopts opts;
  10423. upb_pbdecoder *decoder;
  10424. upb_descreader *reader;
  10425. bool ok;
  10426. size_t i;
  10427. upb_filedef **ret = NULL;
  10428. upb_pbdecodermethodopts_init(&opts, reader_h);
  10429. decoder_m = upb_pbdecodermethod_new(&opts, &decoder_m);
  10430. upb_env_init(&env);
  10431. upb_env_reporterrorsto(&env, status);
  10432. reader = upb_descreader_create(&env, reader_h);
  10433. decoder = upb_pbdecoder_create(&env, decoder_m, upb_descreader_input(reader));
  10434. /* Push input data. */
  10435. ok = upb_bufsrc_putbuf(buf, n, upb_pbdecoder_input(decoder));
  10436. if (!ok) {
  10437. goto cleanup;
  10438. }
  10439. ret = upb_gmalloc(sizeof (*ret) * (upb_descreader_filecount(reader) + 1));
  10440. if (!ret) {
  10441. goto cleanup;
  10442. }
  10443. for (i = 0; i < upb_descreader_filecount(reader); i++) {
  10444. ret[i] = upb_descreader_file(reader, i);
  10445. upb_filedef_ref(ret[i], owner);
  10446. }
  10447. ret[i] = NULL;
  10448. cleanup:
  10449. upb_env_uninit(&env);
  10450. upb_handlers_unref(reader_h, &reader_h);
  10451. upb_pbdecodermethod_unref(decoder_m, &decoder_m);
  10452. return ret;
  10453. }
  10454. /*
  10455. * upb::pb::TextPrinter
  10456. *
  10457. * OPT: This is not optimized at all. It uses printf() which parses the format
  10458. * string every time, and it allocates memory for every put.
  10459. */
  10460. #include <ctype.h>
  10461. #include <float.h>
  10462. #include <inttypes.h>
  10463. #include <stdarg.h>
  10464. #include <stdio.h>
  10465. #include <string.h>
  10466. struct upb_textprinter {
  10467. upb_sink input_;
  10468. upb_bytessink *output_;
  10469. int indent_depth_;
  10470. bool single_line_;
  10471. void *subc;
  10472. };
  10473. #define CHECK(x) if ((x) < 0) goto err;
  10474. static const char *shortname(const char *longname) {
  10475. const char *last = strrchr(longname, '.');
  10476. return last ? last + 1 : longname;
  10477. }
  10478. static int indent(upb_textprinter *p) {
  10479. int i;
  10480. if (!p->single_line_)
  10481. for (i = 0; i < p->indent_depth_; i++)
  10482. upb_bytessink_putbuf(p->output_, p->subc, " ", 2, NULL);
  10483. return 0;
  10484. }
  10485. static int endfield(upb_textprinter *p) {
  10486. const char ch = (p->single_line_ ? ' ' : '\n');
  10487. upb_bytessink_putbuf(p->output_, p->subc, &ch, 1, NULL);
  10488. return 0;
  10489. }
  10490. static int putescaped(upb_textprinter *p, const char *buf, size_t len,
  10491. bool preserve_utf8) {
  10492. /* Based on CEscapeInternal() from Google's protobuf release. */
  10493. char dstbuf[4096], *dst = dstbuf, *dstend = dstbuf + sizeof(dstbuf);
  10494. const char *end = buf + len;
  10495. /* I think hex is prettier and more useful, but proto2 uses octal; should
  10496. * investigate whether it can parse hex also. */
  10497. const bool use_hex = false;
  10498. bool last_hex_escape = false; /* true if last output char was \xNN */
  10499. for (; buf < end; buf++) {
  10500. bool is_hex_escape;
  10501. if (dstend - dst < 4) {
  10502. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  10503. dst = dstbuf;
  10504. }
  10505. is_hex_escape = false;
  10506. switch (*buf) {
  10507. case '\n': *(dst++) = '\\'; *(dst++) = 'n'; break;
  10508. case '\r': *(dst++) = '\\'; *(dst++) = 'r'; break;
  10509. case '\t': *(dst++) = '\\'; *(dst++) = 't'; break;
  10510. case '\"': *(dst++) = '\\'; *(dst++) = '\"'; break;
  10511. case '\'': *(dst++) = '\\'; *(dst++) = '\''; break;
  10512. case '\\': *(dst++) = '\\'; *(dst++) = '\\'; break;
  10513. default:
  10514. /* Note that if we emit \xNN and the buf character after that is a hex
  10515. * digit then that digit must be escaped too to prevent it being
  10516. * interpreted as part of the character code by C. */
  10517. if ((!preserve_utf8 || (uint8_t)*buf < 0x80) &&
  10518. (!isprint(*buf) || (last_hex_escape && isxdigit(*buf)))) {
  10519. sprintf(dst, (use_hex ? "\\x%02x" : "\\%03o"), (uint8_t)*buf);
  10520. is_hex_escape = use_hex;
  10521. dst += 4;
  10522. } else {
  10523. *(dst++) = *buf; break;
  10524. }
  10525. }
  10526. last_hex_escape = is_hex_escape;
  10527. }
  10528. /* Flush remaining data. */
  10529. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  10530. return 0;
  10531. }
  10532. bool putf(upb_textprinter *p, const char *fmt, ...) {
  10533. va_list args;
  10534. va_list args_copy;
  10535. char *str;
  10536. int written;
  10537. int len;
  10538. bool ok;
  10539. va_start(args, fmt);
  10540. /* Run once to get the length of the string. */
  10541. _upb_va_copy(args_copy, args);
  10542. len = _upb_vsnprintf(NULL, 0, fmt, args_copy);
  10543. va_end(args_copy);
  10544. /* + 1 for NULL terminator (vsprintf() requires it even if we don't). */
  10545. str = upb_gmalloc(len + 1);
  10546. if (!str) return false;
  10547. written = vsprintf(str, fmt, args);
  10548. va_end(args);
  10549. UPB_ASSERT(written == len);
  10550. ok = upb_bytessink_putbuf(p->output_, p->subc, str, len, NULL);
  10551. upb_gfree(str);
  10552. return ok;
  10553. }
  10554. /* handlers *******************************************************************/
  10555. static bool textprinter_startmsg(void *c, const void *hd) {
  10556. upb_textprinter *p = c;
  10557. UPB_UNUSED(hd);
  10558. if (p->indent_depth_ == 0) {
  10559. upb_bytessink_start(p->output_, 0, &p->subc);
  10560. }
  10561. return true;
  10562. }
  10563. static bool textprinter_endmsg(void *c, const void *hd, upb_status *s) {
  10564. upb_textprinter *p = c;
  10565. UPB_UNUSED(hd);
  10566. UPB_UNUSED(s);
  10567. if (p->indent_depth_ == 0) {
  10568. upb_bytessink_end(p->output_);
  10569. }
  10570. return true;
  10571. }
  10572. #define TYPE(name, ctype, fmt) \
  10573. static bool textprinter_put ## name(void *closure, const void *handler_data, \
  10574. ctype val) { \
  10575. upb_textprinter *p = closure; \
  10576. const upb_fielddef *f = handler_data; \
  10577. CHECK(indent(p)); \
  10578. putf(p, "%s: " fmt, upb_fielddef_name(f), val); \
  10579. CHECK(endfield(p)); \
  10580. return true; \
  10581. err: \
  10582. return false; \
  10583. }
  10584. static bool textprinter_putbool(void *closure, const void *handler_data,
  10585. bool val) {
  10586. upb_textprinter *p = closure;
  10587. const upb_fielddef *f = handler_data;
  10588. CHECK(indent(p));
  10589. putf(p, "%s: %s", upb_fielddef_name(f), val ? "true" : "false");
  10590. CHECK(endfield(p));
  10591. return true;
  10592. err:
  10593. return false;
  10594. }
  10595. #define STRINGIFY_HELPER(x) #x
  10596. #define STRINGIFY_MACROVAL(x) STRINGIFY_HELPER(x)
  10597. TYPE(int32, int32_t, "%" PRId32)
  10598. TYPE(int64, int64_t, "%" PRId64)
  10599. TYPE(uint32, uint32_t, "%" PRIu32)
  10600. TYPE(uint64, uint64_t, "%" PRIu64)
  10601. TYPE(float, float, "%." STRINGIFY_MACROVAL(FLT_DIG) "g")
  10602. TYPE(double, double, "%." STRINGIFY_MACROVAL(DBL_DIG) "g")
  10603. #undef TYPE
  10604. /* Output a symbolic value from the enum if found, else just print as int32. */
  10605. static bool textprinter_putenum(void *closure, const void *handler_data,
  10606. int32_t val) {
  10607. upb_textprinter *p = closure;
  10608. const upb_fielddef *f = handler_data;
  10609. const upb_enumdef *enum_def = upb_downcast_enumdef(upb_fielddef_subdef(f));
  10610. const char *label = upb_enumdef_iton(enum_def, val);
  10611. if (label) {
  10612. indent(p);
  10613. putf(p, "%s: %s", upb_fielddef_name(f), label);
  10614. endfield(p);
  10615. } else {
  10616. if (!textprinter_putint32(closure, handler_data, val))
  10617. return false;
  10618. }
  10619. return true;
  10620. }
  10621. static void *textprinter_startstr(void *closure, const void *handler_data,
  10622. size_t size_hint) {
  10623. upb_textprinter *p = closure;
  10624. const upb_fielddef *f = handler_data;
  10625. UPB_UNUSED(size_hint);
  10626. indent(p);
  10627. putf(p, "%s: \"", upb_fielddef_name(f));
  10628. return p;
  10629. }
  10630. static bool textprinter_endstr(void *closure, const void *handler_data) {
  10631. upb_textprinter *p = closure;
  10632. UPB_UNUSED(handler_data);
  10633. putf(p, "\"");
  10634. endfield(p);
  10635. return true;
  10636. }
  10637. static size_t textprinter_putstr(void *closure, const void *hd, const char *buf,
  10638. size_t len, const upb_bufhandle *handle) {
  10639. upb_textprinter *p = closure;
  10640. const upb_fielddef *f = hd;
  10641. UPB_UNUSED(handle);
  10642. CHECK(putescaped(p, buf, len, upb_fielddef_type(f) == UPB_TYPE_STRING));
  10643. return len;
  10644. err:
  10645. return 0;
  10646. }
  10647. static void *textprinter_startsubmsg(void *closure, const void *handler_data) {
  10648. upb_textprinter *p = closure;
  10649. const char *name = handler_data;
  10650. CHECK(indent(p));
  10651. putf(p, "%s {%c", name, p->single_line_ ? ' ' : '\n');
  10652. p->indent_depth_++;
  10653. return p;
  10654. err:
  10655. return UPB_BREAK;
  10656. }
  10657. static bool textprinter_endsubmsg(void *closure, const void *handler_data) {
  10658. upb_textprinter *p = closure;
  10659. UPB_UNUSED(handler_data);
  10660. p->indent_depth_--;
  10661. CHECK(indent(p));
  10662. upb_bytessink_putbuf(p->output_, p->subc, "}", 1, NULL);
  10663. CHECK(endfield(p));
  10664. return true;
  10665. err:
  10666. return false;
  10667. }
  10668. static void onmreg(const void *c, upb_handlers *h) {
  10669. const upb_msgdef *m = upb_handlers_msgdef(h);
  10670. upb_msg_field_iter i;
  10671. UPB_UNUSED(c);
  10672. upb_handlers_setstartmsg(h, textprinter_startmsg, NULL);
  10673. upb_handlers_setendmsg(h, textprinter_endmsg, NULL);
  10674. for(upb_msg_field_begin(&i, m);
  10675. !upb_msg_field_done(&i);
  10676. upb_msg_field_next(&i)) {
  10677. upb_fielddef *f = upb_msg_iter_field(&i);
  10678. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  10679. upb_handlerattr_sethandlerdata(&attr, f);
  10680. switch (upb_fielddef_type(f)) {
  10681. case UPB_TYPE_INT32:
  10682. upb_handlers_setint32(h, f, textprinter_putint32, &attr);
  10683. break;
  10684. case UPB_TYPE_INT64:
  10685. upb_handlers_setint64(h, f, textprinter_putint64, &attr);
  10686. break;
  10687. case UPB_TYPE_UINT32:
  10688. upb_handlers_setuint32(h, f, textprinter_putuint32, &attr);
  10689. break;
  10690. case UPB_TYPE_UINT64:
  10691. upb_handlers_setuint64(h, f, textprinter_putuint64, &attr);
  10692. break;
  10693. case UPB_TYPE_FLOAT:
  10694. upb_handlers_setfloat(h, f, textprinter_putfloat, &attr);
  10695. break;
  10696. case UPB_TYPE_DOUBLE:
  10697. upb_handlers_setdouble(h, f, textprinter_putdouble, &attr);
  10698. break;
  10699. case UPB_TYPE_BOOL:
  10700. upb_handlers_setbool(h, f, textprinter_putbool, &attr);
  10701. break;
  10702. case UPB_TYPE_STRING:
  10703. case UPB_TYPE_BYTES:
  10704. upb_handlers_setstartstr(h, f, textprinter_startstr, &attr);
  10705. upb_handlers_setstring(h, f, textprinter_putstr, &attr);
  10706. upb_handlers_setendstr(h, f, textprinter_endstr, &attr);
  10707. break;
  10708. case UPB_TYPE_MESSAGE: {
  10709. const char *name =
  10710. upb_fielddef_istagdelim(f)
  10711. ? shortname(upb_msgdef_fullname(upb_fielddef_msgsubdef(f)))
  10712. : upb_fielddef_name(f);
  10713. upb_handlerattr_sethandlerdata(&attr, name);
  10714. upb_handlers_setstartsubmsg(h, f, textprinter_startsubmsg, &attr);
  10715. upb_handlers_setendsubmsg(h, f, textprinter_endsubmsg, &attr);
  10716. break;
  10717. }
  10718. case UPB_TYPE_ENUM:
  10719. upb_handlers_setint32(h, f, textprinter_putenum, &attr);
  10720. break;
  10721. }
  10722. }
  10723. }
  10724. static void textprinter_reset(upb_textprinter *p, bool single_line) {
  10725. p->single_line_ = single_line;
  10726. p->indent_depth_ = 0;
  10727. }
  10728. /* Public API *****************************************************************/
  10729. upb_textprinter *upb_textprinter_create(upb_env *env, const upb_handlers *h,
  10730. upb_bytessink *output) {
  10731. upb_textprinter *p = upb_env_malloc(env, sizeof(upb_textprinter));
  10732. if (!p) return NULL;
  10733. p->output_ = output;
  10734. upb_sink_reset(&p->input_, h, p);
  10735. textprinter_reset(p, false);
  10736. return p;
  10737. }
  10738. const upb_handlers *upb_textprinter_newhandlers(const upb_msgdef *m,
  10739. const void *owner) {
  10740. return upb_handlers_newfrozen(m, owner, &onmreg, NULL);
  10741. }
  10742. upb_sink *upb_textprinter_input(upb_textprinter *p) { return &p->input_; }
  10743. void upb_textprinter_setsingleline(upb_textprinter *p, bool single_line) {
  10744. p->single_line_ = single_line;
  10745. }
  10746. /* Index is descriptor type. */
  10747. const uint8_t upb_pb_native_wire_types[] = {
  10748. UPB_WIRE_TYPE_END_GROUP, /* ENDGROUP */
  10749. UPB_WIRE_TYPE_64BIT, /* DOUBLE */
  10750. UPB_WIRE_TYPE_32BIT, /* FLOAT */
  10751. UPB_WIRE_TYPE_VARINT, /* INT64 */
  10752. UPB_WIRE_TYPE_VARINT, /* UINT64 */
  10753. UPB_WIRE_TYPE_VARINT, /* INT32 */
  10754. UPB_WIRE_TYPE_64BIT, /* FIXED64 */
  10755. UPB_WIRE_TYPE_32BIT, /* FIXED32 */
  10756. UPB_WIRE_TYPE_VARINT, /* BOOL */
  10757. UPB_WIRE_TYPE_DELIMITED, /* STRING */
  10758. UPB_WIRE_TYPE_START_GROUP, /* GROUP */
  10759. UPB_WIRE_TYPE_DELIMITED, /* MESSAGE */
  10760. UPB_WIRE_TYPE_DELIMITED, /* BYTES */
  10761. UPB_WIRE_TYPE_VARINT, /* UINT32 */
  10762. UPB_WIRE_TYPE_VARINT, /* ENUM */
  10763. UPB_WIRE_TYPE_32BIT, /* SFIXED32 */
  10764. UPB_WIRE_TYPE_64BIT, /* SFIXED64 */
  10765. UPB_WIRE_TYPE_VARINT, /* SINT32 */
  10766. UPB_WIRE_TYPE_VARINT, /* SINT64 */
  10767. };
  10768. /* A basic branch-based decoder, uses 32-bit values to get good performance
  10769. * on 32-bit architectures (but performs well on 64-bits also).
  10770. * This scheme comes from the original Google Protobuf implementation
  10771. * (proto2). */
  10772. upb_decoderet upb_vdecode_max8_branch32(upb_decoderet r) {
  10773. upb_decoderet err = {NULL, 0};
  10774. const char *p = r.p;
  10775. uint32_t low = (uint32_t)r.val;
  10776. uint32_t high = 0;
  10777. uint32_t b;
  10778. b = *(p++); low |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  10779. b = *(p++); low |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  10780. b = *(p++); low |= (b & 0x7fU) << 28;
  10781. high = (b & 0x7fU) >> 4; if (!(b & 0x80)) goto done;
  10782. b = *(p++); high |= (b & 0x7fU) << 3; if (!(b & 0x80)) goto done;
  10783. b = *(p++); high |= (b & 0x7fU) << 10; if (!(b & 0x80)) goto done;
  10784. b = *(p++); high |= (b & 0x7fU) << 17; if (!(b & 0x80)) goto done;
  10785. b = *(p++); high |= (b & 0x7fU) << 24; if (!(b & 0x80)) goto done;
  10786. b = *(p++); high |= (b & 0x7fU) << 31; if (!(b & 0x80)) goto done;
  10787. return err;
  10788. done:
  10789. r.val = ((uint64_t)high << 32) | low;
  10790. r.p = p;
  10791. return r;
  10792. }
  10793. /* Like the previous, but uses 64-bit values. */
  10794. upb_decoderet upb_vdecode_max8_branch64(upb_decoderet r) {
  10795. const char *p = r.p;
  10796. uint64_t val = r.val;
  10797. uint64_t b;
  10798. upb_decoderet err = {NULL, 0};
  10799. b = *(p++); val |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  10800. b = *(p++); val |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  10801. b = *(p++); val |= (b & 0x7fU) << 28; if (!(b & 0x80)) goto done;
  10802. b = *(p++); val |= (b & 0x7fU) << 35; if (!(b & 0x80)) goto done;
  10803. b = *(p++); val |= (b & 0x7fU) << 42; if (!(b & 0x80)) goto done;
  10804. b = *(p++); val |= (b & 0x7fU) << 49; if (!(b & 0x80)) goto done;
  10805. b = *(p++); val |= (b & 0x7fU) << 56; if (!(b & 0x80)) goto done;
  10806. b = *(p++); val |= (b & 0x7fU) << 63; if (!(b & 0x80)) goto done;
  10807. return err;
  10808. done:
  10809. r.val = val;
  10810. r.p = p;
  10811. return r;
  10812. }
  10813. #line 1 "upb/json/parser.rl"
  10814. /*
  10815. ** upb::json::Parser (upb_json_parser)
  10816. **
  10817. ** A parser that uses the Ragel State Machine Compiler to generate
  10818. ** the finite automata.
  10819. **
  10820. ** Ragel only natively handles regular languages, but we can manually
  10821. ** program it a bit to handle context-free languages like JSON, by using
  10822. ** the "fcall" and "fret" constructs.
  10823. **
  10824. ** This parser can handle the basics, but needs several things to be fleshed
  10825. ** out:
  10826. **
  10827. ** - handling of unicode escape sequences (including high surrogate pairs).
  10828. ** - properly check and report errors for unknown fields, stack overflow,
  10829. ** improper array nesting (or lack of nesting).
  10830. ** - handling of base64 sequences with padding characters.
  10831. ** - handling of push-back (non-success returns from sink functions).
  10832. ** - handling of keys/escape-sequences/etc that span input buffers.
  10833. */
  10834. #include <ctype.h>
  10835. #include <errno.h>
  10836. #include <float.h>
  10837. #include <math.h>
  10838. #include <stdint.h>
  10839. #include <stdio.h>
  10840. #include <stdlib.h>
  10841. #include <string.h>
  10842. #include <time.h>
  10843. #define UPB_JSON_MAX_DEPTH 64
  10844. /* Type of value message */
  10845. enum {
  10846. VALUE_NULLVALUE = 0,
  10847. VALUE_NUMBERVALUE = 1,
  10848. VALUE_STRINGVALUE = 2,
  10849. VALUE_BOOLVALUE = 3,
  10850. VALUE_STRUCTVALUE = 4,
  10851. VALUE_LISTVALUE = 5
  10852. };
  10853. /* Forward declare */
  10854. static bool is_top_level(upb_json_parser *p);
  10855. static bool is_wellknown_msg(upb_json_parser *p, upb_wellknowntype_t type);
  10856. static bool is_wellknown_field(upb_json_parser *p, upb_wellknowntype_t type);
  10857. static bool is_number_wrapper_object(upb_json_parser *p);
  10858. static bool does_number_wrapper_start(upb_json_parser *p);
  10859. static bool does_number_wrapper_end(upb_json_parser *p);
  10860. static bool is_string_wrapper_object(upb_json_parser *p);
  10861. static bool does_string_wrapper_start(upb_json_parser *p);
  10862. static bool does_string_wrapper_end(upb_json_parser *p);
  10863. static bool is_fieldmask_object(upb_json_parser *p);
  10864. static bool does_fieldmask_start(upb_json_parser *p);
  10865. static bool does_fieldmask_end(upb_json_parser *p);
  10866. static void start_fieldmask_object(upb_json_parser *p);
  10867. static void end_fieldmask_object(upb_json_parser *p);
  10868. static void start_wrapper_object(upb_json_parser *p);
  10869. static void end_wrapper_object(upb_json_parser *p);
  10870. static void start_value_object(upb_json_parser *p, int value_type);
  10871. static void end_value_object(upb_json_parser *p);
  10872. static void start_listvalue_object(upb_json_parser *p);
  10873. static void end_listvalue_object(upb_json_parser *p);
  10874. static void start_structvalue_object(upb_json_parser *p);
  10875. static void end_structvalue_object(upb_json_parser *p);
  10876. static void start_object(upb_json_parser *p);
  10877. static void end_object(upb_json_parser *p);
  10878. static void start_any_object(upb_json_parser *p, const char *ptr);
  10879. static bool end_any_object(upb_json_parser *p, const char *ptr);
  10880. static bool start_subobject(upb_json_parser *p);
  10881. static void end_subobject(upb_json_parser *p);
  10882. static void start_member(upb_json_parser *p);
  10883. static void end_member(upb_json_parser *p);
  10884. static bool end_membername(upb_json_parser *p);
  10885. static void start_any_member(upb_json_parser *p, const char *ptr);
  10886. static void end_any_member(upb_json_parser *p, const char *ptr);
  10887. static bool end_any_membername(upb_json_parser *p);
  10888. size_t parse(void *closure, const void *hd, const char *buf, size_t size,
  10889. const upb_bufhandle *handle);
  10890. static bool end(void *closure, const void *hd);
  10891. static const char eof_ch = 'e';
  10892. /* stringsink */
  10893. typedef struct {
  10894. upb_byteshandler handler;
  10895. upb_bytessink sink;
  10896. char *ptr;
  10897. size_t len, size;
  10898. } upb_stringsink;
  10899. static void *stringsink_start(void *_sink, const void *hd, size_t size_hint) {
  10900. upb_stringsink *sink = _sink;
  10901. sink->len = 0;
  10902. UPB_UNUSED(hd);
  10903. UPB_UNUSED(size_hint);
  10904. return sink;
  10905. }
  10906. static size_t stringsink_string(void *_sink, const void *hd, const char *ptr,
  10907. size_t len, const upb_bufhandle *handle) {
  10908. upb_stringsink *sink = _sink;
  10909. size_t new_size = sink->size;
  10910. UPB_UNUSED(hd);
  10911. UPB_UNUSED(handle);
  10912. while (sink->len + len > new_size) {
  10913. new_size *= 2;
  10914. }
  10915. if (new_size != sink->size) {
  10916. sink->ptr = realloc(sink->ptr, new_size);
  10917. sink->size = new_size;
  10918. }
  10919. memcpy(sink->ptr + sink->len, ptr, len);
  10920. sink->len += len;
  10921. return len;
  10922. }
  10923. void upb_stringsink_init(upb_stringsink *sink) {
  10924. upb_byteshandler_init(&sink->handler);
  10925. upb_byteshandler_setstartstr(&sink->handler, stringsink_start, NULL);
  10926. upb_byteshandler_setstring(&sink->handler, stringsink_string, NULL);
  10927. upb_bytessink_reset(&sink->sink, &sink->handler, sink);
  10928. sink->size = 32;
  10929. sink->ptr = malloc(sink->size);
  10930. sink->len = 0;
  10931. }
  10932. void upb_stringsink_uninit(upb_stringsink *sink) { free(sink->ptr); }
  10933. typedef struct {
  10934. /* For encoding Any value field in binary format. */
  10935. const upb_handlers *encoder_handlers;
  10936. upb_pb_encoder *encoder;
  10937. upb_stringsink stringsink;
  10938. /* For decoding Any value field in json format. */
  10939. upb_json_parsermethod *parser_method;
  10940. upb_json_parser* parser;
  10941. upb_sink sink;
  10942. /* Mark the range of uninterpreted values in json input before type url. */
  10943. const char *before_type_url_start;
  10944. const char *before_type_url_end;
  10945. /* Mark the range of uninterpreted values in json input after type url. */
  10946. const char *after_type_url_start;
  10947. } upb_jsonparser_any_frame;
  10948. typedef struct {
  10949. upb_sink sink;
  10950. /* The current message in which we're parsing, and the field whose value we're
  10951. * expecting next. */
  10952. const upb_msgdef *m;
  10953. const upb_fielddef *f;
  10954. /* The table mapping json name to fielddef for this message. */
  10955. upb_strtable *name_table;
  10956. /* We are in a repeated-field context. We need this flag to decide whether to
  10957. * handle the array as a normal repeated field or a
  10958. * google.protobuf.ListValue/google.protobuf.Value. */
  10959. bool is_repeated;
  10960. /* We are in a repeated-field context, ready to emit mapentries as
  10961. * submessages. This flag alters the start-of-object (open-brace) behavior to
  10962. * begin a sequence of mapentry messages rather than a single submessage. */
  10963. bool is_map;
  10964. /* We are in a map-entry message context. This flag is set when parsing the
  10965. * value field of a single map entry and indicates to all value-field parsers
  10966. * (subobjects, strings, numbers, and bools) that the map-entry submessage
  10967. * should end as soon as the value is parsed. */
  10968. bool is_mapentry;
  10969. /* If |is_map| or |is_mapentry| is true, |mapfield| refers to the parent
  10970. * message's map field that we're currently parsing. This differs from |f|
  10971. * because |f| is the field in the *current* message (i.e., the map-entry
  10972. * message itself), not the parent's field that leads to this map. */
  10973. const upb_fielddef *mapfield;
  10974. /* We are in an Any message context. This flag is set when parsing the Any
  10975. * message and indicates to all field parsers (subobjects, strings, numbers,
  10976. * and bools) that the parsed field should be serialized as binary data or
  10977. * cached (type url not found yet). */
  10978. bool is_any;
  10979. /* The type of packed message in Any. */
  10980. upb_jsonparser_any_frame *any_frame;
  10981. /* True if the field to be parsed is unknown. */
  10982. bool is_unknown_field;
  10983. } upb_jsonparser_frame;
  10984. static void init_frame(upb_jsonparser_frame* frame) {
  10985. frame->m = NULL;
  10986. frame->f = NULL;
  10987. frame->name_table = NULL;
  10988. frame->is_repeated = false;
  10989. frame->is_map = false;
  10990. frame->is_mapentry = false;
  10991. frame->mapfield = NULL;
  10992. frame->is_any = false;
  10993. frame->any_frame = NULL;
  10994. frame->is_unknown_field = false;
  10995. }
  10996. struct upb_json_parser {
  10997. upb_env *env;
  10998. const upb_json_parsermethod *method;
  10999. upb_bytessink input_;
  11000. /* Stack to track the JSON scopes we are in. */
  11001. upb_jsonparser_frame stack[UPB_JSON_MAX_DEPTH];
  11002. upb_jsonparser_frame *top;
  11003. upb_jsonparser_frame *limit;
  11004. upb_status status;
  11005. /* Ragel's internal parsing stack for the parsing state machine. */
  11006. int current_state;
  11007. int parser_stack[UPB_JSON_MAX_DEPTH];
  11008. int parser_top;
  11009. /* The handle for the current buffer. */
  11010. const upb_bufhandle *handle;
  11011. /* Accumulate buffer. See details in parser.rl. */
  11012. const char *accumulated;
  11013. size_t accumulated_len;
  11014. char *accumulate_buf;
  11015. size_t accumulate_buf_size;
  11016. /* Multi-part text data. See details in parser.rl. */
  11017. int multipart_state;
  11018. upb_selector_t string_selector;
  11019. /* Input capture. See details in parser.rl. */
  11020. const char *capture;
  11021. /* Intermediate result of parsing a unicode escape sequence. */
  11022. uint32_t digit;
  11023. /* For resolve type url in Any. */
  11024. const upb_symtab *symtab;
  11025. /* Whether to proceed if unknown field is met. */
  11026. bool ignore_json_unknown;
  11027. /* Cache for parsing timestamp due to base and zone are handled in different
  11028. * handlers. */
  11029. struct tm tm;
  11030. };
  11031. static upb_jsonparser_frame* start_jsonparser_frame(upb_json_parser *p) {
  11032. upb_jsonparser_frame *inner;
  11033. inner = p->top + 1;
  11034. init_frame(inner);
  11035. return inner;
  11036. }
  11037. struct upb_json_parsermethod {
  11038. upb_refcounted base;
  11039. upb_byteshandler input_handler_;
  11040. /* Mainly for the purposes of refcounting, so all the fielddefs we point
  11041. * to stay alive. */
  11042. const upb_msgdef *msg;
  11043. /* Keys are upb_msgdef*, values are upb_strtable (json_name -> fielddef) */
  11044. upb_inttable name_tables;
  11045. };
  11046. #define PARSER_CHECK_RETURN(x) if (!(x)) return false
  11047. static void json_parser_any_frame_reset(upb_jsonparser_any_frame *frame) {
  11048. frame->encoder_handlers = NULL;
  11049. frame->encoder = NULL;
  11050. frame->parser_method = NULL;
  11051. frame->parser = NULL;
  11052. frame->before_type_url_start = NULL;
  11053. frame->before_type_url_end = NULL;
  11054. frame->after_type_url_start = NULL;
  11055. }
  11056. static void json_parser_any_frame_set_payload_type(
  11057. upb_json_parser *p,
  11058. upb_jsonparser_any_frame *frame,
  11059. const upb_msgdef *payload_type) {
  11060. /* Initialize encoder. */
  11061. frame->encoder_handlers =
  11062. upb_pb_encoder_newhandlers(payload_type, &frame->encoder_handlers);
  11063. upb_stringsink_init(&frame->stringsink);
  11064. frame->encoder =
  11065. upb_pb_encoder_create(
  11066. p->env, frame->encoder_handlers,
  11067. &frame->stringsink.sink);
  11068. /* Initialize parser. */
  11069. frame->parser_method =
  11070. upb_json_parsermethod_new(payload_type, &frame->parser_method);
  11071. upb_sink_reset(&frame->sink, frame->encoder_handlers, frame->encoder);
  11072. frame->parser =
  11073. upb_json_parser_create(p->env, frame->parser_method, p->symtab,
  11074. &frame->sink, p->ignore_json_unknown);
  11075. }
  11076. static void json_parser_any_frame_free(upb_jsonparser_any_frame *frame) {
  11077. upb_handlers_unref(frame->encoder_handlers,
  11078. &frame->encoder_handlers);
  11079. upb_json_parsermethod_unref(frame->parser_method,
  11080. &frame->parser_method);
  11081. upb_stringsink_uninit(&frame->stringsink);
  11082. }
  11083. static bool json_parser_any_frame_has_type_url(
  11084. upb_jsonparser_any_frame *frame) {
  11085. return frame->encoder != NULL;
  11086. }
  11087. static bool json_parser_any_frame_has_value_before_type_url(
  11088. upb_jsonparser_any_frame *frame) {
  11089. return frame->before_type_url_start != frame->before_type_url_end;
  11090. }
  11091. static bool json_parser_any_frame_has_value_after_type_url(
  11092. upb_jsonparser_any_frame *frame) {
  11093. return frame->after_type_url_start != NULL;
  11094. }
  11095. static bool json_parser_any_frame_has_value(
  11096. upb_jsonparser_any_frame *frame) {
  11097. return json_parser_any_frame_has_value_before_type_url(frame) ||
  11098. json_parser_any_frame_has_value_after_type_url(frame);
  11099. }
  11100. static void json_parser_any_frame_set_before_type_url_end(
  11101. upb_jsonparser_any_frame *frame,
  11102. const char *ptr) {
  11103. if (frame->encoder == NULL) {
  11104. frame->before_type_url_end = ptr;
  11105. }
  11106. }
  11107. static void json_parser_any_frame_set_after_type_url_start_once(
  11108. upb_jsonparser_any_frame *frame,
  11109. const char *ptr) {
  11110. if (json_parser_any_frame_has_type_url(frame) &&
  11111. frame->after_type_url_start == NULL) {
  11112. frame->after_type_url_start = ptr;
  11113. }
  11114. }
  11115. /* Used to signal that a capture has been suspended. */
  11116. static char suspend_capture;
  11117. static upb_selector_t getsel_for_handlertype(upb_json_parser *p,
  11118. upb_handlertype_t type) {
  11119. upb_selector_t sel;
  11120. bool ok = upb_handlers_getselector(p->top->f, type, &sel);
  11121. UPB_ASSERT(ok);
  11122. return sel;
  11123. }
  11124. static upb_selector_t parser_getsel(upb_json_parser *p) {
  11125. return getsel_for_handlertype(
  11126. p, upb_handlers_getprimitivehandlertype(p->top->f));
  11127. }
  11128. static bool check_stack(upb_json_parser *p) {
  11129. if ((p->top + 1) == p->limit) {
  11130. upb_status_seterrmsg(&p->status, "Nesting too deep");
  11131. upb_env_reporterror(p->env, &p->status);
  11132. return false;
  11133. }
  11134. return true;
  11135. }
  11136. static void set_name_table(upb_json_parser *p, upb_jsonparser_frame *frame) {
  11137. upb_value v;
  11138. bool ok = upb_inttable_lookupptr(&p->method->name_tables, frame->m, &v);
  11139. UPB_ASSERT(ok);
  11140. frame->name_table = upb_value_getptr(v);
  11141. }
  11142. /* There are GCC/Clang built-ins for overflow checking which we could start
  11143. * using if there was any performance benefit to it. */
  11144. static bool checked_add(size_t a, size_t b, size_t *c) {
  11145. if (SIZE_MAX - a < b) return false;
  11146. *c = a + b;
  11147. return true;
  11148. }
  11149. static size_t saturating_multiply(size_t a, size_t b) {
  11150. /* size_t is unsigned, so this is defined behavior even on overflow. */
  11151. size_t ret = a * b;
  11152. if (b != 0 && ret / b != a) {
  11153. ret = SIZE_MAX;
  11154. }
  11155. return ret;
  11156. }
  11157. /* Base64 decoding ************************************************************/
  11158. /* TODO(haberman): make this streaming. */
  11159. static const signed char b64table[] = {
  11160. -1, -1, -1, -1, -1, -1, -1, -1,
  11161. -1, -1, -1, -1, -1, -1, -1, -1,
  11162. -1, -1, -1, -1, -1, -1, -1, -1,
  11163. -1, -1, -1, -1, -1, -1, -1, -1,
  11164. -1, -1, -1, -1, -1, -1, -1, -1,
  11165. -1, -1, -1, 62/*+*/, -1, -1, -1, 63/*/ */,
  11166. 52/*0*/, 53/*1*/, 54/*2*/, 55/*3*/, 56/*4*/, 57/*5*/, 58/*6*/, 59/*7*/,
  11167. 60/*8*/, 61/*9*/, -1, -1, -1, -1, -1, -1,
  11168. -1, 0/*A*/, 1/*B*/, 2/*C*/, 3/*D*/, 4/*E*/, 5/*F*/, 6/*G*/,
  11169. 07/*H*/, 8/*I*/, 9/*J*/, 10/*K*/, 11/*L*/, 12/*M*/, 13/*N*/, 14/*O*/,
  11170. 15/*P*/, 16/*Q*/, 17/*R*/, 18/*S*/, 19/*T*/, 20/*U*/, 21/*V*/, 22/*W*/,
  11171. 23/*X*/, 24/*Y*/, 25/*Z*/, -1, -1, -1, -1, -1,
  11172. -1, 26/*a*/, 27/*b*/, 28/*c*/, 29/*d*/, 30/*e*/, 31/*f*/, 32/*g*/,
  11173. 33/*h*/, 34/*i*/, 35/*j*/, 36/*k*/, 37/*l*/, 38/*m*/, 39/*n*/, 40/*o*/,
  11174. 41/*p*/, 42/*q*/, 43/*r*/, 44/*s*/, 45/*t*/, 46/*u*/, 47/*v*/, 48/*w*/,
  11175. 49/*x*/, 50/*y*/, 51/*z*/, -1, -1, -1, -1, -1,
  11176. -1, -1, -1, -1, -1, -1, -1, -1,
  11177. -1, -1, -1, -1, -1, -1, -1, -1,
  11178. -1, -1, -1, -1, -1, -1, -1, -1,
  11179. -1, -1, -1, -1, -1, -1, -1, -1,
  11180. -1, -1, -1, -1, -1, -1, -1, -1,
  11181. -1, -1, -1, -1, -1, -1, -1, -1,
  11182. -1, -1, -1, -1, -1, -1, -1, -1,
  11183. -1, -1, -1, -1, -1, -1, -1, -1,
  11184. -1, -1, -1, -1, -1, -1, -1, -1,
  11185. -1, -1, -1, -1, -1, -1, -1, -1,
  11186. -1, -1, -1, -1, -1, -1, -1, -1,
  11187. -1, -1, -1, -1, -1, -1, -1, -1,
  11188. -1, -1, -1, -1, -1, -1, -1, -1,
  11189. -1, -1, -1, -1, -1, -1, -1, -1,
  11190. -1, -1, -1, -1, -1, -1, -1, -1,
  11191. -1, -1, -1, -1, -1, -1, -1, -1
  11192. };
  11193. /* Returns the table value sign-extended to 32 bits. Knowing that the upper
  11194. * bits will be 1 for unrecognized characters makes it easier to check for
  11195. * this error condition later (see below). */
  11196. int32_t b64lookup(unsigned char ch) { return b64table[ch]; }
  11197. /* Returns true if the given character is not a valid base64 character or
  11198. * padding. */
  11199. bool nonbase64(unsigned char ch) { return b64lookup(ch) == -1 && ch != '='; }
  11200. static bool base64_push(upb_json_parser *p, upb_selector_t sel, const char *ptr,
  11201. size_t len) {
  11202. const char *limit = ptr + len;
  11203. for (; ptr < limit; ptr += 4) {
  11204. uint32_t val;
  11205. char output[3];
  11206. if (limit - ptr < 4) {
  11207. upb_status_seterrf(&p->status,
  11208. "Base64 input for bytes field not a multiple of 4: %s",
  11209. upb_fielddef_name(p->top->f));
  11210. upb_env_reporterror(p->env, &p->status);
  11211. return false;
  11212. }
  11213. val = b64lookup(ptr[0]) << 18 |
  11214. b64lookup(ptr[1]) << 12 |
  11215. b64lookup(ptr[2]) << 6 |
  11216. b64lookup(ptr[3]);
  11217. /* Test the upper bit; returns true if any of the characters returned -1. */
  11218. if (val & 0x80000000) {
  11219. goto otherchar;
  11220. }
  11221. output[0] = val >> 16;
  11222. output[1] = (val >> 8) & 0xff;
  11223. output[2] = val & 0xff;
  11224. upb_sink_putstring(&p->top->sink, sel, output, 3, NULL);
  11225. }
  11226. return true;
  11227. otherchar:
  11228. if (nonbase64(ptr[0]) || nonbase64(ptr[1]) || nonbase64(ptr[2]) ||
  11229. nonbase64(ptr[3]) ) {
  11230. upb_status_seterrf(&p->status,
  11231. "Non-base64 characters in bytes field: %s",
  11232. upb_fielddef_name(p->top->f));
  11233. upb_env_reporterror(p->env, &p->status);
  11234. return false;
  11235. } if (ptr[2] == '=') {
  11236. uint32_t val;
  11237. char output;
  11238. /* Last group contains only two input bytes, one output byte. */
  11239. if (ptr[0] == '=' || ptr[1] == '=' || ptr[3] != '=') {
  11240. goto badpadding;
  11241. }
  11242. val = b64lookup(ptr[0]) << 18 |
  11243. b64lookup(ptr[1]) << 12;
  11244. UPB_ASSERT(!(val & 0x80000000));
  11245. output = val >> 16;
  11246. upb_sink_putstring(&p->top->sink, sel, &output, 1, NULL);
  11247. return true;
  11248. } else {
  11249. uint32_t val;
  11250. char output[2];
  11251. /* Last group contains only three input bytes, two output bytes. */
  11252. if (ptr[0] == '=' || ptr[1] == '=' || ptr[2] == '=') {
  11253. goto badpadding;
  11254. }
  11255. val = b64lookup(ptr[0]) << 18 |
  11256. b64lookup(ptr[1]) << 12 |
  11257. b64lookup(ptr[2]) << 6;
  11258. output[0] = val >> 16;
  11259. output[1] = (val >> 8) & 0xff;
  11260. upb_sink_putstring(&p->top->sink, sel, output, 2, NULL);
  11261. return true;
  11262. }
  11263. badpadding:
  11264. upb_status_seterrf(&p->status,
  11265. "Incorrect base64 padding for field: %s (%.*s)",
  11266. upb_fielddef_name(p->top->f),
  11267. 4, ptr);
  11268. upb_env_reporterror(p->env, &p->status);
  11269. return false;
  11270. }
  11271. /* Accumulate buffer **********************************************************/
  11272. /* Functionality for accumulating a buffer.
  11273. *
  11274. * Some parts of the parser need an entire value as a contiguous string. For
  11275. * example, to look up a member name in a hash table, or to turn a string into
  11276. * a number, the relevant library routines need the input string to be in
  11277. * contiguous memory, even if the value spanned two or more buffers in the
  11278. * input. These routines handle that.
  11279. *
  11280. * In the common case we can just point to the input buffer to get this
  11281. * contiguous string and avoid any actual copy. So we optimistically begin
  11282. * this way. But there are a few cases where we must instead copy into a
  11283. * separate buffer:
  11284. *
  11285. * 1. The string was not contiguous in the input (it spanned buffers).
  11286. *
  11287. * 2. The string included escape sequences that need to be interpreted to get
  11288. * the true value in a contiguous buffer. */
  11289. static void assert_accumulate_empty(upb_json_parser *p) {
  11290. UPB_ASSERT(p->accumulated == NULL);
  11291. UPB_ASSERT(p->accumulated_len == 0);
  11292. }
  11293. static void accumulate_clear(upb_json_parser *p) {
  11294. p->accumulated = NULL;
  11295. p->accumulated_len = 0;
  11296. }
  11297. /* Used internally by accumulate_append(). */
  11298. static bool accumulate_realloc(upb_json_parser *p, size_t need) {
  11299. void *mem;
  11300. size_t old_size = p->accumulate_buf_size;
  11301. size_t new_size = UPB_MAX(old_size, 128);
  11302. while (new_size < need) {
  11303. new_size = saturating_multiply(new_size, 2);
  11304. }
  11305. mem = upb_env_realloc(p->env, p->accumulate_buf, old_size, new_size);
  11306. if (!mem) {
  11307. upb_status_seterrmsg(&p->status, "Out of memory allocating buffer.");
  11308. upb_env_reporterror(p->env, &p->status);
  11309. return false;
  11310. }
  11311. p->accumulate_buf = mem;
  11312. p->accumulate_buf_size = new_size;
  11313. return true;
  11314. }
  11315. /* Logically appends the given data to the append buffer.
  11316. * If "can_alias" is true, we will try to avoid actually copying, but the buffer
  11317. * must be valid until the next accumulate_append() call (if any). */
  11318. static bool accumulate_append(upb_json_parser *p, const char *buf, size_t len,
  11319. bool can_alias) {
  11320. size_t need;
  11321. if (!p->accumulated && can_alias) {
  11322. p->accumulated = buf;
  11323. p->accumulated_len = len;
  11324. return true;
  11325. }
  11326. if (!checked_add(p->accumulated_len, len, &need)) {
  11327. upb_status_seterrmsg(&p->status, "Integer overflow.");
  11328. upb_env_reporterror(p->env, &p->status);
  11329. return false;
  11330. }
  11331. if (need > p->accumulate_buf_size && !accumulate_realloc(p, need)) {
  11332. return false;
  11333. }
  11334. if (p->accumulated != p->accumulate_buf) {
  11335. memcpy(p->accumulate_buf, p->accumulated, p->accumulated_len);
  11336. p->accumulated = p->accumulate_buf;
  11337. }
  11338. memcpy(p->accumulate_buf + p->accumulated_len, buf, len);
  11339. p->accumulated_len += len;
  11340. return true;
  11341. }
  11342. /* Returns a pointer to the data accumulated since the last accumulate_clear()
  11343. * call, and writes the length to *len. This with point either to the input
  11344. * buffer or a temporary accumulate buffer. */
  11345. static const char *accumulate_getptr(upb_json_parser *p, size_t *len) {
  11346. UPB_ASSERT(p->accumulated);
  11347. *len = p->accumulated_len;
  11348. return p->accumulated;
  11349. }
  11350. /* Mult-part text data ********************************************************/
  11351. /* When we have text data in the input, it can often come in multiple segments.
  11352. * For example, there may be some raw string data followed by an escape
  11353. * sequence. The two segments are processed with different logic. Also buffer
  11354. * seams in the input can cause multiple segments.
  11355. *
  11356. * As we see segments, there are two main cases for how we want to process them:
  11357. *
  11358. * 1. we want to push the captured input directly to string handlers.
  11359. *
  11360. * 2. we need to accumulate all the parts into a contiguous buffer for further
  11361. * processing (field name lookup, string->number conversion, etc). */
  11362. /* This is the set of states for p->multipart_state. */
  11363. enum {
  11364. /* We are not currently processing multipart data. */
  11365. MULTIPART_INACTIVE = 0,
  11366. /* We are processing multipart data by accumulating it into a contiguous
  11367. * buffer. */
  11368. MULTIPART_ACCUMULATE = 1,
  11369. /* We are processing multipart data by pushing each part directly to the
  11370. * current string handlers. */
  11371. MULTIPART_PUSHEAGERLY = 2
  11372. };
  11373. /* Start a multi-part text value where we accumulate the data for processing at
  11374. * the end. */
  11375. static void multipart_startaccum(upb_json_parser *p) {
  11376. assert_accumulate_empty(p);
  11377. UPB_ASSERT(p->multipart_state == MULTIPART_INACTIVE);
  11378. p->multipart_state = MULTIPART_ACCUMULATE;
  11379. }
  11380. /* Start a multi-part text value where we immediately push text data to a string
  11381. * value with the given selector. */
  11382. static void multipart_start(upb_json_parser *p, upb_selector_t sel) {
  11383. assert_accumulate_empty(p);
  11384. UPB_ASSERT(p->multipart_state == MULTIPART_INACTIVE);
  11385. p->multipart_state = MULTIPART_PUSHEAGERLY;
  11386. p->string_selector = sel;
  11387. }
  11388. static bool multipart_text(upb_json_parser *p, const char *buf, size_t len,
  11389. bool can_alias) {
  11390. switch (p->multipart_state) {
  11391. case MULTIPART_INACTIVE:
  11392. upb_status_seterrmsg(
  11393. &p->status, "Internal error: unexpected state MULTIPART_INACTIVE");
  11394. upb_env_reporterror(p->env, &p->status);
  11395. return false;
  11396. case MULTIPART_ACCUMULATE:
  11397. if (!accumulate_append(p, buf, len, can_alias)) {
  11398. return false;
  11399. }
  11400. break;
  11401. case MULTIPART_PUSHEAGERLY: {
  11402. const upb_bufhandle *handle = can_alias ? p->handle : NULL;
  11403. upb_sink_putstring(&p->top->sink, p->string_selector, buf, len, handle);
  11404. break;
  11405. }
  11406. }
  11407. return true;
  11408. }
  11409. /* Note: this invalidates the accumulate buffer! Call only after reading its
  11410. * contents. */
  11411. static void multipart_end(upb_json_parser *p) {
  11412. UPB_ASSERT(p->multipart_state != MULTIPART_INACTIVE);
  11413. p->multipart_state = MULTIPART_INACTIVE;
  11414. accumulate_clear(p);
  11415. }
  11416. /* Input capture **************************************************************/
  11417. /* Functionality for capturing a region of the input as text. Gracefully
  11418. * handles the case where a buffer seam occurs in the middle of the captured
  11419. * region. */
  11420. static void capture_begin(upb_json_parser *p, const char *ptr) {
  11421. UPB_ASSERT(p->multipart_state != MULTIPART_INACTIVE);
  11422. UPB_ASSERT(p->capture == NULL);
  11423. p->capture = ptr;
  11424. }
  11425. static bool capture_end(upb_json_parser *p, const char *ptr) {
  11426. UPB_ASSERT(p->capture);
  11427. if (multipart_text(p, p->capture, ptr - p->capture, true)) {
  11428. p->capture = NULL;
  11429. return true;
  11430. } else {
  11431. return false;
  11432. }
  11433. }
  11434. /* This is called at the end of each input buffer (ie. when we have hit a
  11435. * buffer seam). If we are in the middle of capturing the input, this
  11436. * processes the unprocessed capture region. */
  11437. static void capture_suspend(upb_json_parser *p, const char **ptr) {
  11438. if (!p->capture) return;
  11439. if (multipart_text(p, p->capture, *ptr - p->capture, false)) {
  11440. /* We use this as a signal that we were in the middle of capturing, and
  11441. * that capturing should resume at the beginning of the next buffer.
  11442. *
  11443. * We can't use *ptr here, because we have no guarantee that this pointer
  11444. * will be valid when we resume (if the underlying memory is freed, then
  11445. * using the pointer at all, even to compare to NULL, is likely undefined
  11446. * behavior). */
  11447. p->capture = &suspend_capture;
  11448. } else {
  11449. /* Need to back up the pointer to the beginning of the capture, since
  11450. * we were not able to actually preserve it. */
  11451. *ptr = p->capture;
  11452. }
  11453. }
  11454. static void capture_resume(upb_json_parser *p, const char *ptr) {
  11455. if (p->capture) {
  11456. UPB_ASSERT(p->capture == &suspend_capture);
  11457. p->capture = ptr;
  11458. }
  11459. }
  11460. /* Callbacks from the parser **************************************************/
  11461. /* These are the functions called directly from the parser itself.
  11462. * We define these in the same order as their declarations in the parser. */
  11463. static char escape_char(char in) {
  11464. switch (in) {
  11465. case 'r': return '\r';
  11466. case 't': return '\t';
  11467. case 'n': return '\n';
  11468. case 'f': return '\f';
  11469. case 'b': return '\b';
  11470. case '/': return '/';
  11471. case '"': return '"';
  11472. case '\\': return '\\';
  11473. default:
  11474. UPB_ASSERT(0);
  11475. return 'x';
  11476. }
  11477. }
  11478. static bool escape(upb_json_parser *p, const char *ptr) {
  11479. char ch = escape_char(*ptr);
  11480. return multipart_text(p, &ch, 1, false);
  11481. }
  11482. static void start_hex(upb_json_parser *p) {
  11483. p->digit = 0;
  11484. }
  11485. static void hexdigit(upb_json_parser *p, const char *ptr) {
  11486. char ch = *ptr;
  11487. p->digit <<= 4;
  11488. if (ch >= '0' && ch <= '9') {
  11489. p->digit += (ch - '0');
  11490. } else if (ch >= 'a' && ch <= 'f') {
  11491. p->digit += ((ch - 'a') + 10);
  11492. } else {
  11493. UPB_ASSERT(ch >= 'A' && ch <= 'F');
  11494. p->digit += ((ch - 'A') + 10);
  11495. }
  11496. }
  11497. static bool end_hex(upb_json_parser *p) {
  11498. uint32_t codepoint = p->digit;
  11499. /* emit the codepoint as UTF-8. */
  11500. char utf8[3]; /* support \u0000 -- \uFFFF -- need only three bytes. */
  11501. int length = 0;
  11502. if (codepoint <= 0x7F) {
  11503. utf8[0] = codepoint;
  11504. length = 1;
  11505. } else if (codepoint <= 0x07FF) {
  11506. utf8[1] = (codepoint & 0x3F) | 0x80;
  11507. codepoint >>= 6;
  11508. utf8[0] = (codepoint & 0x1F) | 0xC0;
  11509. length = 2;
  11510. } else /* codepoint <= 0xFFFF */ {
  11511. utf8[2] = (codepoint & 0x3F) | 0x80;
  11512. codepoint >>= 6;
  11513. utf8[1] = (codepoint & 0x3F) | 0x80;
  11514. codepoint >>= 6;
  11515. utf8[0] = (codepoint & 0x0F) | 0xE0;
  11516. length = 3;
  11517. }
  11518. /* TODO(haberman): Handle high surrogates: if codepoint is a high surrogate
  11519. * we have to wait for the next escape to get the full code point). */
  11520. return multipart_text(p, utf8, length, false);
  11521. }
  11522. static void start_text(upb_json_parser *p, const char *ptr) {
  11523. capture_begin(p, ptr);
  11524. }
  11525. static bool end_text(upb_json_parser *p, const char *ptr) {
  11526. return capture_end(p, ptr);
  11527. }
  11528. static bool start_number(upb_json_parser *p, const char *ptr) {
  11529. if (is_top_level(p)) {
  11530. if (is_number_wrapper_object(p)) {
  11531. start_wrapper_object(p);
  11532. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  11533. start_value_object(p, VALUE_NUMBERVALUE);
  11534. } else {
  11535. return false;
  11536. }
  11537. } else if (does_number_wrapper_start(p)) {
  11538. if (!start_subobject(p)) {
  11539. return false;
  11540. }
  11541. start_wrapper_object(p);
  11542. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  11543. if (!start_subobject(p)) {
  11544. return false;
  11545. }
  11546. start_value_object(p, VALUE_NUMBERVALUE);
  11547. }
  11548. multipart_startaccum(p);
  11549. capture_begin(p, ptr);
  11550. return true;
  11551. }
  11552. static bool parse_number(upb_json_parser *p, bool is_quoted);
  11553. static bool end_number_nontop(upb_json_parser *p, const char *ptr) {
  11554. if (!capture_end(p, ptr)) {
  11555. return false;
  11556. }
  11557. if (p->top->f == NULL) {
  11558. multipart_end(p);
  11559. return true;
  11560. }
  11561. return parse_number(p, false);
  11562. }
  11563. static bool end_number(upb_json_parser *p, const char *ptr) {
  11564. if (!end_number_nontop(p, ptr)) {
  11565. return false;
  11566. }
  11567. if (does_number_wrapper_end(p)) {
  11568. end_wrapper_object(p);
  11569. if (!is_top_level(p)) {
  11570. end_subobject(p);
  11571. }
  11572. return true;
  11573. }
  11574. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  11575. end_value_object(p);
  11576. if (!is_top_level(p)) {
  11577. end_subobject(p);
  11578. }
  11579. return true;
  11580. }
  11581. return true;
  11582. }
  11583. /* |buf| is NULL-terminated. |buf| itself will never include quotes;
  11584. * |is_quoted| tells us whether this text originally appeared inside quotes. */
  11585. static bool parse_number_from_buffer(upb_json_parser *p, const char *buf,
  11586. bool is_quoted) {
  11587. size_t len = strlen(buf);
  11588. const char *bufend = buf + len;
  11589. char *end;
  11590. upb_fieldtype_t type = upb_fielddef_type(p->top->f);
  11591. double val;
  11592. double dummy;
  11593. double inf = 1.0 / 0.0; /* C89 does not have an INFINITY macro. */
  11594. errno = 0;
  11595. if (len == 0 || buf[0] == ' ') {
  11596. return false;
  11597. }
  11598. /* For integer types, first try parsing with integer-specific routines.
  11599. * If these succeed, they will be more accurate for int64/uint64 than
  11600. * strtod().
  11601. */
  11602. switch (type) {
  11603. case UPB_TYPE_ENUM:
  11604. case UPB_TYPE_INT32: {
  11605. long val = strtol(buf, &end, 0);
  11606. if (errno == ERANGE || end != bufend) {
  11607. break;
  11608. } else if (val > INT32_MAX || val < INT32_MIN) {
  11609. return false;
  11610. } else {
  11611. upb_sink_putint32(&p->top->sink, parser_getsel(p), val);
  11612. return true;
  11613. }
  11614. }
  11615. case UPB_TYPE_UINT32: {
  11616. unsigned long val = strtoul(buf, &end, 0);
  11617. if (end != bufend) {
  11618. break;
  11619. } else if (val > UINT32_MAX || errno == ERANGE) {
  11620. return false;
  11621. } else {
  11622. upb_sink_putuint32(&p->top->sink, parser_getsel(p), val);
  11623. return true;
  11624. }
  11625. }
  11626. /* XXX: We can't handle [u]int64 properly on 32-bit machines because
  11627. * strto[u]ll isn't in C89. */
  11628. case UPB_TYPE_INT64: {
  11629. long val = strtol(buf, &end, 0);
  11630. if (errno == ERANGE || end != bufend) {
  11631. break;
  11632. } else {
  11633. upb_sink_putint64(&p->top->sink, parser_getsel(p), val);
  11634. return true;
  11635. }
  11636. }
  11637. case UPB_TYPE_UINT64: {
  11638. unsigned long val = strtoul(p->accumulated, &end, 0);
  11639. if (end != bufend) {
  11640. break;
  11641. } else if (errno == ERANGE) {
  11642. return false;
  11643. } else {
  11644. upb_sink_putuint64(&p->top->sink, parser_getsel(p), val);
  11645. return true;
  11646. }
  11647. }
  11648. default:
  11649. break;
  11650. }
  11651. if (type != UPB_TYPE_DOUBLE && type != UPB_TYPE_FLOAT && is_quoted) {
  11652. /* Quoted numbers for integer types are not allowed to be in double form. */
  11653. return false;
  11654. }
  11655. if (len == strlen("Infinity") && strcmp(buf, "Infinity") == 0) {
  11656. /* C89 does not have an INFINITY macro. */
  11657. val = inf;
  11658. } else if (len == strlen("-Infinity") && strcmp(buf, "-Infinity") == 0) {
  11659. val = -inf;
  11660. } else {
  11661. val = strtod(buf, &end);
  11662. if (errno == ERANGE || end != bufend) {
  11663. return false;
  11664. }
  11665. }
  11666. switch (type) {
  11667. #define CASE(capitaltype, smalltype, ctype, min, max) \
  11668. case UPB_TYPE_ ## capitaltype: { \
  11669. if (modf(val, &dummy) != 0 || val > max || val < min) { \
  11670. return false; \
  11671. } else { \
  11672. upb_sink_put ## smalltype(&p->top->sink, parser_getsel(p), \
  11673. (ctype)val); \
  11674. return true; \
  11675. } \
  11676. break; \
  11677. }
  11678. case UPB_TYPE_ENUM:
  11679. CASE(INT32, int32, int32_t, INT32_MIN, INT32_MAX);
  11680. CASE(INT64, int64, int64_t, INT64_MIN, INT64_MAX);
  11681. CASE(UINT32, uint32, uint32_t, 0, UINT32_MAX);
  11682. CASE(UINT64, uint64, uint64_t, 0, UINT64_MAX);
  11683. #undef CASE
  11684. case UPB_TYPE_DOUBLE:
  11685. upb_sink_putdouble(&p->top->sink, parser_getsel(p), val);
  11686. return true;
  11687. case UPB_TYPE_FLOAT:
  11688. if ((val > FLT_MAX || val < -FLT_MAX) && val != inf && val != -inf) {
  11689. return false;
  11690. } else {
  11691. upb_sink_putfloat(&p->top->sink, parser_getsel(p), val);
  11692. return true;
  11693. }
  11694. default:
  11695. return false;
  11696. }
  11697. }
  11698. static bool parse_number(upb_json_parser *p, bool is_quoted) {
  11699. size_t len;
  11700. const char *buf;
  11701. /* strtol() and friends unfortunately do not support specifying the length of
  11702. * the input string, so we need to force a copy into a NULL-terminated buffer. */
  11703. if (!multipart_text(p, "\0", 1, false)) {
  11704. return false;
  11705. }
  11706. buf = accumulate_getptr(p, &len);
  11707. if (parse_number_from_buffer(p, buf, is_quoted)) {
  11708. multipart_end(p);
  11709. return true;
  11710. } else {
  11711. upb_status_seterrf(&p->status, "error parsing number: %s", buf);
  11712. upb_env_reporterror(p->env, &p->status);
  11713. multipart_end(p);
  11714. return false;
  11715. }
  11716. }
  11717. static bool parser_putbool(upb_json_parser *p, bool val) {
  11718. bool ok;
  11719. if (p->top->f == NULL) {
  11720. return true;
  11721. }
  11722. if (upb_fielddef_type(p->top->f) != UPB_TYPE_BOOL) {
  11723. upb_status_seterrf(&p->status,
  11724. "Boolean value specified for non-bool field: %s",
  11725. upb_fielddef_name(p->top->f));
  11726. upb_env_reporterror(p->env, &p->status);
  11727. return false;
  11728. }
  11729. ok = upb_sink_putbool(&p->top->sink, parser_getsel(p), val);
  11730. UPB_ASSERT(ok);
  11731. return true;
  11732. }
  11733. static bool end_bool(upb_json_parser *p, bool val) {
  11734. if (is_top_level(p)) {
  11735. if (is_wellknown_msg(p, UPB_WELLKNOWN_BOOLVALUE)) {
  11736. start_wrapper_object(p);
  11737. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  11738. start_value_object(p, VALUE_BOOLVALUE);
  11739. } else {
  11740. return false;
  11741. }
  11742. } else if (is_wellknown_field(p, UPB_WELLKNOWN_BOOLVALUE)) {
  11743. if (!start_subobject(p)) {
  11744. return false;
  11745. }
  11746. start_wrapper_object(p);
  11747. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  11748. if (!start_subobject(p)) {
  11749. return false;
  11750. }
  11751. start_value_object(p, VALUE_BOOLVALUE);
  11752. }
  11753. if (p->top->is_unknown_field) {
  11754. return true;
  11755. }
  11756. if (!parser_putbool(p, val)) {
  11757. return false;
  11758. }
  11759. if (is_wellknown_msg(p, UPB_WELLKNOWN_BOOLVALUE)) {
  11760. end_wrapper_object(p);
  11761. if (!is_top_level(p)) {
  11762. end_subobject(p);
  11763. }
  11764. return true;
  11765. }
  11766. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  11767. end_value_object(p);
  11768. if (!is_top_level(p)) {
  11769. end_subobject(p);
  11770. }
  11771. return true;
  11772. }
  11773. return true;
  11774. }
  11775. static bool end_null(upb_json_parser *p) {
  11776. const char *zero_ptr = "0";
  11777. if (is_top_level(p)) {
  11778. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  11779. start_value_object(p, VALUE_NULLVALUE);
  11780. } else {
  11781. return true;
  11782. }
  11783. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  11784. if (!start_subobject(p)) {
  11785. return false;
  11786. }
  11787. start_value_object(p, VALUE_NULLVALUE);
  11788. } else {
  11789. return true;
  11790. }
  11791. /* Fill null_value field. */
  11792. multipart_startaccum(p);
  11793. capture_begin(p, zero_ptr);
  11794. capture_end(p, zero_ptr + 1);
  11795. parse_number(p, false);
  11796. end_value_object(p);
  11797. if (!is_top_level(p)) {
  11798. end_subobject(p);
  11799. }
  11800. return true;
  11801. }
  11802. static bool start_any_stringval(upb_json_parser *p) {
  11803. multipart_startaccum(p);
  11804. return true;
  11805. }
  11806. static bool start_stringval(upb_json_parser *p) {
  11807. if (is_top_level(p)) {
  11808. if (is_string_wrapper_object(p)) {
  11809. start_wrapper_object(p);
  11810. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_FIELDMASK)) {
  11811. start_fieldmask_object(p);
  11812. return true;
  11813. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_TIMESTAMP) ||
  11814. is_wellknown_msg(p, UPB_WELLKNOWN_DURATION)) {
  11815. start_object(p);
  11816. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  11817. start_value_object(p, VALUE_STRINGVALUE);
  11818. } else {
  11819. return false;
  11820. }
  11821. } else if (does_string_wrapper_start(p)) {
  11822. if (!start_subobject(p)) {
  11823. return false;
  11824. }
  11825. start_wrapper_object(p);
  11826. } else if (does_fieldmask_start(p)) {
  11827. if (!start_subobject(p)) {
  11828. return false;
  11829. }
  11830. start_fieldmask_object(p);
  11831. return true;
  11832. } else if (is_wellknown_field(p, UPB_WELLKNOWN_TIMESTAMP) ||
  11833. is_wellknown_field(p, UPB_WELLKNOWN_DURATION)) {
  11834. if (!start_subobject(p)) {
  11835. return false;
  11836. }
  11837. start_object(p);
  11838. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  11839. if (!start_subobject(p)) {
  11840. return false;
  11841. }
  11842. start_value_object(p, VALUE_STRINGVALUE);
  11843. }
  11844. if (p->top->f == NULL) {
  11845. multipart_startaccum(p);
  11846. return true;
  11847. }
  11848. if (p->top->is_any) {
  11849. return start_any_stringval(p);
  11850. }
  11851. if (upb_fielddef_isstring(p->top->f)) {
  11852. upb_jsonparser_frame *inner;
  11853. upb_selector_t sel;
  11854. if (!check_stack(p)) return false;
  11855. /* Start a new parser frame: parser frames correspond one-to-one with
  11856. * handler frames, and string events occur in a sub-frame. */
  11857. inner = start_jsonparser_frame(p);
  11858. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  11859. upb_sink_startstr(&p->top->sink, sel, 0, &inner->sink);
  11860. inner->m = p->top->m;
  11861. inner->f = p->top->f;
  11862. p->top = inner;
  11863. if (upb_fielddef_type(p->top->f) == UPB_TYPE_STRING) {
  11864. /* For STRING fields we push data directly to the handlers as it is
  11865. * parsed. We don't do this yet for BYTES fields, because our base64
  11866. * decoder is not streaming.
  11867. *
  11868. * TODO(haberman): make base64 decoding streaming also. */
  11869. multipart_start(p, getsel_for_handlertype(p, UPB_HANDLER_STRING));
  11870. return true;
  11871. } else {
  11872. multipart_startaccum(p);
  11873. return true;
  11874. }
  11875. } else if (upb_fielddef_type(p->top->f) != UPB_TYPE_BOOL &&
  11876. upb_fielddef_type(p->top->f) != UPB_TYPE_MESSAGE) {
  11877. /* No need to push a frame -- numeric values in quotes remain in the
  11878. * current parser frame. These values must accmulate so we can convert
  11879. * them all at once at the end. */
  11880. multipart_startaccum(p);
  11881. return true;
  11882. } else {
  11883. upb_status_seterrf(&p->status,
  11884. "String specified for bool or submessage field: %s",
  11885. upb_fielddef_name(p->top->f));
  11886. upb_env_reporterror(p->env, &p->status);
  11887. return false;
  11888. }
  11889. }
  11890. static bool end_any_stringval(upb_json_parser *p) {
  11891. size_t len;
  11892. const char *buf = accumulate_getptr(p, &len);
  11893. /* Set type_url */
  11894. upb_selector_t sel;
  11895. upb_jsonparser_frame *inner;
  11896. if (!check_stack(p)) return false;
  11897. inner = p->top + 1;
  11898. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  11899. upb_sink_startstr(&p->top->sink, sel, 0, &inner->sink);
  11900. sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
  11901. upb_sink_putstring(&inner->sink, sel, buf, len, NULL);
  11902. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  11903. upb_sink_endstr(&inner->sink, sel);
  11904. multipart_end(p);
  11905. /* Resolve type url */
  11906. if (strncmp(buf, "type.googleapis.com/", 20) == 0 && len > 20) {
  11907. const upb_msgdef *payload_type = NULL;
  11908. buf += 20;
  11909. len -= 20;
  11910. payload_type = upb_symtab_lookupmsg2(p->symtab, buf, len);
  11911. if (payload_type == NULL) {
  11912. upb_status_seterrf(
  11913. &p->status, "Cannot find packed type: %.*s\n", (int)len, buf);
  11914. upb_env_reporterror(p->env, &p->status);
  11915. return false;
  11916. }
  11917. json_parser_any_frame_set_payload_type(p, p->top->any_frame, payload_type);
  11918. return true;
  11919. } else {
  11920. upb_status_seterrf(
  11921. &p->status, "Invalid type url: %.*s\n", (int)len, buf);
  11922. upb_env_reporterror(p->env, &p->status);
  11923. return false;
  11924. }
  11925. }
  11926. static bool end_stringval_nontop(upb_json_parser *p) {
  11927. bool ok = true;
  11928. if (is_wellknown_msg(p, UPB_WELLKNOWN_TIMESTAMP) ||
  11929. is_wellknown_msg(p, UPB_WELLKNOWN_DURATION)) {
  11930. multipart_end(p);
  11931. return true;
  11932. }
  11933. if (p->top->f == NULL) {
  11934. multipart_end(p);
  11935. return true;
  11936. }
  11937. if (p->top->is_any) {
  11938. return end_any_stringval(p);
  11939. }
  11940. switch (upb_fielddef_type(p->top->f)) {
  11941. case UPB_TYPE_BYTES:
  11942. if (!base64_push(p, getsel_for_handlertype(p, UPB_HANDLER_STRING),
  11943. p->accumulated, p->accumulated_len)) {
  11944. return false;
  11945. }
  11946. /* Fall through. */
  11947. case UPB_TYPE_STRING: {
  11948. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  11949. upb_sink_endstr(&p->top->sink, sel);
  11950. p->top--;
  11951. break;
  11952. }
  11953. case UPB_TYPE_ENUM: {
  11954. /* Resolve enum symbolic name to integer value. */
  11955. const upb_enumdef *enumdef =
  11956. (const upb_enumdef*)upb_fielddef_subdef(p->top->f);
  11957. size_t len;
  11958. const char *buf = accumulate_getptr(p, &len);
  11959. int32_t int_val = 0;
  11960. ok = upb_enumdef_ntoi(enumdef, buf, len, &int_val);
  11961. if (ok) {
  11962. upb_selector_t sel = parser_getsel(p);
  11963. upb_sink_putint32(&p->top->sink, sel, int_val);
  11964. } else {
  11965. upb_status_seterrf(&p->status, "Enum value unknown: '%.*s'", len, buf);
  11966. upb_env_reporterror(p->env, &p->status);
  11967. }
  11968. break;
  11969. }
  11970. case UPB_TYPE_INT32:
  11971. case UPB_TYPE_INT64:
  11972. case UPB_TYPE_UINT32:
  11973. case UPB_TYPE_UINT64:
  11974. case UPB_TYPE_DOUBLE:
  11975. case UPB_TYPE_FLOAT:
  11976. ok = parse_number(p, true);
  11977. break;
  11978. default:
  11979. UPB_ASSERT(false);
  11980. upb_status_seterrmsg(&p->status, "Internal error in JSON decoder");
  11981. upb_env_reporterror(p->env, &p->status);
  11982. ok = false;
  11983. break;
  11984. }
  11985. multipart_end(p);
  11986. return ok;
  11987. }
  11988. static bool end_stringval(upb_json_parser *p) {
  11989. /* FieldMask's stringvals have been ended when handling them. Only need to
  11990. * close FieldMask here.*/
  11991. if (does_fieldmask_end(p)) {
  11992. end_fieldmask_object(p);
  11993. if (!is_top_level(p)) {
  11994. end_subobject(p);
  11995. }
  11996. return true;
  11997. }
  11998. if (!end_stringval_nontop(p)) {
  11999. return false;
  12000. }
  12001. if (does_string_wrapper_end(p)) {
  12002. end_wrapper_object(p);
  12003. if (!is_top_level(p)) {
  12004. end_subobject(p);
  12005. }
  12006. return true;
  12007. }
  12008. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  12009. end_value_object(p);
  12010. if (!is_top_level(p)) {
  12011. end_subobject(p);
  12012. }
  12013. return true;
  12014. }
  12015. if (is_wellknown_msg(p, UPB_WELLKNOWN_TIMESTAMP) ||
  12016. is_wellknown_msg(p, UPB_WELLKNOWN_DURATION) ||
  12017. is_wellknown_msg(p, UPB_WELLKNOWN_FIELDMASK)) {
  12018. end_object(p);
  12019. if (!is_top_level(p)) {
  12020. end_subobject(p);
  12021. }
  12022. return true;
  12023. }
  12024. return true;
  12025. }
  12026. static void start_duration_base(upb_json_parser *p, const char *ptr) {
  12027. capture_begin(p, ptr);
  12028. }
  12029. static bool end_duration_base(upb_json_parser *p, const char *ptr) {
  12030. size_t len;
  12031. const char *buf;
  12032. char seconds_buf[14];
  12033. char nanos_buf[12];
  12034. char *end;
  12035. int64_t seconds = 0;
  12036. int32_t nanos = 0;
  12037. double val = 0.0;
  12038. const char *seconds_membername = "seconds";
  12039. const char *nanos_membername = "nanos";
  12040. size_t fraction_start;
  12041. if (!capture_end(p, ptr)) {
  12042. return false;
  12043. }
  12044. buf = accumulate_getptr(p, &len);
  12045. memset(seconds_buf, 0, 14);
  12046. memset(nanos_buf, 0, 12);
  12047. /* Find out base end. The maximus duration is 315576000000, which cannot be
  12048. * represented by double without losing precision. Thus, we need to handle
  12049. * fraction and base separately. */
  12050. for (fraction_start = 0; fraction_start < len && buf[fraction_start] != '.';
  12051. fraction_start++);
  12052. /* Parse base */
  12053. memcpy(seconds_buf, buf, fraction_start);
  12054. seconds = strtol(seconds_buf, &end, 10);
  12055. if (errno == ERANGE || end != seconds_buf + fraction_start) {
  12056. upb_status_seterrf(&p->status, "error parsing duration: %s",
  12057. seconds_buf);
  12058. upb_env_reporterror(p->env, &p->status);
  12059. return false;
  12060. }
  12061. if (seconds > 315576000000) {
  12062. upb_status_seterrf(&p->status, "error parsing duration: "
  12063. "maximum acceptable value is "
  12064. "315576000000");
  12065. upb_env_reporterror(p->env, &p->status);
  12066. return false;
  12067. }
  12068. if (seconds < -315576000000) {
  12069. upb_status_seterrf(&p->status, "error parsing duration: "
  12070. "minimum acceptable value is "
  12071. "-315576000000");
  12072. upb_env_reporterror(p->env, &p->status);
  12073. return false;
  12074. }
  12075. /* Parse fraction */
  12076. nanos_buf[0] = '0';
  12077. memcpy(nanos_buf + 1, buf + fraction_start, len - fraction_start);
  12078. val = strtod(nanos_buf, &end);
  12079. if (errno == ERANGE || end != nanos_buf + len - fraction_start + 1) {
  12080. upb_status_seterrf(&p->status, "error parsing duration: %s",
  12081. nanos_buf);
  12082. upb_env_reporterror(p->env, &p->status);
  12083. return false;
  12084. }
  12085. nanos = val * 1000000000;
  12086. if (seconds < 0) nanos = -nanos;
  12087. /* Clean up buffer */
  12088. multipart_end(p);
  12089. /* Set seconds */
  12090. start_member(p);
  12091. capture_begin(p, seconds_membername);
  12092. capture_end(p, seconds_membername + 7);
  12093. end_membername(p);
  12094. upb_sink_putint64(&p->top->sink, parser_getsel(p), seconds);
  12095. end_member(p);
  12096. /* Set nanos */
  12097. start_member(p);
  12098. capture_begin(p, nanos_membername);
  12099. capture_end(p, nanos_membername + 5);
  12100. end_membername(p);
  12101. upb_sink_putint32(&p->top->sink, parser_getsel(p), nanos);
  12102. end_member(p);
  12103. /* Continue previous environment */
  12104. multipart_startaccum(p);
  12105. return true;
  12106. }
  12107. static int parse_timestamp_number(upb_json_parser *p) {
  12108. size_t len;
  12109. const char *buf;
  12110. char *end;
  12111. int val;
  12112. /* atoi() and friends unfortunately do not support specifying the length of
  12113. * the input string, so we need to force a copy into a NULL-terminated buffer. */
  12114. multipart_text(p, "\0", 1, false);
  12115. buf = accumulate_getptr(p, &len);
  12116. val = atoi(buf);
  12117. multipart_end(p);
  12118. multipart_startaccum(p);
  12119. return val;
  12120. }
  12121. static void start_year(upb_json_parser *p, const char *ptr) {
  12122. capture_begin(p, ptr);
  12123. }
  12124. static bool end_year(upb_json_parser *p, const char *ptr) {
  12125. if (!capture_end(p, ptr)) {
  12126. return false;
  12127. }
  12128. p->tm.tm_year = parse_timestamp_number(p) - 1900;
  12129. return true;
  12130. }
  12131. static void start_month(upb_json_parser *p, const char *ptr) {
  12132. capture_begin(p, ptr);
  12133. }
  12134. static bool end_month(upb_json_parser *p, const char *ptr) {
  12135. if (!capture_end(p, ptr)) {
  12136. return false;
  12137. }
  12138. p->tm.tm_mon = parse_timestamp_number(p) - 1;
  12139. return true;
  12140. }
  12141. static void start_day(upb_json_parser *p, const char *ptr) {
  12142. capture_begin(p, ptr);
  12143. }
  12144. static bool end_day(upb_json_parser *p, const char *ptr) {
  12145. if (!capture_end(p, ptr)) {
  12146. return false;
  12147. }
  12148. p->tm.tm_mday = parse_timestamp_number(p);
  12149. return true;
  12150. }
  12151. static void start_hour(upb_json_parser *p, const char *ptr) {
  12152. capture_begin(p, ptr);
  12153. }
  12154. static bool end_hour(upb_json_parser *p, const char *ptr) {
  12155. if (!capture_end(p, ptr)) {
  12156. return false;
  12157. }
  12158. p->tm.tm_hour = parse_timestamp_number(p);
  12159. return true;
  12160. }
  12161. static void start_minute(upb_json_parser *p, const char *ptr) {
  12162. capture_begin(p, ptr);
  12163. }
  12164. static bool end_minute(upb_json_parser *p, const char *ptr) {
  12165. if (!capture_end(p, ptr)) {
  12166. return false;
  12167. }
  12168. p->tm.tm_min = parse_timestamp_number(p);
  12169. return true;
  12170. }
  12171. static void start_second(upb_json_parser *p, const char *ptr) {
  12172. capture_begin(p, ptr);
  12173. }
  12174. static bool end_second(upb_json_parser *p, const char *ptr) {
  12175. if (!capture_end(p, ptr)) {
  12176. return false;
  12177. }
  12178. p->tm.tm_sec = parse_timestamp_number(p);
  12179. return true;
  12180. }
  12181. static void start_timestamp_base(upb_json_parser *p) {
  12182. memset(&p->tm, 0, sizeof(struct tm));
  12183. }
  12184. static void start_timestamp_fraction(upb_json_parser *p, const char *ptr) {
  12185. capture_begin(p, ptr);
  12186. }
  12187. static bool end_timestamp_fraction(upb_json_parser *p, const char *ptr) {
  12188. size_t len;
  12189. const char *buf;
  12190. char nanos_buf[12];
  12191. char *end;
  12192. double val = 0.0;
  12193. int32_t nanos;
  12194. const char *nanos_membername = "nanos";
  12195. memset(nanos_buf, 0, 12);
  12196. if (!capture_end(p, ptr)) {
  12197. return false;
  12198. }
  12199. buf = accumulate_getptr(p, &len);
  12200. if (len > 10) {
  12201. upb_status_seterrf(&p->status,
  12202. "error parsing timestamp: at most 9-digit fraction.");
  12203. upb_env_reporterror(p->env, &p->status);
  12204. return false;
  12205. }
  12206. /* Parse nanos */
  12207. nanos_buf[0] = '0';
  12208. memcpy(nanos_buf + 1, buf, len);
  12209. val = strtod(nanos_buf, &end);
  12210. if (errno == ERANGE || end != nanos_buf + len + 1) {
  12211. upb_status_seterrf(&p->status, "error parsing timestamp nanos: %s",
  12212. nanos_buf);
  12213. upb_env_reporterror(p->env, &p->status);
  12214. return false;
  12215. }
  12216. nanos = val * 1000000000;
  12217. /* Clean up previous environment */
  12218. multipart_end(p);
  12219. /* Set nanos */
  12220. start_member(p);
  12221. capture_begin(p, nanos_membername);
  12222. capture_end(p, nanos_membername + 5);
  12223. end_membername(p);
  12224. upb_sink_putint32(&p->top->sink, parser_getsel(p), nanos);
  12225. end_member(p);
  12226. /* Continue previous environment */
  12227. multipart_startaccum(p);
  12228. return true;
  12229. }
  12230. static void start_timestamp_zone(upb_json_parser *p, const char *ptr) {
  12231. capture_begin(p, ptr);
  12232. }
  12233. #define EPOCH_YEAR 1970
  12234. #define TM_YEAR_BASE 1900
  12235. static bool isleap(int year) {
  12236. return (year % 4) == 0 && (year % 100 != 0 || (year % 400) == 0);
  12237. }
  12238. const unsigned short int __mon_yday[2][13] = {
  12239. /* Normal years. */
  12240. { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 },
  12241. /* Leap years. */
  12242. { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }
  12243. };
  12244. int64_t epoch(int year, int yday, int hour, int min, int sec) {
  12245. int64_t years = year - EPOCH_YEAR;
  12246. int64_t leap_days = years / 4 - years / 100 + years / 400;
  12247. int64_t days = years * 365 + yday + leap_days;
  12248. int64_t hours = days * 24 + hour;
  12249. int64_t mins = hours * 60 + min;
  12250. int64_t secs = mins * 60 + sec;
  12251. return secs;
  12252. }
  12253. static int64_t upb_mktime(const struct tm *tp) {
  12254. int sec = tp->tm_sec;
  12255. int min = tp->tm_min;
  12256. int hour = tp->tm_hour;
  12257. int mday = tp->tm_mday;
  12258. int mon = tp->tm_mon;
  12259. int year = tp->tm_year + TM_YEAR_BASE;
  12260. /* Calculate day of year from year, month, and day of month. */
  12261. int mon_yday = ((__mon_yday[isleap(year)][mon]) - 1);
  12262. int yday = mon_yday + mday;
  12263. return epoch(year, yday, hour, min, sec);
  12264. }
  12265. static bool end_timestamp_zone(upb_json_parser *p, const char *ptr) {
  12266. size_t len;
  12267. const char *buf;
  12268. int hours = 0;
  12269. int64_t seconds;
  12270. const char *seconds_membername = "seconds";
  12271. if (!capture_end(p, ptr)) {
  12272. return false;
  12273. }
  12274. buf = accumulate_getptr(p, &len);
  12275. if (buf[0] != 'Z') {
  12276. if (sscanf(buf + 1, "%2d:00", &hours) != 1) {
  12277. upb_status_seterrf(&p->status, "error parsing timestamp offset");
  12278. upb_env_reporterror(p->env, &p->status);
  12279. return false;
  12280. }
  12281. if (buf[0] == '+') {
  12282. hours = -hours;
  12283. }
  12284. }
  12285. /* Normalize tm */
  12286. seconds = upb_mktime(&p->tm);
  12287. seconds += 3600 * hours;
  12288. /* Check timestamp boundary */
  12289. if (seconds < -62135596800) {
  12290. upb_status_seterrf(&p->status, "error parsing timestamp: "
  12291. "minimum acceptable value is "
  12292. "0001-01-01T00:00:00Z");
  12293. upb_env_reporterror(p->env, &p->status);
  12294. return false;
  12295. }
  12296. /* Clean up previous environment */
  12297. multipart_end(p);
  12298. /* Set seconds */
  12299. start_member(p);
  12300. capture_begin(p, seconds_membername);
  12301. capture_end(p, seconds_membername + 7);
  12302. end_membername(p);
  12303. upb_sink_putint64(&p->top->sink, parser_getsel(p), seconds);
  12304. end_member(p);
  12305. /* Continue previous environment */
  12306. multipart_startaccum(p);
  12307. return true;
  12308. }
  12309. static void start_fieldmask_path_text(upb_json_parser *p, const char *ptr) {
  12310. capture_begin(p, ptr);
  12311. }
  12312. static bool end_fieldmask_path_text(upb_json_parser *p, const char *ptr) {
  12313. if (!capture_end(p, ptr)) {
  12314. return false;
  12315. }
  12316. }
  12317. static bool start_fieldmask_path(upb_json_parser *p) {
  12318. upb_jsonparser_frame *inner;
  12319. upb_selector_t sel;
  12320. if (!check_stack(p)) return false;
  12321. /* Start a new parser frame: parser frames correspond one-to-one with
  12322. * handler frames, and string events occur in a sub-frame. */
  12323. inner = start_jsonparser_frame(p);
  12324. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  12325. upb_sink_startstr(&p->top->sink, sel, 0, &inner->sink);
  12326. inner->m = p->top->m;
  12327. inner->f = p->top->f;
  12328. p->top = inner;
  12329. multipart_startaccum(p);
  12330. return true;
  12331. }
  12332. static bool lower_camel_push(
  12333. upb_json_parser *p, upb_selector_t sel, const char *ptr, size_t len) {
  12334. const char *limit = ptr + len;
  12335. bool first = true;
  12336. for (;ptr < limit; ptr++) {
  12337. if (*ptr >= 'A' && *ptr <= 'Z' && !first) {
  12338. char lower = tolower(*ptr);
  12339. upb_sink_putstring(&p->top->sink, sel, "_", 1, NULL);
  12340. upb_sink_putstring(&p->top->sink, sel, &lower, 1, NULL);
  12341. } else {
  12342. upb_sink_putstring(&p->top->sink, sel, ptr, 1, NULL);
  12343. }
  12344. first = false;
  12345. }
  12346. return true;
  12347. }
  12348. static bool end_fieldmask_path(upb_json_parser *p) {
  12349. upb_selector_t sel;
  12350. if (!lower_camel_push(
  12351. p, getsel_for_handlertype(p, UPB_HANDLER_STRING),
  12352. p->accumulated, p->accumulated_len)) {
  12353. return false;
  12354. }
  12355. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  12356. upb_sink_endstr(&p->top->sink, sel);
  12357. p->top--;
  12358. multipart_end(p);
  12359. return true;
  12360. }
  12361. static void start_member(upb_json_parser *p) {
  12362. UPB_ASSERT(!p->top->f);
  12363. multipart_startaccum(p);
  12364. }
  12365. /* Helper: invoked during parse_mapentry() to emit the mapentry message's key
  12366. * field based on the current contents of the accumulate buffer. */
  12367. static bool parse_mapentry_key(upb_json_parser *p) {
  12368. size_t len;
  12369. const char *buf = accumulate_getptr(p, &len);
  12370. /* Emit the key field. We do a bit of ad-hoc parsing here because the
  12371. * parser state machine has already decided that this is a string field
  12372. * name, and we are reinterpreting it as some arbitrary key type. In
  12373. * particular, integer and bool keys are quoted, so we need to parse the
  12374. * quoted string contents here. */
  12375. p->top->f = upb_msgdef_itof(p->top->m, UPB_MAPENTRY_KEY);
  12376. if (p->top->f == NULL) {
  12377. upb_status_seterrmsg(&p->status, "mapentry message has no key");
  12378. upb_env_reporterror(p->env, &p->status);
  12379. return false;
  12380. }
  12381. switch (upb_fielddef_type(p->top->f)) {
  12382. case UPB_TYPE_INT32:
  12383. case UPB_TYPE_INT64:
  12384. case UPB_TYPE_UINT32:
  12385. case UPB_TYPE_UINT64:
  12386. /* Invoke end_number. The accum buffer has the number's text already. */
  12387. if (!parse_number(p, true)) {
  12388. return false;
  12389. }
  12390. break;
  12391. case UPB_TYPE_BOOL:
  12392. if (len == 4 && !strncmp(buf, "true", 4)) {
  12393. if (!parser_putbool(p, true)) {
  12394. return false;
  12395. }
  12396. } else if (len == 5 && !strncmp(buf, "false", 5)) {
  12397. if (!parser_putbool(p, false)) {
  12398. return false;
  12399. }
  12400. } else {
  12401. upb_status_seterrmsg(&p->status,
  12402. "Map bool key not 'true' or 'false'");
  12403. upb_env_reporterror(p->env, &p->status);
  12404. return false;
  12405. }
  12406. multipart_end(p);
  12407. break;
  12408. case UPB_TYPE_STRING:
  12409. case UPB_TYPE_BYTES: {
  12410. upb_sink subsink;
  12411. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  12412. upb_sink_startstr(&p->top->sink, sel, len, &subsink);
  12413. sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
  12414. upb_sink_putstring(&subsink, sel, buf, len, NULL);
  12415. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  12416. upb_sink_endstr(&subsink, sel);
  12417. multipart_end(p);
  12418. break;
  12419. }
  12420. default:
  12421. upb_status_seterrmsg(&p->status, "Invalid field type for map key");
  12422. upb_env_reporterror(p->env, &p->status);
  12423. return false;
  12424. }
  12425. return true;
  12426. }
  12427. /* Helper: emit one map entry (as a submessage in the map field sequence). This
  12428. * is invoked from end_membername(), at the end of the map entry's key string,
  12429. * with the map key in the accumulate buffer. It parses the key from that
  12430. * buffer, emits the handler calls to start the mapentry submessage (setting up
  12431. * its subframe in the process), and sets up state in the subframe so that the
  12432. * value parser (invoked next) will emit the mapentry's value field and then
  12433. * end the mapentry message. */
  12434. static bool handle_mapentry(upb_json_parser *p) {
  12435. const upb_fielddef *mapfield;
  12436. const upb_msgdef *mapentrymsg;
  12437. upb_jsonparser_frame *inner;
  12438. upb_selector_t sel;
  12439. /* Map entry: p->top->sink is the seq frame, so we need to start a frame
  12440. * for the mapentry itself, and then set |f| in that frame so that the map
  12441. * value field is parsed, and also set a flag to end the frame after the
  12442. * map-entry value is parsed. */
  12443. if (!check_stack(p)) return false;
  12444. mapfield = p->top->mapfield;
  12445. mapentrymsg = upb_fielddef_msgsubdef(mapfield);
  12446. inner = start_jsonparser_frame(p);
  12447. p->top->f = mapfield;
  12448. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
  12449. upb_sink_startsubmsg(&p->top->sink, sel, &inner->sink);
  12450. inner->m = mapentrymsg;
  12451. inner->mapfield = mapfield;
  12452. /* Don't set this to true *yet* -- we reuse parsing handlers below to push
  12453. * the key field value to the sink, and these handlers will pop the frame
  12454. * if they see is_mapentry (when invoked by the parser state machine, they
  12455. * would have just seen the map-entry value, not key). */
  12456. inner->is_mapentry = false;
  12457. p->top = inner;
  12458. /* send STARTMSG in submsg frame. */
  12459. upb_sink_startmsg(&p->top->sink);
  12460. parse_mapentry_key(p);
  12461. /* Set up the value field to receive the map-entry value. */
  12462. p->top->f = upb_msgdef_itof(p->top->m, UPB_MAPENTRY_VALUE);
  12463. p->top->is_mapentry = true; /* set up to pop frame after value is parsed. */
  12464. p->top->mapfield = mapfield;
  12465. if (p->top->f == NULL) {
  12466. upb_status_seterrmsg(&p->status, "mapentry message has no value");
  12467. upb_env_reporterror(p->env, &p->status);
  12468. return false;
  12469. }
  12470. return true;
  12471. }
  12472. static bool end_membername(upb_json_parser *p) {
  12473. UPB_ASSERT(!p->top->f);
  12474. if (!p->top->m) {
  12475. p->top->is_unknown_field = true;
  12476. multipart_end(p);
  12477. return true;
  12478. }
  12479. if (p->top->is_any) {
  12480. return end_any_membername(p);
  12481. } else if (p->top->is_map) {
  12482. return handle_mapentry(p);
  12483. } else {
  12484. size_t len;
  12485. const char *buf = accumulate_getptr(p, &len);
  12486. upb_value v;
  12487. if (upb_strtable_lookup2(p->top->name_table, buf, len, &v)) {
  12488. p->top->f = upb_value_getconstptr(v);
  12489. multipart_end(p);
  12490. return true;
  12491. } else if (p->ignore_json_unknown) {
  12492. p->top->is_unknown_field = true;
  12493. multipart_end(p);
  12494. return true;
  12495. } else {
  12496. upb_status_seterrf(&p->status, "No such field: %.*s\n", (int)len, buf);
  12497. upb_env_reporterror(p->env, &p->status);
  12498. return false;
  12499. }
  12500. }
  12501. }
  12502. static bool end_any_membername(upb_json_parser *p) {
  12503. size_t len;
  12504. const char *buf = accumulate_getptr(p, &len);
  12505. upb_value v;
  12506. if (len == 5 && strncmp(buf, "@type", len) == 0) {
  12507. upb_strtable_lookup2(p->top->name_table, "type_url", 8, &v);
  12508. p->top->f = upb_value_getconstptr(v);
  12509. multipart_end(p);
  12510. return true;
  12511. } else {
  12512. p->top->is_unknown_field = true;
  12513. multipart_end(p);
  12514. return true;
  12515. }
  12516. }
  12517. static void end_member(upb_json_parser *p) {
  12518. /* If we just parsed a map-entry value, end that frame too. */
  12519. if (p->top->is_mapentry) {
  12520. upb_status s = UPB_STATUS_INIT;
  12521. upb_selector_t sel;
  12522. bool ok;
  12523. const upb_fielddef *mapfield;
  12524. UPB_ASSERT(p->top > p->stack);
  12525. /* send ENDMSG on submsg. */
  12526. upb_sink_endmsg(&p->top->sink, &s);
  12527. mapfield = p->top->mapfield;
  12528. /* send ENDSUBMSG in repeated-field-of-mapentries frame. */
  12529. p->top--;
  12530. ok = upb_handlers_getselector(mapfield, UPB_HANDLER_ENDSUBMSG, &sel);
  12531. UPB_ASSERT(ok);
  12532. upb_sink_endsubmsg(&p->top->sink, sel);
  12533. }
  12534. p->top->f = NULL;
  12535. p->top->is_unknown_field = false;
  12536. }
  12537. static void start_any_member(upb_json_parser *p, const char *ptr) {
  12538. start_member(p);
  12539. json_parser_any_frame_set_after_type_url_start_once(p->top->any_frame, ptr);
  12540. }
  12541. static void end_any_member(upb_json_parser *p, const char *ptr) {
  12542. json_parser_any_frame_set_before_type_url_end(p->top->any_frame, ptr);
  12543. end_member(p);
  12544. }
  12545. static bool start_subobject(upb_json_parser *p) {
  12546. if (p->top->is_unknown_field) {
  12547. upb_jsonparser_frame *inner;
  12548. if (!check_stack(p)) return false;
  12549. p->top = start_jsonparser_frame(p);
  12550. return true;
  12551. }
  12552. if (upb_fielddef_ismap(p->top->f)) {
  12553. upb_jsonparser_frame *inner;
  12554. upb_selector_t sel;
  12555. /* Beginning of a map. Start a new parser frame in a repeated-field
  12556. * context. */
  12557. if (!check_stack(p)) return false;
  12558. inner = start_jsonparser_frame(p);
  12559. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
  12560. upb_sink_startseq(&p->top->sink, sel, &inner->sink);
  12561. inner->m = upb_fielddef_msgsubdef(p->top->f);
  12562. inner->mapfield = p->top->f;
  12563. inner->is_map = true;
  12564. p->top = inner;
  12565. return true;
  12566. } else if (upb_fielddef_issubmsg(p->top->f)) {
  12567. upb_jsonparser_frame *inner;
  12568. upb_selector_t sel;
  12569. /* Beginning of a subobject. Start a new parser frame in the submsg
  12570. * context. */
  12571. if (!check_stack(p)) return false;
  12572. inner = start_jsonparser_frame(p);
  12573. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
  12574. upb_sink_startsubmsg(&p->top->sink, sel, &inner->sink);
  12575. inner->m = upb_fielddef_msgsubdef(p->top->f);
  12576. set_name_table(p, inner);
  12577. p->top = inner;
  12578. if (is_wellknown_msg(p, UPB_WELLKNOWN_ANY)) {
  12579. p->top->is_any = true;
  12580. p->top->any_frame =
  12581. upb_env_malloc(p->env, sizeof(upb_jsonparser_any_frame));
  12582. json_parser_any_frame_reset(p->top->any_frame);
  12583. } else {
  12584. p->top->is_any = false;
  12585. p->top->any_frame = NULL;
  12586. }
  12587. return true;
  12588. } else {
  12589. upb_status_seterrf(&p->status,
  12590. "Object specified for non-message/group field: %s",
  12591. upb_fielddef_name(p->top->f));
  12592. upb_env_reporterror(p->env, &p->status);
  12593. return false;
  12594. }
  12595. }
  12596. static bool start_subobject_full(upb_json_parser *p) {
  12597. if (is_top_level(p)) {
  12598. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  12599. start_value_object(p, VALUE_STRUCTVALUE);
  12600. if (!start_subobject(p)) return false;
  12601. start_structvalue_object(p);
  12602. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_STRUCT)) {
  12603. start_structvalue_object(p);
  12604. } else {
  12605. return true;
  12606. }
  12607. } else if (is_wellknown_field(p, UPB_WELLKNOWN_STRUCT)) {
  12608. if (!start_subobject(p)) return false;
  12609. start_structvalue_object(p);
  12610. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  12611. if (!start_subobject(p)) return false;
  12612. start_value_object(p, VALUE_STRUCTVALUE);
  12613. if (!start_subobject(p)) return false;
  12614. start_structvalue_object(p);
  12615. }
  12616. return start_subobject(p);
  12617. }
  12618. static void end_subobject(upb_json_parser *p) {
  12619. if (is_top_level(p)) {
  12620. return;
  12621. }
  12622. if (p->top->is_map) {
  12623. upb_selector_t sel;
  12624. p->top--;
  12625. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
  12626. upb_sink_endseq(&p->top->sink, sel);
  12627. } else {
  12628. upb_selector_t sel;
  12629. bool is_unknown = p->top->m == NULL;
  12630. p->top--;
  12631. if (!is_unknown) {
  12632. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSUBMSG);
  12633. upb_sink_endsubmsg(&p->top->sink, sel);
  12634. }
  12635. }
  12636. }
  12637. static void end_subobject_full(upb_json_parser *p) {
  12638. end_subobject(p);
  12639. if (is_wellknown_msg(p, UPB_WELLKNOWN_STRUCT)) {
  12640. end_structvalue_object(p);
  12641. if (!is_top_level(p)) {
  12642. end_subobject(p);
  12643. }
  12644. }
  12645. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  12646. end_value_object(p);
  12647. if (!is_top_level(p)) {
  12648. end_subobject(p);
  12649. }
  12650. }
  12651. }
  12652. static bool start_array(upb_json_parser *p) {
  12653. upb_jsonparser_frame *inner;
  12654. upb_selector_t sel;
  12655. if (is_top_level(p)) {
  12656. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  12657. start_value_object(p, VALUE_LISTVALUE);
  12658. if (!start_subobject(p)) return false;
  12659. start_listvalue_object(p);
  12660. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_LISTVALUE)) {
  12661. start_listvalue_object(p);
  12662. } else {
  12663. return false;
  12664. }
  12665. } else if (is_wellknown_field(p, UPB_WELLKNOWN_LISTVALUE) &&
  12666. (!upb_fielddef_isseq(p->top->f) ||
  12667. p->top->is_repeated)) {
  12668. if (!start_subobject(p)) return false;
  12669. start_listvalue_object(p);
  12670. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE) &&
  12671. (!upb_fielddef_isseq(p->top->f) ||
  12672. p->top->is_repeated)) {
  12673. if (!start_subobject(p)) return false;
  12674. start_value_object(p, VALUE_LISTVALUE);
  12675. if (!start_subobject(p)) return false;
  12676. start_listvalue_object(p);
  12677. }
  12678. if (p->top->is_unknown_field) {
  12679. inner = start_jsonparser_frame(p);
  12680. inner->is_unknown_field = true;
  12681. p->top = inner;
  12682. return true;
  12683. }
  12684. if (!upb_fielddef_isseq(p->top->f)) {
  12685. upb_status_seterrf(&p->status,
  12686. "Array specified for non-repeated field: %s",
  12687. upb_fielddef_name(p->top->f));
  12688. upb_env_reporterror(p->env, &p->status);
  12689. return false;
  12690. }
  12691. if (!check_stack(p)) return false;
  12692. inner = start_jsonparser_frame(p);
  12693. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
  12694. upb_sink_startseq(&p->top->sink, sel, &inner->sink);
  12695. inner->m = p->top->m;
  12696. inner->f = p->top->f;
  12697. inner->is_repeated = true;
  12698. p->top = inner;
  12699. return true;
  12700. }
  12701. static void end_array(upb_json_parser *p) {
  12702. upb_selector_t sel;
  12703. UPB_ASSERT(p->top > p->stack);
  12704. p->top--;
  12705. if (p->top->is_unknown_field) {
  12706. return;
  12707. }
  12708. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
  12709. upb_sink_endseq(&p->top->sink, sel);
  12710. if (is_wellknown_msg(p, UPB_WELLKNOWN_LISTVALUE)) {
  12711. end_listvalue_object(p);
  12712. if (!is_top_level(p)) {
  12713. end_subobject(p);
  12714. }
  12715. }
  12716. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  12717. end_value_object(p);
  12718. if (!is_top_level(p)) {
  12719. end_subobject(p);
  12720. }
  12721. }
  12722. }
  12723. static void start_object(upb_json_parser *p) {
  12724. if (!p->top->is_map && p->top->m != NULL) {
  12725. upb_sink_startmsg(&p->top->sink);
  12726. }
  12727. }
  12728. static void end_object(upb_json_parser *p) {
  12729. if (!p->top->is_map && p->top->m != NULL) {
  12730. upb_status status;
  12731. upb_status_clear(&status);
  12732. upb_sink_endmsg(&p->top->sink, &status);
  12733. if (!upb_ok(&status)) {
  12734. upb_env_reporterror(p->env, &status);
  12735. }
  12736. }
  12737. }
  12738. static void start_any_object(upb_json_parser *p, const char *ptr) {
  12739. start_object(p);
  12740. p->top->any_frame->before_type_url_start = ptr;
  12741. p->top->any_frame->before_type_url_end = ptr;
  12742. }
  12743. static bool end_any_object(upb_json_parser *p, const char *ptr) {
  12744. const char *value_membername = "value";
  12745. bool is_well_known_packed = false;
  12746. const char *packed_end = ptr + 1;
  12747. upb_selector_t sel;
  12748. upb_jsonparser_frame *inner;
  12749. if (json_parser_any_frame_has_value(p->top->any_frame) &&
  12750. !json_parser_any_frame_has_type_url(p->top->any_frame)) {
  12751. upb_status_seterrmsg(&p->status, "No valid type url");
  12752. upb_env_reporterror(p->env, &p->status);
  12753. return false;
  12754. }
  12755. /* Well known types data is represented as value field. */
  12756. if (upb_msgdef_wellknowntype(p->top->any_frame->parser->top->m) !=
  12757. UPB_WELLKNOWN_UNSPECIFIED) {
  12758. is_well_known_packed = true;
  12759. if (json_parser_any_frame_has_value_before_type_url(p->top->any_frame)) {
  12760. p->top->any_frame->before_type_url_start =
  12761. memchr(p->top->any_frame->before_type_url_start, ':',
  12762. p->top->any_frame->before_type_url_end -
  12763. p->top->any_frame->before_type_url_start);
  12764. if (p->top->any_frame->before_type_url_start == NULL) {
  12765. upb_status_seterrmsg(&p->status, "invalid data for well known type.");
  12766. upb_env_reporterror(p->env, &p->status);
  12767. return false;
  12768. }
  12769. p->top->any_frame->before_type_url_start++;
  12770. }
  12771. if (json_parser_any_frame_has_value_after_type_url(p->top->any_frame)) {
  12772. p->top->any_frame->after_type_url_start =
  12773. memchr(p->top->any_frame->after_type_url_start, ':',
  12774. (ptr + 1) -
  12775. p->top->any_frame->after_type_url_start);
  12776. if (p->top->any_frame->after_type_url_start == NULL) {
  12777. upb_status_seterrmsg(&p->status, "Invalid data for well known type.");
  12778. upb_env_reporterror(p->env, &p->status);
  12779. return false;
  12780. }
  12781. p->top->any_frame->after_type_url_start++;
  12782. packed_end = ptr;
  12783. }
  12784. }
  12785. if (json_parser_any_frame_has_value_before_type_url(p->top->any_frame)) {
  12786. if (!parse(p->top->any_frame->parser, NULL,
  12787. p->top->any_frame->before_type_url_start,
  12788. p->top->any_frame->before_type_url_end -
  12789. p->top->any_frame->before_type_url_start, NULL)) {
  12790. return false;
  12791. }
  12792. } else {
  12793. if (!is_well_known_packed) {
  12794. if (!parse(p->top->any_frame->parser, NULL, "{", 1, NULL)) {
  12795. return false;
  12796. }
  12797. }
  12798. }
  12799. if (json_parser_any_frame_has_value_before_type_url(p->top->any_frame) &&
  12800. json_parser_any_frame_has_value_after_type_url(p->top->any_frame)) {
  12801. if (!parse(p->top->any_frame->parser, NULL, ",", 1, NULL)) {
  12802. return false;
  12803. }
  12804. }
  12805. if (json_parser_any_frame_has_value_after_type_url(p->top->any_frame)) {
  12806. if (!parse(p->top->any_frame->parser, NULL,
  12807. p->top->any_frame->after_type_url_start,
  12808. packed_end - p->top->any_frame->after_type_url_start, NULL)) {
  12809. return false;
  12810. }
  12811. } else {
  12812. if (!is_well_known_packed) {
  12813. if (!parse(p->top->any_frame->parser, NULL, "}", 1, NULL)) {
  12814. return false;
  12815. }
  12816. }
  12817. }
  12818. if (!end(p->top->any_frame->parser, NULL)) {
  12819. return false;
  12820. }
  12821. p->top->is_any = false;
  12822. /* Set value */
  12823. start_member(p);
  12824. capture_begin(p, value_membername);
  12825. capture_end(p, value_membername + 5);
  12826. end_membername(p);
  12827. if (!check_stack(p)) return false;
  12828. inner = p->top + 1;
  12829. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  12830. upb_sink_startstr(&p->top->sink, sel, 0, &inner->sink);
  12831. sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
  12832. upb_sink_putstring(&inner->sink, sel, p->top->any_frame->stringsink.ptr,
  12833. p->top->any_frame->stringsink.len, NULL);
  12834. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  12835. upb_sink_endstr(&inner->sink, sel);
  12836. end_member(p);
  12837. end_object(p);
  12838. /* Deallocate any parse frame. */
  12839. json_parser_any_frame_free(p->top->any_frame);
  12840. upb_env_free(p->env, p->top->any_frame);
  12841. return true;
  12842. }
  12843. static bool is_string_wrapper(const upb_msgdef *m) {
  12844. upb_wellknowntype_t type = upb_msgdef_wellknowntype(m);
  12845. return type == UPB_WELLKNOWN_STRINGVALUE ||
  12846. type == UPB_WELLKNOWN_BYTESVALUE;
  12847. }
  12848. static bool is_fieldmask(const upb_msgdef *m) {
  12849. upb_wellknowntype_t type = upb_msgdef_wellknowntype(m);
  12850. return type == UPB_WELLKNOWN_FIELDMASK;
  12851. }
  12852. static void start_fieldmask_object(upb_json_parser *p) {
  12853. const char *membername = "paths";
  12854. start_object(p);
  12855. /* Set up context for parsing value */
  12856. start_member(p);
  12857. capture_begin(p, membername);
  12858. capture_end(p, membername + 5);
  12859. end_membername(p);
  12860. start_array(p);
  12861. }
  12862. static void end_fieldmask_object(upb_json_parser *p) {
  12863. end_array(p);
  12864. end_member(p);
  12865. end_object(p);
  12866. }
  12867. static void start_wrapper_object(upb_json_parser *p) {
  12868. const char *membername = "value";
  12869. start_object(p);
  12870. /* Set up context for parsing value */
  12871. start_member(p);
  12872. capture_begin(p, membername);
  12873. capture_end(p, membername + 5);
  12874. end_membername(p);
  12875. }
  12876. static void end_wrapper_object(upb_json_parser *p) {
  12877. end_member(p);
  12878. end_object(p);
  12879. }
  12880. static void start_value_object(upb_json_parser *p, int value_type) {
  12881. const char *nullmember = "null_value";
  12882. const char *numbermember = "number_value";
  12883. const char *stringmember = "string_value";
  12884. const char *boolmember = "bool_value";
  12885. const char *structmember = "struct_value";
  12886. const char *listmember = "list_value";
  12887. const char *membername = "";
  12888. switch (value_type) {
  12889. case VALUE_NULLVALUE:
  12890. membername = nullmember;
  12891. break;
  12892. case VALUE_NUMBERVALUE:
  12893. membername = numbermember;
  12894. break;
  12895. case VALUE_STRINGVALUE:
  12896. membername = stringmember;
  12897. break;
  12898. case VALUE_BOOLVALUE:
  12899. membername = boolmember;
  12900. break;
  12901. case VALUE_STRUCTVALUE:
  12902. membername = structmember;
  12903. break;
  12904. case VALUE_LISTVALUE:
  12905. membername = listmember;
  12906. break;
  12907. }
  12908. start_object(p);
  12909. /* Set up context for parsing value */
  12910. start_member(p);
  12911. capture_begin(p, membername);
  12912. capture_end(p, membername + strlen(membername));
  12913. end_membername(p);
  12914. }
  12915. static void end_value_object(upb_json_parser *p) {
  12916. end_member(p);
  12917. end_object(p);
  12918. }
  12919. static void start_listvalue_object(upb_json_parser *p) {
  12920. const char *membername = "values";
  12921. start_object(p);
  12922. /* Set up context for parsing value */
  12923. start_member(p);
  12924. capture_begin(p, membername);
  12925. capture_end(p, membername + strlen(membername));
  12926. end_membername(p);
  12927. }
  12928. static void end_listvalue_object(upb_json_parser *p) {
  12929. end_member(p);
  12930. end_object(p);
  12931. }
  12932. static void start_structvalue_object(upb_json_parser *p) {
  12933. const char *membername = "fields";
  12934. start_object(p);
  12935. /* Set up context for parsing value */
  12936. start_member(p);
  12937. capture_begin(p, membername);
  12938. capture_end(p, membername + strlen(membername));
  12939. end_membername(p);
  12940. }
  12941. static void end_structvalue_object(upb_json_parser *p) {
  12942. end_member(p);
  12943. end_object(p);
  12944. }
  12945. static bool is_top_level(upb_json_parser *p) {
  12946. return p->top == p->stack && p->top->f == NULL && !p->top->is_unknown_field;
  12947. }
  12948. static bool is_wellknown_msg(upb_json_parser *p, upb_wellknowntype_t type) {
  12949. return p->top->m != NULL && upb_msgdef_wellknowntype(p->top->m) == type;
  12950. }
  12951. static bool is_wellknown_field(upb_json_parser *p, upb_wellknowntype_t type) {
  12952. return p->top->f != NULL &&
  12953. upb_fielddef_issubmsg(p->top->f) &&
  12954. (upb_msgdef_wellknowntype(upb_fielddef_msgsubdef(p->top->f))
  12955. == type);
  12956. }
  12957. static bool does_number_wrapper_start(upb_json_parser *p) {
  12958. return p->top->f != NULL &&
  12959. upb_fielddef_issubmsg(p->top->f) &&
  12960. upb_msgdef_isnumberwrapper(upb_fielddef_msgsubdef(p->top->f));
  12961. }
  12962. static bool does_number_wrapper_end(upb_json_parser *p) {
  12963. return p->top->m != NULL && upb_msgdef_isnumberwrapper(p->top->m);
  12964. }
  12965. static bool is_number_wrapper_object(upb_json_parser *p) {
  12966. return p->top->m != NULL && upb_msgdef_isnumberwrapper(p->top->m);
  12967. }
  12968. static bool does_string_wrapper_start(upb_json_parser *p) {
  12969. return p->top->f != NULL &&
  12970. upb_fielddef_issubmsg(p->top->f) &&
  12971. is_string_wrapper(upb_fielddef_msgsubdef(p->top->f));
  12972. }
  12973. static bool does_string_wrapper_end(upb_json_parser *p) {
  12974. return p->top->m != NULL && is_string_wrapper(p->top->m);
  12975. }
  12976. static bool is_string_wrapper_object(upb_json_parser *p) {
  12977. return p->top->m != NULL && is_string_wrapper(p->top->m);
  12978. }
  12979. static bool does_fieldmask_start(upb_json_parser *p) {
  12980. return p->top->f != NULL &&
  12981. upb_fielddef_issubmsg(p->top->f) &&
  12982. is_fieldmask(upb_fielddef_msgsubdef(p->top->f));
  12983. }
  12984. static bool does_fieldmask_end(upb_json_parser *p) {
  12985. return p->top->m != NULL && is_fieldmask(p->top->m);
  12986. }
  12987. static bool is_fieldmask_object(upb_json_parser *p) {
  12988. return p->top->m != NULL && is_fieldmask(p->top->m);
  12989. }
  12990. #define CHECK_RETURN_TOP(x) if (!(x)) goto error
  12991. /* The actual parser **********************************************************/
  12992. /* What follows is the Ragel parser itself. The language is specified in Ragel
  12993. * and the actions call our C functions above.
  12994. *
  12995. * Ragel has an extensive set of functionality, and we use only a small part of
  12996. * it. There are many action types but we only use a few:
  12997. *
  12998. * ">" -- transition into a machine
  12999. * "%" -- transition out of a machine
  13000. * "@" -- transition into a final state of a machine.
  13001. *
  13002. * "@" transitions are tricky because a machine can transition into a final
  13003. * state repeatedly. But in some cases we know this can't happen, for example
  13004. * a string which is delimited by a final '"' can only transition into its
  13005. * final state once, when the closing '"' is seen. */
  13006. #line 2789 "upb/json/parser.rl"
  13007. #line 2592 "upb/json/parser.c"
  13008. static const char _json_actions[] = {
  13009. 0, 1, 0, 1, 1, 1, 3, 1,
  13010. 4, 1, 6, 1, 7, 1, 8, 1,
  13011. 9, 1, 11, 1, 12, 1, 13, 1,
  13012. 14, 1, 15, 1, 16, 1, 17, 1,
  13013. 18, 1, 19, 1, 20, 1, 22, 1,
  13014. 23, 1, 24, 1, 35, 1, 37, 1,
  13015. 39, 1, 40, 1, 42, 1, 43, 1,
  13016. 44, 1, 46, 1, 48, 1, 49, 1,
  13017. 50, 1, 51, 1, 53, 1, 54, 2,
  13018. 4, 9, 2, 5, 6, 2, 7, 3,
  13019. 2, 7, 9, 2, 21, 26, 2, 25,
  13020. 10, 2, 27, 28, 2, 29, 30, 2,
  13021. 32, 34, 2, 33, 31, 2, 38, 36,
  13022. 2, 40, 42, 2, 45, 2, 2, 46,
  13023. 54, 2, 47, 36, 2, 49, 54, 2,
  13024. 50, 54, 2, 51, 54, 2, 52, 41,
  13025. 2, 53, 54, 3, 32, 34, 35, 4,
  13026. 21, 26, 27, 28
  13027. };
  13028. static const short _json_key_offsets[] = {
  13029. 0, 0, 12, 13, 18, 23, 28, 29,
  13030. 30, 31, 32, 33, 34, 35, 36, 37,
  13031. 38, 43, 44, 48, 53, 58, 63, 67,
  13032. 71, 74, 77, 79, 83, 87, 89, 91,
  13033. 96, 98, 100, 109, 115, 121, 127, 133,
  13034. 135, 139, 142, 144, 146, 149, 150, 154,
  13035. 156, 158, 160, 162, 163, 165, 167, 168,
  13036. 170, 172, 173, 175, 177, 178, 180, 182,
  13037. 183, 185, 187, 191, 193, 195, 196, 197,
  13038. 198, 199, 201, 206, 208, 210, 212, 221,
  13039. 222, 222, 222, 227, 232, 237, 238, 239,
  13040. 240, 241, 241, 242, 243, 244, 244, 245,
  13041. 246, 247, 247, 252, 253, 257, 262, 267,
  13042. 272, 276, 276, 279, 282, 285, 288, 291,
  13043. 294, 294, 294, 294, 294, 294
  13044. };
  13045. static const char _json_trans_keys[] = {
  13046. 32, 34, 45, 91, 102, 110, 116, 123,
  13047. 9, 13, 48, 57, 34, 32, 93, 125,
  13048. 9, 13, 32, 44, 93, 9, 13, 32,
  13049. 93, 125, 9, 13, 97, 108, 115, 101,
  13050. 117, 108, 108, 114, 117, 101, 32, 34,
  13051. 125, 9, 13, 34, 32, 58, 9, 13,
  13052. 32, 93, 125, 9, 13, 32, 44, 125,
  13053. 9, 13, 32, 44, 125, 9, 13, 32,
  13054. 34, 9, 13, 45, 48, 49, 57, 48,
  13055. 49, 57, 46, 69, 101, 48, 57, 69,
  13056. 101, 48, 57, 43, 45, 48, 57, 48,
  13057. 57, 48, 57, 46, 69, 101, 48, 57,
  13058. 34, 92, 34, 92, 34, 47, 92, 98,
  13059. 102, 110, 114, 116, 117, 48, 57, 65,
  13060. 70, 97, 102, 48, 57, 65, 70, 97,
  13061. 102, 48, 57, 65, 70, 97, 102, 48,
  13062. 57, 65, 70, 97, 102, 34, 92, 45,
  13063. 48, 49, 57, 48, 49, 57, 46, 115,
  13064. 48, 57, 115, 48, 57, 34, 46, 115,
  13065. 48, 57, 48, 57, 48, 57, 48, 57,
  13066. 48, 57, 45, 48, 57, 48, 57, 45,
  13067. 48, 57, 48, 57, 84, 48, 57, 48,
  13068. 57, 58, 48, 57, 48, 57, 58, 48,
  13069. 57, 48, 57, 43, 45, 46, 90, 48,
  13070. 57, 48, 57, 58, 48, 48, 34, 48,
  13071. 57, 43, 45, 90, 48, 57, 34, 44,
  13072. 34, 44, 34, 44, 34, 45, 91, 102,
  13073. 110, 116, 123, 48, 57, 34, 32, 93,
  13074. 125, 9, 13, 32, 44, 93, 9, 13,
  13075. 32, 93, 125, 9, 13, 97, 108, 115,
  13076. 101, 117, 108, 108, 114, 117, 101, 32,
  13077. 34, 125, 9, 13, 34, 32, 58, 9,
  13078. 13, 32, 93, 125, 9, 13, 32, 44,
  13079. 125, 9, 13, 32, 44, 125, 9, 13,
  13080. 32, 34, 9, 13, 32, 9, 13, 32,
  13081. 9, 13, 32, 9, 13, 32, 9, 13,
  13082. 32, 9, 13, 32, 9, 13, 0
  13083. };
  13084. static const char _json_single_lengths[] = {
  13085. 0, 8, 1, 3, 3, 3, 1, 1,
  13086. 1, 1, 1, 1, 1, 1, 1, 1,
  13087. 3, 1, 2, 3, 3, 3, 2, 2,
  13088. 1, 3, 0, 2, 2, 0, 0, 3,
  13089. 2, 2, 9, 0, 0, 0, 0, 2,
  13090. 2, 1, 2, 0, 1, 1, 2, 0,
  13091. 0, 0, 0, 1, 0, 0, 1, 0,
  13092. 0, 1, 0, 0, 1, 0, 0, 1,
  13093. 0, 0, 4, 0, 0, 1, 1, 1,
  13094. 1, 0, 3, 2, 2, 2, 7, 1,
  13095. 0, 0, 3, 3, 3, 1, 1, 1,
  13096. 1, 0, 1, 1, 1, 0, 1, 1,
  13097. 1, 0, 3, 1, 2, 3, 3, 3,
  13098. 2, 0, 1, 1, 1, 1, 1, 1,
  13099. 0, 0, 0, 0, 0, 0
  13100. };
  13101. static const char _json_range_lengths[] = {
  13102. 0, 2, 0, 1, 1, 1, 0, 0,
  13103. 0, 0, 0, 0, 0, 0, 0, 0,
  13104. 1, 0, 1, 1, 1, 1, 1, 1,
  13105. 1, 0, 1, 1, 1, 1, 1, 1,
  13106. 0, 0, 0, 3, 3, 3, 3, 0,
  13107. 1, 1, 0, 1, 1, 0, 1, 1,
  13108. 1, 1, 1, 0, 1, 1, 0, 1,
  13109. 1, 0, 1, 1, 0, 1, 1, 0,
  13110. 1, 1, 0, 1, 1, 0, 0, 0,
  13111. 0, 1, 1, 0, 0, 0, 1, 0,
  13112. 0, 0, 1, 1, 1, 0, 0, 0,
  13113. 0, 0, 0, 0, 0, 0, 0, 0,
  13114. 0, 0, 1, 0, 1, 1, 1, 1,
  13115. 1, 0, 1, 1, 1, 1, 1, 1,
  13116. 0, 0, 0, 0, 0, 0
  13117. };
  13118. static const short _json_index_offsets[] = {
  13119. 0, 0, 11, 13, 18, 23, 28, 30,
  13120. 32, 34, 36, 38, 40, 42, 44, 46,
  13121. 48, 53, 55, 59, 64, 69, 74, 78,
  13122. 82, 85, 89, 91, 95, 99, 101, 103,
  13123. 108, 111, 114, 124, 128, 132, 136, 140,
  13124. 143, 147, 150, 153, 155, 158, 160, 164,
  13125. 166, 168, 170, 172, 174, 176, 178, 180,
  13126. 182, 184, 186, 188, 190, 192, 194, 196,
  13127. 198, 200, 202, 207, 209, 211, 213, 215,
  13128. 217, 219, 221, 226, 229, 232, 235, 244,
  13129. 246, 247, 248, 253, 258, 263, 265, 267,
  13130. 269, 271, 272, 274, 276, 278, 279, 281,
  13131. 283, 285, 286, 291, 293, 297, 302, 307,
  13132. 312, 316, 317, 320, 323, 326, 329, 332,
  13133. 335, 336, 337, 338, 339, 340
  13134. };
  13135. static const unsigned char _json_indicies[] = {
  13136. 0, 2, 3, 4, 5, 6, 7, 8,
  13137. 0, 3, 1, 9, 1, 11, 12, 1,
  13138. 11, 10, 13, 14, 12, 13, 1, 14,
  13139. 1, 1, 14, 10, 15, 1, 16, 1,
  13140. 17, 1, 18, 1, 19, 1, 20, 1,
  13141. 21, 1, 22, 1, 23, 1, 24, 1,
  13142. 25, 26, 27, 25, 1, 28, 1, 29,
  13143. 30, 29, 1, 30, 1, 1, 30, 31,
  13144. 32, 33, 34, 32, 1, 35, 36, 27,
  13145. 35, 1, 36, 26, 36, 1, 37, 38,
  13146. 39, 1, 38, 39, 1, 41, 42, 42,
  13147. 40, 43, 1, 42, 42, 43, 40, 44,
  13148. 44, 45, 1, 45, 1, 45, 40, 41,
  13149. 42, 42, 39, 40, 47, 48, 46, 50,
  13150. 51, 49, 52, 52, 52, 52, 52, 52,
  13151. 52, 52, 53, 1, 54, 54, 54, 1,
  13152. 55, 55, 55, 1, 56, 56, 56, 1,
  13153. 57, 57, 57, 1, 59, 60, 58, 61,
  13154. 62, 63, 1, 64, 65, 1, 66, 67,
  13155. 1, 68, 1, 67, 68, 1, 69, 1,
  13156. 66, 67, 65, 1, 70, 1, 71, 1,
  13157. 72, 1, 73, 1, 74, 1, 75, 1,
  13158. 76, 1, 77, 1, 78, 1, 79, 1,
  13159. 80, 1, 81, 1, 82, 1, 83, 1,
  13160. 84, 1, 85, 1, 86, 1, 87, 1,
  13161. 88, 1, 89, 89, 90, 91, 1, 92,
  13162. 1, 93, 1, 94, 1, 95, 1, 96,
  13163. 1, 97, 1, 98, 1, 99, 99, 100,
  13164. 98, 1, 102, 1, 101, 104, 105, 103,
  13165. 1, 1, 101, 106, 107, 108, 109, 110,
  13166. 111, 112, 107, 1, 113, 1, 114, 115,
  13167. 117, 118, 1, 117, 116, 119, 120, 118,
  13168. 119, 1, 120, 1, 1, 120, 116, 121,
  13169. 1, 122, 1, 123, 1, 124, 1, 125,
  13170. 126, 1, 127, 1, 128, 1, 129, 130,
  13171. 1, 131, 1, 132, 1, 133, 134, 135,
  13172. 136, 134, 1, 137, 1, 138, 139, 138,
  13173. 1, 139, 1, 1, 139, 140, 141, 142,
  13174. 143, 141, 1, 144, 145, 136, 144, 1,
  13175. 145, 135, 145, 1, 146, 147, 147, 1,
  13176. 148, 148, 1, 149, 149, 1, 150, 150,
  13177. 1, 151, 151, 1, 152, 152, 1, 1,
  13178. 1, 1, 1, 1, 1, 0
  13179. };
  13180. static const char _json_trans_targs[] = {
  13181. 1, 0, 2, 107, 3, 6, 10, 13,
  13182. 16, 106, 4, 3, 106, 4, 5, 7,
  13183. 8, 9, 108, 11, 12, 109, 14, 15,
  13184. 110, 16, 17, 111, 18, 18, 19, 20,
  13185. 21, 22, 111, 21, 22, 24, 25, 31,
  13186. 112, 26, 28, 27, 29, 30, 33, 113,
  13187. 34, 33, 113, 34, 32, 35, 36, 37,
  13188. 38, 39, 33, 113, 34, 41, 42, 46,
  13189. 42, 46, 43, 45, 44, 114, 48, 49,
  13190. 50, 51, 52, 53, 54, 55, 56, 57,
  13191. 58, 59, 60, 61, 62, 63, 64, 65,
  13192. 66, 67, 73, 72, 68, 69, 70, 71,
  13193. 72, 115, 74, 67, 72, 76, 116, 76,
  13194. 116, 77, 79, 81, 82, 85, 90, 94,
  13195. 98, 80, 117, 117, 83, 82, 80, 83,
  13196. 84, 86, 87, 88, 89, 117, 91, 92,
  13197. 93, 117, 95, 96, 97, 117, 98, 99,
  13198. 105, 100, 100, 101, 102, 103, 104, 105,
  13199. 103, 104, 117, 106, 106, 106, 106, 106,
  13200. 106
  13201. };
  13202. static const unsigned char _json_trans_actions[] = {
  13203. 0, 0, 113, 107, 53, 0, 0, 0,
  13204. 125, 59, 45, 0, 55, 0, 0, 0,
  13205. 0, 0, 0, 0, 0, 0, 0, 0,
  13206. 0, 0, 101, 51, 47, 0, 0, 45,
  13207. 49, 49, 104, 0, 0, 0, 0, 0,
  13208. 3, 0, 0, 0, 0, 0, 5, 15,
  13209. 0, 0, 71, 7, 13, 0, 74, 9,
  13210. 9, 9, 77, 80, 11, 37, 37, 37,
  13211. 0, 0, 0, 39, 0, 41, 86, 0,
  13212. 0, 0, 17, 19, 0, 21, 23, 0,
  13213. 25, 27, 0, 29, 31, 0, 33, 35,
  13214. 0, 135, 83, 135, 0, 0, 0, 0,
  13215. 0, 92, 0, 89, 89, 98, 43, 0,
  13216. 131, 95, 113, 107, 53, 0, 0, 0,
  13217. 125, 59, 69, 110, 45, 0, 55, 0,
  13218. 0, 0, 0, 0, 0, 119, 0, 0,
  13219. 0, 122, 0, 0, 0, 116, 0, 101,
  13220. 51, 47, 0, 0, 45, 49, 49, 104,
  13221. 0, 0, 128, 0, 57, 63, 65, 61,
  13222. 67
  13223. };
  13224. static const unsigned char _json_eof_actions[] = {
  13225. 0, 0, 0, 0, 0, 0, 0, 0,
  13226. 0, 0, 0, 0, 0, 0, 0, 0,
  13227. 0, 0, 0, 0, 0, 0, 0, 0,
  13228. 0, 1, 0, 1, 0, 0, 1, 1,
  13229. 0, 0, 0, 0, 0, 0, 0, 0,
  13230. 0, 0, 0, 0, 0, 0, 0, 0,
  13231. 0, 0, 0, 0, 0, 0, 0, 0,
  13232. 0, 0, 0, 0, 0, 0, 0, 0,
  13233. 0, 0, 0, 0, 0, 0, 0, 0,
  13234. 0, 0, 0, 0, 0, 0, 0, 0,
  13235. 0, 0, 0, 0, 0, 0, 0, 0,
  13236. 0, 0, 0, 0, 0, 0, 0, 0,
  13237. 0, 0, 0, 0, 0, 0, 0, 0,
  13238. 0, 0, 0, 57, 63, 65, 61, 67,
  13239. 0, 0, 0, 0, 0, 0
  13240. };
  13241. static const int json_start = 1;
  13242. static const int json_en_number_machine = 23;
  13243. static const int json_en_string_machine = 32;
  13244. static const int json_en_duration_machine = 40;
  13245. static const int json_en_timestamp_machine = 47;
  13246. static const int json_en_fieldmask_machine = 75;
  13247. static const int json_en_value_machine = 78;
  13248. static const int json_en_main = 1;
  13249. #line 2792 "upb/json/parser.rl"
  13250. size_t parse(void *closure, const void *hd, const char *buf, size_t size,
  13251. const upb_bufhandle *handle) {
  13252. upb_json_parser *parser = closure;
  13253. /* Variables used by Ragel's generated code. */
  13254. int cs = parser->current_state;
  13255. int *stack = parser->parser_stack;
  13256. int top = parser->parser_top;
  13257. const char *p = buf;
  13258. const char *pe = buf + size;
  13259. const char *eof = &eof_ch;
  13260. parser->handle = handle;
  13261. UPB_UNUSED(hd);
  13262. UPB_UNUSED(handle);
  13263. capture_resume(parser, buf);
  13264. #line 2870 "upb/json/parser.c"
  13265. {
  13266. int _klen;
  13267. unsigned int _trans;
  13268. const char *_acts;
  13269. unsigned int _nacts;
  13270. const char *_keys;
  13271. if ( p == pe )
  13272. goto _test_eof;
  13273. if ( cs == 0 )
  13274. goto _out;
  13275. _resume:
  13276. _keys = _json_trans_keys + _json_key_offsets[cs];
  13277. _trans = _json_index_offsets[cs];
  13278. _klen = _json_single_lengths[cs];
  13279. if ( _klen > 0 ) {
  13280. const char *_lower = _keys;
  13281. const char *_mid;
  13282. const char *_upper = _keys + _klen - 1;
  13283. while (1) {
  13284. if ( _upper < _lower )
  13285. break;
  13286. _mid = _lower + ((_upper-_lower) >> 1);
  13287. if ( (*p) < *_mid )
  13288. _upper = _mid - 1;
  13289. else if ( (*p) > *_mid )
  13290. _lower = _mid + 1;
  13291. else {
  13292. _trans += (unsigned int)(_mid - _keys);
  13293. goto _match;
  13294. }
  13295. }
  13296. _keys += _klen;
  13297. _trans += _klen;
  13298. }
  13299. _klen = _json_range_lengths[cs];
  13300. if ( _klen > 0 ) {
  13301. const char *_lower = _keys;
  13302. const char *_mid;
  13303. const char *_upper = _keys + (_klen<<1) - 2;
  13304. while (1) {
  13305. if ( _upper < _lower )
  13306. break;
  13307. _mid = _lower + (((_upper-_lower) >> 1) & ~1);
  13308. if ( (*p) < _mid[0] )
  13309. _upper = _mid - 2;
  13310. else if ( (*p) > _mid[1] )
  13311. _lower = _mid + 2;
  13312. else {
  13313. _trans += (unsigned int)((_mid - _keys)>>1);
  13314. goto _match;
  13315. }
  13316. }
  13317. _trans += _klen;
  13318. }
  13319. _match:
  13320. _trans = _json_indicies[_trans];
  13321. cs = _json_trans_targs[_trans];
  13322. if ( _json_trans_actions[_trans] == 0 )
  13323. goto _again;
  13324. _acts = _json_actions + _json_trans_actions[_trans];
  13325. _nacts = (unsigned int) *_acts++;
  13326. while ( _nacts-- > 0 )
  13327. {
  13328. switch ( *_acts++ )
  13329. {
  13330. case 1:
  13331. #line 2597 "upb/json/parser.rl"
  13332. { p--; {cs = stack[--top]; goto _again;} }
  13333. break;
  13334. case 2:
  13335. #line 2599 "upb/json/parser.rl"
  13336. { p--; {stack[top++] = cs; cs = 23;goto _again;} }
  13337. break;
  13338. case 3:
  13339. #line 2603 "upb/json/parser.rl"
  13340. { start_text(parser, p); }
  13341. break;
  13342. case 4:
  13343. #line 2604 "upb/json/parser.rl"
  13344. { CHECK_RETURN_TOP(end_text(parser, p)); }
  13345. break;
  13346. case 5:
  13347. #line 2610 "upb/json/parser.rl"
  13348. { start_hex(parser); }
  13349. break;
  13350. case 6:
  13351. #line 2611 "upb/json/parser.rl"
  13352. { hexdigit(parser, p); }
  13353. break;
  13354. case 7:
  13355. #line 2612 "upb/json/parser.rl"
  13356. { CHECK_RETURN_TOP(end_hex(parser)); }
  13357. break;
  13358. case 8:
  13359. #line 2618 "upb/json/parser.rl"
  13360. { CHECK_RETURN_TOP(escape(parser, p)); }
  13361. break;
  13362. case 9:
  13363. #line 2624 "upb/json/parser.rl"
  13364. { p--; {cs = stack[--top]; goto _again;} }
  13365. break;
  13366. case 10:
  13367. #line 2629 "upb/json/parser.rl"
  13368. { start_year(parser, p); }
  13369. break;
  13370. case 11:
  13371. #line 2630 "upb/json/parser.rl"
  13372. { CHECK_RETURN_TOP(end_year(parser, p)); }
  13373. break;
  13374. case 12:
  13375. #line 2634 "upb/json/parser.rl"
  13376. { start_month(parser, p); }
  13377. break;
  13378. case 13:
  13379. #line 2635 "upb/json/parser.rl"
  13380. { CHECK_RETURN_TOP(end_month(parser, p)); }
  13381. break;
  13382. case 14:
  13383. #line 2639 "upb/json/parser.rl"
  13384. { start_day(parser, p); }
  13385. break;
  13386. case 15:
  13387. #line 2640 "upb/json/parser.rl"
  13388. { CHECK_RETURN_TOP(end_day(parser, p)); }
  13389. break;
  13390. case 16:
  13391. #line 2644 "upb/json/parser.rl"
  13392. { start_hour(parser, p); }
  13393. break;
  13394. case 17:
  13395. #line 2645 "upb/json/parser.rl"
  13396. { CHECK_RETURN_TOP(end_hour(parser, p)); }
  13397. break;
  13398. case 18:
  13399. #line 2649 "upb/json/parser.rl"
  13400. { start_minute(parser, p); }
  13401. break;
  13402. case 19:
  13403. #line 2650 "upb/json/parser.rl"
  13404. { CHECK_RETURN_TOP(end_minute(parser, p)); }
  13405. break;
  13406. case 20:
  13407. #line 2654 "upb/json/parser.rl"
  13408. { start_second(parser, p); }
  13409. break;
  13410. case 21:
  13411. #line 2655 "upb/json/parser.rl"
  13412. { CHECK_RETURN_TOP(end_second(parser, p)); }
  13413. break;
  13414. case 22:
  13415. #line 2660 "upb/json/parser.rl"
  13416. { start_duration_base(parser, p); }
  13417. break;
  13418. case 23:
  13419. #line 2661 "upb/json/parser.rl"
  13420. { CHECK_RETURN_TOP(end_duration_base(parser, p)); }
  13421. break;
  13422. case 24:
  13423. #line 2663 "upb/json/parser.rl"
  13424. { p--; {cs = stack[--top]; goto _again;} }
  13425. break;
  13426. case 25:
  13427. #line 2668 "upb/json/parser.rl"
  13428. { start_timestamp_base(parser); }
  13429. break;
  13430. case 26:
  13431. #line 2670 "upb/json/parser.rl"
  13432. { start_timestamp_fraction(parser, p); }
  13433. break;
  13434. case 27:
  13435. #line 2671 "upb/json/parser.rl"
  13436. { CHECK_RETURN_TOP(end_timestamp_fraction(parser, p)); }
  13437. break;
  13438. case 28:
  13439. #line 2673 "upb/json/parser.rl"
  13440. { start_timestamp_zone(parser, p); }
  13441. break;
  13442. case 29:
  13443. #line 2674 "upb/json/parser.rl"
  13444. { CHECK_RETURN_TOP(end_timestamp_zone(parser, p)); }
  13445. break;
  13446. case 30:
  13447. #line 2676 "upb/json/parser.rl"
  13448. { p--; {cs = stack[--top]; goto _again;} }
  13449. break;
  13450. case 31:
  13451. #line 2681 "upb/json/parser.rl"
  13452. { start_fieldmask_path_text(parser, p); }
  13453. break;
  13454. case 32:
  13455. #line 2682 "upb/json/parser.rl"
  13456. { end_fieldmask_path_text(parser, p); }
  13457. break;
  13458. case 33:
  13459. #line 2687 "upb/json/parser.rl"
  13460. { start_fieldmask_path(parser); }
  13461. break;
  13462. case 34:
  13463. #line 2688 "upb/json/parser.rl"
  13464. { end_fieldmask_path(parser); }
  13465. break;
  13466. case 35:
  13467. #line 2694 "upb/json/parser.rl"
  13468. { p--; {cs = stack[--top]; goto _again;} }
  13469. break;
  13470. case 36:
  13471. #line 2699 "upb/json/parser.rl"
  13472. {
  13473. if (is_wellknown_msg(parser, UPB_WELLKNOWN_TIMESTAMP)) {
  13474. {stack[top++] = cs; cs = 47;goto _again;}
  13475. } else if (is_wellknown_msg(parser, UPB_WELLKNOWN_DURATION)) {
  13476. {stack[top++] = cs; cs = 40;goto _again;}
  13477. } else if (is_wellknown_msg(parser, UPB_WELLKNOWN_FIELDMASK)) {
  13478. {stack[top++] = cs; cs = 75;goto _again;}
  13479. } else {
  13480. {stack[top++] = cs; cs = 32;goto _again;}
  13481. }
  13482. }
  13483. break;
  13484. case 37:
  13485. #line 2712 "upb/json/parser.rl"
  13486. { p--; {stack[top++] = cs; cs = 78;goto _again;} }
  13487. break;
  13488. case 38:
  13489. #line 2717 "upb/json/parser.rl"
  13490. {
  13491. if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
  13492. start_any_member(parser, p);
  13493. } else {
  13494. start_member(parser);
  13495. }
  13496. }
  13497. break;
  13498. case 39:
  13499. #line 2724 "upb/json/parser.rl"
  13500. { CHECK_RETURN_TOP(end_membername(parser)); }
  13501. break;
  13502. case 40:
  13503. #line 2727 "upb/json/parser.rl"
  13504. {
  13505. if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
  13506. end_any_member(parser, p);
  13507. } else {
  13508. end_member(parser);
  13509. }
  13510. }
  13511. break;
  13512. case 41:
  13513. #line 2738 "upb/json/parser.rl"
  13514. {
  13515. if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
  13516. start_any_object(parser, p);
  13517. } else {
  13518. start_object(parser);
  13519. }
  13520. }
  13521. break;
  13522. case 42:
  13523. #line 2747 "upb/json/parser.rl"
  13524. {
  13525. if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
  13526. CHECK_RETURN_TOP(end_any_object(parser, p));
  13527. } else {
  13528. end_object(parser);
  13529. }
  13530. }
  13531. break;
  13532. case 43:
  13533. #line 2759 "upb/json/parser.rl"
  13534. { CHECK_RETURN_TOP(start_array(parser)); }
  13535. break;
  13536. case 44:
  13537. #line 2763 "upb/json/parser.rl"
  13538. { end_array(parser); }
  13539. break;
  13540. case 45:
  13541. #line 2768 "upb/json/parser.rl"
  13542. { CHECK_RETURN_TOP(start_number(parser, p)); }
  13543. break;
  13544. case 46:
  13545. #line 2769 "upb/json/parser.rl"
  13546. { CHECK_RETURN_TOP(end_number(parser, p)); }
  13547. break;
  13548. case 47:
  13549. #line 2771 "upb/json/parser.rl"
  13550. { CHECK_RETURN_TOP(start_stringval(parser)); }
  13551. break;
  13552. case 48:
  13553. #line 2772 "upb/json/parser.rl"
  13554. { CHECK_RETURN_TOP(end_stringval(parser)); }
  13555. break;
  13556. case 49:
  13557. #line 2774 "upb/json/parser.rl"
  13558. { CHECK_RETURN_TOP(end_bool(parser, true)); }
  13559. break;
  13560. case 50:
  13561. #line 2776 "upb/json/parser.rl"
  13562. { CHECK_RETURN_TOP(end_bool(parser, false)); }
  13563. break;
  13564. case 51:
  13565. #line 2778 "upb/json/parser.rl"
  13566. { CHECK_RETURN_TOP(end_null(parser)); }
  13567. break;
  13568. case 52:
  13569. #line 2780 "upb/json/parser.rl"
  13570. { CHECK_RETURN_TOP(start_subobject_full(parser)); }
  13571. break;
  13572. case 53:
  13573. #line 2781 "upb/json/parser.rl"
  13574. { end_subobject_full(parser); }
  13575. break;
  13576. case 54:
  13577. #line 2786 "upb/json/parser.rl"
  13578. { p--; {cs = stack[--top]; goto _again;} }
  13579. break;
  13580. #line 3194 "upb/json/parser.c"
  13581. }
  13582. }
  13583. _again:
  13584. if ( cs == 0 )
  13585. goto _out;
  13586. if ( ++p != pe )
  13587. goto _resume;
  13588. _test_eof: {}
  13589. if ( p == eof )
  13590. {
  13591. const char *__acts = _json_actions + _json_eof_actions[cs];
  13592. unsigned int __nacts = (unsigned int) *__acts++;
  13593. while ( __nacts-- > 0 ) {
  13594. switch ( *__acts++ ) {
  13595. case 0:
  13596. #line 2595 "upb/json/parser.rl"
  13597. { p--; {cs = stack[--top]; if ( p == pe )
  13598. goto _test_eof;
  13599. goto _again;} }
  13600. break;
  13601. case 46:
  13602. #line 2769 "upb/json/parser.rl"
  13603. { CHECK_RETURN_TOP(end_number(parser, p)); }
  13604. break;
  13605. case 49:
  13606. #line 2774 "upb/json/parser.rl"
  13607. { CHECK_RETURN_TOP(end_bool(parser, true)); }
  13608. break;
  13609. case 50:
  13610. #line 2776 "upb/json/parser.rl"
  13611. { CHECK_RETURN_TOP(end_bool(parser, false)); }
  13612. break;
  13613. case 51:
  13614. #line 2778 "upb/json/parser.rl"
  13615. { CHECK_RETURN_TOP(end_null(parser)); }
  13616. break;
  13617. case 53:
  13618. #line 2781 "upb/json/parser.rl"
  13619. { end_subobject_full(parser); }
  13620. break;
  13621. #line 3236 "upb/json/parser.c"
  13622. }
  13623. }
  13624. }
  13625. _out: {}
  13626. }
  13627. #line 2814 "upb/json/parser.rl"
  13628. if (p != pe) {
  13629. upb_status_seterrf(&parser->status, "Parse error at '%.*s'\n", pe - p, p);
  13630. upb_env_reporterror(parser->env, &parser->status);
  13631. } else {
  13632. capture_suspend(parser, &p);
  13633. }
  13634. error:
  13635. /* Save parsing state back to parser. */
  13636. parser->current_state = cs;
  13637. parser->parser_top = top;
  13638. return p - buf;
  13639. }
  13640. static bool end(void *closure, const void *hd) {
  13641. upb_json_parser *parser = closure;
  13642. /* Prevent compile warning on unused static constants. */
  13643. UPB_UNUSED(json_start);
  13644. UPB_UNUSED(json_en_duration_machine);
  13645. UPB_UNUSED(json_en_fieldmask_machine);
  13646. UPB_UNUSED(json_en_number_machine);
  13647. UPB_UNUSED(json_en_string_machine);
  13648. UPB_UNUSED(json_en_timestamp_machine);
  13649. UPB_UNUSED(json_en_value_machine);
  13650. UPB_UNUSED(json_en_main);
  13651. parse(parser, hd, &eof_ch, 0, NULL);
  13652. return parser->current_state >= 106;
  13653. }
  13654. static void json_parser_reset(upb_json_parser *p) {
  13655. int cs;
  13656. int top;
  13657. p->top = p->stack;
  13658. init_frame(p->top);
  13659. /* Emit Ragel initialization of the parser. */
  13660. #line 3288 "upb/json/parser.c"
  13661. {
  13662. cs = json_start;
  13663. top = 0;
  13664. }
  13665. #line 2857 "upb/json/parser.rl"
  13666. p->current_state = cs;
  13667. p->parser_top = top;
  13668. accumulate_clear(p);
  13669. p->multipart_state = MULTIPART_INACTIVE;
  13670. p->capture = NULL;
  13671. p->accumulated = NULL;
  13672. upb_status_clear(&p->status);
  13673. }
  13674. static void visit_json_parsermethod(const upb_refcounted *r,
  13675. upb_refcounted_visit *visit,
  13676. void *closure) {
  13677. const upb_json_parsermethod *method = (upb_json_parsermethod*)r;
  13678. visit(r, upb_msgdef_upcast2(method->msg), closure);
  13679. }
  13680. static void free_json_parsermethod(upb_refcounted *r) {
  13681. upb_json_parsermethod *method = (upb_json_parsermethod*)r;
  13682. upb_inttable_iter i;
  13683. upb_inttable_begin(&i, &method->name_tables);
  13684. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  13685. upb_value val = upb_inttable_iter_value(&i);
  13686. upb_strtable *t = upb_value_getptr(val);
  13687. upb_strtable_uninit(t);
  13688. upb_gfree(t);
  13689. }
  13690. upb_inttable_uninit(&method->name_tables);
  13691. upb_gfree(r);
  13692. }
  13693. static void add_jsonname_table(upb_json_parsermethod *m, const upb_msgdef* md) {
  13694. upb_msg_field_iter i;
  13695. upb_strtable *t;
  13696. /* It would be nice to stack-allocate this, but protobufs do not limit the
  13697. * length of fields to any reasonable limit. */
  13698. char *buf = NULL;
  13699. size_t len = 0;
  13700. if (upb_inttable_lookupptr(&m->name_tables, md, NULL)) {
  13701. return;
  13702. }
  13703. /* TODO(haberman): handle malloc failure. */
  13704. t = upb_gmalloc(sizeof(*t));
  13705. upb_strtable_init(t, UPB_CTYPE_CONSTPTR);
  13706. upb_inttable_insertptr(&m->name_tables, md, upb_value_ptr(t));
  13707. for(upb_msg_field_begin(&i, md);
  13708. !upb_msg_field_done(&i);
  13709. upb_msg_field_next(&i)) {
  13710. const upb_fielddef *f = upb_msg_iter_field(&i);
  13711. /* Add an entry for the JSON name. */
  13712. size_t field_len = upb_fielddef_getjsonname(f, buf, len);
  13713. if (field_len > len) {
  13714. size_t len2;
  13715. buf = upb_grealloc(buf, 0, field_len);
  13716. len = field_len;
  13717. len2 = upb_fielddef_getjsonname(f, buf, len);
  13718. UPB_ASSERT(len == len2);
  13719. }
  13720. upb_strtable_insert(t, buf, upb_value_constptr(f));
  13721. if (strcmp(buf, upb_fielddef_name(f)) != 0) {
  13722. /* Since the JSON name is different from the regular field name, add an
  13723. * entry for the raw name (compliant proto3 JSON parsers must accept
  13724. * both). */
  13725. upb_strtable_insert(t, upb_fielddef_name(f), upb_value_constptr(f));
  13726. }
  13727. if (upb_fielddef_issubmsg(f)) {
  13728. add_jsonname_table(m, upb_fielddef_msgsubdef(f));
  13729. }
  13730. }
  13731. upb_gfree(buf);
  13732. }
  13733. /* Public API *****************************************************************/
  13734. upb_json_parser *upb_json_parser_create(upb_env *env,
  13735. const upb_json_parsermethod *method,
  13736. const upb_symtab* symtab,
  13737. upb_sink *output,
  13738. bool ignore_json_unknown) {
  13739. #ifndef NDEBUG
  13740. const size_t size_before = upb_env_bytesallocated(env);
  13741. #endif
  13742. upb_json_parser *p = upb_env_malloc(env, sizeof(upb_json_parser));
  13743. if (!p) return false;
  13744. p->env = env;
  13745. p->method = method;
  13746. p->limit = p->stack + UPB_JSON_MAX_DEPTH;
  13747. p->accumulate_buf = NULL;
  13748. p->accumulate_buf_size = 0;
  13749. upb_bytessink_reset(&p->input_, &method->input_handler_, p);
  13750. json_parser_reset(p);
  13751. upb_sink_reset(&p->top->sink, output->handlers, output->closure);
  13752. p->top->m = upb_handlers_msgdef(output->handlers);
  13753. if (is_wellknown_msg(p, UPB_WELLKNOWN_ANY)) {
  13754. p->top->is_any = true;
  13755. p->top->any_frame =
  13756. upb_env_malloc(p->env, sizeof(upb_jsonparser_any_frame));
  13757. json_parser_any_frame_reset(p->top->any_frame);
  13758. } else {
  13759. p->top->is_any = false;
  13760. p->top->any_frame = NULL;
  13761. }
  13762. set_name_table(p, p->top);
  13763. p->symtab = symtab;
  13764. p->ignore_json_unknown = ignore_json_unknown;
  13765. /* If this fails, uncomment and increase the value in parser.h. */
  13766. /* fprintf(stderr, "%zd\n", upb_env_bytesallocated(env) - size_before); */
  13767. UPB_ASSERT_DEBUGVAR(upb_env_bytesallocated(env) - size_before <=
  13768. UPB_JSON_PARSER_SIZE);
  13769. return p;
  13770. }
  13771. upb_bytessink *upb_json_parser_input(upb_json_parser *p) {
  13772. return &p->input_;
  13773. }
  13774. upb_json_parsermethod *upb_json_parsermethod_new(const upb_msgdef* md,
  13775. const void* owner) {
  13776. static const struct upb_refcounted_vtbl vtbl = {visit_json_parsermethod,
  13777. free_json_parsermethod};
  13778. upb_json_parsermethod *ret = upb_gmalloc(sizeof(*ret));
  13779. upb_refcounted_init(upb_json_parsermethod_upcast_mutable(ret), &vtbl, owner);
  13780. ret->msg = md;
  13781. upb_ref2(md, ret);
  13782. upb_byteshandler_init(&ret->input_handler_);
  13783. upb_byteshandler_setstring(&ret->input_handler_, parse, ret);
  13784. upb_byteshandler_setendstr(&ret->input_handler_, end, ret);
  13785. upb_inttable_init(&ret->name_tables, UPB_CTYPE_PTR);
  13786. add_jsonname_table(ret, md);
  13787. return ret;
  13788. }
  13789. const upb_byteshandler *upb_json_parsermethod_inputhandler(
  13790. const upb_json_parsermethod *m) {
  13791. return &m->input_handler_;
  13792. }
  13793. /*
  13794. ** This currently uses snprintf() to format primitives, and could be optimized
  13795. ** further.
  13796. */
  13797. #include <string.h>
  13798. #include <stdint.h>
  13799. #include <time.h>
  13800. struct upb_json_printer {
  13801. upb_sink input_;
  13802. /* BytesSink closure. */
  13803. void *subc_;
  13804. upb_bytessink *output_;
  13805. /* We track the depth so that we know when to emit startstr/endstr on the
  13806. * output. */
  13807. int depth_;
  13808. /* Have we emitted the first element? This state is necessary to emit commas
  13809. * without leaving a trailing comma in arrays/maps. We keep this state per
  13810. * frame depth.
  13811. *
  13812. * Why max_depth * 2? UPB_MAX_HANDLER_DEPTH counts depth as nested messages.
  13813. * We count frames (contexts in which we separate elements by commas) as both
  13814. * repeated fields and messages (maps), and the worst case is a
  13815. * message->repeated field->submessage->repeated field->... nesting. */
  13816. bool first_elem_[UPB_MAX_HANDLER_DEPTH * 2];
  13817. /* To print timestamp, printer needs to cache its seconds and nanos values
  13818. * and convert them when ending timestamp message. See comments of
  13819. * printer_sethandlers_timestamp for more detail. */
  13820. int64_t seconds;
  13821. int32_t nanos;
  13822. };
  13823. /* StringPiece; a pointer plus a length. */
  13824. typedef struct {
  13825. char *ptr;
  13826. size_t len;
  13827. } strpc;
  13828. void freestrpc(void *ptr) {
  13829. strpc *pc = ptr;
  13830. upb_gfree(pc->ptr);
  13831. upb_gfree(pc);
  13832. }
  13833. /* Convert fielddef name to JSON name and return as a string piece. */
  13834. strpc *newstrpc(upb_handlers *h, const upb_fielddef *f,
  13835. bool preserve_fieldnames) {
  13836. /* TODO(haberman): handle malloc failure. */
  13837. strpc *ret = upb_gmalloc(sizeof(*ret));
  13838. if (preserve_fieldnames) {
  13839. ret->ptr = upb_gstrdup(upb_fielddef_name(f));
  13840. ret->len = strlen(ret->ptr);
  13841. } else {
  13842. size_t len;
  13843. ret->len = upb_fielddef_getjsonname(f, NULL, 0);
  13844. ret->ptr = upb_gmalloc(ret->len);
  13845. len = upb_fielddef_getjsonname(f, ret->ptr, ret->len);
  13846. UPB_ASSERT(len == ret->len);
  13847. ret->len--; /* NULL */
  13848. }
  13849. upb_handlers_addcleanup(h, ret, freestrpc);
  13850. return ret;
  13851. }
  13852. /* Convert a null-terminated const char* to a string piece. */
  13853. strpc *newstrpc_str(upb_handlers *h, const char * str) {
  13854. strpc * ret = upb_gmalloc(sizeof(*ret));
  13855. ret->ptr = upb_gstrdup(str);
  13856. ret->len = strlen(str);
  13857. upb_handlers_addcleanup(h, ret, freestrpc);
  13858. return ret;
  13859. }
  13860. /* ------------ JSON string printing: values, maps, arrays ------------------ */
  13861. static void print_data(
  13862. upb_json_printer *p, const char *buf, unsigned int len) {
  13863. /* TODO: Will need to change if we support pushback from the sink. */
  13864. size_t n = upb_bytessink_putbuf(p->output_, p->subc_, buf, len, NULL);
  13865. UPB_ASSERT(n == len);
  13866. }
  13867. static void print_comma(upb_json_printer *p) {
  13868. if (!p->first_elem_[p->depth_]) {
  13869. print_data(p, ",", 1);
  13870. }
  13871. p->first_elem_[p->depth_] = false;
  13872. }
  13873. /* Helpers that print properly formatted elements to the JSON output stream. */
  13874. /* Used for escaping control chars in strings. */
  13875. static const char kControlCharLimit = 0x20;
  13876. UPB_INLINE bool is_json_escaped(char c) {
  13877. /* See RFC 4627. */
  13878. unsigned char uc = (unsigned char)c;
  13879. return uc < kControlCharLimit || uc == '"' || uc == '\\';
  13880. }
  13881. UPB_INLINE const char* json_nice_escape(char c) {
  13882. switch (c) {
  13883. case '"': return "\\\"";
  13884. case '\\': return "\\\\";
  13885. case '\b': return "\\b";
  13886. case '\f': return "\\f";
  13887. case '\n': return "\\n";
  13888. case '\r': return "\\r";
  13889. case '\t': return "\\t";
  13890. default: return NULL;
  13891. }
  13892. }
  13893. /* Write a properly escaped string chunk. The surrounding quotes are *not*
  13894. * printed; this is so that the caller has the option of emitting the string
  13895. * content in chunks. */
  13896. static void putstring(upb_json_printer *p, const char *buf, unsigned int len) {
  13897. const char* unescaped_run = NULL;
  13898. unsigned int i;
  13899. for (i = 0; i < len; i++) {
  13900. char c = buf[i];
  13901. /* Handle escaping. */
  13902. if (is_json_escaped(c)) {
  13903. /* Use a "nice" escape, like \n, if one exists for this character. */
  13904. const char* escape = json_nice_escape(c);
  13905. /* If we don't have a specific 'nice' escape code, use a \uXXXX-style
  13906. * escape. */
  13907. char escape_buf[8];
  13908. if (!escape) {
  13909. unsigned char byte = (unsigned char)c;
  13910. _upb_snprintf(escape_buf, sizeof(escape_buf), "\\u%04x", (int)byte);
  13911. escape = escape_buf;
  13912. }
  13913. /* N.B. that we assume that the input encoding is equal to the output
  13914. * encoding (both UTF-8 for now), so for chars >= 0x20 and != \, ", we
  13915. * can simply pass the bytes through. */
  13916. /* If there's a current run of unescaped chars, print that run first. */
  13917. if (unescaped_run) {
  13918. print_data(p, unescaped_run, &buf[i] - unescaped_run);
  13919. unescaped_run = NULL;
  13920. }
  13921. /* Then print the escape code. */
  13922. print_data(p, escape, strlen(escape));
  13923. } else {
  13924. /* Add to the current unescaped run of characters. */
  13925. if (unescaped_run == NULL) {
  13926. unescaped_run = &buf[i];
  13927. }
  13928. }
  13929. }
  13930. /* If the string ended in a run of unescaped characters, print that last run. */
  13931. if (unescaped_run) {
  13932. print_data(p, unescaped_run, &buf[len] - unescaped_run);
  13933. }
  13934. }
  13935. #define CHKLENGTH(x) if (!(x)) return -1;
  13936. /* Helpers that format floating point values according to our custom formats.
  13937. * Right now we use %.8g and %.17g for float/double, respectively, to match
  13938. * proto2::util::JsonFormat's defaults. May want to change this later. */
  13939. const char neginf[] = "\"-Infinity\"";
  13940. const char inf[] = "\"Infinity\"";
  13941. static size_t fmt_double(double val, char* buf, size_t length) {
  13942. if (val == (1.0 / 0.0)) {
  13943. CHKLENGTH(length >= strlen(inf));
  13944. strcpy(buf, inf);
  13945. return strlen(inf);
  13946. } else if (val == (-1.0 / 0.0)) {
  13947. CHKLENGTH(length >= strlen(neginf));
  13948. strcpy(buf, neginf);
  13949. return strlen(neginf);
  13950. } else {
  13951. size_t n = _upb_snprintf(buf, length, "%.17g", val);
  13952. CHKLENGTH(n > 0 && n < length);
  13953. return n;
  13954. }
  13955. }
  13956. static size_t fmt_float(float val, char* buf, size_t length) {
  13957. size_t n = _upb_snprintf(buf, length, "%.8g", val);
  13958. CHKLENGTH(n > 0 && n < length);
  13959. return n;
  13960. }
  13961. static size_t fmt_bool(bool val, char* buf, size_t length) {
  13962. size_t n = _upb_snprintf(buf, length, "%s", (val ? "true" : "false"));
  13963. CHKLENGTH(n > 0 && n < length);
  13964. return n;
  13965. }
  13966. static size_t fmt_int64(long val, char* buf, size_t length) {
  13967. size_t n = _upb_snprintf(buf, length, "%ld", val);
  13968. CHKLENGTH(n > 0 && n < length);
  13969. return n;
  13970. }
  13971. static size_t fmt_uint64(unsigned long long val, char* buf, size_t length) {
  13972. size_t n = _upb_snprintf(buf, length, "%llu", val);
  13973. CHKLENGTH(n > 0 && n < length);
  13974. return n;
  13975. }
  13976. /* Print a map key given a field name. Called by scalar field handlers and by
  13977. * startseq for repeated fields. */
  13978. static bool putkey(void *closure, const void *handler_data) {
  13979. upb_json_printer *p = closure;
  13980. const strpc *key = handler_data;
  13981. print_comma(p);
  13982. print_data(p, "\"", 1);
  13983. putstring(p, key->ptr, key->len);
  13984. print_data(p, "\":", 2);
  13985. return true;
  13986. }
  13987. #define CHKFMT(val) if ((val) == (size_t)-1) return false;
  13988. #define CHK(val) if (!(val)) return false;
  13989. #define TYPE_HANDLERS(type, fmt_func) \
  13990. static bool put##type(void *closure, const void *handler_data, type val) { \
  13991. upb_json_printer *p = closure; \
  13992. char data[64]; \
  13993. size_t length = fmt_func(val, data, sizeof(data)); \
  13994. UPB_UNUSED(handler_data); \
  13995. CHKFMT(length); \
  13996. print_data(p, data, length); \
  13997. return true; \
  13998. } \
  13999. static bool scalar_##type(void *closure, const void *handler_data, \
  14000. type val) { \
  14001. CHK(putkey(closure, handler_data)); \
  14002. CHK(put##type(closure, handler_data, val)); \
  14003. return true; \
  14004. } \
  14005. static bool repeated_##type(void *closure, const void *handler_data, \
  14006. type val) { \
  14007. upb_json_printer *p = closure; \
  14008. print_comma(p); \
  14009. CHK(put##type(closure, handler_data, val)); \
  14010. return true; \
  14011. }
  14012. #define TYPE_HANDLERS_MAPKEY(type, fmt_func) \
  14013. static bool putmapkey_##type(void *closure, const void *handler_data, \
  14014. type val) { \
  14015. upb_json_printer *p = closure; \
  14016. print_data(p, "\"", 1); \
  14017. CHK(put##type(closure, handler_data, val)); \
  14018. print_data(p, "\":", 2); \
  14019. return true; \
  14020. }
  14021. TYPE_HANDLERS(double, fmt_double)
  14022. TYPE_HANDLERS(float, fmt_float)
  14023. TYPE_HANDLERS(bool, fmt_bool)
  14024. TYPE_HANDLERS(int32_t, fmt_int64)
  14025. TYPE_HANDLERS(uint32_t, fmt_int64)
  14026. TYPE_HANDLERS(int64_t, fmt_int64)
  14027. TYPE_HANDLERS(uint64_t, fmt_uint64)
  14028. /* double and float are not allowed to be map keys. */
  14029. TYPE_HANDLERS_MAPKEY(bool, fmt_bool)
  14030. TYPE_HANDLERS_MAPKEY(int32_t, fmt_int64)
  14031. TYPE_HANDLERS_MAPKEY(uint32_t, fmt_int64)
  14032. TYPE_HANDLERS_MAPKEY(int64_t, fmt_int64)
  14033. TYPE_HANDLERS_MAPKEY(uint64_t, fmt_uint64)
  14034. #undef TYPE_HANDLERS
  14035. #undef TYPE_HANDLERS_MAPKEY
  14036. typedef struct {
  14037. void *keyname;
  14038. const upb_enumdef *enumdef;
  14039. } EnumHandlerData;
  14040. static bool scalar_enum(void *closure, const void *handler_data,
  14041. int32_t val) {
  14042. const EnumHandlerData *hd = handler_data;
  14043. upb_json_printer *p = closure;
  14044. const char *symbolic_name;
  14045. CHK(putkey(closure, hd->keyname));
  14046. symbolic_name = upb_enumdef_iton(hd->enumdef, val);
  14047. if (symbolic_name) {
  14048. print_data(p, "\"", 1);
  14049. putstring(p, symbolic_name, strlen(symbolic_name));
  14050. print_data(p, "\"", 1);
  14051. } else {
  14052. putint32_t(closure, NULL, val);
  14053. }
  14054. return true;
  14055. }
  14056. static void print_enum_symbolic_name(upb_json_printer *p,
  14057. const upb_enumdef *def,
  14058. int32_t val) {
  14059. const char *symbolic_name = upb_enumdef_iton(def, val);
  14060. if (symbolic_name) {
  14061. print_data(p, "\"", 1);
  14062. putstring(p, symbolic_name, strlen(symbolic_name));
  14063. print_data(p, "\"", 1);
  14064. } else {
  14065. putint32_t(p, NULL, val);
  14066. }
  14067. }
  14068. static bool repeated_enum(void *closure, const void *handler_data,
  14069. int32_t val) {
  14070. const EnumHandlerData *hd = handler_data;
  14071. upb_json_printer *p = closure;
  14072. print_comma(p);
  14073. print_enum_symbolic_name(p, hd->enumdef, val);
  14074. return true;
  14075. }
  14076. static bool mapvalue_enum(void *closure, const void *handler_data,
  14077. int32_t val) {
  14078. const EnumHandlerData *hd = handler_data;
  14079. upb_json_printer *p = closure;
  14080. print_enum_symbolic_name(p, hd->enumdef, val);
  14081. return true;
  14082. }
  14083. static void *scalar_startsubmsg(void *closure, const void *handler_data) {
  14084. return putkey(closure, handler_data) ? closure : UPB_BREAK;
  14085. }
  14086. static void *repeated_startsubmsg(void *closure, const void *handler_data) {
  14087. upb_json_printer *p = closure;
  14088. UPB_UNUSED(handler_data);
  14089. print_comma(p);
  14090. return closure;
  14091. }
  14092. static void start_frame(upb_json_printer *p) {
  14093. p->depth_++;
  14094. p->first_elem_[p->depth_] = true;
  14095. print_data(p, "{", 1);
  14096. }
  14097. static void end_frame(upb_json_printer *p) {
  14098. print_data(p, "}", 1);
  14099. p->depth_--;
  14100. }
  14101. static bool printer_startmsg(void *closure, const void *handler_data) {
  14102. upb_json_printer *p = closure;
  14103. UPB_UNUSED(handler_data);
  14104. if (p->depth_ == 0) {
  14105. upb_bytessink_start(p->output_, 0, &p->subc_);
  14106. }
  14107. start_frame(p);
  14108. return true;
  14109. }
  14110. static bool printer_endmsg(void *closure, const void *handler_data, upb_status *s) {
  14111. upb_json_printer *p = closure;
  14112. UPB_UNUSED(handler_data);
  14113. UPB_UNUSED(s);
  14114. end_frame(p);
  14115. if (p->depth_ == 0) {
  14116. upb_bytessink_end(p->output_);
  14117. }
  14118. return true;
  14119. }
  14120. static void *startseq(void *closure, const void *handler_data) {
  14121. upb_json_printer *p = closure;
  14122. CHK(putkey(closure, handler_data));
  14123. p->depth_++;
  14124. p->first_elem_[p->depth_] = true;
  14125. print_data(p, "[", 1);
  14126. return closure;
  14127. }
  14128. static bool endseq(void *closure, const void *handler_data) {
  14129. upb_json_printer *p = closure;
  14130. UPB_UNUSED(handler_data);
  14131. print_data(p, "]", 1);
  14132. p->depth_--;
  14133. return true;
  14134. }
  14135. static void *startmap(void *closure, const void *handler_data) {
  14136. upb_json_printer *p = closure;
  14137. CHK(putkey(closure, handler_data));
  14138. p->depth_++;
  14139. p->first_elem_[p->depth_] = true;
  14140. print_data(p, "{", 1);
  14141. return closure;
  14142. }
  14143. static bool endmap(void *closure, const void *handler_data) {
  14144. upb_json_printer *p = closure;
  14145. UPB_UNUSED(handler_data);
  14146. print_data(p, "}", 1);
  14147. p->depth_--;
  14148. return true;
  14149. }
  14150. static size_t putstr(void *closure, const void *handler_data, const char *str,
  14151. size_t len, const upb_bufhandle *handle) {
  14152. upb_json_printer *p = closure;
  14153. UPB_UNUSED(handler_data);
  14154. UPB_UNUSED(handle);
  14155. putstring(p, str, len);
  14156. return len;
  14157. }
  14158. /* This has to Base64 encode the bytes, because JSON has no "bytes" type. */
  14159. static size_t putbytes(void *closure, const void *handler_data, const char *str,
  14160. size_t len, const upb_bufhandle *handle) {
  14161. upb_json_printer *p = closure;
  14162. /* This is the regular base64, not the "web-safe" version. */
  14163. static const char base64[] =
  14164. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  14165. /* Base64-encode. */
  14166. char data[16000];
  14167. const char *limit = data + sizeof(data);
  14168. const unsigned char *from = (const unsigned char*)str;
  14169. char *to = data;
  14170. size_t remaining = len;
  14171. size_t bytes;
  14172. UPB_UNUSED(handler_data);
  14173. UPB_UNUSED(handle);
  14174. print_data(p, "\"", 1);
  14175. while (remaining > 2) {
  14176. if (limit - to < 4) {
  14177. bytes = to - data;
  14178. putstring(p, data, bytes);
  14179. to = data;
  14180. }
  14181. to[0] = base64[from[0] >> 2];
  14182. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  14183. to[2] = base64[((from[1] & 0xf) << 2) | (from[2] >> 6)];
  14184. to[3] = base64[from[2] & 0x3f];
  14185. remaining -= 3;
  14186. to += 4;
  14187. from += 3;
  14188. }
  14189. switch (remaining) {
  14190. case 2:
  14191. to[0] = base64[from[0] >> 2];
  14192. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  14193. to[2] = base64[(from[1] & 0xf) << 2];
  14194. to[3] = '=';
  14195. to += 4;
  14196. from += 2;
  14197. break;
  14198. case 1:
  14199. to[0] = base64[from[0] >> 2];
  14200. to[1] = base64[((from[0] & 0x3) << 4)];
  14201. to[2] = '=';
  14202. to[3] = '=';
  14203. to += 4;
  14204. from += 1;
  14205. break;
  14206. }
  14207. bytes = to - data;
  14208. putstring(p, data, bytes);
  14209. print_data(p, "\"", 1);
  14210. return len;
  14211. }
  14212. static void *scalar_startstr(void *closure, const void *handler_data,
  14213. size_t size_hint) {
  14214. upb_json_printer *p = closure;
  14215. UPB_UNUSED(handler_data);
  14216. UPB_UNUSED(size_hint);
  14217. CHK(putkey(closure, handler_data));
  14218. print_data(p, "\"", 1);
  14219. return p;
  14220. }
  14221. static size_t scalar_str(void *closure, const void *handler_data,
  14222. const char *str, size_t len,
  14223. const upb_bufhandle *handle) {
  14224. CHK(putstr(closure, handler_data, str, len, handle));
  14225. return len;
  14226. }
  14227. static bool scalar_endstr(void *closure, const void *handler_data) {
  14228. upb_json_printer *p = closure;
  14229. UPB_UNUSED(handler_data);
  14230. print_data(p, "\"", 1);
  14231. return true;
  14232. }
  14233. static void *repeated_startstr(void *closure, const void *handler_data,
  14234. size_t size_hint) {
  14235. upb_json_printer *p = closure;
  14236. UPB_UNUSED(handler_data);
  14237. UPB_UNUSED(size_hint);
  14238. print_comma(p);
  14239. print_data(p, "\"", 1);
  14240. return p;
  14241. }
  14242. static size_t repeated_str(void *closure, const void *handler_data,
  14243. const char *str, size_t len,
  14244. const upb_bufhandle *handle) {
  14245. CHK(putstr(closure, handler_data, str, len, handle));
  14246. return len;
  14247. }
  14248. static bool repeated_endstr(void *closure, const void *handler_data) {
  14249. upb_json_printer *p = closure;
  14250. UPB_UNUSED(handler_data);
  14251. print_data(p, "\"", 1);
  14252. return true;
  14253. }
  14254. static void *mapkeyval_startstr(void *closure, const void *handler_data,
  14255. size_t size_hint) {
  14256. upb_json_printer *p = closure;
  14257. UPB_UNUSED(handler_data);
  14258. UPB_UNUSED(size_hint);
  14259. print_data(p, "\"", 1);
  14260. return p;
  14261. }
  14262. static size_t mapkey_str(void *closure, const void *handler_data,
  14263. const char *str, size_t len,
  14264. const upb_bufhandle *handle) {
  14265. CHK(putstr(closure, handler_data, str, len, handle));
  14266. return len;
  14267. }
  14268. static bool mapkey_endstr(void *closure, const void *handler_data) {
  14269. upb_json_printer *p = closure;
  14270. UPB_UNUSED(handler_data);
  14271. print_data(p, "\":", 2);
  14272. return true;
  14273. }
  14274. static bool mapvalue_endstr(void *closure, const void *handler_data) {
  14275. upb_json_printer *p = closure;
  14276. UPB_UNUSED(handler_data);
  14277. print_data(p, "\"", 1);
  14278. return true;
  14279. }
  14280. static size_t scalar_bytes(void *closure, const void *handler_data,
  14281. const char *str, size_t len,
  14282. const upb_bufhandle *handle) {
  14283. CHK(putkey(closure, handler_data));
  14284. CHK(putbytes(closure, handler_data, str, len, handle));
  14285. return len;
  14286. }
  14287. static size_t repeated_bytes(void *closure, const void *handler_data,
  14288. const char *str, size_t len,
  14289. const upb_bufhandle *handle) {
  14290. upb_json_printer *p = closure;
  14291. print_comma(p);
  14292. CHK(putbytes(closure, handler_data, str, len, handle));
  14293. return len;
  14294. }
  14295. static size_t mapkey_bytes(void *closure, const void *handler_data,
  14296. const char *str, size_t len,
  14297. const upb_bufhandle *handle) {
  14298. upb_json_printer *p = closure;
  14299. CHK(putbytes(closure, handler_data, str, len, handle));
  14300. print_data(p, ":", 1);
  14301. return len;
  14302. }
  14303. static void set_enum_hd(upb_handlers *h,
  14304. const upb_fielddef *f,
  14305. bool preserve_fieldnames,
  14306. upb_handlerattr *attr) {
  14307. EnumHandlerData *hd = upb_gmalloc(sizeof(EnumHandlerData));
  14308. hd->enumdef = (const upb_enumdef *)upb_fielddef_subdef(f);
  14309. hd->keyname = newstrpc(h, f, preserve_fieldnames);
  14310. upb_handlers_addcleanup(h, hd, upb_gfree);
  14311. upb_handlerattr_sethandlerdata(attr, hd);
  14312. }
  14313. /* Set up handlers for a mapentry submessage (i.e., an individual key/value pair
  14314. * in a map).
  14315. *
  14316. * TODO: Handle missing key, missing value, out-of-order key/value, or repeated
  14317. * key or value cases properly. The right way to do this is to allocate a
  14318. * temporary structure at the start of a mapentry submessage, store key and
  14319. * value data in it as key and value handlers are called, and then print the
  14320. * key/value pair once at the end of the submessage. If we don't do this, we
  14321. * should at least detect the case and throw an error. However, so far all of
  14322. * our sources that emit mapentry messages do so canonically (with one key
  14323. * field, and then one value field), so this is not a pressing concern at the
  14324. * moment. */
  14325. void printer_sethandlers_mapentry(const void *closure, bool preserve_fieldnames,
  14326. upb_handlers *h) {
  14327. const upb_msgdef *md = upb_handlers_msgdef(h);
  14328. /* A mapentry message is printed simply as '"key": value'. Rather than
  14329. * special-case key and value for every type below, we just handle both
  14330. * fields explicitly here. */
  14331. const upb_fielddef* key_field = upb_msgdef_itof(md, UPB_MAPENTRY_KEY);
  14332. const upb_fielddef* value_field = upb_msgdef_itof(md, UPB_MAPENTRY_VALUE);
  14333. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  14334. UPB_UNUSED(closure);
  14335. switch (upb_fielddef_type(key_field)) {
  14336. case UPB_TYPE_INT32:
  14337. upb_handlers_setint32(h, key_field, putmapkey_int32_t, &empty_attr);
  14338. break;
  14339. case UPB_TYPE_INT64:
  14340. upb_handlers_setint64(h, key_field, putmapkey_int64_t, &empty_attr);
  14341. break;
  14342. case UPB_TYPE_UINT32:
  14343. upb_handlers_setuint32(h, key_field, putmapkey_uint32_t, &empty_attr);
  14344. break;
  14345. case UPB_TYPE_UINT64:
  14346. upb_handlers_setuint64(h, key_field, putmapkey_uint64_t, &empty_attr);
  14347. break;
  14348. case UPB_TYPE_BOOL:
  14349. upb_handlers_setbool(h, key_field, putmapkey_bool, &empty_attr);
  14350. break;
  14351. case UPB_TYPE_STRING:
  14352. upb_handlers_setstartstr(h, key_field, mapkeyval_startstr, &empty_attr);
  14353. upb_handlers_setstring(h, key_field, mapkey_str, &empty_attr);
  14354. upb_handlers_setendstr(h, key_field, mapkey_endstr, &empty_attr);
  14355. break;
  14356. case UPB_TYPE_BYTES:
  14357. upb_handlers_setstring(h, key_field, mapkey_bytes, &empty_attr);
  14358. break;
  14359. default:
  14360. UPB_ASSERT(false);
  14361. break;
  14362. }
  14363. switch (upb_fielddef_type(value_field)) {
  14364. case UPB_TYPE_INT32:
  14365. upb_handlers_setint32(h, value_field, putint32_t, &empty_attr);
  14366. break;
  14367. case UPB_TYPE_INT64:
  14368. upb_handlers_setint64(h, value_field, putint64_t, &empty_attr);
  14369. break;
  14370. case UPB_TYPE_UINT32:
  14371. upb_handlers_setuint32(h, value_field, putuint32_t, &empty_attr);
  14372. break;
  14373. case UPB_TYPE_UINT64:
  14374. upb_handlers_setuint64(h, value_field, putuint64_t, &empty_attr);
  14375. break;
  14376. case UPB_TYPE_BOOL:
  14377. upb_handlers_setbool(h, value_field, putbool, &empty_attr);
  14378. break;
  14379. case UPB_TYPE_FLOAT:
  14380. upb_handlers_setfloat(h, value_field, putfloat, &empty_attr);
  14381. break;
  14382. case UPB_TYPE_DOUBLE:
  14383. upb_handlers_setdouble(h, value_field, putdouble, &empty_attr);
  14384. break;
  14385. case UPB_TYPE_STRING:
  14386. upb_handlers_setstartstr(h, value_field, mapkeyval_startstr, &empty_attr);
  14387. upb_handlers_setstring(h, value_field, putstr, &empty_attr);
  14388. upb_handlers_setendstr(h, value_field, mapvalue_endstr, &empty_attr);
  14389. break;
  14390. case UPB_TYPE_BYTES:
  14391. upb_handlers_setstring(h, value_field, putbytes, &empty_attr);
  14392. break;
  14393. case UPB_TYPE_ENUM: {
  14394. upb_handlerattr enum_attr = UPB_HANDLERATTR_INITIALIZER;
  14395. set_enum_hd(h, value_field, preserve_fieldnames, &enum_attr);
  14396. upb_handlers_setint32(h, value_field, mapvalue_enum, &enum_attr);
  14397. upb_handlerattr_uninit(&enum_attr);
  14398. break;
  14399. }
  14400. case UPB_TYPE_MESSAGE:
  14401. /* No handler necessary -- the submsg handlers will print the message
  14402. * as appropriate. */
  14403. break;
  14404. }
  14405. upb_handlerattr_uninit(&empty_attr);
  14406. }
  14407. static bool putseconds(void *closure, const void *handler_data,
  14408. int64_t seconds) {
  14409. upb_json_printer *p = closure;
  14410. p->seconds = seconds;
  14411. UPB_UNUSED(handler_data);
  14412. return true;
  14413. }
  14414. static bool putnanos(void *closure, const void *handler_data,
  14415. int32_t nanos) {
  14416. upb_json_printer *p = closure;
  14417. p->nanos = nanos;
  14418. UPB_UNUSED(handler_data);
  14419. return true;
  14420. }
  14421. static void *scalar_startstr_nokey(void *closure, const void *handler_data,
  14422. size_t size_hint) {
  14423. upb_json_printer *p = closure;
  14424. UPB_UNUSED(handler_data);
  14425. UPB_UNUSED(size_hint);
  14426. print_data(p, "\"", 1);
  14427. return p;
  14428. }
  14429. static size_t putstr_nokey(void *closure, const void *handler_data,
  14430. const char *str, size_t len,
  14431. const upb_bufhandle *handle) {
  14432. upb_json_printer *p = closure;
  14433. UPB_UNUSED(handler_data);
  14434. UPB_UNUSED(handle);
  14435. print_data(p, "\"", 1);
  14436. putstring(p, str, len);
  14437. print_data(p, "\"", 1);
  14438. return len + 2;
  14439. }
  14440. static void *startseq_nokey(void *closure, const void *handler_data) {
  14441. upb_json_printer *p = closure;
  14442. UPB_UNUSED(handler_data);
  14443. p->depth_++;
  14444. p->first_elem_[p->depth_] = true;
  14445. print_data(p, "[", 1);
  14446. return closure;
  14447. }
  14448. static void *startseq_fieldmask(void *closure, const void *handler_data) {
  14449. upb_json_printer *p = closure;
  14450. UPB_UNUSED(handler_data);
  14451. p->depth_++;
  14452. p->first_elem_[p->depth_] = true;
  14453. return closure;
  14454. }
  14455. static bool endseq_fieldmask(void *closure, const void *handler_data) {
  14456. upb_json_printer *p = closure;
  14457. UPB_UNUSED(handler_data);
  14458. p->depth_--;
  14459. return true;
  14460. }
  14461. static void *repeated_startstr_fieldmask(
  14462. void *closure, const void *handler_data,
  14463. size_t size_hint) {
  14464. upb_json_printer *p = closure;
  14465. UPB_UNUSED(handler_data);
  14466. UPB_UNUSED(size_hint);
  14467. print_comma(p);
  14468. return p;
  14469. }
  14470. static size_t repeated_str_fieldmask(
  14471. void *closure, const void *handler_data,
  14472. const char *str, size_t len,
  14473. const upb_bufhandle *handle) {
  14474. const char* limit = str + len;
  14475. bool upper = false;
  14476. size_t result_len = 0;
  14477. for (; str < limit; str++) {
  14478. if (*str == '_') {
  14479. upper = true;
  14480. continue;
  14481. }
  14482. if (upper && *str >= 'a' && *str <= 'z') {
  14483. char upper_char = toupper(*str);
  14484. CHK(putstr(closure, handler_data, &upper_char, 1, handle));
  14485. } else {
  14486. CHK(putstr(closure, handler_data, str, 1, handle));
  14487. }
  14488. upper = false;
  14489. result_len++;
  14490. }
  14491. return result_len;
  14492. }
  14493. static void *startmap_nokey(void *closure, const void *handler_data) {
  14494. upb_json_printer *p = closure;
  14495. UPB_UNUSED(handler_data);
  14496. p->depth_++;
  14497. p->first_elem_[p->depth_] = true;
  14498. print_data(p, "{", 1);
  14499. return closure;
  14500. }
  14501. static bool putnull(void *closure, const void *handler_data,
  14502. int32_t null) {
  14503. upb_json_printer *p = closure;
  14504. print_data(p, "null", 4);
  14505. UPB_UNUSED(handler_data);
  14506. UPB_UNUSED(null);
  14507. return true;
  14508. }
  14509. static bool printer_startdurationmsg(void *closure, const void *handler_data) {
  14510. upb_json_printer *p = closure;
  14511. UPB_UNUSED(handler_data);
  14512. if (p->depth_ == 0) {
  14513. upb_bytessink_start(p->output_, 0, &p->subc_);
  14514. }
  14515. return true;
  14516. }
  14517. #define UPB_DURATION_MAX_JSON_LEN 23
  14518. #define UPB_DURATION_MAX_NANO_LEN 9
  14519. static bool printer_enddurationmsg(void *closure, const void *handler_data,
  14520. upb_status *s) {
  14521. upb_json_printer *p = closure;
  14522. char buffer[UPB_DURATION_MAX_JSON_LEN];
  14523. size_t base_len;
  14524. size_t curr;
  14525. size_t i;
  14526. memset(buffer, 0, UPB_DURATION_MAX_JSON_LEN);
  14527. if (p->seconds < -315576000000) {
  14528. upb_status_seterrf(s, "error parsing duration: "
  14529. "minimum acceptable value is "
  14530. "-315576000000");
  14531. return false;
  14532. }
  14533. if (p->seconds > 315576000000) {
  14534. upb_status_seterrf(s, "error serializing duration: "
  14535. "maximum acceptable value is "
  14536. "315576000000");
  14537. return false;
  14538. }
  14539. _upb_snprintf(buffer, sizeof(buffer), "%ld", (long)p->seconds);
  14540. base_len = strlen(buffer);
  14541. if (p->nanos != 0) {
  14542. char nanos_buffer[UPB_DURATION_MAX_NANO_LEN + 3];
  14543. _upb_snprintf(nanos_buffer, sizeof(nanos_buffer), "%.9f",
  14544. p->nanos / 1000000000.0);
  14545. /* Remove trailing 0. */
  14546. for (i = UPB_DURATION_MAX_NANO_LEN + 2;
  14547. nanos_buffer[i] == '0'; i--) {
  14548. nanos_buffer[i] = 0;
  14549. }
  14550. strcpy(buffer + base_len, nanos_buffer + 1);
  14551. }
  14552. curr = strlen(buffer);
  14553. strcpy(buffer + curr, "s");
  14554. p->seconds = 0;
  14555. p->nanos = 0;
  14556. print_data(p, "\"", 1);
  14557. print_data(p, buffer, strlen(buffer));
  14558. print_data(p, "\"", 1);
  14559. if (p->depth_ == 0) {
  14560. upb_bytessink_end(p->output_);
  14561. }
  14562. UPB_UNUSED(handler_data);
  14563. return true;
  14564. }
  14565. static bool printer_starttimestampmsg(void *closure, const void *handler_data) {
  14566. upb_json_printer *p = closure;
  14567. UPB_UNUSED(handler_data);
  14568. if (p->depth_ == 0) {
  14569. upb_bytessink_start(p->output_, 0, &p->subc_);
  14570. }
  14571. return true;
  14572. }
  14573. #define UPB_TIMESTAMP_MAX_JSON_LEN 31
  14574. #define UPB_TIMESTAMP_BEFORE_NANO_LEN 19
  14575. #define UPB_TIMESTAMP_MAX_NANO_LEN 9
  14576. static bool printer_endtimestampmsg(void *closure, const void *handler_data,
  14577. upb_status *s) {
  14578. upb_json_printer *p = closure;
  14579. char buffer[UPB_TIMESTAMP_MAX_JSON_LEN];
  14580. time_t time = p->seconds;
  14581. size_t curr;
  14582. size_t i;
  14583. size_t year_length =
  14584. strftime(buffer, UPB_TIMESTAMP_MAX_JSON_LEN, "%Y", gmtime(&time));
  14585. if (p->seconds < -62135596800) {
  14586. upb_status_seterrf(s, "error parsing timestamp: "
  14587. "minimum acceptable value is "
  14588. "0001-01-01T00:00:00Z");
  14589. return false;
  14590. }
  14591. if (p->seconds > 253402300799) {
  14592. upb_status_seterrf(s, "error parsing timestamp: "
  14593. "maximum acceptable value is "
  14594. "9999-12-31T23:59:59Z");
  14595. return false;
  14596. }
  14597. /* strftime doesn't guarantee 4 digits for year. Prepend 0 by ourselves. */
  14598. for (i = 0; i < 4 - year_length; i++) {
  14599. buffer[i] = '0';
  14600. }
  14601. strftime(buffer + (4 - year_length), UPB_TIMESTAMP_MAX_JSON_LEN,
  14602. "%Y-%m-%dT%H:%M:%S", gmtime(&time));
  14603. if (p->nanos != 0) {
  14604. char nanos_buffer[UPB_TIMESTAMP_MAX_NANO_LEN + 3];
  14605. _upb_snprintf(nanos_buffer, sizeof(nanos_buffer), "%.9f",
  14606. p->nanos / 1000000000.0);
  14607. /* Remove trailing 0. */
  14608. for (i = UPB_TIMESTAMP_MAX_NANO_LEN + 2;
  14609. nanos_buffer[i] == '0'; i--) {
  14610. nanos_buffer[i] = 0;
  14611. }
  14612. strcpy(buffer + UPB_TIMESTAMP_BEFORE_NANO_LEN, nanos_buffer + 1);
  14613. }
  14614. curr = strlen(buffer);
  14615. strcpy(buffer + curr, "Z");
  14616. p->seconds = 0;
  14617. p->nanos = 0;
  14618. print_data(p, "\"", 1);
  14619. print_data(p, buffer, strlen(buffer));
  14620. print_data(p, "\"", 1);
  14621. if (p->depth_ == 0) {
  14622. upb_bytessink_end(p->output_);
  14623. }
  14624. UPB_UNUSED(handler_data);
  14625. UPB_UNUSED(s);
  14626. return true;
  14627. }
  14628. static bool printer_startmsg_noframe(void *closure, const void *handler_data) {
  14629. upb_json_printer *p = closure;
  14630. UPB_UNUSED(handler_data);
  14631. if (p->depth_ == 0) {
  14632. upb_bytessink_start(p->output_, 0, &p->subc_);
  14633. }
  14634. return true;
  14635. }
  14636. static bool printer_endmsg_noframe(
  14637. void *closure, const void *handler_data, upb_status *s) {
  14638. upb_json_printer *p = closure;
  14639. UPB_UNUSED(handler_data);
  14640. UPB_UNUSED(s);
  14641. if (p->depth_ == 0) {
  14642. upb_bytessink_end(p->output_);
  14643. }
  14644. return true;
  14645. }
  14646. static bool printer_startmsg_fieldmask(
  14647. void *closure, const void *handler_data) {
  14648. upb_json_printer *p = closure;
  14649. UPB_UNUSED(handler_data);
  14650. if (p->depth_ == 0) {
  14651. upb_bytessink_start(p->output_, 0, &p->subc_);
  14652. }
  14653. print_data(p, "\"", 1);
  14654. return true;
  14655. }
  14656. static bool printer_endmsg_fieldmask(
  14657. void *closure, const void *handler_data, upb_status *s) {
  14658. upb_json_printer *p = closure;
  14659. UPB_UNUSED(handler_data);
  14660. UPB_UNUSED(s);
  14661. print_data(p, "\"", 1);
  14662. if (p->depth_ == 0) {
  14663. upb_bytessink_end(p->output_);
  14664. }
  14665. return true;
  14666. }
  14667. static void *scalar_startstr_onlykey(
  14668. void *closure, const void *handler_data, size_t size_hint) {
  14669. upb_json_printer *p = closure;
  14670. UPB_UNUSED(size_hint);
  14671. CHK(putkey(closure, handler_data));
  14672. return p;
  14673. }
  14674. /* Set up handlers for an Any submessage. */
  14675. void printer_sethandlers_any(const void *closure, upb_handlers *h) {
  14676. const upb_msgdef *md = upb_handlers_msgdef(h);
  14677. const upb_fielddef* type_field = upb_msgdef_itof(md, UPB_ANY_TYPE);
  14678. const upb_fielddef* value_field = upb_msgdef_itof(md, UPB_ANY_VALUE);
  14679. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  14680. /* type_url's json name is "@type" */
  14681. upb_handlerattr type_name_attr = UPB_HANDLERATTR_INITIALIZER;
  14682. upb_handlerattr value_name_attr = UPB_HANDLERATTR_INITIALIZER;
  14683. strpc *type_url_json_name = newstrpc_str(h, "@type");
  14684. strpc *value_json_name = newstrpc_str(h, "value");
  14685. upb_handlerattr_sethandlerdata(&type_name_attr, type_url_json_name);
  14686. upb_handlerattr_sethandlerdata(&value_name_attr, value_json_name);
  14687. /* Set up handlers. */
  14688. upb_handlers_setstartmsg(h, printer_startmsg, &empty_attr);
  14689. upb_handlers_setendmsg(h, printer_endmsg, &empty_attr);
  14690. upb_handlers_setstartstr(h, type_field, scalar_startstr, &type_name_attr);
  14691. upb_handlers_setstring(h, type_field, scalar_str, &empty_attr);
  14692. upb_handlers_setendstr(h, type_field, scalar_endstr, &empty_attr);
  14693. /* This is not the full and correct JSON encoding for the Any value field. It
  14694. * requires further processing by the wrapper code based on the type URL.
  14695. */
  14696. upb_handlers_setstartstr(h, value_field, scalar_startstr_onlykey,
  14697. &value_name_attr);
  14698. UPB_UNUSED(closure);
  14699. }
  14700. /* Set up handlers for a fieldmask submessage. */
  14701. void printer_sethandlers_fieldmask(const void *closure, upb_handlers *h) {
  14702. const upb_msgdef *md = upb_handlers_msgdef(h);
  14703. const upb_fielddef* f = upb_msgdef_itof(md, 1);
  14704. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  14705. upb_handlers_setstartseq(h, f, startseq_fieldmask, &empty_attr);
  14706. upb_handlers_setendseq(h, f, endseq_fieldmask, &empty_attr);
  14707. upb_handlers_setstartmsg(h, printer_startmsg_fieldmask, &empty_attr);
  14708. upb_handlers_setendmsg(h, printer_endmsg_fieldmask, &empty_attr);
  14709. upb_handlers_setstartstr(h, f, repeated_startstr_fieldmask, &empty_attr);
  14710. upb_handlers_setstring(h, f, repeated_str_fieldmask, &empty_attr);
  14711. UPB_UNUSED(closure);
  14712. }
  14713. /* Set up handlers for a duration submessage. */
  14714. void printer_sethandlers_duration(const void *closure, upb_handlers *h) {
  14715. const upb_msgdef *md = upb_handlers_msgdef(h);
  14716. const upb_fielddef* seconds_field =
  14717. upb_msgdef_itof(md, UPB_DURATION_SECONDS);
  14718. const upb_fielddef* nanos_field =
  14719. upb_msgdef_itof(md, UPB_DURATION_NANOS);
  14720. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  14721. upb_handlers_setstartmsg(h, printer_startdurationmsg, &empty_attr);
  14722. upb_handlers_setint64(h, seconds_field, putseconds, &empty_attr);
  14723. upb_handlers_setint32(h, nanos_field, putnanos, &empty_attr);
  14724. upb_handlers_setendmsg(h, printer_enddurationmsg, &empty_attr);
  14725. UPB_UNUSED(closure);
  14726. }
  14727. /* Set up handlers for a timestamp submessage. Instead of printing fields
  14728. * separately, the json representation of timestamp follows RFC 3339 */
  14729. void printer_sethandlers_timestamp(const void *closure, upb_handlers *h) {
  14730. const upb_msgdef *md = upb_handlers_msgdef(h);
  14731. const upb_fielddef* seconds_field =
  14732. upb_msgdef_itof(md, UPB_TIMESTAMP_SECONDS);
  14733. const upb_fielddef* nanos_field =
  14734. upb_msgdef_itof(md, UPB_TIMESTAMP_NANOS);
  14735. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  14736. upb_handlers_setstartmsg(h, printer_starttimestampmsg, &empty_attr);
  14737. upb_handlers_setint64(h, seconds_field, putseconds, &empty_attr);
  14738. upb_handlers_setint32(h, nanos_field, putnanos, &empty_attr);
  14739. upb_handlers_setendmsg(h, printer_endtimestampmsg, &empty_attr);
  14740. UPB_UNUSED(closure);
  14741. }
  14742. void printer_sethandlers_value(const void *closure, upb_handlers *h) {
  14743. const upb_msgdef *md = upb_handlers_msgdef(h);
  14744. upb_msg_field_iter i;
  14745. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  14746. upb_handlers_setstartmsg(h, printer_startmsg_noframe, &empty_attr);
  14747. upb_handlers_setendmsg(h, printer_endmsg_noframe, &empty_attr);
  14748. upb_msg_field_begin(&i, md);
  14749. for(; !upb_msg_field_done(&i); upb_msg_field_next(&i)) {
  14750. const upb_fielddef *f = upb_msg_iter_field(&i);
  14751. switch (upb_fielddef_type(f)) {
  14752. case UPB_TYPE_ENUM:
  14753. upb_handlers_setint32(h, f, putnull, &empty_attr);
  14754. break;
  14755. case UPB_TYPE_DOUBLE:
  14756. upb_handlers_setdouble(h, f, putdouble, &empty_attr);
  14757. break;
  14758. case UPB_TYPE_STRING:
  14759. upb_handlers_setstartstr(h, f, scalar_startstr_nokey, &empty_attr);
  14760. upb_handlers_setstring(h, f, scalar_str, &empty_attr);
  14761. upb_handlers_setendstr(h, f, scalar_endstr, &empty_attr);
  14762. break;
  14763. case UPB_TYPE_BOOL:
  14764. upb_handlers_setbool(h, f, putbool, &empty_attr);
  14765. break;
  14766. case UPB_TYPE_MESSAGE:
  14767. break;
  14768. default:
  14769. UPB_ASSERT(false);
  14770. break;
  14771. }
  14772. }
  14773. UPB_UNUSED(closure);
  14774. }
  14775. #define WRAPPER_SETHANDLERS(wrapper, type, putmethod) \
  14776. void printer_sethandlers_##wrapper(const void *closure, upb_handlers *h) { \
  14777. const upb_msgdef *md = upb_handlers_msgdef(h); \
  14778. const upb_fielddef* f = upb_msgdef_itof(md, 1); \
  14779. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER; \
  14780. upb_handlers_setstartmsg(h, printer_startmsg_noframe, &empty_attr); \
  14781. upb_handlers_setendmsg(h, printer_endmsg_noframe, &empty_attr); \
  14782. upb_handlers_set##type(h, f, putmethod, &empty_attr); \
  14783. UPB_UNUSED(closure); \
  14784. }
  14785. WRAPPER_SETHANDLERS(doublevalue, double, putdouble)
  14786. WRAPPER_SETHANDLERS(floatvalue, float, putfloat)
  14787. WRAPPER_SETHANDLERS(int64value, int64, putint64_t)
  14788. WRAPPER_SETHANDLERS(uint64value, uint64, putuint64_t)
  14789. WRAPPER_SETHANDLERS(int32value, int32, putint32_t)
  14790. WRAPPER_SETHANDLERS(uint32value, uint32, putuint32_t)
  14791. WRAPPER_SETHANDLERS(boolvalue, bool, putbool)
  14792. WRAPPER_SETHANDLERS(stringvalue, string, putstr_nokey)
  14793. WRAPPER_SETHANDLERS(bytesvalue, string, putbytes)
  14794. #undef WRAPPER_SETHANDLERS
  14795. void printer_sethandlers_listvalue(const void *closure, upb_handlers *h) {
  14796. const upb_msgdef *md = upb_handlers_msgdef(h);
  14797. const upb_fielddef* f = upb_msgdef_itof(md, 1);
  14798. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  14799. upb_handlers_setstartseq(h, f, startseq_nokey, &empty_attr);
  14800. upb_handlers_setendseq(h, f, endseq, &empty_attr);
  14801. upb_handlers_setstartmsg(h, printer_startmsg_noframe, &empty_attr);
  14802. upb_handlers_setendmsg(h, printer_endmsg_noframe, &empty_attr);
  14803. upb_handlers_setstartsubmsg(h, f, repeated_startsubmsg, &empty_attr);
  14804. UPB_UNUSED(closure);
  14805. }
  14806. void printer_sethandlers_structvalue(const void *closure, upb_handlers *h) {
  14807. const upb_msgdef *md = upb_handlers_msgdef(h);
  14808. const upb_fielddef* f = upb_msgdef_itof(md, 1);
  14809. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  14810. upb_handlers_setstartseq(h, f, startmap_nokey, &empty_attr);
  14811. upb_handlers_setendseq(h, f, endmap, &empty_attr);
  14812. upb_handlers_setstartmsg(h, printer_startmsg_noframe, &empty_attr);
  14813. upb_handlers_setendmsg(h, printer_endmsg_noframe, &empty_attr);
  14814. upb_handlers_setstartsubmsg(h, f, repeated_startsubmsg, &empty_attr);
  14815. UPB_UNUSED(closure);
  14816. }
  14817. void printer_sethandlers(const void *closure, upb_handlers *h) {
  14818. const upb_msgdef *md = upb_handlers_msgdef(h);
  14819. bool is_mapentry = upb_msgdef_mapentry(md);
  14820. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  14821. upb_msg_field_iter i;
  14822. const bool *preserve_fieldnames_ptr = closure;
  14823. const bool preserve_fieldnames = *preserve_fieldnames_ptr;
  14824. if (is_mapentry) {
  14825. /* mapentry messages are sufficiently different that we handle them
  14826. * separately. */
  14827. printer_sethandlers_mapentry(closure, preserve_fieldnames, h);
  14828. return;
  14829. }
  14830. switch (upb_msgdef_wellknowntype(md)) {
  14831. case UPB_WELLKNOWN_UNSPECIFIED:
  14832. break;
  14833. case UPB_WELLKNOWN_ANY:
  14834. printer_sethandlers_any(closure, h);
  14835. return;
  14836. case UPB_WELLKNOWN_FIELDMASK:
  14837. printer_sethandlers_fieldmask(closure, h);
  14838. return;
  14839. case UPB_WELLKNOWN_DURATION:
  14840. printer_sethandlers_duration(closure, h);
  14841. return;
  14842. case UPB_WELLKNOWN_TIMESTAMP:
  14843. printer_sethandlers_timestamp(closure, h);
  14844. return;
  14845. case UPB_WELLKNOWN_VALUE:
  14846. printer_sethandlers_value(closure, h);
  14847. return;
  14848. case UPB_WELLKNOWN_LISTVALUE:
  14849. printer_sethandlers_listvalue(closure, h);
  14850. return;
  14851. case UPB_WELLKNOWN_STRUCT:
  14852. printer_sethandlers_structvalue(closure, h);
  14853. return;
  14854. #define WRAPPER(wellknowntype, name) \
  14855. case wellknowntype: \
  14856. printer_sethandlers_##name(closure, h); \
  14857. return; \
  14858. WRAPPER(UPB_WELLKNOWN_DOUBLEVALUE, doublevalue);
  14859. WRAPPER(UPB_WELLKNOWN_FLOATVALUE, floatvalue);
  14860. WRAPPER(UPB_WELLKNOWN_INT64VALUE, int64value);
  14861. WRAPPER(UPB_WELLKNOWN_UINT64VALUE, uint64value);
  14862. WRAPPER(UPB_WELLKNOWN_INT32VALUE, int32value);
  14863. WRAPPER(UPB_WELLKNOWN_UINT32VALUE, uint32value);
  14864. WRAPPER(UPB_WELLKNOWN_BOOLVALUE, boolvalue);
  14865. WRAPPER(UPB_WELLKNOWN_STRINGVALUE, stringvalue);
  14866. WRAPPER(UPB_WELLKNOWN_BYTESVALUE, bytesvalue);
  14867. #undef WRAPPER
  14868. }
  14869. upb_handlers_setstartmsg(h, printer_startmsg, &empty_attr);
  14870. upb_handlers_setendmsg(h, printer_endmsg, &empty_attr);
  14871. #define TYPE(type, name, ctype) \
  14872. case type: \
  14873. if (upb_fielddef_isseq(f)) { \
  14874. upb_handlers_set##name(h, f, repeated_##ctype, &empty_attr); \
  14875. } else { \
  14876. upb_handlers_set##name(h, f, scalar_##ctype, &name_attr); \
  14877. } \
  14878. break;
  14879. upb_msg_field_begin(&i, md);
  14880. for(; !upb_msg_field_done(&i); upb_msg_field_next(&i)) {
  14881. const upb_fielddef *f = upb_msg_iter_field(&i);
  14882. upb_handlerattr name_attr = UPB_HANDLERATTR_INITIALIZER;
  14883. upb_handlerattr_sethandlerdata(&name_attr,
  14884. newstrpc(h, f, preserve_fieldnames));
  14885. if (upb_fielddef_ismap(f)) {
  14886. upb_handlers_setstartseq(h, f, startmap, &name_attr);
  14887. upb_handlers_setendseq(h, f, endmap, &name_attr);
  14888. } else if (upb_fielddef_isseq(f)) {
  14889. upb_handlers_setstartseq(h, f, startseq, &name_attr);
  14890. upb_handlers_setendseq(h, f, endseq, &empty_attr);
  14891. }
  14892. switch (upb_fielddef_type(f)) {
  14893. TYPE(UPB_TYPE_FLOAT, float, float);
  14894. TYPE(UPB_TYPE_DOUBLE, double, double);
  14895. TYPE(UPB_TYPE_BOOL, bool, bool);
  14896. TYPE(UPB_TYPE_INT32, int32, int32_t);
  14897. TYPE(UPB_TYPE_UINT32, uint32, uint32_t);
  14898. TYPE(UPB_TYPE_INT64, int64, int64_t);
  14899. TYPE(UPB_TYPE_UINT64, uint64, uint64_t);
  14900. case UPB_TYPE_ENUM: {
  14901. /* For now, we always emit symbolic names for enums. We may want an
  14902. * option later to control this behavior, but we will wait for a real
  14903. * need first. */
  14904. upb_handlerattr enum_attr = UPB_HANDLERATTR_INITIALIZER;
  14905. set_enum_hd(h, f, preserve_fieldnames, &enum_attr);
  14906. if (upb_fielddef_isseq(f)) {
  14907. upb_handlers_setint32(h, f, repeated_enum, &enum_attr);
  14908. } else {
  14909. upb_handlers_setint32(h, f, scalar_enum, &enum_attr);
  14910. }
  14911. upb_handlerattr_uninit(&enum_attr);
  14912. break;
  14913. }
  14914. case UPB_TYPE_STRING:
  14915. if (upb_fielddef_isseq(f)) {
  14916. upb_handlers_setstartstr(h, f, repeated_startstr, &empty_attr);
  14917. upb_handlers_setstring(h, f, repeated_str, &empty_attr);
  14918. upb_handlers_setendstr(h, f, repeated_endstr, &empty_attr);
  14919. } else {
  14920. upb_handlers_setstartstr(h, f, scalar_startstr, &name_attr);
  14921. upb_handlers_setstring(h, f, scalar_str, &empty_attr);
  14922. upb_handlers_setendstr(h, f, scalar_endstr, &empty_attr);
  14923. }
  14924. break;
  14925. case UPB_TYPE_BYTES:
  14926. /* XXX: this doesn't support strings that span buffers yet. The base64
  14927. * encoder will need to be made resumable for this to work properly. */
  14928. if (upb_fielddef_isseq(f)) {
  14929. upb_handlers_setstring(h, f, repeated_bytes, &empty_attr);
  14930. } else {
  14931. upb_handlers_setstring(h, f, scalar_bytes, &name_attr);
  14932. }
  14933. break;
  14934. case UPB_TYPE_MESSAGE:
  14935. if (upb_fielddef_isseq(f)) {
  14936. upb_handlers_setstartsubmsg(h, f, repeated_startsubmsg, &name_attr);
  14937. } else {
  14938. upb_handlers_setstartsubmsg(h, f, scalar_startsubmsg, &name_attr);
  14939. }
  14940. break;
  14941. }
  14942. upb_handlerattr_uninit(&name_attr);
  14943. }
  14944. upb_handlerattr_uninit(&empty_attr);
  14945. #undef TYPE
  14946. }
  14947. static void json_printer_reset(upb_json_printer *p) {
  14948. p->depth_ = 0;
  14949. }
  14950. /* Public API *****************************************************************/
  14951. upb_json_printer *upb_json_printer_create(upb_env *e, const upb_handlers *h,
  14952. upb_bytessink *output) {
  14953. #ifndef NDEBUG
  14954. size_t size_before = upb_env_bytesallocated(e);
  14955. #endif
  14956. upb_json_printer *p = upb_env_malloc(e, sizeof(upb_json_printer));
  14957. if (!p) return NULL;
  14958. p->output_ = output;
  14959. json_printer_reset(p);
  14960. upb_sink_reset(&p->input_, h, p);
  14961. p->seconds = 0;
  14962. p->nanos = 0;
  14963. /* If this fails, increase the value in printer.h. */
  14964. UPB_ASSERT_DEBUGVAR(upb_env_bytesallocated(e) - size_before <=
  14965. UPB_JSON_PRINTER_SIZE);
  14966. return p;
  14967. }
  14968. upb_sink *upb_json_printer_input(upb_json_printer *p) {
  14969. return &p->input_;
  14970. }
  14971. const upb_handlers *upb_json_printer_newhandlers(const upb_msgdef *md,
  14972. bool preserve_fieldnames,
  14973. const void *owner) {
  14974. return upb_handlers_newfrozen(
  14975. md, owner, printer_sethandlers, &preserve_fieldnames);
  14976. }
  14977. #undef UPB_SIZE
  14978. #undef UPB_FIELD_AT
  14979. #undef UPB_READ_ONEOF
  14980. #undef UPB_WRITE_ONEOF