upb.c 408 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774
  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. #if UINTPTR_MAX == 0xffffffff
  27. #define UPB_SIZE(size32, size64) size32
  28. #else
  29. #define UPB_SIZE(size32, size64) size64
  30. #endif
  31. /* If we always read/write as a consistent type to each address, this shouldn't
  32. * violate aliasing.
  33. */
  34. #define UPB_PTR_AT(msg, ofs, type) ((type*)((char*)(msg) + (ofs)))
  35. #define UPB_READ_ONEOF(msg, fieldtype, offset, case_offset, case_val, default) \
  36. *UPB_PTR_AT(msg, case_offset, int) == case_val \
  37. ? *UPB_PTR_AT(msg, offset, fieldtype) \
  38. : default
  39. #define UPB_WRITE_ONEOF(msg, fieldtype, offset, value, case_offset, case_val) \
  40. *UPB_PTR_AT(msg, case_offset, int) = case_val; \
  41. *UPB_PTR_AT(msg, offset, fieldtype) = value;
  42. #define UPB_MAPTYPE_STRING 0
  43. /* UPB_INLINE: inline if possible, emit standalone code if required. */
  44. #ifdef __cplusplus
  45. #define UPB_INLINE inline
  46. #elif defined (__GNUC__) || defined(__clang__)
  47. #define UPB_INLINE static __inline__
  48. #else
  49. #define UPB_INLINE static
  50. #endif
  51. /* Hints to the compiler about likely/unlikely branches. */
  52. #if defined (__GNUC__) || defined(__clang__)
  53. #define UPB_LIKELY(x) __builtin_expect((x),1)
  54. #define UPB_UNLIKELY(x) __builtin_expect((x),0)
  55. #else
  56. #define UPB_LIKELY(x) (x)
  57. #define UPB_UNLIKELY(x) (x)
  58. #endif
  59. /* Define UPB_BIG_ENDIAN manually if you're on big endian and your compiler
  60. * doesn't provide these preprocessor symbols. */
  61. #if defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)
  62. #define UPB_BIG_ENDIAN
  63. #endif
  64. /* Macros for function attributes on compilers that support them. */
  65. #ifdef __GNUC__
  66. #define UPB_FORCEINLINE __inline__ __attribute__((always_inline))
  67. #define UPB_NOINLINE __attribute__((noinline))
  68. #define UPB_NORETURN __attribute__((__noreturn__))
  69. #else /* !defined(__GNUC__) */
  70. #define UPB_FORCEINLINE
  71. #define UPB_NOINLINE
  72. #define UPB_NORETURN
  73. #endif
  74. #if __STDC_VERSION__ >= 199901L || __cplusplus >= 201103L
  75. /* C99/C++11 versions. */
  76. #include <stdio.h>
  77. #define _upb_snprintf snprintf
  78. #define _upb_vsnprintf vsnprintf
  79. #define _upb_va_copy(a, b) va_copy(a, b)
  80. #elif defined(_MSC_VER)
  81. /* Microsoft C/C++ versions. */
  82. #include <stdarg.h>
  83. #include <stdio.h>
  84. #if _MSC_VER < 1900
  85. int msvc_snprintf(char* s, size_t n, const char* format, ...);
  86. int msvc_vsnprintf(char* s, size_t n, const char* format, va_list arg);
  87. #define UPB_MSVC_VSNPRINTF
  88. #define _upb_snprintf msvc_snprintf
  89. #define _upb_vsnprintf msvc_vsnprintf
  90. #else
  91. #define _upb_snprintf snprintf
  92. #define _upb_vsnprintf vsnprintf
  93. #endif
  94. #define _upb_va_copy(a, b) va_copy(a, b)
  95. #elif defined __GNUC__
  96. /* A few hacky workarounds for functions not in C89.
  97. * For internal use only!
  98. * TODO(haberman): fix these by including our own implementations, or finding
  99. * another workaround.
  100. */
  101. #define _upb_snprintf __builtin_snprintf
  102. #define _upb_vsnprintf __builtin_vsnprintf
  103. #define _upb_va_copy(a, b) __va_copy(a, b)
  104. #else
  105. #error Need implementations of [v]snprintf and va_copy
  106. #endif
  107. #ifdef __cplusplus
  108. #if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__) || \
  109. (defined(_MSC_VER) && _MSC_VER >= 1900)
  110. /* C++11 is present */
  111. #else
  112. #error upb requires C++11 for C++ support
  113. #endif
  114. #endif
  115. #define UPB_MAX(x, y) ((x) > (y) ? (x) : (y))
  116. #define UPB_MIN(x, y) ((x) < (y) ? (x) : (y))
  117. #define UPB_UNUSED(var) (void)var
  118. /* UPB_ASSUME(): in release mode, we tell the compiler to assume this is true.
  119. */
  120. #ifdef NDEBUG
  121. #ifdef __GNUC__
  122. #define UPB_ASSUME(expr) if (!(expr)) __builtin_unreachable()
  123. #else
  124. #define UPB_ASSUME(expr) do {} if (false && (expr))
  125. #endif
  126. #else
  127. #define UPB_ASSUME(expr) assert(expr)
  128. #endif
  129. /* UPB_ASSERT(): in release mode, we use the expression without letting it be
  130. * evaluated. This prevents "unused variable" warnings. */
  131. #ifdef NDEBUG
  132. #define UPB_ASSERT(expr) do {} while (false && (expr))
  133. #else
  134. #define UPB_ASSERT(expr) assert(expr)
  135. #endif
  136. /* UPB_ASSERT_DEBUGVAR(): assert that uses functions or variables that only
  137. * exist in debug mode. This turns into regular assert. */
  138. #define UPB_ASSERT_DEBUGVAR(expr) assert(expr)
  139. #if defined(__GNUC__) || defined(__clang__)
  140. #define UPB_UNREACHABLE() do { assert(0); __builtin_unreachable(); } while(0)
  141. #else
  142. #define UPB_UNREACHABLE() do { assert(0); } while(0)
  143. #endif
  144. /* UPB_INFINITY representing floating-point positive infinity. */
  145. #include <math.h>
  146. #ifdef INFINITY
  147. #define UPB_INFINITY INFINITY
  148. #else
  149. #define UPB_INFINITY (1.0 / 0.0)
  150. #endif
  151. #include <setjmp.h>
  152. #include <string.h>
  153. /* Maps descriptor type -> upb field type. */
  154. static const uint8_t desctype_to_fieldtype[] = {
  155. -1, /* invalid descriptor type */
  156. UPB_TYPE_DOUBLE, /* DOUBLE */
  157. UPB_TYPE_FLOAT, /* FLOAT */
  158. UPB_TYPE_INT64, /* INT64 */
  159. UPB_TYPE_UINT64, /* UINT64 */
  160. UPB_TYPE_INT32, /* INT32 */
  161. UPB_TYPE_UINT64, /* FIXED64 */
  162. UPB_TYPE_UINT32, /* FIXED32 */
  163. UPB_TYPE_BOOL, /* BOOL */
  164. UPB_TYPE_STRING, /* STRING */
  165. UPB_TYPE_MESSAGE, /* GROUP */
  166. UPB_TYPE_MESSAGE, /* MESSAGE */
  167. UPB_TYPE_BYTES, /* BYTES */
  168. UPB_TYPE_UINT32, /* UINT32 */
  169. UPB_TYPE_ENUM, /* ENUM */
  170. UPB_TYPE_INT32, /* SFIXED32 */
  171. UPB_TYPE_INT64, /* SFIXED64 */
  172. UPB_TYPE_INT32, /* SINT32 */
  173. UPB_TYPE_INT64, /* SINT64 */
  174. };
  175. /* Maps descriptor type -> upb map size. */
  176. static const uint8_t desctype_to_mapsize[] = {
  177. -1, /* invalid descriptor type */
  178. 8, /* DOUBLE */
  179. 4, /* FLOAT */
  180. 8, /* INT64 */
  181. 8, /* UINT64 */
  182. 4, /* INT32 */
  183. 8, /* FIXED64 */
  184. 4, /* FIXED32 */
  185. 1, /* BOOL */
  186. UPB_MAPTYPE_STRING, /* STRING */
  187. sizeof(void *), /* GROUP */
  188. sizeof(void *), /* MESSAGE */
  189. UPB_MAPTYPE_STRING, /* BYTES */
  190. 4, /* UINT32 */
  191. 4, /* ENUM */
  192. 4, /* SFIXED32 */
  193. 8, /* SFIXED64 */
  194. 4, /* SINT32 */
  195. 8, /* SINT64 */
  196. };
  197. static const unsigned fixed32_ok = (1 << UPB_DTYPE_FLOAT) |
  198. (1 << UPB_DTYPE_FIXED32) |
  199. (1 << UPB_DTYPE_SFIXED32);
  200. static const unsigned fixed64_ok = (1 << UPB_DTYPE_DOUBLE) |
  201. (1 << UPB_DTYPE_FIXED64) |
  202. (1 << UPB_DTYPE_SFIXED64);
  203. /* Op: an action to be performed for a wire-type/field-type combination. */
  204. #define OP_SCALAR_LG2(n) (n)
  205. #define OP_FIXPCK_LG2(n) (n + 4)
  206. #define OP_VARPCK_LG2(n) (n + 8)
  207. #define OP_STRING 4
  208. #define OP_SUBMSG 5
  209. static const int8_t varint_ops[19] = {
  210. -1, /* field not found */
  211. -1, /* DOUBLE */
  212. -1, /* FLOAT */
  213. OP_SCALAR_LG2(3), /* INT64 */
  214. OP_SCALAR_LG2(3), /* UINT64 */
  215. OP_SCALAR_LG2(2), /* INT32 */
  216. -1, /* FIXED64 */
  217. -1, /* FIXED32 */
  218. OP_SCALAR_LG2(0), /* BOOL */
  219. -1, /* STRING */
  220. -1, /* GROUP */
  221. -1, /* MESSAGE */
  222. -1, /* BYTES */
  223. OP_SCALAR_LG2(2), /* UINT32 */
  224. OP_SCALAR_LG2(2), /* ENUM */
  225. -1, /* SFIXED32 */
  226. -1, /* SFIXED64 */
  227. OP_SCALAR_LG2(2), /* SINT32 */
  228. OP_SCALAR_LG2(3), /* SINT64 */
  229. };
  230. static const int8_t delim_ops[37] = {
  231. /* For non-repeated field type. */
  232. -1, /* field not found */
  233. -1, /* DOUBLE */
  234. -1, /* FLOAT */
  235. -1, /* INT64 */
  236. -1, /* UINT64 */
  237. -1, /* INT32 */
  238. -1, /* FIXED64 */
  239. -1, /* FIXED32 */
  240. -1, /* BOOL */
  241. OP_STRING, /* STRING */
  242. -1, /* GROUP */
  243. OP_SUBMSG, /* MESSAGE */
  244. OP_STRING, /* BYTES */
  245. -1, /* UINT32 */
  246. -1, /* ENUM */
  247. -1, /* SFIXED32 */
  248. -1, /* SFIXED64 */
  249. -1, /* SINT32 */
  250. -1, /* SINT64 */
  251. /* For repeated field type. */
  252. OP_FIXPCK_LG2(3), /* REPEATED DOUBLE */
  253. OP_FIXPCK_LG2(2), /* REPEATED FLOAT */
  254. OP_VARPCK_LG2(3), /* REPEATED INT64 */
  255. OP_VARPCK_LG2(3), /* REPEATED UINT64 */
  256. OP_VARPCK_LG2(2), /* REPEATED INT32 */
  257. OP_FIXPCK_LG2(3), /* REPEATED FIXED64 */
  258. OP_FIXPCK_LG2(2), /* REPEATED FIXED32 */
  259. OP_VARPCK_LG2(0), /* REPEATED BOOL */
  260. OP_STRING, /* REPEATED STRING */
  261. OP_SUBMSG, /* REPEATED GROUP */
  262. OP_SUBMSG, /* REPEATED MESSAGE */
  263. OP_STRING, /* REPEATED BYTES */
  264. OP_VARPCK_LG2(2), /* REPEATED UINT32 */
  265. OP_VARPCK_LG2(2), /* REPEATED ENUM */
  266. OP_FIXPCK_LG2(2), /* REPEATED SFIXED32 */
  267. OP_FIXPCK_LG2(3), /* REPEATED SFIXED64 */
  268. OP_VARPCK_LG2(2), /* REPEATED SINT32 */
  269. OP_VARPCK_LG2(3), /* REPEATED SINT64 */
  270. };
  271. /* Data pertaining to the parse. */
  272. typedef struct {
  273. const char *limit; /* End of delimited region or end of buffer. */
  274. upb_arena *arena;
  275. int depth;
  276. uint32_t end_group; /* Set to field number of END_GROUP tag, if any. */
  277. jmp_buf err;
  278. } upb_decstate;
  279. typedef union {
  280. bool bool_val;
  281. int32_t int32_val;
  282. int64_t int64_val;
  283. uint32_t uint32_val;
  284. uint64_t uint64_val;
  285. upb_strview str_val;
  286. } wireval;
  287. static const char *decode_msg(upb_decstate *d, const char *ptr, upb_msg *msg,
  288. const upb_msglayout *layout);
  289. UPB_NORETURN static void decode_err(upb_decstate *d) { longjmp(d->err, 1); }
  290. static bool decode_reserve(upb_decstate *d, upb_array *arr, int elem) {
  291. bool need_realloc = arr->size - arr->len < elem;
  292. if (need_realloc && !_upb_array_realloc(arr, arr->len + elem, d->arena)) {
  293. decode_err(d);
  294. }
  295. return need_realloc;
  296. }
  297. UPB_NOINLINE
  298. static const char *decode_longvarint64(upb_decstate *d, const char *ptr,
  299. const char *limit, uint64_t *val) {
  300. uint8_t byte;
  301. int bitpos = 0;
  302. uint64_t out = 0;
  303. do {
  304. if (bitpos >= 70 || ptr == limit) decode_err(d);
  305. byte = *ptr;
  306. out |= (uint64_t)(byte & 0x7F) << bitpos;
  307. ptr++;
  308. bitpos += 7;
  309. } while (byte & 0x80);
  310. *val = out;
  311. return ptr;
  312. }
  313. UPB_FORCEINLINE
  314. static const char *decode_varint64(upb_decstate *d, const char *ptr,
  315. const char *limit, uint64_t *val) {
  316. if (UPB_LIKELY(ptr < limit && (*ptr & 0x80) == 0)) {
  317. *val = (uint8_t)*ptr;
  318. return ptr + 1;
  319. } else {
  320. return decode_longvarint64(d, ptr, limit, val);
  321. }
  322. }
  323. static const char *decode_varint32(upb_decstate *d, const char *ptr,
  324. const char *limit, uint32_t *val) {
  325. uint64_t u64;
  326. ptr = decode_varint64(d, ptr, limit, &u64);
  327. if (u64 > UINT32_MAX) decode_err(d);
  328. *val = (uint32_t)u64;
  329. return ptr;
  330. }
  331. static void decode_munge(int type, wireval *val) {
  332. switch (type) {
  333. case UPB_DESCRIPTOR_TYPE_BOOL:
  334. val->bool_val = val->uint64_val != 0;
  335. break;
  336. case UPB_DESCRIPTOR_TYPE_SINT32: {
  337. uint32_t n = val->uint32_val;
  338. val->int32_val = (n >> 1) ^ -(int32_t)(n & 1);
  339. break;
  340. }
  341. case UPB_DESCRIPTOR_TYPE_SINT64: {
  342. uint64_t n = val->uint64_val;
  343. val->int64_val = (n >> 1) ^ -(int64_t)(n & 1);
  344. break;
  345. }
  346. }
  347. }
  348. static const upb_msglayout_field *upb_find_field(const upb_msglayout *l,
  349. uint32_t field_number) {
  350. static upb_msglayout_field none = {0};
  351. /* Lots of optimization opportunities here. */
  352. int i;
  353. if (l == NULL) return &none;
  354. for (i = 0; i < l->field_count; i++) {
  355. if (l->fields[i].number == field_number) {
  356. return &l->fields[i];
  357. }
  358. }
  359. return &none; /* Unknown field. */
  360. }
  361. static upb_msg *decode_newsubmsg(upb_decstate *d, const upb_msglayout *layout,
  362. const upb_msglayout_field *field) {
  363. const upb_msglayout *subl = layout->submsgs[field->submsg_index];
  364. return _upb_msg_new(subl, d->arena);
  365. }
  366. static void decode_tosubmsg(upb_decstate *d, upb_msg *submsg,
  367. const upb_msglayout *layout,
  368. const upb_msglayout_field *field, upb_strview val) {
  369. const upb_msglayout *subl = layout->submsgs[field->submsg_index];
  370. const char *saved_limit = d->limit;
  371. if (--d->depth < 0) decode_err(d);
  372. d->limit = val.data + val.size;
  373. decode_msg(d, val.data, submsg, subl);
  374. d->limit = saved_limit;
  375. if (d->end_group != 0) decode_err(d);
  376. d->depth++;
  377. }
  378. static const char *decode_group(upb_decstate *d, const char *ptr,
  379. upb_msg *submsg, const upb_msglayout *subl,
  380. uint32_t number) {
  381. if (--d->depth < 0) decode_err(d);
  382. ptr = decode_msg(d, ptr, submsg, subl);
  383. if (d->end_group != number) decode_err(d);
  384. d->end_group = 0;
  385. d->depth++;
  386. return ptr;
  387. }
  388. static const char *decode_togroup(upb_decstate *d, const char *ptr,
  389. upb_msg *submsg, const upb_msglayout *layout,
  390. const upb_msglayout_field *field) {
  391. const upb_msglayout *subl = layout->submsgs[field->submsg_index];
  392. return decode_group(d, ptr, submsg, subl, field->number);
  393. }
  394. static const char *decode_toarray(upb_decstate *d, const char *ptr,
  395. upb_msg *msg, const upb_msglayout *layout,
  396. const upb_msglayout_field *field, wireval val,
  397. int op) {
  398. upb_array **arrp = UPB_PTR_AT(msg, field->offset, void);
  399. upb_array *arr = *arrp;
  400. void *mem;
  401. if (!arr) {
  402. upb_fieldtype_t type = desctype_to_fieldtype[field->descriptortype];
  403. arr = _upb_array_new(d->arena, type);
  404. if (!arr) decode_err(d);
  405. *arrp = arr;
  406. }
  407. decode_reserve(d, arr, 1);
  408. switch (op) {
  409. case OP_SCALAR_LG2(0):
  410. case OP_SCALAR_LG2(2):
  411. case OP_SCALAR_LG2(3):
  412. /* Append scalar value. */
  413. mem = UPB_PTR_AT(_upb_array_ptr(arr), arr->len << op, void);
  414. arr->len++;
  415. memcpy(mem, &val, 1 << op);
  416. return ptr;
  417. case OP_STRING:
  418. /* Append string. */
  419. mem =
  420. UPB_PTR_AT(_upb_array_ptr(arr), arr->len * sizeof(upb_strview), void);
  421. arr->len++;
  422. memcpy(mem, &val, sizeof(upb_strview));
  423. return ptr;
  424. case OP_SUBMSG: {
  425. /* Append submessage / group. */
  426. upb_msg *submsg = decode_newsubmsg(d, layout, field);
  427. *UPB_PTR_AT(_upb_array_ptr(arr), arr->len * sizeof(void *), upb_msg *) =
  428. submsg;
  429. arr->len++;
  430. if (UPB_UNLIKELY(field->descriptortype == UPB_DTYPE_GROUP)) {
  431. ptr = decode_togroup(d, ptr, submsg, layout, field);
  432. } else {
  433. decode_tosubmsg(d, submsg, layout, field, val.str_val);
  434. }
  435. return ptr;
  436. }
  437. case OP_FIXPCK_LG2(2):
  438. case OP_FIXPCK_LG2(3): {
  439. /* Fixed packed. */
  440. int lg2 = op - OP_FIXPCK_LG2(0);
  441. int mask = (1 << lg2) - 1;
  442. int count = val.str_val.size >> lg2;
  443. if ((val.str_val.size & mask) != 0) {
  444. decode_err(d); /* Length isn't a round multiple of elem size. */
  445. }
  446. decode_reserve(d, arr, count);
  447. mem = UPB_PTR_AT(_upb_array_ptr(arr), arr->len << lg2, void);
  448. arr->len += count;
  449. memcpy(mem, val.str_val.data, count << op);
  450. return ptr;
  451. }
  452. case OP_VARPCK_LG2(0):
  453. case OP_VARPCK_LG2(2):
  454. case OP_VARPCK_LG2(3): {
  455. /* Varint packed. */
  456. int lg2 = op - OP_VARPCK_LG2(0);
  457. int scale = 1 << lg2;
  458. const char *ptr = val.str_val.data;
  459. const char *end = ptr + val.str_val.size;
  460. char *out = UPB_PTR_AT(_upb_array_ptr(arr), arr->len << lg2, void);
  461. while (ptr < end) {
  462. wireval elem;
  463. ptr = decode_varint64(d, ptr, end, &elem.uint64_val);
  464. decode_munge(field->descriptortype, &elem);
  465. if (decode_reserve(d, arr, 1)) {
  466. out = UPB_PTR_AT(_upb_array_ptr(arr), arr->len << lg2, void);
  467. }
  468. arr->len++;
  469. memcpy(out, &elem, scale);
  470. out += scale;
  471. }
  472. if (ptr != end) decode_err(d);
  473. return ptr;
  474. }
  475. default:
  476. UPB_UNREACHABLE();
  477. }
  478. }
  479. static void decode_tomap(upb_decstate *d, upb_msg *msg,
  480. const upb_msglayout *layout,
  481. const upb_msglayout_field *field, wireval val) {
  482. upb_map **map_p = UPB_PTR_AT(msg, field->offset, upb_map *);
  483. upb_map *map = *map_p;
  484. upb_map_entry ent;
  485. const upb_msglayout *entry = layout->submsgs[field->submsg_index];
  486. if (!map) {
  487. /* Lazily create map. */
  488. const upb_msglayout *entry = layout->submsgs[field->submsg_index];
  489. const upb_msglayout_field *key_field = &entry->fields[0];
  490. const upb_msglayout_field *val_field = &entry->fields[1];
  491. char key_size = desctype_to_mapsize[key_field->descriptortype];
  492. char val_size = desctype_to_mapsize[val_field->descriptortype];
  493. UPB_ASSERT(key_field->offset == 0);
  494. UPB_ASSERT(val_field->offset == sizeof(upb_strview));
  495. map = _upb_map_new(d->arena, key_size, val_size);
  496. *map_p = map;
  497. }
  498. /* Parse map entry. */
  499. memset(&ent, 0, sizeof(ent));
  500. if (entry->fields[1].descriptortype == UPB_DESCRIPTOR_TYPE_MESSAGE ||
  501. entry->fields[1].descriptortype == UPB_DESCRIPTOR_TYPE_GROUP) {
  502. /* Create proactively to handle the case where it doesn't appear. */
  503. ent.v.val.val = (uint64_t)_upb_msg_new(entry->submsgs[0], d->arena);
  504. }
  505. decode_tosubmsg(d, &ent.k, layout, field, val.str_val);
  506. /* Insert into map. */
  507. _upb_map_set(map, &ent.k, map->key_size, &ent.v, map->val_size, d->arena);
  508. }
  509. static const char *decode_tomsg(upb_decstate *d, const char *ptr, upb_msg *msg,
  510. const upb_msglayout *layout,
  511. const upb_msglayout_field *field, wireval val,
  512. int op) {
  513. void *mem = UPB_PTR_AT(msg, field->offset, void);
  514. int type = field->descriptortype;
  515. /* Set presence if necessary. */
  516. if (field->presence < 0) {
  517. /* Oneof case */
  518. *UPB_PTR_AT(msg, -field->presence, int32_t) = field->number;
  519. } else if (field->presence > 0) {
  520. /* Hasbit */
  521. uint32_t hasbit = field->presence;
  522. *UPB_PTR_AT(msg, hasbit / 8, uint8_t) |= (1 << (hasbit % 8));
  523. }
  524. /* Store into message. */
  525. switch (op) {
  526. case OP_SUBMSG: {
  527. upb_msg **submsgp = mem;
  528. upb_msg *submsg = *submsgp;
  529. if (!submsg) {
  530. submsg = decode_newsubmsg(d, layout, field);
  531. *submsgp = submsg;
  532. }
  533. if (UPB_UNLIKELY(type == UPB_DTYPE_GROUP)) {
  534. ptr = decode_togroup(d, ptr, submsg, layout, field);
  535. } else {
  536. decode_tosubmsg(d, submsg, layout, field, val.str_val);
  537. }
  538. break;
  539. }
  540. case OP_STRING:
  541. memcpy(mem, &val, sizeof(upb_strview));
  542. break;
  543. case OP_SCALAR_LG2(3):
  544. memcpy(mem, &val, 8);
  545. break;
  546. case OP_SCALAR_LG2(2):
  547. memcpy(mem, &val, 4);
  548. break;
  549. case OP_SCALAR_LG2(0):
  550. memcpy(mem, &val, 1);
  551. break;
  552. default:
  553. UPB_UNREACHABLE();
  554. }
  555. return ptr;
  556. }
  557. static const char *decode_msg(upb_decstate *d, const char *ptr, upb_msg *msg,
  558. const upb_msglayout *layout) {
  559. while (ptr < d->limit) {
  560. uint32_t tag;
  561. const upb_msglayout_field *field;
  562. int field_number;
  563. int wire_type;
  564. const char *field_start = ptr;
  565. wireval val;
  566. int op;
  567. ptr = decode_varint32(d, ptr, d->limit, &tag);
  568. field_number = tag >> 3;
  569. wire_type = tag & 7;
  570. field = upb_find_field(layout, field_number);
  571. switch (wire_type) {
  572. case UPB_WIRE_TYPE_VARINT:
  573. ptr = decode_varint64(d, ptr, d->limit, &val.uint64_val);
  574. op = varint_ops[field->descriptortype];
  575. decode_munge(field->descriptortype, &val);
  576. break;
  577. case UPB_WIRE_TYPE_32BIT:
  578. if (d->limit - ptr < 4) decode_err(d);
  579. memcpy(&val, ptr, 4);
  580. ptr += 4;
  581. op = OP_SCALAR_LG2(2);
  582. if (((1 << field->descriptortype) & fixed32_ok) == 0) goto unknown;
  583. break;
  584. case UPB_WIRE_TYPE_64BIT:
  585. if (d->limit - ptr < 8) decode_err(d);
  586. memcpy(&val, ptr, 8);
  587. ptr += 8;
  588. op = OP_SCALAR_LG2(3);
  589. if (((1 << field->descriptortype) & fixed64_ok) == 0) goto unknown;
  590. break;
  591. case UPB_WIRE_TYPE_DELIMITED: {
  592. uint32_t size;
  593. int ndx = field->descriptortype;
  594. if (_upb_isrepeated(field)) ndx += 18;
  595. ptr = decode_varint32(d, ptr, d->limit, &size);
  596. if (size >= INT32_MAX || (size_t)(d->limit - ptr) < size) {
  597. decode_err(d); /* Length overflow. */
  598. }
  599. val.str_val.data = ptr;
  600. val.str_val.size = size;
  601. ptr += size;
  602. op = delim_ops[ndx];
  603. break;
  604. }
  605. case UPB_WIRE_TYPE_START_GROUP:
  606. val.int32_val = field_number;
  607. op = OP_SUBMSG;
  608. if (field->descriptortype != UPB_DTYPE_GROUP) goto unknown;
  609. break;
  610. case UPB_WIRE_TYPE_END_GROUP:
  611. d->end_group = field_number;
  612. return ptr;
  613. default:
  614. decode_err(d);
  615. }
  616. if (op >= 0) {
  617. /* Parse, using op for dispatch. */
  618. switch (field->label) {
  619. case UPB_LABEL_REPEATED:
  620. case _UPB_LABEL_PACKED:
  621. ptr = decode_toarray(d, ptr, msg, layout, field, val, op);
  622. break;
  623. case _UPB_LABEL_MAP:
  624. decode_tomap(d, msg, layout, field, val);
  625. break;
  626. default:
  627. ptr = decode_tomsg(d, ptr, msg, layout, field, val, op);
  628. break;
  629. }
  630. } else {
  631. unknown:
  632. /* Skip unknown field. */
  633. if (field_number == 0) decode_err(d);
  634. if (wire_type == UPB_WIRE_TYPE_START_GROUP) {
  635. ptr = decode_group(d, ptr, NULL, NULL, field_number);
  636. }
  637. if (msg) {
  638. if (!_upb_msg_addunknown(msg, field_start, ptr - field_start,
  639. d->arena)) {
  640. decode_err(d);
  641. }
  642. }
  643. }
  644. }
  645. if (ptr != d->limit) decode_err(d);
  646. return ptr;
  647. }
  648. bool upb_decode(const char *buf, size_t size, void *msg, const upb_msglayout *l,
  649. upb_arena *arena) {
  650. upb_decstate state;
  651. state.limit = buf + size;
  652. state.arena = arena;
  653. state.depth = 64;
  654. state.end_group = 0;
  655. if (setjmp(state.err)) return false;
  656. if (size == 0) return true;
  657. decode_msg(&state, buf, msg, l);
  658. return state.end_group == 0;
  659. }
  660. #undef OP_SCALAR_LG2
  661. #undef OP_FIXPCK_LG2
  662. #undef OP_VARPCK_LG2
  663. #undef OP_STRING
  664. #undef OP_SUBMSG
  665. /* We encode backwards, to avoid pre-computing lengths (one-pass encode). */
  666. #include <string.h>
  667. #define UPB_PB_VARINT_MAX_LEN 10
  668. #define CHK(x) do { if (!(x)) { return false; } } while(0)
  669. static size_t upb_encode_varint(uint64_t val, char *buf) {
  670. size_t i;
  671. if (val < 128) { buf[0] = val; return 1; }
  672. i = 0;
  673. while (val) {
  674. uint8_t byte = val & 0x7fU;
  675. val >>= 7;
  676. if (val) byte |= 0x80U;
  677. buf[i++] = byte;
  678. }
  679. return i;
  680. }
  681. static uint32_t upb_zzencode_32(int32_t n) { return ((uint32_t)n << 1) ^ (n >> 31); }
  682. static uint64_t upb_zzencode_64(int64_t n) { return ((uint64_t)n << 1) ^ (n >> 63); }
  683. typedef struct {
  684. upb_alloc *alloc;
  685. char *buf, *ptr, *limit;
  686. } upb_encstate;
  687. static size_t upb_roundup_pow2(size_t bytes) {
  688. size_t ret = 128;
  689. while (ret < bytes) {
  690. ret *= 2;
  691. }
  692. return ret;
  693. }
  694. static bool upb_encode_growbuffer(upb_encstate *e, size_t bytes) {
  695. size_t old_size = e->limit - e->buf;
  696. size_t new_size = upb_roundup_pow2(bytes + (e->limit - e->ptr));
  697. char *new_buf = upb_realloc(e->alloc, e->buf, old_size, new_size);
  698. CHK(new_buf);
  699. /* We want previous data at the end, realloc() put it at the beginning. */
  700. if (old_size > 0) {
  701. memmove(new_buf + new_size - old_size, e->buf, old_size);
  702. }
  703. e->ptr = new_buf + new_size - (e->limit - e->ptr);
  704. e->limit = new_buf + new_size;
  705. e->buf = new_buf;
  706. return true;
  707. }
  708. /* Call to ensure that at least "bytes" bytes are available for writing at
  709. * e->ptr. Returns false if the bytes could not be allocated. */
  710. static bool upb_encode_reserve(upb_encstate *e, size_t bytes) {
  711. CHK(UPB_LIKELY((size_t)(e->ptr - e->buf) >= bytes) ||
  712. upb_encode_growbuffer(e, bytes));
  713. e->ptr -= bytes;
  714. return true;
  715. }
  716. /* Writes the given bytes to the buffer, handling reserve/advance. */
  717. static bool upb_put_bytes(upb_encstate *e, const void *data, size_t len) {
  718. if (len == 0) return true;
  719. CHK(upb_encode_reserve(e, len));
  720. memcpy(e->ptr, data, len);
  721. return true;
  722. }
  723. static bool upb_put_fixed64(upb_encstate *e, uint64_t val) {
  724. /* TODO(haberman): byte-swap for big endian. */
  725. return upb_put_bytes(e, &val, sizeof(uint64_t));
  726. }
  727. static bool upb_put_fixed32(upb_encstate *e, uint32_t val) {
  728. /* TODO(haberman): byte-swap for big endian. */
  729. return upb_put_bytes(e, &val, sizeof(uint32_t));
  730. }
  731. static bool upb_put_varint(upb_encstate *e, uint64_t val) {
  732. size_t len;
  733. char *start;
  734. CHK(upb_encode_reserve(e, UPB_PB_VARINT_MAX_LEN));
  735. len = upb_encode_varint(val, e->ptr);
  736. start = e->ptr + UPB_PB_VARINT_MAX_LEN - len;
  737. memmove(start, e->ptr, len);
  738. e->ptr = start;
  739. return true;
  740. }
  741. static bool upb_put_double(upb_encstate *e, double d) {
  742. uint64_t u64;
  743. UPB_ASSERT(sizeof(double) == sizeof(uint64_t));
  744. memcpy(&u64, &d, sizeof(uint64_t));
  745. return upb_put_fixed64(e, u64);
  746. }
  747. static bool upb_put_float(upb_encstate *e, float d) {
  748. uint32_t u32;
  749. UPB_ASSERT(sizeof(float) == sizeof(uint32_t));
  750. memcpy(&u32, &d, sizeof(uint32_t));
  751. return upb_put_fixed32(e, u32);
  752. }
  753. static uint32_t upb_readcase(const char *msg, const upb_msglayout_field *f) {
  754. uint32_t ret;
  755. memcpy(&ret, msg - f->presence, sizeof(ret));
  756. return ret;
  757. }
  758. static bool upb_readhasbit(const char *msg, const upb_msglayout_field *f) {
  759. uint32_t hasbit = f->presence;
  760. UPB_ASSERT(f->presence > 0);
  761. return (*UPB_PTR_AT(msg, hasbit / 8, uint8_t)) & (1 << (hasbit % 8));
  762. }
  763. static bool upb_put_tag(upb_encstate *e, int field_number, int wire_type) {
  764. return upb_put_varint(e, (field_number << 3) | wire_type);
  765. }
  766. static bool upb_put_fixedarray(upb_encstate *e, const upb_array *arr,
  767. size_t elem_size, uint32_t tag) {
  768. size_t bytes = arr->len * elem_size;
  769. const char* data = _upb_array_constptr(arr);
  770. const char* ptr = data + bytes - elem_size;
  771. if (tag) {
  772. while (true) {
  773. CHK(upb_put_bytes(e, ptr, elem_size) && upb_put_varint(e, tag));
  774. if (ptr == data) break;
  775. ptr -= elem_size;
  776. }
  777. return true;
  778. } else {
  779. return upb_put_bytes(e, data, bytes) && upb_put_varint(e, bytes);
  780. }
  781. }
  782. bool upb_encode_message(upb_encstate *e, const char *msg,
  783. const upb_msglayout *m, size_t *size);
  784. static bool upb_encode_scalarfield(upb_encstate *e, const void *_field_mem,
  785. const upb_msglayout *m,
  786. const upb_msglayout_field *f,
  787. bool skip_zero_value) {
  788. const char *field_mem = _field_mem;
  789. #define CASE(ctype, type, wire_type, encodeval) do { \
  790. ctype val = *(ctype*)field_mem; \
  791. if (skip_zero_value && val == 0) { \
  792. return true; \
  793. } \
  794. return upb_put_ ## type(e, encodeval) && \
  795. upb_put_tag(e, f->number, wire_type); \
  796. } while(0)
  797. switch (f->descriptortype) {
  798. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  799. CASE(double, double, UPB_WIRE_TYPE_64BIT, val);
  800. case UPB_DESCRIPTOR_TYPE_FLOAT:
  801. CASE(float, float, UPB_WIRE_TYPE_32BIT, val);
  802. case UPB_DESCRIPTOR_TYPE_INT64:
  803. case UPB_DESCRIPTOR_TYPE_UINT64:
  804. CASE(uint64_t, varint, UPB_WIRE_TYPE_VARINT, val);
  805. case UPB_DESCRIPTOR_TYPE_UINT32:
  806. CASE(uint32_t, varint, UPB_WIRE_TYPE_VARINT, val);
  807. case UPB_DESCRIPTOR_TYPE_INT32:
  808. case UPB_DESCRIPTOR_TYPE_ENUM:
  809. CASE(int32_t, varint, UPB_WIRE_TYPE_VARINT, (int64_t)val);
  810. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  811. case UPB_DESCRIPTOR_TYPE_FIXED64:
  812. CASE(uint64_t, fixed64, UPB_WIRE_TYPE_64BIT, val);
  813. case UPB_DESCRIPTOR_TYPE_FIXED32:
  814. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  815. CASE(uint32_t, fixed32, UPB_WIRE_TYPE_32BIT, val);
  816. case UPB_DESCRIPTOR_TYPE_BOOL:
  817. CASE(bool, varint, UPB_WIRE_TYPE_VARINT, val);
  818. case UPB_DESCRIPTOR_TYPE_SINT32:
  819. CASE(int32_t, varint, UPB_WIRE_TYPE_VARINT, upb_zzencode_32(val));
  820. case UPB_DESCRIPTOR_TYPE_SINT64:
  821. CASE(int64_t, varint, UPB_WIRE_TYPE_VARINT, upb_zzencode_64(val));
  822. case UPB_DESCRIPTOR_TYPE_STRING:
  823. case UPB_DESCRIPTOR_TYPE_BYTES: {
  824. upb_strview view = *(upb_strview*)field_mem;
  825. if (skip_zero_value && view.size == 0) {
  826. return true;
  827. }
  828. return upb_put_bytes(e, view.data, view.size) &&
  829. upb_put_varint(e, view.size) &&
  830. upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED);
  831. }
  832. case UPB_DESCRIPTOR_TYPE_GROUP: {
  833. size_t size;
  834. void *submsg = *(void **)field_mem;
  835. const upb_msglayout *subm = m->submsgs[f->submsg_index];
  836. if (submsg == NULL) {
  837. return true;
  838. }
  839. return upb_put_tag(e, f->number, UPB_WIRE_TYPE_END_GROUP) &&
  840. upb_encode_message(e, submsg, subm, &size) &&
  841. upb_put_tag(e, f->number, UPB_WIRE_TYPE_START_GROUP);
  842. }
  843. case UPB_DESCRIPTOR_TYPE_MESSAGE: {
  844. size_t size;
  845. void *submsg = *(void **)field_mem;
  846. const upb_msglayout *subm = m->submsgs[f->submsg_index];
  847. if (submsg == NULL) {
  848. return true;
  849. }
  850. return upb_encode_message(e, submsg, subm, &size) &&
  851. upb_put_varint(e, size) &&
  852. upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED);
  853. }
  854. }
  855. #undef CASE
  856. UPB_UNREACHABLE();
  857. }
  858. static bool upb_encode_array(upb_encstate *e, const char *field_mem,
  859. const upb_msglayout *m,
  860. const upb_msglayout_field *f) {
  861. const upb_array *arr = *(const upb_array**)field_mem;
  862. bool packed = f->label == _UPB_LABEL_PACKED;
  863. if (arr == NULL || arr->len == 0) {
  864. return true;
  865. }
  866. #define VARINT_CASE(ctype, encode) \
  867. { \
  868. const ctype *start = _upb_array_constptr(arr); \
  869. const ctype *ptr = start + arr->len; \
  870. size_t pre_len = e->limit - e->ptr; \
  871. uint32_t tag = packed ? 0 : (f->number << 3) | UPB_WIRE_TYPE_VARINT; \
  872. do { \
  873. ptr--; \
  874. CHK(upb_put_varint(e, encode)); \
  875. if (tag) CHK(upb_put_varint(e, tag)); \
  876. } while (ptr != start); \
  877. if (!tag) CHK(upb_put_varint(e, e->limit - e->ptr - pre_len)); \
  878. } \
  879. break; \
  880. do { \
  881. ; \
  882. } while (0)
  883. #define TAG(wire_type) (packed ? 0 : (f->number << 3 | wire_type))
  884. switch (f->descriptortype) {
  885. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  886. CHK(upb_put_fixedarray(e, arr, sizeof(double), TAG(UPB_WIRE_TYPE_64BIT)));
  887. break;
  888. case UPB_DESCRIPTOR_TYPE_FLOAT:
  889. CHK(upb_put_fixedarray(e, arr, sizeof(float), TAG(UPB_WIRE_TYPE_32BIT)));
  890. break;
  891. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  892. case UPB_DESCRIPTOR_TYPE_FIXED64:
  893. CHK(upb_put_fixedarray(e, arr, sizeof(uint64_t), TAG(UPB_WIRE_TYPE_64BIT)));
  894. break;
  895. case UPB_DESCRIPTOR_TYPE_FIXED32:
  896. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  897. CHK(upb_put_fixedarray(e, arr, sizeof(uint32_t), TAG(UPB_WIRE_TYPE_32BIT)));
  898. break;
  899. case UPB_DESCRIPTOR_TYPE_INT64:
  900. case UPB_DESCRIPTOR_TYPE_UINT64:
  901. VARINT_CASE(uint64_t, *ptr);
  902. case UPB_DESCRIPTOR_TYPE_UINT32:
  903. VARINT_CASE(uint32_t, *ptr);
  904. case UPB_DESCRIPTOR_TYPE_INT32:
  905. case UPB_DESCRIPTOR_TYPE_ENUM:
  906. VARINT_CASE(int32_t, (int64_t)*ptr);
  907. case UPB_DESCRIPTOR_TYPE_BOOL:
  908. VARINT_CASE(bool, *ptr);
  909. case UPB_DESCRIPTOR_TYPE_SINT32:
  910. VARINT_CASE(int32_t, upb_zzencode_32(*ptr));
  911. case UPB_DESCRIPTOR_TYPE_SINT64:
  912. VARINT_CASE(int64_t, upb_zzencode_64(*ptr));
  913. case UPB_DESCRIPTOR_TYPE_STRING:
  914. case UPB_DESCRIPTOR_TYPE_BYTES: {
  915. const upb_strview *start = _upb_array_constptr(arr);
  916. const upb_strview *ptr = start + arr->len;
  917. do {
  918. ptr--;
  919. CHK(upb_put_bytes(e, ptr->data, ptr->size) &&
  920. upb_put_varint(e, ptr->size) &&
  921. upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
  922. } while (ptr != start);
  923. return true;
  924. }
  925. case UPB_DESCRIPTOR_TYPE_GROUP: {
  926. const void *const*start = _upb_array_constptr(arr);
  927. const void *const*ptr = start + arr->len;
  928. const upb_msglayout *subm = m->submsgs[f->submsg_index];
  929. do {
  930. size_t size;
  931. ptr--;
  932. CHK(upb_put_tag(e, f->number, UPB_WIRE_TYPE_END_GROUP) &&
  933. upb_encode_message(e, *ptr, subm, &size) &&
  934. upb_put_tag(e, f->number, UPB_WIRE_TYPE_START_GROUP));
  935. } while (ptr != start);
  936. return true;
  937. }
  938. case UPB_DESCRIPTOR_TYPE_MESSAGE: {
  939. const void *const*start = _upb_array_constptr(arr);
  940. const void *const*ptr = start + arr->len;
  941. const upb_msglayout *subm = m->submsgs[f->submsg_index];
  942. do {
  943. size_t size;
  944. ptr--;
  945. CHK(upb_encode_message(e, *ptr, subm, &size) &&
  946. upb_put_varint(e, size) &&
  947. upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
  948. } while (ptr != start);
  949. return true;
  950. }
  951. }
  952. #undef VARINT_CASE
  953. if (packed) {
  954. CHK(upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
  955. }
  956. return true;
  957. }
  958. static bool upb_encode_map(upb_encstate *e, const char *field_mem,
  959. const upb_msglayout *m,
  960. const upb_msglayout_field *f) {
  961. const upb_map *map = *(const upb_map**)field_mem;
  962. const upb_msglayout *entry = m->submsgs[f->submsg_index];
  963. const upb_msglayout_field *key_field = &entry->fields[0];
  964. const upb_msglayout_field *val_field = &entry->fields[1];
  965. upb_strtable_iter i;
  966. if (map == NULL) {
  967. return true;
  968. }
  969. upb_strtable_begin(&i, &map->table);
  970. for(; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  971. size_t pre_len = e->limit - e->ptr;
  972. size_t size;
  973. upb_strview key = upb_strtable_iter_key(&i);
  974. const upb_value val = upb_strtable_iter_value(&i);
  975. const void *keyp =
  976. map->key_size == UPB_MAPTYPE_STRING ? (void *)&key : key.data;
  977. const void *valp =
  978. map->val_size == UPB_MAPTYPE_STRING ? upb_value_getptr(val) : &val;
  979. CHK(upb_encode_scalarfield(e, valp, entry, val_field, false));
  980. CHK(upb_encode_scalarfield(e, keyp, entry, key_field, false));
  981. size = (e->limit - e->ptr) - pre_len;
  982. CHK(upb_put_varint(e, size));
  983. CHK(upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
  984. }
  985. return true;
  986. }
  987. bool upb_encode_message(upb_encstate *e, const char *msg,
  988. const upb_msglayout *m, size_t *size) {
  989. int i;
  990. size_t pre_len = e->limit - e->ptr;
  991. const char *unknown;
  992. size_t unknown_size;
  993. unknown = upb_msg_getunknown(msg, &unknown_size);
  994. if (unknown) {
  995. upb_put_bytes(e, unknown, unknown_size);
  996. }
  997. for (i = m->field_count - 1; i >= 0; i--) {
  998. const upb_msglayout_field *f = &m->fields[i];
  999. if (_upb_isrepeated(f)) {
  1000. CHK(upb_encode_array(e, msg + f->offset, m, f));
  1001. } else if (f->label == _UPB_LABEL_MAP) {
  1002. CHK(upb_encode_map(e, msg + f->offset, m, f));
  1003. } else {
  1004. bool skip_empty = false;
  1005. if (f->presence == 0) {
  1006. /* Proto3 presence. */
  1007. skip_empty = true;
  1008. } else if (f->presence > 0) {
  1009. /* Proto2 presence: hasbit. */
  1010. if (!upb_readhasbit(msg, f)) {
  1011. continue;
  1012. }
  1013. } else {
  1014. /* Field is in a oneof. */
  1015. if (upb_readcase(msg, f) != f->number) {
  1016. continue;
  1017. }
  1018. }
  1019. CHK(upb_encode_scalarfield(e, msg + f->offset, m, f, skip_empty));
  1020. }
  1021. }
  1022. *size = (e->limit - e->ptr) - pre_len;
  1023. return true;
  1024. }
  1025. char *upb_encode(const void *msg, const upb_msglayout *m, upb_arena *arena,
  1026. size_t *size) {
  1027. upb_encstate e;
  1028. e.alloc = upb_arena_alloc(arena);
  1029. e.buf = NULL;
  1030. e.limit = NULL;
  1031. e.ptr = NULL;
  1032. if (!upb_encode_message(&e, msg, m, size)) {
  1033. *size = 0;
  1034. return NULL;
  1035. }
  1036. *size = e.limit - e.ptr;
  1037. if (*size == 0) {
  1038. static char ch;
  1039. return &ch;
  1040. } else {
  1041. UPB_ASSERT(e.ptr);
  1042. return e.ptr;
  1043. }
  1044. }
  1045. #undef CHK
  1046. /** upb_msg *******************************************************************/
  1047. static const char _upb_fieldtype_to_sizelg2[12] = {
  1048. 0,
  1049. 0, /* UPB_TYPE_BOOL */
  1050. 2, /* UPB_TYPE_FLOAT */
  1051. 2, /* UPB_TYPE_INT32 */
  1052. 2, /* UPB_TYPE_UINT32 */
  1053. 2, /* UPB_TYPE_ENUM */
  1054. UPB_SIZE(2, 3), /* UPB_TYPE_MESSAGE */
  1055. 3, /* UPB_TYPE_DOUBLE */
  1056. 3, /* UPB_TYPE_INT64 */
  1057. 3, /* UPB_TYPE_UINT64 */
  1058. UPB_SIZE(3, 4), /* UPB_TYPE_STRING */
  1059. UPB_SIZE(3, 4), /* UPB_TYPE_BYTES */
  1060. };
  1061. static uintptr_t tag_arrptr(void* ptr, int elem_size_lg2) {
  1062. UPB_ASSERT(elem_size_lg2 <= 4);
  1063. return (uintptr_t)ptr | elem_size_lg2;
  1064. }
  1065. static int upb_msg_internalsize(const upb_msglayout *l) {
  1066. return sizeof(upb_msg_internal) - l->extendable * sizeof(void *);
  1067. }
  1068. static size_t upb_msg_sizeof(const upb_msglayout *l) {
  1069. return l->size + upb_msg_internalsize(l);
  1070. }
  1071. static upb_msg_internal *upb_msg_getinternal(upb_msg *msg) {
  1072. return UPB_PTR_AT(msg, -sizeof(upb_msg_internal), upb_msg_internal);
  1073. }
  1074. static const upb_msg_internal *upb_msg_getinternal_const(const upb_msg *msg) {
  1075. return UPB_PTR_AT(msg, -sizeof(upb_msg_internal), upb_msg_internal);
  1076. }
  1077. static upb_msg_internal_withext *upb_msg_getinternalwithext(
  1078. upb_msg *msg, const upb_msglayout *l) {
  1079. UPB_ASSERT(l->extendable);
  1080. return UPB_PTR_AT(msg, -sizeof(upb_msg_internal_withext),
  1081. upb_msg_internal_withext);
  1082. }
  1083. upb_msg *_upb_msg_new(const upb_msglayout *l, upb_arena *a) {
  1084. void *mem = upb_arena_malloc(a, upb_msg_sizeof(l));
  1085. upb_msg_internal *in;
  1086. upb_msg *msg;
  1087. if (!mem) {
  1088. return NULL;
  1089. }
  1090. msg = UPB_PTR_AT(mem, upb_msg_internalsize(l), upb_msg);
  1091. /* Initialize normal members. */
  1092. memset(msg, 0, l->size);
  1093. /* Initialize internal members. */
  1094. in = upb_msg_getinternal(msg);
  1095. in->unknown = NULL;
  1096. in->unknown_len = 0;
  1097. in->unknown_size = 0;
  1098. if (l->extendable) {
  1099. upb_msg_getinternalwithext(msg, l)->extdict = NULL;
  1100. }
  1101. return msg;
  1102. }
  1103. bool _upb_msg_addunknown(upb_msg *msg, const char *data, size_t len,
  1104. upb_arena *arena) {
  1105. upb_msg_internal *in = upb_msg_getinternal(msg);
  1106. if (len > in->unknown_size - in->unknown_len) {
  1107. upb_alloc *alloc = upb_arena_alloc(arena);
  1108. size_t need = in->unknown_size + len;
  1109. size_t newsize = UPB_MAX(in->unknown_size * 2, need);
  1110. void *mem = upb_realloc(alloc, in->unknown, in->unknown_size, newsize);
  1111. if (!mem) return false;
  1112. in->unknown = mem;
  1113. in->unknown_size = newsize;
  1114. }
  1115. memcpy(in->unknown + in->unknown_len, data, len);
  1116. in->unknown_len += len;
  1117. return true;
  1118. }
  1119. const char *upb_msg_getunknown(const upb_msg *msg, size_t *len) {
  1120. const upb_msg_internal *in = upb_msg_getinternal_const(msg);
  1121. *len = in->unknown_len;
  1122. return in->unknown;
  1123. }
  1124. /** upb_array *****************************************************************/
  1125. upb_array *_upb_array_new(upb_arena *a, upb_fieldtype_t type) {
  1126. upb_array *arr = upb_arena_malloc(a, sizeof(upb_array));
  1127. if (!arr) {
  1128. return NULL;
  1129. }
  1130. arr->data = tag_arrptr(NULL, _upb_fieldtype_to_sizelg2[type]);
  1131. arr->len = 0;
  1132. arr->size = 0;
  1133. return arr;
  1134. }
  1135. bool _upb_array_realloc(upb_array *arr, size_t min_size, upb_arena *arena) {
  1136. size_t new_size = UPB_MAX(arr->size, 4);
  1137. int elem_size_lg2 = arr->data & 7;
  1138. size_t old_bytes = arr->size << elem_size_lg2;
  1139. size_t new_bytes;
  1140. void* ptr = _upb_array_ptr(arr);
  1141. /* Log2 ceiling of size. */
  1142. while (new_size < min_size) new_size *= 2;
  1143. new_bytes = new_size << elem_size_lg2;
  1144. ptr = upb_arena_realloc(arena, ptr, old_bytes, new_bytes);
  1145. if (!ptr) {
  1146. return false;
  1147. }
  1148. arr->data = tag_arrptr(ptr, elem_size_lg2);
  1149. arr->size = new_size;
  1150. return true;
  1151. }
  1152. static upb_array *getorcreate_array(upb_array **arr_ptr, upb_fieldtype_t type,
  1153. upb_arena *arena) {
  1154. upb_array *arr = *arr_ptr;
  1155. if (!arr) {
  1156. arr = _upb_array_new(arena, type);
  1157. if (!arr) return NULL;
  1158. *arr_ptr = arr;
  1159. }
  1160. return arr;
  1161. }
  1162. static bool resize_array(upb_array *arr, size_t size, upb_arena *arena) {
  1163. if (size > arr->size && !_upb_array_realloc(arr, size, arena)) {
  1164. return false;
  1165. }
  1166. arr->len = size;
  1167. return true;
  1168. }
  1169. void *_upb_array_resize_fallback(upb_array **arr_ptr, size_t size,
  1170. upb_fieldtype_t type, upb_arena *arena) {
  1171. upb_array *arr = getorcreate_array(arr_ptr, type, arena);
  1172. return arr && resize_array(arr, size, arena) ? _upb_array_ptr(arr) : NULL;
  1173. }
  1174. bool _upb_array_append_fallback(upb_array **arr_ptr, const void *value,
  1175. upb_fieldtype_t type, upb_arena *arena) {
  1176. upb_array *arr = getorcreate_array(arr_ptr, type, arena);
  1177. size_t elem = arr->len;
  1178. int lg2 = _upb_fieldtype_to_sizelg2[type];
  1179. char *data;
  1180. if (!arr || !resize_array(arr, elem + 1, arena)) return false;
  1181. data = _upb_array_ptr(arr);
  1182. memcpy(data + (elem << lg2), value, 1 << lg2);
  1183. return true;
  1184. }
  1185. /** upb_map *******************************************************************/
  1186. upb_map *_upb_map_new(upb_arena *a, size_t key_size, size_t value_size) {
  1187. upb_map *map = upb_arena_malloc(a, sizeof(upb_map));
  1188. if (!map) {
  1189. return NULL;
  1190. }
  1191. upb_strtable_init2(&map->table, UPB_CTYPE_INT32, upb_arena_alloc(a));
  1192. map->key_size = key_size;
  1193. map->val_size = value_size;
  1194. return map;
  1195. }
  1196. /*
  1197. ** upb_table Implementation
  1198. **
  1199. ** Implementation is heavily inspired by Lua's ltable.c.
  1200. */
  1201. #include <string.h>
  1202. #define UPB_MAXARRSIZE 16 /* 64k. */
  1203. /* From Chromium. */
  1204. #define ARRAY_SIZE(x) \
  1205. ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x])))))
  1206. static const double MAX_LOAD = 0.85;
  1207. /* The minimum utilization of the array part of a mixed hash/array table. This
  1208. * is a speed/memory-usage tradeoff (though it's not straightforward because of
  1209. * cache effects). The lower this is, the more memory we'll use. */
  1210. static const double MIN_DENSITY = 0.1;
  1211. bool is_pow2(uint64_t v) { return v == 0 || (v & (v - 1)) == 0; }
  1212. int log2ceil(uint64_t v) {
  1213. int ret = 0;
  1214. bool pow2 = is_pow2(v);
  1215. while (v >>= 1) ret++;
  1216. ret = pow2 ? ret : ret + 1; /* Ceiling. */
  1217. return UPB_MIN(UPB_MAXARRSIZE, ret);
  1218. }
  1219. char *upb_strdup(const char *s, upb_alloc *a) {
  1220. return upb_strdup2(s, strlen(s), a);
  1221. }
  1222. char *upb_strdup2(const char *s, size_t len, upb_alloc *a) {
  1223. size_t n;
  1224. char *p;
  1225. /* Prevent overflow errors. */
  1226. if (len == SIZE_MAX) return NULL;
  1227. /* Always null-terminate, even if binary data; but don't rely on the input to
  1228. * have a null-terminating byte since it may be a raw binary buffer. */
  1229. n = len + 1;
  1230. p = upb_malloc(a, n);
  1231. if (p) {
  1232. memcpy(p, s, len);
  1233. p[len] = 0;
  1234. }
  1235. return p;
  1236. }
  1237. /* A type to represent the lookup key of either a strtable or an inttable. */
  1238. typedef union {
  1239. uintptr_t num;
  1240. struct {
  1241. const char *str;
  1242. size_t len;
  1243. } str;
  1244. } lookupkey_t;
  1245. static lookupkey_t strkey2(const char *str, size_t len) {
  1246. lookupkey_t k;
  1247. k.str.str = str;
  1248. k.str.len = len;
  1249. return k;
  1250. }
  1251. static lookupkey_t intkey(uintptr_t key) {
  1252. lookupkey_t k;
  1253. k.num = key;
  1254. return k;
  1255. }
  1256. typedef uint32_t hashfunc_t(upb_tabkey key);
  1257. typedef bool eqlfunc_t(upb_tabkey k1, lookupkey_t k2);
  1258. /* Base table (shared code) ***************************************************/
  1259. /* For when we need to cast away const. */
  1260. static upb_tabent *mutable_entries(upb_table *t) {
  1261. return (upb_tabent*)t->entries;
  1262. }
  1263. static bool isfull(upb_table *t) {
  1264. if (upb_table_size(t) == 0) {
  1265. return true;
  1266. } else {
  1267. return ((double)(t->count + 1) / upb_table_size(t)) > MAX_LOAD;
  1268. }
  1269. }
  1270. static bool init(upb_table *t, uint8_t size_lg2, upb_alloc *a) {
  1271. size_t bytes;
  1272. t->count = 0;
  1273. t->size_lg2 = size_lg2;
  1274. t->mask = upb_table_size(t) ? upb_table_size(t) - 1 : 0;
  1275. bytes = upb_table_size(t) * sizeof(upb_tabent);
  1276. if (bytes > 0) {
  1277. t->entries = upb_malloc(a, bytes);
  1278. if (!t->entries) return false;
  1279. memset(mutable_entries(t), 0, bytes);
  1280. } else {
  1281. t->entries = NULL;
  1282. }
  1283. return true;
  1284. }
  1285. static void uninit(upb_table *t, upb_alloc *a) {
  1286. upb_free(a, mutable_entries(t));
  1287. }
  1288. static upb_tabent *emptyent(upb_table *t) {
  1289. upb_tabent *e = mutable_entries(t) + upb_table_size(t);
  1290. while (1) { if (upb_tabent_isempty(--e)) return e; UPB_ASSERT(e > t->entries); }
  1291. }
  1292. static upb_tabent *getentry_mutable(upb_table *t, uint32_t hash) {
  1293. return (upb_tabent*)upb_getentry(t, hash);
  1294. }
  1295. static const upb_tabent *findentry(const upb_table *t, lookupkey_t key,
  1296. uint32_t hash, eqlfunc_t *eql) {
  1297. const upb_tabent *e;
  1298. if (t->size_lg2 == 0) return NULL;
  1299. e = upb_getentry(t, hash);
  1300. if (upb_tabent_isempty(e)) return NULL;
  1301. while (1) {
  1302. if (eql(e->key, key)) return e;
  1303. if ((e = e->next) == NULL) return NULL;
  1304. }
  1305. }
  1306. static upb_tabent *findentry_mutable(upb_table *t, lookupkey_t key,
  1307. uint32_t hash, eqlfunc_t *eql) {
  1308. return (upb_tabent*)findentry(t, key, hash, eql);
  1309. }
  1310. static bool lookup(const upb_table *t, lookupkey_t key, upb_value *v,
  1311. uint32_t hash, eqlfunc_t *eql) {
  1312. const upb_tabent *e = findentry(t, key, hash, eql);
  1313. if (e) {
  1314. if (v) {
  1315. _upb_value_setval(v, e->val.val);
  1316. }
  1317. return true;
  1318. } else {
  1319. return false;
  1320. }
  1321. }
  1322. /* The given key must not already exist in the table. */
  1323. static void insert(upb_table *t, lookupkey_t key, upb_tabkey tabkey,
  1324. upb_value val, uint32_t hash,
  1325. hashfunc_t *hashfunc, eqlfunc_t *eql) {
  1326. upb_tabent *mainpos_e;
  1327. upb_tabent *our_e;
  1328. UPB_ASSERT(findentry(t, key, hash, eql) == NULL);
  1329. t->count++;
  1330. mainpos_e = getentry_mutable(t, hash);
  1331. our_e = mainpos_e;
  1332. if (upb_tabent_isempty(mainpos_e)) {
  1333. /* Our main position is empty; use it. */
  1334. our_e->next = NULL;
  1335. } else {
  1336. /* Collision. */
  1337. upb_tabent *new_e = emptyent(t);
  1338. /* Head of collider's chain. */
  1339. upb_tabent *chain = getentry_mutable(t, hashfunc(mainpos_e->key));
  1340. if (chain == mainpos_e) {
  1341. /* Existing ent is in its main posisiton (it has the same hash as us, and
  1342. * is the head of our chain). Insert to new ent and append to this chain. */
  1343. new_e->next = mainpos_e->next;
  1344. mainpos_e->next = new_e;
  1345. our_e = new_e;
  1346. } else {
  1347. /* Existing ent is not in its main position (it is a node in some other
  1348. * chain). This implies that no existing ent in the table has our hash.
  1349. * Evict it (updating its chain) and use its ent for head of our chain. */
  1350. *new_e = *mainpos_e; /* copies next. */
  1351. while (chain->next != mainpos_e) {
  1352. chain = (upb_tabent*)chain->next;
  1353. UPB_ASSERT(chain);
  1354. }
  1355. chain->next = new_e;
  1356. our_e = mainpos_e;
  1357. our_e->next = NULL;
  1358. }
  1359. }
  1360. our_e->key = tabkey;
  1361. our_e->val.val = val.val;
  1362. UPB_ASSERT(findentry(t, key, hash, eql) == our_e);
  1363. }
  1364. static bool rm(upb_table *t, lookupkey_t key, upb_value *val,
  1365. upb_tabkey *removed, uint32_t hash, eqlfunc_t *eql) {
  1366. upb_tabent *chain = getentry_mutable(t, hash);
  1367. if (upb_tabent_isempty(chain)) return false;
  1368. if (eql(chain->key, key)) {
  1369. /* Element to remove is at the head of its chain. */
  1370. t->count--;
  1371. if (val) _upb_value_setval(val, chain->val.val);
  1372. if (removed) *removed = chain->key;
  1373. if (chain->next) {
  1374. upb_tabent *move = (upb_tabent*)chain->next;
  1375. *chain = *move;
  1376. move->key = 0; /* Make the slot empty. */
  1377. } else {
  1378. chain->key = 0; /* Make the slot empty. */
  1379. }
  1380. return true;
  1381. } else {
  1382. /* Element to remove is either in a non-head position or not in the
  1383. * table. */
  1384. while (chain->next && !eql(chain->next->key, key)) {
  1385. chain = (upb_tabent*)chain->next;
  1386. }
  1387. if (chain->next) {
  1388. /* Found element to remove. */
  1389. upb_tabent *rm = (upb_tabent*)chain->next;
  1390. t->count--;
  1391. if (val) _upb_value_setval(val, chain->next->val.val);
  1392. if (removed) *removed = rm->key;
  1393. rm->key = 0; /* Make the slot empty. */
  1394. chain->next = rm->next;
  1395. return true;
  1396. } else {
  1397. /* Element to remove is not in the table. */
  1398. return false;
  1399. }
  1400. }
  1401. }
  1402. static size_t next(const upb_table *t, size_t i) {
  1403. do {
  1404. if (++i >= upb_table_size(t))
  1405. return SIZE_MAX;
  1406. } while(upb_tabent_isempty(&t->entries[i]));
  1407. return i;
  1408. }
  1409. static size_t begin(const upb_table *t) {
  1410. return next(t, -1);
  1411. }
  1412. /* upb_strtable ***************************************************************/
  1413. /* A simple "subclass" of upb_table that only adds a hash function for strings. */
  1414. static upb_tabkey strcopy(lookupkey_t k2, upb_alloc *a) {
  1415. uint32_t len = (uint32_t) k2.str.len;
  1416. char *str = upb_malloc(a, k2.str.len + sizeof(uint32_t) + 1);
  1417. if (str == NULL) return 0;
  1418. memcpy(str, &len, sizeof(uint32_t));
  1419. memcpy(str + sizeof(uint32_t), k2.str.str, k2.str.len);
  1420. str[sizeof(uint32_t) + k2.str.len] = '\0';
  1421. return (uintptr_t)str;
  1422. }
  1423. static uint32_t strhash(upb_tabkey key) {
  1424. uint32_t len;
  1425. char *str = upb_tabstr(key, &len);
  1426. return upb_murmur_hash2(str, len, 0);
  1427. }
  1428. static bool streql(upb_tabkey k1, lookupkey_t k2) {
  1429. uint32_t len;
  1430. char *str = upb_tabstr(k1, &len);
  1431. return len == k2.str.len && memcmp(str, k2.str.str, len) == 0;
  1432. }
  1433. bool upb_strtable_init2(upb_strtable *t, upb_ctype_t ctype, upb_alloc *a) {
  1434. return init(&t->t, 2, a);
  1435. }
  1436. void upb_strtable_clear(upb_strtable *t) {
  1437. size_t bytes = upb_table_size(&t->t) * sizeof(upb_tabent);
  1438. t->t.count = 0;
  1439. memset((char*)t->t.entries, 0, bytes);
  1440. }
  1441. void upb_strtable_uninit2(upb_strtable *t, upb_alloc *a) {
  1442. size_t i;
  1443. for (i = 0; i < upb_table_size(&t->t); i++)
  1444. upb_free(a, (void*)t->t.entries[i].key);
  1445. uninit(&t->t, a);
  1446. }
  1447. bool upb_strtable_resize(upb_strtable *t, size_t size_lg2, upb_alloc *a) {
  1448. upb_strtable new_table;
  1449. upb_strtable_iter i;
  1450. if (!init(&new_table.t, size_lg2, a))
  1451. return false;
  1452. upb_strtable_begin(&i, t);
  1453. for ( ; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  1454. upb_strview key = upb_strtable_iter_key(&i);
  1455. upb_strtable_insert3(
  1456. &new_table, key.data, key.size,
  1457. upb_strtable_iter_value(&i), a);
  1458. }
  1459. upb_strtable_uninit2(t, a);
  1460. *t = new_table;
  1461. return true;
  1462. }
  1463. bool upb_strtable_insert3(upb_strtable *t, const char *k, size_t len,
  1464. upb_value v, upb_alloc *a) {
  1465. lookupkey_t key;
  1466. upb_tabkey tabkey;
  1467. uint32_t hash;
  1468. if (isfull(&t->t)) {
  1469. /* Need to resize. New table of double the size, add old elements to it. */
  1470. if (!upb_strtable_resize(t, t->t.size_lg2 + 1, a)) {
  1471. return false;
  1472. }
  1473. }
  1474. key = strkey2(k, len);
  1475. tabkey = strcopy(key, a);
  1476. if (tabkey == 0) return false;
  1477. hash = upb_murmur_hash2(key.str.str, key.str.len, 0);
  1478. insert(&t->t, key, tabkey, v, hash, &strhash, &streql);
  1479. return true;
  1480. }
  1481. bool upb_strtable_lookup2(const upb_strtable *t, const char *key, size_t len,
  1482. upb_value *v) {
  1483. uint32_t hash = upb_murmur_hash2(key, len, 0);
  1484. return lookup(&t->t, strkey2(key, len), v, hash, &streql);
  1485. }
  1486. bool upb_strtable_remove3(upb_strtable *t, const char *key, size_t len,
  1487. upb_value *val, upb_alloc *alloc) {
  1488. uint32_t hash = upb_murmur_hash2(key, len, 0);
  1489. upb_tabkey tabkey;
  1490. if (rm(&t->t, strkey2(key, len), val, &tabkey, hash, &streql)) {
  1491. if (alloc) {
  1492. /* Arena-based allocs don't need to free and won't pass this. */
  1493. upb_free(alloc, (void*)tabkey);
  1494. }
  1495. return true;
  1496. } else {
  1497. return false;
  1498. }
  1499. }
  1500. /* Iteration */
  1501. void upb_strtable_begin(upb_strtable_iter *i, const upb_strtable *t) {
  1502. i->t = t;
  1503. i->index = begin(&t->t);
  1504. }
  1505. void upb_strtable_next(upb_strtable_iter *i) {
  1506. i->index = next(&i->t->t, i->index);
  1507. }
  1508. bool upb_strtable_done(const upb_strtable_iter *i) {
  1509. if (!i->t) return true;
  1510. return i->index >= upb_table_size(&i->t->t) ||
  1511. upb_tabent_isempty(str_tabent(i));
  1512. }
  1513. upb_strview upb_strtable_iter_key(const upb_strtable_iter *i) {
  1514. upb_strview key;
  1515. uint32_t len;
  1516. UPB_ASSERT(!upb_strtable_done(i));
  1517. key.data = upb_tabstr(str_tabent(i)->key, &len);
  1518. key.size = len;
  1519. return key;
  1520. }
  1521. upb_value upb_strtable_iter_value(const upb_strtable_iter *i) {
  1522. UPB_ASSERT(!upb_strtable_done(i));
  1523. return _upb_value_val(str_tabent(i)->val.val);
  1524. }
  1525. void upb_strtable_iter_setdone(upb_strtable_iter *i) {
  1526. i->t = NULL;
  1527. i->index = SIZE_MAX;
  1528. }
  1529. bool upb_strtable_iter_isequal(const upb_strtable_iter *i1,
  1530. const upb_strtable_iter *i2) {
  1531. if (upb_strtable_done(i1) && upb_strtable_done(i2))
  1532. return true;
  1533. return i1->t == i2->t && i1->index == i2->index;
  1534. }
  1535. /* upb_inttable ***************************************************************/
  1536. /* For inttables we use a hybrid structure where small keys are kept in an
  1537. * array and large keys are put in the hash table. */
  1538. static uint32_t inthash(upb_tabkey key) { return upb_inthash(key); }
  1539. static bool inteql(upb_tabkey k1, lookupkey_t k2) {
  1540. return k1 == k2.num;
  1541. }
  1542. static upb_tabval *mutable_array(upb_inttable *t) {
  1543. return (upb_tabval*)t->array;
  1544. }
  1545. static upb_tabval *inttable_val(upb_inttable *t, uintptr_t key) {
  1546. if (key < t->array_size) {
  1547. return upb_arrhas(t->array[key]) ? &(mutable_array(t)[key]) : NULL;
  1548. } else {
  1549. upb_tabent *e =
  1550. findentry_mutable(&t->t, intkey(key), upb_inthash(key), &inteql);
  1551. return e ? &e->val : NULL;
  1552. }
  1553. }
  1554. static const upb_tabval *inttable_val_const(const upb_inttable *t,
  1555. uintptr_t key) {
  1556. return inttable_val((upb_inttable*)t, key);
  1557. }
  1558. size_t upb_inttable_count(const upb_inttable *t) {
  1559. return t->t.count + t->array_count;
  1560. }
  1561. static void check(upb_inttable *t) {
  1562. UPB_UNUSED(t);
  1563. #if defined(UPB_DEBUG_TABLE) && !defined(NDEBUG)
  1564. {
  1565. /* This check is very expensive (makes inserts/deletes O(N)). */
  1566. size_t count = 0;
  1567. upb_inttable_iter i;
  1568. upb_inttable_begin(&i, t);
  1569. for(; !upb_inttable_done(&i); upb_inttable_next(&i), count++) {
  1570. UPB_ASSERT(upb_inttable_lookup(t, upb_inttable_iter_key(&i), NULL));
  1571. }
  1572. UPB_ASSERT(count == upb_inttable_count(t));
  1573. }
  1574. #endif
  1575. }
  1576. bool upb_inttable_sizedinit(upb_inttable *t, size_t asize, int hsize_lg2,
  1577. upb_alloc *a) {
  1578. size_t array_bytes;
  1579. if (!init(&t->t, hsize_lg2, a)) return false;
  1580. /* Always make the array part at least 1 long, so that we know key 0
  1581. * won't be in the hash part, which simplifies things. */
  1582. t->array_size = UPB_MAX(1, asize);
  1583. t->array_count = 0;
  1584. array_bytes = t->array_size * sizeof(upb_value);
  1585. t->array = upb_malloc(a, array_bytes);
  1586. if (!t->array) {
  1587. uninit(&t->t, a);
  1588. return false;
  1589. }
  1590. memset(mutable_array(t), 0xff, array_bytes);
  1591. check(t);
  1592. return true;
  1593. }
  1594. bool upb_inttable_init2(upb_inttable *t, upb_ctype_t ctype, upb_alloc *a) {
  1595. return upb_inttable_sizedinit(t, 0, 4, a);
  1596. }
  1597. void upb_inttable_uninit2(upb_inttable *t, upb_alloc *a) {
  1598. uninit(&t->t, a);
  1599. upb_free(a, mutable_array(t));
  1600. }
  1601. bool upb_inttable_insert2(upb_inttable *t, uintptr_t key, upb_value val,
  1602. upb_alloc *a) {
  1603. upb_tabval tabval;
  1604. tabval.val = val.val;
  1605. UPB_ASSERT(upb_arrhas(tabval)); /* This will reject (uint64_t)-1. Fix this. */
  1606. if (key < t->array_size) {
  1607. UPB_ASSERT(!upb_arrhas(t->array[key]));
  1608. t->array_count++;
  1609. mutable_array(t)[key].val = val.val;
  1610. } else {
  1611. if (isfull(&t->t)) {
  1612. /* Need to resize the hash part, but we re-use the array part. */
  1613. size_t i;
  1614. upb_table new_table;
  1615. if (!init(&new_table, t->t.size_lg2 + 1, a)) {
  1616. return false;
  1617. }
  1618. for (i = begin(&t->t); i < upb_table_size(&t->t); i = next(&t->t, i)) {
  1619. const upb_tabent *e = &t->t.entries[i];
  1620. uint32_t hash;
  1621. upb_value v;
  1622. _upb_value_setval(&v, e->val.val);
  1623. hash = upb_inthash(e->key);
  1624. insert(&new_table, intkey(e->key), e->key, v, hash, &inthash, &inteql);
  1625. }
  1626. UPB_ASSERT(t->t.count == new_table.count);
  1627. uninit(&t->t, a);
  1628. t->t = new_table;
  1629. }
  1630. insert(&t->t, intkey(key), key, val, upb_inthash(key), &inthash, &inteql);
  1631. }
  1632. check(t);
  1633. return true;
  1634. }
  1635. bool upb_inttable_lookup(const upb_inttable *t, uintptr_t key, upb_value *v) {
  1636. const upb_tabval *table_v = inttable_val_const(t, key);
  1637. if (!table_v) return false;
  1638. if (v) _upb_value_setval(v, table_v->val);
  1639. return true;
  1640. }
  1641. bool upb_inttable_replace(upb_inttable *t, uintptr_t key, upb_value val) {
  1642. upb_tabval *table_v = inttable_val(t, key);
  1643. if (!table_v) return false;
  1644. table_v->val = val.val;
  1645. return true;
  1646. }
  1647. bool upb_inttable_remove(upb_inttable *t, uintptr_t key, upb_value *val) {
  1648. bool success;
  1649. if (key < t->array_size) {
  1650. if (upb_arrhas(t->array[key])) {
  1651. upb_tabval empty = UPB_TABVALUE_EMPTY_INIT;
  1652. t->array_count--;
  1653. if (val) {
  1654. _upb_value_setval(val, t->array[key].val);
  1655. }
  1656. mutable_array(t)[key] = empty;
  1657. success = true;
  1658. } else {
  1659. success = false;
  1660. }
  1661. } else {
  1662. success = rm(&t->t, intkey(key), val, NULL, upb_inthash(key), &inteql);
  1663. }
  1664. check(t);
  1665. return success;
  1666. }
  1667. bool upb_inttable_push2(upb_inttable *t, upb_value val, upb_alloc *a) {
  1668. return upb_inttable_insert2(t, upb_inttable_count(t), val, a);
  1669. }
  1670. upb_value upb_inttable_pop(upb_inttable *t) {
  1671. upb_value val;
  1672. bool ok = upb_inttable_remove(t, upb_inttable_count(t) - 1, &val);
  1673. UPB_ASSERT(ok);
  1674. return val;
  1675. }
  1676. bool upb_inttable_insertptr2(upb_inttable *t, const void *key, upb_value val,
  1677. upb_alloc *a) {
  1678. return upb_inttable_insert2(t, (uintptr_t)key, val, a);
  1679. }
  1680. bool upb_inttable_lookupptr(const upb_inttable *t, const void *key,
  1681. upb_value *v) {
  1682. return upb_inttable_lookup(t, (uintptr_t)key, v);
  1683. }
  1684. bool upb_inttable_removeptr(upb_inttable *t, const void *key, upb_value *val) {
  1685. return upb_inttable_remove(t, (uintptr_t)key, val);
  1686. }
  1687. void upb_inttable_compact2(upb_inttable *t, upb_alloc *a) {
  1688. /* A power-of-two histogram of the table keys. */
  1689. size_t counts[UPB_MAXARRSIZE + 1] = {0};
  1690. /* The max key in each bucket. */
  1691. uintptr_t max[UPB_MAXARRSIZE + 1] = {0};
  1692. upb_inttable_iter i;
  1693. size_t arr_count;
  1694. int size_lg2;
  1695. upb_inttable new_t;
  1696. upb_inttable_begin(&i, t);
  1697. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  1698. uintptr_t key = upb_inttable_iter_key(&i);
  1699. int bucket = log2ceil(key);
  1700. max[bucket] = UPB_MAX(max[bucket], key);
  1701. counts[bucket]++;
  1702. }
  1703. /* Find the largest power of two that satisfies the MIN_DENSITY
  1704. * definition (while actually having some keys). */
  1705. arr_count = upb_inttable_count(t);
  1706. for (size_lg2 = ARRAY_SIZE(counts) - 1; size_lg2 > 0; size_lg2--) {
  1707. if (counts[size_lg2] == 0) {
  1708. /* We can halve again without losing any entries. */
  1709. continue;
  1710. } else if (arr_count >= (1 << size_lg2) * MIN_DENSITY) {
  1711. break;
  1712. }
  1713. arr_count -= counts[size_lg2];
  1714. }
  1715. UPB_ASSERT(arr_count <= upb_inttable_count(t));
  1716. {
  1717. /* Insert all elements into new, perfectly-sized table. */
  1718. size_t arr_size = max[size_lg2] + 1; /* +1 so arr[max] will fit. */
  1719. size_t hash_count = upb_inttable_count(t) - arr_count;
  1720. size_t hash_size = hash_count ? (hash_count / MAX_LOAD) + 1 : 0;
  1721. int hashsize_lg2 = log2ceil(hash_size);
  1722. upb_inttable_sizedinit(&new_t, arr_size, hashsize_lg2, a);
  1723. upb_inttable_begin(&i, t);
  1724. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  1725. uintptr_t k = upb_inttable_iter_key(&i);
  1726. upb_inttable_insert2(&new_t, k, upb_inttable_iter_value(&i), a);
  1727. }
  1728. UPB_ASSERT(new_t.array_size == arr_size);
  1729. UPB_ASSERT(new_t.t.size_lg2 == hashsize_lg2);
  1730. }
  1731. upb_inttable_uninit2(t, a);
  1732. *t = new_t;
  1733. }
  1734. /* Iteration. */
  1735. static const upb_tabent *int_tabent(const upb_inttable_iter *i) {
  1736. UPB_ASSERT(!i->array_part);
  1737. return &i->t->t.entries[i->index];
  1738. }
  1739. static upb_tabval int_arrent(const upb_inttable_iter *i) {
  1740. UPB_ASSERT(i->array_part);
  1741. return i->t->array[i->index];
  1742. }
  1743. void upb_inttable_begin(upb_inttable_iter *i, const upb_inttable *t) {
  1744. i->t = t;
  1745. i->index = -1;
  1746. i->array_part = true;
  1747. upb_inttable_next(i);
  1748. }
  1749. void upb_inttable_next(upb_inttable_iter *iter) {
  1750. const upb_inttable *t = iter->t;
  1751. if (iter->array_part) {
  1752. while (++iter->index < t->array_size) {
  1753. if (upb_arrhas(int_arrent(iter))) {
  1754. return;
  1755. }
  1756. }
  1757. iter->array_part = false;
  1758. iter->index = begin(&t->t);
  1759. } else {
  1760. iter->index = next(&t->t, iter->index);
  1761. }
  1762. }
  1763. bool upb_inttable_done(const upb_inttable_iter *i) {
  1764. if (!i->t) return true;
  1765. if (i->array_part) {
  1766. return i->index >= i->t->array_size ||
  1767. !upb_arrhas(int_arrent(i));
  1768. } else {
  1769. return i->index >= upb_table_size(&i->t->t) ||
  1770. upb_tabent_isempty(int_tabent(i));
  1771. }
  1772. }
  1773. uintptr_t upb_inttable_iter_key(const upb_inttable_iter *i) {
  1774. UPB_ASSERT(!upb_inttable_done(i));
  1775. return i->array_part ? i->index : int_tabent(i)->key;
  1776. }
  1777. upb_value upb_inttable_iter_value(const upb_inttable_iter *i) {
  1778. UPB_ASSERT(!upb_inttable_done(i));
  1779. return _upb_value_val(
  1780. i->array_part ? i->t->array[i->index].val : int_tabent(i)->val.val);
  1781. }
  1782. void upb_inttable_iter_setdone(upb_inttable_iter *i) {
  1783. i->t = NULL;
  1784. i->index = SIZE_MAX;
  1785. i->array_part = false;
  1786. }
  1787. bool upb_inttable_iter_isequal(const upb_inttable_iter *i1,
  1788. const upb_inttable_iter *i2) {
  1789. if (upb_inttable_done(i1) && upb_inttable_done(i2))
  1790. return true;
  1791. return i1->t == i2->t && i1->index == i2->index &&
  1792. i1->array_part == i2->array_part;
  1793. }
  1794. #if defined(UPB_UNALIGNED_READS_OK) || defined(__s390x__)
  1795. /* -----------------------------------------------------------------------------
  1796. * MurmurHash2, by Austin Appleby (released as public domain).
  1797. * Reformatted and C99-ified by Joshua Haberman.
  1798. * Note - This code makes a few assumptions about how your machine behaves -
  1799. * 1. We can read a 4-byte value from any address without crashing
  1800. * 2. sizeof(int) == 4 (in upb this limitation is removed by using uint32_t
  1801. * And it has a few limitations -
  1802. * 1. It will not work incrementally.
  1803. * 2. It will not produce the same results on little-endian and big-endian
  1804. * machines. */
  1805. uint32_t upb_murmur_hash2(const void *key, size_t len, uint32_t seed) {
  1806. /* 'm' and 'r' are mixing constants generated offline.
  1807. * They're not really 'magic', they just happen to work well. */
  1808. const uint32_t m = 0x5bd1e995;
  1809. const int32_t r = 24;
  1810. /* Initialize the hash to a 'random' value */
  1811. uint32_t h = seed ^ len;
  1812. /* Mix 4 bytes at a time into the hash */
  1813. const uint8_t * data = (const uint8_t *)key;
  1814. while(len >= 4) {
  1815. uint32_t k;
  1816. memcpy(&k, data, sizeof(k));
  1817. k *= m;
  1818. k ^= k >> r;
  1819. k *= m;
  1820. h *= m;
  1821. h ^= k;
  1822. data += 4;
  1823. len -= 4;
  1824. }
  1825. /* Handle the last few bytes of the input array */
  1826. switch(len) {
  1827. case 3: h ^= data[2] << 16;
  1828. case 2: h ^= data[1] << 8;
  1829. case 1: h ^= data[0]; h *= m;
  1830. };
  1831. /* Do a few final mixes of the hash to ensure the last few
  1832. * bytes are well-incorporated. */
  1833. h ^= h >> 13;
  1834. h *= m;
  1835. h ^= h >> 15;
  1836. return h;
  1837. }
  1838. #else /* !UPB_UNALIGNED_READS_OK */
  1839. /* -----------------------------------------------------------------------------
  1840. * MurmurHashAligned2, by Austin Appleby
  1841. * Same algorithm as MurmurHash2, but only does aligned reads - should be safer
  1842. * on certain platforms.
  1843. * Performance will be lower than MurmurHash2 */
  1844. #define MIX(h,k,m) { k *= m; k ^= k >> r; k *= m; h *= m; h ^= k; }
  1845. uint32_t upb_murmur_hash2(const void * key, size_t len, uint32_t seed) {
  1846. const uint32_t m = 0x5bd1e995;
  1847. const int32_t r = 24;
  1848. const uint8_t * data = (const uint8_t *)key;
  1849. uint32_t h = (uint32_t)(seed ^ len);
  1850. uint8_t align = (uintptr_t)data & 3;
  1851. if(align && (len >= 4)) {
  1852. /* Pre-load the temp registers */
  1853. uint32_t t = 0, d = 0;
  1854. int32_t sl;
  1855. int32_t sr;
  1856. switch(align) {
  1857. case 1: t |= data[2] << 16;
  1858. case 2: t |= data[1] << 8;
  1859. case 3: t |= data[0];
  1860. }
  1861. t <<= (8 * align);
  1862. data += 4-align;
  1863. len -= 4-align;
  1864. sl = 8 * (4-align);
  1865. sr = 8 * align;
  1866. /* Mix */
  1867. while(len >= 4) {
  1868. uint32_t k;
  1869. d = *(uint32_t *)data;
  1870. t = (t >> sr) | (d << sl);
  1871. k = t;
  1872. MIX(h,k,m);
  1873. t = d;
  1874. data += 4;
  1875. len -= 4;
  1876. }
  1877. /* Handle leftover data in temp registers */
  1878. d = 0;
  1879. if(len >= align) {
  1880. uint32_t k;
  1881. switch(align) {
  1882. case 3: d |= data[2] << 16;
  1883. case 2: d |= data[1] << 8;
  1884. case 1: d |= data[0];
  1885. }
  1886. k = (t >> sr) | (d << sl);
  1887. MIX(h,k,m);
  1888. data += align;
  1889. len -= align;
  1890. /* ----------
  1891. * Handle tail bytes */
  1892. switch(len) {
  1893. case 3: h ^= data[2] << 16;
  1894. case 2: h ^= data[1] << 8;
  1895. case 1: h ^= data[0]; h *= m;
  1896. };
  1897. } else {
  1898. switch(len) {
  1899. case 3: d |= data[2] << 16;
  1900. case 2: d |= data[1] << 8;
  1901. case 1: d |= data[0];
  1902. case 0: h ^= (t >> sr) | (d << sl); h *= m;
  1903. }
  1904. }
  1905. h ^= h >> 13;
  1906. h *= m;
  1907. h ^= h >> 15;
  1908. return h;
  1909. } else {
  1910. while(len >= 4) {
  1911. uint32_t k = *(uint32_t *)data;
  1912. MIX(h,k,m);
  1913. data += 4;
  1914. len -= 4;
  1915. }
  1916. /* ----------
  1917. * Handle tail bytes */
  1918. switch(len) {
  1919. case 3: h ^= data[2] << 16;
  1920. case 2: h ^= data[1] << 8;
  1921. case 1: h ^= data[0]; h *= m;
  1922. };
  1923. h ^= h >> 13;
  1924. h *= m;
  1925. h ^= h >> 15;
  1926. return h;
  1927. }
  1928. }
  1929. #undef MIX
  1930. #endif /* UPB_UNALIGNED_READS_OK */
  1931. #include <errno.h>
  1932. #include <stdarg.h>
  1933. #include <stddef.h>
  1934. #include <stdint.h>
  1935. #include <stdio.h>
  1936. #include <stdlib.h>
  1937. #include <string.h>
  1938. /* upb_status *****************************************************************/
  1939. void upb_status_clear(upb_status *status) {
  1940. if (!status) return;
  1941. status->ok = true;
  1942. status->msg[0] = '\0';
  1943. }
  1944. bool upb_ok(const upb_status *status) { return status->ok; }
  1945. const char *upb_status_errmsg(const upb_status *status) { return status->msg; }
  1946. void upb_status_seterrmsg(upb_status *status, const char *msg) {
  1947. if (!status) return;
  1948. status->ok = false;
  1949. strncpy(status->msg, msg, UPB_STATUS_MAX_MESSAGE - 1);
  1950. status->msg[UPB_STATUS_MAX_MESSAGE - 1] = '\0';
  1951. }
  1952. void upb_status_seterrf(upb_status *status, const char *fmt, ...) {
  1953. va_list args;
  1954. va_start(args, fmt);
  1955. upb_status_vseterrf(status, fmt, args);
  1956. va_end(args);
  1957. }
  1958. void upb_status_vseterrf(upb_status *status, const char *fmt, va_list args) {
  1959. if (!status) return;
  1960. status->ok = false;
  1961. _upb_vsnprintf(status->msg, sizeof(status->msg), fmt, args);
  1962. status->msg[UPB_STATUS_MAX_MESSAGE - 1] = '\0';
  1963. }
  1964. /* upb_alloc ******************************************************************/
  1965. static void *upb_global_allocfunc(upb_alloc *alloc, void *ptr, size_t oldsize,
  1966. size_t size) {
  1967. UPB_UNUSED(alloc);
  1968. UPB_UNUSED(oldsize);
  1969. if (size == 0) {
  1970. free(ptr);
  1971. return NULL;
  1972. } else {
  1973. return realloc(ptr, size);
  1974. }
  1975. }
  1976. upb_alloc upb_alloc_global = {&upb_global_allocfunc};
  1977. /* upb_arena ******************************************************************/
  1978. /* Be conservative and choose 16 in case anyone is using SSE. */
  1979. struct upb_arena {
  1980. _upb_arena_head head;
  1981. char *start;
  1982. /* Allocator to allocate arena blocks. We are responsible for freeing these
  1983. * when we are destroyed. */
  1984. upb_alloc *block_alloc;
  1985. size_t bytes_allocated;
  1986. size_t next_block_size;
  1987. size_t max_block_size;
  1988. /* Linked list of blocks. Points to an arena_block, defined in env.c */
  1989. void *block_head;
  1990. /* Cleanup entries. Pointer to a cleanup_ent, defined in env.c */
  1991. void *cleanup_head;
  1992. };
  1993. typedef struct mem_block {
  1994. struct mem_block *next;
  1995. bool owned;
  1996. /* Data follows. */
  1997. } mem_block;
  1998. typedef struct cleanup_ent {
  1999. struct cleanup_ent *next;
  2000. upb_cleanup_func *cleanup;
  2001. void *ud;
  2002. } cleanup_ent;
  2003. static void upb_arena_addblock(upb_arena *a, void *ptr, size_t size,
  2004. bool owned) {
  2005. mem_block *block = ptr;
  2006. if (a->block_head) {
  2007. a->bytes_allocated += a->head.ptr - a->start;
  2008. }
  2009. block->next = a->block_head;
  2010. block->owned = owned;
  2011. a->block_head = block;
  2012. a->start = (char*)block + _upb_arena_alignup(sizeof(mem_block));
  2013. a->head.ptr = a->start;
  2014. a->head.end = (char*)block + size;
  2015. /* TODO(haberman): ASAN poison. */
  2016. }
  2017. static mem_block *upb_arena_allocblock(upb_arena *a, size_t size) {
  2018. size_t block_size = UPB_MAX(size, a->next_block_size) + sizeof(mem_block);
  2019. mem_block *block = upb_malloc(a->block_alloc, block_size);
  2020. if (!block) {
  2021. return NULL;
  2022. }
  2023. upb_arena_addblock(a, block, block_size, true);
  2024. a->next_block_size = UPB_MIN(block_size * 2, a->max_block_size);
  2025. return block;
  2026. }
  2027. void *_upb_arena_slowmalloc(upb_arena *a, size_t size) {
  2028. mem_block *block = upb_arena_allocblock(a, size);
  2029. if (!block) return NULL; /* Out of memory. */
  2030. return upb_arena_malloc(a, size);
  2031. }
  2032. static void *upb_arena_doalloc(upb_alloc *alloc, void *ptr, size_t oldsize,
  2033. size_t size) {
  2034. upb_arena *a = (upb_arena*)alloc; /* upb_alloc is initial member. */
  2035. void *ret;
  2036. if (size == 0) {
  2037. return NULL; /* We are an arena, don't need individual frees. */
  2038. }
  2039. ret = upb_arena_malloc(a, size);
  2040. if (!ret) return NULL;
  2041. /* TODO(haberman): special-case if this is a realloc of the last alloc? */
  2042. if (oldsize > 0) {
  2043. memcpy(ret, ptr, oldsize); /* Preserve existing data. */
  2044. }
  2045. /* TODO(haberman): ASAN unpoison. */
  2046. return ret;
  2047. }
  2048. /* Public Arena API ***********************************************************/
  2049. #define upb_alignof(type) offsetof (struct { char c; type member; }, member)
  2050. upb_arena *upb_arena_init(void *mem, size_t n, upb_alloc *alloc) {
  2051. const size_t first_block_overhead = sizeof(upb_arena) + sizeof(mem_block);
  2052. upb_arena *a;
  2053. bool owned = false;
  2054. /* Round block size down to alignof(*a) since we will allocate the arena
  2055. * itself at the end. */
  2056. n &= ~(upb_alignof(upb_arena) - 1);
  2057. if (n < first_block_overhead) {
  2058. /* We need to malloc the initial block. */
  2059. n = first_block_overhead + 256;
  2060. owned = true;
  2061. if (!alloc || !(mem = upb_malloc(alloc, n))) {
  2062. return NULL;
  2063. }
  2064. }
  2065. a = (void*)((char*)mem + n - sizeof(*a));
  2066. n -= sizeof(*a);
  2067. a->head.alloc.func = &upb_arena_doalloc;
  2068. a->head.ptr = NULL;
  2069. a->head.end = NULL;
  2070. a->start = NULL;
  2071. a->block_alloc = &upb_alloc_global;
  2072. a->bytes_allocated = 0;
  2073. a->next_block_size = 256;
  2074. a->max_block_size = 16384;
  2075. a->cleanup_head = NULL;
  2076. a->block_head = NULL;
  2077. a->block_alloc = alloc;
  2078. upb_arena_addblock(a, mem, n, owned);
  2079. return a;
  2080. }
  2081. #undef upb_alignof
  2082. void upb_arena_free(upb_arena *a) {
  2083. cleanup_ent *ent = a->cleanup_head;
  2084. mem_block *block = a->block_head;
  2085. while (ent) {
  2086. ent->cleanup(ent->ud);
  2087. ent = ent->next;
  2088. }
  2089. /* Must do this after running cleanup functions, because this will delete
  2090. * the memory we store our cleanup entries in! */
  2091. while (block) {
  2092. /* Load first since we are deleting block. */
  2093. mem_block *next = block->next;
  2094. if (block->owned) {
  2095. upb_free(a->block_alloc, block);
  2096. }
  2097. block = next;
  2098. }
  2099. }
  2100. bool upb_arena_addcleanup(upb_arena *a, void *ud, upb_cleanup_func *func) {
  2101. cleanup_ent *ent = upb_malloc(&a->head.alloc, sizeof(cleanup_ent));
  2102. if (!ent) {
  2103. return false; /* Out of memory. */
  2104. }
  2105. ent->cleanup = func;
  2106. ent->ud = ud;
  2107. ent->next = a->cleanup_head;
  2108. a->cleanup_head = ent;
  2109. return true;
  2110. }
  2111. size_t upb_arena_bytesallocated(const upb_arena *a) {
  2112. return a->bytes_allocated + (a->head.ptr - a->start);
  2113. }
  2114. /* This file was generated by upbc (the upb compiler) from the input
  2115. * file:
  2116. *
  2117. * google/protobuf/descriptor.proto
  2118. *
  2119. * Do not edit -- your changes will be discarded when the file is
  2120. * regenerated. */
  2121. #include <stddef.h>
  2122. static const upb_msglayout *const google_protobuf_FileDescriptorSet_submsgs[1] = {
  2123. &google_protobuf_FileDescriptorProto_msginit,
  2124. };
  2125. static const upb_msglayout_field google_protobuf_FileDescriptorSet__fields[1] = {
  2126. {1, UPB_SIZE(0, 0), 0, 0, 11, 3},
  2127. };
  2128. const upb_msglayout google_protobuf_FileDescriptorSet_msginit = {
  2129. &google_protobuf_FileDescriptorSet_submsgs[0],
  2130. &google_protobuf_FileDescriptorSet__fields[0],
  2131. UPB_SIZE(4, 8), 1, false,
  2132. };
  2133. static const upb_msglayout *const google_protobuf_FileDescriptorProto_submsgs[6] = {
  2134. &google_protobuf_DescriptorProto_msginit,
  2135. &google_protobuf_EnumDescriptorProto_msginit,
  2136. &google_protobuf_FieldDescriptorProto_msginit,
  2137. &google_protobuf_FileOptions_msginit,
  2138. &google_protobuf_ServiceDescriptorProto_msginit,
  2139. &google_protobuf_SourceCodeInfo_msginit,
  2140. };
  2141. static const upb_msglayout_field google_protobuf_FileDescriptorProto__fields[12] = {
  2142. {1, UPB_SIZE(4, 8), 1, 0, 9, 1},
  2143. {2, UPB_SIZE(12, 24), 2, 0, 9, 1},
  2144. {3, UPB_SIZE(36, 72), 0, 0, 9, 3},
  2145. {4, UPB_SIZE(40, 80), 0, 0, 11, 3},
  2146. {5, UPB_SIZE(44, 88), 0, 1, 11, 3},
  2147. {6, UPB_SIZE(48, 96), 0, 4, 11, 3},
  2148. {7, UPB_SIZE(52, 104), 0, 2, 11, 3},
  2149. {8, UPB_SIZE(28, 56), 4, 3, 11, 1},
  2150. {9, UPB_SIZE(32, 64), 5, 5, 11, 1},
  2151. {10, UPB_SIZE(56, 112), 0, 0, 5, 3},
  2152. {11, UPB_SIZE(60, 120), 0, 0, 5, 3},
  2153. {12, UPB_SIZE(20, 40), 3, 0, 9, 1},
  2154. };
  2155. const upb_msglayout google_protobuf_FileDescriptorProto_msginit = {
  2156. &google_protobuf_FileDescriptorProto_submsgs[0],
  2157. &google_protobuf_FileDescriptorProto__fields[0],
  2158. UPB_SIZE(64, 128), 12, false,
  2159. };
  2160. static const upb_msglayout *const google_protobuf_DescriptorProto_submsgs[8] = {
  2161. &google_protobuf_DescriptorProto_msginit,
  2162. &google_protobuf_DescriptorProto_ExtensionRange_msginit,
  2163. &google_protobuf_DescriptorProto_ReservedRange_msginit,
  2164. &google_protobuf_EnumDescriptorProto_msginit,
  2165. &google_protobuf_FieldDescriptorProto_msginit,
  2166. &google_protobuf_MessageOptions_msginit,
  2167. &google_protobuf_OneofDescriptorProto_msginit,
  2168. };
  2169. static const upb_msglayout_field google_protobuf_DescriptorProto__fields[10] = {
  2170. {1, UPB_SIZE(4, 8), 1, 0, 9, 1},
  2171. {2, UPB_SIZE(16, 32), 0, 4, 11, 3},
  2172. {3, UPB_SIZE(20, 40), 0, 0, 11, 3},
  2173. {4, UPB_SIZE(24, 48), 0, 3, 11, 3},
  2174. {5, UPB_SIZE(28, 56), 0, 1, 11, 3},
  2175. {6, UPB_SIZE(32, 64), 0, 4, 11, 3},
  2176. {7, UPB_SIZE(12, 24), 2, 5, 11, 1},
  2177. {8, UPB_SIZE(36, 72), 0, 6, 11, 3},
  2178. {9, UPB_SIZE(40, 80), 0, 2, 11, 3},
  2179. {10, UPB_SIZE(44, 88), 0, 0, 9, 3},
  2180. };
  2181. const upb_msglayout google_protobuf_DescriptorProto_msginit = {
  2182. &google_protobuf_DescriptorProto_submsgs[0],
  2183. &google_protobuf_DescriptorProto__fields[0],
  2184. UPB_SIZE(48, 96), 10, false,
  2185. };
  2186. static const upb_msglayout *const google_protobuf_DescriptorProto_ExtensionRange_submsgs[1] = {
  2187. &google_protobuf_ExtensionRangeOptions_msginit,
  2188. };
  2189. static const upb_msglayout_field google_protobuf_DescriptorProto_ExtensionRange__fields[3] = {
  2190. {1, UPB_SIZE(4, 4), 1, 0, 5, 1},
  2191. {2, UPB_SIZE(8, 8), 2, 0, 5, 1},
  2192. {3, UPB_SIZE(12, 16), 3, 0, 11, 1},
  2193. };
  2194. const upb_msglayout google_protobuf_DescriptorProto_ExtensionRange_msginit = {
  2195. &google_protobuf_DescriptorProto_ExtensionRange_submsgs[0],
  2196. &google_protobuf_DescriptorProto_ExtensionRange__fields[0],
  2197. UPB_SIZE(16, 24), 3, false,
  2198. };
  2199. static const upb_msglayout_field google_protobuf_DescriptorProto_ReservedRange__fields[2] = {
  2200. {1, UPB_SIZE(4, 4), 1, 0, 5, 1},
  2201. {2, UPB_SIZE(8, 8), 2, 0, 5, 1},
  2202. };
  2203. const upb_msglayout google_protobuf_DescriptorProto_ReservedRange_msginit = {
  2204. NULL,
  2205. &google_protobuf_DescriptorProto_ReservedRange__fields[0],
  2206. UPB_SIZE(12, 12), 2, false,
  2207. };
  2208. static const upb_msglayout *const google_protobuf_ExtensionRangeOptions_submsgs[1] = {
  2209. &google_protobuf_UninterpretedOption_msginit,
  2210. };
  2211. static const upb_msglayout_field google_protobuf_ExtensionRangeOptions__fields[1] = {
  2212. {999, UPB_SIZE(0, 0), 0, 0, 11, 3},
  2213. };
  2214. const upb_msglayout google_protobuf_ExtensionRangeOptions_msginit = {
  2215. &google_protobuf_ExtensionRangeOptions_submsgs[0],
  2216. &google_protobuf_ExtensionRangeOptions__fields[0],
  2217. UPB_SIZE(4, 8), 1, false,
  2218. };
  2219. static const upb_msglayout *const google_protobuf_FieldDescriptorProto_submsgs[1] = {
  2220. &google_protobuf_FieldOptions_msginit,
  2221. };
  2222. static const upb_msglayout_field google_protobuf_FieldDescriptorProto__fields[11] = {
  2223. {1, UPB_SIZE(36, 40), 6, 0, 9, 1},
  2224. {2, UPB_SIZE(44, 56), 7, 0, 9, 1},
  2225. {3, UPB_SIZE(24, 24), 3, 0, 5, 1},
  2226. {4, UPB_SIZE(8, 8), 1, 0, 14, 1},
  2227. {5, UPB_SIZE(16, 16), 2, 0, 14, 1},
  2228. {6, UPB_SIZE(52, 72), 8, 0, 9, 1},
  2229. {7, UPB_SIZE(60, 88), 9, 0, 9, 1},
  2230. {8, UPB_SIZE(76, 120), 11, 0, 11, 1},
  2231. {9, UPB_SIZE(28, 28), 4, 0, 5, 1},
  2232. {10, UPB_SIZE(68, 104), 10, 0, 9, 1},
  2233. {17, UPB_SIZE(32, 32), 5, 0, 8, 1},
  2234. };
  2235. const upb_msglayout google_protobuf_FieldDescriptorProto_msginit = {
  2236. &google_protobuf_FieldDescriptorProto_submsgs[0],
  2237. &google_protobuf_FieldDescriptorProto__fields[0],
  2238. UPB_SIZE(80, 128), 11, false,
  2239. };
  2240. static const upb_msglayout *const google_protobuf_OneofDescriptorProto_submsgs[1] = {
  2241. &google_protobuf_OneofOptions_msginit,
  2242. };
  2243. static const upb_msglayout_field google_protobuf_OneofDescriptorProto__fields[2] = {
  2244. {1, UPB_SIZE(4, 8), 1, 0, 9, 1},
  2245. {2, UPB_SIZE(12, 24), 2, 0, 11, 1},
  2246. };
  2247. const upb_msglayout google_protobuf_OneofDescriptorProto_msginit = {
  2248. &google_protobuf_OneofDescriptorProto_submsgs[0],
  2249. &google_protobuf_OneofDescriptorProto__fields[0],
  2250. UPB_SIZE(16, 32), 2, false,
  2251. };
  2252. static const upb_msglayout *const google_protobuf_EnumDescriptorProto_submsgs[3] = {
  2253. &google_protobuf_EnumDescriptorProto_EnumReservedRange_msginit,
  2254. &google_protobuf_EnumOptions_msginit,
  2255. &google_protobuf_EnumValueDescriptorProto_msginit,
  2256. };
  2257. static const upb_msglayout_field google_protobuf_EnumDescriptorProto__fields[5] = {
  2258. {1, UPB_SIZE(4, 8), 1, 0, 9, 1},
  2259. {2, UPB_SIZE(16, 32), 0, 2, 11, 3},
  2260. {3, UPB_SIZE(12, 24), 2, 1, 11, 1},
  2261. {4, UPB_SIZE(20, 40), 0, 0, 11, 3},
  2262. {5, UPB_SIZE(24, 48), 0, 0, 9, 3},
  2263. };
  2264. const upb_msglayout google_protobuf_EnumDescriptorProto_msginit = {
  2265. &google_protobuf_EnumDescriptorProto_submsgs[0],
  2266. &google_protobuf_EnumDescriptorProto__fields[0],
  2267. UPB_SIZE(32, 64), 5, false,
  2268. };
  2269. static const upb_msglayout_field google_protobuf_EnumDescriptorProto_EnumReservedRange__fields[2] = {
  2270. {1, UPB_SIZE(4, 4), 1, 0, 5, 1},
  2271. {2, UPB_SIZE(8, 8), 2, 0, 5, 1},
  2272. };
  2273. const upb_msglayout google_protobuf_EnumDescriptorProto_EnumReservedRange_msginit = {
  2274. NULL,
  2275. &google_protobuf_EnumDescriptorProto_EnumReservedRange__fields[0],
  2276. UPB_SIZE(12, 12), 2, false,
  2277. };
  2278. static const upb_msglayout *const google_protobuf_EnumValueDescriptorProto_submsgs[1] = {
  2279. &google_protobuf_EnumValueOptions_msginit,
  2280. };
  2281. static const upb_msglayout_field google_protobuf_EnumValueDescriptorProto__fields[3] = {
  2282. {1, UPB_SIZE(8, 8), 2, 0, 9, 1},
  2283. {2, UPB_SIZE(4, 4), 1, 0, 5, 1},
  2284. {3, UPB_SIZE(16, 24), 3, 0, 11, 1},
  2285. };
  2286. const upb_msglayout google_protobuf_EnumValueDescriptorProto_msginit = {
  2287. &google_protobuf_EnumValueDescriptorProto_submsgs[0],
  2288. &google_protobuf_EnumValueDescriptorProto__fields[0],
  2289. UPB_SIZE(24, 32), 3, false,
  2290. };
  2291. static const upb_msglayout *const google_protobuf_ServiceDescriptorProto_submsgs[2] = {
  2292. &google_protobuf_MethodDescriptorProto_msginit,
  2293. &google_protobuf_ServiceOptions_msginit,
  2294. };
  2295. static const upb_msglayout_field google_protobuf_ServiceDescriptorProto__fields[3] = {
  2296. {1, UPB_SIZE(4, 8), 1, 0, 9, 1},
  2297. {2, UPB_SIZE(16, 32), 0, 0, 11, 3},
  2298. {3, UPB_SIZE(12, 24), 2, 1, 11, 1},
  2299. };
  2300. const upb_msglayout google_protobuf_ServiceDescriptorProto_msginit = {
  2301. &google_protobuf_ServiceDescriptorProto_submsgs[0],
  2302. &google_protobuf_ServiceDescriptorProto__fields[0],
  2303. UPB_SIZE(24, 48), 3, false,
  2304. };
  2305. static const upb_msglayout *const google_protobuf_MethodDescriptorProto_submsgs[1] = {
  2306. &google_protobuf_MethodOptions_msginit,
  2307. };
  2308. static const upb_msglayout_field google_protobuf_MethodDescriptorProto__fields[6] = {
  2309. {1, UPB_SIZE(4, 8), 3, 0, 9, 1},
  2310. {2, UPB_SIZE(12, 24), 4, 0, 9, 1},
  2311. {3, UPB_SIZE(20, 40), 5, 0, 9, 1},
  2312. {4, UPB_SIZE(28, 56), 6, 0, 11, 1},
  2313. {5, UPB_SIZE(1, 1), 1, 0, 8, 1},
  2314. {6, UPB_SIZE(2, 2), 2, 0, 8, 1},
  2315. };
  2316. const upb_msglayout google_protobuf_MethodDescriptorProto_msginit = {
  2317. &google_protobuf_MethodDescriptorProto_submsgs[0],
  2318. &google_protobuf_MethodDescriptorProto__fields[0],
  2319. UPB_SIZE(32, 64), 6, false,
  2320. };
  2321. static const upb_msglayout *const google_protobuf_FileOptions_submsgs[1] = {
  2322. &google_protobuf_UninterpretedOption_msginit,
  2323. };
  2324. static const upb_msglayout_field google_protobuf_FileOptions__fields[21] = {
  2325. {1, UPB_SIZE(28, 32), 11, 0, 9, 1},
  2326. {8, UPB_SIZE(36, 48), 12, 0, 9, 1},
  2327. {9, UPB_SIZE(8, 8), 1, 0, 14, 1},
  2328. {10, UPB_SIZE(16, 16), 2, 0, 8, 1},
  2329. {11, UPB_SIZE(44, 64), 13, 0, 9, 1},
  2330. {16, UPB_SIZE(17, 17), 3, 0, 8, 1},
  2331. {17, UPB_SIZE(18, 18), 4, 0, 8, 1},
  2332. {18, UPB_SIZE(19, 19), 5, 0, 8, 1},
  2333. {20, UPB_SIZE(20, 20), 6, 0, 8, 1},
  2334. {23, UPB_SIZE(21, 21), 7, 0, 8, 1},
  2335. {27, UPB_SIZE(22, 22), 8, 0, 8, 1},
  2336. {31, UPB_SIZE(23, 23), 9, 0, 8, 1},
  2337. {36, UPB_SIZE(52, 80), 14, 0, 9, 1},
  2338. {37, UPB_SIZE(60, 96), 15, 0, 9, 1},
  2339. {39, UPB_SIZE(68, 112), 16, 0, 9, 1},
  2340. {40, UPB_SIZE(76, 128), 17, 0, 9, 1},
  2341. {41, UPB_SIZE(84, 144), 18, 0, 9, 1},
  2342. {42, UPB_SIZE(24, 24), 10, 0, 8, 1},
  2343. {44, UPB_SIZE(92, 160), 19, 0, 9, 1},
  2344. {45, UPB_SIZE(100, 176), 20, 0, 9, 1},
  2345. {999, UPB_SIZE(108, 192), 0, 0, 11, 3},
  2346. };
  2347. const upb_msglayout google_protobuf_FileOptions_msginit = {
  2348. &google_protobuf_FileOptions_submsgs[0],
  2349. &google_protobuf_FileOptions__fields[0],
  2350. UPB_SIZE(112, 208), 21, false,
  2351. };
  2352. static const upb_msglayout *const google_protobuf_MessageOptions_submsgs[1] = {
  2353. &google_protobuf_UninterpretedOption_msginit,
  2354. };
  2355. static const upb_msglayout_field google_protobuf_MessageOptions__fields[5] = {
  2356. {1, UPB_SIZE(1, 1), 1, 0, 8, 1},
  2357. {2, UPB_SIZE(2, 2), 2, 0, 8, 1},
  2358. {3, UPB_SIZE(3, 3), 3, 0, 8, 1},
  2359. {7, UPB_SIZE(4, 4), 4, 0, 8, 1},
  2360. {999, UPB_SIZE(8, 8), 0, 0, 11, 3},
  2361. };
  2362. const upb_msglayout google_protobuf_MessageOptions_msginit = {
  2363. &google_protobuf_MessageOptions_submsgs[0],
  2364. &google_protobuf_MessageOptions__fields[0],
  2365. UPB_SIZE(12, 16), 5, false,
  2366. };
  2367. static const upb_msglayout *const google_protobuf_FieldOptions_submsgs[1] = {
  2368. &google_protobuf_UninterpretedOption_msginit,
  2369. };
  2370. static const upb_msglayout_field google_protobuf_FieldOptions__fields[7] = {
  2371. {1, UPB_SIZE(8, 8), 1, 0, 14, 1},
  2372. {2, UPB_SIZE(24, 24), 3, 0, 8, 1},
  2373. {3, UPB_SIZE(25, 25), 4, 0, 8, 1},
  2374. {5, UPB_SIZE(26, 26), 5, 0, 8, 1},
  2375. {6, UPB_SIZE(16, 16), 2, 0, 14, 1},
  2376. {10, UPB_SIZE(27, 27), 6, 0, 8, 1},
  2377. {999, UPB_SIZE(28, 32), 0, 0, 11, 3},
  2378. };
  2379. const upb_msglayout google_protobuf_FieldOptions_msginit = {
  2380. &google_protobuf_FieldOptions_submsgs[0],
  2381. &google_protobuf_FieldOptions__fields[0],
  2382. UPB_SIZE(32, 40), 7, false,
  2383. };
  2384. static const upb_msglayout *const google_protobuf_OneofOptions_submsgs[1] = {
  2385. &google_protobuf_UninterpretedOption_msginit,
  2386. };
  2387. static const upb_msglayout_field google_protobuf_OneofOptions__fields[1] = {
  2388. {999, UPB_SIZE(0, 0), 0, 0, 11, 3},
  2389. };
  2390. const upb_msglayout google_protobuf_OneofOptions_msginit = {
  2391. &google_protobuf_OneofOptions_submsgs[0],
  2392. &google_protobuf_OneofOptions__fields[0],
  2393. UPB_SIZE(4, 8), 1, false,
  2394. };
  2395. static const upb_msglayout *const google_protobuf_EnumOptions_submsgs[1] = {
  2396. &google_protobuf_UninterpretedOption_msginit,
  2397. };
  2398. static const upb_msglayout_field google_protobuf_EnumOptions__fields[3] = {
  2399. {2, UPB_SIZE(1, 1), 1, 0, 8, 1},
  2400. {3, UPB_SIZE(2, 2), 2, 0, 8, 1},
  2401. {999, UPB_SIZE(4, 8), 0, 0, 11, 3},
  2402. };
  2403. const upb_msglayout google_protobuf_EnumOptions_msginit = {
  2404. &google_protobuf_EnumOptions_submsgs[0],
  2405. &google_protobuf_EnumOptions__fields[0],
  2406. UPB_SIZE(8, 16), 3, false,
  2407. };
  2408. static const upb_msglayout *const google_protobuf_EnumValueOptions_submsgs[1] = {
  2409. &google_protobuf_UninterpretedOption_msginit,
  2410. };
  2411. static const upb_msglayout_field google_protobuf_EnumValueOptions__fields[2] = {
  2412. {1, UPB_SIZE(1, 1), 1, 0, 8, 1},
  2413. {999, UPB_SIZE(4, 8), 0, 0, 11, 3},
  2414. };
  2415. const upb_msglayout google_protobuf_EnumValueOptions_msginit = {
  2416. &google_protobuf_EnumValueOptions_submsgs[0],
  2417. &google_protobuf_EnumValueOptions__fields[0],
  2418. UPB_SIZE(8, 16), 2, false,
  2419. };
  2420. static const upb_msglayout *const google_protobuf_ServiceOptions_submsgs[1] = {
  2421. &google_protobuf_UninterpretedOption_msginit,
  2422. };
  2423. static const upb_msglayout_field google_protobuf_ServiceOptions__fields[2] = {
  2424. {33, UPB_SIZE(1, 1), 1, 0, 8, 1},
  2425. {999, UPB_SIZE(4, 8), 0, 0, 11, 3},
  2426. };
  2427. const upb_msglayout google_protobuf_ServiceOptions_msginit = {
  2428. &google_protobuf_ServiceOptions_submsgs[0],
  2429. &google_protobuf_ServiceOptions__fields[0],
  2430. UPB_SIZE(8, 16), 2, false,
  2431. };
  2432. static const upb_msglayout *const google_protobuf_MethodOptions_submsgs[1] = {
  2433. &google_protobuf_UninterpretedOption_msginit,
  2434. };
  2435. static const upb_msglayout_field google_protobuf_MethodOptions__fields[3] = {
  2436. {33, UPB_SIZE(16, 16), 2, 0, 8, 1},
  2437. {34, UPB_SIZE(8, 8), 1, 0, 14, 1},
  2438. {999, UPB_SIZE(20, 24), 0, 0, 11, 3},
  2439. };
  2440. const upb_msglayout google_protobuf_MethodOptions_msginit = {
  2441. &google_protobuf_MethodOptions_submsgs[0],
  2442. &google_protobuf_MethodOptions__fields[0],
  2443. UPB_SIZE(24, 32), 3, false,
  2444. };
  2445. static const upb_msglayout *const google_protobuf_UninterpretedOption_submsgs[1] = {
  2446. &google_protobuf_UninterpretedOption_NamePart_msginit,
  2447. };
  2448. static const upb_msglayout_field google_protobuf_UninterpretedOption__fields[7] = {
  2449. {2, UPB_SIZE(56, 80), 0, 0, 11, 3},
  2450. {3, UPB_SIZE(32, 32), 4, 0, 9, 1},
  2451. {4, UPB_SIZE(8, 8), 1, 0, 4, 1},
  2452. {5, UPB_SIZE(16, 16), 2, 0, 3, 1},
  2453. {6, UPB_SIZE(24, 24), 3, 0, 1, 1},
  2454. {7, UPB_SIZE(40, 48), 5, 0, 12, 1},
  2455. {8, UPB_SIZE(48, 64), 6, 0, 9, 1},
  2456. };
  2457. const upb_msglayout google_protobuf_UninterpretedOption_msginit = {
  2458. &google_protobuf_UninterpretedOption_submsgs[0],
  2459. &google_protobuf_UninterpretedOption__fields[0],
  2460. UPB_SIZE(64, 96), 7, false,
  2461. };
  2462. static const upb_msglayout_field google_protobuf_UninterpretedOption_NamePart__fields[2] = {
  2463. {1, UPB_SIZE(4, 8), 2, 0, 9, 2},
  2464. {2, UPB_SIZE(1, 1), 1, 0, 8, 2},
  2465. };
  2466. const upb_msglayout google_protobuf_UninterpretedOption_NamePart_msginit = {
  2467. NULL,
  2468. &google_protobuf_UninterpretedOption_NamePart__fields[0],
  2469. UPB_SIZE(16, 32), 2, false,
  2470. };
  2471. static const upb_msglayout *const google_protobuf_SourceCodeInfo_submsgs[1] = {
  2472. &google_protobuf_SourceCodeInfo_Location_msginit,
  2473. };
  2474. static const upb_msglayout_field google_protobuf_SourceCodeInfo__fields[1] = {
  2475. {1, UPB_SIZE(0, 0), 0, 0, 11, 3},
  2476. };
  2477. const upb_msglayout google_protobuf_SourceCodeInfo_msginit = {
  2478. &google_protobuf_SourceCodeInfo_submsgs[0],
  2479. &google_protobuf_SourceCodeInfo__fields[0],
  2480. UPB_SIZE(4, 8), 1, false,
  2481. };
  2482. static const upb_msglayout_field google_protobuf_SourceCodeInfo_Location__fields[5] = {
  2483. {1, UPB_SIZE(20, 40), 0, 0, 5, _UPB_LABEL_PACKED},
  2484. {2, UPB_SIZE(24, 48), 0, 0, 5, _UPB_LABEL_PACKED},
  2485. {3, UPB_SIZE(4, 8), 1, 0, 9, 1},
  2486. {4, UPB_SIZE(12, 24), 2, 0, 9, 1},
  2487. {6, UPB_SIZE(28, 56), 0, 0, 9, 3},
  2488. };
  2489. const upb_msglayout google_protobuf_SourceCodeInfo_Location_msginit = {
  2490. NULL,
  2491. &google_protobuf_SourceCodeInfo_Location__fields[0],
  2492. UPB_SIZE(32, 64), 5, false,
  2493. };
  2494. static const upb_msglayout *const google_protobuf_GeneratedCodeInfo_submsgs[1] = {
  2495. &google_protobuf_GeneratedCodeInfo_Annotation_msginit,
  2496. };
  2497. static const upb_msglayout_field google_protobuf_GeneratedCodeInfo__fields[1] = {
  2498. {1, UPB_SIZE(0, 0), 0, 0, 11, 3},
  2499. };
  2500. const upb_msglayout google_protobuf_GeneratedCodeInfo_msginit = {
  2501. &google_protobuf_GeneratedCodeInfo_submsgs[0],
  2502. &google_protobuf_GeneratedCodeInfo__fields[0],
  2503. UPB_SIZE(4, 8), 1, false,
  2504. };
  2505. static const upb_msglayout_field google_protobuf_GeneratedCodeInfo_Annotation__fields[4] = {
  2506. {1, UPB_SIZE(20, 32), 0, 0, 5, _UPB_LABEL_PACKED},
  2507. {2, UPB_SIZE(12, 16), 3, 0, 9, 1},
  2508. {3, UPB_SIZE(4, 4), 1, 0, 5, 1},
  2509. {4, UPB_SIZE(8, 8), 2, 0, 5, 1},
  2510. };
  2511. const upb_msglayout google_protobuf_GeneratedCodeInfo_Annotation_msginit = {
  2512. NULL,
  2513. &google_protobuf_GeneratedCodeInfo_Annotation__fields[0],
  2514. UPB_SIZE(24, 48), 4, false,
  2515. };
  2516. #include <ctype.h>
  2517. #include <errno.h>
  2518. #include <stdlib.h>
  2519. #include <string.h>
  2520. typedef struct {
  2521. size_t len;
  2522. char str[1]; /* Null-terminated string data follows. */
  2523. } str_t;
  2524. static str_t *newstr(upb_alloc *alloc, const char *data, size_t len) {
  2525. str_t *ret = upb_malloc(alloc, sizeof(*ret) + len);
  2526. if (!ret) return NULL;
  2527. ret->len = len;
  2528. memcpy(ret->str, data, len);
  2529. ret->str[len] = '\0';
  2530. return ret;
  2531. }
  2532. struct upb_fielddef {
  2533. const upb_filedef *file;
  2534. const upb_msgdef *msgdef;
  2535. const char *full_name;
  2536. const char *json_name;
  2537. union {
  2538. int64_t sint;
  2539. uint64_t uint;
  2540. double dbl;
  2541. float flt;
  2542. bool boolean;
  2543. str_t *str;
  2544. } defaultval;
  2545. const upb_oneofdef *oneof;
  2546. union {
  2547. const upb_msgdef *msgdef;
  2548. const upb_enumdef *enumdef;
  2549. const google_protobuf_FieldDescriptorProto *unresolved;
  2550. } sub;
  2551. uint32_t number_;
  2552. uint16_t index_;
  2553. uint16_t layout_index;
  2554. uint32_t selector_base; /* Used to index into a upb::Handlers table. */
  2555. bool is_extension_;
  2556. bool lazy_;
  2557. bool packed_;
  2558. bool proto3_optional_;
  2559. upb_descriptortype_t type_;
  2560. upb_label_t label_;
  2561. };
  2562. struct upb_msgdef {
  2563. const upb_msglayout *layout;
  2564. const upb_filedef *file;
  2565. const char *full_name;
  2566. uint32_t selector_count;
  2567. uint32_t submsg_field_count;
  2568. /* Tables for looking up fields by number and name. */
  2569. upb_inttable itof;
  2570. upb_strtable ntof;
  2571. const upb_fielddef *fields;
  2572. const upb_oneofdef *oneofs;
  2573. int field_count;
  2574. int oneof_count;
  2575. /* Is this a map-entry message? */
  2576. bool map_entry;
  2577. upb_wellknowntype_t well_known_type;
  2578. /* TODO(haberman): proper extension ranges (there can be multiple). */
  2579. };
  2580. struct upb_enumdef {
  2581. const upb_filedef *file;
  2582. const char *full_name;
  2583. upb_strtable ntoi;
  2584. upb_inttable iton;
  2585. int32_t defaultval;
  2586. };
  2587. struct upb_oneofdef {
  2588. const upb_msgdef *parent;
  2589. const char *full_name;
  2590. uint32_t index;
  2591. upb_strtable ntof;
  2592. upb_inttable itof;
  2593. };
  2594. struct upb_filedef {
  2595. const char *name;
  2596. const char *package;
  2597. const char *phpprefix;
  2598. const char *phpnamespace;
  2599. upb_syntax_t syntax;
  2600. const upb_filedef **deps;
  2601. const upb_msgdef *msgs;
  2602. const upb_enumdef *enums;
  2603. const upb_fielddef *exts;
  2604. int dep_count;
  2605. int msg_count;
  2606. int enum_count;
  2607. int ext_count;
  2608. };
  2609. struct upb_symtab {
  2610. upb_arena *arena;
  2611. upb_strtable syms; /* full_name -> packed def ptr */
  2612. upb_strtable files; /* file_name -> upb_filedef* */
  2613. };
  2614. /* Inside a symtab we store tagged pointers to specific def types. */
  2615. typedef enum {
  2616. UPB_DEFTYPE_FIELD = 0,
  2617. /* Only inside symtab table. */
  2618. UPB_DEFTYPE_MSG = 1,
  2619. UPB_DEFTYPE_ENUM = 2,
  2620. /* Only inside message table. */
  2621. UPB_DEFTYPE_ONEOF = 1,
  2622. UPB_DEFTYPE_FIELD_JSONNAME = 2
  2623. } upb_deftype_t;
  2624. static const void *unpack_def(upb_value v, upb_deftype_t type) {
  2625. uintptr_t num = (uintptr_t)upb_value_getconstptr(v);
  2626. return (num & 3) == type ? (const void*)(num & ~3) : NULL;
  2627. }
  2628. static upb_value pack_def(const void *ptr, upb_deftype_t type) {
  2629. uintptr_t num = (uintptr_t)ptr | type;
  2630. return upb_value_constptr((const void*)num);
  2631. }
  2632. /* isalpha() etc. from <ctype.h> are locale-dependent, which we don't want. */
  2633. static bool upb_isbetween(char c, char low, char high) {
  2634. return c >= low && c <= high;
  2635. }
  2636. static bool upb_isletter(char c) {
  2637. return upb_isbetween(c, 'A', 'Z') || upb_isbetween(c, 'a', 'z') || c == '_';
  2638. }
  2639. static bool upb_isalphanum(char c) {
  2640. return upb_isletter(c) || upb_isbetween(c, '0', '9');
  2641. }
  2642. static bool upb_isident(upb_strview name, bool full, upb_status *s) {
  2643. const char *str = name.data;
  2644. size_t len = name.size;
  2645. bool start = true;
  2646. size_t i;
  2647. for (i = 0; i < len; i++) {
  2648. char c = str[i];
  2649. if (c == '.') {
  2650. if (start || !full) {
  2651. upb_status_seterrf(s, "invalid name: unexpected '.' (%s)", str);
  2652. return false;
  2653. }
  2654. start = true;
  2655. } else if (start) {
  2656. if (!upb_isletter(c)) {
  2657. upb_status_seterrf(
  2658. s, "invalid name: path components must start with a letter (%s)",
  2659. str);
  2660. return false;
  2661. }
  2662. start = false;
  2663. } else {
  2664. if (!upb_isalphanum(c)) {
  2665. upb_status_seterrf(s, "invalid name: non-alphanumeric character (%s)",
  2666. str);
  2667. return false;
  2668. }
  2669. }
  2670. }
  2671. return !start;
  2672. }
  2673. static const char *shortdefname(const char *fullname) {
  2674. const char *p;
  2675. if (fullname == NULL) {
  2676. return NULL;
  2677. } else if ((p = strrchr(fullname, '.')) == NULL) {
  2678. /* No '.' in the name, return the full string. */
  2679. return fullname;
  2680. } else {
  2681. /* Return one past the last '.'. */
  2682. return p + 1;
  2683. }
  2684. }
  2685. /* All submessage fields are lower than all other fields.
  2686. * Secondly, fields are increasing in order. */
  2687. uint32_t field_rank(const upb_fielddef *f) {
  2688. uint32_t ret = upb_fielddef_number(f);
  2689. const uint32_t high_bit = 1 << 30;
  2690. UPB_ASSERT(ret < high_bit);
  2691. if (!upb_fielddef_issubmsg(f))
  2692. ret |= high_bit;
  2693. return ret;
  2694. }
  2695. int cmp_fields(const void *p1, const void *p2) {
  2696. const upb_fielddef *f1 = *(upb_fielddef*const*)p1;
  2697. const upb_fielddef *f2 = *(upb_fielddef*const*)p2;
  2698. return field_rank(f1) - field_rank(f2);
  2699. }
  2700. /* A few implementation details of handlers. We put these here to avoid
  2701. * a def -> handlers dependency. */
  2702. #define UPB_STATIC_SELECTOR_COUNT 3 /* Warning: also in upb/handlers.h. */
  2703. static uint32_t upb_handlers_selectorbaseoffset(const upb_fielddef *f) {
  2704. return upb_fielddef_isseq(f) ? 2 : 0;
  2705. }
  2706. static uint32_t upb_handlers_selectorcount(const upb_fielddef *f) {
  2707. uint32_t ret = 1;
  2708. if (upb_fielddef_isseq(f)) ret += 2; /* STARTSEQ/ENDSEQ */
  2709. if (upb_fielddef_isstring(f)) ret += 2; /* [STRING]/STARTSTR/ENDSTR */
  2710. if (upb_fielddef_issubmsg(f)) {
  2711. /* ENDSUBMSG (STARTSUBMSG is at table beginning) */
  2712. ret += 0;
  2713. if (upb_fielddef_lazy(f)) {
  2714. /* STARTSTR/ENDSTR/STRING (for lazy) */
  2715. ret += 3;
  2716. }
  2717. }
  2718. return ret;
  2719. }
  2720. static bool assign_msg_indices(upb_msgdef *m, upb_status *s) {
  2721. /* Sort fields. upb internally relies on UPB_TYPE_MESSAGE fields having the
  2722. * lowest indexes, but we do not publicly guarantee this. */
  2723. upb_msg_field_iter j;
  2724. upb_msg_oneof_iter k;
  2725. int i;
  2726. uint32_t selector;
  2727. int n = upb_msgdef_numfields(m);
  2728. upb_fielddef **fields;
  2729. if (n == 0) {
  2730. m->selector_count = UPB_STATIC_SELECTOR_COUNT;
  2731. m->submsg_field_count = 0;
  2732. return true;
  2733. }
  2734. fields = upb_gmalloc(n * sizeof(*fields));
  2735. if (!fields) {
  2736. upb_status_setoom(s);
  2737. return false;
  2738. }
  2739. m->submsg_field_count = 0;
  2740. for(i = 0, upb_msg_field_begin(&j, m);
  2741. !upb_msg_field_done(&j);
  2742. upb_msg_field_next(&j), i++) {
  2743. upb_fielddef *f = upb_msg_iter_field(&j);
  2744. UPB_ASSERT(f->msgdef == m);
  2745. if (upb_fielddef_issubmsg(f)) {
  2746. m->submsg_field_count++;
  2747. }
  2748. fields[i] = f;
  2749. }
  2750. qsort(fields, n, sizeof(*fields), cmp_fields);
  2751. selector = UPB_STATIC_SELECTOR_COUNT + m->submsg_field_count;
  2752. for (i = 0; i < n; i++) {
  2753. upb_fielddef *f = fields[i];
  2754. f->index_ = i;
  2755. f->selector_base = selector + upb_handlers_selectorbaseoffset(f);
  2756. selector += upb_handlers_selectorcount(f);
  2757. }
  2758. m->selector_count = selector;
  2759. for(upb_msg_oneof_begin(&k, m), i = 0;
  2760. !upb_msg_oneof_done(&k);
  2761. upb_msg_oneof_next(&k), i++) {
  2762. upb_oneofdef *o = (upb_oneofdef*)upb_msg_iter_oneof(&k);
  2763. o->index = i;
  2764. }
  2765. upb_gfree(fields);
  2766. return true;
  2767. }
  2768. static void assign_msg_wellknowntype(upb_msgdef *m) {
  2769. const char *name = upb_msgdef_fullname(m);
  2770. if (name == NULL) {
  2771. m->well_known_type = UPB_WELLKNOWN_UNSPECIFIED;
  2772. return;
  2773. }
  2774. if (!strcmp(name, "google.protobuf.Any")) {
  2775. m->well_known_type = UPB_WELLKNOWN_ANY;
  2776. } else if (!strcmp(name, "google.protobuf.FieldMask")) {
  2777. m->well_known_type = UPB_WELLKNOWN_FIELDMASK;
  2778. } else if (!strcmp(name, "google.protobuf.Duration")) {
  2779. m->well_known_type = UPB_WELLKNOWN_DURATION;
  2780. } else if (!strcmp(name, "google.protobuf.Timestamp")) {
  2781. m->well_known_type = UPB_WELLKNOWN_TIMESTAMP;
  2782. } else if (!strcmp(name, "google.protobuf.DoubleValue")) {
  2783. m->well_known_type = UPB_WELLKNOWN_DOUBLEVALUE;
  2784. } else if (!strcmp(name, "google.protobuf.FloatValue")) {
  2785. m->well_known_type = UPB_WELLKNOWN_FLOATVALUE;
  2786. } else if (!strcmp(name, "google.protobuf.Int64Value")) {
  2787. m->well_known_type = UPB_WELLKNOWN_INT64VALUE;
  2788. } else if (!strcmp(name, "google.protobuf.UInt64Value")) {
  2789. m->well_known_type = UPB_WELLKNOWN_UINT64VALUE;
  2790. } else if (!strcmp(name, "google.protobuf.Int32Value")) {
  2791. m->well_known_type = UPB_WELLKNOWN_INT32VALUE;
  2792. } else if (!strcmp(name, "google.protobuf.UInt32Value")) {
  2793. m->well_known_type = UPB_WELLKNOWN_UINT32VALUE;
  2794. } else if (!strcmp(name, "google.protobuf.BoolValue")) {
  2795. m->well_known_type = UPB_WELLKNOWN_BOOLVALUE;
  2796. } else if (!strcmp(name, "google.protobuf.StringValue")) {
  2797. m->well_known_type = UPB_WELLKNOWN_STRINGVALUE;
  2798. } else if (!strcmp(name, "google.protobuf.BytesValue")) {
  2799. m->well_known_type = UPB_WELLKNOWN_BYTESVALUE;
  2800. } else if (!strcmp(name, "google.protobuf.Value")) {
  2801. m->well_known_type = UPB_WELLKNOWN_VALUE;
  2802. } else if (!strcmp(name, "google.protobuf.ListValue")) {
  2803. m->well_known_type = UPB_WELLKNOWN_LISTVALUE;
  2804. } else if (!strcmp(name, "google.protobuf.Struct")) {
  2805. m->well_known_type = UPB_WELLKNOWN_STRUCT;
  2806. } else {
  2807. m->well_known_type = UPB_WELLKNOWN_UNSPECIFIED;
  2808. }
  2809. }
  2810. /* upb_enumdef ****************************************************************/
  2811. const char *upb_enumdef_fullname(const upb_enumdef *e) {
  2812. return e->full_name;
  2813. }
  2814. const char *upb_enumdef_name(const upb_enumdef *e) {
  2815. return shortdefname(e->full_name);
  2816. }
  2817. const upb_filedef *upb_enumdef_file(const upb_enumdef *e) {
  2818. return e->file;
  2819. }
  2820. int32_t upb_enumdef_default(const upb_enumdef *e) {
  2821. UPB_ASSERT(upb_enumdef_iton(e, e->defaultval));
  2822. return e->defaultval;
  2823. }
  2824. int upb_enumdef_numvals(const upb_enumdef *e) {
  2825. return (int)upb_strtable_count(&e->ntoi);
  2826. }
  2827. void upb_enum_begin(upb_enum_iter *i, const upb_enumdef *e) {
  2828. /* We iterate over the ntoi table, to account for duplicate numbers. */
  2829. upb_strtable_begin(i, &e->ntoi);
  2830. }
  2831. void upb_enum_next(upb_enum_iter *iter) { upb_strtable_next(iter); }
  2832. bool upb_enum_done(upb_enum_iter *iter) { return upb_strtable_done(iter); }
  2833. bool upb_enumdef_ntoi(const upb_enumdef *def, const char *name,
  2834. size_t len, int32_t *num) {
  2835. upb_value v;
  2836. if (!upb_strtable_lookup2(&def->ntoi, name, len, &v)) {
  2837. return false;
  2838. }
  2839. if (num) *num = upb_value_getint32(v);
  2840. return true;
  2841. }
  2842. const char *upb_enumdef_iton(const upb_enumdef *def, int32_t num) {
  2843. upb_value v;
  2844. return upb_inttable_lookup32(&def->iton, num, &v) ?
  2845. upb_value_getcstr(v) : NULL;
  2846. }
  2847. const char *upb_enum_iter_name(upb_enum_iter *iter) {
  2848. return upb_strtable_iter_key(iter).data;
  2849. }
  2850. int32_t upb_enum_iter_number(upb_enum_iter *iter) {
  2851. return upb_value_getint32(upb_strtable_iter_value(iter));
  2852. }
  2853. /* upb_fielddef ***************************************************************/
  2854. const char *upb_fielddef_fullname(const upb_fielddef *f) {
  2855. return f->full_name;
  2856. }
  2857. upb_fieldtype_t upb_fielddef_type(const upb_fielddef *f) {
  2858. switch (f->type_) {
  2859. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  2860. return UPB_TYPE_DOUBLE;
  2861. case UPB_DESCRIPTOR_TYPE_FLOAT:
  2862. return UPB_TYPE_FLOAT;
  2863. case UPB_DESCRIPTOR_TYPE_INT64:
  2864. case UPB_DESCRIPTOR_TYPE_SINT64:
  2865. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  2866. return UPB_TYPE_INT64;
  2867. case UPB_DESCRIPTOR_TYPE_INT32:
  2868. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  2869. case UPB_DESCRIPTOR_TYPE_SINT32:
  2870. return UPB_TYPE_INT32;
  2871. case UPB_DESCRIPTOR_TYPE_UINT64:
  2872. case UPB_DESCRIPTOR_TYPE_FIXED64:
  2873. return UPB_TYPE_UINT64;
  2874. case UPB_DESCRIPTOR_TYPE_UINT32:
  2875. case UPB_DESCRIPTOR_TYPE_FIXED32:
  2876. return UPB_TYPE_UINT32;
  2877. case UPB_DESCRIPTOR_TYPE_ENUM:
  2878. return UPB_TYPE_ENUM;
  2879. case UPB_DESCRIPTOR_TYPE_BOOL:
  2880. return UPB_TYPE_BOOL;
  2881. case UPB_DESCRIPTOR_TYPE_STRING:
  2882. return UPB_TYPE_STRING;
  2883. case UPB_DESCRIPTOR_TYPE_BYTES:
  2884. return UPB_TYPE_BYTES;
  2885. case UPB_DESCRIPTOR_TYPE_GROUP:
  2886. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  2887. return UPB_TYPE_MESSAGE;
  2888. }
  2889. UPB_UNREACHABLE();
  2890. }
  2891. upb_descriptortype_t upb_fielddef_descriptortype(const upb_fielddef *f) {
  2892. return f->type_;
  2893. }
  2894. uint32_t upb_fielddef_index(const upb_fielddef *f) {
  2895. return f->index_;
  2896. }
  2897. upb_label_t upb_fielddef_label(const upb_fielddef *f) {
  2898. return f->label_;
  2899. }
  2900. uint32_t upb_fielddef_number(const upb_fielddef *f) {
  2901. return f->number_;
  2902. }
  2903. bool upb_fielddef_isextension(const upb_fielddef *f) {
  2904. return f->is_extension_;
  2905. }
  2906. bool upb_fielddef_lazy(const upb_fielddef *f) {
  2907. return f->lazy_;
  2908. }
  2909. bool upb_fielddef_packed(const upb_fielddef *f) {
  2910. return f->packed_;
  2911. }
  2912. const char *upb_fielddef_name(const upb_fielddef *f) {
  2913. return shortdefname(f->full_name);
  2914. }
  2915. const char *upb_fielddef_jsonname(const upb_fielddef *f) {
  2916. return f->json_name;
  2917. }
  2918. uint32_t upb_fielddef_selectorbase(const upb_fielddef *f) {
  2919. return f->selector_base;
  2920. }
  2921. const upb_msgdef *upb_fielddef_containingtype(const upb_fielddef *f) {
  2922. return f->msgdef;
  2923. }
  2924. const upb_oneofdef *upb_fielddef_containingoneof(const upb_fielddef *f) {
  2925. return f->oneof;
  2926. }
  2927. static void chkdefaulttype(const upb_fielddef *f, int ctype) {
  2928. UPB_UNUSED(f);
  2929. UPB_UNUSED(ctype);
  2930. }
  2931. int64_t upb_fielddef_defaultint64(const upb_fielddef *f) {
  2932. chkdefaulttype(f, UPB_TYPE_INT64);
  2933. return f->defaultval.sint;
  2934. }
  2935. int32_t upb_fielddef_defaultint32(const upb_fielddef *f) {
  2936. chkdefaulttype(f, UPB_TYPE_INT32);
  2937. return (int32_t)f->defaultval.sint;
  2938. }
  2939. uint64_t upb_fielddef_defaultuint64(const upb_fielddef *f) {
  2940. chkdefaulttype(f, UPB_TYPE_UINT64);
  2941. return f->defaultval.uint;
  2942. }
  2943. uint32_t upb_fielddef_defaultuint32(const upb_fielddef *f) {
  2944. chkdefaulttype(f, UPB_TYPE_UINT32);
  2945. return (uint32_t)f->defaultval.uint;
  2946. }
  2947. bool upb_fielddef_defaultbool(const upb_fielddef *f) {
  2948. chkdefaulttype(f, UPB_TYPE_BOOL);
  2949. return f->defaultval.boolean;
  2950. }
  2951. float upb_fielddef_defaultfloat(const upb_fielddef *f) {
  2952. chkdefaulttype(f, UPB_TYPE_FLOAT);
  2953. return f->defaultval.flt;
  2954. }
  2955. double upb_fielddef_defaultdouble(const upb_fielddef *f) {
  2956. chkdefaulttype(f, UPB_TYPE_DOUBLE);
  2957. return f->defaultval.dbl;
  2958. }
  2959. const char *upb_fielddef_defaultstr(const upb_fielddef *f, size_t *len) {
  2960. str_t *str = f->defaultval.str;
  2961. UPB_ASSERT(upb_fielddef_type(f) == UPB_TYPE_STRING ||
  2962. upb_fielddef_type(f) == UPB_TYPE_BYTES ||
  2963. upb_fielddef_type(f) == UPB_TYPE_ENUM);
  2964. if (str) {
  2965. if (len) *len = str->len;
  2966. return str->str;
  2967. } else {
  2968. if (len) *len = 0;
  2969. return NULL;
  2970. }
  2971. }
  2972. const upb_msgdef *upb_fielddef_msgsubdef(const upb_fielddef *f) {
  2973. UPB_ASSERT(upb_fielddef_type(f) == UPB_TYPE_MESSAGE);
  2974. return f->sub.msgdef;
  2975. }
  2976. const upb_enumdef *upb_fielddef_enumsubdef(const upb_fielddef *f) {
  2977. UPB_ASSERT(upb_fielddef_type(f) == UPB_TYPE_ENUM);
  2978. return f->sub.enumdef;
  2979. }
  2980. const upb_msglayout_field *upb_fielddef_layout(const upb_fielddef *f) {
  2981. return &f->msgdef->layout->fields[f->layout_index];
  2982. }
  2983. bool upb_fielddef_issubmsg(const upb_fielddef *f) {
  2984. return upb_fielddef_type(f) == UPB_TYPE_MESSAGE;
  2985. }
  2986. bool upb_fielddef_isstring(const upb_fielddef *f) {
  2987. return upb_fielddef_type(f) == UPB_TYPE_STRING ||
  2988. upb_fielddef_type(f) == UPB_TYPE_BYTES;
  2989. }
  2990. bool upb_fielddef_isseq(const upb_fielddef *f) {
  2991. return upb_fielddef_label(f) == UPB_LABEL_REPEATED;
  2992. }
  2993. bool upb_fielddef_isprimitive(const upb_fielddef *f) {
  2994. return !upb_fielddef_isstring(f) && !upb_fielddef_issubmsg(f);
  2995. }
  2996. bool upb_fielddef_ismap(const upb_fielddef *f) {
  2997. return upb_fielddef_isseq(f) && upb_fielddef_issubmsg(f) &&
  2998. upb_msgdef_mapentry(upb_fielddef_msgsubdef(f));
  2999. }
  3000. bool upb_fielddef_hassubdef(const upb_fielddef *f) {
  3001. return upb_fielddef_issubmsg(f) || upb_fielddef_type(f) == UPB_TYPE_ENUM;
  3002. }
  3003. bool upb_fielddef_haspresence(const upb_fielddef *f) {
  3004. if (upb_fielddef_isseq(f)) return false;
  3005. if (upb_fielddef_issubmsg(f)) return true;
  3006. if (f->proto3_optional_) return true;
  3007. return f->file->syntax == UPB_SYNTAX_PROTO2;
  3008. }
  3009. static bool between(int32_t x, int32_t low, int32_t high) {
  3010. return x >= low && x <= high;
  3011. }
  3012. bool upb_fielddef_checklabel(int32_t label) { return between(label, 1, 3); }
  3013. bool upb_fielddef_checktype(int32_t type) { return between(type, 1, 11); }
  3014. bool upb_fielddef_checkintfmt(int32_t fmt) { return between(fmt, 1, 3); }
  3015. bool upb_fielddef_checkdescriptortype(int32_t type) {
  3016. return between(type, 1, 18);
  3017. }
  3018. /* upb_msgdef *****************************************************************/
  3019. const char *upb_msgdef_fullname(const upb_msgdef *m) {
  3020. return m->full_name;
  3021. }
  3022. const upb_filedef *upb_msgdef_file(const upb_msgdef *m) {
  3023. return m->file;
  3024. }
  3025. const char *upb_msgdef_name(const upb_msgdef *m) {
  3026. return shortdefname(m->full_name);
  3027. }
  3028. upb_syntax_t upb_msgdef_syntax(const upb_msgdef *m) {
  3029. return m->file->syntax;
  3030. }
  3031. size_t upb_msgdef_selectorcount(const upb_msgdef *m) {
  3032. return m->selector_count;
  3033. }
  3034. uint32_t upb_msgdef_submsgfieldcount(const upb_msgdef *m) {
  3035. return m->submsg_field_count;
  3036. }
  3037. const upb_fielddef *upb_msgdef_itof(const upb_msgdef *m, uint32_t i) {
  3038. upb_value val;
  3039. return upb_inttable_lookup32(&m->itof, i, &val) ?
  3040. upb_value_getconstptr(val) : NULL;
  3041. }
  3042. const upb_fielddef *upb_msgdef_ntof(const upb_msgdef *m, const char *name,
  3043. size_t len) {
  3044. upb_value val;
  3045. if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
  3046. return NULL;
  3047. }
  3048. return unpack_def(val, UPB_DEFTYPE_FIELD);
  3049. }
  3050. const upb_oneofdef *upb_msgdef_ntoo(const upb_msgdef *m, const char *name,
  3051. size_t len) {
  3052. upb_value val;
  3053. if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
  3054. return NULL;
  3055. }
  3056. return unpack_def(val, UPB_DEFTYPE_ONEOF);
  3057. }
  3058. bool upb_msgdef_lookupname(const upb_msgdef *m, const char *name, size_t len,
  3059. const upb_fielddef **f, const upb_oneofdef **o) {
  3060. upb_value val;
  3061. if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
  3062. return false;
  3063. }
  3064. *o = unpack_def(val, UPB_DEFTYPE_ONEOF);
  3065. *f = unpack_def(val, UPB_DEFTYPE_FIELD);
  3066. return *o || *f; /* False if this was a JSON name. */
  3067. }
  3068. const upb_fielddef *upb_msgdef_lookupjsonname(const upb_msgdef *m,
  3069. const char *name, size_t len) {
  3070. upb_value val;
  3071. const upb_fielddef* f;
  3072. if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
  3073. return NULL;
  3074. }
  3075. f = unpack_def(val, UPB_DEFTYPE_FIELD);
  3076. if (!f) f = unpack_def(val, UPB_DEFTYPE_FIELD_JSONNAME);
  3077. return f;
  3078. }
  3079. int upb_msgdef_numfields(const upb_msgdef *m) {
  3080. return m->field_count;
  3081. }
  3082. int upb_msgdef_numoneofs(const upb_msgdef *m) {
  3083. return m->oneof_count;
  3084. }
  3085. const upb_msglayout *upb_msgdef_layout(const upb_msgdef *m) {
  3086. return m->layout;
  3087. }
  3088. const upb_fielddef *_upb_msgdef_field(const upb_msgdef *m, int i) {
  3089. if (i >= m->field_count) return NULL;
  3090. return &m->fields[i];
  3091. }
  3092. bool upb_msgdef_mapentry(const upb_msgdef *m) {
  3093. return m->map_entry;
  3094. }
  3095. upb_wellknowntype_t upb_msgdef_wellknowntype(const upb_msgdef *m) {
  3096. return m->well_known_type;
  3097. }
  3098. bool upb_msgdef_isnumberwrapper(const upb_msgdef *m) {
  3099. upb_wellknowntype_t type = upb_msgdef_wellknowntype(m);
  3100. return type >= UPB_WELLKNOWN_DOUBLEVALUE &&
  3101. type <= UPB_WELLKNOWN_UINT32VALUE;
  3102. }
  3103. void upb_msg_field_begin(upb_msg_field_iter *iter, const upb_msgdef *m) {
  3104. upb_inttable_begin(iter, &m->itof);
  3105. }
  3106. void upb_msg_field_next(upb_msg_field_iter *iter) { upb_inttable_next(iter); }
  3107. bool upb_msg_field_done(const upb_msg_field_iter *iter) {
  3108. return upb_inttable_done(iter);
  3109. }
  3110. upb_fielddef *upb_msg_iter_field(const upb_msg_field_iter *iter) {
  3111. return (upb_fielddef *)upb_value_getconstptr(upb_inttable_iter_value(iter));
  3112. }
  3113. void upb_msg_field_iter_setdone(upb_msg_field_iter *iter) {
  3114. upb_inttable_iter_setdone(iter);
  3115. }
  3116. bool upb_msg_field_iter_isequal(const upb_msg_field_iter * iter1,
  3117. const upb_msg_field_iter * iter2) {
  3118. return upb_inttable_iter_isequal(iter1, iter2);
  3119. }
  3120. void upb_msg_oneof_begin(upb_msg_oneof_iter *iter, const upb_msgdef *m) {
  3121. upb_strtable_begin(iter, &m->ntof);
  3122. /* We need to skip past any initial fields. */
  3123. while (!upb_strtable_done(iter) &&
  3124. !unpack_def(upb_strtable_iter_value(iter), UPB_DEFTYPE_ONEOF)) {
  3125. upb_strtable_next(iter);
  3126. }
  3127. }
  3128. void upb_msg_oneof_next(upb_msg_oneof_iter *iter) {
  3129. /* We need to skip past fields to return only oneofs. */
  3130. do {
  3131. upb_strtable_next(iter);
  3132. } while (!upb_strtable_done(iter) &&
  3133. !unpack_def(upb_strtable_iter_value(iter), UPB_DEFTYPE_ONEOF));
  3134. }
  3135. bool upb_msg_oneof_done(const upb_msg_oneof_iter *iter) {
  3136. return upb_strtable_done(iter);
  3137. }
  3138. const upb_oneofdef *upb_msg_iter_oneof(const upb_msg_oneof_iter *iter) {
  3139. return unpack_def(upb_strtable_iter_value(iter), UPB_DEFTYPE_ONEOF);
  3140. }
  3141. void upb_msg_oneof_iter_setdone(upb_msg_oneof_iter *iter) {
  3142. upb_strtable_iter_setdone(iter);
  3143. }
  3144. bool upb_msg_oneof_iter_isequal(const upb_msg_oneof_iter *iter1,
  3145. const upb_msg_oneof_iter *iter2) {
  3146. return upb_strtable_iter_isequal(iter1, iter2);
  3147. }
  3148. /* upb_oneofdef ***************************************************************/
  3149. const char *upb_oneofdef_name(const upb_oneofdef *o) {
  3150. return shortdefname(o->full_name);
  3151. }
  3152. const upb_msgdef *upb_oneofdef_containingtype(const upb_oneofdef *o) {
  3153. return o->parent;
  3154. }
  3155. int upb_oneofdef_numfields(const upb_oneofdef *o) {
  3156. return (int)upb_strtable_count(&o->ntof);
  3157. }
  3158. uint32_t upb_oneofdef_index(const upb_oneofdef *o) {
  3159. return o->index;
  3160. }
  3161. bool upb_oneofdef_synthetic(const upb_oneofdef *o) {
  3162. upb_inttable_iter iter;
  3163. const upb_fielddef *f;
  3164. upb_inttable_begin(&iter, &o->itof);
  3165. if (upb_oneofdef_numfields(o) != 1) return false;
  3166. f = upb_value_getptr(upb_inttable_iter_value(&iter));
  3167. UPB_ASSERT(f);
  3168. return f->proto3_optional_;
  3169. }
  3170. const upb_fielddef *upb_oneofdef_ntof(const upb_oneofdef *o,
  3171. const char *name, size_t length) {
  3172. upb_value val;
  3173. return upb_strtable_lookup2(&o->ntof, name, length, &val) ?
  3174. upb_value_getptr(val) : NULL;
  3175. }
  3176. const upb_fielddef *upb_oneofdef_itof(const upb_oneofdef *o, uint32_t num) {
  3177. upb_value val;
  3178. return upb_inttable_lookup32(&o->itof, num, &val) ?
  3179. upb_value_getptr(val) : NULL;
  3180. }
  3181. void upb_oneof_begin(upb_oneof_iter *iter, const upb_oneofdef *o) {
  3182. upb_inttable_begin(iter, &o->itof);
  3183. }
  3184. void upb_oneof_next(upb_oneof_iter *iter) {
  3185. upb_inttable_next(iter);
  3186. }
  3187. bool upb_oneof_done(upb_oneof_iter *iter) {
  3188. return upb_inttable_done(iter);
  3189. }
  3190. upb_fielddef *upb_oneof_iter_field(const upb_oneof_iter *iter) {
  3191. return (upb_fielddef *)upb_value_getconstptr(upb_inttable_iter_value(iter));
  3192. }
  3193. void upb_oneof_iter_setdone(upb_oneof_iter *iter) {
  3194. upb_inttable_iter_setdone(iter);
  3195. }
  3196. /* Dynamic Layout Generation. *************************************************/
  3197. static bool is_power_of_two(size_t val) {
  3198. return (val & (val - 1)) == 0;
  3199. }
  3200. /* Align up to the given power of 2. */
  3201. static size_t align_up(size_t val, size_t align) {
  3202. UPB_ASSERT(is_power_of_two(align));
  3203. return (val + align - 1) & ~(align - 1);
  3204. }
  3205. static size_t div_round_up(size_t n, size_t d) {
  3206. return (n + d - 1) / d;
  3207. }
  3208. static size_t upb_msgval_sizeof(upb_fieldtype_t type) {
  3209. switch (type) {
  3210. case UPB_TYPE_DOUBLE:
  3211. case UPB_TYPE_INT64:
  3212. case UPB_TYPE_UINT64:
  3213. return 8;
  3214. case UPB_TYPE_ENUM:
  3215. case UPB_TYPE_INT32:
  3216. case UPB_TYPE_UINT32:
  3217. case UPB_TYPE_FLOAT:
  3218. return 4;
  3219. case UPB_TYPE_BOOL:
  3220. return 1;
  3221. case UPB_TYPE_MESSAGE:
  3222. return sizeof(void*);
  3223. case UPB_TYPE_BYTES:
  3224. case UPB_TYPE_STRING:
  3225. return sizeof(upb_strview);
  3226. }
  3227. UPB_UNREACHABLE();
  3228. }
  3229. static uint8_t upb_msg_fielddefsize(const upb_fielddef *f) {
  3230. if (upb_msgdef_mapentry(upb_fielddef_containingtype(f))) {
  3231. upb_map_entry ent;
  3232. UPB_ASSERT(sizeof(ent.k) == sizeof(ent.v));
  3233. return sizeof(ent.k);
  3234. } else if (upb_fielddef_isseq(f)) {
  3235. return sizeof(void*);
  3236. } else {
  3237. return upb_msgval_sizeof(upb_fielddef_type(f));
  3238. }
  3239. }
  3240. static uint32_t upb_msglayout_place(upb_msglayout *l, size_t size) {
  3241. uint32_t ret;
  3242. l->size = align_up(l->size, size);
  3243. ret = l->size;
  3244. l->size += size;
  3245. return ret;
  3246. }
  3247. /* This function is the dynamic equivalent of message_layout.{cc,h} in upbc.
  3248. * It computes a dynamic layout for all of the fields in |m|. */
  3249. static bool make_layout(const upb_symtab *symtab, const upb_msgdef *m) {
  3250. upb_msglayout *l = (upb_msglayout*)m->layout;
  3251. upb_msg_field_iter it;
  3252. upb_msg_oneof_iter oit;
  3253. size_t hasbit;
  3254. size_t submsg_count = m->submsg_field_count;
  3255. const upb_msglayout **submsgs;
  3256. upb_msglayout_field *fields;
  3257. upb_alloc *alloc = upb_arena_alloc(symtab->arena);
  3258. memset(l, 0, sizeof(*l));
  3259. fields = upb_malloc(alloc, upb_msgdef_numfields(m) * sizeof(*fields));
  3260. submsgs = upb_malloc(alloc, submsg_count * sizeof(*submsgs));
  3261. if ((!fields && upb_msgdef_numfields(m)) ||
  3262. (!submsgs && submsg_count)) {
  3263. /* OOM. */
  3264. return false;
  3265. }
  3266. l->field_count = upb_msgdef_numfields(m);
  3267. l->fields = fields;
  3268. l->submsgs = submsgs;
  3269. if (upb_msgdef_mapentry(m)) {
  3270. /* TODO(haberman): refactor this method so this special case is more
  3271. * elegant. */
  3272. const upb_fielddef *key = upb_msgdef_itof(m, 1);
  3273. const upb_fielddef *val = upb_msgdef_itof(m, 2);
  3274. fields[0].number = 1;
  3275. fields[1].number = 2;
  3276. fields[0].label = UPB_LABEL_OPTIONAL;
  3277. fields[1].label = UPB_LABEL_OPTIONAL;
  3278. fields[0].presence = 0;
  3279. fields[1].presence = 0;
  3280. fields[0].descriptortype = upb_fielddef_descriptortype(key);
  3281. fields[1].descriptortype = upb_fielddef_descriptortype(val);
  3282. fields[0].offset = 0;
  3283. fields[1].offset = sizeof(upb_strview);
  3284. fields[1].submsg_index = 0;
  3285. if (upb_fielddef_type(val) == UPB_TYPE_MESSAGE) {
  3286. submsgs[0] = upb_fielddef_msgsubdef(val)->layout;
  3287. }
  3288. l->field_count = 2;
  3289. l->size = 2 * sizeof(upb_strview);align_up(l->size, 8);
  3290. return true;
  3291. }
  3292. /* Allocate data offsets in three stages:
  3293. *
  3294. * 1. hasbits.
  3295. * 2. regular fields.
  3296. * 3. oneof fields.
  3297. *
  3298. * OPT: There is a lot of room for optimization here to minimize the size.
  3299. */
  3300. /* Allocate hasbits and set basic field attributes. */
  3301. submsg_count = 0;
  3302. for (upb_msg_field_begin(&it, m), hasbit = 0;
  3303. !upb_msg_field_done(&it);
  3304. upb_msg_field_next(&it)) {
  3305. upb_fielddef* f = upb_msg_iter_field(&it);
  3306. upb_msglayout_field *field = &fields[upb_fielddef_index(f)];
  3307. field->number = upb_fielddef_number(f);
  3308. field->descriptortype = upb_fielddef_descriptortype(f);
  3309. field->label = upb_fielddef_label(f);
  3310. if (upb_fielddef_ismap(f)) {
  3311. field->label = _UPB_LABEL_MAP;
  3312. } else if (upb_fielddef_packed(f)) {
  3313. field->label = _UPB_LABEL_PACKED;
  3314. }
  3315. /* TODO: we probably should sort the fields by field number to match the
  3316. * output of upbc, and to improve search speed for the table parser. */
  3317. f->layout_index = f->index_;
  3318. if (upb_fielddef_issubmsg(f)) {
  3319. const upb_msgdef *subm = upb_fielddef_msgsubdef(f);
  3320. field->submsg_index = submsg_count++;
  3321. submsgs[field->submsg_index] = subm->layout;
  3322. }
  3323. if (upb_fielddef_haspresence(f) && !upb_fielddef_containingoneof(f)) {
  3324. /* We don't use hasbit 0, so that 0 can indicate "no presence" in the
  3325. * table. This wastes one hasbit, but we don't worry about it for now. */
  3326. field->presence = ++hasbit;
  3327. } else {
  3328. field->presence = 0;
  3329. }
  3330. }
  3331. /* Account for space used by hasbits. */
  3332. l->size = div_round_up(hasbit, 8);
  3333. /* Allocate non-oneof fields. */
  3334. for (upb_msg_field_begin(&it, m); !upb_msg_field_done(&it);
  3335. upb_msg_field_next(&it)) {
  3336. const upb_fielddef* f = upb_msg_iter_field(&it);
  3337. size_t field_size = upb_msg_fielddefsize(f);
  3338. size_t index = upb_fielddef_index(f);
  3339. if (upb_fielddef_containingoneof(f)) {
  3340. /* Oneofs are handled separately below. */
  3341. continue;
  3342. }
  3343. fields[index].offset = upb_msglayout_place(l, field_size);
  3344. }
  3345. /* Allocate oneof fields. Each oneof field consists of a uint32 for the case
  3346. * and space for the actual data. */
  3347. for (upb_msg_oneof_begin(&oit, m); !upb_msg_oneof_done(&oit);
  3348. upb_msg_oneof_next(&oit)) {
  3349. const upb_oneofdef* o = upb_msg_iter_oneof(&oit);
  3350. upb_oneof_iter fit;
  3351. size_t case_size = sizeof(uint32_t); /* Could potentially optimize this. */
  3352. size_t field_size = 0;
  3353. uint32_t case_offset;
  3354. uint32_t data_offset;
  3355. /* Calculate field size: the max of all field sizes. */
  3356. for (upb_oneof_begin(&fit, o);
  3357. !upb_oneof_done(&fit);
  3358. upb_oneof_next(&fit)) {
  3359. const upb_fielddef* f = upb_oneof_iter_field(&fit);
  3360. field_size = UPB_MAX(field_size, upb_msg_fielddefsize(f));
  3361. }
  3362. /* Align and allocate case offset. */
  3363. case_offset = upb_msglayout_place(l, case_size);
  3364. data_offset = upb_msglayout_place(l, field_size);
  3365. for (upb_oneof_begin(&fit, o);
  3366. !upb_oneof_done(&fit);
  3367. upb_oneof_next(&fit)) {
  3368. const upb_fielddef* f = upb_oneof_iter_field(&fit);
  3369. fields[upb_fielddef_index(f)].offset = data_offset;
  3370. fields[upb_fielddef_index(f)].presence = ~case_offset;
  3371. }
  3372. }
  3373. /* Size of the entire structure should be a multiple of its greatest
  3374. * alignment. TODO: track overall alignment for real? */
  3375. l->size = align_up(l->size, 8);
  3376. return true;
  3377. }
  3378. /* Code to build defs from descriptor protos. *********************************/
  3379. /* There is a question of how much validation to do here. It will be difficult
  3380. * to perfectly match the amount of validation performed by proto2. But since
  3381. * this code is used to directly build defs from Ruby (for example) we do need
  3382. * to validate important constraints like uniqueness of names and numbers. */
  3383. #define CHK(x) if (!(x)) { return false; }
  3384. #define CHK_OOM(x) if (!(x)) { upb_status_setoom(ctx->status); return false; }
  3385. typedef struct {
  3386. const upb_symtab *symtab;
  3387. upb_filedef *file; /* File we are building. */
  3388. upb_alloc *alloc; /* Allocate defs here. */
  3389. upb_alloc *tmp; /* Alloc for addtab and any other tmp data. */
  3390. upb_strtable *addtab; /* full_name -> packed def ptr for new defs */
  3391. const upb_msglayout **layouts; /* NULL if we should build layouts. */
  3392. upb_status *status; /* Record errors here. */
  3393. } symtab_addctx;
  3394. static char* strviewdup(const symtab_addctx *ctx, upb_strview view) {
  3395. return upb_strdup2(view.data, view.size, ctx->alloc);
  3396. }
  3397. static bool streql2(const char *a, size_t n, const char *b) {
  3398. return n == strlen(b) && memcmp(a, b, n) == 0;
  3399. }
  3400. static bool streql_view(upb_strview view, const char *b) {
  3401. return streql2(view.data, view.size, b);
  3402. }
  3403. static const char *makefullname(const symtab_addctx *ctx, const char *prefix,
  3404. upb_strview name) {
  3405. if (prefix) {
  3406. /* ret = prefix + '.' + name; */
  3407. size_t n = strlen(prefix);
  3408. char *ret = upb_malloc(ctx->alloc, n + name.size + 2);
  3409. CHK_OOM(ret);
  3410. strcpy(ret, prefix);
  3411. ret[n] = '.';
  3412. memcpy(&ret[n + 1], name.data, name.size);
  3413. ret[n + 1 + name.size] = '\0';
  3414. return ret;
  3415. } else {
  3416. return strviewdup(ctx, name);
  3417. }
  3418. }
  3419. size_t getjsonname(const char *name, char *buf, size_t len) {
  3420. size_t src, dst = 0;
  3421. bool ucase_next = false;
  3422. #define WRITE(byte) \
  3423. ++dst; \
  3424. if (dst < len) buf[dst - 1] = byte; \
  3425. else if (dst == len) buf[dst - 1] = '\0'
  3426. if (!name) {
  3427. WRITE('\0');
  3428. return 0;
  3429. }
  3430. /* Implement the transformation as described in the spec:
  3431. * 1. upper case all letters after an underscore.
  3432. * 2. remove all underscores.
  3433. */
  3434. for (src = 0; name[src]; src++) {
  3435. if (name[src] == '_') {
  3436. ucase_next = true;
  3437. continue;
  3438. }
  3439. if (ucase_next) {
  3440. WRITE(toupper(name[src]));
  3441. ucase_next = false;
  3442. } else {
  3443. WRITE(name[src]);
  3444. }
  3445. }
  3446. WRITE('\0');
  3447. return dst;
  3448. #undef WRITE
  3449. }
  3450. static char* makejsonname(const char* name, upb_alloc *alloc) {
  3451. size_t size = getjsonname(name, NULL, 0);
  3452. char* json_name = upb_malloc(alloc, size);
  3453. getjsonname(name, json_name, size);
  3454. return json_name;
  3455. }
  3456. static bool symtab_add(const symtab_addctx *ctx, const char *name,
  3457. upb_value v) {
  3458. upb_value tmp;
  3459. if (upb_strtable_lookup(ctx->addtab, name, &tmp) ||
  3460. upb_strtable_lookup(&ctx->symtab->syms, name, &tmp)) {
  3461. upb_status_seterrf(ctx->status, "duplicate symbol '%s'", name);
  3462. return false;
  3463. }
  3464. CHK_OOM(upb_strtable_insert3(ctx->addtab, name, strlen(name), v, ctx->tmp));
  3465. return true;
  3466. }
  3467. /* Given a symbol and the base symbol inside which it is defined, find the
  3468. * symbol's definition in t. */
  3469. static bool resolvename(const upb_strtable *t, const upb_fielddef *f,
  3470. const char *base, upb_strview sym,
  3471. upb_deftype_t type, upb_status *status,
  3472. const void **def) {
  3473. if(sym.size == 0) return NULL;
  3474. if(sym.data[0] == '.') {
  3475. /* Symbols starting with '.' are absolute, so we do a single lookup.
  3476. * Slice to omit the leading '.' */
  3477. upb_value v;
  3478. if (!upb_strtable_lookup2(t, sym.data + 1, sym.size - 1, &v)) {
  3479. return false;
  3480. }
  3481. *def = unpack_def(v, type);
  3482. if (!*def) {
  3483. upb_status_seterrf(status,
  3484. "type mismatch when resolving field %s, name %s",
  3485. f->full_name, sym.data);
  3486. return false;
  3487. }
  3488. return true;
  3489. } else {
  3490. /* Remove components from base until we find an entry or run out.
  3491. * TODO: This branch is totally broken, but currently not used. */
  3492. (void)base;
  3493. UPB_ASSERT(false);
  3494. return false;
  3495. }
  3496. }
  3497. const void *symtab_resolve(const symtab_addctx *ctx, const upb_fielddef *f,
  3498. const char *base, upb_strview sym,
  3499. upb_deftype_t type) {
  3500. const void *ret;
  3501. if (!resolvename(ctx->addtab, f, base, sym, type, ctx->status, &ret) &&
  3502. !resolvename(&ctx->symtab->syms, f, base, sym, type, ctx->status, &ret)) {
  3503. if (upb_ok(ctx->status)) {
  3504. upb_status_seterrf(ctx->status, "couldn't resolve name '%s'", sym.data);
  3505. }
  3506. return false;
  3507. }
  3508. return ret;
  3509. }
  3510. static bool create_oneofdef(
  3511. const symtab_addctx *ctx, upb_msgdef *m,
  3512. const google_protobuf_OneofDescriptorProto *oneof_proto) {
  3513. upb_oneofdef *o;
  3514. upb_strview name = google_protobuf_OneofDescriptorProto_name(oneof_proto);
  3515. upb_value v;
  3516. o = (upb_oneofdef*)&m->oneofs[m->oneof_count++];
  3517. o->parent = m;
  3518. o->full_name = makefullname(ctx, m->full_name, name);
  3519. v = pack_def(o, UPB_DEFTYPE_ONEOF);
  3520. CHK_OOM(symtab_add(ctx, o->full_name, v));
  3521. CHK_OOM(upb_strtable_insert3(&m->ntof, name.data, name.size, v, ctx->alloc));
  3522. CHK_OOM(upb_inttable_init2(&o->itof, UPB_CTYPE_CONSTPTR, ctx->alloc));
  3523. CHK_OOM(upb_strtable_init2(&o->ntof, UPB_CTYPE_CONSTPTR, ctx->alloc));
  3524. return true;
  3525. }
  3526. static bool parse_default(const symtab_addctx *ctx, const char *str, size_t len,
  3527. upb_fielddef *f) {
  3528. char *end;
  3529. char nullz[64];
  3530. errno = 0;
  3531. switch (upb_fielddef_type(f)) {
  3532. case UPB_TYPE_INT32:
  3533. case UPB_TYPE_INT64:
  3534. case UPB_TYPE_UINT32:
  3535. case UPB_TYPE_UINT64:
  3536. case UPB_TYPE_DOUBLE:
  3537. case UPB_TYPE_FLOAT:
  3538. /* Standard C number parsing functions expect null-terminated strings. */
  3539. if (len >= sizeof(nullz) - 1) {
  3540. return false;
  3541. }
  3542. memcpy(nullz, str, len);
  3543. nullz[len] = '\0';
  3544. str = nullz;
  3545. break;
  3546. default:
  3547. break;
  3548. }
  3549. switch (upb_fielddef_type(f)) {
  3550. case UPB_TYPE_INT32: {
  3551. long val = strtol(str, &end, 0);
  3552. CHK(val <= INT32_MAX && val >= INT32_MIN && errno != ERANGE && !*end);
  3553. f->defaultval.sint = val;
  3554. break;
  3555. }
  3556. case UPB_TYPE_ENUM: {
  3557. const upb_enumdef *e = f->sub.enumdef;
  3558. int32_t val;
  3559. CHK(upb_enumdef_ntoi(e, str, len, &val));
  3560. f->defaultval.sint = val;
  3561. break;
  3562. }
  3563. case UPB_TYPE_INT64: {
  3564. /* XXX: Need to write our own strtoll, since it's not available in c89. */
  3565. int64_t val = strtol(str, &end, 0);
  3566. CHK(val <= INT64_MAX && val >= INT64_MIN && errno != ERANGE && !*end);
  3567. f->defaultval.sint = val;
  3568. break;
  3569. }
  3570. case UPB_TYPE_UINT32: {
  3571. unsigned long val = strtoul(str, &end, 0);
  3572. CHK(val <= UINT32_MAX && errno != ERANGE && !*end);
  3573. f->defaultval.uint = val;
  3574. break;
  3575. }
  3576. case UPB_TYPE_UINT64: {
  3577. /* XXX: Need to write our own strtoull, since it's not available in c89. */
  3578. uint64_t val = strtoul(str, &end, 0);
  3579. CHK(val <= UINT64_MAX && errno != ERANGE && !*end);
  3580. f->defaultval.uint = val;
  3581. break;
  3582. }
  3583. case UPB_TYPE_DOUBLE: {
  3584. double val = strtod(str, &end);
  3585. CHK(errno != ERANGE && !*end);
  3586. f->defaultval.dbl = val;
  3587. break;
  3588. }
  3589. case UPB_TYPE_FLOAT: {
  3590. /* XXX: Need to write our own strtof, since it's not available in c89. */
  3591. float val = strtod(str, &end);
  3592. CHK(errno != ERANGE && !*end);
  3593. f->defaultval.flt = val;
  3594. break;
  3595. }
  3596. case UPB_TYPE_BOOL: {
  3597. if (streql2(str, len, "false")) {
  3598. f->defaultval.boolean = false;
  3599. } else if (streql2(str, len, "true")) {
  3600. f->defaultval.boolean = true;
  3601. } else {
  3602. return false;
  3603. }
  3604. break;
  3605. }
  3606. case UPB_TYPE_STRING:
  3607. f->defaultval.str = newstr(ctx->alloc, str, len);
  3608. break;
  3609. case UPB_TYPE_BYTES:
  3610. /* XXX: need to interpret the C-escaped value. */
  3611. f->defaultval.str = newstr(ctx->alloc, str, len);
  3612. break;
  3613. case UPB_TYPE_MESSAGE:
  3614. /* Should not have a default value. */
  3615. return false;
  3616. }
  3617. return true;
  3618. }
  3619. static void set_default_default(const symtab_addctx *ctx, upb_fielddef *f) {
  3620. switch (upb_fielddef_type(f)) {
  3621. case UPB_TYPE_INT32:
  3622. case UPB_TYPE_INT64:
  3623. case UPB_TYPE_ENUM:
  3624. f->defaultval.sint = 0;
  3625. break;
  3626. case UPB_TYPE_UINT64:
  3627. case UPB_TYPE_UINT32:
  3628. f->defaultval.uint = 0;
  3629. break;
  3630. case UPB_TYPE_DOUBLE:
  3631. case UPB_TYPE_FLOAT:
  3632. f->defaultval.dbl = 0;
  3633. break;
  3634. case UPB_TYPE_STRING:
  3635. case UPB_TYPE_BYTES:
  3636. f->defaultval.str = newstr(ctx->alloc, NULL, 0);
  3637. break;
  3638. case UPB_TYPE_BOOL:
  3639. f->defaultval.boolean = false;
  3640. break;
  3641. case UPB_TYPE_MESSAGE:
  3642. break;
  3643. }
  3644. }
  3645. static bool create_fielddef(
  3646. const symtab_addctx *ctx, const char *prefix, upb_msgdef *m,
  3647. const google_protobuf_FieldDescriptorProto *field_proto) {
  3648. upb_alloc *alloc = ctx->alloc;
  3649. upb_fielddef *f;
  3650. const google_protobuf_FieldOptions *options;
  3651. upb_strview name;
  3652. const char *full_name;
  3653. const char *json_name;
  3654. const char *shortname;
  3655. uint32_t field_number;
  3656. if (!google_protobuf_FieldDescriptorProto_has_name(field_proto)) {
  3657. upb_status_seterrmsg(ctx->status, "field has no name");
  3658. return false;
  3659. }
  3660. name = google_protobuf_FieldDescriptorProto_name(field_proto);
  3661. CHK(upb_isident(name, false, ctx->status));
  3662. full_name = makefullname(ctx, prefix, name);
  3663. shortname = shortdefname(full_name);
  3664. if (google_protobuf_FieldDescriptorProto_has_json_name(field_proto)) {
  3665. json_name = strviewdup(
  3666. ctx, google_protobuf_FieldDescriptorProto_json_name(field_proto));
  3667. } else {
  3668. json_name = makejsonname(shortname, ctx->alloc);
  3669. }
  3670. field_number = google_protobuf_FieldDescriptorProto_number(field_proto);
  3671. if (field_number == 0 || field_number > UPB_MAX_FIELDNUMBER) {
  3672. upb_status_seterrf(ctx->status, "invalid field number (%u)", field_number);
  3673. return false;
  3674. }
  3675. if (m) {
  3676. /* direct message field. */
  3677. upb_value v, field_v, json_v;
  3678. size_t json_size;
  3679. f = (upb_fielddef*)&m->fields[m->field_count++];
  3680. f->msgdef = m;
  3681. f->is_extension_ = false;
  3682. if (upb_strtable_lookup(&m->ntof, shortname, NULL)) {
  3683. upb_status_seterrf(ctx->status, "duplicate field name (%s)", shortname);
  3684. return false;
  3685. }
  3686. if (upb_strtable_lookup(&m->ntof, json_name, NULL)) {
  3687. upb_status_seterrf(ctx->status, "duplicate json_name (%s)", json_name);
  3688. return false;
  3689. }
  3690. if (upb_inttable_lookup(&m->itof, field_number, NULL)) {
  3691. upb_status_seterrf(ctx->status, "duplicate field number (%u)",
  3692. field_number);
  3693. return false;
  3694. }
  3695. field_v = pack_def(f, UPB_DEFTYPE_FIELD);
  3696. json_v = pack_def(f, UPB_DEFTYPE_FIELD_JSONNAME);
  3697. v = upb_value_constptr(f);
  3698. json_size = strlen(json_name);
  3699. CHK_OOM(
  3700. upb_strtable_insert3(&m->ntof, name.data, name.size, field_v, alloc));
  3701. CHK_OOM(upb_inttable_insert2(&m->itof, field_number, v, alloc));
  3702. if (strcmp(shortname, json_name) != 0) {
  3703. upb_strtable_insert3(&m->ntof, json_name, json_size, json_v, alloc);
  3704. }
  3705. if (ctx->layouts) {
  3706. const upb_msglayout_field *fields = m->layout->fields;
  3707. int count = m->layout->field_count;
  3708. bool found = false;
  3709. int i;
  3710. for (i = 0; i < count; i++) {
  3711. if (fields[i].number == field_number) {
  3712. f->layout_index = i;
  3713. found = true;
  3714. break;
  3715. }
  3716. }
  3717. UPB_ASSERT(found);
  3718. }
  3719. } else {
  3720. /* extension field. */
  3721. f = (upb_fielddef*)&ctx->file->exts[ctx->file->ext_count++];
  3722. f->is_extension_ = true;
  3723. CHK_OOM(symtab_add(ctx, full_name, pack_def(f, UPB_DEFTYPE_FIELD)));
  3724. }
  3725. f->full_name = full_name;
  3726. f->json_name = json_name;
  3727. f->file = ctx->file;
  3728. f->type_ = (int)google_protobuf_FieldDescriptorProto_type(field_proto);
  3729. f->label_ = (int)google_protobuf_FieldDescriptorProto_label(field_proto);
  3730. f->number_ = field_number;
  3731. f->oneof = NULL;
  3732. f->proto3_optional_ =
  3733. google_protobuf_FieldDescriptorProto_proto3_optional(field_proto);
  3734. /* We can't resolve the subdef or (in the case of extensions) the containing
  3735. * message yet, because it may not have been defined yet. We stash a pointer
  3736. * to the field_proto until later when we can properly resolve it. */
  3737. f->sub.unresolved = field_proto;
  3738. if (f->label_ == UPB_LABEL_REQUIRED && f->file->syntax == UPB_SYNTAX_PROTO3) {
  3739. upb_status_seterrf(ctx->status, "proto3 fields cannot be required (%s)",
  3740. f->full_name);
  3741. return false;
  3742. }
  3743. if (google_protobuf_FieldDescriptorProto_has_oneof_index(field_proto)) {
  3744. int oneof_index =
  3745. google_protobuf_FieldDescriptorProto_oneof_index(field_proto);
  3746. upb_oneofdef *oneof;
  3747. upb_value v = upb_value_constptr(f);
  3748. if (upb_fielddef_label(f) != UPB_LABEL_OPTIONAL) {
  3749. upb_status_seterrf(ctx->status,
  3750. "fields in oneof must have OPTIONAL label (%s)",
  3751. f->full_name);
  3752. return false;
  3753. }
  3754. if (!m) {
  3755. upb_status_seterrf(ctx->status,
  3756. "oneof_index provided for extension field (%s)",
  3757. f->full_name);
  3758. return false;
  3759. }
  3760. if (oneof_index >= m->oneof_count) {
  3761. upb_status_seterrf(ctx->status, "oneof_index out of range (%s)",
  3762. f->full_name);
  3763. return false;
  3764. }
  3765. oneof = (upb_oneofdef*)&m->oneofs[oneof_index];
  3766. f->oneof = oneof;
  3767. CHK(upb_inttable_insert2(&oneof->itof, f->number_, v, alloc));
  3768. CHK(upb_strtable_insert3(&oneof->ntof, name.data, name.size, v, alloc));
  3769. } else {
  3770. f->oneof = NULL;
  3771. }
  3772. if (google_protobuf_FieldDescriptorProto_has_options(field_proto)) {
  3773. options = google_protobuf_FieldDescriptorProto_options(field_proto);
  3774. f->lazy_ = google_protobuf_FieldOptions_lazy(options);
  3775. f->packed_ = google_protobuf_FieldOptions_packed(options);
  3776. } else {
  3777. f->lazy_ = false;
  3778. f->packed_ = false;
  3779. }
  3780. return true;
  3781. }
  3782. static bool create_enumdef(
  3783. const symtab_addctx *ctx, const char *prefix,
  3784. const google_protobuf_EnumDescriptorProto *enum_proto) {
  3785. upb_enumdef *e;
  3786. const google_protobuf_EnumValueDescriptorProto *const *values;
  3787. upb_strview name;
  3788. size_t i, n;
  3789. name = google_protobuf_EnumDescriptorProto_name(enum_proto);
  3790. CHK(upb_isident(name, false, ctx->status));
  3791. e = (upb_enumdef*)&ctx->file->enums[ctx->file->enum_count++];
  3792. e->full_name = makefullname(ctx, prefix, name);
  3793. CHK_OOM(symtab_add(ctx, e->full_name, pack_def(e, UPB_DEFTYPE_ENUM)));
  3794. CHK_OOM(upb_strtable_init2(&e->ntoi, UPB_CTYPE_INT32, ctx->alloc));
  3795. CHK_OOM(upb_inttable_init2(&e->iton, UPB_CTYPE_CSTR, ctx->alloc));
  3796. e->file = ctx->file;
  3797. e->defaultval = 0;
  3798. values = google_protobuf_EnumDescriptorProto_value(enum_proto, &n);
  3799. if (n == 0) {
  3800. upb_status_seterrf(ctx->status,
  3801. "enums must contain at least one value (%s)",
  3802. e->full_name);
  3803. return false;
  3804. }
  3805. for (i = 0; i < n; i++) {
  3806. const google_protobuf_EnumValueDescriptorProto *value = values[i];
  3807. upb_strview name = google_protobuf_EnumValueDescriptorProto_name(value);
  3808. char *name2 = strviewdup(ctx, name);
  3809. int32_t num = google_protobuf_EnumValueDescriptorProto_number(value);
  3810. upb_value v = upb_value_int32(num);
  3811. if (i == 0 && e->file->syntax == UPB_SYNTAX_PROTO3 && num != 0) {
  3812. upb_status_seterrf(ctx->status,
  3813. "for proto3, the first enum value must be zero (%s)",
  3814. e->full_name);
  3815. return false;
  3816. }
  3817. if (upb_strtable_lookup(&e->ntoi, name2, NULL)) {
  3818. upb_status_seterrf(ctx->status, "duplicate enum label '%s'", name2);
  3819. return false;
  3820. }
  3821. CHK_OOM(name2)
  3822. CHK_OOM(
  3823. upb_strtable_insert3(&e->ntoi, name2, strlen(name2), v, ctx->alloc));
  3824. if (!upb_inttable_lookup(&e->iton, num, NULL)) {
  3825. upb_value v = upb_value_cstr(name2);
  3826. CHK_OOM(upb_inttable_insert2(&e->iton, num, v, ctx->alloc));
  3827. }
  3828. }
  3829. upb_inttable_compact2(&e->iton, ctx->alloc);
  3830. return true;
  3831. }
  3832. static bool create_msgdef(symtab_addctx *ctx, const char *prefix,
  3833. const google_protobuf_DescriptorProto *msg_proto) {
  3834. upb_msgdef *m;
  3835. const google_protobuf_MessageOptions *options;
  3836. const google_protobuf_OneofDescriptorProto *const *oneofs;
  3837. const google_protobuf_FieldDescriptorProto *const *fields;
  3838. const google_protobuf_EnumDescriptorProto *const *enums;
  3839. const google_protobuf_DescriptorProto *const *msgs;
  3840. size_t i, n;
  3841. upb_strview name;
  3842. name = google_protobuf_DescriptorProto_name(msg_proto);
  3843. CHK(upb_isident(name, false, ctx->status));
  3844. m = (upb_msgdef*)&ctx->file->msgs[ctx->file->msg_count++];
  3845. m->full_name = makefullname(ctx, prefix, name);
  3846. CHK_OOM(symtab_add(ctx, m->full_name, pack_def(m, UPB_DEFTYPE_MSG)));
  3847. CHK_OOM(upb_inttable_init2(&m->itof, UPB_CTYPE_CONSTPTR, ctx->alloc));
  3848. CHK_OOM(upb_strtable_init2(&m->ntof, UPB_CTYPE_CONSTPTR, ctx->alloc));
  3849. m->file = ctx->file;
  3850. m->map_entry = false;
  3851. options = google_protobuf_DescriptorProto_options(msg_proto);
  3852. if (options) {
  3853. m->map_entry = google_protobuf_MessageOptions_map_entry(options);
  3854. }
  3855. if (ctx->layouts) {
  3856. m->layout = *ctx->layouts;
  3857. ctx->layouts++;
  3858. } else {
  3859. /* Allocate now (to allow cross-linking), populate later. */
  3860. m->layout = upb_malloc(ctx->alloc, sizeof(*m->layout));
  3861. }
  3862. oneofs = google_protobuf_DescriptorProto_oneof_decl(msg_proto, &n);
  3863. m->oneof_count = 0;
  3864. m->oneofs = upb_malloc(ctx->alloc, sizeof(*m->oneofs) * n);
  3865. for (i = 0; i < n; i++) {
  3866. CHK(create_oneofdef(ctx, m, oneofs[i]));
  3867. }
  3868. fields = google_protobuf_DescriptorProto_field(msg_proto, &n);
  3869. m->field_count = 0;
  3870. m->fields = upb_malloc(ctx->alloc, sizeof(*m->fields) * n);
  3871. for (i = 0; i < n; i++) {
  3872. CHK(create_fielddef(ctx, m->full_name, m, fields[i]));
  3873. }
  3874. CHK(assign_msg_indices(m, ctx->status));
  3875. assign_msg_wellknowntype(m);
  3876. upb_inttable_compact2(&m->itof, ctx->alloc);
  3877. /* This message is built. Now build nested messages and enums. */
  3878. enums = google_protobuf_DescriptorProto_enum_type(msg_proto, &n);
  3879. for (i = 0; i < n; i++) {
  3880. CHK(create_enumdef(ctx, m->full_name, enums[i]));
  3881. }
  3882. msgs = google_protobuf_DescriptorProto_nested_type(msg_proto, &n);
  3883. for (i = 0; i < n; i++) {
  3884. CHK(create_msgdef(ctx, m->full_name, msgs[i]));
  3885. }
  3886. return true;
  3887. }
  3888. typedef struct {
  3889. int msg_count;
  3890. int enum_count;
  3891. int ext_count;
  3892. } decl_counts;
  3893. static void count_types_in_msg(const google_protobuf_DescriptorProto *msg_proto,
  3894. decl_counts *counts) {
  3895. const google_protobuf_DescriptorProto *const *msgs;
  3896. size_t i, n;
  3897. counts->msg_count++;
  3898. msgs = google_protobuf_DescriptorProto_nested_type(msg_proto, &n);
  3899. for (i = 0; i < n; i++) {
  3900. count_types_in_msg(msgs[i], counts);
  3901. }
  3902. google_protobuf_DescriptorProto_enum_type(msg_proto, &n);
  3903. counts->enum_count += n;
  3904. google_protobuf_DescriptorProto_extension(msg_proto, &n);
  3905. counts->ext_count += n;
  3906. }
  3907. static void count_types_in_file(
  3908. const google_protobuf_FileDescriptorProto *file_proto,
  3909. decl_counts *counts) {
  3910. const google_protobuf_DescriptorProto *const *msgs;
  3911. size_t i, n;
  3912. msgs = google_protobuf_FileDescriptorProto_message_type(file_proto, &n);
  3913. for (i = 0; i < n; i++) {
  3914. count_types_in_msg(msgs[i], counts);
  3915. }
  3916. google_protobuf_FileDescriptorProto_enum_type(file_proto, &n);
  3917. counts->enum_count += n;
  3918. google_protobuf_FileDescriptorProto_extension(file_proto, &n);
  3919. counts->ext_count += n;
  3920. }
  3921. static bool resolve_fielddef(const symtab_addctx *ctx, const char *prefix,
  3922. upb_fielddef *f) {
  3923. upb_strview name;
  3924. const google_protobuf_FieldDescriptorProto *field_proto = f->sub.unresolved;
  3925. if (f->is_extension_) {
  3926. if (!google_protobuf_FieldDescriptorProto_has_extendee(field_proto)) {
  3927. upb_status_seterrf(ctx->status,
  3928. "extension for field '%s' had no extendee",
  3929. f->full_name);
  3930. return false;
  3931. }
  3932. name = google_protobuf_FieldDescriptorProto_extendee(field_proto);
  3933. f->msgdef = symtab_resolve(ctx, f, prefix, name, UPB_DEFTYPE_MSG);
  3934. CHK(f->msgdef);
  3935. }
  3936. if ((upb_fielddef_issubmsg(f) || f->type_ == UPB_DESCRIPTOR_TYPE_ENUM) &&
  3937. !google_protobuf_FieldDescriptorProto_has_type_name(field_proto)) {
  3938. upb_status_seterrf(ctx->status, "field '%s' is missing type name",
  3939. f->full_name);
  3940. return false;
  3941. }
  3942. name = google_protobuf_FieldDescriptorProto_type_name(field_proto);
  3943. if (upb_fielddef_issubmsg(f)) {
  3944. f->sub.msgdef = symtab_resolve(ctx, f, prefix, name, UPB_DEFTYPE_MSG);
  3945. CHK(f->sub.msgdef);
  3946. } else if (f->type_ == UPB_DESCRIPTOR_TYPE_ENUM) {
  3947. f->sub.enumdef = symtab_resolve(ctx, f, prefix, name, UPB_DEFTYPE_ENUM);
  3948. CHK(f->sub.enumdef);
  3949. }
  3950. /* Have to delay resolving of the default value until now because of the enum
  3951. * case, since enum defaults are specified with a label. */
  3952. if (google_protobuf_FieldDescriptorProto_has_default_value(field_proto)) {
  3953. upb_strview defaultval =
  3954. google_protobuf_FieldDescriptorProto_default_value(field_proto);
  3955. if (f->file->syntax == UPB_SYNTAX_PROTO3) {
  3956. upb_status_seterrf(ctx->status,
  3957. "proto3 fields cannot have explicit defaults (%s)",
  3958. f->full_name);
  3959. return false;
  3960. }
  3961. if (upb_fielddef_issubmsg(f)) {
  3962. upb_status_seterrf(ctx->status,
  3963. "message fields cannot have explicit defaults (%s)",
  3964. f->full_name);
  3965. return false;
  3966. }
  3967. if (!parse_default(ctx, defaultval.data, defaultval.size, f)) {
  3968. upb_status_seterrf(ctx->status,
  3969. "couldn't parse default '" UPB_STRVIEW_FORMAT
  3970. "' for field (%s)",
  3971. UPB_STRVIEW_ARGS(defaultval), f->full_name);
  3972. return false;
  3973. }
  3974. } else {
  3975. set_default_default(ctx, f);
  3976. }
  3977. return true;
  3978. }
  3979. static bool build_filedef(
  3980. symtab_addctx *ctx, upb_filedef *file,
  3981. const google_protobuf_FileDescriptorProto *file_proto) {
  3982. upb_alloc *alloc = ctx->alloc;
  3983. const google_protobuf_FileOptions *file_options_proto;
  3984. const google_protobuf_DescriptorProto *const *msgs;
  3985. const google_protobuf_EnumDescriptorProto *const *enums;
  3986. const google_protobuf_FieldDescriptorProto *const *exts;
  3987. const upb_strview* strs;
  3988. size_t i, n;
  3989. decl_counts counts = {0};
  3990. count_types_in_file(file_proto, &counts);
  3991. file->msgs = upb_malloc(alloc, sizeof(*file->msgs) * counts.msg_count);
  3992. file->enums = upb_malloc(alloc, sizeof(*file->enums) * counts.enum_count);
  3993. file->exts = upb_malloc(alloc, sizeof(*file->exts) * counts.ext_count);
  3994. CHK_OOM(counts.msg_count == 0 || file->msgs);
  3995. CHK_OOM(counts.enum_count == 0 || file->enums);
  3996. CHK_OOM(counts.ext_count == 0 || file->exts);
  3997. /* We increment these as defs are added. */
  3998. file->msg_count = 0;
  3999. file->enum_count = 0;
  4000. file->ext_count = 0;
  4001. if (!google_protobuf_FileDescriptorProto_has_name(file_proto)) {
  4002. upb_status_seterrmsg(ctx->status, "File has no name");
  4003. return false;
  4004. }
  4005. file->name =
  4006. strviewdup(ctx, google_protobuf_FileDescriptorProto_name(file_proto));
  4007. file->phpprefix = NULL;
  4008. file->phpnamespace = NULL;
  4009. if (google_protobuf_FileDescriptorProto_has_package(file_proto)) {
  4010. upb_strview package =
  4011. google_protobuf_FileDescriptorProto_package(file_proto);
  4012. CHK(upb_isident(package, true, ctx->status));
  4013. file->package = strviewdup(ctx, package);
  4014. } else {
  4015. file->package = NULL;
  4016. }
  4017. if (google_protobuf_FileDescriptorProto_has_syntax(file_proto)) {
  4018. upb_strview syntax =
  4019. google_protobuf_FileDescriptorProto_syntax(file_proto);
  4020. if (streql_view(syntax, "proto2")) {
  4021. file->syntax = UPB_SYNTAX_PROTO2;
  4022. } else if (streql_view(syntax, "proto3")) {
  4023. file->syntax = UPB_SYNTAX_PROTO3;
  4024. } else {
  4025. upb_status_seterrf(ctx->status, "Invalid syntax '" UPB_STRVIEW_FORMAT "'",
  4026. UPB_STRVIEW_ARGS(syntax));
  4027. return false;
  4028. }
  4029. } else {
  4030. file->syntax = UPB_SYNTAX_PROTO2;
  4031. }
  4032. /* Read options. */
  4033. file_options_proto = google_protobuf_FileDescriptorProto_options(file_proto);
  4034. if (file_options_proto) {
  4035. if (google_protobuf_FileOptions_has_php_class_prefix(file_options_proto)) {
  4036. file->phpprefix = strviewdup(
  4037. ctx,
  4038. google_protobuf_FileOptions_php_class_prefix(file_options_proto));
  4039. }
  4040. if (google_protobuf_FileOptions_has_php_namespace(file_options_proto)) {
  4041. file->phpnamespace = strviewdup(
  4042. ctx, google_protobuf_FileOptions_php_namespace(file_options_proto));
  4043. }
  4044. }
  4045. /* Verify dependencies. */
  4046. strs = google_protobuf_FileDescriptorProto_dependency(file_proto, &n);
  4047. file->deps = upb_malloc(alloc, sizeof(*file->deps) * n) ;
  4048. CHK_OOM(n == 0 || file->deps);
  4049. for (i = 0; i < n; i++) {
  4050. upb_strview dep_name = strs[i];
  4051. upb_value v;
  4052. if (!upb_strtable_lookup2(&ctx->symtab->files, dep_name.data,
  4053. dep_name.size, &v)) {
  4054. upb_status_seterrf(ctx->status,
  4055. "Depends on file '" UPB_STRVIEW_FORMAT
  4056. "', but it has not been loaded",
  4057. UPB_STRVIEW_ARGS(dep_name));
  4058. return false;
  4059. }
  4060. file->deps[i] = upb_value_getconstptr(v);
  4061. }
  4062. /* Create messages. */
  4063. msgs = google_protobuf_FileDescriptorProto_message_type(file_proto, &n);
  4064. for (i = 0; i < n; i++) {
  4065. CHK(create_msgdef(ctx, file->package, msgs[i]));
  4066. }
  4067. /* Create enums. */
  4068. enums = google_protobuf_FileDescriptorProto_enum_type(file_proto, &n);
  4069. for (i = 0; i < n; i++) {
  4070. CHK(create_enumdef(ctx, file->package, enums[i]));
  4071. }
  4072. /* Create extensions. */
  4073. exts = google_protobuf_FileDescriptorProto_extension(file_proto, &n);
  4074. file->exts = upb_malloc(alloc, sizeof(*file->exts) * n);
  4075. CHK_OOM(n == 0 || file->exts);
  4076. for (i = 0; i < n; i++) {
  4077. CHK(create_fielddef(ctx, file->package, NULL, exts[i]));
  4078. }
  4079. /* Now that all names are in the table, build layouts and resolve refs. */
  4080. for (i = 0; i < file->ext_count; i++) {
  4081. CHK(resolve_fielddef(ctx, file->package, (upb_fielddef*)&file->exts[i]));
  4082. }
  4083. for (i = 0; i < file->msg_count; i++) {
  4084. const upb_msgdef *m = &file->msgs[i];
  4085. int j;
  4086. for (j = 0; j < m->field_count; j++) {
  4087. CHK(resolve_fielddef(ctx, m->full_name, (upb_fielddef*)&m->fields[j]));
  4088. }
  4089. }
  4090. if (!ctx->layouts) {
  4091. for (i = 0; i < file->msg_count; i++) {
  4092. const upb_msgdef *m = &file->msgs[i];
  4093. make_layout(ctx->symtab, m);
  4094. }
  4095. }
  4096. return true;
  4097. }
  4098. static bool upb_symtab_addtotabs(upb_symtab *s, symtab_addctx *ctx,
  4099. upb_status *status) {
  4100. const upb_filedef *file = ctx->file;
  4101. upb_alloc *alloc = upb_arena_alloc(s->arena);
  4102. upb_strtable_iter iter;
  4103. CHK_OOM(upb_strtable_insert3(&s->files, file->name, strlen(file->name),
  4104. upb_value_constptr(file), alloc));
  4105. upb_strtable_begin(&iter, ctx->addtab);
  4106. for (; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
  4107. upb_strview key = upb_strtable_iter_key(&iter);
  4108. upb_value value = upb_strtable_iter_value(&iter);
  4109. CHK_OOM(upb_strtable_insert3(&s->syms, key.data, key.size, value, alloc));
  4110. }
  4111. return true;
  4112. }
  4113. /* upb_filedef ****************************************************************/
  4114. const char *upb_filedef_name(const upb_filedef *f) {
  4115. return f->name;
  4116. }
  4117. const char *upb_filedef_package(const upb_filedef *f) {
  4118. return f->package;
  4119. }
  4120. const char *upb_filedef_phpprefix(const upb_filedef *f) {
  4121. return f->phpprefix;
  4122. }
  4123. const char *upb_filedef_phpnamespace(const upb_filedef *f) {
  4124. return f->phpnamespace;
  4125. }
  4126. upb_syntax_t upb_filedef_syntax(const upb_filedef *f) {
  4127. return f->syntax;
  4128. }
  4129. int upb_filedef_msgcount(const upb_filedef *f) {
  4130. return f->msg_count;
  4131. }
  4132. int upb_filedef_depcount(const upb_filedef *f) {
  4133. return f->dep_count;
  4134. }
  4135. int upb_filedef_enumcount(const upb_filedef *f) {
  4136. return f->enum_count;
  4137. }
  4138. const upb_filedef *upb_filedef_dep(const upb_filedef *f, int i) {
  4139. return i < 0 || i >= f->dep_count ? NULL : f->deps[i];
  4140. }
  4141. const upb_msgdef *upb_filedef_msg(const upb_filedef *f, int i) {
  4142. return i < 0 || i >= f->msg_count ? NULL : &f->msgs[i];
  4143. }
  4144. const upb_enumdef *upb_filedef_enum(const upb_filedef *f, int i) {
  4145. return i < 0 || i >= f->enum_count ? NULL : &f->enums[i];
  4146. }
  4147. void upb_symtab_free(upb_symtab *s) {
  4148. upb_arena_free(s->arena);
  4149. upb_gfree(s);
  4150. }
  4151. upb_symtab *upb_symtab_new(void) {
  4152. upb_symtab *s = upb_gmalloc(sizeof(*s));
  4153. upb_alloc *alloc;
  4154. if (!s) {
  4155. return NULL;
  4156. }
  4157. s->arena = upb_arena_new();
  4158. alloc = upb_arena_alloc(s->arena);
  4159. if (!upb_strtable_init2(&s->syms, UPB_CTYPE_CONSTPTR, alloc) ||
  4160. !upb_strtable_init2(&s->files, UPB_CTYPE_CONSTPTR, alloc)) {
  4161. upb_arena_free(s->arena);
  4162. upb_gfree(s);
  4163. s = NULL;
  4164. }
  4165. return s;
  4166. }
  4167. const upb_msgdef *upb_symtab_lookupmsg(const upb_symtab *s, const char *sym) {
  4168. upb_value v;
  4169. return upb_strtable_lookup(&s->syms, sym, &v) ?
  4170. unpack_def(v, UPB_DEFTYPE_MSG) : NULL;
  4171. }
  4172. const upb_msgdef *upb_symtab_lookupmsg2(const upb_symtab *s, const char *sym,
  4173. size_t len) {
  4174. upb_value v;
  4175. return upb_strtable_lookup2(&s->syms, sym, len, &v) ?
  4176. unpack_def(v, UPB_DEFTYPE_MSG) : NULL;
  4177. }
  4178. const upb_enumdef *upb_symtab_lookupenum(const upb_symtab *s, const char *sym) {
  4179. upb_value v;
  4180. return upb_strtable_lookup(&s->syms, sym, &v) ?
  4181. unpack_def(v, UPB_DEFTYPE_ENUM) : NULL;
  4182. }
  4183. const upb_filedef *upb_symtab_lookupfile(const upb_symtab *s, const char *name) {
  4184. upb_value v;
  4185. return upb_strtable_lookup(&s->files, name, &v) ? upb_value_getconstptr(v)
  4186. : NULL;
  4187. }
  4188. int upb_symtab_filecount(const upb_symtab *s) {
  4189. return (int)upb_strtable_count(&s->files);
  4190. }
  4191. static const upb_filedef *_upb_symtab_addfile(
  4192. upb_symtab *s, const google_protobuf_FileDescriptorProto *file_proto,
  4193. const upb_msglayout **layouts, upb_status *status) {
  4194. upb_arena *tmparena = upb_arena_new();
  4195. upb_strtable addtab;
  4196. upb_alloc *alloc = upb_arena_alloc(s->arena);
  4197. upb_filedef *file = upb_malloc(alloc, sizeof(*file));
  4198. bool ok;
  4199. symtab_addctx ctx;
  4200. ctx.file = file;
  4201. ctx.symtab = s;
  4202. ctx.alloc = alloc;
  4203. ctx.tmp = upb_arena_alloc(tmparena);
  4204. ctx.addtab = &addtab;
  4205. ctx.layouts = layouts;
  4206. ctx.status = status;
  4207. ok = file &&
  4208. upb_strtable_init2(&addtab, UPB_CTYPE_CONSTPTR, ctx.tmp) &&
  4209. build_filedef(&ctx, file, file_proto) &&
  4210. upb_symtab_addtotabs(s, &ctx, status);
  4211. upb_arena_free(tmparena);
  4212. return ok ? file : NULL;
  4213. }
  4214. const upb_filedef *upb_symtab_addfile(
  4215. upb_symtab *s, const google_protobuf_FileDescriptorProto *file_proto,
  4216. upb_status *status) {
  4217. return _upb_symtab_addfile(s, file_proto, NULL, status);
  4218. }
  4219. /* Include here since we want most of this file to be stdio-free. */
  4220. #include <stdio.h>
  4221. bool _upb_symtab_loaddefinit(upb_symtab *s, const upb_def_init *init) {
  4222. /* Since this function should never fail (it would indicate a bug in upb) we
  4223. * print errors to stderr instead of returning error status to the user. */
  4224. upb_def_init **deps = init->deps;
  4225. google_protobuf_FileDescriptorProto *file;
  4226. upb_arena *arena;
  4227. upb_status status;
  4228. upb_status_clear(&status);
  4229. if (upb_strtable_lookup(&s->files, init->filename, NULL)) {
  4230. return true;
  4231. }
  4232. arena = upb_arena_new();
  4233. for (; *deps; deps++) {
  4234. if (!_upb_symtab_loaddefinit(s, *deps)) goto err;
  4235. }
  4236. file = google_protobuf_FileDescriptorProto_parse(
  4237. init->descriptor.data, init->descriptor.size, arena);
  4238. if (!file) {
  4239. upb_status_seterrf(
  4240. &status,
  4241. "Failed to parse compiled-in descriptor for file '%s'. This should "
  4242. "never happen.",
  4243. init->filename);
  4244. goto err;
  4245. }
  4246. if (!_upb_symtab_addfile(s, file, init->layouts, &status)) goto err;
  4247. upb_arena_free(arena);
  4248. return true;
  4249. err:
  4250. fprintf(stderr, "Error loading compiled-in descriptor: %s\n",
  4251. upb_status_errmsg(&status));
  4252. upb_arena_free(arena);
  4253. return false;
  4254. }
  4255. #undef CHK
  4256. #undef CHK_OOM
  4257. #include <string.h>
  4258. static char field_size[] = {
  4259. 0,/* 0 */
  4260. 8, /* UPB_DESCRIPTOR_TYPE_DOUBLE */
  4261. 4, /* UPB_DESCRIPTOR_TYPE_FLOAT */
  4262. 8, /* UPB_DESCRIPTOR_TYPE_INT64 */
  4263. 8, /* UPB_DESCRIPTOR_TYPE_UINT64 */
  4264. 4, /* UPB_DESCRIPTOR_TYPE_INT32 */
  4265. 8, /* UPB_DESCRIPTOR_TYPE_FIXED64 */
  4266. 4, /* UPB_DESCRIPTOR_TYPE_FIXED32 */
  4267. 1, /* UPB_DESCRIPTOR_TYPE_BOOL */
  4268. sizeof(upb_strview), /* UPB_DESCRIPTOR_TYPE_STRING */
  4269. sizeof(void*), /* UPB_DESCRIPTOR_TYPE_GROUP */
  4270. sizeof(void*), /* UPB_DESCRIPTOR_TYPE_MESSAGE */
  4271. sizeof(upb_strview), /* UPB_DESCRIPTOR_TYPE_BYTES */
  4272. 4, /* UPB_DESCRIPTOR_TYPE_UINT32 */
  4273. 4, /* UPB_DESCRIPTOR_TYPE_ENUM */
  4274. 4, /* UPB_DESCRIPTOR_TYPE_SFIXED32 */
  4275. 8, /* UPB_DESCRIPTOR_TYPE_SFIXED64 */
  4276. 4, /* UPB_DESCRIPTOR_TYPE_SINT32 */
  4277. 8, /* UPB_DESCRIPTOR_TYPE_SINT64 */
  4278. };
  4279. /* Strings/bytes are special-cased in maps. */
  4280. static char _upb_fieldtype_to_mapsize[12] = {
  4281. 0,
  4282. 1, /* UPB_TYPE_BOOL */
  4283. 4, /* UPB_TYPE_FLOAT */
  4284. 4, /* UPB_TYPE_INT32 */
  4285. 4, /* UPB_TYPE_UINT32 */
  4286. 4, /* UPB_TYPE_ENUM */
  4287. sizeof(void*), /* UPB_TYPE_MESSAGE */
  4288. 8, /* UPB_TYPE_DOUBLE */
  4289. 8, /* UPB_TYPE_INT64 */
  4290. 8, /* UPB_TYPE_UINT64 */
  4291. 0, /* UPB_TYPE_STRING */
  4292. 0, /* UPB_TYPE_BYTES */
  4293. };
  4294. /** upb_msg *******************************************************************/
  4295. upb_msg *upb_msg_new(const upb_msgdef *m, upb_arena *a) {
  4296. return _upb_msg_new(upb_msgdef_layout(m), a);
  4297. }
  4298. static bool in_oneof(const upb_msglayout_field *field) {
  4299. return field->presence < 0;
  4300. }
  4301. static uint32_t *oneofcase(const upb_msg *msg,
  4302. const upb_msglayout_field *field) {
  4303. UPB_ASSERT(in_oneof(field));
  4304. return UPB_PTR_AT(msg, -field->presence, uint32_t);
  4305. }
  4306. static upb_msgval _upb_msg_getraw(const upb_msg *msg, const upb_fielddef *f) {
  4307. const upb_msglayout_field *field = upb_fielddef_layout(f);
  4308. const char *mem = UPB_PTR_AT(msg, field->offset, char);
  4309. upb_msgval val = {0};
  4310. int size = upb_fielddef_isseq(f) ? sizeof(void *)
  4311. : field_size[field->descriptortype];
  4312. memcpy(&val, mem, size);
  4313. return val;
  4314. }
  4315. bool upb_msg_has(const upb_msg *msg, const upb_fielddef *f) {
  4316. const upb_msglayout_field *field = upb_fielddef_layout(f);
  4317. if (in_oneof(field)) {
  4318. return *oneofcase(msg, field) == field->number;
  4319. } else if (field->presence > 0) {
  4320. uint32_t hasbit = field->presence;
  4321. return *UPB_PTR_AT(msg, hasbit / 8, uint8_t) & (1 << (hasbit % 8));
  4322. } else {
  4323. UPB_ASSERT(field->descriptortype == UPB_DESCRIPTOR_TYPE_MESSAGE ||
  4324. field->descriptortype == UPB_DESCRIPTOR_TYPE_GROUP);
  4325. return _upb_msg_getraw(msg, f).msg_val != NULL;
  4326. }
  4327. }
  4328. bool upb_msg_hasoneof(const upb_msg *msg, const upb_oneofdef *o) {
  4329. upb_oneof_iter i;
  4330. const upb_fielddef *f;
  4331. const upb_msglayout_field *field;
  4332. upb_oneof_begin(&i, o);
  4333. if (upb_oneof_done(&i)) return false;
  4334. f = upb_oneof_iter_field(&i);
  4335. field = upb_fielddef_layout(f);
  4336. return *oneofcase(msg, field) != 0;
  4337. }
  4338. upb_msgval upb_msg_get(const upb_msg *msg, const upb_fielddef *f) {
  4339. if (!upb_fielddef_haspresence(f) || upb_msg_has(msg, f)) {
  4340. return _upb_msg_getraw(msg, f);
  4341. } else {
  4342. /* TODO(haberman): change upb_fielddef to not require this switch(). */
  4343. upb_msgval val = {0};
  4344. switch (upb_fielddef_type(f)) {
  4345. case UPB_TYPE_INT32:
  4346. case UPB_TYPE_ENUM:
  4347. val.int32_val = upb_fielddef_defaultint32(f);
  4348. break;
  4349. case UPB_TYPE_INT64:
  4350. val.int64_val = upb_fielddef_defaultint64(f);
  4351. break;
  4352. case UPB_TYPE_UINT32:
  4353. val.uint32_val = upb_fielddef_defaultuint32(f);
  4354. break;
  4355. case UPB_TYPE_UINT64:
  4356. val.uint64_val = upb_fielddef_defaultuint64(f);
  4357. break;
  4358. case UPB_TYPE_FLOAT:
  4359. val.float_val = upb_fielddef_defaultfloat(f);
  4360. break;
  4361. case UPB_TYPE_DOUBLE:
  4362. val.double_val = upb_fielddef_defaultdouble(f);
  4363. break;
  4364. case UPB_TYPE_BOOL:
  4365. val.double_val = upb_fielddef_defaultbool(f);
  4366. break;
  4367. case UPB_TYPE_STRING:
  4368. case UPB_TYPE_BYTES:
  4369. val.str_val.data = upb_fielddef_defaultstr(f, &val.str_val.size);
  4370. break;
  4371. case UPB_TYPE_MESSAGE:
  4372. val.msg_val = NULL;
  4373. break;
  4374. }
  4375. return val;
  4376. }
  4377. }
  4378. upb_mutmsgval upb_msg_mutable(upb_msg *msg, const upb_fielddef *f,
  4379. upb_arena *a) {
  4380. const upb_msglayout_field *field = upb_fielddef_layout(f);
  4381. upb_mutmsgval ret;
  4382. char *mem = UPB_PTR_AT(msg, field->offset, char);
  4383. bool wrong_oneof = in_oneof(field) && *oneofcase(msg, field) != field->number;
  4384. memcpy(&ret, mem, sizeof(void*));
  4385. if (a && (!ret.msg || wrong_oneof)) {
  4386. if (upb_fielddef_ismap(f)) {
  4387. const upb_msgdef *entry = upb_fielddef_msgsubdef(f);
  4388. const upb_fielddef *key = upb_msgdef_itof(entry, UPB_MAPENTRY_KEY);
  4389. const upb_fielddef *value = upb_msgdef_itof(entry, UPB_MAPENTRY_VALUE);
  4390. ret.map = upb_map_new(a, upb_fielddef_type(key), upb_fielddef_type(value));
  4391. } else if (upb_fielddef_isseq(f)) {
  4392. ret.array = upb_array_new(a, upb_fielddef_type(f));
  4393. } else {
  4394. UPB_ASSERT(upb_fielddef_issubmsg(f));
  4395. ret.msg = upb_msg_new(upb_fielddef_msgsubdef(f), a);
  4396. }
  4397. memcpy(mem, &ret, sizeof(void*));
  4398. if (wrong_oneof) {
  4399. *oneofcase(msg, field) = field->number;
  4400. }
  4401. }
  4402. return ret;
  4403. }
  4404. void upb_msg_set(upb_msg *msg, const upb_fielddef *f, upb_msgval val,
  4405. upb_arena *a) {
  4406. const upb_msglayout_field *field = upb_fielddef_layout(f);
  4407. char *mem = UPB_PTR_AT(msg, field->offset, char);
  4408. int size = upb_fielddef_isseq(f) ? sizeof(void *)
  4409. : field_size[field->descriptortype];
  4410. memcpy(mem, &val, size);
  4411. if (in_oneof(field)) {
  4412. *oneofcase(msg, field) = field->number;
  4413. }
  4414. }
  4415. bool upb_msg_next(const upb_msg *msg, const upb_msgdef *m,
  4416. const upb_symtab *ext_pool, const upb_fielddef **out_f,
  4417. upb_msgval *out_val, size_t *iter) {
  4418. size_t i = *iter;
  4419. const upb_msgval zero = {0};
  4420. const upb_fielddef *f;
  4421. while ((f = _upb_msgdef_field(m, (int)++i)) != NULL) {
  4422. upb_msgval val = _upb_msg_getraw(msg, f);
  4423. /* Skip field if unset or empty. */
  4424. if (upb_fielddef_haspresence(f)) {
  4425. if (!upb_msg_has(msg, f)) continue;
  4426. } else {
  4427. upb_msgval test = val;
  4428. if (upb_fielddef_isstring(f) && !upb_fielddef_isseq(f)) {
  4429. /* Clear string pointer, only size matters (ptr could be non-NULL). */
  4430. test.str_val.data = NULL;
  4431. }
  4432. /* Continue if NULL or 0. */
  4433. if (memcmp(&test, &zero, sizeof(test)) == 0) continue;
  4434. /* Continue on empty array or map. */
  4435. if (upb_fielddef_ismap(f)) {
  4436. if (upb_map_size(test.map_val) == 0) continue;
  4437. } else if (upb_fielddef_isseq(f)) {
  4438. if (upb_array_size(test.array_val) == 0) continue;
  4439. }
  4440. }
  4441. *out_val = val;
  4442. *out_f = f;
  4443. *iter = i;
  4444. return true;
  4445. }
  4446. *iter = i;
  4447. return false;
  4448. }
  4449. /** upb_array *****************************************************************/
  4450. upb_array *upb_array_new(upb_arena *a, upb_fieldtype_t type) {
  4451. return _upb_array_new(a, type);
  4452. }
  4453. size_t upb_array_size(const upb_array *arr) {
  4454. return arr->len;
  4455. }
  4456. upb_msgval upb_array_get(const upb_array *arr, size_t i) {
  4457. upb_msgval ret;
  4458. const char* data = _upb_array_constptr(arr);
  4459. int lg2 = arr->data & 7;
  4460. UPB_ASSERT(i < arr->len);
  4461. memcpy(&ret, data + (i << lg2), 1 << lg2);
  4462. return ret;
  4463. }
  4464. void upb_array_set(upb_array *arr, size_t i, upb_msgval val) {
  4465. char* data = _upb_array_ptr(arr);
  4466. int lg2 = arr->data & 7;
  4467. UPB_ASSERT(i < arr->len);
  4468. memcpy(data + (i << lg2), &val, 1 << lg2);
  4469. }
  4470. bool upb_array_append(upb_array *arr, upb_msgval val, upb_arena *arena) {
  4471. if (!_upb_array_realloc(arr, arr->len + 1, arena)) {
  4472. return false;
  4473. }
  4474. arr->len++;
  4475. upb_array_set(arr, arr->len - 1, val);
  4476. return true;
  4477. }
  4478. /* Resizes the array to the given size, reallocating if necessary, and returns a
  4479. * pointer to the new array elements. */
  4480. bool upb_array_resize(upb_array *arr, size_t size, upb_arena *arena) {
  4481. return _upb_array_realloc(arr, size, arena);
  4482. }
  4483. /** upb_map *******************************************************************/
  4484. upb_map *upb_map_new(upb_arena *a, upb_fieldtype_t key_type,
  4485. upb_fieldtype_t value_type) {
  4486. return _upb_map_new(a, _upb_fieldtype_to_mapsize[key_type],
  4487. _upb_fieldtype_to_mapsize[value_type]);
  4488. }
  4489. size_t upb_map_size(const upb_map *map) {
  4490. return _upb_map_size(map);
  4491. }
  4492. bool upb_map_get(const upb_map *map, upb_msgval key, upb_msgval *val) {
  4493. return _upb_map_get(map, &key, map->key_size, val, map->val_size);
  4494. }
  4495. bool upb_map_set(upb_map *map, upb_msgval key, upb_msgval val,
  4496. upb_arena *arena) {
  4497. return _upb_map_set(map, &key, map->key_size, &val, map->val_size, arena);
  4498. }
  4499. bool upb_map_delete(upb_map *map, upb_msgval key) {
  4500. return _upb_map_delete(map, &key, map->key_size);
  4501. }
  4502. bool upb_mapiter_next(const upb_map *map, size_t *iter) {
  4503. return _upb_map_next(map, iter);
  4504. }
  4505. /* Returns the key and value for this entry of the map. */
  4506. upb_msgval upb_mapiter_key(const upb_map *map, size_t iter) {
  4507. upb_strtable_iter i;
  4508. upb_msgval ret;
  4509. i.t = &map->table;
  4510. i.index = iter;
  4511. _upb_map_fromkey(upb_strtable_iter_key(&i), &ret, map->key_size);
  4512. return ret;
  4513. }
  4514. upb_msgval upb_mapiter_value(const upb_map *map, size_t iter) {
  4515. upb_strtable_iter i;
  4516. upb_msgval ret;
  4517. i.t = &map->table;
  4518. i.index = iter;
  4519. _upb_map_fromvalue(upb_strtable_iter_value(&i), &ret, map->val_size);
  4520. return ret;
  4521. }
  4522. /* void upb_mapiter_setvalue(upb_map *map, size_t iter, upb_msgval value); */
  4523. /*
  4524. ** TODO(haberman): it's unclear whether a lot of the consistency checks should
  4525. ** UPB_ASSERT() or return false.
  4526. */
  4527. #include <string.h>
  4528. struct upb_handlers {
  4529. upb_handlercache *cache;
  4530. const upb_msgdef *msg;
  4531. const upb_handlers **sub;
  4532. const void *top_closure_type;
  4533. upb_handlers_tabent table[1]; /* Dynamically-sized field handler array. */
  4534. };
  4535. static void *upb_calloc(upb_arena *arena, size_t size) {
  4536. void *mem = upb_malloc(upb_arena_alloc(arena), size);
  4537. if (mem) {
  4538. memset(mem, 0, size);
  4539. }
  4540. return mem;
  4541. }
  4542. /* Defined for the sole purpose of having a unique pointer value for
  4543. * UPB_NO_CLOSURE. */
  4544. char _upb_noclosure;
  4545. /* Given a selector for a STARTSUBMSG handler, resolves to a pointer to the
  4546. * subhandlers for this submessage field. */
  4547. #define SUBH(h, selector) (h->sub[selector])
  4548. /* The selector for a submessage field is the field index. */
  4549. #define SUBH_F(h, f) SUBH(h, upb_fielddef_index(f))
  4550. static int32_t trygetsel(upb_handlers *h, const upb_fielddef *f,
  4551. upb_handlertype_t type) {
  4552. upb_selector_t sel;
  4553. bool ok;
  4554. ok = upb_handlers_getselector(f, type, &sel);
  4555. UPB_ASSERT(upb_handlers_msgdef(h) == upb_fielddef_containingtype(f));
  4556. UPB_ASSERT(ok);
  4557. return sel;
  4558. }
  4559. static upb_selector_t handlers_getsel(upb_handlers *h, const upb_fielddef *f,
  4560. upb_handlertype_t type) {
  4561. int32_t sel = trygetsel(h, f, type);
  4562. UPB_ASSERT(sel >= 0);
  4563. return sel;
  4564. }
  4565. static const void **returntype(upb_handlers *h, const upb_fielddef *f,
  4566. upb_handlertype_t type) {
  4567. return &h->table[handlers_getsel(h, f, type)].attr.return_closure_type;
  4568. }
  4569. static bool doset(upb_handlers *h, int32_t sel, const upb_fielddef *f,
  4570. upb_handlertype_t type, upb_func *func,
  4571. const upb_handlerattr *attr) {
  4572. upb_handlerattr set_attr = UPB_HANDLERATTR_INIT;
  4573. const void *closure_type;
  4574. const void **context_closure_type;
  4575. UPB_ASSERT(!h->table[sel].func);
  4576. if (attr) {
  4577. set_attr = *attr;
  4578. }
  4579. /* Check that the given closure type matches the closure type that has been
  4580. * established for this context (if any). */
  4581. closure_type = set_attr.closure_type;
  4582. if (type == UPB_HANDLER_STRING) {
  4583. context_closure_type = returntype(h, f, UPB_HANDLER_STARTSTR);
  4584. } else if (f && upb_fielddef_isseq(f) &&
  4585. type != UPB_HANDLER_STARTSEQ &&
  4586. type != UPB_HANDLER_ENDSEQ) {
  4587. context_closure_type = returntype(h, f, UPB_HANDLER_STARTSEQ);
  4588. } else {
  4589. context_closure_type = &h->top_closure_type;
  4590. }
  4591. if (closure_type && *context_closure_type &&
  4592. closure_type != *context_closure_type) {
  4593. return false;
  4594. }
  4595. if (closure_type)
  4596. *context_closure_type = closure_type;
  4597. /* If this is a STARTSEQ or STARTSTR handler, check that the returned pointer
  4598. * matches any pre-existing expectations about what type is expected. */
  4599. if (type == UPB_HANDLER_STARTSEQ || type == UPB_HANDLER_STARTSTR) {
  4600. const void *return_type = set_attr.return_closure_type;
  4601. const void *table_return_type = h->table[sel].attr.return_closure_type;
  4602. if (return_type && table_return_type && return_type != table_return_type) {
  4603. return false;
  4604. }
  4605. if (table_return_type && !return_type) {
  4606. set_attr.return_closure_type = table_return_type;
  4607. }
  4608. }
  4609. h->table[sel].func = (upb_func*)func;
  4610. h->table[sel].attr = set_attr;
  4611. return true;
  4612. }
  4613. /* Returns the effective closure type for this handler (which will propagate
  4614. * from outer frames if this frame has no START* handler). Not implemented for
  4615. * UPB_HANDLER_STRING at the moment since this is not needed. Returns NULL is
  4616. * the effective closure type is unspecified (either no handler was registered
  4617. * to specify it or the handler that was registered did not specify the closure
  4618. * type). */
  4619. const void *effective_closure_type(upb_handlers *h, const upb_fielddef *f,
  4620. upb_handlertype_t type) {
  4621. const void *ret;
  4622. upb_selector_t sel;
  4623. UPB_ASSERT(type != UPB_HANDLER_STRING);
  4624. ret = h->top_closure_type;
  4625. if (upb_fielddef_isseq(f) &&
  4626. type != UPB_HANDLER_STARTSEQ &&
  4627. type != UPB_HANDLER_ENDSEQ &&
  4628. h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSEQ)].func) {
  4629. ret = h->table[sel].attr.return_closure_type;
  4630. }
  4631. if (type == UPB_HANDLER_STRING &&
  4632. h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSTR)].func) {
  4633. ret = h->table[sel].attr.return_closure_type;
  4634. }
  4635. /* The effective type of the submessage; not used yet.
  4636. * if (type == SUBMESSAGE &&
  4637. * h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSUBMSG)].func) {
  4638. * ret = h->table[sel].attr.return_closure_type;
  4639. * } */
  4640. return ret;
  4641. }
  4642. /* Checks whether the START* handler specified by f & type is missing even
  4643. * though it is required to convert the established type of an outer frame
  4644. * ("closure_type") into the established type of an inner frame (represented in
  4645. * the return closure type of this handler's attr. */
  4646. bool checkstart(upb_handlers *h, const upb_fielddef *f, upb_handlertype_t type,
  4647. upb_status *status) {
  4648. const void *closure_type;
  4649. const upb_handlerattr *attr;
  4650. const void *return_closure_type;
  4651. upb_selector_t sel = handlers_getsel(h, f, type);
  4652. if (h->table[sel].func) return true;
  4653. closure_type = effective_closure_type(h, f, type);
  4654. attr = &h->table[sel].attr;
  4655. return_closure_type = attr->return_closure_type;
  4656. if (closure_type && return_closure_type &&
  4657. closure_type != return_closure_type) {
  4658. return false;
  4659. }
  4660. return true;
  4661. }
  4662. static upb_handlers *upb_handlers_new(const upb_msgdef *md,
  4663. upb_handlercache *cache,
  4664. upb_arena *arena) {
  4665. int extra;
  4666. upb_handlers *h;
  4667. extra =
  4668. (int)(sizeof(upb_handlers_tabent) * (upb_msgdef_selectorcount(md) - 1));
  4669. h = upb_calloc(arena, sizeof(*h) + extra);
  4670. if (!h) return NULL;
  4671. h->cache = cache;
  4672. h->msg = md;
  4673. if (upb_msgdef_submsgfieldcount(md) > 0) {
  4674. size_t bytes = upb_msgdef_submsgfieldcount(md) * sizeof(*h->sub);
  4675. h->sub = upb_calloc(arena, bytes);
  4676. if (!h->sub) return NULL;
  4677. } else {
  4678. h->sub = 0;
  4679. }
  4680. /* calloc() above initialized all handlers to NULL. */
  4681. return h;
  4682. }
  4683. /* Public interface ***********************************************************/
  4684. #define SETTER(name, handlerctype, handlertype) \
  4685. bool upb_handlers_set##name(upb_handlers *h, const upb_fielddef *f, \
  4686. handlerctype func, \
  4687. const upb_handlerattr *attr) { \
  4688. int32_t sel = trygetsel(h, f, handlertype); \
  4689. return doset(h, sel, f, handlertype, (upb_func *)func, attr); \
  4690. }
  4691. SETTER(int32, upb_int32_handlerfunc*, UPB_HANDLER_INT32)
  4692. SETTER(int64, upb_int64_handlerfunc*, UPB_HANDLER_INT64)
  4693. SETTER(uint32, upb_uint32_handlerfunc*, UPB_HANDLER_UINT32)
  4694. SETTER(uint64, upb_uint64_handlerfunc*, UPB_HANDLER_UINT64)
  4695. SETTER(float, upb_float_handlerfunc*, UPB_HANDLER_FLOAT)
  4696. SETTER(double, upb_double_handlerfunc*, UPB_HANDLER_DOUBLE)
  4697. SETTER(bool, upb_bool_handlerfunc*, UPB_HANDLER_BOOL)
  4698. SETTER(startstr, upb_startstr_handlerfunc*, UPB_HANDLER_STARTSTR)
  4699. SETTER(string, upb_string_handlerfunc*, UPB_HANDLER_STRING)
  4700. SETTER(endstr, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSTR)
  4701. SETTER(startseq, upb_startfield_handlerfunc*, UPB_HANDLER_STARTSEQ)
  4702. SETTER(startsubmsg, upb_startfield_handlerfunc*, UPB_HANDLER_STARTSUBMSG)
  4703. SETTER(endsubmsg, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSUBMSG)
  4704. SETTER(endseq, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSEQ)
  4705. #undef SETTER
  4706. bool upb_handlers_setunknown(upb_handlers *h, upb_unknown_handlerfunc *func,
  4707. const upb_handlerattr *attr) {
  4708. return doset(h, UPB_UNKNOWN_SELECTOR, NULL, UPB_HANDLER_INT32,
  4709. (upb_func *)func, attr);
  4710. }
  4711. bool upb_handlers_setstartmsg(upb_handlers *h, upb_startmsg_handlerfunc *func,
  4712. const upb_handlerattr *attr) {
  4713. return doset(h, UPB_STARTMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
  4714. (upb_func *)func, attr);
  4715. }
  4716. bool upb_handlers_setendmsg(upb_handlers *h, upb_endmsg_handlerfunc *func,
  4717. const upb_handlerattr *attr) {
  4718. return doset(h, UPB_ENDMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
  4719. (upb_func *)func, attr);
  4720. }
  4721. bool upb_handlers_setsubhandlers(upb_handlers *h, const upb_fielddef *f,
  4722. const upb_handlers *sub) {
  4723. UPB_ASSERT(sub);
  4724. UPB_ASSERT(upb_fielddef_issubmsg(f));
  4725. if (SUBH_F(h, f)) return false; /* Can't reset. */
  4726. if (upb_handlers_msgdef(sub) != upb_fielddef_msgsubdef(f)) {
  4727. return false;
  4728. }
  4729. SUBH_F(h, f) = sub;
  4730. return true;
  4731. }
  4732. const upb_handlers *upb_handlers_getsubhandlers(const upb_handlers *h,
  4733. const upb_fielddef *f) {
  4734. UPB_ASSERT(upb_fielddef_issubmsg(f));
  4735. return SUBH_F(h, f);
  4736. }
  4737. upb_func *upb_handlers_gethandler(const upb_handlers *h, upb_selector_t s,
  4738. const void **handler_data) {
  4739. upb_func *ret = (upb_func *)h->table[s].func;
  4740. if (ret && handler_data) {
  4741. *handler_data = h->table[s].attr.handler_data;
  4742. }
  4743. return ret;
  4744. }
  4745. bool upb_handlers_getattr(const upb_handlers *h, upb_selector_t sel,
  4746. upb_handlerattr *attr) {
  4747. if (!upb_handlers_gethandler(h, sel, NULL))
  4748. return false;
  4749. *attr = h->table[sel].attr;
  4750. return true;
  4751. }
  4752. const upb_handlers *upb_handlers_getsubhandlers_sel(const upb_handlers *h,
  4753. upb_selector_t sel) {
  4754. /* STARTSUBMSG selector in sel is the field's selector base. */
  4755. return SUBH(h, sel - UPB_STATIC_SELECTOR_COUNT);
  4756. }
  4757. const upb_msgdef *upb_handlers_msgdef(const upb_handlers *h) { return h->msg; }
  4758. bool upb_handlers_addcleanup(upb_handlers *h, void *p, upb_handlerfree *func) {
  4759. return upb_handlercache_addcleanup(h->cache, p, func);
  4760. }
  4761. upb_handlertype_t upb_handlers_getprimitivehandlertype(const upb_fielddef *f) {
  4762. switch (upb_fielddef_type(f)) {
  4763. case UPB_TYPE_INT32:
  4764. case UPB_TYPE_ENUM: return UPB_HANDLER_INT32;
  4765. case UPB_TYPE_INT64: return UPB_HANDLER_INT64;
  4766. case UPB_TYPE_UINT32: return UPB_HANDLER_UINT32;
  4767. case UPB_TYPE_UINT64: return UPB_HANDLER_UINT64;
  4768. case UPB_TYPE_FLOAT: return UPB_HANDLER_FLOAT;
  4769. case UPB_TYPE_DOUBLE: return UPB_HANDLER_DOUBLE;
  4770. case UPB_TYPE_BOOL: return UPB_HANDLER_BOOL;
  4771. default: UPB_ASSERT(false); return -1; /* Invalid input. */
  4772. }
  4773. }
  4774. bool upb_handlers_getselector(const upb_fielddef *f, upb_handlertype_t type,
  4775. upb_selector_t *s) {
  4776. uint32_t selector_base = upb_fielddef_selectorbase(f);
  4777. switch (type) {
  4778. case UPB_HANDLER_INT32:
  4779. case UPB_HANDLER_INT64:
  4780. case UPB_HANDLER_UINT32:
  4781. case UPB_HANDLER_UINT64:
  4782. case UPB_HANDLER_FLOAT:
  4783. case UPB_HANDLER_DOUBLE:
  4784. case UPB_HANDLER_BOOL:
  4785. if (!upb_fielddef_isprimitive(f) ||
  4786. upb_handlers_getprimitivehandlertype(f) != type)
  4787. return false;
  4788. *s = selector_base;
  4789. break;
  4790. case UPB_HANDLER_STRING:
  4791. if (upb_fielddef_isstring(f)) {
  4792. *s = selector_base;
  4793. } else if (upb_fielddef_lazy(f)) {
  4794. *s = selector_base + 3;
  4795. } else {
  4796. return false;
  4797. }
  4798. break;
  4799. case UPB_HANDLER_STARTSTR:
  4800. if (upb_fielddef_isstring(f) || upb_fielddef_lazy(f)) {
  4801. *s = selector_base + 1;
  4802. } else {
  4803. return false;
  4804. }
  4805. break;
  4806. case UPB_HANDLER_ENDSTR:
  4807. if (upb_fielddef_isstring(f) || upb_fielddef_lazy(f)) {
  4808. *s = selector_base + 2;
  4809. } else {
  4810. return false;
  4811. }
  4812. break;
  4813. case UPB_HANDLER_STARTSEQ:
  4814. if (!upb_fielddef_isseq(f)) return false;
  4815. *s = selector_base - 2;
  4816. break;
  4817. case UPB_HANDLER_ENDSEQ:
  4818. if (!upb_fielddef_isseq(f)) return false;
  4819. *s = selector_base - 1;
  4820. break;
  4821. case UPB_HANDLER_STARTSUBMSG:
  4822. if (!upb_fielddef_issubmsg(f)) return false;
  4823. /* Selectors for STARTSUBMSG are at the beginning of the table so that the
  4824. * selector can also be used as an index into the "sub" array of
  4825. * subhandlers. The indexes for the two into these two tables are the
  4826. * same, except that in the handler table the static selectors come first. */
  4827. *s = upb_fielddef_index(f) + UPB_STATIC_SELECTOR_COUNT;
  4828. break;
  4829. case UPB_HANDLER_ENDSUBMSG:
  4830. if (!upb_fielddef_issubmsg(f)) return false;
  4831. *s = selector_base;
  4832. break;
  4833. }
  4834. UPB_ASSERT((size_t)*s < upb_msgdef_selectorcount(upb_fielddef_containingtype(f)));
  4835. return true;
  4836. }
  4837. /* upb_handlercache ***********************************************************/
  4838. struct upb_handlercache {
  4839. upb_arena *arena;
  4840. upb_inttable tab; /* maps upb_msgdef* -> upb_handlers*. */
  4841. upb_handlers_callback *callback;
  4842. const void *closure;
  4843. };
  4844. const upb_handlers *upb_handlercache_get(upb_handlercache *c,
  4845. const upb_msgdef *md) {
  4846. upb_msg_field_iter i;
  4847. upb_value v;
  4848. upb_handlers *h;
  4849. if (upb_inttable_lookupptr(&c->tab, md, &v)) {
  4850. return upb_value_getptr(v);
  4851. }
  4852. h = upb_handlers_new(md, c, c->arena);
  4853. v = upb_value_ptr(h);
  4854. if (!h) return NULL;
  4855. if (!upb_inttable_insertptr(&c->tab, md, v)) return NULL;
  4856. c->callback(c->closure, h);
  4857. /* For each submessage field, get or create a handlers object and set it as
  4858. * the subhandlers. */
  4859. for(upb_msg_field_begin(&i, md);
  4860. !upb_msg_field_done(&i);
  4861. upb_msg_field_next(&i)) {
  4862. upb_fielddef *f = upb_msg_iter_field(&i);
  4863. if (upb_fielddef_issubmsg(f)) {
  4864. const upb_msgdef *subdef = upb_fielddef_msgsubdef(f);
  4865. const upb_handlers *sub_mh = upb_handlercache_get(c, subdef);
  4866. if (!sub_mh) return NULL;
  4867. upb_handlers_setsubhandlers(h, f, sub_mh);
  4868. }
  4869. }
  4870. return h;
  4871. }
  4872. upb_handlercache *upb_handlercache_new(upb_handlers_callback *callback,
  4873. const void *closure) {
  4874. upb_handlercache *cache = upb_gmalloc(sizeof(*cache));
  4875. if (!cache) return NULL;
  4876. cache->arena = upb_arena_new();
  4877. cache->callback = callback;
  4878. cache->closure = closure;
  4879. if (!upb_inttable_init(&cache->tab, UPB_CTYPE_PTR)) goto oom;
  4880. return cache;
  4881. oom:
  4882. upb_gfree(cache);
  4883. return NULL;
  4884. }
  4885. void upb_handlercache_free(upb_handlercache *cache) {
  4886. upb_inttable_uninit(&cache->tab);
  4887. upb_arena_free(cache->arena);
  4888. upb_gfree(cache);
  4889. }
  4890. bool upb_handlercache_addcleanup(upb_handlercache *c, void *p,
  4891. upb_handlerfree *func) {
  4892. return upb_arena_addcleanup(c->arena, p, func);
  4893. }
  4894. /* upb_byteshandler ***********************************************************/
  4895. bool upb_byteshandler_setstartstr(upb_byteshandler *h,
  4896. upb_startstr_handlerfunc *func, void *d) {
  4897. h->table[UPB_STARTSTR_SELECTOR].func = (upb_func*)func;
  4898. h->table[UPB_STARTSTR_SELECTOR].attr.handler_data = d;
  4899. return true;
  4900. }
  4901. bool upb_byteshandler_setstring(upb_byteshandler *h,
  4902. upb_string_handlerfunc *func, void *d) {
  4903. h->table[UPB_STRING_SELECTOR].func = (upb_func*)func;
  4904. h->table[UPB_STRING_SELECTOR].attr.handler_data = d;
  4905. return true;
  4906. }
  4907. bool upb_byteshandler_setendstr(upb_byteshandler *h,
  4908. upb_endfield_handlerfunc *func, void *d) {
  4909. h->table[UPB_ENDSTR_SELECTOR].func = (upb_func*)func;
  4910. h->table[UPB_ENDSTR_SELECTOR].attr.handler_data = d;
  4911. return true;
  4912. }
  4913. /** Handlers for upb_msg ******************************************************/
  4914. typedef struct {
  4915. size_t offset;
  4916. int32_t hasbit;
  4917. } upb_msg_handlerdata;
  4918. /* Fallback implementation if the handler is not specialized by the producer. */
  4919. #define MSG_WRITER(type, ctype) \
  4920. bool upb_msg_set ## type (void *c, const void *hd, ctype val) { \
  4921. uint8_t *m = c; \
  4922. const upb_msg_handlerdata *d = hd; \
  4923. if (d->hasbit > 0) \
  4924. *(uint8_t*)&m[d->hasbit / 8] |= 1 << (d->hasbit % 8); \
  4925. *(ctype*)&m[d->offset] = val; \
  4926. return true; \
  4927. } \
  4928. MSG_WRITER(double, double)
  4929. MSG_WRITER(float, float)
  4930. MSG_WRITER(int32, int32_t)
  4931. MSG_WRITER(int64, int64_t)
  4932. MSG_WRITER(uint32, uint32_t)
  4933. MSG_WRITER(uint64, uint64_t)
  4934. MSG_WRITER(bool, bool)
  4935. bool upb_msg_setscalarhandler(upb_handlers *h, const upb_fielddef *f,
  4936. size_t offset, int32_t hasbit) {
  4937. upb_handlerattr attr = UPB_HANDLERATTR_INIT;
  4938. bool ok;
  4939. upb_msg_handlerdata *d = upb_gmalloc(sizeof(*d));
  4940. if (!d) return false;
  4941. d->offset = offset;
  4942. d->hasbit = hasbit;
  4943. attr.handler_data = d;
  4944. attr.alwaysok = true;
  4945. upb_handlers_addcleanup(h, d, upb_gfree);
  4946. #define TYPE(u, l) \
  4947. case UPB_TYPE_##u: \
  4948. ok = upb_handlers_set##l(h, f, upb_msg_set##l, &attr); break;
  4949. ok = false;
  4950. switch (upb_fielddef_type(f)) {
  4951. TYPE(INT64, int64);
  4952. TYPE(INT32, int32);
  4953. TYPE(ENUM, int32);
  4954. TYPE(UINT64, uint64);
  4955. TYPE(UINT32, uint32);
  4956. TYPE(DOUBLE, double);
  4957. TYPE(FLOAT, float);
  4958. TYPE(BOOL, bool);
  4959. default: UPB_ASSERT(false); break;
  4960. }
  4961. #undef TYPE
  4962. return ok;
  4963. }
  4964. bool upb_msg_getscalarhandlerdata(const upb_handlers *h,
  4965. upb_selector_t s,
  4966. upb_fieldtype_t *type,
  4967. size_t *offset,
  4968. int32_t *hasbit) {
  4969. const upb_msg_handlerdata *d;
  4970. const void *p;
  4971. upb_func *f = upb_handlers_gethandler(h, s, &p);
  4972. if ((upb_int64_handlerfunc*)f == upb_msg_setint64) {
  4973. *type = UPB_TYPE_INT64;
  4974. } else if ((upb_int32_handlerfunc*)f == upb_msg_setint32) {
  4975. *type = UPB_TYPE_INT32;
  4976. } else if ((upb_uint64_handlerfunc*)f == upb_msg_setuint64) {
  4977. *type = UPB_TYPE_UINT64;
  4978. } else if ((upb_uint32_handlerfunc*)f == upb_msg_setuint32) {
  4979. *type = UPB_TYPE_UINT32;
  4980. } else if ((upb_double_handlerfunc*)f == upb_msg_setdouble) {
  4981. *type = UPB_TYPE_DOUBLE;
  4982. } else if ((upb_float_handlerfunc*)f == upb_msg_setfloat) {
  4983. *type = UPB_TYPE_FLOAT;
  4984. } else if ((upb_bool_handlerfunc*)f == upb_msg_setbool) {
  4985. *type = UPB_TYPE_BOOL;
  4986. } else {
  4987. return false;
  4988. }
  4989. d = p;
  4990. *offset = d->offset;
  4991. *hasbit = d->hasbit;
  4992. return true;
  4993. }
  4994. bool upb_bufsrc_putbuf(const char *buf, size_t len, upb_bytessink sink) {
  4995. void *subc;
  4996. bool ret;
  4997. upb_bufhandle handle = UPB_BUFHANDLE_INIT;
  4998. handle.buf = buf;
  4999. ret = upb_bytessink_start(sink, len, &subc);
  5000. if (ret && len != 0) {
  5001. ret = (upb_bytessink_putbuf(sink, subc, buf, len, &handle) >= len);
  5002. }
  5003. if (ret) {
  5004. ret = upb_bytessink_end(sink);
  5005. }
  5006. return ret;
  5007. }
  5008. #ifdef UPB_MSVC_VSNPRINTF
  5009. /* Visual C++ earlier than 2015 doesn't have standard C99 snprintf and
  5010. * vsnprintf. To support them, missing functions are manually implemented
  5011. * using the existing secure functions. */
  5012. int msvc_vsnprintf(char* s, size_t n, const char* format, va_list arg) {
  5013. if (!s) {
  5014. return _vscprintf(format, arg);
  5015. }
  5016. int ret = _vsnprintf_s(s, n, _TRUNCATE, format, arg);
  5017. if (ret < 0) {
  5018. ret = _vscprintf(format, arg);
  5019. }
  5020. return ret;
  5021. }
  5022. int msvc_snprintf(char* s, size_t n, const char* format, ...) {
  5023. va_list arg;
  5024. va_start(arg, format);
  5025. int ret = msvc_vsnprintf(s, n, format, arg);
  5026. va_end(arg);
  5027. return ret;
  5028. }
  5029. #endif
  5030. /*
  5031. ** protobuf decoder bytecode compiler
  5032. **
  5033. ** Code to compile a upb::Handlers into bytecode for decoding a protobuf
  5034. ** according to that specific schema and destination handlers.
  5035. **
  5036. ** Bytecode definition is in decoder.int.h.
  5037. */
  5038. #include <stdarg.h>
  5039. #ifdef UPB_DUMP_BYTECODE
  5040. #include <stdio.h>
  5041. #endif
  5042. #define MAXLABEL 5
  5043. #define EMPTYLABEL -1
  5044. /* upb_pbdecodermethod ********************************************************/
  5045. static void freemethod(upb_pbdecodermethod *method) {
  5046. upb_inttable_uninit(&method->dispatch);
  5047. upb_gfree(method);
  5048. }
  5049. static upb_pbdecodermethod *newmethod(const upb_handlers *dest_handlers,
  5050. mgroup *group) {
  5051. upb_pbdecodermethod *ret = upb_gmalloc(sizeof(*ret));
  5052. upb_byteshandler_init(&ret->input_handler_);
  5053. ret->group = group;
  5054. ret->dest_handlers_ = dest_handlers;
  5055. upb_inttable_init(&ret->dispatch, UPB_CTYPE_UINT64);
  5056. return ret;
  5057. }
  5058. const upb_handlers *upb_pbdecodermethod_desthandlers(
  5059. const upb_pbdecodermethod *m) {
  5060. return m->dest_handlers_;
  5061. }
  5062. const upb_byteshandler *upb_pbdecodermethod_inputhandler(
  5063. const upb_pbdecodermethod *m) {
  5064. return &m->input_handler_;
  5065. }
  5066. bool upb_pbdecodermethod_isnative(const upb_pbdecodermethod *m) {
  5067. return m->is_native_;
  5068. }
  5069. /* mgroup *********************************************************************/
  5070. static void freegroup(mgroup *g) {
  5071. upb_inttable_iter i;
  5072. upb_inttable_begin(&i, &g->methods);
  5073. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5074. freemethod(upb_value_getptr(upb_inttable_iter_value(&i)));
  5075. }
  5076. upb_inttable_uninit(&g->methods);
  5077. upb_gfree(g->bytecode);
  5078. upb_gfree(g);
  5079. }
  5080. mgroup *newgroup(void) {
  5081. mgroup *g = upb_gmalloc(sizeof(*g));
  5082. upb_inttable_init(&g->methods, UPB_CTYPE_PTR);
  5083. g->bytecode = NULL;
  5084. g->bytecode_end = NULL;
  5085. return g;
  5086. }
  5087. /* bytecode compiler **********************************************************/
  5088. /* Data used only at compilation time. */
  5089. typedef struct {
  5090. mgroup *group;
  5091. uint32_t *pc;
  5092. int fwd_labels[MAXLABEL];
  5093. int back_labels[MAXLABEL];
  5094. /* For fields marked "lazy", parse them lazily or eagerly? */
  5095. bool lazy;
  5096. } compiler;
  5097. static compiler *newcompiler(mgroup *group, bool lazy) {
  5098. compiler *ret = upb_gmalloc(sizeof(*ret));
  5099. int i;
  5100. ret->group = group;
  5101. ret->lazy = lazy;
  5102. for (i = 0; i < MAXLABEL; i++) {
  5103. ret->fwd_labels[i] = EMPTYLABEL;
  5104. ret->back_labels[i] = EMPTYLABEL;
  5105. }
  5106. return ret;
  5107. }
  5108. static void freecompiler(compiler *c) {
  5109. upb_gfree(c);
  5110. }
  5111. const size_t ptr_words = sizeof(void*) / sizeof(uint32_t);
  5112. /* How many words an instruction is. */
  5113. static int instruction_len(uint32_t instr) {
  5114. switch (getop(instr)) {
  5115. case OP_SETDISPATCH: return 1 + ptr_words;
  5116. case OP_TAGN: return 3;
  5117. case OP_SETBIGGROUPNUM: return 2;
  5118. default: return 1;
  5119. }
  5120. }
  5121. bool op_has_longofs(int32_t instruction) {
  5122. switch (getop(instruction)) {
  5123. case OP_CALL:
  5124. case OP_BRANCH:
  5125. case OP_CHECKDELIM:
  5126. return true;
  5127. /* The "tag" instructions only have 8 bytes available for the jump target,
  5128. * but that is ok because these opcodes only require short jumps. */
  5129. case OP_TAG1:
  5130. case OP_TAG2:
  5131. case OP_TAGN:
  5132. return false;
  5133. default:
  5134. UPB_ASSERT(false);
  5135. return false;
  5136. }
  5137. }
  5138. static int32_t getofs(uint32_t instruction) {
  5139. if (op_has_longofs(instruction)) {
  5140. return (int32_t)instruction >> 8;
  5141. } else {
  5142. return (int8_t)(instruction >> 8);
  5143. }
  5144. }
  5145. static void setofs(uint32_t *instruction, int32_t ofs) {
  5146. if (op_has_longofs(*instruction)) {
  5147. *instruction = getop(*instruction) | (uint32_t)ofs << 8;
  5148. } else {
  5149. *instruction = (*instruction & ~0xff00) | ((ofs & 0xff) << 8);
  5150. }
  5151. UPB_ASSERT(getofs(*instruction) == ofs); /* Would fail in cases of overflow. */
  5152. }
  5153. static uint32_t pcofs(compiler *c) {
  5154. return (uint32_t)(c->pc - c->group->bytecode);
  5155. }
  5156. /* Defines a local label at the current PC location. All previous forward
  5157. * references are updated to point to this location. The location is noted
  5158. * for any future backward references. */
  5159. static void label(compiler *c, unsigned int label) {
  5160. int val;
  5161. uint32_t *codep;
  5162. UPB_ASSERT(label < MAXLABEL);
  5163. val = c->fwd_labels[label];
  5164. codep = (val == EMPTYLABEL) ? NULL : c->group->bytecode + val;
  5165. while (codep) {
  5166. int ofs = getofs(*codep);
  5167. setofs(codep, (int32_t)(c->pc - codep - instruction_len(*codep)));
  5168. codep = ofs ? codep + ofs : NULL;
  5169. }
  5170. c->fwd_labels[label] = EMPTYLABEL;
  5171. c->back_labels[label] = pcofs(c);
  5172. }
  5173. /* Creates a reference to a numbered label; either a forward reference
  5174. * (positive arg) or backward reference (negative arg). For forward references
  5175. * the value returned now is actually a "next" pointer into a linked list of all
  5176. * instructions that use this label and will be patched later when the label is
  5177. * defined with label().
  5178. *
  5179. * The returned value is the offset that should be written into the instruction.
  5180. */
  5181. static int32_t labelref(compiler *c, int label) {
  5182. UPB_ASSERT(label < MAXLABEL);
  5183. if (label == LABEL_DISPATCH) {
  5184. /* No resolving required. */
  5185. return 0;
  5186. } else if (label < 0) {
  5187. /* Backward local label. Relative to the next instruction. */
  5188. uint32_t from = (uint32_t)((c->pc + 1) - c->group->bytecode);
  5189. return c->back_labels[-label] - from;
  5190. } else {
  5191. /* Forward local label: prepend to (possibly-empty) linked list. */
  5192. int *lptr = &c->fwd_labels[label];
  5193. int32_t ret = (*lptr == EMPTYLABEL) ? 0 : *lptr - pcofs(c);
  5194. *lptr = pcofs(c);
  5195. return ret;
  5196. }
  5197. }
  5198. static void put32(compiler *c, uint32_t v) {
  5199. mgroup *g = c->group;
  5200. if (c->pc == g->bytecode_end) {
  5201. int ofs = pcofs(c);
  5202. size_t oldsize = g->bytecode_end - g->bytecode;
  5203. size_t newsize = UPB_MAX(oldsize * 2, 64);
  5204. /* TODO(haberman): handle OOM. */
  5205. g->bytecode = upb_grealloc(g->bytecode, oldsize * sizeof(uint32_t),
  5206. newsize * sizeof(uint32_t));
  5207. g->bytecode_end = g->bytecode + newsize;
  5208. c->pc = g->bytecode + ofs;
  5209. }
  5210. *c->pc++ = v;
  5211. }
  5212. static void putop(compiler *c, int op, ...) {
  5213. va_list ap;
  5214. va_start(ap, op);
  5215. switch (op) {
  5216. case OP_SETDISPATCH: {
  5217. uintptr_t ptr = (uintptr_t)va_arg(ap, void*);
  5218. put32(c, OP_SETDISPATCH);
  5219. put32(c, (uint32_t)ptr);
  5220. if (sizeof(uintptr_t) > sizeof(uint32_t))
  5221. put32(c, (uint64_t)ptr >> 32);
  5222. break;
  5223. }
  5224. case OP_STARTMSG:
  5225. case OP_ENDMSG:
  5226. case OP_PUSHLENDELIM:
  5227. case OP_POP:
  5228. case OP_SETDELIM:
  5229. case OP_HALT:
  5230. case OP_RET:
  5231. case OP_DISPATCH:
  5232. put32(c, op);
  5233. break;
  5234. case OP_PARSE_DOUBLE:
  5235. case OP_PARSE_FLOAT:
  5236. case OP_PARSE_INT64:
  5237. case OP_PARSE_UINT64:
  5238. case OP_PARSE_INT32:
  5239. case OP_PARSE_FIXED64:
  5240. case OP_PARSE_FIXED32:
  5241. case OP_PARSE_BOOL:
  5242. case OP_PARSE_UINT32:
  5243. case OP_PARSE_SFIXED32:
  5244. case OP_PARSE_SFIXED64:
  5245. case OP_PARSE_SINT32:
  5246. case OP_PARSE_SINT64:
  5247. case OP_STARTSEQ:
  5248. case OP_ENDSEQ:
  5249. case OP_STARTSUBMSG:
  5250. case OP_ENDSUBMSG:
  5251. case OP_STARTSTR:
  5252. case OP_STRING:
  5253. case OP_ENDSTR:
  5254. case OP_PUSHTAGDELIM:
  5255. put32(c, op | va_arg(ap, upb_selector_t) << 8);
  5256. break;
  5257. case OP_SETBIGGROUPNUM:
  5258. put32(c, op);
  5259. put32(c, va_arg(ap, int));
  5260. break;
  5261. case OP_CALL: {
  5262. const upb_pbdecodermethod *method = va_arg(ap, upb_pbdecodermethod *);
  5263. put32(c, op | (method->code_base.ofs - (pcofs(c) + 1)) << 8);
  5264. break;
  5265. }
  5266. case OP_CHECKDELIM:
  5267. case OP_BRANCH: {
  5268. uint32_t instruction = op;
  5269. int label = va_arg(ap, int);
  5270. setofs(&instruction, labelref(c, label));
  5271. put32(c, instruction);
  5272. break;
  5273. }
  5274. case OP_TAG1:
  5275. case OP_TAG2: {
  5276. int label = va_arg(ap, int);
  5277. uint64_t tag = va_arg(ap, uint64_t);
  5278. uint32_t instruction = (uint32_t)(op | (tag << 16));
  5279. UPB_ASSERT(tag <= 0xffff);
  5280. setofs(&instruction, labelref(c, label));
  5281. put32(c, instruction);
  5282. break;
  5283. }
  5284. case OP_TAGN: {
  5285. int label = va_arg(ap, int);
  5286. uint64_t tag = va_arg(ap, uint64_t);
  5287. uint32_t instruction = op | (upb_value_size(tag) << 16);
  5288. setofs(&instruction, labelref(c, label));
  5289. put32(c, instruction);
  5290. put32(c, (uint32_t)tag);
  5291. put32(c, tag >> 32);
  5292. break;
  5293. }
  5294. }
  5295. va_end(ap);
  5296. }
  5297. #if defined(UPB_DUMP_BYTECODE)
  5298. const char *upb_pbdecoder_getopname(unsigned int op) {
  5299. #define QUOTE(x) #x
  5300. #define EXPAND_AND_QUOTE(x) QUOTE(x)
  5301. #define OPNAME(x) OP_##x
  5302. #define OP(x) case OPNAME(x): return EXPAND_AND_QUOTE(OPNAME(x));
  5303. #define T(x) OP(PARSE_##x)
  5304. /* Keep in sync with list in decoder.int.h. */
  5305. switch ((opcode)op) {
  5306. T(DOUBLE) T(FLOAT) T(INT64) T(UINT64) T(INT32) T(FIXED64) T(FIXED32)
  5307. T(BOOL) T(UINT32) T(SFIXED32) T(SFIXED64) T(SINT32) T(SINT64)
  5308. OP(STARTMSG) OP(ENDMSG) OP(STARTSEQ) OP(ENDSEQ) OP(STARTSUBMSG)
  5309. OP(ENDSUBMSG) OP(STARTSTR) OP(STRING) OP(ENDSTR) OP(CALL) OP(RET)
  5310. OP(PUSHLENDELIM) OP(PUSHTAGDELIM) OP(SETDELIM) OP(CHECKDELIM)
  5311. OP(BRANCH) OP(TAG1) OP(TAG2) OP(TAGN) OP(SETDISPATCH) OP(POP)
  5312. OP(SETBIGGROUPNUM) OP(DISPATCH) OP(HALT)
  5313. }
  5314. return "<unknown op>";
  5315. #undef OP
  5316. #undef T
  5317. }
  5318. #endif
  5319. #ifdef UPB_DUMP_BYTECODE
  5320. static void dumpbc(uint32_t *p, uint32_t *end, FILE *f) {
  5321. uint32_t *begin = p;
  5322. while (p < end) {
  5323. fprintf(f, "%p %8tx", p, p - begin);
  5324. uint32_t instr = *p++;
  5325. uint8_t op = getop(instr);
  5326. fprintf(f, " %s", upb_pbdecoder_getopname(op));
  5327. switch ((opcode)op) {
  5328. case OP_SETDISPATCH: {
  5329. const upb_inttable *dispatch;
  5330. memcpy(&dispatch, p, sizeof(void*));
  5331. p += ptr_words;
  5332. const upb_pbdecodermethod *method =
  5333. (void *)((char *)dispatch -
  5334. offsetof(upb_pbdecodermethod, dispatch));
  5335. fprintf(f, " %s", upb_msgdef_fullname(
  5336. upb_handlers_msgdef(method->dest_handlers_)));
  5337. break;
  5338. }
  5339. case OP_DISPATCH:
  5340. case OP_STARTMSG:
  5341. case OP_ENDMSG:
  5342. case OP_PUSHLENDELIM:
  5343. case OP_POP:
  5344. case OP_SETDELIM:
  5345. case OP_HALT:
  5346. case OP_RET:
  5347. break;
  5348. case OP_PARSE_DOUBLE:
  5349. case OP_PARSE_FLOAT:
  5350. case OP_PARSE_INT64:
  5351. case OP_PARSE_UINT64:
  5352. case OP_PARSE_INT32:
  5353. case OP_PARSE_FIXED64:
  5354. case OP_PARSE_FIXED32:
  5355. case OP_PARSE_BOOL:
  5356. case OP_PARSE_UINT32:
  5357. case OP_PARSE_SFIXED32:
  5358. case OP_PARSE_SFIXED64:
  5359. case OP_PARSE_SINT32:
  5360. case OP_PARSE_SINT64:
  5361. case OP_STARTSEQ:
  5362. case OP_ENDSEQ:
  5363. case OP_STARTSUBMSG:
  5364. case OP_ENDSUBMSG:
  5365. case OP_STARTSTR:
  5366. case OP_STRING:
  5367. case OP_ENDSTR:
  5368. case OP_PUSHTAGDELIM:
  5369. fprintf(f, " %d", instr >> 8);
  5370. break;
  5371. case OP_SETBIGGROUPNUM:
  5372. fprintf(f, " %d", *p++);
  5373. break;
  5374. case OP_CHECKDELIM:
  5375. case OP_CALL:
  5376. case OP_BRANCH:
  5377. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  5378. break;
  5379. case OP_TAG1:
  5380. case OP_TAG2: {
  5381. fprintf(f, " tag:0x%x", instr >> 16);
  5382. if (getofs(instr)) {
  5383. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  5384. }
  5385. break;
  5386. }
  5387. case OP_TAGN: {
  5388. uint64_t tag = *p++;
  5389. tag |= (uint64_t)*p++ << 32;
  5390. fprintf(f, " tag:0x%llx", (long long)tag);
  5391. fprintf(f, " n:%d", instr >> 16);
  5392. if (getofs(instr)) {
  5393. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  5394. }
  5395. break;
  5396. }
  5397. }
  5398. fputs("\n", f);
  5399. }
  5400. }
  5401. #endif
  5402. static uint64_t get_encoded_tag(const upb_fielddef *f, int wire_type) {
  5403. uint32_t tag = (upb_fielddef_number(f) << 3) | wire_type;
  5404. uint64_t encoded_tag = upb_vencode32(tag);
  5405. /* No tag should be greater than 5 bytes. */
  5406. UPB_ASSERT(encoded_tag <= 0xffffffffff);
  5407. return encoded_tag;
  5408. }
  5409. static void putchecktag(compiler *c, const upb_fielddef *f,
  5410. int wire_type, int dest) {
  5411. uint64_t tag = get_encoded_tag(f, wire_type);
  5412. switch (upb_value_size(tag)) {
  5413. case 1:
  5414. putop(c, OP_TAG1, dest, tag);
  5415. break;
  5416. case 2:
  5417. putop(c, OP_TAG2, dest, tag);
  5418. break;
  5419. default:
  5420. putop(c, OP_TAGN, dest, tag);
  5421. break;
  5422. }
  5423. }
  5424. static upb_selector_t getsel(const upb_fielddef *f, upb_handlertype_t type) {
  5425. upb_selector_t selector;
  5426. bool ok = upb_handlers_getselector(f, type, &selector);
  5427. UPB_ASSERT(ok);
  5428. return selector;
  5429. }
  5430. /* Takes an existing, primary dispatch table entry and repacks it with a
  5431. * different alternate wire type. Called when we are inserting a secondary
  5432. * dispatch table entry for an alternate wire type. */
  5433. static uint64_t repack(uint64_t dispatch, int new_wt2) {
  5434. uint64_t ofs;
  5435. uint8_t wt1;
  5436. uint8_t old_wt2;
  5437. upb_pbdecoder_unpackdispatch(dispatch, &ofs, &wt1, &old_wt2);
  5438. UPB_ASSERT(old_wt2 == NO_WIRE_TYPE); /* wt2 should not be set yet. */
  5439. return upb_pbdecoder_packdispatch(ofs, wt1, new_wt2);
  5440. }
  5441. /* Marks the current bytecode position as the dispatch target for this message,
  5442. * field, and wire type. */
  5443. static void dispatchtarget(compiler *c, upb_pbdecodermethod *method,
  5444. const upb_fielddef *f, int wire_type) {
  5445. /* Offset is relative to msg base. */
  5446. uint64_t ofs = pcofs(c) - method->code_base.ofs;
  5447. uint32_t fn = upb_fielddef_number(f);
  5448. upb_inttable *d = &method->dispatch;
  5449. upb_value v;
  5450. if (upb_inttable_remove(d, fn, &v)) {
  5451. /* TODO: prioritize based on packed setting in .proto file. */
  5452. uint64_t repacked = repack(upb_value_getuint64(v), wire_type);
  5453. upb_inttable_insert(d, fn, upb_value_uint64(repacked));
  5454. upb_inttable_insert(d, fn + UPB_MAX_FIELDNUMBER, upb_value_uint64(ofs));
  5455. } else {
  5456. uint64_t val = upb_pbdecoder_packdispatch(ofs, wire_type, NO_WIRE_TYPE);
  5457. upb_inttable_insert(d, fn, upb_value_uint64(val));
  5458. }
  5459. }
  5460. static void putpush(compiler *c, const upb_fielddef *f) {
  5461. if (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE) {
  5462. putop(c, OP_PUSHLENDELIM);
  5463. } else {
  5464. uint32_t fn = upb_fielddef_number(f);
  5465. if (fn >= 1 << 24) {
  5466. putop(c, OP_PUSHTAGDELIM, 0);
  5467. putop(c, OP_SETBIGGROUPNUM, fn);
  5468. } else {
  5469. putop(c, OP_PUSHTAGDELIM, fn);
  5470. }
  5471. }
  5472. }
  5473. static upb_pbdecodermethod *find_submethod(const compiler *c,
  5474. const upb_pbdecodermethod *method,
  5475. const upb_fielddef *f) {
  5476. const upb_handlers *sub =
  5477. upb_handlers_getsubhandlers(method->dest_handlers_, f);
  5478. upb_value v;
  5479. return upb_inttable_lookupptr(&c->group->methods, sub, &v)
  5480. ? upb_value_getptr(v)
  5481. : NULL;
  5482. }
  5483. static void putsel(compiler *c, opcode op, upb_selector_t sel,
  5484. const upb_handlers *h) {
  5485. if (upb_handlers_gethandler(h, sel, NULL)) {
  5486. putop(c, op, sel);
  5487. }
  5488. }
  5489. /* Puts an opcode to call a callback, but only if a callback actually exists for
  5490. * this field and handler type. */
  5491. static void maybeput(compiler *c, opcode op, const upb_handlers *h,
  5492. const upb_fielddef *f, upb_handlertype_t type) {
  5493. putsel(c, op, getsel(f, type), h);
  5494. }
  5495. static bool haslazyhandlers(const upb_handlers *h, const upb_fielddef *f) {
  5496. if (!upb_fielddef_lazy(f))
  5497. return false;
  5498. return upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STARTSTR), NULL) ||
  5499. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STRING), NULL) ||
  5500. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_ENDSTR), NULL);
  5501. }
  5502. /* bytecode compiler code generation ******************************************/
  5503. /* Symbolic names for our local labels. */
  5504. #define LABEL_LOOPSTART 1 /* Top of a repeated field loop. */
  5505. #define LABEL_LOOPBREAK 2 /* To jump out of a repeated loop */
  5506. #define LABEL_FIELD 3 /* Jump backward to find the most recent field. */
  5507. #define LABEL_ENDMSG 4 /* To reach the OP_ENDMSG instr for this msg. */
  5508. /* Generates bytecode to parse a single non-lazy message field. */
  5509. static void generate_msgfield(compiler *c, const upb_fielddef *f,
  5510. upb_pbdecodermethod *method) {
  5511. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  5512. const upb_pbdecodermethod *sub_m = find_submethod(c, method, f);
  5513. int wire_type;
  5514. if (!sub_m) {
  5515. /* Don't emit any code for this field at all; it will be parsed as an
  5516. * unknown field.
  5517. *
  5518. * TODO(haberman): we should change this to parse it as a string field
  5519. * instead. It will probably be faster, but more importantly, once we
  5520. * start vending unknown fields, a field shouldn't be treated as unknown
  5521. * just because it doesn't have subhandlers registered. */
  5522. return;
  5523. }
  5524. label(c, LABEL_FIELD);
  5525. wire_type =
  5526. (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE)
  5527. ? UPB_WIRE_TYPE_DELIMITED
  5528. : UPB_WIRE_TYPE_START_GROUP;
  5529. if (upb_fielddef_isseq(f)) {
  5530. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5531. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  5532. dispatchtarget(c, method, f, wire_type);
  5533. putop(c, OP_PUSHTAGDELIM, 0);
  5534. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  5535. label(c, LABEL_LOOPSTART);
  5536. putpush(c, f);
  5537. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  5538. putop(c, OP_CALL, sub_m);
  5539. putop(c, OP_POP);
  5540. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  5541. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  5542. putop(c, OP_SETDELIM);
  5543. }
  5544. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5545. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  5546. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5547. label(c, LABEL_LOOPBREAK);
  5548. putop(c, OP_POP);
  5549. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  5550. } else {
  5551. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5552. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  5553. dispatchtarget(c, method, f, wire_type);
  5554. putpush(c, f);
  5555. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  5556. putop(c, OP_CALL, sub_m);
  5557. putop(c, OP_POP);
  5558. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  5559. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  5560. putop(c, OP_SETDELIM);
  5561. }
  5562. }
  5563. }
  5564. /* Generates bytecode to parse a single string or lazy submessage field. */
  5565. static void generate_delimfield(compiler *c, const upb_fielddef *f,
  5566. upb_pbdecodermethod *method) {
  5567. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  5568. label(c, LABEL_FIELD);
  5569. if (upb_fielddef_isseq(f)) {
  5570. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5571. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  5572. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  5573. putop(c, OP_PUSHTAGDELIM, 0);
  5574. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  5575. label(c, LABEL_LOOPSTART);
  5576. putop(c, OP_PUSHLENDELIM);
  5577. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  5578. /* Need to emit even if no handler to skip past the string. */
  5579. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  5580. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  5581. putop(c, OP_POP);
  5582. putop(c, OP_SETDELIM);
  5583. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5584. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_LOOPBREAK);
  5585. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5586. label(c, LABEL_LOOPBREAK);
  5587. putop(c, OP_POP);
  5588. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  5589. } else {
  5590. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5591. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  5592. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  5593. putop(c, OP_PUSHLENDELIM);
  5594. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  5595. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  5596. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  5597. putop(c, OP_POP);
  5598. putop(c, OP_SETDELIM);
  5599. }
  5600. }
  5601. /* Generates bytecode to parse a single primitive field. */
  5602. static void generate_primitivefield(compiler *c, const upb_fielddef *f,
  5603. upb_pbdecodermethod *method) {
  5604. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  5605. upb_descriptortype_t descriptor_type = upb_fielddef_descriptortype(f);
  5606. opcode parse_type;
  5607. upb_selector_t sel;
  5608. int wire_type;
  5609. label(c, LABEL_FIELD);
  5610. /* From a decoding perspective, ENUM is the same as INT32. */
  5611. if (descriptor_type == UPB_DESCRIPTOR_TYPE_ENUM)
  5612. descriptor_type = UPB_DESCRIPTOR_TYPE_INT32;
  5613. parse_type = (opcode)descriptor_type;
  5614. /* TODO(haberman): generate packed or non-packed first depending on "packed"
  5615. * setting in the fielddef. This will favor (in speed) whichever was
  5616. * specified. */
  5617. UPB_ASSERT((int)parse_type >= 0 && parse_type <= OP_MAX);
  5618. sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  5619. wire_type = upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  5620. if (upb_fielddef_isseq(f)) {
  5621. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5622. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  5623. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  5624. putop(c, OP_PUSHLENDELIM);
  5625. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); /* Packed */
  5626. label(c, LABEL_LOOPSTART);
  5627. putop(c, parse_type, sel);
  5628. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5629. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5630. dispatchtarget(c, method, f, wire_type);
  5631. putop(c, OP_PUSHTAGDELIM, 0);
  5632. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); /* Non-packed */
  5633. label(c, LABEL_LOOPSTART);
  5634. putop(c, parse_type, sel);
  5635. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5636. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  5637. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5638. label(c, LABEL_LOOPBREAK);
  5639. putop(c, OP_POP); /* Packed and non-packed join. */
  5640. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  5641. putop(c, OP_SETDELIM); /* Could remove for non-packed by dup ENDSEQ. */
  5642. } else {
  5643. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5644. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  5645. dispatchtarget(c, method, f, wire_type);
  5646. putop(c, parse_type, sel);
  5647. }
  5648. }
  5649. /* Adds bytecode for parsing the given message to the given decoderplan,
  5650. * while adding all dispatch targets to this message's dispatch table. */
  5651. static void compile_method(compiler *c, upb_pbdecodermethod *method) {
  5652. const upb_handlers *h;
  5653. const upb_msgdef *md;
  5654. uint32_t* start_pc;
  5655. upb_msg_field_iter i;
  5656. upb_value val;
  5657. UPB_ASSERT(method);
  5658. /* Clear all entries in the dispatch table. */
  5659. upb_inttable_uninit(&method->dispatch);
  5660. upb_inttable_init(&method->dispatch, UPB_CTYPE_UINT64);
  5661. h = upb_pbdecodermethod_desthandlers(method);
  5662. md = upb_handlers_msgdef(h);
  5663. method->code_base.ofs = pcofs(c);
  5664. putop(c, OP_SETDISPATCH, &method->dispatch);
  5665. putsel(c, OP_STARTMSG, UPB_STARTMSG_SELECTOR, h);
  5666. label(c, LABEL_FIELD);
  5667. start_pc = c->pc;
  5668. for(upb_msg_field_begin(&i, md);
  5669. !upb_msg_field_done(&i);
  5670. upb_msg_field_next(&i)) {
  5671. const upb_fielddef *f = upb_msg_iter_field(&i);
  5672. upb_fieldtype_t type = upb_fielddef_type(f);
  5673. if (type == UPB_TYPE_MESSAGE && !(haslazyhandlers(h, f) && c->lazy)) {
  5674. generate_msgfield(c, f, method);
  5675. } else if (type == UPB_TYPE_STRING || type == UPB_TYPE_BYTES ||
  5676. type == UPB_TYPE_MESSAGE) {
  5677. generate_delimfield(c, f, method);
  5678. } else {
  5679. generate_primitivefield(c, f, method);
  5680. }
  5681. }
  5682. /* If there were no fields, or if no handlers were defined, we need to
  5683. * generate a non-empty loop body so that we can at least dispatch for unknown
  5684. * fields and check for the end of the message. */
  5685. if (c->pc == start_pc) {
  5686. /* Check for end-of-message. */
  5687. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5688. /* Unconditionally dispatch. */
  5689. putop(c, OP_DISPATCH, 0);
  5690. }
  5691. /* For now we just loop back to the last field of the message (or if none,
  5692. * the DISPATCH opcode for the message). */
  5693. putop(c, OP_BRANCH, -LABEL_FIELD);
  5694. /* Insert both a label and a dispatch table entry for this end-of-msg. */
  5695. label(c, LABEL_ENDMSG);
  5696. val = upb_value_uint64(pcofs(c) - method->code_base.ofs);
  5697. upb_inttable_insert(&method->dispatch, DISPATCH_ENDMSG, val);
  5698. putsel(c, OP_ENDMSG, UPB_ENDMSG_SELECTOR, h);
  5699. putop(c, OP_RET);
  5700. upb_inttable_compact(&method->dispatch);
  5701. }
  5702. /* Populate "methods" with new upb_pbdecodermethod objects reachable from "h".
  5703. * Returns the method for these handlers.
  5704. *
  5705. * Generates a new method for every destination handlers reachable from "h". */
  5706. static void find_methods(compiler *c, const upb_handlers *h) {
  5707. upb_value v;
  5708. upb_msg_field_iter i;
  5709. const upb_msgdef *md;
  5710. upb_pbdecodermethod *method;
  5711. if (upb_inttable_lookupptr(&c->group->methods, h, &v))
  5712. return;
  5713. method = newmethod(h, c->group);
  5714. upb_inttable_insertptr(&c->group->methods, h, upb_value_ptr(method));
  5715. /* Find submethods. */
  5716. md = upb_handlers_msgdef(h);
  5717. for(upb_msg_field_begin(&i, md);
  5718. !upb_msg_field_done(&i);
  5719. upb_msg_field_next(&i)) {
  5720. const upb_fielddef *f = upb_msg_iter_field(&i);
  5721. const upb_handlers *sub_h;
  5722. if (upb_fielddef_type(f) == UPB_TYPE_MESSAGE &&
  5723. (sub_h = upb_handlers_getsubhandlers(h, f)) != NULL) {
  5724. /* We only generate a decoder method for submessages with handlers.
  5725. * Others will be parsed as unknown fields. */
  5726. find_methods(c, sub_h);
  5727. }
  5728. }
  5729. }
  5730. /* (Re-)compile bytecode for all messages in "msgs."
  5731. * Overwrites any existing bytecode in "c". */
  5732. static void compile_methods(compiler *c) {
  5733. upb_inttable_iter i;
  5734. /* Start over at the beginning of the bytecode. */
  5735. c->pc = c->group->bytecode;
  5736. upb_inttable_begin(&i, &c->group->methods);
  5737. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5738. upb_pbdecodermethod *method = upb_value_getptr(upb_inttable_iter_value(&i));
  5739. compile_method(c, method);
  5740. }
  5741. }
  5742. static void set_bytecode_handlers(mgroup *g) {
  5743. upb_inttable_iter i;
  5744. upb_inttable_begin(&i, &g->methods);
  5745. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5746. upb_pbdecodermethod *m = upb_value_getptr(upb_inttable_iter_value(&i));
  5747. upb_byteshandler *h = &m->input_handler_;
  5748. m->code_base.ptr = g->bytecode + m->code_base.ofs;
  5749. upb_byteshandler_setstartstr(h, upb_pbdecoder_startbc, m->code_base.ptr);
  5750. upb_byteshandler_setstring(h, upb_pbdecoder_decode, g);
  5751. upb_byteshandler_setendstr(h, upb_pbdecoder_end, m);
  5752. }
  5753. }
  5754. /* TODO(haberman): allow this to be constructed for an arbitrary set of dest
  5755. * handlers and other mgroups (but verify we have a transitive closure). */
  5756. const mgroup *mgroup_new(const upb_handlers *dest, bool lazy) {
  5757. mgroup *g;
  5758. compiler *c;
  5759. g = newgroup();
  5760. c = newcompiler(g, lazy);
  5761. find_methods(c, dest);
  5762. /* We compile in two passes:
  5763. * 1. all messages are assigned relative offsets from the beginning of the
  5764. * bytecode (saved in method->code_base).
  5765. * 2. forwards OP_CALL instructions can be correctly linked since message
  5766. * offsets have been previously assigned.
  5767. *
  5768. * Could avoid the second pass by linking OP_CALL instructions somehow. */
  5769. compile_methods(c);
  5770. compile_methods(c);
  5771. g->bytecode_end = c->pc;
  5772. freecompiler(c);
  5773. #ifdef UPB_DUMP_BYTECODE
  5774. {
  5775. FILE *f = fopen("/tmp/upb-bytecode", "w");
  5776. UPB_ASSERT(f);
  5777. dumpbc(g->bytecode, g->bytecode_end, stderr);
  5778. dumpbc(g->bytecode, g->bytecode_end, f);
  5779. fclose(f);
  5780. f = fopen("/tmp/upb-bytecode.bin", "wb");
  5781. UPB_ASSERT(f);
  5782. fwrite(g->bytecode, 1, g->bytecode_end - g->bytecode, f);
  5783. fclose(f);
  5784. }
  5785. #endif
  5786. set_bytecode_handlers(g);
  5787. return g;
  5788. }
  5789. /* upb_pbcodecache ************************************************************/
  5790. upb_pbcodecache *upb_pbcodecache_new(upb_handlercache *dest) {
  5791. upb_pbcodecache *c = upb_gmalloc(sizeof(*c));
  5792. if (!c) return NULL;
  5793. c->dest = dest;
  5794. c->lazy = false;
  5795. c->arena = upb_arena_new();
  5796. if (!upb_inttable_init(&c->groups, UPB_CTYPE_CONSTPTR)) return NULL;
  5797. return c;
  5798. }
  5799. void upb_pbcodecache_free(upb_pbcodecache *c) {
  5800. upb_inttable_iter i;
  5801. upb_inttable_begin(&i, &c->groups);
  5802. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5803. upb_value val = upb_inttable_iter_value(&i);
  5804. freegroup((void*)upb_value_getconstptr(val));
  5805. }
  5806. upb_inttable_uninit(&c->groups);
  5807. upb_arena_free(c->arena);
  5808. upb_gfree(c);
  5809. }
  5810. void upb_pbdecodermethodopts_setlazy(upb_pbcodecache *c, bool lazy) {
  5811. UPB_ASSERT(upb_inttable_count(&c->groups) == 0);
  5812. c->lazy = lazy;
  5813. }
  5814. const upb_pbdecodermethod *upb_pbcodecache_get(upb_pbcodecache *c,
  5815. const upb_msgdef *md) {
  5816. upb_value v;
  5817. bool ok;
  5818. const upb_handlers *h;
  5819. const mgroup *g;
  5820. h = upb_handlercache_get(c->dest, md);
  5821. if (upb_inttable_lookupptr(&c->groups, md, &v)) {
  5822. g = upb_value_getconstptr(v);
  5823. } else {
  5824. g = mgroup_new(h, c->lazy);
  5825. ok = upb_inttable_insertptr(&c->groups, md, upb_value_constptr(g));
  5826. UPB_ASSUME(ok);
  5827. }
  5828. ok = upb_inttable_lookupptr(&g->methods, h, &v);
  5829. UPB_ASSUME(ok);
  5830. return upb_value_getptr(v);
  5831. }
  5832. /*
  5833. ** upb::Decoder (Bytecode Decoder VM)
  5834. **
  5835. ** Bytecode must previously have been generated using the bytecode compiler in
  5836. ** compile_decoder.c. This decoder then walks through the bytecode op-by-op to
  5837. ** parse the input.
  5838. **
  5839. ** Decoding is fully resumable; we just keep a pointer to the current bytecode
  5840. ** instruction and resume from there. A fair amount of the logic here is to
  5841. ** handle the fact that values can span buffer seams and we have to be able to
  5842. ** be capable of suspending/resuming from any byte in the stream. This
  5843. ** sometimes requires keeping a few trailing bytes from the last buffer around
  5844. ** in the "residual" buffer.
  5845. */
  5846. #include <inttypes.h>
  5847. #include <stddef.h>
  5848. #ifdef UPB_DUMP_BYTECODE
  5849. #include <stdio.h>
  5850. #endif
  5851. #define CHECK_SUSPEND(x) if (!(x)) return upb_pbdecoder_suspend(d);
  5852. /* Error messages that are shared between the bytecode and JIT decoders. */
  5853. const char *kPbDecoderStackOverflow = "Nesting too deep.";
  5854. const char *kPbDecoderSubmessageTooLong =
  5855. "Submessage end extends past enclosing submessage.";
  5856. /* Error messages shared within this file. */
  5857. static const char *kUnterminatedVarint = "Unterminated varint.";
  5858. /* upb_pbdecoder **************************************************************/
  5859. static opcode halt = OP_HALT;
  5860. /* A dummy character we can point to when the user passes us a NULL buffer.
  5861. * We need this because in C (NULL + 0) and (NULL - NULL) are undefined
  5862. * behavior, which would invalidate functions like curbufleft(). */
  5863. static const char dummy_char;
  5864. /* Whether an op consumes any of the input buffer. */
  5865. static bool consumes_input(opcode op) {
  5866. switch (op) {
  5867. case OP_SETDISPATCH:
  5868. case OP_STARTMSG:
  5869. case OP_ENDMSG:
  5870. case OP_STARTSEQ:
  5871. case OP_ENDSEQ:
  5872. case OP_STARTSUBMSG:
  5873. case OP_ENDSUBMSG:
  5874. case OP_STARTSTR:
  5875. case OP_ENDSTR:
  5876. case OP_PUSHTAGDELIM:
  5877. case OP_POP:
  5878. case OP_SETDELIM:
  5879. case OP_SETBIGGROUPNUM:
  5880. case OP_CHECKDELIM:
  5881. case OP_CALL:
  5882. case OP_RET:
  5883. case OP_BRANCH:
  5884. return false;
  5885. default:
  5886. return true;
  5887. }
  5888. }
  5889. static size_t stacksize(upb_pbdecoder *d, size_t entries) {
  5890. UPB_UNUSED(d);
  5891. return entries * sizeof(upb_pbdecoder_frame);
  5892. }
  5893. static size_t callstacksize(upb_pbdecoder *d, size_t entries) {
  5894. UPB_UNUSED(d);
  5895. return entries * sizeof(uint32_t*);
  5896. }
  5897. static bool in_residual_buf(const upb_pbdecoder *d, const char *p);
  5898. /* It's unfortunate that we have to micro-manage the compiler with
  5899. * UPB_FORCEINLINE and UPB_NOINLINE, especially since this tuning is necessarily
  5900. * specific to one hardware configuration. But empirically on a Core i7,
  5901. * performance increases 30-50% with these annotations. Every instance where
  5902. * these appear, gcc 4.2.1 made the wrong decision and degraded performance in
  5903. * benchmarks. */
  5904. static void seterr(upb_pbdecoder *d, const char *msg) {
  5905. upb_status_seterrmsg(d->status, msg);
  5906. }
  5907. void upb_pbdecoder_seterr(upb_pbdecoder *d, const char *msg) {
  5908. seterr(d, msg);
  5909. }
  5910. /* Buffering ******************************************************************/
  5911. /* We operate on one buffer at a time, which is either the user's buffer passed
  5912. * to our "decode" callback or some residual bytes from the previous buffer. */
  5913. /* How many bytes can be safely read from d->ptr without reading past end-of-buf
  5914. * or past the current delimited end. */
  5915. static size_t curbufleft(const upb_pbdecoder *d) {
  5916. UPB_ASSERT(d->data_end >= d->ptr);
  5917. return d->data_end - d->ptr;
  5918. }
  5919. /* How many bytes are available before end-of-buffer. */
  5920. static size_t bufleft(const upb_pbdecoder *d) {
  5921. return d->end - d->ptr;
  5922. }
  5923. /* Overall stream offset of d->ptr. */
  5924. uint64_t offset(const upb_pbdecoder *d) {
  5925. return d->bufstart_ofs + (d->ptr - d->buf);
  5926. }
  5927. /* How many bytes are available before the end of this delimited region. */
  5928. size_t delim_remaining(const upb_pbdecoder *d) {
  5929. return d->top->end_ofs - offset(d);
  5930. }
  5931. /* Advances d->ptr. */
  5932. static void advance(upb_pbdecoder *d, size_t len) {
  5933. UPB_ASSERT(curbufleft(d) >= len);
  5934. d->ptr += len;
  5935. }
  5936. static bool in_buf(const char *p, const char *buf, const char *end) {
  5937. return p >= buf && p <= end;
  5938. }
  5939. static bool in_residual_buf(const upb_pbdecoder *d, const char *p) {
  5940. return in_buf(p, d->residual, d->residual_end);
  5941. }
  5942. /* Calculates the delim_end value, which is affected by both the current buffer
  5943. * and the parsing stack, so must be called whenever either is updated. */
  5944. static void set_delim_end(upb_pbdecoder *d) {
  5945. size_t delim_ofs = d->top->end_ofs - d->bufstart_ofs;
  5946. if (delim_ofs <= (size_t)(d->end - d->buf)) {
  5947. d->delim_end = d->buf + delim_ofs;
  5948. d->data_end = d->delim_end;
  5949. } else {
  5950. d->data_end = d->end;
  5951. d->delim_end = NULL;
  5952. }
  5953. }
  5954. static void switchtobuf(upb_pbdecoder *d, const char *buf, const char *end) {
  5955. d->ptr = buf;
  5956. d->buf = buf;
  5957. d->end = end;
  5958. set_delim_end(d);
  5959. }
  5960. static void advancetobuf(upb_pbdecoder *d, const char *buf, size_t len) {
  5961. UPB_ASSERT(curbufleft(d) == 0);
  5962. d->bufstart_ofs += (d->end - d->buf);
  5963. switchtobuf(d, buf, buf + len);
  5964. }
  5965. static void checkpoint(upb_pbdecoder *d) {
  5966. /* The assertion here is in the interests of efficiency, not correctness.
  5967. * We are trying to ensure that we don't checkpoint() more often than
  5968. * necessary. */
  5969. UPB_ASSERT(d->checkpoint != d->ptr);
  5970. d->checkpoint = d->ptr;
  5971. }
  5972. /* Skips "bytes" bytes in the stream, which may be more than available. If we
  5973. * skip more bytes than are available, we return a long read count to the caller
  5974. * indicating how many bytes can be skipped over before passing actual data
  5975. * again. Skipped bytes can pass a NULL buffer and the decoder guarantees they
  5976. * won't actually be read.
  5977. */
  5978. static int32_t skip(upb_pbdecoder *d, size_t bytes) {
  5979. UPB_ASSERT(!in_residual_buf(d, d->ptr) || d->size_param == 0);
  5980. UPB_ASSERT(d->skip == 0);
  5981. if (bytes > delim_remaining(d)) {
  5982. seterr(d, "Skipped value extended beyond enclosing submessage.");
  5983. return (int32_t)upb_pbdecoder_suspend(d);
  5984. } else if (bufleft(d) >= bytes) {
  5985. /* Skipped data is all in current buffer, and more is still available. */
  5986. advance(d, bytes);
  5987. d->skip = 0;
  5988. return DECODE_OK;
  5989. } else {
  5990. /* Skipped data extends beyond currently available buffers. */
  5991. d->pc = d->last;
  5992. d->skip = bytes - curbufleft(d);
  5993. d->bufstart_ofs += (d->end - d->buf);
  5994. d->residual_end = d->residual;
  5995. switchtobuf(d, d->residual, d->residual_end);
  5996. return (int32_t)(d->size_param + d->skip);
  5997. }
  5998. }
  5999. /* Resumes the decoder from an initial state or from a previous suspend. */
  6000. int32_t upb_pbdecoder_resume(upb_pbdecoder *d, void *p, const char *buf,
  6001. size_t size, const upb_bufhandle *handle) {
  6002. UPB_UNUSED(p); /* Useless; just for the benefit of the JIT. */
  6003. /* d->skip and d->residual_end could probably elegantly be represented
  6004. * as a single variable, to more easily represent this invariant. */
  6005. UPB_ASSERT(!(d->skip && d->residual_end > d->residual));
  6006. /* We need to remember the original size_param, so that the value we return
  6007. * is relative to it, even if we do some skipping first. */
  6008. d->size_param = size;
  6009. d->handle = handle;
  6010. /* Have to handle this case specially (ie. not with skip()) because the user
  6011. * is allowed to pass a NULL buffer here, which won't allow us to safely
  6012. * calculate a d->end or use our normal functions like curbufleft(). */
  6013. if (d->skip && d->skip >= size) {
  6014. d->skip -= size;
  6015. d->bufstart_ofs += size;
  6016. buf = &dummy_char;
  6017. size = 0;
  6018. /* We can't just return now, because we might need to execute some ops
  6019. * like CHECKDELIM, which could call some callbacks and pop the stack. */
  6020. }
  6021. /* We need to pretend that this was the actual buffer param, since some of the
  6022. * calculations assume that d->ptr/d->buf is relative to this. */
  6023. d->buf_param = buf;
  6024. if (!buf) {
  6025. /* NULL buf is ok if its entire span is covered by the "skip" above, but
  6026. * by this point we know that "skip" doesn't cover the buffer. */
  6027. seterr(d, "Passed NULL buffer over non-skippable region.");
  6028. return (int32_t)upb_pbdecoder_suspend(d);
  6029. }
  6030. if (d->residual_end > d->residual) {
  6031. /* We have residual bytes from the last buffer. */
  6032. UPB_ASSERT(d->ptr == d->residual);
  6033. } else {
  6034. switchtobuf(d, buf, buf + size);
  6035. }
  6036. d->checkpoint = d->ptr;
  6037. /* Handle skips that don't cover the whole buffer (as above). */
  6038. if (d->skip) {
  6039. size_t skip_bytes = d->skip;
  6040. d->skip = 0;
  6041. CHECK_RETURN(skip(d, skip_bytes));
  6042. checkpoint(d);
  6043. }
  6044. /* If we're inside an unknown group, continue to parse unknown values. */
  6045. if (d->top->groupnum < 0) {
  6046. CHECK_RETURN(upb_pbdecoder_skipunknown(d, -1, 0));
  6047. checkpoint(d);
  6048. }
  6049. return DECODE_OK;
  6050. }
  6051. /* Suspends the decoder at the last checkpoint, without saving any residual
  6052. * bytes. If there are any unconsumed bytes, returns a short byte count. */
  6053. size_t upb_pbdecoder_suspend(upb_pbdecoder *d) {
  6054. d->pc = d->last;
  6055. if (d->checkpoint == d->residual) {
  6056. /* Checkpoint was in residual buf; no user bytes were consumed. */
  6057. d->ptr = d->residual;
  6058. return 0;
  6059. } else {
  6060. size_t ret = d->size_param - (d->end - d->checkpoint);
  6061. UPB_ASSERT(!in_residual_buf(d, d->checkpoint));
  6062. UPB_ASSERT(d->buf == d->buf_param || d->buf == &dummy_char);
  6063. d->bufstart_ofs += (d->checkpoint - d->buf);
  6064. d->residual_end = d->residual;
  6065. switchtobuf(d, d->residual, d->residual_end);
  6066. return ret;
  6067. }
  6068. }
  6069. /* Suspends the decoder at the last checkpoint, and saves any unconsumed
  6070. * bytes in our residual buffer. This is necessary if we need more user
  6071. * bytes to form a complete value, which might not be contiguous in the
  6072. * user's buffers. Always consumes all user bytes. */
  6073. static size_t suspend_save(upb_pbdecoder *d) {
  6074. /* We hit end-of-buffer before we could parse a full value.
  6075. * Save any unconsumed bytes (if any) to the residual buffer. */
  6076. d->pc = d->last;
  6077. if (d->checkpoint == d->residual) {
  6078. /* Checkpoint was in residual buf; append user byte(s) to residual buf. */
  6079. UPB_ASSERT((d->residual_end - d->residual) + d->size_param <=
  6080. sizeof(d->residual));
  6081. if (!in_residual_buf(d, d->ptr)) {
  6082. d->bufstart_ofs -= (d->residual_end - d->residual);
  6083. }
  6084. memcpy(d->residual_end, d->buf_param, d->size_param);
  6085. d->residual_end += d->size_param;
  6086. } else {
  6087. /* Checkpoint was in user buf; old residual bytes not needed. */
  6088. size_t save;
  6089. UPB_ASSERT(!in_residual_buf(d, d->checkpoint));
  6090. d->ptr = d->checkpoint;
  6091. save = curbufleft(d);
  6092. UPB_ASSERT(save <= sizeof(d->residual));
  6093. memcpy(d->residual, d->ptr, save);
  6094. d->residual_end = d->residual + save;
  6095. d->bufstart_ofs = offset(d);
  6096. }
  6097. switchtobuf(d, d->residual, d->residual_end);
  6098. return d->size_param;
  6099. }
  6100. /* Copies the next "bytes" bytes into "buf" and advances the stream.
  6101. * Requires that this many bytes are available in the current buffer. */
  6102. UPB_FORCEINLINE static void consumebytes(upb_pbdecoder *d, void *buf,
  6103. size_t bytes) {
  6104. UPB_ASSERT(bytes <= curbufleft(d));
  6105. memcpy(buf, d->ptr, bytes);
  6106. advance(d, bytes);
  6107. }
  6108. /* Slow path for getting the next "bytes" bytes, regardless of whether they are
  6109. * available in the current buffer or not. Returns a status code as described
  6110. * in decoder.int.h. */
  6111. UPB_NOINLINE static int32_t getbytes_slow(upb_pbdecoder *d, void *buf,
  6112. size_t bytes) {
  6113. const size_t avail = curbufleft(d);
  6114. consumebytes(d, buf, avail);
  6115. bytes -= avail;
  6116. UPB_ASSERT(bytes > 0);
  6117. if (in_residual_buf(d, d->ptr)) {
  6118. advancetobuf(d, d->buf_param, d->size_param);
  6119. }
  6120. if (curbufleft(d) >= bytes) {
  6121. consumebytes(d, (char *)buf + avail, bytes);
  6122. return DECODE_OK;
  6123. } else if (d->data_end == d->delim_end) {
  6124. seterr(d, "Submessage ended in the middle of a value or group");
  6125. return (int32_t)upb_pbdecoder_suspend(d);
  6126. } else {
  6127. return (int32_t)suspend_save(d);
  6128. }
  6129. }
  6130. /* Gets the next "bytes" bytes, regardless of whether they are available in the
  6131. * current buffer or not. Returns a status code as described in decoder.int.h.
  6132. */
  6133. UPB_FORCEINLINE static int32_t getbytes(upb_pbdecoder *d, void *buf,
  6134. size_t bytes) {
  6135. if (curbufleft(d) >= bytes) {
  6136. /* Buffer has enough data to satisfy. */
  6137. consumebytes(d, buf, bytes);
  6138. return DECODE_OK;
  6139. } else {
  6140. return getbytes_slow(d, buf, bytes);
  6141. }
  6142. }
  6143. UPB_NOINLINE static size_t peekbytes_slow(upb_pbdecoder *d, void *buf,
  6144. size_t bytes) {
  6145. size_t ret = curbufleft(d);
  6146. memcpy(buf, d->ptr, ret);
  6147. if (in_residual_buf(d, d->ptr)) {
  6148. size_t copy = UPB_MIN(bytes - ret, d->size_param);
  6149. memcpy((char *)buf + ret, d->buf_param, copy);
  6150. ret += copy;
  6151. }
  6152. return ret;
  6153. }
  6154. UPB_FORCEINLINE static size_t peekbytes(upb_pbdecoder *d, void *buf,
  6155. size_t bytes) {
  6156. if (curbufleft(d) >= bytes) {
  6157. memcpy(buf, d->ptr, bytes);
  6158. return bytes;
  6159. } else {
  6160. return peekbytes_slow(d, buf, bytes);
  6161. }
  6162. }
  6163. /* Decoding of wire types *****************************************************/
  6164. /* Slow path for decoding a varint from the current buffer position.
  6165. * Returns a status code as described in decoder.int.h. */
  6166. UPB_NOINLINE int32_t upb_pbdecoder_decode_varint_slow(upb_pbdecoder *d,
  6167. uint64_t *u64) {
  6168. uint8_t byte = 0x80;
  6169. int bitpos;
  6170. *u64 = 0;
  6171. for(bitpos = 0; bitpos < 70 && (byte & 0x80); bitpos += 7) {
  6172. CHECK_RETURN(getbytes(d, &byte, 1));
  6173. *u64 |= (uint64_t)(byte & 0x7F) << bitpos;
  6174. }
  6175. if(bitpos == 70 && (byte & 0x80)) {
  6176. seterr(d, kUnterminatedVarint);
  6177. return (int32_t)upb_pbdecoder_suspend(d);
  6178. }
  6179. return DECODE_OK;
  6180. }
  6181. /* Decodes a varint from the current buffer position.
  6182. * Returns a status code as described in decoder.int.h. */
  6183. UPB_FORCEINLINE static int32_t decode_varint(upb_pbdecoder *d, uint64_t *u64) {
  6184. if (curbufleft(d) > 0 && !(*d->ptr & 0x80)) {
  6185. *u64 = *d->ptr;
  6186. advance(d, 1);
  6187. return DECODE_OK;
  6188. } else if (curbufleft(d) >= 10) {
  6189. /* Fast case. */
  6190. upb_decoderet r = upb_vdecode_fast(d->ptr);
  6191. if (r.p == NULL) {
  6192. seterr(d, kUnterminatedVarint);
  6193. return (int32_t)upb_pbdecoder_suspend(d);
  6194. }
  6195. advance(d, r.p - d->ptr);
  6196. *u64 = r.val;
  6197. return DECODE_OK;
  6198. } else {
  6199. /* Slow case -- varint spans buffer seam. */
  6200. return upb_pbdecoder_decode_varint_slow(d, u64);
  6201. }
  6202. }
  6203. /* Decodes a 32-bit varint from the current buffer position.
  6204. * Returns a status code as described in decoder.int.h. */
  6205. UPB_FORCEINLINE static int32_t decode_v32(upb_pbdecoder *d, uint32_t *u32) {
  6206. uint64_t u64;
  6207. int32_t ret = decode_varint(d, &u64);
  6208. if (ret >= 0) return ret;
  6209. if (u64 > UINT32_MAX) {
  6210. seterr(d, "Unterminated 32-bit varint");
  6211. /* TODO(haberman) guarantee that this function return is >= 0 somehow,
  6212. * so we know this path will always be treated as error by our caller.
  6213. * Right now the size_t -> int32_t can overflow and produce negative values.
  6214. */
  6215. *u32 = 0;
  6216. return (int32_t)upb_pbdecoder_suspend(d);
  6217. }
  6218. *u32 = (uint32_t)u64;
  6219. return DECODE_OK;
  6220. }
  6221. /* Decodes a fixed32 from the current buffer position.
  6222. * Returns a status code as described in decoder.int.h.
  6223. * TODO: proper byte swapping for big-endian machines. */
  6224. UPB_FORCEINLINE static int32_t decode_fixed32(upb_pbdecoder *d, uint32_t *u32) {
  6225. return getbytes(d, u32, 4);
  6226. }
  6227. /* Decodes a fixed64 from the current buffer position.
  6228. * Returns a status code as described in decoder.int.h.
  6229. * TODO: proper byte swapping for big-endian machines. */
  6230. UPB_FORCEINLINE static int32_t decode_fixed64(upb_pbdecoder *d, uint64_t *u64) {
  6231. return getbytes(d, u64, 8);
  6232. }
  6233. /* Non-static versions of the above functions.
  6234. * These are called by the JIT for fallback paths. */
  6235. int32_t upb_pbdecoder_decode_f32(upb_pbdecoder *d, uint32_t *u32) {
  6236. return decode_fixed32(d, u32);
  6237. }
  6238. int32_t upb_pbdecoder_decode_f64(upb_pbdecoder *d, uint64_t *u64) {
  6239. return decode_fixed64(d, u64);
  6240. }
  6241. static double as_double(uint64_t n) { double d; memcpy(&d, &n, 8); return d; }
  6242. static float as_float(uint32_t n) { float f; memcpy(&f, &n, 4); return f; }
  6243. /* Pushes a frame onto the decoder stack. */
  6244. static bool decoder_push(upb_pbdecoder *d, uint64_t end) {
  6245. upb_pbdecoder_frame *fr = d->top;
  6246. if (end > fr->end_ofs) {
  6247. seterr(d, kPbDecoderSubmessageTooLong);
  6248. return false;
  6249. } else if (fr == d->limit) {
  6250. seterr(d, kPbDecoderStackOverflow);
  6251. return false;
  6252. }
  6253. fr++;
  6254. fr->end_ofs = end;
  6255. fr->dispatch = NULL;
  6256. fr->groupnum = 0;
  6257. d->top = fr;
  6258. return true;
  6259. }
  6260. static bool pushtagdelim(upb_pbdecoder *d, uint32_t arg) {
  6261. /* While we expect to see an "end" tag (either ENDGROUP or a non-sequence
  6262. * field number) prior to hitting any enclosing submessage end, pushing our
  6263. * existing delim end prevents us from continuing to parse values from a
  6264. * corrupt proto that doesn't give us an END tag in time. */
  6265. if (!decoder_push(d, d->top->end_ofs))
  6266. return false;
  6267. d->top->groupnum = arg;
  6268. return true;
  6269. }
  6270. /* Pops a frame from the decoder stack. */
  6271. static void decoder_pop(upb_pbdecoder *d) { d->top--; }
  6272. UPB_NOINLINE int32_t upb_pbdecoder_checktag_slow(upb_pbdecoder *d,
  6273. uint64_t expected) {
  6274. uint64_t data = 0;
  6275. size_t bytes = upb_value_size(expected);
  6276. size_t read = peekbytes(d, &data, bytes);
  6277. if (read == bytes && data == expected) {
  6278. /* Advance past matched bytes. */
  6279. int32_t ok = getbytes(d, &data, read);
  6280. UPB_ASSERT(ok < 0);
  6281. return DECODE_OK;
  6282. } else if (read < bytes && memcmp(&data, &expected, read) == 0) {
  6283. return (int32_t)suspend_save(d);
  6284. } else {
  6285. return DECODE_MISMATCH;
  6286. }
  6287. }
  6288. int32_t upb_pbdecoder_skipunknown(upb_pbdecoder *d, int32_t fieldnum,
  6289. uint8_t wire_type) {
  6290. if (fieldnum >= 0)
  6291. goto have_tag;
  6292. while (true) {
  6293. uint32_t tag;
  6294. CHECK_RETURN(decode_v32(d, &tag));
  6295. wire_type = tag & 0x7;
  6296. fieldnum = tag >> 3;
  6297. have_tag:
  6298. if (fieldnum == 0) {
  6299. seterr(d, "Saw invalid field number (0)");
  6300. return (int32_t)upb_pbdecoder_suspend(d);
  6301. }
  6302. switch (wire_type) {
  6303. case UPB_WIRE_TYPE_32BIT:
  6304. CHECK_RETURN(skip(d, 4));
  6305. break;
  6306. case UPB_WIRE_TYPE_64BIT:
  6307. CHECK_RETURN(skip(d, 8));
  6308. break;
  6309. case UPB_WIRE_TYPE_VARINT: {
  6310. uint64_t u64;
  6311. CHECK_RETURN(decode_varint(d, &u64));
  6312. break;
  6313. }
  6314. case UPB_WIRE_TYPE_DELIMITED: {
  6315. uint32_t len;
  6316. CHECK_RETURN(decode_v32(d, &len));
  6317. CHECK_RETURN(skip(d, len));
  6318. break;
  6319. }
  6320. case UPB_WIRE_TYPE_START_GROUP:
  6321. if (!pushtagdelim(d, -fieldnum)) {
  6322. return (int32_t)upb_pbdecoder_suspend(d);
  6323. }
  6324. break;
  6325. case UPB_WIRE_TYPE_END_GROUP:
  6326. if (fieldnum == -d->top->groupnum) {
  6327. decoder_pop(d);
  6328. } else if (fieldnum == d->top->groupnum) {
  6329. return DECODE_ENDGROUP;
  6330. } else {
  6331. seterr(d, "Unmatched ENDGROUP tag.");
  6332. return (int32_t)upb_pbdecoder_suspend(d);
  6333. }
  6334. break;
  6335. default:
  6336. seterr(d, "Invalid wire type");
  6337. return (int32_t)upb_pbdecoder_suspend(d);
  6338. }
  6339. if (d->top->groupnum >= 0) {
  6340. /* TODO: More code needed for handling unknown groups. */
  6341. upb_sink_putunknown(d->top->sink, d->checkpoint, d->ptr - d->checkpoint);
  6342. return DECODE_OK;
  6343. }
  6344. /* Unknown group -- continue looping over unknown fields. */
  6345. checkpoint(d);
  6346. }
  6347. }
  6348. static void goto_endmsg(upb_pbdecoder *d) {
  6349. upb_value v;
  6350. bool found = upb_inttable_lookup32(d->top->dispatch, DISPATCH_ENDMSG, &v);
  6351. UPB_ASSERT(found);
  6352. d->pc = d->top->base + upb_value_getuint64(v);
  6353. }
  6354. /* Parses a tag and jumps to the corresponding bytecode instruction for this
  6355. * field.
  6356. *
  6357. * If the tag is unknown (or the wire type doesn't match), parses the field as
  6358. * unknown. If the tag is a valid ENDGROUP tag, jumps to the bytecode
  6359. * instruction for the end of message. */
  6360. static int32_t dispatch(upb_pbdecoder *d) {
  6361. upb_inttable *dispatch = d->top->dispatch;
  6362. uint32_t tag;
  6363. uint8_t wire_type;
  6364. uint32_t fieldnum;
  6365. upb_value val;
  6366. int32_t retval;
  6367. /* Decode tag. */
  6368. CHECK_RETURN(decode_v32(d, &tag));
  6369. wire_type = tag & 0x7;
  6370. fieldnum = tag >> 3;
  6371. /* Lookup tag. Because of packed/non-packed compatibility, we have to
  6372. * check the wire type against two possibilities. */
  6373. if (fieldnum != DISPATCH_ENDMSG &&
  6374. upb_inttable_lookup32(dispatch, fieldnum, &val)) {
  6375. uint64_t v = upb_value_getuint64(val);
  6376. if (wire_type == (v & 0xff)) {
  6377. d->pc = d->top->base + (v >> 16);
  6378. return DECODE_OK;
  6379. } else if (wire_type == ((v >> 8) & 0xff)) {
  6380. bool found =
  6381. upb_inttable_lookup(dispatch, fieldnum + UPB_MAX_FIELDNUMBER, &val);
  6382. UPB_ASSERT(found);
  6383. d->pc = d->top->base + upb_value_getuint64(val);
  6384. return DECODE_OK;
  6385. }
  6386. }
  6387. /* We have some unknown fields (or ENDGROUP) to parse. The DISPATCH or TAG
  6388. * bytecode that triggered this is preceded by a CHECKDELIM bytecode which
  6389. * we need to back up to, so that when we're done skipping unknown data we
  6390. * can re-check the delimited end. */
  6391. d->last--; /* Necessary if we get suspended */
  6392. d->pc = d->last;
  6393. UPB_ASSERT(getop(*d->last) == OP_CHECKDELIM);
  6394. /* Unknown field or ENDGROUP. */
  6395. retval = upb_pbdecoder_skipunknown(d, fieldnum, wire_type);
  6396. CHECK_RETURN(retval);
  6397. if (retval == DECODE_ENDGROUP) {
  6398. goto_endmsg(d);
  6399. return DECODE_OK;
  6400. }
  6401. return DECODE_OK;
  6402. }
  6403. /* Callers know that the stack is more than one deep because the opcodes that
  6404. * call this only occur after PUSH operations. */
  6405. upb_pbdecoder_frame *outer_frame(upb_pbdecoder *d) {
  6406. UPB_ASSERT(d->top != d->stack);
  6407. return d->top - 1;
  6408. }
  6409. /* The main decoding loop *****************************************************/
  6410. /* The main decoder VM function. Uses traditional bytecode dispatch loop with a
  6411. * switch() statement. */
  6412. size_t run_decoder_vm(upb_pbdecoder *d, const mgroup *group,
  6413. const upb_bufhandle* handle) {
  6414. #define VMCASE(op, code) \
  6415. case op: { code; if (consumes_input(op)) checkpoint(d); break; }
  6416. #define PRIMITIVE_OP(type, wt, name, convfunc, ctype) \
  6417. VMCASE(OP_PARSE_ ## type, { \
  6418. ctype val; \
  6419. CHECK_RETURN(decode_ ## wt(d, &val)); \
  6420. upb_sink_put ## name(d->top->sink, arg, (convfunc)(val)); \
  6421. })
  6422. while(1) {
  6423. int32_t instruction;
  6424. opcode op;
  6425. uint32_t arg;
  6426. int32_t longofs;
  6427. d->last = d->pc;
  6428. instruction = *d->pc++;
  6429. op = getop(instruction);
  6430. arg = instruction >> 8;
  6431. longofs = arg;
  6432. UPB_ASSERT(d->ptr != d->residual_end);
  6433. UPB_UNUSED(group);
  6434. #ifdef UPB_DUMP_BYTECODE
  6435. fprintf(stderr, "s_ofs=%d buf_ofs=%d data_rem=%d buf_rem=%d delim_rem=%d "
  6436. "%x %s (%d)\n",
  6437. (int)offset(d),
  6438. (int)(d->ptr - d->buf),
  6439. (int)(d->data_end - d->ptr),
  6440. (int)(d->end - d->ptr),
  6441. (int)((d->top->end_ofs - d->bufstart_ofs) - (d->ptr - d->buf)),
  6442. (int)(d->pc - 1 - group->bytecode),
  6443. upb_pbdecoder_getopname(op),
  6444. arg);
  6445. #endif
  6446. switch (op) {
  6447. /* Technically, we are losing data if we see a 32-bit varint that is not
  6448. * properly sign-extended. We could detect this and error about the data
  6449. * loss, but proto2 does not do this, so we pass. */
  6450. PRIMITIVE_OP(INT32, varint, int32, int32_t, uint64_t)
  6451. PRIMITIVE_OP(INT64, varint, int64, int64_t, uint64_t)
  6452. PRIMITIVE_OP(UINT32, varint, uint32, uint32_t, uint64_t)
  6453. PRIMITIVE_OP(UINT64, varint, uint64, uint64_t, uint64_t)
  6454. PRIMITIVE_OP(FIXED32, fixed32, uint32, uint32_t, uint32_t)
  6455. PRIMITIVE_OP(FIXED64, fixed64, uint64, uint64_t, uint64_t)
  6456. PRIMITIVE_OP(SFIXED32, fixed32, int32, int32_t, uint32_t)
  6457. PRIMITIVE_OP(SFIXED64, fixed64, int64, int64_t, uint64_t)
  6458. PRIMITIVE_OP(BOOL, varint, bool, bool, uint64_t)
  6459. PRIMITIVE_OP(DOUBLE, fixed64, double, as_double, uint64_t)
  6460. PRIMITIVE_OP(FLOAT, fixed32, float, as_float, uint32_t)
  6461. PRIMITIVE_OP(SINT32, varint, int32, upb_zzdec_32, uint64_t)
  6462. PRIMITIVE_OP(SINT64, varint, int64, upb_zzdec_64, uint64_t)
  6463. VMCASE(OP_SETDISPATCH,
  6464. d->top->base = d->pc - 1;
  6465. memcpy(&d->top->dispatch, d->pc, sizeof(void*));
  6466. d->pc += sizeof(void*) / sizeof(uint32_t);
  6467. )
  6468. VMCASE(OP_STARTMSG,
  6469. CHECK_SUSPEND(upb_sink_startmsg(d->top->sink));
  6470. )
  6471. VMCASE(OP_ENDMSG,
  6472. CHECK_SUSPEND(upb_sink_endmsg(d->top->sink, d->status));
  6473. )
  6474. VMCASE(OP_STARTSEQ,
  6475. upb_pbdecoder_frame *outer = outer_frame(d);
  6476. CHECK_SUSPEND(upb_sink_startseq(outer->sink, arg, &d->top->sink));
  6477. )
  6478. VMCASE(OP_ENDSEQ,
  6479. CHECK_SUSPEND(upb_sink_endseq(d->top->sink, arg));
  6480. )
  6481. VMCASE(OP_STARTSUBMSG,
  6482. upb_pbdecoder_frame *outer = outer_frame(d);
  6483. CHECK_SUSPEND(upb_sink_startsubmsg(outer->sink, arg, &d->top->sink));
  6484. )
  6485. VMCASE(OP_ENDSUBMSG,
  6486. upb_sink subsink = (d->top + 1)->sink;
  6487. CHECK_SUSPEND(upb_sink_endsubmsg(d->top->sink, subsink, arg));
  6488. )
  6489. VMCASE(OP_STARTSTR,
  6490. uint32_t len = (uint32_t)delim_remaining(d);
  6491. upb_pbdecoder_frame *outer = outer_frame(d);
  6492. CHECK_SUSPEND(upb_sink_startstr(outer->sink, arg, len, &d->top->sink));
  6493. if (len == 0) {
  6494. d->pc++; /* Skip OP_STRING. */
  6495. }
  6496. )
  6497. VMCASE(OP_STRING,
  6498. uint32_t len = (uint32_t)curbufleft(d);
  6499. size_t n = upb_sink_putstring(d->top->sink, arg, d->ptr, len, handle);
  6500. if (n > len) {
  6501. if (n > delim_remaining(d)) {
  6502. seterr(d, "Tried to skip past end of string.");
  6503. return upb_pbdecoder_suspend(d);
  6504. } else {
  6505. int32_t ret = skip(d, n);
  6506. /* This shouldn't return DECODE_OK, because n > len. */
  6507. UPB_ASSERT(ret >= 0);
  6508. return ret;
  6509. }
  6510. }
  6511. advance(d, n);
  6512. if (n < len || d->delim_end == NULL) {
  6513. /* We aren't finished with this string yet. */
  6514. d->pc--; /* Repeat OP_STRING. */
  6515. if (n > 0) checkpoint(d);
  6516. return upb_pbdecoder_suspend(d);
  6517. }
  6518. )
  6519. VMCASE(OP_ENDSTR,
  6520. CHECK_SUSPEND(upb_sink_endstr(d->top->sink, arg));
  6521. )
  6522. VMCASE(OP_PUSHTAGDELIM,
  6523. CHECK_SUSPEND(pushtagdelim(d, arg));
  6524. )
  6525. VMCASE(OP_SETBIGGROUPNUM,
  6526. d->top->groupnum = *d->pc++;
  6527. )
  6528. VMCASE(OP_POP,
  6529. UPB_ASSERT(d->top > d->stack);
  6530. decoder_pop(d);
  6531. )
  6532. VMCASE(OP_PUSHLENDELIM,
  6533. uint32_t len;
  6534. CHECK_RETURN(decode_v32(d, &len));
  6535. CHECK_SUSPEND(decoder_push(d, offset(d) + len));
  6536. set_delim_end(d);
  6537. )
  6538. VMCASE(OP_SETDELIM,
  6539. set_delim_end(d);
  6540. )
  6541. VMCASE(OP_CHECKDELIM,
  6542. /* We are guaranteed of this assert because we never allow ourselves to
  6543. * consume bytes beyond data_end, which covers delim_end when non-NULL.
  6544. */
  6545. UPB_ASSERT(!(d->delim_end && d->ptr > d->delim_end));
  6546. if (d->ptr == d->delim_end)
  6547. d->pc += longofs;
  6548. )
  6549. VMCASE(OP_CALL,
  6550. d->callstack[d->call_len++] = d->pc;
  6551. d->pc += longofs;
  6552. )
  6553. VMCASE(OP_RET,
  6554. UPB_ASSERT(d->call_len > 0);
  6555. d->pc = d->callstack[--d->call_len];
  6556. )
  6557. VMCASE(OP_BRANCH,
  6558. d->pc += longofs;
  6559. )
  6560. VMCASE(OP_TAG1,
  6561. uint8_t expected;
  6562. CHECK_SUSPEND(curbufleft(d) > 0);
  6563. expected = (arg >> 8) & 0xff;
  6564. if (*d->ptr == expected) {
  6565. advance(d, 1);
  6566. } else {
  6567. int8_t shortofs;
  6568. badtag:
  6569. shortofs = arg;
  6570. if (shortofs == LABEL_DISPATCH) {
  6571. CHECK_RETURN(dispatch(d));
  6572. } else {
  6573. d->pc += shortofs;
  6574. break; /* Avoid checkpoint(). */
  6575. }
  6576. }
  6577. )
  6578. VMCASE(OP_TAG2,
  6579. uint16_t expected;
  6580. CHECK_SUSPEND(curbufleft(d) > 0);
  6581. expected = (arg >> 8) & 0xffff;
  6582. if (curbufleft(d) >= 2) {
  6583. uint16_t actual;
  6584. memcpy(&actual, d->ptr, 2);
  6585. if (expected == actual) {
  6586. advance(d, 2);
  6587. } else {
  6588. goto badtag;
  6589. }
  6590. } else {
  6591. int32_t result = upb_pbdecoder_checktag_slow(d, expected);
  6592. if (result == DECODE_MISMATCH) goto badtag;
  6593. if (result >= 0) return result;
  6594. }
  6595. )
  6596. VMCASE(OP_TAGN, {
  6597. uint64_t expected;
  6598. int32_t result;
  6599. memcpy(&expected, d->pc, 8);
  6600. d->pc += 2;
  6601. result = upb_pbdecoder_checktag_slow(d, expected);
  6602. if (result == DECODE_MISMATCH) goto badtag;
  6603. if (result >= 0) return result;
  6604. })
  6605. VMCASE(OP_DISPATCH, {
  6606. CHECK_RETURN(dispatch(d));
  6607. })
  6608. VMCASE(OP_HALT, {
  6609. return d->size_param;
  6610. })
  6611. }
  6612. }
  6613. }
  6614. /* BytesHandler handlers ******************************************************/
  6615. void *upb_pbdecoder_startbc(void *closure, const void *pc, size_t size_hint) {
  6616. upb_pbdecoder *d = closure;
  6617. UPB_UNUSED(size_hint);
  6618. d->top->end_ofs = UINT64_MAX;
  6619. d->bufstart_ofs = 0;
  6620. d->call_len = 1;
  6621. d->callstack[0] = &halt;
  6622. d->pc = pc;
  6623. d->skip = 0;
  6624. return d;
  6625. }
  6626. bool upb_pbdecoder_end(void *closure, const void *handler_data) {
  6627. upb_pbdecoder *d = closure;
  6628. const upb_pbdecodermethod *method = handler_data;
  6629. uint64_t end;
  6630. char dummy;
  6631. if (d->residual_end > d->residual) {
  6632. seterr(d, "Unexpected EOF: decoder still has buffered unparsed data");
  6633. return false;
  6634. }
  6635. if (d->skip) {
  6636. seterr(d, "Unexpected EOF inside skipped data");
  6637. return false;
  6638. }
  6639. if (d->top->end_ofs != UINT64_MAX) {
  6640. seterr(d, "Unexpected EOF inside delimited string");
  6641. return false;
  6642. }
  6643. /* The user's end() call indicates that the message ends here. */
  6644. end = offset(d);
  6645. d->top->end_ofs = end;
  6646. {
  6647. const uint32_t *p = d->pc;
  6648. d->stack->end_ofs = end;
  6649. /* Check the previous bytecode, but guard against beginning. */
  6650. if (p != method->code_base.ptr) p--;
  6651. if (getop(*p) == OP_CHECKDELIM) {
  6652. /* Rewind from OP_TAG* to OP_CHECKDELIM. */
  6653. UPB_ASSERT(getop(*d->pc) == OP_TAG1 ||
  6654. getop(*d->pc) == OP_TAG2 ||
  6655. getop(*d->pc) == OP_TAGN ||
  6656. getop(*d->pc) == OP_DISPATCH);
  6657. d->pc = p;
  6658. }
  6659. upb_pbdecoder_decode(closure, handler_data, &dummy, 0, NULL);
  6660. }
  6661. if (d->call_len != 0) {
  6662. seterr(d, "Unexpected EOF inside submessage or group");
  6663. return false;
  6664. }
  6665. return true;
  6666. }
  6667. size_t upb_pbdecoder_decode(void *decoder, const void *group, const char *buf,
  6668. size_t size, const upb_bufhandle *handle) {
  6669. int32_t result = upb_pbdecoder_resume(decoder, NULL, buf, size, handle);
  6670. if (result == DECODE_ENDGROUP) goto_endmsg(decoder);
  6671. CHECK_RETURN(result);
  6672. return run_decoder_vm(decoder, group, handle);
  6673. }
  6674. /* Public API *****************************************************************/
  6675. void upb_pbdecoder_reset(upb_pbdecoder *d) {
  6676. d->top = d->stack;
  6677. d->top->groupnum = 0;
  6678. d->ptr = d->residual;
  6679. d->buf = d->residual;
  6680. d->end = d->residual;
  6681. d->residual_end = d->residual;
  6682. }
  6683. upb_pbdecoder *upb_pbdecoder_create(upb_arena *a, const upb_pbdecodermethod *m,
  6684. upb_sink sink, upb_status *status) {
  6685. const size_t default_max_nesting = 64;
  6686. #ifndef NDEBUG
  6687. size_t size_before = upb_arena_bytesallocated(a);
  6688. #endif
  6689. upb_pbdecoder *d = upb_arena_malloc(a, sizeof(upb_pbdecoder));
  6690. if (!d) return NULL;
  6691. d->method_ = m;
  6692. d->callstack = upb_arena_malloc(a, callstacksize(d, default_max_nesting));
  6693. d->stack = upb_arena_malloc(a, stacksize(d, default_max_nesting));
  6694. if (!d->stack || !d->callstack) {
  6695. return NULL;
  6696. }
  6697. d->arena = a;
  6698. d->limit = d->stack + default_max_nesting - 1;
  6699. d->stack_size = default_max_nesting;
  6700. d->status = status;
  6701. upb_pbdecoder_reset(d);
  6702. upb_bytessink_reset(&d->input_, &m->input_handler_, d);
  6703. if (d->method_->dest_handlers_) {
  6704. if (sink.handlers != d->method_->dest_handlers_)
  6705. return NULL;
  6706. }
  6707. d->top->sink = sink;
  6708. /* If this fails, increase the value in decoder.h. */
  6709. UPB_ASSERT_DEBUGVAR(upb_arena_bytesallocated(a) - size_before <=
  6710. UPB_PB_DECODER_SIZE);
  6711. return d;
  6712. }
  6713. uint64_t upb_pbdecoder_bytesparsed(const upb_pbdecoder *d) {
  6714. return offset(d);
  6715. }
  6716. const upb_pbdecodermethod *upb_pbdecoder_method(const upb_pbdecoder *d) {
  6717. return d->method_;
  6718. }
  6719. upb_bytessink upb_pbdecoder_input(upb_pbdecoder *d) {
  6720. return d->input_;
  6721. }
  6722. size_t upb_pbdecoder_maxnesting(const upb_pbdecoder *d) {
  6723. return d->stack_size;
  6724. }
  6725. bool upb_pbdecoder_setmaxnesting(upb_pbdecoder *d, size_t max) {
  6726. UPB_ASSERT(d->top >= d->stack);
  6727. if (max < (size_t)(d->top - d->stack)) {
  6728. /* Can't set a limit smaller than what we are currently at. */
  6729. return false;
  6730. }
  6731. if (max > d->stack_size) {
  6732. /* Need to reallocate stack and callstack to accommodate. */
  6733. size_t old_size = stacksize(d, d->stack_size);
  6734. size_t new_size = stacksize(d, max);
  6735. void *p = upb_arena_realloc(d->arena, d->stack, old_size, new_size);
  6736. if (!p) {
  6737. return false;
  6738. }
  6739. d->stack = p;
  6740. old_size = callstacksize(d, d->stack_size);
  6741. new_size = callstacksize(d, max);
  6742. p = upb_arena_realloc(d->arena, d->callstack, old_size, new_size);
  6743. if (!p) {
  6744. return false;
  6745. }
  6746. d->callstack = p;
  6747. d->stack_size = max;
  6748. }
  6749. d->limit = d->stack + max - 1;
  6750. return true;
  6751. }
  6752. /*
  6753. ** upb::Encoder
  6754. **
  6755. ** Since we are implementing pure handlers (ie. without any out-of-band access
  6756. ** to pre-computed lengths), we have to buffer all submessages before we can
  6757. ** emit even their first byte.
  6758. **
  6759. ** Not knowing the size of submessages also means we can't write a perfect
  6760. ** zero-copy implementation, even with buffering. Lengths are stored as
  6761. ** varints, which means that we don't know how many bytes to reserve for the
  6762. ** length until we know what the length is.
  6763. **
  6764. ** This leaves us with three main choices:
  6765. **
  6766. ** 1. buffer all submessage data in a temporary buffer, then copy it exactly
  6767. ** once into the output buffer.
  6768. **
  6769. ** 2. attempt to buffer data directly into the output buffer, estimating how
  6770. ** many bytes each length will take. When our guesses are wrong, use
  6771. ** memmove() to grow or shrink the allotted space.
  6772. **
  6773. ** 3. buffer directly into the output buffer, allocating a max length
  6774. ** ahead-of-time for each submessage length. If we overallocated, we waste
  6775. ** space, but no memcpy() or memmove() is required. This approach requires
  6776. ** defining a maximum size for submessages and rejecting submessages that
  6777. ** exceed that size.
  6778. **
  6779. ** (2) and (3) have the potential to have better performance, but they are more
  6780. ** complicated and subtle to implement:
  6781. **
  6782. ** (3) requires making an arbitrary choice of the maximum message size; it
  6783. ** wastes space when submessages are shorter than this and fails
  6784. ** completely when they are longer. This makes it more finicky and
  6785. ** requires configuration based on the input. It also makes it impossible
  6786. ** to perfectly match the output of reference encoders that always use the
  6787. ** optimal amount of space for each length.
  6788. **
  6789. ** (2) requires guessing the the size upfront, and if multiple lengths are
  6790. ** guessed wrong the minimum required number of memmove() operations may
  6791. ** be complicated to compute correctly. Implemented properly, it may have
  6792. ** a useful amortized or average cost, but more investigation is required
  6793. ** to determine this and what the optimal algorithm is to achieve it.
  6794. **
  6795. ** (1) makes you always pay for exactly one copy, but its implementation is
  6796. ** the simplest and its performance is predictable.
  6797. **
  6798. ** So for now, we implement (1) only. If we wish to optimize later, we should
  6799. ** be able to do it without affecting users.
  6800. **
  6801. ** The strategy is to buffer the segments of data that do *not* depend on
  6802. ** unknown lengths in one buffer, and keep a separate buffer of segment pointers
  6803. ** and lengths. When the top-level submessage ends, we can go beginning to end,
  6804. ** alternating the writing of lengths with memcpy() of the rest of the data.
  6805. ** At the top level though, no buffering is required.
  6806. */
  6807. /* The output buffer is divided into segments; a segment is a string of data
  6808. * that is "ready to go" -- it does not need any varint lengths inserted into
  6809. * the middle. The seams between segments are where varints will be inserted
  6810. * once they are known.
  6811. *
  6812. * We also use the concept of a "run", which is a range of encoded bytes that
  6813. * occur at a single submessage level. Every segment contains one or more runs.
  6814. *
  6815. * A segment can span messages. Consider:
  6816. *
  6817. * .--Submessage lengths---------.
  6818. * | | |
  6819. * | V V
  6820. * V | |--------------- | |-----------------
  6821. * Submessages: | |-----------------------------------------------
  6822. * Top-level msg: ------------------------------------------------------------
  6823. *
  6824. * Segments: ----- ------------------- -----------------
  6825. * Runs: *---- *--------------*--- *----------------
  6826. * (* marks the start)
  6827. *
  6828. * Note that the top-level menssage is not in any segment because it does not
  6829. * have any length preceding it.
  6830. *
  6831. * A segment is only interrupted when another length needs to be inserted. So
  6832. * observe how the second segment spans both the inner submessage and part of
  6833. * the next enclosing message. */
  6834. typedef struct {
  6835. uint32_t msglen; /* The length to varint-encode before this segment. */
  6836. uint32_t seglen; /* Length of the segment. */
  6837. } upb_pb_encoder_segment;
  6838. struct upb_pb_encoder {
  6839. upb_arena *arena;
  6840. /* Our input and output. */
  6841. upb_sink input_;
  6842. upb_bytessink output_;
  6843. /* The "subclosure" -- used as the inner closure as part of the bytessink
  6844. * protocol. */
  6845. void *subc;
  6846. /* The output buffer and limit, and our current write position. "buf"
  6847. * initially points to "initbuf", but is dynamically allocated if we need to
  6848. * grow beyond the initial size. */
  6849. char *buf, *ptr, *limit;
  6850. /* The beginning of the current run, or undefined if we are at the top
  6851. * level. */
  6852. char *runbegin;
  6853. /* The list of segments we are accumulating. */
  6854. upb_pb_encoder_segment *segbuf, *segptr, *seglimit;
  6855. /* The stack of enclosing submessages. Each entry in the stack points to the
  6856. * segment where this submessage's length is being accumulated. */
  6857. int *stack, *top, *stacklimit;
  6858. /* Depth of startmsg/endmsg calls. */
  6859. int depth;
  6860. };
  6861. /* low-level buffering ********************************************************/
  6862. /* Low-level functions for interacting with the output buffer. */
  6863. /* TODO(haberman): handle pushback */
  6864. static void putbuf(upb_pb_encoder *e, const char *buf, size_t len) {
  6865. size_t n = upb_bytessink_putbuf(e->output_, e->subc, buf, len, NULL);
  6866. UPB_ASSERT(n == len);
  6867. }
  6868. static upb_pb_encoder_segment *top(upb_pb_encoder *e) {
  6869. return &e->segbuf[*e->top];
  6870. }
  6871. /* Call to ensure that at least "bytes" bytes are available for writing at
  6872. * e->ptr. Returns false if the bytes could not be allocated. */
  6873. static bool reserve(upb_pb_encoder *e, size_t bytes) {
  6874. if ((size_t)(e->limit - e->ptr) < bytes) {
  6875. /* Grow buffer. */
  6876. char *new_buf;
  6877. size_t needed = bytes + (e->ptr - e->buf);
  6878. size_t old_size = e->limit - e->buf;
  6879. size_t new_size = old_size;
  6880. while (new_size < needed) {
  6881. new_size *= 2;
  6882. }
  6883. new_buf = upb_arena_realloc(e->arena, e->buf, old_size, new_size);
  6884. if (new_buf == NULL) {
  6885. return false;
  6886. }
  6887. e->ptr = new_buf + (e->ptr - e->buf);
  6888. e->runbegin = new_buf + (e->runbegin - e->buf);
  6889. e->limit = new_buf + new_size;
  6890. e->buf = new_buf;
  6891. }
  6892. return true;
  6893. }
  6894. /* Call when "bytes" bytes have been writte at e->ptr. The caller *must* have
  6895. * previously called reserve() with at least this many bytes. */
  6896. static void encoder_advance(upb_pb_encoder *e, size_t bytes) {
  6897. UPB_ASSERT((size_t)(e->limit - e->ptr) >= bytes);
  6898. e->ptr += bytes;
  6899. }
  6900. /* Call when all of the bytes for a handler have been written. Flushes the
  6901. * bytes if possible and necessary, returning false if this failed. */
  6902. static bool commit(upb_pb_encoder *e) {
  6903. if (!e->top) {
  6904. /* We aren't inside a delimited region. Flush our accumulated bytes to
  6905. * the output.
  6906. *
  6907. * TODO(haberman): in the future we may want to delay flushing for
  6908. * efficiency reasons. */
  6909. putbuf(e, e->buf, e->ptr - e->buf);
  6910. e->ptr = e->buf;
  6911. }
  6912. return true;
  6913. }
  6914. /* Writes the given bytes to the buffer, handling reserve/advance. */
  6915. static bool encode_bytes(upb_pb_encoder *e, const void *data, size_t len) {
  6916. if (!reserve(e, len)) {
  6917. return false;
  6918. }
  6919. memcpy(e->ptr, data, len);
  6920. encoder_advance(e, len);
  6921. return true;
  6922. }
  6923. /* Finish the current run by adding the run totals to the segment and message
  6924. * length. */
  6925. static void accumulate(upb_pb_encoder *e) {
  6926. size_t run_len;
  6927. UPB_ASSERT(e->ptr >= e->runbegin);
  6928. run_len = e->ptr - e->runbegin;
  6929. e->segptr->seglen += run_len;
  6930. top(e)->msglen += run_len;
  6931. e->runbegin = e->ptr;
  6932. }
  6933. /* Call to indicate the start of delimited region for which the full length is
  6934. * not yet known. All data will be buffered until the length is known.
  6935. * Delimited regions may be nested; their lengths will all be tracked properly. */
  6936. static bool start_delim(upb_pb_encoder *e) {
  6937. if (e->top) {
  6938. /* We are already buffering, advance to the next segment and push it on the
  6939. * stack. */
  6940. accumulate(e);
  6941. if (++e->top == e->stacklimit) {
  6942. /* TODO(haberman): grow stack? */
  6943. return false;
  6944. }
  6945. if (++e->segptr == e->seglimit) {
  6946. /* Grow segment buffer. */
  6947. size_t old_size =
  6948. (e->seglimit - e->segbuf) * sizeof(upb_pb_encoder_segment);
  6949. size_t new_size = old_size * 2;
  6950. upb_pb_encoder_segment *new_buf =
  6951. upb_arena_realloc(e->arena, e->segbuf, old_size, new_size);
  6952. if (new_buf == NULL) {
  6953. return false;
  6954. }
  6955. e->segptr = new_buf + (e->segptr - e->segbuf);
  6956. e->seglimit = new_buf + (new_size / sizeof(upb_pb_encoder_segment));
  6957. e->segbuf = new_buf;
  6958. }
  6959. } else {
  6960. /* We were previously at the top level, start buffering. */
  6961. e->segptr = e->segbuf;
  6962. e->top = e->stack;
  6963. e->runbegin = e->ptr;
  6964. }
  6965. *e->top = (int)(e->segptr - e->segbuf);
  6966. e->segptr->seglen = 0;
  6967. e->segptr->msglen = 0;
  6968. return true;
  6969. }
  6970. /* Call to indicate the end of a delimited region. We now know the length of
  6971. * the delimited region. If we are not nested inside any other delimited
  6972. * regions, we can now emit all of the buffered data we accumulated. */
  6973. static bool end_delim(upb_pb_encoder *e) {
  6974. size_t msglen;
  6975. accumulate(e);
  6976. msglen = top(e)->msglen;
  6977. if (e->top == e->stack) {
  6978. /* All lengths are now available, emit all buffered data. */
  6979. char buf[UPB_PB_VARINT_MAX_LEN];
  6980. upb_pb_encoder_segment *s;
  6981. const char *ptr = e->buf;
  6982. for (s = e->segbuf; s <= e->segptr; s++) {
  6983. size_t lenbytes = upb_vencode64(s->msglen, buf);
  6984. putbuf(e, buf, lenbytes);
  6985. putbuf(e, ptr, s->seglen);
  6986. ptr += s->seglen;
  6987. }
  6988. e->ptr = e->buf;
  6989. e->top = NULL;
  6990. } else {
  6991. /* Need to keep buffering; propagate length info into enclosing
  6992. * submessages. */
  6993. --e->top;
  6994. top(e)->msglen += msglen + upb_varint_size(msglen);
  6995. }
  6996. return true;
  6997. }
  6998. /* tag_t **********************************************************************/
  6999. /* A precomputed (pre-encoded) tag and length. */
  7000. typedef struct {
  7001. uint8_t bytes;
  7002. char tag[7];
  7003. } tag_t;
  7004. /* Allocates a new tag for this field, and sets it in these handlerattr. */
  7005. static void new_tag(upb_handlers *h, const upb_fielddef *f, upb_wiretype_t wt,
  7006. upb_handlerattr *attr) {
  7007. uint32_t n = upb_fielddef_number(f);
  7008. tag_t *tag = upb_gmalloc(sizeof(tag_t));
  7009. tag->bytes = upb_vencode64((n << 3) | wt, tag->tag);
  7010. attr->handler_data = tag;
  7011. upb_handlers_addcleanup(h, tag, upb_gfree);
  7012. }
  7013. static bool encode_tag(upb_pb_encoder *e, const tag_t *tag) {
  7014. return encode_bytes(e, tag->tag, tag->bytes);
  7015. }
  7016. /* encoding of wire types *****************************************************/
  7017. static bool encode_fixed64(upb_pb_encoder *e, uint64_t val) {
  7018. /* TODO(haberman): byte-swap for big endian. */
  7019. return encode_bytes(e, &val, sizeof(uint64_t));
  7020. }
  7021. static bool encode_fixed32(upb_pb_encoder *e, uint32_t val) {
  7022. /* TODO(haberman): byte-swap for big endian. */
  7023. return encode_bytes(e, &val, sizeof(uint32_t));
  7024. }
  7025. static bool encode_varint(upb_pb_encoder *e, uint64_t val) {
  7026. if (!reserve(e, UPB_PB_VARINT_MAX_LEN)) {
  7027. return false;
  7028. }
  7029. encoder_advance(e, upb_vencode64(val, e->ptr));
  7030. return true;
  7031. }
  7032. static uint64_t dbl2uint64(double d) {
  7033. uint64_t ret;
  7034. memcpy(&ret, &d, sizeof(uint64_t));
  7035. return ret;
  7036. }
  7037. static uint32_t flt2uint32(float d) {
  7038. uint32_t ret;
  7039. memcpy(&ret, &d, sizeof(uint32_t));
  7040. return ret;
  7041. }
  7042. /* encoding of proto types ****************************************************/
  7043. static bool startmsg(void *c, const void *hd) {
  7044. upb_pb_encoder *e = c;
  7045. UPB_UNUSED(hd);
  7046. if (e->depth++ == 0) {
  7047. upb_bytessink_start(e->output_, 0, &e->subc);
  7048. }
  7049. return true;
  7050. }
  7051. static bool endmsg(void *c, const void *hd, upb_status *status) {
  7052. upb_pb_encoder *e = c;
  7053. UPB_UNUSED(hd);
  7054. UPB_UNUSED(status);
  7055. if (--e->depth == 0) {
  7056. upb_bytessink_end(e->output_);
  7057. }
  7058. return true;
  7059. }
  7060. static void *encode_startdelimfield(void *c, const void *hd) {
  7061. bool ok = encode_tag(c, hd) && commit(c) && start_delim(c);
  7062. return ok ? c : UPB_BREAK;
  7063. }
  7064. static bool encode_unknown(void *c, const void *hd, const char *buf,
  7065. size_t len) {
  7066. UPB_UNUSED(hd);
  7067. return encode_bytes(c, buf, len) && commit(c);
  7068. }
  7069. static bool encode_enddelimfield(void *c, const void *hd) {
  7070. UPB_UNUSED(hd);
  7071. return end_delim(c);
  7072. }
  7073. static void *encode_startgroup(void *c, const void *hd) {
  7074. return (encode_tag(c, hd) && commit(c)) ? c : UPB_BREAK;
  7075. }
  7076. static bool encode_endgroup(void *c, const void *hd) {
  7077. return encode_tag(c, hd) && commit(c);
  7078. }
  7079. static void *encode_startstr(void *c, const void *hd, size_t size_hint) {
  7080. UPB_UNUSED(size_hint);
  7081. return encode_startdelimfield(c, hd);
  7082. }
  7083. static size_t encode_strbuf(void *c, const void *hd, const char *buf,
  7084. size_t len, const upb_bufhandle *h) {
  7085. UPB_UNUSED(hd);
  7086. UPB_UNUSED(h);
  7087. return encode_bytes(c, buf, len) ? len : 0;
  7088. }
  7089. #define T(type, ctype, convert, encode) \
  7090. static bool encode_scalar_##type(void *e, const void *hd, ctype val) { \
  7091. return encode_tag(e, hd) && encode(e, (convert)(val)) && commit(e); \
  7092. } \
  7093. static bool encode_packed_##type(void *e, const void *hd, ctype val) { \
  7094. UPB_UNUSED(hd); \
  7095. return encode(e, (convert)(val)); \
  7096. }
  7097. T(double, double, dbl2uint64, encode_fixed64)
  7098. T(float, float, flt2uint32, encode_fixed32)
  7099. T(int64, int64_t, uint64_t, encode_varint)
  7100. T(int32, int32_t, int64_t, encode_varint)
  7101. T(fixed64, uint64_t, uint64_t, encode_fixed64)
  7102. T(fixed32, uint32_t, uint32_t, encode_fixed32)
  7103. T(bool, bool, bool, encode_varint)
  7104. T(uint32, uint32_t, uint32_t, encode_varint)
  7105. T(uint64, uint64_t, uint64_t, encode_varint)
  7106. T(enum, int32_t, uint32_t, encode_varint)
  7107. T(sfixed32, int32_t, uint32_t, encode_fixed32)
  7108. T(sfixed64, int64_t, uint64_t, encode_fixed64)
  7109. T(sint32, int32_t, upb_zzenc_32, encode_varint)
  7110. T(sint64, int64_t, upb_zzenc_64, encode_varint)
  7111. #undef T
  7112. /* code to build the handlers *************************************************/
  7113. #include <stdio.h>
  7114. static void newhandlers_callback(const void *closure, upb_handlers *h) {
  7115. const upb_msgdef *m;
  7116. upb_msg_field_iter i;
  7117. UPB_UNUSED(closure);
  7118. upb_handlers_setstartmsg(h, startmsg, NULL);
  7119. upb_handlers_setendmsg(h, endmsg, NULL);
  7120. upb_handlers_setunknown(h, encode_unknown, NULL);
  7121. m = upb_handlers_msgdef(h);
  7122. for(upb_msg_field_begin(&i, m);
  7123. !upb_msg_field_done(&i);
  7124. upb_msg_field_next(&i)) {
  7125. const upb_fielddef *f = upb_msg_iter_field(&i);
  7126. bool packed = upb_fielddef_isseq(f) && upb_fielddef_isprimitive(f) &&
  7127. upb_fielddef_packed(f);
  7128. upb_handlerattr attr = UPB_HANDLERATTR_INIT;
  7129. upb_wiretype_t wt =
  7130. packed ? UPB_WIRE_TYPE_DELIMITED
  7131. : upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  7132. /* Pre-encode the tag for this field. */
  7133. new_tag(h, f, wt, &attr);
  7134. if (packed) {
  7135. upb_handlers_setstartseq(h, f, encode_startdelimfield, &attr);
  7136. upb_handlers_setendseq(h, f, encode_enddelimfield, &attr);
  7137. }
  7138. #define T(upper, lower, upbtype) \
  7139. case UPB_DESCRIPTOR_TYPE_##upper: \
  7140. if (packed) { \
  7141. upb_handlers_set##upbtype(h, f, encode_packed_##lower, &attr); \
  7142. } else { \
  7143. upb_handlers_set##upbtype(h, f, encode_scalar_##lower, &attr); \
  7144. } \
  7145. break;
  7146. switch (upb_fielddef_descriptortype(f)) {
  7147. T(DOUBLE, double, double);
  7148. T(FLOAT, float, float);
  7149. T(INT64, int64, int64);
  7150. T(INT32, int32, int32);
  7151. T(FIXED64, fixed64, uint64);
  7152. T(FIXED32, fixed32, uint32);
  7153. T(BOOL, bool, bool);
  7154. T(UINT32, uint32, uint32);
  7155. T(UINT64, uint64, uint64);
  7156. T(ENUM, enum, int32);
  7157. T(SFIXED32, sfixed32, int32);
  7158. T(SFIXED64, sfixed64, int64);
  7159. T(SINT32, sint32, int32);
  7160. T(SINT64, sint64, int64);
  7161. case UPB_DESCRIPTOR_TYPE_STRING:
  7162. case UPB_DESCRIPTOR_TYPE_BYTES:
  7163. upb_handlers_setstartstr(h, f, encode_startstr, &attr);
  7164. upb_handlers_setendstr(h, f, encode_enddelimfield, &attr);
  7165. upb_handlers_setstring(h, f, encode_strbuf, &attr);
  7166. break;
  7167. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  7168. upb_handlers_setstartsubmsg(h, f, encode_startdelimfield, &attr);
  7169. upb_handlers_setendsubmsg(h, f, encode_enddelimfield, &attr);
  7170. break;
  7171. case UPB_DESCRIPTOR_TYPE_GROUP: {
  7172. /* Endgroup takes a different tag (wire_type = END_GROUP). */
  7173. upb_handlerattr attr2 = UPB_HANDLERATTR_INIT;
  7174. new_tag(h, f, UPB_WIRE_TYPE_END_GROUP, &attr2);
  7175. upb_handlers_setstartsubmsg(h, f, encode_startgroup, &attr);
  7176. upb_handlers_setendsubmsg(h, f, encode_endgroup, &attr2);
  7177. break;
  7178. }
  7179. }
  7180. #undef T
  7181. }
  7182. }
  7183. void upb_pb_encoder_reset(upb_pb_encoder *e) {
  7184. e->segptr = NULL;
  7185. e->top = NULL;
  7186. e->depth = 0;
  7187. }
  7188. /* public API *****************************************************************/
  7189. upb_handlercache *upb_pb_encoder_newcache(void) {
  7190. return upb_handlercache_new(newhandlers_callback, NULL);
  7191. }
  7192. upb_pb_encoder *upb_pb_encoder_create(upb_arena *arena, const upb_handlers *h,
  7193. upb_bytessink output) {
  7194. const size_t initial_bufsize = 256;
  7195. const size_t initial_segbufsize = 16;
  7196. /* TODO(haberman): make this configurable. */
  7197. const size_t stack_size = 64;
  7198. #ifndef NDEBUG
  7199. const size_t size_before = upb_arena_bytesallocated(arena);
  7200. #endif
  7201. upb_pb_encoder *e = upb_arena_malloc(arena, sizeof(upb_pb_encoder));
  7202. if (!e) return NULL;
  7203. e->buf = upb_arena_malloc(arena, initial_bufsize);
  7204. e->segbuf = upb_arena_malloc(arena, initial_segbufsize * sizeof(*e->segbuf));
  7205. e->stack = upb_arena_malloc(arena, stack_size * sizeof(*e->stack));
  7206. if (!e->buf || !e->segbuf || !e->stack) {
  7207. return NULL;
  7208. }
  7209. e->limit = e->buf + initial_bufsize;
  7210. e->seglimit = e->segbuf + initial_segbufsize;
  7211. e->stacklimit = e->stack + stack_size;
  7212. upb_pb_encoder_reset(e);
  7213. upb_sink_reset(&e->input_, h, e);
  7214. e->arena = arena;
  7215. e->output_ = output;
  7216. e->subc = output.closure;
  7217. e->ptr = e->buf;
  7218. /* If this fails, increase the value in encoder.h. */
  7219. UPB_ASSERT_DEBUGVAR(upb_arena_bytesallocated(arena) - size_before <=
  7220. UPB_PB_ENCODER_SIZE);
  7221. return e;
  7222. }
  7223. upb_sink upb_pb_encoder_input(upb_pb_encoder *e) { return e->input_; }
  7224. /*
  7225. * upb::pb::TextPrinter
  7226. *
  7227. * OPT: This is not optimized at all. It uses printf() which parses the format
  7228. * string every time, and it allocates memory for every put.
  7229. */
  7230. #include <ctype.h>
  7231. #include <float.h>
  7232. #include <inttypes.h>
  7233. #include <stdarg.h>
  7234. #include <stdio.h>
  7235. #include <string.h>
  7236. struct upb_textprinter {
  7237. upb_sink input_;
  7238. upb_bytessink output_;
  7239. int indent_depth_;
  7240. bool single_line_;
  7241. void *subc;
  7242. };
  7243. #define CHECK(x) if ((x) < 0) goto err;
  7244. static const char *shortname(const char *longname) {
  7245. const char *last = strrchr(longname, '.');
  7246. return last ? last + 1 : longname;
  7247. }
  7248. static int indent(upb_textprinter *p) {
  7249. int i;
  7250. if (!p->single_line_)
  7251. for (i = 0; i < p->indent_depth_; i++)
  7252. upb_bytessink_putbuf(p->output_, p->subc, " ", 2, NULL);
  7253. return 0;
  7254. }
  7255. static int endfield(upb_textprinter *p) {
  7256. const char ch = (p->single_line_ ? ' ' : '\n');
  7257. upb_bytessink_putbuf(p->output_, p->subc, &ch, 1, NULL);
  7258. return 0;
  7259. }
  7260. static int putescaped(upb_textprinter *p, const char *buf, size_t len,
  7261. bool preserve_utf8) {
  7262. /* Based on CEscapeInternal() from Google's protobuf release. */
  7263. char dstbuf[4096], *dst = dstbuf, *dstend = dstbuf + sizeof(dstbuf);
  7264. const char *end = buf + len;
  7265. /* I think hex is prettier and more useful, but proto2 uses octal; should
  7266. * investigate whether it can parse hex also. */
  7267. const bool use_hex = false;
  7268. bool last_hex_escape = false; /* true if last output char was \xNN */
  7269. for (; buf < end; buf++) {
  7270. bool is_hex_escape;
  7271. if (dstend - dst < 4) {
  7272. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  7273. dst = dstbuf;
  7274. }
  7275. is_hex_escape = false;
  7276. switch (*buf) {
  7277. case '\n': *(dst++) = '\\'; *(dst++) = 'n'; break;
  7278. case '\r': *(dst++) = '\\'; *(dst++) = 'r'; break;
  7279. case '\t': *(dst++) = '\\'; *(dst++) = 't'; break;
  7280. case '\"': *(dst++) = '\\'; *(dst++) = '\"'; break;
  7281. case '\'': *(dst++) = '\\'; *(dst++) = '\''; break;
  7282. case '\\': *(dst++) = '\\'; *(dst++) = '\\'; break;
  7283. default:
  7284. /* Note that if we emit \xNN and the buf character after that is a hex
  7285. * digit then that digit must be escaped too to prevent it being
  7286. * interpreted as part of the character code by C. */
  7287. if ((!preserve_utf8 || (uint8_t)*buf < 0x80) &&
  7288. (!isprint(*buf) || (last_hex_escape && isxdigit(*buf)))) {
  7289. sprintf(dst, (use_hex ? "\\x%02x" : "\\%03o"), (uint8_t)*buf);
  7290. is_hex_escape = use_hex;
  7291. dst += 4;
  7292. } else {
  7293. *(dst++) = *buf; break;
  7294. }
  7295. }
  7296. last_hex_escape = is_hex_escape;
  7297. }
  7298. /* Flush remaining data. */
  7299. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  7300. return 0;
  7301. }
  7302. bool putf(upb_textprinter *p, const char *fmt, ...) {
  7303. va_list args;
  7304. va_list args_copy;
  7305. char *str;
  7306. int written;
  7307. int len;
  7308. bool ok;
  7309. va_start(args, fmt);
  7310. /* Run once to get the length of the string. */
  7311. _upb_va_copy(args_copy, args);
  7312. len = _upb_vsnprintf(NULL, 0, fmt, args_copy);
  7313. va_end(args_copy);
  7314. /* + 1 for NULL terminator (vsprintf() requires it even if we don't). */
  7315. str = upb_gmalloc(len + 1);
  7316. if (!str) return false;
  7317. written = vsprintf(str, fmt, args);
  7318. va_end(args);
  7319. UPB_ASSERT(written == len);
  7320. ok = upb_bytessink_putbuf(p->output_, p->subc, str, len, NULL);
  7321. upb_gfree(str);
  7322. return ok;
  7323. }
  7324. /* handlers *******************************************************************/
  7325. static bool textprinter_startmsg(void *c, const void *hd) {
  7326. upb_textprinter *p = c;
  7327. UPB_UNUSED(hd);
  7328. if (p->indent_depth_ == 0) {
  7329. upb_bytessink_start(p->output_, 0, &p->subc);
  7330. }
  7331. return true;
  7332. }
  7333. static bool textprinter_endmsg(void *c, const void *hd, upb_status *s) {
  7334. upb_textprinter *p = c;
  7335. UPB_UNUSED(hd);
  7336. UPB_UNUSED(s);
  7337. if (p->indent_depth_ == 0) {
  7338. upb_bytessink_end(p->output_);
  7339. }
  7340. return true;
  7341. }
  7342. #define TYPE(name, ctype, fmt) \
  7343. static bool textprinter_put ## name(void *closure, const void *handler_data, \
  7344. ctype val) { \
  7345. upb_textprinter *p = closure; \
  7346. const upb_fielddef *f = handler_data; \
  7347. CHECK(indent(p)); \
  7348. putf(p, "%s: " fmt, upb_fielddef_name(f), val); \
  7349. CHECK(endfield(p)); \
  7350. return true; \
  7351. err: \
  7352. return false; \
  7353. }
  7354. static bool textprinter_putbool(void *closure, const void *handler_data,
  7355. bool val) {
  7356. upb_textprinter *p = closure;
  7357. const upb_fielddef *f = handler_data;
  7358. CHECK(indent(p));
  7359. putf(p, "%s: %s", upb_fielddef_name(f), val ? "true" : "false");
  7360. CHECK(endfield(p));
  7361. return true;
  7362. err:
  7363. return false;
  7364. }
  7365. #define STRINGIFY_HELPER(x) #x
  7366. #define STRINGIFY_MACROVAL(x) STRINGIFY_HELPER(x)
  7367. TYPE(int32, int32_t, "%" PRId32)
  7368. TYPE(int64, int64_t, "%" PRId64)
  7369. TYPE(uint32, uint32_t, "%" PRIu32)
  7370. TYPE(uint64, uint64_t, "%" PRIu64)
  7371. TYPE(float, float, "%." STRINGIFY_MACROVAL(FLT_DIG) "g")
  7372. TYPE(double, double, "%." STRINGIFY_MACROVAL(DBL_DIG) "g")
  7373. #undef TYPE
  7374. /* Output a symbolic value from the enum if found, else just print as int32. */
  7375. static bool textprinter_putenum(void *closure, const void *handler_data,
  7376. int32_t val) {
  7377. upb_textprinter *p = closure;
  7378. const upb_fielddef *f = handler_data;
  7379. const upb_enumdef *enum_def = upb_fielddef_enumsubdef(f);
  7380. const char *label = upb_enumdef_iton(enum_def, val);
  7381. if (label) {
  7382. indent(p);
  7383. putf(p, "%s: %s", upb_fielddef_name(f), label);
  7384. endfield(p);
  7385. } else {
  7386. if (!textprinter_putint32(closure, handler_data, val))
  7387. return false;
  7388. }
  7389. return true;
  7390. }
  7391. static void *textprinter_startstr(void *closure, const void *handler_data,
  7392. size_t size_hint) {
  7393. upb_textprinter *p = closure;
  7394. const upb_fielddef *f = handler_data;
  7395. UPB_UNUSED(size_hint);
  7396. indent(p);
  7397. putf(p, "%s: \"", upb_fielddef_name(f));
  7398. return p;
  7399. }
  7400. static bool textprinter_endstr(void *closure, const void *handler_data) {
  7401. upb_textprinter *p = closure;
  7402. UPB_UNUSED(handler_data);
  7403. putf(p, "\"");
  7404. endfield(p);
  7405. return true;
  7406. }
  7407. static size_t textprinter_putstr(void *closure, const void *hd, const char *buf,
  7408. size_t len, const upb_bufhandle *handle) {
  7409. upb_textprinter *p = closure;
  7410. const upb_fielddef *f = hd;
  7411. UPB_UNUSED(handle);
  7412. CHECK(putescaped(p, buf, len, upb_fielddef_type(f) == UPB_TYPE_STRING));
  7413. return len;
  7414. err:
  7415. return 0;
  7416. }
  7417. static void *textprinter_startsubmsg(void *closure, const void *handler_data) {
  7418. upb_textprinter *p = closure;
  7419. const char *name = handler_data;
  7420. CHECK(indent(p));
  7421. putf(p, "%s {%c", name, p->single_line_ ? ' ' : '\n');
  7422. p->indent_depth_++;
  7423. return p;
  7424. err:
  7425. return UPB_BREAK;
  7426. }
  7427. static bool textprinter_endsubmsg(void *closure, const void *handler_data) {
  7428. upb_textprinter *p = closure;
  7429. UPB_UNUSED(handler_data);
  7430. p->indent_depth_--;
  7431. CHECK(indent(p));
  7432. upb_bytessink_putbuf(p->output_, p->subc, "}", 1, NULL);
  7433. CHECK(endfield(p));
  7434. return true;
  7435. err:
  7436. return false;
  7437. }
  7438. static void onmreg(const void *c, upb_handlers *h) {
  7439. const upb_msgdef *m = upb_handlers_msgdef(h);
  7440. upb_msg_field_iter i;
  7441. UPB_UNUSED(c);
  7442. upb_handlers_setstartmsg(h, textprinter_startmsg, NULL);
  7443. upb_handlers_setendmsg(h, textprinter_endmsg, NULL);
  7444. for(upb_msg_field_begin(&i, m);
  7445. !upb_msg_field_done(&i);
  7446. upb_msg_field_next(&i)) {
  7447. upb_fielddef *f = upb_msg_iter_field(&i);
  7448. upb_handlerattr attr = UPB_HANDLERATTR_INIT;
  7449. attr.handler_data = f;
  7450. switch (upb_fielddef_type(f)) {
  7451. case UPB_TYPE_INT32:
  7452. upb_handlers_setint32(h, f, textprinter_putint32, &attr);
  7453. break;
  7454. case UPB_TYPE_INT64:
  7455. upb_handlers_setint64(h, f, textprinter_putint64, &attr);
  7456. break;
  7457. case UPB_TYPE_UINT32:
  7458. upb_handlers_setuint32(h, f, textprinter_putuint32, &attr);
  7459. break;
  7460. case UPB_TYPE_UINT64:
  7461. upb_handlers_setuint64(h, f, textprinter_putuint64, &attr);
  7462. break;
  7463. case UPB_TYPE_FLOAT:
  7464. upb_handlers_setfloat(h, f, textprinter_putfloat, &attr);
  7465. break;
  7466. case UPB_TYPE_DOUBLE:
  7467. upb_handlers_setdouble(h, f, textprinter_putdouble, &attr);
  7468. break;
  7469. case UPB_TYPE_BOOL:
  7470. upb_handlers_setbool(h, f, textprinter_putbool, &attr);
  7471. break;
  7472. case UPB_TYPE_STRING:
  7473. case UPB_TYPE_BYTES:
  7474. upb_handlers_setstartstr(h, f, textprinter_startstr, &attr);
  7475. upb_handlers_setstring(h, f, textprinter_putstr, &attr);
  7476. upb_handlers_setendstr(h, f, textprinter_endstr, &attr);
  7477. break;
  7478. case UPB_TYPE_MESSAGE: {
  7479. const char *name =
  7480. upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_GROUP
  7481. ? shortname(upb_msgdef_fullname(upb_fielddef_msgsubdef(f)))
  7482. : upb_fielddef_name(f);
  7483. attr.handler_data = name;
  7484. upb_handlers_setstartsubmsg(h, f, textprinter_startsubmsg, &attr);
  7485. upb_handlers_setendsubmsg(h, f, textprinter_endsubmsg, &attr);
  7486. break;
  7487. }
  7488. case UPB_TYPE_ENUM:
  7489. upb_handlers_setint32(h, f, textprinter_putenum, &attr);
  7490. break;
  7491. }
  7492. }
  7493. }
  7494. static void textprinter_reset(upb_textprinter *p, bool single_line) {
  7495. p->single_line_ = single_line;
  7496. p->indent_depth_ = 0;
  7497. }
  7498. /* Public API *****************************************************************/
  7499. upb_textprinter *upb_textprinter_create(upb_arena *arena, const upb_handlers *h,
  7500. upb_bytessink output) {
  7501. upb_textprinter *p = upb_arena_malloc(arena, sizeof(upb_textprinter));
  7502. if (!p) return NULL;
  7503. p->output_ = output;
  7504. upb_sink_reset(&p->input_, h, p);
  7505. textprinter_reset(p, false);
  7506. return p;
  7507. }
  7508. upb_handlercache *upb_textprinter_newcache(void) {
  7509. return upb_handlercache_new(&onmreg, NULL);
  7510. }
  7511. upb_sink upb_textprinter_input(upb_textprinter *p) { return p->input_; }
  7512. void upb_textprinter_setsingleline(upb_textprinter *p, bool single_line) {
  7513. p->single_line_ = single_line;
  7514. }
  7515. /* Index is descriptor type. */
  7516. const uint8_t upb_pb_native_wire_types[] = {
  7517. UPB_WIRE_TYPE_END_GROUP, /* ENDGROUP */
  7518. UPB_WIRE_TYPE_64BIT, /* DOUBLE */
  7519. UPB_WIRE_TYPE_32BIT, /* FLOAT */
  7520. UPB_WIRE_TYPE_VARINT, /* INT64 */
  7521. UPB_WIRE_TYPE_VARINT, /* UINT64 */
  7522. UPB_WIRE_TYPE_VARINT, /* INT32 */
  7523. UPB_WIRE_TYPE_64BIT, /* FIXED64 */
  7524. UPB_WIRE_TYPE_32BIT, /* FIXED32 */
  7525. UPB_WIRE_TYPE_VARINT, /* BOOL */
  7526. UPB_WIRE_TYPE_DELIMITED, /* STRING */
  7527. UPB_WIRE_TYPE_START_GROUP, /* GROUP */
  7528. UPB_WIRE_TYPE_DELIMITED, /* MESSAGE */
  7529. UPB_WIRE_TYPE_DELIMITED, /* BYTES */
  7530. UPB_WIRE_TYPE_VARINT, /* UINT32 */
  7531. UPB_WIRE_TYPE_VARINT, /* ENUM */
  7532. UPB_WIRE_TYPE_32BIT, /* SFIXED32 */
  7533. UPB_WIRE_TYPE_64BIT, /* SFIXED64 */
  7534. UPB_WIRE_TYPE_VARINT, /* SINT32 */
  7535. UPB_WIRE_TYPE_VARINT, /* SINT64 */
  7536. };
  7537. /* A basic branch-based decoder, uses 32-bit values to get good performance
  7538. * on 32-bit architectures (but performs well on 64-bits also).
  7539. * This scheme comes from the original Google Protobuf implementation
  7540. * (proto2). */
  7541. upb_decoderet upb_vdecode_max8_branch32(upb_decoderet r) {
  7542. upb_decoderet err = {NULL, 0};
  7543. const char *p = r.p;
  7544. uint32_t low = (uint32_t)r.val;
  7545. uint32_t high = 0;
  7546. uint32_t b;
  7547. b = *(p++); low |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  7548. b = *(p++); low |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  7549. b = *(p++); low |= (b & 0x7fU) << 28;
  7550. high = (b & 0x7fU) >> 4; if (!(b & 0x80)) goto done;
  7551. b = *(p++); high |= (b & 0x7fU) << 3; if (!(b & 0x80)) goto done;
  7552. b = *(p++); high |= (b & 0x7fU) << 10; if (!(b & 0x80)) goto done;
  7553. b = *(p++); high |= (b & 0x7fU) << 17; if (!(b & 0x80)) goto done;
  7554. b = *(p++); high |= (b & 0x7fU) << 24; if (!(b & 0x80)) goto done;
  7555. b = *(p++); high |= (b & 0x7fU) << 31; if (!(b & 0x80)) goto done;
  7556. return err;
  7557. done:
  7558. r.val = ((uint64_t)high << 32) | low;
  7559. r.p = p;
  7560. return r;
  7561. }
  7562. /* Like the previous, but uses 64-bit values. */
  7563. upb_decoderet upb_vdecode_max8_branch64(upb_decoderet r) {
  7564. const char *p = r.p;
  7565. uint64_t val = r.val;
  7566. uint64_t b;
  7567. upb_decoderet err = {NULL, 0};
  7568. b = *(p++); val |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  7569. b = *(p++); val |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  7570. b = *(p++); val |= (b & 0x7fU) << 28; if (!(b & 0x80)) goto done;
  7571. b = *(p++); val |= (b & 0x7fU) << 35; if (!(b & 0x80)) goto done;
  7572. b = *(p++); val |= (b & 0x7fU) << 42; if (!(b & 0x80)) goto done;
  7573. b = *(p++); val |= (b & 0x7fU) << 49; if (!(b & 0x80)) goto done;
  7574. b = *(p++); val |= (b & 0x7fU) << 56; if (!(b & 0x80)) goto done;
  7575. b = *(p++); val |= (b & 0x7fU) << 63; if (!(b & 0x80)) goto done;
  7576. return err;
  7577. done:
  7578. r.val = val;
  7579. r.p = p;
  7580. return r;
  7581. }
  7582. #line 1 "upb/json/parser.rl"
  7583. /*
  7584. ** upb::json::Parser (upb_json_parser)
  7585. **
  7586. ** A parser that uses the Ragel State Machine Compiler to generate
  7587. ** the finite automata.
  7588. **
  7589. ** Ragel only natively handles regular languages, but we can manually
  7590. ** program it a bit to handle context-free languages like JSON, by using
  7591. ** the "fcall" and "fret" constructs.
  7592. **
  7593. ** This parser can handle the basics, but needs several things to be fleshed
  7594. ** out:
  7595. **
  7596. ** - handling of unicode escape sequences (including high surrogate pairs).
  7597. ** - properly check and report errors for unknown fields, stack overflow,
  7598. ** improper array nesting (or lack of nesting).
  7599. ** - handling of base64 sequences with padding characters.
  7600. ** - handling of push-back (non-success returns from sink functions).
  7601. ** - handling of keys/escape-sequences/etc that span input buffers.
  7602. */
  7603. #include <ctype.h>
  7604. #include <errno.h>
  7605. #include <float.h>
  7606. #include <math.h>
  7607. #include <stdint.h>
  7608. #include <stdio.h>
  7609. #include <stdlib.h>
  7610. #include <string.h>
  7611. #include <time.h>
  7612. #define UPB_JSON_MAX_DEPTH 64
  7613. /* Type of value message */
  7614. enum {
  7615. VALUE_NULLVALUE = 0,
  7616. VALUE_NUMBERVALUE = 1,
  7617. VALUE_STRINGVALUE = 2,
  7618. VALUE_BOOLVALUE = 3,
  7619. VALUE_STRUCTVALUE = 4,
  7620. VALUE_LISTVALUE = 5
  7621. };
  7622. /* Forward declare */
  7623. static bool is_top_level(upb_json_parser *p);
  7624. static bool is_wellknown_msg(upb_json_parser *p, upb_wellknowntype_t type);
  7625. static bool is_wellknown_field(upb_json_parser *p, upb_wellknowntype_t type);
  7626. static bool is_number_wrapper_object(upb_json_parser *p);
  7627. static bool does_number_wrapper_start(upb_json_parser *p);
  7628. static bool does_number_wrapper_end(upb_json_parser *p);
  7629. static bool is_string_wrapper_object(upb_json_parser *p);
  7630. static bool does_string_wrapper_start(upb_json_parser *p);
  7631. static bool does_string_wrapper_end(upb_json_parser *p);
  7632. static bool does_fieldmask_start(upb_json_parser *p);
  7633. static bool does_fieldmask_end(upb_json_parser *p);
  7634. static void start_fieldmask_object(upb_json_parser *p);
  7635. static void end_fieldmask_object(upb_json_parser *p);
  7636. static void start_wrapper_object(upb_json_parser *p);
  7637. static void end_wrapper_object(upb_json_parser *p);
  7638. static void start_value_object(upb_json_parser *p, int value_type);
  7639. static void end_value_object(upb_json_parser *p);
  7640. static void start_listvalue_object(upb_json_parser *p);
  7641. static void end_listvalue_object(upb_json_parser *p);
  7642. static void start_structvalue_object(upb_json_parser *p);
  7643. static void end_structvalue_object(upb_json_parser *p);
  7644. static void start_object(upb_json_parser *p);
  7645. static void end_object(upb_json_parser *p);
  7646. static void start_any_object(upb_json_parser *p, const char *ptr);
  7647. static bool end_any_object(upb_json_parser *p, const char *ptr);
  7648. static bool start_subobject(upb_json_parser *p);
  7649. static void end_subobject(upb_json_parser *p);
  7650. static void start_member(upb_json_parser *p);
  7651. static void end_member(upb_json_parser *p);
  7652. static bool end_membername(upb_json_parser *p);
  7653. static void start_any_member(upb_json_parser *p, const char *ptr);
  7654. static void end_any_member(upb_json_parser *p, const char *ptr);
  7655. static bool end_any_membername(upb_json_parser *p);
  7656. size_t parse(void *closure, const void *hd, const char *buf, size_t size,
  7657. const upb_bufhandle *handle);
  7658. static bool end(void *closure, const void *hd);
  7659. static const char eof_ch = 'e';
  7660. /* stringsink */
  7661. typedef struct {
  7662. upb_byteshandler handler;
  7663. upb_bytessink sink;
  7664. char *ptr;
  7665. size_t len, size;
  7666. } upb_stringsink;
  7667. static void *stringsink_start(void *_sink, const void *hd, size_t size_hint) {
  7668. upb_stringsink *sink = _sink;
  7669. sink->len = 0;
  7670. UPB_UNUSED(hd);
  7671. UPB_UNUSED(size_hint);
  7672. return sink;
  7673. }
  7674. static size_t stringsink_string(void *_sink, const void *hd, const char *ptr,
  7675. size_t len, const upb_bufhandle *handle) {
  7676. upb_stringsink *sink = _sink;
  7677. size_t new_size = sink->size;
  7678. UPB_UNUSED(hd);
  7679. UPB_UNUSED(handle);
  7680. while (sink->len + len > new_size) {
  7681. new_size *= 2;
  7682. }
  7683. if (new_size != sink->size) {
  7684. sink->ptr = realloc(sink->ptr, new_size);
  7685. sink->size = new_size;
  7686. }
  7687. memcpy(sink->ptr + sink->len, ptr, len);
  7688. sink->len += len;
  7689. return len;
  7690. }
  7691. void upb_stringsink_init(upb_stringsink *sink) {
  7692. upb_byteshandler_init(&sink->handler);
  7693. upb_byteshandler_setstartstr(&sink->handler, stringsink_start, NULL);
  7694. upb_byteshandler_setstring(&sink->handler, stringsink_string, NULL);
  7695. upb_bytessink_reset(&sink->sink, &sink->handler, sink);
  7696. sink->size = 32;
  7697. sink->ptr = malloc(sink->size);
  7698. sink->len = 0;
  7699. }
  7700. void upb_stringsink_uninit(upb_stringsink *sink) { free(sink->ptr); }
  7701. typedef struct {
  7702. /* For encoding Any value field in binary format. */
  7703. upb_handlercache *encoder_handlercache;
  7704. upb_stringsink stringsink;
  7705. /* For decoding Any value field in json format. */
  7706. upb_json_codecache *parser_codecache;
  7707. upb_sink sink;
  7708. upb_json_parser *parser;
  7709. /* Mark the range of uninterpreted values in json input before type url. */
  7710. const char *before_type_url_start;
  7711. const char *before_type_url_end;
  7712. /* Mark the range of uninterpreted values in json input after type url. */
  7713. const char *after_type_url_start;
  7714. } upb_jsonparser_any_frame;
  7715. typedef struct {
  7716. upb_sink sink;
  7717. /* The current message in which we're parsing, and the field whose value we're
  7718. * expecting next. */
  7719. const upb_msgdef *m;
  7720. const upb_fielddef *f;
  7721. /* The table mapping json name to fielddef for this message. */
  7722. const upb_strtable *name_table;
  7723. /* We are in a repeated-field context. We need this flag to decide whether to
  7724. * handle the array as a normal repeated field or a
  7725. * google.protobuf.ListValue/google.protobuf.Value. */
  7726. bool is_repeated;
  7727. /* We are in a repeated-field context, ready to emit mapentries as
  7728. * submessages. This flag alters the start-of-object (open-brace) behavior to
  7729. * begin a sequence of mapentry messages rather than a single submessage. */
  7730. bool is_map;
  7731. /* We are in a map-entry message context. This flag is set when parsing the
  7732. * value field of a single map entry and indicates to all value-field parsers
  7733. * (subobjects, strings, numbers, and bools) that the map-entry submessage
  7734. * should end as soon as the value is parsed. */
  7735. bool is_mapentry;
  7736. /* If |is_map| or |is_mapentry| is true, |mapfield| refers to the parent
  7737. * message's map field that we're currently parsing. This differs from |f|
  7738. * because |f| is the field in the *current* message (i.e., the map-entry
  7739. * message itself), not the parent's field that leads to this map. */
  7740. const upb_fielddef *mapfield;
  7741. /* We are in an Any message context. This flag is set when parsing the Any
  7742. * message and indicates to all field parsers (subobjects, strings, numbers,
  7743. * and bools) that the parsed field should be serialized as binary data or
  7744. * cached (type url not found yet). */
  7745. bool is_any;
  7746. /* The type of packed message in Any. */
  7747. upb_jsonparser_any_frame *any_frame;
  7748. /* True if the field to be parsed is unknown. */
  7749. bool is_unknown_field;
  7750. } upb_jsonparser_frame;
  7751. static void init_frame(upb_jsonparser_frame* frame) {
  7752. frame->m = NULL;
  7753. frame->f = NULL;
  7754. frame->name_table = NULL;
  7755. frame->is_repeated = false;
  7756. frame->is_map = false;
  7757. frame->is_mapentry = false;
  7758. frame->mapfield = NULL;
  7759. frame->is_any = false;
  7760. frame->any_frame = NULL;
  7761. frame->is_unknown_field = false;
  7762. }
  7763. struct upb_json_parser {
  7764. upb_arena *arena;
  7765. const upb_json_parsermethod *method;
  7766. upb_bytessink input_;
  7767. /* Stack to track the JSON scopes we are in. */
  7768. upb_jsonparser_frame stack[UPB_JSON_MAX_DEPTH];
  7769. upb_jsonparser_frame *top;
  7770. upb_jsonparser_frame *limit;
  7771. upb_status *status;
  7772. /* Ragel's internal parsing stack for the parsing state machine. */
  7773. int current_state;
  7774. int parser_stack[UPB_JSON_MAX_DEPTH];
  7775. int parser_top;
  7776. /* The handle for the current buffer. */
  7777. const upb_bufhandle *handle;
  7778. /* Accumulate buffer. See details in parser.rl. */
  7779. const char *accumulated;
  7780. size_t accumulated_len;
  7781. char *accumulate_buf;
  7782. size_t accumulate_buf_size;
  7783. /* Multi-part text data. See details in parser.rl. */
  7784. int multipart_state;
  7785. upb_selector_t string_selector;
  7786. /* Input capture. See details in parser.rl. */
  7787. const char *capture;
  7788. /* Intermediate result of parsing a unicode escape sequence. */
  7789. uint32_t digit;
  7790. /* For resolve type url in Any. */
  7791. const upb_symtab *symtab;
  7792. /* Whether to proceed if unknown field is met. */
  7793. bool ignore_json_unknown;
  7794. /* Cache for parsing timestamp due to base and zone are handled in different
  7795. * handlers. */
  7796. struct tm tm;
  7797. };
  7798. static upb_jsonparser_frame* start_jsonparser_frame(upb_json_parser *p) {
  7799. upb_jsonparser_frame *inner;
  7800. inner = p->top + 1;
  7801. init_frame(inner);
  7802. return inner;
  7803. }
  7804. struct upb_json_codecache {
  7805. upb_arena *arena;
  7806. upb_inttable methods; /* upb_msgdef* -> upb_json_parsermethod* */
  7807. };
  7808. struct upb_json_parsermethod {
  7809. const upb_json_codecache *cache;
  7810. upb_byteshandler input_handler_;
  7811. /* Maps json_name -> fielddef */
  7812. upb_strtable name_table;
  7813. };
  7814. #define PARSER_CHECK_RETURN(x) if (!(x)) return false
  7815. static upb_jsonparser_any_frame *json_parser_any_frame_new(
  7816. upb_json_parser *p) {
  7817. upb_jsonparser_any_frame *frame;
  7818. frame = upb_arena_malloc(p->arena, sizeof(upb_jsonparser_any_frame));
  7819. frame->encoder_handlercache = upb_pb_encoder_newcache();
  7820. frame->parser_codecache = upb_json_codecache_new();
  7821. frame->parser = NULL;
  7822. frame->before_type_url_start = NULL;
  7823. frame->before_type_url_end = NULL;
  7824. frame->after_type_url_start = NULL;
  7825. upb_stringsink_init(&frame->stringsink);
  7826. return frame;
  7827. }
  7828. static void json_parser_any_frame_set_payload_type(
  7829. upb_json_parser *p,
  7830. upb_jsonparser_any_frame *frame,
  7831. const upb_msgdef *payload_type) {
  7832. const upb_handlers *h;
  7833. const upb_json_parsermethod *parser_method;
  7834. upb_pb_encoder *encoder;
  7835. /* Initialize encoder. */
  7836. h = upb_handlercache_get(frame->encoder_handlercache, payload_type);
  7837. encoder = upb_pb_encoder_create(p->arena, h, frame->stringsink.sink);
  7838. /* Initialize parser. */
  7839. parser_method = upb_json_codecache_get(frame->parser_codecache, payload_type);
  7840. upb_sink_reset(&frame->sink, h, encoder);
  7841. frame->parser =
  7842. upb_json_parser_create(p->arena, parser_method, p->symtab, frame->sink,
  7843. p->status, p->ignore_json_unknown);
  7844. }
  7845. static void json_parser_any_frame_free(upb_jsonparser_any_frame *frame) {
  7846. upb_handlercache_free(frame->encoder_handlercache);
  7847. upb_json_codecache_free(frame->parser_codecache);
  7848. upb_stringsink_uninit(&frame->stringsink);
  7849. }
  7850. static bool json_parser_any_frame_has_type_url(
  7851. upb_jsonparser_any_frame *frame) {
  7852. return frame->parser != NULL;
  7853. }
  7854. static bool json_parser_any_frame_has_value_before_type_url(
  7855. upb_jsonparser_any_frame *frame) {
  7856. return frame->before_type_url_start != frame->before_type_url_end;
  7857. }
  7858. static bool json_parser_any_frame_has_value_after_type_url(
  7859. upb_jsonparser_any_frame *frame) {
  7860. return frame->after_type_url_start != NULL;
  7861. }
  7862. static bool json_parser_any_frame_has_value(
  7863. upb_jsonparser_any_frame *frame) {
  7864. return json_parser_any_frame_has_value_before_type_url(frame) ||
  7865. json_parser_any_frame_has_value_after_type_url(frame);
  7866. }
  7867. static void json_parser_any_frame_set_before_type_url_end(
  7868. upb_jsonparser_any_frame *frame,
  7869. const char *ptr) {
  7870. if (frame->parser == NULL) {
  7871. frame->before_type_url_end = ptr;
  7872. }
  7873. }
  7874. static void json_parser_any_frame_set_after_type_url_start_once(
  7875. upb_jsonparser_any_frame *frame,
  7876. const char *ptr) {
  7877. if (json_parser_any_frame_has_type_url(frame) &&
  7878. frame->after_type_url_start == NULL) {
  7879. frame->after_type_url_start = ptr;
  7880. }
  7881. }
  7882. /* Used to signal that a capture has been suspended. */
  7883. static char suspend_capture;
  7884. static upb_selector_t getsel_for_handlertype(upb_json_parser *p,
  7885. upb_handlertype_t type) {
  7886. upb_selector_t sel;
  7887. bool ok = upb_handlers_getselector(p->top->f, type, &sel);
  7888. UPB_ASSUME(ok);
  7889. return sel;
  7890. }
  7891. static upb_selector_t parser_getsel(upb_json_parser *p) {
  7892. return getsel_for_handlertype(
  7893. p, upb_handlers_getprimitivehandlertype(p->top->f));
  7894. }
  7895. static bool check_stack(upb_json_parser *p) {
  7896. if ((p->top + 1) == p->limit) {
  7897. upb_status_seterrmsg(p->status, "Nesting too deep");
  7898. return false;
  7899. }
  7900. return true;
  7901. }
  7902. static void set_name_table(upb_json_parser *p, upb_jsonparser_frame *frame) {
  7903. upb_value v;
  7904. const upb_json_codecache *cache = p->method->cache;
  7905. bool ok;
  7906. const upb_json_parsermethod *method;
  7907. ok = upb_inttable_lookupptr(&cache->methods, frame->m, &v);
  7908. UPB_ASSUME(ok);
  7909. method = upb_value_getconstptr(v);
  7910. frame->name_table = &method->name_table;
  7911. }
  7912. /* There are GCC/Clang built-ins for overflow checking which we could start
  7913. * using if there was any performance benefit to it. */
  7914. static bool checked_add(size_t a, size_t b, size_t *c) {
  7915. if (SIZE_MAX - a < b) return false;
  7916. *c = a + b;
  7917. return true;
  7918. }
  7919. static size_t saturating_multiply(size_t a, size_t b) {
  7920. /* size_t is unsigned, so this is defined behavior even on overflow. */
  7921. size_t ret = a * b;
  7922. if (b != 0 && ret / b != a) {
  7923. ret = SIZE_MAX;
  7924. }
  7925. return ret;
  7926. }
  7927. /* Base64 decoding ************************************************************/
  7928. /* TODO(haberman): make this streaming. */
  7929. static const signed char b64table[] = {
  7930. -1, -1, -1, -1, -1, -1, -1, -1,
  7931. -1, -1, -1, -1, -1, -1, -1, -1,
  7932. -1, -1, -1, -1, -1, -1, -1, -1,
  7933. -1, -1, -1, -1, -1, -1, -1, -1,
  7934. -1, -1, -1, -1, -1, -1, -1, -1,
  7935. -1, -1, -1, 62/*+*/, -1, -1, -1, 63/*/ */,
  7936. 52/*0*/, 53/*1*/, 54/*2*/, 55/*3*/, 56/*4*/, 57/*5*/, 58/*6*/, 59/*7*/,
  7937. 60/*8*/, 61/*9*/, -1, -1, -1, -1, -1, -1,
  7938. -1, 0/*A*/, 1/*B*/, 2/*C*/, 3/*D*/, 4/*E*/, 5/*F*/, 6/*G*/,
  7939. 07/*H*/, 8/*I*/, 9/*J*/, 10/*K*/, 11/*L*/, 12/*M*/, 13/*N*/, 14/*O*/,
  7940. 15/*P*/, 16/*Q*/, 17/*R*/, 18/*S*/, 19/*T*/, 20/*U*/, 21/*V*/, 22/*W*/,
  7941. 23/*X*/, 24/*Y*/, 25/*Z*/, -1, -1, -1, -1, -1,
  7942. -1, 26/*a*/, 27/*b*/, 28/*c*/, 29/*d*/, 30/*e*/, 31/*f*/, 32/*g*/,
  7943. 33/*h*/, 34/*i*/, 35/*j*/, 36/*k*/, 37/*l*/, 38/*m*/, 39/*n*/, 40/*o*/,
  7944. 41/*p*/, 42/*q*/, 43/*r*/, 44/*s*/, 45/*t*/, 46/*u*/, 47/*v*/, 48/*w*/,
  7945. 49/*x*/, 50/*y*/, 51/*z*/, -1, -1, -1, -1, -1,
  7946. -1, -1, -1, -1, -1, -1, -1, -1,
  7947. -1, -1, -1, -1, -1, -1, -1, -1,
  7948. -1, -1, -1, -1, -1, -1, -1, -1,
  7949. -1, -1, -1, -1, -1, -1, -1, -1,
  7950. -1, -1, -1, -1, -1, -1, -1, -1,
  7951. -1, -1, -1, -1, -1, -1, -1, -1,
  7952. -1, -1, -1, -1, -1, -1, -1, -1,
  7953. -1, -1, -1, -1, -1, -1, -1, -1,
  7954. -1, -1, -1, -1, -1, -1, -1, -1,
  7955. -1, -1, -1, -1, -1, -1, -1, -1,
  7956. -1, -1, -1, -1, -1, -1, -1, -1,
  7957. -1, -1, -1, -1, -1, -1, -1, -1,
  7958. -1, -1, -1, -1, -1, -1, -1, -1,
  7959. -1, -1, -1, -1, -1, -1, -1, -1,
  7960. -1, -1, -1, -1, -1, -1, -1, -1,
  7961. -1, -1, -1, -1, -1, -1, -1, -1
  7962. };
  7963. /* Returns the table value sign-extended to 32 bits. Knowing that the upper
  7964. * bits will be 1 for unrecognized characters makes it easier to check for
  7965. * this error condition later (see below). */
  7966. int32_t b64lookup(unsigned char ch) { return b64table[ch]; }
  7967. /* Returns true if the given character is not a valid base64 character or
  7968. * padding. */
  7969. bool nonbase64(unsigned char ch) { return b64lookup(ch) == -1 && ch != '='; }
  7970. static bool base64_push(upb_json_parser *p, upb_selector_t sel, const char *ptr,
  7971. size_t len) {
  7972. const char *limit = ptr + len;
  7973. for (; ptr < limit; ptr += 4) {
  7974. uint32_t val;
  7975. char output[3];
  7976. if (limit - ptr < 4) {
  7977. upb_status_seterrf(p->status,
  7978. "Base64 input for bytes field not a multiple of 4: %s",
  7979. upb_fielddef_name(p->top->f));
  7980. return false;
  7981. }
  7982. val = b64lookup(ptr[0]) << 18 |
  7983. b64lookup(ptr[1]) << 12 |
  7984. b64lookup(ptr[2]) << 6 |
  7985. b64lookup(ptr[3]);
  7986. /* Test the upper bit; returns true if any of the characters returned -1. */
  7987. if (val & 0x80000000) {
  7988. goto otherchar;
  7989. }
  7990. output[0] = val >> 16;
  7991. output[1] = (val >> 8) & 0xff;
  7992. output[2] = val & 0xff;
  7993. upb_sink_putstring(p->top->sink, sel, output, 3, NULL);
  7994. }
  7995. return true;
  7996. otherchar:
  7997. if (nonbase64(ptr[0]) || nonbase64(ptr[1]) || nonbase64(ptr[2]) ||
  7998. nonbase64(ptr[3]) ) {
  7999. upb_status_seterrf(p->status,
  8000. "Non-base64 characters in bytes field: %s",
  8001. upb_fielddef_name(p->top->f));
  8002. return false;
  8003. } if (ptr[2] == '=') {
  8004. uint32_t val;
  8005. char output;
  8006. /* Last group contains only two input bytes, one output byte. */
  8007. if (ptr[0] == '=' || ptr[1] == '=' || ptr[3] != '=') {
  8008. goto badpadding;
  8009. }
  8010. val = b64lookup(ptr[0]) << 18 |
  8011. b64lookup(ptr[1]) << 12;
  8012. UPB_ASSERT(!(val & 0x80000000));
  8013. output = val >> 16;
  8014. upb_sink_putstring(p->top->sink, sel, &output, 1, NULL);
  8015. return true;
  8016. } else {
  8017. uint32_t val;
  8018. char output[2];
  8019. /* Last group contains only three input bytes, two output bytes. */
  8020. if (ptr[0] == '=' || ptr[1] == '=' || ptr[2] == '=') {
  8021. goto badpadding;
  8022. }
  8023. val = b64lookup(ptr[0]) << 18 |
  8024. b64lookup(ptr[1]) << 12 |
  8025. b64lookup(ptr[2]) << 6;
  8026. output[0] = val >> 16;
  8027. output[1] = (val >> 8) & 0xff;
  8028. upb_sink_putstring(p->top->sink, sel, output, 2, NULL);
  8029. return true;
  8030. }
  8031. badpadding:
  8032. upb_status_seterrf(p->status,
  8033. "Incorrect base64 padding for field: %s (%.*s)",
  8034. upb_fielddef_name(p->top->f),
  8035. 4, ptr);
  8036. return false;
  8037. }
  8038. /* Accumulate buffer **********************************************************/
  8039. /* Functionality for accumulating a buffer.
  8040. *
  8041. * Some parts of the parser need an entire value as a contiguous string. For
  8042. * example, to look up a member name in a hash table, or to turn a string into
  8043. * a number, the relevant library routines need the input string to be in
  8044. * contiguous memory, even if the value spanned two or more buffers in the
  8045. * input. These routines handle that.
  8046. *
  8047. * In the common case we can just point to the input buffer to get this
  8048. * contiguous string and avoid any actual copy. So we optimistically begin
  8049. * this way. But there are a few cases where we must instead copy into a
  8050. * separate buffer:
  8051. *
  8052. * 1. The string was not contiguous in the input (it spanned buffers).
  8053. *
  8054. * 2. The string included escape sequences that need to be interpreted to get
  8055. * the true value in a contiguous buffer. */
  8056. static void assert_accumulate_empty(upb_json_parser *p) {
  8057. UPB_ASSERT(p->accumulated == NULL);
  8058. UPB_ASSERT(p->accumulated_len == 0);
  8059. }
  8060. static void accumulate_clear(upb_json_parser *p) {
  8061. p->accumulated = NULL;
  8062. p->accumulated_len = 0;
  8063. }
  8064. /* Used internally by accumulate_append(). */
  8065. static bool accumulate_realloc(upb_json_parser *p, size_t need) {
  8066. void *mem;
  8067. size_t old_size = p->accumulate_buf_size;
  8068. size_t new_size = UPB_MAX(old_size, 128);
  8069. while (new_size < need) {
  8070. new_size = saturating_multiply(new_size, 2);
  8071. }
  8072. mem = upb_arena_realloc(p->arena, p->accumulate_buf, old_size, new_size);
  8073. if (!mem) {
  8074. upb_status_seterrmsg(p->status, "Out of memory allocating buffer.");
  8075. return false;
  8076. }
  8077. p->accumulate_buf = mem;
  8078. p->accumulate_buf_size = new_size;
  8079. return true;
  8080. }
  8081. /* Logically appends the given data to the append buffer.
  8082. * If "can_alias" is true, we will try to avoid actually copying, but the buffer
  8083. * must be valid until the next accumulate_append() call (if any). */
  8084. static bool accumulate_append(upb_json_parser *p, const char *buf, size_t len,
  8085. bool can_alias) {
  8086. size_t need;
  8087. if (!p->accumulated && can_alias) {
  8088. p->accumulated = buf;
  8089. p->accumulated_len = len;
  8090. return true;
  8091. }
  8092. if (!checked_add(p->accumulated_len, len, &need)) {
  8093. upb_status_seterrmsg(p->status, "Integer overflow.");
  8094. return false;
  8095. }
  8096. if (need > p->accumulate_buf_size && !accumulate_realloc(p, need)) {
  8097. return false;
  8098. }
  8099. if (p->accumulated != p->accumulate_buf) {
  8100. memcpy(p->accumulate_buf, p->accumulated, p->accumulated_len);
  8101. p->accumulated = p->accumulate_buf;
  8102. }
  8103. memcpy(p->accumulate_buf + p->accumulated_len, buf, len);
  8104. p->accumulated_len += len;
  8105. return true;
  8106. }
  8107. /* Returns a pointer to the data accumulated since the last accumulate_clear()
  8108. * call, and writes the length to *len. This with point either to the input
  8109. * buffer or a temporary accumulate buffer. */
  8110. static const char *accumulate_getptr(upb_json_parser *p, size_t *len) {
  8111. UPB_ASSERT(p->accumulated);
  8112. *len = p->accumulated_len;
  8113. return p->accumulated;
  8114. }
  8115. /* Mult-part text data ********************************************************/
  8116. /* When we have text data in the input, it can often come in multiple segments.
  8117. * For example, there may be some raw string data followed by an escape
  8118. * sequence. The two segments are processed with different logic. Also buffer
  8119. * seams in the input can cause multiple segments.
  8120. *
  8121. * As we see segments, there are two main cases for how we want to process them:
  8122. *
  8123. * 1. we want to push the captured input directly to string handlers.
  8124. *
  8125. * 2. we need to accumulate all the parts into a contiguous buffer for further
  8126. * processing (field name lookup, string->number conversion, etc). */
  8127. /* This is the set of states for p->multipart_state. */
  8128. enum {
  8129. /* We are not currently processing multipart data. */
  8130. MULTIPART_INACTIVE = 0,
  8131. /* We are processing multipart data by accumulating it into a contiguous
  8132. * buffer. */
  8133. MULTIPART_ACCUMULATE = 1,
  8134. /* We are processing multipart data by pushing each part directly to the
  8135. * current string handlers. */
  8136. MULTIPART_PUSHEAGERLY = 2
  8137. };
  8138. /* Start a multi-part text value where we accumulate the data for processing at
  8139. * the end. */
  8140. static void multipart_startaccum(upb_json_parser *p) {
  8141. assert_accumulate_empty(p);
  8142. UPB_ASSERT(p->multipart_state == MULTIPART_INACTIVE);
  8143. p->multipart_state = MULTIPART_ACCUMULATE;
  8144. }
  8145. /* Start a multi-part text value where we immediately push text data to a string
  8146. * value with the given selector. */
  8147. static void multipart_start(upb_json_parser *p, upb_selector_t sel) {
  8148. assert_accumulate_empty(p);
  8149. UPB_ASSERT(p->multipart_state == MULTIPART_INACTIVE);
  8150. p->multipart_state = MULTIPART_PUSHEAGERLY;
  8151. p->string_selector = sel;
  8152. }
  8153. static bool multipart_text(upb_json_parser *p, const char *buf, size_t len,
  8154. bool can_alias) {
  8155. switch (p->multipart_state) {
  8156. case MULTIPART_INACTIVE:
  8157. upb_status_seterrmsg(
  8158. p->status, "Internal error: unexpected state MULTIPART_INACTIVE");
  8159. return false;
  8160. case MULTIPART_ACCUMULATE:
  8161. if (!accumulate_append(p, buf, len, can_alias)) {
  8162. return false;
  8163. }
  8164. break;
  8165. case MULTIPART_PUSHEAGERLY: {
  8166. const upb_bufhandle *handle = can_alias ? p->handle : NULL;
  8167. upb_sink_putstring(p->top->sink, p->string_selector, buf, len, handle);
  8168. break;
  8169. }
  8170. }
  8171. return true;
  8172. }
  8173. /* Note: this invalidates the accumulate buffer! Call only after reading its
  8174. * contents. */
  8175. static void multipart_end(upb_json_parser *p) {
  8176. UPB_ASSERT(p->multipart_state != MULTIPART_INACTIVE);
  8177. p->multipart_state = MULTIPART_INACTIVE;
  8178. accumulate_clear(p);
  8179. }
  8180. /* Input capture **************************************************************/
  8181. /* Functionality for capturing a region of the input as text. Gracefully
  8182. * handles the case where a buffer seam occurs in the middle of the captured
  8183. * region. */
  8184. static void capture_begin(upb_json_parser *p, const char *ptr) {
  8185. UPB_ASSERT(p->multipart_state != MULTIPART_INACTIVE);
  8186. UPB_ASSERT(p->capture == NULL);
  8187. p->capture = ptr;
  8188. }
  8189. static bool capture_end(upb_json_parser *p, const char *ptr) {
  8190. UPB_ASSERT(p->capture);
  8191. if (multipart_text(p, p->capture, ptr - p->capture, true)) {
  8192. p->capture = NULL;
  8193. return true;
  8194. } else {
  8195. return false;
  8196. }
  8197. }
  8198. /* This is called at the end of each input buffer (ie. when we have hit a
  8199. * buffer seam). If we are in the middle of capturing the input, this
  8200. * processes the unprocessed capture region. */
  8201. static void capture_suspend(upb_json_parser *p, const char **ptr) {
  8202. if (!p->capture) return;
  8203. if (multipart_text(p, p->capture, *ptr - p->capture, false)) {
  8204. /* We use this as a signal that we were in the middle of capturing, and
  8205. * that capturing should resume at the beginning of the next buffer.
  8206. *
  8207. * We can't use *ptr here, because we have no guarantee that this pointer
  8208. * will be valid when we resume (if the underlying memory is freed, then
  8209. * using the pointer at all, even to compare to NULL, is likely undefined
  8210. * behavior). */
  8211. p->capture = &suspend_capture;
  8212. } else {
  8213. /* Need to back up the pointer to the beginning of the capture, since
  8214. * we were not able to actually preserve it. */
  8215. *ptr = p->capture;
  8216. }
  8217. }
  8218. static void capture_resume(upb_json_parser *p, const char *ptr) {
  8219. if (p->capture) {
  8220. UPB_ASSERT(p->capture == &suspend_capture);
  8221. p->capture = ptr;
  8222. }
  8223. }
  8224. /* Callbacks from the parser **************************************************/
  8225. /* These are the functions called directly from the parser itself.
  8226. * We define these in the same order as their declarations in the parser. */
  8227. static char escape_char(char in) {
  8228. switch (in) {
  8229. case 'r': return '\r';
  8230. case 't': return '\t';
  8231. case 'n': return '\n';
  8232. case 'f': return '\f';
  8233. case 'b': return '\b';
  8234. case '/': return '/';
  8235. case '"': return '"';
  8236. case '\\': return '\\';
  8237. default:
  8238. UPB_ASSERT(0);
  8239. return 'x';
  8240. }
  8241. }
  8242. static bool escape(upb_json_parser *p, const char *ptr) {
  8243. char ch = escape_char(*ptr);
  8244. return multipart_text(p, &ch, 1, false);
  8245. }
  8246. static void start_hex(upb_json_parser *p) {
  8247. p->digit = 0;
  8248. }
  8249. static void hexdigit(upb_json_parser *p, const char *ptr) {
  8250. char ch = *ptr;
  8251. p->digit <<= 4;
  8252. if (ch >= '0' && ch <= '9') {
  8253. p->digit += (ch - '0');
  8254. } else if (ch >= 'a' && ch <= 'f') {
  8255. p->digit += ((ch - 'a') + 10);
  8256. } else {
  8257. UPB_ASSERT(ch >= 'A' && ch <= 'F');
  8258. p->digit += ((ch - 'A') + 10);
  8259. }
  8260. }
  8261. static bool end_hex(upb_json_parser *p) {
  8262. uint32_t codepoint = p->digit;
  8263. /* emit the codepoint as UTF-8. */
  8264. char utf8[3]; /* support \u0000 -- \uFFFF -- need only three bytes. */
  8265. int length = 0;
  8266. if (codepoint <= 0x7F) {
  8267. utf8[0] = codepoint;
  8268. length = 1;
  8269. } else if (codepoint <= 0x07FF) {
  8270. utf8[1] = (codepoint & 0x3F) | 0x80;
  8271. codepoint >>= 6;
  8272. utf8[0] = (codepoint & 0x1F) | 0xC0;
  8273. length = 2;
  8274. } else /* codepoint <= 0xFFFF */ {
  8275. utf8[2] = (codepoint & 0x3F) | 0x80;
  8276. codepoint >>= 6;
  8277. utf8[1] = (codepoint & 0x3F) | 0x80;
  8278. codepoint >>= 6;
  8279. utf8[0] = (codepoint & 0x0F) | 0xE0;
  8280. length = 3;
  8281. }
  8282. /* TODO(haberman): Handle high surrogates: if codepoint is a high surrogate
  8283. * we have to wait for the next escape to get the full code point). */
  8284. return multipart_text(p, utf8, length, false);
  8285. }
  8286. static void start_text(upb_json_parser *p, const char *ptr) {
  8287. capture_begin(p, ptr);
  8288. }
  8289. static bool end_text(upb_json_parser *p, const char *ptr) {
  8290. return capture_end(p, ptr);
  8291. }
  8292. static bool start_number(upb_json_parser *p, const char *ptr) {
  8293. if (is_top_level(p)) {
  8294. if (is_number_wrapper_object(p)) {
  8295. start_wrapper_object(p);
  8296. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8297. start_value_object(p, VALUE_NUMBERVALUE);
  8298. } else {
  8299. return false;
  8300. }
  8301. } else if (does_number_wrapper_start(p)) {
  8302. if (!start_subobject(p)) {
  8303. return false;
  8304. }
  8305. start_wrapper_object(p);
  8306. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  8307. if (!start_subobject(p)) {
  8308. return false;
  8309. }
  8310. start_value_object(p, VALUE_NUMBERVALUE);
  8311. }
  8312. multipart_startaccum(p);
  8313. capture_begin(p, ptr);
  8314. return true;
  8315. }
  8316. static bool parse_number(upb_json_parser *p, bool is_quoted);
  8317. static bool end_number_nontop(upb_json_parser *p, const char *ptr) {
  8318. if (!capture_end(p, ptr)) {
  8319. return false;
  8320. }
  8321. if (p->top->f == NULL) {
  8322. multipart_end(p);
  8323. return true;
  8324. }
  8325. return parse_number(p, false);
  8326. }
  8327. static bool end_number(upb_json_parser *p, const char *ptr) {
  8328. if (!end_number_nontop(p, ptr)) {
  8329. return false;
  8330. }
  8331. if (does_number_wrapper_end(p)) {
  8332. end_wrapper_object(p);
  8333. if (!is_top_level(p)) {
  8334. end_subobject(p);
  8335. }
  8336. return true;
  8337. }
  8338. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8339. end_value_object(p);
  8340. if (!is_top_level(p)) {
  8341. end_subobject(p);
  8342. }
  8343. return true;
  8344. }
  8345. return true;
  8346. }
  8347. /* |buf| is NULL-terminated. |buf| itself will never include quotes;
  8348. * |is_quoted| tells us whether this text originally appeared inside quotes. */
  8349. static bool parse_number_from_buffer(upb_json_parser *p, const char *buf,
  8350. bool is_quoted) {
  8351. size_t len = strlen(buf);
  8352. const char *bufend = buf + len;
  8353. char *end;
  8354. upb_fieldtype_t type = upb_fielddef_type(p->top->f);
  8355. double val;
  8356. double dummy;
  8357. double inf = UPB_INFINITY;
  8358. errno = 0;
  8359. if (len == 0 || buf[0] == ' ') {
  8360. return false;
  8361. }
  8362. /* For integer types, first try parsing with integer-specific routines.
  8363. * If these succeed, they will be more accurate for int64/uint64 than
  8364. * strtod().
  8365. */
  8366. switch (type) {
  8367. case UPB_TYPE_ENUM:
  8368. case UPB_TYPE_INT32: {
  8369. long val = strtol(buf, &end, 0);
  8370. if (errno == ERANGE || end != bufend) {
  8371. break;
  8372. } else if (val > INT32_MAX || val < INT32_MIN) {
  8373. return false;
  8374. } else {
  8375. upb_sink_putint32(p->top->sink, parser_getsel(p), (int32_t)val);
  8376. return true;
  8377. }
  8378. }
  8379. case UPB_TYPE_UINT32: {
  8380. unsigned long val = strtoul(buf, &end, 0);
  8381. if (end != bufend) {
  8382. break;
  8383. } else if (val > UINT32_MAX || errno == ERANGE) {
  8384. return false;
  8385. } else {
  8386. upb_sink_putuint32(p->top->sink, parser_getsel(p), (uint32_t)val);
  8387. return true;
  8388. }
  8389. }
  8390. /* XXX: We can't handle [u]int64 properly on 32-bit machines because
  8391. * strto[u]ll isn't in C89. */
  8392. case UPB_TYPE_INT64: {
  8393. long val = strtol(buf, &end, 0);
  8394. if (errno == ERANGE || end != bufend) {
  8395. break;
  8396. } else {
  8397. upb_sink_putint64(p->top->sink, parser_getsel(p), val);
  8398. return true;
  8399. }
  8400. }
  8401. case UPB_TYPE_UINT64: {
  8402. unsigned long val = strtoul(p->accumulated, &end, 0);
  8403. if (end != bufend) {
  8404. break;
  8405. } else if (errno == ERANGE) {
  8406. return false;
  8407. } else {
  8408. upb_sink_putuint64(p->top->sink, parser_getsel(p), val);
  8409. return true;
  8410. }
  8411. }
  8412. default:
  8413. break;
  8414. }
  8415. if (type != UPB_TYPE_DOUBLE && type != UPB_TYPE_FLOAT && is_quoted) {
  8416. /* Quoted numbers for integer types are not allowed to be in double form. */
  8417. return false;
  8418. }
  8419. if (len == strlen("Infinity") && strcmp(buf, "Infinity") == 0) {
  8420. /* C89 does not have an INFINITY macro. */
  8421. val = inf;
  8422. } else if (len == strlen("-Infinity") && strcmp(buf, "-Infinity") == 0) {
  8423. val = -inf;
  8424. } else {
  8425. val = strtod(buf, &end);
  8426. if (errno == ERANGE || end != bufend) {
  8427. return false;
  8428. }
  8429. }
  8430. switch (type) {
  8431. #define CASE(capitaltype, smalltype, ctype, min, max) \
  8432. case UPB_TYPE_ ## capitaltype: { \
  8433. if (modf(val, &dummy) != 0 || val > max || val < min) { \
  8434. return false; \
  8435. } else { \
  8436. upb_sink_put ## smalltype(p->top->sink, parser_getsel(p), \
  8437. (ctype)val); \
  8438. return true; \
  8439. } \
  8440. break; \
  8441. }
  8442. case UPB_TYPE_ENUM:
  8443. CASE(INT32, int32, int32_t, INT32_MIN, INT32_MAX);
  8444. CASE(INT64, int64, int64_t, INT64_MIN, INT64_MAX);
  8445. CASE(UINT32, uint32, uint32_t, 0, UINT32_MAX);
  8446. CASE(UINT64, uint64, uint64_t, 0, UINT64_MAX);
  8447. #undef CASE
  8448. case UPB_TYPE_DOUBLE:
  8449. upb_sink_putdouble(p->top->sink, parser_getsel(p), val);
  8450. return true;
  8451. case UPB_TYPE_FLOAT:
  8452. if ((val > FLT_MAX || val < -FLT_MAX) && val != inf && val != -inf) {
  8453. return false;
  8454. } else {
  8455. upb_sink_putfloat(p->top->sink, parser_getsel(p), val);
  8456. return true;
  8457. }
  8458. default:
  8459. return false;
  8460. }
  8461. }
  8462. static bool parse_number(upb_json_parser *p, bool is_quoted) {
  8463. size_t len;
  8464. const char *buf;
  8465. /* strtol() and friends unfortunately do not support specifying the length of
  8466. * the input string, so we need to force a copy into a NULL-terminated buffer. */
  8467. if (!multipart_text(p, "\0", 1, false)) {
  8468. return false;
  8469. }
  8470. buf = accumulate_getptr(p, &len);
  8471. if (parse_number_from_buffer(p, buf, is_quoted)) {
  8472. multipart_end(p);
  8473. return true;
  8474. } else {
  8475. upb_status_seterrf(p->status, "error parsing number: %s", buf);
  8476. multipart_end(p);
  8477. return false;
  8478. }
  8479. }
  8480. static bool parser_putbool(upb_json_parser *p, bool val) {
  8481. bool ok;
  8482. if (p->top->f == NULL) {
  8483. return true;
  8484. }
  8485. if (upb_fielddef_type(p->top->f) != UPB_TYPE_BOOL) {
  8486. upb_status_seterrf(p->status,
  8487. "Boolean value specified for non-bool field: %s",
  8488. upb_fielddef_name(p->top->f));
  8489. return false;
  8490. }
  8491. ok = upb_sink_putbool(p->top->sink, parser_getsel(p), val);
  8492. UPB_ASSERT(ok);
  8493. return true;
  8494. }
  8495. static bool end_bool(upb_json_parser *p, bool val) {
  8496. if (is_top_level(p)) {
  8497. if (is_wellknown_msg(p, UPB_WELLKNOWN_BOOLVALUE)) {
  8498. start_wrapper_object(p);
  8499. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8500. start_value_object(p, VALUE_BOOLVALUE);
  8501. } else {
  8502. return false;
  8503. }
  8504. } else if (is_wellknown_field(p, UPB_WELLKNOWN_BOOLVALUE)) {
  8505. if (!start_subobject(p)) {
  8506. return false;
  8507. }
  8508. start_wrapper_object(p);
  8509. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  8510. if (!start_subobject(p)) {
  8511. return false;
  8512. }
  8513. start_value_object(p, VALUE_BOOLVALUE);
  8514. }
  8515. if (p->top->is_unknown_field) {
  8516. return true;
  8517. }
  8518. if (!parser_putbool(p, val)) {
  8519. return false;
  8520. }
  8521. if (is_wellknown_msg(p, UPB_WELLKNOWN_BOOLVALUE)) {
  8522. end_wrapper_object(p);
  8523. if (!is_top_level(p)) {
  8524. end_subobject(p);
  8525. }
  8526. return true;
  8527. }
  8528. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8529. end_value_object(p);
  8530. if (!is_top_level(p)) {
  8531. end_subobject(p);
  8532. }
  8533. return true;
  8534. }
  8535. return true;
  8536. }
  8537. static bool end_null(upb_json_parser *p) {
  8538. const char *zero_ptr = "0";
  8539. if (is_top_level(p)) {
  8540. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8541. start_value_object(p, VALUE_NULLVALUE);
  8542. } else {
  8543. return true;
  8544. }
  8545. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  8546. if (!start_subobject(p)) {
  8547. return false;
  8548. }
  8549. start_value_object(p, VALUE_NULLVALUE);
  8550. } else {
  8551. return true;
  8552. }
  8553. /* Fill null_value field. */
  8554. multipart_startaccum(p);
  8555. capture_begin(p, zero_ptr);
  8556. capture_end(p, zero_ptr + 1);
  8557. parse_number(p, false);
  8558. end_value_object(p);
  8559. if (!is_top_level(p)) {
  8560. end_subobject(p);
  8561. }
  8562. return true;
  8563. }
  8564. static bool start_any_stringval(upb_json_parser *p) {
  8565. multipart_startaccum(p);
  8566. return true;
  8567. }
  8568. static bool start_stringval(upb_json_parser *p) {
  8569. if (is_top_level(p)) {
  8570. if (is_string_wrapper_object(p) ||
  8571. is_number_wrapper_object(p)) {
  8572. start_wrapper_object(p);
  8573. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_FIELDMASK)) {
  8574. start_fieldmask_object(p);
  8575. return true;
  8576. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_TIMESTAMP) ||
  8577. is_wellknown_msg(p, UPB_WELLKNOWN_DURATION)) {
  8578. start_object(p);
  8579. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8580. start_value_object(p, VALUE_STRINGVALUE);
  8581. } else {
  8582. return false;
  8583. }
  8584. } else if (does_string_wrapper_start(p) ||
  8585. does_number_wrapper_start(p)) {
  8586. if (!start_subobject(p)) {
  8587. return false;
  8588. }
  8589. start_wrapper_object(p);
  8590. } else if (does_fieldmask_start(p)) {
  8591. if (!start_subobject(p)) {
  8592. return false;
  8593. }
  8594. start_fieldmask_object(p);
  8595. return true;
  8596. } else if (is_wellknown_field(p, UPB_WELLKNOWN_TIMESTAMP) ||
  8597. is_wellknown_field(p, UPB_WELLKNOWN_DURATION)) {
  8598. if (!start_subobject(p)) {
  8599. return false;
  8600. }
  8601. start_object(p);
  8602. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  8603. if (!start_subobject(p)) {
  8604. return false;
  8605. }
  8606. start_value_object(p, VALUE_STRINGVALUE);
  8607. }
  8608. if (p->top->f == NULL) {
  8609. multipart_startaccum(p);
  8610. return true;
  8611. }
  8612. if (p->top->is_any) {
  8613. return start_any_stringval(p);
  8614. }
  8615. if (upb_fielddef_isstring(p->top->f)) {
  8616. upb_jsonparser_frame *inner;
  8617. upb_selector_t sel;
  8618. if (!check_stack(p)) return false;
  8619. /* Start a new parser frame: parser frames correspond one-to-one with
  8620. * handler frames, and string events occur in a sub-frame. */
  8621. inner = start_jsonparser_frame(p);
  8622. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  8623. upb_sink_startstr(p->top->sink, sel, 0, &inner->sink);
  8624. inner->m = p->top->m;
  8625. inner->f = p->top->f;
  8626. p->top = inner;
  8627. if (upb_fielddef_type(p->top->f) == UPB_TYPE_STRING) {
  8628. /* For STRING fields we push data directly to the handlers as it is
  8629. * parsed. We don't do this yet for BYTES fields, because our base64
  8630. * decoder is not streaming.
  8631. *
  8632. * TODO(haberman): make base64 decoding streaming also. */
  8633. multipart_start(p, getsel_for_handlertype(p, UPB_HANDLER_STRING));
  8634. return true;
  8635. } else {
  8636. multipart_startaccum(p);
  8637. return true;
  8638. }
  8639. } else if (upb_fielddef_type(p->top->f) != UPB_TYPE_BOOL &&
  8640. upb_fielddef_type(p->top->f) != UPB_TYPE_MESSAGE) {
  8641. /* No need to push a frame -- numeric values in quotes remain in the
  8642. * current parser frame. These values must accmulate so we can convert
  8643. * them all at once at the end. */
  8644. multipart_startaccum(p);
  8645. return true;
  8646. } else {
  8647. upb_status_seterrf(p->status,
  8648. "String specified for bool or submessage field: %s",
  8649. upb_fielddef_name(p->top->f));
  8650. return false;
  8651. }
  8652. }
  8653. static bool end_any_stringval(upb_json_parser *p) {
  8654. size_t len;
  8655. const char *buf = accumulate_getptr(p, &len);
  8656. /* Set type_url */
  8657. upb_selector_t sel;
  8658. upb_jsonparser_frame *inner;
  8659. if (!check_stack(p)) return false;
  8660. inner = p->top + 1;
  8661. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  8662. upb_sink_startstr(p->top->sink, sel, 0, &inner->sink);
  8663. sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
  8664. upb_sink_putstring(inner->sink, sel, buf, len, NULL);
  8665. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  8666. upb_sink_endstr(inner->sink, sel);
  8667. multipart_end(p);
  8668. /* Resolve type url */
  8669. if (strncmp(buf, "type.googleapis.com/", 20) == 0 && len > 20) {
  8670. const upb_msgdef *payload_type = NULL;
  8671. buf += 20;
  8672. len -= 20;
  8673. payload_type = upb_symtab_lookupmsg2(p->symtab, buf, len);
  8674. if (payload_type == NULL) {
  8675. upb_status_seterrf(
  8676. p->status, "Cannot find packed type: %.*s\n", (int)len, buf);
  8677. return false;
  8678. }
  8679. json_parser_any_frame_set_payload_type(p, p->top->any_frame, payload_type);
  8680. return true;
  8681. } else {
  8682. upb_status_seterrf(
  8683. p->status, "Invalid type url: %.*s\n", (int)len, buf);
  8684. return false;
  8685. }
  8686. }
  8687. static bool end_stringval_nontop(upb_json_parser *p) {
  8688. bool ok = true;
  8689. if (is_wellknown_msg(p, UPB_WELLKNOWN_TIMESTAMP) ||
  8690. is_wellknown_msg(p, UPB_WELLKNOWN_DURATION)) {
  8691. multipart_end(p);
  8692. return true;
  8693. }
  8694. if (p->top->f == NULL) {
  8695. multipart_end(p);
  8696. return true;
  8697. }
  8698. if (p->top->is_any) {
  8699. return end_any_stringval(p);
  8700. }
  8701. switch (upb_fielddef_type(p->top->f)) {
  8702. case UPB_TYPE_BYTES:
  8703. if (!base64_push(p, getsel_for_handlertype(p, UPB_HANDLER_STRING),
  8704. p->accumulated, p->accumulated_len)) {
  8705. return false;
  8706. }
  8707. /* Fall through. */
  8708. case UPB_TYPE_STRING: {
  8709. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  8710. upb_sink_endstr(p->top->sink, sel);
  8711. p->top--;
  8712. break;
  8713. }
  8714. case UPB_TYPE_ENUM: {
  8715. /* Resolve enum symbolic name to integer value. */
  8716. const upb_enumdef *enumdef = upb_fielddef_enumsubdef(p->top->f);
  8717. size_t len;
  8718. const char *buf = accumulate_getptr(p, &len);
  8719. int32_t int_val = 0;
  8720. ok = upb_enumdef_ntoi(enumdef, buf, len, &int_val);
  8721. if (ok) {
  8722. upb_selector_t sel = parser_getsel(p);
  8723. upb_sink_putint32(p->top->sink, sel, int_val);
  8724. } else {
  8725. upb_status_seterrf(p->status, "Enum value unknown: '%.*s'", len, buf);
  8726. }
  8727. break;
  8728. }
  8729. case UPB_TYPE_INT32:
  8730. case UPB_TYPE_INT64:
  8731. case UPB_TYPE_UINT32:
  8732. case UPB_TYPE_UINT64:
  8733. case UPB_TYPE_DOUBLE:
  8734. case UPB_TYPE_FLOAT:
  8735. ok = parse_number(p, true);
  8736. break;
  8737. default:
  8738. UPB_ASSERT(false);
  8739. upb_status_seterrmsg(p->status, "Internal error in JSON decoder");
  8740. ok = false;
  8741. break;
  8742. }
  8743. multipart_end(p);
  8744. return ok;
  8745. }
  8746. static bool end_stringval(upb_json_parser *p) {
  8747. /* FieldMask's stringvals have been ended when handling them. Only need to
  8748. * close FieldMask here.*/
  8749. if (does_fieldmask_end(p)) {
  8750. end_fieldmask_object(p);
  8751. if (!is_top_level(p)) {
  8752. end_subobject(p);
  8753. }
  8754. return true;
  8755. }
  8756. if (!end_stringval_nontop(p)) {
  8757. return false;
  8758. }
  8759. if (does_string_wrapper_end(p) ||
  8760. does_number_wrapper_end(p)) {
  8761. end_wrapper_object(p);
  8762. if (!is_top_level(p)) {
  8763. end_subobject(p);
  8764. }
  8765. return true;
  8766. }
  8767. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8768. end_value_object(p);
  8769. if (!is_top_level(p)) {
  8770. end_subobject(p);
  8771. }
  8772. return true;
  8773. }
  8774. if (is_wellknown_msg(p, UPB_WELLKNOWN_TIMESTAMP) ||
  8775. is_wellknown_msg(p, UPB_WELLKNOWN_DURATION) ||
  8776. is_wellknown_msg(p, UPB_WELLKNOWN_FIELDMASK)) {
  8777. end_object(p);
  8778. if (!is_top_level(p)) {
  8779. end_subobject(p);
  8780. }
  8781. return true;
  8782. }
  8783. return true;
  8784. }
  8785. static void start_duration_base(upb_json_parser *p, const char *ptr) {
  8786. capture_begin(p, ptr);
  8787. }
  8788. static bool end_duration_base(upb_json_parser *p, const char *ptr) {
  8789. size_t len;
  8790. const char *buf;
  8791. char seconds_buf[14];
  8792. char nanos_buf[12];
  8793. char *end;
  8794. int64_t seconds = 0;
  8795. int32_t nanos = 0;
  8796. double val = 0.0;
  8797. const char *seconds_membername = "seconds";
  8798. const char *nanos_membername = "nanos";
  8799. size_t fraction_start;
  8800. if (!capture_end(p, ptr)) {
  8801. return false;
  8802. }
  8803. buf = accumulate_getptr(p, &len);
  8804. memset(seconds_buf, 0, 14);
  8805. memset(nanos_buf, 0, 12);
  8806. /* Find out base end. The maximus duration is 315576000000, which cannot be
  8807. * represented by double without losing precision. Thus, we need to handle
  8808. * fraction and base separately. */
  8809. for (fraction_start = 0; fraction_start < len && buf[fraction_start] != '.';
  8810. fraction_start++);
  8811. /* Parse base */
  8812. memcpy(seconds_buf, buf, fraction_start);
  8813. seconds = strtol(seconds_buf, &end, 10);
  8814. if (errno == ERANGE || end != seconds_buf + fraction_start) {
  8815. upb_status_seterrf(p->status, "error parsing duration: %s",
  8816. seconds_buf);
  8817. return false;
  8818. }
  8819. if (seconds > 315576000000) {
  8820. upb_status_seterrf(p->status, "error parsing duration: "
  8821. "maximum acceptable value is "
  8822. "315576000000");
  8823. return false;
  8824. }
  8825. if (seconds < -315576000000) {
  8826. upb_status_seterrf(p->status, "error parsing duration: "
  8827. "minimum acceptable value is "
  8828. "-315576000000");
  8829. return false;
  8830. }
  8831. /* Parse fraction */
  8832. nanos_buf[0] = '0';
  8833. memcpy(nanos_buf + 1, buf + fraction_start, len - fraction_start);
  8834. val = strtod(nanos_buf, &end);
  8835. if (errno == ERANGE || end != nanos_buf + len - fraction_start + 1) {
  8836. upb_status_seterrf(p->status, "error parsing duration: %s",
  8837. nanos_buf);
  8838. return false;
  8839. }
  8840. nanos = val * 1000000000;
  8841. if (seconds < 0) nanos = -nanos;
  8842. /* Clean up buffer */
  8843. multipart_end(p);
  8844. /* Set seconds */
  8845. start_member(p);
  8846. capture_begin(p, seconds_membername);
  8847. capture_end(p, seconds_membername + 7);
  8848. end_membername(p);
  8849. upb_sink_putint64(p->top->sink, parser_getsel(p), seconds);
  8850. end_member(p);
  8851. /* Set nanos */
  8852. start_member(p);
  8853. capture_begin(p, nanos_membername);
  8854. capture_end(p, nanos_membername + 5);
  8855. end_membername(p);
  8856. upb_sink_putint32(p->top->sink, parser_getsel(p), nanos);
  8857. end_member(p);
  8858. /* Continue previous arena */
  8859. multipart_startaccum(p);
  8860. return true;
  8861. }
  8862. static int parse_timestamp_number(upb_json_parser *p) {
  8863. size_t len;
  8864. const char *buf;
  8865. int val;
  8866. /* atoi() and friends unfortunately do not support specifying the length of
  8867. * the input string, so we need to force a copy into a NULL-terminated buffer. */
  8868. multipart_text(p, "\0", 1, false);
  8869. buf = accumulate_getptr(p, &len);
  8870. val = atoi(buf);
  8871. multipart_end(p);
  8872. multipart_startaccum(p);
  8873. return val;
  8874. }
  8875. static void start_year(upb_json_parser *p, const char *ptr) {
  8876. capture_begin(p, ptr);
  8877. }
  8878. static bool end_year(upb_json_parser *p, const char *ptr) {
  8879. if (!capture_end(p, ptr)) {
  8880. return false;
  8881. }
  8882. p->tm.tm_year = parse_timestamp_number(p) - 1900;
  8883. return true;
  8884. }
  8885. static void start_month(upb_json_parser *p, const char *ptr) {
  8886. capture_begin(p, ptr);
  8887. }
  8888. static bool end_month(upb_json_parser *p, const char *ptr) {
  8889. if (!capture_end(p, ptr)) {
  8890. return false;
  8891. }
  8892. p->tm.tm_mon = parse_timestamp_number(p) - 1;
  8893. return true;
  8894. }
  8895. static void start_day(upb_json_parser *p, const char *ptr) {
  8896. capture_begin(p, ptr);
  8897. }
  8898. static bool end_day(upb_json_parser *p, const char *ptr) {
  8899. if (!capture_end(p, ptr)) {
  8900. return false;
  8901. }
  8902. p->tm.tm_mday = parse_timestamp_number(p);
  8903. return true;
  8904. }
  8905. static void start_hour(upb_json_parser *p, const char *ptr) {
  8906. capture_begin(p, ptr);
  8907. }
  8908. static bool end_hour(upb_json_parser *p, const char *ptr) {
  8909. if (!capture_end(p, ptr)) {
  8910. return false;
  8911. }
  8912. p->tm.tm_hour = parse_timestamp_number(p);
  8913. return true;
  8914. }
  8915. static void start_minute(upb_json_parser *p, const char *ptr) {
  8916. capture_begin(p, ptr);
  8917. }
  8918. static bool end_minute(upb_json_parser *p, const char *ptr) {
  8919. if (!capture_end(p, ptr)) {
  8920. return false;
  8921. }
  8922. p->tm.tm_min = parse_timestamp_number(p);
  8923. return true;
  8924. }
  8925. static void start_second(upb_json_parser *p, const char *ptr) {
  8926. capture_begin(p, ptr);
  8927. }
  8928. static bool end_second(upb_json_parser *p, const char *ptr) {
  8929. if (!capture_end(p, ptr)) {
  8930. return false;
  8931. }
  8932. p->tm.tm_sec = parse_timestamp_number(p);
  8933. return true;
  8934. }
  8935. static void start_timestamp_base(upb_json_parser *p) {
  8936. memset(&p->tm, 0, sizeof(struct tm));
  8937. }
  8938. static void start_timestamp_fraction(upb_json_parser *p, const char *ptr) {
  8939. capture_begin(p, ptr);
  8940. }
  8941. static bool end_timestamp_fraction(upb_json_parser *p, const char *ptr) {
  8942. size_t len;
  8943. const char *buf;
  8944. char nanos_buf[12];
  8945. char *end;
  8946. double val = 0.0;
  8947. int32_t nanos;
  8948. const char *nanos_membername = "nanos";
  8949. memset(nanos_buf, 0, 12);
  8950. if (!capture_end(p, ptr)) {
  8951. return false;
  8952. }
  8953. buf = accumulate_getptr(p, &len);
  8954. if (len > 10) {
  8955. upb_status_seterrf(p->status,
  8956. "error parsing timestamp: at most 9-digit fraction.");
  8957. return false;
  8958. }
  8959. /* Parse nanos */
  8960. nanos_buf[0] = '0';
  8961. memcpy(nanos_buf + 1, buf, len);
  8962. val = strtod(nanos_buf, &end);
  8963. if (errno == ERANGE || end != nanos_buf + len + 1) {
  8964. upb_status_seterrf(p->status, "error parsing timestamp nanos: %s",
  8965. nanos_buf);
  8966. return false;
  8967. }
  8968. nanos = val * 1000000000;
  8969. /* Clean up previous environment */
  8970. multipart_end(p);
  8971. /* Set nanos */
  8972. start_member(p);
  8973. capture_begin(p, nanos_membername);
  8974. capture_end(p, nanos_membername + 5);
  8975. end_membername(p);
  8976. upb_sink_putint32(p->top->sink, parser_getsel(p), nanos);
  8977. end_member(p);
  8978. /* Continue previous environment */
  8979. multipart_startaccum(p);
  8980. return true;
  8981. }
  8982. static void start_timestamp_zone(upb_json_parser *p, const char *ptr) {
  8983. capture_begin(p, ptr);
  8984. }
  8985. static int div_round_up2(int n, int d) {
  8986. return (n + d - 1) / d;
  8987. }
  8988. /* epoch_days(1970, 1, 1) == 1970-01-01 == 0. */
  8989. static int epoch_days(int year, int month, int day) {
  8990. static const uint16_t month_yday[12] = {0, 31, 59, 90, 120, 151,
  8991. 181, 212, 243, 273, 304, 334};
  8992. int febs_since_0 = month > 2 ? year + 1 : year;
  8993. int leap_days_since_0 = div_round_up2(febs_since_0, 4) -
  8994. div_round_up2(febs_since_0, 100) +
  8995. div_round_up2(febs_since_0, 400);
  8996. int days_since_0 =
  8997. 365 * year + month_yday[month - 1] + (day - 1) + leap_days_since_0;
  8998. /* Convert from 0-epoch (0001-01-01 BC) to Unix Epoch (1970-01-01 AD).
  8999. * Since the "BC" system does not have a year zero, 1 BC == year zero. */
  9000. return days_since_0 - 719528;
  9001. }
  9002. static int64_t upb_timegm(const struct tm *tp) {
  9003. int64_t ret = epoch_days(tp->tm_year + 1900, tp->tm_mon + 1, tp->tm_mday);
  9004. ret = (ret * 24) + tp->tm_hour;
  9005. ret = (ret * 60) + tp->tm_min;
  9006. ret = (ret * 60) + tp->tm_sec;
  9007. return ret;
  9008. }
  9009. static bool end_timestamp_zone(upb_json_parser *p, const char *ptr) {
  9010. size_t len;
  9011. const char *buf;
  9012. int hours;
  9013. int64_t seconds;
  9014. const char *seconds_membername = "seconds";
  9015. if (!capture_end(p, ptr)) {
  9016. return false;
  9017. }
  9018. buf = accumulate_getptr(p, &len);
  9019. if (buf[0] != 'Z') {
  9020. if (sscanf(buf + 1, "%2d:00", &hours) != 1) {
  9021. upb_status_seterrf(p->status, "error parsing timestamp offset");
  9022. return false;
  9023. }
  9024. if (buf[0] == '+') {
  9025. hours = -hours;
  9026. }
  9027. p->tm.tm_hour += hours;
  9028. }
  9029. /* Normalize tm */
  9030. seconds = upb_timegm(&p->tm);
  9031. /* Check timestamp boundary */
  9032. if (seconds < -62135596800) {
  9033. upb_status_seterrf(p->status, "error parsing timestamp: "
  9034. "minimum acceptable value is "
  9035. "0001-01-01T00:00:00Z");
  9036. return false;
  9037. }
  9038. /* Clean up previous environment */
  9039. multipart_end(p);
  9040. /* Set seconds */
  9041. start_member(p);
  9042. capture_begin(p, seconds_membername);
  9043. capture_end(p, seconds_membername + 7);
  9044. end_membername(p);
  9045. upb_sink_putint64(p->top->sink, parser_getsel(p), seconds);
  9046. end_member(p);
  9047. /* Continue previous environment */
  9048. multipart_startaccum(p);
  9049. return true;
  9050. }
  9051. static void start_fieldmask_path_text(upb_json_parser *p, const char *ptr) {
  9052. capture_begin(p, ptr);
  9053. }
  9054. static bool end_fieldmask_path_text(upb_json_parser *p, const char *ptr) {
  9055. return capture_end(p, ptr);
  9056. }
  9057. static bool start_fieldmask_path(upb_json_parser *p) {
  9058. upb_jsonparser_frame *inner;
  9059. upb_selector_t sel;
  9060. if (!check_stack(p)) return false;
  9061. /* Start a new parser frame: parser frames correspond one-to-one with
  9062. * handler frames, and string events occur in a sub-frame. */
  9063. inner = start_jsonparser_frame(p);
  9064. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  9065. upb_sink_startstr(p->top->sink, sel, 0, &inner->sink);
  9066. inner->m = p->top->m;
  9067. inner->f = p->top->f;
  9068. p->top = inner;
  9069. multipart_startaccum(p);
  9070. return true;
  9071. }
  9072. static bool lower_camel_push(
  9073. upb_json_parser *p, upb_selector_t sel, const char *ptr, size_t len) {
  9074. const char *limit = ptr + len;
  9075. bool first = true;
  9076. for (;ptr < limit; ptr++) {
  9077. if (*ptr >= 'A' && *ptr <= 'Z' && !first) {
  9078. char lower = tolower(*ptr);
  9079. upb_sink_putstring(p->top->sink, sel, "_", 1, NULL);
  9080. upb_sink_putstring(p->top->sink, sel, &lower, 1, NULL);
  9081. } else {
  9082. upb_sink_putstring(p->top->sink, sel, ptr, 1, NULL);
  9083. }
  9084. first = false;
  9085. }
  9086. return true;
  9087. }
  9088. static bool end_fieldmask_path(upb_json_parser *p) {
  9089. upb_selector_t sel;
  9090. if (!lower_camel_push(
  9091. p, getsel_for_handlertype(p, UPB_HANDLER_STRING),
  9092. p->accumulated, p->accumulated_len)) {
  9093. return false;
  9094. }
  9095. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  9096. upb_sink_endstr(p->top->sink, sel);
  9097. p->top--;
  9098. multipart_end(p);
  9099. return true;
  9100. }
  9101. static void start_member(upb_json_parser *p) {
  9102. UPB_ASSERT(!p->top->f);
  9103. multipart_startaccum(p);
  9104. }
  9105. /* Helper: invoked during parse_mapentry() to emit the mapentry message's key
  9106. * field based on the current contents of the accumulate buffer. */
  9107. static bool parse_mapentry_key(upb_json_parser *p) {
  9108. size_t len;
  9109. const char *buf = accumulate_getptr(p, &len);
  9110. /* Emit the key field. We do a bit of ad-hoc parsing here because the
  9111. * parser state machine has already decided that this is a string field
  9112. * name, and we are reinterpreting it as some arbitrary key type. In
  9113. * particular, integer and bool keys are quoted, so we need to parse the
  9114. * quoted string contents here. */
  9115. p->top->f = upb_msgdef_itof(p->top->m, UPB_MAPENTRY_KEY);
  9116. if (p->top->f == NULL) {
  9117. upb_status_seterrmsg(p->status, "mapentry message has no key");
  9118. return false;
  9119. }
  9120. switch (upb_fielddef_type(p->top->f)) {
  9121. case UPB_TYPE_INT32:
  9122. case UPB_TYPE_INT64:
  9123. case UPB_TYPE_UINT32:
  9124. case UPB_TYPE_UINT64:
  9125. /* Invoke end_number. The accum buffer has the number's text already. */
  9126. if (!parse_number(p, true)) {
  9127. return false;
  9128. }
  9129. break;
  9130. case UPB_TYPE_BOOL:
  9131. if (len == 4 && !strncmp(buf, "true", 4)) {
  9132. if (!parser_putbool(p, true)) {
  9133. return false;
  9134. }
  9135. } else if (len == 5 && !strncmp(buf, "false", 5)) {
  9136. if (!parser_putbool(p, false)) {
  9137. return false;
  9138. }
  9139. } else {
  9140. upb_status_seterrmsg(p->status,
  9141. "Map bool key not 'true' or 'false'");
  9142. return false;
  9143. }
  9144. multipart_end(p);
  9145. break;
  9146. case UPB_TYPE_STRING:
  9147. case UPB_TYPE_BYTES: {
  9148. upb_sink subsink;
  9149. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  9150. upb_sink_startstr(p->top->sink, sel, len, &subsink);
  9151. sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
  9152. upb_sink_putstring(subsink, sel, buf, len, NULL);
  9153. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  9154. upb_sink_endstr(subsink, sel);
  9155. multipart_end(p);
  9156. break;
  9157. }
  9158. default:
  9159. upb_status_seterrmsg(p->status, "Invalid field type for map key");
  9160. return false;
  9161. }
  9162. return true;
  9163. }
  9164. /* Helper: emit one map entry (as a submessage in the map field sequence). This
  9165. * is invoked from end_membername(), at the end of the map entry's key string,
  9166. * with the map key in the accumulate buffer. It parses the key from that
  9167. * buffer, emits the handler calls to start the mapentry submessage (setting up
  9168. * its subframe in the process), and sets up state in the subframe so that the
  9169. * value parser (invoked next) will emit the mapentry's value field and then
  9170. * end the mapentry message. */
  9171. static bool handle_mapentry(upb_json_parser *p) {
  9172. const upb_fielddef *mapfield;
  9173. const upb_msgdef *mapentrymsg;
  9174. upb_jsonparser_frame *inner;
  9175. upb_selector_t sel;
  9176. /* Map entry: p->top->sink is the seq frame, so we need to start a frame
  9177. * for the mapentry itself, and then set |f| in that frame so that the map
  9178. * value field is parsed, and also set a flag to end the frame after the
  9179. * map-entry value is parsed. */
  9180. if (!check_stack(p)) return false;
  9181. mapfield = p->top->mapfield;
  9182. mapentrymsg = upb_fielddef_msgsubdef(mapfield);
  9183. inner = start_jsonparser_frame(p);
  9184. p->top->f = mapfield;
  9185. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
  9186. upb_sink_startsubmsg(p->top->sink, sel, &inner->sink);
  9187. inner->m = mapentrymsg;
  9188. inner->mapfield = mapfield;
  9189. /* Don't set this to true *yet* -- we reuse parsing handlers below to push
  9190. * the key field value to the sink, and these handlers will pop the frame
  9191. * if they see is_mapentry (when invoked by the parser state machine, they
  9192. * would have just seen the map-entry value, not key). */
  9193. inner->is_mapentry = false;
  9194. p->top = inner;
  9195. /* send STARTMSG in submsg frame. */
  9196. upb_sink_startmsg(p->top->sink);
  9197. parse_mapentry_key(p);
  9198. /* Set up the value field to receive the map-entry value. */
  9199. p->top->f = upb_msgdef_itof(p->top->m, UPB_MAPENTRY_VALUE);
  9200. p->top->is_mapentry = true; /* set up to pop frame after value is parsed. */
  9201. p->top->mapfield = mapfield;
  9202. if (p->top->f == NULL) {
  9203. upb_status_seterrmsg(p->status, "mapentry message has no value");
  9204. return false;
  9205. }
  9206. return true;
  9207. }
  9208. static bool end_membername(upb_json_parser *p) {
  9209. UPB_ASSERT(!p->top->f);
  9210. if (!p->top->m) {
  9211. p->top->is_unknown_field = true;
  9212. multipart_end(p);
  9213. return true;
  9214. }
  9215. if (p->top->is_any) {
  9216. return end_any_membername(p);
  9217. } else if (p->top->is_map) {
  9218. return handle_mapentry(p);
  9219. } else {
  9220. size_t len;
  9221. const char *buf = accumulate_getptr(p, &len);
  9222. upb_value v;
  9223. if (upb_strtable_lookup2(p->top->name_table, buf, len, &v)) {
  9224. p->top->f = upb_value_getconstptr(v);
  9225. multipart_end(p);
  9226. return true;
  9227. } else if (p->ignore_json_unknown) {
  9228. p->top->is_unknown_field = true;
  9229. multipart_end(p);
  9230. return true;
  9231. } else {
  9232. upb_status_seterrf(p->status, "No such field: %.*s\n", (int)len, buf);
  9233. return false;
  9234. }
  9235. }
  9236. }
  9237. static bool end_any_membername(upb_json_parser *p) {
  9238. size_t len;
  9239. const char *buf = accumulate_getptr(p, &len);
  9240. upb_value v;
  9241. if (len == 5 && strncmp(buf, "@type", len) == 0) {
  9242. upb_strtable_lookup2(p->top->name_table, "type_url", 8, &v);
  9243. p->top->f = upb_value_getconstptr(v);
  9244. multipart_end(p);
  9245. return true;
  9246. } else {
  9247. p->top->is_unknown_field = true;
  9248. multipart_end(p);
  9249. return true;
  9250. }
  9251. }
  9252. static void end_member(upb_json_parser *p) {
  9253. /* If we just parsed a map-entry value, end that frame too. */
  9254. if (p->top->is_mapentry) {
  9255. upb_selector_t sel;
  9256. bool ok;
  9257. const upb_fielddef *mapfield;
  9258. UPB_ASSERT(p->top > p->stack);
  9259. /* send ENDMSG on submsg. */
  9260. upb_sink_endmsg(p->top->sink, p->status);
  9261. mapfield = p->top->mapfield;
  9262. /* send ENDSUBMSG in repeated-field-of-mapentries frame. */
  9263. p->top--;
  9264. ok = upb_handlers_getselector(mapfield, UPB_HANDLER_ENDSUBMSG, &sel);
  9265. UPB_ASSUME(ok);
  9266. upb_sink_endsubmsg(p->top->sink, (p->top + 1)->sink, sel);
  9267. }
  9268. p->top->f = NULL;
  9269. p->top->is_unknown_field = false;
  9270. }
  9271. static void start_any_member(upb_json_parser *p, const char *ptr) {
  9272. start_member(p);
  9273. json_parser_any_frame_set_after_type_url_start_once(p->top->any_frame, ptr);
  9274. }
  9275. static void end_any_member(upb_json_parser *p, const char *ptr) {
  9276. json_parser_any_frame_set_before_type_url_end(p->top->any_frame, ptr);
  9277. end_member(p);
  9278. }
  9279. static bool start_subobject(upb_json_parser *p) {
  9280. if (p->top->is_unknown_field) {
  9281. if (!check_stack(p)) return false;
  9282. p->top = start_jsonparser_frame(p);
  9283. return true;
  9284. }
  9285. if (upb_fielddef_ismap(p->top->f)) {
  9286. upb_jsonparser_frame *inner;
  9287. upb_selector_t sel;
  9288. /* Beginning of a map. Start a new parser frame in a repeated-field
  9289. * context. */
  9290. if (!check_stack(p)) return false;
  9291. inner = start_jsonparser_frame(p);
  9292. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
  9293. upb_sink_startseq(p->top->sink, sel, &inner->sink);
  9294. inner->m = upb_fielddef_msgsubdef(p->top->f);
  9295. inner->mapfield = p->top->f;
  9296. inner->is_map = true;
  9297. p->top = inner;
  9298. return true;
  9299. } else if (upb_fielddef_issubmsg(p->top->f)) {
  9300. upb_jsonparser_frame *inner;
  9301. upb_selector_t sel;
  9302. /* Beginning of a subobject. Start a new parser frame in the submsg
  9303. * context. */
  9304. if (!check_stack(p)) return false;
  9305. inner = start_jsonparser_frame(p);
  9306. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
  9307. upb_sink_startsubmsg(p->top->sink, sel, &inner->sink);
  9308. inner->m = upb_fielddef_msgsubdef(p->top->f);
  9309. set_name_table(p, inner);
  9310. p->top = inner;
  9311. if (is_wellknown_msg(p, UPB_WELLKNOWN_ANY)) {
  9312. p->top->is_any = true;
  9313. p->top->any_frame = json_parser_any_frame_new(p);
  9314. } else {
  9315. p->top->is_any = false;
  9316. p->top->any_frame = NULL;
  9317. }
  9318. return true;
  9319. } else {
  9320. upb_status_seterrf(p->status,
  9321. "Object specified for non-message/group field: %s",
  9322. upb_fielddef_name(p->top->f));
  9323. return false;
  9324. }
  9325. }
  9326. static bool start_subobject_full(upb_json_parser *p) {
  9327. if (is_top_level(p)) {
  9328. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  9329. start_value_object(p, VALUE_STRUCTVALUE);
  9330. if (!start_subobject(p)) return false;
  9331. start_structvalue_object(p);
  9332. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_STRUCT)) {
  9333. start_structvalue_object(p);
  9334. } else {
  9335. return true;
  9336. }
  9337. } else if (is_wellknown_field(p, UPB_WELLKNOWN_STRUCT)) {
  9338. if (!start_subobject(p)) return false;
  9339. start_structvalue_object(p);
  9340. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  9341. if (!start_subobject(p)) return false;
  9342. start_value_object(p, VALUE_STRUCTVALUE);
  9343. if (!start_subobject(p)) return false;
  9344. start_structvalue_object(p);
  9345. }
  9346. return start_subobject(p);
  9347. }
  9348. static void end_subobject(upb_json_parser *p) {
  9349. if (is_top_level(p)) {
  9350. return;
  9351. }
  9352. if (p->top->is_map) {
  9353. upb_selector_t sel;
  9354. p->top--;
  9355. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
  9356. upb_sink_endseq(p->top->sink, sel);
  9357. } else {
  9358. upb_selector_t sel;
  9359. bool is_unknown = p->top->m == NULL;
  9360. p->top--;
  9361. if (!is_unknown) {
  9362. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSUBMSG);
  9363. upb_sink_endsubmsg(p->top->sink, (p->top + 1)->sink, sel);
  9364. }
  9365. }
  9366. }
  9367. static void end_subobject_full(upb_json_parser *p) {
  9368. end_subobject(p);
  9369. if (is_wellknown_msg(p, UPB_WELLKNOWN_STRUCT)) {
  9370. end_structvalue_object(p);
  9371. if (!is_top_level(p)) {
  9372. end_subobject(p);
  9373. }
  9374. }
  9375. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  9376. end_value_object(p);
  9377. if (!is_top_level(p)) {
  9378. end_subobject(p);
  9379. }
  9380. }
  9381. }
  9382. static bool start_array(upb_json_parser *p) {
  9383. upb_jsonparser_frame *inner;
  9384. upb_selector_t sel;
  9385. if (is_top_level(p)) {
  9386. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  9387. start_value_object(p, VALUE_LISTVALUE);
  9388. if (!start_subobject(p)) return false;
  9389. start_listvalue_object(p);
  9390. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_LISTVALUE)) {
  9391. start_listvalue_object(p);
  9392. } else {
  9393. return false;
  9394. }
  9395. } else if (is_wellknown_field(p, UPB_WELLKNOWN_LISTVALUE) &&
  9396. (!upb_fielddef_isseq(p->top->f) ||
  9397. p->top->is_repeated)) {
  9398. if (!start_subobject(p)) return false;
  9399. start_listvalue_object(p);
  9400. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE) &&
  9401. (!upb_fielddef_isseq(p->top->f) ||
  9402. p->top->is_repeated)) {
  9403. if (!start_subobject(p)) return false;
  9404. start_value_object(p, VALUE_LISTVALUE);
  9405. if (!start_subobject(p)) return false;
  9406. start_listvalue_object(p);
  9407. }
  9408. if (p->top->is_unknown_field) {
  9409. inner = start_jsonparser_frame(p);
  9410. inner->is_unknown_field = true;
  9411. p->top = inner;
  9412. return true;
  9413. }
  9414. if (!upb_fielddef_isseq(p->top->f)) {
  9415. upb_status_seterrf(p->status,
  9416. "Array specified for non-repeated field: %s",
  9417. upb_fielddef_name(p->top->f));
  9418. return false;
  9419. }
  9420. if (!check_stack(p)) return false;
  9421. inner = start_jsonparser_frame(p);
  9422. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
  9423. upb_sink_startseq(p->top->sink, sel, &inner->sink);
  9424. inner->m = p->top->m;
  9425. inner->f = p->top->f;
  9426. inner->is_repeated = true;
  9427. p->top = inner;
  9428. return true;
  9429. }
  9430. static void end_array(upb_json_parser *p) {
  9431. upb_selector_t sel;
  9432. UPB_ASSERT(p->top > p->stack);
  9433. p->top--;
  9434. if (p->top->is_unknown_field) {
  9435. return;
  9436. }
  9437. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
  9438. upb_sink_endseq(p->top->sink, sel);
  9439. if (is_wellknown_msg(p, UPB_WELLKNOWN_LISTVALUE)) {
  9440. end_listvalue_object(p);
  9441. if (!is_top_level(p)) {
  9442. end_subobject(p);
  9443. }
  9444. }
  9445. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  9446. end_value_object(p);
  9447. if (!is_top_level(p)) {
  9448. end_subobject(p);
  9449. }
  9450. }
  9451. }
  9452. static void start_object(upb_json_parser *p) {
  9453. if (!p->top->is_map && p->top->m != NULL) {
  9454. upb_sink_startmsg(p->top->sink);
  9455. }
  9456. }
  9457. static void end_object(upb_json_parser *p) {
  9458. if (!p->top->is_map && p->top->m != NULL) {
  9459. upb_sink_endmsg(p->top->sink, p->status);
  9460. }
  9461. }
  9462. static void start_any_object(upb_json_parser *p, const char *ptr) {
  9463. start_object(p);
  9464. p->top->any_frame->before_type_url_start = ptr;
  9465. p->top->any_frame->before_type_url_end = ptr;
  9466. }
  9467. static bool end_any_object(upb_json_parser *p, const char *ptr) {
  9468. const char *value_membername = "value";
  9469. bool is_well_known_packed = false;
  9470. const char *packed_end = ptr + 1;
  9471. upb_selector_t sel;
  9472. upb_jsonparser_frame *inner;
  9473. if (json_parser_any_frame_has_value(p->top->any_frame) &&
  9474. !json_parser_any_frame_has_type_url(p->top->any_frame)) {
  9475. upb_status_seterrmsg(p->status, "No valid type url");
  9476. return false;
  9477. }
  9478. /* Well known types data is represented as value field. */
  9479. if (upb_msgdef_wellknowntype(p->top->any_frame->parser->top->m) !=
  9480. UPB_WELLKNOWN_UNSPECIFIED) {
  9481. is_well_known_packed = true;
  9482. if (json_parser_any_frame_has_value_before_type_url(p->top->any_frame)) {
  9483. p->top->any_frame->before_type_url_start =
  9484. memchr(p->top->any_frame->before_type_url_start, ':',
  9485. p->top->any_frame->before_type_url_end -
  9486. p->top->any_frame->before_type_url_start);
  9487. if (p->top->any_frame->before_type_url_start == NULL) {
  9488. upb_status_seterrmsg(p->status, "invalid data for well known type.");
  9489. return false;
  9490. }
  9491. p->top->any_frame->before_type_url_start++;
  9492. }
  9493. if (json_parser_any_frame_has_value_after_type_url(p->top->any_frame)) {
  9494. p->top->any_frame->after_type_url_start =
  9495. memchr(p->top->any_frame->after_type_url_start, ':',
  9496. (ptr + 1) -
  9497. p->top->any_frame->after_type_url_start);
  9498. if (p->top->any_frame->after_type_url_start == NULL) {
  9499. upb_status_seterrmsg(p->status, "Invalid data for well known type.");
  9500. return false;
  9501. }
  9502. p->top->any_frame->after_type_url_start++;
  9503. packed_end = ptr;
  9504. }
  9505. }
  9506. if (json_parser_any_frame_has_value_before_type_url(p->top->any_frame)) {
  9507. if (!parse(p->top->any_frame->parser, NULL,
  9508. p->top->any_frame->before_type_url_start,
  9509. p->top->any_frame->before_type_url_end -
  9510. p->top->any_frame->before_type_url_start, NULL)) {
  9511. return false;
  9512. }
  9513. } else {
  9514. if (!is_well_known_packed) {
  9515. if (!parse(p->top->any_frame->parser, NULL, "{", 1, NULL)) {
  9516. return false;
  9517. }
  9518. }
  9519. }
  9520. if (json_parser_any_frame_has_value_before_type_url(p->top->any_frame) &&
  9521. json_parser_any_frame_has_value_after_type_url(p->top->any_frame)) {
  9522. if (!parse(p->top->any_frame->parser, NULL, ",", 1, NULL)) {
  9523. return false;
  9524. }
  9525. }
  9526. if (json_parser_any_frame_has_value_after_type_url(p->top->any_frame)) {
  9527. if (!parse(p->top->any_frame->parser, NULL,
  9528. p->top->any_frame->after_type_url_start,
  9529. packed_end - p->top->any_frame->after_type_url_start, NULL)) {
  9530. return false;
  9531. }
  9532. } else {
  9533. if (!is_well_known_packed) {
  9534. if (!parse(p->top->any_frame->parser, NULL, "}", 1, NULL)) {
  9535. return false;
  9536. }
  9537. }
  9538. }
  9539. if (!end(p->top->any_frame->parser, NULL)) {
  9540. return false;
  9541. }
  9542. p->top->is_any = false;
  9543. /* Set value */
  9544. start_member(p);
  9545. capture_begin(p, value_membername);
  9546. capture_end(p, value_membername + 5);
  9547. end_membername(p);
  9548. if (!check_stack(p)) return false;
  9549. inner = p->top + 1;
  9550. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  9551. upb_sink_startstr(p->top->sink, sel, 0, &inner->sink);
  9552. sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
  9553. upb_sink_putstring(inner->sink, sel, p->top->any_frame->stringsink.ptr,
  9554. p->top->any_frame->stringsink.len, NULL);
  9555. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  9556. upb_sink_endstr(inner->sink, sel);
  9557. end_member(p);
  9558. end_object(p);
  9559. /* Deallocate any parse frame. */
  9560. json_parser_any_frame_free(p->top->any_frame);
  9561. return true;
  9562. }
  9563. static bool is_string_wrapper(const upb_msgdef *m) {
  9564. upb_wellknowntype_t type = upb_msgdef_wellknowntype(m);
  9565. return type == UPB_WELLKNOWN_STRINGVALUE ||
  9566. type == UPB_WELLKNOWN_BYTESVALUE;
  9567. }
  9568. static bool is_fieldmask(const upb_msgdef *m) {
  9569. upb_wellknowntype_t type = upb_msgdef_wellknowntype(m);
  9570. return type == UPB_WELLKNOWN_FIELDMASK;
  9571. }
  9572. static void start_fieldmask_object(upb_json_parser *p) {
  9573. const char *membername = "paths";
  9574. start_object(p);
  9575. /* Set up context for parsing value */
  9576. start_member(p);
  9577. capture_begin(p, membername);
  9578. capture_end(p, membername + 5);
  9579. end_membername(p);
  9580. start_array(p);
  9581. }
  9582. static void end_fieldmask_object(upb_json_parser *p) {
  9583. end_array(p);
  9584. end_member(p);
  9585. end_object(p);
  9586. }
  9587. static void start_wrapper_object(upb_json_parser *p) {
  9588. const char *membername = "value";
  9589. start_object(p);
  9590. /* Set up context for parsing value */
  9591. start_member(p);
  9592. capture_begin(p, membername);
  9593. capture_end(p, membername + 5);
  9594. end_membername(p);
  9595. }
  9596. static void end_wrapper_object(upb_json_parser *p) {
  9597. end_member(p);
  9598. end_object(p);
  9599. }
  9600. static void start_value_object(upb_json_parser *p, int value_type) {
  9601. const char *nullmember = "null_value";
  9602. const char *numbermember = "number_value";
  9603. const char *stringmember = "string_value";
  9604. const char *boolmember = "bool_value";
  9605. const char *structmember = "struct_value";
  9606. const char *listmember = "list_value";
  9607. const char *membername = "";
  9608. switch (value_type) {
  9609. case VALUE_NULLVALUE:
  9610. membername = nullmember;
  9611. break;
  9612. case VALUE_NUMBERVALUE:
  9613. membername = numbermember;
  9614. break;
  9615. case VALUE_STRINGVALUE:
  9616. membername = stringmember;
  9617. break;
  9618. case VALUE_BOOLVALUE:
  9619. membername = boolmember;
  9620. break;
  9621. case VALUE_STRUCTVALUE:
  9622. membername = structmember;
  9623. break;
  9624. case VALUE_LISTVALUE:
  9625. membername = listmember;
  9626. break;
  9627. }
  9628. start_object(p);
  9629. /* Set up context for parsing value */
  9630. start_member(p);
  9631. capture_begin(p, membername);
  9632. capture_end(p, membername + strlen(membername));
  9633. end_membername(p);
  9634. }
  9635. static void end_value_object(upb_json_parser *p) {
  9636. end_member(p);
  9637. end_object(p);
  9638. }
  9639. static void start_listvalue_object(upb_json_parser *p) {
  9640. const char *membername = "values";
  9641. start_object(p);
  9642. /* Set up context for parsing value */
  9643. start_member(p);
  9644. capture_begin(p, membername);
  9645. capture_end(p, membername + strlen(membername));
  9646. end_membername(p);
  9647. }
  9648. static void end_listvalue_object(upb_json_parser *p) {
  9649. end_member(p);
  9650. end_object(p);
  9651. }
  9652. static void start_structvalue_object(upb_json_parser *p) {
  9653. const char *membername = "fields";
  9654. start_object(p);
  9655. /* Set up context for parsing value */
  9656. start_member(p);
  9657. capture_begin(p, membername);
  9658. capture_end(p, membername + strlen(membername));
  9659. end_membername(p);
  9660. }
  9661. static void end_structvalue_object(upb_json_parser *p) {
  9662. end_member(p);
  9663. end_object(p);
  9664. }
  9665. static bool is_top_level(upb_json_parser *p) {
  9666. return p->top == p->stack && p->top->f == NULL && !p->top->is_unknown_field;
  9667. }
  9668. static bool is_wellknown_msg(upb_json_parser *p, upb_wellknowntype_t type) {
  9669. return p->top->m != NULL && upb_msgdef_wellknowntype(p->top->m) == type;
  9670. }
  9671. static bool is_wellknown_field(upb_json_parser *p, upb_wellknowntype_t type) {
  9672. return p->top->f != NULL &&
  9673. upb_fielddef_issubmsg(p->top->f) &&
  9674. (upb_msgdef_wellknowntype(upb_fielddef_msgsubdef(p->top->f))
  9675. == type);
  9676. }
  9677. static bool does_number_wrapper_start(upb_json_parser *p) {
  9678. return p->top->f != NULL &&
  9679. upb_fielddef_issubmsg(p->top->f) &&
  9680. upb_msgdef_isnumberwrapper(upb_fielddef_msgsubdef(p->top->f));
  9681. }
  9682. static bool does_number_wrapper_end(upb_json_parser *p) {
  9683. return p->top->m != NULL && upb_msgdef_isnumberwrapper(p->top->m);
  9684. }
  9685. static bool is_number_wrapper_object(upb_json_parser *p) {
  9686. return p->top->m != NULL && upb_msgdef_isnumberwrapper(p->top->m);
  9687. }
  9688. static bool does_string_wrapper_start(upb_json_parser *p) {
  9689. return p->top->f != NULL &&
  9690. upb_fielddef_issubmsg(p->top->f) &&
  9691. is_string_wrapper(upb_fielddef_msgsubdef(p->top->f));
  9692. }
  9693. static bool does_string_wrapper_end(upb_json_parser *p) {
  9694. return p->top->m != NULL && is_string_wrapper(p->top->m);
  9695. }
  9696. static bool is_string_wrapper_object(upb_json_parser *p) {
  9697. return p->top->m != NULL && is_string_wrapper(p->top->m);
  9698. }
  9699. static bool does_fieldmask_start(upb_json_parser *p) {
  9700. return p->top->f != NULL &&
  9701. upb_fielddef_issubmsg(p->top->f) &&
  9702. is_fieldmask(upb_fielddef_msgsubdef(p->top->f));
  9703. }
  9704. static bool does_fieldmask_end(upb_json_parser *p) {
  9705. return p->top->m != NULL && is_fieldmask(p->top->m);
  9706. }
  9707. #define CHECK_RETURN_TOP(x) if (!(x)) goto error
  9708. /* The actual parser **********************************************************/
  9709. /* What follows is the Ragel parser itself. The language is specified in Ragel
  9710. * and the actions call our C functions above.
  9711. *
  9712. * Ragel has an extensive set of functionality, and we use only a small part of
  9713. * it. There are many action types but we only use a few:
  9714. *
  9715. * ">" -- transition into a machine
  9716. * "%" -- transition out of a machine
  9717. * "@" -- transition into a final state of a machine.
  9718. *
  9719. * "@" transitions are tricky because a machine can transition into a final
  9720. * state repeatedly. But in some cases we know this can't happen, for example
  9721. * a string which is delimited by a final '"' can only transition into its
  9722. * final state once, when the closing '"' is seen. */
  9723. #line 2780 "upb/json/parser.rl"
  9724. #line 2583 "upb/json/parser.c"
  9725. static const char _json_actions[] = {
  9726. 0, 1, 0, 1, 1, 1, 3, 1,
  9727. 4, 1, 6, 1, 7, 1, 8, 1,
  9728. 9, 1, 11, 1, 12, 1, 13, 1,
  9729. 14, 1, 15, 1, 16, 1, 17, 1,
  9730. 18, 1, 19, 1, 20, 1, 22, 1,
  9731. 23, 1, 24, 1, 35, 1, 37, 1,
  9732. 39, 1, 40, 1, 42, 1, 43, 1,
  9733. 44, 1, 46, 1, 48, 1, 49, 1,
  9734. 50, 1, 51, 1, 53, 1, 54, 2,
  9735. 4, 9, 2, 5, 6, 2, 7, 3,
  9736. 2, 7, 9, 2, 21, 26, 2, 25,
  9737. 10, 2, 27, 28, 2, 29, 30, 2,
  9738. 32, 34, 2, 33, 31, 2, 38, 36,
  9739. 2, 40, 42, 2, 45, 2, 2, 46,
  9740. 54, 2, 47, 36, 2, 49, 54, 2,
  9741. 50, 54, 2, 51, 54, 2, 52, 41,
  9742. 2, 53, 54, 3, 32, 34, 35, 4,
  9743. 21, 26, 27, 28
  9744. };
  9745. static const short _json_key_offsets[] = {
  9746. 0, 0, 12, 13, 18, 23, 28, 29,
  9747. 30, 31, 32, 33, 34, 35, 36, 37,
  9748. 38, 43, 44, 48, 53, 58, 63, 67,
  9749. 71, 74, 77, 79, 83, 87, 89, 91,
  9750. 96, 98, 100, 109, 115, 121, 127, 133,
  9751. 135, 139, 142, 144, 146, 149, 150, 154,
  9752. 156, 158, 160, 162, 163, 165, 167, 168,
  9753. 170, 172, 173, 175, 177, 178, 180, 182,
  9754. 183, 185, 187, 191, 193, 195, 196, 197,
  9755. 198, 199, 201, 206, 208, 210, 212, 221,
  9756. 222, 222, 222, 227, 232, 237, 238, 239,
  9757. 240, 241, 241, 242, 243, 244, 244, 245,
  9758. 246, 247, 247, 252, 253, 257, 262, 267,
  9759. 272, 276, 276, 279, 282, 285, 288, 291,
  9760. 294, 294, 294, 294, 294, 294
  9761. };
  9762. static const char _json_trans_keys[] = {
  9763. 32, 34, 45, 91, 102, 110, 116, 123,
  9764. 9, 13, 48, 57, 34, 32, 93, 125,
  9765. 9, 13, 32, 44, 93, 9, 13, 32,
  9766. 93, 125, 9, 13, 97, 108, 115, 101,
  9767. 117, 108, 108, 114, 117, 101, 32, 34,
  9768. 125, 9, 13, 34, 32, 58, 9, 13,
  9769. 32, 93, 125, 9, 13, 32, 44, 125,
  9770. 9, 13, 32, 44, 125, 9, 13, 32,
  9771. 34, 9, 13, 45, 48, 49, 57, 48,
  9772. 49, 57, 46, 69, 101, 48, 57, 69,
  9773. 101, 48, 57, 43, 45, 48, 57, 48,
  9774. 57, 48, 57, 46, 69, 101, 48, 57,
  9775. 34, 92, 34, 92, 34, 47, 92, 98,
  9776. 102, 110, 114, 116, 117, 48, 57, 65,
  9777. 70, 97, 102, 48, 57, 65, 70, 97,
  9778. 102, 48, 57, 65, 70, 97, 102, 48,
  9779. 57, 65, 70, 97, 102, 34, 92, 45,
  9780. 48, 49, 57, 48, 49, 57, 46, 115,
  9781. 48, 57, 115, 48, 57, 34, 46, 115,
  9782. 48, 57, 48, 57, 48, 57, 48, 57,
  9783. 48, 57, 45, 48, 57, 48, 57, 45,
  9784. 48, 57, 48, 57, 84, 48, 57, 48,
  9785. 57, 58, 48, 57, 48, 57, 58, 48,
  9786. 57, 48, 57, 43, 45, 46, 90, 48,
  9787. 57, 48, 57, 58, 48, 48, 34, 48,
  9788. 57, 43, 45, 90, 48, 57, 34, 44,
  9789. 34, 44, 34, 44, 34, 45, 91, 102,
  9790. 110, 116, 123, 48, 57, 34, 32, 93,
  9791. 125, 9, 13, 32, 44, 93, 9, 13,
  9792. 32, 93, 125, 9, 13, 97, 108, 115,
  9793. 101, 117, 108, 108, 114, 117, 101, 32,
  9794. 34, 125, 9, 13, 34, 32, 58, 9,
  9795. 13, 32, 93, 125, 9, 13, 32, 44,
  9796. 125, 9, 13, 32, 44, 125, 9, 13,
  9797. 32, 34, 9, 13, 32, 9, 13, 32,
  9798. 9, 13, 32, 9, 13, 32, 9, 13,
  9799. 32, 9, 13, 32, 9, 13, 0
  9800. };
  9801. static const char _json_single_lengths[] = {
  9802. 0, 8, 1, 3, 3, 3, 1, 1,
  9803. 1, 1, 1, 1, 1, 1, 1, 1,
  9804. 3, 1, 2, 3, 3, 3, 2, 2,
  9805. 1, 3, 0, 2, 2, 0, 0, 3,
  9806. 2, 2, 9, 0, 0, 0, 0, 2,
  9807. 2, 1, 2, 0, 1, 1, 2, 0,
  9808. 0, 0, 0, 1, 0, 0, 1, 0,
  9809. 0, 1, 0, 0, 1, 0, 0, 1,
  9810. 0, 0, 4, 0, 0, 1, 1, 1,
  9811. 1, 0, 3, 2, 2, 2, 7, 1,
  9812. 0, 0, 3, 3, 3, 1, 1, 1,
  9813. 1, 0, 1, 1, 1, 0, 1, 1,
  9814. 1, 0, 3, 1, 2, 3, 3, 3,
  9815. 2, 0, 1, 1, 1, 1, 1, 1,
  9816. 0, 0, 0, 0, 0, 0
  9817. };
  9818. static const char _json_range_lengths[] = {
  9819. 0, 2, 0, 1, 1, 1, 0, 0,
  9820. 0, 0, 0, 0, 0, 0, 0, 0,
  9821. 1, 0, 1, 1, 1, 1, 1, 1,
  9822. 1, 0, 1, 1, 1, 1, 1, 1,
  9823. 0, 0, 0, 3, 3, 3, 3, 0,
  9824. 1, 1, 0, 1, 1, 0, 1, 1,
  9825. 1, 1, 1, 0, 1, 1, 0, 1,
  9826. 1, 0, 1, 1, 0, 1, 1, 0,
  9827. 1, 1, 0, 1, 1, 0, 0, 0,
  9828. 0, 1, 1, 0, 0, 0, 1, 0,
  9829. 0, 0, 1, 1, 1, 0, 0, 0,
  9830. 0, 0, 0, 0, 0, 0, 0, 0,
  9831. 0, 0, 1, 0, 1, 1, 1, 1,
  9832. 1, 0, 1, 1, 1, 1, 1, 1,
  9833. 0, 0, 0, 0, 0, 0
  9834. };
  9835. static const short _json_index_offsets[] = {
  9836. 0, 0, 11, 13, 18, 23, 28, 30,
  9837. 32, 34, 36, 38, 40, 42, 44, 46,
  9838. 48, 53, 55, 59, 64, 69, 74, 78,
  9839. 82, 85, 89, 91, 95, 99, 101, 103,
  9840. 108, 111, 114, 124, 128, 132, 136, 140,
  9841. 143, 147, 150, 153, 155, 158, 160, 164,
  9842. 166, 168, 170, 172, 174, 176, 178, 180,
  9843. 182, 184, 186, 188, 190, 192, 194, 196,
  9844. 198, 200, 202, 207, 209, 211, 213, 215,
  9845. 217, 219, 221, 226, 229, 232, 235, 244,
  9846. 246, 247, 248, 253, 258, 263, 265, 267,
  9847. 269, 271, 272, 274, 276, 278, 279, 281,
  9848. 283, 285, 286, 291, 293, 297, 302, 307,
  9849. 312, 316, 317, 320, 323, 326, 329, 332,
  9850. 335, 336, 337, 338, 339, 340
  9851. };
  9852. static const unsigned char _json_indicies[] = {
  9853. 0, 2, 3, 4, 5, 6, 7, 8,
  9854. 0, 3, 1, 9, 1, 11, 12, 1,
  9855. 11, 10, 13, 14, 12, 13, 1, 14,
  9856. 1, 1, 14, 10, 15, 1, 16, 1,
  9857. 17, 1, 18, 1, 19, 1, 20, 1,
  9858. 21, 1, 22, 1, 23, 1, 24, 1,
  9859. 25, 26, 27, 25, 1, 28, 1, 29,
  9860. 30, 29, 1, 30, 1, 1, 30, 31,
  9861. 32, 33, 34, 32, 1, 35, 36, 27,
  9862. 35, 1, 36, 26, 36, 1, 37, 38,
  9863. 39, 1, 38, 39, 1, 41, 42, 42,
  9864. 40, 43, 1, 42, 42, 43, 40, 44,
  9865. 44, 45, 1, 45, 1, 45, 40, 41,
  9866. 42, 42, 39, 40, 47, 48, 46, 50,
  9867. 51, 49, 52, 52, 52, 52, 52, 52,
  9868. 52, 52, 53, 1, 54, 54, 54, 1,
  9869. 55, 55, 55, 1, 56, 56, 56, 1,
  9870. 57, 57, 57, 1, 59, 60, 58, 61,
  9871. 62, 63, 1, 64, 65, 1, 66, 67,
  9872. 1, 68, 1, 67, 68, 1, 69, 1,
  9873. 66, 67, 65, 1, 70, 1, 71, 1,
  9874. 72, 1, 73, 1, 74, 1, 75, 1,
  9875. 76, 1, 77, 1, 78, 1, 79, 1,
  9876. 80, 1, 81, 1, 82, 1, 83, 1,
  9877. 84, 1, 85, 1, 86, 1, 87, 1,
  9878. 88, 1, 89, 89, 90, 91, 1, 92,
  9879. 1, 93, 1, 94, 1, 95, 1, 96,
  9880. 1, 97, 1, 98, 1, 99, 99, 100,
  9881. 98, 1, 102, 1, 101, 104, 105, 103,
  9882. 1, 1, 101, 106, 107, 108, 109, 110,
  9883. 111, 112, 107, 1, 113, 1, 114, 115,
  9884. 117, 118, 1, 117, 116, 119, 120, 118,
  9885. 119, 1, 120, 1, 1, 120, 116, 121,
  9886. 1, 122, 1, 123, 1, 124, 1, 125,
  9887. 126, 1, 127, 1, 128, 1, 129, 130,
  9888. 1, 131, 1, 132, 1, 133, 134, 135,
  9889. 136, 134, 1, 137, 1, 138, 139, 138,
  9890. 1, 139, 1, 1, 139, 140, 141, 142,
  9891. 143, 141, 1, 144, 145, 136, 144, 1,
  9892. 145, 135, 145, 1, 146, 147, 147, 1,
  9893. 148, 148, 1, 149, 149, 1, 150, 150,
  9894. 1, 151, 151, 1, 152, 152, 1, 1,
  9895. 1, 1, 1, 1, 1, 0
  9896. };
  9897. static const char _json_trans_targs[] = {
  9898. 1, 0, 2, 107, 3, 6, 10, 13,
  9899. 16, 106, 4, 3, 106, 4, 5, 7,
  9900. 8, 9, 108, 11, 12, 109, 14, 15,
  9901. 110, 16, 17, 111, 18, 18, 19, 20,
  9902. 21, 22, 111, 21, 22, 24, 25, 31,
  9903. 112, 26, 28, 27, 29, 30, 33, 113,
  9904. 34, 33, 113, 34, 32, 35, 36, 37,
  9905. 38, 39, 33, 113, 34, 41, 42, 46,
  9906. 42, 46, 43, 45, 44, 114, 48, 49,
  9907. 50, 51, 52, 53, 54, 55, 56, 57,
  9908. 58, 59, 60, 61, 62, 63, 64, 65,
  9909. 66, 67, 73, 72, 68, 69, 70, 71,
  9910. 72, 115, 74, 67, 72, 76, 116, 76,
  9911. 116, 77, 79, 81, 82, 85, 90, 94,
  9912. 98, 80, 117, 117, 83, 82, 80, 83,
  9913. 84, 86, 87, 88, 89, 117, 91, 92,
  9914. 93, 117, 95, 96, 97, 117, 98, 99,
  9915. 105, 100, 100, 101, 102, 103, 104, 105,
  9916. 103, 104, 117, 106, 106, 106, 106, 106,
  9917. 106
  9918. };
  9919. static const unsigned char _json_trans_actions[] = {
  9920. 0, 0, 113, 107, 53, 0, 0, 0,
  9921. 125, 59, 45, 0, 55, 0, 0, 0,
  9922. 0, 0, 0, 0, 0, 0, 0, 0,
  9923. 0, 0, 101, 51, 47, 0, 0, 45,
  9924. 49, 49, 104, 0, 0, 0, 0, 0,
  9925. 3, 0, 0, 0, 0, 0, 5, 15,
  9926. 0, 0, 71, 7, 13, 0, 74, 9,
  9927. 9, 9, 77, 80, 11, 37, 37, 37,
  9928. 0, 0, 0, 39, 0, 41, 86, 0,
  9929. 0, 0, 17, 19, 0, 21, 23, 0,
  9930. 25, 27, 0, 29, 31, 0, 33, 35,
  9931. 0, 135, 83, 135, 0, 0, 0, 0,
  9932. 0, 92, 0, 89, 89, 98, 43, 0,
  9933. 131, 95, 113, 107, 53, 0, 0, 0,
  9934. 125, 59, 69, 110, 45, 0, 55, 0,
  9935. 0, 0, 0, 0, 0, 119, 0, 0,
  9936. 0, 122, 0, 0, 0, 116, 0, 101,
  9937. 51, 47, 0, 0, 45, 49, 49, 104,
  9938. 0, 0, 128, 0, 57, 63, 65, 61,
  9939. 67
  9940. };
  9941. static const unsigned char _json_eof_actions[] = {
  9942. 0, 0, 0, 0, 0, 0, 0, 0,
  9943. 0, 0, 0, 0, 0, 0, 0, 0,
  9944. 0, 0, 0, 0, 0, 0, 0, 0,
  9945. 0, 1, 0, 1, 0, 0, 1, 1,
  9946. 0, 0, 0, 0, 0, 0, 0, 0,
  9947. 0, 0, 0, 0, 0, 0, 0, 0,
  9948. 0, 0, 0, 0, 0, 0, 0, 0,
  9949. 0, 0, 0, 0, 0, 0, 0, 0,
  9950. 0, 0, 0, 0, 0, 0, 0, 0,
  9951. 0, 0, 0, 0, 0, 0, 0, 0,
  9952. 0, 0, 0, 0, 0, 0, 0, 0,
  9953. 0, 0, 0, 0, 0, 0, 0, 0,
  9954. 0, 0, 0, 0, 0, 0, 0, 0,
  9955. 0, 0, 0, 57, 63, 65, 61, 67,
  9956. 0, 0, 0, 0, 0, 0
  9957. };
  9958. static const int json_start = 1;
  9959. static const int json_en_number_machine = 23;
  9960. static const int json_en_string_machine = 32;
  9961. static const int json_en_duration_machine = 40;
  9962. static const int json_en_timestamp_machine = 47;
  9963. static const int json_en_fieldmask_machine = 75;
  9964. static const int json_en_value_machine = 78;
  9965. static const int json_en_main = 1;
  9966. #line 2783 "upb/json/parser.rl"
  9967. size_t parse(void *closure, const void *hd, const char *buf, size_t size,
  9968. const upb_bufhandle *handle) {
  9969. upb_json_parser *parser = closure;
  9970. /* Variables used by Ragel's generated code. */
  9971. int cs = parser->current_state;
  9972. int *stack = parser->parser_stack;
  9973. int top = parser->parser_top;
  9974. const char *p = buf;
  9975. const char *pe = buf + size;
  9976. const char *eof = &eof_ch;
  9977. parser->handle = handle;
  9978. UPB_UNUSED(hd);
  9979. UPB_UNUSED(handle);
  9980. capture_resume(parser, buf);
  9981. #line 2861 "upb/json/parser.c"
  9982. {
  9983. int _klen;
  9984. unsigned int _trans;
  9985. const char *_acts;
  9986. unsigned int _nacts;
  9987. const char *_keys;
  9988. if ( p == pe )
  9989. goto _test_eof;
  9990. if ( cs == 0 )
  9991. goto _out;
  9992. _resume:
  9993. _keys = _json_trans_keys + _json_key_offsets[cs];
  9994. _trans = _json_index_offsets[cs];
  9995. _klen = _json_single_lengths[cs];
  9996. if ( _klen > 0 ) {
  9997. const char *_lower = _keys;
  9998. const char *_mid;
  9999. const char *_upper = _keys + _klen - 1;
  10000. while (1) {
  10001. if ( _upper < _lower )
  10002. break;
  10003. _mid = _lower + ((_upper-_lower) >> 1);
  10004. if ( (*p) < *_mid )
  10005. _upper = _mid - 1;
  10006. else if ( (*p) > *_mid )
  10007. _lower = _mid + 1;
  10008. else {
  10009. _trans += (unsigned int)(_mid - _keys);
  10010. goto _match;
  10011. }
  10012. }
  10013. _keys += _klen;
  10014. _trans += _klen;
  10015. }
  10016. _klen = _json_range_lengths[cs];
  10017. if ( _klen > 0 ) {
  10018. const char *_lower = _keys;
  10019. const char *_mid;
  10020. const char *_upper = _keys + (_klen<<1) - 2;
  10021. while (1) {
  10022. if ( _upper < _lower )
  10023. break;
  10024. _mid = _lower + (((_upper-_lower) >> 1) & ~1);
  10025. if ( (*p) < _mid[0] )
  10026. _upper = _mid - 2;
  10027. else if ( (*p) > _mid[1] )
  10028. _lower = _mid + 2;
  10029. else {
  10030. _trans += (unsigned int)((_mid - _keys)>>1);
  10031. goto _match;
  10032. }
  10033. }
  10034. _trans += _klen;
  10035. }
  10036. _match:
  10037. _trans = _json_indicies[_trans];
  10038. cs = _json_trans_targs[_trans];
  10039. if ( _json_trans_actions[_trans] == 0 )
  10040. goto _again;
  10041. _acts = _json_actions + _json_trans_actions[_trans];
  10042. _nacts = (unsigned int) *_acts++;
  10043. while ( _nacts-- > 0 )
  10044. {
  10045. switch ( *_acts++ )
  10046. {
  10047. case 1:
  10048. #line 2588 "upb/json/parser.rl"
  10049. { p--; {cs = stack[--top]; goto _again;} }
  10050. break;
  10051. case 2:
  10052. #line 2590 "upb/json/parser.rl"
  10053. { p--; {stack[top++] = cs; cs = 23;goto _again;} }
  10054. break;
  10055. case 3:
  10056. #line 2594 "upb/json/parser.rl"
  10057. { start_text(parser, p); }
  10058. break;
  10059. case 4:
  10060. #line 2595 "upb/json/parser.rl"
  10061. { CHECK_RETURN_TOP(end_text(parser, p)); }
  10062. break;
  10063. case 5:
  10064. #line 2601 "upb/json/parser.rl"
  10065. { start_hex(parser); }
  10066. break;
  10067. case 6:
  10068. #line 2602 "upb/json/parser.rl"
  10069. { hexdigit(parser, p); }
  10070. break;
  10071. case 7:
  10072. #line 2603 "upb/json/parser.rl"
  10073. { CHECK_RETURN_TOP(end_hex(parser)); }
  10074. break;
  10075. case 8:
  10076. #line 2609 "upb/json/parser.rl"
  10077. { CHECK_RETURN_TOP(escape(parser, p)); }
  10078. break;
  10079. case 9:
  10080. #line 2615 "upb/json/parser.rl"
  10081. { p--; {cs = stack[--top]; goto _again;} }
  10082. break;
  10083. case 10:
  10084. #line 2620 "upb/json/parser.rl"
  10085. { start_year(parser, p); }
  10086. break;
  10087. case 11:
  10088. #line 2621 "upb/json/parser.rl"
  10089. { CHECK_RETURN_TOP(end_year(parser, p)); }
  10090. break;
  10091. case 12:
  10092. #line 2625 "upb/json/parser.rl"
  10093. { start_month(parser, p); }
  10094. break;
  10095. case 13:
  10096. #line 2626 "upb/json/parser.rl"
  10097. { CHECK_RETURN_TOP(end_month(parser, p)); }
  10098. break;
  10099. case 14:
  10100. #line 2630 "upb/json/parser.rl"
  10101. { start_day(parser, p); }
  10102. break;
  10103. case 15:
  10104. #line 2631 "upb/json/parser.rl"
  10105. { CHECK_RETURN_TOP(end_day(parser, p)); }
  10106. break;
  10107. case 16:
  10108. #line 2635 "upb/json/parser.rl"
  10109. { start_hour(parser, p); }
  10110. break;
  10111. case 17:
  10112. #line 2636 "upb/json/parser.rl"
  10113. { CHECK_RETURN_TOP(end_hour(parser, p)); }
  10114. break;
  10115. case 18:
  10116. #line 2640 "upb/json/parser.rl"
  10117. { start_minute(parser, p); }
  10118. break;
  10119. case 19:
  10120. #line 2641 "upb/json/parser.rl"
  10121. { CHECK_RETURN_TOP(end_minute(parser, p)); }
  10122. break;
  10123. case 20:
  10124. #line 2645 "upb/json/parser.rl"
  10125. { start_second(parser, p); }
  10126. break;
  10127. case 21:
  10128. #line 2646 "upb/json/parser.rl"
  10129. { CHECK_RETURN_TOP(end_second(parser, p)); }
  10130. break;
  10131. case 22:
  10132. #line 2651 "upb/json/parser.rl"
  10133. { start_duration_base(parser, p); }
  10134. break;
  10135. case 23:
  10136. #line 2652 "upb/json/parser.rl"
  10137. { CHECK_RETURN_TOP(end_duration_base(parser, p)); }
  10138. break;
  10139. case 24:
  10140. #line 2654 "upb/json/parser.rl"
  10141. { p--; {cs = stack[--top]; goto _again;} }
  10142. break;
  10143. case 25:
  10144. #line 2659 "upb/json/parser.rl"
  10145. { start_timestamp_base(parser); }
  10146. break;
  10147. case 26:
  10148. #line 2661 "upb/json/parser.rl"
  10149. { start_timestamp_fraction(parser, p); }
  10150. break;
  10151. case 27:
  10152. #line 2662 "upb/json/parser.rl"
  10153. { CHECK_RETURN_TOP(end_timestamp_fraction(parser, p)); }
  10154. break;
  10155. case 28:
  10156. #line 2664 "upb/json/parser.rl"
  10157. { start_timestamp_zone(parser, p); }
  10158. break;
  10159. case 29:
  10160. #line 2665 "upb/json/parser.rl"
  10161. { CHECK_RETURN_TOP(end_timestamp_zone(parser, p)); }
  10162. break;
  10163. case 30:
  10164. #line 2667 "upb/json/parser.rl"
  10165. { p--; {cs = stack[--top]; goto _again;} }
  10166. break;
  10167. case 31:
  10168. #line 2672 "upb/json/parser.rl"
  10169. { start_fieldmask_path_text(parser, p); }
  10170. break;
  10171. case 32:
  10172. #line 2673 "upb/json/parser.rl"
  10173. { end_fieldmask_path_text(parser, p); }
  10174. break;
  10175. case 33:
  10176. #line 2678 "upb/json/parser.rl"
  10177. { start_fieldmask_path(parser); }
  10178. break;
  10179. case 34:
  10180. #line 2679 "upb/json/parser.rl"
  10181. { end_fieldmask_path(parser); }
  10182. break;
  10183. case 35:
  10184. #line 2685 "upb/json/parser.rl"
  10185. { p--; {cs = stack[--top]; goto _again;} }
  10186. break;
  10187. case 36:
  10188. #line 2690 "upb/json/parser.rl"
  10189. {
  10190. if (is_wellknown_msg(parser, UPB_WELLKNOWN_TIMESTAMP)) {
  10191. {stack[top++] = cs; cs = 47;goto _again;}
  10192. } else if (is_wellknown_msg(parser, UPB_WELLKNOWN_DURATION)) {
  10193. {stack[top++] = cs; cs = 40;goto _again;}
  10194. } else if (is_wellknown_msg(parser, UPB_WELLKNOWN_FIELDMASK)) {
  10195. {stack[top++] = cs; cs = 75;goto _again;}
  10196. } else {
  10197. {stack[top++] = cs; cs = 32;goto _again;}
  10198. }
  10199. }
  10200. break;
  10201. case 37:
  10202. #line 2703 "upb/json/parser.rl"
  10203. { p--; {stack[top++] = cs; cs = 78;goto _again;} }
  10204. break;
  10205. case 38:
  10206. #line 2708 "upb/json/parser.rl"
  10207. {
  10208. if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
  10209. start_any_member(parser, p);
  10210. } else {
  10211. start_member(parser);
  10212. }
  10213. }
  10214. break;
  10215. case 39:
  10216. #line 2715 "upb/json/parser.rl"
  10217. { CHECK_RETURN_TOP(end_membername(parser)); }
  10218. break;
  10219. case 40:
  10220. #line 2718 "upb/json/parser.rl"
  10221. {
  10222. if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
  10223. end_any_member(parser, p);
  10224. } else {
  10225. end_member(parser);
  10226. }
  10227. }
  10228. break;
  10229. case 41:
  10230. #line 2729 "upb/json/parser.rl"
  10231. {
  10232. if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
  10233. start_any_object(parser, p);
  10234. } else {
  10235. start_object(parser);
  10236. }
  10237. }
  10238. break;
  10239. case 42:
  10240. #line 2738 "upb/json/parser.rl"
  10241. {
  10242. if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
  10243. CHECK_RETURN_TOP(end_any_object(parser, p));
  10244. } else {
  10245. end_object(parser);
  10246. }
  10247. }
  10248. break;
  10249. case 43:
  10250. #line 2750 "upb/json/parser.rl"
  10251. { CHECK_RETURN_TOP(start_array(parser)); }
  10252. break;
  10253. case 44:
  10254. #line 2754 "upb/json/parser.rl"
  10255. { end_array(parser); }
  10256. break;
  10257. case 45:
  10258. #line 2759 "upb/json/parser.rl"
  10259. { CHECK_RETURN_TOP(start_number(parser, p)); }
  10260. break;
  10261. case 46:
  10262. #line 2760 "upb/json/parser.rl"
  10263. { CHECK_RETURN_TOP(end_number(parser, p)); }
  10264. break;
  10265. case 47:
  10266. #line 2762 "upb/json/parser.rl"
  10267. { CHECK_RETURN_TOP(start_stringval(parser)); }
  10268. break;
  10269. case 48:
  10270. #line 2763 "upb/json/parser.rl"
  10271. { CHECK_RETURN_TOP(end_stringval(parser)); }
  10272. break;
  10273. case 49:
  10274. #line 2765 "upb/json/parser.rl"
  10275. { CHECK_RETURN_TOP(end_bool(parser, true)); }
  10276. break;
  10277. case 50:
  10278. #line 2767 "upb/json/parser.rl"
  10279. { CHECK_RETURN_TOP(end_bool(parser, false)); }
  10280. break;
  10281. case 51:
  10282. #line 2769 "upb/json/parser.rl"
  10283. { CHECK_RETURN_TOP(end_null(parser)); }
  10284. break;
  10285. case 52:
  10286. #line 2771 "upb/json/parser.rl"
  10287. { CHECK_RETURN_TOP(start_subobject_full(parser)); }
  10288. break;
  10289. case 53:
  10290. #line 2772 "upb/json/parser.rl"
  10291. { end_subobject_full(parser); }
  10292. break;
  10293. case 54:
  10294. #line 2777 "upb/json/parser.rl"
  10295. { p--; {cs = stack[--top]; goto _again;} }
  10296. break;
  10297. #line 3185 "upb/json/parser.c"
  10298. }
  10299. }
  10300. _again:
  10301. if ( cs == 0 )
  10302. goto _out;
  10303. if ( ++p != pe )
  10304. goto _resume;
  10305. _test_eof: {}
  10306. if ( p == eof )
  10307. {
  10308. const char *__acts = _json_actions + _json_eof_actions[cs];
  10309. unsigned int __nacts = (unsigned int) *__acts++;
  10310. while ( __nacts-- > 0 ) {
  10311. switch ( *__acts++ ) {
  10312. case 0:
  10313. #line 2586 "upb/json/parser.rl"
  10314. { p--; {cs = stack[--top]; if ( p == pe )
  10315. goto _test_eof;
  10316. goto _again;} }
  10317. break;
  10318. case 46:
  10319. #line 2760 "upb/json/parser.rl"
  10320. { CHECK_RETURN_TOP(end_number(parser, p)); }
  10321. break;
  10322. case 49:
  10323. #line 2765 "upb/json/parser.rl"
  10324. { CHECK_RETURN_TOP(end_bool(parser, true)); }
  10325. break;
  10326. case 50:
  10327. #line 2767 "upb/json/parser.rl"
  10328. { CHECK_RETURN_TOP(end_bool(parser, false)); }
  10329. break;
  10330. case 51:
  10331. #line 2769 "upb/json/parser.rl"
  10332. { CHECK_RETURN_TOP(end_null(parser)); }
  10333. break;
  10334. case 53:
  10335. #line 2772 "upb/json/parser.rl"
  10336. { end_subobject_full(parser); }
  10337. break;
  10338. #line 3227 "upb/json/parser.c"
  10339. }
  10340. }
  10341. }
  10342. _out: {}
  10343. }
  10344. #line 2805 "upb/json/parser.rl"
  10345. if (p != pe) {
  10346. upb_status_seterrf(parser->status, "Parse error at '%.*s'\n", pe - p, p);
  10347. } else {
  10348. capture_suspend(parser, &p);
  10349. }
  10350. error:
  10351. /* Save parsing state back to parser. */
  10352. parser->current_state = cs;
  10353. parser->parser_top = top;
  10354. return p - buf;
  10355. }
  10356. static bool end(void *closure, const void *hd) {
  10357. upb_json_parser *parser = closure;
  10358. /* Prevent compile warning on unused static constants. */
  10359. UPB_UNUSED(json_start);
  10360. UPB_UNUSED(json_en_duration_machine);
  10361. UPB_UNUSED(json_en_fieldmask_machine);
  10362. UPB_UNUSED(json_en_number_machine);
  10363. UPB_UNUSED(json_en_string_machine);
  10364. UPB_UNUSED(json_en_timestamp_machine);
  10365. UPB_UNUSED(json_en_value_machine);
  10366. UPB_UNUSED(json_en_main);
  10367. parse(parser, hd, &eof_ch, 0, NULL);
  10368. return parser->current_state >= 106;
  10369. }
  10370. static void json_parser_reset(upb_json_parser *p) {
  10371. int cs;
  10372. int top;
  10373. p->top = p->stack;
  10374. init_frame(p->top);
  10375. /* Emit Ragel initialization of the parser. */
  10376. #line 3278 "upb/json/parser.c"
  10377. {
  10378. cs = json_start;
  10379. top = 0;
  10380. }
  10381. #line 2847 "upb/json/parser.rl"
  10382. p->current_state = cs;
  10383. p->parser_top = top;
  10384. accumulate_clear(p);
  10385. p->multipart_state = MULTIPART_INACTIVE;
  10386. p->capture = NULL;
  10387. p->accumulated = NULL;
  10388. }
  10389. static upb_json_parsermethod *parsermethod_new(upb_json_codecache *c,
  10390. const upb_msgdef *md) {
  10391. upb_msg_field_iter i;
  10392. upb_alloc *alloc = upb_arena_alloc(c->arena);
  10393. upb_json_parsermethod *m = upb_malloc(alloc, sizeof(*m));
  10394. m->cache = c;
  10395. upb_byteshandler_init(&m->input_handler_);
  10396. upb_byteshandler_setstring(&m->input_handler_, parse, m);
  10397. upb_byteshandler_setendstr(&m->input_handler_, end, m);
  10398. upb_strtable_init2(&m->name_table, UPB_CTYPE_CONSTPTR, alloc);
  10399. /* Build name_table */
  10400. for(upb_msg_field_begin(&i, md);
  10401. !upb_msg_field_done(&i);
  10402. upb_msg_field_next(&i)) {
  10403. const upb_fielddef *f = upb_msg_iter_field(&i);
  10404. upb_value v = upb_value_constptr(f);
  10405. const char *name;
  10406. /* Add an entry for the JSON name. */
  10407. name = upb_fielddef_jsonname(f);
  10408. upb_strtable_insert3(&m->name_table, name, strlen(name), v, alloc);
  10409. if (strcmp(name, upb_fielddef_name(f)) != 0) {
  10410. /* Since the JSON name is different from the regular field name, add an
  10411. * entry for the raw name (compliant proto3 JSON parsers must accept
  10412. * both). */
  10413. const char *name = upb_fielddef_name(f);
  10414. upb_strtable_insert3(&m->name_table, name, strlen(name), v, alloc);
  10415. }
  10416. }
  10417. return m;
  10418. }
  10419. /* Public API *****************************************************************/
  10420. upb_json_parser *upb_json_parser_create(upb_arena *arena,
  10421. const upb_json_parsermethod *method,
  10422. const upb_symtab* symtab,
  10423. upb_sink output,
  10424. upb_status *status,
  10425. bool ignore_json_unknown) {
  10426. #ifndef NDEBUG
  10427. const size_t size_before = upb_arena_bytesallocated(arena);
  10428. #endif
  10429. upb_json_parser *p = upb_arena_malloc(arena, sizeof(upb_json_parser));
  10430. if (!p) return false;
  10431. p->arena = arena;
  10432. p->method = method;
  10433. p->status = status;
  10434. p->limit = p->stack + UPB_JSON_MAX_DEPTH;
  10435. p->accumulate_buf = NULL;
  10436. p->accumulate_buf_size = 0;
  10437. upb_bytessink_reset(&p->input_, &method->input_handler_, p);
  10438. json_parser_reset(p);
  10439. p->top->sink = output;
  10440. p->top->m = upb_handlers_msgdef(output.handlers);
  10441. if (is_wellknown_msg(p, UPB_WELLKNOWN_ANY)) {
  10442. p->top->is_any = true;
  10443. p->top->any_frame = json_parser_any_frame_new(p);
  10444. } else {
  10445. p->top->is_any = false;
  10446. p->top->any_frame = NULL;
  10447. }
  10448. set_name_table(p, p->top);
  10449. p->symtab = symtab;
  10450. p->ignore_json_unknown = ignore_json_unknown;
  10451. /* If this fails, uncomment and increase the value in parser.h. */
  10452. /* fprintf(stderr, "%zd\n", upb_arena_bytesallocated(arena) - size_before); */
  10453. UPB_ASSERT_DEBUGVAR(upb_arena_bytesallocated(arena) - size_before <=
  10454. UPB_JSON_PARSER_SIZE);
  10455. return p;
  10456. }
  10457. upb_bytessink upb_json_parser_input(upb_json_parser *p) {
  10458. return p->input_;
  10459. }
  10460. const upb_byteshandler *upb_json_parsermethod_inputhandler(
  10461. const upb_json_parsermethod *m) {
  10462. return &m->input_handler_;
  10463. }
  10464. upb_json_codecache *upb_json_codecache_new(void) {
  10465. upb_alloc *alloc;
  10466. upb_json_codecache *c;
  10467. c = upb_gmalloc(sizeof(*c));
  10468. c->arena = upb_arena_new();
  10469. alloc = upb_arena_alloc(c->arena);
  10470. upb_inttable_init2(&c->methods, UPB_CTYPE_CONSTPTR, alloc);
  10471. return c;
  10472. }
  10473. void upb_json_codecache_free(upb_json_codecache *c) {
  10474. upb_arena_free(c->arena);
  10475. upb_gfree(c);
  10476. }
  10477. const upb_json_parsermethod *upb_json_codecache_get(upb_json_codecache *c,
  10478. const upb_msgdef *md) {
  10479. upb_json_parsermethod *m;
  10480. upb_value v;
  10481. upb_msg_field_iter i;
  10482. upb_alloc *alloc = upb_arena_alloc(c->arena);
  10483. if (upb_inttable_lookupptr(&c->methods, md, &v)) {
  10484. return upb_value_getconstptr(v);
  10485. }
  10486. m = parsermethod_new(c, md);
  10487. v = upb_value_constptr(m);
  10488. if (!m) return NULL;
  10489. if (!upb_inttable_insertptr2(&c->methods, md, v, alloc)) return NULL;
  10490. /* Populate parser methods for all submessages, so the name tables will
  10491. * be available during parsing. */
  10492. for(upb_msg_field_begin(&i, md);
  10493. !upb_msg_field_done(&i);
  10494. upb_msg_field_next(&i)) {
  10495. upb_fielddef *f = upb_msg_iter_field(&i);
  10496. if (upb_fielddef_issubmsg(f)) {
  10497. const upb_msgdef *subdef = upb_fielddef_msgsubdef(f);
  10498. const upb_json_parsermethod *sub_method =
  10499. upb_json_codecache_get(c, subdef);
  10500. if (!sub_method) return NULL;
  10501. }
  10502. }
  10503. return m;
  10504. }
  10505. /*
  10506. ** This currently uses snprintf() to format primitives, and could be optimized
  10507. ** further.
  10508. */
  10509. #include <ctype.h>
  10510. #include <inttypes.h>
  10511. #include <stdint.h>
  10512. #include <string.h>
  10513. #include <time.h>
  10514. struct upb_json_printer {
  10515. upb_sink input_;
  10516. /* BytesSink closure. */
  10517. void *subc_;
  10518. upb_bytessink output_;
  10519. /* We track the depth so that we know when to emit startstr/endstr on the
  10520. * output. */
  10521. int depth_;
  10522. /* Have we emitted the first element? This state is necessary to emit commas
  10523. * without leaving a trailing comma in arrays/maps. We keep this state per
  10524. * frame depth.
  10525. *
  10526. * Why max_depth * 2? UPB_MAX_HANDLER_DEPTH counts depth as nested messages.
  10527. * We count frames (contexts in which we separate elements by commas) as both
  10528. * repeated fields and messages (maps), and the worst case is a
  10529. * message->repeated field->submessage->repeated field->... nesting. */
  10530. bool first_elem_[UPB_MAX_HANDLER_DEPTH * 2];
  10531. /* To print timestamp, printer needs to cache its seconds and nanos values
  10532. * and convert them when ending timestamp message. See comments of
  10533. * printer_sethandlers_timestamp for more detail. */
  10534. int64_t seconds;
  10535. int32_t nanos;
  10536. };
  10537. /* StringPiece; a pointer plus a length. */
  10538. typedef struct {
  10539. char *ptr;
  10540. size_t len;
  10541. } strpc;
  10542. void freestrpc(void *ptr) {
  10543. strpc *pc = ptr;
  10544. upb_gfree(pc->ptr);
  10545. upb_gfree(pc);
  10546. }
  10547. typedef struct {
  10548. bool preserve_fieldnames;
  10549. } upb_json_printercache;
  10550. /* Convert fielddef name to JSON name and return as a string piece. */
  10551. strpc *newstrpc(upb_handlers *h, const upb_fielddef *f,
  10552. bool preserve_fieldnames) {
  10553. /* TODO(haberman): handle malloc failure. */
  10554. strpc *ret = upb_gmalloc(sizeof(*ret));
  10555. if (preserve_fieldnames) {
  10556. ret->ptr = upb_gstrdup(upb_fielddef_name(f));
  10557. ret->len = strlen(ret->ptr);
  10558. } else {
  10559. ret->ptr = upb_gstrdup(upb_fielddef_jsonname(f));
  10560. ret->len = strlen(ret->ptr);
  10561. }
  10562. upb_handlers_addcleanup(h, ret, freestrpc);
  10563. return ret;
  10564. }
  10565. /* Convert a null-terminated const char* to a string piece. */
  10566. strpc *newstrpc_str(upb_handlers *h, const char * str) {
  10567. strpc * ret = upb_gmalloc(sizeof(*ret));
  10568. ret->ptr = upb_gstrdup(str);
  10569. ret->len = strlen(str);
  10570. upb_handlers_addcleanup(h, ret, freestrpc);
  10571. return ret;
  10572. }
  10573. /* ------------ JSON string printing: values, maps, arrays ------------------ */
  10574. static void print_data(
  10575. upb_json_printer *p, const char *buf, size_t len) {
  10576. /* TODO: Will need to change if we support pushback from the sink. */
  10577. size_t n = upb_bytessink_putbuf(p->output_, p->subc_, buf, len, NULL);
  10578. UPB_ASSERT(n == len);
  10579. }
  10580. static void print_comma(upb_json_printer *p) {
  10581. if (!p->first_elem_[p->depth_]) {
  10582. print_data(p, ",", 1);
  10583. }
  10584. p->first_elem_[p->depth_] = false;
  10585. }
  10586. /* Helpers that print properly formatted elements to the JSON output stream. */
  10587. /* Used for escaping control chars in strings. */
  10588. static const char kControlCharLimit = 0x20;
  10589. UPB_INLINE bool is_json_escaped(char c) {
  10590. /* See RFC 4627. */
  10591. unsigned char uc = (unsigned char)c;
  10592. return uc < kControlCharLimit || uc == '"' || uc == '\\';
  10593. }
  10594. UPB_INLINE const char* json_nice_escape(char c) {
  10595. switch (c) {
  10596. case '"': return "\\\"";
  10597. case '\\': return "\\\\";
  10598. case '\b': return "\\b";
  10599. case '\f': return "\\f";
  10600. case '\n': return "\\n";
  10601. case '\r': return "\\r";
  10602. case '\t': return "\\t";
  10603. default: return NULL;
  10604. }
  10605. }
  10606. /* Write a properly escaped string chunk. The surrounding quotes are *not*
  10607. * printed; this is so that the caller has the option of emitting the string
  10608. * content in chunks. */
  10609. static void putstring(upb_json_printer *p, const char *buf, size_t len) {
  10610. const char* unescaped_run = NULL;
  10611. unsigned int i;
  10612. for (i = 0; i < len; i++) {
  10613. char c = buf[i];
  10614. /* Handle escaping. */
  10615. if (is_json_escaped(c)) {
  10616. /* Use a "nice" escape, like \n, if one exists for this character. */
  10617. const char* escape = json_nice_escape(c);
  10618. /* If we don't have a specific 'nice' escape code, use a \uXXXX-style
  10619. * escape. */
  10620. char escape_buf[8];
  10621. if (!escape) {
  10622. unsigned char byte = (unsigned char)c;
  10623. _upb_snprintf(escape_buf, sizeof(escape_buf), "\\u%04x", (int)byte);
  10624. escape = escape_buf;
  10625. }
  10626. /* N.B. that we assume that the input encoding is equal to the output
  10627. * encoding (both UTF-8 for now), so for chars >= 0x20 and != \, ", we
  10628. * can simply pass the bytes through. */
  10629. /* If there's a current run of unescaped chars, print that run first. */
  10630. if (unescaped_run) {
  10631. print_data(p, unescaped_run, &buf[i] - unescaped_run);
  10632. unescaped_run = NULL;
  10633. }
  10634. /* Then print the escape code. */
  10635. print_data(p, escape, strlen(escape));
  10636. } else {
  10637. /* Add to the current unescaped run of characters. */
  10638. if (unescaped_run == NULL) {
  10639. unescaped_run = &buf[i];
  10640. }
  10641. }
  10642. }
  10643. /* If the string ended in a run of unescaped characters, print that last run. */
  10644. if (unescaped_run) {
  10645. print_data(p, unescaped_run, &buf[len] - unescaped_run);
  10646. }
  10647. }
  10648. #define CHKLENGTH(x) if (!(x)) return -1;
  10649. /* Helpers that format floating point values according to our custom formats.
  10650. * Right now we use %.8g and %.17g for float/double, respectively, to match
  10651. * proto2::util::JsonFormat's defaults. May want to change this later. */
  10652. const char neginf[] = "\"-Infinity\"";
  10653. const char inf[] = "\"Infinity\"";
  10654. static size_t fmt_double(double val, char* buf, size_t length) {
  10655. if (val == UPB_INFINITY) {
  10656. CHKLENGTH(length >= strlen(inf));
  10657. strcpy(buf, inf);
  10658. return strlen(inf);
  10659. } else if (val == -UPB_INFINITY) {
  10660. CHKLENGTH(length >= strlen(neginf));
  10661. strcpy(buf, neginf);
  10662. return strlen(neginf);
  10663. } else {
  10664. size_t n = _upb_snprintf(buf, length, "%.17g", val);
  10665. CHKLENGTH(n > 0 && n < length);
  10666. return n;
  10667. }
  10668. }
  10669. static size_t fmt_float(float val, char* buf, size_t length) {
  10670. size_t n = _upb_snprintf(buf, length, "%.8g", val);
  10671. CHKLENGTH(n > 0 && n < length);
  10672. return n;
  10673. }
  10674. static size_t fmt_bool(bool val, char* buf, size_t length) {
  10675. size_t n = _upb_snprintf(buf, length, "%s", (val ? "true" : "false"));
  10676. CHKLENGTH(n > 0 && n < length);
  10677. return n;
  10678. }
  10679. static size_t fmt_int64_as_number(int64_t val, char* buf, size_t length) {
  10680. size_t n = _upb_snprintf(buf, length, "%" PRId64, val);
  10681. CHKLENGTH(n > 0 && n < length);
  10682. return n;
  10683. }
  10684. static size_t fmt_uint64_as_number(uint64_t val, char* buf, size_t length) {
  10685. size_t n = _upb_snprintf(buf, length, "%" PRIu64, val);
  10686. CHKLENGTH(n > 0 && n < length);
  10687. return n;
  10688. }
  10689. static size_t fmt_int64_as_string(int64_t val, char* buf, size_t length) {
  10690. size_t n = _upb_snprintf(buf, length, "\"%" PRId64 "\"", val);
  10691. CHKLENGTH(n > 0 && n < length);
  10692. return n;
  10693. }
  10694. static size_t fmt_uint64_as_string(uint64_t val, char* buf, size_t length) {
  10695. size_t n = _upb_snprintf(buf, length, "\"%" PRIu64 "\"", val);
  10696. CHKLENGTH(n > 0 && n < length);
  10697. return n;
  10698. }
  10699. /* Print a map key given a field name. Called by scalar field handlers and by
  10700. * startseq for repeated fields. */
  10701. static bool putkey(void *closure, const void *handler_data) {
  10702. upb_json_printer *p = closure;
  10703. const strpc *key = handler_data;
  10704. print_comma(p);
  10705. print_data(p, "\"", 1);
  10706. putstring(p, key->ptr, key->len);
  10707. print_data(p, "\":", 2);
  10708. return true;
  10709. }
  10710. #define CHKFMT(val) if ((val) == (size_t)-1) return false;
  10711. #define CHK(val) if (!(val)) return false;
  10712. #define TYPE_HANDLERS(type, fmt_func) \
  10713. static bool put##type(void *closure, const void *handler_data, type val) { \
  10714. upb_json_printer *p = closure; \
  10715. char data[64]; \
  10716. size_t length = fmt_func(val, data, sizeof(data)); \
  10717. UPB_UNUSED(handler_data); \
  10718. CHKFMT(length); \
  10719. print_data(p, data, length); \
  10720. return true; \
  10721. } \
  10722. static bool scalar_##type(void *closure, const void *handler_data, \
  10723. type val) { \
  10724. CHK(putkey(closure, handler_data)); \
  10725. CHK(put##type(closure, handler_data, val)); \
  10726. return true; \
  10727. } \
  10728. static bool repeated_##type(void *closure, const void *handler_data, \
  10729. type val) { \
  10730. upb_json_printer *p = closure; \
  10731. print_comma(p); \
  10732. CHK(put##type(closure, handler_data, val)); \
  10733. return true; \
  10734. }
  10735. #define TYPE_HANDLERS_MAPKEY(type, fmt_func) \
  10736. static bool putmapkey_##type(void *closure, const void *handler_data, \
  10737. type val) { \
  10738. upb_json_printer *p = closure; \
  10739. char data[64]; \
  10740. size_t length = fmt_func(val, data, sizeof(data)); \
  10741. UPB_UNUSED(handler_data); \
  10742. print_data(p, "\"", 1); \
  10743. print_data(p, data, length); \
  10744. print_data(p, "\":", 2); \
  10745. return true; \
  10746. }
  10747. TYPE_HANDLERS(double, fmt_double)
  10748. TYPE_HANDLERS(float, fmt_float)
  10749. TYPE_HANDLERS(bool, fmt_bool)
  10750. TYPE_HANDLERS(int32_t, fmt_int64_as_number)
  10751. TYPE_HANDLERS(uint32_t, fmt_int64_as_number)
  10752. TYPE_HANDLERS(int64_t, fmt_int64_as_string)
  10753. TYPE_HANDLERS(uint64_t, fmt_uint64_as_string)
  10754. /* double and float are not allowed to be map keys. */
  10755. TYPE_HANDLERS_MAPKEY(bool, fmt_bool)
  10756. TYPE_HANDLERS_MAPKEY(int32_t, fmt_int64_as_number)
  10757. TYPE_HANDLERS_MAPKEY(uint32_t, fmt_int64_as_number)
  10758. TYPE_HANDLERS_MAPKEY(int64_t, fmt_int64_as_number)
  10759. TYPE_HANDLERS_MAPKEY(uint64_t, fmt_uint64_as_number)
  10760. #undef TYPE_HANDLERS
  10761. #undef TYPE_HANDLERS_MAPKEY
  10762. typedef struct {
  10763. void *keyname;
  10764. const upb_enumdef *enumdef;
  10765. } EnumHandlerData;
  10766. static bool scalar_enum(void *closure, const void *handler_data,
  10767. int32_t val) {
  10768. const EnumHandlerData *hd = handler_data;
  10769. upb_json_printer *p = closure;
  10770. const char *symbolic_name;
  10771. CHK(putkey(closure, hd->keyname));
  10772. symbolic_name = upb_enumdef_iton(hd->enumdef, val);
  10773. if (symbolic_name) {
  10774. print_data(p, "\"", 1);
  10775. putstring(p, symbolic_name, strlen(symbolic_name));
  10776. print_data(p, "\"", 1);
  10777. } else {
  10778. putint32_t(closure, NULL, val);
  10779. }
  10780. return true;
  10781. }
  10782. static void print_enum_symbolic_name(upb_json_printer *p,
  10783. const upb_enumdef *def,
  10784. int32_t val) {
  10785. const char *symbolic_name = upb_enumdef_iton(def, val);
  10786. if (symbolic_name) {
  10787. print_data(p, "\"", 1);
  10788. putstring(p, symbolic_name, strlen(symbolic_name));
  10789. print_data(p, "\"", 1);
  10790. } else {
  10791. putint32_t(p, NULL, val);
  10792. }
  10793. }
  10794. static bool repeated_enum(void *closure, const void *handler_data,
  10795. int32_t val) {
  10796. const EnumHandlerData *hd = handler_data;
  10797. upb_json_printer *p = closure;
  10798. print_comma(p);
  10799. print_enum_symbolic_name(p, hd->enumdef, val);
  10800. return true;
  10801. }
  10802. static bool mapvalue_enum(void *closure, const void *handler_data,
  10803. int32_t val) {
  10804. const EnumHandlerData *hd = handler_data;
  10805. upb_json_printer *p = closure;
  10806. print_enum_symbolic_name(p, hd->enumdef, val);
  10807. return true;
  10808. }
  10809. static void *scalar_startsubmsg(void *closure, const void *handler_data) {
  10810. return putkey(closure, handler_data) ? closure : UPB_BREAK;
  10811. }
  10812. static void *repeated_startsubmsg(void *closure, const void *handler_data) {
  10813. upb_json_printer *p = closure;
  10814. UPB_UNUSED(handler_data);
  10815. print_comma(p);
  10816. return closure;
  10817. }
  10818. static void start_frame(upb_json_printer *p) {
  10819. p->depth_++;
  10820. p->first_elem_[p->depth_] = true;
  10821. print_data(p, "{", 1);
  10822. }
  10823. static void end_frame(upb_json_printer *p) {
  10824. print_data(p, "}", 1);
  10825. p->depth_--;
  10826. }
  10827. static bool printer_startmsg(void *closure, const void *handler_data) {
  10828. upb_json_printer *p = closure;
  10829. UPB_UNUSED(handler_data);
  10830. if (p->depth_ == 0) {
  10831. upb_bytessink_start(p->output_, 0, &p->subc_);
  10832. }
  10833. start_frame(p);
  10834. return true;
  10835. }
  10836. static bool printer_endmsg(void *closure, const void *handler_data, upb_status *s) {
  10837. upb_json_printer *p = closure;
  10838. UPB_UNUSED(handler_data);
  10839. UPB_UNUSED(s);
  10840. end_frame(p);
  10841. if (p->depth_ == 0) {
  10842. upb_bytessink_end(p->output_);
  10843. }
  10844. return true;
  10845. }
  10846. static void *startseq(void *closure, const void *handler_data) {
  10847. upb_json_printer *p = closure;
  10848. CHK(putkey(closure, handler_data));
  10849. p->depth_++;
  10850. p->first_elem_[p->depth_] = true;
  10851. print_data(p, "[", 1);
  10852. return closure;
  10853. }
  10854. static bool endseq(void *closure, const void *handler_data) {
  10855. upb_json_printer *p = closure;
  10856. UPB_UNUSED(handler_data);
  10857. print_data(p, "]", 1);
  10858. p->depth_--;
  10859. return true;
  10860. }
  10861. static void *startmap(void *closure, const void *handler_data) {
  10862. upb_json_printer *p = closure;
  10863. CHK(putkey(closure, handler_data));
  10864. p->depth_++;
  10865. p->first_elem_[p->depth_] = true;
  10866. print_data(p, "{", 1);
  10867. return closure;
  10868. }
  10869. static bool endmap(void *closure, const void *handler_data) {
  10870. upb_json_printer *p = closure;
  10871. UPB_UNUSED(handler_data);
  10872. print_data(p, "}", 1);
  10873. p->depth_--;
  10874. return true;
  10875. }
  10876. static size_t putstr(void *closure, const void *handler_data, const char *str,
  10877. size_t len, const upb_bufhandle *handle) {
  10878. upb_json_printer *p = closure;
  10879. UPB_UNUSED(handler_data);
  10880. UPB_UNUSED(handle);
  10881. putstring(p, str, len);
  10882. return len;
  10883. }
  10884. /* This has to Base64 encode the bytes, because JSON has no "bytes" type. */
  10885. static size_t putbytes(void *closure, const void *handler_data, const char *str,
  10886. size_t len, const upb_bufhandle *handle) {
  10887. upb_json_printer *p = closure;
  10888. /* This is the regular base64, not the "web-safe" version. */
  10889. static const char base64[] =
  10890. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  10891. /* Base64-encode. */
  10892. char data[16000];
  10893. const char *limit = data + sizeof(data);
  10894. const unsigned char *from = (const unsigned char*)str;
  10895. char *to = data;
  10896. size_t remaining = len;
  10897. size_t bytes;
  10898. UPB_UNUSED(handler_data);
  10899. UPB_UNUSED(handle);
  10900. print_data(p, "\"", 1);
  10901. while (remaining > 2) {
  10902. if (limit - to < 4) {
  10903. bytes = to - data;
  10904. putstring(p, data, bytes);
  10905. to = data;
  10906. }
  10907. to[0] = base64[from[0] >> 2];
  10908. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  10909. to[2] = base64[((from[1] & 0xf) << 2) | (from[2] >> 6)];
  10910. to[3] = base64[from[2] & 0x3f];
  10911. remaining -= 3;
  10912. to += 4;
  10913. from += 3;
  10914. }
  10915. switch (remaining) {
  10916. case 2:
  10917. to[0] = base64[from[0] >> 2];
  10918. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  10919. to[2] = base64[(from[1] & 0xf) << 2];
  10920. to[3] = '=';
  10921. to += 4;
  10922. from += 2;
  10923. break;
  10924. case 1:
  10925. to[0] = base64[from[0] >> 2];
  10926. to[1] = base64[((from[0] & 0x3) << 4)];
  10927. to[2] = '=';
  10928. to[3] = '=';
  10929. to += 4;
  10930. from += 1;
  10931. break;
  10932. }
  10933. bytes = to - data;
  10934. putstring(p, data, bytes);
  10935. print_data(p, "\"", 1);
  10936. return len;
  10937. }
  10938. static void *scalar_startstr(void *closure, const void *handler_data,
  10939. size_t size_hint) {
  10940. upb_json_printer *p = closure;
  10941. UPB_UNUSED(handler_data);
  10942. UPB_UNUSED(size_hint);
  10943. CHK(putkey(closure, handler_data));
  10944. print_data(p, "\"", 1);
  10945. return p;
  10946. }
  10947. static size_t scalar_str(void *closure, const void *handler_data,
  10948. const char *str, size_t len,
  10949. const upb_bufhandle *handle) {
  10950. CHK(putstr(closure, handler_data, str, len, handle));
  10951. return len;
  10952. }
  10953. static bool scalar_endstr(void *closure, const void *handler_data) {
  10954. upb_json_printer *p = closure;
  10955. UPB_UNUSED(handler_data);
  10956. print_data(p, "\"", 1);
  10957. return true;
  10958. }
  10959. static void *repeated_startstr(void *closure, const void *handler_data,
  10960. size_t size_hint) {
  10961. upb_json_printer *p = closure;
  10962. UPB_UNUSED(handler_data);
  10963. UPB_UNUSED(size_hint);
  10964. print_comma(p);
  10965. print_data(p, "\"", 1);
  10966. return p;
  10967. }
  10968. static size_t repeated_str(void *closure, const void *handler_data,
  10969. const char *str, size_t len,
  10970. const upb_bufhandle *handle) {
  10971. CHK(putstr(closure, handler_data, str, len, handle));
  10972. return len;
  10973. }
  10974. static bool repeated_endstr(void *closure, const void *handler_data) {
  10975. upb_json_printer *p = closure;
  10976. UPB_UNUSED(handler_data);
  10977. print_data(p, "\"", 1);
  10978. return true;
  10979. }
  10980. static void *mapkeyval_startstr(void *closure, const void *handler_data,
  10981. size_t size_hint) {
  10982. upb_json_printer *p = closure;
  10983. UPB_UNUSED(handler_data);
  10984. UPB_UNUSED(size_hint);
  10985. print_data(p, "\"", 1);
  10986. return p;
  10987. }
  10988. static size_t mapkey_str(void *closure, const void *handler_data,
  10989. const char *str, size_t len,
  10990. const upb_bufhandle *handle) {
  10991. CHK(putstr(closure, handler_data, str, len, handle));
  10992. return len;
  10993. }
  10994. static bool mapkey_endstr(void *closure, const void *handler_data) {
  10995. upb_json_printer *p = closure;
  10996. UPB_UNUSED(handler_data);
  10997. print_data(p, "\":", 2);
  10998. return true;
  10999. }
  11000. static bool mapvalue_endstr(void *closure, const void *handler_data) {
  11001. upb_json_printer *p = closure;
  11002. UPB_UNUSED(handler_data);
  11003. print_data(p, "\"", 1);
  11004. return true;
  11005. }
  11006. static size_t scalar_bytes(void *closure, const void *handler_data,
  11007. const char *str, size_t len,
  11008. const upb_bufhandle *handle) {
  11009. CHK(putkey(closure, handler_data));
  11010. CHK(putbytes(closure, handler_data, str, len, handle));
  11011. return len;
  11012. }
  11013. static size_t repeated_bytes(void *closure, const void *handler_data,
  11014. const char *str, size_t len,
  11015. const upb_bufhandle *handle) {
  11016. upb_json_printer *p = closure;
  11017. print_comma(p);
  11018. CHK(putbytes(closure, handler_data, str, len, handle));
  11019. return len;
  11020. }
  11021. static size_t mapkey_bytes(void *closure, const void *handler_data,
  11022. const char *str, size_t len,
  11023. const upb_bufhandle *handle) {
  11024. upb_json_printer *p = closure;
  11025. CHK(putbytes(closure, handler_data, str, len, handle));
  11026. print_data(p, ":", 1);
  11027. return len;
  11028. }
  11029. static void set_enum_hd(upb_handlers *h,
  11030. const upb_fielddef *f,
  11031. bool preserve_fieldnames,
  11032. upb_handlerattr *attr) {
  11033. EnumHandlerData *hd = upb_gmalloc(sizeof(EnumHandlerData));
  11034. hd->enumdef = upb_fielddef_enumsubdef(f);
  11035. hd->keyname = newstrpc(h, f, preserve_fieldnames);
  11036. upb_handlers_addcleanup(h, hd, upb_gfree);
  11037. attr->handler_data = hd;
  11038. }
  11039. /* Set up handlers for a mapentry submessage (i.e., an individual key/value pair
  11040. * in a map).
  11041. *
  11042. * TODO: Handle missing key, missing value, out-of-order key/value, or repeated
  11043. * key or value cases properly. The right way to do this is to allocate a
  11044. * temporary structure at the start of a mapentry submessage, store key and
  11045. * value data in it as key and value handlers are called, and then print the
  11046. * key/value pair once at the end of the submessage. If we don't do this, we
  11047. * should at least detect the case and throw an error. However, so far all of
  11048. * our sources that emit mapentry messages do so canonically (with one key
  11049. * field, and then one value field), so this is not a pressing concern at the
  11050. * moment. */
  11051. void printer_sethandlers_mapentry(const void *closure, bool preserve_fieldnames,
  11052. upb_handlers *h) {
  11053. const upb_msgdef *md = upb_handlers_msgdef(h);
  11054. /* A mapentry message is printed simply as '"key": value'. Rather than
  11055. * special-case key and value for every type below, we just handle both
  11056. * fields explicitly here. */
  11057. const upb_fielddef* key_field = upb_msgdef_itof(md, UPB_MAPENTRY_KEY);
  11058. const upb_fielddef* value_field = upb_msgdef_itof(md, UPB_MAPENTRY_VALUE);
  11059. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11060. UPB_UNUSED(closure);
  11061. switch (upb_fielddef_type(key_field)) {
  11062. case UPB_TYPE_INT32:
  11063. upb_handlers_setint32(h, key_field, putmapkey_int32_t, &empty_attr);
  11064. break;
  11065. case UPB_TYPE_INT64:
  11066. upb_handlers_setint64(h, key_field, putmapkey_int64_t, &empty_attr);
  11067. break;
  11068. case UPB_TYPE_UINT32:
  11069. upb_handlers_setuint32(h, key_field, putmapkey_uint32_t, &empty_attr);
  11070. break;
  11071. case UPB_TYPE_UINT64:
  11072. upb_handlers_setuint64(h, key_field, putmapkey_uint64_t, &empty_attr);
  11073. break;
  11074. case UPB_TYPE_BOOL:
  11075. upb_handlers_setbool(h, key_field, putmapkey_bool, &empty_attr);
  11076. break;
  11077. case UPB_TYPE_STRING:
  11078. upb_handlers_setstartstr(h, key_field, mapkeyval_startstr, &empty_attr);
  11079. upb_handlers_setstring(h, key_field, mapkey_str, &empty_attr);
  11080. upb_handlers_setendstr(h, key_field, mapkey_endstr, &empty_attr);
  11081. break;
  11082. case UPB_TYPE_BYTES:
  11083. upb_handlers_setstring(h, key_field, mapkey_bytes, &empty_attr);
  11084. break;
  11085. default:
  11086. UPB_ASSERT(false);
  11087. break;
  11088. }
  11089. switch (upb_fielddef_type(value_field)) {
  11090. case UPB_TYPE_INT32:
  11091. upb_handlers_setint32(h, value_field, putint32_t, &empty_attr);
  11092. break;
  11093. case UPB_TYPE_INT64:
  11094. upb_handlers_setint64(h, value_field, putint64_t, &empty_attr);
  11095. break;
  11096. case UPB_TYPE_UINT32:
  11097. upb_handlers_setuint32(h, value_field, putuint32_t, &empty_attr);
  11098. break;
  11099. case UPB_TYPE_UINT64:
  11100. upb_handlers_setuint64(h, value_field, putuint64_t, &empty_attr);
  11101. break;
  11102. case UPB_TYPE_BOOL:
  11103. upb_handlers_setbool(h, value_field, putbool, &empty_attr);
  11104. break;
  11105. case UPB_TYPE_FLOAT:
  11106. upb_handlers_setfloat(h, value_field, putfloat, &empty_attr);
  11107. break;
  11108. case UPB_TYPE_DOUBLE:
  11109. upb_handlers_setdouble(h, value_field, putdouble, &empty_attr);
  11110. break;
  11111. case UPB_TYPE_STRING:
  11112. upb_handlers_setstartstr(h, value_field, mapkeyval_startstr, &empty_attr);
  11113. upb_handlers_setstring(h, value_field, putstr, &empty_attr);
  11114. upb_handlers_setendstr(h, value_field, mapvalue_endstr, &empty_attr);
  11115. break;
  11116. case UPB_TYPE_BYTES:
  11117. upb_handlers_setstring(h, value_field, putbytes, &empty_attr);
  11118. break;
  11119. case UPB_TYPE_ENUM: {
  11120. upb_handlerattr enum_attr = UPB_HANDLERATTR_INIT;
  11121. set_enum_hd(h, value_field, preserve_fieldnames, &enum_attr);
  11122. upb_handlers_setint32(h, value_field, mapvalue_enum, &enum_attr);
  11123. break;
  11124. }
  11125. case UPB_TYPE_MESSAGE:
  11126. /* No handler necessary -- the submsg handlers will print the message
  11127. * as appropriate. */
  11128. break;
  11129. }
  11130. }
  11131. static bool putseconds(void *closure, const void *handler_data,
  11132. int64_t seconds) {
  11133. upb_json_printer *p = closure;
  11134. p->seconds = seconds;
  11135. UPB_UNUSED(handler_data);
  11136. return true;
  11137. }
  11138. static bool putnanos(void *closure, const void *handler_data,
  11139. int32_t nanos) {
  11140. upb_json_printer *p = closure;
  11141. p->nanos = nanos;
  11142. UPB_UNUSED(handler_data);
  11143. return true;
  11144. }
  11145. static void *scalar_startstr_nokey(void *closure, const void *handler_data,
  11146. size_t size_hint) {
  11147. upb_json_printer *p = closure;
  11148. UPB_UNUSED(handler_data);
  11149. UPB_UNUSED(size_hint);
  11150. print_data(p, "\"", 1);
  11151. return p;
  11152. }
  11153. static size_t putstr_nokey(void *closure, const void *handler_data,
  11154. const char *str, size_t len,
  11155. const upb_bufhandle *handle) {
  11156. upb_json_printer *p = closure;
  11157. UPB_UNUSED(handler_data);
  11158. UPB_UNUSED(handle);
  11159. print_data(p, "\"", 1);
  11160. putstring(p, str, len);
  11161. print_data(p, "\"", 1);
  11162. return len + 2;
  11163. }
  11164. static void *startseq_nokey(void *closure, const void *handler_data) {
  11165. upb_json_printer *p = closure;
  11166. UPB_UNUSED(handler_data);
  11167. p->depth_++;
  11168. p->first_elem_[p->depth_] = true;
  11169. print_data(p, "[", 1);
  11170. return closure;
  11171. }
  11172. static void *startseq_fieldmask(void *closure, const void *handler_data) {
  11173. upb_json_printer *p = closure;
  11174. UPB_UNUSED(handler_data);
  11175. p->depth_++;
  11176. p->first_elem_[p->depth_] = true;
  11177. return closure;
  11178. }
  11179. static bool endseq_fieldmask(void *closure, const void *handler_data) {
  11180. upb_json_printer *p = closure;
  11181. UPB_UNUSED(handler_data);
  11182. p->depth_--;
  11183. return true;
  11184. }
  11185. static void *repeated_startstr_fieldmask(
  11186. void *closure, const void *handler_data,
  11187. size_t size_hint) {
  11188. upb_json_printer *p = closure;
  11189. UPB_UNUSED(handler_data);
  11190. UPB_UNUSED(size_hint);
  11191. print_comma(p);
  11192. return p;
  11193. }
  11194. static size_t repeated_str_fieldmask(
  11195. void *closure, const void *handler_data,
  11196. const char *str, size_t len,
  11197. const upb_bufhandle *handle) {
  11198. const char* limit = str + len;
  11199. bool upper = false;
  11200. size_t result_len = 0;
  11201. for (; str < limit; str++) {
  11202. if (*str == '_') {
  11203. upper = true;
  11204. continue;
  11205. }
  11206. if (upper && *str >= 'a' && *str <= 'z') {
  11207. char upper_char = toupper(*str);
  11208. CHK(putstr(closure, handler_data, &upper_char, 1, handle));
  11209. } else {
  11210. CHK(putstr(closure, handler_data, str, 1, handle));
  11211. }
  11212. upper = false;
  11213. result_len++;
  11214. }
  11215. return result_len;
  11216. }
  11217. static void *startmap_nokey(void *closure, const void *handler_data) {
  11218. upb_json_printer *p = closure;
  11219. UPB_UNUSED(handler_data);
  11220. p->depth_++;
  11221. p->first_elem_[p->depth_] = true;
  11222. print_data(p, "{", 1);
  11223. return closure;
  11224. }
  11225. static bool putnull(void *closure, const void *handler_data,
  11226. int32_t null) {
  11227. upb_json_printer *p = closure;
  11228. print_data(p, "null", 4);
  11229. UPB_UNUSED(handler_data);
  11230. UPB_UNUSED(null);
  11231. return true;
  11232. }
  11233. static bool printer_startdurationmsg(void *closure, const void *handler_data) {
  11234. upb_json_printer *p = closure;
  11235. UPB_UNUSED(handler_data);
  11236. if (p->depth_ == 0) {
  11237. upb_bytessink_start(p->output_, 0, &p->subc_);
  11238. }
  11239. return true;
  11240. }
  11241. #define UPB_DURATION_MAX_JSON_LEN 23
  11242. #define UPB_DURATION_MAX_NANO_LEN 9
  11243. static bool printer_enddurationmsg(void *closure, const void *handler_data,
  11244. upb_status *s) {
  11245. upb_json_printer *p = closure;
  11246. char buffer[UPB_DURATION_MAX_JSON_LEN];
  11247. size_t base_len;
  11248. size_t curr;
  11249. size_t i;
  11250. memset(buffer, 0, UPB_DURATION_MAX_JSON_LEN);
  11251. if (p->seconds < -315576000000) {
  11252. upb_status_seterrf(s, "error parsing duration: "
  11253. "minimum acceptable value is "
  11254. "-315576000000");
  11255. return false;
  11256. }
  11257. if (p->seconds > 315576000000) {
  11258. upb_status_seterrf(s, "error serializing duration: "
  11259. "maximum acceptable value is "
  11260. "315576000000");
  11261. return false;
  11262. }
  11263. _upb_snprintf(buffer, sizeof(buffer), "%ld", (long)p->seconds);
  11264. base_len = strlen(buffer);
  11265. if (p->nanos != 0) {
  11266. char nanos_buffer[UPB_DURATION_MAX_NANO_LEN + 3];
  11267. _upb_snprintf(nanos_buffer, sizeof(nanos_buffer), "%.9f",
  11268. p->nanos / 1000000000.0);
  11269. /* Remove trailing 0. */
  11270. for (i = UPB_DURATION_MAX_NANO_LEN + 2;
  11271. nanos_buffer[i] == '0'; i--) {
  11272. nanos_buffer[i] = 0;
  11273. }
  11274. strcpy(buffer + base_len, nanos_buffer + 1);
  11275. }
  11276. curr = strlen(buffer);
  11277. strcpy(buffer + curr, "s");
  11278. p->seconds = 0;
  11279. p->nanos = 0;
  11280. print_data(p, "\"", 1);
  11281. print_data(p, buffer, strlen(buffer));
  11282. print_data(p, "\"", 1);
  11283. if (p->depth_ == 0) {
  11284. upb_bytessink_end(p->output_);
  11285. }
  11286. UPB_UNUSED(handler_data);
  11287. return true;
  11288. }
  11289. static bool printer_starttimestampmsg(void *closure, const void *handler_data) {
  11290. upb_json_printer *p = closure;
  11291. UPB_UNUSED(handler_data);
  11292. if (p->depth_ == 0) {
  11293. upb_bytessink_start(p->output_, 0, &p->subc_);
  11294. }
  11295. return true;
  11296. }
  11297. #define UPB_TIMESTAMP_MAX_JSON_LEN 31
  11298. #define UPB_TIMESTAMP_BEFORE_NANO_LEN 19
  11299. #define UPB_TIMESTAMP_MAX_NANO_LEN 9
  11300. static bool printer_endtimestampmsg(void *closure, const void *handler_data,
  11301. upb_status *s) {
  11302. upb_json_printer *p = closure;
  11303. char buffer[UPB_TIMESTAMP_MAX_JSON_LEN];
  11304. time_t time = p->seconds;
  11305. size_t curr;
  11306. size_t i;
  11307. size_t year_length =
  11308. strftime(buffer, UPB_TIMESTAMP_MAX_JSON_LEN, "%Y", gmtime(&time));
  11309. if (p->seconds < -62135596800) {
  11310. upb_status_seterrf(s, "error parsing timestamp: "
  11311. "minimum acceptable value is "
  11312. "0001-01-01T00:00:00Z");
  11313. return false;
  11314. }
  11315. if (p->seconds > 253402300799) {
  11316. upb_status_seterrf(s, "error parsing timestamp: "
  11317. "maximum acceptable value is "
  11318. "9999-12-31T23:59:59Z");
  11319. return false;
  11320. }
  11321. /* strftime doesn't guarantee 4 digits for year. Prepend 0 by ourselves. */
  11322. for (i = 0; i < 4 - year_length; i++) {
  11323. buffer[i] = '0';
  11324. }
  11325. strftime(buffer + (4 - year_length), UPB_TIMESTAMP_MAX_JSON_LEN,
  11326. "%Y-%m-%dT%H:%M:%S", gmtime(&time));
  11327. if (p->nanos != 0) {
  11328. char nanos_buffer[UPB_TIMESTAMP_MAX_NANO_LEN + 3];
  11329. _upb_snprintf(nanos_buffer, sizeof(nanos_buffer), "%.9f",
  11330. p->nanos / 1000000000.0);
  11331. /* Remove trailing 0. */
  11332. for (i = UPB_TIMESTAMP_MAX_NANO_LEN + 2;
  11333. nanos_buffer[i] == '0'; i--) {
  11334. nanos_buffer[i] = 0;
  11335. }
  11336. strcpy(buffer + UPB_TIMESTAMP_BEFORE_NANO_LEN, nanos_buffer + 1);
  11337. }
  11338. curr = strlen(buffer);
  11339. strcpy(buffer + curr, "Z");
  11340. p->seconds = 0;
  11341. p->nanos = 0;
  11342. print_data(p, "\"", 1);
  11343. print_data(p, buffer, strlen(buffer));
  11344. print_data(p, "\"", 1);
  11345. if (p->depth_ == 0) {
  11346. upb_bytessink_end(p->output_);
  11347. }
  11348. UPB_UNUSED(handler_data);
  11349. UPB_UNUSED(s);
  11350. return true;
  11351. }
  11352. static bool printer_startmsg_noframe(void *closure, const void *handler_data) {
  11353. upb_json_printer *p = closure;
  11354. UPB_UNUSED(handler_data);
  11355. if (p->depth_ == 0) {
  11356. upb_bytessink_start(p->output_, 0, &p->subc_);
  11357. }
  11358. return true;
  11359. }
  11360. static bool printer_endmsg_noframe(
  11361. void *closure, const void *handler_data, upb_status *s) {
  11362. upb_json_printer *p = closure;
  11363. UPB_UNUSED(handler_data);
  11364. UPB_UNUSED(s);
  11365. if (p->depth_ == 0) {
  11366. upb_bytessink_end(p->output_);
  11367. }
  11368. return true;
  11369. }
  11370. static bool printer_startmsg_fieldmask(
  11371. void *closure, const void *handler_data) {
  11372. upb_json_printer *p = closure;
  11373. UPB_UNUSED(handler_data);
  11374. if (p->depth_ == 0) {
  11375. upb_bytessink_start(p->output_, 0, &p->subc_);
  11376. }
  11377. print_data(p, "\"", 1);
  11378. return true;
  11379. }
  11380. static bool printer_endmsg_fieldmask(
  11381. void *closure, const void *handler_data, upb_status *s) {
  11382. upb_json_printer *p = closure;
  11383. UPB_UNUSED(handler_data);
  11384. UPB_UNUSED(s);
  11385. print_data(p, "\"", 1);
  11386. if (p->depth_ == 0) {
  11387. upb_bytessink_end(p->output_);
  11388. }
  11389. return true;
  11390. }
  11391. static void *scalar_startstr_onlykey(
  11392. void *closure, const void *handler_data, size_t size_hint) {
  11393. upb_json_printer *p = closure;
  11394. UPB_UNUSED(size_hint);
  11395. CHK(putkey(closure, handler_data));
  11396. return p;
  11397. }
  11398. /* Set up handlers for an Any submessage. */
  11399. void printer_sethandlers_any(const void *closure, upb_handlers *h) {
  11400. const upb_msgdef *md = upb_handlers_msgdef(h);
  11401. const upb_fielddef* type_field = upb_msgdef_itof(md, UPB_ANY_TYPE);
  11402. const upb_fielddef* value_field = upb_msgdef_itof(md, UPB_ANY_VALUE);
  11403. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11404. /* type_url's json name is "@type" */
  11405. upb_handlerattr type_name_attr = UPB_HANDLERATTR_INIT;
  11406. upb_handlerattr value_name_attr = UPB_HANDLERATTR_INIT;
  11407. strpc *type_url_json_name = newstrpc_str(h, "@type");
  11408. strpc *value_json_name = newstrpc_str(h, "value");
  11409. type_name_attr.handler_data = type_url_json_name;
  11410. value_name_attr.handler_data = value_json_name;
  11411. /* Set up handlers. */
  11412. upb_handlers_setstartmsg(h, printer_startmsg, &empty_attr);
  11413. upb_handlers_setendmsg(h, printer_endmsg, &empty_attr);
  11414. upb_handlers_setstartstr(h, type_field, scalar_startstr, &type_name_attr);
  11415. upb_handlers_setstring(h, type_field, scalar_str, &empty_attr);
  11416. upb_handlers_setendstr(h, type_field, scalar_endstr, &empty_attr);
  11417. /* This is not the full and correct JSON encoding for the Any value field. It
  11418. * requires further processing by the wrapper code based on the type URL.
  11419. */
  11420. upb_handlers_setstartstr(h, value_field, scalar_startstr_onlykey,
  11421. &value_name_attr);
  11422. UPB_UNUSED(closure);
  11423. }
  11424. /* Set up handlers for a fieldmask submessage. */
  11425. void printer_sethandlers_fieldmask(const void *closure, upb_handlers *h) {
  11426. const upb_msgdef *md = upb_handlers_msgdef(h);
  11427. const upb_fielddef* f = upb_msgdef_itof(md, 1);
  11428. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11429. upb_handlers_setstartseq(h, f, startseq_fieldmask, &empty_attr);
  11430. upb_handlers_setendseq(h, f, endseq_fieldmask, &empty_attr);
  11431. upb_handlers_setstartmsg(h, printer_startmsg_fieldmask, &empty_attr);
  11432. upb_handlers_setendmsg(h, printer_endmsg_fieldmask, &empty_attr);
  11433. upb_handlers_setstartstr(h, f, repeated_startstr_fieldmask, &empty_attr);
  11434. upb_handlers_setstring(h, f, repeated_str_fieldmask, &empty_attr);
  11435. UPB_UNUSED(closure);
  11436. }
  11437. /* Set up handlers for a duration submessage. */
  11438. void printer_sethandlers_duration(const void *closure, upb_handlers *h) {
  11439. const upb_msgdef *md = upb_handlers_msgdef(h);
  11440. const upb_fielddef* seconds_field =
  11441. upb_msgdef_itof(md, UPB_DURATION_SECONDS);
  11442. const upb_fielddef* nanos_field =
  11443. upb_msgdef_itof(md, UPB_DURATION_NANOS);
  11444. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11445. upb_handlers_setstartmsg(h, printer_startdurationmsg, &empty_attr);
  11446. upb_handlers_setint64(h, seconds_field, putseconds, &empty_attr);
  11447. upb_handlers_setint32(h, nanos_field, putnanos, &empty_attr);
  11448. upb_handlers_setendmsg(h, printer_enddurationmsg, &empty_attr);
  11449. UPB_UNUSED(closure);
  11450. }
  11451. /* Set up handlers for a timestamp submessage. Instead of printing fields
  11452. * separately, the json representation of timestamp follows RFC 3339 */
  11453. void printer_sethandlers_timestamp(const void *closure, upb_handlers *h) {
  11454. const upb_msgdef *md = upb_handlers_msgdef(h);
  11455. const upb_fielddef* seconds_field =
  11456. upb_msgdef_itof(md, UPB_TIMESTAMP_SECONDS);
  11457. const upb_fielddef* nanos_field =
  11458. upb_msgdef_itof(md, UPB_TIMESTAMP_NANOS);
  11459. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11460. upb_handlers_setstartmsg(h, printer_starttimestampmsg, &empty_attr);
  11461. upb_handlers_setint64(h, seconds_field, putseconds, &empty_attr);
  11462. upb_handlers_setint32(h, nanos_field, putnanos, &empty_attr);
  11463. upb_handlers_setendmsg(h, printer_endtimestampmsg, &empty_attr);
  11464. UPB_UNUSED(closure);
  11465. }
  11466. void printer_sethandlers_value(const void *closure, upb_handlers *h) {
  11467. const upb_msgdef *md = upb_handlers_msgdef(h);
  11468. upb_msg_field_iter i;
  11469. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11470. upb_handlers_setstartmsg(h, printer_startmsg_noframe, &empty_attr);
  11471. upb_handlers_setendmsg(h, printer_endmsg_noframe, &empty_attr);
  11472. upb_msg_field_begin(&i, md);
  11473. for(; !upb_msg_field_done(&i); upb_msg_field_next(&i)) {
  11474. const upb_fielddef *f = upb_msg_iter_field(&i);
  11475. switch (upb_fielddef_type(f)) {
  11476. case UPB_TYPE_ENUM:
  11477. upb_handlers_setint32(h, f, putnull, &empty_attr);
  11478. break;
  11479. case UPB_TYPE_DOUBLE:
  11480. upb_handlers_setdouble(h, f, putdouble, &empty_attr);
  11481. break;
  11482. case UPB_TYPE_STRING:
  11483. upb_handlers_setstartstr(h, f, scalar_startstr_nokey, &empty_attr);
  11484. upb_handlers_setstring(h, f, scalar_str, &empty_attr);
  11485. upb_handlers_setendstr(h, f, scalar_endstr, &empty_attr);
  11486. break;
  11487. case UPB_TYPE_BOOL:
  11488. upb_handlers_setbool(h, f, putbool, &empty_attr);
  11489. break;
  11490. case UPB_TYPE_MESSAGE:
  11491. break;
  11492. default:
  11493. UPB_ASSERT(false);
  11494. break;
  11495. }
  11496. }
  11497. UPB_UNUSED(closure);
  11498. }
  11499. #define WRAPPER_SETHANDLERS(wrapper, type, putmethod) \
  11500. void printer_sethandlers_##wrapper(const void *closure, upb_handlers *h) { \
  11501. const upb_msgdef *md = upb_handlers_msgdef(h); \
  11502. const upb_fielddef* f = upb_msgdef_itof(md, 1); \
  11503. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT; \
  11504. upb_handlers_setstartmsg(h, printer_startmsg_noframe, &empty_attr); \
  11505. upb_handlers_setendmsg(h, printer_endmsg_noframe, &empty_attr); \
  11506. upb_handlers_set##type(h, f, putmethod, &empty_attr); \
  11507. UPB_UNUSED(closure); \
  11508. }
  11509. WRAPPER_SETHANDLERS(doublevalue, double, putdouble)
  11510. WRAPPER_SETHANDLERS(floatvalue, float, putfloat)
  11511. WRAPPER_SETHANDLERS(int64value, int64, putint64_t)
  11512. WRAPPER_SETHANDLERS(uint64value, uint64, putuint64_t)
  11513. WRAPPER_SETHANDLERS(int32value, int32, putint32_t)
  11514. WRAPPER_SETHANDLERS(uint32value, uint32, putuint32_t)
  11515. WRAPPER_SETHANDLERS(boolvalue, bool, putbool)
  11516. WRAPPER_SETHANDLERS(stringvalue, string, putstr_nokey)
  11517. WRAPPER_SETHANDLERS(bytesvalue, string, putbytes)
  11518. #undef WRAPPER_SETHANDLERS
  11519. void printer_sethandlers_listvalue(const void *closure, upb_handlers *h) {
  11520. const upb_msgdef *md = upb_handlers_msgdef(h);
  11521. const upb_fielddef* f = upb_msgdef_itof(md, 1);
  11522. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11523. upb_handlers_setstartseq(h, f, startseq_nokey, &empty_attr);
  11524. upb_handlers_setendseq(h, f, endseq, &empty_attr);
  11525. upb_handlers_setstartmsg(h, printer_startmsg_noframe, &empty_attr);
  11526. upb_handlers_setendmsg(h, printer_endmsg_noframe, &empty_attr);
  11527. upb_handlers_setstartsubmsg(h, f, repeated_startsubmsg, &empty_attr);
  11528. UPB_UNUSED(closure);
  11529. }
  11530. void printer_sethandlers_structvalue(const void *closure, upb_handlers *h) {
  11531. const upb_msgdef *md = upb_handlers_msgdef(h);
  11532. const upb_fielddef* f = upb_msgdef_itof(md, 1);
  11533. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11534. upb_handlers_setstartseq(h, f, startmap_nokey, &empty_attr);
  11535. upb_handlers_setendseq(h, f, endmap, &empty_attr);
  11536. upb_handlers_setstartmsg(h, printer_startmsg_noframe, &empty_attr);
  11537. upb_handlers_setendmsg(h, printer_endmsg_noframe, &empty_attr);
  11538. upb_handlers_setstartsubmsg(h, f, repeated_startsubmsg, &empty_attr);
  11539. UPB_UNUSED(closure);
  11540. }
  11541. void printer_sethandlers(const void *closure, upb_handlers *h) {
  11542. const upb_msgdef *md = upb_handlers_msgdef(h);
  11543. bool is_mapentry = upb_msgdef_mapentry(md);
  11544. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11545. upb_msg_field_iter i;
  11546. const upb_json_printercache *cache = closure;
  11547. const bool preserve_fieldnames = cache->preserve_fieldnames;
  11548. if (is_mapentry) {
  11549. /* mapentry messages are sufficiently different that we handle them
  11550. * separately. */
  11551. printer_sethandlers_mapentry(closure, preserve_fieldnames, h);
  11552. return;
  11553. }
  11554. switch (upb_msgdef_wellknowntype(md)) {
  11555. case UPB_WELLKNOWN_UNSPECIFIED:
  11556. break;
  11557. case UPB_WELLKNOWN_ANY:
  11558. printer_sethandlers_any(closure, h);
  11559. return;
  11560. case UPB_WELLKNOWN_FIELDMASK:
  11561. printer_sethandlers_fieldmask(closure, h);
  11562. return;
  11563. case UPB_WELLKNOWN_DURATION:
  11564. printer_sethandlers_duration(closure, h);
  11565. return;
  11566. case UPB_WELLKNOWN_TIMESTAMP:
  11567. printer_sethandlers_timestamp(closure, h);
  11568. return;
  11569. case UPB_WELLKNOWN_VALUE:
  11570. printer_sethandlers_value(closure, h);
  11571. return;
  11572. case UPB_WELLKNOWN_LISTVALUE:
  11573. printer_sethandlers_listvalue(closure, h);
  11574. return;
  11575. case UPB_WELLKNOWN_STRUCT:
  11576. printer_sethandlers_structvalue(closure, h);
  11577. return;
  11578. #define WRAPPER(wellknowntype, name) \
  11579. case wellknowntype: \
  11580. printer_sethandlers_##name(closure, h); \
  11581. return; \
  11582. WRAPPER(UPB_WELLKNOWN_DOUBLEVALUE, doublevalue);
  11583. WRAPPER(UPB_WELLKNOWN_FLOATVALUE, floatvalue);
  11584. WRAPPER(UPB_WELLKNOWN_INT64VALUE, int64value);
  11585. WRAPPER(UPB_WELLKNOWN_UINT64VALUE, uint64value);
  11586. WRAPPER(UPB_WELLKNOWN_INT32VALUE, int32value);
  11587. WRAPPER(UPB_WELLKNOWN_UINT32VALUE, uint32value);
  11588. WRAPPER(UPB_WELLKNOWN_BOOLVALUE, boolvalue);
  11589. WRAPPER(UPB_WELLKNOWN_STRINGVALUE, stringvalue);
  11590. WRAPPER(UPB_WELLKNOWN_BYTESVALUE, bytesvalue);
  11591. #undef WRAPPER
  11592. }
  11593. upb_handlers_setstartmsg(h, printer_startmsg, &empty_attr);
  11594. upb_handlers_setendmsg(h, printer_endmsg, &empty_attr);
  11595. #define TYPE(type, name, ctype) \
  11596. case type: \
  11597. if (upb_fielddef_isseq(f)) { \
  11598. upb_handlers_set##name(h, f, repeated_##ctype, &empty_attr); \
  11599. } else { \
  11600. upb_handlers_set##name(h, f, scalar_##ctype, &name_attr); \
  11601. } \
  11602. break;
  11603. upb_msg_field_begin(&i, md);
  11604. for(; !upb_msg_field_done(&i); upb_msg_field_next(&i)) {
  11605. const upb_fielddef *f = upb_msg_iter_field(&i);
  11606. upb_handlerattr name_attr = UPB_HANDLERATTR_INIT;
  11607. name_attr.handler_data = newstrpc(h, f, preserve_fieldnames);
  11608. if (upb_fielddef_ismap(f)) {
  11609. upb_handlers_setstartseq(h, f, startmap, &name_attr);
  11610. upb_handlers_setendseq(h, f, endmap, &name_attr);
  11611. } else if (upb_fielddef_isseq(f)) {
  11612. upb_handlers_setstartseq(h, f, startseq, &name_attr);
  11613. upb_handlers_setendseq(h, f, endseq, &empty_attr);
  11614. }
  11615. switch (upb_fielddef_type(f)) {
  11616. TYPE(UPB_TYPE_FLOAT, float, float);
  11617. TYPE(UPB_TYPE_DOUBLE, double, double);
  11618. TYPE(UPB_TYPE_BOOL, bool, bool);
  11619. TYPE(UPB_TYPE_INT32, int32, int32_t);
  11620. TYPE(UPB_TYPE_UINT32, uint32, uint32_t);
  11621. TYPE(UPB_TYPE_INT64, int64, int64_t);
  11622. TYPE(UPB_TYPE_UINT64, uint64, uint64_t);
  11623. case UPB_TYPE_ENUM: {
  11624. /* For now, we always emit symbolic names for enums. We may want an
  11625. * option later to control this behavior, but we will wait for a real
  11626. * need first. */
  11627. upb_handlerattr enum_attr = UPB_HANDLERATTR_INIT;
  11628. set_enum_hd(h, f, preserve_fieldnames, &enum_attr);
  11629. if (upb_fielddef_isseq(f)) {
  11630. upb_handlers_setint32(h, f, repeated_enum, &enum_attr);
  11631. } else {
  11632. upb_handlers_setint32(h, f, scalar_enum, &enum_attr);
  11633. }
  11634. break;
  11635. }
  11636. case UPB_TYPE_STRING:
  11637. if (upb_fielddef_isseq(f)) {
  11638. upb_handlers_setstartstr(h, f, repeated_startstr, &empty_attr);
  11639. upb_handlers_setstring(h, f, repeated_str, &empty_attr);
  11640. upb_handlers_setendstr(h, f, repeated_endstr, &empty_attr);
  11641. } else {
  11642. upb_handlers_setstartstr(h, f, scalar_startstr, &name_attr);
  11643. upb_handlers_setstring(h, f, scalar_str, &empty_attr);
  11644. upb_handlers_setendstr(h, f, scalar_endstr, &empty_attr);
  11645. }
  11646. break;
  11647. case UPB_TYPE_BYTES:
  11648. /* XXX: this doesn't support strings that span buffers yet. The base64
  11649. * encoder will need to be made resumable for this to work properly. */
  11650. if (upb_fielddef_isseq(f)) {
  11651. upb_handlers_setstring(h, f, repeated_bytes, &empty_attr);
  11652. } else {
  11653. upb_handlers_setstring(h, f, scalar_bytes, &name_attr);
  11654. }
  11655. break;
  11656. case UPB_TYPE_MESSAGE:
  11657. if (upb_fielddef_isseq(f)) {
  11658. upb_handlers_setstartsubmsg(h, f, repeated_startsubmsg, &name_attr);
  11659. } else {
  11660. upb_handlers_setstartsubmsg(h, f, scalar_startsubmsg, &name_attr);
  11661. }
  11662. break;
  11663. }
  11664. }
  11665. #undef TYPE
  11666. }
  11667. static void json_printer_reset(upb_json_printer *p) {
  11668. p->depth_ = 0;
  11669. }
  11670. /* Public API *****************************************************************/
  11671. upb_json_printer *upb_json_printer_create(upb_arena *a, const upb_handlers *h,
  11672. upb_bytessink output) {
  11673. #ifndef NDEBUG
  11674. size_t size_before = upb_arena_bytesallocated(a);
  11675. #endif
  11676. upb_json_printer *p = upb_arena_malloc(a, sizeof(upb_json_printer));
  11677. if (!p) return NULL;
  11678. p->output_ = output;
  11679. json_printer_reset(p);
  11680. upb_sink_reset(&p->input_, h, p);
  11681. p->seconds = 0;
  11682. p->nanos = 0;
  11683. /* If this fails, increase the value in printer.h. */
  11684. UPB_ASSERT_DEBUGVAR(upb_arena_bytesallocated(a) - size_before <=
  11685. UPB_JSON_PRINTER_SIZE);
  11686. return p;
  11687. }
  11688. upb_sink upb_json_printer_input(upb_json_printer *p) {
  11689. return p->input_;
  11690. }
  11691. upb_handlercache *upb_json_printer_newcache(bool preserve_proto_fieldnames) {
  11692. upb_json_printercache *cache = upb_gmalloc(sizeof(*cache));
  11693. upb_handlercache *ret = upb_handlercache_new(printer_sethandlers, cache);
  11694. cache->preserve_fieldnames = preserve_proto_fieldnames;
  11695. upb_handlercache_addcleanup(ret, cache, upb_gfree);
  11696. return ret;
  11697. }
  11698. /* See port_def.inc. This should #undef all macros #defined there. */
  11699. #undef UPB_MAPTYPE_STRING
  11700. #undef UPB_SIZE
  11701. #undef UPB_PTR_AT
  11702. #undef UPB_READ_ONEOF
  11703. #undef UPB_WRITE_ONEOF
  11704. #undef UPB_INLINE
  11705. #undef UPB_FORCEINLINE
  11706. #undef UPB_NOINLINE
  11707. #undef UPB_NORETURN
  11708. #undef UPB_MAX
  11709. #undef UPB_MIN
  11710. #undef UPB_UNUSED
  11711. #undef UPB_ASSUME
  11712. #undef UPB_ASSERT
  11713. #undef UPB_ASSERT_DEBUGVAR
  11714. #undef UPB_UNREACHABLE
  11715. #undef UPB_INFINITY
  11716. #undef UPB_MSVC_VSNPRINTF
  11717. #undef _upb_snprintf
  11718. #undef _upb_vsnprintf
  11719. #undef _upb_va_copy