upb.c 409 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840
  1. /* Amalgamated source file */
  2. #include "upb.h"
  3. /*
  4. * This is where we define macros used across upb.
  5. *
  6. * All of these macros are undef'd in port_undef.inc to avoid leaking them to
  7. * users.
  8. *
  9. * The correct usage is:
  10. *
  11. * #include "upb/foobar.h"
  12. * #include "upb/baz.h"
  13. *
  14. * // MUST be last included header.
  15. * #include "upb/port_def.inc"
  16. *
  17. * // Code for this file.
  18. * // <...>
  19. *
  20. * // Can be omitted for .c files, required for .h.
  21. * #include "upb/port_undef.inc"
  22. *
  23. * This file is private and must not be included by users!
  24. */
  25. #include <stdint.h>
  26. #include <stddef.h>
  27. #if UINTPTR_MAX == 0xffffffff
  28. #define UPB_SIZE(size32, size64) size32
  29. #else
  30. #define UPB_SIZE(size32, size64) size64
  31. #endif
  32. /* If we always read/write as a consistent type to each address, this shouldn't
  33. * violate aliasing.
  34. */
  35. #define UPB_PTR_AT(msg, ofs, type) ((type*)((char*)(msg) + (ofs)))
  36. #define UPB_READ_ONEOF(msg, fieldtype, offset, case_offset, case_val, default) \
  37. *UPB_PTR_AT(msg, case_offset, int) == case_val \
  38. ? *UPB_PTR_AT(msg, offset, fieldtype) \
  39. : default
  40. #define UPB_WRITE_ONEOF(msg, fieldtype, offset, value, case_offset, case_val) \
  41. *UPB_PTR_AT(msg, case_offset, int) = case_val; \
  42. *UPB_PTR_AT(msg, offset, fieldtype) = value;
  43. #define UPB_MAPTYPE_STRING 0
  44. /* UPB_INLINE: inline if possible, emit standalone code if required. */
  45. #ifdef __cplusplus
  46. #define UPB_INLINE inline
  47. #elif defined (__GNUC__) || defined(__clang__)
  48. #define UPB_INLINE static __inline__
  49. #else
  50. #define UPB_INLINE static
  51. #endif
  52. #define UPB_ALIGN_UP(size, align) (((size) + (align) - 1) / (align) * (align))
  53. #define UPB_ALIGN_DOWN(size, align) ((size) / (align) * (align))
  54. #define UPB_ALIGN_MALLOC(size) UPB_ALIGN_UP(size, 16)
  55. #define UPB_ALIGN_OF(type) offsetof (struct { char c; type member; }, member)
  56. /* Hints to the compiler about likely/unlikely branches. */
  57. #if defined (__GNUC__) || defined(__clang__)
  58. #define UPB_LIKELY(x) __builtin_expect((x),1)
  59. #define UPB_UNLIKELY(x) __builtin_expect((x),0)
  60. #else
  61. #define UPB_LIKELY(x) (x)
  62. #define UPB_UNLIKELY(x) (x)
  63. #endif
  64. /* Define UPB_BIG_ENDIAN manually if you're on big endian and your compiler
  65. * doesn't provide these preprocessor symbols. */
  66. #if defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)
  67. #define UPB_BIG_ENDIAN
  68. #endif
  69. /* Macros for function attributes on compilers that support them. */
  70. #ifdef __GNUC__
  71. #define UPB_FORCEINLINE __inline__ __attribute__((always_inline))
  72. #define UPB_NOINLINE __attribute__((noinline))
  73. #define UPB_NORETURN __attribute__((__noreturn__))
  74. #else /* !defined(__GNUC__) */
  75. #define UPB_FORCEINLINE
  76. #define UPB_NOINLINE
  77. #define UPB_NORETURN
  78. #endif
  79. #if __STDC_VERSION__ >= 199901L || __cplusplus >= 201103L
  80. /* C99/C++11 versions. */
  81. #include <stdio.h>
  82. #define _upb_snprintf snprintf
  83. #define _upb_vsnprintf vsnprintf
  84. #define _upb_va_copy(a, b) va_copy(a, b)
  85. #elif defined(_MSC_VER)
  86. /* Microsoft C/C++ versions. */
  87. #include <stdarg.h>
  88. #include <stdio.h>
  89. #if _MSC_VER < 1900
  90. int msvc_snprintf(char* s, size_t n, const char* format, ...);
  91. int msvc_vsnprintf(char* s, size_t n, const char* format, va_list arg);
  92. #define UPB_MSVC_VSNPRINTF
  93. #define _upb_snprintf msvc_snprintf
  94. #define _upb_vsnprintf msvc_vsnprintf
  95. #else
  96. #define _upb_snprintf snprintf
  97. #define _upb_vsnprintf vsnprintf
  98. #endif
  99. #define _upb_va_copy(a, b) va_copy(a, b)
  100. #elif defined __GNUC__
  101. /* A few hacky workarounds for functions not in C89.
  102. * For internal use only!
  103. * TODO(haberman): fix these by including our own implementations, or finding
  104. * another workaround.
  105. */
  106. #define _upb_snprintf __builtin_snprintf
  107. #define _upb_vsnprintf __builtin_vsnprintf
  108. #define _upb_va_copy(a, b) __va_copy(a, b)
  109. #else
  110. #error Need implementations of [v]snprintf and va_copy
  111. #endif
  112. #ifdef __cplusplus
  113. #if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__) || \
  114. (defined(_MSC_VER) && _MSC_VER >= 1900)
  115. /* C++11 is present */
  116. #else
  117. #error upb requires C++11 for C++ support
  118. #endif
  119. #endif
  120. #define UPB_MAX(x, y) ((x) > (y) ? (x) : (y))
  121. #define UPB_MIN(x, y) ((x) < (y) ? (x) : (y))
  122. #define UPB_UNUSED(var) (void)var
  123. /* UPB_ASSUME(): in release mode, we tell the compiler to assume this is true.
  124. */
  125. #ifdef NDEBUG
  126. #ifdef __GNUC__
  127. #define UPB_ASSUME(expr) if (!(expr)) __builtin_unreachable()
  128. #else
  129. #define UPB_ASSUME(expr) do {} if (false && (expr))
  130. #endif
  131. #else
  132. #define UPB_ASSUME(expr) assert(expr)
  133. #endif
  134. /* UPB_ASSERT(): in release mode, we use the expression without letting it be
  135. * evaluated. This prevents "unused variable" warnings. */
  136. #ifdef NDEBUG
  137. #define UPB_ASSERT(expr) do {} while (false && (expr))
  138. #else
  139. #define UPB_ASSERT(expr) assert(expr)
  140. #endif
  141. /* UPB_ASSERT_DEBUGVAR(): assert that uses functions or variables that only
  142. * exist in debug mode. This turns into regular assert. */
  143. #define UPB_ASSERT_DEBUGVAR(expr) assert(expr)
  144. #if defined(__GNUC__) || defined(__clang__)
  145. #define UPB_UNREACHABLE() do { assert(0); __builtin_unreachable(); } while(0)
  146. #else
  147. #define UPB_UNREACHABLE() do { assert(0); } while(0)
  148. #endif
  149. /* UPB_INFINITY representing floating-point positive infinity. */
  150. #include <math.h>
  151. #ifdef INFINITY
  152. #define UPB_INFINITY INFINITY
  153. #else
  154. #define UPB_INFINITY (1.0 / 0.0)
  155. #endif
  156. #include <setjmp.h>
  157. #include <string.h>
  158. /* Maps descriptor type -> upb field type. */
  159. static const uint8_t desctype_to_fieldtype[] = {
  160. -1, /* invalid descriptor type */
  161. UPB_TYPE_DOUBLE, /* DOUBLE */
  162. UPB_TYPE_FLOAT, /* FLOAT */
  163. UPB_TYPE_INT64, /* INT64 */
  164. UPB_TYPE_UINT64, /* UINT64 */
  165. UPB_TYPE_INT32, /* INT32 */
  166. UPB_TYPE_UINT64, /* FIXED64 */
  167. UPB_TYPE_UINT32, /* FIXED32 */
  168. UPB_TYPE_BOOL, /* BOOL */
  169. UPB_TYPE_STRING, /* STRING */
  170. UPB_TYPE_MESSAGE, /* GROUP */
  171. UPB_TYPE_MESSAGE, /* MESSAGE */
  172. UPB_TYPE_BYTES, /* BYTES */
  173. UPB_TYPE_UINT32, /* UINT32 */
  174. UPB_TYPE_ENUM, /* ENUM */
  175. UPB_TYPE_INT32, /* SFIXED32 */
  176. UPB_TYPE_INT64, /* SFIXED64 */
  177. UPB_TYPE_INT32, /* SINT32 */
  178. UPB_TYPE_INT64, /* SINT64 */
  179. };
  180. /* Maps descriptor type -> upb map size. */
  181. static const uint8_t desctype_to_mapsize[] = {
  182. -1, /* invalid descriptor type */
  183. 8, /* DOUBLE */
  184. 4, /* FLOAT */
  185. 8, /* INT64 */
  186. 8, /* UINT64 */
  187. 4, /* INT32 */
  188. 8, /* FIXED64 */
  189. 4, /* FIXED32 */
  190. 1, /* BOOL */
  191. UPB_MAPTYPE_STRING, /* STRING */
  192. sizeof(void *), /* GROUP */
  193. sizeof(void *), /* MESSAGE */
  194. UPB_MAPTYPE_STRING, /* BYTES */
  195. 4, /* UINT32 */
  196. 4, /* ENUM */
  197. 4, /* SFIXED32 */
  198. 8, /* SFIXED64 */
  199. 4, /* SINT32 */
  200. 8, /* SINT64 */
  201. };
  202. static const unsigned fixed32_ok = (1 << UPB_DTYPE_FLOAT) |
  203. (1 << UPB_DTYPE_FIXED32) |
  204. (1 << UPB_DTYPE_SFIXED32);
  205. static const unsigned fixed64_ok = (1 << UPB_DTYPE_DOUBLE) |
  206. (1 << UPB_DTYPE_FIXED64) |
  207. (1 << UPB_DTYPE_SFIXED64);
  208. /* Op: an action to be performed for a wire-type/field-type combination. */
  209. #define OP_SCALAR_LG2(n) (n)
  210. #define OP_FIXPCK_LG2(n) (n + 4)
  211. #define OP_VARPCK_LG2(n) (n + 8)
  212. #define OP_STRING 4
  213. #define OP_SUBMSG 5
  214. static const int8_t varint_ops[19] = {
  215. -1, /* field not found */
  216. -1, /* DOUBLE */
  217. -1, /* FLOAT */
  218. OP_SCALAR_LG2(3), /* INT64 */
  219. OP_SCALAR_LG2(3), /* UINT64 */
  220. OP_SCALAR_LG2(2), /* INT32 */
  221. -1, /* FIXED64 */
  222. -1, /* FIXED32 */
  223. OP_SCALAR_LG2(0), /* BOOL */
  224. -1, /* STRING */
  225. -1, /* GROUP */
  226. -1, /* MESSAGE */
  227. -1, /* BYTES */
  228. OP_SCALAR_LG2(2), /* UINT32 */
  229. OP_SCALAR_LG2(2), /* ENUM */
  230. -1, /* SFIXED32 */
  231. -1, /* SFIXED64 */
  232. OP_SCALAR_LG2(2), /* SINT32 */
  233. OP_SCALAR_LG2(3), /* SINT64 */
  234. };
  235. static const int8_t delim_ops[37] = {
  236. /* For non-repeated field type. */
  237. -1, /* field not found */
  238. -1, /* DOUBLE */
  239. -1, /* FLOAT */
  240. -1, /* INT64 */
  241. -1, /* UINT64 */
  242. -1, /* INT32 */
  243. -1, /* FIXED64 */
  244. -1, /* FIXED32 */
  245. -1, /* BOOL */
  246. OP_STRING, /* STRING */
  247. -1, /* GROUP */
  248. OP_SUBMSG, /* MESSAGE */
  249. OP_STRING, /* BYTES */
  250. -1, /* UINT32 */
  251. -1, /* ENUM */
  252. -1, /* SFIXED32 */
  253. -1, /* SFIXED64 */
  254. -1, /* SINT32 */
  255. -1, /* SINT64 */
  256. /* For repeated field type. */
  257. OP_FIXPCK_LG2(3), /* REPEATED DOUBLE */
  258. OP_FIXPCK_LG2(2), /* REPEATED FLOAT */
  259. OP_VARPCK_LG2(3), /* REPEATED INT64 */
  260. OP_VARPCK_LG2(3), /* REPEATED UINT64 */
  261. OP_VARPCK_LG2(2), /* REPEATED INT32 */
  262. OP_FIXPCK_LG2(3), /* REPEATED FIXED64 */
  263. OP_FIXPCK_LG2(2), /* REPEATED FIXED32 */
  264. OP_VARPCK_LG2(0), /* REPEATED BOOL */
  265. OP_STRING, /* REPEATED STRING */
  266. OP_SUBMSG, /* REPEATED GROUP */
  267. OP_SUBMSG, /* REPEATED MESSAGE */
  268. OP_STRING, /* REPEATED BYTES */
  269. OP_VARPCK_LG2(2), /* REPEATED UINT32 */
  270. OP_VARPCK_LG2(2), /* REPEATED ENUM */
  271. OP_FIXPCK_LG2(2), /* REPEATED SFIXED32 */
  272. OP_FIXPCK_LG2(3), /* REPEATED SFIXED64 */
  273. OP_VARPCK_LG2(2), /* REPEATED SINT32 */
  274. OP_VARPCK_LG2(3), /* REPEATED SINT64 */
  275. };
  276. /* Data pertaining to the parse. */
  277. typedef struct {
  278. const char *limit; /* End of delimited region or end of buffer. */
  279. upb_arena *arena;
  280. int depth;
  281. uint32_t end_group; /* Set to field number of END_GROUP tag, if any. */
  282. jmp_buf err;
  283. } upb_decstate;
  284. typedef union {
  285. bool bool_val;
  286. int32_t int32_val;
  287. int64_t int64_val;
  288. uint32_t uint32_val;
  289. uint64_t uint64_val;
  290. upb_strview str_val;
  291. } wireval;
  292. static const char *decode_msg(upb_decstate *d, const char *ptr, upb_msg *msg,
  293. const upb_msglayout *layout);
  294. UPB_NORETURN static void decode_err(upb_decstate *d) { longjmp(d->err, 1); }
  295. static bool decode_reserve(upb_decstate *d, upb_array *arr, int elem) {
  296. bool need_realloc = arr->size - arr->len < elem;
  297. if (need_realloc && !_upb_array_realloc(arr, arr->len + elem, d->arena)) {
  298. decode_err(d);
  299. }
  300. return need_realloc;
  301. }
  302. UPB_NOINLINE
  303. static const char *decode_longvarint64(upb_decstate *d, const char *ptr,
  304. const char *limit, uint64_t *val) {
  305. uint8_t byte;
  306. int bitpos = 0;
  307. uint64_t out = 0;
  308. do {
  309. if (bitpos >= 70 || ptr == limit) decode_err(d);
  310. byte = *ptr;
  311. out |= (uint64_t)(byte & 0x7F) << bitpos;
  312. ptr++;
  313. bitpos += 7;
  314. } while (byte & 0x80);
  315. *val = out;
  316. return ptr;
  317. }
  318. UPB_FORCEINLINE
  319. static const char *decode_varint64(upb_decstate *d, const char *ptr,
  320. const char *limit, uint64_t *val) {
  321. if (UPB_LIKELY(ptr < limit && (*ptr & 0x80) == 0)) {
  322. *val = (uint8_t)*ptr;
  323. return ptr + 1;
  324. } else {
  325. return decode_longvarint64(d, ptr, limit, val);
  326. }
  327. }
  328. static const char *decode_varint32(upb_decstate *d, const char *ptr,
  329. const char *limit, uint32_t *val) {
  330. uint64_t u64;
  331. ptr = decode_varint64(d, ptr, limit, &u64);
  332. if (u64 > UINT32_MAX) decode_err(d);
  333. *val = (uint32_t)u64;
  334. return ptr;
  335. }
  336. static void decode_munge(int type, wireval *val) {
  337. switch (type) {
  338. case UPB_DESCRIPTOR_TYPE_BOOL:
  339. val->bool_val = val->uint64_val != 0;
  340. break;
  341. case UPB_DESCRIPTOR_TYPE_SINT32: {
  342. uint32_t n = val->uint32_val;
  343. val->int32_val = (n >> 1) ^ -(int32_t)(n & 1);
  344. break;
  345. }
  346. case UPB_DESCRIPTOR_TYPE_SINT64: {
  347. uint64_t n = val->uint64_val;
  348. val->int64_val = (n >> 1) ^ -(int64_t)(n & 1);
  349. break;
  350. }
  351. }
  352. }
  353. static const upb_msglayout_field *upb_find_field(const upb_msglayout *l,
  354. uint32_t field_number) {
  355. static upb_msglayout_field none = {0};
  356. /* Lots of optimization opportunities here. */
  357. int i;
  358. if (l == NULL) return &none;
  359. for (i = 0; i < l->field_count; i++) {
  360. if (l->fields[i].number == field_number) {
  361. return &l->fields[i];
  362. }
  363. }
  364. return &none; /* Unknown field. */
  365. }
  366. static upb_msg *decode_newsubmsg(upb_decstate *d, const upb_msglayout *layout,
  367. const upb_msglayout_field *field) {
  368. const upb_msglayout *subl = layout->submsgs[field->submsg_index];
  369. return _upb_msg_new(subl, d->arena);
  370. }
  371. static void decode_tosubmsg(upb_decstate *d, upb_msg *submsg,
  372. const upb_msglayout *layout,
  373. const upb_msglayout_field *field, upb_strview val) {
  374. const upb_msglayout *subl = layout->submsgs[field->submsg_index];
  375. const char *saved_limit = d->limit;
  376. if (--d->depth < 0) decode_err(d);
  377. d->limit = val.data + val.size;
  378. decode_msg(d, val.data, submsg, subl);
  379. d->limit = saved_limit;
  380. if (d->end_group != 0) decode_err(d);
  381. d->depth++;
  382. }
  383. static const char *decode_group(upb_decstate *d, const char *ptr,
  384. upb_msg *submsg, const upb_msglayout *subl,
  385. uint32_t number) {
  386. if (--d->depth < 0) decode_err(d);
  387. ptr = decode_msg(d, ptr, submsg, subl);
  388. if (d->end_group != number) decode_err(d);
  389. d->end_group = 0;
  390. d->depth++;
  391. return ptr;
  392. }
  393. static const char *decode_togroup(upb_decstate *d, const char *ptr,
  394. upb_msg *submsg, const upb_msglayout *layout,
  395. const upb_msglayout_field *field) {
  396. const upb_msglayout *subl = layout->submsgs[field->submsg_index];
  397. return decode_group(d, ptr, submsg, subl, field->number);
  398. }
  399. static const char *decode_toarray(upb_decstate *d, const char *ptr,
  400. upb_msg *msg, const upb_msglayout *layout,
  401. const upb_msglayout_field *field, wireval val,
  402. int op) {
  403. upb_array **arrp = UPB_PTR_AT(msg, field->offset, void);
  404. upb_array *arr = *arrp;
  405. void *mem;
  406. if (!arr) {
  407. upb_fieldtype_t type = desctype_to_fieldtype[field->descriptortype];
  408. arr = _upb_array_new(d->arena, type);
  409. if (!arr) decode_err(d);
  410. *arrp = arr;
  411. }
  412. decode_reserve(d, arr, 1);
  413. switch (op) {
  414. case OP_SCALAR_LG2(0):
  415. case OP_SCALAR_LG2(2):
  416. case OP_SCALAR_LG2(3):
  417. /* Append scalar value. */
  418. mem = UPB_PTR_AT(_upb_array_ptr(arr), arr->len << op, void);
  419. arr->len++;
  420. memcpy(mem, &val, 1 << op);
  421. return ptr;
  422. case OP_STRING:
  423. /* Append string. */
  424. mem =
  425. UPB_PTR_AT(_upb_array_ptr(arr), arr->len * sizeof(upb_strview), void);
  426. arr->len++;
  427. memcpy(mem, &val, sizeof(upb_strview));
  428. return ptr;
  429. case OP_SUBMSG: {
  430. /* Append submessage / group. */
  431. upb_msg *submsg = decode_newsubmsg(d, layout, field);
  432. *UPB_PTR_AT(_upb_array_ptr(arr), arr->len * sizeof(void *), upb_msg *) =
  433. submsg;
  434. arr->len++;
  435. if (UPB_UNLIKELY(field->descriptortype == UPB_DTYPE_GROUP)) {
  436. ptr = decode_togroup(d, ptr, submsg, layout, field);
  437. } else {
  438. decode_tosubmsg(d, submsg, layout, field, val.str_val);
  439. }
  440. return ptr;
  441. }
  442. case OP_FIXPCK_LG2(2):
  443. case OP_FIXPCK_LG2(3): {
  444. /* Fixed packed. */
  445. int lg2 = op - OP_FIXPCK_LG2(0);
  446. int mask = (1 << lg2) - 1;
  447. int count = val.str_val.size >> lg2;
  448. if ((val.str_val.size & mask) != 0) {
  449. decode_err(d); /* Length isn't a round multiple of elem size. */
  450. }
  451. decode_reserve(d, arr, count);
  452. mem = UPB_PTR_AT(_upb_array_ptr(arr), arr->len << lg2, void);
  453. arr->len += count;
  454. memcpy(mem, val.str_val.data, val.str_val.size);
  455. return ptr;
  456. }
  457. case OP_VARPCK_LG2(0):
  458. case OP_VARPCK_LG2(2):
  459. case OP_VARPCK_LG2(3): {
  460. /* Varint packed. */
  461. int lg2 = op - OP_VARPCK_LG2(0);
  462. int scale = 1 << lg2;
  463. const char *ptr = val.str_val.data;
  464. const char *end = ptr + val.str_val.size;
  465. char *out = UPB_PTR_AT(_upb_array_ptr(arr), arr->len << lg2, void);
  466. while (ptr < end) {
  467. wireval elem;
  468. ptr = decode_varint64(d, ptr, end, &elem.uint64_val);
  469. decode_munge(field->descriptortype, &elem);
  470. if (decode_reserve(d, arr, 1)) {
  471. out = UPB_PTR_AT(_upb_array_ptr(arr), arr->len << lg2, void);
  472. }
  473. arr->len++;
  474. memcpy(out, &elem, scale);
  475. out += scale;
  476. }
  477. if (ptr != end) decode_err(d);
  478. return ptr;
  479. }
  480. default:
  481. UPB_UNREACHABLE();
  482. }
  483. }
  484. static void decode_tomap(upb_decstate *d, upb_msg *msg,
  485. const upb_msglayout *layout,
  486. const upb_msglayout_field *field, wireval val) {
  487. upb_map **map_p = UPB_PTR_AT(msg, field->offset, upb_map *);
  488. upb_map *map = *map_p;
  489. upb_map_entry ent;
  490. const upb_msglayout *entry = layout->submsgs[field->submsg_index];
  491. if (!map) {
  492. /* Lazily create map. */
  493. const upb_msglayout *entry = layout->submsgs[field->submsg_index];
  494. const upb_msglayout_field *key_field = &entry->fields[0];
  495. const upb_msglayout_field *val_field = &entry->fields[1];
  496. char key_size = desctype_to_mapsize[key_field->descriptortype];
  497. char val_size = desctype_to_mapsize[val_field->descriptortype];
  498. UPB_ASSERT(key_field->offset == 0);
  499. UPB_ASSERT(val_field->offset == sizeof(upb_strview));
  500. map = _upb_map_new(d->arena, key_size, val_size);
  501. *map_p = map;
  502. }
  503. /* Parse map entry. */
  504. memset(&ent, 0, sizeof(ent));
  505. if (entry->fields[1].descriptortype == UPB_DESCRIPTOR_TYPE_MESSAGE ||
  506. entry->fields[1].descriptortype == UPB_DESCRIPTOR_TYPE_GROUP) {
  507. /* Create proactively to handle the case where it doesn't appear. */
  508. ent.v.val.val = (uint64_t)_upb_msg_new(entry->submsgs[0], d->arena);
  509. }
  510. decode_tosubmsg(d, &ent.k, layout, field, val.str_val);
  511. /* Insert into map. */
  512. _upb_map_set(map, &ent.k, map->key_size, &ent.v, map->val_size, d->arena);
  513. }
  514. static const char *decode_tomsg(upb_decstate *d, const char *ptr, upb_msg *msg,
  515. const upb_msglayout *layout,
  516. const upb_msglayout_field *field, wireval val,
  517. int op) {
  518. void *mem = UPB_PTR_AT(msg, field->offset, void);
  519. int type = field->descriptortype;
  520. /* Set presence if necessary. */
  521. if (field->presence < 0) {
  522. /* Oneof case */
  523. *UPB_PTR_AT(msg, -field->presence, int32_t) = field->number;
  524. } else if (field->presence > 0) {
  525. /* Hasbit */
  526. uint32_t hasbit = field->presence;
  527. *UPB_PTR_AT(msg, hasbit / 8, uint8_t) |= (1 << (hasbit % 8));
  528. }
  529. /* Store into message. */
  530. switch (op) {
  531. case OP_SUBMSG: {
  532. upb_msg **submsgp = mem;
  533. upb_msg *submsg = *submsgp;
  534. if (!submsg) {
  535. submsg = decode_newsubmsg(d, layout, field);
  536. *submsgp = submsg;
  537. }
  538. if (UPB_UNLIKELY(type == UPB_DTYPE_GROUP)) {
  539. ptr = decode_togroup(d, ptr, submsg, layout, field);
  540. } else {
  541. decode_tosubmsg(d, submsg, layout, field, val.str_val);
  542. }
  543. break;
  544. }
  545. case OP_STRING:
  546. memcpy(mem, &val, sizeof(upb_strview));
  547. break;
  548. case OP_SCALAR_LG2(3):
  549. memcpy(mem, &val, 8);
  550. break;
  551. case OP_SCALAR_LG2(2):
  552. memcpy(mem, &val, 4);
  553. break;
  554. case OP_SCALAR_LG2(0):
  555. memcpy(mem, &val, 1);
  556. break;
  557. default:
  558. UPB_UNREACHABLE();
  559. }
  560. return ptr;
  561. }
  562. static const char *decode_msg(upb_decstate *d, const char *ptr, upb_msg *msg,
  563. const upb_msglayout *layout) {
  564. while (ptr < d->limit) {
  565. uint32_t tag;
  566. const upb_msglayout_field *field;
  567. int field_number;
  568. int wire_type;
  569. const char *field_start = ptr;
  570. wireval val;
  571. int op;
  572. ptr = decode_varint32(d, ptr, d->limit, &tag);
  573. field_number = tag >> 3;
  574. wire_type = tag & 7;
  575. field = upb_find_field(layout, field_number);
  576. switch (wire_type) {
  577. case UPB_WIRE_TYPE_VARINT:
  578. ptr = decode_varint64(d, ptr, d->limit, &val.uint64_val);
  579. op = varint_ops[field->descriptortype];
  580. decode_munge(field->descriptortype, &val);
  581. break;
  582. case UPB_WIRE_TYPE_32BIT:
  583. if (d->limit - ptr < 4) decode_err(d);
  584. memcpy(&val, ptr, 4);
  585. ptr += 4;
  586. op = OP_SCALAR_LG2(2);
  587. if (((1 << field->descriptortype) & fixed32_ok) == 0) goto unknown;
  588. break;
  589. case UPB_WIRE_TYPE_64BIT:
  590. if (d->limit - ptr < 8) decode_err(d);
  591. memcpy(&val, ptr, 8);
  592. ptr += 8;
  593. op = OP_SCALAR_LG2(3);
  594. if (((1 << field->descriptortype) & fixed64_ok) == 0) goto unknown;
  595. break;
  596. case UPB_WIRE_TYPE_DELIMITED: {
  597. uint32_t size;
  598. int ndx = field->descriptortype;
  599. if (_upb_isrepeated(field)) ndx += 18;
  600. ptr = decode_varint32(d, ptr, d->limit, &size);
  601. if (size >= INT32_MAX || (size_t)(d->limit - ptr) < size) {
  602. decode_err(d); /* Length overflow. */
  603. }
  604. val.str_val.data = ptr;
  605. val.str_val.size = size;
  606. ptr += size;
  607. op = delim_ops[ndx];
  608. break;
  609. }
  610. case UPB_WIRE_TYPE_START_GROUP:
  611. val.int32_val = field_number;
  612. op = OP_SUBMSG;
  613. if (field->descriptortype != UPB_DTYPE_GROUP) goto unknown;
  614. break;
  615. case UPB_WIRE_TYPE_END_GROUP:
  616. d->end_group = field_number;
  617. return ptr;
  618. default:
  619. decode_err(d);
  620. }
  621. if (op >= 0) {
  622. /* Parse, using op for dispatch. */
  623. switch (field->label) {
  624. case UPB_LABEL_REPEATED:
  625. case _UPB_LABEL_PACKED:
  626. ptr = decode_toarray(d, ptr, msg, layout, field, val, op);
  627. break;
  628. case _UPB_LABEL_MAP:
  629. decode_tomap(d, msg, layout, field, val);
  630. break;
  631. default:
  632. ptr = decode_tomsg(d, ptr, msg, layout, field, val, op);
  633. break;
  634. }
  635. } else {
  636. unknown:
  637. /* Skip unknown field. */
  638. if (field_number == 0) decode_err(d);
  639. if (wire_type == UPB_WIRE_TYPE_START_GROUP) {
  640. ptr = decode_group(d, ptr, NULL, NULL, field_number);
  641. }
  642. if (msg) {
  643. if (!_upb_msg_addunknown(msg, field_start, ptr - field_start,
  644. d->arena)) {
  645. decode_err(d);
  646. }
  647. }
  648. }
  649. }
  650. if (ptr != d->limit) decode_err(d);
  651. return ptr;
  652. }
  653. bool upb_decode(const char *buf, size_t size, void *msg, const upb_msglayout *l,
  654. upb_arena *arena) {
  655. upb_decstate state;
  656. state.limit = buf + size;
  657. state.arena = arena;
  658. state.depth = 64;
  659. state.end_group = 0;
  660. if (setjmp(state.err)) return false;
  661. if (size == 0) return true;
  662. decode_msg(&state, buf, msg, l);
  663. return state.end_group == 0;
  664. }
  665. #undef OP_SCALAR_LG2
  666. #undef OP_FIXPCK_LG2
  667. #undef OP_VARPCK_LG2
  668. #undef OP_STRING
  669. #undef OP_SUBMSG
  670. /* We encode backwards, to avoid pre-computing lengths (one-pass encode). */
  671. #include <string.h>
  672. #define UPB_PB_VARINT_MAX_LEN 10
  673. #define CHK(x) do { if (!(x)) { return false; } } while(0)
  674. static size_t upb_encode_varint(uint64_t val, char *buf) {
  675. size_t i;
  676. if (val < 128) { buf[0] = val; return 1; }
  677. i = 0;
  678. while (val) {
  679. uint8_t byte = val & 0x7fU;
  680. val >>= 7;
  681. if (val) byte |= 0x80U;
  682. buf[i++] = byte;
  683. }
  684. return i;
  685. }
  686. static uint32_t upb_zzencode_32(int32_t n) { return ((uint32_t)n << 1) ^ (n >> 31); }
  687. static uint64_t upb_zzencode_64(int64_t n) { return ((uint64_t)n << 1) ^ (n >> 63); }
  688. typedef struct {
  689. upb_alloc *alloc;
  690. char *buf, *ptr, *limit;
  691. } upb_encstate;
  692. static size_t upb_roundup_pow2(size_t bytes) {
  693. size_t ret = 128;
  694. while (ret < bytes) {
  695. ret *= 2;
  696. }
  697. return ret;
  698. }
  699. static bool upb_encode_growbuffer(upb_encstate *e, size_t bytes) {
  700. size_t old_size = e->limit - e->buf;
  701. size_t new_size = upb_roundup_pow2(bytes + (e->limit - e->ptr));
  702. char *new_buf = upb_realloc(e->alloc, e->buf, old_size, new_size);
  703. CHK(new_buf);
  704. /* We want previous data at the end, realloc() put it at the beginning. */
  705. if (old_size > 0) {
  706. memmove(new_buf + new_size - old_size, e->buf, old_size);
  707. }
  708. e->ptr = new_buf + new_size - (e->limit - e->ptr);
  709. e->limit = new_buf + new_size;
  710. e->buf = new_buf;
  711. return true;
  712. }
  713. /* Call to ensure that at least "bytes" bytes are available for writing at
  714. * e->ptr. Returns false if the bytes could not be allocated. */
  715. static bool upb_encode_reserve(upb_encstate *e, size_t bytes) {
  716. CHK(UPB_LIKELY((size_t)(e->ptr - e->buf) >= bytes) ||
  717. upb_encode_growbuffer(e, bytes));
  718. e->ptr -= bytes;
  719. return true;
  720. }
  721. /* Writes the given bytes to the buffer, handling reserve/advance. */
  722. static bool upb_put_bytes(upb_encstate *e, const void *data, size_t len) {
  723. if (len == 0) return true;
  724. CHK(upb_encode_reserve(e, len));
  725. memcpy(e->ptr, data, len);
  726. return true;
  727. }
  728. static bool upb_put_fixed64(upb_encstate *e, uint64_t val) {
  729. /* TODO(haberman): byte-swap for big endian. */
  730. return upb_put_bytes(e, &val, sizeof(uint64_t));
  731. }
  732. static bool upb_put_fixed32(upb_encstate *e, uint32_t val) {
  733. /* TODO(haberman): byte-swap for big endian. */
  734. return upb_put_bytes(e, &val, sizeof(uint32_t));
  735. }
  736. static bool upb_put_varint(upb_encstate *e, uint64_t val) {
  737. size_t len;
  738. char *start;
  739. CHK(upb_encode_reserve(e, UPB_PB_VARINT_MAX_LEN));
  740. len = upb_encode_varint(val, e->ptr);
  741. start = e->ptr + UPB_PB_VARINT_MAX_LEN - len;
  742. memmove(start, e->ptr, len);
  743. e->ptr = start;
  744. return true;
  745. }
  746. static bool upb_put_double(upb_encstate *e, double d) {
  747. uint64_t u64;
  748. UPB_ASSERT(sizeof(double) == sizeof(uint64_t));
  749. memcpy(&u64, &d, sizeof(uint64_t));
  750. return upb_put_fixed64(e, u64);
  751. }
  752. static bool upb_put_float(upb_encstate *e, float d) {
  753. uint32_t u32;
  754. UPB_ASSERT(sizeof(float) == sizeof(uint32_t));
  755. memcpy(&u32, &d, sizeof(uint32_t));
  756. return upb_put_fixed32(e, u32);
  757. }
  758. static uint32_t upb_readcase(const char *msg, const upb_msglayout_field *f) {
  759. uint32_t ret;
  760. memcpy(&ret, msg - f->presence, sizeof(ret));
  761. return ret;
  762. }
  763. static bool upb_readhasbit(const char *msg, const upb_msglayout_field *f) {
  764. uint32_t hasbit = f->presence;
  765. UPB_ASSERT(f->presence > 0);
  766. return (*UPB_PTR_AT(msg, hasbit / 8, uint8_t)) & (1 << (hasbit % 8));
  767. }
  768. static bool upb_put_tag(upb_encstate *e, int field_number, int wire_type) {
  769. return upb_put_varint(e, (field_number << 3) | wire_type);
  770. }
  771. static bool upb_put_fixedarray(upb_encstate *e, const upb_array *arr,
  772. size_t elem_size, uint32_t tag) {
  773. size_t bytes = arr->len * elem_size;
  774. const char* data = _upb_array_constptr(arr);
  775. const char* ptr = data + bytes - elem_size;
  776. if (tag) {
  777. while (true) {
  778. CHK(upb_put_bytes(e, ptr, elem_size) && upb_put_varint(e, tag));
  779. if (ptr == data) break;
  780. ptr -= elem_size;
  781. }
  782. return true;
  783. } else {
  784. return upb_put_bytes(e, data, bytes) && upb_put_varint(e, bytes);
  785. }
  786. }
  787. bool upb_encode_message(upb_encstate *e, const char *msg,
  788. const upb_msglayout *m, size_t *size);
  789. static bool upb_encode_scalarfield(upb_encstate *e, const void *_field_mem,
  790. const upb_msglayout *m,
  791. const upb_msglayout_field *f,
  792. bool skip_zero_value) {
  793. const char *field_mem = _field_mem;
  794. #define CASE(ctype, type, wire_type, encodeval) do { \
  795. ctype val = *(ctype*)field_mem; \
  796. if (skip_zero_value && val == 0) { \
  797. return true; \
  798. } \
  799. return upb_put_ ## type(e, encodeval) && \
  800. upb_put_tag(e, f->number, wire_type); \
  801. } while(0)
  802. switch (f->descriptortype) {
  803. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  804. CASE(double, double, UPB_WIRE_TYPE_64BIT, val);
  805. case UPB_DESCRIPTOR_TYPE_FLOAT:
  806. CASE(float, float, UPB_WIRE_TYPE_32BIT, val);
  807. case UPB_DESCRIPTOR_TYPE_INT64:
  808. case UPB_DESCRIPTOR_TYPE_UINT64:
  809. CASE(uint64_t, varint, UPB_WIRE_TYPE_VARINT, val);
  810. case UPB_DESCRIPTOR_TYPE_UINT32:
  811. CASE(uint32_t, varint, UPB_WIRE_TYPE_VARINT, val);
  812. case UPB_DESCRIPTOR_TYPE_INT32:
  813. case UPB_DESCRIPTOR_TYPE_ENUM:
  814. CASE(int32_t, varint, UPB_WIRE_TYPE_VARINT, (int64_t)val);
  815. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  816. case UPB_DESCRIPTOR_TYPE_FIXED64:
  817. CASE(uint64_t, fixed64, UPB_WIRE_TYPE_64BIT, val);
  818. case UPB_DESCRIPTOR_TYPE_FIXED32:
  819. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  820. CASE(uint32_t, fixed32, UPB_WIRE_TYPE_32BIT, val);
  821. case UPB_DESCRIPTOR_TYPE_BOOL:
  822. CASE(bool, varint, UPB_WIRE_TYPE_VARINT, val);
  823. case UPB_DESCRIPTOR_TYPE_SINT32:
  824. CASE(int32_t, varint, UPB_WIRE_TYPE_VARINT, upb_zzencode_32(val));
  825. case UPB_DESCRIPTOR_TYPE_SINT64:
  826. CASE(int64_t, varint, UPB_WIRE_TYPE_VARINT, upb_zzencode_64(val));
  827. case UPB_DESCRIPTOR_TYPE_STRING:
  828. case UPB_DESCRIPTOR_TYPE_BYTES: {
  829. upb_strview view = *(upb_strview*)field_mem;
  830. if (skip_zero_value && view.size == 0) {
  831. return true;
  832. }
  833. return upb_put_bytes(e, view.data, view.size) &&
  834. upb_put_varint(e, view.size) &&
  835. upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED);
  836. }
  837. case UPB_DESCRIPTOR_TYPE_GROUP: {
  838. size_t size;
  839. void *submsg = *(void **)field_mem;
  840. const upb_msglayout *subm = m->submsgs[f->submsg_index];
  841. if (submsg == NULL) {
  842. return true;
  843. }
  844. return upb_put_tag(e, f->number, UPB_WIRE_TYPE_END_GROUP) &&
  845. upb_encode_message(e, submsg, subm, &size) &&
  846. upb_put_tag(e, f->number, UPB_WIRE_TYPE_START_GROUP);
  847. }
  848. case UPB_DESCRIPTOR_TYPE_MESSAGE: {
  849. size_t size;
  850. void *submsg = *(void **)field_mem;
  851. const upb_msglayout *subm = m->submsgs[f->submsg_index];
  852. if (submsg == NULL) {
  853. return true;
  854. }
  855. return upb_encode_message(e, submsg, subm, &size) &&
  856. upb_put_varint(e, size) &&
  857. upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED);
  858. }
  859. }
  860. #undef CASE
  861. UPB_UNREACHABLE();
  862. }
  863. static bool upb_encode_array(upb_encstate *e, const char *field_mem,
  864. const upb_msglayout *m,
  865. const upb_msglayout_field *f) {
  866. const upb_array *arr = *(const upb_array**)field_mem;
  867. bool packed = f->label == _UPB_LABEL_PACKED;
  868. if (arr == NULL || arr->len == 0) {
  869. return true;
  870. }
  871. #define VARINT_CASE(ctype, encode) \
  872. { \
  873. const ctype *start = _upb_array_constptr(arr); \
  874. const ctype *ptr = start + arr->len; \
  875. size_t pre_len = e->limit - e->ptr; \
  876. uint32_t tag = packed ? 0 : (f->number << 3) | UPB_WIRE_TYPE_VARINT; \
  877. do { \
  878. ptr--; \
  879. CHK(upb_put_varint(e, encode)); \
  880. if (tag) CHK(upb_put_varint(e, tag)); \
  881. } while (ptr != start); \
  882. if (!tag) CHK(upb_put_varint(e, e->limit - e->ptr - pre_len)); \
  883. } \
  884. break; \
  885. do { \
  886. ; \
  887. } while (0)
  888. #define TAG(wire_type) (packed ? 0 : (f->number << 3 | wire_type))
  889. switch (f->descriptortype) {
  890. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  891. CHK(upb_put_fixedarray(e, arr, sizeof(double), TAG(UPB_WIRE_TYPE_64BIT)));
  892. break;
  893. case UPB_DESCRIPTOR_TYPE_FLOAT:
  894. CHK(upb_put_fixedarray(e, arr, sizeof(float), TAG(UPB_WIRE_TYPE_32BIT)));
  895. break;
  896. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  897. case UPB_DESCRIPTOR_TYPE_FIXED64:
  898. CHK(upb_put_fixedarray(e, arr, sizeof(uint64_t), TAG(UPB_WIRE_TYPE_64BIT)));
  899. break;
  900. case UPB_DESCRIPTOR_TYPE_FIXED32:
  901. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  902. CHK(upb_put_fixedarray(e, arr, sizeof(uint32_t), TAG(UPB_WIRE_TYPE_32BIT)));
  903. break;
  904. case UPB_DESCRIPTOR_TYPE_INT64:
  905. case UPB_DESCRIPTOR_TYPE_UINT64:
  906. VARINT_CASE(uint64_t, *ptr);
  907. case UPB_DESCRIPTOR_TYPE_UINT32:
  908. VARINT_CASE(uint32_t, *ptr);
  909. case UPB_DESCRIPTOR_TYPE_INT32:
  910. case UPB_DESCRIPTOR_TYPE_ENUM:
  911. VARINT_CASE(int32_t, (int64_t)*ptr);
  912. case UPB_DESCRIPTOR_TYPE_BOOL:
  913. VARINT_CASE(bool, *ptr);
  914. case UPB_DESCRIPTOR_TYPE_SINT32:
  915. VARINT_CASE(int32_t, upb_zzencode_32(*ptr));
  916. case UPB_DESCRIPTOR_TYPE_SINT64:
  917. VARINT_CASE(int64_t, upb_zzencode_64(*ptr));
  918. case UPB_DESCRIPTOR_TYPE_STRING:
  919. case UPB_DESCRIPTOR_TYPE_BYTES: {
  920. const upb_strview *start = _upb_array_constptr(arr);
  921. const upb_strview *ptr = start + arr->len;
  922. do {
  923. ptr--;
  924. CHK(upb_put_bytes(e, ptr->data, ptr->size) &&
  925. upb_put_varint(e, ptr->size) &&
  926. upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
  927. } while (ptr != start);
  928. return true;
  929. }
  930. case UPB_DESCRIPTOR_TYPE_GROUP: {
  931. const void *const*start = _upb_array_constptr(arr);
  932. const void *const*ptr = start + arr->len;
  933. const upb_msglayout *subm = m->submsgs[f->submsg_index];
  934. do {
  935. size_t size;
  936. ptr--;
  937. CHK(upb_put_tag(e, f->number, UPB_WIRE_TYPE_END_GROUP) &&
  938. upb_encode_message(e, *ptr, subm, &size) &&
  939. upb_put_tag(e, f->number, UPB_WIRE_TYPE_START_GROUP));
  940. } while (ptr != start);
  941. return true;
  942. }
  943. case UPB_DESCRIPTOR_TYPE_MESSAGE: {
  944. const void *const*start = _upb_array_constptr(arr);
  945. const void *const*ptr = start + arr->len;
  946. const upb_msglayout *subm = m->submsgs[f->submsg_index];
  947. do {
  948. size_t size;
  949. ptr--;
  950. CHK(upb_encode_message(e, *ptr, subm, &size) &&
  951. upb_put_varint(e, size) &&
  952. upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
  953. } while (ptr != start);
  954. return true;
  955. }
  956. }
  957. #undef VARINT_CASE
  958. if (packed) {
  959. CHK(upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
  960. }
  961. return true;
  962. }
  963. static bool upb_encode_map(upb_encstate *e, const char *field_mem,
  964. const upb_msglayout *m,
  965. const upb_msglayout_field *f) {
  966. const upb_map *map = *(const upb_map**)field_mem;
  967. const upb_msglayout *entry = m->submsgs[f->submsg_index];
  968. const upb_msglayout_field *key_field = &entry->fields[0];
  969. const upb_msglayout_field *val_field = &entry->fields[1];
  970. upb_strtable_iter i;
  971. if (map == NULL) {
  972. return true;
  973. }
  974. upb_strtable_begin(&i, &map->table);
  975. for(; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  976. size_t pre_len = e->limit - e->ptr;
  977. size_t size;
  978. upb_strview key = upb_strtable_iter_key(&i);
  979. const upb_value val = upb_strtable_iter_value(&i);
  980. const void *keyp =
  981. map->key_size == UPB_MAPTYPE_STRING ? (void *)&key : key.data;
  982. const void *valp =
  983. map->val_size == UPB_MAPTYPE_STRING ? upb_value_getptr(val) : &val;
  984. CHK(upb_encode_scalarfield(e, valp, entry, val_field, false));
  985. CHK(upb_encode_scalarfield(e, keyp, entry, key_field, false));
  986. size = (e->limit - e->ptr) - pre_len;
  987. CHK(upb_put_varint(e, size));
  988. CHK(upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
  989. }
  990. return true;
  991. }
  992. bool upb_encode_message(upb_encstate *e, const char *msg,
  993. const upb_msglayout *m, size_t *size) {
  994. int i;
  995. size_t pre_len = e->limit - e->ptr;
  996. const char *unknown;
  997. size_t unknown_size;
  998. unknown = upb_msg_getunknown(msg, &unknown_size);
  999. if (unknown) {
  1000. upb_put_bytes(e, unknown, unknown_size);
  1001. }
  1002. for (i = m->field_count - 1; i >= 0; i--) {
  1003. const upb_msglayout_field *f = &m->fields[i];
  1004. if (_upb_isrepeated(f)) {
  1005. CHK(upb_encode_array(e, msg + f->offset, m, f));
  1006. } else if (f->label == _UPB_LABEL_MAP) {
  1007. CHK(upb_encode_map(e, msg + f->offset, m, f));
  1008. } else {
  1009. bool skip_empty = false;
  1010. if (f->presence == 0) {
  1011. /* Proto3 presence. */
  1012. skip_empty = true;
  1013. } else if (f->presence > 0) {
  1014. /* Proto2 presence: hasbit. */
  1015. if (!upb_readhasbit(msg, f)) {
  1016. continue;
  1017. }
  1018. } else {
  1019. /* Field is in a oneof. */
  1020. if (upb_readcase(msg, f) != f->number) {
  1021. continue;
  1022. }
  1023. }
  1024. CHK(upb_encode_scalarfield(e, msg + f->offset, m, f, skip_empty));
  1025. }
  1026. }
  1027. *size = (e->limit - e->ptr) - pre_len;
  1028. return true;
  1029. }
  1030. char *upb_encode(const void *msg, const upb_msglayout *m, upb_arena *arena,
  1031. size_t *size) {
  1032. upb_encstate e;
  1033. e.alloc = upb_arena_alloc(arena);
  1034. e.buf = NULL;
  1035. e.limit = NULL;
  1036. e.ptr = NULL;
  1037. if (!upb_encode_message(&e, msg, m, size)) {
  1038. *size = 0;
  1039. return NULL;
  1040. }
  1041. *size = e.limit - e.ptr;
  1042. if (*size == 0) {
  1043. static char ch;
  1044. return &ch;
  1045. } else {
  1046. UPB_ASSERT(e.ptr);
  1047. return e.ptr;
  1048. }
  1049. }
  1050. #undef CHK
  1051. /** upb_msg *******************************************************************/
  1052. static const char _upb_fieldtype_to_sizelg2[12] = {
  1053. 0,
  1054. 0, /* UPB_TYPE_BOOL */
  1055. 2, /* UPB_TYPE_FLOAT */
  1056. 2, /* UPB_TYPE_INT32 */
  1057. 2, /* UPB_TYPE_UINT32 */
  1058. 2, /* UPB_TYPE_ENUM */
  1059. UPB_SIZE(2, 3), /* UPB_TYPE_MESSAGE */
  1060. 3, /* UPB_TYPE_DOUBLE */
  1061. 3, /* UPB_TYPE_INT64 */
  1062. 3, /* UPB_TYPE_UINT64 */
  1063. UPB_SIZE(3, 4), /* UPB_TYPE_STRING */
  1064. UPB_SIZE(3, 4), /* UPB_TYPE_BYTES */
  1065. };
  1066. static uintptr_t tag_arrptr(void* ptr, int elem_size_lg2) {
  1067. UPB_ASSERT(elem_size_lg2 <= 4);
  1068. return (uintptr_t)ptr | elem_size_lg2;
  1069. }
  1070. static int upb_msg_internalsize(const upb_msglayout *l) {
  1071. return sizeof(upb_msg_internal) - l->extendable * sizeof(void *);
  1072. }
  1073. static size_t upb_msg_sizeof(const upb_msglayout *l) {
  1074. return l->size + upb_msg_internalsize(l);
  1075. }
  1076. static upb_msg_internal *upb_msg_getinternal(upb_msg *msg) {
  1077. return UPB_PTR_AT(msg, -sizeof(upb_msg_internal), upb_msg_internal);
  1078. }
  1079. static const upb_msg_internal *upb_msg_getinternal_const(const upb_msg *msg) {
  1080. return UPB_PTR_AT(msg, -sizeof(upb_msg_internal), upb_msg_internal);
  1081. }
  1082. static upb_msg_internal_withext *upb_msg_getinternalwithext(
  1083. upb_msg *msg, const upb_msglayout *l) {
  1084. UPB_ASSERT(l->extendable);
  1085. return UPB_PTR_AT(msg, -sizeof(upb_msg_internal_withext),
  1086. upb_msg_internal_withext);
  1087. }
  1088. upb_msg *_upb_msg_new(const upb_msglayout *l, upb_arena *a) {
  1089. void *mem = upb_arena_malloc(a, upb_msg_sizeof(l));
  1090. upb_msg_internal *in;
  1091. upb_msg *msg;
  1092. if (!mem) {
  1093. return NULL;
  1094. }
  1095. msg = UPB_PTR_AT(mem, upb_msg_internalsize(l), upb_msg);
  1096. /* Initialize normal members. */
  1097. memset(msg, 0, l->size);
  1098. /* Initialize internal members. */
  1099. in = upb_msg_getinternal(msg);
  1100. in->unknown = NULL;
  1101. in->unknown_len = 0;
  1102. in->unknown_size = 0;
  1103. if (l->extendable) {
  1104. upb_msg_getinternalwithext(msg, l)->extdict = NULL;
  1105. }
  1106. return msg;
  1107. }
  1108. bool _upb_msg_addunknown(upb_msg *msg, const char *data, size_t len,
  1109. upb_arena *arena) {
  1110. upb_msg_internal *in = upb_msg_getinternal(msg);
  1111. if (len > in->unknown_size - in->unknown_len) {
  1112. upb_alloc *alloc = upb_arena_alloc(arena);
  1113. size_t need = in->unknown_size + len;
  1114. size_t newsize = UPB_MAX(in->unknown_size * 2, need);
  1115. void *mem = upb_realloc(alloc, in->unknown, in->unknown_size, newsize);
  1116. if (!mem) return false;
  1117. in->unknown = mem;
  1118. in->unknown_size = newsize;
  1119. }
  1120. memcpy(in->unknown + in->unknown_len, data, len);
  1121. in->unknown_len += len;
  1122. return true;
  1123. }
  1124. const char *upb_msg_getunknown(const upb_msg *msg, size_t *len) {
  1125. const upb_msg_internal *in = upb_msg_getinternal_const(msg);
  1126. *len = in->unknown_len;
  1127. return in->unknown;
  1128. }
  1129. /** upb_array *****************************************************************/
  1130. upb_array *_upb_array_new(upb_arena *a, upb_fieldtype_t type) {
  1131. upb_array *arr = upb_arena_malloc(a, sizeof(upb_array));
  1132. if (!arr) {
  1133. return NULL;
  1134. }
  1135. arr->data = tag_arrptr(NULL, _upb_fieldtype_to_sizelg2[type]);
  1136. arr->len = 0;
  1137. arr->size = 0;
  1138. return arr;
  1139. }
  1140. bool _upb_array_realloc(upb_array *arr, size_t min_size, upb_arena *arena) {
  1141. size_t new_size = UPB_MAX(arr->size, 4);
  1142. int elem_size_lg2 = arr->data & 7;
  1143. size_t old_bytes = arr->size << elem_size_lg2;
  1144. size_t new_bytes;
  1145. void* ptr = _upb_array_ptr(arr);
  1146. /* Log2 ceiling of size. */
  1147. while (new_size < min_size) new_size *= 2;
  1148. new_bytes = new_size << elem_size_lg2;
  1149. ptr = upb_arena_realloc(arena, ptr, old_bytes, new_bytes);
  1150. if (!ptr) {
  1151. return false;
  1152. }
  1153. arr->data = tag_arrptr(ptr, elem_size_lg2);
  1154. arr->size = new_size;
  1155. return true;
  1156. }
  1157. static upb_array *getorcreate_array(upb_array **arr_ptr, upb_fieldtype_t type,
  1158. upb_arena *arena) {
  1159. upb_array *arr = *arr_ptr;
  1160. if (!arr) {
  1161. arr = _upb_array_new(arena, type);
  1162. if (!arr) return NULL;
  1163. *arr_ptr = arr;
  1164. }
  1165. return arr;
  1166. }
  1167. static bool resize_array(upb_array *arr, size_t size, upb_arena *arena) {
  1168. if (size > arr->size && !_upb_array_realloc(arr, size, arena)) {
  1169. return false;
  1170. }
  1171. arr->len = size;
  1172. return true;
  1173. }
  1174. void *_upb_array_resize_fallback(upb_array **arr_ptr, size_t size,
  1175. upb_fieldtype_t type, upb_arena *arena) {
  1176. upb_array *arr = getorcreate_array(arr_ptr, type, arena);
  1177. return arr && resize_array(arr, size, arena) ? _upb_array_ptr(arr) : NULL;
  1178. }
  1179. bool _upb_array_append_fallback(upb_array **arr_ptr, const void *value,
  1180. upb_fieldtype_t type, upb_arena *arena) {
  1181. upb_array *arr = getorcreate_array(arr_ptr, type, arena);
  1182. size_t elem = arr->len;
  1183. int lg2 = _upb_fieldtype_to_sizelg2[type];
  1184. char *data;
  1185. if (!arr || !resize_array(arr, elem + 1, arena)) return false;
  1186. data = _upb_array_ptr(arr);
  1187. memcpy(data + (elem << lg2), value, 1 << lg2);
  1188. return true;
  1189. }
  1190. /** upb_map *******************************************************************/
  1191. upb_map *_upb_map_new(upb_arena *a, size_t key_size, size_t value_size) {
  1192. upb_map *map = upb_arena_malloc(a, sizeof(upb_map));
  1193. if (!map) {
  1194. return NULL;
  1195. }
  1196. upb_strtable_init2(&map->table, UPB_CTYPE_INT32, upb_arena_alloc(a));
  1197. map->key_size = key_size;
  1198. map->val_size = value_size;
  1199. return map;
  1200. }
  1201. /*
  1202. ** upb_table Implementation
  1203. **
  1204. ** Implementation is heavily inspired by Lua's ltable.c.
  1205. */
  1206. #include <string.h>
  1207. #define UPB_MAXARRSIZE 16 /* 64k. */
  1208. /* From Chromium. */
  1209. #define ARRAY_SIZE(x) \
  1210. ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x])))))
  1211. static const double MAX_LOAD = 0.85;
  1212. /* The minimum utilization of the array part of a mixed hash/array table. This
  1213. * is a speed/memory-usage tradeoff (though it's not straightforward because of
  1214. * cache effects). The lower this is, the more memory we'll use. */
  1215. static const double MIN_DENSITY = 0.1;
  1216. bool is_pow2(uint64_t v) { return v == 0 || (v & (v - 1)) == 0; }
  1217. int log2ceil(uint64_t v) {
  1218. int ret = 0;
  1219. bool pow2 = is_pow2(v);
  1220. while (v >>= 1) ret++;
  1221. ret = pow2 ? ret : ret + 1; /* Ceiling. */
  1222. return UPB_MIN(UPB_MAXARRSIZE, ret);
  1223. }
  1224. char *upb_strdup(const char *s, upb_alloc *a) {
  1225. return upb_strdup2(s, strlen(s), a);
  1226. }
  1227. char *upb_strdup2(const char *s, size_t len, upb_alloc *a) {
  1228. size_t n;
  1229. char *p;
  1230. /* Prevent overflow errors. */
  1231. if (len == SIZE_MAX) return NULL;
  1232. /* Always null-terminate, even if binary data; but don't rely on the input to
  1233. * have a null-terminating byte since it may be a raw binary buffer. */
  1234. n = len + 1;
  1235. p = upb_malloc(a, n);
  1236. if (p) {
  1237. memcpy(p, s, len);
  1238. p[len] = 0;
  1239. }
  1240. return p;
  1241. }
  1242. /* A type to represent the lookup key of either a strtable or an inttable. */
  1243. typedef union {
  1244. uintptr_t num;
  1245. struct {
  1246. const char *str;
  1247. size_t len;
  1248. } str;
  1249. } lookupkey_t;
  1250. static lookupkey_t strkey2(const char *str, size_t len) {
  1251. lookupkey_t k;
  1252. k.str.str = str;
  1253. k.str.len = len;
  1254. return k;
  1255. }
  1256. static lookupkey_t intkey(uintptr_t key) {
  1257. lookupkey_t k;
  1258. k.num = key;
  1259. return k;
  1260. }
  1261. typedef uint32_t hashfunc_t(upb_tabkey key);
  1262. typedef bool eqlfunc_t(upb_tabkey k1, lookupkey_t k2);
  1263. /* Base table (shared code) ***************************************************/
  1264. /* For when we need to cast away const. */
  1265. static upb_tabent *mutable_entries(upb_table *t) {
  1266. return (upb_tabent*)t->entries;
  1267. }
  1268. static bool isfull(upb_table *t) {
  1269. if (upb_table_size(t) == 0) {
  1270. return true;
  1271. } else {
  1272. return ((double)(t->count + 1) / upb_table_size(t)) > MAX_LOAD;
  1273. }
  1274. }
  1275. static bool init(upb_table *t, uint8_t size_lg2, upb_alloc *a) {
  1276. size_t bytes;
  1277. t->count = 0;
  1278. t->size_lg2 = size_lg2;
  1279. t->mask = upb_table_size(t) ? upb_table_size(t) - 1 : 0;
  1280. bytes = upb_table_size(t) * sizeof(upb_tabent);
  1281. if (bytes > 0) {
  1282. t->entries = upb_malloc(a, bytes);
  1283. if (!t->entries) return false;
  1284. memset(mutable_entries(t), 0, bytes);
  1285. } else {
  1286. t->entries = NULL;
  1287. }
  1288. return true;
  1289. }
  1290. static void uninit(upb_table *t, upb_alloc *a) {
  1291. upb_free(a, mutable_entries(t));
  1292. }
  1293. static upb_tabent *emptyent(upb_table *t) {
  1294. upb_tabent *e = mutable_entries(t) + upb_table_size(t);
  1295. while (1) { if (upb_tabent_isempty(--e)) return e; UPB_ASSERT(e > t->entries); }
  1296. }
  1297. static upb_tabent *getentry_mutable(upb_table *t, uint32_t hash) {
  1298. return (upb_tabent*)upb_getentry(t, hash);
  1299. }
  1300. static const upb_tabent *findentry(const upb_table *t, lookupkey_t key,
  1301. uint32_t hash, eqlfunc_t *eql) {
  1302. const upb_tabent *e;
  1303. if (t->size_lg2 == 0) return NULL;
  1304. e = upb_getentry(t, hash);
  1305. if (upb_tabent_isempty(e)) return NULL;
  1306. while (1) {
  1307. if (eql(e->key, key)) return e;
  1308. if ((e = e->next) == NULL) return NULL;
  1309. }
  1310. }
  1311. static upb_tabent *findentry_mutable(upb_table *t, lookupkey_t key,
  1312. uint32_t hash, eqlfunc_t *eql) {
  1313. return (upb_tabent*)findentry(t, key, hash, eql);
  1314. }
  1315. static bool lookup(const upb_table *t, lookupkey_t key, upb_value *v,
  1316. uint32_t hash, eqlfunc_t *eql) {
  1317. const upb_tabent *e = findentry(t, key, hash, eql);
  1318. if (e) {
  1319. if (v) {
  1320. _upb_value_setval(v, e->val.val);
  1321. }
  1322. return true;
  1323. } else {
  1324. return false;
  1325. }
  1326. }
  1327. /* The given key must not already exist in the table. */
  1328. static void insert(upb_table *t, lookupkey_t key, upb_tabkey tabkey,
  1329. upb_value val, uint32_t hash,
  1330. hashfunc_t *hashfunc, eqlfunc_t *eql) {
  1331. upb_tabent *mainpos_e;
  1332. upb_tabent *our_e;
  1333. UPB_ASSERT(findentry(t, key, hash, eql) == NULL);
  1334. t->count++;
  1335. mainpos_e = getentry_mutable(t, hash);
  1336. our_e = mainpos_e;
  1337. if (upb_tabent_isempty(mainpos_e)) {
  1338. /* Our main position is empty; use it. */
  1339. our_e->next = NULL;
  1340. } else {
  1341. /* Collision. */
  1342. upb_tabent *new_e = emptyent(t);
  1343. /* Head of collider's chain. */
  1344. upb_tabent *chain = getentry_mutable(t, hashfunc(mainpos_e->key));
  1345. if (chain == mainpos_e) {
  1346. /* Existing ent is in its main posisiton (it has the same hash as us, and
  1347. * is the head of our chain). Insert to new ent and append to this chain. */
  1348. new_e->next = mainpos_e->next;
  1349. mainpos_e->next = new_e;
  1350. our_e = new_e;
  1351. } else {
  1352. /* Existing ent is not in its main position (it is a node in some other
  1353. * chain). This implies that no existing ent in the table has our hash.
  1354. * Evict it (updating its chain) and use its ent for head of our chain. */
  1355. *new_e = *mainpos_e; /* copies next. */
  1356. while (chain->next != mainpos_e) {
  1357. chain = (upb_tabent*)chain->next;
  1358. UPB_ASSERT(chain);
  1359. }
  1360. chain->next = new_e;
  1361. our_e = mainpos_e;
  1362. our_e->next = NULL;
  1363. }
  1364. }
  1365. our_e->key = tabkey;
  1366. our_e->val.val = val.val;
  1367. UPB_ASSERT(findentry(t, key, hash, eql) == our_e);
  1368. }
  1369. static bool rm(upb_table *t, lookupkey_t key, upb_value *val,
  1370. upb_tabkey *removed, uint32_t hash, eqlfunc_t *eql) {
  1371. upb_tabent *chain = getentry_mutable(t, hash);
  1372. if (upb_tabent_isempty(chain)) return false;
  1373. if (eql(chain->key, key)) {
  1374. /* Element to remove is at the head of its chain. */
  1375. t->count--;
  1376. if (val) _upb_value_setval(val, chain->val.val);
  1377. if (removed) *removed = chain->key;
  1378. if (chain->next) {
  1379. upb_tabent *move = (upb_tabent*)chain->next;
  1380. *chain = *move;
  1381. move->key = 0; /* Make the slot empty. */
  1382. } else {
  1383. chain->key = 0; /* Make the slot empty. */
  1384. }
  1385. return true;
  1386. } else {
  1387. /* Element to remove is either in a non-head position or not in the
  1388. * table. */
  1389. while (chain->next && !eql(chain->next->key, key)) {
  1390. chain = (upb_tabent*)chain->next;
  1391. }
  1392. if (chain->next) {
  1393. /* Found element to remove. */
  1394. upb_tabent *rm = (upb_tabent*)chain->next;
  1395. t->count--;
  1396. if (val) _upb_value_setval(val, chain->next->val.val);
  1397. if (removed) *removed = rm->key;
  1398. rm->key = 0; /* Make the slot empty. */
  1399. chain->next = rm->next;
  1400. return true;
  1401. } else {
  1402. /* Element to remove is not in the table. */
  1403. return false;
  1404. }
  1405. }
  1406. }
  1407. static size_t next(const upb_table *t, size_t i) {
  1408. do {
  1409. if (++i >= upb_table_size(t))
  1410. return SIZE_MAX;
  1411. } while(upb_tabent_isempty(&t->entries[i]));
  1412. return i;
  1413. }
  1414. static size_t begin(const upb_table *t) {
  1415. return next(t, -1);
  1416. }
  1417. /* upb_strtable ***************************************************************/
  1418. /* A simple "subclass" of upb_table that only adds a hash function for strings. */
  1419. static upb_tabkey strcopy(lookupkey_t k2, upb_alloc *a) {
  1420. uint32_t len = (uint32_t) k2.str.len;
  1421. char *str = upb_malloc(a, k2.str.len + sizeof(uint32_t) + 1);
  1422. if (str == NULL) return 0;
  1423. memcpy(str, &len, sizeof(uint32_t));
  1424. memcpy(str + sizeof(uint32_t), k2.str.str, k2.str.len);
  1425. str[sizeof(uint32_t) + k2.str.len] = '\0';
  1426. return (uintptr_t)str;
  1427. }
  1428. static uint32_t strhash(upb_tabkey key) {
  1429. uint32_t len;
  1430. char *str = upb_tabstr(key, &len);
  1431. return upb_murmur_hash2(str, len, 0);
  1432. }
  1433. static bool streql(upb_tabkey k1, lookupkey_t k2) {
  1434. uint32_t len;
  1435. char *str = upb_tabstr(k1, &len);
  1436. return len == k2.str.len && memcmp(str, k2.str.str, len) == 0;
  1437. }
  1438. bool upb_strtable_init2(upb_strtable *t, upb_ctype_t ctype, upb_alloc *a) {
  1439. return init(&t->t, 2, a);
  1440. }
  1441. void upb_strtable_clear(upb_strtable *t) {
  1442. size_t bytes = upb_table_size(&t->t) * sizeof(upb_tabent);
  1443. t->t.count = 0;
  1444. memset((char*)t->t.entries, 0, bytes);
  1445. }
  1446. void upb_strtable_uninit2(upb_strtable *t, upb_alloc *a) {
  1447. size_t i;
  1448. for (i = 0; i < upb_table_size(&t->t); i++)
  1449. upb_free(a, (void*)t->t.entries[i].key);
  1450. uninit(&t->t, a);
  1451. }
  1452. bool upb_strtable_resize(upb_strtable *t, size_t size_lg2, upb_alloc *a) {
  1453. upb_strtable new_table;
  1454. upb_strtable_iter i;
  1455. if (!init(&new_table.t, size_lg2, a))
  1456. return false;
  1457. upb_strtable_begin(&i, t);
  1458. for ( ; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  1459. upb_strview key = upb_strtable_iter_key(&i);
  1460. upb_strtable_insert3(
  1461. &new_table, key.data, key.size,
  1462. upb_strtable_iter_value(&i), a);
  1463. }
  1464. upb_strtable_uninit2(t, a);
  1465. *t = new_table;
  1466. return true;
  1467. }
  1468. bool upb_strtable_insert3(upb_strtable *t, const char *k, size_t len,
  1469. upb_value v, upb_alloc *a) {
  1470. lookupkey_t key;
  1471. upb_tabkey tabkey;
  1472. uint32_t hash;
  1473. if (isfull(&t->t)) {
  1474. /* Need to resize. New table of double the size, add old elements to it. */
  1475. if (!upb_strtable_resize(t, t->t.size_lg2 + 1, a)) {
  1476. return false;
  1477. }
  1478. }
  1479. key = strkey2(k, len);
  1480. tabkey = strcopy(key, a);
  1481. if (tabkey == 0) return false;
  1482. hash = upb_murmur_hash2(key.str.str, key.str.len, 0);
  1483. insert(&t->t, key, tabkey, v, hash, &strhash, &streql);
  1484. return true;
  1485. }
  1486. bool upb_strtable_lookup2(const upb_strtable *t, const char *key, size_t len,
  1487. upb_value *v) {
  1488. uint32_t hash = upb_murmur_hash2(key, len, 0);
  1489. return lookup(&t->t, strkey2(key, len), v, hash, &streql);
  1490. }
  1491. bool upb_strtable_remove3(upb_strtable *t, const char *key, size_t len,
  1492. upb_value *val, upb_alloc *alloc) {
  1493. uint32_t hash = upb_murmur_hash2(key, len, 0);
  1494. upb_tabkey tabkey;
  1495. if (rm(&t->t, strkey2(key, len), val, &tabkey, hash, &streql)) {
  1496. if (alloc) {
  1497. /* Arena-based allocs don't need to free and won't pass this. */
  1498. upb_free(alloc, (void*)tabkey);
  1499. }
  1500. return true;
  1501. } else {
  1502. return false;
  1503. }
  1504. }
  1505. /* Iteration */
  1506. void upb_strtable_begin(upb_strtable_iter *i, const upb_strtable *t) {
  1507. i->t = t;
  1508. i->index = begin(&t->t);
  1509. }
  1510. void upb_strtable_next(upb_strtable_iter *i) {
  1511. i->index = next(&i->t->t, i->index);
  1512. }
  1513. bool upb_strtable_done(const upb_strtable_iter *i) {
  1514. if (!i->t) return true;
  1515. return i->index >= upb_table_size(&i->t->t) ||
  1516. upb_tabent_isempty(str_tabent(i));
  1517. }
  1518. upb_strview upb_strtable_iter_key(const upb_strtable_iter *i) {
  1519. upb_strview key;
  1520. uint32_t len;
  1521. UPB_ASSERT(!upb_strtable_done(i));
  1522. key.data = upb_tabstr(str_tabent(i)->key, &len);
  1523. key.size = len;
  1524. return key;
  1525. }
  1526. upb_value upb_strtable_iter_value(const upb_strtable_iter *i) {
  1527. UPB_ASSERT(!upb_strtable_done(i));
  1528. return _upb_value_val(str_tabent(i)->val.val);
  1529. }
  1530. void upb_strtable_iter_setdone(upb_strtable_iter *i) {
  1531. i->t = NULL;
  1532. i->index = SIZE_MAX;
  1533. }
  1534. bool upb_strtable_iter_isequal(const upb_strtable_iter *i1,
  1535. const upb_strtable_iter *i2) {
  1536. if (upb_strtable_done(i1) && upb_strtable_done(i2))
  1537. return true;
  1538. return i1->t == i2->t && i1->index == i2->index;
  1539. }
  1540. /* upb_inttable ***************************************************************/
  1541. /* For inttables we use a hybrid structure where small keys are kept in an
  1542. * array and large keys are put in the hash table. */
  1543. static uint32_t inthash(upb_tabkey key) { return upb_inthash(key); }
  1544. static bool inteql(upb_tabkey k1, lookupkey_t k2) {
  1545. return k1 == k2.num;
  1546. }
  1547. static upb_tabval *mutable_array(upb_inttable *t) {
  1548. return (upb_tabval*)t->array;
  1549. }
  1550. static upb_tabval *inttable_val(upb_inttable *t, uintptr_t key) {
  1551. if (key < t->array_size) {
  1552. return upb_arrhas(t->array[key]) ? &(mutable_array(t)[key]) : NULL;
  1553. } else {
  1554. upb_tabent *e =
  1555. findentry_mutable(&t->t, intkey(key), upb_inthash(key), &inteql);
  1556. return e ? &e->val : NULL;
  1557. }
  1558. }
  1559. static const upb_tabval *inttable_val_const(const upb_inttable *t,
  1560. uintptr_t key) {
  1561. return inttable_val((upb_inttable*)t, key);
  1562. }
  1563. size_t upb_inttable_count(const upb_inttable *t) {
  1564. return t->t.count + t->array_count;
  1565. }
  1566. static void check(upb_inttable *t) {
  1567. UPB_UNUSED(t);
  1568. #if defined(UPB_DEBUG_TABLE) && !defined(NDEBUG)
  1569. {
  1570. /* This check is very expensive (makes inserts/deletes O(N)). */
  1571. size_t count = 0;
  1572. upb_inttable_iter i;
  1573. upb_inttable_begin(&i, t);
  1574. for(; !upb_inttable_done(&i); upb_inttable_next(&i), count++) {
  1575. UPB_ASSERT(upb_inttable_lookup(t, upb_inttable_iter_key(&i), NULL));
  1576. }
  1577. UPB_ASSERT(count == upb_inttable_count(t));
  1578. }
  1579. #endif
  1580. }
  1581. bool upb_inttable_sizedinit(upb_inttable *t, size_t asize, int hsize_lg2,
  1582. upb_alloc *a) {
  1583. size_t array_bytes;
  1584. if (!init(&t->t, hsize_lg2, a)) return false;
  1585. /* Always make the array part at least 1 long, so that we know key 0
  1586. * won't be in the hash part, which simplifies things. */
  1587. t->array_size = UPB_MAX(1, asize);
  1588. t->array_count = 0;
  1589. array_bytes = t->array_size * sizeof(upb_value);
  1590. t->array = upb_malloc(a, array_bytes);
  1591. if (!t->array) {
  1592. uninit(&t->t, a);
  1593. return false;
  1594. }
  1595. memset(mutable_array(t), 0xff, array_bytes);
  1596. check(t);
  1597. return true;
  1598. }
  1599. bool upb_inttable_init2(upb_inttable *t, upb_ctype_t ctype, upb_alloc *a) {
  1600. return upb_inttable_sizedinit(t, 0, 4, a);
  1601. }
  1602. void upb_inttable_uninit2(upb_inttable *t, upb_alloc *a) {
  1603. uninit(&t->t, a);
  1604. upb_free(a, mutable_array(t));
  1605. }
  1606. bool upb_inttable_insert2(upb_inttable *t, uintptr_t key, upb_value val,
  1607. upb_alloc *a) {
  1608. upb_tabval tabval;
  1609. tabval.val = val.val;
  1610. UPB_ASSERT(upb_arrhas(tabval)); /* This will reject (uint64_t)-1. Fix this. */
  1611. if (key < t->array_size) {
  1612. UPB_ASSERT(!upb_arrhas(t->array[key]));
  1613. t->array_count++;
  1614. mutable_array(t)[key].val = val.val;
  1615. } else {
  1616. if (isfull(&t->t)) {
  1617. /* Need to resize the hash part, but we re-use the array part. */
  1618. size_t i;
  1619. upb_table new_table;
  1620. if (!init(&new_table, t->t.size_lg2 + 1, a)) {
  1621. return false;
  1622. }
  1623. for (i = begin(&t->t); i < upb_table_size(&t->t); i = next(&t->t, i)) {
  1624. const upb_tabent *e = &t->t.entries[i];
  1625. uint32_t hash;
  1626. upb_value v;
  1627. _upb_value_setval(&v, e->val.val);
  1628. hash = upb_inthash(e->key);
  1629. insert(&new_table, intkey(e->key), e->key, v, hash, &inthash, &inteql);
  1630. }
  1631. UPB_ASSERT(t->t.count == new_table.count);
  1632. uninit(&t->t, a);
  1633. t->t = new_table;
  1634. }
  1635. insert(&t->t, intkey(key), key, val, upb_inthash(key), &inthash, &inteql);
  1636. }
  1637. check(t);
  1638. return true;
  1639. }
  1640. bool upb_inttable_lookup(const upb_inttable *t, uintptr_t key, upb_value *v) {
  1641. const upb_tabval *table_v = inttable_val_const(t, key);
  1642. if (!table_v) return false;
  1643. if (v) _upb_value_setval(v, table_v->val);
  1644. return true;
  1645. }
  1646. bool upb_inttable_replace(upb_inttable *t, uintptr_t key, upb_value val) {
  1647. upb_tabval *table_v = inttable_val(t, key);
  1648. if (!table_v) return false;
  1649. table_v->val = val.val;
  1650. return true;
  1651. }
  1652. bool upb_inttable_remove(upb_inttable *t, uintptr_t key, upb_value *val) {
  1653. bool success;
  1654. if (key < t->array_size) {
  1655. if (upb_arrhas(t->array[key])) {
  1656. upb_tabval empty = UPB_TABVALUE_EMPTY_INIT;
  1657. t->array_count--;
  1658. if (val) {
  1659. _upb_value_setval(val, t->array[key].val);
  1660. }
  1661. mutable_array(t)[key] = empty;
  1662. success = true;
  1663. } else {
  1664. success = false;
  1665. }
  1666. } else {
  1667. success = rm(&t->t, intkey(key), val, NULL, upb_inthash(key), &inteql);
  1668. }
  1669. check(t);
  1670. return success;
  1671. }
  1672. bool upb_inttable_push2(upb_inttable *t, upb_value val, upb_alloc *a) {
  1673. return upb_inttable_insert2(t, upb_inttable_count(t), val, a);
  1674. }
  1675. upb_value upb_inttable_pop(upb_inttable *t) {
  1676. upb_value val;
  1677. bool ok = upb_inttable_remove(t, upb_inttable_count(t) - 1, &val);
  1678. UPB_ASSERT(ok);
  1679. return val;
  1680. }
  1681. bool upb_inttable_insertptr2(upb_inttable *t, const void *key, upb_value val,
  1682. upb_alloc *a) {
  1683. return upb_inttable_insert2(t, (uintptr_t)key, val, a);
  1684. }
  1685. bool upb_inttable_lookupptr(const upb_inttable *t, const void *key,
  1686. upb_value *v) {
  1687. return upb_inttable_lookup(t, (uintptr_t)key, v);
  1688. }
  1689. bool upb_inttable_removeptr(upb_inttable *t, const void *key, upb_value *val) {
  1690. return upb_inttable_remove(t, (uintptr_t)key, val);
  1691. }
  1692. void upb_inttable_compact2(upb_inttable *t, upb_alloc *a) {
  1693. /* A power-of-two histogram of the table keys. */
  1694. size_t counts[UPB_MAXARRSIZE + 1] = {0};
  1695. /* The max key in each bucket. */
  1696. uintptr_t max[UPB_MAXARRSIZE + 1] = {0};
  1697. upb_inttable_iter i;
  1698. size_t arr_count;
  1699. int size_lg2;
  1700. upb_inttable new_t;
  1701. upb_inttable_begin(&i, t);
  1702. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  1703. uintptr_t key = upb_inttable_iter_key(&i);
  1704. int bucket = log2ceil(key);
  1705. max[bucket] = UPB_MAX(max[bucket], key);
  1706. counts[bucket]++;
  1707. }
  1708. /* Find the largest power of two that satisfies the MIN_DENSITY
  1709. * definition (while actually having some keys). */
  1710. arr_count = upb_inttable_count(t);
  1711. for (size_lg2 = ARRAY_SIZE(counts) - 1; size_lg2 > 0; size_lg2--) {
  1712. if (counts[size_lg2] == 0) {
  1713. /* We can halve again without losing any entries. */
  1714. continue;
  1715. } else if (arr_count >= (1 << size_lg2) * MIN_DENSITY) {
  1716. break;
  1717. }
  1718. arr_count -= counts[size_lg2];
  1719. }
  1720. UPB_ASSERT(arr_count <= upb_inttable_count(t));
  1721. {
  1722. /* Insert all elements into new, perfectly-sized table. */
  1723. size_t arr_size = max[size_lg2] + 1; /* +1 so arr[max] will fit. */
  1724. size_t hash_count = upb_inttable_count(t) - arr_count;
  1725. size_t hash_size = hash_count ? (hash_count / MAX_LOAD) + 1 : 0;
  1726. int hashsize_lg2 = log2ceil(hash_size);
  1727. upb_inttable_sizedinit(&new_t, arr_size, hashsize_lg2, a);
  1728. upb_inttable_begin(&i, t);
  1729. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  1730. uintptr_t k = upb_inttable_iter_key(&i);
  1731. upb_inttable_insert2(&new_t, k, upb_inttable_iter_value(&i), a);
  1732. }
  1733. UPB_ASSERT(new_t.array_size == arr_size);
  1734. UPB_ASSERT(new_t.t.size_lg2 == hashsize_lg2);
  1735. }
  1736. upb_inttable_uninit2(t, a);
  1737. *t = new_t;
  1738. }
  1739. /* Iteration. */
  1740. static const upb_tabent *int_tabent(const upb_inttable_iter *i) {
  1741. UPB_ASSERT(!i->array_part);
  1742. return &i->t->t.entries[i->index];
  1743. }
  1744. static upb_tabval int_arrent(const upb_inttable_iter *i) {
  1745. UPB_ASSERT(i->array_part);
  1746. return i->t->array[i->index];
  1747. }
  1748. void upb_inttable_begin(upb_inttable_iter *i, const upb_inttable *t) {
  1749. i->t = t;
  1750. i->index = -1;
  1751. i->array_part = true;
  1752. upb_inttable_next(i);
  1753. }
  1754. void upb_inttable_next(upb_inttable_iter *iter) {
  1755. const upb_inttable *t = iter->t;
  1756. if (iter->array_part) {
  1757. while (++iter->index < t->array_size) {
  1758. if (upb_arrhas(int_arrent(iter))) {
  1759. return;
  1760. }
  1761. }
  1762. iter->array_part = false;
  1763. iter->index = begin(&t->t);
  1764. } else {
  1765. iter->index = next(&t->t, iter->index);
  1766. }
  1767. }
  1768. bool upb_inttable_done(const upb_inttable_iter *i) {
  1769. if (!i->t) return true;
  1770. if (i->array_part) {
  1771. return i->index >= i->t->array_size ||
  1772. !upb_arrhas(int_arrent(i));
  1773. } else {
  1774. return i->index >= upb_table_size(&i->t->t) ||
  1775. upb_tabent_isempty(int_tabent(i));
  1776. }
  1777. }
  1778. uintptr_t upb_inttable_iter_key(const upb_inttable_iter *i) {
  1779. UPB_ASSERT(!upb_inttable_done(i));
  1780. return i->array_part ? i->index : int_tabent(i)->key;
  1781. }
  1782. upb_value upb_inttable_iter_value(const upb_inttable_iter *i) {
  1783. UPB_ASSERT(!upb_inttable_done(i));
  1784. return _upb_value_val(
  1785. i->array_part ? i->t->array[i->index].val : int_tabent(i)->val.val);
  1786. }
  1787. void upb_inttable_iter_setdone(upb_inttable_iter *i) {
  1788. i->t = NULL;
  1789. i->index = SIZE_MAX;
  1790. i->array_part = false;
  1791. }
  1792. bool upb_inttable_iter_isequal(const upb_inttable_iter *i1,
  1793. const upb_inttable_iter *i2) {
  1794. if (upb_inttable_done(i1) && upb_inttable_done(i2))
  1795. return true;
  1796. return i1->t == i2->t && i1->index == i2->index &&
  1797. i1->array_part == i2->array_part;
  1798. }
  1799. #if defined(UPB_UNALIGNED_READS_OK) || defined(__s390x__)
  1800. /* -----------------------------------------------------------------------------
  1801. * MurmurHash2, by Austin Appleby (released as public domain).
  1802. * Reformatted and C99-ified by Joshua Haberman.
  1803. * Note - This code makes a few assumptions about how your machine behaves -
  1804. * 1. We can read a 4-byte value from any address without crashing
  1805. * 2. sizeof(int) == 4 (in upb this limitation is removed by using uint32_t
  1806. * And it has a few limitations -
  1807. * 1. It will not work incrementally.
  1808. * 2. It will not produce the same results on little-endian and big-endian
  1809. * machines. */
  1810. uint32_t upb_murmur_hash2(const void *key, size_t len, uint32_t seed) {
  1811. /* 'm' and 'r' are mixing constants generated offline.
  1812. * They're not really 'magic', they just happen to work well. */
  1813. const uint32_t m = 0x5bd1e995;
  1814. const int32_t r = 24;
  1815. /* Initialize the hash to a 'random' value */
  1816. uint32_t h = seed ^ len;
  1817. /* Mix 4 bytes at a time into the hash */
  1818. const uint8_t * data = (const uint8_t *)key;
  1819. while(len >= 4) {
  1820. uint32_t k;
  1821. memcpy(&k, data, sizeof(k));
  1822. k *= m;
  1823. k ^= k >> r;
  1824. k *= m;
  1825. h *= m;
  1826. h ^= k;
  1827. data += 4;
  1828. len -= 4;
  1829. }
  1830. /* Handle the last few bytes of the input array */
  1831. switch(len) {
  1832. case 3: h ^= data[2] << 16;
  1833. case 2: h ^= data[1] << 8;
  1834. case 1: h ^= data[0]; h *= m;
  1835. };
  1836. /* Do a few final mixes of the hash to ensure the last few
  1837. * bytes are well-incorporated. */
  1838. h ^= h >> 13;
  1839. h *= m;
  1840. h ^= h >> 15;
  1841. return h;
  1842. }
  1843. #else /* !UPB_UNALIGNED_READS_OK */
  1844. /* -----------------------------------------------------------------------------
  1845. * MurmurHashAligned2, by Austin Appleby
  1846. * Same algorithm as MurmurHash2, but only does aligned reads - should be safer
  1847. * on certain platforms.
  1848. * Performance will be lower than MurmurHash2 */
  1849. #define MIX(h,k,m) { k *= m; k ^= k >> r; k *= m; h *= m; h ^= k; }
  1850. uint32_t upb_murmur_hash2(const void * key, size_t len, uint32_t seed) {
  1851. const uint32_t m = 0x5bd1e995;
  1852. const int32_t r = 24;
  1853. const uint8_t * data = (const uint8_t *)key;
  1854. uint32_t h = (uint32_t)(seed ^ len);
  1855. uint8_t align = (uintptr_t)data & 3;
  1856. if(align && (len >= 4)) {
  1857. /* Pre-load the temp registers */
  1858. uint32_t t = 0, d = 0;
  1859. int32_t sl;
  1860. int32_t sr;
  1861. switch(align) {
  1862. case 1: t |= data[2] << 16;
  1863. case 2: t |= data[1] << 8;
  1864. case 3: t |= data[0];
  1865. }
  1866. t <<= (8 * align);
  1867. data += 4-align;
  1868. len -= 4-align;
  1869. sl = 8 * (4-align);
  1870. sr = 8 * align;
  1871. /* Mix */
  1872. while(len >= 4) {
  1873. uint32_t k;
  1874. d = *(uint32_t *)data;
  1875. t = (t >> sr) | (d << sl);
  1876. k = t;
  1877. MIX(h,k,m);
  1878. t = d;
  1879. data += 4;
  1880. len -= 4;
  1881. }
  1882. /* Handle leftover data in temp registers */
  1883. d = 0;
  1884. if(len >= align) {
  1885. uint32_t k;
  1886. switch(align) {
  1887. case 3: d |= data[2] << 16;
  1888. case 2: d |= data[1] << 8;
  1889. case 1: d |= data[0];
  1890. }
  1891. k = (t >> sr) | (d << sl);
  1892. MIX(h,k,m);
  1893. data += align;
  1894. len -= align;
  1895. /* ----------
  1896. * Handle tail bytes */
  1897. switch(len) {
  1898. case 3: h ^= data[2] << 16;
  1899. case 2: h ^= data[1] << 8;
  1900. case 1: h ^= data[0]; h *= m;
  1901. };
  1902. } else {
  1903. switch(len) {
  1904. case 3: d |= data[2] << 16;
  1905. case 2: d |= data[1] << 8;
  1906. case 1: d |= data[0];
  1907. case 0: h ^= (t >> sr) | (d << sl); h *= m;
  1908. }
  1909. }
  1910. h ^= h >> 13;
  1911. h *= m;
  1912. h ^= h >> 15;
  1913. return h;
  1914. } else {
  1915. while(len >= 4) {
  1916. uint32_t k = *(uint32_t *)data;
  1917. MIX(h,k,m);
  1918. data += 4;
  1919. len -= 4;
  1920. }
  1921. /* ----------
  1922. * Handle tail bytes */
  1923. switch(len) {
  1924. case 3: h ^= data[2] << 16;
  1925. case 2: h ^= data[1] << 8;
  1926. case 1: h ^= data[0]; h *= m;
  1927. };
  1928. h ^= h >> 13;
  1929. h *= m;
  1930. h ^= h >> 15;
  1931. return h;
  1932. }
  1933. }
  1934. #undef MIX
  1935. #endif /* UPB_UNALIGNED_READS_OK */
  1936. #include <errno.h>
  1937. #include <stdarg.h>
  1938. #include <stddef.h>
  1939. #include <stdint.h>
  1940. #include <stdio.h>
  1941. #include <stdlib.h>
  1942. #include <string.h>
  1943. /* upb_status *****************************************************************/
  1944. void upb_status_clear(upb_status *status) {
  1945. if (!status) return;
  1946. status->ok = true;
  1947. status->msg[0] = '\0';
  1948. }
  1949. bool upb_ok(const upb_status *status) { return status->ok; }
  1950. const char *upb_status_errmsg(const upb_status *status) { return status->msg; }
  1951. void upb_status_seterrmsg(upb_status *status, const char *msg) {
  1952. if (!status) return;
  1953. status->ok = false;
  1954. strncpy(status->msg, msg, UPB_STATUS_MAX_MESSAGE - 1);
  1955. status->msg[UPB_STATUS_MAX_MESSAGE - 1] = '\0';
  1956. }
  1957. void upb_status_seterrf(upb_status *status, const char *fmt, ...) {
  1958. va_list args;
  1959. va_start(args, fmt);
  1960. upb_status_vseterrf(status, fmt, args);
  1961. va_end(args);
  1962. }
  1963. void upb_status_vseterrf(upb_status *status, const char *fmt, va_list args) {
  1964. if (!status) return;
  1965. status->ok = false;
  1966. _upb_vsnprintf(status->msg, sizeof(status->msg), fmt, args);
  1967. status->msg[UPB_STATUS_MAX_MESSAGE - 1] = '\0';
  1968. }
  1969. /* upb_alloc ******************************************************************/
  1970. static void *upb_global_allocfunc(upb_alloc *alloc, void *ptr, size_t oldsize,
  1971. size_t size) {
  1972. UPB_UNUSED(alloc);
  1973. UPB_UNUSED(oldsize);
  1974. if (size == 0) {
  1975. free(ptr);
  1976. return NULL;
  1977. } else {
  1978. return realloc(ptr, size);
  1979. }
  1980. }
  1981. upb_alloc upb_alloc_global = {&upb_global_allocfunc};
  1982. /* upb_arena ******************************************************************/
  1983. /* Be conservative and choose 16 in case anyone is using SSE. */
  1984. typedef struct mem_block {
  1985. struct mem_block *next;
  1986. uint32_t size;
  1987. uint32_t cleanups;
  1988. /* Data follows. */
  1989. } mem_block;
  1990. typedef struct cleanup_ent {
  1991. upb_cleanup_func *cleanup;
  1992. void *ud;
  1993. } cleanup_ent;
  1994. struct upb_arena {
  1995. _upb_arena_head head;
  1996. uint32_t *cleanups;
  1997. /* Allocator to allocate arena blocks. We are responsible for freeing these
  1998. * when we are destroyed. */
  1999. upb_alloc *block_alloc;
  2000. uint32_t last_size;
  2001. /* When multiple arenas are fused together, each arena points to a parent
  2002. * arena (root points to itself). The root tracks how many live arenas
  2003. * reference it. */
  2004. uint32_t refcount; /* Only used when a->parent == a */
  2005. struct upb_arena *parent;
  2006. /* Linked list of blocks to free/cleanup. */
  2007. mem_block *freelist, *freelist_tail;
  2008. };
  2009. static const size_t memblock_reserve = UPB_ALIGN_UP(sizeof(mem_block), 16);
  2010. static void upb_arena_addblock(upb_arena *a, void *ptr, size_t size) {
  2011. mem_block *block = ptr;
  2012. block->next = a->freelist;
  2013. block->size = size;
  2014. block->cleanups = 0;
  2015. a->freelist = block;
  2016. a->last_size = size;
  2017. if (!a->freelist_tail) a->freelist_tail = block;
  2018. a->head.ptr = UPB_PTR_AT(block, memblock_reserve, char);
  2019. a->head.end = UPB_PTR_AT(block, size, char);
  2020. a->cleanups = &block->cleanups;
  2021. /* TODO(haberman): ASAN poison. */
  2022. }
  2023. static bool upb_arena_allocblock(upb_arena *a, size_t size) {
  2024. size_t block_size = UPB_MAX(size, a->last_size * 2) + memblock_reserve;
  2025. mem_block *block = upb_malloc(a->block_alloc, block_size);
  2026. if (!block) return false;
  2027. upb_arena_addblock(a, block, block_size);
  2028. return true;
  2029. }
  2030. static bool arena_has(upb_arena *a, size_t size) {
  2031. _upb_arena_head *h = (_upb_arena_head*)a;
  2032. return (size_t)(h->end - h->ptr) >= size;
  2033. }
  2034. void *_upb_arena_slowmalloc(upb_arena *a, size_t size) {
  2035. if (!upb_arena_allocblock(a, size)) return NULL; /* Out of memory. */
  2036. UPB_ASSERT(arena_has(a, size));
  2037. return upb_arena_malloc(a, size);
  2038. }
  2039. static void *upb_arena_doalloc(upb_alloc *alloc, void *ptr, size_t oldsize,
  2040. size_t size) {
  2041. upb_arena *a = (upb_arena*)alloc; /* upb_alloc is initial member. */
  2042. return upb_arena_realloc(a, ptr, oldsize, size);
  2043. }
  2044. static upb_arena *arena_findroot(upb_arena *a) {
  2045. /* Path splitting keeps time complexity down, see:
  2046. * https://en.wikipedia.org/wiki/Disjoint-set_data_structure */
  2047. while (a->parent != a) {
  2048. upb_arena *next = a->parent;
  2049. a->parent = next->parent;
  2050. a = next;
  2051. }
  2052. return a;
  2053. }
  2054. /* Public Arena API ***********************************************************/
  2055. upb_arena *arena_initslow(void *mem, size_t n, upb_alloc *alloc) {
  2056. const size_t first_block_overhead = sizeof(upb_arena) + memblock_reserve;
  2057. upb_arena *a;
  2058. /* We need to malloc the initial block. */
  2059. n = first_block_overhead + 256;
  2060. if (!alloc || !(mem = upb_malloc(alloc, n))) {
  2061. return NULL;
  2062. }
  2063. a = UPB_PTR_AT(mem, n - sizeof(*a), upb_arena);
  2064. n -= sizeof(*a);
  2065. a->head.alloc.func = &upb_arena_doalloc;
  2066. a->block_alloc = alloc;
  2067. a->parent = a;
  2068. a->refcount = 1;
  2069. a->freelist = NULL;
  2070. a->freelist_tail = NULL;
  2071. upb_arena_addblock(a, mem, n);
  2072. return a;
  2073. }
  2074. upb_arena *upb_arena_init(void *mem, size_t n, upb_alloc *alloc) {
  2075. upb_arena *a;
  2076. /* Round block size down to alignof(*a) since we will allocate the arena
  2077. * itself at the end. */
  2078. n = UPB_ALIGN_DOWN(n, UPB_ALIGN_OF(upb_arena));
  2079. if (UPB_UNLIKELY(n < sizeof(upb_arena))) {
  2080. return arena_initslow(mem, n, alloc);
  2081. }
  2082. a = UPB_PTR_AT(mem, n - sizeof(*a), upb_arena);
  2083. n -= sizeof(*a);
  2084. a->head.alloc.func = &upb_arena_doalloc;
  2085. a->block_alloc = alloc;
  2086. a->parent = a;
  2087. a->refcount = 1;
  2088. a->last_size = 128;
  2089. a->head.ptr = mem;
  2090. a->head.end = UPB_PTR_AT(mem, n, char);
  2091. a->freelist = NULL;
  2092. a->cleanups = NULL;
  2093. return a;
  2094. }
  2095. static void arena_dofree(upb_arena *a) {
  2096. mem_block *block = a->freelist;
  2097. UPB_ASSERT(a->parent == a);
  2098. UPB_ASSERT(a->refcount == 0);
  2099. while (block) {
  2100. /* Load first since we are deleting block. */
  2101. mem_block *next = block->next;
  2102. if (block->cleanups > 0) {
  2103. cleanup_ent *end = UPB_PTR_AT(block, block->size, void);
  2104. cleanup_ent *ptr = end - block->cleanups;
  2105. for (; ptr < end; ptr++) {
  2106. ptr->cleanup(ptr->ud);
  2107. }
  2108. }
  2109. upb_free(a->block_alloc, block);
  2110. block = next;
  2111. }
  2112. }
  2113. void upb_arena_free(upb_arena *a) {
  2114. a = arena_findroot(a);
  2115. if (--a->refcount == 0) arena_dofree(a);
  2116. }
  2117. bool upb_arena_addcleanup(upb_arena *a, void *ud, upb_cleanup_func *func) {
  2118. cleanup_ent *ent;
  2119. if (!a->cleanups || !arena_has(a, sizeof(cleanup_ent))) {
  2120. if (!upb_arena_allocblock(a, 128)) return false; /* Out of memory. */
  2121. UPB_ASSERT(arena_has(a, sizeof(cleanup_ent)));
  2122. }
  2123. a->head.end -= sizeof(cleanup_ent);
  2124. ent = (cleanup_ent*)a->head.end;
  2125. (*a->cleanups)++;
  2126. ent->cleanup = func;
  2127. ent->ud = ud;
  2128. return true;
  2129. }
  2130. void upb_arena_fuse(upb_arena *a1, upb_arena *a2) {
  2131. upb_arena *r1 = arena_findroot(a1);
  2132. upb_arena *r2 = arena_findroot(a2);
  2133. if (r1 == r2) return; /* Already fused. */
  2134. /* We want to join the smaller tree to the larger tree.
  2135. * So swap first if they are backwards. */
  2136. if (r1->refcount < r2->refcount) {
  2137. upb_arena *tmp = r1;
  2138. r1 = r2;
  2139. r2 = tmp;
  2140. }
  2141. /* r1 takes over r2's freelist and refcount. */
  2142. r1->refcount += r2->refcount;
  2143. if (r2->freelist_tail) {
  2144. UPB_ASSERT(r2->freelist_tail->next == NULL);
  2145. r2->freelist_tail->next = r1->freelist;
  2146. r1->freelist = r2->freelist;
  2147. }
  2148. r2->parent = r1;
  2149. }
  2150. /* This file was generated by upbc (the upb compiler) from the input
  2151. * file:
  2152. *
  2153. * google/protobuf/descriptor.proto
  2154. *
  2155. * Do not edit -- your changes will be discarded when the file is
  2156. * regenerated. */
  2157. #include <stddef.h>
  2158. static const upb_msglayout *const google_protobuf_FileDescriptorSet_submsgs[1] = {
  2159. &google_protobuf_FileDescriptorProto_msginit,
  2160. };
  2161. static const upb_msglayout_field google_protobuf_FileDescriptorSet__fields[1] = {
  2162. {1, UPB_SIZE(0, 0), 0, 0, 11, 3},
  2163. };
  2164. const upb_msglayout google_protobuf_FileDescriptorSet_msginit = {
  2165. &google_protobuf_FileDescriptorSet_submsgs[0],
  2166. &google_protobuf_FileDescriptorSet__fields[0],
  2167. UPB_SIZE(4, 8), 1, false,
  2168. };
  2169. static const upb_msglayout *const google_protobuf_FileDescriptorProto_submsgs[6] = {
  2170. &google_protobuf_DescriptorProto_msginit,
  2171. &google_protobuf_EnumDescriptorProto_msginit,
  2172. &google_protobuf_FieldDescriptorProto_msginit,
  2173. &google_protobuf_FileOptions_msginit,
  2174. &google_protobuf_ServiceDescriptorProto_msginit,
  2175. &google_protobuf_SourceCodeInfo_msginit,
  2176. };
  2177. static const upb_msglayout_field google_protobuf_FileDescriptorProto__fields[12] = {
  2178. {1, UPB_SIZE(4, 8), 1, 0, 9, 1},
  2179. {2, UPB_SIZE(12, 24), 2, 0, 9, 1},
  2180. {3, UPB_SIZE(36, 72), 0, 0, 9, 3},
  2181. {4, UPB_SIZE(40, 80), 0, 0, 11, 3},
  2182. {5, UPB_SIZE(44, 88), 0, 1, 11, 3},
  2183. {6, UPB_SIZE(48, 96), 0, 4, 11, 3},
  2184. {7, UPB_SIZE(52, 104), 0, 2, 11, 3},
  2185. {8, UPB_SIZE(28, 56), 4, 3, 11, 1},
  2186. {9, UPB_SIZE(32, 64), 5, 5, 11, 1},
  2187. {10, UPB_SIZE(56, 112), 0, 0, 5, 3},
  2188. {11, UPB_SIZE(60, 120), 0, 0, 5, 3},
  2189. {12, UPB_SIZE(20, 40), 3, 0, 9, 1},
  2190. };
  2191. const upb_msglayout google_protobuf_FileDescriptorProto_msginit = {
  2192. &google_protobuf_FileDescriptorProto_submsgs[0],
  2193. &google_protobuf_FileDescriptorProto__fields[0],
  2194. UPB_SIZE(64, 128), 12, false,
  2195. };
  2196. static const upb_msglayout *const google_protobuf_DescriptorProto_submsgs[8] = {
  2197. &google_protobuf_DescriptorProto_msginit,
  2198. &google_protobuf_DescriptorProto_ExtensionRange_msginit,
  2199. &google_protobuf_DescriptorProto_ReservedRange_msginit,
  2200. &google_protobuf_EnumDescriptorProto_msginit,
  2201. &google_protobuf_FieldDescriptorProto_msginit,
  2202. &google_protobuf_MessageOptions_msginit,
  2203. &google_protobuf_OneofDescriptorProto_msginit,
  2204. };
  2205. static const upb_msglayout_field google_protobuf_DescriptorProto__fields[10] = {
  2206. {1, UPB_SIZE(4, 8), 1, 0, 9, 1},
  2207. {2, UPB_SIZE(16, 32), 0, 4, 11, 3},
  2208. {3, UPB_SIZE(20, 40), 0, 0, 11, 3},
  2209. {4, UPB_SIZE(24, 48), 0, 3, 11, 3},
  2210. {5, UPB_SIZE(28, 56), 0, 1, 11, 3},
  2211. {6, UPB_SIZE(32, 64), 0, 4, 11, 3},
  2212. {7, UPB_SIZE(12, 24), 2, 5, 11, 1},
  2213. {8, UPB_SIZE(36, 72), 0, 6, 11, 3},
  2214. {9, UPB_SIZE(40, 80), 0, 2, 11, 3},
  2215. {10, UPB_SIZE(44, 88), 0, 0, 9, 3},
  2216. };
  2217. const upb_msglayout google_protobuf_DescriptorProto_msginit = {
  2218. &google_protobuf_DescriptorProto_submsgs[0],
  2219. &google_protobuf_DescriptorProto__fields[0],
  2220. UPB_SIZE(48, 96), 10, false,
  2221. };
  2222. static const upb_msglayout *const google_protobuf_DescriptorProto_ExtensionRange_submsgs[1] = {
  2223. &google_protobuf_ExtensionRangeOptions_msginit,
  2224. };
  2225. static const upb_msglayout_field google_protobuf_DescriptorProto_ExtensionRange__fields[3] = {
  2226. {1, UPB_SIZE(4, 4), 1, 0, 5, 1},
  2227. {2, UPB_SIZE(8, 8), 2, 0, 5, 1},
  2228. {3, UPB_SIZE(12, 16), 3, 0, 11, 1},
  2229. };
  2230. const upb_msglayout google_protobuf_DescriptorProto_ExtensionRange_msginit = {
  2231. &google_protobuf_DescriptorProto_ExtensionRange_submsgs[0],
  2232. &google_protobuf_DescriptorProto_ExtensionRange__fields[0],
  2233. UPB_SIZE(16, 24), 3, false,
  2234. };
  2235. static const upb_msglayout_field google_protobuf_DescriptorProto_ReservedRange__fields[2] = {
  2236. {1, UPB_SIZE(4, 4), 1, 0, 5, 1},
  2237. {2, UPB_SIZE(8, 8), 2, 0, 5, 1},
  2238. };
  2239. const upb_msglayout google_protobuf_DescriptorProto_ReservedRange_msginit = {
  2240. NULL,
  2241. &google_protobuf_DescriptorProto_ReservedRange__fields[0],
  2242. UPB_SIZE(12, 12), 2, false,
  2243. };
  2244. static const upb_msglayout *const google_protobuf_ExtensionRangeOptions_submsgs[1] = {
  2245. &google_protobuf_UninterpretedOption_msginit,
  2246. };
  2247. static const upb_msglayout_field google_protobuf_ExtensionRangeOptions__fields[1] = {
  2248. {999, UPB_SIZE(0, 0), 0, 0, 11, 3},
  2249. };
  2250. const upb_msglayout google_protobuf_ExtensionRangeOptions_msginit = {
  2251. &google_protobuf_ExtensionRangeOptions_submsgs[0],
  2252. &google_protobuf_ExtensionRangeOptions__fields[0],
  2253. UPB_SIZE(4, 8), 1, false,
  2254. };
  2255. static const upb_msglayout *const google_protobuf_FieldDescriptorProto_submsgs[1] = {
  2256. &google_protobuf_FieldOptions_msginit,
  2257. };
  2258. static const upb_msglayout_field google_protobuf_FieldDescriptorProto__fields[11] = {
  2259. {1, UPB_SIZE(36, 40), 6, 0, 9, 1},
  2260. {2, UPB_SIZE(44, 56), 7, 0, 9, 1},
  2261. {3, UPB_SIZE(24, 24), 3, 0, 5, 1},
  2262. {4, UPB_SIZE(8, 8), 1, 0, 14, 1},
  2263. {5, UPB_SIZE(16, 16), 2, 0, 14, 1},
  2264. {6, UPB_SIZE(52, 72), 8, 0, 9, 1},
  2265. {7, UPB_SIZE(60, 88), 9, 0, 9, 1},
  2266. {8, UPB_SIZE(76, 120), 11, 0, 11, 1},
  2267. {9, UPB_SIZE(28, 28), 4, 0, 5, 1},
  2268. {10, UPB_SIZE(68, 104), 10, 0, 9, 1},
  2269. {17, UPB_SIZE(32, 32), 5, 0, 8, 1},
  2270. };
  2271. const upb_msglayout google_protobuf_FieldDescriptorProto_msginit = {
  2272. &google_protobuf_FieldDescriptorProto_submsgs[0],
  2273. &google_protobuf_FieldDescriptorProto__fields[0],
  2274. UPB_SIZE(80, 128), 11, false,
  2275. };
  2276. static const upb_msglayout *const google_protobuf_OneofDescriptorProto_submsgs[1] = {
  2277. &google_protobuf_OneofOptions_msginit,
  2278. };
  2279. static const upb_msglayout_field google_protobuf_OneofDescriptorProto__fields[2] = {
  2280. {1, UPB_SIZE(4, 8), 1, 0, 9, 1},
  2281. {2, UPB_SIZE(12, 24), 2, 0, 11, 1},
  2282. };
  2283. const upb_msglayout google_protobuf_OneofDescriptorProto_msginit = {
  2284. &google_protobuf_OneofDescriptorProto_submsgs[0],
  2285. &google_protobuf_OneofDescriptorProto__fields[0],
  2286. UPB_SIZE(16, 32), 2, false,
  2287. };
  2288. static const upb_msglayout *const google_protobuf_EnumDescriptorProto_submsgs[3] = {
  2289. &google_protobuf_EnumDescriptorProto_EnumReservedRange_msginit,
  2290. &google_protobuf_EnumOptions_msginit,
  2291. &google_protobuf_EnumValueDescriptorProto_msginit,
  2292. };
  2293. static const upb_msglayout_field google_protobuf_EnumDescriptorProto__fields[5] = {
  2294. {1, UPB_SIZE(4, 8), 1, 0, 9, 1},
  2295. {2, UPB_SIZE(16, 32), 0, 2, 11, 3},
  2296. {3, UPB_SIZE(12, 24), 2, 1, 11, 1},
  2297. {4, UPB_SIZE(20, 40), 0, 0, 11, 3},
  2298. {5, UPB_SIZE(24, 48), 0, 0, 9, 3},
  2299. };
  2300. const upb_msglayout google_protobuf_EnumDescriptorProto_msginit = {
  2301. &google_protobuf_EnumDescriptorProto_submsgs[0],
  2302. &google_protobuf_EnumDescriptorProto__fields[0],
  2303. UPB_SIZE(32, 64), 5, false,
  2304. };
  2305. static const upb_msglayout_field google_protobuf_EnumDescriptorProto_EnumReservedRange__fields[2] = {
  2306. {1, UPB_SIZE(4, 4), 1, 0, 5, 1},
  2307. {2, UPB_SIZE(8, 8), 2, 0, 5, 1},
  2308. };
  2309. const upb_msglayout google_protobuf_EnumDescriptorProto_EnumReservedRange_msginit = {
  2310. NULL,
  2311. &google_protobuf_EnumDescriptorProto_EnumReservedRange__fields[0],
  2312. UPB_SIZE(12, 12), 2, false,
  2313. };
  2314. static const upb_msglayout *const google_protobuf_EnumValueDescriptorProto_submsgs[1] = {
  2315. &google_protobuf_EnumValueOptions_msginit,
  2316. };
  2317. static const upb_msglayout_field google_protobuf_EnumValueDescriptorProto__fields[3] = {
  2318. {1, UPB_SIZE(8, 8), 2, 0, 9, 1},
  2319. {2, UPB_SIZE(4, 4), 1, 0, 5, 1},
  2320. {3, UPB_SIZE(16, 24), 3, 0, 11, 1},
  2321. };
  2322. const upb_msglayout google_protobuf_EnumValueDescriptorProto_msginit = {
  2323. &google_protobuf_EnumValueDescriptorProto_submsgs[0],
  2324. &google_protobuf_EnumValueDescriptorProto__fields[0],
  2325. UPB_SIZE(24, 32), 3, false,
  2326. };
  2327. static const upb_msglayout *const google_protobuf_ServiceDescriptorProto_submsgs[2] = {
  2328. &google_protobuf_MethodDescriptorProto_msginit,
  2329. &google_protobuf_ServiceOptions_msginit,
  2330. };
  2331. static const upb_msglayout_field google_protobuf_ServiceDescriptorProto__fields[3] = {
  2332. {1, UPB_SIZE(4, 8), 1, 0, 9, 1},
  2333. {2, UPB_SIZE(16, 32), 0, 0, 11, 3},
  2334. {3, UPB_SIZE(12, 24), 2, 1, 11, 1},
  2335. };
  2336. const upb_msglayout google_protobuf_ServiceDescriptorProto_msginit = {
  2337. &google_protobuf_ServiceDescriptorProto_submsgs[0],
  2338. &google_protobuf_ServiceDescriptorProto__fields[0],
  2339. UPB_SIZE(24, 48), 3, false,
  2340. };
  2341. static const upb_msglayout *const google_protobuf_MethodDescriptorProto_submsgs[1] = {
  2342. &google_protobuf_MethodOptions_msginit,
  2343. };
  2344. static const upb_msglayout_field google_protobuf_MethodDescriptorProto__fields[6] = {
  2345. {1, UPB_SIZE(4, 8), 3, 0, 9, 1},
  2346. {2, UPB_SIZE(12, 24), 4, 0, 9, 1},
  2347. {3, UPB_SIZE(20, 40), 5, 0, 9, 1},
  2348. {4, UPB_SIZE(28, 56), 6, 0, 11, 1},
  2349. {5, UPB_SIZE(1, 1), 1, 0, 8, 1},
  2350. {6, UPB_SIZE(2, 2), 2, 0, 8, 1},
  2351. };
  2352. const upb_msglayout google_protobuf_MethodDescriptorProto_msginit = {
  2353. &google_protobuf_MethodDescriptorProto_submsgs[0],
  2354. &google_protobuf_MethodDescriptorProto__fields[0],
  2355. UPB_SIZE(32, 64), 6, false,
  2356. };
  2357. static const upb_msglayout *const google_protobuf_FileOptions_submsgs[1] = {
  2358. &google_protobuf_UninterpretedOption_msginit,
  2359. };
  2360. static const upb_msglayout_field google_protobuf_FileOptions__fields[21] = {
  2361. {1, UPB_SIZE(28, 32), 11, 0, 9, 1},
  2362. {8, UPB_SIZE(36, 48), 12, 0, 9, 1},
  2363. {9, UPB_SIZE(8, 8), 1, 0, 14, 1},
  2364. {10, UPB_SIZE(16, 16), 2, 0, 8, 1},
  2365. {11, UPB_SIZE(44, 64), 13, 0, 9, 1},
  2366. {16, UPB_SIZE(17, 17), 3, 0, 8, 1},
  2367. {17, UPB_SIZE(18, 18), 4, 0, 8, 1},
  2368. {18, UPB_SIZE(19, 19), 5, 0, 8, 1},
  2369. {20, UPB_SIZE(20, 20), 6, 0, 8, 1},
  2370. {23, UPB_SIZE(21, 21), 7, 0, 8, 1},
  2371. {27, UPB_SIZE(22, 22), 8, 0, 8, 1},
  2372. {31, UPB_SIZE(23, 23), 9, 0, 8, 1},
  2373. {36, UPB_SIZE(52, 80), 14, 0, 9, 1},
  2374. {37, UPB_SIZE(60, 96), 15, 0, 9, 1},
  2375. {39, UPB_SIZE(68, 112), 16, 0, 9, 1},
  2376. {40, UPB_SIZE(76, 128), 17, 0, 9, 1},
  2377. {41, UPB_SIZE(84, 144), 18, 0, 9, 1},
  2378. {42, UPB_SIZE(24, 24), 10, 0, 8, 1},
  2379. {44, UPB_SIZE(92, 160), 19, 0, 9, 1},
  2380. {45, UPB_SIZE(100, 176), 20, 0, 9, 1},
  2381. {999, UPB_SIZE(108, 192), 0, 0, 11, 3},
  2382. };
  2383. const upb_msglayout google_protobuf_FileOptions_msginit = {
  2384. &google_protobuf_FileOptions_submsgs[0],
  2385. &google_protobuf_FileOptions__fields[0],
  2386. UPB_SIZE(112, 208), 21, false,
  2387. };
  2388. static const upb_msglayout *const google_protobuf_MessageOptions_submsgs[1] = {
  2389. &google_protobuf_UninterpretedOption_msginit,
  2390. };
  2391. static const upb_msglayout_field google_protobuf_MessageOptions__fields[5] = {
  2392. {1, UPB_SIZE(1, 1), 1, 0, 8, 1},
  2393. {2, UPB_SIZE(2, 2), 2, 0, 8, 1},
  2394. {3, UPB_SIZE(3, 3), 3, 0, 8, 1},
  2395. {7, UPB_SIZE(4, 4), 4, 0, 8, 1},
  2396. {999, UPB_SIZE(8, 8), 0, 0, 11, 3},
  2397. };
  2398. const upb_msglayout google_protobuf_MessageOptions_msginit = {
  2399. &google_protobuf_MessageOptions_submsgs[0],
  2400. &google_protobuf_MessageOptions__fields[0],
  2401. UPB_SIZE(12, 16), 5, false,
  2402. };
  2403. static const upb_msglayout *const google_protobuf_FieldOptions_submsgs[1] = {
  2404. &google_protobuf_UninterpretedOption_msginit,
  2405. };
  2406. static const upb_msglayout_field google_protobuf_FieldOptions__fields[7] = {
  2407. {1, UPB_SIZE(8, 8), 1, 0, 14, 1},
  2408. {2, UPB_SIZE(24, 24), 3, 0, 8, 1},
  2409. {3, UPB_SIZE(25, 25), 4, 0, 8, 1},
  2410. {5, UPB_SIZE(26, 26), 5, 0, 8, 1},
  2411. {6, UPB_SIZE(16, 16), 2, 0, 14, 1},
  2412. {10, UPB_SIZE(27, 27), 6, 0, 8, 1},
  2413. {999, UPB_SIZE(28, 32), 0, 0, 11, 3},
  2414. };
  2415. const upb_msglayout google_protobuf_FieldOptions_msginit = {
  2416. &google_protobuf_FieldOptions_submsgs[0],
  2417. &google_protobuf_FieldOptions__fields[0],
  2418. UPB_SIZE(32, 40), 7, false,
  2419. };
  2420. static const upb_msglayout *const google_protobuf_OneofOptions_submsgs[1] = {
  2421. &google_protobuf_UninterpretedOption_msginit,
  2422. };
  2423. static const upb_msglayout_field google_protobuf_OneofOptions__fields[1] = {
  2424. {999, UPB_SIZE(0, 0), 0, 0, 11, 3},
  2425. };
  2426. const upb_msglayout google_protobuf_OneofOptions_msginit = {
  2427. &google_protobuf_OneofOptions_submsgs[0],
  2428. &google_protobuf_OneofOptions__fields[0],
  2429. UPB_SIZE(4, 8), 1, false,
  2430. };
  2431. static const upb_msglayout *const google_protobuf_EnumOptions_submsgs[1] = {
  2432. &google_protobuf_UninterpretedOption_msginit,
  2433. };
  2434. static const upb_msglayout_field google_protobuf_EnumOptions__fields[3] = {
  2435. {2, UPB_SIZE(1, 1), 1, 0, 8, 1},
  2436. {3, UPB_SIZE(2, 2), 2, 0, 8, 1},
  2437. {999, UPB_SIZE(4, 8), 0, 0, 11, 3},
  2438. };
  2439. const upb_msglayout google_protobuf_EnumOptions_msginit = {
  2440. &google_protobuf_EnumOptions_submsgs[0],
  2441. &google_protobuf_EnumOptions__fields[0],
  2442. UPB_SIZE(8, 16), 3, false,
  2443. };
  2444. static const upb_msglayout *const google_protobuf_EnumValueOptions_submsgs[1] = {
  2445. &google_protobuf_UninterpretedOption_msginit,
  2446. };
  2447. static const upb_msglayout_field google_protobuf_EnumValueOptions__fields[2] = {
  2448. {1, UPB_SIZE(1, 1), 1, 0, 8, 1},
  2449. {999, UPB_SIZE(4, 8), 0, 0, 11, 3},
  2450. };
  2451. const upb_msglayout google_protobuf_EnumValueOptions_msginit = {
  2452. &google_protobuf_EnumValueOptions_submsgs[0],
  2453. &google_protobuf_EnumValueOptions__fields[0],
  2454. UPB_SIZE(8, 16), 2, false,
  2455. };
  2456. static const upb_msglayout *const google_protobuf_ServiceOptions_submsgs[1] = {
  2457. &google_protobuf_UninterpretedOption_msginit,
  2458. };
  2459. static const upb_msglayout_field google_protobuf_ServiceOptions__fields[2] = {
  2460. {33, UPB_SIZE(1, 1), 1, 0, 8, 1},
  2461. {999, UPB_SIZE(4, 8), 0, 0, 11, 3},
  2462. };
  2463. const upb_msglayout google_protobuf_ServiceOptions_msginit = {
  2464. &google_protobuf_ServiceOptions_submsgs[0],
  2465. &google_protobuf_ServiceOptions__fields[0],
  2466. UPB_SIZE(8, 16), 2, false,
  2467. };
  2468. static const upb_msglayout *const google_protobuf_MethodOptions_submsgs[1] = {
  2469. &google_protobuf_UninterpretedOption_msginit,
  2470. };
  2471. static const upb_msglayout_field google_protobuf_MethodOptions__fields[3] = {
  2472. {33, UPB_SIZE(16, 16), 2, 0, 8, 1},
  2473. {34, UPB_SIZE(8, 8), 1, 0, 14, 1},
  2474. {999, UPB_SIZE(20, 24), 0, 0, 11, 3},
  2475. };
  2476. const upb_msglayout google_protobuf_MethodOptions_msginit = {
  2477. &google_protobuf_MethodOptions_submsgs[0],
  2478. &google_protobuf_MethodOptions__fields[0],
  2479. UPB_SIZE(24, 32), 3, false,
  2480. };
  2481. static const upb_msglayout *const google_protobuf_UninterpretedOption_submsgs[1] = {
  2482. &google_protobuf_UninterpretedOption_NamePart_msginit,
  2483. };
  2484. static const upb_msglayout_field google_protobuf_UninterpretedOption__fields[7] = {
  2485. {2, UPB_SIZE(56, 80), 0, 0, 11, 3},
  2486. {3, UPB_SIZE(32, 32), 4, 0, 9, 1},
  2487. {4, UPB_SIZE(8, 8), 1, 0, 4, 1},
  2488. {5, UPB_SIZE(16, 16), 2, 0, 3, 1},
  2489. {6, UPB_SIZE(24, 24), 3, 0, 1, 1},
  2490. {7, UPB_SIZE(40, 48), 5, 0, 12, 1},
  2491. {8, UPB_SIZE(48, 64), 6, 0, 9, 1},
  2492. };
  2493. const upb_msglayout google_protobuf_UninterpretedOption_msginit = {
  2494. &google_protobuf_UninterpretedOption_submsgs[0],
  2495. &google_protobuf_UninterpretedOption__fields[0],
  2496. UPB_SIZE(64, 96), 7, false,
  2497. };
  2498. static const upb_msglayout_field google_protobuf_UninterpretedOption_NamePart__fields[2] = {
  2499. {1, UPB_SIZE(4, 8), 2, 0, 9, 2},
  2500. {2, UPB_SIZE(1, 1), 1, 0, 8, 2},
  2501. };
  2502. const upb_msglayout google_protobuf_UninterpretedOption_NamePart_msginit = {
  2503. NULL,
  2504. &google_protobuf_UninterpretedOption_NamePart__fields[0],
  2505. UPB_SIZE(16, 32), 2, false,
  2506. };
  2507. static const upb_msglayout *const google_protobuf_SourceCodeInfo_submsgs[1] = {
  2508. &google_protobuf_SourceCodeInfo_Location_msginit,
  2509. };
  2510. static const upb_msglayout_field google_protobuf_SourceCodeInfo__fields[1] = {
  2511. {1, UPB_SIZE(0, 0), 0, 0, 11, 3},
  2512. };
  2513. const upb_msglayout google_protobuf_SourceCodeInfo_msginit = {
  2514. &google_protobuf_SourceCodeInfo_submsgs[0],
  2515. &google_protobuf_SourceCodeInfo__fields[0],
  2516. UPB_SIZE(4, 8), 1, false,
  2517. };
  2518. static const upb_msglayout_field google_protobuf_SourceCodeInfo_Location__fields[5] = {
  2519. {1, UPB_SIZE(20, 40), 0, 0, 5, _UPB_LABEL_PACKED},
  2520. {2, UPB_SIZE(24, 48), 0, 0, 5, _UPB_LABEL_PACKED},
  2521. {3, UPB_SIZE(4, 8), 1, 0, 9, 1},
  2522. {4, UPB_SIZE(12, 24), 2, 0, 9, 1},
  2523. {6, UPB_SIZE(28, 56), 0, 0, 9, 3},
  2524. };
  2525. const upb_msglayout google_protobuf_SourceCodeInfo_Location_msginit = {
  2526. NULL,
  2527. &google_protobuf_SourceCodeInfo_Location__fields[0],
  2528. UPB_SIZE(32, 64), 5, false,
  2529. };
  2530. static const upb_msglayout *const google_protobuf_GeneratedCodeInfo_submsgs[1] = {
  2531. &google_protobuf_GeneratedCodeInfo_Annotation_msginit,
  2532. };
  2533. static const upb_msglayout_field google_protobuf_GeneratedCodeInfo__fields[1] = {
  2534. {1, UPB_SIZE(0, 0), 0, 0, 11, 3},
  2535. };
  2536. const upb_msglayout google_protobuf_GeneratedCodeInfo_msginit = {
  2537. &google_protobuf_GeneratedCodeInfo_submsgs[0],
  2538. &google_protobuf_GeneratedCodeInfo__fields[0],
  2539. UPB_SIZE(4, 8), 1, false,
  2540. };
  2541. static const upb_msglayout_field google_protobuf_GeneratedCodeInfo_Annotation__fields[4] = {
  2542. {1, UPB_SIZE(20, 32), 0, 0, 5, _UPB_LABEL_PACKED},
  2543. {2, UPB_SIZE(12, 16), 3, 0, 9, 1},
  2544. {3, UPB_SIZE(4, 4), 1, 0, 5, 1},
  2545. {4, UPB_SIZE(8, 8), 2, 0, 5, 1},
  2546. };
  2547. const upb_msglayout google_protobuf_GeneratedCodeInfo_Annotation_msginit = {
  2548. NULL,
  2549. &google_protobuf_GeneratedCodeInfo_Annotation__fields[0],
  2550. UPB_SIZE(24, 48), 4, false,
  2551. };
  2552. #include <ctype.h>
  2553. #include <errno.h>
  2554. #include <stdlib.h>
  2555. #include <string.h>
  2556. typedef struct {
  2557. size_t len;
  2558. char str[1]; /* Null-terminated string data follows. */
  2559. } str_t;
  2560. static str_t *newstr(upb_alloc *alloc, const char *data, size_t len) {
  2561. str_t *ret = upb_malloc(alloc, sizeof(*ret) + len);
  2562. if (!ret) return NULL;
  2563. ret->len = len;
  2564. memcpy(ret->str, data, len);
  2565. ret->str[len] = '\0';
  2566. return ret;
  2567. }
  2568. struct upb_fielddef {
  2569. const upb_filedef *file;
  2570. const upb_msgdef *msgdef;
  2571. const char *full_name;
  2572. const char *json_name;
  2573. union {
  2574. int64_t sint;
  2575. uint64_t uint;
  2576. double dbl;
  2577. float flt;
  2578. bool boolean;
  2579. str_t *str;
  2580. } defaultval;
  2581. const upb_oneofdef *oneof;
  2582. union {
  2583. const upb_msgdef *msgdef;
  2584. const upb_enumdef *enumdef;
  2585. const google_protobuf_FieldDescriptorProto *unresolved;
  2586. } sub;
  2587. uint32_t number_;
  2588. uint16_t index_;
  2589. uint16_t layout_index;
  2590. uint32_t selector_base; /* Used to index into a upb::Handlers table. */
  2591. bool is_extension_;
  2592. bool lazy_;
  2593. bool packed_;
  2594. bool proto3_optional_;
  2595. upb_descriptortype_t type_;
  2596. upb_label_t label_;
  2597. };
  2598. struct upb_msgdef {
  2599. const upb_msglayout *layout;
  2600. const upb_filedef *file;
  2601. const char *full_name;
  2602. uint32_t selector_count;
  2603. uint32_t submsg_field_count;
  2604. /* Tables for looking up fields by number and name. */
  2605. upb_inttable itof;
  2606. upb_strtable ntof;
  2607. const upb_fielddef *fields;
  2608. const upb_oneofdef *oneofs;
  2609. int field_count;
  2610. int oneof_count;
  2611. int real_oneof_count;
  2612. /* Is this a map-entry message? */
  2613. bool map_entry;
  2614. upb_wellknowntype_t well_known_type;
  2615. /* TODO(haberman): proper extension ranges (there can be multiple). */
  2616. };
  2617. struct upb_enumdef {
  2618. const upb_filedef *file;
  2619. const char *full_name;
  2620. upb_strtable ntoi;
  2621. upb_inttable iton;
  2622. int32_t defaultval;
  2623. };
  2624. struct upb_oneofdef {
  2625. const upb_msgdef *parent;
  2626. const char *full_name;
  2627. uint32_t index;
  2628. upb_strtable ntof;
  2629. upb_inttable itof;
  2630. };
  2631. struct upb_filedef {
  2632. const char *name;
  2633. const char *package;
  2634. const char *phpprefix;
  2635. const char *phpnamespace;
  2636. upb_syntax_t syntax;
  2637. const upb_filedef **deps;
  2638. const upb_msgdef *msgs;
  2639. const upb_enumdef *enums;
  2640. const upb_fielddef *exts;
  2641. int dep_count;
  2642. int msg_count;
  2643. int enum_count;
  2644. int ext_count;
  2645. };
  2646. struct upb_symtab {
  2647. upb_arena *arena;
  2648. upb_strtable syms; /* full_name -> packed def ptr */
  2649. upb_strtable files; /* file_name -> upb_filedef* */
  2650. };
  2651. /* Inside a symtab we store tagged pointers to specific def types. */
  2652. typedef enum {
  2653. UPB_DEFTYPE_FIELD = 0,
  2654. /* Only inside symtab table. */
  2655. UPB_DEFTYPE_MSG = 1,
  2656. UPB_DEFTYPE_ENUM = 2,
  2657. /* Only inside message table. */
  2658. UPB_DEFTYPE_ONEOF = 1,
  2659. UPB_DEFTYPE_FIELD_JSONNAME = 2
  2660. } upb_deftype_t;
  2661. static const void *unpack_def(upb_value v, upb_deftype_t type) {
  2662. uintptr_t num = (uintptr_t)upb_value_getconstptr(v);
  2663. return (num & 3) == type ? (const void*)(num & ~3) : NULL;
  2664. }
  2665. static upb_value pack_def(const void *ptr, upb_deftype_t type) {
  2666. uintptr_t num = (uintptr_t)ptr | type;
  2667. return upb_value_constptr((const void*)num);
  2668. }
  2669. /* isalpha() etc. from <ctype.h> are locale-dependent, which we don't want. */
  2670. static bool upb_isbetween(char c, char low, char high) {
  2671. return c >= low && c <= high;
  2672. }
  2673. static bool upb_isletter(char c) {
  2674. return upb_isbetween(c, 'A', 'Z') || upb_isbetween(c, 'a', 'z') || c == '_';
  2675. }
  2676. static bool upb_isalphanum(char c) {
  2677. return upb_isletter(c) || upb_isbetween(c, '0', '9');
  2678. }
  2679. static bool upb_isident(upb_strview name, bool full, upb_status *s) {
  2680. const char *str = name.data;
  2681. size_t len = name.size;
  2682. bool start = true;
  2683. size_t i;
  2684. for (i = 0; i < len; i++) {
  2685. char c = str[i];
  2686. if (c == '.') {
  2687. if (start || !full) {
  2688. upb_status_seterrf(s, "invalid name: unexpected '.' (%s)", str);
  2689. return false;
  2690. }
  2691. start = true;
  2692. } else if (start) {
  2693. if (!upb_isletter(c)) {
  2694. upb_status_seterrf(
  2695. s, "invalid name: path components must start with a letter (%s)",
  2696. str);
  2697. return false;
  2698. }
  2699. start = false;
  2700. } else {
  2701. if (!upb_isalphanum(c)) {
  2702. upb_status_seterrf(s, "invalid name: non-alphanumeric character (%s)",
  2703. str);
  2704. return false;
  2705. }
  2706. }
  2707. }
  2708. return !start;
  2709. }
  2710. static const char *shortdefname(const char *fullname) {
  2711. const char *p;
  2712. if (fullname == NULL) {
  2713. return NULL;
  2714. } else if ((p = strrchr(fullname, '.')) == NULL) {
  2715. /* No '.' in the name, return the full string. */
  2716. return fullname;
  2717. } else {
  2718. /* Return one past the last '.'. */
  2719. return p + 1;
  2720. }
  2721. }
  2722. /* All submessage fields are lower than all other fields.
  2723. * Secondly, fields are increasing in order. */
  2724. uint32_t field_rank(const upb_fielddef *f) {
  2725. uint32_t ret = upb_fielddef_number(f);
  2726. const uint32_t high_bit = 1 << 30;
  2727. UPB_ASSERT(ret < high_bit);
  2728. if (!upb_fielddef_issubmsg(f))
  2729. ret |= high_bit;
  2730. return ret;
  2731. }
  2732. int cmp_fields(const void *p1, const void *p2) {
  2733. const upb_fielddef *f1 = *(upb_fielddef*const*)p1;
  2734. const upb_fielddef *f2 = *(upb_fielddef*const*)p2;
  2735. return field_rank(f1) - field_rank(f2);
  2736. }
  2737. /* A few implementation details of handlers. We put these here to avoid
  2738. * a def -> handlers dependency. */
  2739. #define UPB_STATIC_SELECTOR_COUNT 3 /* Warning: also in upb/handlers.h. */
  2740. static uint32_t upb_handlers_selectorbaseoffset(const upb_fielddef *f) {
  2741. return upb_fielddef_isseq(f) ? 2 : 0;
  2742. }
  2743. static uint32_t upb_handlers_selectorcount(const upb_fielddef *f) {
  2744. uint32_t ret = 1;
  2745. if (upb_fielddef_isseq(f)) ret += 2; /* STARTSEQ/ENDSEQ */
  2746. if (upb_fielddef_isstring(f)) ret += 2; /* [STRING]/STARTSTR/ENDSTR */
  2747. if (upb_fielddef_issubmsg(f)) {
  2748. /* ENDSUBMSG (STARTSUBMSG is at table beginning) */
  2749. ret += 0;
  2750. if (upb_fielddef_lazy(f)) {
  2751. /* STARTSTR/ENDSTR/STRING (for lazy) */
  2752. ret += 3;
  2753. }
  2754. }
  2755. return ret;
  2756. }
  2757. static void upb_status_setoom(upb_status *status) {
  2758. upb_status_seterrmsg(status, "out of memory");
  2759. }
  2760. static bool assign_msg_indices(upb_msgdef *m, upb_status *s) {
  2761. /* Sort fields. upb internally relies on UPB_TYPE_MESSAGE fields having the
  2762. * lowest indexes, but we do not publicly guarantee this. */
  2763. upb_msg_field_iter j;
  2764. int i;
  2765. uint32_t selector;
  2766. int n = upb_msgdef_numfields(m);
  2767. upb_fielddef **fields;
  2768. if (n == 0) {
  2769. m->selector_count = UPB_STATIC_SELECTOR_COUNT;
  2770. m->submsg_field_count = 0;
  2771. return true;
  2772. }
  2773. fields = upb_gmalloc(n * sizeof(*fields));
  2774. if (!fields) {
  2775. upb_status_setoom(s);
  2776. return false;
  2777. }
  2778. m->submsg_field_count = 0;
  2779. for(i = 0, upb_msg_field_begin(&j, m);
  2780. !upb_msg_field_done(&j);
  2781. upb_msg_field_next(&j), i++) {
  2782. upb_fielddef *f = upb_msg_iter_field(&j);
  2783. UPB_ASSERT(f->msgdef == m);
  2784. if (upb_fielddef_issubmsg(f)) {
  2785. m->submsg_field_count++;
  2786. }
  2787. fields[i] = f;
  2788. }
  2789. qsort(fields, n, sizeof(*fields), cmp_fields);
  2790. selector = UPB_STATIC_SELECTOR_COUNT + m->submsg_field_count;
  2791. for (i = 0; i < n; i++) {
  2792. upb_fielddef *f = fields[i];
  2793. f->index_ = i;
  2794. f->selector_base = selector + upb_handlers_selectorbaseoffset(f);
  2795. selector += upb_handlers_selectorcount(f);
  2796. }
  2797. m->selector_count = selector;
  2798. upb_gfree(fields);
  2799. return true;
  2800. }
  2801. static bool check_oneofs(upb_msgdef *m, upb_status *s) {
  2802. int i;
  2803. int first_synthetic = -1;
  2804. upb_oneofdef *mutable_oneofs = (upb_oneofdef*)m->oneofs;
  2805. for (i = 0; i < m->oneof_count; i++) {
  2806. mutable_oneofs[i].index = i;
  2807. if (upb_oneofdef_issynthetic(&mutable_oneofs[i])) {
  2808. if (first_synthetic == -1) {
  2809. first_synthetic = i;
  2810. }
  2811. } else {
  2812. if (first_synthetic != -1) {
  2813. upb_status_seterrf(
  2814. s, "Synthetic oneofs must be after all other oneofs: %s",
  2815. upb_oneofdef_name(&mutable_oneofs[i]));
  2816. return false;
  2817. }
  2818. }
  2819. }
  2820. if (first_synthetic == -1) {
  2821. m->real_oneof_count = m->oneof_count;
  2822. } else {
  2823. m->real_oneof_count = first_synthetic;
  2824. }
  2825. return true;
  2826. }
  2827. static void assign_msg_wellknowntype(upb_msgdef *m) {
  2828. const char *name = upb_msgdef_fullname(m);
  2829. if (name == NULL) {
  2830. m->well_known_type = UPB_WELLKNOWN_UNSPECIFIED;
  2831. return;
  2832. }
  2833. if (!strcmp(name, "google.protobuf.Any")) {
  2834. m->well_known_type = UPB_WELLKNOWN_ANY;
  2835. } else if (!strcmp(name, "google.protobuf.FieldMask")) {
  2836. m->well_known_type = UPB_WELLKNOWN_FIELDMASK;
  2837. } else if (!strcmp(name, "google.protobuf.Duration")) {
  2838. m->well_known_type = UPB_WELLKNOWN_DURATION;
  2839. } else if (!strcmp(name, "google.protobuf.Timestamp")) {
  2840. m->well_known_type = UPB_WELLKNOWN_TIMESTAMP;
  2841. } else if (!strcmp(name, "google.protobuf.DoubleValue")) {
  2842. m->well_known_type = UPB_WELLKNOWN_DOUBLEVALUE;
  2843. } else if (!strcmp(name, "google.protobuf.FloatValue")) {
  2844. m->well_known_type = UPB_WELLKNOWN_FLOATVALUE;
  2845. } else if (!strcmp(name, "google.protobuf.Int64Value")) {
  2846. m->well_known_type = UPB_WELLKNOWN_INT64VALUE;
  2847. } else if (!strcmp(name, "google.protobuf.UInt64Value")) {
  2848. m->well_known_type = UPB_WELLKNOWN_UINT64VALUE;
  2849. } else if (!strcmp(name, "google.protobuf.Int32Value")) {
  2850. m->well_known_type = UPB_WELLKNOWN_INT32VALUE;
  2851. } else if (!strcmp(name, "google.protobuf.UInt32Value")) {
  2852. m->well_known_type = UPB_WELLKNOWN_UINT32VALUE;
  2853. } else if (!strcmp(name, "google.protobuf.BoolValue")) {
  2854. m->well_known_type = UPB_WELLKNOWN_BOOLVALUE;
  2855. } else if (!strcmp(name, "google.protobuf.StringValue")) {
  2856. m->well_known_type = UPB_WELLKNOWN_STRINGVALUE;
  2857. } else if (!strcmp(name, "google.protobuf.BytesValue")) {
  2858. m->well_known_type = UPB_WELLKNOWN_BYTESVALUE;
  2859. } else if (!strcmp(name, "google.protobuf.Value")) {
  2860. m->well_known_type = UPB_WELLKNOWN_VALUE;
  2861. } else if (!strcmp(name, "google.protobuf.ListValue")) {
  2862. m->well_known_type = UPB_WELLKNOWN_LISTVALUE;
  2863. } else if (!strcmp(name, "google.protobuf.Struct")) {
  2864. m->well_known_type = UPB_WELLKNOWN_STRUCT;
  2865. } else {
  2866. m->well_known_type = UPB_WELLKNOWN_UNSPECIFIED;
  2867. }
  2868. }
  2869. /* upb_enumdef ****************************************************************/
  2870. const char *upb_enumdef_fullname(const upb_enumdef *e) {
  2871. return e->full_name;
  2872. }
  2873. const char *upb_enumdef_name(const upb_enumdef *e) {
  2874. return shortdefname(e->full_name);
  2875. }
  2876. const upb_filedef *upb_enumdef_file(const upb_enumdef *e) {
  2877. return e->file;
  2878. }
  2879. int32_t upb_enumdef_default(const upb_enumdef *e) {
  2880. UPB_ASSERT(upb_enumdef_iton(e, e->defaultval));
  2881. return e->defaultval;
  2882. }
  2883. int upb_enumdef_numvals(const upb_enumdef *e) {
  2884. return (int)upb_strtable_count(&e->ntoi);
  2885. }
  2886. void upb_enum_begin(upb_enum_iter *i, const upb_enumdef *e) {
  2887. /* We iterate over the ntoi table, to account for duplicate numbers. */
  2888. upb_strtable_begin(i, &e->ntoi);
  2889. }
  2890. void upb_enum_next(upb_enum_iter *iter) { upb_strtable_next(iter); }
  2891. bool upb_enum_done(upb_enum_iter *iter) { return upb_strtable_done(iter); }
  2892. bool upb_enumdef_ntoi(const upb_enumdef *def, const char *name,
  2893. size_t len, int32_t *num) {
  2894. upb_value v;
  2895. if (!upb_strtable_lookup2(&def->ntoi, name, len, &v)) {
  2896. return false;
  2897. }
  2898. if (num) *num = upb_value_getint32(v);
  2899. return true;
  2900. }
  2901. const char *upb_enumdef_iton(const upb_enumdef *def, int32_t num) {
  2902. upb_value v;
  2903. return upb_inttable_lookup32(&def->iton, num, &v) ?
  2904. upb_value_getcstr(v) : NULL;
  2905. }
  2906. const char *upb_enum_iter_name(upb_enum_iter *iter) {
  2907. return upb_strtable_iter_key(iter).data;
  2908. }
  2909. int32_t upb_enum_iter_number(upb_enum_iter *iter) {
  2910. return upb_value_getint32(upb_strtable_iter_value(iter));
  2911. }
  2912. /* upb_fielddef ***************************************************************/
  2913. const char *upb_fielddef_fullname(const upb_fielddef *f) {
  2914. return f->full_name;
  2915. }
  2916. upb_fieldtype_t upb_fielddef_type(const upb_fielddef *f) {
  2917. switch (f->type_) {
  2918. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  2919. return UPB_TYPE_DOUBLE;
  2920. case UPB_DESCRIPTOR_TYPE_FLOAT:
  2921. return UPB_TYPE_FLOAT;
  2922. case UPB_DESCRIPTOR_TYPE_INT64:
  2923. case UPB_DESCRIPTOR_TYPE_SINT64:
  2924. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  2925. return UPB_TYPE_INT64;
  2926. case UPB_DESCRIPTOR_TYPE_INT32:
  2927. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  2928. case UPB_DESCRIPTOR_TYPE_SINT32:
  2929. return UPB_TYPE_INT32;
  2930. case UPB_DESCRIPTOR_TYPE_UINT64:
  2931. case UPB_DESCRIPTOR_TYPE_FIXED64:
  2932. return UPB_TYPE_UINT64;
  2933. case UPB_DESCRIPTOR_TYPE_UINT32:
  2934. case UPB_DESCRIPTOR_TYPE_FIXED32:
  2935. return UPB_TYPE_UINT32;
  2936. case UPB_DESCRIPTOR_TYPE_ENUM:
  2937. return UPB_TYPE_ENUM;
  2938. case UPB_DESCRIPTOR_TYPE_BOOL:
  2939. return UPB_TYPE_BOOL;
  2940. case UPB_DESCRIPTOR_TYPE_STRING:
  2941. return UPB_TYPE_STRING;
  2942. case UPB_DESCRIPTOR_TYPE_BYTES:
  2943. return UPB_TYPE_BYTES;
  2944. case UPB_DESCRIPTOR_TYPE_GROUP:
  2945. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  2946. return UPB_TYPE_MESSAGE;
  2947. }
  2948. UPB_UNREACHABLE();
  2949. }
  2950. upb_descriptortype_t upb_fielddef_descriptortype(const upb_fielddef *f) {
  2951. return f->type_;
  2952. }
  2953. uint32_t upb_fielddef_index(const upb_fielddef *f) {
  2954. return f->index_;
  2955. }
  2956. upb_label_t upb_fielddef_label(const upb_fielddef *f) {
  2957. return f->label_;
  2958. }
  2959. uint32_t upb_fielddef_number(const upb_fielddef *f) {
  2960. return f->number_;
  2961. }
  2962. bool upb_fielddef_isextension(const upb_fielddef *f) {
  2963. return f->is_extension_;
  2964. }
  2965. bool upb_fielddef_lazy(const upb_fielddef *f) {
  2966. return f->lazy_;
  2967. }
  2968. bool upb_fielddef_packed(const upb_fielddef *f) {
  2969. return f->packed_;
  2970. }
  2971. const char *upb_fielddef_name(const upb_fielddef *f) {
  2972. return shortdefname(f->full_name);
  2973. }
  2974. const char *upb_fielddef_jsonname(const upb_fielddef *f) {
  2975. return f->json_name;
  2976. }
  2977. uint32_t upb_fielddef_selectorbase(const upb_fielddef *f) {
  2978. return f->selector_base;
  2979. }
  2980. const upb_filedef *upb_fielddef_file(const upb_fielddef *f) {
  2981. return f->file;
  2982. }
  2983. const upb_msgdef *upb_fielddef_containingtype(const upb_fielddef *f) {
  2984. return f->msgdef;
  2985. }
  2986. const upb_oneofdef *upb_fielddef_containingoneof(const upb_fielddef *f) {
  2987. return f->oneof;
  2988. }
  2989. const upb_oneofdef *upb_fielddef_realcontainingoneof(const upb_fielddef *f) {
  2990. if (!f->oneof || upb_oneofdef_issynthetic(f->oneof)) return NULL;
  2991. return f->oneof;
  2992. }
  2993. static void chkdefaulttype(const upb_fielddef *f, int ctype) {
  2994. UPB_UNUSED(f);
  2995. UPB_UNUSED(ctype);
  2996. }
  2997. int64_t upb_fielddef_defaultint64(const upb_fielddef *f) {
  2998. chkdefaulttype(f, UPB_TYPE_INT64);
  2999. return f->defaultval.sint;
  3000. }
  3001. int32_t upb_fielddef_defaultint32(const upb_fielddef *f) {
  3002. chkdefaulttype(f, UPB_TYPE_INT32);
  3003. return (int32_t)f->defaultval.sint;
  3004. }
  3005. uint64_t upb_fielddef_defaultuint64(const upb_fielddef *f) {
  3006. chkdefaulttype(f, UPB_TYPE_UINT64);
  3007. return f->defaultval.uint;
  3008. }
  3009. uint32_t upb_fielddef_defaultuint32(const upb_fielddef *f) {
  3010. chkdefaulttype(f, UPB_TYPE_UINT32);
  3011. return (uint32_t)f->defaultval.uint;
  3012. }
  3013. bool upb_fielddef_defaultbool(const upb_fielddef *f) {
  3014. chkdefaulttype(f, UPB_TYPE_BOOL);
  3015. return f->defaultval.boolean;
  3016. }
  3017. float upb_fielddef_defaultfloat(const upb_fielddef *f) {
  3018. chkdefaulttype(f, UPB_TYPE_FLOAT);
  3019. return f->defaultval.flt;
  3020. }
  3021. double upb_fielddef_defaultdouble(const upb_fielddef *f) {
  3022. chkdefaulttype(f, UPB_TYPE_DOUBLE);
  3023. return f->defaultval.dbl;
  3024. }
  3025. const char *upb_fielddef_defaultstr(const upb_fielddef *f, size_t *len) {
  3026. str_t *str = f->defaultval.str;
  3027. UPB_ASSERT(upb_fielddef_type(f) == UPB_TYPE_STRING ||
  3028. upb_fielddef_type(f) == UPB_TYPE_BYTES ||
  3029. upb_fielddef_type(f) == UPB_TYPE_ENUM);
  3030. if (str) {
  3031. if (len) *len = str->len;
  3032. return str->str;
  3033. } else {
  3034. if (len) *len = 0;
  3035. return NULL;
  3036. }
  3037. }
  3038. const upb_msgdef *upb_fielddef_msgsubdef(const upb_fielddef *f) {
  3039. UPB_ASSERT(upb_fielddef_type(f) == UPB_TYPE_MESSAGE);
  3040. return f->sub.msgdef;
  3041. }
  3042. const upb_enumdef *upb_fielddef_enumsubdef(const upb_fielddef *f) {
  3043. UPB_ASSERT(upb_fielddef_type(f) == UPB_TYPE_ENUM);
  3044. return f->sub.enumdef;
  3045. }
  3046. const upb_msglayout_field *upb_fielddef_layout(const upb_fielddef *f) {
  3047. return &f->msgdef->layout->fields[f->layout_index];
  3048. }
  3049. bool upb_fielddef_issubmsg(const upb_fielddef *f) {
  3050. return upb_fielddef_type(f) == UPB_TYPE_MESSAGE;
  3051. }
  3052. bool upb_fielddef_isstring(const upb_fielddef *f) {
  3053. return upb_fielddef_type(f) == UPB_TYPE_STRING ||
  3054. upb_fielddef_type(f) == UPB_TYPE_BYTES;
  3055. }
  3056. bool upb_fielddef_isseq(const upb_fielddef *f) {
  3057. return upb_fielddef_label(f) == UPB_LABEL_REPEATED;
  3058. }
  3059. bool upb_fielddef_isprimitive(const upb_fielddef *f) {
  3060. return !upb_fielddef_isstring(f) && !upb_fielddef_issubmsg(f);
  3061. }
  3062. bool upb_fielddef_ismap(const upb_fielddef *f) {
  3063. return upb_fielddef_isseq(f) && upb_fielddef_issubmsg(f) &&
  3064. upb_msgdef_mapentry(upb_fielddef_msgsubdef(f));
  3065. }
  3066. bool upb_fielddef_hassubdef(const upb_fielddef *f) {
  3067. return upb_fielddef_issubmsg(f) || upb_fielddef_type(f) == UPB_TYPE_ENUM;
  3068. }
  3069. bool upb_fielddef_haspresence(const upb_fielddef *f) {
  3070. if (upb_fielddef_isseq(f)) return false;
  3071. return upb_fielddef_issubmsg(f) || upb_fielddef_containingoneof(f) ||
  3072. f->file->syntax == UPB_SYNTAX_PROTO2;
  3073. }
  3074. static bool between(int32_t x, int32_t low, int32_t high) {
  3075. return x >= low && x <= high;
  3076. }
  3077. bool upb_fielddef_checklabel(int32_t label) { return between(label, 1, 3); }
  3078. bool upb_fielddef_checktype(int32_t type) { return between(type, 1, 11); }
  3079. bool upb_fielddef_checkintfmt(int32_t fmt) { return between(fmt, 1, 3); }
  3080. bool upb_fielddef_checkdescriptortype(int32_t type) {
  3081. return between(type, 1, 18);
  3082. }
  3083. /* upb_msgdef *****************************************************************/
  3084. const char *upb_msgdef_fullname(const upb_msgdef *m) {
  3085. return m->full_name;
  3086. }
  3087. const upb_filedef *upb_msgdef_file(const upb_msgdef *m) {
  3088. return m->file;
  3089. }
  3090. const char *upb_msgdef_name(const upb_msgdef *m) {
  3091. return shortdefname(m->full_name);
  3092. }
  3093. upb_syntax_t upb_msgdef_syntax(const upb_msgdef *m) {
  3094. return m->file->syntax;
  3095. }
  3096. size_t upb_msgdef_selectorcount(const upb_msgdef *m) {
  3097. return m->selector_count;
  3098. }
  3099. uint32_t upb_msgdef_submsgfieldcount(const upb_msgdef *m) {
  3100. return m->submsg_field_count;
  3101. }
  3102. const upb_fielddef *upb_msgdef_itof(const upb_msgdef *m, uint32_t i) {
  3103. upb_value val;
  3104. return upb_inttable_lookup32(&m->itof, i, &val) ?
  3105. upb_value_getconstptr(val) : NULL;
  3106. }
  3107. const upb_fielddef *upb_msgdef_ntof(const upb_msgdef *m, const char *name,
  3108. size_t len) {
  3109. upb_value val;
  3110. if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
  3111. return NULL;
  3112. }
  3113. return unpack_def(val, UPB_DEFTYPE_FIELD);
  3114. }
  3115. const upb_oneofdef *upb_msgdef_ntoo(const upb_msgdef *m, const char *name,
  3116. size_t len) {
  3117. upb_value val;
  3118. if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
  3119. return NULL;
  3120. }
  3121. return unpack_def(val, UPB_DEFTYPE_ONEOF);
  3122. }
  3123. bool upb_msgdef_lookupname(const upb_msgdef *m, const char *name, size_t len,
  3124. const upb_fielddef **f, const upb_oneofdef **o) {
  3125. upb_value val;
  3126. if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
  3127. return false;
  3128. }
  3129. *o = unpack_def(val, UPB_DEFTYPE_ONEOF);
  3130. *f = unpack_def(val, UPB_DEFTYPE_FIELD);
  3131. return *o || *f; /* False if this was a JSON name. */
  3132. }
  3133. const upb_fielddef *upb_msgdef_lookupjsonname(const upb_msgdef *m,
  3134. const char *name, size_t len) {
  3135. upb_value val;
  3136. const upb_fielddef* f;
  3137. if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
  3138. return NULL;
  3139. }
  3140. f = unpack_def(val, UPB_DEFTYPE_FIELD);
  3141. if (!f) f = unpack_def(val, UPB_DEFTYPE_FIELD_JSONNAME);
  3142. return f;
  3143. }
  3144. int upb_msgdef_numfields(const upb_msgdef *m) {
  3145. return m->field_count;
  3146. }
  3147. int upb_msgdef_numoneofs(const upb_msgdef *m) {
  3148. return m->oneof_count;
  3149. }
  3150. int upb_msgdef_numrealoneofs(const upb_msgdef *m) {
  3151. return m->real_oneof_count;
  3152. }
  3153. const upb_msglayout *upb_msgdef_layout(const upb_msgdef *m) {
  3154. return m->layout;
  3155. }
  3156. const upb_fielddef *_upb_msgdef_field(const upb_msgdef *m, int i) {
  3157. if (i >= m->field_count) return NULL;
  3158. return &m->fields[i];
  3159. }
  3160. bool upb_msgdef_mapentry(const upb_msgdef *m) {
  3161. return m->map_entry;
  3162. }
  3163. upb_wellknowntype_t upb_msgdef_wellknowntype(const upb_msgdef *m) {
  3164. return m->well_known_type;
  3165. }
  3166. bool upb_msgdef_isnumberwrapper(const upb_msgdef *m) {
  3167. upb_wellknowntype_t type = upb_msgdef_wellknowntype(m);
  3168. return type >= UPB_WELLKNOWN_DOUBLEVALUE &&
  3169. type <= UPB_WELLKNOWN_UINT32VALUE;
  3170. }
  3171. void upb_msg_field_begin(upb_msg_field_iter *iter, const upb_msgdef *m) {
  3172. upb_inttable_begin(iter, &m->itof);
  3173. }
  3174. void upb_msg_field_next(upb_msg_field_iter *iter) { upb_inttable_next(iter); }
  3175. bool upb_msg_field_done(const upb_msg_field_iter *iter) {
  3176. return upb_inttable_done(iter);
  3177. }
  3178. upb_fielddef *upb_msg_iter_field(const upb_msg_field_iter *iter) {
  3179. return (upb_fielddef *)upb_value_getconstptr(upb_inttable_iter_value(iter));
  3180. }
  3181. void upb_msg_field_iter_setdone(upb_msg_field_iter *iter) {
  3182. upb_inttable_iter_setdone(iter);
  3183. }
  3184. bool upb_msg_field_iter_isequal(const upb_msg_field_iter * iter1,
  3185. const upb_msg_field_iter * iter2) {
  3186. return upb_inttable_iter_isequal(iter1, iter2);
  3187. }
  3188. void upb_msg_oneof_begin(upb_msg_oneof_iter *iter, const upb_msgdef *m) {
  3189. upb_strtable_begin(iter, &m->ntof);
  3190. /* We need to skip past any initial fields. */
  3191. while (!upb_strtable_done(iter) &&
  3192. !unpack_def(upb_strtable_iter_value(iter), UPB_DEFTYPE_ONEOF)) {
  3193. upb_strtable_next(iter);
  3194. }
  3195. }
  3196. void upb_msg_oneof_next(upb_msg_oneof_iter *iter) {
  3197. /* We need to skip past fields to return only oneofs. */
  3198. do {
  3199. upb_strtable_next(iter);
  3200. } while (!upb_strtable_done(iter) &&
  3201. !unpack_def(upb_strtable_iter_value(iter), UPB_DEFTYPE_ONEOF));
  3202. }
  3203. bool upb_msg_oneof_done(const upb_msg_oneof_iter *iter) {
  3204. return upb_strtable_done(iter);
  3205. }
  3206. const upb_oneofdef *upb_msg_iter_oneof(const upb_msg_oneof_iter *iter) {
  3207. return unpack_def(upb_strtable_iter_value(iter), UPB_DEFTYPE_ONEOF);
  3208. }
  3209. void upb_msg_oneof_iter_setdone(upb_msg_oneof_iter *iter) {
  3210. upb_strtable_iter_setdone(iter);
  3211. }
  3212. bool upb_msg_oneof_iter_isequal(const upb_msg_oneof_iter *iter1,
  3213. const upb_msg_oneof_iter *iter2) {
  3214. return upb_strtable_iter_isequal(iter1, iter2);
  3215. }
  3216. /* upb_oneofdef ***************************************************************/
  3217. const char *upb_oneofdef_name(const upb_oneofdef *o) {
  3218. return shortdefname(o->full_name);
  3219. }
  3220. const upb_msgdef *upb_oneofdef_containingtype(const upb_oneofdef *o) {
  3221. return o->parent;
  3222. }
  3223. int upb_oneofdef_numfields(const upb_oneofdef *o) {
  3224. return (int)upb_strtable_count(&o->ntof);
  3225. }
  3226. uint32_t upb_oneofdef_index(const upb_oneofdef *o) {
  3227. return o->index;
  3228. }
  3229. bool upb_oneofdef_issynthetic(const upb_oneofdef *o) {
  3230. upb_inttable_iter iter;
  3231. const upb_fielddef *f;
  3232. upb_inttable_begin(&iter, &o->itof);
  3233. if (upb_oneofdef_numfields(o) != 1) return false;
  3234. f = upb_value_getptr(upb_inttable_iter_value(&iter));
  3235. UPB_ASSERT(f);
  3236. return f->proto3_optional_;
  3237. }
  3238. const upb_fielddef *upb_oneofdef_ntof(const upb_oneofdef *o,
  3239. const char *name, size_t length) {
  3240. upb_value val;
  3241. return upb_strtable_lookup2(&o->ntof, name, length, &val) ?
  3242. upb_value_getptr(val) : NULL;
  3243. }
  3244. const upb_fielddef *upb_oneofdef_itof(const upb_oneofdef *o, uint32_t num) {
  3245. upb_value val;
  3246. return upb_inttable_lookup32(&o->itof, num, &val) ?
  3247. upb_value_getptr(val) : NULL;
  3248. }
  3249. void upb_oneof_begin(upb_oneof_iter *iter, const upb_oneofdef *o) {
  3250. upb_inttable_begin(iter, &o->itof);
  3251. }
  3252. void upb_oneof_next(upb_oneof_iter *iter) {
  3253. upb_inttable_next(iter);
  3254. }
  3255. bool upb_oneof_done(upb_oneof_iter *iter) {
  3256. return upb_inttable_done(iter);
  3257. }
  3258. upb_fielddef *upb_oneof_iter_field(const upb_oneof_iter *iter) {
  3259. return (upb_fielddef *)upb_value_getconstptr(upb_inttable_iter_value(iter));
  3260. }
  3261. void upb_oneof_iter_setdone(upb_oneof_iter *iter) {
  3262. upb_inttable_iter_setdone(iter);
  3263. }
  3264. /* Dynamic Layout Generation. *************************************************/
  3265. static size_t div_round_up(size_t n, size_t d) {
  3266. return (n + d - 1) / d;
  3267. }
  3268. static size_t upb_msgval_sizeof(upb_fieldtype_t type) {
  3269. switch (type) {
  3270. case UPB_TYPE_DOUBLE:
  3271. case UPB_TYPE_INT64:
  3272. case UPB_TYPE_UINT64:
  3273. return 8;
  3274. case UPB_TYPE_ENUM:
  3275. case UPB_TYPE_INT32:
  3276. case UPB_TYPE_UINT32:
  3277. case UPB_TYPE_FLOAT:
  3278. return 4;
  3279. case UPB_TYPE_BOOL:
  3280. return 1;
  3281. case UPB_TYPE_MESSAGE:
  3282. return sizeof(void*);
  3283. case UPB_TYPE_BYTES:
  3284. case UPB_TYPE_STRING:
  3285. return sizeof(upb_strview);
  3286. }
  3287. UPB_UNREACHABLE();
  3288. }
  3289. static uint8_t upb_msg_fielddefsize(const upb_fielddef *f) {
  3290. if (upb_msgdef_mapentry(upb_fielddef_containingtype(f))) {
  3291. upb_map_entry ent;
  3292. UPB_ASSERT(sizeof(ent.k) == sizeof(ent.v));
  3293. return sizeof(ent.k);
  3294. } else if (upb_fielddef_isseq(f)) {
  3295. return sizeof(void*);
  3296. } else {
  3297. return upb_msgval_sizeof(upb_fielddef_type(f));
  3298. }
  3299. }
  3300. static uint32_t upb_msglayout_place(upb_msglayout *l, size_t size) {
  3301. uint32_t ret;
  3302. l->size = UPB_ALIGN_UP(l->size, size);
  3303. ret = l->size;
  3304. l->size += size;
  3305. return ret;
  3306. }
  3307. /* This function is the dynamic equivalent of message_layout.{cc,h} in upbc.
  3308. * It computes a dynamic layout for all of the fields in |m|. */
  3309. static bool make_layout(const upb_symtab *symtab, const upb_msgdef *m) {
  3310. upb_msglayout *l = (upb_msglayout*)m->layout;
  3311. upb_msg_field_iter it;
  3312. upb_msg_oneof_iter oit;
  3313. size_t hasbit;
  3314. size_t submsg_count = m->submsg_field_count;
  3315. const upb_msglayout **submsgs;
  3316. upb_msglayout_field *fields;
  3317. upb_alloc *alloc = upb_arena_alloc(symtab->arena);
  3318. memset(l, 0, sizeof(*l));
  3319. fields = upb_malloc(alloc, upb_msgdef_numfields(m) * sizeof(*fields));
  3320. submsgs = upb_malloc(alloc, submsg_count * sizeof(*submsgs));
  3321. if ((!fields && upb_msgdef_numfields(m)) ||
  3322. (!submsgs && submsg_count)) {
  3323. /* OOM. */
  3324. return false;
  3325. }
  3326. l->field_count = upb_msgdef_numfields(m);
  3327. l->fields = fields;
  3328. l->submsgs = submsgs;
  3329. if (upb_msgdef_mapentry(m)) {
  3330. /* TODO(haberman): refactor this method so this special case is more
  3331. * elegant. */
  3332. const upb_fielddef *key = upb_msgdef_itof(m, 1);
  3333. const upb_fielddef *val = upb_msgdef_itof(m, 2);
  3334. fields[0].number = 1;
  3335. fields[1].number = 2;
  3336. fields[0].label = UPB_LABEL_OPTIONAL;
  3337. fields[1].label = UPB_LABEL_OPTIONAL;
  3338. fields[0].presence = 0;
  3339. fields[1].presence = 0;
  3340. fields[0].descriptortype = upb_fielddef_descriptortype(key);
  3341. fields[1].descriptortype = upb_fielddef_descriptortype(val);
  3342. fields[0].offset = 0;
  3343. fields[1].offset = sizeof(upb_strview);
  3344. fields[1].submsg_index = 0;
  3345. if (upb_fielddef_type(val) == UPB_TYPE_MESSAGE) {
  3346. submsgs[0] = upb_fielddef_msgsubdef(val)->layout;
  3347. }
  3348. l->field_count = 2;
  3349. l->size = 2 * sizeof(upb_strview);
  3350. l->size = UPB_ALIGN_UP(l->size, 8);
  3351. return true;
  3352. }
  3353. /* Allocate data offsets in three stages:
  3354. *
  3355. * 1. hasbits.
  3356. * 2. regular fields.
  3357. * 3. oneof fields.
  3358. *
  3359. * OPT: There is a lot of room for optimization here to minimize the size.
  3360. */
  3361. /* Allocate hasbits and set basic field attributes. */
  3362. submsg_count = 0;
  3363. for (upb_msg_field_begin(&it, m), hasbit = 0;
  3364. !upb_msg_field_done(&it);
  3365. upb_msg_field_next(&it)) {
  3366. upb_fielddef* f = upb_msg_iter_field(&it);
  3367. upb_msglayout_field *field = &fields[upb_fielddef_index(f)];
  3368. field->number = upb_fielddef_number(f);
  3369. field->descriptortype = upb_fielddef_descriptortype(f);
  3370. field->label = upb_fielddef_label(f);
  3371. if (upb_fielddef_ismap(f)) {
  3372. field->label = _UPB_LABEL_MAP;
  3373. } else if (upb_fielddef_packed(f)) {
  3374. field->label = _UPB_LABEL_PACKED;
  3375. }
  3376. /* TODO: we probably should sort the fields by field number to match the
  3377. * output of upbc, and to improve search speed for the table parser. */
  3378. f->layout_index = f->index_;
  3379. if (upb_fielddef_issubmsg(f)) {
  3380. const upb_msgdef *subm = upb_fielddef_msgsubdef(f);
  3381. field->submsg_index = submsg_count++;
  3382. submsgs[field->submsg_index] = subm->layout;
  3383. }
  3384. if (upb_fielddef_haspresence(f) && !upb_fielddef_realcontainingoneof(f)) {
  3385. /* We don't use hasbit 0, so that 0 can indicate "no presence" in the
  3386. * table. This wastes one hasbit, but we don't worry about it for now. */
  3387. field->presence = ++hasbit;
  3388. } else {
  3389. field->presence = 0;
  3390. }
  3391. }
  3392. /* Account for space used by hasbits. */
  3393. l->size = div_round_up(hasbit, 8);
  3394. /* Allocate non-oneof fields. */
  3395. for (upb_msg_field_begin(&it, m); !upb_msg_field_done(&it);
  3396. upb_msg_field_next(&it)) {
  3397. const upb_fielddef* f = upb_msg_iter_field(&it);
  3398. size_t field_size = upb_msg_fielddefsize(f);
  3399. size_t index = upb_fielddef_index(f);
  3400. if (upb_fielddef_realcontainingoneof(f)) {
  3401. /* Oneofs are handled separately below. */
  3402. continue;
  3403. }
  3404. fields[index].offset = upb_msglayout_place(l, field_size);
  3405. }
  3406. /* Allocate oneof fields. Each oneof field consists of a uint32 for the case
  3407. * and space for the actual data. */
  3408. for (upb_msg_oneof_begin(&oit, m); !upb_msg_oneof_done(&oit);
  3409. upb_msg_oneof_next(&oit)) {
  3410. const upb_oneofdef* o = upb_msg_iter_oneof(&oit);
  3411. upb_oneof_iter fit;
  3412. size_t case_size = sizeof(uint32_t); /* Could potentially optimize this. */
  3413. size_t field_size = 0;
  3414. uint32_t case_offset;
  3415. uint32_t data_offset;
  3416. if (upb_oneofdef_issynthetic(o)) continue;
  3417. /* Calculate field size: the max of all field sizes. */
  3418. for (upb_oneof_begin(&fit, o);
  3419. !upb_oneof_done(&fit);
  3420. upb_oneof_next(&fit)) {
  3421. const upb_fielddef* f = upb_oneof_iter_field(&fit);
  3422. field_size = UPB_MAX(field_size, upb_msg_fielddefsize(f));
  3423. }
  3424. /* Align and allocate case offset. */
  3425. case_offset = upb_msglayout_place(l, case_size);
  3426. data_offset = upb_msglayout_place(l, field_size);
  3427. for (upb_oneof_begin(&fit, o);
  3428. !upb_oneof_done(&fit);
  3429. upb_oneof_next(&fit)) {
  3430. const upb_fielddef* f = upb_oneof_iter_field(&fit);
  3431. fields[upb_fielddef_index(f)].offset = data_offset;
  3432. fields[upb_fielddef_index(f)].presence = ~case_offset;
  3433. }
  3434. }
  3435. /* Size of the entire structure should be a multiple of its greatest
  3436. * alignment. TODO: track overall alignment for real? */
  3437. l->size = UPB_ALIGN_UP(l->size, 8);
  3438. return true;
  3439. }
  3440. /* Code to build defs from descriptor protos. *********************************/
  3441. /* There is a question of how much validation to do here. It will be difficult
  3442. * to perfectly match the amount of validation performed by proto2. But since
  3443. * this code is used to directly build defs from Ruby (for example) we do need
  3444. * to validate important constraints like uniqueness of names and numbers. */
  3445. #define CHK(x) if (!(x)) { return false; }
  3446. #define CHK_OOM(x) if (!(x)) { upb_status_setoom(ctx->status); return false; }
  3447. typedef struct {
  3448. const upb_symtab *symtab;
  3449. upb_filedef *file; /* File we are building. */
  3450. upb_alloc *alloc; /* Allocate defs here. */
  3451. upb_alloc *tmp; /* Alloc for addtab and any other tmp data. */
  3452. upb_strtable *addtab; /* full_name -> packed def ptr for new defs */
  3453. const upb_msglayout **layouts; /* NULL if we should build layouts. */
  3454. upb_status *status; /* Record errors here. */
  3455. } symtab_addctx;
  3456. static char* strviewdup(const symtab_addctx *ctx, upb_strview view) {
  3457. return upb_strdup2(view.data, view.size, ctx->alloc);
  3458. }
  3459. static bool streql2(const char *a, size_t n, const char *b) {
  3460. return n == strlen(b) && memcmp(a, b, n) == 0;
  3461. }
  3462. static bool streql_view(upb_strview view, const char *b) {
  3463. return streql2(view.data, view.size, b);
  3464. }
  3465. static const char *makefullname(const symtab_addctx *ctx, const char *prefix,
  3466. upb_strview name) {
  3467. if (prefix) {
  3468. /* ret = prefix + '.' + name; */
  3469. size_t n = strlen(prefix);
  3470. char *ret = upb_malloc(ctx->alloc, n + name.size + 2);
  3471. CHK_OOM(ret);
  3472. strcpy(ret, prefix);
  3473. ret[n] = '.';
  3474. memcpy(&ret[n + 1], name.data, name.size);
  3475. ret[n + 1 + name.size] = '\0';
  3476. return ret;
  3477. } else {
  3478. return strviewdup(ctx, name);
  3479. }
  3480. }
  3481. size_t getjsonname(const char *name, char *buf, size_t len) {
  3482. size_t src, dst = 0;
  3483. bool ucase_next = false;
  3484. #define WRITE(byte) \
  3485. ++dst; \
  3486. if (dst < len) buf[dst - 1] = byte; \
  3487. else if (dst == len) buf[dst - 1] = '\0'
  3488. if (!name) {
  3489. WRITE('\0');
  3490. return 0;
  3491. }
  3492. /* Implement the transformation as described in the spec:
  3493. * 1. upper case all letters after an underscore.
  3494. * 2. remove all underscores.
  3495. */
  3496. for (src = 0; name[src]; src++) {
  3497. if (name[src] == '_') {
  3498. ucase_next = true;
  3499. continue;
  3500. }
  3501. if (ucase_next) {
  3502. WRITE(toupper(name[src]));
  3503. ucase_next = false;
  3504. } else {
  3505. WRITE(name[src]);
  3506. }
  3507. }
  3508. WRITE('\0');
  3509. return dst;
  3510. #undef WRITE
  3511. }
  3512. static char* makejsonname(const char* name, upb_alloc *alloc) {
  3513. size_t size = getjsonname(name, NULL, 0);
  3514. char* json_name = upb_malloc(alloc, size);
  3515. getjsonname(name, json_name, size);
  3516. return json_name;
  3517. }
  3518. static bool symtab_add(const symtab_addctx *ctx, const char *name,
  3519. upb_value v) {
  3520. upb_value tmp;
  3521. if (upb_strtable_lookup(ctx->addtab, name, &tmp) ||
  3522. upb_strtable_lookup(&ctx->symtab->syms, name, &tmp)) {
  3523. upb_status_seterrf(ctx->status, "duplicate symbol '%s'", name);
  3524. return false;
  3525. }
  3526. CHK_OOM(upb_strtable_insert3(ctx->addtab, name, strlen(name), v, ctx->tmp));
  3527. return true;
  3528. }
  3529. /* Given a symbol and the base symbol inside which it is defined, find the
  3530. * symbol's definition in t. */
  3531. static bool resolvename(const upb_strtable *t, const upb_fielddef *f,
  3532. const char *base, upb_strview sym,
  3533. upb_deftype_t type, upb_status *status,
  3534. const void **def) {
  3535. if(sym.size == 0) return NULL;
  3536. if(sym.data[0] == '.') {
  3537. /* Symbols starting with '.' are absolute, so we do a single lookup.
  3538. * Slice to omit the leading '.' */
  3539. upb_value v;
  3540. if (!upb_strtable_lookup2(t, sym.data + 1, sym.size - 1, &v)) {
  3541. return false;
  3542. }
  3543. *def = unpack_def(v, type);
  3544. if (!*def) {
  3545. upb_status_seterrf(status,
  3546. "type mismatch when resolving field %s, name %s",
  3547. f->full_name, sym.data);
  3548. return false;
  3549. }
  3550. return true;
  3551. } else {
  3552. /* Remove components from base until we find an entry or run out.
  3553. * TODO: This branch is totally broken, but currently not used. */
  3554. (void)base;
  3555. UPB_ASSERT(false);
  3556. return false;
  3557. }
  3558. }
  3559. const void *symtab_resolve(const symtab_addctx *ctx, const upb_fielddef *f,
  3560. const char *base, upb_strview sym,
  3561. upb_deftype_t type) {
  3562. const void *ret;
  3563. if (!resolvename(ctx->addtab, f, base, sym, type, ctx->status, &ret) &&
  3564. !resolvename(&ctx->symtab->syms, f, base, sym, type, ctx->status, &ret)) {
  3565. if (upb_ok(ctx->status)) {
  3566. upb_status_seterrf(ctx->status, "couldn't resolve name '%s'", sym.data);
  3567. }
  3568. return false;
  3569. }
  3570. return ret;
  3571. }
  3572. static bool create_oneofdef(
  3573. const symtab_addctx *ctx, upb_msgdef *m,
  3574. const google_protobuf_OneofDescriptorProto *oneof_proto) {
  3575. upb_oneofdef *o;
  3576. upb_strview name = google_protobuf_OneofDescriptorProto_name(oneof_proto);
  3577. upb_value v;
  3578. o = (upb_oneofdef*)&m->oneofs[m->oneof_count++];
  3579. o->parent = m;
  3580. o->full_name = makefullname(ctx, m->full_name, name);
  3581. v = pack_def(o, UPB_DEFTYPE_ONEOF);
  3582. CHK_OOM(symtab_add(ctx, o->full_name, v));
  3583. CHK_OOM(upb_strtable_insert3(&m->ntof, name.data, name.size, v, ctx->alloc));
  3584. CHK_OOM(upb_inttable_init2(&o->itof, UPB_CTYPE_CONSTPTR, ctx->alloc));
  3585. CHK_OOM(upb_strtable_init2(&o->ntof, UPB_CTYPE_CONSTPTR, ctx->alloc));
  3586. return true;
  3587. }
  3588. static bool parse_default(const symtab_addctx *ctx, const char *str, size_t len,
  3589. upb_fielddef *f) {
  3590. char *end;
  3591. char nullz[64];
  3592. errno = 0;
  3593. switch (upb_fielddef_type(f)) {
  3594. case UPB_TYPE_INT32:
  3595. case UPB_TYPE_INT64:
  3596. case UPB_TYPE_UINT32:
  3597. case UPB_TYPE_UINT64:
  3598. case UPB_TYPE_DOUBLE:
  3599. case UPB_TYPE_FLOAT:
  3600. /* Standard C number parsing functions expect null-terminated strings. */
  3601. if (len >= sizeof(nullz) - 1) {
  3602. return false;
  3603. }
  3604. memcpy(nullz, str, len);
  3605. nullz[len] = '\0';
  3606. str = nullz;
  3607. break;
  3608. default:
  3609. break;
  3610. }
  3611. switch (upb_fielddef_type(f)) {
  3612. case UPB_TYPE_INT32: {
  3613. long val = strtol(str, &end, 0);
  3614. CHK(val <= INT32_MAX && val >= INT32_MIN && errno != ERANGE && !*end);
  3615. f->defaultval.sint = val;
  3616. break;
  3617. }
  3618. case UPB_TYPE_ENUM: {
  3619. const upb_enumdef *e = f->sub.enumdef;
  3620. int32_t val;
  3621. CHK(upb_enumdef_ntoi(e, str, len, &val));
  3622. f->defaultval.sint = val;
  3623. break;
  3624. }
  3625. case UPB_TYPE_INT64: {
  3626. /* XXX: Need to write our own strtoll, since it's not available in c89. */
  3627. int64_t val = strtol(str, &end, 0);
  3628. CHK(val <= INT64_MAX && val >= INT64_MIN && errno != ERANGE && !*end);
  3629. f->defaultval.sint = val;
  3630. break;
  3631. }
  3632. case UPB_TYPE_UINT32: {
  3633. unsigned long val = strtoul(str, &end, 0);
  3634. CHK(val <= UINT32_MAX && errno != ERANGE && !*end);
  3635. f->defaultval.uint = val;
  3636. break;
  3637. }
  3638. case UPB_TYPE_UINT64: {
  3639. /* XXX: Need to write our own strtoull, since it's not available in c89. */
  3640. uint64_t val = strtoul(str, &end, 0);
  3641. CHK(val <= UINT64_MAX && errno != ERANGE && !*end);
  3642. f->defaultval.uint = val;
  3643. break;
  3644. }
  3645. case UPB_TYPE_DOUBLE: {
  3646. double val = strtod(str, &end);
  3647. CHK(errno != ERANGE && !*end);
  3648. f->defaultval.dbl = val;
  3649. break;
  3650. }
  3651. case UPB_TYPE_FLOAT: {
  3652. /* XXX: Need to write our own strtof, since it's not available in c89. */
  3653. float val = strtod(str, &end);
  3654. CHK(errno != ERANGE && !*end);
  3655. f->defaultval.flt = val;
  3656. break;
  3657. }
  3658. case UPB_TYPE_BOOL: {
  3659. if (streql2(str, len, "false")) {
  3660. f->defaultval.boolean = false;
  3661. } else if (streql2(str, len, "true")) {
  3662. f->defaultval.boolean = true;
  3663. } else {
  3664. return false;
  3665. }
  3666. break;
  3667. }
  3668. case UPB_TYPE_STRING:
  3669. f->defaultval.str = newstr(ctx->alloc, str, len);
  3670. break;
  3671. case UPB_TYPE_BYTES:
  3672. /* XXX: need to interpret the C-escaped value. */
  3673. f->defaultval.str = newstr(ctx->alloc, str, len);
  3674. break;
  3675. case UPB_TYPE_MESSAGE:
  3676. /* Should not have a default value. */
  3677. return false;
  3678. }
  3679. return true;
  3680. }
  3681. static void set_default_default(const symtab_addctx *ctx, upb_fielddef *f) {
  3682. switch (upb_fielddef_type(f)) {
  3683. case UPB_TYPE_INT32:
  3684. case UPB_TYPE_INT64:
  3685. case UPB_TYPE_ENUM:
  3686. f->defaultval.sint = 0;
  3687. break;
  3688. case UPB_TYPE_UINT64:
  3689. case UPB_TYPE_UINT32:
  3690. f->defaultval.uint = 0;
  3691. break;
  3692. case UPB_TYPE_DOUBLE:
  3693. case UPB_TYPE_FLOAT:
  3694. f->defaultval.dbl = 0;
  3695. break;
  3696. case UPB_TYPE_STRING:
  3697. case UPB_TYPE_BYTES:
  3698. f->defaultval.str = newstr(ctx->alloc, NULL, 0);
  3699. break;
  3700. case UPB_TYPE_BOOL:
  3701. f->defaultval.boolean = false;
  3702. break;
  3703. case UPB_TYPE_MESSAGE:
  3704. break;
  3705. }
  3706. }
  3707. static bool create_fielddef(
  3708. const symtab_addctx *ctx, const char *prefix, upb_msgdef *m,
  3709. const google_protobuf_FieldDescriptorProto *field_proto) {
  3710. upb_alloc *alloc = ctx->alloc;
  3711. upb_fielddef *f;
  3712. const google_protobuf_FieldOptions *options;
  3713. upb_strview name;
  3714. const char *full_name;
  3715. const char *json_name;
  3716. const char *shortname;
  3717. uint32_t field_number;
  3718. if (!google_protobuf_FieldDescriptorProto_has_name(field_proto)) {
  3719. upb_status_seterrmsg(ctx->status, "field has no name");
  3720. return false;
  3721. }
  3722. name = google_protobuf_FieldDescriptorProto_name(field_proto);
  3723. CHK(upb_isident(name, false, ctx->status));
  3724. full_name = makefullname(ctx, prefix, name);
  3725. shortname = shortdefname(full_name);
  3726. if (google_protobuf_FieldDescriptorProto_has_json_name(field_proto)) {
  3727. json_name = strviewdup(
  3728. ctx, google_protobuf_FieldDescriptorProto_json_name(field_proto));
  3729. } else {
  3730. json_name = makejsonname(shortname, ctx->alloc);
  3731. }
  3732. field_number = google_protobuf_FieldDescriptorProto_number(field_proto);
  3733. if (field_number == 0 || field_number > UPB_MAX_FIELDNUMBER) {
  3734. upb_status_seterrf(ctx->status, "invalid field number (%u)", field_number);
  3735. return false;
  3736. }
  3737. if (m) {
  3738. /* direct message field. */
  3739. upb_value v, field_v, json_v;
  3740. size_t json_size;
  3741. f = (upb_fielddef*)&m->fields[m->field_count++];
  3742. f->msgdef = m;
  3743. f->is_extension_ = false;
  3744. if (upb_strtable_lookup(&m->ntof, shortname, NULL)) {
  3745. upb_status_seterrf(ctx->status, "duplicate field name (%s)", shortname);
  3746. return false;
  3747. }
  3748. if (upb_strtable_lookup(&m->ntof, json_name, NULL)) {
  3749. upb_status_seterrf(ctx->status, "duplicate json_name (%s)", json_name);
  3750. return false;
  3751. }
  3752. if (upb_inttable_lookup(&m->itof, field_number, NULL)) {
  3753. upb_status_seterrf(ctx->status, "duplicate field number (%u)",
  3754. field_number);
  3755. return false;
  3756. }
  3757. field_v = pack_def(f, UPB_DEFTYPE_FIELD);
  3758. json_v = pack_def(f, UPB_DEFTYPE_FIELD_JSONNAME);
  3759. v = upb_value_constptr(f);
  3760. json_size = strlen(json_name);
  3761. CHK_OOM(
  3762. upb_strtable_insert3(&m->ntof, name.data, name.size, field_v, alloc));
  3763. CHK_OOM(upb_inttable_insert2(&m->itof, field_number, v, alloc));
  3764. if (strcmp(shortname, json_name) != 0) {
  3765. upb_strtable_insert3(&m->ntof, json_name, json_size, json_v, alloc);
  3766. }
  3767. if (ctx->layouts) {
  3768. const upb_msglayout_field *fields = m->layout->fields;
  3769. int count = m->layout->field_count;
  3770. bool found = false;
  3771. int i;
  3772. for (i = 0; i < count; i++) {
  3773. if (fields[i].number == field_number) {
  3774. f->layout_index = i;
  3775. found = true;
  3776. break;
  3777. }
  3778. }
  3779. UPB_ASSERT(found);
  3780. }
  3781. } else {
  3782. /* extension field. */
  3783. f = (upb_fielddef*)&ctx->file->exts[ctx->file->ext_count++];
  3784. f->is_extension_ = true;
  3785. CHK_OOM(symtab_add(ctx, full_name, pack_def(f, UPB_DEFTYPE_FIELD)));
  3786. }
  3787. f->full_name = full_name;
  3788. f->json_name = json_name;
  3789. f->file = ctx->file;
  3790. f->type_ = (int)google_protobuf_FieldDescriptorProto_type(field_proto);
  3791. f->label_ = (int)google_protobuf_FieldDescriptorProto_label(field_proto);
  3792. f->number_ = field_number;
  3793. f->oneof = NULL;
  3794. f->proto3_optional_ =
  3795. google_protobuf_FieldDescriptorProto_proto3_optional(field_proto);
  3796. /* We can't resolve the subdef or (in the case of extensions) the containing
  3797. * message yet, because it may not have been defined yet. We stash a pointer
  3798. * to the field_proto until later when we can properly resolve it. */
  3799. f->sub.unresolved = field_proto;
  3800. if (f->label_ == UPB_LABEL_REQUIRED && f->file->syntax == UPB_SYNTAX_PROTO3) {
  3801. upb_status_seterrf(ctx->status, "proto3 fields cannot be required (%s)",
  3802. f->full_name);
  3803. return false;
  3804. }
  3805. if (google_protobuf_FieldDescriptorProto_has_oneof_index(field_proto)) {
  3806. int oneof_index =
  3807. google_protobuf_FieldDescriptorProto_oneof_index(field_proto);
  3808. upb_oneofdef *oneof;
  3809. upb_value v = upb_value_constptr(f);
  3810. if (upb_fielddef_label(f) != UPB_LABEL_OPTIONAL) {
  3811. upb_status_seterrf(ctx->status,
  3812. "fields in oneof must have OPTIONAL label (%s)",
  3813. f->full_name);
  3814. return false;
  3815. }
  3816. if (!m) {
  3817. upb_status_seterrf(ctx->status,
  3818. "oneof_index provided for extension field (%s)",
  3819. f->full_name);
  3820. return false;
  3821. }
  3822. if (oneof_index >= m->oneof_count) {
  3823. upb_status_seterrf(ctx->status, "oneof_index out of range (%s)",
  3824. f->full_name);
  3825. return false;
  3826. }
  3827. oneof = (upb_oneofdef*)&m->oneofs[oneof_index];
  3828. f->oneof = oneof;
  3829. CHK(upb_inttable_insert2(&oneof->itof, f->number_, v, alloc));
  3830. CHK(upb_strtable_insert3(&oneof->ntof, name.data, name.size, v, alloc));
  3831. } else {
  3832. f->oneof = NULL;
  3833. }
  3834. if (google_protobuf_FieldDescriptorProto_has_options(field_proto)) {
  3835. options = google_protobuf_FieldDescriptorProto_options(field_proto);
  3836. f->lazy_ = google_protobuf_FieldOptions_lazy(options);
  3837. f->packed_ = google_protobuf_FieldOptions_packed(options);
  3838. } else {
  3839. f->lazy_ = false;
  3840. f->packed_ = false;
  3841. }
  3842. return true;
  3843. }
  3844. static bool create_enumdef(
  3845. const symtab_addctx *ctx, const char *prefix,
  3846. const google_protobuf_EnumDescriptorProto *enum_proto) {
  3847. upb_enumdef *e;
  3848. const google_protobuf_EnumValueDescriptorProto *const *values;
  3849. upb_strview name;
  3850. size_t i, n;
  3851. name = google_protobuf_EnumDescriptorProto_name(enum_proto);
  3852. CHK(upb_isident(name, false, ctx->status));
  3853. e = (upb_enumdef*)&ctx->file->enums[ctx->file->enum_count++];
  3854. e->full_name = makefullname(ctx, prefix, name);
  3855. CHK_OOM(symtab_add(ctx, e->full_name, pack_def(e, UPB_DEFTYPE_ENUM)));
  3856. CHK_OOM(upb_strtable_init2(&e->ntoi, UPB_CTYPE_INT32, ctx->alloc));
  3857. CHK_OOM(upb_inttable_init2(&e->iton, UPB_CTYPE_CSTR, ctx->alloc));
  3858. e->file = ctx->file;
  3859. e->defaultval = 0;
  3860. values = google_protobuf_EnumDescriptorProto_value(enum_proto, &n);
  3861. if (n == 0) {
  3862. upb_status_seterrf(ctx->status,
  3863. "enums must contain at least one value (%s)",
  3864. e->full_name);
  3865. return false;
  3866. }
  3867. for (i = 0; i < n; i++) {
  3868. const google_protobuf_EnumValueDescriptorProto *value = values[i];
  3869. upb_strview name = google_protobuf_EnumValueDescriptorProto_name(value);
  3870. char *name2 = strviewdup(ctx, name);
  3871. int32_t num = google_protobuf_EnumValueDescriptorProto_number(value);
  3872. upb_value v = upb_value_int32(num);
  3873. if (i == 0 && e->file->syntax == UPB_SYNTAX_PROTO3 && num != 0) {
  3874. upb_status_seterrf(ctx->status,
  3875. "for proto3, the first enum value must be zero (%s)",
  3876. e->full_name);
  3877. return false;
  3878. }
  3879. if (upb_strtable_lookup(&e->ntoi, name2, NULL)) {
  3880. upb_status_seterrf(ctx->status, "duplicate enum label '%s'", name2);
  3881. return false;
  3882. }
  3883. CHK_OOM(name2)
  3884. CHK_OOM(
  3885. upb_strtable_insert3(&e->ntoi, name2, strlen(name2), v, ctx->alloc));
  3886. if (!upb_inttable_lookup(&e->iton, num, NULL)) {
  3887. upb_value v = upb_value_cstr(name2);
  3888. CHK_OOM(upb_inttable_insert2(&e->iton, num, v, ctx->alloc));
  3889. }
  3890. }
  3891. upb_inttable_compact2(&e->iton, ctx->alloc);
  3892. return true;
  3893. }
  3894. static bool create_msgdef(symtab_addctx *ctx, const char *prefix,
  3895. const google_protobuf_DescriptorProto *msg_proto) {
  3896. upb_msgdef *m;
  3897. const google_protobuf_MessageOptions *options;
  3898. const google_protobuf_OneofDescriptorProto *const *oneofs;
  3899. const google_protobuf_FieldDescriptorProto *const *fields;
  3900. const google_protobuf_EnumDescriptorProto *const *enums;
  3901. const google_protobuf_DescriptorProto *const *msgs;
  3902. size_t i, n;
  3903. upb_strview name;
  3904. name = google_protobuf_DescriptorProto_name(msg_proto);
  3905. CHK(upb_isident(name, false, ctx->status));
  3906. m = (upb_msgdef*)&ctx->file->msgs[ctx->file->msg_count++];
  3907. m->full_name = makefullname(ctx, prefix, name);
  3908. CHK_OOM(symtab_add(ctx, m->full_name, pack_def(m, UPB_DEFTYPE_MSG)));
  3909. CHK_OOM(upb_inttable_init2(&m->itof, UPB_CTYPE_CONSTPTR, ctx->alloc));
  3910. CHK_OOM(upb_strtable_init2(&m->ntof, UPB_CTYPE_CONSTPTR, ctx->alloc));
  3911. m->file = ctx->file;
  3912. m->map_entry = false;
  3913. options = google_protobuf_DescriptorProto_options(msg_proto);
  3914. if (options) {
  3915. m->map_entry = google_protobuf_MessageOptions_map_entry(options);
  3916. }
  3917. if (ctx->layouts) {
  3918. m->layout = *ctx->layouts;
  3919. ctx->layouts++;
  3920. } else {
  3921. /* Allocate now (to allow cross-linking), populate later. */
  3922. m->layout = upb_malloc(ctx->alloc, sizeof(*m->layout));
  3923. }
  3924. oneofs = google_protobuf_DescriptorProto_oneof_decl(msg_proto, &n);
  3925. m->oneof_count = 0;
  3926. m->oneofs = upb_malloc(ctx->alloc, sizeof(*m->oneofs) * n);
  3927. for (i = 0; i < n; i++) {
  3928. CHK(create_oneofdef(ctx, m, oneofs[i]));
  3929. }
  3930. fields = google_protobuf_DescriptorProto_field(msg_proto, &n);
  3931. m->field_count = 0;
  3932. m->fields = upb_malloc(ctx->alloc, sizeof(*m->fields) * n);
  3933. for (i = 0; i < n; i++) {
  3934. CHK(create_fielddef(ctx, m->full_name, m, fields[i]));
  3935. }
  3936. CHK(assign_msg_indices(m, ctx->status));
  3937. CHK(check_oneofs(m, ctx->status));
  3938. assign_msg_wellknowntype(m);
  3939. upb_inttable_compact2(&m->itof, ctx->alloc);
  3940. /* This message is built. Now build nested messages and enums. */
  3941. enums = google_protobuf_DescriptorProto_enum_type(msg_proto, &n);
  3942. for (i = 0; i < n; i++) {
  3943. CHK(create_enumdef(ctx, m->full_name, enums[i]));
  3944. }
  3945. msgs = google_protobuf_DescriptorProto_nested_type(msg_proto, &n);
  3946. for (i = 0; i < n; i++) {
  3947. CHK(create_msgdef(ctx, m->full_name, msgs[i]));
  3948. }
  3949. return true;
  3950. }
  3951. typedef struct {
  3952. int msg_count;
  3953. int enum_count;
  3954. int ext_count;
  3955. } decl_counts;
  3956. static void count_types_in_msg(const google_protobuf_DescriptorProto *msg_proto,
  3957. decl_counts *counts) {
  3958. const google_protobuf_DescriptorProto *const *msgs;
  3959. size_t i, n;
  3960. counts->msg_count++;
  3961. msgs = google_protobuf_DescriptorProto_nested_type(msg_proto, &n);
  3962. for (i = 0; i < n; i++) {
  3963. count_types_in_msg(msgs[i], counts);
  3964. }
  3965. google_protobuf_DescriptorProto_enum_type(msg_proto, &n);
  3966. counts->enum_count += n;
  3967. google_protobuf_DescriptorProto_extension(msg_proto, &n);
  3968. counts->ext_count += n;
  3969. }
  3970. static void count_types_in_file(
  3971. const google_protobuf_FileDescriptorProto *file_proto,
  3972. decl_counts *counts) {
  3973. const google_protobuf_DescriptorProto *const *msgs;
  3974. size_t i, n;
  3975. msgs = google_protobuf_FileDescriptorProto_message_type(file_proto, &n);
  3976. for (i = 0; i < n; i++) {
  3977. count_types_in_msg(msgs[i], counts);
  3978. }
  3979. google_protobuf_FileDescriptorProto_enum_type(file_proto, &n);
  3980. counts->enum_count += n;
  3981. google_protobuf_FileDescriptorProto_extension(file_proto, &n);
  3982. counts->ext_count += n;
  3983. }
  3984. static bool resolve_fielddef(const symtab_addctx *ctx, const char *prefix,
  3985. upb_fielddef *f) {
  3986. upb_strview name;
  3987. const google_protobuf_FieldDescriptorProto *field_proto = f->sub.unresolved;
  3988. if (f->is_extension_) {
  3989. if (!google_protobuf_FieldDescriptorProto_has_extendee(field_proto)) {
  3990. upb_status_seterrf(ctx->status,
  3991. "extension for field '%s' had no extendee",
  3992. f->full_name);
  3993. return false;
  3994. }
  3995. name = google_protobuf_FieldDescriptorProto_extendee(field_proto);
  3996. f->msgdef = symtab_resolve(ctx, f, prefix, name, UPB_DEFTYPE_MSG);
  3997. CHK(f->msgdef);
  3998. }
  3999. if ((upb_fielddef_issubmsg(f) || f->type_ == UPB_DESCRIPTOR_TYPE_ENUM) &&
  4000. !google_protobuf_FieldDescriptorProto_has_type_name(field_proto)) {
  4001. upb_status_seterrf(ctx->status, "field '%s' is missing type name",
  4002. f->full_name);
  4003. return false;
  4004. }
  4005. name = google_protobuf_FieldDescriptorProto_type_name(field_proto);
  4006. if (upb_fielddef_issubmsg(f)) {
  4007. f->sub.msgdef = symtab_resolve(ctx, f, prefix, name, UPB_DEFTYPE_MSG);
  4008. CHK(f->sub.msgdef);
  4009. } else if (f->type_ == UPB_DESCRIPTOR_TYPE_ENUM) {
  4010. f->sub.enumdef = symtab_resolve(ctx, f, prefix, name, UPB_DEFTYPE_ENUM);
  4011. CHK(f->sub.enumdef);
  4012. }
  4013. /* Have to delay resolving of the default value until now because of the enum
  4014. * case, since enum defaults are specified with a label. */
  4015. if (google_protobuf_FieldDescriptorProto_has_default_value(field_proto)) {
  4016. upb_strview defaultval =
  4017. google_protobuf_FieldDescriptorProto_default_value(field_proto);
  4018. if (f->file->syntax == UPB_SYNTAX_PROTO3) {
  4019. upb_status_seterrf(ctx->status,
  4020. "proto3 fields cannot have explicit defaults (%s)",
  4021. f->full_name);
  4022. return false;
  4023. }
  4024. if (upb_fielddef_issubmsg(f)) {
  4025. upb_status_seterrf(ctx->status,
  4026. "message fields cannot have explicit defaults (%s)",
  4027. f->full_name);
  4028. return false;
  4029. }
  4030. if (!parse_default(ctx, defaultval.data, defaultval.size, f)) {
  4031. upb_status_seterrf(ctx->status,
  4032. "couldn't parse default '" UPB_STRVIEW_FORMAT
  4033. "' for field (%s)",
  4034. UPB_STRVIEW_ARGS(defaultval), f->full_name);
  4035. return false;
  4036. }
  4037. } else {
  4038. set_default_default(ctx, f);
  4039. }
  4040. return true;
  4041. }
  4042. static bool build_filedef(
  4043. symtab_addctx *ctx, upb_filedef *file,
  4044. const google_protobuf_FileDescriptorProto *file_proto) {
  4045. upb_alloc *alloc = ctx->alloc;
  4046. const google_protobuf_FileOptions *file_options_proto;
  4047. const google_protobuf_DescriptorProto *const *msgs;
  4048. const google_protobuf_EnumDescriptorProto *const *enums;
  4049. const google_protobuf_FieldDescriptorProto *const *exts;
  4050. const upb_strview* strs;
  4051. size_t i, n;
  4052. decl_counts counts = {0};
  4053. count_types_in_file(file_proto, &counts);
  4054. file->msgs = upb_malloc(alloc, sizeof(*file->msgs) * counts.msg_count);
  4055. file->enums = upb_malloc(alloc, sizeof(*file->enums) * counts.enum_count);
  4056. file->exts = upb_malloc(alloc, sizeof(*file->exts) * counts.ext_count);
  4057. CHK_OOM(counts.msg_count == 0 || file->msgs);
  4058. CHK_OOM(counts.enum_count == 0 || file->enums);
  4059. CHK_OOM(counts.ext_count == 0 || file->exts);
  4060. /* We increment these as defs are added. */
  4061. file->msg_count = 0;
  4062. file->enum_count = 0;
  4063. file->ext_count = 0;
  4064. if (!google_protobuf_FileDescriptorProto_has_name(file_proto)) {
  4065. upb_status_seterrmsg(ctx->status, "File has no name");
  4066. return false;
  4067. }
  4068. file->name =
  4069. strviewdup(ctx, google_protobuf_FileDescriptorProto_name(file_proto));
  4070. file->phpprefix = NULL;
  4071. file->phpnamespace = NULL;
  4072. if (google_protobuf_FileDescriptorProto_has_package(file_proto)) {
  4073. upb_strview package =
  4074. google_protobuf_FileDescriptorProto_package(file_proto);
  4075. CHK(upb_isident(package, true, ctx->status));
  4076. file->package = strviewdup(ctx, package);
  4077. } else {
  4078. file->package = NULL;
  4079. }
  4080. if (google_protobuf_FileDescriptorProto_has_syntax(file_proto)) {
  4081. upb_strview syntax =
  4082. google_protobuf_FileDescriptorProto_syntax(file_proto);
  4083. if (streql_view(syntax, "proto2")) {
  4084. file->syntax = UPB_SYNTAX_PROTO2;
  4085. } else if (streql_view(syntax, "proto3")) {
  4086. file->syntax = UPB_SYNTAX_PROTO3;
  4087. } else {
  4088. upb_status_seterrf(ctx->status, "Invalid syntax '" UPB_STRVIEW_FORMAT "'",
  4089. UPB_STRVIEW_ARGS(syntax));
  4090. return false;
  4091. }
  4092. } else {
  4093. file->syntax = UPB_SYNTAX_PROTO2;
  4094. }
  4095. /* Read options. */
  4096. file_options_proto = google_protobuf_FileDescriptorProto_options(file_proto);
  4097. if (file_options_proto) {
  4098. if (google_protobuf_FileOptions_has_php_class_prefix(file_options_proto)) {
  4099. file->phpprefix = strviewdup(
  4100. ctx,
  4101. google_protobuf_FileOptions_php_class_prefix(file_options_proto));
  4102. }
  4103. if (google_protobuf_FileOptions_has_php_namespace(file_options_proto)) {
  4104. file->phpnamespace = strviewdup(
  4105. ctx, google_protobuf_FileOptions_php_namespace(file_options_proto));
  4106. }
  4107. }
  4108. /* Verify dependencies. */
  4109. strs = google_protobuf_FileDescriptorProto_dependency(file_proto, &n);
  4110. file->deps = upb_malloc(alloc, sizeof(*file->deps) * n) ;
  4111. CHK_OOM(n == 0 || file->deps);
  4112. for (i = 0; i < n; i++) {
  4113. upb_strview dep_name = strs[i];
  4114. upb_value v;
  4115. if (!upb_strtable_lookup2(&ctx->symtab->files, dep_name.data,
  4116. dep_name.size, &v)) {
  4117. upb_status_seterrf(ctx->status,
  4118. "Depends on file '" UPB_STRVIEW_FORMAT
  4119. "', but it has not been loaded",
  4120. UPB_STRVIEW_ARGS(dep_name));
  4121. return false;
  4122. }
  4123. file->deps[i] = upb_value_getconstptr(v);
  4124. }
  4125. /* Create messages. */
  4126. msgs = google_protobuf_FileDescriptorProto_message_type(file_proto, &n);
  4127. for (i = 0; i < n; i++) {
  4128. CHK(create_msgdef(ctx, file->package, msgs[i]));
  4129. }
  4130. /* Create enums. */
  4131. enums = google_protobuf_FileDescriptorProto_enum_type(file_proto, &n);
  4132. for (i = 0; i < n; i++) {
  4133. CHK(create_enumdef(ctx, file->package, enums[i]));
  4134. }
  4135. /* Create extensions. */
  4136. exts = google_protobuf_FileDescriptorProto_extension(file_proto, &n);
  4137. file->exts = upb_malloc(alloc, sizeof(*file->exts) * n);
  4138. CHK_OOM(n == 0 || file->exts);
  4139. for (i = 0; i < n; i++) {
  4140. CHK(create_fielddef(ctx, file->package, NULL, exts[i]));
  4141. }
  4142. /* Now that all names are in the table, build layouts and resolve refs. */
  4143. for (i = 0; i < file->ext_count; i++) {
  4144. CHK(resolve_fielddef(ctx, file->package, (upb_fielddef*)&file->exts[i]));
  4145. }
  4146. for (i = 0; i < file->msg_count; i++) {
  4147. const upb_msgdef *m = &file->msgs[i];
  4148. int j;
  4149. for (j = 0; j < m->field_count; j++) {
  4150. CHK(resolve_fielddef(ctx, m->full_name, (upb_fielddef*)&m->fields[j]));
  4151. }
  4152. }
  4153. if (!ctx->layouts) {
  4154. for (i = 0; i < file->msg_count; i++) {
  4155. const upb_msgdef *m = &file->msgs[i];
  4156. make_layout(ctx->symtab, m);
  4157. }
  4158. }
  4159. return true;
  4160. }
  4161. static bool upb_symtab_addtotabs(upb_symtab *s, symtab_addctx *ctx,
  4162. upb_status *status) {
  4163. const upb_filedef *file = ctx->file;
  4164. upb_alloc *alloc = upb_arena_alloc(s->arena);
  4165. upb_strtable_iter iter;
  4166. CHK_OOM(upb_strtable_insert3(&s->files, file->name, strlen(file->name),
  4167. upb_value_constptr(file), alloc));
  4168. upb_strtable_begin(&iter, ctx->addtab);
  4169. for (; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
  4170. upb_strview key = upb_strtable_iter_key(&iter);
  4171. upb_value value = upb_strtable_iter_value(&iter);
  4172. CHK_OOM(upb_strtable_insert3(&s->syms, key.data, key.size, value, alloc));
  4173. }
  4174. return true;
  4175. }
  4176. /* upb_filedef ****************************************************************/
  4177. const char *upb_filedef_name(const upb_filedef *f) {
  4178. return f->name;
  4179. }
  4180. const char *upb_filedef_package(const upb_filedef *f) {
  4181. return f->package;
  4182. }
  4183. const char *upb_filedef_phpprefix(const upb_filedef *f) {
  4184. return f->phpprefix;
  4185. }
  4186. const char *upb_filedef_phpnamespace(const upb_filedef *f) {
  4187. return f->phpnamespace;
  4188. }
  4189. upb_syntax_t upb_filedef_syntax(const upb_filedef *f) {
  4190. return f->syntax;
  4191. }
  4192. int upb_filedef_msgcount(const upb_filedef *f) {
  4193. return f->msg_count;
  4194. }
  4195. int upb_filedef_depcount(const upb_filedef *f) {
  4196. return f->dep_count;
  4197. }
  4198. int upb_filedef_enumcount(const upb_filedef *f) {
  4199. return f->enum_count;
  4200. }
  4201. const upb_filedef *upb_filedef_dep(const upb_filedef *f, int i) {
  4202. return i < 0 || i >= f->dep_count ? NULL : f->deps[i];
  4203. }
  4204. const upb_msgdef *upb_filedef_msg(const upb_filedef *f, int i) {
  4205. return i < 0 || i >= f->msg_count ? NULL : &f->msgs[i];
  4206. }
  4207. const upb_enumdef *upb_filedef_enum(const upb_filedef *f, int i) {
  4208. return i < 0 || i >= f->enum_count ? NULL : &f->enums[i];
  4209. }
  4210. void upb_symtab_free(upb_symtab *s) {
  4211. upb_arena_free(s->arena);
  4212. upb_gfree(s);
  4213. }
  4214. upb_symtab *upb_symtab_new(void) {
  4215. upb_symtab *s = upb_gmalloc(sizeof(*s));
  4216. upb_alloc *alloc;
  4217. if (!s) {
  4218. return NULL;
  4219. }
  4220. s->arena = upb_arena_new();
  4221. alloc = upb_arena_alloc(s->arena);
  4222. if (!upb_strtable_init2(&s->syms, UPB_CTYPE_CONSTPTR, alloc) ||
  4223. !upb_strtable_init2(&s->files, UPB_CTYPE_CONSTPTR, alloc)) {
  4224. upb_arena_free(s->arena);
  4225. upb_gfree(s);
  4226. s = NULL;
  4227. }
  4228. return s;
  4229. }
  4230. const upb_msgdef *upb_symtab_lookupmsg(const upb_symtab *s, const char *sym) {
  4231. upb_value v;
  4232. return upb_strtable_lookup(&s->syms, sym, &v) ?
  4233. unpack_def(v, UPB_DEFTYPE_MSG) : NULL;
  4234. }
  4235. const upb_msgdef *upb_symtab_lookupmsg2(const upb_symtab *s, const char *sym,
  4236. size_t len) {
  4237. upb_value v;
  4238. return upb_strtable_lookup2(&s->syms, sym, len, &v) ?
  4239. unpack_def(v, UPB_DEFTYPE_MSG) : NULL;
  4240. }
  4241. const upb_enumdef *upb_symtab_lookupenum(const upb_symtab *s, const char *sym) {
  4242. upb_value v;
  4243. return upb_strtable_lookup(&s->syms, sym, &v) ?
  4244. unpack_def(v, UPB_DEFTYPE_ENUM) : NULL;
  4245. }
  4246. const upb_filedef *upb_symtab_lookupfile(const upb_symtab *s, const char *name) {
  4247. upb_value v;
  4248. return upb_strtable_lookup(&s->files, name, &v) ? upb_value_getconstptr(v)
  4249. : NULL;
  4250. }
  4251. const upb_filedef *upb_symtab_lookupfile2(
  4252. const upb_symtab *s, const char *name, size_t len) {
  4253. upb_value v;
  4254. return upb_strtable_lookup2(&s->files, name, len, &v) ?
  4255. upb_value_getconstptr(v) : NULL;
  4256. }
  4257. int upb_symtab_filecount(const upb_symtab *s) {
  4258. return (int)upb_strtable_count(&s->files);
  4259. }
  4260. static const upb_filedef *_upb_symtab_addfile(
  4261. upb_symtab *s, const google_protobuf_FileDescriptorProto *file_proto,
  4262. const upb_msglayout **layouts, upb_status *status) {
  4263. upb_arena *tmparena = upb_arena_new();
  4264. upb_strtable addtab;
  4265. upb_alloc *alloc = upb_arena_alloc(s->arena);
  4266. upb_filedef *file = upb_malloc(alloc, sizeof(*file));
  4267. bool ok;
  4268. symtab_addctx ctx;
  4269. ctx.file = file;
  4270. ctx.symtab = s;
  4271. ctx.alloc = alloc;
  4272. ctx.tmp = upb_arena_alloc(tmparena);
  4273. ctx.addtab = &addtab;
  4274. ctx.layouts = layouts;
  4275. ctx.status = status;
  4276. ok = file &&
  4277. upb_strtable_init2(&addtab, UPB_CTYPE_CONSTPTR, ctx.tmp) &&
  4278. build_filedef(&ctx, file, file_proto) &&
  4279. upb_symtab_addtotabs(s, &ctx, status);
  4280. upb_arena_free(tmparena);
  4281. return ok ? file : NULL;
  4282. }
  4283. const upb_filedef *upb_symtab_addfile(
  4284. upb_symtab *s, const google_protobuf_FileDescriptorProto *file_proto,
  4285. upb_status *status) {
  4286. return _upb_symtab_addfile(s, file_proto, NULL, status);
  4287. }
  4288. /* Include here since we want most of this file to be stdio-free. */
  4289. #include <stdio.h>
  4290. bool _upb_symtab_loaddefinit(upb_symtab *s, const upb_def_init *init) {
  4291. /* Since this function should never fail (it would indicate a bug in upb) we
  4292. * print errors to stderr instead of returning error status to the user. */
  4293. upb_def_init **deps = init->deps;
  4294. google_protobuf_FileDescriptorProto *file;
  4295. upb_arena *arena;
  4296. upb_status status;
  4297. upb_status_clear(&status);
  4298. if (upb_strtable_lookup(&s->files, init->filename, NULL)) {
  4299. return true;
  4300. }
  4301. arena = upb_arena_new();
  4302. for (; *deps; deps++) {
  4303. if (!_upb_symtab_loaddefinit(s, *deps)) goto err;
  4304. }
  4305. file = google_protobuf_FileDescriptorProto_parse(
  4306. init->descriptor.data, init->descriptor.size, arena);
  4307. if (!file) {
  4308. upb_status_seterrf(
  4309. &status,
  4310. "Failed to parse compiled-in descriptor for file '%s'. This should "
  4311. "never happen.",
  4312. init->filename);
  4313. goto err;
  4314. }
  4315. if (!_upb_symtab_addfile(s, file, init->layouts, &status)) goto err;
  4316. upb_arena_free(arena);
  4317. return true;
  4318. err:
  4319. fprintf(stderr, "Error loading compiled-in descriptor: %s\n",
  4320. upb_status_errmsg(&status));
  4321. upb_arena_free(arena);
  4322. return false;
  4323. }
  4324. #undef CHK
  4325. #undef CHK_OOM
  4326. #include <string.h>
  4327. static char field_size[] = {
  4328. 0,/* 0 */
  4329. 8, /* UPB_DESCRIPTOR_TYPE_DOUBLE */
  4330. 4, /* UPB_DESCRIPTOR_TYPE_FLOAT */
  4331. 8, /* UPB_DESCRIPTOR_TYPE_INT64 */
  4332. 8, /* UPB_DESCRIPTOR_TYPE_UINT64 */
  4333. 4, /* UPB_DESCRIPTOR_TYPE_INT32 */
  4334. 8, /* UPB_DESCRIPTOR_TYPE_FIXED64 */
  4335. 4, /* UPB_DESCRIPTOR_TYPE_FIXED32 */
  4336. 1, /* UPB_DESCRIPTOR_TYPE_BOOL */
  4337. sizeof(upb_strview), /* UPB_DESCRIPTOR_TYPE_STRING */
  4338. sizeof(void*), /* UPB_DESCRIPTOR_TYPE_GROUP */
  4339. sizeof(void*), /* UPB_DESCRIPTOR_TYPE_MESSAGE */
  4340. sizeof(upb_strview), /* UPB_DESCRIPTOR_TYPE_BYTES */
  4341. 4, /* UPB_DESCRIPTOR_TYPE_UINT32 */
  4342. 4, /* UPB_DESCRIPTOR_TYPE_ENUM */
  4343. 4, /* UPB_DESCRIPTOR_TYPE_SFIXED32 */
  4344. 8, /* UPB_DESCRIPTOR_TYPE_SFIXED64 */
  4345. 4, /* UPB_DESCRIPTOR_TYPE_SINT32 */
  4346. 8, /* UPB_DESCRIPTOR_TYPE_SINT64 */
  4347. };
  4348. /* Strings/bytes are special-cased in maps. */
  4349. static char _upb_fieldtype_to_mapsize[12] = {
  4350. 0,
  4351. 1, /* UPB_TYPE_BOOL */
  4352. 4, /* UPB_TYPE_FLOAT */
  4353. 4, /* UPB_TYPE_INT32 */
  4354. 4, /* UPB_TYPE_UINT32 */
  4355. 4, /* UPB_TYPE_ENUM */
  4356. sizeof(void*), /* UPB_TYPE_MESSAGE */
  4357. 8, /* UPB_TYPE_DOUBLE */
  4358. 8, /* UPB_TYPE_INT64 */
  4359. 8, /* UPB_TYPE_UINT64 */
  4360. 0, /* UPB_TYPE_STRING */
  4361. 0, /* UPB_TYPE_BYTES */
  4362. };
  4363. /** upb_msg *******************************************************************/
  4364. upb_msg *upb_msg_new(const upb_msgdef *m, upb_arena *a) {
  4365. return _upb_msg_new(upb_msgdef_layout(m), a);
  4366. }
  4367. static bool in_oneof(const upb_msglayout_field *field) {
  4368. return field->presence < 0;
  4369. }
  4370. static uint32_t *oneofcase(const upb_msg *msg,
  4371. const upb_msglayout_field *field) {
  4372. UPB_ASSERT(in_oneof(field));
  4373. return UPB_PTR_AT(msg, -field->presence, uint32_t);
  4374. }
  4375. static upb_msgval _upb_msg_getraw(const upb_msg *msg, const upb_fielddef *f) {
  4376. const upb_msglayout_field *field = upb_fielddef_layout(f);
  4377. const char *mem = UPB_PTR_AT(msg, field->offset, char);
  4378. upb_msgval val = {0};
  4379. int size = upb_fielddef_isseq(f) ? sizeof(void *)
  4380. : field_size[field->descriptortype];
  4381. memcpy(&val, mem, size);
  4382. return val;
  4383. }
  4384. bool upb_msg_has(const upb_msg *msg, const upb_fielddef *f) {
  4385. const upb_msglayout_field *field = upb_fielddef_layout(f);
  4386. if (in_oneof(field)) {
  4387. return *oneofcase(msg, field) == field->number;
  4388. } else if (field->presence > 0) {
  4389. uint32_t hasbit = field->presence;
  4390. return *UPB_PTR_AT(msg, hasbit / 8, uint8_t) & (1 << (hasbit % 8));
  4391. } else {
  4392. UPB_ASSERT(field->descriptortype == UPB_DESCRIPTOR_TYPE_MESSAGE ||
  4393. field->descriptortype == UPB_DESCRIPTOR_TYPE_GROUP);
  4394. return _upb_msg_getraw(msg, f).msg_val != NULL;
  4395. }
  4396. }
  4397. bool upb_msg_hasoneof(const upb_msg *msg, const upb_oneofdef *o) {
  4398. upb_oneof_iter i;
  4399. const upb_fielddef *f;
  4400. const upb_msglayout_field *field;
  4401. upb_oneof_begin(&i, o);
  4402. if (upb_oneof_done(&i)) return false;
  4403. f = upb_oneof_iter_field(&i);
  4404. field = upb_fielddef_layout(f);
  4405. return *oneofcase(msg, field) != 0;
  4406. }
  4407. upb_msgval upb_msg_get(const upb_msg *msg, const upb_fielddef *f) {
  4408. if (!upb_fielddef_haspresence(f) || upb_msg_has(msg, f)) {
  4409. return _upb_msg_getraw(msg, f);
  4410. } else {
  4411. /* TODO(haberman): change upb_fielddef to not require this switch(). */
  4412. upb_msgval val = {0};
  4413. switch (upb_fielddef_type(f)) {
  4414. case UPB_TYPE_INT32:
  4415. case UPB_TYPE_ENUM:
  4416. val.int32_val = upb_fielddef_defaultint32(f);
  4417. break;
  4418. case UPB_TYPE_INT64:
  4419. val.int64_val = upb_fielddef_defaultint64(f);
  4420. break;
  4421. case UPB_TYPE_UINT32:
  4422. val.uint32_val = upb_fielddef_defaultuint32(f);
  4423. break;
  4424. case UPB_TYPE_UINT64:
  4425. val.uint64_val = upb_fielddef_defaultuint64(f);
  4426. break;
  4427. case UPB_TYPE_FLOAT:
  4428. val.float_val = upb_fielddef_defaultfloat(f);
  4429. break;
  4430. case UPB_TYPE_DOUBLE:
  4431. val.double_val = upb_fielddef_defaultdouble(f);
  4432. break;
  4433. case UPB_TYPE_BOOL:
  4434. val.double_val = upb_fielddef_defaultbool(f);
  4435. break;
  4436. case UPB_TYPE_STRING:
  4437. case UPB_TYPE_BYTES:
  4438. val.str_val.data = upb_fielddef_defaultstr(f, &val.str_val.size);
  4439. break;
  4440. case UPB_TYPE_MESSAGE:
  4441. val.msg_val = NULL;
  4442. break;
  4443. }
  4444. return val;
  4445. }
  4446. }
  4447. upb_mutmsgval upb_msg_mutable(upb_msg *msg, const upb_fielddef *f,
  4448. upb_arena *a) {
  4449. const upb_msglayout_field *field = upb_fielddef_layout(f);
  4450. upb_mutmsgval ret;
  4451. char *mem = UPB_PTR_AT(msg, field->offset, char);
  4452. bool wrong_oneof = in_oneof(field) && *oneofcase(msg, field) != field->number;
  4453. memcpy(&ret, mem, sizeof(void*));
  4454. if (a && (!ret.msg || wrong_oneof)) {
  4455. if (upb_fielddef_ismap(f)) {
  4456. const upb_msgdef *entry = upb_fielddef_msgsubdef(f);
  4457. const upb_fielddef *key = upb_msgdef_itof(entry, UPB_MAPENTRY_KEY);
  4458. const upb_fielddef *value = upb_msgdef_itof(entry, UPB_MAPENTRY_VALUE);
  4459. ret.map = upb_map_new(a, upb_fielddef_type(key), upb_fielddef_type(value));
  4460. } else if (upb_fielddef_isseq(f)) {
  4461. ret.array = upb_array_new(a, upb_fielddef_type(f));
  4462. } else {
  4463. UPB_ASSERT(upb_fielddef_issubmsg(f));
  4464. ret.msg = upb_msg_new(upb_fielddef_msgsubdef(f), a);
  4465. }
  4466. memcpy(mem, &ret, sizeof(void*));
  4467. if (wrong_oneof) {
  4468. *oneofcase(msg, field) = field->number;
  4469. }
  4470. }
  4471. return ret;
  4472. }
  4473. void upb_msg_set(upb_msg *msg, const upb_fielddef *f, upb_msgval val,
  4474. upb_arena *a) {
  4475. const upb_msglayout_field *field = upb_fielddef_layout(f);
  4476. char *mem = UPB_PTR_AT(msg, field->offset, char);
  4477. int size = upb_fielddef_isseq(f) ? sizeof(void *)
  4478. : field_size[field->descriptortype];
  4479. memcpy(mem, &val, size);
  4480. if (in_oneof(field)) {
  4481. *oneofcase(msg, field) = field->number;
  4482. }
  4483. }
  4484. bool upb_msg_next(const upb_msg *msg, const upb_msgdef *m,
  4485. const upb_symtab *ext_pool, const upb_fielddef **out_f,
  4486. upb_msgval *out_val, size_t *iter) {
  4487. size_t i = *iter;
  4488. const upb_msgval zero = {0};
  4489. const upb_fielddef *f;
  4490. while ((f = _upb_msgdef_field(m, (int)++i)) != NULL) {
  4491. upb_msgval val = _upb_msg_getraw(msg, f);
  4492. /* Skip field if unset or empty. */
  4493. if (upb_fielddef_haspresence(f)) {
  4494. if (!upb_msg_has(msg, f)) continue;
  4495. } else {
  4496. upb_msgval test = val;
  4497. if (upb_fielddef_isstring(f) && !upb_fielddef_isseq(f)) {
  4498. /* Clear string pointer, only size matters (ptr could be non-NULL). */
  4499. test.str_val.data = NULL;
  4500. }
  4501. /* Continue if NULL or 0. */
  4502. if (memcmp(&test, &zero, sizeof(test)) == 0) continue;
  4503. /* Continue on empty array or map. */
  4504. if (upb_fielddef_ismap(f)) {
  4505. if (upb_map_size(test.map_val) == 0) continue;
  4506. } else if (upb_fielddef_isseq(f)) {
  4507. if (upb_array_size(test.array_val) == 0) continue;
  4508. }
  4509. }
  4510. *out_val = val;
  4511. *out_f = f;
  4512. *iter = i;
  4513. return true;
  4514. }
  4515. *iter = i;
  4516. return false;
  4517. }
  4518. /** upb_array *****************************************************************/
  4519. upb_array *upb_array_new(upb_arena *a, upb_fieldtype_t type) {
  4520. return _upb_array_new(a, type);
  4521. }
  4522. size_t upb_array_size(const upb_array *arr) {
  4523. return arr->len;
  4524. }
  4525. upb_msgval upb_array_get(const upb_array *arr, size_t i) {
  4526. upb_msgval ret;
  4527. const char* data = _upb_array_constptr(arr);
  4528. int lg2 = arr->data & 7;
  4529. UPB_ASSERT(i < arr->len);
  4530. memcpy(&ret, data + (i << lg2), 1 << lg2);
  4531. return ret;
  4532. }
  4533. void upb_array_set(upb_array *arr, size_t i, upb_msgval val) {
  4534. char* data = _upb_array_ptr(arr);
  4535. int lg2 = arr->data & 7;
  4536. UPB_ASSERT(i < arr->len);
  4537. memcpy(data + (i << lg2), &val, 1 << lg2);
  4538. }
  4539. bool upb_array_append(upb_array *arr, upb_msgval val, upb_arena *arena) {
  4540. if (!_upb_array_realloc(arr, arr->len + 1, arena)) {
  4541. return false;
  4542. }
  4543. arr->len++;
  4544. upb_array_set(arr, arr->len - 1, val);
  4545. return true;
  4546. }
  4547. /* Resizes the array to the given size, reallocating if necessary, and returns a
  4548. * pointer to the new array elements. */
  4549. bool upb_array_resize(upb_array *arr, size_t size, upb_arena *arena) {
  4550. return _upb_array_realloc(arr, size, arena);
  4551. }
  4552. /** upb_map *******************************************************************/
  4553. upb_map *upb_map_new(upb_arena *a, upb_fieldtype_t key_type,
  4554. upb_fieldtype_t value_type) {
  4555. return _upb_map_new(a, _upb_fieldtype_to_mapsize[key_type],
  4556. _upb_fieldtype_to_mapsize[value_type]);
  4557. }
  4558. size_t upb_map_size(const upb_map *map) {
  4559. return _upb_map_size(map);
  4560. }
  4561. bool upb_map_get(const upb_map *map, upb_msgval key, upb_msgval *val) {
  4562. return _upb_map_get(map, &key, map->key_size, val, map->val_size);
  4563. }
  4564. bool upb_map_set(upb_map *map, upb_msgval key, upb_msgval val,
  4565. upb_arena *arena) {
  4566. return _upb_map_set(map, &key, map->key_size, &val, map->val_size, arena);
  4567. }
  4568. bool upb_map_delete(upb_map *map, upb_msgval key) {
  4569. return _upb_map_delete(map, &key, map->key_size);
  4570. }
  4571. bool upb_mapiter_next(const upb_map *map, size_t *iter) {
  4572. return _upb_map_next(map, iter);
  4573. }
  4574. /* Returns the key and value for this entry of the map. */
  4575. upb_msgval upb_mapiter_key(const upb_map *map, size_t iter) {
  4576. upb_strtable_iter i;
  4577. upb_msgval ret;
  4578. i.t = &map->table;
  4579. i.index = iter;
  4580. _upb_map_fromkey(upb_strtable_iter_key(&i), &ret, map->key_size);
  4581. return ret;
  4582. }
  4583. upb_msgval upb_mapiter_value(const upb_map *map, size_t iter) {
  4584. upb_strtable_iter i;
  4585. upb_msgval ret;
  4586. i.t = &map->table;
  4587. i.index = iter;
  4588. _upb_map_fromvalue(upb_strtable_iter_value(&i), &ret, map->val_size);
  4589. return ret;
  4590. }
  4591. /* void upb_mapiter_setvalue(upb_map *map, size_t iter, upb_msgval value); */
  4592. /*
  4593. ** TODO(haberman): it's unclear whether a lot of the consistency checks should
  4594. ** UPB_ASSERT() or return false.
  4595. */
  4596. #include <string.h>
  4597. struct upb_handlers {
  4598. upb_handlercache *cache;
  4599. const upb_msgdef *msg;
  4600. const upb_handlers **sub;
  4601. const void *top_closure_type;
  4602. upb_handlers_tabent table[1]; /* Dynamically-sized field handler array. */
  4603. };
  4604. static void *upb_calloc(upb_arena *arena, size_t size) {
  4605. void *mem = upb_malloc(upb_arena_alloc(arena), size);
  4606. if (mem) {
  4607. memset(mem, 0, size);
  4608. }
  4609. return mem;
  4610. }
  4611. /* Defined for the sole purpose of having a unique pointer value for
  4612. * UPB_NO_CLOSURE. */
  4613. char _upb_noclosure;
  4614. /* Given a selector for a STARTSUBMSG handler, resolves to a pointer to the
  4615. * subhandlers for this submessage field. */
  4616. #define SUBH(h, selector) (h->sub[selector])
  4617. /* The selector for a submessage field is the field index. */
  4618. #define SUBH_F(h, f) SUBH(h, upb_fielddef_index(f))
  4619. static int32_t trygetsel(upb_handlers *h, const upb_fielddef *f,
  4620. upb_handlertype_t type) {
  4621. upb_selector_t sel;
  4622. bool ok;
  4623. ok = upb_handlers_getselector(f, type, &sel);
  4624. UPB_ASSERT(upb_handlers_msgdef(h) == upb_fielddef_containingtype(f));
  4625. UPB_ASSERT(ok);
  4626. return sel;
  4627. }
  4628. static upb_selector_t handlers_getsel(upb_handlers *h, const upb_fielddef *f,
  4629. upb_handlertype_t type) {
  4630. int32_t sel = trygetsel(h, f, type);
  4631. UPB_ASSERT(sel >= 0);
  4632. return sel;
  4633. }
  4634. static const void **returntype(upb_handlers *h, const upb_fielddef *f,
  4635. upb_handlertype_t type) {
  4636. return &h->table[handlers_getsel(h, f, type)].attr.return_closure_type;
  4637. }
  4638. static bool doset(upb_handlers *h, int32_t sel, const upb_fielddef *f,
  4639. upb_handlertype_t type, upb_func *func,
  4640. const upb_handlerattr *attr) {
  4641. upb_handlerattr set_attr = UPB_HANDLERATTR_INIT;
  4642. const void *closure_type;
  4643. const void **context_closure_type;
  4644. UPB_ASSERT(!h->table[sel].func);
  4645. if (attr) {
  4646. set_attr = *attr;
  4647. }
  4648. /* Check that the given closure type matches the closure type that has been
  4649. * established for this context (if any). */
  4650. closure_type = set_attr.closure_type;
  4651. if (type == UPB_HANDLER_STRING) {
  4652. context_closure_type = returntype(h, f, UPB_HANDLER_STARTSTR);
  4653. } else if (f && upb_fielddef_isseq(f) &&
  4654. type != UPB_HANDLER_STARTSEQ &&
  4655. type != UPB_HANDLER_ENDSEQ) {
  4656. context_closure_type = returntype(h, f, UPB_HANDLER_STARTSEQ);
  4657. } else {
  4658. context_closure_type = &h->top_closure_type;
  4659. }
  4660. if (closure_type && *context_closure_type &&
  4661. closure_type != *context_closure_type) {
  4662. return false;
  4663. }
  4664. if (closure_type)
  4665. *context_closure_type = closure_type;
  4666. /* If this is a STARTSEQ or STARTSTR handler, check that the returned pointer
  4667. * matches any pre-existing expectations about what type is expected. */
  4668. if (type == UPB_HANDLER_STARTSEQ || type == UPB_HANDLER_STARTSTR) {
  4669. const void *return_type = set_attr.return_closure_type;
  4670. const void *table_return_type = h->table[sel].attr.return_closure_type;
  4671. if (return_type && table_return_type && return_type != table_return_type) {
  4672. return false;
  4673. }
  4674. if (table_return_type && !return_type) {
  4675. set_attr.return_closure_type = table_return_type;
  4676. }
  4677. }
  4678. h->table[sel].func = (upb_func*)func;
  4679. h->table[sel].attr = set_attr;
  4680. return true;
  4681. }
  4682. /* Returns the effective closure type for this handler (which will propagate
  4683. * from outer frames if this frame has no START* handler). Not implemented for
  4684. * UPB_HANDLER_STRING at the moment since this is not needed. Returns NULL is
  4685. * the effective closure type is unspecified (either no handler was registered
  4686. * to specify it or the handler that was registered did not specify the closure
  4687. * type). */
  4688. const void *effective_closure_type(upb_handlers *h, const upb_fielddef *f,
  4689. upb_handlertype_t type) {
  4690. const void *ret;
  4691. upb_selector_t sel;
  4692. UPB_ASSERT(type != UPB_HANDLER_STRING);
  4693. ret = h->top_closure_type;
  4694. if (upb_fielddef_isseq(f) &&
  4695. type != UPB_HANDLER_STARTSEQ &&
  4696. type != UPB_HANDLER_ENDSEQ &&
  4697. h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSEQ)].func) {
  4698. ret = h->table[sel].attr.return_closure_type;
  4699. }
  4700. if (type == UPB_HANDLER_STRING &&
  4701. h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSTR)].func) {
  4702. ret = h->table[sel].attr.return_closure_type;
  4703. }
  4704. /* The effective type of the submessage; not used yet.
  4705. * if (type == SUBMESSAGE &&
  4706. * h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSUBMSG)].func) {
  4707. * ret = h->table[sel].attr.return_closure_type;
  4708. * } */
  4709. return ret;
  4710. }
  4711. /* Checks whether the START* handler specified by f & type is missing even
  4712. * though it is required to convert the established type of an outer frame
  4713. * ("closure_type") into the established type of an inner frame (represented in
  4714. * the return closure type of this handler's attr. */
  4715. bool checkstart(upb_handlers *h, const upb_fielddef *f, upb_handlertype_t type,
  4716. upb_status *status) {
  4717. const void *closure_type;
  4718. const upb_handlerattr *attr;
  4719. const void *return_closure_type;
  4720. upb_selector_t sel = handlers_getsel(h, f, type);
  4721. if (h->table[sel].func) return true;
  4722. closure_type = effective_closure_type(h, f, type);
  4723. attr = &h->table[sel].attr;
  4724. return_closure_type = attr->return_closure_type;
  4725. if (closure_type && return_closure_type &&
  4726. closure_type != return_closure_type) {
  4727. return false;
  4728. }
  4729. return true;
  4730. }
  4731. static upb_handlers *upb_handlers_new(const upb_msgdef *md,
  4732. upb_handlercache *cache,
  4733. upb_arena *arena) {
  4734. int extra;
  4735. upb_handlers *h;
  4736. extra =
  4737. (int)(sizeof(upb_handlers_tabent) * (upb_msgdef_selectorcount(md) - 1));
  4738. h = upb_calloc(arena, sizeof(*h) + extra);
  4739. if (!h) return NULL;
  4740. h->cache = cache;
  4741. h->msg = md;
  4742. if (upb_msgdef_submsgfieldcount(md) > 0) {
  4743. size_t bytes = upb_msgdef_submsgfieldcount(md) * sizeof(*h->sub);
  4744. h->sub = upb_calloc(arena, bytes);
  4745. if (!h->sub) return NULL;
  4746. } else {
  4747. h->sub = 0;
  4748. }
  4749. /* calloc() above initialized all handlers to NULL. */
  4750. return h;
  4751. }
  4752. /* Public interface ***********************************************************/
  4753. #define SETTER(name, handlerctype, handlertype) \
  4754. bool upb_handlers_set##name(upb_handlers *h, const upb_fielddef *f, \
  4755. handlerctype func, \
  4756. const upb_handlerattr *attr) { \
  4757. int32_t sel = trygetsel(h, f, handlertype); \
  4758. return doset(h, sel, f, handlertype, (upb_func *)func, attr); \
  4759. }
  4760. SETTER(int32, upb_int32_handlerfunc*, UPB_HANDLER_INT32)
  4761. SETTER(int64, upb_int64_handlerfunc*, UPB_HANDLER_INT64)
  4762. SETTER(uint32, upb_uint32_handlerfunc*, UPB_HANDLER_UINT32)
  4763. SETTER(uint64, upb_uint64_handlerfunc*, UPB_HANDLER_UINT64)
  4764. SETTER(float, upb_float_handlerfunc*, UPB_HANDLER_FLOAT)
  4765. SETTER(double, upb_double_handlerfunc*, UPB_HANDLER_DOUBLE)
  4766. SETTER(bool, upb_bool_handlerfunc*, UPB_HANDLER_BOOL)
  4767. SETTER(startstr, upb_startstr_handlerfunc*, UPB_HANDLER_STARTSTR)
  4768. SETTER(string, upb_string_handlerfunc*, UPB_HANDLER_STRING)
  4769. SETTER(endstr, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSTR)
  4770. SETTER(startseq, upb_startfield_handlerfunc*, UPB_HANDLER_STARTSEQ)
  4771. SETTER(startsubmsg, upb_startfield_handlerfunc*, UPB_HANDLER_STARTSUBMSG)
  4772. SETTER(endsubmsg, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSUBMSG)
  4773. SETTER(endseq, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSEQ)
  4774. #undef SETTER
  4775. bool upb_handlers_setunknown(upb_handlers *h, upb_unknown_handlerfunc *func,
  4776. const upb_handlerattr *attr) {
  4777. return doset(h, UPB_UNKNOWN_SELECTOR, NULL, UPB_HANDLER_INT32,
  4778. (upb_func *)func, attr);
  4779. }
  4780. bool upb_handlers_setstartmsg(upb_handlers *h, upb_startmsg_handlerfunc *func,
  4781. const upb_handlerattr *attr) {
  4782. return doset(h, UPB_STARTMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
  4783. (upb_func *)func, attr);
  4784. }
  4785. bool upb_handlers_setendmsg(upb_handlers *h, upb_endmsg_handlerfunc *func,
  4786. const upb_handlerattr *attr) {
  4787. return doset(h, UPB_ENDMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
  4788. (upb_func *)func, attr);
  4789. }
  4790. bool upb_handlers_setsubhandlers(upb_handlers *h, const upb_fielddef *f,
  4791. const upb_handlers *sub) {
  4792. UPB_ASSERT(sub);
  4793. UPB_ASSERT(upb_fielddef_issubmsg(f));
  4794. if (SUBH_F(h, f)) return false; /* Can't reset. */
  4795. if (upb_handlers_msgdef(sub) != upb_fielddef_msgsubdef(f)) {
  4796. return false;
  4797. }
  4798. SUBH_F(h, f) = sub;
  4799. return true;
  4800. }
  4801. const upb_handlers *upb_handlers_getsubhandlers(const upb_handlers *h,
  4802. const upb_fielddef *f) {
  4803. UPB_ASSERT(upb_fielddef_issubmsg(f));
  4804. return SUBH_F(h, f);
  4805. }
  4806. upb_func *upb_handlers_gethandler(const upb_handlers *h, upb_selector_t s,
  4807. const void **handler_data) {
  4808. upb_func *ret = (upb_func *)h->table[s].func;
  4809. if (ret && handler_data) {
  4810. *handler_data = h->table[s].attr.handler_data;
  4811. }
  4812. return ret;
  4813. }
  4814. bool upb_handlers_getattr(const upb_handlers *h, upb_selector_t sel,
  4815. upb_handlerattr *attr) {
  4816. if (!upb_handlers_gethandler(h, sel, NULL))
  4817. return false;
  4818. *attr = h->table[sel].attr;
  4819. return true;
  4820. }
  4821. const upb_handlers *upb_handlers_getsubhandlers_sel(const upb_handlers *h,
  4822. upb_selector_t sel) {
  4823. /* STARTSUBMSG selector in sel is the field's selector base. */
  4824. return SUBH(h, sel - UPB_STATIC_SELECTOR_COUNT);
  4825. }
  4826. const upb_msgdef *upb_handlers_msgdef(const upb_handlers *h) { return h->msg; }
  4827. bool upb_handlers_addcleanup(upb_handlers *h, void *p, upb_handlerfree *func) {
  4828. return upb_handlercache_addcleanup(h->cache, p, func);
  4829. }
  4830. upb_handlertype_t upb_handlers_getprimitivehandlertype(const upb_fielddef *f) {
  4831. switch (upb_fielddef_type(f)) {
  4832. case UPB_TYPE_INT32:
  4833. case UPB_TYPE_ENUM: return UPB_HANDLER_INT32;
  4834. case UPB_TYPE_INT64: return UPB_HANDLER_INT64;
  4835. case UPB_TYPE_UINT32: return UPB_HANDLER_UINT32;
  4836. case UPB_TYPE_UINT64: return UPB_HANDLER_UINT64;
  4837. case UPB_TYPE_FLOAT: return UPB_HANDLER_FLOAT;
  4838. case UPB_TYPE_DOUBLE: return UPB_HANDLER_DOUBLE;
  4839. case UPB_TYPE_BOOL: return UPB_HANDLER_BOOL;
  4840. default: UPB_ASSERT(false); return -1; /* Invalid input. */
  4841. }
  4842. }
  4843. bool upb_handlers_getselector(const upb_fielddef *f, upb_handlertype_t type,
  4844. upb_selector_t *s) {
  4845. uint32_t selector_base = upb_fielddef_selectorbase(f);
  4846. switch (type) {
  4847. case UPB_HANDLER_INT32:
  4848. case UPB_HANDLER_INT64:
  4849. case UPB_HANDLER_UINT32:
  4850. case UPB_HANDLER_UINT64:
  4851. case UPB_HANDLER_FLOAT:
  4852. case UPB_HANDLER_DOUBLE:
  4853. case UPB_HANDLER_BOOL:
  4854. if (!upb_fielddef_isprimitive(f) ||
  4855. upb_handlers_getprimitivehandlertype(f) != type)
  4856. return false;
  4857. *s = selector_base;
  4858. break;
  4859. case UPB_HANDLER_STRING:
  4860. if (upb_fielddef_isstring(f)) {
  4861. *s = selector_base;
  4862. } else if (upb_fielddef_lazy(f)) {
  4863. *s = selector_base + 3;
  4864. } else {
  4865. return false;
  4866. }
  4867. break;
  4868. case UPB_HANDLER_STARTSTR:
  4869. if (upb_fielddef_isstring(f) || upb_fielddef_lazy(f)) {
  4870. *s = selector_base + 1;
  4871. } else {
  4872. return false;
  4873. }
  4874. break;
  4875. case UPB_HANDLER_ENDSTR:
  4876. if (upb_fielddef_isstring(f) || upb_fielddef_lazy(f)) {
  4877. *s = selector_base + 2;
  4878. } else {
  4879. return false;
  4880. }
  4881. break;
  4882. case UPB_HANDLER_STARTSEQ:
  4883. if (!upb_fielddef_isseq(f)) return false;
  4884. *s = selector_base - 2;
  4885. break;
  4886. case UPB_HANDLER_ENDSEQ:
  4887. if (!upb_fielddef_isseq(f)) return false;
  4888. *s = selector_base - 1;
  4889. break;
  4890. case UPB_HANDLER_STARTSUBMSG:
  4891. if (!upb_fielddef_issubmsg(f)) return false;
  4892. /* Selectors for STARTSUBMSG are at the beginning of the table so that the
  4893. * selector can also be used as an index into the "sub" array of
  4894. * subhandlers. The indexes for the two into these two tables are the
  4895. * same, except that in the handler table the static selectors come first. */
  4896. *s = upb_fielddef_index(f) + UPB_STATIC_SELECTOR_COUNT;
  4897. break;
  4898. case UPB_HANDLER_ENDSUBMSG:
  4899. if (!upb_fielddef_issubmsg(f)) return false;
  4900. *s = selector_base;
  4901. break;
  4902. }
  4903. UPB_ASSERT((size_t)*s < upb_msgdef_selectorcount(upb_fielddef_containingtype(f)));
  4904. return true;
  4905. }
  4906. /* upb_handlercache ***********************************************************/
  4907. struct upb_handlercache {
  4908. upb_arena *arena;
  4909. upb_inttable tab; /* maps upb_msgdef* -> upb_handlers*. */
  4910. upb_handlers_callback *callback;
  4911. const void *closure;
  4912. };
  4913. const upb_handlers *upb_handlercache_get(upb_handlercache *c,
  4914. const upb_msgdef *md) {
  4915. upb_msg_field_iter i;
  4916. upb_value v;
  4917. upb_handlers *h;
  4918. if (upb_inttable_lookupptr(&c->tab, md, &v)) {
  4919. return upb_value_getptr(v);
  4920. }
  4921. h = upb_handlers_new(md, c, c->arena);
  4922. v = upb_value_ptr(h);
  4923. if (!h) return NULL;
  4924. if (!upb_inttable_insertptr(&c->tab, md, v)) return NULL;
  4925. c->callback(c->closure, h);
  4926. /* For each submessage field, get or create a handlers object and set it as
  4927. * the subhandlers. */
  4928. for(upb_msg_field_begin(&i, md);
  4929. !upb_msg_field_done(&i);
  4930. upb_msg_field_next(&i)) {
  4931. upb_fielddef *f = upb_msg_iter_field(&i);
  4932. if (upb_fielddef_issubmsg(f)) {
  4933. const upb_msgdef *subdef = upb_fielddef_msgsubdef(f);
  4934. const upb_handlers *sub_mh = upb_handlercache_get(c, subdef);
  4935. if (!sub_mh) return NULL;
  4936. upb_handlers_setsubhandlers(h, f, sub_mh);
  4937. }
  4938. }
  4939. return h;
  4940. }
  4941. upb_handlercache *upb_handlercache_new(upb_handlers_callback *callback,
  4942. const void *closure) {
  4943. upb_handlercache *cache = upb_gmalloc(sizeof(*cache));
  4944. if (!cache) return NULL;
  4945. cache->arena = upb_arena_new();
  4946. cache->callback = callback;
  4947. cache->closure = closure;
  4948. if (!upb_inttable_init(&cache->tab, UPB_CTYPE_PTR)) goto oom;
  4949. return cache;
  4950. oom:
  4951. upb_gfree(cache);
  4952. return NULL;
  4953. }
  4954. void upb_handlercache_free(upb_handlercache *cache) {
  4955. upb_inttable_uninit(&cache->tab);
  4956. upb_arena_free(cache->arena);
  4957. upb_gfree(cache);
  4958. }
  4959. bool upb_handlercache_addcleanup(upb_handlercache *c, void *p,
  4960. upb_handlerfree *func) {
  4961. return upb_arena_addcleanup(c->arena, p, func);
  4962. }
  4963. /* upb_byteshandler ***********************************************************/
  4964. bool upb_byteshandler_setstartstr(upb_byteshandler *h,
  4965. upb_startstr_handlerfunc *func, void *d) {
  4966. h->table[UPB_STARTSTR_SELECTOR].func = (upb_func*)func;
  4967. h->table[UPB_STARTSTR_SELECTOR].attr.handler_data = d;
  4968. return true;
  4969. }
  4970. bool upb_byteshandler_setstring(upb_byteshandler *h,
  4971. upb_string_handlerfunc *func, void *d) {
  4972. h->table[UPB_STRING_SELECTOR].func = (upb_func*)func;
  4973. h->table[UPB_STRING_SELECTOR].attr.handler_data = d;
  4974. return true;
  4975. }
  4976. bool upb_byteshandler_setendstr(upb_byteshandler *h,
  4977. upb_endfield_handlerfunc *func, void *d) {
  4978. h->table[UPB_ENDSTR_SELECTOR].func = (upb_func*)func;
  4979. h->table[UPB_ENDSTR_SELECTOR].attr.handler_data = d;
  4980. return true;
  4981. }
  4982. /** Handlers for upb_msg ******************************************************/
  4983. typedef struct {
  4984. size_t offset;
  4985. int32_t hasbit;
  4986. } upb_msg_handlerdata;
  4987. /* Fallback implementation if the handler is not specialized by the producer. */
  4988. #define MSG_WRITER(type, ctype) \
  4989. bool upb_msg_set ## type (void *c, const void *hd, ctype val) { \
  4990. uint8_t *m = c; \
  4991. const upb_msg_handlerdata *d = hd; \
  4992. if (d->hasbit > 0) \
  4993. *(uint8_t*)&m[d->hasbit / 8] |= 1 << (d->hasbit % 8); \
  4994. *(ctype*)&m[d->offset] = val; \
  4995. return true; \
  4996. } \
  4997. MSG_WRITER(double, double)
  4998. MSG_WRITER(float, float)
  4999. MSG_WRITER(int32, int32_t)
  5000. MSG_WRITER(int64, int64_t)
  5001. MSG_WRITER(uint32, uint32_t)
  5002. MSG_WRITER(uint64, uint64_t)
  5003. MSG_WRITER(bool, bool)
  5004. bool upb_msg_setscalarhandler(upb_handlers *h, const upb_fielddef *f,
  5005. size_t offset, int32_t hasbit) {
  5006. upb_handlerattr attr = UPB_HANDLERATTR_INIT;
  5007. bool ok;
  5008. upb_msg_handlerdata *d = upb_gmalloc(sizeof(*d));
  5009. if (!d) return false;
  5010. d->offset = offset;
  5011. d->hasbit = hasbit;
  5012. attr.handler_data = d;
  5013. attr.alwaysok = true;
  5014. upb_handlers_addcleanup(h, d, upb_gfree);
  5015. #define TYPE(u, l) \
  5016. case UPB_TYPE_##u: \
  5017. ok = upb_handlers_set##l(h, f, upb_msg_set##l, &attr); break;
  5018. ok = false;
  5019. switch (upb_fielddef_type(f)) {
  5020. TYPE(INT64, int64);
  5021. TYPE(INT32, int32);
  5022. TYPE(ENUM, int32);
  5023. TYPE(UINT64, uint64);
  5024. TYPE(UINT32, uint32);
  5025. TYPE(DOUBLE, double);
  5026. TYPE(FLOAT, float);
  5027. TYPE(BOOL, bool);
  5028. default: UPB_ASSERT(false); break;
  5029. }
  5030. #undef TYPE
  5031. return ok;
  5032. }
  5033. bool upb_msg_getscalarhandlerdata(const upb_handlers *h,
  5034. upb_selector_t s,
  5035. upb_fieldtype_t *type,
  5036. size_t *offset,
  5037. int32_t *hasbit) {
  5038. const upb_msg_handlerdata *d;
  5039. const void *p;
  5040. upb_func *f = upb_handlers_gethandler(h, s, &p);
  5041. if ((upb_int64_handlerfunc*)f == upb_msg_setint64) {
  5042. *type = UPB_TYPE_INT64;
  5043. } else if ((upb_int32_handlerfunc*)f == upb_msg_setint32) {
  5044. *type = UPB_TYPE_INT32;
  5045. } else if ((upb_uint64_handlerfunc*)f == upb_msg_setuint64) {
  5046. *type = UPB_TYPE_UINT64;
  5047. } else if ((upb_uint32_handlerfunc*)f == upb_msg_setuint32) {
  5048. *type = UPB_TYPE_UINT32;
  5049. } else if ((upb_double_handlerfunc*)f == upb_msg_setdouble) {
  5050. *type = UPB_TYPE_DOUBLE;
  5051. } else if ((upb_float_handlerfunc*)f == upb_msg_setfloat) {
  5052. *type = UPB_TYPE_FLOAT;
  5053. } else if ((upb_bool_handlerfunc*)f == upb_msg_setbool) {
  5054. *type = UPB_TYPE_BOOL;
  5055. } else {
  5056. return false;
  5057. }
  5058. d = p;
  5059. *offset = d->offset;
  5060. *hasbit = d->hasbit;
  5061. return true;
  5062. }
  5063. bool upb_bufsrc_putbuf(const char *buf, size_t len, upb_bytessink sink) {
  5064. void *subc;
  5065. bool ret;
  5066. upb_bufhandle handle = UPB_BUFHANDLE_INIT;
  5067. handle.buf = buf;
  5068. ret = upb_bytessink_start(sink, len, &subc);
  5069. if (ret && len != 0) {
  5070. ret = (upb_bytessink_putbuf(sink, subc, buf, len, &handle) >= len);
  5071. }
  5072. if (ret) {
  5073. ret = upb_bytessink_end(sink);
  5074. }
  5075. return ret;
  5076. }
  5077. #ifdef UPB_MSVC_VSNPRINTF
  5078. /* Visual C++ earlier than 2015 doesn't have standard C99 snprintf and
  5079. * vsnprintf. To support them, missing functions are manually implemented
  5080. * using the existing secure functions. */
  5081. int msvc_vsnprintf(char* s, size_t n, const char* format, va_list arg) {
  5082. if (!s) {
  5083. return _vscprintf(format, arg);
  5084. }
  5085. int ret = _vsnprintf_s(s, n, _TRUNCATE, format, arg);
  5086. if (ret < 0) {
  5087. ret = _vscprintf(format, arg);
  5088. }
  5089. return ret;
  5090. }
  5091. int msvc_snprintf(char* s, size_t n, const char* format, ...) {
  5092. va_list arg;
  5093. va_start(arg, format);
  5094. int ret = msvc_vsnprintf(s, n, format, arg);
  5095. va_end(arg);
  5096. return ret;
  5097. }
  5098. #endif
  5099. /*
  5100. ** protobuf decoder bytecode compiler
  5101. **
  5102. ** Code to compile a upb::Handlers into bytecode for decoding a protobuf
  5103. ** according to that specific schema and destination handlers.
  5104. **
  5105. ** Bytecode definition is in decoder.int.h.
  5106. */
  5107. #include <stdarg.h>
  5108. #ifdef UPB_DUMP_BYTECODE
  5109. #include <stdio.h>
  5110. #endif
  5111. #define MAXLABEL 5
  5112. #define EMPTYLABEL -1
  5113. /* upb_pbdecodermethod ********************************************************/
  5114. static void freemethod(upb_pbdecodermethod *method) {
  5115. upb_inttable_uninit(&method->dispatch);
  5116. upb_gfree(method);
  5117. }
  5118. static upb_pbdecodermethod *newmethod(const upb_handlers *dest_handlers,
  5119. mgroup *group) {
  5120. upb_pbdecodermethod *ret = upb_gmalloc(sizeof(*ret));
  5121. upb_byteshandler_init(&ret->input_handler_);
  5122. ret->group = group;
  5123. ret->dest_handlers_ = dest_handlers;
  5124. upb_inttable_init(&ret->dispatch, UPB_CTYPE_UINT64);
  5125. return ret;
  5126. }
  5127. const upb_handlers *upb_pbdecodermethod_desthandlers(
  5128. const upb_pbdecodermethod *m) {
  5129. return m->dest_handlers_;
  5130. }
  5131. const upb_byteshandler *upb_pbdecodermethod_inputhandler(
  5132. const upb_pbdecodermethod *m) {
  5133. return &m->input_handler_;
  5134. }
  5135. bool upb_pbdecodermethod_isnative(const upb_pbdecodermethod *m) {
  5136. return m->is_native_;
  5137. }
  5138. /* mgroup *********************************************************************/
  5139. static void freegroup(mgroup *g) {
  5140. upb_inttable_iter i;
  5141. upb_inttable_begin(&i, &g->methods);
  5142. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5143. freemethod(upb_value_getptr(upb_inttable_iter_value(&i)));
  5144. }
  5145. upb_inttable_uninit(&g->methods);
  5146. upb_gfree(g->bytecode);
  5147. upb_gfree(g);
  5148. }
  5149. mgroup *newgroup(void) {
  5150. mgroup *g = upb_gmalloc(sizeof(*g));
  5151. upb_inttable_init(&g->methods, UPB_CTYPE_PTR);
  5152. g->bytecode = NULL;
  5153. g->bytecode_end = NULL;
  5154. return g;
  5155. }
  5156. /* bytecode compiler **********************************************************/
  5157. /* Data used only at compilation time. */
  5158. typedef struct {
  5159. mgroup *group;
  5160. uint32_t *pc;
  5161. int fwd_labels[MAXLABEL];
  5162. int back_labels[MAXLABEL];
  5163. /* For fields marked "lazy", parse them lazily or eagerly? */
  5164. bool lazy;
  5165. } compiler;
  5166. static compiler *newcompiler(mgroup *group, bool lazy) {
  5167. compiler *ret = upb_gmalloc(sizeof(*ret));
  5168. int i;
  5169. ret->group = group;
  5170. ret->lazy = lazy;
  5171. for (i = 0; i < MAXLABEL; i++) {
  5172. ret->fwd_labels[i] = EMPTYLABEL;
  5173. ret->back_labels[i] = EMPTYLABEL;
  5174. }
  5175. return ret;
  5176. }
  5177. static void freecompiler(compiler *c) {
  5178. upb_gfree(c);
  5179. }
  5180. const size_t ptr_words = sizeof(void*) / sizeof(uint32_t);
  5181. /* How many words an instruction is. */
  5182. static int instruction_len(uint32_t instr) {
  5183. switch (getop(instr)) {
  5184. case OP_SETDISPATCH: return 1 + ptr_words;
  5185. case OP_TAGN: return 3;
  5186. case OP_SETBIGGROUPNUM: return 2;
  5187. default: return 1;
  5188. }
  5189. }
  5190. bool op_has_longofs(int32_t instruction) {
  5191. switch (getop(instruction)) {
  5192. case OP_CALL:
  5193. case OP_BRANCH:
  5194. case OP_CHECKDELIM:
  5195. return true;
  5196. /* The "tag" instructions only have 8 bytes available for the jump target,
  5197. * but that is ok because these opcodes only require short jumps. */
  5198. case OP_TAG1:
  5199. case OP_TAG2:
  5200. case OP_TAGN:
  5201. return false;
  5202. default:
  5203. UPB_ASSERT(false);
  5204. return false;
  5205. }
  5206. }
  5207. static int32_t getofs(uint32_t instruction) {
  5208. if (op_has_longofs(instruction)) {
  5209. return (int32_t)instruction >> 8;
  5210. } else {
  5211. return (int8_t)(instruction >> 8);
  5212. }
  5213. }
  5214. static void setofs(uint32_t *instruction, int32_t ofs) {
  5215. if (op_has_longofs(*instruction)) {
  5216. *instruction = getop(*instruction) | (uint32_t)ofs << 8;
  5217. } else {
  5218. *instruction = (*instruction & ~0xff00) | ((ofs & 0xff) << 8);
  5219. }
  5220. UPB_ASSERT(getofs(*instruction) == ofs); /* Would fail in cases of overflow. */
  5221. }
  5222. static uint32_t pcofs(compiler *c) {
  5223. return (uint32_t)(c->pc - c->group->bytecode);
  5224. }
  5225. /* Defines a local label at the current PC location. All previous forward
  5226. * references are updated to point to this location. The location is noted
  5227. * for any future backward references. */
  5228. static void label(compiler *c, unsigned int label) {
  5229. int val;
  5230. uint32_t *codep;
  5231. UPB_ASSERT(label < MAXLABEL);
  5232. val = c->fwd_labels[label];
  5233. codep = (val == EMPTYLABEL) ? NULL : c->group->bytecode + val;
  5234. while (codep) {
  5235. int ofs = getofs(*codep);
  5236. setofs(codep, (int32_t)(c->pc - codep - instruction_len(*codep)));
  5237. codep = ofs ? codep + ofs : NULL;
  5238. }
  5239. c->fwd_labels[label] = EMPTYLABEL;
  5240. c->back_labels[label] = pcofs(c);
  5241. }
  5242. /* Creates a reference to a numbered label; either a forward reference
  5243. * (positive arg) or backward reference (negative arg). For forward references
  5244. * the value returned now is actually a "next" pointer into a linked list of all
  5245. * instructions that use this label and will be patched later when the label is
  5246. * defined with label().
  5247. *
  5248. * The returned value is the offset that should be written into the instruction.
  5249. */
  5250. static int32_t labelref(compiler *c, int label) {
  5251. UPB_ASSERT(label < MAXLABEL);
  5252. if (label == LABEL_DISPATCH) {
  5253. /* No resolving required. */
  5254. return 0;
  5255. } else if (label < 0) {
  5256. /* Backward local label. Relative to the next instruction. */
  5257. uint32_t from = (uint32_t)((c->pc + 1) - c->group->bytecode);
  5258. return c->back_labels[-label] - from;
  5259. } else {
  5260. /* Forward local label: prepend to (possibly-empty) linked list. */
  5261. int *lptr = &c->fwd_labels[label];
  5262. int32_t ret = (*lptr == EMPTYLABEL) ? 0 : *lptr - pcofs(c);
  5263. *lptr = pcofs(c);
  5264. return ret;
  5265. }
  5266. }
  5267. static void put32(compiler *c, uint32_t v) {
  5268. mgroup *g = c->group;
  5269. if (c->pc == g->bytecode_end) {
  5270. int ofs = pcofs(c);
  5271. size_t oldsize = g->bytecode_end - g->bytecode;
  5272. size_t newsize = UPB_MAX(oldsize * 2, 64);
  5273. /* TODO(haberman): handle OOM. */
  5274. g->bytecode = upb_grealloc(g->bytecode, oldsize * sizeof(uint32_t),
  5275. newsize * sizeof(uint32_t));
  5276. g->bytecode_end = g->bytecode + newsize;
  5277. c->pc = g->bytecode + ofs;
  5278. }
  5279. *c->pc++ = v;
  5280. }
  5281. static void putop(compiler *c, int op, ...) {
  5282. va_list ap;
  5283. va_start(ap, op);
  5284. switch (op) {
  5285. case OP_SETDISPATCH: {
  5286. uintptr_t ptr = (uintptr_t)va_arg(ap, void*);
  5287. put32(c, OP_SETDISPATCH);
  5288. put32(c, (uint32_t)ptr);
  5289. if (sizeof(uintptr_t) > sizeof(uint32_t))
  5290. put32(c, (uint64_t)ptr >> 32);
  5291. break;
  5292. }
  5293. case OP_STARTMSG:
  5294. case OP_ENDMSG:
  5295. case OP_PUSHLENDELIM:
  5296. case OP_POP:
  5297. case OP_SETDELIM:
  5298. case OP_HALT:
  5299. case OP_RET:
  5300. case OP_DISPATCH:
  5301. put32(c, op);
  5302. break;
  5303. case OP_PARSE_DOUBLE:
  5304. case OP_PARSE_FLOAT:
  5305. case OP_PARSE_INT64:
  5306. case OP_PARSE_UINT64:
  5307. case OP_PARSE_INT32:
  5308. case OP_PARSE_FIXED64:
  5309. case OP_PARSE_FIXED32:
  5310. case OP_PARSE_BOOL:
  5311. case OP_PARSE_UINT32:
  5312. case OP_PARSE_SFIXED32:
  5313. case OP_PARSE_SFIXED64:
  5314. case OP_PARSE_SINT32:
  5315. case OP_PARSE_SINT64:
  5316. case OP_STARTSEQ:
  5317. case OP_ENDSEQ:
  5318. case OP_STARTSUBMSG:
  5319. case OP_ENDSUBMSG:
  5320. case OP_STARTSTR:
  5321. case OP_STRING:
  5322. case OP_ENDSTR:
  5323. case OP_PUSHTAGDELIM:
  5324. put32(c, op | va_arg(ap, upb_selector_t) << 8);
  5325. break;
  5326. case OP_SETBIGGROUPNUM:
  5327. put32(c, op);
  5328. put32(c, va_arg(ap, int));
  5329. break;
  5330. case OP_CALL: {
  5331. const upb_pbdecodermethod *method = va_arg(ap, upb_pbdecodermethod *);
  5332. put32(c, op | (method->code_base.ofs - (pcofs(c) + 1)) << 8);
  5333. break;
  5334. }
  5335. case OP_CHECKDELIM:
  5336. case OP_BRANCH: {
  5337. uint32_t instruction = op;
  5338. int label = va_arg(ap, int);
  5339. setofs(&instruction, labelref(c, label));
  5340. put32(c, instruction);
  5341. break;
  5342. }
  5343. case OP_TAG1:
  5344. case OP_TAG2: {
  5345. int label = va_arg(ap, int);
  5346. uint64_t tag = va_arg(ap, uint64_t);
  5347. uint32_t instruction = (uint32_t)(op | (tag << 16));
  5348. UPB_ASSERT(tag <= 0xffff);
  5349. setofs(&instruction, labelref(c, label));
  5350. put32(c, instruction);
  5351. break;
  5352. }
  5353. case OP_TAGN: {
  5354. int label = va_arg(ap, int);
  5355. uint64_t tag = va_arg(ap, uint64_t);
  5356. uint32_t instruction = op | (upb_value_size(tag) << 16);
  5357. setofs(&instruction, labelref(c, label));
  5358. put32(c, instruction);
  5359. put32(c, (uint32_t)tag);
  5360. put32(c, tag >> 32);
  5361. break;
  5362. }
  5363. }
  5364. va_end(ap);
  5365. }
  5366. #if defined(UPB_DUMP_BYTECODE)
  5367. const char *upb_pbdecoder_getopname(unsigned int op) {
  5368. #define QUOTE(x) #x
  5369. #define EXPAND_AND_QUOTE(x) QUOTE(x)
  5370. #define OPNAME(x) OP_##x
  5371. #define OP(x) case OPNAME(x): return EXPAND_AND_QUOTE(OPNAME(x));
  5372. #define T(x) OP(PARSE_##x)
  5373. /* Keep in sync with list in decoder.int.h. */
  5374. switch ((opcode)op) {
  5375. T(DOUBLE) T(FLOAT) T(INT64) T(UINT64) T(INT32) T(FIXED64) T(FIXED32)
  5376. T(BOOL) T(UINT32) T(SFIXED32) T(SFIXED64) T(SINT32) T(SINT64)
  5377. OP(STARTMSG) OP(ENDMSG) OP(STARTSEQ) OP(ENDSEQ) OP(STARTSUBMSG)
  5378. OP(ENDSUBMSG) OP(STARTSTR) OP(STRING) OP(ENDSTR) OP(CALL) OP(RET)
  5379. OP(PUSHLENDELIM) OP(PUSHTAGDELIM) OP(SETDELIM) OP(CHECKDELIM)
  5380. OP(BRANCH) OP(TAG1) OP(TAG2) OP(TAGN) OP(SETDISPATCH) OP(POP)
  5381. OP(SETBIGGROUPNUM) OP(DISPATCH) OP(HALT)
  5382. }
  5383. return "<unknown op>";
  5384. #undef OP
  5385. #undef T
  5386. }
  5387. #endif
  5388. #ifdef UPB_DUMP_BYTECODE
  5389. static void dumpbc(uint32_t *p, uint32_t *end, FILE *f) {
  5390. uint32_t *begin = p;
  5391. while (p < end) {
  5392. fprintf(f, "%p %8tx", p, p - begin);
  5393. uint32_t instr = *p++;
  5394. uint8_t op = getop(instr);
  5395. fprintf(f, " %s", upb_pbdecoder_getopname(op));
  5396. switch ((opcode)op) {
  5397. case OP_SETDISPATCH: {
  5398. const upb_inttable *dispatch;
  5399. memcpy(&dispatch, p, sizeof(void*));
  5400. p += ptr_words;
  5401. const upb_pbdecodermethod *method =
  5402. (void *)((char *)dispatch -
  5403. offsetof(upb_pbdecodermethod, dispatch));
  5404. fprintf(f, " %s", upb_msgdef_fullname(
  5405. upb_handlers_msgdef(method->dest_handlers_)));
  5406. break;
  5407. }
  5408. case OP_DISPATCH:
  5409. case OP_STARTMSG:
  5410. case OP_ENDMSG:
  5411. case OP_PUSHLENDELIM:
  5412. case OP_POP:
  5413. case OP_SETDELIM:
  5414. case OP_HALT:
  5415. case OP_RET:
  5416. break;
  5417. case OP_PARSE_DOUBLE:
  5418. case OP_PARSE_FLOAT:
  5419. case OP_PARSE_INT64:
  5420. case OP_PARSE_UINT64:
  5421. case OP_PARSE_INT32:
  5422. case OP_PARSE_FIXED64:
  5423. case OP_PARSE_FIXED32:
  5424. case OP_PARSE_BOOL:
  5425. case OP_PARSE_UINT32:
  5426. case OP_PARSE_SFIXED32:
  5427. case OP_PARSE_SFIXED64:
  5428. case OP_PARSE_SINT32:
  5429. case OP_PARSE_SINT64:
  5430. case OP_STARTSEQ:
  5431. case OP_ENDSEQ:
  5432. case OP_STARTSUBMSG:
  5433. case OP_ENDSUBMSG:
  5434. case OP_STARTSTR:
  5435. case OP_STRING:
  5436. case OP_ENDSTR:
  5437. case OP_PUSHTAGDELIM:
  5438. fprintf(f, " %d", instr >> 8);
  5439. break;
  5440. case OP_SETBIGGROUPNUM:
  5441. fprintf(f, " %d", *p++);
  5442. break;
  5443. case OP_CHECKDELIM:
  5444. case OP_CALL:
  5445. case OP_BRANCH:
  5446. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  5447. break;
  5448. case OP_TAG1:
  5449. case OP_TAG2: {
  5450. fprintf(f, " tag:0x%x", instr >> 16);
  5451. if (getofs(instr)) {
  5452. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  5453. }
  5454. break;
  5455. }
  5456. case OP_TAGN: {
  5457. uint64_t tag = *p++;
  5458. tag |= (uint64_t)*p++ << 32;
  5459. fprintf(f, " tag:0x%llx", (long long)tag);
  5460. fprintf(f, " n:%d", instr >> 16);
  5461. if (getofs(instr)) {
  5462. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  5463. }
  5464. break;
  5465. }
  5466. }
  5467. fputs("\n", f);
  5468. }
  5469. }
  5470. #endif
  5471. static uint64_t get_encoded_tag(const upb_fielddef *f, int wire_type) {
  5472. uint32_t tag = (upb_fielddef_number(f) << 3) | wire_type;
  5473. uint64_t encoded_tag = upb_vencode32(tag);
  5474. /* No tag should be greater than 5 bytes. */
  5475. UPB_ASSERT(encoded_tag <= 0xffffffffff);
  5476. return encoded_tag;
  5477. }
  5478. static void putchecktag(compiler *c, const upb_fielddef *f,
  5479. int wire_type, int dest) {
  5480. uint64_t tag = get_encoded_tag(f, wire_type);
  5481. switch (upb_value_size(tag)) {
  5482. case 1:
  5483. putop(c, OP_TAG1, dest, tag);
  5484. break;
  5485. case 2:
  5486. putop(c, OP_TAG2, dest, tag);
  5487. break;
  5488. default:
  5489. putop(c, OP_TAGN, dest, tag);
  5490. break;
  5491. }
  5492. }
  5493. static upb_selector_t getsel(const upb_fielddef *f, upb_handlertype_t type) {
  5494. upb_selector_t selector;
  5495. bool ok = upb_handlers_getselector(f, type, &selector);
  5496. UPB_ASSERT(ok);
  5497. return selector;
  5498. }
  5499. /* Takes an existing, primary dispatch table entry and repacks it with a
  5500. * different alternate wire type. Called when we are inserting a secondary
  5501. * dispatch table entry for an alternate wire type. */
  5502. static uint64_t repack(uint64_t dispatch, int new_wt2) {
  5503. uint64_t ofs;
  5504. uint8_t wt1;
  5505. uint8_t old_wt2;
  5506. upb_pbdecoder_unpackdispatch(dispatch, &ofs, &wt1, &old_wt2);
  5507. UPB_ASSERT(old_wt2 == NO_WIRE_TYPE); /* wt2 should not be set yet. */
  5508. return upb_pbdecoder_packdispatch(ofs, wt1, new_wt2);
  5509. }
  5510. /* Marks the current bytecode position as the dispatch target for this message,
  5511. * field, and wire type. */
  5512. static void dispatchtarget(compiler *c, upb_pbdecodermethod *method,
  5513. const upb_fielddef *f, int wire_type) {
  5514. /* Offset is relative to msg base. */
  5515. uint64_t ofs = pcofs(c) - method->code_base.ofs;
  5516. uint32_t fn = upb_fielddef_number(f);
  5517. upb_inttable *d = &method->dispatch;
  5518. upb_value v;
  5519. if (upb_inttable_remove(d, fn, &v)) {
  5520. /* TODO: prioritize based on packed setting in .proto file. */
  5521. uint64_t repacked = repack(upb_value_getuint64(v), wire_type);
  5522. upb_inttable_insert(d, fn, upb_value_uint64(repacked));
  5523. upb_inttable_insert(d, fn + UPB_MAX_FIELDNUMBER, upb_value_uint64(ofs));
  5524. } else {
  5525. uint64_t val = upb_pbdecoder_packdispatch(ofs, wire_type, NO_WIRE_TYPE);
  5526. upb_inttable_insert(d, fn, upb_value_uint64(val));
  5527. }
  5528. }
  5529. static void putpush(compiler *c, const upb_fielddef *f) {
  5530. if (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE) {
  5531. putop(c, OP_PUSHLENDELIM);
  5532. } else {
  5533. uint32_t fn = upb_fielddef_number(f);
  5534. if (fn >= 1 << 24) {
  5535. putop(c, OP_PUSHTAGDELIM, 0);
  5536. putop(c, OP_SETBIGGROUPNUM, fn);
  5537. } else {
  5538. putop(c, OP_PUSHTAGDELIM, fn);
  5539. }
  5540. }
  5541. }
  5542. static upb_pbdecodermethod *find_submethod(const compiler *c,
  5543. const upb_pbdecodermethod *method,
  5544. const upb_fielddef *f) {
  5545. const upb_handlers *sub =
  5546. upb_handlers_getsubhandlers(method->dest_handlers_, f);
  5547. upb_value v;
  5548. return upb_inttable_lookupptr(&c->group->methods, sub, &v)
  5549. ? upb_value_getptr(v)
  5550. : NULL;
  5551. }
  5552. static void putsel(compiler *c, opcode op, upb_selector_t sel,
  5553. const upb_handlers *h) {
  5554. if (upb_handlers_gethandler(h, sel, NULL)) {
  5555. putop(c, op, sel);
  5556. }
  5557. }
  5558. /* Puts an opcode to call a callback, but only if a callback actually exists for
  5559. * this field and handler type. */
  5560. static void maybeput(compiler *c, opcode op, const upb_handlers *h,
  5561. const upb_fielddef *f, upb_handlertype_t type) {
  5562. putsel(c, op, getsel(f, type), h);
  5563. }
  5564. static bool haslazyhandlers(const upb_handlers *h, const upb_fielddef *f) {
  5565. if (!upb_fielddef_lazy(f))
  5566. return false;
  5567. return upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STARTSTR), NULL) ||
  5568. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STRING), NULL) ||
  5569. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_ENDSTR), NULL);
  5570. }
  5571. /* bytecode compiler code generation ******************************************/
  5572. /* Symbolic names for our local labels. */
  5573. #define LABEL_LOOPSTART 1 /* Top of a repeated field loop. */
  5574. #define LABEL_LOOPBREAK 2 /* To jump out of a repeated loop */
  5575. #define LABEL_FIELD 3 /* Jump backward to find the most recent field. */
  5576. #define LABEL_ENDMSG 4 /* To reach the OP_ENDMSG instr for this msg. */
  5577. /* Generates bytecode to parse a single non-lazy message field. */
  5578. static void generate_msgfield(compiler *c, const upb_fielddef *f,
  5579. upb_pbdecodermethod *method) {
  5580. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  5581. const upb_pbdecodermethod *sub_m = find_submethod(c, method, f);
  5582. int wire_type;
  5583. if (!sub_m) {
  5584. /* Don't emit any code for this field at all; it will be parsed as an
  5585. * unknown field.
  5586. *
  5587. * TODO(haberman): we should change this to parse it as a string field
  5588. * instead. It will probably be faster, but more importantly, once we
  5589. * start vending unknown fields, a field shouldn't be treated as unknown
  5590. * just because it doesn't have subhandlers registered. */
  5591. return;
  5592. }
  5593. label(c, LABEL_FIELD);
  5594. wire_type =
  5595. (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE)
  5596. ? UPB_WIRE_TYPE_DELIMITED
  5597. : UPB_WIRE_TYPE_START_GROUP;
  5598. if (upb_fielddef_isseq(f)) {
  5599. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5600. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  5601. dispatchtarget(c, method, f, wire_type);
  5602. putop(c, OP_PUSHTAGDELIM, 0);
  5603. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  5604. label(c, LABEL_LOOPSTART);
  5605. putpush(c, f);
  5606. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  5607. putop(c, OP_CALL, sub_m);
  5608. putop(c, OP_POP);
  5609. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  5610. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  5611. putop(c, OP_SETDELIM);
  5612. }
  5613. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5614. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  5615. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5616. label(c, LABEL_LOOPBREAK);
  5617. putop(c, OP_POP);
  5618. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  5619. } else {
  5620. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5621. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  5622. dispatchtarget(c, method, f, wire_type);
  5623. putpush(c, f);
  5624. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  5625. putop(c, OP_CALL, sub_m);
  5626. putop(c, OP_POP);
  5627. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  5628. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  5629. putop(c, OP_SETDELIM);
  5630. }
  5631. }
  5632. }
  5633. /* Generates bytecode to parse a single string or lazy submessage field. */
  5634. static void generate_delimfield(compiler *c, const upb_fielddef *f,
  5635. upb_pbdecodermethod *method) {
  5636. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  5637. label(c, LABEL_FIELD);
  5638. if (upb_fielddef_isseq(f)) {
  5639. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5640. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  5641. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  5642. putop(c, OP_PUSHTAGDELIM, 0);
  5643. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  5644. label(c, LABEL_LOOPSTART);
  5645. putop(c, OP_PUSHLENDELIM);
  5646. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  5647. /* Need to emit even if no handler to skip past the string. */
  5648. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  5649. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  5650. putop(c, OP_POP);
  5651. putop(c, OP_SETDELIM);
  5652. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5653. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_LOOPBREAK);
  5654. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5655. label(c, LABEL_LOOPBREAK);
  5656. putop(c, OP_POP);
  5657. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  5658. } else {
  5659. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5660. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  5661. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  5662. putop(c, OP_PUSHLENDELIM);
  5663. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  5664. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  5665. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  5666. putop(c, OP_POP);
  5667. putop(c, OP_SETDELIM);
  5668. }
  5669. }
  5670. /* Generates bytecode to parse a single primitive field. */
  5671. static void generate_primitivefield(compiler *c, const upb_fielddef *f,
  5672. upb_pbdecodermethod *method) {
  5673. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  5674. upb_descriptortype_t descriptor_type = upb_fielddef_descriptortype(f);
  5675. opcode parse_type;
  5676. upb_selector_t sel;
  5677. int wire_type;
  5678. label(c, LABEL_FIELD);
  5679. /* From a decoding perspective, ENUM is the same as INT32. */
  5680. if (descriptor_type == UPB_DESCRIPTOR_TYPE_ENUM)
  5681. descriptor_type = UPB_DESCRIPTOR_TYPE_INT32;
  5682. parse_type = (opcode)descriptor_type;
  5683. /* TODO(haberman): generate packed or non-packed first depending on "packed"
  5684. * setting in the fielddef. This will favor (in speed) whichever was
  5685. * specified. */
  5686. UPB_ASSERT((int)parse_type >= 0 && parse_type <= OP_MAX);
  5687. sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  5688. wire_type = upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  5689. if (upb_fielddef_isseq(f)) {
  5690. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5691. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  5692. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  5693. putop(c, OP_PUSHLENDELIM);
  5694. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); /* Packed */
  5695. label(c, LABEL_LOOPSTART);
  5696. putop(c, parse_type, sel);
  5697. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5698. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5699. dispatchtarget(c, method, f, wire_type);
  5700. putop(c, OP_PUSHTAGDELIM, 0);
  5701. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); /* Non-packed */
  5702. label(c, LABEL_LOOPSTART);
  5703. putop(c, parse_type, sel);
  5704. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5705. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  5706. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5707. label(c, LABEL_LOOPBREAK);
  5708. putop(c, OP_POP); /* Packed and non-packed join. */
  5709. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  5710. putop(c, OP_SETDELIM); /* Could remove for non-packed by dup ENDSEQ. */
  5711. } else {
  5712. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5713. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  5714. dispatchtarget(c, method, f, wire_type);
  5715. putop(c, parse_type, sel);
  5716. }
  5717. }
  5718. /* Adds bytecode for parsing the given message to the given decoderplan,
  5719. * while adding all dispatch targets to this message's dispatch table. */
  5720. static void compile_method(compiler *c, upb_pbdecodermethod *method) {
  5721. const upb_handlers *h;
  5722. const upb_msgdef *md;
  5723. uint32_t* start_pc;
  5724. upb_msg_field_iter i;
  5725. upb_value val;
  5726. UPB_ASSERT(method);
  5727. /* Clear all entries in the dispatch table. */
  5728. upb_inttable_uninit(&method->dispatch);
  5729. upb_inttable_init(&method->dispatch, UPB_CTYPE_UINT64);
  5730. h = upb_pbdecodermethod_desthandlers(method);
  5731. md = upb_handlers_msgdef(h);
  5732. method->code_base.ofs = pcofs(c);
  5733. putop(c, OP_SETDISPATCH, &method->dispatch);
  5734. putsel(c, OP_STARTMSG, UPB_STARTMSG_SELECTOR, h);
  5735. label(c, LABEL_FIELD);
  5736. start_pc = c->pc;
  5737. for(upb_msg_field_begin(&i, md);
  5738. !upb_msg_field_done(&i);
  5739. upb_msg_field_next(&i)) {
  5740. const upb_fielddef *f = upb_msg_iter_field(&i);
  5741. upb_fieldtype_t type = upb_fielddef_type(f);
  5742. if (type == UPB_TYPE_MESSAGE && !(haslazyhandlers(h, f) && c->lazy)) {
  5743. generate_msgfield(c, f, method);
  5744. } else if (type == UPB_TYPE_STRING || type == UPB_TYPE_BYTES ||
  5745. type == UPB_TYPE_MESSAGE) {
  5746. generate_delimfield(c, f, method);
  5747. } else {
  5748. generate_primitivefield(c, f, method);
  5749. }
  5750. }
  5751. /* If there were no fields, or if no handlers were defined, we need to
  5752. * generate a non-empty loop body so that we can at least dispatch for unknown
  5753. * fields and check for the end of the message. */
  5754. if (c->pc == start_pc) {
  5755. /* Check for end-of-message. */
  5756. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5757. /* Unconditionally dispatch. */
  5758. putop(c, OP_DISPATCH, 0);
  5759. }
  5760. /* For now we just loop back to the last field of the message (or if none,
  5761. * the DISPATCH opcode for the message). */
  5762. putop(c, OP_BRANCH, -LABEL_FIELD);
  5763. /* Insert both a label and a dispatch table entry for this end-of-msg. */
  5764. label(c, LABEL_ENDMSG);
  5765. val = upb_value_uint64(pcofs(c) - method->code_base.ofs);
  5766. upb_inttable_insert(&method->dispatch, DISPATCH_ENDMSG, val);
  5767. putsel(c, OP_ENDMSG, UPB_ENDMSG_SELECTOR, h);
  5768. putop(c, OP_RET);
  5769. upb_inttable_compact(&method->dispatch);
  5770. }
  5771. /* Populate "methods" with new upb_pbdecodermethod objects reachable from "h".
  5772. * Returns the method for these handlers.
  5773. *
  5774. * Generates a new method for every destination handlers reachable from "h". */
  5775. static void find_methods(compiler *c, const upb_handlers *h) {
  5776. upb_value v;
  5777. upb_msg_field_iter i;
  5778. const upb_msgdef *md;
  5779. upb_pbdecodermethod *method;
  5780. if (upb_inttable_lookupptr(&c->group->methods, h, &v))
  5781. return;
  5782. method = newmethod(h, c->group);
  5783. upb_inttable_insertptr(&c->group->methods, h, upb_value_ptr(method));
  5784. /* Find submethods. */
  5785. md = upb_handlers_msgdef(h);
  5786. for(upb_msg_field_begin(&i, md);
  5787. !upb_msg_field_done(&i);
  5788. upb_msg_field_next(&i)) {
  5789. const upb_fielddef *f = upb_msg_iter_field(&i);
  5790. const upb_handlers *sub_h;
  5791. if (upb_fielddef_type(f) == UPB_TYPE_MESSAGE &&
  5792. (sub_h = upb_handlers_getsubhandlers(h, f)) != NULL) {
  5793. /* We only generate a decoder method for submessages with handlers.
  5794. * Others will be parsed as unknown fields. */
  5795. find_methods(c, sub_h);
  5796. }
  5797. }
  5798. }
  5799. /* (Re-)compile bytecode for all messages in "msgs."
  5800. * Overwrites any existing bytecode in "c". */
  5801. static void compile_methods(compiler *c) {
  5802. upb_inttable_iter i;
  5803. /* Start over at the beginning of the bytecode. */
  5804. c->pc = c->group->bytecode;
  5805. upb_inttable_begin(&i, &c->group->methods);
  5806. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5807. upb_pbdecodermethod *method = upb_value_getptr(upb_inttable_iter_value(&i));
  5808. compile_method(c, method);
  5809. }
  5810. }
  5811. static void set_bytecode_handlers(mgroup *g) {
  5812. upb_inttable_iter i;
  5813. upb_inttable_begin(&i, &g->methods);
  5814. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5815. upb_pbdecodermethod *m = upb_value_getptr(upb_inttable_iter_value(&i));
  5816. upb_byteshandler *h = &m->input_handler_;
  5817. m->code_base.ptr = g->bytecode + m->code_base.ofs;
  5818. upb_byteshandler_setstartstr(h, upb_pbdecoder_startbc, m->code_base.ptr);
  5819. upb_byteshandler_setstring(h, upb_pbdecoder_decode, g);
  5820. upb_byteshandler_setendstr(h, upb_pbdecoder_end, m);
  5821. }
  5822. }
  5823. /* TODO(haberman): allow this to be constructed for an arbitrary set of dest
  5824. * handlers and other mgroups (but verify we have a transitive closure). */
  5825. const mgroup *mgroup_new(const upb_handlers *dest, bool lazy) {
  5826. mgroup *g;
  5827. compiler *c;
  5828. g = newgroup();
  5829. c = newcompiler(g, lazy);
  5830. find_methods(c, dest);
  5831. /* We compile in two passes:
  5832. * 1. all messages are assigned relative offsets from the beginning of the
  5833. * bytecode (saved in method->code_base).
  5834. * 2. forwards OP_CALL instructions can be correctly linked since message
  5835. * offsets have been previously assigned.
  5836. *
  5837. * Could avoid the second pass by linking OP_CALL instructions somehow. */
  5838. compile_methods(c);
  5839. compile_methods(c);
  5840. g->bytecode_end = c->pc;
  5841. freecompiler(c);
  5842. #ifdef UPB_DUMP_BYTECODE
  5843. {
  5844. FILE *f = fopen("/tmp/upb-bytecode", "w");
  5845. UPB_ASSERT(f);
  5846. dumpbc(g->bytecode, g->bytecode_end, stderr);
  5847. dumpbc(g->bytecode, g->bytecode_end, f);
  5848. fclose(f);
  5849. f = fopen("/tmp/upb-bytecode.bin", "wb");
  5850. UPB_ASSERT(f);
  5851. fwrite(g->bytecode, 1, g->bytecode_end - g->bytecode, f);
  5852. fclose(f);
  5853. }
  5854. #endif
  5855. set_bytecode_handlers(g);
  5856. return g;
  5857. }
  5858. /* upb_pbcodecache ************************************************************/
  5859. upb_pbcodecache *upb_pbcodecache_new(upb_handlercache *dest) {
  5860. upb_pbcodecache *c = upb_gmalloc(sizeof(*c));
  5861. if (!c) return NULL;
  5862. c->dest = dest;
  5863. c->lazy = false;
  5864. c->arena = upb_arena_new();
  5865. if (!upb_inttable_init(&c->groups, UPB_CTYPE_CONSTPTR)) return NULL;
  5866. return c;
  5867. }
  5868. void upb_pbcodecache_free(upb_pbcodecache *c) {
  5869. upb_inttable_iter i;
  5870. upb_inttable_begin(&i, &c->groups);
  5871. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5872. upb_value val = upb_inttable_iter_value(&i);
  5873. freegroup((void*)upb_value_getconstptr(val));
  5874. }
  5875. upb_inttable_uninit(&c->groups);
  5876. upb_arena_free(c->arena);
  5877. upb_gfree(c);
  5878. }
  5879. void upb_pbdecodermethodopts_setlazy(upb_pbcodecache *c, bool lazy) {
  5880. UPB_ASSERT(upb_inttable_count(&c->groups) == 0);
  5881. c->lazy = lazy;
  5882. }
  5883. const upb_pbdecodermethod *upb_pbcodecache_get(upb_pbcodecache *c,
  5884. const upb_msgdef *md) {
  5885. upb_value v;
  5886. bool ok;
  5887. const upb_handlers *h;
  5888. const mgroup *g;
  5889. h = upb_handlercache_get(c->dest, md);
  5890. if (upb_inttable_lookupptr(&c->groups, md, &v)) {
  5891. g = upb_value_getconstptr(v);
  5892. } else {
  5893. g = mgroup_new(h, c->lazy);
  5894. ok = upb_inttable_insertptr(&c->groups, md, upb_value_constptr(g));
  5895. UPB_ASSUME(ok);
  5896. }
  5897. ok = upb_inttable_lookupptr(&g->methods, h, &v);
  5898. UPB_ASSUME(ok);
  5899. return upb_value_getptr(v);
  5900. }
  5901. /*
  5902. ** upb::Decoder (Bytecode Decoder VM)
  5903. **
  5904. ** Bytecode must previously have been generated using the bytecode compiler in
  5905. ** compile_decoder.c. This decoder then walks through the bytecode op-by-op to
  5906. ** parse the input.
  5907. **
  5908. ** Decoding is fully resumable; we just keep a pointer to the current bytecode
  5909. ** instruction and resume from there. A fair amount of the logic here is to
  5910. ** handle the fact that values can span buffer seams and we have to be able to
  5911. ** be capable of suspending/resuming from any byte in the stream. This
  5912. ** sometimes requires keeping a few trailing bytes from the last buffer around
  5913. ** in the "residual" buffer.
  5914. */
  5915. #include <inttypes.h>
  5916. #include <stddef.h>
  5917. #ifdef UPB_DUMP_BYTECODE
  5918. #include <stdio.h>
  5919. #endif
  5920. #define CHECK_SUSPEND(x) if (!(x)) return upb_pbdecoder_suspend(d);
  5921. /* Error messages that are shared between the bytecode and JIT decoders. */
  5922. const char *kPbDecoderStackOverflow = "Nesting too deep.";
  5923. const char *kPbDecoderSubmessageTooLong =
  5924. "Submessage end extends past enclosing submessage.";
  5925. /* Error messages shared within this file. */
  5926. static const char *kUnterminatedVarint = "Unterminated varint.";
  5927. /* upb_pbdecoder **************************************************************/
  5928. static opcode halt = OP_HALT;
  5929. /* A dummy character we can point to when the user passes us a NULL buffer.
  5930. * We need this because in C (NULL + 0) and (NULL - NULL) are undefined
  5931. * behavior, which would invalidate functions like curbufleft(). */
  5932. static const char dummy_char;
  5933. /* Whether an op consumes any of the input buffer. */
  5934. static bool consumes_input(opcode op) {
  5935. switch (op) {
  5936. case OP_SETDISPATCH:
  5937. case OP_STARTMSG:
  5938. case OP_ENDMSG:
  5939. case OP_STARTSEQ:
  5940. case OP_ENDSEQ:
  5941. case OP_STARTSUBMSG:
  5942. case OP_ENDSUBMSG:
  5943. case OP_STARTSTR:
  5944. case OP_ENDSTR:
  5945. case OP_PUSHTAGDELIM:
  5946. case OP_POP:
  5947. case OP_SETDELIM:
  5948. case OP_SETBIGGROUPNUM:
  5949. case OP_CHECKDELIM:
  5950. case OP_CALL:
  5951. case OP_RET:
  5952. case OP_BRANCH:
  5953. return false;
  5954. default:
  5955. return true;
  5956. }
  5957. }
  5958. static size_t stacksize(upb_pbdecoder *d, size_t entries) {
  5959. UPB_UNUSED(d);
  5960. return entries * sizeof(upb_pbdecoder_frame);
  5961. }
  5962. static size_t callstacksize(upb_pbdecoder *d, size_t entries) {
  5963. UPB_UNUSED(d);
  5964. return entries * sizeof(uint32_t*);
  5965. }
  5966. static bool in_residual_buf(const upb_pbdecoder *d, const char *p);
  5967. /* It's unfortunate that we have to micro-manage the compiler with
  5968. * UPB_FORCEINLINE and UPB_NOINLINE, especially since this tuning is necessarily
  5969. * specific to one hardware configuration. But empirically on a Core i7,
  5970. * performance increases 30-50% with these annotations. Every instance where
  5971. * these appear, gcc 4.2.1 made the wrong decision and degraded performance in
  5972. * benchmarks. */
  5973. static void seterr(upb_pbdecoder *d, const char *msg) {
  5974. upb_status_seterrmsg(d->status, msg);
  5975. }
  5976. void upb_pbdecoder_seterr(upb_pbdecoder *d, const char *msg) {
  5977. seterr(d, msg);
  5978. }
  5979. /* Buffering ******************************************************************/
  5980. /* We operate on one buffer at a time, which is either the user's buffer passed
  5981. * to our "decode" callback or some residual bytes from the previous buffer. */
  5982. /* How many bytes can be safely read from d->ptr without reading past end-of-buf
  5983. * or past the current delimited end. */
  5984. static size_t curbufleft(const upb_pbdecoder *d) {
  5985. UPB_ASSERT(d->data_end >= d->ptr);
  5986. return d->data_end - d->ptr;
  5987. }
  5988. /* How many bytes are available before end-of-buffer. */
  5989. static size_t bufleft(const upb_pbdecoder *d) {
  5990. return d->end - d->ptr;
  5991. }
  5992. /* Overall stream offset of d->ptr. */
  5993. uint64_t offset(const upb_pbdecoder *d) {
  5994. return d->bufstart_ofs + (d->ptr - d->buf);
  5995. }
  5996. /* How many bytes are available before the end of this delimited region. */
  5997. size_t delim_remaining(const upb_pbdecoder *d) {
  5998. return d->top->end_ofs - offset(d);
  5999. }
  6000. /* Advances d->ptr. */
  6001. static void advance(upb_pbdecoder *d, size_t len) {
  6002. UPB_ASSERT(curbufleft(d) >= len);
  6003. d->ptr += len;
  6004. }
  6005. static bool in_buf(const char *p, const char *buf, const char *end) {
  6006. return p >= buf && p <= end;
  6007. }
  6008. static bool in_residual_buf(const upb_pbdecoder *d, const char *p) {
  6009. return in_buf(p, d->residual, d->residual_end);
  6010. }
  6011. /* Calculates the delim_end value, which is affected by both the current buffer
  6012. * and the parsing stack, so must be called whenever either is updated. */
  6013. static void set_delim_end(upb_pbdecoder *d) {
  6014. size_t delim_ofs = d->top->end_ofs - d->bufstart_ofs;
  6015. if (delim_ofs <= (size_t)(d->end - d->buf)) {
  6016. d->delim_end = d->buf + delim_ofs;
  6017. d->data_end = d->delim_end;
  6018. } else {
  6019. d->data_end = d->end;
  6020. d->delim_end = NULL;
  6021. }
  6022. }
  6023. static void switchtobuf(upb_pbdecoder *d, const char *buf, const char *end) {
  6024. d->ptr = buf;
  6025. d->buf = buf;
  6026. d->end = end;
  6027. set_delim_end(d);
  6028. }
  6029. static void advancetobuf(upb_pbdecoder *d, const char *buf, size_t len) {
  6030. UPB_ASSERT(curbufleft(d) == 0);
  6031. d->bufstart_ofs += (d->end - d->buf);
  6032. switchtobuf(d, buf, buf + len);
  6033. }
  6034. static void checkpoint(upb_pbdecoder *d) {
  6035. /* The assertion here is in the interests of efficiency, not correctness.
  6036. * We are trying to ensure that we don't checkpoint() more often than
  6037. * necessary. */
  6038. UPB_ASSERT(d->checkpoint != d->ptr);
  6039. d->checkpoint = d->ptr;
  6040. }
  6041. /* Skips "bytes" bytes in the stream, which may be more than available. If we
  6042. * skip more bytes than are available, we return a long read count to the caller
  6043. * indicating how many bytes can be skipped over before passing actual data
  6044. * again. Skipped bytes can pass a NULL buffer and the decoder guarantees they
  6045. * won't actually be read.
  6046. */
  6047. static int32_t skip(upb_pbdecoder *d, size_t bytes) {
  6048. UPB_ASSERT(!in_residual_buf(d, d->ptr) || d->size_param == 0);
  6049. UPB_ASSERT(d->skip == 0);
  6050. if (bytes > delim_remaining(d)) {
  6051. seterr(d, "Skipped value extended beyond enclosing submessage.");
  6052. return (int32_t)upb_pbdecoder_suspend(d);
  6053. } else if (bufleft(d) >= bytes) {
  6054. /* Skipped data is all in current buffer, and more is still available. */
  6055. advance(d, bytes);
  6056. d->skip = 0;
  6057. return DECODE_OK;
  6058. } else {
  6059. /* Skipped data extends beyond currently available buffers. */
  6060. d->pc = d->last;
  6061. d->skip = bytes - curbufleft(d);
  6062. d->bufstart_ofs += (d->end - d->buf);
  6063. d->residual_end = d->residual;
  6064. switchtobuf(d, d->residual, d->residual_end);
  6065. return (int32_t)(d->size_param + d->skip);
  6066. }
  6067. }
  6068. /* Resumes the decoder from an initial state or from a previous suspend. */
  6069. int32_t upb_pbdecoder_resume(upb_pbdecoder *d, void *p, const char *buf,
  6070. size_t size, const upb_bufhandle *handle) {
  6071. UPB_UNUSED(p); /* Useless; just for the benefit of the JIT. */
  6072. /* d->skip and d->residual_end could probably elegantly be represented
  6073. * as a single variable, to more easily represent this invariant. */
  6074. UPB_ASSERT(!(d->skip && d->residual_end > d->residual));
  6075. /* We need to remember the original size_param, so that the value we return
  6076. * is relative to it, even if we do some skipping first. */
  6077. d->size_param = size;
  6078. d->handle = handle;
  6079. /* Have to handle this case specially (ie. not with skip()) because the user
  6080. * is allowed to pass a NULL buffer here, which won't allow us to safely
  6081. * calculate a d->end or use our normal functions like curbufleft(). */
  6082. if (d->skip && d->skip >= size) {
  6083. d->skip -= size;
  6084. d->bufstart_ofs += size;
  6085. buf = &dummy_char;
  6086. size = 0;
  6087. /* We can't just return now, because we might need to execute some ops
  6088. * like CHECKDELIM, which could call some callbacks and pop the stack. */
  6089. }
  6090. /* We need to pretend that this was the actual buffer param, since some of the
  6091. * calculations assume that d->ptr/d->buf is relative to this. */
  6092. d->buf_param = buf;
  6093. if (!buf) {
  6094. /* NULL buf is ok if its entire span is covered by the "skip" above, but
  6095. * by this point we know that "skip" doesn't cover the buffer. */
  6096. seterr(d, "Passed NULL buffer over non-skippable region.");
  6097. return (int32_t)upb_pbdecoder_suspend(d);
  6098. }
  6099. if (d->residual_end > d->residual) {
  6100. /* We have residual bytes from the last buffer. */
  6101. UPB_ASSERT(d->ptr == d->residual);
  6102. } else {
  6103. switchtobuf(d, buf, buf + size);
  6104. }
  6105. d->checkpoint = d->ptr;
  6106. /* Handle skips that don't cover the whole buffer (as above). */
  6107. if (d->skip) {
  6108. size_t skip_bytes = d->skip;
  6109. d->skip = 0;
  6110. CHECK_RETURN(skip(d, skip_bytes));
  6111. checkpoint(d);
  6112. }
  6113. /* If we're inside an unknown group, continue to parse unknown values. */
  6114. if (d->top->groupnum < 0) {
  6115. CHECK_RETURN(upb_pbdecoder_skipunknown(d, -1, 0));
  6116. checkpoint(d);
  6117. }
  6118. return DECODE_OK;
  6119. }
  6120. /* Suspends the decoder at the last checkpoint, without saving any residual
  6121. * bytes. If there are any unconsumed bytes, returns a short byte count. */
  6122. size_t upb_pbdecoder_suspend(upb_pbdecoder *d) {
  6123. d->pc = d->last;
  6124. if (d->checkpoint == d->residual) {
  6125. /* Checkpoint was in residual buf; no user bytes were consumed. */
  6126. d->ptr = d->residual;
  6127. return 0;
  6128. } else {
  6129. size_t ret = d->size_param - (d->end - d->checkpoint);
  6130. UPB_ASSERT(!in_residual_buf(d, d->checkpoint));
  6131. UPB_ASSERT(d->buf == d->buf_param || d->buf == &dummy_char);
  6132. d->bufstart_ofs += (d->checkpoint - d->buf);
  6133. d->residual_end = d->residual;
  6134. switchtobuf(d, d->residual, d->residual_end);
  6135. return ret;
  6136. }
  6137. }
  6138. /* Suspends the decoder at the last checkpoint, and saves any unconsumed
  6139. * bytes in our residual buffer. This is necessary if we need more user
  6140. * bytes to form a complete value, which might not be contiguous in the
  6141. * user's buffers. Always consumes all user bytes. */
  6142. static size_t suspend_save(upb_pbdecoder *d) {
  6143. /* We hit end-of-buffer before we could parse a full value.
  6144. * Save any unconsumed bytes (if any) to the residual buffer. */
  6145. d->pc = d->last;
  6146. if (d->checkpoint == d->residual) {
  6147. /* Checkpoint was in residual buf; append user byte(s) to residual buf. */
  6148. UPB_ASSERT((d->residual_end - d->residual) + d->size_param <=
  6149. sizeof(d->residual));
  6150. if (!in_residual_buf(d, d->ptr)) {
  6151. d->bufstart_ofs -= (d->residual_end - d->residual);
  6152. }
  6153. memcpy(d->residual_end, d->buf_param, d->size_param);
  6154. d->residual_end += d->size_param;
  6155. } else {
  6156. /* Checkpoint was in user buf; old residual bytes not needed. */
  6157. size_t save;
  6158. UPB_ASSERT(!in_residual_buf(d, d->checkpoint));
  6159. d->ptr = d->checkpoint;
  6160. save = curbufleft(d);
  6161. UPB_ASSERT(save <= sizeof(d->residual));
  6162. memcpy(d->residual, d->ptr, save);
  6163. d->residual_end = d->residual + save;
  6164. d->bufstart_ofs = offset(d);
  6165. }
  6166. switchtobuf(d, d->residual, d->residual_end);
  6167. return d->size_param;
  6168. }
  6169. /* Copies the next "bytes" bytes into "buf" and advances the stream.
  6170. * Requires that this many bytes are available in the current buffer. */
  6171. UPB_FORCEINLINE static void consumebytes(upb_pbdecoder *d, void *buf,
  6172. size_t bytes) {
  6173. UPB_ASSERT(bytes <= curbufleft(d));
  6174. memcpy(buf, d->ptr, bytes);
  6175. advance(d, bytes);
  6176. }
  6177. /* Slow path for getting the next "bytes" bytes, regardless of whether they are
  6178. * available in the current buffer or not. Returns a status code as described
  6179. * in decoder.int.h. */
  6180. UPB_NOINLINE static int32_t getbytes_slow(upb_pbdecoder *d, void *buf,
  6181. size_t bytes) {
  6182. const size_t avail = curbufleft(d);
  6183. consumebytes(d, buf, avail);
  6184. bytes -= avail;
  6185. UPB_ASSERT(bytes > 0);
  6186. if (in_residual_buf(d, d->ptr)) {
  6187. advancetobuf(d, d->buf_param, d->size_param);
  6188. }
  6189. if (curbufleft(d) >= bytes) {
  6190. consumebytes(d, (char *)buf + avail, bytes);
  6191. return DECODE_OK;
  6192. } else if (d->data_end == d->delim_end) {
  6193. seterr(d, "Submessage ended in the middle of a value or group");
  6194. return (int32_t)upb_pbdecoder_suspend(d);
  6195. } else {
  6196. return (int32_t)suspend_save(d);
  6197. }
  6198. }
  6199. /* Gets the next "bytes" bytes, regardless of whether they are available in the
  6200. * current buffer or not. Returns a status code as described in decoder.int.h.
  6201. */
  6202. UPB_FORCEINLINE static int32_t getbytes(upb_pbdecoder *d, void *buf,
  6203. size_t bytes) {
  6204. if (curbufleft(d) >= bytes) {
  6205. /* Buffer has enough data to satisfy. */
  6206. consumebytes(d, buf, bytes);
  6207. return DECODE_OK;
  6208. } else {
  6209. return getbytes_slow(d, buf, bytes);
  6210. }
  6211. }
  6212. UPB_NOINLINE static size_t peekbytes_slow(upb_pbdecoder *d, void *buf,
  6213. size_t bytes) {
  6214. size_t ret = curbufleft(d);
  6215. memcpy(buf, d->ptr, ret);
  6216. if (in_residual_buf(d, d->ptr)) {
  6217. size_t copy = UPB_MIN(bytes - ret, d->size_param);
  6218. memcpy((char *)buf + ret, d->buf_param, copy);
  6219. ret += copy;
  6220. }
  6221. return ret;
  6222. }
  6223. UPB_FORCEINLINE static size_t peekbytes(upb_pbdecoder *d, void *buf,
  6224. size_t bytes) {
  6225. if (curbufleft(d) >= bytes) {
  6226. memcpy(buf, d->ptr, bytes);
  6227. return bytes;
  6228. } else {
  6229. return peekbytes_slow(d, buf, bytes);
  6230. }
  6231. }
  6232. /* Decoding of wire types *****************************************************/
  6233. /* Slow path for decoding a varint from the current buffer position.
  6234. * Returns a status code as described in decoder.int.h. */
  6235. UPB_NOINLINE int32_t upb_pbdecoder_decode_varint_slow(upb_pbdecoder *d,
  6236. uint64_t *u64) {
  6237. uint8_t byte = 0x80;
  6238. int bitpos;
  6239. *u64 = 0;
  6240. for(bitpos = 0; bitpos < 70 && (byte & 0x80); bitpos += 7) {
  6241. CHECK_RETURN(getbytes(d, &byte, 1));
  6242. *u64 |= (uint64_t)(byte & 0x7F) << bitpos;
  6243. }
  6244. if(bitpos == 70 && (byte & 0x80)) {
  6245. seterr(d, kUnterminatedVarint);
  6246. return (int32_t)upb_pbdecoder_suspend(d);
  6247. }
  6248. return DECODE_OK;
  6249. }
  6250. /* Decodes a varint from the current buffer position.
  6251. * Returns a status code as described in decoder.int.h. */
  6252. UPB_FORCEINLINE static int32_t decode_varint(upb_pbdecoder *d, uint64_t *u64) {
  6253. if (curbufleft(d) > 0 && !(*d->ptr & 0x80)) {
  6254. *u64 = *d->ptr;
  6255. advance(d, 1);
  6256. return DECODE_OK;
  6257. } else if (curbufleft(d) >= 10) {
  6258. /* Fast case. */
  6259. upb_decoderet r = upb_vdecode_fast(d->ptr);
  6260. if (r.p == NULL) {
  6261. seterr(d, kUnterminatedVarint);
  6262. return (int32_t)upb_pbdecoder_suspend(d);
  6263. }
  6264. advance(d, r.p - d->ptr);
  6265. *u64 = r.val;
  6266. return DECODE_OK;
  6267. } else {
  6268. /* Slow case -- varint spans buffer seam. */
  6269. return upb_pbdecoder_decode_varint_slow(d, u64);
  6270. }
  6271. }
  6272. /* Decodes a 32-bit varint from the current buffer position.
  6273. * Returns a status code as described in decoder.int.h. */
  6274. UPB_FORCEINLINE static int32_t decode_v32(upb_pbdecoder *d, uint32_t *u32) {
  6275. uint64_t u64;
  6276. int32_t ret = decode_varint(d, &u64);
  6277. if (ret >= 0) return ret;
  6278. if (u64 > UINT32_MAX) {
  6279. seterr(d, "Unterminated 32-bit varint");
  6280. /* TODO(haberman) guarantee that this function return is >= 0 somehow,
  6281. * so we know this path will always be treated as error by our caller.
  6282. * Right now the size_t -> int32_t can overflow and produce negative values.
  6283. */
  6284. *u32 = 0;
  6285. return (int32_t)upb_pbdecoder_suspend(d);
  6286. }
  6287. *u32 = (uint32_t)u64;
  6288. return DECODE_OK;
  6289. }
  6290. /* Decodes a fixed32 from the current buffer position.
  6291. * Returns a status code as described in decoder.int.h.
  6292. * TODO: proper byte swapping for big-endian machines. */
  6293. UPB_FORCEINLINE static int32_t decode_fixed32(upb_pbdecoder *d, uint32_t *u32) {
  6294. return getbytes(d, u32, 4);
  6295. }
  6296. /* Decodes a fixed64 from the current buffer position.
  6297. * Returns a status code as described in decoder.int.h.
  6298. * TODO: proper byte swapping for big-endian machines. */
  6299. UPB_FORCEINLINE static int32_t decode_fixed64(upb_pbdecoder *d, uint64_t *u64) {
  6300. return getbytes(d, u64, 8);
  6301. }
  6302. /* Non-static versions of the above functions.
  6303. * These are called by the JIT for fallback paths. */
  6304. int32_t upb_pbdecoder_decode_f32(upb_pbdecoder *d, uint32_t *u32) {
  6305. return decode_fixed32(d, u32);
  6306. }
  6307. int32_t upb_pbdecoder_decode_f64(upb_pbdecoder *d, uint64_t *u64) {
  6308. return decode_fixed64(d, u64);
  6309. }
  6310. static double as_double(uint64_t n) { double d; memcpy(&d, &n, 8); return d; }
  6311. static float as_float(uint32_t n) { float f; memcpy(&f, &n, 4); return f; }
  6312. /* Pushes a frame onto the decoder stack. */
  6313. static bool decoder_push(upb_pbdecoder *d, uint64_t end) {
  6314. upb_pbdecoder_frame *fr = d->top;
  6315. if (end > fr->end_ofs) {
  6316. seterr(d, kPbDecoderSubmessageTooLong);
  6317. return false;
  6318. } else if (fr == d->limit) {
  6319. seterr(d, kPbDecoderStackOverflow);
  6320. return false;
  6321. }
  6322. fr++;
  6323. fr->end_ofs = end;
  6324. fr->dispatch = NULL;
  6325. fr->groupnum = 0;
  6326. d->top = fr;
  6327. return true;
  6328. }
  6329. static bool pushtagdelim(upb_pbdecoder *d, uint32_t arg) {
  6330. /* While we expect to see an "end" tag (either ENDGROUP or a non-sequence
  6331. * field number) prior to hitting any enclosing submessage end, pushing our
  6332. * existing delim end prevents us from continuing to parse values from a
  6333. * corrupt proto that doesn't give us an END tag in time. */
  6334. if (!decoder_push(d, d->top->end_ofs))
  6335. return false;
  6336. d->top->groupnum = arg;
  6337. return true;
  6338. }
  6339. /* Pops a frame from the decoder stack. */
  6340. static void decoder_pop(upb_pbdecoder *d) { d->top--; }
  6341. UPB_NOINLINE int32_t upb_pbdecoder_checktag_slow(upb_pbdecoder *d,
  6342. uint64_t expected) {
  6343. uint64_t data = 0;
  6344. size_t bytes = upb_value_size(expected);
  6345. size_t read = peekbytes(d, &data, bytes);
  6346. if (read == bytes && data == expected) {
  6347. /* Advance past matched bytes. */
  6348. int32_t ok = getbytes(d, &data, read);
  6349. UPB_ASSERT(ok < 0);
  6350. return DECODE_OK;
  6351. } else if (read < bytes && memcmp(&data, &expected, read) == 0) {
  6352. return (int32_t)suspend_save(d);
  6353. } else {
  6354. return DECODE_MISMATCH;
  6355. }
  6356. }
  6357. int32_t upb_pbdecoder_skipunknown(upb_pbdecoder *d, int32_t fieldnum,
  6358. uint8_t wire_type) {
  6359. if (fieldnum >= 0)
  6360. goto have_tag;
  6361. while (true) {
  6362. uint32_t tag;
  6363. CHECK_RETURN(decode_v32(d, &tag));
  6364. wire_type = tag & 0x7;
  6365. fieldnum = tag >> 3;
  6366. have_tag:
  6367. if (fieldnum == 0) {
  6368. seterr(d, "Saw invalid field number (0)");
  6369. return (int32_t)upb_pbdecoder_suspend(d);
  6370. }
  6371. switch (wire_type) {
  6372. case UPB_WIRE_TYPE_32BIT:
  6373. CHECK_RETURN(skip(d, 4));
  6374. break;
  6375. case UPB_WIRE_TYPE_64BIT:
  6376. CHECK_RETURN(skip(d, 8));
  6377. break;
  6378. case UPB_WIRE_TYPE_VARINT: {
  6379. uint64_t u64;
  6380. CHECK_RETURN(decode_varint(d, &u64));
  6381. break;
  6382. }
  6383. case UPB_WIRE_TYPE_DELIMITED: {
  6384. uint32_t len;
  6385. CHECK_RETURN(decode_v32(d, &len));
  6386. CHECK_RETURN(skip(d, len));
  6387. break;
  6388. }
  6389. case UPB_WIRE_TYPE_START_GROUP:
  6390. if (!pushtagdelim(d, -fieldnum)) {
  6391. return (int32_t)upb_pbdecoder_suspend(d);
  6392. }
  6393. break;
  6394. case UPB_WIRE_TYPE_END_GROUP:
  6395. if (fieldnum == -d->top->groupnum) {
  6396. decoder_pop(d);
  6397. } else if (fieldnum == d->top->groupnum) {
  6398. return DECODE_ENDGROUP;
  6399. } else {
  6400. seterr(d, "Unmatched ENDGROUP tag.");
  6401. return (int32_t)upb_pbdecoder_suspend(d);
  6402. }
  6403. break;
  6404. default:
  6405. seterr(d, "Invalid wire type");
  6406. return (int32_t)upb_pbdecoder_suspend(d);
  6407. }
  6408. if (d->top->groupnum >= 0) {
  6409. /* TODO: More code needed for handling unknown groups. */
  6410. upb_sink_putunknown(d->top->sink, d->checkpoint, d->ptr - d->checkpoint);
  6411. return DECODE_OK;
  6412. }
  6413. /* Unknown group -- continue looping over unknown fields. */
  6414. checkpoint(d);
  6415. }
  6416. }
  6417. static void goto_endmsg(upb_pbdecoder *d) {
  6418. upb_value v;
  6419. bool found = upb_inttable_lookup32(d->top->dispatch, DISPATCH_ENDMSG, &v);
  6420. UPB_ASSERT(found);
  6421. d->pc = d->top->base + upb_value_getuint64(v);
  6422. }
  6423. /* Parses a tag and jumps to the corresponding bytecode instruction for this
  6424. * field.
  6425. *
  6426. * If the tag is unknown (or the wire type doesn't match), parses the field as
  6427. * unknown. If the tag is a valid ENDGROUP tag, jumps to the bytecode
  6428. * instruction for the end of message. */
  6429. static int32_t dispatch(upb_pbdecoder *d) {
  6430. upb_inttable *dispatch = d->top->dispatch;
  6431. uint32_t tag;
  6432. uint8_t wire_type;
  6433. uint32_t fieldnum;
  6434. upb_value val;
  6435. int32_t retval;
  6436. /* Decode tag. */
  6437. CHECK_RETURN(decode_v32(d, &tag));
  6438. wire_type = tag & 0x7;
  6439. fieldnum = tag >> 3;
  6440. /* Lookup tag. Because of packed/non-packed compatibility, we have to
  6441. * check the wire type against two possibilities. */
  6442. if (fieldnum != DISPATCH_ENDMSG &&
  6443. upb_inttable_lookup32(dispatch, fieldnum, &val)) {
  6444. uint64_t v = upb_value_getuint64(val);
  6445. if (wire_type == (v & 0xff)) {
  6446. d->pc = d->top->base + (v >> 16);
  6447. return DECODE_OK;
  6448. } else if (wire_type == ((v >> 8) & 0xff)) {
  6449. bool found =
  6450. upb_inttable_lookup(dispatch, fieldnum + UPB_MAX_FIELDNUMBER, &val);
  6451. UPB_ASSERT(found);
  6452. d->pc = d->top->base + upb_value_getuint64(val);
  6453. return DECODE_OK;
  6454. }
  6455. }
  6456. /* We have some unknown fields (or ENDGROUP) to parse. The DISPATCH or TAG
  6457. * bytecode that triggered this is preceded by a CHECKDELIM bytecode which
  6458. * we need to back up to, so that when we're done skipping unknown data we
  6459. * can re-check the delimited end. */
  6460. d->last--; /* Necessary if we get suspended */
  6461. d->pc = d->last;
  6462. UPB_ASSERT(getop(*d->last) == OP_CHECKDELIM);
  6463. /* Unknown field or ENDGROUP. */
  6464. retval = upb_pbdecoder_skipunknown(d, fieldnum, wire_type);
  6465. CHECK_RETURN(retval);
  6466. if (retval == DECODE_ENDGROUP) {
  6467. goto_endmsg(d);
  6468. return DECODE_OK;
  6469. }
  6470. return DECODE_OK;
  6471. }
  6472. /* Callers know that the stack is more than one deep because the opcodes that
  6473. * call this only occur after PUSH operations. */
  6474. upb_pbdecoder_frame *outer_frame(upb_pbdecoder *d) {
  6475. UPB_ASSERT(d->top != d->stack);
  6476. return d->top - 1;
  6477. }
  6478. /* The main decoding loop *****************************************************/
  6479. /* The main decoder VM function. Uses traditional bytecode dispatch loop with a
  6480. * switch() statement. */
  6481. size_t run_decoder_vm(upb_pbdecoder *d, const mgroup *group,
  6482. const upb_bufhandle* handle) {
  6483. #define VMCASE(op, code) \
  6484. case op: { code; if (consumes_input(op)) checkpoint(d); break; }
  6485. #define PRIMITIVE_OP(type, wt, name, convfunc, ctype) \
  6486. VMCASE(OP_PARSE_ ## type, { \
  6487. ctype val; \
  6488. CHECK_RETURN(decode_ ## wt(d, &val)); \
  6489. upb_sink_put ## name(d->top->sink, arg, (convfunc)(val)); \
  6490. })
  6491. while(1) {
  6492. int32_t instruction;
  6493. opcode op;
  6494. uint32_t arg;
  6495. int32_t longofs;
  6496. d->last = d->pc;
  6497. instruction = *d->pc++;
  6498. op = getop(instruction);
  6499. arg = instruction >> 8;
  6500. longofs = arg;
  6501. UPB_ASSERT(d->ptr != d->residual_end);
  6502. UPB_UNUSED(group);
  6503. #ifdef UPB_DUMP_BYTECODE
  6504. fprintf(stderr, "s_ofs=%d buf_ofs=%d data_rem=%d buf_rem=%d delim_rem=%d "
  6505. "%x %s (%d)\n",
  6506. (int)offset(d),
  6507. (int)(d->ptr - d->buf),
  6508. (int)(d->data_end - d->ptr),
  6509. (int)(d->end - d->ptr),
  6510. (int)((d->top->end_ofs - d->bufstart_ofs) - (d->ptr - d->buf)),
  6511. (int)(d->pc - 1 - group->bytecode),
  6512. upb_pbdecoder_getopname(op),
  6513. arg);
  6514. #endif
  6515. switch (op) {
  6516. /* Technically, we are losing data if we see a 32-bit varint that is not
  6517. * properly sign-extended. We could detect this and error about the data
  6518. * loss, but proto2 does not do this, so we pass. */
  6519. PRIMITIVE_OP(INT32, varint, int32, int32_t, uint64_t)
  6520. PRIMITIVE_OP(INT64, varint, int64, int64_t, uint64_t)
  6521. PRIMITIVE_OP(UINT32, varint, uint32, uint32_t, uint64_t)
  6522. PRIMITIVE_OP(UINT64, varint, uint64, uint64_t, uint64_t)
  6523. PRIMITIVE_OP(FIXED32, fixed32, uint32, uint32_t, uint32_t)
  6524. PRIMITIVE_OP(FIXED64, fixed64, uint64, uint64_t, uint64_t)
  6525. PRIMITIVE_OP(SFIXED32, fixed32, int32, int32_t, uint32_t)
  6526. PRIMITIVE_OP(SFIXED64, fixed64, int64, int64_t, uint64_t)
  6527. PRIMITIVE_OP(BOOL, varint, bool, bool, uint64_t)
  6528. PRIMITIVE_OP(DOUBLE, fixed64, double, as_double, uint64_t)
  6529. PRIMITIVE_OP(FLOAT, fixed32, float, as_float, uint32_t)
  6530. PRIMITIVE_OP(SINT32, varint, int32, upb_zzdec_32, uint64_t)
  6531. PRIMITIVE_OP(SINT64, varint, int64, upb_zzdec_64, uint64_t)
  6532. VMCASE(OP_SETDISPATCH,
  6533. d->top->base = d->pc - 1;
  6534. memcpy(&d->top->dispatch, d->pc, sizeof(void*));
  6535. d->pc += sizeof(void*) / sizeof(uint32_t);
  6536. )
  6537. VMCASE(OP_STARTMSG,
  6538. CHECK_SUSPEND(upb_sink_startmsg(d->top->sink));
  6539. )
  6540. VMCASE(OP_ENDMSG,
  6541. CHECK_SUSPEND(upb_sink_endmsg(d->top->sink, d->status));
  6542. )
  6543. VMCASE(OP_STARTSEQ,
  6544. upb_pbdecoder_frame *outer = outer_frame(d);
  6545. CHECK_SUSPEND(upb_sink_startseq(outer->sink, arg, &d->top->sink));
  6546. )
  6547. VMCASE(OP_ENDSEQ,
  6548. CHECK_SUSPEND(upb_sink_endseq(d->top->sink, arg));
  6549. )
  6550. VMCASE(OP_STARTSUBMSG,
  6551. upb_pbdecoder_frame *outer = outer_frame(d);
  6552. CHECK_SUSPEND(upb_sink_startsubmsg(outer->sink, arg, &d->top->sink));
  6553. )
  6554. VMCASE(OP_ENDSUBMSG,
  6555. upb_sink subsink = (d->top + 1)->sink;
  6556. CHECK_SUSPEND(upb_sink_endsubmsg(d->top->sink, subsink, arg));
  6557. )
  6558. VMCASE(OP_STARTSTR,
  6559. uint32_t len = (uint32_t)delim_remaining(d);
  6560. upb_pbdecoder_frame *outer = outer_frame(d);
  6561. CHECK_SUSPEND(upb_sink_startstr(outer->sink, arg, len, &d->top->sink));
  6562. if (len == 0) {
  6563. d->pc++; /* Skip OP_STRING. */
  6564. }
  6565. )
  6566. VMCASE(OP_STRING,
  6567. uint32_t len = (uint32_t)curbufleft(d);
  6568. size_t n = upb_sink_putstring(d->top->sink, arg, d->ptr, len, handle);
  6569. if (n > len) {
  6570. if (n > delim_remaining(d)) {
  6571. seterr(d, "Tried to skip past end of string.");
  6572. return upb_pbdecoder_suspend(d);
  6573. } else {
  6574. int32_t ret = skip(d, n);
  6575. /* This shouldn't return DECODE_OK, because n > len. */
  6576. UPB_ASSERT(ret >= 0);
  6577. return ret;
  6578. }
  6579. }
  6580. advance(d, n);
  6581. if (n < len || d->delim_end == NULL) {
  6582. /* We aren't finished with this string yet. */
  6583. d->pc--; /* Repeat OP_STRING. */
  6584. if (n > 0) checkpoint(d);
  6585. return upb_pbdecoder_suspend(d);
  6586. }
  6587. )
  6588. VMCASE(OP_ENDSTR,
  6589. CHECK_SUSPEND(upb_sink_endstr(d->top->sink, arg));
  6590. )
  6591. VMCASE(OP_PUSHTAGDELIM,
  6592. CHECK_SUSPEND(pushtagdelim(d, arg));
  6593. )
  6594. VMCASE(OP_SETBIGGROUPNUM,
  6595. d->top->groupnum = *d->pc++;
  6596. )
  6597. VMCASE(OP_POP,
  6598. UPB_ASSERT(d->top > d->stack);
  6599. decoder_pop(d);
  6600. )
  6601. VMCASE(OP_PUSHLENDELIM,
  6602. uint32_t len;
  6603. CHECK_RETURN(decode_v32(d, &len));
  6604. CHECK_SUSPEND(decoder_push(d, offset(d) + len));
  6605. set_delim_end(d);
  6606. )
  6607. VMCASE(OP_SETDELIM,
  6608. set_delim_end(d);
  6609. )
  6610. VMCASE(OP_CHECKDELIM,
  6611. /* We are guaranteed of this assert because we never allow ourselves to
  6612. * consume bytes beyond data_end, which covers delim_end when non-NULL.
  6613. */
  6614. UPB_ASSERT(!(d->delim_end && d->ptr > d->delim_end));
  6615. if (d->ptr == d->delim_end)
  6616. d->pc += longofs;
  6617. )
  6618. VMCASE(OP_CALL,
  6619. d->callstack[d->call_len++] = d->pc;
  6620. d->pc += longofs;
  6621. )
  6622. VMCASE(OP_RET,
  6623. UPB_ASSERT(d->call_len > 0);
  6624. d->pc = d->callstack[--d->call_len];
  6625. )
  6626. VMCASE(OP_BRANCH,
  6627. d->pc += longofs;
  6628. )
  6629. VMCASE(OP_TAG1,
  6630. uint8_t expected;
  6631. CHECK_SUSPEND(curbufleft(d) > 0);
  6632. expected = (arg >> 8) & 0xff;
  6633. if (*d->ptr == expected) {
  6634. advance(d, 1);
  6635. } else {
  6636. int8_t shortofs;
  6637. badtag:
  6638. shortofs = arg;
  6639. if (shortofs == LABEL_DISPATCH) {
  6640. CHECK_RETURN(dispatch(d));
  6641. } else {
  6642. d->pc += shortofs;
  6643. break; /* Avoid checkpoint(). */
  6644. }
  6645. }
  6646. )
  6647. VMCASE(OP_TAG2,
  6648. uint16_t expected;
  6649. CHECK_SUSPEND(curbufleft(d) > 0);
  6650. expected = (arg >> 8) & 0xffff;
  6651. if (curbufleft(d) >= 2) {
  6652. uint16_t actual;
  6653. memcpy(&actual, d->ptr, 2);
  6654. if (expected == actual) {
  6655. advance(d, 2);
  6656. } else {
  6657. goto badtag;
  6658. }
  6659. } else {
  6660. int32_t result = upb_pbdecoder_checktag_slow(d, expected);
  6661. if (result == DECODE_MISMATCH) goto badtag;
  6662. if (result >= 0) return result;
  6663. }
  6664. )
  6665. VMCASE(OP_TAGN, {
  6666. uint64_t expected;
  6667. int32_t result;
  6668. memcpy(&expected, d->pc, 8);
  6669. d->pc += 2;
  6670. result = upb_pbdecoder_checktag_slow(d, expected);
  6671. if (result == DECODE_MISMATCH) goto badtag;
  6672. if (result >= 0) return result;
  6673. })
  6674. VMCASE(OP_DISPATCH, {
  6675. CHECK_RETURN(dispatch(d));
  6676. })
  6677. VMCASE(OP_HALT, {
  6678. return d->size_param;
  6679. })
  6680. }
  6681. }
  6682. }
  6683. /* BytesHandler handlers ******************************************************/
  6684. void *upb_pbdecoder_startbc(void *closure, const void *pc, size_t size_hint) {
  6685. upb_pbdecoder *d = closure;
  6686. UPB_UNUSED(size_hint);
  6687. d->top->end_ofs = UINT64_MAX;
  6688. d->bufstart_ofs = 0;
  6689. d->call_len = 1;
  6690. d->callstack[0] = &halt;
  6691. d->pc = pc;
  6692. d->skip = 0;
  6693. return d;
  6694. }
  6695. bool upb_pbdecoder_end(void *closure, const void *handler_data) {
  6696. upb_pbdecoder *d = closure;
  6697. const upb_pbdecodermethod *method = handler_data;
  6698. uint64_t end;
  6699. char dummy;
  6700. if (d->residual_end > d->residual) {
  6701. seterr(d, "Unexpected EOF: decoder still has buffered unparsed data");
  6702. return false;
  6703. }
  6704. if (d->skip) {
  6705. seterr(d, "Unexpected EOF inside skipped data");
  6706. return false;
  6707. }
  6708. if (d->top->end_ofs != UINT64_MAX) {
  6709. seterr(d, "Unexpected EOF inside delimited string");
  6710. return false;
  6711. }
  6712. /* The user's end() call indicates that the message ends here. */
  6713. end = offset(d);
  6714. d->top->end_ofs = end;
  6715. {
  6716. const uint32_t *p = d->pc;
  6717. d->stack->end_ofs = end;
  6718. /* Check the previous bytecode, but guard against beginning. */
  6719. if (p != method->code_base.ptr) p--;
  6720. if (getop(*p) == OP_CHECKDELIM) {
  6721. /* Rewind from OP_TAG* to OP_CHECKDELIM. */
  6722. UPB_ASSERT(getop(*d->pc) == OP_TAG1 ||
  6723. getop(*d->pc) == OP_TAG2 ||
  6724. getop(*d->pc) == OP_TAGN ||
  6725. getop(*d->pc) == OP_DISPATCH);
  6726. d->pc = p;
  6727. }
  6728. upb_pbdecoder_decode(closure, handler_data, &dummy, 0, NULL);
  6729. }
  6730. if (d->call_len != 0) {
  6731. seterr(d, "Unexpected EOF inside submessage or group");
  6732. return false;
  6733. }
  6734. return true;
  6735. }
  6736. size_t upb_pbdecoder_decode(void *decoder, const void *group, const char *buf,
  6737. size_t size, const upb_bufhandle *handle) {
  6738. int32_t result = upb_pbdecoder_resume(decoder, NULL, buf, size, handle);
  6739. if (result == DECODE_ENDGROUP) goto_endmsg(decoder);
  6740. CHECK_RETURN(result);
  6741. return run_decoder_vm(decoder, group, handle);
  6742. }
  6743. /* Public API *****************************************************************/
  6744. void upb_pbdecoder_reset(upb_pbdecoder *d) {
  6745. d->top = d->stack;
  6746. d->top->groupnum = 0;
  6747. d->ptr = d->residual;
  6748. d->buf = d->residual;
  6749. d->end = d->residual;
  6750. d->residual_end = d->residual;
  6751. }
  6752. upb_pbdecoder *upb_pbdecoder_create(upb_arena *a, const upb_pbdecodermethod *m,
  6753. upb_sink sink, upb_status *status) {
  6754. const size_t default_max_nesting = 64;
  6755. upb_pbdecoder *d = upb_arena_malloc(a, sizeof(upb_pbdecoder));
  6756. if (!d) return NULL;
  6757. d->method_ = m;
  6758. d->callstack = upb_arena_malloc(a, callstacksize(d, default_max_nesting));
  6759. d->stack = upb_arena_malloc(a, stacksize(d, default_max_nesting));
  6760. if (!d->stack || !d->callstack) {
  6761. return NULL;
  6762. }
  6763. d->arena = a;
  6764. d->limit = d->stack + default_max_nesting - 1;
  6765. d->stack_size = default_max_nesting;
  6766. d->status = status;
  6767. upb_pbdecoder_reset(d);
  6768. upb_bytessink_reset(&d->input_, &m->input_handler_, d);
  6769. if (d->method_->dest_handlers_) {
  6770. if (sink.handlers != d->method_->dest_handlers_)
  6771. return NULL;
  6772. }
  6773. d->top->sink = sink;
  6774. return d;
  6775. }
  6776. uint64_t upb_pbdecoder_bytesparsed(const upb_pbdecoder *d) {
  6777. return offset(d);
  6778. }
  6779. const upb_pbdecodermethod *upb_pbdecoder_method(const upb_pbdecoder *d) {
  6780. return d->method_;
  6781. }
  6782. upb_bytessink upb_pbdecoder_input(upb_pbdecoder *d) {
  6783. return d->input_;
  6784. }
  6785. size_t upb_pbdecoder_maxnesting(const upb_pbdecoder *d) {
  6786. return d->stack_size;
  6787. }
  6788. bool upb_pbdecoder_setmaxnesting(upb_pbdecoder *d, size_t max) {
  6789. UPB_ASSERT(d->top >= d->stack);
  6790. if (max < (size_t)(d->top - d->stack)) {
  6791. /* Can't set a limit smaller than what we are currently at. */
  6792. return false;
  6793. }
  6794. if (max > d->stack_size) {
  6795. /* Need to reallocate stack and callstack to accommodate. */
  6796. size_t old_size = stacksize(d, d->stack_size);
  6797. size_t new_size = stacksize(d, max);
  6798. void *p = upb_arena_realloc(d->arena, d->stack, old_size, new_size);
  6799. if (!p) {
  6800. return false;
  6801. }
  6802. d->stack = p;
  6803. old_size = callstacksize(d, d->stack_size);
  6804. new_size = callstacksize(d, max);
  6805. p = upb_arena_realloc(d->arena, d->callstack, old_size, new_size);
  6806. if (!p) {
  6807. return false;
  6808. }
  6809. d->callstack = p;
  6810. d->stack_size = max;
  6811. }
  6812. d->limit = d->stack + max - 1;
  6813. return true;
  6814. }
  6815. /*
  6816. ** upb::Encoder
  6817. **
  6818. ** Since we are implementing pure handlers (ie. without any out-of-band access
  6819. ** to pre-computed lengths), we have to buffer all submessages before we can
  6820. ** emit even their first byte.
  6821. **
  6822. ** Not knowing the size of submessages also means we can't write a perfect
  6823. ** zero-copy implementation, even with buffering. Lengths are stored as
  6824. ** varints, which means that we don't know how many bytes to reserve for the
  6825. ** length until we know what the length is.
  6826. **
  6827. ** This leaves us with three main choices:
  6828. **
  6829. ** 1. buffer all submessage data in a temporary buffer, then copy it exactly
  6830. ** once into the output buffer.
  6831. **
  6832. ** 2. attempt to buffer data directly into the output buffer, estimating how
  6833. ** many bytes each length will take. When our guesses are wrong, use
  6834. ** memmove() to grow or shrink the allotted space.
  6835. **
  6836. ** 3. buffer directly into the output buffer, allocating a max length
  6837. ** ahead-of-time for each submessage length. If we overallocated, we waste
  6838. ** space, but no memcpy() or memmove() is required. This approach requires
  6839. ** defining a maximum size for submessages and rejecting submessages that
  6840. ** exceed that size.
  6841. **
  6842. ** (2) and (3) have the potential to have better performance, but they are more
  6843. ** complicated and subtle to implement:
  6844. **
  6845. ** (3) requires making an arbitrary choice of the maximum message size; it
  6846. ** wastes space when submessages are shorter than this and fails
  6847. ** completely when they are longer. This makes it more finicky and
  6848. ** requires configuration based on the input. It also makes it impossible
  6849. ** to perfectly match the output of reference encoders that always use the
  6850. ** optimal amount of space for each length.
  6851. **
  6852. ** (2) requires guessing the the size upfront, and if multiple lengths are
  6853. ** guessed wrong the minimum required number of memmove() operations may
  6854. ** be complicated to compute correctly. Implemented properly, it may have
  6855. ** a useful amortized or average cost, but more investigation is required
  6856. ** to determine this and what the optimal algorithm is to achieve it.
  6857. **
  6858. ** (1) makes you always pay for exactly one copy, but its implementation is
  6859. ** the simplest and its performance is predictable.
  6860. **
  6861. ** So for now, we implement (1) only. If we wish to optimize later, we should
  6862. ** be able to do it without affecting users.
  6863. **
  6864. ** The strategy is to buffer the segments of data that do *not* depend on
  6865. ** unknown lengths in one buffer, and keep a separate buffer of segment pointers
  6866. ** and lengths. When the top-level submessage ends, we can go beginning to end,
  6867. ** alternating the writing of lengths with memcpy() of the rest of the data.
  6868. ** At the top level though, no buffering is required.
  6869. */
  6870. /* The output buffer is divided into segments; a segment is a string of data
  6871. * that is "ready to go" -- it does not need any varint lengths inserted into
  6872. * the middle. The seams between segments are where varints will be inserted
  6873. * once they are known.
  6874. *
  6875. * We also use the concept of a "run", which is a range of encoded bytes that
  6876. * occur at a single submessage level. Every segment contains one or more runs.
  6877. *
  6878. * A segment can span messages. Consider:
  6879. *
  6880. * .--Submessage lengths---------.
  6881. * | | |
  6882. * | V V
  6883. * V | |--------------- | |-----------------
  6884. * Submessages: | |-----------------------------------------------
  6885. * Top-level msg: ------------------------------------------------------------
  6886. *
  6887. * Segments: ----- ------------------- -----------------
  6888. * Runs: *---- *--------------*--- *----------------
  6889. * (* marks the start)
  6890. *
  6891. * Note that the top-level menssage is not in any segment because it does not
  6892. * have any length preceding it.
  6893. *
  6894. * A segment is only interrupted when another length needs to be inserted. So
  6895. * observe how the second segment spans both the inner submessage and part of
  6896. * the next enclosing message. */
  6897. typedef struct {
  6898. uint32_t msglen; /* The length to varint-encode before this segment. */
  6899. uint32_t seglen; /* Length of the segment. */
  6900. } upb_pb_encoder_segment;
  6901. struct upb_pb_encoder {
  6902. upb_arena *arena;
  6903. /* Our input and output. */
  6904. upb_sink input_;
  6905. upb_bytessink output_;
  6906. /* The "subclosure" -- used as the inner closure as part of the bytessink
  6907. * protocol. */
  6908. void *subc;
  6909. /* The output buffer and limit, and our current write position. "buf"
  6910. * initially points to "initbuf", but is dynamically allocated if we need to
  6911. * grow beyond the initial size. */
  6912. char *buf, *ptr, *limit;
  6913. /* The beginning of the current run, or undefined if we are at the top
  6914. * level. */
  6915. char *runbegin;
  6916. /* The list of segments we are accumulating. */
  6917. upb_pb_encoder_segment *segbuf, *segptr, *seglimit;
  6918. /* The stack of enclosing submessages. Each entry in the stack points to the
  6919. * segment where this submessage's length is being accumulated. */
  6920. int *stack, *top, *stacklimit;
  6921. /* Depth of startmsg/endmsg calls. */
  6922. int depth;
  6923. };
  6924. /* low-level buffering ********************************************************/
  6925. /* Low-level functions for interacting with the output buffer. */
  6926. /* TODO(haberman): handle pushback */
  6927. static void putbuf(upb_pb_encoder *e, const char *buf, size_t len) {
  6928. size_t n = upb_bytessink_putbuf(e->output_, e->subc, buf, len, NULL);
  6929. UPB_ASSERT(n == len);
  6930. }
  6931. static upb_pb_encoder_segment *top(upb_pb_encoder *e) {
  6932. return &e->segbuf[*e->top];
  6933. }
  6934. /* Call to ensure that at least "bytes" bytes are available for writing at
  6935. * e->ptr. Returns false if the bytes could not be allocated. */
  6936. static bool reserve(upb_pb_encoder *e, size_t bytes) {
  6937. if ((size_t)(e->limit - e->ptr) < bytes) {
  6938. /* Grow buffer. */
  6939. char *new_buf;
  6940. size_t needed = bytes + (e->ptr - e->buf);
  6941. size_t old_size = e->limit - e->buf;
  6942. size_t new_size = old_size;
  6943. while (new_size < needed) {
  6944. new_size *= 2;
  6945. }
  6946. new_buf = upb_arena_realloc(e->arena, e->buf, old_size, new_size);
  6947. if (new_buf == NULL) {
  6948. return false;
  6949. }
  6950. e->ptr = new_buf + (e->ptr - e->buf);
  6951. e->runbegin = new_buf + (e->runbegin - e->buf);
  6952. e->limit = new_buf + new_size;
  6953. e->buf = new_buf;
  6954. }
  6955. return true;
  6956. }
  6957. /* Call when "bytes" bytes have been writte at e->ptr. The caller *must* have
  6958. * previously called reserve() with at least this many bytes. */
  6959. static void encoder_advance(upb_pb_encoder *e, size_t bytes) {
  6960. UPB_ASSERT((size_t)(e->limit - e->ptr) >= bytes);
  6961. e->ptr += bytes;
  6962. }
  6963. /* Call when all of the bytes for a handler have been written. Flushes the
  6964. * bytes if possible and necessary, returning false if this failed. */
  6965. static bool commit(upb_pb_encoder *e) {
  6966. if (!e->top) {
  6967. /* We aren't inside a delimited region. Flush our accumulated bytes to
  6968. * the output.
  6969. *
  6970. * TODO(haberman): in the future we may want to delay flushing for
  6971. * efficiency reasons. */
  6972. putbuf(e, e->buf, e->ptr - e->buf);
  6973. e->ptr = e->buf;
  6974. }
  6975. return true;
  6976. }
  6977. /* Writes the given bytes to the buffer, handling reserve/advance. */
  6978. static bool encode_bytes(upb_pb_encoder *e, const void *data, size_t len) {
  6979. if (!reserve(e, len)) {
  6980. return false;
  6981. }
  6982. memcpy(e->ptr, data, len);
  6983. encoder_advance(e, len);
  6984. return true;
  6985. }
  6986. /* Finish the current run by adding the run totals to the segment and message
  6987. * length. */
  6988. static void accumulate(upb_pb_encoder *e) {
  6989. size_t run_len;
  6990. UPB_ASSERT(e->ptr >= e->runbegin);
  6991. run_len = e->ptr - e->runbegin;
  6992. e->segptr->seglen += run_len;
  6993. top(e)->msglen += run_len;
  6994. e->runbegin = e->ptr;
  6995. }
  6996. /* Call to indicate the start of delimited region for which the full length is
  6997. * not yet known. All data will be buffered until the length is known.
  6998. * Delimited regions may be nested; their lengths will all be tracked properly. */
  6999. static bool start_delim(upb_pb_encoder *e) {
  7000. if (e->top) {
  7001. /* We are already buffering, advance to the next segment and push it on the
  7002. * stack. */
  7003. accumulate(e);
  7004. if (++e->top == e->stacklimit) {
  7005. /* TODO(haberman): grow stack? */
  7006. return false;
  7007. }
  7008. if (++e->segptr == e->seglimit) {
  7009. /* Grow segment buffer. */
  7010. size_t old_size =
  7011. (e->seglimit - e->segbuf) * sizeof(upb_pb_encoder_segment);
  7012. size_t new_size = old_size * 2;
  7013. upb_pb_encoder_segment *new_buf =
  7014. upb_arena_realloc(e->arena, e->segbuf, old_size, new_size);
  7015. if (new_buf == NULL) {
  7016. return false;
  7017. }
  7018. e->segptr = new_buf + (e->segptr - e->segbuf);
  7019. e->seglimit = new_buf + (new_size / sizeof(upb_pb_encoder_segment));
  7020. e->segbuf = new_buf;
  7021. }
  7022. } else {
  7023. /* We were previously at the top level, start buffering. */
  7024. e->segptr = e->segbuf;
  7025. e->top = e->stack;
  7026. e->runbegin = e->ptr;
  7027. }
  7028. *e->top = (int)(e->segptr - e->segbuf);
  7029. e->segptr->seglen = 0;
  7030. e->segptr->msglen = 0;
  7031. return true;
  7032. }
  7033. /* Call to indicate the end of a delimited region. We now know the length of
  7034. * the delimited region. If we are not nested inside any other delimited
  7035. * regions, we can now emit all of the buffered data we accumulated. */
  7036. static bool end_delim(upb_pb_encoder *e) {
  7037. size_t msglen;
  7038. accumulate(e);
  7039. msglen = top(e)->msglen;
  7040. if (e->top == e->stack) {
  7041. /* All lengths are now available, emit all buffered data. */
  7042. char buf[UPB_PB_VARINT_MAX_LEN];
  7043. upb_pb_encoder_segment *s;
  7044. const char *ptr = e->buf;
  7045. for (s = e->segbuf; s <= e->segptr; s++) {
  7046. size_t lenbytes = upb_vencode64(s->msglen, buf);
  7047. putbuf(e, buf, lenbytes);
  7048. putbuf(e, ptr, s->seglen);
  7049. ptr += s->seglen;
  7050. }
  7051. e->ptr = e->buf;
  7052. e->top = NULL;
  7053. } else {
  7054. /* Need to keep buffering; propagate length info into enclosing
  7055. * submessages. */
  7056. --e->top;
  7057. top(e)->msglen += msglen + upb_varint_size(msglen);
  7058. }
  7059. return true;
  7060. }
  7061. /* tag_t **********************************************************************/
  7062. /* A precomputed (pre-encoded) tag and length. */
  7063. typedef struct {
  7064. uint8_t bytes;
  7065. char tag[7];
  7066. } tag_t;
  7067. /* Allocates a new tag for this field, and sets it in these handlerattr. */
  7068. static void new_tag(upb_handlers *h, const upb_fielddef *f, upb_wiretype_t wt,
  7069. upb_handlerattr *attr) {
  7070. uint32_t n = upb_fielddef_number(f);
  7071. tag_t *tag = upb_gmalloc(sizeof(tag_t));
  7072. tag->bytes = upb_vencode64((n << 3) | wt, tag->tag);
  7073. attr->handler_data = tag;
  7074. upb_handlers_addcleanup(h, tag, upb_gfree);
  7075. }
  7076. static bool encode_tag(upb_pb_encoder *e, const tag_t *tag) {
  7077. return encode_bytes(e, tag->tag, tag->bytes);
  7078. }
  7079. /* encoding of wire types *****************************************************/
  7080. static bool encode_fixed64(upb_pb_encoder *e, uint64_t val) {
  7081. /* TODO(haberman): byte-swap for big endian. */
  7082. return encode_bytes(e, &val, sizeof(uint64_t));
  7083. }
  7084. static bool encode_fixed32(upb_pb_encoder *e, uint32_t val) {
  7085. /* TODO(haberman): byte-swap for big endian. */
  7086. return encode_bytes(e, &val, sizeof(uint32_t));
  7087. }
  7088. static bool encode_varint(upb_pb_encoder *e, uint64_t val) {
  7089. if (!reserve(e, UPB_PB_VARINT_MAX_LEN)) {
  7090. return false;
  7091. }
  7092. encoder_advance(e, upb_vencode64(val, e->ptr));
  7093. return true;
  7094. }
  7095. static uint64_t dbl2uint64(double d) {
  7096. uint64_t ret;
  7097. memcpy(&ret, &d, sizeof(uint64_t));
  7098. return ret;
  7099. }
  7100. static uint32_t flt2uint32(float d) {
  7101. uint32_t ret;
  7102. memcpy(&ret, &d, sizeof(uint32_t));
  7103. return ret;
  7104. }
  7105. /* encoding of proto types ****************************************************/
  7106. static bool startmsg(void *c, const void *hd) {
  7107. upb_pb_encoder *e = c;
  7108. UPB_UNUSED(hd);
  7109. if (e->depth++ == 0) {
  7110. upb_bytessink_start(e->output_, 0, &e->subc);
  7111. }
  7112. return true;
  7113. }
  7114. static bool endmsg(void *c, const void *hd, upb_status *status) {
  7115. upb_pb_encoder *e = c;
  7116. UPB_UNUSED(hd);
  7117. UPB_UNUSED(status);
  7118. if (--e->depth == 0) {
  7119. upb_bytessink_end(e->output_);
  7120. }
  7121. return true;
  7122. }
  7123. static void *encode_startdelimfield(void *c, const void *hd) {
  7124. bool ok = encode_tag(c, hd) && commit(c) && start_delim(c);
  7125. return ok ? c : UPB_BREAK;
  7126. }
  7127. static bool encode_unknown(void *c, const void *hd, const char *buf,
  7128. size_t len) {
  7129. UPB_UNUSED(hd);
  7130. return encode_bytes(c, buf, len) && commit(c);
  7131. }
  7132. static bool encode_enddelimfield(void *c, const void *hd) {
  7133. UPB_UNUSED(hd);
  7134. return end_delim(c);
  7135. }
  7136. static void *encode_startgroup(void *c, const void *hd) {
  7137. return (encode_tag(c, hd) && commit(c)) ? c : UPB_BREAK;
  7138. }
  7139. static bool encode_endgroup(void *c, const void *hd) {
  7140. return encode_tag(c, hd) && commit(c);
  7141. }
  7142. static void *encode_startstr(void *c, const void *hd, size_t size_hint) {
  7143. UPB_UNUSED(size_hint);
  7144. return encode_startdelimfield(c, hd);
  7145. }
  7146. static size_t encode_strbuf(void *c, const void *hd, const char *buf,
  7147. size_t len, const upb_bufhandle *h) {
  7148. UPB_UNUSED(hd);
  7149. UPB_UNUSED(h);
  7150. return encode_bytes(c, buf, len) ? len : 0;
  7151. }
  7152. #define T(type, ctype, convert, encode) \
  7153. static bool encode_scalar_##type(void *e, const void *hd, ctype val) { \
  7154. return encode_tag(e, hd) && encode(e, (convert)(val)) && commit(e); \
  7155. } \
  7156. static bool encode_packed_##type(void *e, const void *hd, ctype val) { \
  7157. UPB_UNUSED(hd); \
  7158. return encode(e, (convert)(val)); \
  7159. }
  7160. T(double, double, dbl2uint64, encode_fixed64)
  7161. T(float, float, flt2uint32, encode_fixed32)
  7162. T(int64, int64_t, uint64_t, encode_varint)
  7163. T(int32, int32_t, int64_t, encode_varint)
  7164. T(fixed64, uint64_t, uint64_t, encode_fixed64)
  7165. T(fixed32, uint32_t, uint32_t, encode_fixed32)
  7166. T(bool, bool, bool, encode_varint)
  7167. T(uint32, uint32_t, uint32_t, encode_varint)
  7168. T(uint64, uint64_t, uint64_t, encode_varint)
  7169. T(enum, int32_t, uint32_t, encode_varint)
  7170. T(sfixed32, int32_t, uint32_t, encode_fixed32)
  7171. T(sfixed64, int64_t, uint64_t, encode_fixed64)
  7172. T(sint32, int32_t, upb_zzenc_32, encode_varint)
  7173. T(sint64, int64_t, upb_zzenc_64, encode_varint)
  7174. #undef T
  7175. /* code to build the handlers *************************************************/
  7176. #include <stdio.h>
  7177. static void newhandlers_callback(const void *closure, upb_handlers *h) {
  7178. const upb_msgdef *m;
  7179. upb_msg_field_iter i;
  7180. UPB_UNUSED(closure);
  7181. upb_handlers_setstartmsg(h, startmsg, NULL);
  7182. upb_handlers_setendmsg(h, endmsg, NULL);
  7183. upb_handlers_setunknown(h, encode_unknown, NULL);
  7184. m = upb_handlers_msgdef(h);
  7185. for(upb_msg_field_begin(&i, m);
  7186. !upb_msg_field_done(&i);
  7187. upb_msg_field_next(&i)) {
  7188. const upb_fielddef *f = upb_msg_iter_field(&i);
  7189. bool packed = upb_fielddef_isseq(f) && upb_fielddef_isprimitive(f) &&
  7190. upb_fielddef_packed(f);
  7191. upb_handlerattr attr = UPB_HANDLERATTR_INIT;
  7192. upb_wiretype_t wt =
  7193. packed ? UPB_WIRE_TYPE_DELIMITED
  7194. : upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  7195. /* Pre-encode the tag for this field. */
  7196. new_tag(h, f, wt, &attr);
  7197. if (packed) {
  7198. upb_handlers_setstartseq(h, f, encode_startdelimfield, &attr);
  7199. upb_handlers_setendseq(h, f, encode_enddelimfield, &attr);
  7200. }
  7201. #define T(upper, lower, upbtype) \
  7202. case UPB_DESCRIPTOR_TYPE_##upper: \
  7203. if (packed) { \
  7204. upb_handlers_set##upbtype(h, f, encode_packed_##lower, &attr); \
  7205. } else { \
  7206. upb_handlers_set##upbtype(h, f, encode_scalar_##lower, &attr); \
  7207. } \
  7208. break;
  7209. switch (upb_fielddef_descriptortype(f)) {
  7210. T(DOUBLE, double, double);
  7211. T(FLOAT, float, float);
  7212. T(INT64, int64, int64);
  7213. T(INT32, int32, int32);
  7214. T(FIXED64, fixed64, uint64);
  7215. T(FIXED32, fixed32, uint32);
  7216. T(BOOL, bool, bool);
  7217. T(UINT32, uint32, uint32);
  7218. T(UINT64, uint64, uint64);
  7219. T(ENUM, enum, int32);
  7220. T(SFIXED32, sfixed32, int32);
  7221. T(SFIXED64, sfixed64, int64);
  7222. T(SINT32, sint32, int32);
  7223. T(SINT64, sint64, int64);
  7224. case UPB_DESCRIPTOR_TYPE_STRING:
  7225. case UPB_DESCRIPTOR_TYPE_BYTES:
  7226. upb_handlers_setstartstr(h, f, encode_startstr, &attr);
  7227. upb_handlers_setendstr(h, f, encode_enddelimfield, &attr);
  7228. upb_handlers_setstring(h, f, encode_strbuf, &attr);
  7229. break;
  7230. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  7231. upb_handlers_setstartsubmsg(h, f, encode_startdelimfield, &attr);
  7232. upb_handlers_setendsubmsg(h, f, encode_enddelimfield, &attr);
  7233. break;
  7234. case UPB_DESCRIPTOR_TYPE_GROUP: {
  7235. /* Endgroup takes a different tag (wire_type = END_GROUP). */
  7236. upb_handlerattr attr2 = UPB_HANDLERATTR_INIT;
  7237. new_tag(h, f, UPB_WIRE_TYPE_END_GROUP, &attr2);
  7238. upb_handlers_setstartsubmsg(h, f, encode_startgroup, &attr);
  7239. upb_handlers_setendsubmsg(h, f, encode_endgroup, &attr2);
  7240. break;
  7241. }
  7242. }
  7243. #undef T
  7244. }
  7245. }
  7246. void upb_pb_encoder_reset(upb_pb_encoder *e) {
  7247. e->segptr = NULL;
  7248. e->top = NULL;
  7249. e->depth = 0;
  7250. }
  7251. /* public API *****************************************************************/
  7252. upb_handlercache *upb_pb_encoder_newcache(void) {
  7253. return upb_handlercache_new(newhandlers_callback, NULL);
  7254. }
  7255. upb_pb_encoder *upb_pb_encoder_create(upb_arena *arena, const upb_handlers *h,
  7256. upb_bytessink output) {
  7257. const size_t initial_bufsize = 256;
  7258. const size_t initial_segbufsize = 16;
  7259. /* TODO(haberman): make this configurable. */
  7260. const size_t stack_size = 64;
  7261. upb_pb_encoder *e = upb_arena_malloc(arena, sizeof(upb_pb_encoder));
  7262. if (!e) return NULL;
  7263. e->buf = upb_arena_malloc(arena, initial_bufsize);
  7264. e->segbuf = upb_arena_malloc(arena, initial_segbufsize * sizeof(*e->segbuf));
  7265. e->stack = upb_arena_malloc(arena, stack_size * sizeof(*e->stack));
  7266. if (!e->buf || !e->segbuf || !e->stack) {
  7267. return NULL;
  7268. }
  7269. e->limit = e->buf + initial_bufsize;
  7270. e->seglimit = e->segbuf + initial_segbufsize;
  7271. e->stacklimit = e->stack + stack_size;
  7272. upb_pb_encoder_reset(e);
  7273. upb_sink_reset(&e->input_, h, e);
  7274. e->arena = arena;
  7275. e->output_ = output;
  7276. e->subc = output.closure;
  7277. e->ptr = e->buf;
  7278. return e;
  7279. }
  7280. upb_sink upb_pb_encoder_input(upb_pb_encoder *e) { return e->input_; }
  7281. /*
  7282. * upb::pb::TextPrinter
  7283. *
  7284. * OPT: This is not optimized at all. It uses printf() which parses the format
  7285. * string every time, and it allocates memory for every put.
  7286. */
  7287. #include <ctype.h>
  7288. #include <float.h>
  7289. #include <inttypes.h>
  7290. #include <stdarg.h>
  7291. #include <stdio.h>
  7292. #include <string.h>
  7293. struct upb_textprinter {
  7294. upb_sink input_;
  7295. upb_bytessink output_;
  7296. int indent_depth_;
  7297. bool single_line_;
  7298. void *subc;
  7299. };
  7300. #define CHECK(x) if ((x) < 0) goto err;
  7301. static const char *shortname(const char *longname) {
  7302. const char *last = strrchr(longname, '.');
  7303. return last ? last + 1 : longname;
  7304. }
  7305. static int indent(upb_textprinter *p) {
  7306. int i;
  7307. if (!p->single_line_)
  7308. for (i = 0; i < p->indent_depth_; i++)
  7309. upb_bytessink_putbuf(p->output_, p->subc, " ", 2, NULL);
  7310. return 0;
  7311. }
  7312. static int endfield(upb_textprinter *p) {
  7313. const char ch = (p->single_line_ ? ' ' : '\n');
  7314. upb_bytessink_putbuf(p->output_, p->subc, &ch, 1, NULL);
  7315. return 0;
  7316. }
  7317. static int putescaped(upb_textprinter *p, const char *buf, size_t len,
  7318. bool preserve_utf8) {
  7319. /* Based on CEscapeInternal() from Google's protobuf release. */
  7320. char dstbuf[4096], *dst = dstbuf, *dstend = dstbuf + sizeof(dstbuf);
  7321. const char *end = buf + len;
  7322. /* I think hex is prettier and more useful, but proto2 uses octal; should
  7323. * investigate whether it can parse hex also. */
  7324. const bool use_hex = false;
  7325. bool last_hex_escape = false; /* true if last output char was \xNN */
  7326. for (; buf < end; buf++) {
  7327. bool is_hex_escape;
  7328. if (dstend - dst < 4) {
  7329. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  7330. dst = dstbuf;
  7331. }
  7332. is_hex_escape = false;
  7333. switch (*buf) {
  7334. case '\n': *(dst++) = '\\'; *(dst++) = 'n'; break;
  7335. case '\r': *(dst++) = '\\'; *(dst++) = 'r'; break;
  7336. case '\t': *(dst++) = '\\'; *(dst++) = 't'; break;
  7337. case '\"': *(dst++) = '\\'; *(dst++) = '\"'; break;
  7338. case '\'': *(dst++) = '\\'; *(dst++) = '\''; break;
  7339. case '\\': *(dst++) = '\\'; *(dst++) = '\\'; break;
  7340. default:
  7341. /* Note that if we emit \xNN and the buf character after that is a hex
  7342. * digit then that digit must be escaped too to prevent it being
  7343. * interpreted as part of the character code by C. */
  7344. if ((!preserve_utf8 || (uint8_t)*buf < 0x80) &&
  7345. (!isprint(*buf) || (last_hex_escape && isxdigit(*buf)))) {
  7346. sprintf(dst, (use_hex ? "\\x%02x" : "\\%03o"), (uint8_t)*buf);
  7347. is_hex_escape = use_hex;
  7348. dst += 4;
  7349. } else {
  7350. *(dst++) = *buf; break;
  7351. }
  7352. }
  7353. last_hex_escape = is_hex_escape;
  7354. }
  7355. /* Flush remaining data. */
  7356. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  7357. return 0;
  7358. }
  7359. bool putf(upb_textprinter *p, const char *fmt, ...) {
  7360. va_list args;
  7361. va_list args_copy;
  7362. char *str;
  7363. int written;
  7364. int len;
  7365. bool ok;
  7366. va_start(args, fmt);
  7367. /* Run once to get the length of the string. */
  7368. _upb_va_copy(args_copy, args);
  7369. len = _upb_vsnprintf(NULL, 0, fmt, args_copy);
  7370. va_end(args_copy);
  7371. /* + 1 for NULL terminator (vsprintf() requires it even if we don't). */
  7372. str = upb_gmalloc(len + 1);
  7373. if (!str) return false;
  7374. written = vsprintf(str, fmt, args);
  7375. va_end(args);
  7376. UPB_ASSERT(written == len);
  7377. ok = upb_bytessink_putbuf(p->output_, p->subc, str, len, NULL);
  7378. upb_gfree(str);
  7379. return ok;
  7380. }
  7381. /* handlers *******************************************************************/
  7382. static bool textprinter_startmsg(void *c, const void *hd) {
  7383. upb_textprinter *p = c;
  7384. UPB_UNUSED(hd);
  7385. if (p->indent_depth_ == 0) {
  7386. upb_bytessink_start(p->output_, 0, &p->subc);
  7387. }
  7388. return true;
  7389. }
  7390. static bool textprinter_endmsg(void *c, const void *hd, upb_status *s) {
  7391. upb_textprinter *p = c;
  7392. UPB_UNUSED(hd);
  7393. UPB_UNUSED(s);
  7394. if (p->indent_depth_ == 0) {
  7395. upb_bytessink_end(p->output_);
  7396. }
  7397. return true;
  7398. }
  7399. #define TYPE(name, ctype, fmt) \
  7400. static bool textprinter_put ## name(void *closure, const void *handler_data, \
  7401. ctype val) { \
  7402. upb_textprinter *p = closure; \
  7403. const upb_fielddef *f = handler_data; \
  7404. CHECK(indent(p)); \
  7405. putf(p, "%s: " fmt, upb_fielddef_name(f), val); \
  7406. CHECK(endfield(p)); \
  7407. return true; \
  7408. err: \
  7409. return false; \
  7410. }
  7411. static bool textprinter_putbool(void *closure, const void *handler_data,
  7412. bool val) {
  7413. upb_textprinter *p = closure;
  7414. const upb_fielddef *f = handler_data;
  7415. CHECK(indent(p));
  7416. putf(p, "%s: %s", upb_fielddef_name(f), val ? "true" : "false");
  7417. CHECK(endfield(p));
  7418. return true;
  7419. err:
  7420. return false;
  7421. }
  7422. #define STRINGIFY_HELPER(x) #x
  7423. #define STRINGIFY_MACROVAL(x) STRINGIFY_HELPER(x)
  7424. TYPE(int32, int32_t, "%" PRId32)
  7425. TYPE(int64, int64_t, "%" PRId64)
  7426. TYPE(uint32, uint32_t, "%" PRIu32)
  7427. TYPE(uint64, uint64_t, "%" PRIu64)
  7428. TYPE(float, float, "%." STRINGIFY_MACROVAL(FLT_DIG) "g")
  7429. TYPE(double, double, "%." STRINGIFY_MACROVAL(DBL_DIG) "g")
  7430. #undef TYPE
  7431. /* Output a symbolic value from the enum if found, else just print as int32. */
  7432. static bool textprinter_putenum(void *closure, const void *handler_data,
  7433. int32_t val) {
  7434. upb_textprinter *p = closure;
  7435. const upb_fielddef *f = handler_data;
  7436. const upb_enumdef *enum_def = upb_fielddef_enumsubdef(f);
  7437. const char *label = upb_enumdef_iton(enum_def, val);
  7438. if (label) {
  7439. indent(p);
  7440. putf(p, "%s: %s", upb_fielddef_name(f), label);
  7441. endfield(p);
  7442. } else {
  7443. if (!textprinter_putint32(closure, handler_data, val))
  7444. return false;
  7445. }
  7446. return true;
  7447. }
  7448. static void *textprinter_startstr(void *closure, const void *handler_data,
  7449. size_t size_hint) {
  7450. upb_textprinter *p = closure;
  7451. const upb_fielddef *f = handler_data;
  7452. UPB_UNUSED(size_hint);
  7453. indent(p);
  7454. putf(p, "%s: \"", upb_fielddef_name(f));
  7455. return p;
  7456. }
  7457. static bool textprinter_endstr(void *closure, const void *handler_data) {
  7458. upb_textprinter *p = closure;
  7459. UPB_UNUSED(handler_data);
  7460. putf(p, "\"");
  7461. endfield(p);
  7462. return true;
  7463. }
  7464. static size_t textprinter_putstr(void *closure, const void *hd, const char *buf,
  7465. size_t len, const upb_bufhandle *handle) {
  7466. upb_textprinter *p = closure;
  7467. const upb_fielddef *f = hd;
  7468. UPB_UNUSED(handle);
  7469. CHECK(putescaped(p, buf, len, upb_fielddef_type(f) == UPB_TYPE_STRING));
  7470. return len;
  7471. err:
  7472. return 0;
  7473. }
  7474. static void *textprinter_startsubmsg(void *closure, const void *handler_data) {
  7475. upb_textprinter *p = closure;
  7476. const char *name = handler_data;
  7477. CHECK(indent(p));
  7478. putf(p, "%s {%c", name, p->single_line_ ? ' ' : '\n');
  7479. p->indent_depth_++;
  7480. return p;
  7481. err:
  7482. return UPB_BREAK;
  7483. }
  7484. static bool textprinter_endsubmsg(void *closure, const void *handler_data) {
  7485. upb_textprinter *p = closure;
  7486. UPB_UNUSED(handler_data);
  7487. p->indent_depth_--;
  7488. CHECK(indent(p));
  7489. upb_bytessink_putbuf(p->output_, p->subc, "}", 1, NULL);
  7490. CHECK(endfield(p));
  7491. return true;
  7492. err:
  7493. return false;
  7494. }
  7495. static void onmreg(const void *c, upb_handlers *h) {
  7496. const upb_msgdef *m = upb_handlers_msgdef(h);
  7497. upb_msg_field_iter i;
  7498. UPB_UNUSED(c);
  7499. upb_handlers_setstartmsg(h, textprinter_startmsg, NULL);
  7500. upb_handlers_setendmsg(h, textprinter_endmsg, NULL);
  7501. for(upb_msg_field_begin(&i, m);
  7502. !upb_msg_field_done(&i);
  7503. upb_msg_field_next(&i)) {
  7504. upb_fielddef *f = upb_msg_iter_field(&i);
  7505. upb_handlerattr attr = UPB_HANDLERATTR_INIT;
  7506. attr.handler_data = f;
  7507. switch (upb_fielddef_type(f)) {
  7508. case UPB_TYPE_INT32:
  7509. upb_handlers_setint32(h, f, textprinter_putint32, &attr);
  7510. break;
  7511. case UPB_TYPE_INT64:
  7512. upb_handlers_setint64(h, f, textprinter_putint64, &attr);
  7513. break;
  7514. case UPB_TYPE_UINT32:
  7515. upb_handlers_setuint32(h, f, textprinter_putuint32, &attr);
  7516. break;
  7517. case UPB_TYPE_UINT64:
  7518. upb_handlers_setuint64(h, f, textprinter_putuint64, &attr);
  7519. break;
  7520. case UPB_TYPE_FLOAT:
  7521. upb_handlers_setfloat(h, f, textprinter_putfloat, &attr);
  7522. break;
  7523. case UPB_TYPE_DOUBLE:
  7524. upb_handlers_setdouble(h, f, textprinter_putdouble, &attr);
  7525. break;
  7526. case UPB_TYPE_BOOL:
  7527. upb_handlers_setbool(h, f, textprinter_putbool, &attr);
  7528. break;
  7529. case UPB_TYPE_STRING:
  7530. case UPB_TYPE_BYTES:
  7531. upb_handlers_setstartstr(h, f, textprinter_startstr, &attr);
  7532. upb_handlers_setstring(h, f, textprinter_putstr, &attr);
  7533. upb_handlers_setendstr(h, f, textprinter_endstr, &attr);
  7534. break;
  7535. case UPB_TYPE_MESSAGE: {
  7536. const char *name =
  7537. upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_GROUP
  7538. ? shortname(upb_msgdef_fullname(upb_fielddef_msgsubdef(f)))
  7539. : upb_fielddef_name(f);
  7540. attr.handler_data = name;
  7541. upb_handlers_setstartsubmsg(h, f, textprinter_startsubmsg, &attr);
  7542. upb_handlers_setendsubmsg(h, f, textprinter_endsubmsg, &attr);
  7543. break;
  7544. }
  7545. case UPB_TYPE_ENUM:
  7546. upb_handlers_setint32(h, f, textprinter_putenum, &attr);
  7547. break;
  7548. }
  7549. }
  7550. }
  7551. static void textprinter_reset(upb_textprinter *p, bool single_line) {
  7552. p->single_line_ = single_line;
  7553. p->indent_depth_ = 0;
  7554. }
  7555. /* Public API *****************************************************************/
  7556. upb_textprinter *upb_textprinter_create(upb_arena *arena, const upb_handlers *h,
  7557. upb_bytessink output) {
  7558. upb_textprinter *p = upb_arena_malloc(arena, sizeof(upb_textprinter));
  7559. if (!p) return NULL;
  7560. p->output_ = output;
  7561. upb_sink_reset(&p->input_, h, p);
  7562. textprinter_reset(p, false);
  7563. return p;
  7564. }
  7565. upb_handlercache *upb_textprinter_newcache(void) {
  7566. return upb_handlercache_new(&onmreg, NULL);
  7567. }
  7568. upb_sink upb_textprinter_input(upb_textprinter *p) { return p->input_; }
  7569. void upb_textprinter_setsingleline(upb_textprinter *p, bool single_line) {
  7570. p->single_line_ = single_line;
  7571. }
  7572. /* Index is descriptor type. */
  7573. const uint8_t upb_pb_native_wire_types[] = {
  7574. UPB_WIRE_TYPE_END_GROUP, /* ENDGROUP */
  7575. UPB_WIRE_TYPE_64BIT, /* DOUBLE */
  7576. UPB_WIRE_TYPE_32BIT, /* FLOAT */
  7577. UPB_WIRE_TYPE_VARINT, /* INT64 */
  7578. UPB_WIRE_TYPE_VARINT, /* UINT64 */
  7579. UPB_WIRE_TYPE_VARINT, /* INT32 */
  7580. UPB_WIRE_TYPE_64BIT, /* FIXED64 */
  7581. UPB_WIRE_TYPE_32BIT, /* FIXED32 */
  7582. UPB_WIRE_TYPE_VARINT, /* BOOL */
  7583. UPB_WIRE_TYPE_DELIMITED, /* STRING */
  7584. UPB_WIRE_TYPE_START_GROUP, /* GROUP */
  7585. UPB_WIRE_TYPE_DELIMITED, /* MESSAGE */
  7586. UPB_WIRE_TYPE_DELIMITED, /* BYTES */
  7587. UPB_WIRE_TYPE_VARINT, /* UINT32 */
  7588. UPB_WIRE_TYPE_VARINT, /* ENUM */
  7589. UPB_WIRE_TYPE_32BIT, /* SFIXED32 */
  7590. UPB_WIRE_TYPE_64BIT, /* SFIXED64 */
  7591. UPB_WIRE_TYPE_VARINT, /* SINT32 */
  7592. UPB_WIRE_TYPE_VARINT, /* SINT64 */
  7593. };
  7594. /* A basic branch-based decoder, uses 32-bit values to get good performance
  7595. * on 32-bit architectures (but performs well on 64-bits also).
  7596. * This scheme comes from the original Google Protobuf implementation
  7597. * (proto2). */
  7598. upb_decoderet upb_vdecode_max8_branch32(upb_decoderet r) {
  7599. upb_decoderet err = {NULL, 0};
  7600. const char *p = r.p;
  7601. uint32_t low = (uint32_t)r.val;
  7602. uint32_t high = 0;
  7603. uint32_t b;
  7604. b = *(p++); low |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  7605. b = *(p++); low |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  7606. b = *(p++); low |= (b & 0x7fU) << 28;
  7607. high = (b & 0x7fU) >> 4; if (!(b & 0x80)) goto done;
  7608. b = *(p++); high |= (b & 0x7fU) << 3; if (!(b & 0x80)) goto done;
  7609. b = *(p++); high |= (b & 0x7fU) << 10; if (!(b & 0x80)) goto done;
  7610. b = *(p++); high |= (b & 0x7fU) << 17; if (!(b & 0x80)) goto done;
  7611. b = *(p++); high |= (b & 0x7fU) << 24; if (!(b & 0x80)) goto done;
  7612. b = *(p++); high |= (b & 0x7fU) << 31; if (!(b & 0x80)) goto done;
  7613. return err;
  7614. done:
  7615. r.val = ((uint64_t)high << 32) | low;
  7616. r.p = p;
  7617. return r;
  7618. }
  7619. /* Like the previous, but uses 64-bit values. */
  7620. upb_decoderet upb_vdecode_max8_branch64(upb_decoderet r) {
  7621. const char *p = r.p;
  7622. uint64_t val = r.val;
  7623. uint64_t b;
  7624. upb_decoderet err = {NULL, 0};
  7625. b = *(p++); val |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  7626. b = *(p++); val |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  7627. b = *(p++); val |= (b & 0x7fU) << 28; if (!(b & 0x80)) goto done;
  7628. b = *(p++); val |= (b & 0x7fU) << 35; if (!(b & 0x80)) goto done;
  7629. b = *(p++); val |= (b & 0x7fU) << 42; if (!(b & 0x80)) goto done;
  7630. b = *(p++); val |= (b & 0x7fU) << 49; if (!(b & 0x80)) goto done;
  7631. b = *(p++); val |= (b & 0x7fU) << 56; if (!(b & 0x80)) goto done;
  7632. b = *(p++); val |= (b & 0x7fU) << 63; if (!(b & 0x80)) goto done;
  7633. return err;
  7634. done:
  7635. r.val = val;
  7636. r.p = p;
  7637. return r;
  7638. }
  7639. #line 1 "upb/json/parser.rl"
  7640. /*
  7641. ** upb::json::Parser (upb_json_parser)
  7642. **
  7643. ** A parser that uses the Ragel State Machine Compiler to generate
  7644. ** the finite automata.
  7645. **
  7646. ** Ragel only natively handles regular languages, but we can manually
  7647. ** program it a bit to handle context-free languages like JSON, by using
  7648. ** the "fcall" and "fret" constructs.
  7649. **
  7650. ** This parser can handle the basics, but needs several things to be fleshed
  7651. ** out:
  7652. **
  7653. ** - handling of unicode escape sequences (including high surrogate pairs).
  7654. ** - properly check and report errors for unknown fields, stack overflow,
  7655. ** improper array nesting (or lack of nesting).
  7656. ** - handling of base64 sequences with padding characters.
  7657. ** - handling of push-back (non-success returns from sink functions).
  7658. ** - handling of keys/escape-sequences/etc that span input buffers.
  7659. */
  7660. #include <ctype.h>
  7661. #include <errno.h>
  7662. #include <float.h>
  7663. #include <math.h>
  7664. #include <stdint.h>
  7665. #include <stdio.h>
  7666. #include <stdlib.h>
  7667. #include <string.h>
  7668. #include <time.h>
  7669. #define UPB_JSON_MAX_DEPTH 64
  7670. /* Type of value message */
  7671. enum {
  7672. VALUE_NULLVALUE = 0,
  7673. VALUE_NUMBERVALUE = 1,
  7674. VALUE_STRINGVALUE = 2,
  7675. VALUE_BOOLVALUE = 3,
  7676. VALUE_STRUCTVALUE = 4,
  7677. VALUE_LISTVALUE = 5
  7678. };
  7679. /* Forward declare */
  7680. static bool is_top_level(upb_json_parser *p);
  7681. static bool is_wellknown_msg(upb_json_parser *p, upb_wellknowntype_t type);
  7682. static bool is_wellknown_field(upb_json_parser *p, upb_wellknowntype_t type);
  7683. static bool is_number_wrapper_object(upb_json_parser *p);
  7684. static bool does_number_wrapper_start(upb_json_parser *p);
  7685. static bool does_number_wrapper_end(upb_json_parser *p);
  7686. static bool is_string_wrapper_object(upb_json_parser *p);
  7687. static bool does_string_wrapper_start(upb_json_parser *p);
  7688. static bool does_string_wrapper_end(upb_json_parser *p);
  7689. static bool does_fieldmask_start(upb_json_parser *p);
  7690. static bool does_fieldmask_end(upb_json_parser *p);
  7691. static void start_fieldmask_object(upb_json_parser *p);
  7692. static void end_fieldmask_object(upb_json_parser *p);
  7693. static void start_wrapper_object(upb_json_parser *p);
  7694. static void end_wrapper_object(upb_json_parser *p);
  7695. static void start_value_object(upb_json_parser *p, int value_type);
  7696. static void end_value_object(upb_json_parser *p);
  7697. static void start_listvalue_object(upb_json_parser *p);
  7698. static void end_listvalue_object(upb_json_parser *p);
  7699. static void start_structvalue_object(upb_json_parser *p);
  7700. static void end_structvalue_object(upb_json_parser *p);
  7701. static void start_object(upb_json_parser *p);
  7702. static void end_object(upb_json_parser *p);
  7703. static void start_any_object(upb_json_parser *p, const char *ptr);
  7704. static bool end_any_object(upb_json_parser *p, const char *ptr);
  7705. static bool start_subobject(upb_json_parser *p);
  7706. static void end_subobject(upb_json_parser *p);
  7707. static void start_member(upb_json_parser *p);
  7708. static void end_member(upb_json_parser *p);
  7709. static bool end_membername(upb_json_parser *p);
  7710. static void start_any_member(upb_json_parser *p, const char *ptr);
  7711. static void end_any_member(upb_json_parser *p, const char *ptr);
  7712. static bool end_any_membername(upb_json_parser *p);
  7713. size_t parse(void *closure, const void *hd, const char *buf, size_t size,
  7714. const upb_bufhandle *handle);
  7715. static bool end(void *closure, const void *hd);
  7716. static const char eof_ch = 'e';
  7717. /* stringsink */
  7718. typedef struct {
  7719. upb_byteshandler handler;
  7720. upb_bytessink sink;
  7721. char *ptr;
  7722. size_t len, size;
  7723. } upb_stringsink;
  7724. static void *stringsink_start(void *_sink, const void *hd, size_t size_hint) {
  7725. upb_stringsink *sink = _sink;
  7726. sink->len = 0;
  7727. UPB_UNUSED(hd);
  7728. UPB_UNUSED(size_hint);
  7729. return sink;
  7730. }
  7731. static size_t stringsink_string(void *_sink, const void *hd, const char *ptr,
  7732. size_t len, const upb_bufhandle *handle) {
  7733. upb_stringsink *sink = _sink;
  7734. size_t new_size = sink->size;
  7735. UPB_UNUSED(hd);
  7736. UPB_UNUSED(handle);
  7737. while (sink->len + len > new_size) {
  7738. new_size *= 2;
  7739. }
  7740. if (new_size != sink->size) {
  7741. sink->ptr = realloc(sink->ptr, new_size);
  7742. sink->size = new_size;
  7743. }
  7744. memcpy(sink->ptr + sink->len, ptr, len);
  7745. sink->len += len;
  7746. return len;
  7747. }
  7748. void upb_stringsink_init(upb_stringsink *sink) {
  7749. upb_byteshandler_init(&sink->handler);
  7750. upb_byteshandler_setstartstr(&sink->handler, stringsink_start, NULL);
  7751. upb_byteshandler_setstring(&sink->handler, stringsink_string, NULL);
  7752. upb_bytessink_reset(&sink->sink, &sink->handler, sink);
  7753. sink->size = 32;
  7754. sink->ptr = malloc(sink->size);
  7755. sink->len = 0;
  7756. }
  7757. void upb_stringsink_uninit(upb_stringsink *sink) { free(sink->ptr); }
  7758. typedef struct {
  7759. /* For encoding Any value field in binary format. */
  7760. upb_handlercache *encoder_handlercache;
  7761. upb_stringsink stringsink;
  7762. /* For decoding Any value field in json format. */
  7763. upb_json_codecache *parser_codecache;
  7764. upb_sink sink;
  7765. upb_json_parser *parser;
  7766. /* Mark the range of uninterpreted values in json input before type url. */
  7767. const char *before_type_url_start;
  7768. const char *before_type_url_end;
  7769. /* Mark the range of uninterpreted values in json input after type url. */
  7770. const char *after_type_url_start;
  7771. } upb_jsonparser_any_frame;
  7772. typedef struct {
  7773. upb_sink sink;
  7774. /* The current message in which we're parsing, and the field whose value we're
  7775. * expecting next. */
  7776. const upb_msgdef *m;
  7777. const upb_fielddef *f;
  7778. /* The table mapping json name to fielddef for this message. */
  7779. const upb_strtable *name_table;
  7780. /* We are in a repeated-field context. We need this flag to decide whether to
  7781. * handle the array as a normal repeated field or a
  7782. * google.protobuf.ListValue/google.protobuf.Value. */
  7783. bool is_repeated;
  7784. /* We are in a repeated-field context, ready to emit mapentries as
  7785. * submessages. This flag alters the start-of-object (open-brace) behavior to
  7786. * begin a sequence of mapentry messages rather than a single submessage. */
  7787. bool is_map;
  7788. /* We are in a map-entry message context. This flag is set when parsing the
  7789. * value field of a single map entry and indicates to all value-field parsers
  7790. * (subobjects, strings, numbers, and bools) that the map-entry submessage
  7791. * should end as soon as the value is parsed. */
  7792. bool is_mapentry;
  7793. /* If |is_map| or |is_mapentry| is true, |mapfield| refers to the parent
  7794. * message's map field that we're currently parsing. This differs from |f|
  7795. * because |f| is the field in the *current* message (i.e., the map-entry
  7796. * message itself), not the parent's field that leads to this map. */
  7797. const upb_fielddef *mapfield;
  7798. /* We are in an Any message context. This flag is set when parsing the Any
  7799. * message and indicates to all field parsers (subobjects, strings, numbers,
  7800. * and bools) that the parsed field should be serialized as binary data or
  7801. * cached (type url not found yet). */
  7802. bool is_any;
  7803. /* The type of packed message in Any. */
  7804. upb_jsonparser_any_frame *any_frame;
  7805. /* True if the field to be parsed is unknown. */
  7806. bool is_unknown_field;
  7807. } upb_jsonparser_frame;
  7808. static void init_frame(upb_jsonparser_frame* frame) {
  7809. frame->m = NULL;
  7810. frame->f = NULL;
  7811. frame->name_table = NULL;
  7812. frame->is_repeated = false;
  7813. frame->is_map = false;
  7814. frame->is_mapentry = false;
  7815. frame->mapfield = NULL;
  7816. frame->is_any = false;
  7817. frame->any_frame = NULL;
  7818. frame->is_unknown_field = false;
  7819. }
  7820. struct upb_json_parser {
  7821. upb_arena *arena;
  7822. const upb_json_parsermethod *method;
  7823. upb_bytessink input_;
  7824. /* Stack to track the JSON scopes we are in. */
  7825. upb_jsonparser_frame stack[UPB_JSON_MAX_DEPTH];
  7826. upb_jsonparser_frame *top;
  7827. upb_jsonparser_frame *limit;
  7828. upb_status *status;
  7829. /* Ragel's internal parsing stack for the parsing state machine. */
  7830. int current_state;
  7831. int parser_stack[UPB_JSON_MAX_DEPTH];
  7832. int parser_top;
  7833. /* The handle for the current buffer. */
  7834. const upb_bufhandle *handle;
  7835. /* Accumulate buffer. See details in parser.rl. */
  7836. const char *accumulated;
  7837. size_t accumulated_len;
  7838. char *accumulate_buf;
  7839. size_t accumulate_buf_size;
  7840. /* Multi-part text data. See details in parser.rl. */
  7841. int multipart_state;
  7842. upb_selector_t string_selector;
  7843. /* Input capture. See details in parser.rl. */
  7844. const char *capture;
  7845. /* Intermediate result of parsing a unicode escape sequence. */
  7846. uint32_t digit;
  7847. /* For resolve type url in Any. */
  7848. const upb_symtab *symtab;
  7849. /* Whether to proceed if unknown field is met. */
  7850. bool ignore_json_unknown;
  7851. /* Cache for parsing timestamp due to base and zone are handled in different
  7852. * handlers. */
  7853. struct tm tm;
  7854. };
  7855. static upb_jsonparser_frame* start_jsonparser_frame(upb_json_parser *p) {
  7856. upb_jsonparser_frame *inner;
  7857. inner = p->top + 1;
  7858. init_frame(inner);
  7859. return inner;
  7860. }
  7861. struct upb_json_codecache {
  7862. upb_arena *arena;
  7863. upb_inttable methods; /* upb_msgdef* -> upb_json_parsermethod* */
  7864. };
  7865. struct upb_json_parsermethod {
  7866. const upb_json_codecache *cache;
  7867. upb_byteshandler input_handler_;
  7868. /* Maps json_name -> fielddef */
  7869. upb_strtable name_table;
  7870. };
  7871. #define PARSER_CHECK_RETURN(x) if (!(x)) return false
  7872. static upb_jsonparser_any_frame *json_parser_any_frame_new(
  7873. upb_json_parser *p) {
  7874. upb_jsonparser_any_frame *frame;
  7875. frame = upb_arena_malloc(p->arena, sizeof(upb_jsonparser_any_frame));
  7876. frame->encoder_handlercache = upb_pb_encoder_newcache();
  7877. frame->parser_codecache = upb_json_codecache_new();
  7878. frame->parser = NULL;
  7879. frame->before_type_url_start = NULL;
  7880. frame->before_type_url_end = NULL;
  7881. frame->after_type_url_start = NULL;
  7882. upb_stringsink_init(&frame->stringsink);
  7883. return frame;
  7884. }
  7885. static void json_parser_any_frame_set_payload_type(
  7886. upb_json_parser *p,
  7887. upb_jsonparser_any_frame *frame,
  7888. const upb_msgdef *payload_type) {
  7889. const upb_handlers *h;
  7890. const upb_json_parsermethod *parser_method;
  7891. upb_pb_encoder *encoder;
  7892. /* Initialize encoder. */
  7893. h = upb_handlercache_get(frame->encoder_handlercache, payload_type);
  7894. encoder = upb_pb_encoder_create(p->arena, h, frame->stringsink.sink);
  7895. /* Initialize parser. */
  7896. parser_method = upb_json_codecache_get(frame->parser_codecache, payload_type);
  7897. upb_sink_reset(&frame->sink, h, encoder);
  7898. frame->parser =
  7899. upb_json_parser_create(p->arena, parser_method, p->symtab, frame->sink,
  7900. p->status, p->ignore_json_unknown);
  7901. }
  7902. static void json_parser_any_frame_free(upb_jsonparser_any_frame *frame) {
  7903. upb_handlercache_free(frame->encoder_handlercache);
  7904. upb_json_codecache_free(frame->parser_codecache);
  7905. upb_stringsink_uninit(&frame->stringsink);
  7906. }
  7907. static bool json_parser_any_frame_has_type_url(
  7908. upb_jsonparser_any_frame *frame) {
  7909. return frame->parser != NULL;
  7910. }
  7911. static bool json_parser_any_frame_has_value_before_type_url(
  7912. upb_jsonparser_any_frame *frame) {
  7913. return frame->before_type_url_start != frame->before_type_url_end;
  7914. }
  7915. static bool json_parser_any_frame_has_value_after_type_url(
  7916. upb_jsonparser_any_frame *frame) {
  7917. return frame->after_type_url_start != NULL;
  7918. }
  7919. static bool json_parser_any_frame_has_value(
  7920. upb_jsonparser_any_frame *frame) {
  7921. return json_parser_any_frame_has_value_before_type_url(frame) ||
  7922. json_parser_any_frame_has_value_after_type_url(frame);
  7923. }
  7924. static void json_parser_any_frame_set_before_type_url_end(
  7925. upb_jsonparser_any_frame *frame,
  7926. const char *ptr) {
  7927. if (frame->parser == NULL) {
  7928. frame->before_type_url_end = ptr;
  7929. }
  7930. }
  7931. static void json_parser_any_frame_set_after_type_url_start_once(
  7932. upb_jsonparser_any_frame *frame,
  7933. const char *ptr) {
  7934. if (json_parser_any_frame_has_type_url(frame) &&
  7935. frame->after_type_url_start == NULL) {
  7936. frame->after_type_url_start = ptr;
  7937. }
  7938. }
  7939. /* Used to signal that a capture has been suspended. */
  7940. static char suspend_capture;
  7941. static upb_selector_t getsel_for_handlertype(upb_json_parser *p,
  7942. upb_handlertype_t type) {
  7943. upb_selector_t sel;
  7944. bool ok = upb_handlers_getselector(p->top->f, type, &sel);
  7945. UPB_ASSUME(ok);
  7946. return sel;
  7947. }
  7948. static upb_selector_t parser_getsel(upb_json_parser *p) {
  7949. return getsel_for_handlertype(
  7950. p, upb_handlers_getprimitivehandlertype(p->top->f));
  7951. }
  7952. static bool check_stack(upb_json_parser *p) {
  7953. if ((p->top + 1) == p->limit) {
  7954. upb_status_seterrmsg(p->status, "Nesting too deep");
  7955. return false;
  7956. }
  7957. return true;
  7958. }
  7959. static void set_name_table(upb_json_parser *p, upb_jsonparser_frame *frame) {
  7960. upb_value v;
  7961. const upb_json_codecache *cache = p->method->cache;
  7962. bool ok;
  7963. const upb_json_parsermethod *method;
  7964. ok = upb_inttable_lookupptr(&cache->methods, frame->m, &v);
  7965. UPB_ASSUME(ok);
  7966. method = upb_value_getconstptr(v);
  7967. frame->name_table = &method->name_table;
  7968. }
  7969. /* There are GCC/Clang built-ins for overflow checking which we could start
  7970. * using if there was any performance benefit to it. */
  7971. static bool checked_add(size_t a, size_t b, size_t *c) {
  7972. if (SIZE_MAX - a < b) return false;
  7973. *c = a + b;
  7974. return true;
  7975. }
  7976. static size_t saturating_multiply(size_t a, size_t b) {
  7977. /* size_t is unsigned, so this is defined behavior even on overflow. */
  7978. size_t ret = a * b;
  7979. if (b != 0 && ret / b != a) {
  7980. ret = SIZE_MAX;
  7981. }
  7982. return ret;
  7983. }
  7984. /* Base64 decoding ************************************************************/
  7985. /* TODO(haberman): make this streaming. */
  7986. static const signed char b64table[] = {
  7987. -1, -1, -1, -1, -1, -1, -1, -1,
  7988. -1, -1, -1, -1, -1, -1, -1, -1,
  7989. -1, -1, -1, -1, -1, -1, -1, -1,
  7990. -1, -1, -1, -1, -1, -1, -1, -1,
  7991. -1, -1, -1, -1, -1, -1, -1, -1,
  7992. -1, -1, -1, 62/*+*/, -1, -1, -1, 63/*/ */,
  7993. 52/*0*/, 53/*1*/, 54/*2*/, 55/*3*/, 56/*4*/, 57/*5*/, 58/*6*/, 59/*7*/,
  7994. 60/*8*/, 61/*9*/, -1, -1, -1, -1, -1, -1,
  7995. -1, 0/*A*/, 1/*B*/, 2/*C*/, 3/*D*/, 4/*E*/, 5/*F*/, 6/*G*/,
  7996. 07/*H*/, 8/*I*/, 9/*J*/, 10/*K*/, 11/*L*/, 12/*M*/, 13/*N*/, 14/*O*/,
  7997. 15/*P*/, 16/*Q*/, 17/*R*/, 18/*S*/, 19/*T*/, 20/*U*/, 21/*V*/, 22/*W*/,
  7998. 23/*X*/, 24/*Y*/, 25/*Z*/, -1, -1, -1, -1, -1,
  7999. -1, 26/*a*/, 27/*b*/, 28/*c*/, 29/*d*/, 30/*e*/, 31/*f*/, 32/*g*/,
  8000. 33/*h*/, 34/*i*/, 35/*j*/, 36/*k*/, 37/*l*/, 38/*m*/, 39/*n*/, 40/*o*/,
  8001. 41/*p*/, 42/*q*/, 43/*r*/, 44/*s*/, 45/*t*/, 46/*u*/, 47/*v*/, 48/*w*/,
  8002. 49/*x*/, 50/*y*/, 51/*z*/, -1, -1, -1, -1, -1,
  8003. -1, -1, -1, -1, -1, -1, -1, -1,
  8004. -1, -1, -1, -1, -1, -1, -1, -1,
  8005. -1, -1, -1, -1, -1, -1, -1, -1,
  8006. -1, -1, -1, -1, -1, -1, -1, -1,
  8007. -1, -1, -1, -1, -1, -1, -1, -1,
  8008. -1, -1, -1, -1, -1, -1, -1, -1,
  8009. -1, -1, -1, -1, -1, -1, -1, -1,
  8010. -1, -1, -1, -1, -1, -1, -1, -1,
  8011. -1, -1, -1, -1, -1, -1, -1, -1,
  8012. -1, -1, -1, -1, -1, -1, -1, -1,
  8013. -1, -1, -1, -1, -1, -1, -1, -1,
  8014. -1, -1, -1, -1, -1, -1, -1, -1,
  8015. -1, -1, -1, -1, -1, -1, -1, -1,
  8016. -1, -1, -1, -1, -1, -1, -1, -1,
  8017. -1, -1, -1, -1, -1, -1, -1, -1,
  8018. -1, -1, -1, -1, -1, -1, -1, -1
  8019. };
  8020. /* Returns the table value sign-extended to 32 bits. Knowing that the upper
  8021. * bits will be 1 for unrecognized characters makes it easier to check for
  8022. * this error condition later (see below). */
  8023. int32_t b64lookup(unsigned char ch) { return b64table[ch]; }
  8024. /* Returns true if the given character is not a valid base64 character or
  8025. * padding. */
  8026. bool nonbase64(unsigned char ch) { return b64lookup(ch) == -1 && ch != '='; }
  8027. static bool base64_push(upb_json_parser *p, upb_selector_t sel, const char *ptr,
  8028. size_t len) {
  8029. const char *limit = ptr + len;
  8030. for (; ptr < limit; ptr += 4) {
  8031. uint32_t val;
  8032. char output[3];
  8033. if (limit - ptr < 4) {
  8034. upb_status_seterrf(p->status,
  8035. "Base64 input for bytes field not a multiple of 4: %s",
  8036. upb_fielddef_name(p->top->f));
  8037. return false;
  8038. }
  8039. val = b64lookup(ptr[0]) << 18 |
  8040. b64lookup(ptr[1]) << 12 |
  8041. b64lookup(ptr[2]) << 6 |
  8042. b64lookup(ptr[3]);
  8043. /* Test the upper bit; returns true if any of the characters returned -1. */
  8044. if (val & 0x80000000) {
  8045. goto otherchar;
  8046. }
  8047. output[0] = val >> 16;
  8048. output[1] = (val >> 8) & 0xff;
  8049. output[2] = val & 0xff;
  8050. upb_sink_putstring(p->top->sink, sel, output, 3, NULL);
  8051. }
  8052. return true;
  8053. otherchar:
  8054. if (nonbase64(ptr[0]) || nonbase64(ptr[1]) || nonbase64(ptr[2]) ||
  8055. nonbase64(ptr[3]) ) {
  8056. upb_status_seterrf(p->status,
  8057. "Non-base64 characters in bytes field: %s",
  8058. upb_fielddef_name(p->top->f));
  8059. return false;
  8060. } if (ptr[2] == '=') {
  8061. uint32_t val;
  8062. char output;
  8063. /* Last group contains only two input bytes, one output byte. */
  8064. if (ptr[0] == '=' || ptr[1] == '=' || ptr[3] != '=') {
  8065. goto badpadding;
  8066. }
  8067. val = b64lookup(ptr[0]) << 18 |
  8068. b64lookup(ptr[1]) << 12;
  8069. UPB_ASSERT(!(val & 0x80000000));
  8070. output = val >> 16;
  8071. upb_sink_putstring(p->top->sink, sel, &output, 1, NULL);
  8072. return true;
  8073. } else {
  8074. uint32_t val;
  8075. char output[2];
  8076. /* Last group contains only three input bytes, two output bytes. */
  8077. if (ptr[0] == '=' || ptr[1] == '=' || ptr[2] == '=') {
  8078. goto badpadding;
  8079. }
  8080. val = b64lookup(ptr[0]) << 18 |
  8081. b64lookup(ptr[1]) << 12 |
  8082. b64lookup(ptr[2]) << 6;
  8083. output[0] = val >> 16;
  8084. output[1] = (val >> 8) & 0xff;
  8085. upb_sink_putstring(p->top->sink, sel, output, 2, NULL);
  8086. return true;
  8087. }
  8088. badpadding:
  8089. upb_status_seterrf(p->status,
  8090. "Incorrect base64 padding for field: %s (%.*s)",
  8091. upb_fielddef_name(p->top->f),
  8092. 4, ptr);
  8093. return false;
  8094. }
  8095. /* Accumulate buffer **********************************************************/
  8096. /* Functionality for accumulating a buffer.
  8097. *
  8098. * Some parts of the parser need an entire value as a contiguous string. For
  8099. * example, to look up a member name in a hash table, or to turn a string into
  8100. * a number, the relevant library routines need the input string to be in
  8101. * contiguous memory, even if the value spanned two or more buffers in the
  8102. * input. These routines handle that.
  8103. *
  8104. * In the common case we can just point to the input buffer to get this
  8105. * contiguous string and avoid any actual copy. So we optimistically begin
  8106. * this way. But there are a few cases where we must instead copy into a
  8107. * separate buffer:
  8108. *
  8109. * 1. The string was not contiguous in the input (it spanned buffers).
  8110. *
  8111. * 2. The string included escape sequences that need to be interpreted to get
  8112. * the true value in a contiguous buffer. */
  8113. static void assert_accumulate_empty(upb_json_parser *p) {
  8114. UPB_ASSERT(p->accumulated == NULL);
  8115. UPB_ASSERT(p->accumulated_len == 0);
  8116. }
  8117. static void accumulate_clear(upb_json_parser *p) {
  8118. p->accumulated = NULL;
  8119. p->accumulated_len = 0;
  8120. }
  8121. /* Used internally by accumulate_append(). */
  8122. static bool accumulate_realloc(upb_json_parser *p, size_t need) {
  8123. void *mem;
  8124. size_t old_size = p->accumulate_buf_size;
  8125. size_t new_size = UPB_MAX(old_size, 128);
  8126. while (new_size < need) {
  8127. new_size = saturating_multiply(new_size, 2);
  8128. }
  8129. mem = upb_arena_realloc(p->arena, p->accumulate_buf, old_size, new_size);
  8130. if (!mem) {
  8131. upb_status_seterrmsg(p->status, "Out of memory allocating buffer.");
  8132. return false;
  8133. }
  8134. p->accumulate_buf = mem;
  8135. p->accumulate_buf_size = new_size;
  8136. return true;
  8137. }
  8138. /* Logically appends the given data to the append buffer.
  8139. * If "can_alias" is true, we will try to avoid actually copying, but the buffer
  8140. * must be valid until the next accumulate_append() call (if any). */
  8141. static bool accumulate_append(upb_json_parser *p, const char *buf, size_t len,
  8142. bool can_alias) {
  8143. size_t need;
  8144. if (!p->accumulated && can_alias) {
  8145. p->accumulated = buf;
  8146. p->accumulated_len = len;
  8147. return true;
  8148. }
  8149. if (!checked_add(p->accumulated_len, len, &need)) {
  8150. upb_status_seterrmsg(p->status, "Integer overflow.");
  8151. return false;
  8152. }
  8153. if (need > p->accumulate_buf_size && !accumulate_realloc(p, need)) {
  8154. return false;
  8155. }
  8156. if (p->accumulated != p->accumulate_buf) {
  8157. memcpy(p->accumulate_buf, p->accumulated, p->accumulated_len);
  8158. p->accumulated = p->accumulate_buf;
  8159. }
  8160. memcpy(p->accumulate_buf + p->accumulated_len, buf, len);
  8161. p->accumulated_len += len;
  8162. return true;
  8163. }
  8164. /* Returns a pointer to the data accumulated since the last accumulate_clear()
  8165. * call, and writes the length to *len. This with point either to the input
  8166. * buffer or a temporary accumulate buffer. */
  8167. static const char *accumulate_getptr(upb_json_parser *p, size_t *len) {
  8168. UPB_ASSERT(p->accumulated);
  8169. *len = p->accumulated_len;
  8170. return p->accumulated;
  8171. }
  8172. /* Mult-part text data ********************************************************/
  8173. /* When we have text data in the input, it can often come in multiple segments.
  8174. * For example, there may be some raw string data followed by an escape
  8175. * sequence. The two segments are processed with different logic. Also buffer
  8176. * seams in the input can cause multiple segments.
  8177. *
  8178. * As we see segments, there are two main cases for how we want to process them:
  8179. *
  8180. * 1. we want to push the captured input directly to string handlers.
  8181. *
  8182. * 2. we need to accumulate all the parts into a contiguous buffer for further
  8183. * processing (field name lookup, string->number conversion, etc). */
  8184. /* This is the set of states for p->multipart_state. */
  8185. enum {
  8186. /* We are not currently processing multipart data. */
  8187. MULTIPART_INACTIVE = 0,
  8188. /* We are processing multipart data by accumulating it into a contiguous
  8189. * buffer. */
  8190. MULTIPART_ACCUMULATE = 1,
  8191. /* We are processing multipart data by pushing each part directly to the
  8192. * current string handlers. */
  8193. MULTIPART_PUSHEAGERLY = 2
  8194. };
  8195. /* Start a multi-part text value where we accumulate the data for processing at
  8196. * the end. */
  8197. static void multipart_startaccum(upb_json_parser *p) {
  8198. assert_accumulate_empty(p);
  8199. UPB_ASSERT(p->multipart_state == MULTIPART_INACTIVE);
  8200. p->multipart_state = MULTIPART_ACCUMULATE;
  8201. }
  8202. /* Start a multi-part text value where we immediately push text data to a string
  8203. * value with the given selector. */
  8204. static void multipart_start(upb_json_parser *p, upb_selector_t sel) {
  8205. assert_accumulate_empty(p);
  8206. UPB_ASSERT(p->multipart_state == MULTIPART_INACTIVE);
  8207. p->multipart_state = MULTIPART_PUSHEAGERLY;
  8208. p->string_selector = sel;
  8209. }
  8210. static bool multipart_text(upb_json_parser *p, const char *buf, size_t len,
  8211. bool can_alias) {
  8212. switch (p->multipart_state) {
  8213. case MULTIPART_INACTIVE:
  8214. upb_status_seterrmsg(
  8215. p->status, "Internal error: unexpected state MULTIPART_INACTIVE");
  8216. return false;
  8217. case MULTIPART_ACCUMULATE:
  8218. if (!accumulate_append(p, buf, len, can_alias)) {
  8219. return false;
  8220. }
  8221. break;
  8222. case MULTIPART_PUSHEAGERLY: {
  8223. const upb_bufhandle *handle = can_alias ? p->handle : NULL;
  8224. upb_sink_putstring(p->top->sink, p->string_selector, buf, len, handle);
  8225. break;
  8226. }
  8227. }
  8228. return true;
  8229. }
  8230. /* Note: this invalidates the accumulate buffer! Call only after reading its
  8231. * contents. */
  8232. static void multipart_end(upb_json_parser *p) {
  8233. /* This is false sometimes. Probably a bug of some sort, but this code is
  8234. * intended for deletion soon. */
  8235. /* UPB_ASSERT(p->multipart_state != MULTIPART_INACTIVE); */
  8236. p->multipart_state = MULTIPART_INACTIVE;
  8237. accumulate_clear(p);
  8238. }
  8239. /* Input capture **************************************************************/
  8240. /* Functionality for capturing a region of the input as text. Gracefully
  8241. * handles the case where a buffer seam occurs in the middle of the captured
  8242. * region. */
  8243. static void capture_begin(upb_json_parser *p, const char *ptr) {
  8244. UPB_ASSERT(p->multipart_state != MULTIPART_INACTIVE);
  8245. UPB_ASSERT(p->capture == NULL);
  8246. p->capture = ptr;
  8247. }
  8248. static bool capture_end(upb_json_parser *p, const char *ptr) {
  8249. UPB_ASSERT(p->capture);
  8250. if (multipart_text(p, p->capture, ptr - p->capture, true)) {
  8251. p->capture = NULL;
  8252. return true;
  8253. } else {
  8254. return false;
  8255. }
  8256. }
  8257. /* This is called at the end of each input buffer (ie. when we have hit a
  8258. * buffer seam). If we are in the middle of capturing the input, this
  8259. * processes the unprocessed capture region. */
  8260. static void capture_suspend(upb_json_parser *p, const char **ptr) {
  8261. if (!p->capture) return;
  8262. if (multipart_text(p, p->capture, *ptr - p->capture, false)) {
  8263. /* We use this as a signal that we were in the middle of capturing, and
  8264. * that capturing should resume at the beginning of the next buffer.
  8265. *
  8266. * We can't use *ptr here, because we have no guarantee that this pointer
  8267. * will be valid when we resume (if the underlying memory is freed, then
  8268. * using the pointer at all, even to compare to NULL, is likely undefined
  8269. * behavior). */
  8270. p->capture = &suspend_capture;
  8271. } else {
  8272. /* Need to back up the pointer to the beginning of the capture, since
  8273. * we were not able to actually preserve it. */
  8274. *ptr = p->capture;
  8275. }
  8276. }
  8277. static void capture_resume(upb_json_parser *p, const char *ptr) {
  8278. if (p->capture) {
  8279. UPB_ASSERT(p->capture == &suspend_capture);
  8280. p->capture = ptr;
  8281. }
  8282. }
  8283. /* Callbacks from the parser **************************************************/
  8284. /* These are the functions called directly from the parser itself.
  8285. * We define these in the same order as their declarations in the parser. */
  8286. static char escape_char(char in) {
  8287. switch (in) {
  8288. case 'r': return '\r';
  8289. case 't': return '\t';
  8290. case 'n': return '\n';
  8291. case 'f': return '\f';
  8292. case 'b': return '\b';
  8293. case '/': return '/';
  8294. case '"': return '"';
  8295. case '\\': return '\\';
  8296. default:
  8297. UPB_ASSERT(0);
  8298. return 'x';
  8299. }
  8300. }
  8301. static bool escape(upb_json_parser *p, const char *ptr) {
  8302. char ch = escape_char(*ptr);
  8303. return multipart_text(p, &ch, 1, false);
  8304. }
  8305. static void start_hex(upb_json_parser *p) {
  8306. p->digit = 0;
  8307. }
  8308. static void hexdigit(upb_json_parser *p, const char *ptr) {
  8309. char ch = *ptr;
  8310. p->digit <<= 4;
  8311. if (ch >= '0' && ch <= '9') {
  8312. p->digit += (ch - '0');
  8313. } else if (ch >= 'a' && ch <= 'f') {
  8314. p->digit += ((ch - 'a') + 10);
  8315. } else {
  8316. UPB_ASSERT(ch >= 'A' && ch <= 'F');
  8317. p->digit += ((ch - 'A') + 10);
  8318. }
  8319. }
  8320. static bool end_hex(upb_json_parser *p) {
  8321. uint32_t codepoint = p->digit;
  8322. /* emit the codepoint as UTF-8. */
  8323. char utf8[3]; /* support \u0000 -- \uFFFF -- need only three bytes. */
  8324. int length = 0;
  8325. if (codepoint <= 0x7F) {
  8326. utf8[0] = codepoint;
  8327. length = 1;
  8328. } else if (codepoint <= 0x07FF) {
  8329. utf8[1] = (codepoint & 0x3F) | 0x80;
  8330. codepoint >>= 6;
  8331. utf8[0] = (codepoint & 0x1F) | 0xC0;
  8332. length = 2;
  8333. } else /* codepoint <= 0xFFFF */ {
  8334. utf8[2] = (codepoint & 0x3F) | 0x80;
  8335. codepoint >>= 6;
  8336. utf8[1] = (codepoint & 0x3F) | 0x80;
  8337. codepoint >>= 6;
  8338. utf8[0] = (codepoint & 0x0F) | 0xE0;
  8339. length = 3;
  8340. }
  8341. /* TODO(haberman): Handle high surrogates: if codepoint is a high surrogate
  8342. * we have to wait for the next escape to get the full code point). */
  8343. return multipart_text(p, utf8, length, false);
  8344. }
  8345. static void start_text(upb_json_parser *p, const char *ptr) {
  8346. capture_begin(p, ptr);
  8347. }
  8348. static bool end_text(upb_json_parser *p, const char *ptr) {
  8349. return capture_end(p, ptr);
  8350. }
  8351. static bool start_number(upb_json_parser *p, const char *ptr) {
  8352. if (is_top_level(p)) {
  8353. if (is_number_wrapper_object(p)) {
  8354. start_wrapper_object(p);
  8355. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8356. start_value_object(p, VALUE_NUMBERVALUE);
  8357. } else {
  8358. return false;
  8359. }
  8360. } else if (does_number_wrapper_start(p)) {
  8361. if (!start_subobject(p)) {
  8362. return false;
  8363. }
  8364. start_wrapper_object(p);
  8365. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  8366. if (!start_subobject(p)) {
  8367. return false;
  8368. }
  8369. start_value_object(p, VALUE_NUMBERVALUE);
  8370. }
  8371. multipart_startaccum(p);
  8372. capture_begin(p, ptr);
  8373. return true;
  8374. }
  8375. static bool parse_number(upb_json_parser *p, bool is_quoted);
  8376. static bool end_number_nontop(upb_json_parser *p, const char *ptr) {
  8377. if (!capture_end(p, ptr)) {
  8378. return false;
  8379. }
  8380. if (p->top->f == NULL) {
  8381. multipart_end(p);
  8382. return true;
  8383. }
  8384. return parse_number(p, false);
  8385. }
  8386. static bool end_number(upb_json_parser *p, const char *ptr) {
  8387. if (!end_number_nontop(p, ptr)) {
  8388. return false;
  8389. }
  8390. if (does_number_wrapper_end(p)) {
  8391. end_wrapper_object(p);
  8392. if (!is_top_level(p)) {
  8393. end_subobject(p);
  8394. }
  8395. return true;
  8396. }
  8397. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8398. end_value_object(p);
  8399. if (!is_top_level(p)) {
  8400. end_subobject(p);
  8401. }
  8402. return true;
  8403. }
  8404. return true;
  8405. }
  8406. /* |buf| is NULL-terminated. |buf| itself will never include quotes;
  8407. * |is_quoted| tells us whether this text originally appeared inside quotes. */
  8408. static bool parse_number_from_buffer(upb_json_parser *p, const char *buf,
  8409. bool is_quoted) {
  8410. size_t len = strlen(buf);
  8411. const char *bufend = buf + len;
  8412. char *end;
  8413. upb_fieldtype_t type = upb_fielddef_type(p->top->f);
  8414. double val;
  8415. double dummy;
  8416. double inf = UPB_INFINITY;
  8417. errno = 0;
  8418. if (len == 0 || buf[0] == ' ') {
  8419. return false;
  8420. }
  8421. /* For integer types, first try parsing with integer-specific routines.
  8422. * If these succeed, they will be more accurate for int64/uint64 than
  8423. * strtod().
  8424. */
  8425. switch (type) {
  8426. case UPB_TYPE_ENUM:
  8427. case UPB_TYPE_INT32: {
  8428. long val = strtol(buf, &end, 0);
  8429. if (errno == ERANGE || end != bufend) {
  8430. break;
  8431. } else if (val > INT32_MAX || val < INT32_MIN) {
  8432. return false;
  8433. } else {
  8434. upb_sink_putint32(p->top->sink, parser_getsel(p), (int32_t)val);
  8435. return true;
  8436. }
  8437. }
  8438. case UPB_TYPE_UINT32: {
  8439. unsigned long val = strtoul(buf, &end, 0);
  8440. if (end != bufend) {
  8441. break;
  8442. } else if (val > UINT32_MAX || errno == ERANGE) {
  8443. return false;
  8444. } else {
  8445. upb_sink_putuint32(p->top->sink, parser_getsel(p), (uint32_t)val);
  8446. return true;
  8447. }
  8448. }
  8449. /* XXX: We can't handle [u]int64 properly on 32-bit machines because
  8450. * strto[u]ll isn't in C89. */
  8451. case UPB_TYPE_INT64: {
  8452. long val = strtol(buf, &end, 0);
  8453. if (errno == ERANGE || end != bufend) {
  8454. break;
  8455. } else {
  8456. upb_sink_putint64(p->top->sink, parser_getsel(p), val);
  8457. return true;
  8458. }
  8459. }
  8460. case UPB_TYPE_UINT64: {
  8461. unsigned long val = strtoul(p->accumulated, &end, 0);
  8462. if (end != bufend) {
  8463. break;
  8464. } else if (errno == ERANGE) {
  8465. return false;
  8466. } else {
  8467. upb_sink_putuint64(p->top->sink, parser_getsel(p), val);
  8468. return true;
  8469. }
  8470. }
  8471. default:
  8472. break;
  8473. }
  8474. if (type != UPB_TYPE_DOUBLE && type != UPB_TYPE_FLOAT && is_quoted) {
  8475. /* Quoted numbers for integer types are not allowed to be in double form. */
  8476. return false;
  8477. }
  8478. if (len == strlen("Infinity") && strcmp(buf, "Infinity") == 0) {
  8479. /* C89 does not have an INFINITY macro. */
  8480. val = inf;
  8481. } else if (len == strlen("-Infinity") && strcmp(buf, "-Infinity") == 0) {
  8482. val = -inf;
  8483. } else {
  8484. val = strtod(buf, &end);
  8485. if (errno == ERANGE || end != bufend) {
  8486. return false;
  8487. }
  8488. }
  8489. switch (type) {
  8490. #define CASE(capitaltype, smalltype, ctype, min, max) \
  8491. case UPB_TYPE_ ## capitaltype: { \
  8492. if (modf(val, &dummy) != 0 || val > max || val < min) { \
  8493. return false; \
  8494. } else { \
  8495. upb_sink_put ## smalltype(p->top->sink, parser_getsel(p), \
  8496. (ctype)val); \
  8497. return true; \
  8498. } \
  8499. break; \
  8500. }
  8501. case UPB_TYPE_ENUM:
  8502. CASE(INT32, int32, int32_t, INT32_MIN, INT32_MAX);
  8503. CASE(INT64, int64, int64_t, INT64_MIN, INT64_MAX);
  8504. CASE(UINT32, uint32, uint32_t, 0, UINT32_MAX);
  8505. CASE(UINT64, uint64, uint64_t, 0, UINT64_MAX);
  8506. #undef CASE
  8507. case UPB_TYPE_DOUBLE:
  8508. upb_sink_putdouble(p->top->sink, parser_getsel(p), val);
  8509. return true;
  8510. case UPB_TYPE_FLOAT:
  8511. if ((val > FLT_MAX || val < -FLT_MAX) && val != inf && val != -inf) {
  8512. return false;
  8513. } else {
  8514. upb_sink_putfloat(p->top->sink, parser_getsel(p), val);
  8515. return true;
  8516. }
  8517. default:
  8518. return false;
  8519. }
  8520. }
  8521. static bool parse_number(upb_json_parser *p, bool is_quoted) {
  8522. size_t len;
  8523. const char *buf;
  8524. /* strtol() and friends unfortunately do not support specifying the length of
  8525. * the input string, so we need to force a copy into a NULL-terminated buffer. */
  8526. if (!multipart_text(p, "\0", 1, false)) {
  8527. return false;
  8528. }
  8529. buf = accumulate_getptr(p, &len);
  8530. if (parse_number_from_buffer(p, buf, is_quoted)) {
  8531. multipart_end(p);
  8532. return true;
  8533. } else {
  8534. upb_status_seterrf(p->status, "error parsing number: %s", buf);
  8535. multipart_end(p);
  8536. return false;
  8537. }
  8538. }
  8539. static bool parser_putbool(upb_json_parser *p, bool val) {
  8540. bool ok;
  8541. if (p->top->f == NULL) {
  8542. return true;
  8543. }
  8544. if (upb_fielddef_type(p->top->f) != UPB_TYPE_BOOL) {
  8545. upb_status_seterrf(p->status,
  8546. "Boolean value specified for non-bool field: %s",
  8547. upb_fielddef_name(p->top->f));
  8548. return false;
  8549. }
  8550. ok = upb_sink_putbool(p->top->sink, parser_getsel(p), val);
  8551. UPB_ASSERT(ok);
  8552. return true;
  8553. }
  8554. static bool end_bool(upb_json_parser *p, bool val) {
  8555. if (is_top_level(p)) {
  8556. if (is_wellknown_msg(p, UPB_WELLKNOWN_BOOLVALUE)) {
  8557. start_wrapper_object(p);
  8558. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8559. start_value_object(p, VALUE_BOOLVALUE);
  8560. } else {
  8561. return false;
  8562. }
  8563. } else if (is_wellknown_field(p, UPB_WELLKNOWN_BOOLVALUE)) {
  8564. if (!start_subobject(p)) {
  8565. return false;
  8566. }
  8567. start_wrapper_object(p);
  8568. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  8569. if (!start_subobject(p)) {
  8570. return false;
  8571. }
  8572. start_value_object(p, VALUE_BOOLVALUE);
  8573. }
  8574. if (p->top->is_unknown_field) {
  8575. return true;
  8576. }
  8577. if (!parser_putbool(p, val)) {
  8578. return false;
  8579. }
  8580. if (is_wellknown_msg(p, UPB_WELLKNOWN_BOOLVALUE)) {
  8581. end_wrapper_object(p);
  8582. if (!is_top_level(p)) {
  8583. end_subobject(p);
  8584. }
  8585. return true;
  8586. }
  8587. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8588. end_value_object(p);
  8589. if (!is_top_level(p)) {
  8590. end_subobject(p);
  8591. }
  8592. return true;
  8593. }
  8594. return true;
  8595. }
  8596. static bool end_null(upb_json_parser *p) {
  8597. const char *zero_ptr = "0";
  8598. if (is_top_level(p)) {
  8599. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8600. start_value_object(p, VALUE_NULLVALUE);
  8601. } else {
  8602. return true;
  8603. }
  8604. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  8605. if (!start_subobject(p)) {
  8606. return false;
  8607. }
  8608. start_value_object(p, VALUE_NULLVALUE);
  8609. } else {
  8610. return true;
  8611. }
  8612. /* Fill null_value field. */
  8613. multipart_startaccum(p);
  8614. capture_begin(p, zero_ptr);
  8615. capture_end(p, zero_ptr + 1);
  8616. parse_number(p, false);
  8617. end_value_object(p);
  8618. if (!is_top_level(p)) {
  8619. end_subobject(p);
  8620. }
  8621. return true;
  8622. }
  8623. static bool start_any_stringval(upb_json_parser *p) {
  8624. multipart_startaccum(p);
  8625. return true;
  8626. }
  8627. static bool start_stringval(upb_json_parser *p) {
  8628. if (is_top_level(p)) {
  8629. if (is_string_wrapper_object(p) ||
  8630. is_number_wrapper_object(p)) {
  8631. start_wrapper_object(p);
  8632. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_FIELDMASK)) {
  8633. start_fieldmask_object(p);
  8634. return true;
  8635. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_TIMESTAMP) ||
  8636. is_wellknown_msg(p, UPB_WELLKNOWN_DURATION)) {
  8637. start_object(p);
  8638. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8639. start_value_object(p, VALUE_STRINGVALUE);
  8640. } else {
  8641. return false;
  8642. }
  8643. } else if (does_string_wrapper_start(p) ||
  8644. does_number_wrapper_start(p)) {
  8645. if (!start_subobject(p)) {
  8646. return false;
  8647. }
  8648. start_wrapper_object(p);
  8649. } else if (does_fieldmask_start(p)) {
  8650. if (!start_subobject(p)) {
  8651. return false;
  8652. }
  8653. start_fieldmask_object(p);
  8654. return true;
  8655. } else if (is_wellknown_field(p, UPB_WELLKNOWN_TIMESTAMP) ||
  8656. is_wellknown_field(p, UPB_WELLKNOWN_DURATION)) {
  8657. if (!start_subobject(p)) {
  8658. return false;
  8659. }
  8660. start_object(p);
  8661. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  8662. if (!start_subobject(p)) {
  8663. return false;
  8664. }
  8665. start_value_object(p, VALUE_STRINGVALUE);
  8666. }
  8667. if (p->top->f == NULL) {
  8668. multipart_startaccum(p);
  8669. return true;
  8670. }
  8671. if (p->top->is_any) {
  8672. return start_any_stringval(p);
  8673. }
  8674. if (upb_fielddef_isstring(p->top->f)) {
  8675. upb_jsonparser_frame *inner;
  8676. upb_selector_t sel;
  8677. if (!check_stack(p)) return false;
  8678. /* Start a new parser frame: parser frames correspond one-to-one with
  8679. * handler frames, and string events occur in a sub-frame. */
  8680. inner = start_jsonparser_frame(p);
  8681. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  8682. upb_sink_startstr(p->top->sink, sel, 0, &inner->sink);
  8683. inner->m = p->top->m;
  8684. inner->f = p->top->f;
  8685. p->top = inner;
  8686. if (upb_fielddef_type(p->top->f) == UPB_TYPE_STRING) {
  8687. /* For STRING fields we push data directly to the handlers as it is
  8688. * parsed. We don't do this yet for BYTES fields, because our base64
  8689. * decoder is not streaming.
  8690. *
  8691. * TODO(haberman): make base64 decoding streaming also. */
  8692. multipart_start(p, getsel_for_handlertype(p, UPB_HANDLER_STRING));
  8693. return true;
  8694. } else {
  8695. multipart_startaccum(p);
  8696. return true;
  8697. }
  8698. } else if (upb_fielddef_type(p->top->f) != UPB_TYPE_BOOL &&
  8699. upb_fielddef_type(p->top->f) != UPB_TYPE_MESSAGE) {
  8700. /* No need to push a frame -- numeric values in quotes remain in the
  8701. * current parser frame. These values must accmulate so we can convert
  8702. * them all at once at the end. */
  8703. multipart_startaccum(p);
  8704. return true;
  8705. } else {
  8706. upb_status_seterrf(p->status,
  8707. "String specified for bool or submessage field: %s",
  8708. upb_fielddef_name(p->top->f));
  8709. return false;
  8710. }
  8711. }
  8712. static bool end_any_stringval(upb_json_parser *p) {
  8713. size_t len;
  8714. const char *buf = accumulate_getptr(p, &len);
  8715. /* Set type_url */
  8716. upb_selector_t sel;
  8717. upb_jsonparser_frame *inner;
  8718. if (!check_stack(p)) return false;
  8719. inner = p->top + 1;
  8720. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  8721. upb_sink_startstr(p->top->sink, sel, 0, &inner->sink);
  8722. sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
  8723. upb_sink_putstring(inner->sink, sel, buf, len, NULL);
  8724. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  8725. upb_sink_endstr(inner->sink, sel);
  8726. multipart_end(p);
  8727. /* Resolve type url */
  8728. if (strncmp(buf, "type.googleapis.com/", 20) == 0 && len > 20) {
  8729. const upb_msgdef *payload_type = NULL;
  8730. buf += 20;
  8731. len -= 20;
  8732. payload_type = upb_symtab_lookupmsg2(p->symtab, buf, len);
  8733. if (payload_type == NULL) {
  8734. upb_status_seterrf(
  8735. p->status, "Cannot find packed type: %.*s\n", (int)len, buf);
  8736. return false;
  8737. }
  8738. json_parser_any_frame_set_payload_type(p, p->top->any_frame, payload_type);
  8739. return true;
  8740. } else {
  8741. upb_status_seterrf(
  8742. p->status, "Invalid type url: %.*s\n", (int)len, buf);
  8743. return false;
  8744. }
  8745. }
  8746. static bool end_stringval_nontop(upb_json_parser *p) {
  8747. bool ok = true;
  8748. if (is_wellknown_msg(p, UPB_WELLKNOWN_TIMESTAMP) ||
  8749. is_wellknown_msg(p, UPB_WELLKNOWN_DURATION)) {
  8750. multipart_end(p);
  8751. return true;
  8752. }
  8753. if (p->top->f == NULL) {
  8754. multipart_end(p);
  8755. return true;
  8756. }
  8757. if (p->top->is_any) {
  8758. return end_any_stringval(p);
  8759. }
  8760. switch (upb_fielddef_type(p->top->f)) {
  8761. case UPB_TYPE_BYTES:
  8762. if (!base64_push(p, getsel_for_handlertype(p, UPB_HANDLER_STRING),
  8763. p->accumulated, p->accumulated_len)) {
  8764. return false;
  8765. }
  8766. /* Fall through. */
  8767. case UPB_TYPE_STRING: {
  8768. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  8769. upb_sink_endstr(p->top->sink, sel);
  8770. p->top--;
  8771. break;
  8772. }
  8773. case UPB_TYPE_ENUM: {
  8774. /* Resolve enum symbolic name to integer value. */
  8775. const upb_enumdef *enumdef = upb_fielddef_enumsubdef(p->top->f);
  8776. size_t len;
  8777. const char *buf = accumulate_getptr(p, &len);
  8778. int32_t int_val = 0;
  8779. ok = upb_enumdef_ntoi(enumdef, buf, len, &int_val);
  8780. if (ok) {
  8781. upb_selector_t sel = parser_getsel(p);
  8782. upb_sink_putint32(p->top->sink, sel, int_val);
  8783. } else {
  8784. if (p->ignore_json_unknown) {
  8785. ok = true;
  8786. /* TODO(teboring): Should also clean this field. */
  8787. } else {
  8788. upb_status_seterrf(p->status, "Enum value unknown: '%.*s'", len, buf);
  8789. }
  8790. }
  8791. break;
  8792. }
  8793. case UPB_TYPE_INT32:
  8794. case UPB_TYPE_INT64:
  8795. case UPB_TYPE_UINT32:
  8796. case UPB_TYPE_UINT64:
  8797. case UPB_TYPE_DOUBLE:
  8798. case UPB_TYPE_FLOAT:
  8799. ok = parse_number(p, true);
  8800. break;
  8801. default:
  8802. UPB_ASSERT(false);
  8803. upb_status_seterrmsg(p->status, "Internal error in JSON decoder");
  8804. ok = false;
  8805. break;
  8806. }
  8807. multipart_end(p);
  8808. return ok;
  8809. }
  8810. static bool end_stringval(upb_json_parser *p) {
  8811. /* FieldMask's stringvals have been ended when handling them. Only need to
  8812. * close FieldMask here.*/
  8813. if (does_fieldmask_end(p)) {
  8814. end_fieldmask_object(p);
  8815. if (!is_top_level(p)) {
  8816. end_subobject(p);
  8817. }
  8818. return true;
  8819. }
  8820. if (!end_stringval_nontop(p)) {
  8821. return false;
  8822. }
  8823. if (does_string_wrapper_end(p) ||
  8824. does_number_wrapper_end(p)) {
  8825. end_wrapper_object(p);
  8826. if (!is_top_level(p)) {
  8827. end_subobject(p);
  8828. }
  8829. return true;
  8830. }
  8831. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8832. end_value_object(p);
  8833. if (!is_top_level(p)) {
  8834. end_subobject(p);
  8835. }
  8836. return true;
  8837. }
  8838. if (is_wellknown_msg(p, UPB_WELLKNOWN_TIMESTAMP) ||
  8839. is_wellknown_msg(p, UPB_WELLKNOWN_DURATION) ||
  8840. is_wellknown_msg(p, UPB_WELLKNOWN_FIELDMASK)) {
  8841. end_object(p);
  8842. if (!is_top_level(p)) {
  8843. end_subobject(p);
  8844. }
  8845. return true;
  8846. }
  8847. return true;
  8848. }
  8849. static void start_duration_base(upb_json_parser *p, const char *ptr) {
  8850. capture_begin(p, ptr);
  8851. }
  8852. static bool end_duration_base(upb_json_parser *p, const char *ptr) {
  8853. size_t len;
  8854. const char *buf;
  8855. char seconds_buf[14];
  8856. char nanos_buf[12];
  8857. char *end;
  8858. int64_t seconds = 0;
  8859. int32_t nanos = 0;
  8860. double val = 0.0;
  8861. const char *seconds_membername = "seconds";
  8862. const char *nanos_membername = "nanos";
  8863. size_t fraction_start;
  8864. if (!capture_end(p, ptr)) {
  8865. return false;
  8866. }
  8867. buf = accumulate_getptr(p, &len);
  8868. memset(seconds_buf, 0, 14);
  8869. memset(nanos_buf, 0, 12);
  8870. /* Find out base end. The maximus duration is 315576000000, which cannot be
  8871. * represented by double without losing precision. Thus, we need to handle
  8872. * fraction and base separately. */
  8873. for (fraction_start = 0; fraction_start < len && buf[fraction_start] != '.';
  8874. fraction_start++);
  8875. /* Parse base */
  8876. memcpy(seconds_buf, buf, fraction_start);
  8877. seconds = strtol(seconds_buf, &end, 10);
  8878. if (errno == ERANGE || end != seconds_buf + fraction_start) {
  8879. upb_status_seterrf(p->status, "error parsing duration: %s",
  8880. seconds_buf);
  8881. return false;
  8882. }
  8883. if (seconds > 315576000000) {
  8884. upb_status_seterrf(p->status, "error parsing duration: "
  8885. "maximum acceptable value is "
  8886. "315576000000");
  8887. return false;
  8888. }
  8889. if (seconds < -315576000000) {
  8890. upb_status_seterrf(p->status, "error parsing duration: "
  8891. "minimum acceptable value is "
  8892. "-315576000000");
  8893. return false;
  8894. }
  8895. /* Parse fraction */
  8896. nanos_buf[0] = '0';
  8897. memcpy(nanos_buf + 1, buf + fraction_start, len - fraction_start);
  8898. val = strtod(nanos_buf, &end);
  8899. if (errno == ERANGE || end != nanos_buf + len - fraction_start + 1) {
  8900. upb_status_seterrf(p->status, "error parsing duration: %s",
  8901. nanos_buf);
  8902. return false;
  8903. }
  8904. nanos = val * 1000000000;
  8905. if (seconds < 0) nanos = -nanos;
  8906. /* Clean up buffer */
  8907. multipart_end(p);
  8908. /* Set seconds */
  8909. start_member(p);
  8910. capture_begin(p, seconds_membername);
  8911. capture_end(p, seconds_membername + 7);
  8912. end_membername(p);
  8913. upb_sink_putint64(p->top->sink, parser_getsel(p), seconds);
  8914. end_member(p);
  8915. /* Set nanos */
  8916. start_member(p);
  8917. capture_begin(p, nanos_membername);
  8918. capture_end(p, nanos_membername + 5);
  8919. end_membername(p);
  8920. upb_sink_putint32(p->top->sink, parser_getsel(p), nanos);
  8921. end_member(p);
  8922. /* Continue previous arena */
  8923. multipart_startaccum(p);
  8924. return true;
  8925. }
  8926. static int parse_timestamp_number(upb_json_parser *p) {
  8927. size_t len;
  8928. const char *buf;
  8929. int val;
  8930. /* atoi() and friends unfortunately do not support specifying the length of
  8931. * the input string, so we need to force a copy into a NULL-terminated buffer. */
  8932. multipart_text(p, "\0", 1, false);
  8933. buf = accumulate_getptr(p, &len);
  8934. val = atoi(buf);
  8935. multipart_end(p);
  8936. multipart_startaccum(p);
  8937. return val;
  8938. }
  8939. static void start_year(upb_json_parser *p, const char *ptr) {
  8940. capture_begin(p, ptr);
  8941. }
  8942. static bool end_year(upb_json_parser *p, const char *ptr) {
  8943. if (!capture_end(p, ptr)) {
  8944. return false;
  8945. }
  8946. p->tm.tm_year = parse_timestamp_number(p) - 1900;
  8947. return true;
  8948. }
  8949. static void start_month(upb_json_parser *p, const char *ptr) {
  8950. capture_begin(p, ptr);
  8951. }
  8952. static bool end_month(upb_json_parser *p, const char *ptr) {
  8953. if (!capture_end(p, ptr)) {
  8954. return false;
  8955. }
  8956. p->tm.tm_mon = parse_timestamp_number(p) - 1;
  8957. return true;
  8958. }
  8959. static void start_day(upb_json_parser *p, const char *ptr) {
  8960. capture_begin(p, ptr);
  8961. }
  8962. static bool end_day(upb_json_parser *p, const char *ptr) {
  8963. if (!capture_end(p, ptr)) {
  8964. return false;
  8965. }
  8966. p->tm.tm_mday = parse_timestamp_number(p);
  8967. return true;
  8968. }
  8969. static void start_hour(upb_json_parser *p, const char *ptr) {
  8970. capture_begin(p, ptr);
  8971. }
  8972. static bool end_hour(upb_json_parser *p, const char *ptr) {
  8973. if (!capture_end(p, ptr)) {
  8974. return false;
  8975. }
  8976. p->tm.tm_hour = parse_timestamp_number(p);
  8977. return true;
  8978. }
  8979. static void start_minute(upb_json_parser *p, const char *ptr) {
  8980. capture_begin(p, ptr);
  8981. }
  8982. static bool end_minute(upb_json_parser *p, const char *ptr) {
  8983. if (!capture_end(p, ptr)) {
  8984. return false;
  8985. }
  8986. p->tm.tm_min = parse_timestamp_number(p);
  8987. return true;
  8988. }
  8989. static void start_second(upb_json_parser *p, const char *ptr) {
  8990. capture_begin(p, ptr);
  8991. }
  8992. static bool end_second(upb_json_parser *p, const char *ptr) {
  8993. if (!capture_end(p, ptr)) {
  8994. return false;
  8995. }
  8996. p->tm.tm_sec = parse_timestamp_number(p);
  8997. return true;
  8998. }
  8999. static void start_timestamp_base(upb_json_parser *p) {
  9000. memset(&p->tm, 0, sizeof(struct tm));
  9001. }
  9002. static void start_timestamp_fraction(upb_json_parser *p, const char *ptr) {
  9003. capture_begin(p, ptr);
  9004. }
  9005. static bool end_timestamp_fraction(upb_json_parser *p, const char *ptr) {
  9006. size_t len;
  9007. const char *buf;
  9008. char nanos_buf[12];
  9009. char *end;
  9010. double val = 0.0;
  9011. int32_t nanos;
  9012. const char *nanos_membername = "nanos";
  9013. memset(nanos_buf, 0, 12);
  9014. if (!capture_end(p, ptr)) {
  9015. return false;
  9016. }
  9017. buf = accumulate_getptr(p, &len);
  9018. if (len > 10) {
  9019. upb_status_seterrf(p->status,
  9020. "error parsing timestamp: at most 9-digit fraction.");
  9021. return false;
  9022. }
  9023. /* Parse nanos */
  9024. nanos_buf[0] = '0';
  9025. memcpy(nanos_buf + 1, buf, len);
  9026. val = strtod(nanos_buf, &end);
  9027. if (errno == ERANGE || end != nanos_buf + len + 1) {
  9028. upb_status_seterrf(p->status, "error parsing timestamp nanos: %s",
  9029. nanos_buf);
  9030. return false;
  9031. }
  9032. nanos = val * 1000000000;
  9033. /* Clean up previous environment */
  9034. multipart_end(p);
  9035. /* Set nanos */
  9036. start_member(p);
  9037. capture_begin(p, nanos_membername);
  9038. capture_end(p, nanos_membername + 5);
  9039. end_membername(p);
  9040. upb_sink_putint32(p->top->sink, parser_getsel(p), nanos);
  9041. end_member(p);
  9042. /* Continue previous environment */
  9043. multipart_startaccum(p);
  9044. return true;
  9045. }
  9046. static void start_timestamp_zone(upb_json_parser *p, const char *ptr) {
  9047. capture_begin(p, ptr);
  9048. }
  9049. static int div_round_up2(int n, int d) {
  9050. return (n + d - 1) / d;
  9051. }
  9052. /* epoch_days(1970, 1, 1) == 1970-01-01 == 0. */
  9053. static int epoch_days(int year, int month, int day) {
  9054. static const uint16_t month_yday[12] = {0, 31, 59, 90, 120, 151,
  9055. 181, 212, 243, 273, 304, 334};
  9056. int febs_since_0 = month > 2 ? year + 1 : year;
  9057. int leap_days_since_0 = div_round_up2(febs_since_0, 4) -
  9058. div_round_up2(febs_since_0, 100) +
  9059. div_round_up2(febs_since_0, 400);
  9060. int days_since_0 =
  9061. 365 * year + month_yday[month - 1] + (day - 1) + leap_days_since_0;
  9062. /* Convert from 0-epoch (0001-01-01 BC) to Unix Epoch (1970-01-01 AD).
  9063. * Since the "BC" system does not have a year zero, 1 BC == year zero. */
  9064. return days_since_0 - 719528;
  9065. }
  9066. static int64_t upb_timegm(const struct tm *tp) {
  9067. int64_t ret = epoch_days(tp->tm_year + 1900, tp->tm_mon + 1, tp->tm_mday);
  9068. ret = (ret * 24) + tp->tm_hour;
  9069. ret = (ret * 60) + tp->tm_min;
  9070. ret = (ret * 60) + tp->tm_sec;
  9071. return ret;
  9072. }
  9073. static bool end_timestamp_zone(upb_json_parser *p, const char *ptr) {
  9074. size_t len;
  9075. const char *buf;
  9076. int hours;
  9077. int64_t seconds;
  9078. const char *seconds_membername = "seconds";
  9079. if (!capture_end(p, ptr)) {
  9080. return false;
  9081. }
  9082. buf = accumulate_getptr(p, &len);
  9083. if (buf[0] != 'Z') {
  9084. if (sscanf(buf + 1, "%2d:00", &hours) != 1) {
  9085. upb_status_seterrf(p->status, "error parsing timestamp offset");
  9086. return false;
  9087. }
  9088. if (buf[0] == '+') {
  9089. hours = -hours;
  9090. }
  9091. p->tm.tm_hour += hours;
  9092. }
  9093. /* Normalize tm */
  9094. seconds = upb_timegm(&p->tm);
  9095. /* Check timestamp boundary */
  9096. if (seconds < -62135596800) {
  9097. upb_status_seterrf(p->status, "error parsing timestamp: "
  9098. "minimum acceptable value is "
  9099. "0001-01-01T00:00:00Z");
  9100. return false;
  9101. }
  9102. /* Clean up previous environment */
  9103. multipart_end(p);
  9104. /* Set seconds */
  9105. start_member(p);
  9106. capture_begin(p, seconds_membername);
  9107. capture_end(p, seconds_membername + 7);
  9108. end_membername(p);
  9109. upb_sink_putint64(p->top->sink, parser_getsel(p), seconds);
  9110. end_member(p);
  9111. /* Continue previous environment */
  9112. multipart_startaccum(p);
  9113. return true;
  9114. }
  9115. static void start_fieldmask_path_text(upb_json_parser *p, const char *ptr) {
  9116. capture_begin(p, ptr);
  9117. }
  9118. static bool end_fieldmask_path_text(upb_json_parser *p, const char *ptr) {
  9119. return capture_end(p, ptr);
  9120. }
  9121. static bool start_fieldmask_path(upb_json_parser *p) {
  9122. upb_jsonparser_frame *inner;
  9123. upb_selector_t sel;
  9124. if (!check_stack(p)) return false;
  9125. /* Start a new parser frame: parser frames correspond one-to-one with
  9126. * handler frames, and string events occur in a sub-frame. */
  9127. inner = start_jsonparser_frame(p);
  9128. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  9129. upb_sink_startstr(p->top->sink, sel, 0, &inner->sink);
  9130. inner->m = p->top->m;
  9131. inner->f = p->top->f;
  9132. p->top = inner;
  9133. multipart_startaccum(p);
  9134. return true;
  9135. }
  9136. static bool lower_camel_push(
  9137. upb_json_parser *p, upb_selector_t sel, const char *ptr, size_t len) {
  9138. const char *limit = ptr + len;
  9139. bool first = true;
  9140. for (;ptr < limit; ptr++) {
  9141. if (*ptr >= 'A' && *ptr <= 'Z' && !first) {
  9142. char lower = tolower(*ptr);
  9143. upb_sink_putstring(p->top->sink, sel, "_", 1, NULL);
  9144. upb_sink_putstring(p->top->sink, sel, &lower, 1, NULL);
  9145. } else {
  9146. upb_sink_putstring(p->top->sink, sel, ptr, 1, NULL);
  9147. }
  9148. first = false;
  9149. }
  9150. return true;
  9151. }
  9152. static bool end_fieldmask_path(upb_json_parser *p) {
  9153. upb_selector_t sel;
  9154. if (!lower_camel_push(
  9155. p, getsel_for_handlertype(p, UPB_HANDLER_STRING),
  9156. p->accumulated, p->accumulated_len)) {
  9157. return false;
  9158. }
  9159. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  9160. upb_sink_endstr(p->top->sink, sel);
  9161. p->top--;
  9162. multipart_end(p);
  9163. return true;
  9164. }
  9165. static void start_member(upb_json_parser *p) {
  9166. UPB_ASSERT(!p->top->f);
  9167. multipart_startaccum(p);
  9168. }
  9169. /* Helper: invoked during parse_mapentry() to emit the mapentry message's key
  9170. * field based on the current contents of the accumulate buffer. */
  9171. static bool parse_mapentry_key(upb_json_parser *p) {
  9172. size_t len;
  9173. const char *buf = accumulate_getptr(p, &len);
  9174. /* Emit the key field. We do a bit of ad-hoc parsing here because the
  9175. * parser state machine has already decided that this is a string field
  9176. * name, and we are reinterpreting it as some arbitrary key type. In
  9177. * particular, integer and bool keys are quoted, so we need to parse the
  9178. * quoted string contents here. */
  9179. p->top->f = upb_msgdef_itof(p->top->m, UPB_MAPENTRY_KEY);
  9180. if (p->top->f == NULL) {
  9181. upb_status_seterrmsg(p->status, "mapentry message has no key");
  9182. return false;
  9183. }
  9184. switch (upb_fielddef_type(p->top->f)) {
  9185. case UPB_TYPE_INT32:
  9186. case UPB_TYPE_INT64:
  9187. case UPB_TYPE_UINT32:
  9188. case UPB_TYPE_UINT64:
  9189. /* Invoke end_number. The accum buffer has the number's text already. */
  9190. if (!parse_number(p, true)) {
  9191. return false;
  9192. }
  9193. break;
  9194. case UPB_TYPE_BOOL:
  9195. if (len == 4 && !strncmp(buf, "true", 4)) {
  9196. if (!parser_putbool(p, true)) {
  9197. return false;
  9198. }
  9199. } else if (len == 5 && !strncmp(buf, "false", 5)) {
  9200. if (!parser_putbool(p, false)) {
  9201. return false;
  9202. }
  9203. } else {
  9204. upb_status_seterrmsg(p->status,
  9205. "Map bool key not 'true' or 'false'");
  9206. return false;
  9207. }
  9208. multipart_end(p);
  9209. break;
  9210. case UPB_TYPE_STRING:
  9211. case UPB_TYPE_BYTES: {
  9212. upb_sink subsink;
  9213. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  9214. upb_sink_startstr(p->top->sink, sel, len, &subsink);
  9215. sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
  9216. upb_sink_putstring(subsink, sel, buf, len, NULL);
  9217. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  9218. upb_sink_endstr(subsink, sel);
  9219. multipart_end(p);
  9220. break;
  9221. }
  9222. default:
  9223. upb_status_seterrmsg(p->status, "Invalid field type for map key");
  9224. return false;
  9225. }
  9226. return true;
  9227. }
  9228. /* Helper: emit one map entry (as a submessage in the map field sequence). This
  9229. * is invoked from end_membername(), at the end of the map entry's key string,
  9230. * with the map key in the accumulate buffer. It parses the key from that
  9231. * buffer, emits the handler calls to start the mapentry submessage (setting up
  9232. * its subframe in the process), and sets up state in the subframe so that the
  9233. * value parser (invoked next) will emit the mapentry's value field and then
  9234. * end the mapentry message. */
  9235. static bool handle_mapentry(upb_json_parser *p) {
  9236. const upb_fielddef *mapfield;
  9237. const upb_msgdef *mapentrymsg;
  9238. upb_jsonparser_frame *inner;
  9239. upb_selector_t sel;
  9240. /* Map entry: p->top->sink is the seq frame, so we need to start a frame
  9241. * for the mapentry itself, and then set |f| in that frame so that the map
  9242. * value field is parsed, and also set a flag to end the frame after the
  9243. * map-entry value is parsed. */
  9244. if (!check_stack(p)) return false;
  9245. mapfield = p->top->mapfield;
  9246. mapentrymsg = upb_fielddef_msgsubdef(mapfield);
  9247. inner = start_jsonparser_frame(p);
  9248. p->top->f = mapfield;
  9249. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
  9250. upb_sink_startsubmsg(p->top->sink, sel, &inner->sink);
  9251. inner->m = mapentrymsg;
  9252. inner->mapfield = mapfield;
  9253. /* Don't set this to true *yet* -- we reuse parsing handlers below to push
  9254. * the key field value to the sink, and these handlers will pop the frame
  9255. * if they see is_mapentry (when invoked by the parser state machine, they
  9256. * would have just seen the map-entry value, not key). */
  9257. inner->is_mapentry = false;
  9258. p->top = inner;
  9259. /* send STARTMSG in submsg frame. */
  9260. upb_sink_startmsg(p->top->sink);
  9261. parse_mapentry_key(p);
  9262. /* Set up the value field to receive the map-entry value. */
  9263. p->top->f = upb_msgdef_itof(p->top->m, UPB_MAPENTRY_VALUE);
  9264. p->top->is_mapentry = true; /* set up to pop frame after value is parsed. */
  9265. p->top->mapfield = mapfield;
  9266. if (p->top->f == NULL) {
  9267. upb_status_seterrmsg(p->status, "mapentry message has no value");
  9268. return false;
  9269. }
  9270. return true;
  9271. }
  9272. static bool end_membername(upb_json_parser *p) {
  9273. UPB_ASSERT(!p->top->f);
  9274. if (!p->top->m) {
  9275. p->top->is_unknown_field = true;
  9276. multipart_end(p);
  9277. return true;
  9278. }
  9279. if (p->top->is_any) {
  9280. return end_any_membername(p);
  9281. } else if (p->top->is_map) {
  9282. return handle_mapentry(p);
  9283. } else {
  9284. size_t len;
  9285. const char *buf = accumulate_getptr(p, &len);
  9286. upb_value v;
  9287. if (upb_strtable_lookup2(p->top->name_table, buf, len, &v)) {
  9288. p->top->f = upb_value_getconstptr(v);
  9289. multipart_end(p);
  9290. return true;
  9291. } else if (p->ignore_json_unknown) {
  9292. p->top->is_unknown_field = true;
  9293. multipart_end(p);
  9294. return true;
  9295. } else {
  9296. upb_status_seterrf(p->status, "No such field: %.*s\n", (int)len, buf);
  9297. return false;
  9298. }
  9299. }
  9300. }
  9301. static bool end_any_membername(upb_json_parser *p) {
  9302. size_t len;
  9303. const char *buf = accumulate_getptr(p, &len);
  9304. upb_value v;
  9305. if (len == 5 && strncmp(buf, "@type", len) == 0) {
  9306. upb_strtable_lookup2(p->top->name_table, "type_url", 8, &v);
  9307. p->top->f = upb_value_getconstptr(v);
  9308. multipart_end(p);
  9309. return true;
  9310. } else {
  9311. p->top->is_unknown_field = true;
  9312. multipart_end(p);
  9313. return true;
  9314. }
  9315. }
  9316. static void end_member(upb_json_parser *p) {
  9317. /* If we just parsed a map-entry value, end that frame too. */
  9318. if (p->top->is_mapentry) {
  9319. upb_selector_t sel;
  9320. bool ok;
  9321. const upb_fielddef *mapfield;
  9322. UPB_ASSERT(p->top > p->stack);
  9323. /* send ENDMSG on submsg. */
  9324. upb_sink_endmsg(p->top->sink, p->status);
  9325. mapfield = p->top->mapfield;
  9326. /* send ENDSUBMSG in repeated-field-of-mapentries frame. */
  9327. p->top--;
  9328. ok = upb_handlers_getselector(mapfield, UPB_HANDLER_ENDSUBMSG, &sel);
  9329. UPB_ASSUME(ok);
  9330. upb_sink_endsubmsg(p->top->sink, (p->top + 1)->sink, sel);
  9331. }
  9332. p->top->f = NULL;
  9333. p->top->is_unknown_field = false;
  9334. }
  9335. static void start_any_member(upb_json_parser *p, const char *ptr) {
  9336. start_member(p);
  9337. json_parser_any_frame_set_after_type_url_start_once(p->top->any_frame, ptr);
  9338. }
  9339. static void end_any_member(upb_json_parser *p, const char *ptr) {
  9340. json_parser_any_frame_set_before_type_url_end(p->top->any_frame, ptr);
  9341. end_member(p);
  9342. }
  9343. static bool start_subobject(upb_json_parser *p) {
  9344. if (p->top->is_unknown_field) {
  9345. if (!check_stack(p)) return false;
  9346. p->top = start_jsonparser_frame(p);
  9347. return true;
  9348. }
  9349. if (upb_fielddef_ismap(p->top->f)) {
  9350. upb_jsonparser_frame *inner;
  9351. upb_selector_t sel;
  9352. /* Beginning of a map. Start a new parser frame in a repeated-field
  9353. * context. */
  9354. if (!check_stack(p)) return false;
  9355. inner = start_jsonparser_frame(p);
  9356. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
  9357. upb_sink_startseq(p->top->sink, sel, &inner->sink);
  9358. inner->m = upb_fielddef_msgsubdef(p->top->f);
  9359. inner->mapfield = p->top->f;
  9360. inner->is_map = true;
  9361. p->top = inner;
  9362. return true;
  9363. } else if (upb_fielddef_issubmsg(p->top->f)) {
  9364. upb_jsonparser_frame *inner;
  9365. upb_selector_t sel;
  9366. /* Beginning of a subobject. Start a new parser frame in the submsg
  9367. * context. */
  9368. if (!check_stack(p)) return false;
  9369. inner = start_jsonparser_frame(p);
  9370. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
  9371. upb_sink_startsubmsg(p->top->sink, sel, &inner->sink);
  9372. inner->m = upb_fielddef_msgsubdef(p->top->f);
  9373. set_name_table(p, inner);
  9374. p->top = inner;
  9375. if (is_wellknown_msg(p, UPB_WELLKNOWN_ANY)) {
  9376. p->top->is_any = true;
  9377. p->top->any_frame = json_parser_any_frame_new(p);
  9378. } else {
  9379. p->top->is_any = false;
  9380. p->top->any_frame = NULL;
  9381. }
  9382. return true;
  9383. } else {
  9384. upb_status_seterrf(p->status,
  9385. "Object specified for non-message/group field: %s",
  9386. upb_fielddef_name(p->top->f));
  9387. return false;
  9388. }
  9389. }
  9390. static bool start_subobject_full(upb_json_parser *p) {
  9391. if (is_top_level(p)) {
  9392. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  9393. start_value_object(p, VALUE_STRUCTVALUE);
  9394. if (!start_subobject(p)) return false;
  9395. start_structvalue_object(p);
  9396. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_STRUCT)) {
  9397. start_structvalue_object(p);
  9398. } else {
  9399. return true;
  9400. }
  9401. } else if (is_wellknown_field(p, UPB_WELLKNOWN_STRUCT)) {
  9402. if (!start_subobject(p)) return false;
  9403. start_structvalue_object(p);
  9404. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  9405. if (!start_subobject(p)) return false;
  9406. start_value_object(p, VALUE_STRUCTVALUE);
  9407. if (!start_subobject(p)) return false;
  9408. start_structvalue_object(p);
  9409. }
  9410. return start_subobject(p);
  9411. }
  9412. static void end_subobject(upb_json_parser *p) {
  9413. if (is_top_level(p)) {
  9414. return;
  9415. }
  9416. if (p->top->is_map) {
  9417. upb_selector_t sel;
  9418. p->top--;
  9419. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
  9420. upb_sink_endseq(p->top->sink, sel);
  9421. } else {
  9422. upb_selector_t sel;
  9423. bool is_unknown = p->top->m == NULL;
  9424. p->top--;
  9425. if (!is_unknown) {
  9426. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSUBMSG);
  9427. upb_sink_endsubmsg(p->top->sink, (p->top + 1)->sink, sel);
  9428. }
  9429. }
  9430. }
  9431. static void end_subobject_full(upb_json_parser *p) {
  9432. end_subobject(p);
  9433. if (is_wellknown_msg(p, UPB_WELLKNOWN_STRUCT)) {
  9434. end_structvalue_object(p);
  9435. if (!is_top_level(p)) {
  9436. end_subobject(p);
  9437. }
  9438. }
  9439. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  9440. end_value_object(p);
  9441. if (!is_top_level(p)) {
  9442. end_subobject(p);
  9443. }
  9444. }
  9445. }
  9446. static bool start_array(upb_json_parser *p) {
  9447. upb_jsonparser_frame *inner;
  9448. upb_selector_t sel;
  9449. if (is_top_level(p)) {
  9450. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  9451. start_value_object(p, VALUE_LISTVALUE);
  9452. if (!start_subobject(p)) return false;
  9453. start_listvalue_object(p);
  9454. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_LISTVALUE)) {
  9455. start_listvalue_object(p);
  9456. } else {
  9457. return false;
  9458. }
  9459. } else if (is_wellknown_field(p, UPB_WELLKNOWN_LISTVALUE) &&
  9460. (!upb_fielddef_isseq(p->top->f) ||
  9461. p->top->is_repeated)) {
  9462. if (!start_subobject(p)) return false;
  9463. start_listvalue_object(p);
  9464. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE) &&
  9465. (!upb_fielddef_isseq(p->top->f) ||
  9466. p->top->is_repeated)) {
  9467. if (!start_subobject(p)) return false;
  9468. start_value_object(p, VALUE_LISTVALUE);
  9469. if (!start_subobject(p)) return false;
  9470. start_listvalue_object(p);
  9471. }
  9472. if (p->top->is_unknown_field) {
  9473. inner = start_jsonparser_frame(p);
  9474. inner->is_unknown_field = true;
  9475. p->top = inner;
  9476. return true;
  9477. }
  9478. if (!upb_fielddef_isseq(p->top->f)) {
  9479. upb_status_seterrf(p->status,
  9480. "Array specified for non-repeated field: %s",
  9481. upb_fielddef_name(p->top->f));
  9482. return false;
  9483. }
  9484. if (!check_stack(p)) return false;
  9485. inner = start_jsonparser_frame(p);
  9486. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
  9487. upb_sink_startseq(p->top->sink, sel, &inner->sink);
  9488. inner->m = p->top->m;
  9489. inner->f = p->top->f;
  9490. inner->is_repeated = true;
  9491. p->top = inner;
  9492. return true;
  9493. }
  9494. static void end_array(upb_json_parser *p) {
  9495. upb_selector_t sel;
  9496. UPB_ASSERT(p->top > p->stack);
  9497. p->top--;
  9498. if (p->top->is_unknown_field) {
  9499. return;
  9500. }
  9501. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
  9502. upb_sink_endseq(p->top->sink, sel);
  9503. if (is_wellknown_msg(p, UPB_WELLKNOWN_LISTVALUE)) {
  9504. end_listvalue_object(p);
  9505. if (!is_top_level(p)) {
  9506. end_subobject(p);
  9507. }
  9508. }
  9509. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  9510. end_value_object(p);
  9511. if (!is_top_level(p)) {
  9512. end_subobject(p);
  9513. }
  9514. }
  9515. }
  9516. static void start_object(upb_json_parser *p) {
  9517. if (!p->top->is_map && p->top->m != NULL) {
  9518. upb_sink_startmsg(p->top->sink);
  9519. }
  9520. }
  9521. static void end_object(upb_json_parser *p) {
  9522. if (!p->top->is_map && p->top->m != NULL) {
  9523. upb_sink_endmsg(p->top->sink, p->status);
  9524. }
  9525. }
  9526. static void start_any_object(upb_json_parser *p, const char *ptr) {
  9527. start_object(p);
  9528. p->top->any_frame->before_type_url_start = ptr;
  9529. p->top->any_frame->before_type_url_end = ptr;
  9530. }
  9531. static bool end_any_object(upb_json_parser *p, const char *ptr) {
  9532. const char *value_membername = "value";
  9533. bool is_well_known_packed = false;
  9534. const char *packed_end = ptr + 1;
  9535. upb_selector_t sel;
  9536. upb_jsonparser_frame *inner;
  9537. if (json_parser_any_frame_has_value(p->top->any_frame) &&
  9538. !json_parser_any_frame_has_type_url(p->top->any_frame)) {
  9539. upb_status_seterrmsg(p->status, "No valid type url");
  9540. return false;
  9541. }
  9542. /* Well known types data is represented as value field. */
  9543. if (upb_msgdef_wellknowntype(p->top->any_frame->parser->top->m) !=
  9544. UPB_WELLKNOWN_UNSPECIFIED) {
  9545. is_well_known_packed = true;
  9546. if (json_parser_any_frame_has_value_before_type_url(p->top->any_frame)) {
  9547. p->top->any_frame->before_type_url_start =
  9548. memchr(p->top->any_frame->before_type_url_start, ':',
  9549. p->top->any_frame->before_type_url_end -
  9550. p->top->any_frame->before_type_url_start);
  9551. if (p->top->any_frame->before_type_url_start == NULL) {
  9552. upb_status_seterrmsg(p->status, "invalid data for well known type.");
  9553. return false;
  9554. }
  9555. p->top->any_frame->before_type_url_start++;
  9556. }
  9557. if (json_parser_any_frame_has_value_after_type_url(p->top->any_frame)) {
  9558. p->top->any_frame->after_type_url_start =
  9559. memchr(p->top->any_frame->after_type_url_start, ':',
  9560. (ptr + 1) -
  9561. p->top->any_frame->after_type_url_start);
  9562. if (p->top->any_frame->after_type_url_start == NULL) {
  9563. upb_status_seterrmsg(p->status, "Invalid data for well known type.");
  9564. return false;
  9565. }
  9566. p->top->any_frame->after_type_url_start++;
  9567. packed_end = ptr;
  9568. }
  9569. }
  9570. if (json_parser_any_frame_has_value_before_type_url(p->top->any_frame)) {
  9571. if (!parse(p->top->any_frame->parser, NULL,
  9572. p->top->any_frame->before_type_url_start,
  9573. p->top->any_frame->before_type_url_end -
  9574. p->top->any_frame->before_type_url_start, NULL)) {
  9575. return false;
  9576. }
  9577. } else {
  9578. if (!is_well_known_packed) {
  9579. if (!parse(p->top->any_frame->parser, NULL, "{", 1, NULL)) {
  9580. return false;
  9581. }
  9582. }
  9583. }
  9584. if (json_parser_any_frame_has_value_before_type_url(p->top->any_frame) &&
  9585. json_parser_any_frame_has_value_after_type_url(p->top->any_frame)) {
  9586. if (!parse(p->top->any_frame->parser, NULL, ",", 1, NULL)) {
  9587. return false;
  9588. }
  9589. }
  9590. if (json_parser_any_frame_has_value_after_type_url(p->top->any_frame)) {
  9591. if (!parse(p->top->any_frame->parser, NULL,
  9592. p->top->any_frame->after_type_url_start,
  9593. packed_end - p->top->any_frame->after_type_url_start, NULL)) {
  9594. return false;
  9595. }
  9596. } else {
  9597. if (!is_well_known_packed) {
  9598. if (!parse(p->top->any_frame->parser, NULL, "}", 1, NULL)) {
  9599. return false;
  9600. }
  9601. }
  9602. }
  9603. if (!end(p->top->any_frame->parser, NULL)) {
  9604. return false;
  9605. }
  9606. p->top->is_any = false;
  9607. /* Set value */
  9608. start_member(p);
  9609. capture_begin(p, value_membername);
  9610. capture_end(p, value_membername + 5);
  9611. end_membername(p);
  9612. if (!check_stack(p)) return false;
  9613. inner = p->top + 1;
  9614. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  9615. upb_sink_startstr(p->top->sink, sel, 0, &inner->sink);
  9616. sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
  9617. upb_sink_putstring(inner->sink, sel, p->top->any_frame->stringsink.ptr,
  9618. p->top->any_frame->stringsink.len, NULL);
  9619. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  9620. upb_sink_endstr(inner->sink, sel);
  9621. end_member(p);
  9622. end_object(p);
  9623. /* Deallocate any parse frame. */
  9624. json_parser_any_frame_free(p->top->any_frame);
  9625. return true;
  9626. }
  9627. static bool is_string_wrapper(const upb_msgdef *m) {
  9628. upb_wellknowntype_t type = upb_msgdef_wellknowntype(m);
  9629. return type == UPB_WELLKNOWN_STRINGVALUE ||
  9630. type == UPB_WELLKNOWN_BYTESVALUE;
  9631. }
  9632. static bool is_fieldmask(const upb_msgdef *m) {
  9633. upb_wellknowntype_t type = upb_msgdef_wellknowntype(m);
  9634. return type == UPB_WELLKNOWN_FIELDMASK;
  9635. }
  9636. static void start_fieldmask_object(upb_json_parser *p) {
  9637. const char *membername = "paths";
  9638. start_object(p);
  9639. /* Set up context for parsing value */
  9640. start_member(p);
  9641. capture_begin(p, membername);
  9642. capture_end(p, membername + 5);
  9643. end_membername(p);
  9644. start_array(p);
  9645. }
  9646. static void end_fieldmask_object(upb_json_parser *p) {
  9647. end_array(p);
  9648. end_member(p);
  9649. end_object(p);
  9650. }
  9651. static void start_wrapper_object(upb_json_parser *p) {
  9652. const char *membername = "value";
  9653. start_object(p);
  9654. /* Set up context for parsing value */
  9655. start_member(p);
  9656. capture_begin(p, membername);
  9657. capture_end(p, membername + 5);
  9658. end_membername(p);
  9659. }
  9660. static void end_wrapper_object(upb_json_parser *p) {
  9661. end_member(p);
  9662. end_object(p);
  9663. }
  9664. static void start_value_object(upb_json_parser *p, int value_type) {
  9665. const char *nullmember = "null_value";
  9666. const char *numbermember = "number_value";
  9667. const char *stringmember = "string_value";
  9668. const char *boolmember = "bool_value";
  9669. const char *structmember = "struct_value";
  9670. const char *listmember = "list_value";
  9671. const char *membername = "";
  9672. switch (value_type) {
  9673. case VALUE_NULLVALUE:
  9674. membername = nullmember;
  9675. break;
  9676. case VALUE_NUMBERVALUE:
  9677. membername = numbermember;
  9678. break;
  9679. case VALUE_STRINGVALUE:
  9680. membername = stringmember;
  9681. break;
  9682. case VALUE_BOOLVALUE:
  9683. membername = boolmember;
  9684. break;
  9685. case VALUE_STRUCTVALUE:
  9686. membername = structmember;
  9687. break;
  9688. case VALUE_LISTVALUE:
  9689. membername = listmember;
  9690. break;
  9691. }
  9692. start_object(p);
  9693. /* Set up context for parsing value */
  9694. start_member(p);
  9695. capture_begin(p, membername);
  9696. capture_end(p, membername + strlen(membername));
  9697. end_membername(p);
  9698. }
  9699. static void end_value_object(upb_json_parser *p) {
  9700. end_member(p);
  9701. end_object(p);
  9702. }
  9703. static void start_listvalue_object(upb_json_parser *p) {
  9704. const char *membername = "values";
  9705. start_object(p);
  9706. /* Set up context for parsing value */
  9707. start_member(p);
  9708. capture_begin(p, membername);
  9709. capture_end(p, membername + strlen(membername));
  9710. end_membername(p);
  9711. }
  9712. static void end_listvalue_object(upb_json_parser *p) {
  9713. end_member(p);
  9714. end_object(p);
  9715. }
  9716. static void start_structvalue_object(upb_json_parser *p) {
  9717. const char *membername = "fields";
  9718. start_object(p);
  9719. /* Set up context for parsing value */
  9720. start_member(p);
  9721. capture_begin(p, membername);
  9722. capture_end(p, membername + strlen(membername));
  9723. end_membername(p);
  9724. }
  9725. static void end_structvalue_object(upb_json_parser *p) {
  9726. end_member(p);
  9727. end_object(p);
  9728. }
  9729. static bool is_top_level(upb_json_parser *p) {
  9730. return p->top == p->stack && p->top->f == NULL && !p->top->is_unknown_field;
  9731. }
  9732. static bool is_wellknown_msg(upb_json_parser *p, upb_wellknowntype_t type) {
  9733. return p->top->m != NULL && upb_msgdef_wellknowntype(p->top->m) == type;
  9734. }
  9735. static bool is_wellknown_field(upb_json_parser *p, upb_wellknowntype_t type) {
  9736. return p->top->f != NULL &&
  9737. upb_fielddef_issubmsg(p->top->f) &&
  9738. (upb_msgdef_wellknowntype(upb_fielddef_msgsubdef(p->top->f))
  9739. == type);
  9740. }
  9741. static bool does_number_wrapper_start(upb_json_parser *p) {
  9742. return p->top->f != NULL &&
  9743. upb_fielddef_issubmsg(p->top->f) &&
  9744. upb_msgdef_isnumberwrapper(upb_fielddef_msgsubdef(p->top->f));
  9745. }
  9746. static bool does_number_wrapper_end(upb_json_parser *p) {
  9747. return p->top->m != NULL && upb_msgdef_isnumberwrapper(p->top->m);
  9748. }
  9749. static bool is_number_wrapper_object(upb_json_parser *p) {
  9750. return p->top->m != NULL && upb_msgdef_isnumberwrapper(p->top->m);
  9751. }
  9752. static bool does_string_wrapper_start(upb_json_parser *p) {
  9753. return p->top->f != NULL &&
  9754. upb_fielddef_issubmsg(p->top->f) &&
  9755. is_string_wrapper(upb_fielddef_msgsubdef(p->top->f));
  9756. }
  9757. static bool does_string_wrapper_end(upb_json_parser *p) {
  9758. return p->top->m != NULL && is_string_wrapper(p->top->m);
  9759. }
  9760. static bool is_string_wrapper_object(upb_json_parser *p) {
  9761. return p->top->m != NULL && is_string_wrapper(p->top->m);
  9762. }
  9763. static bool does_fieldmask_start(upb_json_parser *p) {
  9764. return p->top->f != NULL &&
  9765. upb_fielddef_issubmsg(p->top->f) &&
  9766. is_fieldmask(upb_fielddef_msgsubdef(p->top->f));
  9767. }
  9768. static bool does_fieldmask_end(upb_json_parser *p) {
  9769. return p->top->m != NULL && is_fieldmask(p->top->m);
  9770. }
  9771. #define CHECK_RETURN_TOP(x) if (!(x)) goto error
  9772. /* The actual parser **********************************************************/
  9773. /* What follows is the Ragel parser itself. The language is specified in Ragel
  9774. * and the actions call our C functions above.
  9775. *
  9776. * Ragel has an extensive set of functionality, and we use only a small part of
  9777. * it. There are many action types but we only use a few:
  9778. *
  9779. * ">" -- transition into a machine
  9780. * "%" -- transition out of a machine
  9781. * "@" -- transition into a final state of a machine.
  9782. *
  9783. * "@" transitions are tricky because a machine can transition into a final
  9784. * state repeatedly. But in some cases we know this can't happen, for example
  9785. * a string which is delimited by a final '"' can only transition into its
  9786. * final state once, when the closing '"' is seen. */
  9787. #line 2787 "upb/json/parser.rl"
  9788. #line 2590 "upb/json/parser.c"
  9789. static const char _json_actions[] = {
  9790. 0, 1, 0, 1, 1, 1, 3, 1,
  9791. 4, 1, 6, 1, 7, 1, 8, 1,
  9792. 9, 1, 11, 1, 12, 1, 13, 1,
  9793. 14, 1, 15, 1, 16, 1, 17, 1,
  9794. 18, 1, 19, 1, 20, 1, 22, 1,
  9795. 23, 1, 24, 1, 35, 1, 37, 1,
  9796. 39, 1, 40, 1, 42, 1, 43, 1,
  9797. 44, 1, 46, 1, 48, 1, 49, 1,
  9798. 50, 1, 51, 1, 53, 1, 54, 2,
  9799. 4, 9, 2, 5, 6, 2, 7, 3,
  9800. 2, 7, 9, 2, 21, 26, 2, 25,
  9801. 10, 2, 27, 28, 2, 29, 30, 2,
  9802. 32, 34, 2, 33, 31, 2, 38, 36,
  9803. 2, 40, 42, 2, 45, 2, 2, 46,
  9804. 54, 2, 47, 36, 2, 49, 54, 2,
  9805. 50, 54, 2, 51, 54, 2, 52, 41,
  9806. 2, 53, 54, 3, 32, 34, 35, 4,
  9807. 21, 26, 27, 28
  9808. };
  9809. static const short _json_key_offsets[] = {
  9810. 0, 0, 12, 13, 18, 23, 28, 29,
  9811. 30, 31, 32, 33, 34, 35, 36, 37,
  9812. 38, 43, 44, 48, 53, 58, 63, 67,
  9813. 71, 74, 77, 79, 83, 87, 89, 91,
  9814. 96, 98, 100, 109, 115, 121, 127, 133,
  9815. 135, 139, 142, 144, 146, 149, 150, 154,
  9816. 156, 158, 160, 162, 163, 165, 167, 168,
  9817. 170, 172, 173, 175, 177, 178, 180, 182,
  9818. 183, 185, 187, 191, 193, 195, 196, 197,
  9819. 198, 199, 201, 206, 208, 210, 212, 221,
  9820. 222, 222, 222, 227, 232, 237, 238, 239,
  9821. 240, 241, 241, 242, 243, 244, 244, 245,
  9822. 246, 247, 247, 252, 253, 257, 262, 267,
  9823. 272, 276, 276, 279, 282, 285, 288, 291,
  9824. 294, 294, 294, 294, 294, 294
  9825. };
  9826. static const char _json_trans_keys[] = {
  9827. 32, 34, 45, 91, 102, 110, 116, 123,
  9828. 9, 13, 48, 57, 34, 32, 93, 125,
  9829. 9, 13, 32, 44, 93, 9, 13, 32,
  9830. 93, 125, 9, 13, 97, 108, 115, 101,
  9831. 117, 108, 108, 114, 117, 101, 32, 34,
  9832. 125, 9, 13, 34, 32, 58, 9, 13,
  9833. 32, 93, 125, 9, 13, 32, 44, 125,
  9834. 9, 13, 32, 44, 125, 9, 13, 32,
  9835. 34, 9, 13, 45, 48, 49, 57, 48,
  9836. 49, 57, 46, 69, 101, 48, 57, 69,
  9837. 101, 48, 57, 43, 45, 48, 57, 48,
  9838. 57, 48, 57, 46, 69, 101, 48, 57,
  9839. 34, 92, 34, 92, 34, 47, 92, 98,
  9840. 102, 110, 114, 116, 117, 48, 57, 65,
  9841. 70, 97, 102, 48, 57, 65, 70, 97,
  9842. 102, 48, 57, 65, 70, 97, 102, 48,
  9843. 57, 65, 70, 97, 102, 34, 92, 45,
  9844. 48, 49, 57, 48, 49, 57, 46, 115,
  9845. 48, 57, 115, 48, 57, 34, 46, 115,
  9846. 48, 57, 48, 57, 48, 57, 48, 57,
  9847. 48, 57, 45, 48, 57, 48, 57, 45,
  9848. 48, 57, 48, 57, 84, 48, 57, 48,
  9849. 57, 58, 48, 57, 48, 57, 58, 48,
  9850. 57, 48, 57, 43, 45, 46, 90, 48,
  9851. 57, 48, 57, 58, 48, 48, 34, 48,
  9852. 57, 43, 45, 90, 48, 57, 34, 44,
  9853. 34, 44, 34, 44, 34, 45, 91, 102,
  9854. 110, 116, 123, 48, 57, 34, 32, 93,
  9855. 125, 9, 13, 32, 44, 93, 9, 13,
  9856. 32, 93, 125, 9, 13, 97, 108, 115,
  9857. 101, 117, 108, 108, 114, 117, 101, 32,
  9858. 34, 125, 9, 13, 34, 32, 58, 9,
  9859. 13, 32, 93, 125, 9, 13, 32, 44,
  9860. 125, 9, 13, 32, 44, 125, 9, 13,
  9861. 32, 34, 9, 13, 32, 9, 13, 32,
  9862. 9, 13, 32, 9, 13, 32, 9, 13,
  9863. 32, 9, 13, 32, 9, 13, 0
  9864. };
  9865. static const char _json_single_lengths[] = {
  9866. 0, 8, 1, 3, 3, 3, 1, 1,
  9867. 1, 1, 1, 1, 1, 1, 1, 1,
  9868. 3, 1, 2, 3, 3, 3, 2, 2,
  9869. 1, 3, 0, 2, 2, 0, 0, 3,
  9870. 2, 2, 9, 0, 0, 0, 0, 2,
  9871. 2, 1, 2, 0, 1, 1, 2, 0,
  9872. 0, 0, 0, 1, 0, 0, 1, 0,
  9873. 0, 1, 0, 0, 1, 0, 0, 1,
  9874. 0, 0, 4, 0, 0, 1, 1, 1,
  9875. 1, 0, 3, 2, 2, 2, 7, 1,
  9876. 0, 0, 3, 3, 3, 1, 1, 1,
  9877. 1, 0, 1, 1, 1, 0, 1, 1,
  9878. 1, 0, 3, 1, 2, 3, 3, 3,
  9879. 2, 0, 1, 1, 1, 1, 1, 1,
  9880. 0, 0, 0, 0, 0, 0
  9881. };
  9882. static const char _json_range_lengths[] = {
  9883. 0, 2, 0, 1, 1, 1, 0, 0,
  9884. 0, 0, 0, 0, 0, 0, 0, 0,
  9885. 1, 0, 1, 1, 1, 1, 1, 1,
  9886. 1, 0, 1, 1, 1, 1, 1, 1,
  9887. 0, 0, 0, 3, 3, 3, 3, 0,
  9888. 1, 1, 0, 1, 1, 0, 1, 1,
  9889. 1, 1, 1, 0, 1, 1, 0, 1,
  9890. 1, 0, 1, 1, 0, 1, 1, 0,
  9891. 1, 1, 0, 1, 1, 0, 0, 0,
  9892. 0, 1, 1, 0, 0, 0, 1, 0,
  9893. 0, 0, 1, 1, 1, 0, 0, 0,
  9894. 0, 0, 0, 0, 0, 0, 0, 0,
  9895. 0, 0, 1, 0, 1, 1, 1, 1,
  9896. 1, 0, 1, 1, 1, 1, 1, 1,
  9897. 0, 0, 0, 0, 0, 0
  9898. };
  9899. static const short _json_index_offsets[] = {
  9900. 0, 0, 11, 13, 18, 23, 28, 30,
  9901. 32, 34, 36, 38, 40, 42, 44, 46,
  9902. 48, 53, 55, 59, 64, 69, 74, 78,
  9903. 82, 85, 89, 91, 95, 99, 101, 103,
  9904. 108, 111, 114, 124, 128, 132, 136, 140,
  9905. 143, 147, 150, 153, 155, 158, 160, 164,
  9906. 166, 168, 170, 172, 174, 176, 178, 180,
  9907. 182, 184, 186, 188, 190, 192, 194, 196,
  9908. 198, 200, 202, 207, 209, 211, 213, 215,
  9909. 217, 219, 221, 226, 229, 232, 235, 244,
  9910. 246, 247, 248, 253, 258, 263, 265, 267,
  9911. 269, 271, 272, 274, 276, 278, 279, 281,
  9912. 283, 285, 286, 291, 293, 297, 302, 307,
  9913. 312, 316, 317, 320, 323, 326, 329, 332,
  9914. 335, 336, 337, 338, 339, 340
  9915. };
  9916. static const unsigned char _json_indicies[] = {
  9917. 0, 2, 3, 4, 5, 6, 7, 8,
  9918. 0, 3, 1, 9, 1, 11, 12, 1,
  9919. 11, 10, 13, 14, 12, 13, 1, 14,
  9920. 1, 1, 14, 10, 15, 1, 16, 1,
  9921. 17, 1, 18, 1, 19, 1, 20, 1,
  9922. 21, 1, 22, 1, 23, 1, 24, 1,
  9923. 25, 26, 27, 25, 1, 28, 1, 29,
  9924. 30, 29, 1, 30, 1, 1, 30, 31,
  9925. 32, 33, 34, 32, 1, 35, 36, 27,
  9926. 35, 1, 36, 26, 36, 1, 37, 38,
  9927. 39, 1, 38, 39, 1, 41, 42, 42,
  9928. 40, 43, 1, 42, 42, 43, 40, 44,
  9929. 44, 45, 1, 45, 1, 45, 40, 41,
  9930. 42, 42, 39, 40, 47, 48, 46, 50,
  9931. 51, 49, 52, 52, 52, 52, 52, 52,
  9932. 52, 52, 53, 1, 54, 54, 54, 1,
  9933. 55, 55, 55, 1, 56, 56, 56, 1,
  9934. 57, 57, 57, 1, 59, 60, 58, 61,
  9935. 62, 63, 1, 64, 65, 1, 66, 67,
  9936. 1, 68, 1, 67, 68, 1, 69, 1,
  9937. 66, 67, 65, 1, 70, 1, 71, 1,
  9938. 72, 1, 73, 1, 74, 1, 75, 1,
  9939. 76, 1, 77, 1, 78, 1, 79, 1,
  9940. 80, 1, 81, 1, 82, 1, 83, 1,
  9941. 84, 1, 85, 1, 86, 1, 87, 1,
  9942. 88, 1, 89, 89, 90, 91, 1, 92,
  9943. 1, 93, 1, 94, 1, 95, 1, 96,
  9944. 1, 97, 1, 98, 1, 99, 99, 100,
  9945. 98, 1, 102, 1, 101, 104, 105, 103,
  9946. 1, 1, 101, 106, 107, 108, 109, 110,
  9947. 111, 112, 107, 1, 113, 1, 114, 115,
  9948. 117, 118, 1, 117, 116, 119, 120, 118,
  9949. 119, 1, 120, 1, 1, 120, 116, 121,
  9950. 1, 122, 1, 123, 1, 124, 1, 125,
  9951. 126, 1, 127, 1, 128, 1, 129, 130,
  9952. 1, 131, 1, 132, 1, 133, 134, 135,
  9953. 136, 134, 1, 137, 1, 138, 139, 138,
  9954. 1, 139, 1, 1, 139, 140, 141, 142,
  9955. 143, 141, 1, 144, 145, 136, 144, 1,
  9956. 145, 135, 145, 1, 146, 147, 147, 1,
  9957. 148, 148, 1, 149, 149, 1, 150, 150,
  9958. 1, 151, 151, 1, 152, 152, 1, 1,
  9959. 1, 1, 1, 1, 1, 0
  9960. };
  9961. static const char _json_trans_targs[] = {
  9962. 1, 0, 2, 107, 3, 6, 10, 13,
  9963. 16, 106, 4, 3, 106, 4, 5, 7,
  9964. 8, 9, 108, 11, 12, 109, 14, 15,
  9965. 110, 16, 17, 111, 18, 18, 19, 20,
  9966. 21, 22, 111, 21, 22, 24, 25, 31,
  9967. 112, 26, 28, 27, 29, 30, 33, 113,
  9968. 34, 33, 113, 34, 32, 35, 36, 37,
  9969. 38, 39, 33, 113, 34, 41, 42, 46,
  9970. 42, 46, 43, 45, 44, 114, 48, 49,
  9971. 50, 51, 52, 53, 54, 55, 56, 57,
  9972. 58, 59, 60, 61, 62, 63, 64, 65,
  9973. 66, 67, 73, 72, 68, 69, 70, 71,
  9974. 72, 115, 74, 67, 72, 76, 116, 76,
  9975. 116, 77, 79, 81, 82, 85, 90, 94,
  9976. 98, 80, 117, 117, 83, 82, 80, 83,
  9977. 84, 86, 87, 88, 89, 117, 91, 92,
  9978. 93, 117, 95, 96, 97, 117, 98, 99,
  9979. 105, 100, 100, 101, 102, 103, 104, 105,
  9980. 103, 104, 117, 106, 106, 106, 106, 106,
  9981. 106
  9982. };
  9983. static const unsigned char _json_trans_actions[] = {
  9984. 0, 0, 113, 107, 53, 0, 0, 0,
  9985. 125, 59, 45, 0, 55, 0, 0, 0,
  9986. 0, 0, 0, 0, 0, 0, 0, 0,
  9987. 0, 0, 101, 51, 47, 0, 0, 45,
  9988. 49, 49, 104, 0, 0, 0, 0, 0,
  9989. 3, 0, 0, 0, 0, 0, 5, 15,
  9990. 0, 0, 71, 7, 13, 0, 74, 9,
  9991. 9, 9, 77, 80, 11, 37, 37, 37,
  9992. 0, 0, 0, 39, 0, 41, 86, 0,
  9993. 0, 0, 17, 19, 0, 21, 23, 0,
  9994. 25, 27, 0, 29, 31, 0, 33, 35,
  9995. 0, 135, 83, 135, 0, 0, 0, 0,
  9996. 0, 92, 0, 89, 89, 98, 43, 0,
  9997. 131, 95, 113, 107, 53, 0, 0, 0,
  9998. 125, 59, 69, 110, 45, 0, 55, 0,
  9999. 0, 0, 0, 0, 0, 119, 0, 0,
  10000. 0, 122, 0, 0, 0, 116, 0, 101,
  10001. 51, 47, 0, 0, 45, 49, 49, 104,
  10002. 0, 0, 128, 0, 57, 63, 65, 61,
  10003. 67
  10004. };
  10005. static const unsigned char _json_eof_actions[] = {
  10006. 0, 0, 0, 0, 0, 0, 0, 0,
  10007. 0, 0, 0, 0, 0, 0, 0, 0,
  10008. 0, 0, 0, 0, 0, 0, 0, 0,
  10009. 0, 1, 0, 1, 0, 0, 1, 1,
  10010. 0, 0, 0, 0, 0, 0, 0, 0,
  10011. 0, 0, 0, 0, 0, 0, 0, 0,
  10012. 0, 0, 0, 0, 0, 0, 0, 0,
  10013. 0, 0, 0, 0, 0, 0, 0, 0,
  10014. 0, 0, 0, 0, 0, 0, 0, 0,
  10015. 0, 0, 0, 0, 0, 0, 0, 0,
  10016. 0, 0, 0, 0, 0, 0, 0, 0,
  10017. 0, 0, 0, 0, 0, 0, 0, 0,
  10018. 0, 0, 0, 0, 0, 0, 0, 0,
  10019. 0, 0, 0, 57, 63, 65, 61, 67,
  10020. 0, 0, 0, 0, 0, 0
  10021. };
  10022. static const int json_start = 1;
  10023. static const int json_en_number_machine = 23;
  10024. static const int json_en_string_machine = 32;
  10025. static const int json_en_duration_machine = 40;
  10026. static const int json_en_timestamp_machine = 47;
  10027. static const int json_en_fieldmask_machine = 75;
  10028. static const int json_en_value_machine = 78;
  10029. static const int json_en_main = 1;
  10030. #line 2790 "upb/json/parser.rl"
  10031. size_t parse(void *closure, const void *hd, const char *buf, size_t size,
  10032. const upb_bufhandle *handle) {
  10033. upb_json_parser *parser = closure;
  10034. /* Variables used by Ragel's generated code. */
  10035. int cs = parser->current_state;
  10036. int *stack = parser->parser_stack;
  10037. int top = parser->parser_top;
  10038. const char *p = buf;
  10039. const char *pe = buf + size;
  10040. const char *eof = &eof_ch;
  10041. parser->handle = handle;
  10042. UPB_UNUSED(hd);
  10043. UPB_UNUSED(handle);
  10044. capture_resume(parser, buf);
  10045. #line 2868 "upb/json/parser.c"
  10046. {
  10047. int _klen;
  10048. unsigned int _trans;
  10049. const char *_acts;
  10050. unsigned int _nacts;
  10051. const char *_keys;
  10052. if ( p == pe )
  10053. goto _test_eof;
  10054. if ( cs == 0 )
  10055. goto _out;
  10056. _resume:
  10057. _keys = _json_trans_keys + _json_key_offsets[cs];
  10058. _trans = _json_index_offsets[cs];
  10059. _klen = _json_single_lengths[cs];
  10060. if ( _klen > 0 ) {
  10061. const char *_lower = _keys;
  10062. const char *_mid;
  10063. const char *_upper = _keys + _klen - 1;
  10064. while (1) {
  10065. if ( _upper < _lower )
  10066. break;
  10067. _mid = _lower + ((_upper-_lower) >> 1);
  10068. if ( (*p) < *_mid )
  10069. _upper = _mid - 1;
  10070. else if ( (*p) > *_mid )
  10071. _lower = _mid + 1;
  10072. else {
  10073. _trans += (unsigned int)(_mid - _keys);
  10074. goto _match;
  10075. }
  10076. }
  10077. _keys += _klen;
  10078. _trans += _klen;
  10079. }
  10080. _klen = _json_range_lengths[cs];
  10081. if ( _klen > 0 ) {
  10082. const char *_lower = _keys;
  10083. const char *_mid;
  10084. const char *_upper = _keys + (_klen<<1) - 2;
  10085. while (1) {
  10086. if ( _upper < _lower )
  10087. break;
  10088. _mid = _lower + (((_upper-_lower) >> 1) & ~1);
  10089. if ( (*p) < _mid[0] )
  10090. _upper = _mid - 2;
  10091. else if ( (*p) > _mid[1] )
  10092. _lower = _mid + 2;
  10093. else {
  10094. _trans += (unsigned int)((_mid - _keys)>>1);
  10095. goto _match;
  10096. }
  10097. }
  10098. _trans += _klen;
  10099. }
  10100. _match:
  10101. _trans = _json_indicies[_trans];
  10102. cs = _json_trans_targs[_trans];
  10103. if ( _json_trans_actions[_trans] == 0 )
  10104. goto _again;
  10105. _acts = _json_actions + _json_trans_actions[_trans];
  10106. _nacts = (unsigned int) *_acts++;
  10107. while ( _nacts-- > 0 )
  10108. {
  10109. switch ( *_acts++ )
  10110. {
  10111. case 1:
  10112. #line 2595 "upb/json/parser.rl"
  10113. { p--; {cs = stack[--top]; goto _again;} }
  10114. break;
  10115. case 2:
  10116. #line 2597 "upb/json/parser.rl"
  10117. { p--; {stack[top++] = cs; cs = 23;goto _again;} }
  10118. break;
  10119. case 3:
  10120. #line 2601 "upb/json/parser.rl"
  10121. { start_text(parser, p); }
  10122. break;
  10123. case 4:
  10124. #line 2602 "upb/json/parser.rl"
  10125. { CHECK_RETURN_TOP(end_text(parser, p)); }
  10126. break;
  10127. case 5:
  10128. #line 2608 "upb/json/parser.rl"
  10129. { start_hex(parser); }
  10130. break;
  10131. case 6:
  10132. #line 2609 "upb/json/parser.rl"
  10133. { hexdigit(parser, p); }
  10134. break;
  10135. case 7:
  10136. #line 2610 "upb/json/parser.rl"
  10137. { CHECK_RETURN_TOP(end_hex(parser)); }
  10138. break;
  10139. case 8:
  10140. #line 2616 "upb/json/parser.rl"
  10141. { CHECK_RETURN_TOP(escape(parser, p)); }
  10142. break;
  10143. case 9:
  10144. #line 2622 "upb/json/parser.rl"
  10145. { p--; {cs = stack[--top]; goto _again;} }
  10146. break;
  10147. case 10:
  10148. #line 2627 "upb/json/parser.rl"
  10149. { start_year(parser, p); }
  10150. break;
  10151. case 11:
  10152. #line 2628 "upb/json/parser.rl"
  10153. { CHECK_RETURN_TOP(end_year(parser, p)); }
  10154. break;
  10155. case 12:
  10156. #line 2632 "upb/json/parser.rl"
  10157. { start_month(parser, p); }
  10158. break;
  10159. case 13:
  10160. #line 2633 "upb/json/parser.rl"
  10161. { CHECK_RETURN_TOP(end_month(parser, p)); }
  10162. break;
  10163. case 14:
  10164. #line 2637 "upb/json/parser.rl"
  10165. { start_day(parser, p); }
  10166. break;
  10167. case 15:
  10168. #line 2638 "upb/json/parser.rl"
  10169. { CHECK_RETURN_TOP(end_day(parser, p)); }
  10170. break;
  10171. case 16:
  10172. #line 2642 "upb/json/parser.rl"
  10173. { start_hour(parser, p); }
  10174. break;
  10175. case 17:
  10176. #line 2643 "upb/json/parser.rl"
  10177. { CHECK_RETURN_TOP(end_hour(parser, p)); }
  10178. break;
  10179. case 18:
  10180. #line 2647 "upb/json/parser.rl"
  10181. { start_minute(parser, p); }
  10182. break;
  10183. case 19:
  10184. #line 2648 "upb/json/parser.rl"
  10185. { CHECK_RETURN_TOP(end_minute(parser, p)); }
  10186. break;
  10187. case 20:
  10188. #line 2652 "upb/json/parser.rl"
  10189. { start_second(parser, p); }
  10190. break;
  10191. case 21:
  10192. #line 2653 "upb/json/parser.rl"
  10193. { CHECK_RETURN_TOP(end_second(parser, p)); }
  10194. break;
  10195. case 22:
  10196. #line 2658 "upb/json/parser.rl"
  10197. { start_duration_base(parser, p); }
  10198. break;
  10199. case 23:
  10200. #line 2659 "upb/json/parser.rl"
  10201. { CHECK_RETURN_TOP(end_duration_base(parser, p)); }
  10202. break;
  10203. case 24:
  10204. #line 2661 "upb/json/parser.rl"
  10205. { p--; {cs = stack[--top]; goto _again;} }
  10206. break;
  10207. case 25:
  10208. #line 2666 "upb/json/parser.rl"
  10209. { start_timestamp_base(parser); }
  10210. break;
  10211. case 26:
  10212. #line 2668 "upb/json/parser.rl"
  10213. { start_timestamp_fraction(parser, p); }
  10214. break;
  10215. case 27:
  10216. #line 2669 "upb/json/parser.rl"
  10217. { CHECK_RETURN_TOP(end_timestamp_fraction(parser, p)); }
  10218. break;
  10219. case 28:
  10220. #line 2671 "upb/json/parser.rl"
  10221. { start_timestamp_zone(parser, p); }
  10222. break;
  10223. case 29:
  10224. #line 2672 "upb/json/parser.rl"
  10225. { CHECK_RETURN_TOP(end_timestamp_zone(parser, p)); }
  10226. break;
  10227. case 30:
  10228. #line 2674 "upb/json/parser.rl"
  10229. { p--; {cs = stack[--top]; goto _again;} }
  10230. break;
  10231. case 31:
  10232. #line 2679 "upb/json/parser.rl"
  10233. { start_fieldmask_path_text(parser, p); }
  10234. break;
  10235. case 32:
  10236. #line 2680 "upb/json/parser.rl"
  10237. { end_fieldmask_path_text(parser, p); }
  10238. break;
  10239. case 33:
  10240. #line 2685 "upb/json/parser.rl"
  10241. { start_fieldmask_path(parser); }
  10242. break;
  10243. case 34:
  10244. #line 2686 "upb/json/parser.rl"
  10245. { end_fieldmask_path(parser); }
  10246. break;
  10247. case 35:
  10248. #line 2692 "upb/json/parser.rl"
  10249. { p--; {cs = stack[--top]; goto _again;} }
  10250. break;
  10251. case 36:
  10252. #line 2697 "upb/json/parser.rl"
  10253. {
  10254. if (is_wellknown_msg(parser, UPB_WELLKNOWN_TIMESTAMP)) {
  10255. {stack[top++] = cs; cs = 47;goto _again;}
  10256. } else if (is_wellknown_msg(parser, UPB_WELLKNOWN_DURATION)) {
  10257. {stack[top++] = cs; cs = 40;goto _again;}
  10258. } else if (is_wellknown_msg(parser, UPB_WELLKNOWN_FIELDMASK)) {
  10259. {stack[top++] = cs; cs = 75;goto _again;}
  10260. } else {
  10261. {stack[top++] = cs; cs = 32;goto _again;}
  10262. }
  10263. }
  10264. break;
  10265. case 37:
  10266. #line 2710 "upb/json/parser.rl"
  10267. { p--; {stack[top++] = cs; cs = 78;goto _again;} }
  10268. break;
  10269. case 38:
  10270. #line 2715 "upb/json/parser.rl"
  10271. {
  10272. if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
  10273. start_any_member(parser, p);
  10274. } else {
  10275. start_member(parser);
  10276. }
  10277. }
  10278. break;
  10279. case 39:
  10280. #line 2722 "upb/json/parser.rl"
  10281. { CHECK_RETURN_TOP(end_membername(parser)); }
  10282. break;
  10283. case 40:
  10284. #line 2725 "upb/json/parser.rl"
  10285. {
  10286. if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
  10287. end_any_member(parser, p);
  10288. } else {
  10289. end_member(parser);
  10290. }
  10291. }
  10292. break;
  10293. case 41:
  10294. #line 2736 "upb/json/parser.rl"
  10295. {
  10296. if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
  10297. start_any_object(parser, p);
  10298. } else {
  10299. start_object(parser);
  10300. }
  10301. }
  10302. break;
  10303. case 42:
  10304. #line 2745 "upb/json/parser.rl"
  10305. {
  10306. if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
  10307. CHECK_RETURN_TOP(end_any_object(parser, p));
  10308. } else {
  10309. end_object(parser);
  10310. }
  10311. }
  10312. break;
  10313. case 43:
  10314. #line 2757 "upb/json/parser.rl"
  10315. { CHECK_RETURN_TOP(start_array(parser)); }
  10316. break;
  10317. case 44:
  10318. #line 2761 "upb/json/parser.rl"
  10319. { end_array(parser); }
  10320. break;
  10321. case 45:
  10322. #line 2766 "upb/json/parser.rl"
  10323. { CHECK_RETURN_TOP(start_number(parser, p)); }
  10324. break;
  10325. case 46:
  10326. #line 2767 "upb/json/parser.rl"
  10327. { CHECK_RETURN_TOP(end_number(parser, p)); }
  10328. break;
  10329. case 47:
  10330. #line 2769 "upb/json/parser.rl"
  10331. { CHECK_RETURN_TOP(start_stringval(parser)); }
  10332. break;
  10333. case 48:
  10334. #line 2770 "upb/json/parser.rl"
  10335. { CHECK_RETURN_TOP(end_stringval(parser)); }
  10336. break;
  10337. case 49:
  10338. #line 2772 "upb/json/parser.rl"
  10339. { CHECK_RETURN_TOP(end_bool(parser, true)); }
  10340. break;
  10341. case 50:
  10342. #line 2774 "upb/json/parser.rl"
  10343. { CHECK_RETURN_TOP(end_bool(parser, false)); }
  10344. break;
  10345. case 51:
  10346. #line 2776 "upb/json/parser.rl"
  10347. { CHECK_RETURN_TOP(end_null(parser)); }
  10348. break;
  10349. case 52:
  10350. #line 2778 "upb/json/parser.rl"
  10351. { CHECK_RETURN_TOP(start_subobject_full(parser)); }
  10352. break;
  10353. case 53:
  10354. #line 2779 "upb/json/parser.rl"
  10355. { end_subobject_full(parser); }
  10356. break;
  10357. case 54:
  10358. #line 2784 "upb/json/parser.rl"
  10359. { p--; {cs = stack[--top]; goto _again;} }
  10360. break;
  10361. #line 3192 "upb/json/parser.c"
  10362. }
  10363. }
  10364. _again:
  10365. if ( cs == 0 )
  10366. goto _out;
  10367. if ( ++p != pe )
  10368. goto _resume;
  10369. _test_eof: {}
  10370. if ( p == eof )
  10371. {
  10372. const char *__acts = _json_actions + _json_eof_actions[cs];
  10373. unsigned int __nacts = (unsigned int) *__acts++;
  10374. while ( __nacts-- > 0 ) {
  10375. switch ( *__acts++ ) {
  10376. case 0:
  10377. #line 2593 "upb/json/parser.rl"
  10378. { p--; {cs = stack[--top]; if ( p == pe )
  10379. goto _test_eof;
  10380. goto _again;} }
  10381. break;
  10382. case 46:
  10383. #line 2767 "upb/json/parser.rl"
  10384. { CHECK_RETURN_TOP(end_number(parser, p)); }
  10385. break;
  10386. case 49:
  10387. #line 2772 "upb/json/parser.rl"
  10388. { CHECK_RETURN_TOP(end_bool(parser, true)); }
  10389. break;
  10390. case 50:
  10391. #line 2774 "upb/json/parser.rl"
  10392. { CHECK_RETURN_TOP(end_bool(parser, false)); }
  10393. break;
  10394. case 51:
  10395. #line 2776 "upb/json/parser.rl"
  10396. { CHECK_RETURN_TOP(end_null(parser)); }
  10397. break;
  10398. case 53:
  10399. #line 2779 "upb/json/parser.rl"
  10400. { end_subobject_full(parser); }
  10401. break;
  10402. #line 3234 "upb/json/parser.c"
  10403. }
  10404. }
  10405. }
  10406. _out: {}
  10407. }
  10408. #line 2812 "upb/json/parser.rl"
  10409. if (p != pe) {
  10410. upb_status_seterrf(parser->status, "Parse error at '%.*s'\n", pe - p, p);
  10411. } else {
  10412. capture_suspend(parser, &p);
  10413. }
  10414. error:
  10415. /* Save parsing state back to parser. */
  10416. parser->current_state = cs;
  10417. parser->parser_top = top;
  10418. return p - buf;
  10419. }
  10420. static bool end(void *closure, const void *hd) {
  10421. upb_json_parser *parser = closure;
  10422. /* Prevent compile warning on unused static constants. */
  10423. UPB_UNUSED(json_start);
  10424. UPB_UNUSED(json_en_duration_machine);
  10425. UPB_UNUSED(json_en_fieldmask_machine);
  10426. UPB_UNUSED(json_en_number_machine);
  10427. UPB_UNUSED(json_en_string_machine);
  10428. UPB_UNUSED(json_en_timestamp_machine);
  10429. UPB_UNUSED(json_en_value_machine);
  10430. UPB_UNUSED(json_en_main);
  10431. parse(parser, hd, &eof_ch, 0, NULL);
  10432. return parser->current_state >= 106;
  10433. }
  10434. static void json_parser_reset(upb_json_parser *p) {
  10435. int cs;
  10436. int top;
  10437. p->top = p->stack;
  10438. init_frame(p->top);
  10439. /* Emit Ragel initialization of the parser. */
  10440. #line 3285 "upb/json/parser.c"
  10441. {
  10442. cs = json_start;
  10443. top = 0;
  10444. }
  10445. #line 2854 "upb/json/parser.rl"
  10446. p->current_state = cs;
  10447. p->parser_top = top;
  10448. accumulate_clear(p);
  10449. p->multipart_state = MULTIPART_INACTIVE;
  10450. p->capture = NULL;
  10451. p->accumulated = NULL;
  10452. }
  10453. static upb_json_parsermethod *parsermethod_new(upb_json_codecache *c,
  10454. const upb_msgdef *md) {
  10455. upb_msg_field_iter i;
  10456. upb_alloc *alloc = upb_arena_alloc(c->arena);
  10457. upb_json_parsermethod *m = upb_malloc(alloc, sizeof(*m));
  10458. m->cache = c;
  10459. upb_byteshandler_init(&m->input_handler_);
  10460. upb_byteshandler_setstring(&m->input_handler_, parse, m);
  10461. upb_byteshandler_setendstr(&m->input_handler_, end, m);
  10462. upb_strtable_init2(&m->name_table, UPB_CTYPE_CONSTPTR, alloc);
  10463. /* Build name_table */
  10464. for(upb_msg_field_begin(&i, md);
  10465. !upb_msg_field_done(&i);
  10466. upb_msg_field_next(&i)) {
  10467. const upb_fielddef *f = upb_msg_iter_field(&i);
  10468. upb_value v = upb_value_constptr(f);
  10469. const char *name;
  10470. /* Add an entry for the JSON name. */
  10471. name = upb_fielddef_jsonname(f);
  10472. upb_strtable_insert3(&m->name_table, name, strlen(name), v, alloc);
  10473. if (strcmp(name, upb_fielddef_name(f)) != 0) {
  10474. /* Since the JSON name is different from the regular field name, add an
  10475. * entry for the raw name (compliant proto3 JSON parsers must accept
  10476. * both). */
  10477. const char *name = upb_fielddef_name(f);
  10478. upb_strtable_insert3(&m->name_table, name, strlen(name), v, alloc);
  10479. }
  10480. }
  10481. return m;
  10482. }
  10483. /* Public API *****************************************************************/
  10484. upb_json_parser *upb_json_parser_create(upb_arena *arena,
  10485. const upb_json_parsermethod *method,
  10486. const upb_symtab* symtab,
  10487. upb_sink output,
  10488. upb_status *status,
  10489. bool ignore_json_unknown) {
  10490. upb_json_parser *p = upb_arena_malloc(arena, sizeof(upb_json_parser));
  10491. if (!p) return false;
  10492. p->arena = arena;
  10493. p->method = method;
  10494. p->status = status;
  10495. p->limit = p->stack + UPB_JSON_MAX_DEPTH;
  10496. p->accumulate_buf = NULL;
  10497. p->accumulate_buf_size = 0;
  10498. upb_bytessink_reset(&p->input_, &method->input_handler_, p);
  10499. json_parser_reset(p);
  10500. p->top->sink = output;
  10501. p->top->m = upb_handlers_msgdef(output.handlers);
  10502. if (is_wellknown_msg(p, UPB_WELLKNOWN_ANY)) {
  10503. p->top->is_any = true;
  10504. p->top->any_frame = json_parser_any_frame_new(p);
  10505. } else {
  10506. p->top->is_any = false;
  10507. p->top->any_frame = NULL;
  10508. }
  10509. set_name_table(p, p->top);
  10510. p->symtab = symtab;
  10511. p->ignore_json_unknown = ignore_json_unknown;
  10512. return p;
  10513. }
  10514. upb_bytessink upb_json_parser_input(upb_json_parser *p) {
  10515. return p->input_;
  10516. }
  10517. const upb_byteshandler *upb_json_parsermethod_inputhandler(
  10518. const upb_json_parsermethod *m) {
  10519. return &m->input_handler_;
  10520. }
  10521. upb_json_codecache *upb_json_codecache_new(void) {
  10522. upb_alloc *alloc;
  10523. upb_json_codecache *c;
  10524. c = upb_gmalloc(sizeof(*c));
  10525. c->arena = upb_arena_new();
  10526. alloc = upb_arena_alloc(c->arena);
  10527. upb_inttable_init2(&c->methods, UPB_CTYPE_CONSTPTR, alloc);
  10528. return c;
  10529. }
  10530. void upb_json_codecache_free(upb_json_codecache *c) {
  10531. upb_arena_free(c->arena);
  10532. upb_gfree(c);
  10533. }
  10534. const upb_json_parsermethod *upb_json_codecache_get(upb_json_codecache *c,
  10535. const upb_msgdef *md) {
  10536. upb_json_parsermethod *m;
  10537. upb_value v;
  10538. upb_msg_field_iter i;
  10539. upb_alloc *alloc = upb_arena_alloc(c->arena);
  10540. if (upb_inttable_lookupptr(&c->methods, md, &v)) {
  10541. return upb_value_getconstptr(v);
  10542. }
  10543. m = parsermethod_new(c, md);
  10544. v = upb_value_constptr(m);
  10545. if (!m) return NULL;
  10546. if (!upb_inttable_insertptr2(&c->methods, md, v, alloc)) return NULL;
  10547. /* Populate parser methods for all submessages, so the name tables will
  10548. * be available during parsing. */
  10549. for(upb_msg_field_begin(&i, md);
  10550. !upb_msg_field_done(&i);
  10551. upb_msg_field_next(&i)) {
  10552. upb_fielddef *f = upb_msg_iter_field(&i);
  10553. if (upb_fielddef_issubmsg(f)) {
  10554. const upb_msgdef *subdef = upb_fielddef_msgsubdef(f);
  10555. const upb_json_parsermethod *sub_method =
  10556. upb_json_codecache_get(c, subdef);
  10557. if (!sub_method) return NULL;
  10558. }
  10559. }
  10560. return m;
  10561. }
  10562. /*
  10563. ** This currently uses snprintf() to format primitives, and could be optimized
  10564. ** further.
  10565. */
  10566. #include <ctype.h>
  10567. #include <inttypes.h>
  10568. #include <stdint.h>
  10569. #include <string.h>
  10570. #include <time.h>
  10571. struct upb_json_printer {
  10572. upb_sink input_;
  10573. /* BytesSink closure. */
  10574. void *subc_;
  10575. upb_bytessink output_;
  10576. /* We track the depth so that we know when to emit startstr/endstr on the
  10577. * output. */
  10578. int depth_;
  10579. /* Have we emitted the first element? This state is necessary to emit commas
  10580. * without leaving a trailing comma in arrays/maps. We keep this state per
  10581. * frame depth.
  10582. *
  10583. * Why max_depth * 2? UPB_MAX_HANDLER_DEPTH counts depth as nested messages.
  10584. * We count frames (contexts in which we separate elements by commas) as both
  10585. * repeated fields and messages (maps), and the worst case is a
  10586. * message->repeated field->submessage->repeated field->... nesting. */
  10587. bool first_elem_[UPB_MAX_HANDLER_DEPTH * 2];
  10588. /* To print timestamp, printer needs to cache its seconds and nanos values
  10589. * and convert them when ending timestamp message. See comments of
  10590. * printer_sethandlers_timestamp for more detail. */
  10591. int64_t seconds;
  10592. int32_t nanos;
  10593. };
  10594. /* StringPiece; a pointer plus a length. */
  10595. typedef struct {
  10596. char *ptr;
  10597. size_t len;
  10598. } strpc;
  10599. void freestrpc(void *ptr) {
  10600. strpc *pc = ptr;
  10601. upb_gfree(pc->ptr);
  10602. upb_gfree(pc);
  10603. }
  10604. typedef struct {
  10605. bool preserve_fieldnames;
  10606. } upb_json_printercache;
  10607. /* Convert fielddef name to JSON name and return as a string piece. */
  10608. strpc *newstrpc(upb_handlers *h, const upb_fielddef *f,
  10609. bool preserve_fieldnames) {
  10610. /* TODO(haberman): handle malloc failure. */
  10611. strpc *ret = upb_gmalloc(sizeof(*ret));
  10612. if (preserve_fieldnames) {
  10613. ret->ptr = upb_gstrdup(upb_fielddef_name(f));
  10614. ret->len = strlen(ret->ptr);
  10615. } else {
  10616. ret->ptr = upb_gstrdup(upb_fielddef_jsonname(f));
  10617. ret->len = strlen(ret->ptr);
  10618. }
  10619. upb_handlers_addcleanup(h, ret, freestrpc);
  10620. return ret;
  10621. }
  10622. /* Convert a null-terminated const char* to a string piece. */
  10623. strpc *newstrpc_str(upb_handlers *h, const char * str) {
  10624. strpc * ret = upb_gmalloc(sizeof(*ret));
  10625. ret->ptr = upb_gstrdup(str);
  10626. ret->len = strlen(str);
  10627. upb_handlers_addcleanup(h, ret, freestrpc);
  10628. return ret;
  10629. }
  10630. /* ------------ JSON string printing: values, maps, arrays ------------------ */
  10631. static void print_data(
  10632. upb_json_printer *p, const char *buf, size_t len) {
  10633. /* TODO: Will need to change if we support pushback from the sink. */
  10634. size_t n = upb_bytessink_putbuf(p->output_, p->subc_, buf, len, NULL);
  10635. UPB_ASSERT(n == len);
  10636. }
  10637. static void print_comma(upb_json_printer *p) {
  10638. if (!p->first_elem_[p->depth_]) {
  10639. print_data(p, ",", 1);
  10640. }
  10641. p->first_elem_[p->depth_] = false;
  10642. }
  10643. /* Helpers that print properly formatted elements to the JSON output stream. */
  10644. /* Used for escaping control chars in strings. */
  10645. static const char kControlCharLimit = 0x20;
  10646. UPB_INLINE bool is_json_escaped(char c) {
  10647. /* See RFC 4627. */
  10648. unsigned char uc = (unsigned char)c;
  10649. return uc < kControlCharLimit || uc == '"' || uc == '\\';
  10650. }
  10651. UPB_INLINE const char* json_nice_escape(char c) {
  10652. switch (c) {
  10653. case '"': return "\\\"";
  10654. case '\\': return "\\\\";
  10655. case '\b': return "\\b";
  10656. case '\f': return "\\f";
  10657. case '\n': return "\\n";
  10658. case '\r': return "\\r";
  10659. case '\t': return "\\t";
  10660. default: return NULL;
  10661. }
  10662. }
  10663. /* Write a properly escaped string chunk. The surrounding quotes are *not*
  10664. * printed; this is so that the caller has the option of emitting the string
  10665. * content in chunks. */
  10666. static void putstring(upb_json_printer *p, const char *buf, size_t len) {
  10667. const char* unescaped_run = NULL;
  10668. unsigned int i;
  10669. for (i = 0; i < len; i++) {
  10670. char c = buf[i];
  10671. /* Handle escaping. */
  10672. if (is_json_escaped(c)) {
  10673. /* Use a "nice" escape, like \n, if one exists for this character. */
  10674. const char* escape = json_nice_escape(c);
  10675. /* If we don't have a specific 'nice' escape code, use a \uXXXX-style
  10676. * escape. */
  10677. char escape_buf[8];
  10678. if (!escape) {
  10679. unsigned char byte = (unsigned char)c;
  10680. _upb_snprintf(escape_buf, sizeof(escape_buf), "\\u%04x", (int)byte);
  10681. escape = escape_buf;
  10682. }
  10683. /* N.B. that we assume that the input encoding is equal to the output
  10684. * encoding (both UTF-8 for now), so for chars >= 0x20 and != \, ", we
  10685. * can simply pass the bytes through. */
  10686. /* If there's a current run of unescaped chars, print that run first. */
  10687. if (unescaped_run) {
  10688. print_data(p, unescaped_run, &buf[i] - unescaped_run);
  10689. unescaped_run = NULL;
  10690. }
  10691. /* Then print the escape code. */
  10692. print_data(p, escape, strlen(escape));
  10693. } else {
  10694. /* Add to the current unescaped run of characters. */
  10695. if (unescaped_run == NULL) {
  10696. unescaped_run = &buf[i];
  10697. }
  10698. }
  10699. }
  10700. /* If the string ended in a run of unescaped characters, print that last run. */
  10701. if (unescaped_run) {
  10702. print_data(p, unescaped_run, &buf[len] - unescaped_run);
  10703. }
  10704. }
  10705. #define CHKLENGTH(x) if (!(x)) return -1;
  10706. /* Helpers that format floating point values according to our custom formats.
  10707. * Right now we use %.8g and %.17g for float/double, respectively, to match
  10708. * proto2::util::JsonFormat's defaults. May want to change this later. */
  10709. const char neginf[] = "\"-Infinity\"";
  10710. const char inf[] = "\"Infinity\"";
  10711. static size_t fmt_double(double val, char* buf, size_t length) {
  10712. if (val == UPB_INFINITY) {
  10713. CHKLENGTH(length >= strlen(inf));
  10714. strcpy(buf, inf);
  10715. return strlen(inf);
  10716. } else if (val == -UPB_INFINITY) {
  10717. CHKLENGTH(length >= strlen(neginf));
  10718. strcpy(buf, neginf);
  10719. return strlen(neginf);
  10720. } else {
  10721. size_t n = _upb_snprintf(buf, length, "%.17g", val);
  10722. CHKLENGTH(n > 0 && n < length);
  10723. return n;
  10724. }
  10725. }
  10726. static size_t fmt_float(float val, char* buf, size_t length) {
  10727. size_t n = _upb_snprintf(buf, length, "%.8g", val);
  10728. CHKLENGTH(n > 0 && n < length);
  10729. return n;
  10730. }
  10731. static size_t fmt_bool(bool val, char* buf, size_t length) {
  10732. size_t n = _upb_snprintf(buf, length, "%s", (val ? "true" : "false"));
  10733. CHKLENGTH(n > 0 && n < length);
  10734. return n;
  10735. }
  10736. static size_t fmt_int64_as_number(int64_t val, char* buf, size_t length) {
  10737. size_t n = _upb_snprintf(buf, length, "%" PRId64, val);
  10738. CHKLENGTH(n > 0 && n < length);
  10739. return n;
  10740. }
  10741. static size_t fmt_uint64_as_number(uint64_t val, char* buf, size_t length) {
  10742. size_t n = _upb_snprintf(buf, length, "%" PRIu64, val);
  10743. CHKLENGTH(n > 0 && n < length);
  10744. return n;
  10745. }
  10746. static size_t fmt_int64_as_string(int64_t val, char* buf, size_t length) {
  10747. size_t n = _upb_snprintf(buf, length, "\"%" PRId64 "\"", val);
  10748. CHKLENGTH(n > 0 && n < length);
  10749. return n;
  10750. }
  10751. static size_t fmt_uint64_as_string(uint64_t val, char* buf, size_t length) {
  10752. size_t n = _upb_snprintf(buf, length, "\"%" PRIu64 "\"", val);
  10753. CHKLENGTH(n > 0 && n < length);
  10754. return n;
  10755. }
  10756. /* Print a map key given a field name. Called by scalar field handlers and by
  10757. * startseq for repeated fields. */
  10758. static bool putkey(void *closure, const void *handler_data) {
  10759. upb_json_printer *p = closure;
  10760. const strpc *key = handler_data;
  10761. print_comma(p);
  10762. print_data(p, "\"", 1);
  10763. putstring(p, key->ptr, key->len);
  10764. print_data(p, "\":", 2);
  10765. return true;
  10766. }
  10767. #define CHKFMT(val) if ((val) == (size_t)-1) return false;
  10768. #define CHK(val) if (!(val)) return false;
  10769. #define TYPE_HANDLERS(type, fmt_func) \
  10770. static bool put##type(void *closure, const void *handler_data, type val) { \
  10771. upb_json_printer *p = closure; \
  10772. char data[64]; \
  10773. size_t length = fmt_func(val, data, sizeof(data)); \
  10774. UPB_UNUSED(handler_data); \
  10775. CHKFMT(length); \
  10776. print_data(p, data, length); \
  10777. return true; \
  10778. } \
  10779. static bool scalar_##type(void *closure, const void *handler_data, \
  10780. type val) { \
  10781. CHK(putkey(closure, handler_data)); \
  10782. CHK(put##type(closure, handler_data, val)); \
  10783. return true; \
  10784. } \
  10785. static bool repeated_##type(void *closure, const void *handler_data, \
  10786. type val) { \
  10787. upb_json_printer *p = closure; \
  10788. print_comma(p); \
  10789. CHK(put##type(closure, handler_data, val)); \
  10790. return true; \
  10791. }
  10792. #define TYPE_HANDLERS_MAPKEY(type, fmt_func) \
  10793. static bool putmapkey_##type(void *closure, const void *handler_data, \
  10794. type val) { \
  10795. upb_json_printer *p = closure; \
  10796. char data[64]; \
  10797. size_t length = fmt_func(val, data, sizeof(data)); \
  10798. UPB_UNUSED(handler_data); \
  10799. print_data(p, "\"", 1); \
  10800. print_data(p, data, length); \
  10801. print_data(p, "\":", 2); \
  10802. return true; \
  10803. }
  10804. TYPE_HANDLERS(double, fmt_double)
  10805. TYPE_HANDLERS(float, fmt_float)
  10806. TYPE_HANDLERS(bool, fmt_bool)
  10807. TYPE_HANDLERS(int32_t, fmt_int64_as_number)
  10808. TYPE_HANDLERS(uint32_t, fmt_int64_as_number)
  10809. TYPE_HANDLERS(int64_t, fmt_int64_as_string)
  10810. TYPE_HANDLERS(uint64_t, fmt_uint64_as_string)
  10811. /* double and float are not allowed to be map keys. */
  10812. TYPE_HANDLERS_MAPKEY(bool, fmt_bool)
  10813. TYPE_HANDLERS_MAPKEY(int32_t, fmt_int64_as_number)
  10814. TYPE_HANDLERS_MAPKEY(uint32_t, fmt_int64_as_number)
  10815. TYPE_HANDLERS_MAPKEY(int64_t, fmt_int64_as_number)
  10816. TYPE_HANDLERS_MAPKEY(uint64_t, fmt_uint64_as_number)
  10817. #undef TYPE_HANDLERS
  10818. #undef TYPE_HANDLERS_MAPKEY
  10819. typedef struct {
  10820. void *keyname;
  10821. const upb_enumdef *enumdef;
  10822. } EnumHandlerData;
  10823. static bool scalar_enum(void *closure, const void *handler_data,
  10824. int32_t val) {
  10825. const EnumHandlerData *hd = handler_data;
  10826. upb_json_printer *p = closure;
  10827. const char *symbolic_name;
  10828. CHK(putkey(closure, hd->keyname));
  10829. symbolic_name = upb_enumdef_iton(hd->enumdef, val);
  10830. if (symbolic_name) {
  10831. print_data(p, "\"", 1);
  10832. putstring(p, symbolic_name, strlen(symbolic_name));
  10833. print_data(p, "\"", 1);
  10834. } else {
  10835. putint32_t(closure, NULL, val);
  10836. }
  10837. return true;
  10838. }
  10839. static void print_enum_symbolic_name(upb_json_printer *p,
  10840. const upb_enumdef *def,
  10841. int32_t val) {
  10842. const char *symbolic_name = upb_enumdef_iton(def, val);
  10843. if (symbolic_name) {
  10844. print_data(p, "\"", 1);
  10845. putstring(p, symbolic_name, strlen(symbolic_name));
  10846. print_data(p, "\"", 1);
  10847. } else {
  10848. putint32_t(p, NULL, val);
  10849. }
  10850. }
  10851. static bool repeated_enum(void *closure, const void *handler_data,
  10852. int32_t val) {
  10853. const EnumHandlerData *hd = handler_data;
  10854. upb_json_printer *p = closure;
  10855. print_comma(p);
  10856. print_enum_symbolic_name(p, hd->enumdef, val);
  10857. return true;
  10858. }
  10859. static bool mapvalue_enum(void *closure, const void *handler_data,
  10860. int32_t val) {
  10861. const EnumHandlerData *hd = handler_data;
  10862. upb_json_printer *p = closure;
  10863. print_enum_symbolic_name(p, hd->enumdef, val);
  10864. return true;
  10865. }
  10866. static void *scalar_startsubmsg(void *closure, const void *handler_data) {
  10867. return putkey(closure, handler_data) ? closure : UPB_BREAK;
  10868. }
  10869. static void *repeated_startsubmsg(void *closure, const void *handler_data) {
  10870. upb_json_printer *p = closure;
  10871. UPB_UNUSED(handler_data);
  10872. print_comma(p);
  10873. return closure;
  10874. }
  10875. static void start_frame(upb_json_printer *p) {
  10876. p->depth_++;
  10877. p->first_elem_[p->depth_] = true;
  10878. print_data(p, "{", 1);
  10879. }
  10880. static void end_frame(upb_json_printer *p) {
  10881. print_data(p, "}", 1);
  10882. p->depth_--;
  10883. }
  10884. static bool printer_startmsg(void *closure, const void *handler_data) {
  10885. upb_json_printer *p = closure;
  10886. UPB_UNUSED(handler_data);
  10887. if (p->depth_ == 0) {
  10888. upb_bytessink_start(p->output_, 0, &p->subc_);
  10889. }
  10890. start_frame(p);
  10891. return true;
  10892. }
  10893. static bool printer_endmsg(void *closure, const void *handler_data, upb_status *s) {
  10894. upb_json_printer *p = closure;
  10895. UPB_UNUSED(handler_data);
  10896. UPB_UNUSED(s);
  10897. end_frame(p);
  10898. if (p->depth_ == 0) {
  10899. upb_bytessink_end(p->output_);
  10900. }
  10901. return true;
  10902. }
  10903. static void *startseq(void *closure, const void *handler_data) {
  10904. upb_json_printer *p = closure;
  10905. CHK(putkey(closure, handler_data));
  10906. p->depth_++;
  10907. p->first_elem_[p->depth_] = true;
  10908. print_data(p, "[", 1);
  10909. return closure;
  10910. }
  10911. static bool endseq(void *closure, const void *handler_data) {
  10912. upb_json_printer *p = closure;
  10913. UPB_UNUSED(handler_data);
  10914. print_data(p, "]", 1);
  10915. p->depth_--;
  10916. return true;
  10917. }
  10918. static void *startmap(void *closure, const void *handler_data) {
  10919. upb_json_printer *p = closure;
  10920. CHK(putkey(closure, handler_data));
  10921. p->depth_++;
  10922. p->first_elem_[p->depth_] = true;
  10923. print_data(p, "{", 1);
  10924. return closure;
  10925. }
  10926. static bool endmap(void *closure, const void *handler_data) {
  10927. upb_json_printer *p = closure;
  10928. UPB_UNUSED(handler_data);
  10929. print_data(p, "}", 1);
  10930. p->depth_--;
  10931. return true;
  10932. }
  10933. static size_t putstr(void *closure, const void *handler_data, const char *str,
  10934. size_t len, const upb_bufhandle *handle) {
  10935. upb_json_printer *p = closure;
  10936. UPB_UNUSED(handler_data);
  10937. UPB_UNUSED(handle);
  10938. putstring(p, str, len);
  10939. return len;
  10940. }
  10941. /* This has to Base64 encode the bytes, because JSON has no "bytes" type. */
  10942. static size_t putbytes(void *closure, const void *handler_data, const char *str,
  10943. size_t len, const upb_bufhandle *handle) {
  10944. upb_json_printer *p = closure;
  10945. /* This is the regular base64, not the "web-safe" version. */
  10946. static const char base64[] =
  10947. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  10948. /* Base64-encode. */
  10949. char data[16000];
  10950. const char *limit = data + sizeof(data);
  10951. const unsigned char *from = (const unsigned char*)str;
  10952. char *to = data;
  10953. size_t remaining = len;
  10954. size_t bytes;
  10955. UPB_UNUSED(handler_data);
  10956. UPB_UNUSED(handle);
  10957. print_data(p, "\"", 1);
  10958. while (remaining > 2) {
  10959. if (limit - to < 4) {
  10960. bytes = to - data;
  10961. putstring(p, data, bytes);
  10962. to = data;
  10963. }
  10964. to[0] = base64[from[0] >> 2];
  10965. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  10966. to[2] = base64[((from[1] & 0xf) << 2) | (from[2] >> 6)];
  10967. to[3] = base64[from[2] & 0x3f];
  10968. remaining -= 3;
  10969. to += 4;
  10970. from += 3;
  10971. }
  10972. switch (remaining) {
  10973. case 2:
  10974. to[0] = base64[from[0] >> 2];
  10975. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  10976. to[2] = base64[(from[1] & 0xf) << 2];
  10977. to[3] = '=';
  10978. to += 4;
  10979. from += 2;
  10980. break;
  10981. case 1:
  10982. to[0] = base64[from[0] >> 2];
  10983. to[1] = base64[((from[0] & 0x3) << 4)];
  10984. to[2] = '=';
  10985. to[3] = '=';
  10986. to += 4;
  10987. from += 1;
  10988. break;
  10989. }
  10990. bytes = to - data;
  10991. putstring(p, data, bytes);
  10992. print_data(p, "\"", 1);
  10993. return len;
  10994. }
  10995. static void *scalar_startstr(void *closure, const void *handler_data,
  10996. size_t size_hint) {
  10997. upb_json_printer *p = closure;
  10998. UPB_UNUSED(handler_data);
  10999. UPB_UNUSED(size_hint);
  11000. CHK(putkey(closure, handler_data));
  11001. print_data(p, "\"", 1);
  11002. return p;
  11003. }
  11004. static size_t scalar_str(void *closure, const void *handler_data,
  11005. const char *str, size_t len,
  11006. const upb_bufhandle *handle) {
  11007. CHK(putstr(closure, handler_data, str, len, handle));
  11008. return len;
  11009. }
  11010. static bool scalar_endstr(void *closure, const void *handler_data) {
  11011. upb_json_printer *p = closure;
  11012. UPB_UNUSED(handler_data);
  11013. print_data(p, "\"", 1);
  11014. return true;
  11015. }
  11016. static void *repeated_startstr(void *closure, const void *handler_data,
  11017. size_t size_hint) {
  11018. upb_json_printer *p = closure;
  11019. UPB_UNUSED(handler_data);
  11020. UPB_UNUSED(size_hint);
  11021. print_comma(p);
  11022. print_data(p, "\"", 1);
  11023. return p;
  11024. }
  11025. static size_t repeated_str(void *closure, const void *handler_data,
  11026. const char *str, size_t len,
  11027. const upb_bufhandle *handle) {
  11028. CHK(putstr(closure, handler_data, str, len, handle));
  11029. return len;
  11030. }
  11031. static bool repeated_endstr(void *closure, const void *handler_data) {
  11032. upb_json_printer *p = closure;
  11033. UPB_UNUSED(handler_data);
  11034. print_data(p, "\"", 1);
  11035. return true;
  11036. }
  11037. static void *mapkeyval_startstr(void *closure, const void *handler_data,
  11038. size_t size_hint) {
  11039. upb_json_printer *p = closure;
  11040. UPB_UNUSED(handler_data);
  11041. UPB_UNUSED(size_hint);
  11042. print_data(p, "\"", 1);
  11043. return p;
  11044. }
  11045. static size_t mapkey_str(void *closure, const void *handler_data,
  11046. const char *str, size_t len,
  11047. const upb_bufhandle *handle) {
  11048. CHK(putstr(closure, handler_data, str, len, handle));
  11049. return len;
  11050. }
  11051. static bool mapkey_endstr(void *closure, const void *handler_data) {
  11052. upb_json_printer *p = closure;
  11053. UPB_UNUSED(handler_data);
  11054. print_data(p, "\":", 2);
  11055. return true;
  11056. }
  11057. static bool mapvalue_endstr(void *closure, const void *handler_data) {
  11058. upb_json_printer *p = closure;
  11059. UPB_UNUSED(handler_data);
  11060. print_data(p, "\"", 1);
  11061. return true;
  11062. }
  11063. static size_t scalar_bytes(void *closure, const void *handler_data,
  11064. const char *str, size_t len,
  11065. const upb_bufhandle *handle) {
  11066. CHK(putkey(closure, handler_data));
  11067. CHK(putbytes(closure, handler_data, str, len, handle));
  11068. return len;
  11069. }
  11070. static size_t repeated_bytes(void *closure, const void *handler_data,
  11071. const char *str, size_t len,
  11072. const upb_bufhandle *handle) {
  11073. upb_json_printer *p = closure;
  11074. print_comma(p);
  11075. CHK(putbytes(closure, handler_data, str, len, handle));
  11076. return len;
  11077. }
  11078. static size_t mapkey_bytes(void *closure, const void *handler_data,
  11079. const char *str, size_t len,
  11080. const upb_bufhandle *handle) {
  11081. upb_json_printer *p = closure;
  11082. CHK(putbytes(closure, handler_data, str, len, handle));
  11083. print_data(p, ":", 1);
  11084. return len;
  11085. }
  11086. static void set_enum_hd(upb_handlers *h,
  11087. const upb_fielddef *f,
  11088. bool preserve_fieldnames,
  11089. upb_handlerattr *attr) {
  11090. EnumHandlerData *hd = upb_gmalloc(sizeof(EnumHandlerData));
  11091. hd->enumdef = upb_fielddef_enumsubdef(f);
  11092. hd->keyname = newstrpc(h, f, preserve_fieldnames);
  11093. upb_handlers_addcleanup(h, hd, upb_gfree);
  11094. attr->handler_data = hd;
  11095. }
  11096. /* Set up handlers for a mapentry submessage (i.e., an individual key/value pair
  11097. * in a map).
  11098. *
  11099. * TODO: Handle missing key, missing value, out-of-order key/value, or repeated
  11100. * key or value cases properly. The right way to do this is to allocate a
  11101. * temporary structure at the start of a mapentry submessage, store key and
  11102. * value data in it as key and value handlers are called, and then print the
  11103. * key/value pair once at the end of the submessage. If we don't do this, we
  11104. * should at least detect the case and throw an error. However, so far all of
  11105. * our sources that emit mapentry messages do so canonically (with one key
  11106. * field, and then one value field), so this is not a pressing concern at the
  11107. * moment. */
  11108. void printer_sethandlers_mapentry(const void *closure, bool preserve_fieldnames,
  11109. upb_handlers *h) {
  11110. const upb_msgdef *md = upb_handlers_msgdef(h);
  11111. /* A mapentry message is printed simply as '"key": value'. Rather than
  11112. * special-case key and value for every type below, we just handle both
  11113. * fields explicitly here. */
  11114. const upb_fielddef* key_field = upb_msgdef_itof(md, UPB_MAPENTRY_KEY);
  11115. const upb_fielddef* value_field = upb_msgdef_itof(md, UPB_MAPENTRY_VALUE);
  11116. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11117. UPB_UNUSED(closure);
  11118. switch (upb_fielddef_type(key_field)) {
  11119. case UPB_TYPE_INT32:
  11120. upb_handlers_setint32(h, key_field, putmapkey_int32_t, &empty_attr);
  11121. break;
  11122. case UPB_TYPE_INT64:
  11123. upb_handlers_setint64(h, key_field, putmapkey_int64_t, &empty_attr);
  11124. break;
  11125. case UPB_TYPE_UINT32:
  11126. upb_handlers_setuint32(h, key_field, putmapkey_uint32_t, &empty_attr);
  11127. break;
  11128. case UPB_TYPE_UINT64:
  11129. upb_handlers_setuint64(h, key_field, putmapkey_uint64_t, &empty_attr);
  11130. break;
  11131. case UPB_TYPE_BOOL:
  11132. upb_handlers_setbool(h, key_field, putmapkey_bool, &empty_attr);
  11133. break;
  11134. case UPB_TYPE_STRING:
  11135. upb_handlers_setstartstr(h, key_field, mapkeyval_startstr, &empty_attr);
  11136. upb_handlers_setstring(h, key_field, mapkey_str, &empty_attr);
  11137. upb_handlers_setendstr(h, key_field, mapkey_endstr, &empty_attr);
  11138. break;
  11139. case UPB_TYPE_BYTES:
  11140. upb_handlers_setstring(h, key_field, mapkey_bytes, &empty_attr);
  11141. break;
  11142. default:
  11143. UPB_ASSERT(false);
  11144. break;
  11145. }
  11146. switch (upb_fielddef_type(value_field)) {
  11147. case UPB_TYPE_INT32:
  11148. upb_handlers_setint32(h, value_field, putint32_t, &empty_attr);
  11149. break;
  11150. case UPB_TYPE_INT64:
  11151. upb_handlers_setint64(h, value_field, putint64_t, &empty_attr);
  11152. break;
  11153. case UPB_TYPE_UINT32:
  11154. upb_handlers_setuint32(h, value_field, putuint32_t, &empty_attr);
  11155. break;
  11156. case UPB_TYPE_UINT64:
  11157. upb_handlers_setuint64(h, value_field, putuint64_t, &empty_attr);
  11158. break;
  11159. case UPB_TYPE_BOOL:
  11160. upb_handlers_setbool(h, value_field, putbool, &empty_attr);
  11161. break;
  11162. case UPB_TYPE_FLOAT:
  11163. upb_handlers_setfloat(h, value_field, putfloat, &empty_attr);
  11164. break;
  11165. case UPB_TYPE_DOUBLE:
  11166. upb_handlers_setdouble(h, value_field, putdouble, &empty_attr);
  11167. break;
  11168. case UPB_TYPE_STRING:
  11169. upb_handlers_setstartstr(h, value_field, mapkeyval_startstr, &empty_attr);
  11170. upb_handlers_setstring(h, value_field, putstr, &empty_attr);
  11171. upb_handlers_setendstr(h, value_field, mapvalue_endstr, &empty_attr);
  11172. break;
  11173. case UPB_TYPE_BYTES:
  11174. upb_handlers_setstring(h, value_field, putbytes, &empty_attr);
  11175. break;
  11176. case UPB_TYPE_ENUM: {
  11177. upb_handlerattr enum_attr = UPB_HANDLERATTR_INIT;
  11178. set_enum_hd(h, value_field, preserve_fieldnames, &enum_attr);
  11179. upb_handlers_setint32(h, value_field, mapvalue_enum, &enum_attr);
  11180. break;
  11181. }
  11182. case UPB_TYPE_MESSAGE:
  11183. /* No handler necessary -- the submsg handlers will print the message
  11184. * as appropriate. */
  11185. break;
  11186. }
  11187. }
  11188. static bool putseconds(void *closure, const void *handler_data,
  11189. int64_t seconds) {
  11190. upb_json_printer *p = closure;
  11191. p->seconds = seconds;
  11192. UPB_UNUSED(handler_data);
  11193. return true;
  11194. }
  11195. static bool putnanos(void *closure, const void *handler_data,
  11196. int32_t nanos) {
  11197. upb_json_printer *p = closure;
  11198. p->nanos = nanos;
  11199. UPB_UNUSED(handler_data);
  11200. return true;
  11201. }
  11202. static void *scalar_startstr_nokey(void *closure, const void *handler_data,
  11203. size_t size_hint) {
  11204. upb_json_printer *p = closure;
  11205. UPB_UNUSED(handler_data);
  11206. UPB_UNUSED(size_hint);
  11207. print_data(p, "\"", 1);
  11208. return p;
  11209. }
  11210. static size_t putstr_nokey(void *closure, const void *handler_data,
  11211. const char *str, size_t len,
  11212. const upb_bufhandle *handle) {
  11213. upb_json_printer *p = closure;
  11214. UPB_UNUSED(handler_data);
  11215. UPB_UNUSED(handle);
  11216. print_data(p, "\"", 1);
  11217. putstring(p, str, len);
  11218. print_data(p, "\"", 1);
  11219. return len + 2;
  11220. }
  11221. static void *startseq_nokey(void *closure, const void *handler_data) {
  11222. upb_json_printer *p = closure;
  11223. UPB_UNUSED(handler_data);
  11224. p->depth_++;
  11225. p->first_elem_[p->depth_] = true;
  11226. print_data(p, "[", 1);
  11227. return closure;
  11228. }
  11229. static void *startseq_fieldmask(void *closure, const void *handler_data) {
  11230. upb_json_printer *p = closure;
  11231. UPB_UNUSED(handler_data);
  11232. p->depth_++;
  11233. p->first_elem_[p->depth_] = true;
  11234. return closure;
  11235. }
  11236. static bool endseq_fieldmask(void *closure, const void *handler_data) {
  11237. upb_json_printer *p = closure;
  11238. UPB_UNUSED(handler_data);
  11239. p->depth_--;
  11240. return true;
  11241. }
  11242. static void *repeated_startstr_fieldmask(
  11243. void *closure, const void *handler_data,
  11244. size_t size_hint) {
  11245. upb_json_printer *p = closure;
  11246. UPB_UNUSED(handler_data);
  11247. UPB_UNUSED(size_hint);
  11248. print_comma(p);
  11249. return p;
  11250. }
  11251. static size_t repeated_str_fieldmask(
  11252. void *closure, const void *handler_data,
  11253. const char *str, size_t len,
  11254. const upb_bufhandle *handle) {
  11255. const char* limit = str + len;
  11256. bool upper = false;
  11257. size_t result_len = 0;
  11258. for (; str < limit; str++) {
  11259. if (*str == '_') {
  11260. upper = true;
  11261. continue;
  11262. }
  11263. if (upper && *str >= 'a' && *str <= 'z') {
  11264. char upper_char = toupper(*str);
  11265. CHK(putstr(closure, handler_data, &upper_char, 1, handle));
  11266. } else {
  11267. CHK(putstr(closure, handler_data, str, 1, handle));
  11268. }
  11269. upper = false;
  11270. result_len++;
  11271. }
  11272. return result_len;
  11273. }
  11274. static void *startmap_nokey(void *closure, const void *handler_data) {
  11275. upb_json_printer *p = closure;
  11276. UPB_UNUSED(handler_data);
  11277. p->depth_++;
  11278. p->first_elem_[p->depth_] = true;
  11279. print_data(p, "{", 1);
  11280. return closure;
  11281. }
  11282. static bool putnull(void *closure, const void *handler_data,
  11283. int32_t null) {
  11284. upb_json_printer *p = closure;
  11285. print_data(p, "null", 4);
  11286. UPB_UNUSED(handler_data);
  11287. UPB_UNUSED(null);
  11288. return true;
  11289. }
  11290. static bool printer_startdurationmsg(void *closure, const void *handler_data) {
  11291. upb_json_printer *p = closure;
  11292. UPB_UNUSED(handler_data);
  11293. if (p->depth_ == 0) {
  11294. upb_bytessink_start(p->output_, 0, &p->subc_);
  11295. }
  11296. return true;
  11297. }
  11298. #define UPB_DURATION_MAX_JSON_LEN 23
  11299. #define UPB_DURATION_MAX_NANO_LEN 9
  11300. static bool printer_enddurationmsg(void *closure, const void *handler_data,
  11301. upb_status *s) {
  11302. upb_json_printer *p = closure;
  11303. char buffer[UPB_DURATION_MAX_JSON_LEN];
  11304. size_t base_len;
  11305. size_t curr;
  11306. size_t i;
  11307. memset(buffer, 0, UPB_DURATION_MAX_JSON_LEN);
  11308. if (p->seconds < -315576000000) {
  11309. upb_status_seterrf(s, "error parsing duration: "
  11310. "minimum acceptable value is "
  11311. "-315576000000");
  11312. return false;
  11313. }
  11314. if (p->seconds > 315576000000) {
  11315. upb_status_seterrf(s, "error serializing duration: "
  11316. "maximum acceptable value is "
  11317. "315576000000");
  11318. return false;
  11319. }
  11320. _upb_snprintf(buffer, sizeof(buffer), "%ld", (long)p->seconds);
  11321. base_len = strlen(buffer);
  11322. if (p->nanos != 0) {
  11323. char nanos_buffer[UPB_DURATION_MAX_NANO_LEN + 3];
  11324. _upb_snprintf(nanos_buffer, sizeof(nanos_buffer), "%.9f",
  11325. p->nanos / 1000000000.0);
  11326. /* Remove trailing 0. */
  11327. for (i = UPB_DURATION_MAX_NANO_LEN + 2;
  11328. nanos_buffer[i] == '0'; i--) {
  11329. nanos_buffer[i] = 0;
  11330. }
  11331. strcpy(buffer + base_len, nanos_buffer + 1);
  11332. }
  11333. curr = strlen(buffer);
  11334. strcpy(buffer + curr, "s");
  11335. p->seconds = 0;
  11336. p->nanos = 0;
  11337. print_data(p, "\"", 1);
  11338. print_data(p, buffer, strlen(buffer));
  11339. print_data(p, "\"", 1);
  11340. if (p->depth_ == 0) {
  11341. upb_bytessink_end(p->output_);
  11342. }
  11343. UPB_UNUSED(handler_data);
  11344. return true;
  11345. }
  11346. static bool printer_starttimestampmsg(void *closure, const void *handler_data) {
  11347. upb_json_printer *p = closure;
  11348. UPB_UNUSED(handler_data);
  11349. if (p->depth_ == 0) {
  11350. upb_bytessink_start(p->output_, 0, &p->subc_);
  11351. }
  11352. return true;
  11353. }
  11354. #define UPB_TIMESTAMP_MAX_JSON_LEN 31
  11355. #define UPB_TIMESTAMP_BEFORE_NANO_LEN 19
  11356. #define UPB_TIMESTAMP_MAX_NANO_LEN 9
  11357. static bool printer_endtimestampmsg(void *closure, const void *handler_data,
  11358. upb_status *s) {
  11359. upb_json_printer *p = closure;
  11360. char buffer[UPB_TIMESTAMP_MAX_JSON_LEN];
  11361. time_t time = p->seconds;
  11362. size_t curr;
  11363. size_t i;
  11364. size_t year_length =
  11365. strftime(buffer, UPB_TIMESTAMP_MAX_JSON_LEN, "%Y", gmtime(&time));
  11366. if (p->seconds < -62135596800) {
  11367. upb_status_seterrf(s, "error parsing timestamp: "
  11368. "minimum acceptable value is "
  11369. "0001-01-01T00:00:00Z");
  11370. return false;
  11371. }
  11372. if (p->seconds > 253402300799) {
  11373. upb_status_seterrf(s, "error parsing timestamp: "
  11374. "maximum acceptable value is "
  11375. "9999-12-31T23:59:59Z");
  11376. return false;
  11377. }
  11378. /* strftime doesn't guarantee 4 digits for year. Prepend 0 by ourselves. */
  11379. for (i = 0; i < 4 - year_length; i++) {
  11380. buffer[i] = '0';
  11381. }
  11382. strftime(buffer + (4 - year_length), UPB_TIMESTAMP_MAX_JSON_LEN,
  11383. "%Y-%m-%dT%H:%M:%S", gmtime(&time));
  11384. if (p->nanos != 0) {
  11385. char nanos_buffer[UPB_TIMESTAMP_MAX_NANO_LEN + 3];
  11386. _upb_snprintf(nanos_buffer, sizeof(nanos_buffer), "%.9f",
  11387. p->nanos / 1000000000.0);
  11388. /* Remove trailing 0. */
  11389. for (i = UPB_TIMESTAMP_MAX_NANO_LEN + 2;
  11390. nanos_buffer[i] == '0'; i--) {
  11391. nanos_buffer[i] = 0;
  11392. }
  11393. strcpy(buffer + UPB_TIMESTAMP_BEFORE_NANO_LEN, nanos_buffer + 1);
  11394. }
  11395. curr = strlen(buffer);
  11396. strcpy(buffer + curr, "Z");
  11397. p->seconds = 0;
  11398. p->nanos = 0;
  11399. print_data(p, "\"", 1);
  11400. print_data(p, buffer, strlen(buffer));
  11401. print_data(p, "\"", 1);
  11402. if (p->depth_ == 0) {
  11403. upb_bytessink_end(p->output_);
  11404. }
  11405. UPB_UNUSED(handler_data);
  11406. UPB_UNUSED(s);
  11407. return true;
  11408. }
  11409. static bool printer_startmsg_noframe(void *closure, const void *handler_data) {
  11410. upb_json_printer *p = closure;
  11411. UPB_UNUSED(handler_data);
  11412. if (p->depth_ == 0) {
  11413. upb_bytessink_start(p->output_, 0, &p->subc_);
  11414. }
  11415. return true;
  11416. }
  11417. static bool printer_endmsg_noframe(
  11418. void *closure, const void *handler_data, upb_status *s) {
  11419. upb_json_printer *p = closure;
  11420. UPB_UNUSED(handler_data);
  11421. UPB_UNUSED(s);
  11422. if (p->depth_ == 0) {
  11423. upb_bytessink_end(p->output_);
  11424. }
  11425. return true;
  11426. }
  11427. static bool printer_startmsg_fieldmask(
  11428. void *closure, const void *handler_data) {
  11429. upb_json_printer *p = closure;
  11430. UPB_UNUSED(handler_data);
  11431. if (p->depth_ == 0) {
  11432. upb_bytessink_start(p->output_, 0, &p->subc_);
  11433. }
  11434. print_data(p, "\"", 1);
  11435. return true;
  11436. }
  11437. static bool printer_endmsg_fieldmask(
  11438. void *closure, const void *handler_data, upb_status *s) {
  11439. upb_json_printer *p = closure;
  11440. UPB_UNUSED(handler_data);
  11441. UPB_UNUSED(s);
  11442. print_data(p, "\"", 1);
  11443. if (p->depth_ == 0) {
  11444. upb_bytessink_end(p->output_);
  11445. }
  11446. return true;
  11447. }
  11448. static void *scalar_startstr_onlykey(
  11449. void *closure, const void *handler_data, size_t size_hint) {
  11450. upb_json_printer *p = closure;
  11451. UPB_UNUSED(size_hint);
  11452. CHK(putkey(closure, handler_data));
  11453. return p;
  11454. }
  11455. /* Set up handlers for an Any submessage. */
  11456. void printer_sethandlers_any(const void *closure, upb_handlers *h) {
  11457. const upb_msgdef *md = upb_handlers_msgdef(h);
  11458. const upb_fielddef* type_field = upb_msgdef_itof(md, UPB_ANY_TYPE);
  11459. const upb_fielddef* value_field = upb_msgdef_itof(md, UPB_ANY_VALUE);
  11460. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11461. /* type_url's json name is "@type" */
  11462. upb_handlerattr type_name_attr = UPB_HANDLERATTR_INIT;
  11463. upb_handlerattr value_name_attr = UPB_HANDLERATTR_INIT;
  11464. strpc *type_url_json_name = newstrpc_str(h, "@type");
  11465. strpc *value_json_name = newstrpc_str(h, "value");
  11466. type_name_attr.handler_data = type_url_json_name;
  11467. value_name_attr.handler_data = value_json_name;
  11468. /* Set up handlers. */
  11469. upb_handlers_setstartmsg(h, printer_startmsg, &empty_attr);
  11470. upb_handlers_setendmsg(h, printer_endmsg, &empty_attr);
  11471. upb_handlers_setstartstr(h, type_field, scalar_startstr, &type_name_attr);
  11472. upb_handlers_setstring(h, type_field, scalar_str, &empty_attr);
  11473. upb_handlers_setendstr(h, type_field, scalar_endstr, &empty_attr);
  11474. /* This is not the full and correct JSON encoding for the Any value field. It
  11475. * requires further processing by the wrapper code based on the type URL.
  11476. */
  11477. upb_handlers_setstartstr(h, value_field, scalar_startstr_onlykey,
  11478. &value_name_attr);
  11479. UPB_UNUSED(closure);
  11480. }
  11481. /* Set up handlers for a fieldmask submessage. */
  11482. void printer_sethandlers_fieldmask(const void *closure, upb_handlers *h) {
  11483. const upb_msgdef *md = upb_handlers_msgdef(h);
  11484. const upb_fielddef* f = upb_msgdef_itof(md, 1);
  11485. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11486. upb_handlers_setstartseq(h, f, startseq_fieldmask, &empty_attr);
  11487. upb_handlers_setendseq(h, f, endseq_fieldmask, &empty_attr);
  11488. upb_handlers_setstartmsg(h, printer_startmsg_fieldmask, &empty_attr);
  11489. upb_handlers_setendmsg(h, printer_endmsg_fieldmask, &empty_attr);
  11490. upb_handlers_setstartstr(h, f, repeated_startstr_fieldmask, &empty_attr);
  11491. upb_handlers_setstring(h, f, repeated_str_fieldmask, &empty_attr);
  11492. UPB_UNUSED(closure);
  11493. }
  11494. /* Set up handlers for a duration submessage. */
  11495. void printer_sethandlers_duration(const void *closure, upb_handlers *h) {
  11496. const upb_msgdef *md = upb_handlers_msgdef(h);
  11497. const upb_fielddef* seconds_field =
  11498. upb_msgdef_itof(md, UPB_DURATION_SECONDS);
  11499. const upb_fielddef* nanos_field =
  11500. upb_msgdef_itof(md, UPB_DURATION_NANOS);
  11501. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11502. upb_handlers_setstartmsg(h, printer_startdurationmsg, &empty_attr);
  11503. upb_handlers_setint64(h, seconds_field, putseconds, &empty_attr);
  11504. upb_handlers_setint32(h, nanos_field, putnanos, &empty_attr);
  11505. upb_handlers_setendmsg(h, printer_enddurationmsg, &empty_attr);
  11506. UPB_UNUSED(closure);
  11507. }
  11508. /* Set up handlers for a timestamp submessage. Instead of printing fields
  11509. * separately, the json representation of timestamp follows RFC 3339 */
  11510. void printer_sethandlers_timestamp(const void *closure, upb_handlers *h) {
  11511. const upb_msgdef *md = upb_handlers_msgdef(h);
  11512. const upb_fielddef* seconds_field =
  11513. upb_msgdef_itof(md, UPB_TIMESTAMP_SECONDS);
  11514. const upb_fielddef* nanos_field =
  11515. upb_msgdef_itof(md, UPB_TIMESTAMP_NANOS);
  11516. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11517. upb_handlers_setstartmsg(h, printer_starttimestampmsg, &empty_attr);
  11518. upb_handlers_setint64(h, seconds_field, putseconds, &empty_attr);
  11519. upb_handlers_setint32(h, nanos_field, putnanos, &empty_attr);
  11520. upb_handlers_setendmsg(h, printer_endtimestampmsg, &empty_attr);
  11521. UPB_UNUSED(closure);
  11522. }
  11523. void printer_sethandlers_value(const void *closure, upb_handlers *h) {
  11524. const upb_msgdef *md = upb_handlers_msgdef(h);
  11525. upb_msg_field_iter i;
  11526. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11527. upb_handlers_setstartmsg(h, printer_startmsg_noframe, &empty_attr);
  11528. upb_handlers_setendmsg(h, printer_endmsg_noframe, &empty_attr);
  11529. upb_msg_field_begin(&i, md);
  11530. for(; !upb_msg_field_done(&i); upb_msg_field_next(&i)) {
  11531. const upb_fielddef *f = upb_msg_iter_field(&i);
  11532. switch (upb_fielddef_type(f)) {
  11533. case UPB_TYPE_ENUM:
  11534. upb_handlers_setint32(h, f, putnull, &empty_attr);
  11535. break;
  11536. case UPB_TYPE_DOUBLE:
  11537. upb_handlers_setdouble(h, f, putdouble, &empty_attr);
  11538. break;
  11539. case UPB_TYPE_STRING:
  11540. upb_handlers_setstartstr(h, f, scalar_startstr_nokey, &empty_attr);
  11541. upb_handlers_setstring(h, f, scalar_str, &empty_attr);
  11542. upb_handlers_setendstr(h, f, scalar_endstr, &empty_attr);
  11543. break;
  11544. case UPB_TYPE_BOOL:
  11545. upb_handlers_setbool(h, f, putbool, &empty_attr);
  11546. break;
  11547. case UPB_TYPE_MESSAGE:
  11548. break;
  11549. default:
  11550. UPB_ASSERT(false);
  11551. break;
  11552. }
  11553. }
  11554. UPB_UNUSED(closure);
  11555. }
  11556. #define WRAPPER_SETHANDLERS(wrapper, type, putmethod) \
  11557. void printer_sethandlers_##wrapper(const void *closure, upb_handlers *h) { \
  11558. const upb_msgdef *md = upb_handlers_msgdef(h); \
  11559. const upb_fielddef* f = upb_msgdef_itof(md, 1); \
  11560. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT; \
  11561. upb_handlers_setstartmsg(h, printer_startmsg_noframe, &empty_attr); \
  11562. upb_handlers_setendmsg(h, printer_endmsg_noframe, &empty_attr); \
  11563. upb_handlers_set##type(h, f, putmethod, &empty_attr); \
  11564. UPB_UNUSED(closure); \
  11565. }
  11566. WRAPPER_SETHANDLERS(doublevalue, double, putdouble)
  11567. WRAPPER_SETHANDLERS(floatvalue, float, putfloat)
  11568. WRAPPER_SETHANDLERS(int64value, int64, putint64_t)
  11569. WRAPPER_SETHANDLERS(uint64value, uint64, putuint64_t)
  11570. WRAPPER_SETHANDLERS(int32value, int32, putint32_t)
  11571. WRAPPER_SETHANDLERS(uint32value, uint32, putuint32_t)
  11572. WRAPPER_SETHANDLERS(boolvalue, bool, putbool)
  11573. WRAPPER_SETHANDLERS(stringvalue, string, putstr_nokey)
  11574. WRAPPER_SETHANDLERS(bytesvalue, string, putbytes)
  11575. #undef WRAPPER_SETHANDLERS
  11576. void printer_sethandlers_listvalue(const void *closure, upb_handlers *h) {
  11577. const upb_msgdef *md = upb_handlers_msgdef(h);
  11578. const upb_fielddef* f = upb_msgdef_itof(md, 1);
  11579. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11580. upb_handlers_setstartseq(h, f, startseq_nokey, &empty_attr);
  11581. upb_handlers_setendseq(h, f, endseq, &empty_attr);
  11582. upb_handlers_setstartmsg(h, printer_startmsg_noframe, &empty_attr);
  11583. upb_handlers_setendmsg(h, printer_endmsg_noframe, &empty_attr);
  11584. upb_handlers_setstartsubmsg(h, f, repeated_startsubmsg, &empty_attr);
  11585. UPB_UNUSED(closure);
  11586. }
  11587. void printer_sethandlers_structvalue(const void *closure, upb_handlers *h) {
  11588. const upb_msgdef *md = upb_handlers_msgdef(h);
  11589. const upb_fielddef* f = upb_msgdef_itof(md, 1);
  11590. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11591. upb_handlers_setstartseq(h, f, startmap_nokey, &empty_attr);
  11592. upb_handlers_setendseq(h, f, endmap, &empty_attr);
  11593. upb_handlers_setstartmsg(h, printer_startmsg_noframe, &empty_attr);
  11594. upb_handlers_setendmsg(h, printer_endmsg_noframe, &empty_attr);
  11595. upb_handlers_setstartsubmsg(h, f, repeated_startsubmsg, &empty_attr);
  11596. UPB_UNUSED(closure);
  11597. }
  11598. void printer_sethandlers(const void *closure, upb_handlers *h) {
  11599. const upb_msgdef *md = upb_handlers_msgdef(h);
  11600. bool is_mapentry = upb_msgdef_mapentry(md);
  11601. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11602. upb_msg_field_iter i;
  11603. const upb_json_printercache *cache = closure;
  11604. const bool preserve_fieldnames = cache->preserve_fieldnames;
  11605. if (is_mapentry) {
  11606. /* mapentry messages are sufficiently different that we handle them
  11607. * separately. */
  11608. printer_sethandlers_mapentry(closure, preserve_fieldnames, h);
  11609. return;
  11610. }
  11611. switch (upb_msgdef_wellknowntype(md)) {
  11612. case UPB_WELLKNOWN_UNSPECIFIED:
  11613. break;
  11614. case UPB_WELLKNOWN_ANY:
  11615. printer_sethandlers_any(closure, h);
  11616. return;
  11617. case UPB_WELLKNOWN_FIELDMASK:
  11618. printer_sethandlers_fieldmask(closure, h);
  11619. return;
  11620. case UPB_WELLKNOWN_DURATION:
  11621. printer_sethandlers_duration(closure, h);
  11622. return;
  11623. case UPB_WELLKNOWN_TIMESTAMP:
  11624. printer_sethandlers_timestamp(closure, h);
  11625. return;
  11626. case UPB_WELLKNOWN_VALUE:
  11627. printer_sethandlers_value(closure, h);
  11628. return;
  11629. case UPB_WELLKNOWN_LISTVALUE:
  11630. printer_sethandlers_listvalue(closure, h);
  11631. return;
  11632. case UPB_WELLKNOWN_STRUCT:
  11633. printer_sethandlers_structvalue(closure, h);
  11634. return;
  11635. #define WRAPPER(wellknowntype, name) \
  11636. case wellknowntype: \
  11637. printer_sethandlers_##name(closure, h); \
  11638. return; \
  11639. WRAPPER(UPB_WELLKNOWN_DOUBLEVALUE, doublevalue);
  11640. WRAPPER(UPB_WELLKNOWN_FLOATVALUE, floatvalue);
  11641. WRAPPER(UPB_WELLKNOWN_INT64VALUE, int64value);
  11642. WRAPPER(UPB_WELLKNOWN_UINT64VALUE, uint64value);
  11643. WRAPPER(UPB_WELLKNOWN_INT32VALUE, int32value);
  11644. WRAPPER(UPB_WELLKNOWN_UINT32VALUE, uint32value);
  11645. WRAPPER(UPB_WELLKNOWN_BOOLVALUE, boolvalue);
  11646. WRAPPER(UPB_WELLKNOWN_STRINGVALUE, stringvalue);
  11647. WRAPPER(UPB_WELLKNOWN_BYTESVALUE, bytesvalue);
  11648. #undef WRAPPER
  11649. }
  11650. upb_handlers_setstartmsg(h, printer_startmsg, &empty_attr);
  11651. upb_handlers_setendmsg(h, printer_endmsg, &empty_attr);
  11652. #define TYPE(type, name, ctype) \
  11653. case type: \
  11654. if (upb_fielddef_isseq(f)) { \
  11655. upb_handlers_set##name(h, f, repeated_##ctype, &empty_attr); \
  11656. } else { \
  11657. upb_handlers_set##name(h, f, scalar_##ctype, &name_attr); \
  11658. } \
  11659. break;
  11660. upb_msg_field_begin(&i, md);
  11661. for(; !upb_msg_field_done(&i); upb_msg_field_next(&i)) {
  11662. const upb_fielddef *f = upb_msg_iter_field(&i);
  11663. upb_handlerattr name_attr = UPB_HANDLERATTR_INIT;
  11664. name_attr.handler_data = newstrpc(h, f, preserve_fieldnames);
  11665. if (upb_fielddef_ismap(f)) {
  11666. upb_handlers_setstartseq(h, f, startmap, &name_attr);
  11667. upb_handlers_setendseq(h, f, endmap, &name_attr);
  11668. } else if (upb_fielddef_isseq(f)) {
  11669. upb_handlers_setstartseq(h, f, startseq, &name_attr);
  11670. upb_handlers_setendseq(h, f, endseq, &empty_attr);
  11671. }
  11672. switch (upb_fielddef_type(f)) {
  11673. TYPE(UPB_TYPE_FLOAT, float, float);
  11674. TYPE(UPB_TYPE_DOUBLE, double, double);
  11675. TYPE(UPB_TYPE_BOOL, bool, bool);
  11676. TYPE(UPB_TYPE_INT32, int32, int32_t);
  11677. TYPE(UPB_TYPE_UINT32, uint32, uint32_t);
  11678. TYPE(UPB_TYPE_INT64, int64, int64_t);
  11679. TYPE(UPB_TYPE_UINT64, uint64, uint64_t);
  11680. case UPB_TYPE_ENUM: {
  11681. /* For now, we always emit symbolic names for enums. We may want an
  11682. * option later to control this behavior, but we will wait for a real
  11683. * need first. */
  11684. upb_handlerattr enum_attr = UPB_HANDLERATTR_INIT;
  11685. set_enum_hd(h, f, preserve_fieldnames, &enum_attr);
  11686. if (upb_fielddef_isseq(f)) {
  11687. upb_handlers_setint32(h, f, repeated_enum, &enum_attr);
  11688. } else {
  11689. upb_handlers_setint32(h, f, scalar_enum, &enum_attr);
  11690. }
  11691. break;
  11692. }
  11693. case UPB_TYPE_STRING:
  11694. if (upb_fielddef_isseq(f)) {
  11695. upb_handlers_setstartstr(h, f, repeated_startstr, &empty_attr);
  11696. upb_handlers_setstring(h, f, repeated_str, &empty_attr);
  11697. upb_handlers_setendstr(h, f, repeated_endstr, &empty_attr);
  11698. } else {
  11699. upb_handlers_setstartstr(h, f, scalar_startstr, &name_attr);
  11700. upb_handlers_setstring(h, f, scalar_str, &empty_attr);
  11701. upb_handlers_setendstr(h, f, scalar_endstr, &empty_attr);
  11702. }
  11703. break;
  11704. case UPB_TYPE_BYTES:
  11705. /* XXX: this doesn't support strings that span buffers yet. The base64
  11706. * encoder will need to be made resumable for this to work properly. */
  11707. if (upb_fielddef_isseq(f)) {
  11708. upb_handlers_setstring(h, f, repeated_bytes, &empty_attr);
  11709. } else {
  11710. upb_handlers_setstring(h, f, scalar_bytes, &name_attr);
  11711. }
  11712. break;
  11713. case UPB_TYPE_MESSAGE:
  11714. if (upb_fielddef_isseq(f)) {
  11715. upb_handlers_setstartsubmsg(h, f, repeated_startsubmsg, &name_attr);
  11716. } else {
  11717. upb_handlers_setstartsubmsg(h, f, scalar_startsubmsg, &name_attr);
  11718. }
  11719. break;
  11720. }
  11721. }
  11722. #undef TYPE
  11723. }
  11724. static void json_printer_reset(upb_json_printer *p) {
  11725. p->depth_ = 0;
  11726. }
  11727. /* Public API *****************************************************************/
  11728. upb_json_printer *upb_json_printer_create(upb_arena *a, const upb_handlers *h,
  11729. upb_bytessink output) {
  11730. upb_json_printer *p = upb_arena_malloc(a, sizeof(upb_json_printer));
  11731. if (!p) return NULL;
  11732. p->output_ = output;
  11733. json_printer_reset(p);
  11734. upb_sink_reset(&p->input_, h, p);
  11735. p->seconds = 0;
  11736. p->nanos = 0;
  11737. return p;
  11738. }
  11739. upb_sink upb_json_printer_input(upb_json_printer *p) {
  11740. return p->input_;
  11741. }
  11742. upb_handlercache *upb_json_printer_newcache(bool preserve_proto_fieldnames) {
  11743. upb_json_printercache *cache = upb_gmalloc(sizeof(*cache));
  11744. upb_handlercache *ret = upb_handlercache_new(printer_sethandlers, cache);
  11745. cache->preserve_fieldnames = preserve_proto_fieldnames;
  11746. upb_handlercache_addcleanup(ret, cache, upb_gfree);
  11747. return ret;
  11748. }
  11749. /* See port_def.inc. This should #undef all macros #defined there. */
  11750. #undef UPB_MAPTYPE_STRING
  11751. #undef UPB_SIZE
  11752. #undef UPB_PTR_AT
  11753. #undef UPB_READ_ONEOF
  11754. #undef UPB_WRITE_ONEOF
  11755. #undef UPB_INLINE
  11756. #undef UPB_ALIGN_UP
  11757. #undef UPB_ALIGN_DOWN
  11758. #undef UPB_ALIGN_MALLOC
  11759. #undef UPB_ALIGN_OF
  11760. #undef UPB_FORCEINLINE
  11761. #undef UPB_NOINLINE
  11762. #undef UPB_NORETURN
  11763. #undef UPB_MAX
  11764. #undef UPB_MIN
  11765. #undef UPB_UNUSED
  11766. #undef UPB_ASSUME
  11767. #undef UPB_ASSERT
  11768. #undef UPB_ASSERT_DEBUGVAR
  11769. #undef UPB_UNREACHABLE
  11770. #undef UPB_INFINITY
  11771. #undef UPB_MSVC_VSNPRINTF
  11772. #undef _upb_snprintf
  11773. #undef _upb_vsnprintf
  11774. #undef _upb_va_copy