upb.c 392 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345
  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. #ifndef UINTPTR_MAX
  26. #error must include stdint.h first
  27. #endif
  28. #if UINTPTR_MAX == 0xffffffff
  29. #define UPB_SIZE(size32, size64) size32
  30. #else
  31. #define UPB_SIZE(size32, size64) size64
  32. #endif
  33. #define UPB_FIELD_AT(msg, fieldtype, offset) \
  34. *(fieldtype*)((const char*)(msg) + offset)
  35. #define UPB_READ_ONEOF(msg, fieldtype, offset, case_offset, case_val, default) \
  36. UPB_FIELD_AT(msg, int, case_offset) == case_val \
  37. ? UPB_FIELD_AT(msg, fieldtype, offset) \
  38. : default
  39. #define UPB_WRITE_ONEOF(msg, fieldtype, offset, value, case_offset, case_val) \
  40. UPB_FIELD_AT(msg, int, case_offset) = case_val; \
  41. UPB_FIELD_AT(msg, fieldtype, offset) = value;
  42. /* UPB_INLINE: inline if possible, emit standalone code if required. */
  43. #ifdef __cplusplus
  44. #define UPB_INLINE inline
  45. #elif defined (__GNUC__) || defined(__clang__)
  46. #define UPB_INLINE static __inline__
  47. #else
  48. #define UPB_INLINE static
  49. #endif
  50. /* Hints to the compiler about likely/unlikely branches. */
  51. #if defined (__GNUC__) || defined(__clang__)
  52. #define UPB_LIKELY(x) __builtin_expect((x),1)
  53. #define UPB_UNLIKELY(x) __builtin_expect((x),0)
  54. #else
  55. #define UPB_LIKELY(x) (x)
  56. #define UPB_UNLIKELY(x) (x)
  57. #endif
  58. /* Define UPB_BIG_ENDIAN manually if you're on big endian and your compiler
  59. * doesn't provide these preprocessor symbols. */
  60. #if defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)
  61. #define UPB_BIG_ENDIAN
  62. #endif
  63. /* Macros for function attributes on compilers that support them. */
  64. #ifdef __GNUC__
  65. #define UPB_FORCEINLINE __inline__ __attribute__((always_inline))
  66. #define UPB_NOINLINE __attribute__((noinline))
  67. #define UPB_NORETURN __attribute__((__noreturn__))
  68. #else /* !defined(__GNUC__) */
  69. #define UPB_FORCEINLINE
  70. #define UPB_NOINLINE
  71. #define UPB_NORETURN
  72. #endif
  73. #if __STDC_VERSION__ >= 199901L || __cplusplus >= 201103L
  74. /* C99/C++11 versions. */
  75. #include <stdio.h>
  76. #define _upb_snprintf snprintf
  77. #define _upb_vsnprintf vsnprintf
  78. #define _upb_va_copy(a, b) va_copy(a, b)
  79. #elif defined(_MSC_VER)
  80. /* Microsoft C/C++ versions. */
  81. #include <stdarg.h>
  82. #include <stdio.h>
  83. #if _MSC_VER < 1900
  84. int msvc_snprintf(char* s, size_t n, const char* format, ...);
  85. int msvc_vsnprintf(char* s, size_t n, const char* format, va_list arg);
  86. #define UPB_MSVC_VSNPRINTF
  87. #define _upb_snprintf msvc_snprintf
  88. #define _upb_vsnprintf msvc_vsnprintf
  89. #else
  90. #define _upb_snprintf snprintf
  91. #define _upb_vsnprintf vsnprintf
  92. #endif
  93. #define _upb_va_copy(a, b) va_copy(a, b)
  94. #elif defined __GNUC__
  95. /* A few hacky workarounds for functions not in C89.
  96. * For internal use only!
  97. * TODO(haberman): fix these by including our own implementations, or finding
  98. * another workaround.
  99. */
  100. #define _upb_snprintf __builtin_snprintf
  101. #define _upb_vsnprintf __builtin_vsnprintf
  102. #define _upb_va_copy(a, b) __va_copy(a, b)
  103. #else
  104. #error Need implementations of [v]snprintf and va_copy
  105. #endif
  106. #ifdef __cplusplus
  107. #if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__) || \
  108. (defined(_MSC_VER) && _MSC_VER >= 1900)
  109. // C++11 is present
  110. #else
  111. #error upb requires C++11 for C++ support
  112. #endif
  113. #endif
  114. #define UPB_MAX(x, y) ((x) > (y) ? (x) : (y))
  115. #define UPB_MIN(x, y) ((x) < (y) ? (x) : (y))
  116. #define UPB_UNUSED(var) (void)var
  117. /* UPB_ASSERT(): in release mode, we use the expression without letting it be
  118. * evaluated. This prevents "unused variable" warnings. */
  119. #ifdef NDEBUG
  120. #define UPB_ASSERT(expr) do {} while (false && (expr))
  121. #else
  122. #define UPB_ASSERT(expr) assert(expr)
  123. #endif
  124. /* UPB_ASSERT_DEBUGVAR(): assert that uses functions or variables that only
  125. * exist in debug mode. This turns into regular assert. */
  126. #define UPB_ASSERT_DEBUGVAR(expr) assert(expr)
  127. #if defined(__GNUC__) || defined(__clang__)
  128. #define UPB_UNREACHABLE() do { assert(0); __builtin_unreachable(); } while(0)
  129. #else
  130. #define UPB_UNREACHABLE() do { assert(0); } while(0)
  131. #endif
  132. /* UPB_INFINITY representing floating-point positive infinity. */
  133. #include <math.h>
  134. #ifdef INFINITY
  135. #define UPB_INFINITY INFINITY
  136. #else
  137. #define UPB_INFINITY (1.0 / 0.0)
  138. #endif
  139. #include <string.h>
  140. /* Maps descriptor type -> upb field type. */
  141. const uint8_t upb_desctype_to_fieldtype[] = {
  142. UPB_WIRE_TYPE_END_GROUP, /* ENDGROUP */
  143. UPB_TYPE_DOUBLE, /* DOUBLE */
  144. UPB_TYPE_FLOAT, /* FLOAT */
  145. UPB_TYPE_INT64, /* INT64 */
  146. UPB_TYPE_UINT64, /* UINT64 */
  147. UPB_TYPE_INT32, /* INT32 */
  148. UPB_TYPE_UINT64, /* FIXED64 */
  149. UPB_TYPE_UINT32, /* FIXED32 */
  150. UPB_TYPE_BOOL, /* BOOL */
  151. UPB_TYPE_STRING, /* STRING */
  152. UPB_TYPE_MESSAGE, /* GROUP */
  153. UPB_TYPE_MESSAGE, /* MESSAGE */
  154. UPB_TYPE_BYTES, /* BYTES */
  155. UPB_TYPE_UINT32, /* UINT32 */
  156. UPB_TYPE_ENUM, /* ENUM */
  157. UPB_TYPE_INT32, /* SFIXED32 */
  158. UPB_TYPE_INT64, /* SFIXED64 */
  159. UPB_TYPE_INT32, /* SINT32 */
  160. UPB_TYPE_INT64, /* SINT64 */
  161. };
  162. /* Data pertaining to the parse. */
  163. typedef struct {
  164. const char *ptr; /* Current parsing position. */
  165. const char *field_start; /* Start of this field. */
  166. const char *limit; /* End of delimited region or end of buffer. */
  167. upb_arena *arena;
  168. int depth;
  169. uint32_t end_group; /* Set to field number of END_GROUP tag, if any. */
  170. } upb_decstate;
  171. /* Data passed by value to each parsing function. */
  172. typedef struct {
  173. char *msg;
  174. const upb_msglayout *layout;
  175. upb_decstate *state;
  176. } upb_decframe;
  177. #define CHK(x) if (!(x)) { return 0; }
  178. static bool upb_skip_unknowngroup(upb_decstate *d, int field_number);
  179. static bool upb_decode_message(upb_decstate *d, char *msg,
  180. const upb_msglayout *l);
  181. static bool upb_decode_varint(const char **ptr, const char *limit,
  182. uint64_t *val) {
  183. uint8_t byte;
  184. int bitpos = 0;
  185. const char *p = *ptr;
  186. *val = 0;
  187. do {
  188. CHK(bitpos < 70 && p < limit);
  189. byte = *p;
  190. *val |= (uint64_t)(byte & 0x7F) << bitpos;
  191. p++;
  192. bitpos += 7;
  193. } while (byte & 0x80);
  194. *ptr = p;
  195. return true;
  196. }
  197. static bool upb_decode_varint32(const char **ptr, const char *limit,
  198. uint32_t *val) {
  199. uint64_t u64;
  200. CHK(upb_decode_varint(ptr, limit, &u64) && u64 <= UINT32_MAX);
  201. *val = (uint32_t)u64;
  202. return true;
  203. }
  204. static bool upb_decode_64bit(const char **ptr, const char *limit,
  205. uint64_t *val) {
  206. CHK(limit - *ptr >= 8);
  207. memcpy(val, *ptr, 8);
  208. *ptr += 8;
  209. return true;
  210. }
  211. static bool upb_decode_32bit(const char **ptr, const char *limit,
  212. uint32_t *val) {
  213. CHK(limit - *ptr >= 4);
  214. memcpy(val, *ptr, 4);
  215. *ptr += 4;
  216. return true;
  217. }
  218. static int32_t upb_zzdecode_32(uint32_t n) {
  219. return (n >> 1) ^ -(int32_t)(n & 1);
  220. }
  221. static int64_t upb_zzdecode_64(uint64_t n) {
  222. return (n >> 1) ^ -(int64_t)(n & 1);
  223. }
  224. static bool upb_decode_string(const char **ptr, const char *limit,
  225. int *outlen) {
  226. uint32_t len;
  227. CHK(upb_decode_varint32(ptr, limit, &len) &&
  228. len < INT32_MAX &&
  229. limit - *ptr >= (int32_t)len);
  230. *outlen = len;
  231. return true;
  232. }
  233. static void upb_set32(void *msg, size_t ofs, uint32_t val) {
  234. memcpy((char*)msg + ofs, &val, sizeof(val));
  235. }
  236. static bool upb_append_unknown(upb_decstate *d, upb_decframe *frame) {
  237. upb_msg_addunknown(frame->msg, d->field_start, d->ptr - d->field_start,
  238. d->arena);
  239. return true;
  240. }
  241. static bool upb_skip_unknownfielddata(upb_decstate *d, uint32_t tag,
  242. uint32_t group_fieldnum) {
  243. switch (tag & 7) {
  244. case UPB_WIRE_TYPE_VARINT: {
  245. uint64_t val;
  246. return upb_decode_varint(&d->ptr, d->limit, &val);
  247. }
  248. case UPB_WIRE_TYPE_32BIT: {
  249. uint32_t val;
  250. return upb_decode_32bit(&d->ptr, d->limit, &val);
  251. }
  252. case UPB_WIRE_TYPE_64BIT: {
  253. uint64_t val;
  254. return upb_decode_64bit(&d->ptr, d->limit, &val);
  255. }
  256. case UPB_WIRE_TYPE_DELIMITED: {
  257. int len;
  258. CHK(upb_decode_string(&d->ptr, d->limit, &len));
  259. d->ptr += len;
  260. return true;
  261. }
  262. case UPB_WIRE_TYPE_START_GROUP:
  263. return upb_skip_unknowngroup(d, tag >> 3);
  264. case UPB_WIRE_TYPE_END_GROUP:
  265. return (tag >> 3) == group_fieldnum;
  266. }
  267. return false;
  268. }
  269. static bool upb_skip_unknowngroup(upb_decstate *d, int field_number) {
  270. while (d->ptr < d->limit && d->end_group == 0) {
  271. uint32_t tag = 0;
  272. CHK(upb_decode_varint32(&d->ptr, d->limit, &tag));
  273. CHK(upb_skip_unknownfielddata(d, tag, field_number));
  274. }
  275. CHK(d->end_group == field_number);
  276. d->end_group = 0;
  277. return true;
  278. }
  279. static bool upb_array_grow(upb_array *arr, size_t elements, size_t elem_size,
  280. upb_arena *arena) {
  281. size_t needed = arr->len + elements;
  282. size_t new_size = UPB_MAX(arr->size, 8);
  283. size_t new_bytes;
  284. size_t old_bytes;
  285. void *new_data;
  286. upb_alloc *alloc = upb_arena_alloc(arena);
  287. while (new_size < needed) {
  288. new_size *= 2;
  289. }
  290. old_bytes = arr->len * elem_size;
  291. new_bytes = new_size * elem_size;
  292. new_data = upb_realloc(alloc, arr->data, old_bytes, new_bytes);
  293. CHK(new_data);
  294. arr->data = new_data;
  295. arr->size = new_size;
  296. return true;
  297. }
  298. static void *upb_array_reserve(upb_array *arr, size_t elements,
  299. size_t elem_size, upb_arena *arena) {
  300. if (arr->size - arr->len < elements) {
  301. CHK(upb_array_grow(arr, elements, elem_size, arena));
  302. }
  303. return (char*)arr->data + (arr->len * elem_size);
  304. }
  305. bool upb_array_add(upb_array *arr, size_t elements, size_t elem_size,
  306. const void *data, upb_arena *arena) {
  307. void *dest = upb_array_reserve(arr, elements, elem_size, arena);
  308. CHK(dest);
  309. arr->len += elements;
  310. memcpy(dest, data, elements * elem_size);
  311. return true;
  312. }
  313. static upb_array *upb_getarr(upb_decframe *frame,
  314. const upb_msglayout_field *field) {
  315. UPB_ASSERT(field->label == UPB_LABEL_REPEATED);
  316. return *(upb_array**)&frame->msg[field->offset];
  317. }
  318. static upb_array *upb_getorcreatearr(upb_decframe *frame,
  319. const upb_msglayout_field *field) {
  320. upb_array *arr = upb_getarr(frame, field);
  321. if (!arr) {
  322. arr = upb_array_new(frame->state->arena);
  323. CHK(arr);
  324. *(upb_array**)&frame->msg[field->offset] = arr;
  325. }
  326. return arr;
  327. }
  328. static upb_msg *upb_getorcreatemsg(upb_decframe *frame,
  329. const upb_msglayout_field *field,
  330. const upb_msglayout **subm) {
  331. upb_msg **submsg = (void*)(frame->msg + field->offset);
  332. *subm = frame->layout->submsgs[field->submsg_index];
  333. UPB_ASSERT(field->label != UPB_LABEL_REPEATED);
  334. if (!*submsg) {
  335. *submsg = upb_msg_new(*subm, frame->state->arena);
  336. CHK(*submsg);
  337. }
  338. return *submsg;
  339. }
  340. static upb_msg *upb_addmsg(upb_decframe *frame,
  341. const upb_msglayout_field *field,
  342. const upb_msglayout **subm) {
  343. upb_msg *submsg;
  344. upb_array *arr = upb_getorcreatearr(frame, field);
  345. *subm = frame->layout->submsgs[field->submsg_index];
  346. submsg = upb_msg_new(*subm, frame->state->arena);
  347. CHK(submsg);
  348. upb_array_add(arr, 1, sizeof(submsg), &submsg, frame->state->arena);
  349. return submsg;
  350. }
  351. static void upb_sethasbit(upb_decframe *frame,
  352. const upb_msglayout_field *field) {
  353. int32_t hasbit = field->presence;
  354. UPB_ASSERT(field->presence > 0);
  355. frame->msg[hasbit / 8] |= (1 << (hasbit % 8));
  356. }
  357. static void upb_setoneofcase(upb_decframe *frame,
  358. const upb_msglayout_field *field) {
  359. UPB_ASSERT(field->presence < 0);
  360. upb_set32(frame->msg, ~field->presence, field->number);
  361. }
  362. static bool upb_decode_addval(upb_decframe *frame,
  363. const upb_msglayout_field *field, void *val,
  364. size_t size) {
  365. char *field_mem = frame->msg + field->offset;
  366. upb_array *arr;
  367. if (field->label == UPB_LABEL_REPEATED) {
  368. arr = upb_getorcreatearr(frame, field);
  369. CHK(arr);
  370. field_mem = upb_array_reserve(arr, 1, size, frame->state->arena);
  371. CHK(field_mem);
  372. }
  373. memcpy(field_mem, val, size);
  374. return true;
  375. }
  376. static void upb_decode_setpresent(upb_decframe *frame,
  377. const upb_msglayout_field *field) {
  378. if (field->label == UPB_LABEL_REPEATED) {
  379. upb_array *arr = upb_getarr(frame, field);
  380. UPB_ASSERT(arr->len < arr->size);
  381. arr->len++;
  382. } else if (field->presence < 0) {
  383. upb_setoneofcase(frame, field);
  384. } else if (field->presence > 0) {
  385. upb_sethasbit(frame, field);
  386. }
  387. }
  388. static bool upb_decode_msgfield(upb_decstate *d, upb_msg *msg,
  389. const upb_msglayout *layout, int limit) {
  390. const char* saved_limit = d->limit;
  391. d->limit = d->ptr + limit;
  392. CHK(--d->depth >= 0);
  393. upb_decode_message(d, msg, layout);
  394. d->depth++;
  395. d->limit = saved_limit;
  396. CHK(d->end_group == 0);
  397. return true;
  398. }
  399. static bool upb_decode_groupfield(upb_decstate *d, upb_msg *msg,
  400. const upb_msglayout *layout,
  401. int field_number) {
  402. CHK(--d->depth >= 0);
  403. upb_decode_message(d, msg, layout);
  404. d->depth++;
  405. CHK(d->end_group == field_number);
  406. d->end_group = 0;
  407. return true;
  408. }
  409. static bool upb_decode_varintfield(upb_decstate *d, upb_decframe *frame,
  410. const upb_msglayout_field *field) {
  411. uint64_t val;
  412. CHK(upb_decode_varint(&d->ptr, d->limit, &val));
  413. switch (field->descriptortype) {
  414. case UPB_DESCRIPTOR_TYPE_INT64:
  415. case UPB_DESCRIPTOR_TYPE_UINT64:
  416. CHK(upb_decode_addval(frame, field, &val, sizeof(val)));
  417. break;
  418. case UPB_DESCRIPTOR_TYPE_INT32:
  419. case UPB_DESCRIPTOR_TYPE_UINT32:
  420. case UPB_DESCRIPTOR_TYPE_ENUM: {
  421. uint32_t val32 = (uint32_t)val;
  422. CHK(upb_decode_addval(frame, field, &val32, sizeof(val32)));
  423. break;
  424. }
  425. case UPB_DESCRIPTOR_TYPE_BOOL: {
  426. bool valbool = val != 0;
  427. CHK(upb_decode_addval(frame, field, &valbool, sizeof(valbool)));
  428. break;
  429. }
  430. case UPB_DESCRIPTOR_TYPE_SINT32: {
  431. int32_t decoded = upb_zzdecode_32((uint32_t)val);
  432. CHK(upb_decode_addval(frame, field, &decoded, sizeof(decoded)));
  433. break;
  434. }
  435. case UPB_DESCRIPTOR_TYPE_SINT64: {
  436. int64_t decoded = upb_zzdecode_64(val);
  437. CHK(upb_decode_addval(frame, field, &decoded, sizeof(decoded)));
  438. break;
  439. }
  440. default:
  441. return upb_append_unknown(d, frame);
  442. }
  443. upb_decode_setpresent(frame, field);
  444. return true;
  445. }
  446. static bool upb_decode_64bitfield(upb_decstate *d, upb_decframe *frame,
  447. const upb_msglayout_field *field) {
  448. uint64_t val;
  449. CHK(upb_decode_64bit(&d->ptr, d->limit, &val));
  450. switch (field->descriptortype) {
  451. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  452. case UPB_DESCRIPTOR_TYPE_FIXED64:
  453. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  454. CHK(upb_decode_addval(frame, field, &val, sizeof(val)));
  455. break;
  456. default:
  457. return upb_append_unknown(d, frame);
  458. }
  459. upb_decode_setpresent(frame, field);
  460. return true;
  461. }
  462. static bool upb_decode_32bitfield(upb_decstate *d, upb_decframe *frame,
  463. const upb_msglayout_field *field) {
  464. uint32_t val;
  465. CHK(upb_decode_32bit(&d->ptr, d->limit, &val));
  466. switch (field->descriptortype) {
  467. case UPB_DESCRIPTOR_TYPE_FLOAT:
  468. case UPB_DESCRIPTOR_TYPE_FIXED32:
  469. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  470. CHK(upb_decode_addval(frame, field, &val, sizeof(val)));
  471. break;
  472. default:
  473. return upb_append_unknown(d, frame);
  474. }
  475. upb_decode_setpresent(frame, field);
  476. return true;
  477. }
  478. static bool upb_decode_fixedpacked(upb_decstate *d, upb_array *arr,
  479. uint32_t len, int elem_size) {
  480. size_t elements = len / elem_size;
  481. CHK((size_t)(elements * elem_size) == len);
  482. CHK(upb_array_add(arr, elements, elem_size, d->ptr, d->arena));
  483. d->ptr += len;
  484. return true;
  485. }
  486. static upb_strview upb_decode_strfield(upb_decstate *d, uint32_t len) {
  487. upb_strview ret;
  488. ret.data = d->ptr;
  489. ret.size = len;
  490. d->ptr += len;
  491. return ret;
  492. }
  493. static bool upb_decode_toarray(upb_decstate *d, upb_decframe *frame,
  494. const upb_msglayout_field *field, int len) {
  495. upb_array *arr = upb_getorcreatearr(frame, field);
  496. CHK(arr);
  497. #define VARINT_CASE(ctype, decode) \
  498. VARINT_CASE_EX(ctype, decode, decode)
  499. #define VARINT_CASE_EX(ctype, decode, dtype) \
  500. { \
  501. const char *ptr = d->ptr; \
  502. const char *limit = ptr + len; \
  503. while (ptr < limit) { \
  504. uint64_t val; \
  505. ctype decoded; \
  506. CHK(upb_decode_varint(&ptr, limit, &val)); \
  507. decoded = (decode)((dtype)val); \
  508. CHK(upb_array_add(arr, 1, sizeof(decoded), &decoded, d->arena)); \
  509. } \
  510. d->ptr = ptr; \
  511. return true; \
  512. }
  513. switch (field->descriptortype) {
  514. case UPB_DESCRIPTOR_TYPE_STRING:
  515. case UPB_DESCRIPTOR_TYPE_BYTES: {
  516. upb_strview str = upb_decode_strfield(d, len);
  517. return upb_array_add(arr, 1, sizeof(str), &str, d->arena);
  518. }
  519. case UPB_DESCRIPTOR_TYPE_FLOAT:
  520. case UPB_DESCRIPTOR_TYPE_FIXED32:
  521. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  522. return upb_decode_fixedpacked(d, arr, len, sizeof(int32_t));
  523. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  524. case UPB_DESCRIPTOR_TYPE_FIXED64:
  525. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  526. return upb_decode_fixedpacked(d, arr, len, sizeof(int64_t));
  527. case UPB_DESCRIPTOR_TYPE_INT32:
  528. case UPB_DESCRIPTOR_TYPE_UINT32:
  529. case UPB_DESCRIPTOR_TYPE_ENUM:
  530. VARINT_CASE(uint32_t, uint32_t);
  531. case UPB_DESCRIPTOR_TYPE_INT64:
  532. case UPB_DESCRIPTOR_TYPE_UINT64:
  533. VARINT_CASE(uint64_t, uint64_t);
  534. case UPB_DESCRIPTOR_TYPE_BOOL:
  535. VARINT_CASE(bool, bool);
  536. case UPB_DESCRIPTOR_TYPE_SINT32:
  537. VARINT_CASE_EX(int32_t, upb_zzdecode_32, uint32_t);
  538. case UPB_DESCRIPTOR_TYPE_SINT64:
  539. VARINT_CASE_EX(int64_t, upb_zzdecode_64, uint64_t);
  540. case UPB_DESCRIPTOR_TYPE_MESSAGE: {
  541. const upb_msglayout *subm;
  542. upb_msg *submsg = upb_addmsg(frame, field, &subm);
  543. CHK(submsg);
  544. return upb_decode_msgfield(d, submsg, subm, len);
  545. }
  546. case UPB_DESCRIPTOR_TYPE_GROUP:
  547. return upb_append_unknown(d, frame);
  548. }
  549. #undef VARINT_CASE
  550. UPB_UNREACHABLE();
  551. }
  552. static bool upb_decode_delimitedfield(upb_decstate *d, upb_decframe *frame,
  553. const upb_msglayout_field *field) {
  554. int len;
  555. CHK(upb_decode_string(&d->ptr, d->limit, &len));
  556. if (field->label == UPB_LABEL_REPEATED) {
  557. return upb_decode_toarray(d, frame, field, len);
  558. } else {
  559. switch (field->descriptortype) {
  560. case UPB_DESCRIPTOR_TYPE_STRING:
  561. case UPB_DESCRIPTOR_TYPE_BYTES: {
  562. upb_strview str = upb_decode_strfield(d, len);
  563. CHK(upb_decode_addval(frame, field, &str, sizeof(str)));
  564. break;
  565. }
  566. case UPB_DESCRIPTOR_TYPE_MESSAGE: {
  567. const upb_msglayout *subm;
  568. upb_msg *submsg = upb_getorcreatemsg(frame, field, &subm);
  569. CHK(submsg);
  570. CHK(upb_decode_msgfield(d, submsg, subm, len));
  571. break;
  572. }
  573. default:
  574. /* TODO(haberman): should we accept the last element of a packed? */
  575. d->ptr += len;
  576. return upb_append_unknown(d, frame);
  577. }
  578. upb_decode_setpresent(frame, field);
  579. return true;
  580. }
  581. }
  582. static const upb_msglayout_field *upb_find_field(const upb_msglayout *l,
  583. uint32_t field_number) {
  584. /* Lots of optimization opportunities here. */
  585. int i;
  586. for (i = 0; i < l->field_count; i++) {
  587. if (l->fields[i].number == field_number) {
  588. return &l->fields[i];
  589. }
  590. }
  591. return NULL; /* Unknown field. */
  592. }
  593. static bool upb_decode_field(upb_decstate *d, upb_decframe *frame) {
  594. uint32_t tag;
  595. const upb_msglayout_field *field;
  596. int field_number;
  597. d->field_start = d->ptr;
  598. CHK(upb_decode_varint32(&d->ptr, d->limit, &tag));
  599. field_number = tag >> 3;
  600. field = upb_find_field(frame->layout, field_number);
  601. if (field) {
  602. switch (tag & 7) {
  603. case UPB_WIRE_TYPE_VARINT:
  604. return upb_decode_varintfield(d, frame, field);
  605. case UPB_WIRE_TYPE_32BIT:
  606. return upb_decode_32bitfield(d, frame, field);
  607. case UPB_WIRE_TYPE_64BIT:
  608. return upb_decode_64bitfield(d, frame, field);
  609. case UPB_WIRE_TYPE_DELIMITED:
  610. return upb_decode_delimitedfield(d, frame, field);
  611. case UPB_WIRE_TYPE_START_GROUP: {
  612. const upb_msglayout *layout;
  613. upb_msg *group;
  614. if (field->label == UPB_LABEL_REPEATED) {
  615. group = upb_addmsg(frame, field, &layout);
  616. } else {
  617. group = upb_getorcreatemsg(frame, field, &layout);
  618. }
  619. return upb_decode_groupfield(d, group, layout, field_number);
  620. }
  621. case UPB_WIRE_TYPE_END_GROUP:
  622. d->end_group = field_number;
  623. return true;
  624. default:
  625. CHK(false);
  626. }
  627. } else {
  628. CHK(field_number != 0);
  629. CHK(upb_skip_unknownfielddata(d, tag, -1));
  630. CHK(upb_append_unknown(d, frame));
  631. return true;
  632. }
  633. }
  634. static bool upb_decode_message(upb_decstate *d, char *msg, const upb_msglayout *l) {
  635. upb_decframe frame;
  636. frame.msg = msg;
  637. frame.layout = l;
  638. frame.state = d;
  639. while (d->ptr < d->limit) {
  640. CHK(upb_decode_field(d, &frame));
  641. }
  642. return true;
  643. }
  644. bool upb_decode(const char *buf, size_t size, void *msg, const upb_msglayout *l,
  645. upb_arena *arena) {
  646. upb_decstate state;
  647. state.ptr = buf;
  648. state.limit = buf + size;
  649. state.arena = arena;
  650. state.depth = 64;
  651. state.end_group = 0;
  652. CHK(upb_decode_message(&state, msg, l));
  653. return state.end_group == 0;
  654. }
  655. #undef CHK
  656. /* We encode backwards, to avoid pre-computing lengths (one-pass encode). */
  657. #include <string.h>
  658. #define UPB_PB_VARINT_MAX_LEN 10
  659. #define CHK(x) do { if (!(x)) { return false; } } while(0)
  660. static size_t upb_encode_varint(uint64_t val, char *buf) {
  661. size_t i;
  662. if (val < 128) { buf[0] = val; return 1; }
  663. i = 0;
  664. while (val) {
  665. uint8_t byte = val & 0x7fU;
  666. val >>= 7;
  667. if (val) byte |= 0x80U;
  668. buf[i++] = byte;
  669. }
  670. return i;
  671. }
  672. static uint32_t upb_zzencode_32(int32_t n) { return ((uint32_t)n << 1) ^ (n >> 31); }
  673. static uint64_t upb_zzencode_64(int64_t n) { return ((uint64_t)n << 1) ^ (n >> 63); }
  674. typedef struct {
  675. upb_alloc *alloc;
  676. char *buf, *ptr, *limit;
  677. } upb_encstate;
  678. static size_t upb_roundup_pow2(size_t bytes) {
  679. size_t ret = 128;
  680. while (ret < bytes) {
  681. ret *= 2;
  682. }
  683. return ret;
  684. }
  685. static bool upb_encode_growbuffer(upb_encstate *e, size_t bytes) {
  686. size_t old_size = e->limit - e->buf;
  687. size_t new_size = upb_roundup_pow2(bytes + (e->limit - e->ptr));
  688. char *new_buf = upb_realloc(e->alloc, e->buf, old_size, new_size);
  689. CHK(new_buf);
  690. /* We want previous data at the end, realloc() put it at the beginning. */
  691. if (old_size > 0) {
  692. memmove(new_buf + new_size - old_size, e->buf, old_size);
  693. }
  694. e->ptr = new_buf + new_size - (e->limit - e->ptr);
  695. e->limit = new_buf + new_size;
  696. e->buf = new_buf;
  697. return true;
  698. }
  699. /* Call to ensure that at least "bytes" bytes are available for writing at
  700. * e->ptr. Returns false if the bytes could not be allocated. */
  701. static bool upb_encode_reserve(upb_encstate *e, size_t bytes) {
  702. CHK(UPB_LIKELY((size_t)(e->ptr - e->buf) >= bytes) ||
  703. upb_encode_growbuffer(e, bytes));
  704. e->ptr -= bytes;
  705. return true;
  706. }
  707. /* Writes the given bytes to the buffer, handling reserve/advance. */
  708. static bool upb_put_bytes(upb_encstate *e, const void *data, size_t len) {
  709. CHK(upb_encode_reserve(e, len));
  710. memcpy(e->ptr, data, len);
  711. return true;
  712. }
  713. static bool upb_put_fixed64(upb_encstate *e, uint64_t val) {
  714. /* TODO(haberman): byte-swap for big endian. */
  715. return upb_put_bytes(e, &val, sizeof(uint64_t));
  716. }
  717. static bool upb_put_fixed32(upb_encstate *e, uint32_t val) {
  718. /* TODO(haberman): byte-swap for big endian. */
  719. return upb_put_bytes(e, &val, sizeof(uint32_t));
  720. }
  721. static bool upb_put_varint(upb_encstate *e, uint64_t val) {
  722. size_t len;
  723. char *start;
  724. CHK(upb_encode_reserve(e, UPB_PB_VARINT_MAX_LEN));
  725. len = upb_encode_varint(val, e->ptr);
  726. start = e->ptr + UPB_PB_VARINT_MAX_LEN - len;
  727. memmove(start, e->ptr, len);
  728. e->ptr = start;
  729. return true;
  730. }
  731. static bool upb_put_double(upb_encstate *e, double d) {
  732. uint64_t u64;
  733. UPB_ASSERT(sizeof(double) == sizeof(uint64_t));
  734. memcpy(&u64, &d, sizeof(uint64_t));
  735. return upb_put_fixed64(e, u64);
  736. }
  737. static bool upb_put_float(upb_encstate *e, float d) {
  738. uint32_t u32;
  739. UPB_ASSERT(sizeof(float) == sizeof(uint32_t));
  740. memcpy(&u32, &d, sizeof(uint32_t));
  741. return upb_put_fixed32(e, u32);
  742. }
  743. static uint32_t upb_readcase(const char *msg, const upb_msglayout_field *f) {
  744. uint32_t ret;
  745. uint32_t offset = ~f->presence;
  746. memcpy(&ret, msg + offset, sizeof(ret));
  747. return ret;
  748. }
  749. static bool upb_readhasbit(const char *msg, const upb_msglayout_field *f) {
  750. uint32_t hasbit = f->presence;
  751. UPB_ASSERT(f->presence > 0);
  752. return msg[hasbit / 8] & (1 << (hasbit % 8));
  753. }
  754. static bool upb_put_tag(upb_encstate *e, int field_number, int wire_type) {
  755. return upb_put_varint(e, (field_number << 3) | wire_type);
  756. }
  757. static bool upb_put_fixedarray(upb_encstate *e, const upb_array *arr,
  758. size_t size) {
  759. size_t bytes = arr->len * size;
  760. return upb_put_bytes(e, arr->data, bytes) && upb_put_varint(e, bytes);
  761. }
  762. bool upb_encode_message(upb_encstate *e, const char *msg,
  763. const upb_msglayout *m, size_t *size);
  764. static bool upb_encode_array(upb_encstate *e, const char *field_mem,
  765. const upb_msglayout *m,
  766. const upb_msglayout_field *f) {
  767. const upb_array *arr = *(const upb_array**)field_mem;
  768. if (arr == NULL || arr->len == 0) {
  769. return true;
  770. }
  771. #define VARINT_CASE(ctype, encode) { \
  772. ctype *start = arr->data; \
  773. ctype *ptr = start + arr->len; \
  774. size_t pre_len = e->limit - e->ptr; \
  775. do { \
  776. ptr--; \
  777. CHK(upb_put_varint(e, encode)); \
  778. } while (ptr != start); \
  779. CHK(upb_put_varint(e, e->limit - e->ptr - pre_len)); \
  780. } \
  781. break; \
  782. do { ; } while(0)
  783. switch (f->descriptortype) {
  784. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  785. CHK(upb_put_fixedarray(e, arr, sizeof(double)));
  786. break;
  787. case UPB_DESCRIPTOR_TYPE_FLOAT:
  788. CHK(upb_put_fixedarray(e, arr, sizeof(float)));
  789. break;
  790. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  791. case UPB_DESCRIPTOR_TYPE_FIXED64:
  792. CHK(upb_put_fixedarray(e, arr, sizeof(uint64_t)));
  793. break;
  794. case UPB_DESCRIPTOR_TYPE_FIXED32:
  795. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  796. CHK(upb_put_fixedarray(e, arr, sizeof(uint32_t)));
  797. break;
  798. case UPB_DESCRIPTOR_TYPE_INT64:
  799. case UPB_DESCRIPTOR_TYPE_UINT64:
  800. VARINT_CASE(uint64_t, *ptr);
  801. case UPB_DESCRIPTOR_TYPE_UINT32:
  802. VARINT_CASE(uint32_t, *ptr);
  803. case UPB_DESCRIPTOR_TYPE_INT32:
  804. case UPB_DESCRIPTOR_TYPE_ENUM:
  805. VARINT_CASE(int32_t, (int64_t)*ptr);
  806. case UPB_DESCRIPTOR_TYPE_BOOL:
  807. VARINT_CASE(bool, *ptr);
  808. case UPB_DESCRIPTOR_TYPE_SINT32:
  809. VARINT_CASE(int32_t, upb_zzencode_32(*ptr));
  810. case UPB_DESCRIPTOR_TYPE_SINT64:
  811. VARINT_CASE(int64_t, upb_zzencode_64(*ptr));
  812. case UPB_DESCRIPTOR_TYPE_STRING:
  813. case UPB_DESCRIPTOR_TYPE_BYTES: {
  814. upb_strview *start = arr->data;
  815. upb_strview *ptr = start + arr->len;
  816. do {
  817. ptr--;
  818. CHK(upb_put_bytes(e, ptr->data, ptr->size) &&
  819. upb_put_varint(e, ptr->size) &&
  820. upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
  821. } while (ptr != start);
  822. return true;
  823. }
  824. case UPB_DESCRIPTOR_TYPE_GROUP: {
  825. void **start = arr->data;
  826. void **ptr = start + arr->len;
  827. const upb_msglayout *subm = m->submsgs[f->submsg_index];
  828. do {
  829. size_t size;
  830. ptr--;
  831. CHK(upb_put_tag(e, f->number, UPB_WIRE_TYPE_END_GROUP) &&
  832. upb_encode_message(e, *ptr, subm, &size) &&
  833. upb_put_tag(e, f->number, UPB_WIRE_TYPE_START_GROUP));
  834. } while (ptr != start);
  835. return true;
  836. }
  837. case UPB_DESCRIPTOR_TYPE_MESSAGE: {
  838. void **start = arr->data;
  839. void **ptr = start + arr->len;
  840. const upb_msglayout *subm = m->submsgs[f->submsg_index];
  841. do {
  842. size_t size;
  843. ptr--;
  844. CHK(upb_encode_message(e, *ptr, subm, &size) &&
  845. upb_put_varint(e, size) &&
  846. upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
  847. } while (ptr != start);
  848. return true;
  849. }
  850. }
  851. #undef VARINT_CASE
  852. /* We encode all primitive arrays as packed, regardless of what was specified
  853. * in the .proto file. Could special case 1-sized arrays. */
  854. CHK(upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
  855. return true;
  856. }
  857. static bool upb_encode_scalarfield(upb_encstate *e, const char *field_mem,
  858. const upb_msglayout *m,
  859. const upb_msglayout_field *f,
  860. bool skip_zero_value) {
  861. #define CASE(ctype, type, wire_type, encodeval) do { \
  862. ctype val = *(ctype*)field_mem; \
  863. if (skip_zero_value && val == 0) { \
  864. return true; \
  865. } \
  866. return upb_put_ ## type(e, encodeval) && \
  867. upb_put_tag(e, f->number, wire_type); \
  868. } while(0)
  869. switch (f->descriptortype) {
  870. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  871. CASE(double, double, UPB_WIRE_TYPE_64BIT, val);
  872. case UPB_DESCRIPTOR_TYPE_FLOAT:
  873. CASE(float, float, UPB_WIRE_TYPE_32BIT, val);
  874. case UPB_DESCRIPTOR_TYPE_INT64:
  875. case UPB_DESCRIPTOR_TYPE_UINT64:
  876. CASE(uint64_t, varint, UPB_WIRE_TYPE_VARINT, val);
  877. case UPB_DESCRIPTOR_TYPE_UINT32:
  878. CASE(uint32_t, varint, UPB_WIRE_TYPE_VARINT, val);
  879. case UPB_DESCRIPTOR_TYPE_INT32:
  880. case UPB_DESCRIPTOR_TYPE_ENUM:
  881. CASE(int32_t, varint, UPB_WIRE_TYPE_VARINT, (int64_t)val);
  882. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  883. case UPB_DESCRIPTOR_TYPE_FIXED64:
  884. CASE(uint64_t, fixed64, UPB_WIRE_TYPE_64BIT, val);
  885. case UPB_DESCRIPTOR_TYPE_FIXED32:
  886. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  887. CASE(uint32_t, fixed32, UPB_WIRE_TYPE_32BIT, val);
  888. case UPB_DESCRIPTOR_TYPE_BOOL:
  889. CASE(bool, varint, UPB_WIRE_TYPE_VARINT, val);
  890. case UPB_DESCRIPTOR_TYPE_SINT32:
  891. CASE(int32_t, varint, UPB_WIRE_TYPE_VARINT, upb_zzencode_32(val));
  892. case UPB_DESCRIPTOR_TYPE_SINT64:
  893. CASE(int64_t, varint, UPB_WIRE_TYPE_VARINT, upb_zzencode_64(val));
  894. case UPB_DESCRIPTOR_TYPE_STRING:
  895. case UPB_DESCRIPTOR_TYPE_BYTES: {
  896. upb_strview view = *(upb_strview*)field_mem;
  897. if (skip_zero_value && view.size == 0) {
  898. return true;
  899. }
  900. return upb_put_bytes(e, view.data, view.size) &&
  901. upb_put_varint(e, view.size) &&
  902. upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED);
  903. }
  904. case UPB_DESCRIPTOR_TYPE_GROUP: {
  905. size_t size;
  906. void *submsg = *(void **)field_mem;
  907. const upb_msglayout *subm = m->submsgs[f->submsg_index];
  908. if (submsg == NULL) {
  909. return true;
  910. }
  911. return upb_put_tag(e, f->number, UPB_WIRE_TYPE_END_GROUP) &&
  912. upb_encode_message(e, submsg, subm, &size) &&
  913. upb_put_tag(e, f->number, UPB_WIRE_TYPE_START_GROUP);
  914. }
  915. case UPB_DESCRIPTOR_TYPE_MESSAGE: {
  916. size_t size;
  917. void *submsg = *(void **)field_mem;
  918. const upb_msglayout *subm = m->submsgs[f->submsg_index];
  919. if (submsg == NULL) {
  920. return true;
  921. }
  922. return upb_encode_message(e, submsg, subm, &size) &&
  923. upb_put_varint(e, size) &&
  924. upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED);
  925. }
  926. }
  927. #undef CASE
  928. UPB_UNREACHABLE();
  929. }
  930. bool upb_encode_message(upb_encstate *e, const char *msg,
  931. const upb_msglayout *m, size_t *size) {
  932. int i;
  933. size_t pre_len = e->limit - e->ptr;
  934. const char *unknown;
  935. size_t unknown_size;
  936. for (i = m->field_count - 1; i >= 0; i--) {
  937. const upb_msglayout_field *f = &m->fields[i];
  938. if (f->label == UPB_LABEL_REPEATED) {
  939. CHK(upb_encode_array(e, msg + f->offset, m, f));
  940. } else {
  941. bool skip_empty = false;
  942. if (f->presence == 0) {
  943. /* Proto3 presence. */
  944. skip_empty = true;
  945. } else if (f->presence > 0) {
  946. /* Proto2 presence: hasbit. */
  947. if (!upb_readhasbit(msg, f)) {
  948. continue;
  949. }
  950. } else {
  951. /* Field is in a oneof. */
  952. if (upb_readcase(msg, f) != f->number) {
  953. continue;
  954. }
  955. }
  956. CHK(upb_encode_scalarfield(e, msg + f->offset, m, f, skip_empty));
  957. }
  958. }
  959. unknown = upb_msg_getunknown(msg, &unknown_size);
  960. if (unknown) {
  961. upb_put_bytes(e, unknown, unknown_size);
  962. }
  963. *size = (e->limit - e->ptr) - pre_len;
  964. return true;
  965. }
  966. char *upb_encode(const void *msg, const upb_msglayout *m, upb_arena *arena,
  967. size_t *size) {
  968. upb_encstate e;
  969. e.alloc = upb_arena_alloc(arena);
  970. e.buf = NULL;
  971. e.limit = NULL;
  972. e.ptr = NULL;
  973. if (!upb_encode_message(&e, msg, m, size)) {
  974. *size = 0;
  975. return NULL;
  976. }
  977. *size = e.limit - e.ptr;
  978. if (*size == 0) {
  979. static char ch;
  980. return &ch;
  981. } else {
  982. UPB_ASSERT(e.ptr);
  983. return e.ptr;
  984. }
  985. }
  986. #undef CHK
  987. #define VOIDPTR_AT(msg, ofs) (void*)((char*)msg + (int)ofs)
  988. /* Internal members of a upb_msg. We can change this without breaking binary
  989. * compatibility. We put these before the user's data. The user's upb_msg*
  990. * points after the upb_msg_internal. */
  991. /* Used when a message is not extendable. */
  992. typedef struct {
  993. char *unknown;
  994. size_t unknown_len;
  995. size_t unknown_size;
  996. } upb_msg_internal;
  997. /* Used when a message is extendable. */
  998. typedef struct {
  999. upb_inttable *extdict;
  1000. upb_msg_internal base;
  1001. } upb_msg_internal_withext;
  1002. static int upb_msg_internalsize(const upb_msglayout *l) {
  1003. return sizeof(upb_msg_internal) - l->extendable * sizeof(void *);
  1004. }
  1005. static size_t upb_msg_sizeof(const upb_msglayout *l) {
  1006. return l->size + upb_msg_internalsize(l);
  1007. }
  1008. static upb_msg_internal *upb_msg_getinternal(upb_msg *msg) {
  1009. return VOIDPTR_AT(msg, -sizeof(upb_msg_internal));
  1010. }
  1011. static const upb_msg_internal *upb_msg_getinternal_const(const upb_msg *msg) {
  1012. return VOIDPTR_AT(msg, -sizeof(upb_msg_internal));
  1013. }
  1014. static upb_msg_internal_withext *upb_msg_getinternalwithext(
  1015. upb_msg *msg, const upb_msglayout *l) {
  1016. UPB_ASSERT(l->extendable);
  1017. return VOIDPTR_AT(msg, -sizeof(upb_msg_internal_withext));
  1018. }
  1019. upb_msg *upb_msg_new(const upb_msglayout *l, upb_arena *a) {
  1020. upb_alloc *alloc = upb_arena_alloc(a);
  1021. void *mem = upb_malloc(alloc, upb_msg_sizeof(l));
  1022. upb_msg_internal *in;
  1023. upb_msg *msg;
  1024. if (!mem) {
  1025. return NULL;
  1026. }
  1027. msg = VOIDPTR_AT(mem, upb_msg_internalsize(l));
  1028. /* Initialize normal members. */
  1029. memset(msg, 0, l->size);
  1030. /* Initialize internal members. */
  1031. in = upb_msg_getinternal(msg);
  1032. in->unknown = NULL;
  1033. in->unknown_len = 0;
  1034. in->unknown_size = 0;
  1035. if (l->extendable) {
  1036. upb_msg_getinternalwithext(msg, l)->extdict = NULL;
  1037. }
  1038. return msg;
  1039. }
  1040. upb_array *upb_array_new(upb_arena *a) {
  1041. upb_array *ret = upb_arena_malloc(a, sizeof(upb_array));
  1042. if (!ret) {
  1043. return NULL;
  1044. }
  1045. ret->data = NULL;
  1046. ret->len = 0;
  1047. ret->size = 0;
  1048. return ret;
  1049. }
  1050. void upb_msg_addunknown(upb_msg *msg, const char *data, size_t len,
  1051. upb_arena *arena) {
  1052. upb_msg_internal *in = upb_msg_getinternal(msg);
  1053. if (len > in->unknown_size - in->unknown_len) {
  1054. upb_alloc *alloc = upb_arena_alloc(arena);
  1055. size_t need = in->unknown_size + len;
  1056. size_t newsize = UPB_MAX(in->unknown_size * 2, need);
  1057. in->unknown = upb_realloc(alloc, in->unknown, in->unknown_size, newsize);
  1058. in->unknown_size = newsize;
  1059. }
  1060. memcpy(in->unknown + in->unknown_len, data, len);
  1061. in->unknown_len += len;
  1062. }
  1063. const char *upb_msg_getunknown(const upb_msg *msg, size_t *len) {
  1064. const upb_msg_internal* in = upb_msg_getinternal_const(msg);
  1065. *len = in->unknown_len;
  1066. return in->unknown;
  1067. }
  1068. #undef VOIDPTR_AT
  1069. #ifdef UPB_MSVC_VSNPRINTF
  1070. /* Visual C++ earlier than 2015 doesn't have standard C99 snprintf and
  1071. * vsnprintf. To support them, missing functions are manually implemented
  1072. * using the existing secure functions. */
  1073. int msvc_vsnprintf(char* s, size_t n, const char* format, va_list arg) {
  1074. if (!s) {
  1075. return _vscprintf(format, arg);
  1076. }
  1077. int ret = _vsnprintf_s(s, n, _TRUNCATE, format, arg);
  1078. if (ret < 0) {
  1079. ret = _vscprintf(format, arg);
  1080. }
  1081. return ret;
  1082. }
  1083. int msvc_snprintf(char* s, size_t n, const char* format, ...) {
  1084. va_list arg;
  1085. va_start(arg, format);
  1086. int ret = msvc_vsnprintf(s, n, format, arg);
  1087. va_end(arg);
  1088. return ret;
  1089. }
  1090. #endif
  1091. /*
  1092. ** upb_table Implementation
  1093. **
  1094. ** Implementation is heavily inspired by Lua's ltable.c.
  1095. */
  1096. #include <string.h>
  1097. #define UPB_MAXARRSIZE 16 /* 64k. */
  1098. /* From Chromium. */
  1099. #define ARRAY_SIZE(x) \
  1100. ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x])))))
  1101. static void upb_check_alloc(upb_table *t, upb_alloc *a) {
  1102. UPB_UNUSED(t);
  1103. UPB_UNUSED(a);
  1104. UPB_ASSERT_DEBUGVAR(t->alloc == a);
  1105. }
  1106. static const double MAX_LOAD = 0.85;
  1107. /* The minimum utilization of the array part of a mixed hash/array table. This
  1108. * is a speed/memory-usage tradeoff (though it's not straightforward because of
  1109. * cache effects). The lower this is, the more memory we'll use. */
  1110. static const double MIN_DENSITY = 0.1;
  1111. bool is_pow2(uint64_t v) { return v == 0 || (v & (v - 1)) == 0; }
  1112. int log2ceil(uint64_t v) {
  1113. int ret = 0;
  1114. bool pow2 = is_pow2(v);
  1115. while (v >>= 1) ret++;
  1116. ret = pow2 ? ret : ret + 1; /* Ceiling. */
  1117. return UPB_MIN(UPB_MAXARRSIZE, ret);
  1118. }
  1119. char *upb_strdup(const char *s, upb_alloc *a) {
  1120. return upb_strdup2(s, strlen(s), a);
  1121. }
  1122. char *upb_strdup2(const char *s, size_t len, upb_alloc *a) {
  1123. size_t n;
  1124. char *p;
  1125. /* Prevent overflow errors. */
  1126. if (len == SIZE_MAX) return NULL;
  1127. /* Always null-terminate, even if binary data; but don't rely on the input to
  1128. * have a null-terminating byte since it may be a raw binary buffer. */
  1129. n = len + 1;
  1130. p = upb_malloc(a, n);
  1131. if (p) {
  1132. memcpy(p, s, len);
  1133. p[len] = 0;
  1134. }
  1135. return p;
  1136. }
  1137. /* A type to represent the lookup key of either a strtable or an inttable. */
  1138. typedef union {
  1139. uintptr_t num;
  1140. struct {
  1141. const char *str;
  1142. size_t len;
  1143. } str;
  1144. } lookupkey_t;
  1145. static lookupkey_t strkey2(const char *str, size_t len) {
  1146. lookupkey_t k;
  1147. k.str.str = str;
  1148. k.str.len = len;
  1149. return k;
  1150. }
  1151. static lookupkey_t intkey(uintptr_t key) {
  1152. lookupkey_t k;
  1153. k.num = key;
  1154. return k;
  1155. }
  1156. typedef uint32_t hashfunc_t(upb_tabkey key);
  1157. typedef bool eqlfunc_t(upb_tabkey k1, lookupkey_t k2);
  1158. /* Base table (shared code) ***************************************************/
  1159. /* For when we need to cast away const. */
  1160. static upb_tabent *mutable_entries(upb_table *t) {
  1161. return (upb_tabent*)t->entries;
  1162. }
  1163. static bool isfull(upb_table *t) {
  1164. if (upb_table_size(t) == 0) {
  1165. return true;
  1166. } else {
  1167. return ((double)(t->count + 1) / upb_table_size(t)) > MAX_LOAD;
  1168. }
  1169. }
  1170. static bool init(upb_table *t, upb_ctype_t ctype, uint8_t size_lg2,
  1171. upb_alloc *a) {
  1172. size_t bytes;
  1173. t->count = 0;
  1174. t->ctype = ctype;
  1175. t->size_lg2 = size_lg2;
  1176. t->mask = upb_table_size(t) ? upb_table_size(t) - 1 : 0;
  1177. #ifndef NDEBUG
  1178. t->alloc = a;
  1179. #endif
  1180. bytes = upb_table_size(t) * sizeof(upb_tabent);
  1181. if (bytes > 0) {
  1182. t->entries = upb_malloc(a, bytes);
  1183. if (!t->entries) return false;
  1184. memset(mutable_entries(t), 0, bytes);
  1185. } else {
  1186. t->entries = NULL;
  1187. }
  1188. return true;
  1189. }
  1190. static void uninit(upb_table *t, upb_alloc *a) {
  1191. upb_check_alloc(t, a);
  1192. upb_free(a, mutable_entries(t));
  1193. }
  1194. static upb_tabent *emptyent(upb_table *t) {
  1195. upb_tabent *e = mutable_entries(t) + upb_table_size(t);
  1196. while (1) { if (upb_tabent_isempty(--e)) return e; UPB_ASSERT(e > t->entries); }
  1197. }
  1198. static upb_tabent *getentry_mutable(upb_table *t, uint32_t hash) {
  1199. return (upb_tabent*)upb_getentry(t, hash);
  1200. }
  1201. static const upb_tabent *findentry(const upb_table *t, lookupkey_t key,
  1202. uint32_t hash, eqlfunc_t *eql) {
  1203. const upb_tabent *e;
  1204. if (t->size_lg2 == 0) return NULL;
  1205. e = upb_getentry(t, hash);
  1206. if (upb_tabent_isempty(e)) return NULL;
  1207. while (1) {
  1208. if (eql(e->key, key)) return e;
  1209. if ((e = e->next) == NULL) return NULL;
  1210. }
  1211. }
  1212. static upb_tabent *findentry_mutable(upb_table *t, lookupkey_t key,
  1213. uint32_t hash, eqlfunc_t *eql) {
  1214. return (upb_tabent*)findentry(t, key, hash, eql);
  1215. }
  1216. static bool lookup(const upb_table *t, lookupkey_t key, upb_value *v,
  1217. uint32_t hash, eqlfunc_t *eql) {
  1218. const upb_tabent *e = findentry(t, key, hash, eql);
  1219. if (e) {
  1220. if (v) {
  1221. _upb_value_setval(v, e->val.val, t->ctype);
  1222. }
  1223. return true;
  1224. } else {
  1225. return false;
  1226. }
  1227. }
  1228. /* The given key must not already exist in the table. */
  1229. static void insert(upb_table *t, lookupkey_t key, upb_tabkey tabkey,
  1230. upb_value val, uint32_t hash,
  1231. hashfunc_t *hashfunc, eqlfunc_t *eql) {
  1232. upb_tabent *mainpos_e;
  1233. upb_tabent *our_e;
  1234. UPB_ASSERT(findentry(t, key, hash, eql) == NULL);
  1235. UPB_ASSERT_DEBUGVAR(val.ctype == t->ctype);
  1236. t->count++;
  1237. mainpos_e = getentry_mutable(t, hash);
  1238. our_e = mainpos_e;
  1239. if (upb_tabent_isempty(mainpos_e)) {
  1240. /* Our main position is empty; use it. */
  1241. our_e->next = NULL;
  1242. } else {
  1243. /* Collision. */
  1244. upb_tabent *new_e = emptyent(t);
  1245. /* Head of collider's chain. */
  1246. upb_tabent *chain = getentry_mutable(t, hashfunc(mainpos_e->key));
  1247. if (chain == mainpos_e) {
  1248. /* Existing ent is in its main posisiton (it has the same hash as us, and
  1249. * is the head of our chain). Insert to new ent and append to this chain. */
  1250. new_e->next = mainpos_e->next;
  1251. mainpos_e->next = new_e;
  1252. our_e = new_e;
  1253. } else {
  1254. /* Existing ent is not in its main position (it is a node in some other
  1255. * chain). This implies that no existing ent in the table has our hash.
  1256. * Evict it (updating its chain) and use its ent for head of our chain. */
  1257. *new_e = *mainpos_e; /* copies next. */
  1258. while (chain->next != mainpos_e) {
  1259. chain = (upb_tabent*)chain->next;
  1260. UPB_ASSERT(chain);
  1261. }
  1262. chain->next = new_e;
  1263. our_e = mainpos_e;
  1264. our_e->next = NULL;
  1265. }
  1266. }
  1267. our_e->key = tabkey;
  1268. our_e->val.val = val.val;
  1269. UPB_ASSERT(findentry(t, key, hash, eql) == our_e);
  1270. }
  1271. static bool rm(upb_table *t, lookupkey_t key, upb_value *val,
  1272. upb_tabkey *removed, uint32_t hash, eqlfunc_t *eql) {
  1273. upb_tabent *chain = getentry_mutable(t, hash);
  1274. if (upb_tabent_isempty(chain)) return false;
  1275. if (eql(chain->key, key)) {
  1276. /* Element to remove is at the head of its chain. */
  1277. t->count--;
  1278. if (val) _upb_value_setval(val, chain->val.val, t->ctype);
  1279. if (removed) *removed = chain->key;
  1280. if (chain->next) {
  1281. upb_tabent *move = (upb_tabent*)chain->next;
  1282. *chain = *move;
  1283. move->key = 0; /* Make the slot empty. */
  1284. } else {
  1285. chain->key = 0; /* Make the slot empty. */
  1286. }
  1287. return true;
  1288. } else {
  1289. /* Element to remove is either in a non-head position or not in the
  1290. * table. */
  1291. while (chain->next && !eql(chain->next->key, key)) {
  1292. chain = (upb_tabent*)chain->next;
  1293. }
  1294. if (chain->next) {
  1295. /* Found element to remove. */
  1296. upb_tabent *rm = (upb_tabent*)chain->next;
  1297. t->count--;
  1298. if (val) _upb_value_setval(val, chain->next->val.val, t->ctype);
  1299. if (removed) *removed = rm->key;
  1300. rm->key = 0; /* Make the slot empty. */
  1301. chain->next = rm->next;
  1302. return true;
  1303. } else {
  1304. /* Element to remove is not in the table. */
  1305. return false;
  1306. }
  1307. }
  1308. }
  1309. static size_t next(const upb_table *t, size_t i) {
  1310. do {
  1311. if (++i >= upb_table_size(t))
  1312. return SIZE_MAX;
  1313. } while(upb_tabent_isempty(&t->entries[i]));
  1314. return i;
  1315. }
  1316. static size_t begin(const upb_table *t) {
  1317. return next(t, -1);
  1318. }
  1319. /* upb_strtable ***************************************************************/
  1320. /* A simple "subclass" of upb_table that only adds a hash function for strings. */
  1321. static upb_tabkey strcopy(lookupkey_t k2, upb_alloc *a) {
  1322. uint32_t len = (uint32_t) k2.str.len;
  1323. char *str = upb_malloc(a, k2.str.len + sizeof(uint32_t) + 1);
  1324. if (str == NULL) return 0;
  1325. memcpy(str, &len, sizeof(uint32_t));
  1326. memcpy(str + sizeof(uint32_t), k2.str.str, k2.str.len + 1);
  1327. return (uintptr_t)str;
  1328. }
  1329. static uint32_t strhash(upb_tabkey key) {
  1330. uint32_t len;
  1331. char *str = upb_tabstr(key, &len);
  1332. return upb_murmur_hash2(str, len, 0);
  1333. }
  1334. static bool streql(upb_tabkey k1, lookupkey_t k2) {
  1335. uint32_t len;
  1336. char *str = upb_tabstr(k1, &len);
  1337. return len == k2.str.len && memcmp(str, k2.str.str, len) == 0;
  1338. }
  1339. bool upb_strtable_init2(upb_strtable *t, upb_ctype_t ctype, upb_alloc *a) {
  1340. return init(&t->t, ctype, 2, a);
  1341. }
  1342. void upb_strtable_uninit2(upb_strtable *t, upb_alloc *a) {
  1343. size_t i;
  1344. for (i = 0; i < upb_table_size(&t->t); i++)
  1345. upb_free(a, (void*)t->t.entries[i].key);
  1346. uninit(&t->t, a);
  1347. }
  1348. bool upb_strtable_resize(upb_strtable *t, size_t size_lg2, upb_alloc *a) {
  1349. upb_strtable new_table;
  1350. upb_strtable_iter i;
  1351. upb_check_alloc(&t->t, a);
  1352. if (!init(&new_table.t, t->t.ctype, size_lg2, a))
  1353. return false;
  1354. upb_strtable_begin(&i, t);
  1355. for ( ; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  1356. upb_strtable_insert3(
  1357. &new_table,
  1358. upb_strtable_iter_key(&i),
  1359. upb_strtable_iter_keylength(&i),
  1360. upb_strtable_iter_value(&i),
  1361. a);
  1362. }
  1363. upb_strtable_uninit2(t, a);
  1364. *t = new_table;
  1365. return true;
  1366. }
  1367. bool upb_strtable_insert3(upb_strtable *t, const char *k, size_t len,
  1368. upb_value v, upb_alloc *a) {
  1369. lookupkey_t key;
  1370. upb_tabkey tabkey;
  1371. uint32_t hash;
  1372. upb_check_alloc(&t->t, a);
  1373. if (isfull(&t->t)) {
  1374. /* Need to resize. New table of double the size, add old elements to it. */
  1375. if (!upb_strtable_resize(t, t->t.size_lg2 + 1, a)) {
  1376. return false;
  1377. }
  1378. }
  1379. key = strkey2(k, len);
  1380. tabkey = strcopy(key, a);
  1381. if (tabkey == 0) return false;
  1382. hash = upb_murmur_hash2(key.str.str, key.str.len, 0);
  1383. insert(&t->t, key, tabkey, v, hash, &strhash, &streql);
  1384. return true;
  1385. }
  1386. bool upb_strtable_lookup2(const upb_strtable *t, const char *key, size_t len,
  1387. upb_value *v) {
  1388. uint32_t hash = upb_murmur_hash2(key, len, 0);
  1389. return lookup(&t->t, strkey2(key, len), v, hash, &streql);
  1390. }
  1391. bool upb_strtable_remove3(upb_strtable *t, const char *key, size_t len,
  1392. upb_value *val, upb_alloc *alloc) {
  1393. uint32_t hash = upb_murmur_hash2(key, len, 0);
  1394. upb_tabkey tabkey;
  1395. if (rm(&t->t, strkey2(key, len), val, &tabkey, hash, &streql)) {
  1396. upb_free(alloc, (void*)tabkey);
  1397. return true;
  1398. } else {
  1399. return false;
  1400. }
  1401. }
  1402. /* Iteration */
  1403. static const upb_tabent *str_tabent(const upb_strtable_iter *i) {
  1404. return &i->t->t.entries[i->index];
  1405. }
  1406. void upb_strtable_begin(upb_strtable_iter *i, const upb_strtable *t) {
  1407. i->t = t;
  1408. i->index = begin(&t->t);
  1409. }
  1410. void upb_strtable_next(upb_strtable_iter *i) {
  1411. i->index = next(&i->t->t, i->index);
  1412. }
  1413. bool upb_strtable_done(const upb_strtable_iter *i) {
  1414. if (!i->t) return true;
  1415. return i->index >= upb_table_size(&i->t->t) ||
  1416. upb_tabent_isempty(str_tabent(i));
  1417. }
  1418. const char *upb_strtable_iter_key(const upb_strtable_iter *i) {
  1419. UPB_ASSERT(!upb_strtable_done(i));
  1420. return upb_tabstr(str_tabent(i)->key, NULL);
  1421. }
  1422. size_t upb_strtable_iter_keylength(const upb_strtable_iter *i) {
  1423. uint32_t len;
  1424. UPB_ASSERT(!upb_strtable_done(i));
  1425. upb_tabstr(str_tabent(i)->key, &len);
  1426. return len;
  1427. }
  1428. upb_value upb_strtable_iter_value(const upb_strtable_iter *i) {
  1429. UPB_ASSERT(!upb_strtable_done(i));
  1430. return _upb_value_val(str_tabent(i)->val.val, i->t->t.ctype);
  1431. }
  1432. void upb_strtable_iter_setdone(upb_strtable_iter *i) {
  1433. i->t = NULL;
  1434. i->index = SIZE_MAX;
  1435. }
  1436. bool upb_strtable_iter_isequal(const upb_strtable_iter *i1,
  1437. const upb_strtable_iter *i2) {
  1438. if (upb_strtable_done(i1) && upb_strtable_done(i2))
  1439. return true;
  1440. return i1->t == i2->t && i1->index == i2->index;
  1441. }
  1442. /* upb_inttable ***************************************************************/
  1443. /* For inttables we use a hybrid structure where small keys are kept in an
  1444. * array and large keys are put in the hash table. */
  1445. static uint32_t inthash(upb_tabkey key) { return upb_inthash(key); }
  1446. static bool inteql(upb_tabkey k1, lookupkey_t k2) {
  1447. return k1 == k2.num;
  1448. }
  1449. static upb_tabval *mutable_array(upb_inttable *t) {
  1450. return (upb_tabval*)t->array;
  1451. }
  1452. static upb_tabval *inttable_val(upb_inttable *t, uintptr_t key) {
  1453. if (key < t->array_size) {
  1454. return upb_arrhas(t->array[key]) ? &(mutable_array(t)[key]) : NULL;
  1455. } else {
  1456. upb_tabent *e =
  1457. findentry_mutable(&t->t, intkey(key), upb_inthash(key), &inteql);
  1458. return e ? &e->val : NULL;
  1459. }
  1460. }
  1461. static const upb_tabval *inttable_val_const(const upb_inttable *t,
  1462. uintptr_t key) {
  1463. return inttable_val((upb_inttable*)t, key);
  1464. }
  1465. size_t upb_inttable_count(const upb_inttable *t) {
  1466. return t->t.count + t->array_count;
  1467. }
  1468. static void check(upb_inttable *t) {
  1469. UPB_UNUSED(t);
  1470. #if defined(UPB_DEBUG_TABLE) && !defined(NDEBUG)
  1471. {
  1472. /* This check is very expensive (makes inserts/deletes O(N)). */
  1473. size_t count = 0;
  1474. upb_inttable_iter i;
  1475. upb_inttable_begin(&i, t);
  1476. for(; !upb_inttable_done(&i); upb_inttable_next(&i), count++) {
  1477. UPB_ASSERT(upb_inttable_lookup(t, upb_inttable_iter_key(&i), NULL));
  1478. }
  1479. UPB_ASSERT(count == upb_inttable_count(t));
  1480. }
  1481. #endif
  1482. }
  1483. bool upb_inttable_sizedinit(upb_inttable *t, upb_ctype_t ctype,
  1484. size_t asize, int hsize_lg2, upb_alloc *a) {
  1485. size_t array_bytes;
  1486. if (!init(&t->t, ctype, hsize_lg2, a)) return false;
  1487. /* Always make the array part at least 1 long, so that we know key 0
  1488. * won't be in the hash part, which simplifies things. */
  1489. t->array_size = UPB_MAX(1, asize);
  1490. t->array_count = 0;
  1491. array_bytes = t->array_size * sizeof(upb_value);
  1492. t->array = upb_malloc(a, array_bytes);
  1493. if (!t->array) {
  1494. uninit(&t->t, a);
  1495. return false;
  1496. }
  1497. memset(mutable_array(t), 0xff, array_bytes);
  1498. check(t);
  1499. return true;
  1500. }
  1501. bool upb_inttable_init2(upb_inttable *t, upb_ctype_t ctype, upb_alloc *a) {
  1502. return upb_inttable_sizedinit(t, ctype, 0, 4, a);
  1503. }
  1504. void upb_inttable_uninit2(upb_inttable *t, upb_alloc *a) {
  1505. uninit(&t->t, a);
  1506. upb_free(a, mutable_array(t));
  1507. }
  1508. bool upb_inttable_insert2(upb_inttable *t, uintptr_t key, upb_value val,
  1509. upb_alloc *a) {
  1510. upb_tabval tabval;
  1511. tabval.val = val.val;
  1512. UPB_ASSERT(upb_arrhas(tabval)); /* This will reject (uint64_t)-1. Fix this. */
  1513. upb_check_alloc(&t->t, a);
  1514. if (key < t->array_size) {
  1515. UPB_ASSERT(!upb_arrhas(t->array[key]));
  1516. t->array_count++;
  1517. mutable_array(t)[key].val = val.val;
  1518. } else {
  1519. if (isfull(&t->t)) {
  1520. /* Need to resize the hash part, but we re-use the array part. */
  1521. size_t i;
  1522. upb_table new_table;
  1523. if (!init(&new_table, t->t.ctype, t->t.size_lg2 + 1, a)) {
  1524. return false;
  1525. }
  1526. for (i = begin(&t->t); i < upb_table_size(&t->t); i = next(&t->t, i)) {
  1527. const upb_tabent *e = &t->t.entries[i];
  1528. uint32_t hash;
  1529. upb_value v;
  1530. _upb_value_setval(&v, e->val.val, t->t.ctype);
  1531. hash = upb_inthash(e->key);
  1532. insert(&new_table, intkey(e->key), e->key, v, hash, &inthash, &inteql);
  1533. }
  1534. UPB_ASSERT(t->t.count == new_table.count);
  1535. uninit(&t->t, a);
  1536. t->t = new_table;
  1537. }
  1538. insert(&t->t, intkey(key), key, val, upb_inthash(key), &inthash, &inteql);
  1539. }
  1540. check(t);
  1541. return true;
  1542. }
  1543. bool upb_inttable_lookup(const upb_inttable *t, uintptr_t key, upb_value *v) {
  1544. const upb_tabval *table_v = inttable_val_const(t, key);
  1545. if (!table_v) return false;
  1546. if (v) _upb_value_setval(v, table_v->val, t->t.ctype);
  1547. return true;
  1548. }
  1549. bool upb_inttable_replace(upb_inttable *t, uintptr_t key, upb_value val) {
  1550. upb_tabval *table_v = inttable_val(t, key);
  1551. if (!table_v) return false;
  1552. table_v->val = val.val;
  1553. return true;
  1554. }
  1555. bool upb_inttable_remove(upb_inttable *t, uintptr_t key, upb_value *val) {
  1556. bool success;
  1557. if (key < t->array_size) {
  1558. if (upb_arrhas(t->array[key])) {
  1559. upb_tabval empty = UPB_TABVALUE_EMPTY_INIT;
  1560. t->array_count--;
  1561. if (val) {
  1562. _upb_value_setval(val, t->array[key].val, t->t.ctype);
  1563. }
  1564. mutable_array(t)[key] = empty;
  1565. success = true;
  1566. } else {
  1567. success = false;
  1568. }
  1569. } else {
  1570. success = rm(&t->t, intkey(key), val, NULL, upb_inthash(key), &inteql);
  1571. }
  1572. check(t);
  1573. return success;
  1574. }
  1575. bool upb_inttable_push2(upb_inttable *t, upb_value val, upb_alloc *a) {
  1576. upb_check_alloc(&t->t, a);
  1577. return upb_inttable_insert2(t, upb_inttable_count(t), val, a);
  1578. }
  1579. upb_value upb_inttable_pop(upb_inttable *t) {
  1580. upb_value val;
  1581. bool ok = upb_inttable_remove(t, upb_inttable_count(t) - 1, &val);
  1582. UPB_ASSERT(ok);
  1583. return val;
  1584. }
  1585. bool upb_inttable_insertptr2(upb_inttable *t, const void *key, upb_value val,
  1586. upb_alloc *a) {
  1587. upb_check_alloc(&t->t, a);
  1588. return upb_inttable_insert2(t, (uintptr_t)key, val, a);
  1589. }
  1590. bool upb_inttable_lookupptr(const upb_inttable *t, const void *key,
  1591. upb_value *v) {
  1592. return upb_inttable_lookup(t, (uintptr_t)key, v);
  1593. }
  1594. bool upb_inttable_removeptr(upb_inttable *t, const void *key, upb_value *val) {
  1595. return upb_inttable_remove(t, (uintptr_t)key, val);
  1596. }
  1597. void upb_inttable_compact2(upb_inttable *t, upb_alloc *a) {
  1598. /* A power-of-two histogram of the table keys. */
  1599. size_t counts[UPB_MAXARRSIZE + 1] = {0};
  1600. /* The max key in each bucket. */
  1601. uintptr_t max[UPB_MAXARRSIZE + 1] = {0};
  1602. upb_inttable_iter i;
  1603. size_t arr_count;
  1604. int size_lg2;
  1605. upb_inttable new_t;
  1606. upb_check_alloc(&t->t, a);
  1607. upb_inttable_begin(&i, t);
  1608. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  1609. uintptr_t key = upb_inttable_iter_key(&i);
  1610. int bucket = log2ceil(key);
  1611. max[bucket] = UPB_MAX(max[bucket], key);
  1612. counts[bucket]++;
  1613. }
  1614. /* Find the largest power of two that satisfies the MIN_DENSITY
  1615. * definition (while actually having some keys). */
  1616. arr_count = upb_inttable_count(t);
  1617. for (size_lg2 = ARRAY_SIZE(counts) - 1; size_lg2 > 0; size_lg2--) {
  1618. if (counts[size_lg2] == 0) {
  1619. /* We can halve again without losing any entries. */
  1620. continue;
  1621. } else if (arr_count >= (1 << size_lg2) * MIN_DENSITY) {
  1622. break;
  1623. }
  1624. arr_count -= counts[size_lg2];
  1625. }
  1626. UPB_ASSERT(arr_count <= upb_inttable_count(t));
  1627. {
  1628. /* Insert all elements into new, perfectly-sized table. */
  1629. size_t arr_size = max[size_lg2] + 1; /* +1 so arr[max] will fit. */
  1630. size_t hash_count = upb_inttable_count(t) - arr_count;
  1631. size_t hash_size = hash_count ? (hash_count / MAX_LOAD) + 1 : 0;
  1632. int hashsize_lg2 = log2ceil(hash_size);
  1633. upb_inttable_sizedinit(&new_t, t->t.ctype, arr_size, hashsize_lg2, a);
  1634. upb_inttable_begin(&i, t);
  1635. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  1636. uintptr_t k = upb_inttable_iter_key(&i);
  1637. upb_inttable_insert2(&new_t, k, upb_inttable_iter_value(&i), a);
  1638. }
  1639. UPB_ASSERT(new_t.array_size == arr_size);
  1640. UPB_ASSERT(new_t.t.size_lg2 == hashsize_lg2);
  1641. }
  1642. upb_inttable_uninit2(t, a);
  1643. *t = new_t;
  1644. }
  1645. /* Iteration. */
  1646. static const upb_tabent *int_tabent(const upb_inttable_iter *i) {
  1647. UPB_ASSERT(!i->array_part);
  1648. return &i->t->t.entries[i->index];
  1649. }
  1650. static upb_tabval int_arrent(const upb_inttable_iter *i) {
  1651. UPB_ASSERT(i->array_part);
  1652. return i->t->array[i->index];
  1653. }
  1654. void upb_inttable_begin(upb_inttable_iter *i, const upb_inttable *t) {
  1655. i->t = t;
  1656. i->index = -1;
  1657. i->array_part = true;
  1658. upb_inttable_next(i);
  1659. }
  1660. void upb_inttable_next(upb_inttable_iter *iter) {
  1661. const upb_inttable *t = iter->t;
  1662. if (iter->array_part) {
  1663. while (++iter->index < t->array_size) {
  1664. if (upb_arrhas(int_arrent(iter))) {
  1665. return;
  1666. }
  1667. }
  1668. iter->array_part = false;
  1669. iter->index = begin(&t->t);
  1670. } else {
  1671. iter->index = next(&t->t, iter->index);
  1672. }
  1673. }
  1674. bool upb_inttable_done(const upb_inttable_iter *i) {
  1675. if (!i->t) return true;
  1676. if (i->array_part) {
  1677. return i->index >= i->t->array_size ||
  1678. !upb_arrhas(int_arrent(i));
  1679. } else {
  1680. return i->index >= upb_table_size(&i->t->t) ||
  1681. upb_tabent_isempty(int_tabent(i));
  1682. }
  1683. }
  1684. uintptr_t upb_inttable_iter_key(const upb_inttable_iter *i) {
  1685. UPB_ASSERT(!upb_inttable_done(i));
  1686. return i->array_part ? i->index : int_tabent(i)->key;
  1687. }
  1688. upb_value upb_inttable_iter_value(const upb_inttable_iter *i) {
  1689. UPB_ASSERT(!upb_inttable_done(i));
  1690. return _upb_value_val(
  1691. i->array_part ? i->t->array[i->index].val : int_tabent(i)->val.val,
  1692. i->t->t.ctype);
  1693. }
  1694. void upb_inttable_iter_setdone(upb_inttable_iter *i) {
  1695. i->t = NULL;
  1696. i->index = SIZE_MAX;
  1697. i->array_part = false;
  1698. }
  1699. bool upb_inttable_iter_isequal(const upb_inttable_iter *i1,
  1700. const upb_inttable_iter *i2) {
  1701. if (upb_inttable_done(i1) && upb_inttable_done(i2))
  1702. return true;
  1703. return i1->t == i2->t && i1->index == i2->index &&
  1704. i1->array_part == i2->array_part;
  1705. }
  1706. #if defined(UPB_UNALIGNED_READS_OK) || defined(__s390x__)
  1707. /* -----------------------------------------------------------------------------
  1708. * MurmurHash2, by Austin Appleby (released as public domain).
  1709. * Reformatted and C99-ified by Joshua Haberman.
  1710. * Note - This code makes a few assumptions about how your machine behaves -
  1711. * 1. We can read a 4-byte value from any address without crashing
  1712. * 2. sizeof(int) == 4 (in upb this limitation is removed by using uint32_t
  1713. * And it has a few limitations -
  1714. * 1. It will not work incrementally.
  1715. * 2. It will not produce the same results on little-endian and big-endian
  1716. * machines. */
  1717. uint32_t upb_murmur_hash2(const void *key, size_t len, uint32_t seed) {
  1718. /* 'm' and 'r' are mixing constants generated offline.
  1719. * They're not really 'magic', they just happen to work well. */
  1720. const uint32_t m = 0x5bd1e995;
  1721. const int32_t r = 24;
  1722. /* Initialize the hash to a 'random' value */
  1723. uint32_t h = seed ^ len;
  1724. /* Mix 4 bytes at a time into the hash */
  1725. const uint8_t * data = (const uint8_t *)key;
  1726. while(len >= 4) {
  1727. uint32_t k = *(uint32_t *)data;
  1728. k *= m;
  1729. k ^= k >> r;
  1730. k *= m;
  1731. h *= m;
  1732. h ^= k;
  1733. data += 4;
  1734. len -= 4;
  1735. }
  1736. /* Handle the last few bytes of the input array */
  1737. switch(len) {
  1738. case 3: h ^= data[2] << 16;
  1739. case 2: h ^= data[1] << 8;
  1740. case 1: h ^= data[0]; h *= m;
  1741. };
  1742. /* Do a few final mixes of the hash to ensure the last few
  1743. * bytes are well-incorporated. */
  1744. h ^= h >> 13;
  1745. h *= m;
  1746. h ^= h >> 15;
  1747. return h;
  1748. }
  1749. #else /* !UPB_UNALIGNED_READS_OK */
  1750. /* -----------------------------------------------------------------------------
  1751. * MurmurHashAligned2, by Austin Appleby
  1752. * Same algorithm as MurmurHash2, but only does aligned reads - should be safer
  1753. * on certain platforms.
  1754. * Performance will be lower than MurmurHash2 */
  1755. #define MIX(h,k,m) { k *= m; k ^= k >> r; k *= m; h *= m; h ^= k; }
  1756. uint32_t upb_murmur_hash2(const void * key, size_t len, uint32_t seed) {
  1757. const uint32_t m = 0x5bd1e995;
  1758. const int32_t r = 24;
  1759. const uint8_t * data = (const uint8_t *)key;
  1760. uint32_t h = (uint32_t)(seed ^ len);
  1761. uint8_t align = (uintptr_t)data & 3;
  1762. if(align && (len >= 4)) {
  1763. /* Pre-load the temp registers */
  1764. uint32_t t = 0, d = 0;
  1765. int32_t sl;
  1766. int32_t sr;
  1767. switch(align) {
  1768. case 1: t |= data[2] << 16;
  1769. case 2: t |= data[1] << 8;
  1770. case 3: t |= data[0];
  1771. }
  1772. t <<= (8 * align);
  1773. data += 4-align;
  1774. len -= 4-align;
  1775. sl = 8 * (4-align);
  1776. sr = 8 * align;
  1777. /* Mix */
  1778. while(len >= 4) {
  1779. uint32_t k;
  1780. d = *(uint32_t *)data;
  1781. t = (t >> sr) | (d << sl);
  1782. k = t;
  1783. MIX(h,k,m);
  1784. t = d;
  1785. data += 4;
  1786. len -= 4;
  1787. }
  1788. /* Handle leftover data in temp registers */
  1789. d = 0;
  1790. if(len >= align) {
  1791. uint32_t k;
  1792. switch(align) {
  1793. case 3: d |= data[2] << 16;
  1794. case 2: d |= data[1] << 8;
  1795. case 1: d |= data[0];
  1796. }
  1797. k = (t >> sr) | (d << sl);
  1798. MIX(h,k,m);
  1799. data += align;
  1800. len -= align;
  1801. /* ----------
  1802. * Handle tail bytes */
  1803. switch(len) {
  1804. case 3: h ^= data[2] << 16;
  1805. case 2: h ^= data[1] << 8;
  1806. case 1: h ^= data[0]; h *= m;
  1807. };
  1808. } else {
  1809. switch(len) {
  1810. case 3: d |= data[2] << 16;
  1811. case 2: d |= data[1] << 8;
  1812. case 1: d |= data[0];
  1813. case 0: h ^= (t >> sr) | (d << sl); h *= m;
  1814. }
  1815. }
  1816. h ^= h >> 13;
  1817. h *= m;
  1818. h ^= h >> 15;
  1819. return h;
  1820. } else {
  1821. while(len >= 4) {
  1822. uint32_t k = *(uint32_t *)data;
  1823. MIX(h,k,m);
  1824. data += 4;
  1825. len -= 4;
  1826. }
  1827. /* ----------
  1828. * Handle tail bytes */
  1829. switch(len) {
  1830. case 3: h ^= data[2] << 16;
  1831. case 2: h ^= data[1] << 8;
  1832. case 1: h ^= data[0]; h *= m;
  1833. };
  1834. h ^= h >> 13;
  1835. h *= m;
  1836. h ^= h >> 15;
  1837. return h;
  1838. }
  1839. }
  1840. #undef MIX
  1841. #endif /* UPB_UNALIGNED_READS_OK */
  1842. #include <errno.h>
  1843. #include <stdarg.h>
  1844. #include <stddef.h>
  1845. #include <stdint.h>
  1846. #include <stdio.h>
  1847. #include <stdlib.h>
  1848. #include <string.h>
  1849. /* Guarantee null-termination and provide ellipsis truncation.
  1850. * It may be tempting to "optimize" this by initializing these final
  1851. * four bytes up-front and then being careful never to overwrite them,
  1852. * this is safer and simpler. */
  1853. static void nullz(upb_status *status) {
  1854. const char *ellipsis = "...";
  1855. size_t len = strlen(ellipsis);
  1856. UPB_ASSERT(sizeof(status->msg) > len);
  1857. memcpy(status->msg + sizeof(status->msg) - len, ellipsis, len);
  1858. }
  1859. /* upb_status *****************************************************************/
  1860. void upb_status_clear(upb_status *status) {
  1861. if (!status) return;
  1862. status->ok = true;
  1863. status->msg[0] = '\0';
  1864. }
  1865. bool upb_ok(const upb_status *status) { return status->ok; }
  1866. const char *upb_status_errmsg(const upb_status *status) { return status->msg; }
  1867. void upb_status_seterrmsg(upb_status *status, const char *msg) {
  1868. if (!status) return;
  1869. status->ok = false;
  1870. strncpy(status->msg, msg, sizeof(status->msg));
  1871. nullz(status);
  1872. }
  1873. void upb_status_seterrf(upb_status *status, const char *fmt, ...) {
  1874. va_list args;
  1875. va_start(args, fmt);
  1876. upb_status_vseterrf(status, fmt, args);
  1877. va_end(args);
  1878. }
  1879. void upb_status_vseterrf(upb_status *status, const char *fmt, va_list args) {
  1880. if (!status) return;
  1881. status->ok = false;
  1882. _upb_vsnprintf(status->msg, sizeof(status->msg), fmt, args);
  1883. nullz(status);
  1884. }
  1885. /* upb_alloc ******************************************************************/
  1886. static void *upb_global_allocfunc(upb_alloc *alloc, void *ptr, size_t oldsize,
  1887. size_t size) {
  1888. UPB_UNUSED(alloc);
  1889. UPB_UNUSED(oldsize);
  1890. if (size == 0) {
  1891. free(ptr);
  1892. return NULL;
  1893. } else {
  1894. return realloc(ptr, size);
  1895. }
  1896. }
  1897. upb_alloc upb_alloc_global = {&upb_global_allocfunc};
  1898. /* upb_arena ******************************************************************/
  1899. /* Be conservative and choose 16 in case anyone is using SSE. */
  1900. static const size_t maxalign = 16;
  1901. static size_t align_up_max(size_t size) {
  1902. return ((size + maxalign - 1) / maxalign) * maxalign;
  1903. }
  1904. struct upb_arena {
  1905. /* We implement the allocator interface.
  1906. * This must be the first member of upb_arena! */
  1907. upb_alloc alloc;
  1908. /* Allocator to allocate arena blocks. We are responsible for freeing these
  1909. * when we are destroyed. */
  1910. upb_alloc *block_alloc;
  1911. size_t bytes_allocated;
  1912. size_t next_block_size;
  1913. size_t max_block_size;
  1914. /* Linked list of blocks. Points to an arena_block, defined in env.c */
  1915. void *block_head;
  1916. /* Cleanup entries. Pointer to a cleanup_ent, defined in env.c */
  1917. void *cleanup_head;
  1918. };
  1919. typedef struct mem_block {
  1920. struct mem_block *next;
  1921. size_t size;
  1922. size_t used;
  1923. bool owned;
  1924. /* Data follows. */
  1925. } mem_block;
  1926. typedef struct cleanup_ent {
  1927. struct cleanup_ent *next;
  1928. upb_cleanup_func *cleanup;
  1929. void *ud;
  1930. } cleanup_ent;
  1931. static void upb_arena_addblock(upb_arena *a, void *ptr, size_t size,
  1932. bool owned) {
  1933. mem_block *block = ptr;
  1934. block->next = a->block_head;
  1935. block->size = size;
  1936. block->used = align_up_max(sizeof(mem_block));
  1937. block->owned = owned;
  1938. a->block_head = block;
  1939. /* TODO(haberman): ASAN poison. */
  1940. }
  1941. static mem_block *upb_arena_allocblock(upb_arena *a, size_t size) {
  1942. size_t block_size = UPB_MAX(size, a->next_block_size) + sizeof(mem_block);
  1943. mem_block *block = upb_malloc(a->block_alloc, block_size);
  1944. if (!block) {
  1945. return NULL;
  1946. }
  1947. upb_arena_addblock(a, block, block_size, true);
  1948. a->next_block_size = UPB_MIN(block_size * 2, a->max_block_size);
  1949. return block;
  1950. }
  1951. static void *upb_arena_doalloc(upb_alloc *alloc, void *ptr, size_t oldsize,
  1952. size_t size) {
  1953. upb_arena *a = (upb_arena*)alloc; /* upb_alloc is initial member. */
  1954. mem_block *block = a->block_head;
  1955. void *ret;
  1956. if (size == 0) {
  1957. return NULL; /* We are an arena, don't need individual frees. */
  1958. }
  1959. size = align_up_max(size);
  1960. /* TODO(haberman): special-case if this is a realloc of the last alloc? */
  1961. if (!block || block->size - block->used < size) {
  1962. /* Slow path: have to allocate a new block. */
  1963. block = upb_arena_allocblock(a, size);
  1964. if (!block) {
  1965. return NULL; /* Out of memory. */
  1966. }
  1967. }
  1968. ret = (char*)block + block->used;
  1969. block->used += size;
  1970. if (oldsize > 0) {
  1971. memcpy(ret, ptr, oldsize); /* Preserve existing data. */
  1972. }
  1973. /* TODO(haberman): ASAN unpoison. */
  1974. a->bytes_allocated += size;
  1975. return ret;
  1976. }
  1977. /* Public Arena API ***********************************************************/
  1978. #define upb_alignof(type) offsetof (struct { char c; type member; }, member)
  1979. upb_arena *upb_arena_init(void *mem, size_t n, upb_alloc *alloc) {
  1980. const size_t first_block_overhead = sizeof(upb_arena) + sizeof(mem_block);
  1981. upb_arena *a;
  1982. bool owned = false;
  1983. /* Round block size down to alignof(*a) since we will allocate the arena
  1984. * itself at the end. */
  1985. n &= ~(upb_alignof(upb_arena) - 1);
  1986. if (n < first_block_overhead) {
  1987. /* We need to malloc the initial block. */
  1988. n = first_block_overhead + 256;
  1989. owned = true;
  1990. if (!alloc || !(mem = upb_malloc(alloc, n))) {
  1991. return NULL;
  1992. }
  1993. }
  1994. a = (void*)((char*)mem + n - sizeof(*a));
  1995. n -= sizeof(*a);
  1996. a->alloc.func = &upb_arena_doalloc;
  1997. a->block_alloc = &upb_alloc_global;
  1998. a->bytes_allocated = 0;
  1999. a->next_block_size = 256;
  2000. a->max_block_size = 16384;
  2001. a->cleanup_head = NULL;
  2002. a->block_head = NULL;
  2003. a->block_alloc = alloc;
  2004. upb_arena_addblock(a, mem, n, owned);
  2005. return a;
  2006. }
  2007. #undef upb_alignof
  2008. void upb_arena_free(upb_arena *a) {
  2009. cleanup_ent *ent = a->cleanup_head;
  2010. mem_block *block = a->block_head;
  2011. while (ent) {
  2012. ent->cleanup(ent->ud);
  2013. ent = ent->next;
  2014. }
  2015. /* Must do this after running cleanup functions, because this will delete
  2016. * the memory we store our cleanup entries in! */
  2017. while (block) {
  2018. /* Load first since we are deleting block. */
  2019. mem_block *next = block->next;
  2020. if (block->owned) {
  2021. upb_free(a->block_alloc, block);
  2022. }
  2023. block = next;
  2024. }
  2025. }
  2026. bool upb_arena_addcleanup(upb_arena *a, void *ud, upb_cleanup_func *func) {
  2027. cleanup_ent *ent = upb_malloc(&a->alloc, sizeof(cleanup_ent));
  2028. if (!ent) {
  2029. return false; /* Out of memory. */
  2030. }
  2031. ent->cleanup = func;
  2032. ent->ud = ud;
  2033. ent->next = a->cleanup_head;
  2034. a->cleanup_head = ent;
  2035. return true;
  2036. }
  2037. size_t upb_arena_bytesallocated(const upb_arena *a) {
  2038. return a->bytes_allocated;
  2039. }
  2040. /* This file was generated by upbc (the upb compiler) from the input
  2041. * file:
  2042. *
  2043. * google/protobuf/descriptor.proto
  2044. *
  2045. * Do not edit -- your changes will be discarded when the file is
  2046. * regenerated. */
  2047. #include <stddef.h>
  2048. static const upb_msglayout *const google_protobuf_FileDescriptorSet_submsgs[1] = {
  2049. &google_protobuf_FileDescriptorProto_msginit,
  2050. };
  2051. static const upb_msglayout_field google_protobuf_FileDescriptorSet__fields[1] = {
  2052. {1, UPB_SIZE(0, 0), 0, 0, 11, 3},
  2053. };
  2054. const upb_msglayout google_protobuf_FileDescriptorSet_msginit = {
  2055. &google_protobuf_FileDescriptorSet_submsgs[0],
  2056. &google_protobuf_FileDescriptorSet__fields[0],
  2057. UPB_SIZE(4, 8), 1, false,
  2058. };
  2059. static const upb_msglayout *const google_protobuf_FileDescriptorProto_submsgs[6] = {
  2060. &google_protobuf_DescriptorProto_msginit,
  2061. &google_protobuf_EnumDescriptorProto_msginit,
  2062. &google_protobuf_FieldDescriptorProto_msginit,
  2063. &google_protobuf_FileOptions_msginit,
  2064. &google_protobuf_ServiceDescriptorProto_msginit,
  2065. &google_protobuf_SourceCodeInfo_msginit,
  2066. };
  2067. static const upb_msglayout_field google_protobuf_FileDescriptorProto__fields[12] = {
  2068. {1, UPB_SIZE(4, 8), 1, 0, 9, 1},
  2069. {2, UPB_SIZE(12, 24), 2, 0, 9, 1},
  2070. {3, UPB_SIZE(36, 72), 0, 0, 9, 3},
  2071. {4, UPB_SIZE(40, 80), 0, 0, 11, 3},
  2072. {5, UPB_SIZE(44, 88), 0, 1, 11, 3},
  2073. {6, UPB_SIZE(48, 96), 0, 4, 11, 3},
  2074. {7, UPB_SIZE(52, 104), 0, 2, 11, 3},
  2075. {8, UPB_SIZE(28, 56), 4, 3, 11, 1},
  2076. {9, UPB_SIZE(32, 64), 5, 5, 11, 1},
  2077. {10, UPB_SIZE(56, 112), 0, 0, 5, 3},
  2078. {11, UPB_SIZE(60, 120), 0, 0, 5, 3},
  2079. {12, UPB_SIZE(20, 40), 3, 0, 9, 1},
  2080. };
  2081. const upb_msglayout google_protobuf_FileDescriptorProto_msginit = {
  2082. &google_protobuf_FileDescriptorProto_submsgs[0],
  2083. &google_protobuf_FileDescriptorProto__fields[0],
  2084. UPB_SIZE(64, 128), 12, false,
  2085. };
  2086. static const upb_msglayout *const google_protobuf_DescriptorProto_submsgs[8] = {
  2087. &google_protobuf_DescriptorProto_msginit,
  2088. &google_protobuf_DescriptorProto_ExtensionRange_msginit,
  2089. &google_protobuf_DescriptorProto_ReservedRange_msginit,
  2090. &google_protobuf_EnumDescriptorProto_msginit,
  2091. &google_protobuf_FieldDescriptorProto_msginit,
  2092. &google_protobuf_MessageOptions_msginit,
  2093. &google_protobuf_OneofDescriptorProto_msginit,
  2094. };
  2095. static const upb_msglayout_field google_protobuf_DescriptorProto__fields[10] = {
  2096. {1, UPB_SIZE(4, 8), 1, 0, 9, 1},
  2097. {2, UPB_SIZE(16, 32), 0, 4, 11, 3},
  2098. {3, UPB_SIZE(20, 40), 0, 0, 11, 3},
  2099. {4, UPB_SIZE(24, 48), 0, 3, 11, 3},
  2100. {5, UPB_SIZE(28, 56), 0, 1, 11, 3},
  2101. {6, UPB_SIZE(32, 64), 0, 4, 11, 3},
  2102. {7, UPB_SIZE(12, 24), 2, 5, 11, 1},
  2103. {8, UPB_SIZE(36, 72), 0, 6, 11, 3},
  2104. {9, UPB_SIZE(40, 80), 0, 2, 11, 3},
  2105. {10, UPB_SIZE(44, 88), 0, 0, 9, 3},
  2106. };
  2107. const upb_msglayout google_protobuf_DescriptorProto_msginit = {
  2108. &google_protobuf_DescriptorProto_submsgs[0],
  2109. &google_protobuf_DescriptorProto__fields[0],
  2110. UPB_SIZE(48, 96), 10, false,
  2111. };
  2112. static const upb_msglayout *const google_protobuf_DescriptorProto_ExtensionRange_submsgs[1] = {
  2113. &google_protobuf_ExtensionRangeOptions_msginit,
  2114. };
  2115. static const upb_msglayout_field google_protobuf_DescriptorProto_ExtensionRange__fields[3] = {
  2116. {1, UPB_SIZE(4, 4), 1, 0, 5, 1},
  2117. {2, UPB_SIZE(8, 8), 2, 0, 5, 1},
  2118. {3, UPB_SIZE(12, 16), 3, 0, 11, 1},
  2119. };
  2120. const upb_msglayout google_protobuf_DescriptorProto_ExtensionRange_msginit = {
  2121. &google_protobuf_DescriptorProto_ExtensionRange_submsgs[0],
  2122. &google_protobuf_DescriptorProto_ExtensionRange__fields[0],
  2123. UPB_SIZE(16, 24), 3, false,
  2124. };
  2125. static const upb_msglayout_field google_protobuf_DescriptorProto_ReservedRange__fields[2] = {
  2126. {1, UPB_SIZE(4, 4), 1, 0, 5, 1},
  2127. {2, UPB_SIZE(8, 8), 2, 0, 5, 1},
  2128. };
  2129. const upb_msglayout google_protobuf_DescriptorProto_ReservedRange_msginit = {
  2130. NULL,
  2131. &google_protobuf_DescriptorProto_ReservedRange__fields[0],
  2132. UPB_SIZE(12, 12), 2, false,
  2133. };
  2134. static const upb_msglayout *const google_protobuf_ExtensionRangeOptions_submsgs[1] = {
  2135. &google_protobuf_UninterpretedOption_msginit,
  2136. };
  2137. static const upb_msglayout_field google_protobuf_ExtensionRangeOptions__fields[1] = {
  2138. {999, UPB_SIZE(0, 0), 0, 0, 11, 3},
  2139. };
  2140. const upb_msglayout google_protobuf_ExtensionRangeOptions_msginit = {
  2141. &google_protobuf_ExtensionRangeOptions_submsgs[0],
  2142. &google_protobuf_ExtensionRangeOptions__fields[0],
  2143. UPB_SIZE(4, 8), 1, false,
  2144. };
  2145. static const upb_msglayout *const google_protobuf_FieldDescriptorProto_submsgs[1] = {
  2146. &google_protobuf_FieldOptions_msginit,
  2147. };
  2148. static const upb_msglayout_field google_protobuf_FieldDescriptorProto__fields[10] = {
  2149. {1, UPB_SIZE(32, 32), 5, 0, 9, 1},
  2150. {2, UPB_SIZE(40, 48), 6, 0, 9, 1},
  2151. {3, UPB_SIZE(24, 24), 3, 0, 5, 1},
  2152. {4, UPB_SIZE(8, 8), 1, 0, 14, 1},
  2153. {5, UPB_SIZE(16, 16), 2, 0, 14, 1},
  2154. {6, UPB_SIZE(48, 64), 7, 0, 9, 1},
  2155. {7, UPB_SIZE(56, 80), 8, 0, 9, 1},
  2156. {8, UPB_SIZE(72, 112), 10, 0, 11, 1},
  2157. {9, UPB_SIZE(28, 28), 4, 0, 5, 1},
  2158. {10, UPB_SIZE(64, 96), 9, 0, 9, 1},
  2159. };
  2160. const upb_msglayout google_protobuf_FieldDescriptorProto_msginit = {
  2161. &google_protobuf_FieldDescriptorProto_submsgs[0],
  2162. &google_protobuf_FieldDescriptorProto__fields[0],
  2163. UPB_SIZE(80, 128), 10, false,
  2164. };
  2165. static const upb_msglayout *const google_protobuf_OneofDescriptorProto_submsgs[1] = {
  2166. &google_protobuf_OneofOptions_msginit,
  2167. };
  2168. static const upb_msglayout_field google_protobuf_OneofDescriptorProto__fields[2] = {
  2169. {1, UPB_SIZE(4, 8), 1, 0, 9, 1},
  2170. {2, UPB_SIZE(12, 24), 2, 0, 11, 1},
  2171. };
  2172. const upb_msglayout google_protobuf_OneofDescriptorProto_msginit = {
  2173. &google_protobuf_OneofDescriptorProto_submsgs[0],
  2174. &google_protobuf_OneofDescriptorProto__fields[0],
  2175. UPB_SIZE(16, 32), 2, false,
  2176. };
  2177. static const upb_msglayout *const google_protobuf_EnumDescriptorProto_submsgs[3] = {
  2178. &google_protobuf_EnumDescriptorProto_EnumReservedRange_msginit,
  2179. &google_protobuf_EnumOptions_msginit,
  2180. &google_protobuf_EnumValueDescriptorProto_msginit,
  2181. };
  2182. static const upb_msglayout_field google_protobuf_EnumDescriptorProto__fields[5] = {
  2183. {1, UPB_SIZE(4, 8), 1, 0, 9, 1},
  2184. {2, UPB_SIZE(16, 32), 0, 2, 11, 3},
  2185. {3, UPB_SIZE(12, 24), 2, 1, 11, 1},
  2186. {4, UPB_SIZE(20, 40), 0, 0, 11, 3},
  2187. {5, UPB_SIZE(24, 48), 0, 0, 9, 3},
  2188. };
  2189. const upb_msglayout google_protobuf_EnumDescriptorProto_msginit = {
  2190. &google_protobuf_EnumDescriptorProto_submsgs[0],
  2191. &google_protobuf_EnumDescriptorProto__fields[0],
  2192. UPB_SIZE(32, 64), 5, false,
  2193. };
  2194. static const upb_msglayout_field google_protobuf_EnumDescriptorProto_EnumReservedRange__fields[2] = {
  2195. {1, UPB_SIZE(4, 4), 1, 0, 5, 1},
  2196. {2, UPB_SIZE(8, 8), 2, 0, 5, 1},
  2197. };
  2198. const upb_msglayout google_protobuf_EnumDescriptorProto_EnumReservedRange_msginit = {
  2199. NULL,
  2200. &google_protobuf_EnumDescriptorProto_EnumReservedRange__fields[0],
  2201. UPB_SIZE(12, 12), 2, false,
  2202. };
  2203. static const upb_msglayout *const google_protobuf_EnumValueDescriptorProto_submsgs[1] = {
  2204. &google_protobuf_EnumValueOptions_msginit,
  2205. };
  2206. static const upb_msglayout_field google_protobuf_EnumValueDescriptorProto__fields[3] = {
  2207. {1, UPB_SIZE(8, 8), 2, 0, 9, 1},
  2208. {2, UPB_SIZE(4, 4), 1, 0, 5, 1},
  2209. {3, UPB_SIZE(16, 24), 3, 0, 11, 1},
  2210. };
  2211. const upb_msglayout google_protobuf_EnumValueDescriptorProto_msginit = {
  2212. &google_protobuf_EnumValueDescriptorProto_submsgs[0],
  2213. &google_protobuf_EnumValueDescriptorProto__fields[0],
  2214. UPB_SIZE(24, 32), 3, false,
  2215. };
  2216. static const upb_msglayout *const google_protobuf_ServiceDescriptorProto_submsgs[2] = {
  2217. &google_protobuf_MethodDescriptorProto_msginit,
  2218. &google_protobuf_ServiceOptions_msginit,
  2219. };
  2220. static const upb_msglayout_field google_protobuf_ServiceDescriptorProto__fields[3] = {
  2221. {1, UPB_SIZE(4, 8), 1, 0, 9, 1},
  2222. {2, UPB_SIZE(16, 32), 0, 0, 11, 3},
  2223. {3, UPB_SIZE(12, 24), 2, 1, 11, 1},
  2224. };
  2225. const upb_msglayout google_protobuf_ServiceDescriptorProto_msginit = {
  2226. &google_protobuf_ServiceDescriptorProto_submsgs[0],
  2227. &google_protobuf_ServiceDescriptorProto__fields[0],
  2228. UPB_SIZE(24, 48), 3, false,
  2229. };
  2230. static const upb_msglayout *const google_protobuf_MethodDescriptorProto_submsgs[1] = {
  2231. &google_protobuf_MethodOptions_msginit,
  2232. };
  2233. static const upb_msglayout_field google_protobuf_MethodDescriptorProto__fields[6] = {
  2234. {1, UPB_SIZE(4, 8), 3, 0, 9, 1},
  2235. {2, UPB_SIZE(12, 24), 4, 0, 9, 1},
  2236. {3, UPB_SIZE(20, 40), 5, 0, 9, 1},
  2237. {4, UPB_SIZE(28, 56), 6, 0, 11, 1},
  2238. {5, UPB_SIZE(1, 1), 1, 0, 8, 1},
  2239. {6, UPB_SIZE(2, 2), 2, 0, 8, 1},
  2240. };
  2241. const upb_msglayout google_protobuf_MethodDescriptorProto_msginit = {
  2242. &google_protobuf_MethodDescriptorProto_submsgs[0],
  2243. &google_protobuf_MethodDescriptorProto__fields[0],
  2244. UPB_SIZE(32, 64), 6, false,
  2245. };
  2246. static const upb_msglayout *const google_protobuf_FileOptions_submsgs[1] = {
  2247. &google_protobuf_UninterpretedOption_msginit,
  2248. };
  2249. static const upb_msglayout_field google_protobuf_FileOptions__fields[21] = {
  2250. {1, UPB_SIZE(28, 32), 11, 0, 9, 1},
  2251. {8, UPB_SIZE(36, 48), 12, 0, 9, 1},
  2252. {9, UPB_SIZE(8, 8), 1, 0, 14, 1},
  2253. {10, UPB_SIZE(16, 16), 2, 0, 8, 1},
  2254. {11, UPB_SIZE(44, 64), 13, 0, 9, 1},
  2255. {16, UPB_SIZE(17, 17), 3, 0, 8, 1},
  2256. {17, UPB_SIZE(18, 18), 4, 0, 8, 1},
  2257. {18, UPB_SIZE(19, 19), 5, 0, 8, 1},
  2258. {20, UPB_SIZE(20, 20), 6, 0, 8, 1},
  2259. {23, UPB_SIZE(21, 21), 7, 0, 8, 1},
  2260. {27, UPB_SIZE(22, 22), 8, 0, 8, 1},
  2261. {31, UPB_SIZE(23, 23), 9, 0, 8, 1},
  2262. {36, UPB_SIZE(52, 80), 14, 0, 9, 1},
  2263. {37, UPB_SIZE(60, 96), 15, 0, 9, 1},
  2264. {39, UPB_SIZE(68, 112), 16, 0, 9, 1},
  2265. {40, UPB_SIZE(76, 128), 17, 0, 9, 1},
  2266. {41, UPB_SIZE(84, 144), 18, 0, 9, 1},
  2267. {42, UPB_SIZE(24, 24), 10, 0, 8, 1},
  2268. {44, UPB_SIZE(92, 160), 19, 0, 9, 1},
  2269. {45, UPB_SIZE(100, 176), 20, 0, 9, 1},
  2270. {999, UPB_SIZE(108, 192), 0, 0, 11, 3},
  2271. };
  2272. const upb_msglayout google_protobuf_FileOptions_msginit = {
  2273. &google_protobuf_FileOptions_submsgs[0],
  2274. &google_protobuf_FileOptions__fields[0],
  2275. UPB_SIZE(112, 208), 21, false,
  2276. };
  2277. static const upb_msglayout *const google_protobuf_MessageOptions_submsgs[1] = {
  2278. &google_protobuf_UninterpretedOption_msginit,
  2279. };
  2280. static const upb_msglayout_field google_protobuf_MessageOptions__fields[5] = {
  2281. {1, UPB_SIZE(1, 1), 1, 0, 8, 1},
  2282. {2, UPB_SIZE(2, 2), 2, 0, 8, 1},
  2283. {3, UPB_SIZE(3, 3), 3, 0, 8, 1},
  2284. {7, UPB_SIZE(4, 4), 4, 0, 8, 1},
  2285. {999, UPB_SIZE(8, 8), 0, 0, 11, 3},
  2286. };
  2287. const upb_msglayout google_protobuf_MessageOptions_msginit = {
  2288. &google_protobuf_MessageOptions_submsgs[0],
  2289. &google_protobuf_MessageOptions__fields[0],
  2290. UPB_SIZE(12, 16), 5, false,
  2291. };
  2292. static const upb_msglayout *const google_protobuf_FieldOptions_submsgs[1] = {
  2293. &google_protobuf_UninterpretedOption_msginit,
  2294. };
  2295. static const upb_msglayout_field google_protobuf_FieldOptions__fields[7] = {
  2296. {1, UPB_SIZE(8, 8), 1, 0, 14, 1},
  2297. {2, UPB_SIZE(24, 24), 3, 0, 8, 1},
  2298. {3, UPB_SIZE(25, 25), 4, 0, 8, 1},
  2299. {5, UPB_SIZE(26, 26), 5, 0, 8, 1},
  2300. {6, UPB_SIZE(16, 16), 2, 0, 14, 1},
  2301. {10, UPB_SIZE(27, 27), 6, 0, 8, 1},
  2302. {999, UPB_SIZE(28, 32), 0, 0, 11, 3},
  2303. };
  2304. const upb_msglayout google_protobuf_FieldOptions_msginit = {
  2305. &google_protobuf_FieldOptions_submsgs[0],
  2306. &google_protobuf_FieldOptions__fields[0],
  2307. UPB_SIZE(32, 40), 7, false,
  2308. };
  2309. static const upb_msglayout *const google_protobuf_OneofOptions_submsgs[1] = {
  2310. &google_protobuf_UninterpretedOption_msginit,
  2311. };
  2312. static const upb_msglayout_field google_protobuf_OneofOptions__fields[1] = {
  2313. {999, UPB_SIZE(0, 0), 0, 0, 11, 3},
  2314. };
  2315. const upb_msglayout google_protobuf_OneofOptions_msginit = {
  2316. &google_protobuf_OneofOptions_submsgs[0],
  2317. &google_protobuf_OneofOptions__fields[0],
  2318. UPB_SIZE(4, 8), 1, false,
  2319. };
  2320. static const upb_msglayout *const google_protobuf_EnumOptions_submsgs[1] = {
  2321. &google_protobuf_UninterpretedOption_msginit,
  2322. };
  2323. static const upb_msglayout_field google_protobuf_EnumOptions__fields[3] = {
  2324. {2, UPB_SIZE(1, 1), 1, 0, 8, 1},
  2325. {3, UPB_SIZE(2, 2), 2, 0, 8, 1},
  2326. {999, UPB_SIZE(4, 8), 0, 0, 11, 3},
  2327. };
  2328. const upb_msglayout google_protobuf_EnumOptions_msginit = {
  2329. &google_protobuf_EnumOptions_submsgs[0],
  2330. &google_protobuf_EnumOptions__fields[0],
  2331. UPB_SIZE(8, 16), 3, false,
  2332. };
  2333. static const upb_msglayout *const google_protobuf_EnumValueOptions_submsgs[1] = {
  2334. &google_protobuf_UninterpretedOption_msginit,
  2335. };
  2336. static const upb_msglayout_field google_protobuf_EnumValueOptions__fields[2] = {
  2337. {1, UPB_SIZE(1, 1), 1, 0, 8, 1},
  2338. {999, UPB_SIZE(4, 8), 0, 0, 11, 3},
  2339. };
  2340. const upb_msglayout google_protobuf_EnumValueOptions_msginit = {
  2341. &google_protobuf_EnumValueOptions_submsgs[0],
  2342. &google_protobuf_EnumValueOptions__fields[0],
  2343. UPB_SIZE(8, 16), 2, false,
  2344. };
  2345. static const upb_msglayout *const google_protobuf_ServiceOptions_submsgs[1] = {
  2346. &google_protobuf_UninterpretedOption_msginit,
  2347. };
  2348. static const upb_msglayout_field google_protobuf_ServiceOptions__fields[2] = {
  2349. {33, UPB_SIZE(1, 1), 1, 0, 8, 1},
  2350. {999, UPB_SIZE(4, 8), 0, 0, 11, 3},
  2351. };
  2352. const upb_msglayout google_protobuf_ServiceOptions_msginit = {
  2353. &google_protobuf_ServiceOptions_submsgs[0],
  2354. &google_protobuf_ServiceOptions__fields[0],
  2355. UPB_SIZE(8, 16), 2, false,
  2356. };
  2357. static const upb_msglayout *const google_protobuf_MethodOptions_submsgs[1] = {
  2358. &google_protobuf_UninterpretedOption_msginit,
  2359. };
  2360. static const upb_msglayout_field google_protobuf_MethodOptions__fields[3] = {
  2361. {33, UPB_SIZE(16, 16), 2, 0, 8, 1},
  2362. {34, UPB_SIZE(8, 8), 1, 0, 14, 1},
  2363. {999, UPB_SIZE(20, 24), 0, 0, 11, 3},
  2364. };
  2365. const upb_msglayout google_protobuf_MethodOptions_msginit = {
  2366. &google_protobuf_MethodOptions_submsgs[0],
  2367. &google_protobuf_MethodOptions__fields[0],
  2368. UPB_SIZE(24, 32), 3, false,
  2369. };
  2370. static const upb_msglayout *const google_protobuf_UninterpretedOption_submsgs[1] = {
  2371. &google_protobuf_UninterpretedOption_NamePart_msginit,
  2372. };
  2373. static const upb_msglayout_field google_protobuf_UninterpretedOption__fields[7] = {
  2374. {2, UPB_SIZE(56, 80), 0, 0, 11, 3},
  2375. {3, UPB_SIZE(32, 32), 4, 0, 9, 1},
  2376. {4, UPB_SIZE(8, 8), 1, 0, 4, 1},
  2377. {5, UPB_SIZE(16, 16), 2, 0, 3, 1},
  2378. {6, UPB_SIZE(24, 24), 3, 0, 1, 1},
  2379. {7, UPB_SIZE(40, 48), 5, 0, 12, 1},
  2380. {8, UPB_SIZE(48, 64), 6, 0, 9, 1},
  2381. };
  2382. const upb_msglayout google_protobuf_UninterpretedOption_msginit = {
  2383. &google_protobuf_UninterpretedOption_submsgs[0],
  2384. &google_protobuf_UninterpretedOption__fields[0],
  2385. UPB_SIZE(64, 96), 7, false,
  2386. };
  2387. static const upb_msglayout_field google_protobuf_UninterpretedOption_NamePart__fields[2] = {
  2388. {1, UPB_SIZE(4, 8), 2, 0, 9, 2},
  2389. {2, UPB_SIZE(1, 1), 1, 0, 8, 2},
  2390. };
  2391. const upb_msglayout google_protobuf_UninterpretedOption_NamePart_msginit = {
  2392. NULL,
  2393. &google_protobuf_UninterpretedOption_NamePart__fields[0],
  2394. UPB_SIZE(16, 32), 2, false,
  2395. };
  2396. static const upb_msglayout *const google_protobuf_SourceCodeInfo_submsgs[1] = {
  2397. &google_protobuf_SourceCodeInfo_Location_msginit,
  2398. };
  2399. static const upb_msglayout_field google_protobuf_SourceCodeInfo__fields[1] = {
  2400. {1, UPB_SIZE(0, 0), 0, 0, 11, 3},
  2401. };
  2402. const upb_msglayout google_protobuf_SourceCodeInfo_msginit = {
  2403. &google_protobuf_SourceCodeInfo_submsgs[0],
  2404. &google_protobuf_SourceCodeInfo__fields[0],
  2405. UPB_SIZE(4, 8), 1, false,
  2406. };
  2407. static const upb_msglayout_field google_protobuf_SourceCodeInfo_Location__fields[5] = {
  2408. {1, UPB_SIZE(20, 40), 0, 0, 5, 3},
  2409. {2, UPB_SIZE(24, 48), 0, 0, 5, 3},
  2410. {3, UPB_SIZE(4, 8), 1, 0, 9, 1},
  2411. {4, UPB_SIZE(12, 24), 2, 0, 9, 1},
  2412. {6, UPB_SIZE(28, 56), 0, 0, 9, 3},
  2413. };
  2414. const upb_msglayout google_protobuf_SourceCodeInfo_Location_msginit = {
  2415. NULL,
  2416. &google_protobuf_SourceCodeInfo_Location__fields[0],
  2417. UPB_SIZE(32, 64), 5, false,
  2418. };
  2419. static const upb_msglayout *const google_protobuf_GeneratedCodeInfo_submsgs[1] = {
  2420. &google_protobuf_GeneratedCodeInfo_Annotation_msginit,
  2421. };
  2422. static const upb_msglayout_field google_protobuf_GeneratedCodeInfo__fields[1] = {
  2423. {1, UPB_SIZE(0, 0), 0, 0, 11, 3},
  2424. };
  2425. const upb_msglayout google_protobuf_GeneratedCodeInfo_msginit = {
  2426. &google_protobuf_GeneratedCodeInfo_submsgs[0],
  2427. &google_protobuf_GeneratedCodeInfo__fields[0],
  2428. UPB_SIZE(4, 8), 1, false,
  2429. };
  2430. static const upb_msglayout_field google_protobuf_GeneratedCodeInfo_Annotation__fields[4] = {
  2431. {1, UPB_SIZE(20, 32), 0, 0, 5, 3},
  2432. {2, UPB_SIZE(12, 16), 3, 0, 9, 1},
  2433. {3, UPB_SIZE(4, 4), 1, 0, 5, 1},
  2434. {4, UPB_SIZE(8, 8), 2, 0, 5, 1},
  2435. };
  2436. const upb_msglayout google_protobuf_GeneratedCodeInfo_Annotation_msginit = {
  2437. NULL,
  2438. &google_protobuf_GeneratedCodeInfo_Annotation__fields[0],
  2439. UPB_SIZE(24, 48), 4, false,
  2440. };
  2441. #include <ctype.h>
  2442. #include <errno.h>
  2443. #include <stdlib.h>
  2444. #include <string.h>
  2445. typedef struct {
  2446. size_t len;
  2447. char str[1]; /* Null-terminated string data follows. */
  2448. } str_t;
  2449. static str_t *newstr(upb_alloc *alloc, const char *data, size_t len) {
  2450. str_t *ret = upb_malloc(alloc, sizeof(*ret) + len);
  2451. if (!ret) return NULL;
  2452. ret->len = len;
  2453. memcpy(ret->str, data, len);
  2454. ret->str[len] = '\0';
  2455. return ret;
  2456. }
  2457. struct upb_fielddef {
  2458. const upb_filedef *file;
  2459. const upb_msgdef *msgdef;
  2460. const char *full_name;
  2461. union {
  2462. int64_t sint;
  2463. uint64_t uint;
  2464. double dbl;
  2465. float flt;
  2466. bool boolean;
  2467. str_t *str;
  2468. } defaultval;
  2469. const upb_oneofdef *oneof;
  2470. union {
  2471. const upb_msgdef *msgdef;
  2472. const upb_enumdef *enumdef;
  2473. const google_protobuf_FieldDescriptorProto *unresolved;
  2474. } sub;
  2475. uint32_t number_;
  2476. uint32_t index_;
  2477. uint32_t selector_base; /* Used to index into a upb::Handlers table. */
  2478. bool is_extension_;
  2479. bool lazy_;
  2480. bool packed_;
  2481. upb_descriptortype_t type_;
  2482. upb_label_t label_;
  2483. };
  2484. struct upb_msgdef {
  2485. const upb_filedef *file;
  2486. const char *full_name;
  2487. uint32_t selector_count;
  2488. uint32_t submsg_field_count;
  2489. /* Tables for looking up fields by number and name. */
  2490. upb_inttable itof;
  2491. upb_strtable ntof;
  2492. const upb_fielddef *fields;
  2493. const upb_oneofdef *oneofs;
  2494. int field_count;
  2495. int oneof_count;
  2496. /* Is this a map-entry message? */
  2497. bool map_entry;
  2498. upb_wellknowntype_t well_known_type;
  2499. /* TODO(haberman): proper extension ranges (there can be multiple). */
  2500. };
  2501. struct upb_enumdef {
  2502. const upb_filedef *file;
  2503. const char *full_name;
  2504. upb_strtable ntoi;
  2505. upb_inttable iton;
  2506. int32_t defaultval;
  2507. };
  2508. struct upb_oneofdef {
  2509. const upb_msgdef *parent;
  2510. const char *full_name;
  2511. uint32_t index;
  2512. upb_strtable ntof;
  2513. upb_inttable itof;
  2514. };
  2515. struct upb_filedef {
  2516. const char *name;
  2517. const char *package;
  2518. const char *phpprefix;
  2519. const char *phpnamespace;
  2520. upb_syntax_t syntax;
  2521. const upb_filedef **deps;
  2522. const upb_msgdef *msgs;
  2523. const upb_enumdef *enums;
  2524. const upb_fielddef *exts;
  2525. int dep_count;
  2526. int msg_count;
  2527. int enum_count;
  2528. int ext_count;
  2529. };
  2530. struct upb_symtab {
  2531. upb_arena *arena;
  2532. upb_strtable syms; /* full_name -> packed def ptr */
  2533. upb_strtable files; /* file_name -> upb_filedef* */
  2534. };
  2535. /* Inside a symtab we store tagged pointers to specific def types. */
  2536. typedef enum {
  2537. UPB_DEFTYPE_MSG = 0,
  2538. UPB_DEFTYPE_ENUM = 1,
  2539. UPB_DEFTYPE_FIELD = 2,
  2540. UPB_DEFTYPE_ONEOF = 3
  2541. } upb_deftype_t;
  2542. static const void *unpack_def(upb_value v, upb_deftype_t type) {
  2543. uintptr_t num = (uintptr_t)upb_value_getconstptr(v);
  2544. return (num & 3) == type ? (const void*)(num & ~3) : NULL;
  2545. }
  2546. static upb_value pack_def(const void *ptr, upb_deftype_t type) {
  2547. uintptr_t num = (uintptr_t)ptr | type;
  2548. return upb_value_constptr((const void*)num);
  2549. }
  2550. /* isalpha() etc. from <ctype.h> are locale-dependent, which we don't want. */
  2551. static bool upb_isbetween(char c, char low, char high) {
  2552. return c >= low && c <= high;
  2553. }
  2554. static bool upb_isletter(char c) {
  2555. return upb_isbetween(c, 'A', 'Z') || upb_isbetween(c, 'a', 'z') || c == '_';
  2556. }
  2557. static bool upb_isalphanum(char c) {
  2558. return upb_isletter(c) || upb_isbetween(c, '0', '9');
  2559. }
  2560. static bool upb_isident(upb_strview name, bool full, upb_status *s) {
  2561. const char *str = name.data;
  2562. size_t len = name.size;
  2563. bool start = true;
  2564. size_t i;
  2565. for (i = 0; i < len; i++) {
  2566. char c = str[i];
  2567. if (c == '.') {
  2568. if (start || !full) {
  2569. upb_status_seterrf(s, "invalid name: unexpected '.' (%s)", str);
  2570. return false;
  2571. }
  2572. start = true;
  2573. } else if (start) {
  2574. if (!upb_isletter(c)) {
  2575. upb_status_seterrf(
  2576. s, "invalid name: path components must start with a letter (%s)",
  2577. str);
  2578. return false;
  2579. }
  2580. start = false;
  2581. } else {
  2582. if (!upb_isalphanum(c)) {
  2583. upb_status_seterrf(s, "invalid name: non-alphanumeric character (%s)",
  2584. str);
  2585. return false;
  2586. }
  2587. }
  2588. }
  2589. return !start;
  2590. }
  2591. static const char *shortdefname(const char *fullname) {
  2592. const char *p;
  2593. if (fullname == NULL) {
  2594. return NULL;
  2595. } else if ((p = strrchr(fullname, '.')) == NULL) {
  2596. /* No '.' in the name, return the full string. */
  2597. return fullname;
  2598. } else {
  2599. /* Return one past the last '.'. */
  2600. return p + 1;
  2601. }
  2602. }
  2603. /* All submessage fields are lower than all other fields.
  2604. * Secondly, fields are increasing in order. */
  2605. uint32_t field_rank(const upb_fielddef *f) {
  2606. uint32_t ret = upb_fielddef_number(f);
  2607. const uint32_t high_bit = 1 << 30;
  2608. UPB_ASSERT(ret < high_bit);
  2609. if (!upb_fielddef_issubmsg(f))
  2610. ret |= high_bit;
  2611. return ret;
  2612. }
  2613. int cmp_fields(const void *p1, const void *p2) {
  2614. const upb_fielddef *f1 = *(upb_fielddef*const*)p1;
  2615. const upb_fielddef *f2 = *(upb_fielddef*const*)p2;
  2616. return field_rank(f1) - field_rank(f2);
  2617. }
  2618. /* A few implementation details of handlers. We put these here to avoid
  2619. * a def -> handlers dependency. */
  2620. #define UPB_STATIC_SELECTOR_COUNT 3 /* Warning: also in upb/handlers.h. */
  2621. static uint32_t upb_handlers_selectorbaseoffset(const upb_fielddef *f) {
  2622. return upb_fielddef_isseq(f) ? 2 : 0;
  2623. }
  2624. static uint32_t upb_handlers_selectorcount(const upb_fielddef *f) {
  2625. uint32_t ret = 1;
  2626. if (upb_fielddef_isseq(f)) ret += 2; /* STARTSEQ/ENDSEQ */
  2627. if (upb_fielddef_isstring(f)) ret += 2; /* [STRING]/STARTSTR/ENDSTR */
  2628. if (upb_fielddef_issubmsg(f)) {
  2629. /* ENDSUBMSG (STARTSUBMSG is at table beginning) */
  2630. ret += 0;
  2631. if (upb_fielddef_lazy(f)) {
  2632. /* STARTSTR/ENDSTR/STRING (for lazy) */
  2633. ret += 3;
  2634. }
  2635. }
  2636. return ret;
  2637. }
  2638. static bool assign_msg_indices(upb_msgdef *m, upb_status *s) {
  2639. /* Sort fields. upb internally relies on UPB_TYPE_MESSAGE fields having the
  2640. * lowest indexes, but we do not publicly guarantee this. */
  2641. upb_msg_field_iter j;
  2642. upb_msg_oneof_iter k;
  2643. int i;
  2644. uint32_t selector;
  2645. int n = upb_msgdef_numfields(m);
  2646. upb_fielddef **fields;
  2647. if (n == 0) {
  2648. m->selector_count = UPB_STATIC_SELECTOR_COUNT;
  2649. m->submsg_field_count = 0;
  2650. return true;
  2651. }
  2652. fields = upb_gmalloc(n * sizeof(*fields));
  2653. if (!fields) {
  2654. upb_status_setoom(s);
  2655. return false;
  2656. }
  2657. m->submsg_field_count = 0;
  2658. for(i = 0, upb_msg_field_begin(&j, m);
  2659. !upb_msg_field_done(&j);
  2660. upb_msg_field_next(&j), i++) {
  2661. upb_fielddef *f = upb_msg_iter_field(&j);
  2662. UPB_ASSERT(f->msgdef == m);
  2663. if (upb_fielddef_issubmsg(f)) {
  2664. m->submsg_field_count++;
  2665. }
  2666. fields[i] = f;
  2667. }
  2668. qsort(fields, n, sizeof(*fields), cmp_fields);
  2669. selector = UPB_STATIC_SELECTOR_COUNT + m->submsg_field_count;
  2670. for (i = 0; i < n; i++) {
  2671. upb_fielddef *f = fields[i];
  2672. f->index_ = i;
  2673. f->selector_base = selector + upb_handlers_selectorbaseoffset(f);
  2674. selector += upb_handlers_selectorcount(f);
  2675. }
  2676. m->selector_count = selector;
  2677. for(upb_msg_oneof_begin(&k, m), i = 0;
  2678. !upb_msg_oneof_done(&k);
  2679. upb_msg_oneof_next(&k), i++) {
  2680. upb_oneofdef *o = (upb_oneofdef*)upb_msg_iter_oneof(&k);
  2681. o->index = i;
  2682. }
  2683. upb_gfree(fields);
  2684. return true;
  2685. }
  2686. static void assign_msg_wellknowntype(upb_msgdef *m) {
  2687. const char *name = upb_msgdef_fullname(m);
  2688. if (name == NULL) {
  2689. m->well_known_type = UPB_WELLKNOWN_UNSPECIFIED;
  2690. return;
  2691. }
  2692. if (!strcmp(name, "google.protobuf.Any")) {
  2693. m->well_known_type = UPB_WELLKNOWN_ANY;
  2694. } else if (!strcmp(name, "google.protobuf.FieldMask")) {
  2695. m->well_known_type = UPB_WELLKNOWN_FIELDMASK;
  2696. } else if (!strcmp(name, "google.protobuf.Duration")) {
  2697. m->well_known_type = UPB_WELLKNOWN_DURATION;
  2698. } else if (!strcmp(name, "google.protobuf.Timestamp")) {
  2699. m->well_known_type = UPB_WELLKNOWN_TIMESTAMP;
  2700. } else if (!strcmp(name, "google.protobuf.DoubleValue")) {
  2701. m->well_known_type = UPB_WELLKNOWN_DOUBLEVALUE;
  2702. } else if (!strcmp(name, "google.protobuf.FloatValue")) {
  2703. m->well_known_type = UPB_WELLKNOWN_FLOATVALUE;
  2704. } else if (!strcmp(name, "google.protobuf.Int64Value")) {
  2705. m->well_known_type = UPB_WELLKNOWN_INT64VALUE;
  2706. } else if (!strcmp(name, "google.protobuf.UInt64Value")) {
  2707. m->well_known_type = UPB_WELLKNOWN_UINT64VALUE;
  2708. } else if (!strcmp(name, "google.protobuf.Int32Value")) {
  2709. m->well_known_type = UPB_WELLKNOWN_INT32VALUE;
  2710. } else if (!strcmp(name, "google.protobuf.UInt32Value")) {
  2711. m->well_known_type = UPB_WELLKNOWN_UINT32VALUE;
  2712. } else if (!strcmp(name, "google.protobuf.BoolValue")) {
  2713. m->well_known_type = UPB_WELLKNOWN_BOOLVALUE;
  2714. } else if (!strcmp(name, "google.protobuf.StringValue")) {
  2715. m->well_known_type = UPB_WELLKNOWN_STRINGVALUE;
  2716. } else if (!strcmp(name, "google.protobuf.BytesValue")) {
  2717. m->well_known_type = UPB_WELLKNOWN_BYTESVALUE;
  2718. } else if (!strcmp(name, "google.protobuf.Value")) {
  2719. m->well_known_type = UPB_WELLKNOWN_VALUE;
  2720. } else if (!strcmp(name, "google.protobuf.ListValue")) {
  2721. m->well_known_type = UPB_WELLKNOWN_LISTVALUE;
  2722. } else if (!strcmp(name, "google.protobuf.Struct")) {
  2723. m->well_known_type = UPB_WELLKNOWN_STRUCT;
  2724. } else {
  2725. m->well_known_type = UPB_WELLKNOWN_UNSPECIFIED;
  2726. }
  2727. }
  2728. /* upb_enumdef ****************************************************************/
  2729. const char *upb_enumdef_fullname(const upb_enumdef *e) {
  2730. return e->full_name;
  2731. }
  2732. const char *upb_enumdef_name(const upb_enumdef *e) {
  2733. return shortdefname(e->full_name);
  2734. }
  2735. const upb_filedef *upb_enumdef_file(const upb_enumdef *e) {
  2736. return e->file;
  2737. }
  2738. int32_t upb_enumdef_default(const upb_enumdef *e) {
  2739. UPB_ASSERT(upb_enumdef_iton(e, e->defaultval));
  2740. return e->defaultval;
  2741. }
  2742. int upb_enumdef_numvals(const upb_enumdef *e) {
  2743. return upb_strtable_count(&e->ntoi);
  2744. }
  2745. void upb_enum_begin(upb_enum_iter *i, const upb_enumdef *e) {
  2746. /* We iterate over the ntoi table, to account for duplicate numbers. */
  2747. upb_strtable_begin(i, &e->ntoi);
  2748. }
  2749. void upb_enum_next(upb_enum_iter *iter) { upb_strtable_next(iter); }
  2750. bool upb_enum_done(upb_enum_iter *iter) { return upb_strtable_done(iter); }
  2751. bool upb_enumdef_ntoi(const upb_enumdef *def, const char *name,
  2752. size_t len, int32_t *num) {
  2753. upb_value v;
  2754. if (!upb_strtable_lookup2(&def->ntoi, name, len, &v)) {
  2755. return false;
  2756. }
  2757. if (num) *num = upb_value_getint32(v);
  2758. return true;
  2759. }
  2760. const char *upb_enumdef_iton(const upb_enumdef *def, int32_t num) {
  2761. upb_value v;
  2762. return upb_inttable_lookup32(&def->iton, num, &v) ?
  2763. upb_value_getcstr(v) : NULL;
  2764. }
  2765. const char *upb_enum_iter_name(upb_enum_iter *iter) {
  2766. return upb_strtable_iter_key(iter);
  2767. }
  2768. int32_t upb_enum_iter_number(upb_enum_iter *iter) {
  2769. return upb_value_getint32(upb_strtable_iter_value(iter));
  2770. }
  2771. /* upb_fielddef ***************************************************************/
  2772. const char *upb_fielddef_fullname(const upb_fielddef *f) {
  2773. return f->full_name;
  2774. }
  2775. upb_fieldtype_t upb_fielddef_type(const upb_fielddef *f) {
  2776. switch (f->type_) {
  2777. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  2778. return UPB_TYPE_DOUBLE;
  2779. case UPB_DESCRIPTOR_TYPE_FLOAT:
  2780. return UPB_TYPE_FLOAT;
  2781. case UPB_DESCRIPTOR_TYPE_INT64:
  2782. case UPB_DESCRIPTOR_TYPE_SINT64:
  2783. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  2784. return UPB_TYPE_INT64;
  2785. case UPB_DESCRIPTOR_TYPE_INT32:
  2786. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  2787. case UPB_DESCRIPTOR_TYPE_SINT32:
  2788. return UPB_TYPE_INT32;
  2789. case UPB_DESCRIPTOR_TYPE_UINT64:
  2790. case UPB_DESCRIPTOR_TYPE_FIXED64:
  2791. return UPB_TYPE_UINT64;
  2792. case UPB_DESCRIPTOR_TYPE_UINT32:
  2793. case UPB_DESCRIPTOR_TYPE_FIXED32:
  2794. return UPB_TYPE_UINT32;
  2795. case UPB_DESCRIPTOR_TYPE_ENUM:
  2796. return UPB_TYPE_ENUM;
  2797. case UPB_DESCRIPTOR_TYPE_BOOL:
  2798. return UPB_TYPE_BOOL;
  2799. case UPB_DESCRIPTOR_TYPE_STRING:
  2800. return UPB_TYPE_STRING;
  2801. case UPB_DESCRIPTOR_TYPE_BYTES:
  2802. return UPB_TYPE_BYTES;
  2803. case UPB_DESCRIPTOR_TYPE_GROUP:
  2804. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  2805. return UPB_TYPE_MESSAGE;
  2806. }
  2807. UPB_UNREACHABLE();
  2808. }
  2809. upb_descriptortype_t upb_fielddef_descriptortype(const upb_fielddef *f) {
  2810. return f->type_;
  2811. }
  2812. uint32_t upb_fielddef_index(const upb_fielddef *f) {
  2813. return f->index_;
  2814. }
  2815. upb_label_t upb_fielddef_label(const upb_fielddef *f) {
  2816. return f->label_;
  2817. }
  2818. uint32_t upb_fielddef_number(const upb_fielddef *f) {
  2819. return f->number_;
  2820. }
  2821. bool upb_fielddef_isextension(const upb_fielddef *f) {
  2822. return f->is_extension_;
  2823. }
  2824. bool upb_fielddef_lazy(const upb_fielddef *f) {
  2825. return f->lazy_;
  2826. }
  2827. bool upb_fielddef_packed(const upb_fielddef *f) {
  2828. return f->packed_;
  2829. }
  2830. const char *upb_fielddef_name(const upb_fielddef *f) {
  2831. return shortdefname(f->full_name);
  2832. }
  2833. uint32_t upb_fielddef_selectorbase(const upb_fielddef *f) {
  2834. return f->selector_base;
  2835. }
  2836. size_t upb_fielddef_getjsonname(const upb_fielddef *f, char *buf, size_t len) {
  2837. const char *name = upb_fielddef_name(f);
  2838. size_t src, dst = 0;
  2839. bool ucase_next = false;
  2840. #define WRITE(byte) \
  2841. ++dst; \
  2842. if (dst < len) buf[dst - 1] = byte; \
  2843. else if (dst == len) buf[dst - 1] = '\0'
  2844. if (!name) {
  2845. WRITE('\0');
  2846. return 0;
  2847. }
  2848. /* Implement the transformation as described in the spec:
  2849. * 1. upper case all letters after an underscore.
  2850. * 2. remove all underscores.
  2851. */
  2852. for (src = 0; name[src]; src++) {
  2853. if (name[src] == '_') {
  2854. ucase_next = true;
  2855. continue;
  2856. }
  2857. if (ucase_next) {
  2858. WRITE(toupper(name[src]));
  2859. ucase_next = false;
  2860. } else {
  2861. WRITE(name[src]);
  2862. }
  2863. }
  2864. WRITE('\0');
  2865. return dst;
  2866. #undef WRITE
  2867. }
  2868. const upb_msgdef *upb_fielddef_containingtype(const upb_fielddef *f) {
  2869. return f->msgdef;
  2870. }
  2871. const upb_oneofdef *upb_fielddef_containingoneof(const upb_fielddef *f) {
  2872. return f->oneof;
  2873. }
  2874. static void chkdefaulttype(const upb_fielddef *f, int ctype) {
  2875. UPB_UNUSED(f);
  2876. UPB_UNUSED(ctype);
  2877. }
  2878. int64_t upb_fielddef_defaultint64(const upb_fielddef *f) {
  2879. chkdefaulttype(f, UPB_TYPE_INT64);
  2880. return f->defaultval.sint;
  2881. }
  2882. int32_t upb_fielddef_defaultint32(const upb_fielddef *f) {
  2883. chkdefaulttype(f, UPB_TYPE_INT32);
  2884. return f->defaultval.sint;
  2885. }
  2886. uint64_t upb_fielddef_defaultuint64(const upb_fielddef *f) {
  2887. chkdefaulttype(f, UPB_TYPE_UINT64);
  2888. return f->defaultval.uint;
  2889. }
  2890. uint32_t upb_fielddef_defaultuint32(const upb_fielddef *f) {
  2891. chkdefaulttype(f, UPB_TYPE_UINT32);
  2892. return f->defaultval.uint;
  2893. }
  2894. bool upb_fielddef_defaultbool(const upb_fielddef *f) {
  2895. chkdefaulttype(f, UPB_TYPE_BOOL);
  2896. return f->defaultval.boolean;
  2897. }
  2898. float upb_fielddef_defaultfloat(const upb_fielddef *f) {
  2899. chkdefaulttype(f, UPB_TYPE_FLOAT);
  2900. return f->defaultval.flt;
  2901. }
  2902. double upb_fielddef_defaultdouble(const upb_fielddef *f) {
  2903. chkdefaulttype(f, UPB_TYPE_DOUBLE);
  2904. return f->defaultval.dbl;
  2905. }
  2906. const char *upb_fielddef_defaultstr(const upb_fielddef *f, size_t *len) {
  2907. str_t *str = f->defaultval.str;
  2908. UPB_ASSERT(upb_fielddef_type(f) == UPB_TYPE_STRING ||
  2909. upb_fielddef_type(f) == UPB_TYPE_BYTES ||
  2910. upb_fielddef_type(f) == UPB_TYPE_ENUM);
  2911. if (str) {
  2912. if (len) *len = str->len;
  2913. return str->str;
  2914. } else {
  2915. if (len) *len = 0;
  2916. return NULL;
  2917. }
  2918. }
  2919. const upb_msgdef *upb_fielddef_msgsubdef(const upb_fielddef *f) {
  2920. UPB_ASSERT(upb_fielddef_type(f) == UPB_TYPE_MESSAGE);
  2921. return f->sub.msgdef;
  2922. }
  2923. const upb_enumdef *upb_fielddef_enumsubdef(const upb_fielddef *f) {
  2924. UPB_ASSERT(upb_fielddef_type(f) == UPB_TYPE_ENUM);
  2925. return f->sub.enumdef;
  2926. }
  2927. bool upb_fielddef_issubmsg(const upb_fielddef *f) {
  2928. return upb_fielddef_type(f) == UPB_TYPE_MESSAGE;
  2929. }
  2930. bool upb_fielddef_isstring(const upb_fielddef *f) {
  2931. return upb_fielddef_type(f) == UPB_TYPE_STRING ||
  2932. upb_fielddef_type(f) == UPB_TYPE_BYTES;
  2933. }
  2934. bool upb_fielddef_isseq(const upb_fielddef *f) {
  2935. return upb_fielddef_label(f) == UPB_LABEL_REPEATED;
  2936. }
  2937. bool upb_fielddef_isprimitive(const upb_fielddef *f) {
  2938. return !upb_fielddef_isstring(f) && !upb_fielddef_issubmsg(f);
  2939. }
  2940. bool upb_fielddef_ismap(const upb_fielddef *f) {
  2941. return upb_fielddef_isseq(f) && upb_fielddef_issubmsg(f) &&
  2942. upb_msgdef_mapentry(upb_fielddef_msgsubdef(f));
  2943. }
  2944. bool upb_fielddef_hassubdef(const upb_fielddef *f) {
  2945. return upb_fielddef_issubmsg(f) || upb_fielddef_type(f) == UPB_TYPE_ENUM;
  2946. }
  2947. bool upb_fielddef_haspresence(const upb_fielddef *f) {
  2948. if (upb_fielddef_isseq(f)) return false;
  2949. if (upb_fielddef_issubmsg(f)) return true;
  2950. return f->file->syntax == UPB_SYNTAX_PROTO2;
  2951. }
  2952. static bool between(int32_t x, int32_t low, int32_t high) {
  2953. return x >= low && x <= high;
  2954. }
  2955. bool upb_fielddef_checklabel(int32_t label) { return between(label, 1, 3); }
  2956. bool upb_fielddef_checktype(int32_t type) { return between(type, 1, 11); }
  2957. bool upb_fielddef_checkintfmt(int32_t fmt) { return between(fmt, 1, 3); }
  2958. bool upb_fielddef_checkdescriptortype(int32_t type) {
  2959. return between(type, 1, 18);
  2960. }
  2961. /* upb_msgdef *****************************************************************/
  2962. const char *upb_msgdef_fullname(const upb_msgdef *m) {
  2963. return m->full_name;
  2964. }
  2965. const upb_filedef *upb_msgdef_file(const upb_msgdef *m) {
  2966. return m->file;
  2967. }
  2968. const char *upb_msgdef_name(const upb_msgdef *m) {
  2969. return shortdefname(m->full_name);
  2970. }
  2971. upb_syntax_t upb_msgdef_syntax(const upb_msgdef *m) {
  2972. return m->file->syntax;
  2973. }
  2974. size_t upb_msgdef_selectorcount(const upb_msgdef *m) {
  2975. return m->selector_count;
  2976. }
  2977. uint32_t upb_msgdef_submsgfieldcount(const upb_msgdef *m) {
  2978. return m->submsg_field_count;
  2979. }
  2980. const upb_fielddef *upb_msgdef_itof(const upb_msgdef *m, uint32_t i) {
  2981. upb_value val;
  2982. return upb_inttable_lookup32(&m->itof, i, &val) ?
  2983. upb_value_getconstptr(val) : NULL;
  2984. }
  2985. const upb_fielddef *upb_msgdef_ntof(const upb_msgdef *m, const char *name,
  2986. size_t len) {
  2987. upb_value val;
  2988. if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
  2989. return NULL;
  2990. }
  2991. return unpack_def(val, UPB_DEFTYPE_FIELD);
  2992. }
  2993. const upb_oneofdef *upb_msgdef_ntoo(const upb_msgdef *m, const char *name,
  2994. size_t len) {
  2995. upb_value val;
  2996. if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
  2997. return NULL;
  2998. }
  2999. return unpack_def(val, UPB_DEFTYPE_ONEOF);
  3000. }
  3001. bool upb_msgdef_lookupname(const upb_msgdef *m, const char *name, size_t len,
  3002. const upb_fielddef **f, const upb_oneofdef **o) {
  3003. upb_value val;
  3004. if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
  3005. return false;
  3006. }
  3007. *o = unpack_def(val, UPB_DEFTYPE_ONEOF);
  3008. *f = unpack_def(val, UPB_DEFTYPE_FIELD);
  3009. UPB_ASSERT((*o != NULL) ^ (*f != NULL)); /* Exactly one of the two should be set. */
  3010. return true;
  3011. }
  3012. int upb_msgdef_numfields(const upb_msgdef *m) {
  3013. /* The number table contains only fields. */
  3014. return upb_inttable_count(&m->itof);
  3015. }
  3016. int upb_msgdef_numoneofs(const upb_msgdef *m) {
  3017. /* The name table includes oneofs, and the number table does not. */
  3018. return upb_strtable_count(&m->ntof) - upb_inttable_count(&m->itof);
  3019. }
  3020. bool upb_msgdef_mapentry(const upb_msgdef *m) {
  3021. return m->map_entry;
  3022. }
  3023. upb_wellknowntype_t upb_msgdef_wellknowntype(const upb_msgdef *m) {
  3024. return m->well_known_type;
  3025. }
  3026. bool upb_msgdef_isnumberwrapper(const upb_msgdef *m) {
  3027. upb_wellknowntype_t type = upb_msgdef_wellknowntype(m);
  3028. return type >= UPB_WELLKNOWN_DOUBLEVALUE &&
  3029. type <= UPB_WELLKNOWN_UINT32VALUE;
  3030. }
  3031. void upb_msg_field_begin(upb_msg_field_iter *iter, const upb_msgdef *m) {
  3032. upb_inttable_begin(iter, &m->itof);
  3033. }
  3034. void upb_msg_field_next(upb_msg_field_iter *iter) { upb_inttable_next(iter); }
  3035. bool upb_msg_field_done(const upb_msg_field_iter *iter) {
  3036. return upb_inttable_done(iter);
  3037. }
  3038. upb_fielddef *upb_msg_iter_field(const upb_msg_field_iter *iter) {
  3039. return (upb_fielddef *)upb_value_getconstptr(upb_inttable_iter_value(iter));
  3040. }
  3041. void upb_msg_field_iter_setdone(upb_msg_field_iter *iter) {
  3042. upb_inttable_iter_setdone(iter);
  3043. }
  3044. bool upb_msg_field_iter_isequal(const upb_msg_field_iter * iter1,
  3045. const upb_msg_field_iter * iter2) {
  3046. return upb_inttable_iter_isequal(iter1, iter2);
  3047. }
  3048. void upb_msg_oneof_begin(upb_msg_oneof_iter *iter, const upb_msgdef *m) {
  3049. upb_strtable_begin(iter, &m->ntof);
  3050. /* We need to skip past any initial fields. */
  3051. while (!upb_strtable_done(iter) &&
  3052. !unpack_def(upb_strtable_iter_value(iter), UPB_DEFTYPE_ONEOF)) {
  3053. upb_strtable_next(iter);
  3054. }
  3055. }
  3056. void upb_msg_oneof_next(upb_msg_oneof_iter *iter) {
  3057. /* We need to skip past fields to return only oneofs. */
  3058. do {
  3059. upb_strtable_next(iter);
  3060. } while (!upb_strtable_done(iter) &&
  3061. !unpack_def(upb_strtable_iter_value(iter), UPB_DEFTYPE_ONEOF));
  3062. }
  3063. bool upb_msg_oneof_done(const upb_msg_oneof_iter *iter) {
  3064. return upb_strtable_done(iter);
  3065. }
  3066. const upb_oneofdef *upb_msg_iter_oneof(const upb_msg_oneof_iter *iter) {
  3067. return unpack_def(upb_strtable_iter_value(iter), UPB_DEFTYPE_ONEOF);
  3068. }
  3069. void upb_msg_oneof_iter_setdone(upb_msg_oneof_iter *iter) {
  3070. upb_strtable_iter_setdone(iter);
  3071. }
  3072. bool upb_msg_oneof_iter_isequal(const upb_msg_oneof_iter *iter1,
  3073. const upb_msg_oneof_iter *iter2) {
  3074. return upb_strtable_iter_isequal(iter1, iter2);
  3075. }
  3076. /* upb_oneofdef ***************************************************************/
  3077. const char *upb_oneofdef_name(const upb_oneofdef *o) {
  3078. return shortdefname(o->full_name);
  3079. }
  3080. const upb_msgdef *upb_oneofdef_containingtype(const upb_oneofdef *o) {
  3081. return o->parent;
  3082. }
  3083. int upb_oneofdef_numfields(const upb_oneofdef *o) {
  3084. return upb_strtable_count(&o->ntof);
  3085. }
  3086. uint32_t upb_oneofdef_index(const upb_oneofdef *o) {
  3087. return o->index;
  3088. }
  3089. const upb_fielddef *upb_oneofdef_ntof(const upb_oneofdef *o,
  3090. const char *name, size_t length) {
  3091. upb_value val;
  3092. return upb_strtable_lookup2(&o->ntof, name, length, &val) ?
  3093. upb_value_getptr(val) : NULL;
  3094. }
  3095. const upb_fielddef *upb_oneofdef_itof(const upb_oneofdef *o, uint32_t num) {
  3096. upb_value val;
  3097. return upb_inttable_lookup32(&o->itof, num, &val) ?
  3098. upb_value_getptr(val) : NULL;
  3099. }
  3100. void upb_oneof_begin(upb_oneof_iter *iter, const upb_oneofdef *o) {
  3101. upb_inttable_begin(iter, &o->itof);
  3102. }
  3103. void upb_oneof_next(upb_oneof_iter *iter) {
  3104. upb_inttable_next(iter);
  3105. }
  3106. bool upb_oneof_done(upb_oneof_iter *iter) {
  3107. return upb_inttable_done(iter);
  3108. }
  3109. upb_fielddef *upb_oneof_iter_field(const upb_oneof_iter *iter) {
  3110. return (upb_fielddef *)upb_value_getconstptr(upb_inttable_iter_value(iter));
  3111. }
  3112. void upb_oneof_iter_setdone(upb_oneof_iter *iter) {
  3113. upb_inttable_iter_setdone(iter);
  3114. }
  3115. /* Code to build defs from descriptor protos. *********************************/
  3116. /* There is a question of how much validation to do here. It will be difficult
  3117. * to perfectly match the amount of validation performed by proto2. But since
  3118. * this code is used to directly build defs from Ruby (for example) we do need
  3119. * to validate important constraints like uniqueness of names and numbers. */
  3120. #define CHK(x) if (!(x)) { return false; }
  3121. #define CHK_OOM(x) if (!(x)) { upb_status_setoom(ctx->status); return false; }
  3122. typedef struct {
  3123. const upb_symtab *symtab;
  3124. upb_filedef *file; /* File we are building. */
  3125. upb_alloc *alloc; /* Allocate defs here. */
  3126. upb_alloc *tmp; /* Alloc for addtab and any other tmp data. */
  3127. upb_strtable *addtab; /* full_name -> packed def ptr for new defs. */
  3128. upb_status *status; /* Record errors here. */
  3129. } symtab_addctx;
  3130. static char* strviewdup(const symtab_addctx *ctx, upb_strview view) {
  3131. return upb_strdup2(view.data, view.size, ctx->alloc);
  3132. }
  3133. static bool streql2(const char *a, size_t n, const char *b) {
  3134. return n == strlen(b) && memcmp(a, b, n) == 0;
  3135. }
  3136. static bool streql_view(upb_strview view, const char *b) {
  3137. return streql2(view.data, view.size, b);
  3138. }
  3139. static const char *makefullname(const symtab_addctx *ctx, const char *prefix,
  3140. upb_strview name) {
  3141. if (prefix) {
  3142. /* ret = prefix + '.' + name; */
  3143. size_t n = strlen(prefix);
  3144. char *ret = upb_malloc(ctx->alloc, n + name.size + 2);
  3145. CHK_OOM(ret);
  3146. strcpy(ret, prefix);
  3147. ret[n] = '.';
  3148. memcpy(&ret[n + 1], name.data, name.size);
  3149. ret[n + 1 + name.size] = '\0';
  3150. return ret;
  3151. } else {
  3152. return strviewdup(ctx, name);
  3153. }
  3154. }
  3155. static bool symtab_add(const symtab_addctx *ctx, const char *name,
  3156. upb_value v) {
  3157. upb_value tmp;
  3158. if (upb_strtable_lookup(ctx->addtab, name, &tmp) ||
  3159. upb_strtable_lookup(&ctx->symtab->syms, name, &tmp)) {
  3160. upb_status_seterrf(ctx->status, "duplicate symbol '%s'", name);
  3161. return false;
  3162. }
  3163. CHK_OOM(upb_strtable_insert3(ctx->addtab, name, strlen(name), v, ctx->tmp));
  3164. return true;
  3165. }
  3166. /* Given a symbol and the base symbol inside which it is defined, find the
  3167. * symbol's definition in t. */
  3168. static bool resolvename(const upb_strtable *t, const upb_fielddef *f,
  3169. const char *base, upb_strview sym,
  3170. upb_deftype_t type, upb_status *status,
  3171. const void **def) {
  3172. if(sym.size == 0) return NULL;
  3173. if(sym.data[0] == '.') {
  3174. /* Symbols starting with '.' are absolute, so we do a single lookup.
  3175. * Slice to omit the leading '.' */
  3176. upb_value v;
  3177. if (!upb_strtable_lookup2(t, sym.data + 1, sym.size - 1, &v)) {
  3178. return false;
  3179. }
  3180. *def = unpack_def(v, type);
  3181. if (!*def) {
  3182. upb_status_seterrf(status,
  3183. "type mismatch when resolving field %s, name %s",
  3184. f->full_name, sym.data);
  3185. return false;
  3186. }
  3187. return true;
  3188. } else {
  3189. /* Remove components from base until we find an entry or run out.
  3190. * TODO: This branch is totally broken, but currently not used. */
  3191. (void)base;
  3192. UPB_ASSERT(false);
  3193. return false;
  3194. }
  3195. }
  3196. const void *symtab_resolve(const symtab_addctx *ctx, const upb_fielddef *f,
  3197. const char *base, upb_strview sym,
  3198. upb_deftype_t type) {
  3199. const void *ret;
  3200. if (!resolvename(ctx->addtab, f, base, sym, type, ctx->status, &ret) &&
  3201. !resolvename(&ctx->symtab->syms, f, base, sym, type, ctx->status, &ret)) {
  3202. if (upb_ok(ctx->status)) {
  3203. upb_status_seterrf(ctx->status, "couldn't resolve name '%s'", sym.data);
  3204. }
  3205. return false;
  3206. }
  3207. return ret;
  3208. }
  3209. static bool create_oneofdef(
  3210. const symtab_addctx *ctx, upb_msgdef *m,
  3211. const google_protobuf_OneofDescriptorProto *oneof_proto) {
  3212. upb_oneofdef *o;
  3213. upb_strview name = google_protobuf_OneofDescriptorProto_name(oneof_proto);
  3214. upb_value v;
  3215. o = (upb_oneofdef*)&m->oneofs[m->oneof_count++];
  3216. o->parent = m;
  3217. o->full_name = makefullname(ctx, m->full_name, name);
  3218. v = pack_def(o, UPB_DEFTYPE_ONEOF);
  3219. CHK_OOM(symtab_add(ctx, o->full_name, v));
  3220. CHK_OOM(upb_strtable_insert3(&m->ntof, name.data, name.size, v, ctx->alloc));
  3221. CHK_OOM(upb_inttable_init2(&o->itof, UPB_CTYPE_CONSTPTR, ctx->alloc));
  3222. CHK_OOM(upb_strtable_init2(&o->ntof, UPB_CTYPE_CONSTPTR, ctx->alloc));
  3223. return true;
  3224. }
  3225. static bool parse_default(const symtab_addctx *ctx, const char *str, size_t len,
  3226. upb_fielddef *f) {
  3227. char *end;
  3228. char nullz[64];
  3229. errno = 0;
  3230. switch (upb_fielddef_type(f)) {
  3231. case UPB_TYPE_INT32:
  3232. case UPB_TYPE_INT64:
  3233. case UPB_TYPE_UINT32:
  3234. case UPB_TYPE_UINT64:
  3235. case UPB_TYPE_DOUBLE:
  3236. case UPB_TYPE_FLOAT:
  3237. /* Standard C number parsing functions expect null-terminated strings. */
  3238. if (len >= sizeof(nullz) - 1) {
  3239. return false;
  3240. }
  3241. memcpy(nullz, str, len);
  3242. nullz[len] = '\0';
  3243. str = nullz;
  3244. break;
  3245. default:
  3246. break;
  3247. }
  3248. switch (upb_fielddef_type(f)) {
  3249. case UPB_TYPE_INT32: {
  3250. long val = strtol(str, &end, 0);
  3251. CHK(val <= INT32_MAX && val >= INT32_MIN && errno != ERANGE && !*end);
  3252. f->defaultval.sint = val;
  3253. break;
  3254. }
  3255. case UPB_TYPE_ENUM: {
  3256. const upb_enumdef *e = f->sub.enumdef;
  3257. int32_t val;
  3258. CHK(upb_enumdef_ntoi(e, str, len, &val));
  3259. f->defaultval.sint = val;
  3260. break;
  3261. }
  3262. case UPB_TYPE_INT64: {
  3263. /* XXX: Need to write our own strtoll, since it's not available in c89. */
  3264. long long val = strtol(str, &end, 0);
  3265. CHK(val <= INT64_MAX && val >= INT64_MIN && errno != ERANGE && !*end);
  3266. f->defaultval.sint = val;
  3267. break;
  3268. }
  3269. case UPB_TYPE_UINT32: {
  3270. unsigned long val = strtoul(str, &end, 0);
  3271. CHK(val <= UINT32_MAX && errno != ERANGE && !*end);
  3272. f->defaultval.uint = val;
  3273. break;
  3274. }
  3275. case UPB_TYPE_UINT64: {
  3276. /* XXX: Need to write our own strtoull, since it's not available in c89. */
  3277. unsigned long long val = strtoul(str, &end, 0);
  3278. CHK(val <= UINT64_MAX && errno != ERANGE && !*end);
  3279. f->defaultval.uint = val;
  3280. break;
  3281. }
  3282. case UPB_TYPE_DOUBLE: {
  3283. double val = strtod(str, &end);
  3284. CHK(errno != ERANGE && !*end);
  3285. f->defaultval.dbl = val;
  3286. break;
  3287. }
  3288. case UPB_TYPE_FLOAT: {
  3289. /* XXX: Need to write our own strtof, since it's not available in c89. */
  3290. float val = strtod(str, &end);
  3291. CHK(errno != ERANGE && !*end);
  3292. f->defaultval.flt = val;
  3293. break;
  3294. }
  3295. case UPB_TYPE_BOOL: {
  3296. if (streql2(str, len, "false")) {
  3297. f->defaultval.boolean = false;
  3298. } else if (streql2(str, len, "true")) {
  3299. f->defaultval.boolean = true;
  3300. } else {
  3301. return false;
  3302. }
  3303. break;
  3304. }
  3305. case UPB_TYPE_STRING:
  3306. f->defaultval.str = newstr(ctx->alloc, str, len);
  3307. break;
  3308. case UPB_TYPE_BYTES:
  3309. /* XXX: need to interpret the C-escaped value. */
  3310. f->defaultval.str = newstr(ctx->alloc, str, len);
  3311. break;
  3312. case UPB_TYPE_MESSAGE:
  3313. /* Should not have a default value. */
  3314. return false;
  3315. }
  3316. return true;
  3317. }
  3318. static void set_default_default(const symtab_addctx *ctx, upb_fielddef *f) {
  3319. switch (upb_fielddef_type(f)) {
  3320. case UPB_TYPE_INT32:
  3321. case UPB_TYPE_INT64:
  3322. case UPB_TYPE_ENUM:
  3323. f->defaultval.sint = 0;
  3324. break;
  3325. case UPB_TYPE_UINT64:
  3326. case UPB_TYPE_UINT32:
  3327. f->defaultval.uint = 0;
  3328. break;
  3329. case UPB_TYPE_DOUBLE:
  3330. case UPB_TYPE_FLOAT:
  3331. f->defaultval.dbl = 0;
  3332. break;
  3333. case UPB_TYPE_STRING:
  3334. case UPB_TYPE_BYTES:
  3335. f->defaultval.str = newstr(ctx->alloc, NULL, 0);
  3336. break;
  3337. case UPB_TYPE_BOOL:
  3338. f->defaultval.boolean = false;
  3339. break;
  3340. case UPB_TYPE_MESSAGE:
  3341. break;
  3342. }
  3343. }
  3344. static bool create_fielddef(
  3345. const symtab_addctx *ctx, const char *prefix, upb_msgdef *m,
  3346. const google_protobuf_FieldDescriptorProto *field_proto) {
  3347. upb_alloc *alloc = ctx->alloc;
  3348. upb_fielddef *f;
  3349. const google_protobuf_FieldOptions *options;
  3350. upb_strview name;
  3351. const char *full_name;
  3352. const char *shortname;
  3353. uint32_t field_number;
  3354. if (!google_protobuf_FieldDescriptorProto_has_name(field_proto)) {
  3355. upb_status_seterrmsg(ctx->status, "field has no name");
  3356. return false;
  3357. }
  3358. name = google_protobuf_FieldDescriptorProto_name(field_proto);
  3359. CHK(upb_isident(name, false, ctx->status));
  3360. full_name = makefullname(ctx, prefix, name);
  3361. shortname = shortdefname(full_name);
  3362. field_number = google_protobuf_FieldDescriptorProto_number(field_proto);
  3363. if (field_number == 0 || field_number > UPB_MAX_FIELDNUMBER) {
  3364. upb_status_seterrf(ctx->status, "invalid field number (%u)", field_number);
  3365. return false;
  3366. }
  3367. if (m) {
  3368. /* direct message field. */
  3369. upb_value v, packed_v;
  3370. f = (upb_fielddef*)&m->fields[m->field_count++];
  3371. f->msgdef = m;
  3372. f->is_extension_ = false;
  3373. packed_v = pack_def(f, UPB_DEFTYPE_FIELD);
  3374. v = upb_value_constptr(f);
  3375. if (!upb_strtable_insert3(&m->ntof, name.data, name.size, packed_v, alloc)) {
  3376. upb_status_seterrf(ctx->status, "duplicate field name (%s)", shortname);
  3377. return false;
  3378. }
  3379. if (!upb_inttable_insert2(&m->itof, field_number, v, alloc)) {
  3380. upb_status_seterrf(ctx->status, "duplicate field number (%u)",
  3381. field_number);
  3382. return false;
  3383. }
  3384. } else {
  3385. /* extension field. */
  3386. f = (upb_fielddef*)&ctx->file->exts[ctx->file->ext_count];
  3387. f->is_extension_ = true;
  3388. CHK_OOM(symtab_add(ctx, full_name, pack_def(f, UPB_DEFTYPE_FIELD)));
  3389. }
  3390. f->full_name = full_name;
  3391. f->file = ctx->file;
  3392. f->type_ = (int)google_protobuf_FieldDescriptorProto_type(field_proto);
  3393. f->label_ = (int)google_protobuf_FieldDescriptorProto_label(field_proto);
  3394. f->number_ = field_number;
  3395. f->oneof = NULL;
  3396. /* We can't resolve the subdef or (in the case of extensions) the containing
  3397. * message yet, because it may not have been defined yet. We stash a pointer
  3398. * to the field_proto until later when we can properly resolve it. */
  3399. f->sub.unresolved = field_proto;
  3400. if (f->label_ == UPB_LABEL_REQUIRED && f->file->syntax == UPB_SYNTAX_PROTO3) {
  3401. upb_status_seterrf(ctx->status, "proto3 fields cannot be required (%s)",
  3402. f->full_name);
  3403. return false;
  3404. }
  3405. if (google_protobuf_FieldDescriptorProto_has_oneof_index(field_proto)) {
  3406. int oneof_index =
  3407. google_protobuf_FieldDescriptorProto_oneof_index(field_proto);
  3408. upb_oneofdef *oneof;
  3409. upb_value v = upb_value_constptr(f);
  3410. if (upb_fielddef_label(f) != UPB_LABEL_OPTIONAL) {
  3411. upb_status_seterrf(ctx->status,
  3412. "fields in oneof must have OPTIONAL label (%s)",
  3413. f->full_name);
  3414. return false;
  3415. }
  3416. if (!m) {
  3417. upb_status_seterrf(ctx->status,
  3418. "oneof_index provided for extension field (%s)",
  3419. f->full_name);
  3420. return false;
  3421. }
  3422. if (oneof_index >= m->oneof_count) {
  3423. upb_status_seterrf(ctx->status, "oneof_index out of range (%s)",
  3424. f->full_name);
  3425. return false;
  3426. }
  3427. oneof = (upb_oneofdef*)&m->oneofs[oneof_index];
  3428. f->oneof = oneof;
  3429. CHK(upb_inttable_insert2(&oneof->itof, f->number_, v, alloc));
  3430. CHK(upb_strtable_insert3(&oneof->ntof, name.data, name.size, v, alloc));
  3431. } else {
  3432. f->oneof = NULL;
  3433. }
  3434. if (google_protobuf_FieldDescriptorProto_has_options(field_proto)) {
  3435. options = google_protobuf_FieldDescriptorProto_options(field_proto);
  3436. f->lazy_ = google_protobuf_FieldOptions_lazy(options);
  3437. f->packed_ = google_protobuf_FieldOptions_packed(options);
  3438. } else {
  3439. f->lazy_ = false;
  3440. f->packed_ = false;
  3441. }
  3442. return true;
  3443. }
  3444. static bool create_enumdef(
  3445. const symtab_addctx *ctx, const char *prefix,
  3446. const google_protobuf_EnumDescriptorProto *enum_proto) {
  3447. upb_enumdef *e;
  3448. const google_protobuf_EnumValueDescriptorProto *const *values;
  3449. upb_strview name;
  3450. size_t i, n;
  3451. name = google_protobuf_EnumDescriptorProto_name(enum_proto);
  3452. CHK(upb_isident(name, false, ctx->status));
  3453. e = (upb_enumdef*)&ctx->file->enums[ctx->file->enum_count++];
  3454. e->full_name = makefullname(ctx, prefix, name);
  3455. CHK_OOM(symtab_add(ctx, e->full_name, pack_def(e, UPB_DEFTYPE_ENUM)));
  3456. CHK_OOM(upb_strtable_init2(&e->ntoi, UPB_CTYPE_INT32, ctx->alloc));
  3457. CHK_OOM(upb_inttable_init2(&e->iton, UPB_CTYPE_CSTR, ctx->alloc));
  3458. e->file = ctx->file;
  3459. e->defaultval = 0;
  3460. values = google_protobuf_EnumDescriptorProto_value(enum_proto, &n);
  3461. if (n == 0) {
  3462. upb_status_seterrf(ctx->status,
  3463. "enums must contain at least one value (%s)",
  3464. e->full_name);
  3465. return false;
  3466. }
  3467. for (i = 0; i < n; i++) {
  3468. const google_protobuf_EnumValueDescriptorProto *value = values[i];
  3469. upb_strview name = google_protobuf_EnumValueDescriptorProto_name(value);
  3470. char *name2 = strviewdup(ctx, name);
  3471. int32_t num = google_protobuf_EnumValueDescriptorProto_number(value);
  3472. upb_value v = upb_value_int32(num);
  3473. if (i == 0 && e->file->syntax == UPB_SYNTAX_PROTO3 && num != 0) {
  3474. upb_status_seterrf(ctx->status,
  3475. "for proto3, the first enum value must be zero (%s)",
  3476. e->full_name);
  3477. return false;
  3478. }
  3479. if (upb_strtable_lookup(&e->ntoi, name2, NULL)) {
  3480. upb_status_seterrf(ctx->status, "duplicate enum label '%s'", name2);
  3481. return false;
  3482. }
  3483. CHK_OOM(name2)
  3484. CHK_OOM(
  3485. upb_strtable_insert3(&e->ntoi, name2, strlen(name2), v, ctx->alloc));
  3486. if (!upb_inttable_lookup(&e->iton, num, NULL)) {
  3487. upb_value v = upb_value_cstr(name2);
  3488. CHK_OOM(upb_inttable_insert2(&e->iton, num, v, ctx->alloc));
  3489. }
  3490. }
  3491. upb_inttable_compact2(&e->iton, ctx->alloc);
  3492. return true;
  3493. }
  3494. static bool create_msgdef(const symtab_addctx *ctx, const char *prefix,
  3495. const google_protobuf_DescriptorProto *msg_proto) {
  3496. upb_msgdef *m;
  3497. const google_protobuf_MessageOptions *options;
  3498. const google_protobuf_OneofDescriptorProto *const *oneofs;
  3499. const google_protobuf_FieldDescriptorProto *const *fields;
  3500. const google_protobuf_EnumDescriptorProto *const *enums;
  3501. const google_protobuf_DescriptorProto *const *msgs;
  3502. size_t i, n;
  3503. upb_strview name;
  3504. name = google_protobuf_DescriptorProto_name(msg_proto);
  3505. CHK(upb_isident(name, false, ctx->status));
  3506. m = (upb_msgdef*)&ctx->file->msgs[ctx->file->msg_count++];
  3507. m->full_name = makefullname(ctx, prefix, name);
  3508. CHK_OOM(symtab_add(ctx, m->full_name, pack_def(m, UPB_DEFTYPE_MSG)));
  3509. CHK_OOM(upb_inttable_init2(&m->itof, UPB_CTYPE_CONSTPTR, ctx->alloc));
  3510. CHK_OOM(upb_strtable_init2(&m->ntof, UPB_CTYPE_CONSTPTR, ctx->alloc));
  3511. m->file = ctx->file;
  3512. m->map_entry = false;
  3513. options = google_protobuf_DescriptorProto_options(msg_proto);
  3514. if (options) {
  3515. m->map_entry = google_protobuf_MessageOptions_map_entry(options);
  3516. }
  3517. oneofs = google_protobuf_DescriptorProto_oneof_decl(msg_proto, &n);
  3518. m->oneof_count = 0;
  3519. m->oneofs = upb_malloc(ctx->alloc, sizeof(*m->oneofs) * n);
  3520. for (i = 0; i < n; i++) {
  3521. CHK(create_oneofdef(ctx, m, oneofs[i]));
  3522. }
  3523. fields = google_protobuf_DescriptorProto_field(msg_proto, &n);
  3524. m->field_count = 0;
  3525. m->fields = upb_malloc(ctx->alloc, sizeof(*m->fields) * n);
  3526. for (i = 0; i < n; i++) {
  3527. CHK(create_fielddef(ctx, m->full_name, m, fields[i]));
  3528. }
  3529. CHK(assign_msg_indices(m, ctx->status));
  3530. assign_msg_wellknowntype(m);
  3531. upb_inttable_compact2(&m->itof, ctx->alloc);
  3532. /* This message is built. Now build nested messages and enums. */
  3533. enums = google_protobuf_DescriptorProto_enum_type(msg_proto, &n);
  3534. for (i = 0; i < n; i++) {
  3535. CHK(create_enumdef(ctx, m->full_name, enums[i]));
  3536. }
  3537. msgs = google_protobuf_DescriptorProto_nested_type(msg_proto, &n);
  3538. for (i = 0; i < n; i++) {
  3539. CHK(create_msgdef(ctx, m->full_name, msgs[i]));
  3540. }
  3541. return true;
  3542. }
  3543. typedef struct {
  3544. int msg_count;
  3545. int enum_count;
  3546. int ext_count;
  3547. } decl_counts;
  3548. static void count_types_in_msg(const google_protobuf_DescriptorProto *msg_proto,
  3549. decl_counts *counts) {
  3550. const google_protobuf_DescriptorProto *const *msgs;
  3551. size_t i, n;
  3552. counts->msg_count++;
  3553. msgs = google_protobuf_DescriptorProto_nested_type(msg_proto, &n);
  3554. for (i = 0; i < n; i++) {
  3555. count_types_in_msg(msgs[i], counts);
  3556. }
  3557. google_protobuf_DescriptorProto_enum_type(msg_proto, &n);
  3558. counts->enum_count += n;
  3559. google_protobuf_DescriptorProto_extension(msg_proto, &n);
  3560. counts->ext_count += n;
  3561. }
  3562. static void count_types_in_file(
  3563. const google_protobuf_FileDescriptorProto *file_proto,
  3564. decl_counts *counts) {
  3565. const google_protobuf_DescriptorProto *const *msgs;
  3566. size_t i, n;
  3567. msgs = google_protobuf_FileDescriptorProto_message_type(file_proto, &n);
  3568. for (i = 0; i < n; i++) {
  3569. count_types_in_msg(msgs[i], counts);
  3570. }
  3571. google_protobuf_FileDescriptorProto_enum_type(file_proto, &n);
  3572. counts->enum_count += n;
  3573. google_protobuf_FileDescriptorProto_extension(file_proto, &n);
  3574. counts->ext_count += n;
  3575. }
  3576. static bool resolve_fielddef(const symtab_addctx *ctx, const char *prefix,
  3577. upb_fielddef *f) {
  3578. upb_strview name;
  3579. const google_protobuf_FieldDescriptorProto *field_proto = f->sub.unresolved;
  3580. if (f->is_extension_) {
  3581. if (!google_protobuf_FieldDescriptorProto_has_extendee(field_proto)) {
  3582. upb_status_seterrf(ctx->status,
  3583. "extension for field '%s' had no extendee",
  3584. f->full_name);
  3585. return false;
  3586. }
  3587. name = google_protobuf_FieldDescriptorProto_extendee(field_proto);
  3588. f->msgdef = symtab_resolve(ctx, f, prefix, name, UPB_DEFTYPE_MSG);
  3589. CHK(f->msgdef);
  3590. }
  3591. if ((upb_fielddef_issubmsg(f) || f->type_ == UPB_DESCRIPTOR_TYPE_ENUM) &&
  3592. !google_protobuf_FieldDescriptorProto_has_type_name(field_proto)) {
  3593. upb_status_seterrf(ctx->status, "field '%s' is missing type name",
  3594. f->full_name);
  3595. return false;
  3596. }
  3597. name = google_protobuf_FieldDescriptorProto_type_name(field_proto);
  3598. if (upb_fielddef_issubmsg(f)) {
  3599. f->sub.msgdef = symtab_resolve(ctx, f, prefix, name, UPB_DEFTYPE_MSG);
  3600. CHK(f->sub.msgdef);
  3601. } else if (f->type_ == UPB_DESCRIPTOR_TYPE_ENUM) {
  3602. f->sub.enumdef = symtab_resolve(ctx, f, prefix, name, UPB_DEFTYPE_ENUM);
  3603. CHK(f->sub.enumdef);
  3604. }
  3605. /* Have to delay resolving of the default value until now because of the enum
  3606. * case, since enum defaults are specified with a label. */
  3607. if (google_protobuf_FieldDescriptorProto_has_default_value(field_proto)) {
  3608. upb_strview defaultval =
  3609. google_protobuf_FieldDescriptorProto_default_value(field_proto);
  3610. if (f->file->syntax == UPB_SYNTAX_PROTO3) {
  3611. upb_status_seterrf(ctx->status,
  3612. "proto3 fields cannot have explicit defaults (%s)",
  3613. f->full_name);
  3614. return false;
  3615. }
  3616. if (upb_fielddef_issubmsg(f)) {
  3617. upb_status_seterrf(ctx->status,
  3618. "message fields cannot have explicit defaults (%s)",
  3619. f->full_name);
  3620. return false;
  3621. }
  3622. if (!parse_default(ctx, defaultval.data, defaultval.size, f)) {
  3623. upb_status_seterrf(ctx->status,
  3624. "couldn't parse default '" UPB_STRVIEW_FORMAT
  3625. "' for field (%s)",
  3626. UPB_STRVIEW_ARGS(defaultval), f->full_name);
  3627. return false;
  3628. }
  3629. } else {
  3630. set_default_default(ctx, f);
  3631. }
  3632. return true;
  3633. }
  3634. static bool build_filedef(
  3635. const symtab_addctx *ctx, upb_filedef *file,
  3636. const google_protobuf_FileDescriptorProto *file_proto) {
  3637. upb_alloc *alloc = ctx->alloc;
  3638. const google_protobuf_FileOptions *file_options_proto;
  3639. const google_protobuf_DescriptorProto *const *msgs;
  3640. const google_protobuf_EnumDescriptorProto *const *enums;
  3641. const google_protobuf_FieldDescriptorProto *const *exts;
  3642. const upb_strview* strs;
  3643. size_t i, n;
  3644. decl_counts counts = {0};
  3645. count_types_in_file(file_proto, &counts);
  3646. file->msgs = upb_malloc(alloc, sizeof(*file->msgs) * counts.msg_count);
  3647. file->enums = upb_malloc(alloc, sizeof(*file->enums) * counts.enum_count);
  3648. file->exts = upb_malloc(alloc, sizeof(*file->exts) * counts.ext_count);
  3649. CHK_OOM(counts.msg_count == 0 || file->msgs);
  3650. CHK_OOM(counts.enum_count == 0 || file->enums);
  3651. CHK_OOM(counts.ext_count == 0 || file->exts);
  3652. /* We increment these as defs are added. */
  3653. file->msg_count = 0;
  3654. file->enum_count = 0;
  3655. file->ext_count = 0;
  3656. if (!google_protobuf_FileDescriptorProto_has_name(file_proto)) {
  3657. upb_status_seterrmsg(ctx->status, "File has no name");
  3658. return false;
  3659. }
  3660. file->name =
  3661. strviewdup(ctx, google_protobuf_FileDescriptorProto_name(file_proto));
  3662. file->phpprefix = NULL;
  3663. file->phpnamespace = NULL;
  3664. if (google_protobuf_FileDescriptorProto_has_package(file_proto)) {
  3665. upb_strview package =
  3666. google_protobuf_FileDescriptorProto_package(file_proto);
  3667. CHK(upb_isident(package, true, ctx->status));
  3668. file->package = strviewdup(ctx, package);
  3669. } else {
  3670. file->package = NULL;
  3671. }
  3672. if (google_protobuf_FileDescriptorProto_has_syntax(file_proto)) {
  3673. upb_strview syntax =
  3674. google_protobuf_FileDescriptorProto_syntax(file_proto);
  3675. if (streql_view(syntax, "proto2")) {
  3676. file->syntax = UPB_SYNTAX_PROTO2;
  3677. } else if (streql_view(syntax, "proto3")) {
  3678. file->syntax = UPB_SYNTAX_PROTO3;
  3679. } else {
  3680. upb_status_seterrf(ctx->status, "Invalid syntax '%s'", syntax);
  3681. return false;
  3682. }
  3683. } else {
  3684. file->syntax = UPB_SYNTAX_PROTO2;
  3685. }
  3686. /* Read options. */
  3687. file_options_proto = google_protobuf_FileDescriptorProto_options(file_proto);
  3688. if (file_options_proto) {
  3689. if (google_protobuf_FileOptions_has_php_class_prefix(file_options_proto)) {
  3690. file->phpprefix = strviewdup(
  3691. ctx,
  3692. google_protobuf_FileOptions_php_class_prefix(file_options_proto));
  3693. }
  3694. if (google_protobuf_FileOptions_has_php_namespace(file_options_proto)) {
  3695. file->phpnamespace = strviewdup(
  3696. ctx, google_protobuf_FileOptions_php_namespace(file_options_proto));
  3697. }
  3698. }
  3699. /* Verify dependencies. */
  3700. strs = google_protobuf_FileDescriptorProto_dependency(file_proto, &n);
  3701. file->deps = upb_malloc(alloc, sizeof(*file->deps) * n) ;
  3702. CHK_OOM(n == 0 || file->deps);
  3703. for (i = 0; i < n; i++) {
  3704. upb_strview dep_name = strs[i];
  3705. upb_value v;
  3706. if (!upb_strtable_lookup2(&ctx->symtab->files, dep_name.data,
  3707. dep_name.size, &v)) {
  3708. upb_status_seterrf(ctx->status,
  3709. "Depends on file '" UPB_STRVIEW_FORMAT
  3710. "', but it has not been loaded",
  3711. UPB_STRVIEW_ARGS(dep_name));
  3712. return false;
  3713. }
  3714. file->deps[i] = upb_value_getconstptr(v);
  3715. }
  3716. /* Create messages. */
  3717. msgs = google_protobuf_FileDescriptorProto_message_type(file_proto, &n);
  3718. for (i = 0; i < n; i++) {
  3719. CHK(create_msgdef(ctx, file->package, msgs[i]));
  3720. }
  3721. /* Create enums. */
  3722. enums = google_protobuf_FileDescriptorProto_enum_type(file_proto, &n);
  3723. for (i = 0; i < n; i++) {
  3724. CHK(create_enumdef(ctx, file->package, enums[i]));
  3725. }
  3726. /* Create extensions. */
  3727. exts = google_protobuf_FileDescriptorProto_extension(file_proto, &n);
  3728. file->exts = upb_malloc(alloc, sizeof(*file->exts) * n);
  3729. CHK_OOM(n == 0 || file->exts);
  3730. for (i = 0; i < n; i++) {
  3731. CHK(create_fielddef(ctx, file->package, NULL, exts[i]));
  3732. }
  3733. /* Now that all names are in the table, resolve references. */
  3734. for (i = 0; i < file->ext_count; i++) {
  3735. CHK(resolve_fielddef(ctx, file->package, (upb_fielddef*)&file->exts[i]));
  3736. }
  3737. for (i = 0; i < file->msg_count; i++) {
  3738. const upb_msgdef *m = &file->msgs[i];
  3739. int j;
  3740. for (j = 0; j < m->field_count; j++) {
  3741. CHK(resolve_fielddef(ctx, m->full_name, (upb_fielddef*)&m->fields[j]));
  3742. }
  3743. }
  3744. return true;
  3745. }
  3746. static bool upb_symtab_addtotabs(upb_symtab *s, symtab_addctx *ctx,
  3747. upb_status *status) {
  3748. const upb_filedef *file = ctx->file;
  3749. upb_alloc *alloc = upb_arena_alloc(s->arena);
  3750. upb_strtable_iter iter;
  3751. CHK_OOM(upb_strtable_insert3(&s->files, file->name, strlen(file->name),
  3752. upb_value_constptr(file), alloc));
  3753. upb_strtable_begin(&iter, ctx->addtab);
  3754. for (; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
  3755. const char *key = upb_strtable_iter_key(&iter);
  3756. size_t keylen = upb_strtable_iter_keylength(&iter);
  3757. upb_value value = upb_strtable_iter_value(&iter);
  3758. CHK_OOM(upb_strtable_insert3(&s->syms, key, keylen, value, alloc));
  3759. }
  3760. return true;
  3761. }
  3762. /* upb_filedef ****************************************************************/
  3763. const char *upb_filedef_name(const upb_filedef *f) {
  3764. return f->name;
  3765. }
  3766. const char *upb_filedef_package(const upb_filedef *f) {
  3767. return f->package;
  3768. }
  3769. const char *upb_filedef_phpprefix(const upb_filedef *f) {
  3770. return f->phpprefix;
  3771. }
  3772. const char *upb_filedef_phpnamespace(const upb_filedef *f) {
  3773. return f->phpnamespace;
  3774. }
  3775. upb_syntax_t upb_filedef_syntax(const upb_filedef *f) {
  3776. return f->syntax;
  3777. }
  3778. int upb_filedef_msgcount(const upb_filedef *f) {
  3779. return f->msg_count;
  3780. }
  3781. int upb_filedef_depcount(const upb_filedef *f) {
  3782. return f->dep_count;
  3783. }
  3784. int upb_filedef_enumcount(const upb_filedef *f) {
  3785. return f->enum_count;
  3786. }
  3787. const upb_filedef *upb_filedef_dep(const upb_filedef *f, int i) {
  3788. return i < 0 || i >= f->dep_count ? NULL : f->deps[i];
  3789. }
  3790. const upb_msgdef *upb_filedef_msg(const upb_filedef *f, int i) {
  3791. return i < 0 || i >= f->msg_count ? NULL : &f->msgs[i];
  3792. }
  3793. const upb_enumdef *upb_filedef_enum(const upb_filedef *f, int i) {
  3794. return i < 0 || i >= f->enum_count ? NULL : &f->enums[i];
  3795. }
  3796. void upb_symtab_free(upb_symtab *s) {
  3797. upb_arena_free(s->arena);
  3798. upb_gfree(s);
  3799. }
  3800. upb_symtab *upb_symtab_new(void) {
  3801. upb_symtab *s = upb_gmalloc(sizeof(*s));
  3802. upb_alloc *alloc;
  3803. if (!s) {
  3804. return NULL;
  3805. }
  3806. s->arena = upb_arena_new();
  3807. alloc = upb_arena_alloc(s->arena);
  3808. if (!upb_strtable_init2(&s->syms, UPB_CTYPE_CONSTPTR, alloc) ||
  3809. !upb_strtable_init2(&s->files, UPB_CTYPE_CONSTPTR, alloc)) {
  3810. upb_arena_free(s->arena);
  3811. upb_gfree(s);
  3812. s = NULL;
  3813. }
  3814. return s;
  3815. }
  3816. const upb_msgdef *upb_symtab_lookupmsg(const upb_symtab *s, const char *sym) {
  3817. upb_value v;
  3818. return upb_strtable_lookup(&s->syms, sym, &v) ?
  3819. unpack_def(v, UPB_DEFTYPE_MSG) : NULL;
  3820. }
  3821. const upb_msgdef *upb_symtab_lookupmsg2(const upb_symtab *s, const char *sym,
  3822. size_t len) {
  3823. upb_value v;
  3824. return upb_strtable_lookup2(&s->syms, sym, len, &v) ?
  3825. unpack_def(v, UPB_DEFTYPE_MSG) : NULL;
  3826. }
  3827. const upb_enumdef *upb_symtab_lookupenum(const upb_symtab *s, const char *sym) {
  3828. upb_value v;
  3829. return upb_strtable_lookup(&s->syms, sym, &v) ?
  3830. unpack_def(v, UPB_DEFTYPE_ENUM) : NULL;
  3831. }
  3832. const upb_filedef *upb_symtab_lookupfile(const upb_symtab *s, const char *name) {
  3833. upb_value v;
  3834. return upb_strtable_lookup(&s->files, name, &v) ? upb_value_getconstptr(v)
  3835. : NULL;
  3836. }
  3837. const upb_filedef *upb_symtab_addfile(
  3838. upb_symtab *s, const google_protobuf_FileDescriptorProto *file_proto,
  3839. upb_status *status) {
  3840. upb_arena *tmparena = upb_arena_new();
  3841. upb_strtable addtab;
  3842. upb_alloc *alloc = upb_arena_alloc(s->arena);
  3843. upb_filedef *file = upb_malloc(alloc, sizeof(*file));
  3844. bool ok;
  3845. symtab_addctx ctx;
  3846. ctx.file = file;
  3847. ctx.symtab = s;
  3848. ctx.alloc = alloc;
  3849. ctx.tmp = upb_arena_alloc(tmparena);
  3850. ctx.addtab = &addtab;
  3851. ctx.status = status;
  3852. ok = file &&
  3853. upb_strtable_init2(&addtab, UPB_CTYPE_CONSTPTR, ctx.tmp) &&
  3854. build_filedef(&ctx, file, file_proto) &&
  3855. upb_symtab_addtotabs(s, &ctx, status);
  3856. upb_arena_free(tmparena);
  3857. return ok ? file : NULL;
  3858. }
  3859. /* Include here since we want most of this file to be stdio-free. */
  3860. #include <stdio.h>
  3861. bool _upb_symtab_loaddefinit(upb_symtab *s, const upb_def_init *init) {
  3862. /* Since this function should never fail (it would indicate a bug in upb) we
  3863. * print errors to stderr instead of returning error status to the user. */
  3864. upb_def_init **deps = init->deps;
  3865. google_protobuf_FileDescriptorProto *file;
  3866. upb_arena *arena;
  3867. upb_status status;
  3868. upb_status_clear(&status);
  3869. if (upb_strtable_lookup(&s->files, init->filename, NULL)) {
  3870. return true;
  3871. }
  3872. arena = upb_arena_new();
  3873. for (; *deps; deps++) {
  3874. if (!_upb_symtab_loaddefinit(s, *deps)) goto err;
  3875. }
  3876. file = google_protobuf_FileDescriptorProto_parse(
  3877. init->descriptor.data, init->descriptor.size, arena);
  3878. if (!file) {
  3879. upb_status_seterrf(
  3880. &status,
  3881. "Failed to parse compiled-in descriptor for file '%s'. This should "
  3882. "never happen.",
  3883. init->filename);
  3884. goto err;
  3885. }
  3886. if (!upb_symtab_addfile(s, file, &status)) goto err;
  3887. upb_arena_free(arena);
  3888. return true;
  3889. err:
  3890. fprintf(stderr, "Error loading compiled-in descriptor: %s\n",
  3891. upb_status_errmsg(&status));
  3892. upb_arena_free(arena);
  3893. return false;
  3894. }
  3895. #undef CHK
  3896. #undef CHK_OOM
  3897. static bool is_power_of_two(size_t val) {
  3898. return (val & (val - 1)) == 0;
  3899. }
  3900. /* Align up to the given power of 2. */
  3901. static size_t align_up(size_t val, size_t align) {
  3902. UPB_ASSERT(is_power_of_two(align));
  3903. return (val + align - 1) & ~(align - 1);
  3904. }
  3905. static size_t div_round_up(size_t n, size_t d) {
  3906. return (n + d - 1) / d;
  3907. }
  3908. static size_t upb_msgval_sizeof2(upb_fieldtype_t type) {
  3909. switch (type) {
  3910. case UPB_TYPE_DOUBLE:
  3911. case UPB_TYPE_INT64:
  3912. case UPB_TYPE_UINT64:
  3913. return 8;
  3914. case UPB_TYPE_ENUM:
  3915. case UPB_TYPE_INT32:
  3916. case UPB_TYPE_UINT32:
  3917. case UPB_TYPE_FLOAT:
  3918. return 4;
  3919. case UPB_TYPE_BOOL:
  3920. return 1;
  3921. case UPB_TYPE_MESSAGE:
  3922. return sizeof(void*);
  3923. case UPB_TYPE_BYTES:
  3924. case UPB_TYPE_STRING:
  3925. return sizeof(upb_strview);
  3926. }
  3927. UPB_UNREACHABLE();
  3928. }
  3929. static uint8_t upb_msg_fielddefsize(const upb_fielddef *f) {
  3930. if (upb_fielddef_isseq(f)) {
  3931. return sizeof(void*);
  3932. } else {
  3933. return upb_msgval_sizeof2(upb_fielddef_type(f));
  3934. }
  3935. }
  3936. /** upb_msglayout *************************************************************/
  3937. static void upb_msglayout_free(upb_msglayout *l) {
  3938. upb_gfree(l);
  3939. }
  3940. static size_t upb_msglayout_place(upb_msglayout *l, size_t size) {
  3941. size_t ret;
  3942. l->size = align_up(l->size, size);
  3943. ret = l->size;
  3944. l->size += size;
  3945. return ret;
  3946. }
  3947. static bool upb_msglayout_init(const upb_msgdef *m,
  3948. upb_msglayout *l,
  3949. upb_msgfactory *factory) {
  3950. upb_msg_field_iter it;
  3951. upb_msg_oneof_iter oit;
  3952. size_t hasbit;
  3953. size_t submsg_count = 0;
  3954. const upb_msglayout **submsgs;
  3955. upb_msglayout_field *fields;
  3956. for (upb_msg_field_begin(&it, m);
  3957. !upb_msg_field_done(&it);
  3958. upb_msg_field_next(&it)) {
  3959. const upb_fielddef* f = upb_msg_iter_field(&it);
  3960. if (upb_fielddef_issubmsg(f)) {
  3961. submsg_count++;
  3962. }
  3963. }
  3964. memset(l, 0, sizeof(*l));
  3965. fields = upb_gmalloc(upb_msgdef_numfields(m) * sizeof(*fields));
  3966. submsgs = upb_gmalloc(submsg_count * sizeof(*submsgs));
  3967. if ((!fields && upb_msgdef_numfields(m)) ||
  3968. (!submsgs && submsg_count)) {
  3969. /* OOM. */
  3970. upb_gfree(fields);
  3971. upb_gfree(submsgs);
  3972. return false;
  3973. }
  3974. l->field_count = upb_msgdef_numfields(m);
  3975. l->fields = fields;
  3976. l->submsgs = submsgs;
  3977. /* Allocate data offsets in three stages:
  3978. *
  3979. * 1. hasbits.
  3980. * 2. regular fields.
  3981. * 3. oneof fields.
  3982. *
  3983. * OPT: There is a lot of room for optimization here to minimize the size.
  3984. */
  3985. /* Allocate hasbits and set basic field attributes. */
  3986. submsg_count = 0;
  3987. for (upb_msg_field_begin(&it, m), hasbit = 0;
  3988. !upb_msg_field_done(&it);
  3989. upb_msg_field_next(&it)) {
  3990. const upb_fielddef* f = upb_msg_iter_field(&it);
  3991. upb_msglayout_field *field = &fields[upb_fielddef_index(f)];
  3992. field->number = upb_fielddef_number(f);
  3993. field->descriptortype = upb_fielddef_descriptortype(f);
  3994. field->label = upb_fielddef_label(f);
  3995. if (upb_fielddef_issubmsg(f)) {
  3996. const upb_msglayout *sub_layout =
  3997. upb_msgfactory_getlayout(factory, upb_fielddef_msgsubdef(f));
  3998. field->submsg_index = submsg_count++;
  3999. submsgs[field->submsg_index] = sub_layout;
  4000. }
  4001. if (upb_fielddef_haspresence(f) && !upb_fielddef_containingoneof(f)) {
  4002. field->presence = (hasbit++);
  4003. } else {
  4004. field->presence = 0;
  4005. }
  4006. }
  4007. /* Account for space used by hasbits. */
  4008. l->size = div_round_up(hasbit, 8);
  4009. /* Allocate non-oneof fields. */
  4010. for (upb_msg_field_begin(&it, m); !upb_msg_field_done(&it);
  4011. upb_msg_field_next(&it)) {
  4012. const upb_fielddef* f = upb_msg_iter_field(&it);
  4013. size_t field_size = upb_msg_fielddefsize(f);
  4014. size_t index = upb_fielddef_index(f);
  4015. if (upb_fielddef_containingoneof(f)) {
  4016. /* Oneofs are handled separately below. */
  4017. continue;
  4018. }
  4019. fields[index].offset = upb_msglayout_place(l, field_size);
  4020. }
  4021. /* Allocate oneof fields. Each oneof field consists of a uint32 for the case
  4022. * and space for the actual data. */
  4023. for (upb_msg_oneof_begin(&oit, m); !upb_msg_oneof_done(&oit);
  4024. upb_msg_oneof_next(&oit)) {
  4025. const upb_oneofdef* o = upb_msg_iter_oneof(&oit);
  4026. upb_oneof_iter fit;
  4027. size_t case_size = sizeof(uint32_t); /* Could potentially optimize this. */
  4028. size_t field_size = 0;
  4029. uint32_t case_offset;
  4030. uint32_t data_offset;
  4031. /* Calculate field size: the max of all field sizes. */
  4032. for (upb_oneof_begin(&fit, o);
  4033. !upb_oneof_done(&fit);
  4034. upb_oneof_next(&fit)) {
  4035. const upb_fielddef* f = upb_oneof_iter_field(&fit);
  4036. field_size = UPB_MAX(field_size, upb_msg_fielddefsize(f));
  4037. }
  4038. /* Align and allocate case offset. */
  4039. case_offset = upb_msglayout_place(l, case_size);
  4040. data_offset = upb_msglayout_place(l, field_size);
  4041. for (upb_oneof_begin(&fit, o);
  4042. !upb_oneof_done(&fit);
  4043. upb_oneof_next(&fit)) {
  4044. const upb_fielddef* f = upb_oneof_iter_field(&fit);
  4045. fields[upb_fielddef_index(f)].offset = data_offset;
  4046. fields[upb_fielddef_index(f)].presence = ~case_offset;
  4047. }
  4048. }
  4049. /* Size of the entire structure should be a multiple of its greatest
  4050. * alignment. TODO: track overall alignment for real? */
  4051. l->size = align_up(l->size, 8);
  4052. return true;
  4053. }
  4054. /** upb_msgfactory ************************************************************/
  4055. struct upb_msgfactory {
  4056. const upb_symtab *symtab; /* We own a ref. */
  4057. upb_inttable layouts;
  4058. };
  4059. upb_msgfactory *upb_msgfactory_new(const upb_symtab *symtab) {
  4060. upb_msgfactory *ret = upb_gmalloc(sizeof(*ret));
  4061. ret->symtab = symtab;
  4062. upb_inttable_init(&ret->layouts, UPB_CTYPE_PTR);
  4063. return ret;
  4064. }
  4065. void upb_msgfactory_free(upb_msgfactory *f) {
  4066. upb_inttable_iter i;
  4067. upb_inttable_begin(&i, &f->layouts);
  4068. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  4069. upb_msglayout *l = upb_value_getptr(upb_inttable_iter_value(&i));
  4070. upb_msglayout_free(l);
  4071. }
  4072. upb_inttable_uninit(&f->layouts);
  4073. upb_gfree(f);
  4074. }
  4075. const upb_symtab *upb_msgfactory_symtab(const upb_msgfactory *f) {
  4076. return f->symtab;
  4077. }
  4078. const upb_msglayout *upb_msgfactory_getlayout(upb_msgfactory *f,
  4079. const upb_msgdef *m) {
  4080. upb_value v;
  4081. UPB_ASSERT(upb_symtab_lookupmsg(f->symtab, upb_msgdef_fullname(m)) == m);
  4082. UPB_ASSERT(!upb_msgdef_mapentry(m));
  4083. if (upb_inttable_lookupptr(&f->layouts, m, &v)) {
  4084. UPB_ASSERT(upb_value_getptr(v));
  4085. return upb_value_getptr(v);
  4086. } else {
  4087. /* In case of circular dependency, layout has to be inserted first. */
  4088. upb_msglayout *l = upb_gmalloc(sizeof(*l));
  4089. upb_msgfactory *mutable_f = (void*)f;
  4090. upb_inttable_insertptr(&mutable_f->layouts, m, upb_value_ptr(l));
  4091. UPB_ASSERT(l);
  4092. if (!upb_msglayout_init(m, l, f)) {
  4093. upb_msglayout_free(l);
  4094. }
  4095. return l;
  4096. }
  4097. }
  4098. /*
  4099. ** TODO(haberman): it's unclear whether a lot of the consistency checks should
  4100. ** UPB_ASSERT() or return false.
  4101. */
  4102. #include <string.h>
  4103. struct upb_handlers {
  4104. upb_handlercache *cache;
  4105. const upb_msgdef *msg;
  4106. const upb_handlers **sub;
  4107. const void *top_closure_type;
  4108. upb_handlers_tabent table[1]; /* Dynamically-sized field handler array. */
  4109. };
  4110. static void *upb_calloc(upb_arena *arena, size_t size) {
  4111. void *mem = upb_malloc(upb_arena_alloc(arena), size);
  4112. if (mem) {
  4113. memset(mem, 0, size);
  4114. }
  4115. return mem;
  4116. }
  4117. /* Defined for the sole purpose of having a unique pointer value for
  4118. * UPB_NO_CLOSURE. */
  4119. char _upb_noclosure;
  4120. /* Given a selector for a STARTSUBMSG handler, resolves to a pointer to the
  4121. * subhandlers for this submessage field. */
  4122. #define SUBH(h, selector) (h->sub[selector])
  4123. /* The selector for a submessage field is the field index. */
  4124. #define SUBH_F(h, f) SUBH(h, upb_fielddef_index(f))
  4125. static int32_t trygetsel(upb_handlers *h, const upb_fielddef *f,
  4126. upb_handlertype_t type) {
  4127. upb_selector_t sel;
  4128. bool ok;
  4129. ok = upb_handlers_getselector(f, type, &sel);
  4130. UPB_ASSERT(upb_handlers_msgdef(h) == upb_fielddef_containingtype(f));
  4131. UPB_ASSERT(ok);
  4132. return sel;
  4133. }
  4134. static upb_selector_t handlers_getsel(upb_handlers *h, const upb_fielddef *f,
  4135. upb_handlertype_t type) {
  4136. int32_t sel = trygetsel(h, f, type);
  4137. UPB_ASSERT(sel >= 0);
  4138. return sel;
  4139. }
  4140. static const void **returntype(upb_handlers *h, const upb_fielddef *f,
  4141. upb_handlertype_t type) {
  4142. return &h->table[handlers_getsel(h, f, type)].attr.return_closure_type;
  4143. }
  4144. static bool doset(upb_handlers *h, int32_t sel, const upb_fielddef *f,
  4145. upb_handlertype_t type, upb_func *func,
  4146. const upb_handlerattr *attr) {
  4147. upb_handlerattr set_attr = UPB_HANDLERATTR_INIT;
  4148. const void *closure_type;
  4149. const void **context_closure_type;
  4150. UPB_ASSERT(!h->table[sel].func);
  4151. if (attr) {
  4152. set_attr = *attr;
  4153. }
  4154. /* Check that the given closure type matches the closure type that has been
  4155. * established for this context (if any). */
  4156. closure_type = set_attr.closure_type;
  4157. if (type == UPB_HANDLER_STRING) {
  4158. context_closure_type = returntype(h, f, UPB_HANDLER_STARTSTR);
  4159. } else if (f && upb_fielddef_isseq(f) &&
  4160. type != UPB_HANDLER_STARTSEQ &&
  4161. type != UPB_HANDLER_ENDSEQ) {
  4162. context_closure_type = returntype(h, f, UPB_HANDLER_STARTSEQ);
  4163. } else {
  4164. context_closure_type = &h->top_closure_type;
  4165. }
  4166. if (closure_type && *context_closure_type &&
  4167. closure_type != *context_closure_type) {
  4168. return false;
  4169. }
  4170. if (closure_type)
  4171. *context_closure_type = closure_type;
  4172. /* If this is a STARTSEQ or STARTSTR handler, check that the returned pointer
  4173. * matches any pre-existing expectations about what type is expected. */
  4174. if (type == UPB_HANDLER_STARTSEQ || type == UPB_HANDLER_STARTSTR) {
  4175. const void *return_type = set_attr.return_closure_type;
  4176. const void *table_return_type = h->table[sel].attr.return_closure_type;
  4177. if (return_type && table_return_type && return_type != table_return_type) {
  4178. return false;
  4179. }
  4180. if (table_return_type && !return_type) {
  4181. set_attr.return_closure_type = table_return_type;
  4182. }
  4183. }
  4184. h->table[sel].func = (upb_func*)func;
  4185. h->table[sel].attr = set_attr;
  4186. return true;
  4187. }
  4188. /* Returns the effective closure type for this handler (which will propagate
  4189. * from outer frames if this frame has no START* handler). Not implemented for
  4190. * UPB_HANDLER_STRING at the moment since this is not needed. Returns NULL is
  4191. * the effective closure type is unspecified (either no handler was registered
  4192. * to specify it or the handler that was registered did not specify the closure
  4193. * type). */
  4194. const void *effective_closure_type(upb_handlers *h, const upb_fielddef *f,
  4195. upb_handlertype_t type) {
  4196. const void *ret;
  4197. upb_selector_t sel;
  4198. UPB_ASSERT(type != UPB_HANDLER_STRING);
  4199. ret = h->top_closure_type;
  4200. if (upb_fielddef_isseq(f) &&
  4201. type != UPB_HANDLER_STARTSEQ &&
  4202. type != UPB_HANDLER_ENDSEQ &&
  4203. h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSEQ)].func) {
  4204. ret = h->table[sel].attr.return_closure_type;
  4205. }
  4206. if (type == UPB_HANDLER_STRING &&
  4207. h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSTR)].func) {
  4208. ret = h->table[sel].attr.return_closure_type;
  4209. }
  4210. /* The effective type of the submessage; not used yet.
  4211. * if (type == SUBMESSAGE &&
  4212. * h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSUBMSG)].func) {
  4213. * ret = h->table[sel].attr.return_closure_type;
  4214. * } */
  4215. return ret;
  4216. }
  4217. /* Checks whether the START* handler specified by f & type is missing even
  4218. * though it is required to convert the established type of an outer frame
  4219. * ("closure_type") into the established type of an inner frame (represented in
  4220. * the return closure type of this handler's attr. */
  4221. bool checkstart(upb_handlers *h, const upb_fielddef *f, upb_handlertype_t type,
  4222. upb_status *status) {
  4223. const void *closure_type;
  4224. const upb_handlerattr *attr;
  4225. const void *return_closure_type;
  4226. upb_selector_t sel = handlers_getsel(h, f, type);
  4227. if (h->table[sel].func) return true;
  4228. closure_type = effective_closure_type(h, f, type);
  4229. attr = &h->table[sel].attr;
  4230. return_closure_type = attr->return_closure_type;
  4231. if (closure_type && return_closure_type &&
  4232. closure_type != return_closure_type) {
  4233. return false;
  4234. }
  4235. return true;
  4236. }
  4237. static upb_handlers *upb_handlers_new(const upb_msgdef *md,
  4238. upb_handlercache *cache,
  4239. upb_arena *arena) {
  4240. int extra;
  4241. upb_handlers *h;
  4242. extra = sizeof(upb_handlers_tabent) * (upb_msgdef_selectorcount(md) - 1);
  4243. h = upb_calloc(arena, sizeof(*h) + extra);
  4244. if (!h) return NULL;
  4245. h->cache = cache;
  4246. h->msg = md;
  4247. if (upb_msgdef_submsgfieldcount(md) > 0) {
  4248. size_t bytes = upb_msgdef_submsgfieldcount(md) * sizeof(*h->sub);
  4249. h->sub = upb_calloc(arena, bytes);
  4250. if (!h->sub) return NULL;
  4251. } else {
  4252. h->sub = 0;
  4253. }
  4254. /* calloc() above initialized all handlers to NULL. */
  4255. return h;
  4256. }
  4257. /* Public interface ***********************************************************/
  4258. #define SETTER(name, handlerctype, handlertype) \
  4259. bool upb_handlers_set##name(upb_handlers *h, const upb_fielddef *f, \
  4260. handlerctype func, \
  4261. const upb_handlerattr *attr) { \
  4262. int32_t sel = trygetsel(h, f, handlertype); \
  4263. return doset(h, sel, f, handlertype, (upb_func *)func, attr); \
  4264. }
  4265. SETTER(int32, upb_int32_handlerfunc*, UPB_HANDLER_INT32)
  4266. SETTER(int64, upb_int64_handlerfunc*, UPB_HANDLER_INT64)
  4267. SETTER(uint32, upb_uint32_handlerfunc*, UPB_HANDLER_UINT32)
  4268. SETTER(uint64, upb_uint64_handlerfunc*, UPB_HANDLER_UINT64)
  4269. SETTER(float, upb_float_handlerfunc*, UPB_HANDLER_FLOAT)
  4270. SETTER(double, upb_double_handlerfunc*, UPB_HANDLER_DOUBLE)
  4271. SETTER(bool, upb_bool_handlerfunc*, UPB_HANDLER_BOOL)
  4272. SETTER(startstr, upb_startstr_handlerfunc*, UPB_HANDLER_STARTSTR)
  4273. SETTER(string, upb_string_handlerfunc*, UPB_HANDLER_STRING)
  4274. SETTER(endstr, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSTR)
  4275. SETTER(startseq, upb_startfield_handlerfunc*, UPB_HANDLER_STARTSEQ)
  4276. SETTER(startsubmsg, upb_startfield_handlerfunc*, UPB_HANDLER_STARTSUBMSG)
  4277. SETTER(endsubmsg, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSUBMSG)
  4278. SETTER(endseq, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSEQ)
  4279. #undef SETTER
  4280. bool upb_handlers_setunknown(upb_handlers *h, upb_unknown_handlerfunc *func,
  4281. const upb_handlerattr *attr) {
  4282. return doset(h, UPB_UNKNOWN_SELECTOR, NULL, UPB_HANDLER_INT32,
  4283. (upb_func *)func, attr);
  4284. }
  4285. bool upb_handlers_setstartmsg(upb_handlers *h, upb_startmsg_handlerfunc *func,
  4286. const upb_handlerattr *attr) {
  4287. return doset(h, UPB_STARTMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
  4288. (upb_func *)func, attr);
  4289. }
  4290. bool upb_handlers_setendmsg(upb_handlers *h, upb_endmsg_handlerfunc *func,
  4291. const upb_handlerattr *attr) {
  4292. return doset(h, UPB_ENDMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
  4293. (upb_func *)func, attr);
  4294. }
  4295. bool upb_handlers_setsubhandlers(upb_handlers *h, const upb_fielddef *f,
  4296. const upb_handlers *sub) {
  4297. UPB_ASSERT(sub);
  4298. UPB_ASSERT(upb_fielddef_issubmsg(f));
  4299. if (SUBH_F(h, f)) return false; /* Can't reset. */
  4300. if (upb_handlers_msgdef(sub) != upb_fielddef_msgsubdef(f)) {
  4301. return false;
  4302. }
  4303. SUBH_F(h, f) = sub;
  4304. return true;
  4305. }
  4306. const upb_handlers *upb_handlers_getsubhandlers(const upb_handlers *h,
  4307. const upb_fielddef *f) {
  4308. UPB_ASSERT(upb_fielddef_issubmsg(f));
  4309. return SUBH_F(h, f);
  4310. }
  4311. upb_func *upb_handlers_gethandler(const upb_handlers *h, upb_selector_t s,
  4312. const void **handler_data) {
  4313. upb_func *ret = (upb_func *)h->table[s].func;
  4314. if (ret && handler_data) {
  4315. *handler_data = h->table[s].attr.handler_data;
  4316. }
  4317. return ret;
  4318. }
  4319. bool upb_handlers_getattr(const upb_handlers *h, upb_selector_t sel,
  4320. upb_handlerattr *attr) {
  4321. if (!upb_handlers_gethandler(h, sel, NULL))
  4322. return false;
  4323. *attr = h->table[sel].attr;
  4324. return true;
  4325. }
  4326. const upb_handlers *upb_handlers_getsubhandlers_sel(const upb_handlers *h,
  4327. upb_selector_t sel) {
  4328. /* STARTSUBMSG selector in sel is the field's selector base. */
  4329. return SUBH(h, sel - UPB_STATIC_SELECTOR_COUNT);
  4330. }
  4331. const upb_msgdef *upb_handlers_msgdef(const upb_handlers *h) { return h->msg; }
  4332. bool upb_handlers_addcleanup(upb_handlers *h, void *p, upb_handlerfree *func) {
  4333. return upb_handlercache_addcleanup(h->cache, p, func);
  4334. }
  4335. upb_handlertype_t upb_handlers_getprimitivehandlertype(const upb_fielddef *f) {
  4336. switch (upb_fielddef_type(f)) {
  4337. case UPB_TYPE_INT32:
  4338. case UPB_TYPE_ENUM: return UPB_HANDLER_INT32;
  4339. case UPB_TYPE_INT64: return UPB_HANDLER_INT64;
  4340. case UPB_TYPE_UINT32: return UPB_HANDLER_UINT32;
  4341. case UPB_TYPE_UINT64: return UPB_HANDLER_UINT64;
  4342. case UPB_TYPE_FLOAT: return UPB_HANDLER_FLOAT;
  4343. case UPB_TYPE_DOUBLE: return UPB_HANDLER_DOUBLE;
  4344. case UPB_TYPE_BOOL: return UPB_HANDLER_BOOL;
  4345. default: UPB_ASSERT(false); return -1; /* Invalid input. */
  4346. }
  4347. }
  4348. bool upb_handlers_getselector(const upb_fielddef *f, upb_handlertype_t type,
  4349. upb_selector_t *s) {
  4350. uint32_t selector_base = upb_fielddef_selectorbase(f);
  4351. switch (type) {
  4352. case UPB_HANDLER_INT32:
  4353. case UPB_HANDLER_INT64:
  4354. case UPB_HANDLER_UINT32:
  4355. case UPB_HANDLER_UINT64:
  4356. case UPB_HANDLER_FLOAT:
  4357. case UPB_HANDLER_DOUBLE:
  4358. case UPB_HANDLER_BOOL:
  4359. if (!upb_fielddef_isprimitive(f) ||
  4360. upb_handlers_getprimitivehandlertype(f) != type)
  4361. return false;
  4362. *s = selector_base;
  4363. break;
  4364. case UPB_HANDLER_STRING:
  4365. if (upb_fielddef_isstring(f)) {
  4366. *s = selector_base;
  4367. } else if (upb_fielddef_lazy(f)) {
  4368. *s = selector_base + 3;
  4369. } else {
  4370. return false;
  4371. }
  4372. break;
  4373. case UPB_HANDLER_STARTSTR:
  4374. if (upb_fielddef_isstring(f) || upb_fielddef_lazy(f)) {
  4375. *s = selector_base + 1;
  4376. } else {
  4377. return false;
  4378. }
  4379. break;
  4380. case UPB_HANDLER_ENDSTR:
  4381. if (upb_fielddef_isstring(f) || upb_fielddef_lazy(f)) {
  4382. *s = selector_base + 2;
  4383. } else {
  4384. return false;
  4385. }
  4386. break;
  4387. case UPB_HANDLER_STARTSEQ:
  4388. if (!upb_fielddef_isseq(f)) return false;
  4389. *s = selector_base - 2;
  4390. break;
  4391. case UPB_HANDLER_ENDSEQ:
  4392. if (!upb_fielddef_isseq(f)) return false;
  4393. *s = selector_base - 1;
  4394. break;
  4395. case UPB_HANDLER_STARTSUBMSG:
  4396. if (!upb_fielddef_issubmsg(f)) return false;
  4397. /* Selectors for STARTSUBMSG are at the beginning of the table so that the
  4398. * selector can also be used as an index into the "sub" array of
  4399. * subhandlers. The indexes for the two into these two tables are the
  4400. * same, except that in the handler table the static selectors come first. */
  4401. *s = upb_fielddef_index(f) + UPB_STATIC_SELECTOR_COUNT;
  4402. break;
  4403. case UPB_HANDLER_ENDSUBMSG:
  4404. if (!upb_fielddef_issubmsg(f)) return false;
  4405. *s = selector_base;
  4406. break;
  4407. }
  4408. UPB_ASSERT((size_t)*s < upb_msgdef_selectorcount(upb_fielddef_containingtype(f)));
  4409. return true;
  4410. }
  4411. /* upb_handlercache ***********************************************************/
  4412. struct upb_handlercache {
  4413. upb_arena *arena;
  4414. upb_inttable tab; /* maps upb_msgdef* -> upb_handlers*. */
  4415. upb_handlers_callback *callback;
  4416. const void *closure;
  4417. };
  4418. const upb_handlers *upb_handlercache_get(upb_handlercache *c,
  4419. const upb_msgdef *md) {
  4420. upb_msg_field_iter i;
  4421. upb_value v;
  4422. upb_handlers *h;
  4423. if (upb_inttable_lookupptr(&c->tab, md, &v)) {
  4424. return upb_value_getptr(v);
  4425. }
  4426. h = upb_handlers_new(md, c, c->arena);
  4427. v = upb_value_ptr(h);
  4428. if (!h) return NULL;
  4429. if (!upb_inttable_insertptr(&c->tab, md, v)) return NULL;
  4430. c->callback(c->closure, h);
  4431. /* For each submessage field, get or create a handlers object and set it as
  4432. * the subhandlers. */
  4433. for(upb_msg_field_begin(&i, md);
  4434. !upb_msg_field_done(&i);
  4435. upb_msg_field_next(&i)) {
  4436. upb_fielddef *f = upb_msg_iter_field(&i);
  4437. if (upb_fielddef_issubmsg(f)) {
  4438. const upb_msgdef *subdef = upb_fielddef_msgsubdef(f);
  4439. const upb_handlers *sub_mh = upb_handlercache_get(c, subdef);
  4440. if (!sub_mh) return NULL;
  4441. upb_handlers_setsubhandlers(h, f, sub_mh);
  4442. }
  4443. }
  4444. return h;
  4445. }
  4446. upb_handlercache *upb_handlercache_new(upb_handlers_callback *callback,
  4447. const void *closure) {
  4448. upb_handlercache *cache = upb_gmalloc(sizeof(*cache));
  4449. if (!cache) return NULL;
  4450. cache->arena = upb_arena_new();
  4451. cache->callback = callback;
  4452. cache->closure = closure;
  4453. if (!upb_inttable_init(&cache->tab, UPB_CTYPE_PTR)) goto oom;
  4454. return cache;
  4455. oom:
  4456. upb_gfree(cache);
  4457. return NULL;
  4458. }
  4459. void upb_handlercache_free(upb_handlercache *cache) {
  4460. upb_inttable_uninit(&cache->tab);
  4461. upb_arena_free(cache->arena);
  4462. upb_gfree(cache);
  4463. }
  4464. bool upb_handlercache_addcleanup(upb_handlercache *c, void *p,
  4465. upb_handlerfree *func) {
  4466. return upb_arena_addcleanup(c->arena, p, func);
  4467. }
  4468. /* upb_byteshandler ***********************************************************/
  4469. bool upb_byteshandler_setstartstr(upb_byteshandler *h,
  4470. upb_startstr_handlerfunc *func, void *d) {
  4471. h->table[UPB_STARTSTR_SELECTOR].func = (upb_func*)func;
  4472. h->table[UPB_STARTSTR_SELECTOR].attr.handler_data = d;
  4473. return true;
  4474. }
  4475. bool upb_byteshandler_setstring(upb_byteshandler *h,
  4476. upb_string_handlerfunc *func, void *d) {
  4477. h->table[UPB_STRING_SELECTOR].func = (upb_func*)func;
  4478. h->table[UPB_STRING_SELECTOR].attr.handler_data = d;
  4479. return true;
  4480. }
  4481. bool upb_byteshandler_setendstr(upb_byteshandler *h,
  4482. upb_endfield_handlerfunc *func, void *d) {
  4483. h->table[UPB_ENDSTR_SELECTOR].func = (upb_func*)func;
  4484. h->table[UPB_ENDSTR_SELECTOR].attr.handler_data = d;
  4485. return true;
  4486. }
  4487. /** Handlers for upb_msg ******************************************************/
  4488. typedef struct {
  4489. size_t offset;
  4490. int32_t hasbit;
  4491. } upb_msg_handlerdata;
  4492. /* Fallback implementation if the handler is not specialized by the producer. */
  4493. #define MSG_WRITER(type, ctype) \
  4494. bool upb_msg_set ## type (void *c, const void *hd, ctype val) { \
  4495. uint8_t *m = c; \
  4496. const upb_msg_handlerdata *d = hd; \
  4497. if (d->hasbit > 0) \
  4498. *(uint8_t*)&m[d->hasbit / 8] |= 1 << (d->hasbit % 8); \
  4499. *(ctype*)&m[d->offset] = val; \
  4500. return true; \
  4501. } \
  4502. MSG_WRITER(double, double)
  4503. MSG_WRITER(float, float)
  4504. MSG_WRITER(int32, int32_t)
  4505. MSG_WRITER(int64, int64_t)
  4506. MSG_WRITER(uint32, uint32_t)
  4507. MSG_WRITER(uint64, uint64_t)
  4508. MSG_WRITER(bool, bool)
  4509. bool upb_msg_setscalarhandler(upb_handlers *h, const upb_fielddef *f,
  4510. size_t offset, int32_t hasbit) {
  4511. upb_handlerattr attr = UPB_HANDLERATTR_INIT;
  4512. bool ok;
  4513. upb_msg_handlerdata *d = upb_gmalloc(sizeof(*d));
  4514. if (!d) return false;
  4515. d->offset = offset;
  4516. d->hasbit = hasbit;
  4517. attr.handler_data = d;
  4518. attr.alwaysok = true;
  4519. upb_handlers_addcleanup(h, d, upb_gfree);
  4520. #define TYPE(u, l) \
  4521. case UPB_TYPE_##u: \
  4522. ok = upb_handlers_set##l(h, f, upb_msg_set##l, &attr); break;
  4523. ok = false;
  4524. switch (upb_fielddef_type(f)) {
  4525. TYPE(INT64, int64);
  4526. TYPE(INT32, int32);
  4527. TYPE(ENUM, int32);
  4528. TYPE(UINT64, uint64);
  4529. TYPE(UINT32, uint32);
  4530. TYPE(DOUBLE, double);
  4531. TYPE(FLOAT, float);
  4532. TYPE(BOOL, bool);
  4533. default: UPB_ASSERT(false); break;
  4534. }
  4535. #undef TYPE
  4536. return ok;
  4537. }
  4538. bool upb_msg_getscalarhandlerdata(const upb_handlers *h,
  4539. upb_selector_t s,
  4540. upb_fieldtype_t *type,
  4541. size_t *offset,
  4542. int32_t *hasbit) {
  4543. const upb_msg_handlerdata *d;
  4544. const void *p;
  4545. upb_func *f = upb_handlers_gethandler(h, s, &p);
  4546. if ((upb_int64_handlerfunc*)f == upb_msg_setint64) {
  4547. *type = UPB_TYPE_INT64;
  4548. } else if ((upb_int32_handlerfunc*)f == upb_msg_setint32) {
  4549. *type = UPB_TYPE_INT32;
  4550. } else if ((upb_uint64_handlerfunc*)f == upb_msg_setuint64) {
  4551. *type = UPB_TYPE_UINT64;
  4552. } else if ((upb_uint32_handlerfunc*)f == upb_msg_setuint32) {
  4553. *type = UPB_TYPE_UINT32;
  4554. } else if ((upb_double_handlerfunc*)f == upb_msg_setdouble) {
  4555. *type = UPB_TYPE_DOUBLE;
  4556. } else if ((upb_float_handlerfunc*)f == upb_msg_setfloat) {
  4557. *type = UPB_TYPE_FLOAT;
  4558. } else if ((upb_bool_handlerfunc*)f == upb_msg_setbool) {
  4559. *type = UPB_TYPE_BOOL;
  4560. } else {
  4561. return false;
  4562. }
  4563. d = p;
  4564. *offset = d->offset;
  4565. *hasbit = d->hasbit;
  4566. return true;
  4567. }
  4568. bool upb_bufsrc_putbuf(const char *buf, size_t len, upb_bytessink sink) {
  4569. void *subc;
  4570. bool ret;
  4571. upb_bufhandle handle = UPB_BUFHANDLE_INIT;
  4572. handle.buf = buf;
  4573. ret = upb_bytessink_start(sink, len, &subc);
  4574. if (ret && len != 0) {
  4575. ret = (upb_bytessink_putbuf(sink, subc, buf, len, &handle) >= len);
  4576. }
  4577. if (ret) {
  4578. ret = upb_bytessink_end(sink);
  4579. }
  4580. return ret;
  4581. }
  4582. /*
  4583. ** protobuf decoder bytecode compiler
  4584. **
  4585. ** Code to compile a upb::Handlers into bytecode for decoding a protobuf
  4586. ** according to that specific schema and destination handlers.
  4587. **
  4588. ** Bytecode definition is in decoder.int.h.
  4589. */
  4590. #include <stdarg.h>
  4591. #ifdef UPB_DUMP_BYTECODE
  4592. #include <stdio.h>
  4593. #endif
  4594. #define MAXLABEL 5
  4595. #define EMPTYLABEL -1
  4596. /* upb_pbdecodermethod ********************************************************/
  4597. static void freemethod(upb_pbdecodermethod *method) {
  4598. upb_inttable_uninit(&method->dispatch);
  4599. upb_gfree(method);
  4600. }
  4601. static upb_pbdecodermethod *newmethod(const upb_handlers *dest_handlers,
  4602. mgroup *group) {
  4603. upb_pbdecodermethod *ret = upb_gmalloc(sizeof(*ret));
  4604. upb_byteshandler_init(&ret->input_handler_);
  4605. ret->group = group;
  4606. ret->dest_handlers_ = dest_handlers;
  4607. upb_inttable_init(&ret->dispatch, UPB_CTYPE_UINT64);
  4608. return ret;
  4609. }
  4610. const upb_handlers *upb_pbdecodermethod_desthandlers(
  4611. const upb_pbdecodermethod *m) {
  4612. return m->dest_handlers_;
  4613. }
  4614. const upb_byteshandler *upb_pbdecodermethod_inputhandler(
  4615. const upb_pbdecodermethod *m) {
  4616. return &m->input_handler_;
  4617. }
  4618. bool upb_pbdecodermethod_isnative(const upb_pbdecodermethod *m) {
  4619. return m->is_native_;
  4620. }
  4621. /* mgroup *********************************************************************/
  4622. static void freegroup(mgroup *g) {
  4623. upb_inttable_iter i;
  4624. upb_inttable_begin(&i, &g->methods);
  4625. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  4626. freemethod(upb_value_getptr(upb_inttable_iter_value(&i)));
  4627. }
  4628. upb_inttable_uninit(&g->methods);
  4629. upb_gfree(g->bytecode);
  4630. upb_gfree(g);
  4631. }
  4632. mgroup *newgroup(void) {
  4633. mgroup *g = upb_gmalloc(sizeof(*g));
  4634. upb_inttable_init(&g->methods, UPB_CTYPE_PTR);
  4635. g->bytecode = NULL;
  4636. g->bytecode_end = NULL;
  4637. return g;
  4638. }
  4639. /* bytecode compiler **********************************************************/
  4640. /* Data used only at compilation time. */
  4641. typedef struct {
  4642. mgroup *group;
  4643. uint32_t *pc;
  4644. int fwd_labels[MAXLABEL];
  4645. int back_labels[MAXLABEL];
  4646. /* For fields marked "lazy", parse them lazily or eagerly? */
  4647. bool lazy;
  4648. } compiler;
  4649. static compiler *newcompiler(mgroup *group, bool lazy) {
  4650. compiler *ret = upb_gmalloc(sizeof(*ret));
  4651. int i;
  4652. ret->group = group;
  4653. ret->lazy = lazy;
  4654. for (i = 0; i < MAXLABEL; i++) {
  4655. ret->fwd_labels[i] = EMPTYLABEL;
  4656. ret->back_labels[i] = EMPTYLABEL;
  4657. }
  4658. return ret;
  4659. }
  4660. static void freecompiler(compiler *c) {
  4661. upb_gfree(c);
  4662. }
  4663. const size_t ptr_words = sizeof(void*) / sizeof(uint32_t);
  4664. /* How many words an instruction is. */
  4665. static int instruction_len(uint32_t instr) {
  4666. switch (getop(instr)) {
  4667. case OP_SETDISPATCH: return 1 + ptr_words;
  4668. case OP_TAGN: return 3;
  4669. case OP_SETBIGGROUPNUM: return 2;
  4670. default: return 1;
  4671. }
  4672. }
  4673. bool op_has_longofs(int32_t instruction) {
  4674. switch (getop(instruction)) {
  4675. case OP_CALL:
  4676. case OP_BRANCH:
  4677. case OP_CHECKDELIM:
  4678. return true;
  4679. /* The "tag" instructions only have 8 bytes available for the jump target,
  4680. * but that is ok because these opcodes only require short jumps. */
  4681. case OP_TAG1:
  4682. case OP_TAG2:
  4683. case OP_TAGN:
  4684. return false;
  4685. default:
  4686. UPB_ASSERT(false);
  4687. return false;
  4688. }
  4689. }
  4690. static int32_t getofs(uint32_t instruction) {
  4691. if (op_has_longofs(instruction)) {
  4692. return (int32_t)instruction >> 8;
  4693. } else {
  4694. return (int8_t)(instruction >> 8);
  4695. }
  4696. }
  4697. static void setofs(uint32_t *instruction, int32_t ofs) {
  4698. if (op_has_longofs(*instruction)) {
  4699. *instruction = getop(*instruction) | (uint32_t)ofs << 8;
  4700. } else {
  4701. *instruction = (*instruction & ~0xff00) | ((ofs & 0xff) << 8);
  4702. }
  4703. UPB_ASSERT(getofs(*instruction) == ofs); /* Would fail in cases of overflow. */
  4704. }
  4705. static uint32_t pcofs(compiler *c) { return c->pc - c->group->bytecode; }
  4706. /* Defines a local label at the current PC location. All previous forward
  4707. * references are updated to point to this location. The location is noted
  4708. * for any future backward references. */
  4709. static void label(compiler *c, unsigned int label) {
  4710. int val;
  4711. uint32_t *codep;
  4712. UPB_ASSERT(label < MAXLABEL);
  4713. val = c->fwd_labels[label];
  4714. codep = (val == EMPTYLABEL) ? NULL : c->group->bytecode + val;
  4715. while (codep) {
  4716. int ofs = getofs(*codep);
  4717. setofs(codep, c->pc - codep - instruction_len(*codep));
  4718. codep = ofs ? codep + ofs : NULL;
  4719. }
  4720. c->fwd_labels[label] = EMPTYLABEL;
  4721. c->back_labels[label] = pcofs(c);
  4722. }
  4723. /* Creates a reference to a numbered label; either a forward reference
  4724. * (positive arg) or backward reference (negative arg). For forward references
  4725. * the value returned now is actually a "next" pointer into a linked list of all
  4726. * instructions that use this label and will be patched later when the label is
  4727. * defined with label().
  4728. *
  4729. * The returned value is the offset that should be written into the instruction.
  4730. */
  4731. static int32_t labelref(compiler *c, int label) {
  4732. UPB_ASSERT(label < MAXLABEL);
  4733. if (label == LABEL_DISPATCH) {
  4734. /* No resolving required. */
  4735. return 0;
  4736. } else if (label < 0) {
  4737. /* Backward local label. Relative to the next instruction. */
  4738. uint32_t from = (c->pc + 1) - c->group->bytecode;
  4739. return c->back_labels[-label] - from;
  4740. } else {
  4741. /* Forward local label: prepend to (possibly-empty) linked list. */
  4742. int *lptr = &c->fwd_labels[label];
  4743. int32_t ret = (*lptr == EMPTYLABEL) ? 0 : *lptr - pcofs(c);
  4744. *lptr = pcofs(c);
  4745. return ret;
  4746. }
  4747. }
  4748. static void put32(compiler *c, uint32_t v) {
  4749. mgroup *g = c->group;
  4750. if (c->pc == g->bytecode_end) {
  4751. int ofs = pcofs(c);
  4752. size_t oldsize = g->bytecode_end - g->bytecode;
  4753. size_t newsize = UPB_MAX(oldsize * 2, 64);
  4754. /* TODO(haberman): handle OOM. */
  4755. g->bytecode = upb_grealloc(g->bytecode, oldsize * sizeof(uint32_t),
  4756. newsize * sizeof(uint32_t));
  4757. g->bytecode_end = g->bytecode + newsize;
  4758. c->pc = g->bytecode + ofs;
  4759. }
  4760. *c->pc++ = v;
  4761. }
  4762. static void putop(compiler *c, int op, ...) {
  4763. va_list ap;
  4764. va_start(ap, op);
  4765. switch (op) {
  4766. case OP_SETDISPATCH: {
  4767. uintptr_t ptr = (uintptr_t)va_arg(ap, void*);
  4768. put32(c, OP_SETDISPATCH);
  4769. put32(c, ptr);
  4770. if (sizeof(uintptr_t) > sizeof(uint32_t))
  4771. put32(c, (uint64_t)ptr >> 32);
  4772. break;
  4773. }
  4774. case OP_STARTMSG:
  4775. case OP_ENDMSG:
  4776. case OP_PUSHLENDELIM:
  4777. case OP_POP:
  4778. case OP_SETDELIM:
  4779. case OP_HALT:
  4780. case OP_RET:
  4781. case OP_DISPATCH:
  4782. put32(c, op);
  4783. break;
  4784. case OP_PARSE_DOUBLE:
  4785. case OP_PARSE_FLOAT:
  4786. case OP_PARSE_INT64:
  4787. case OP_PARSE_UINT64:
  4788. case OP_PARSE_INT32:
  4789. case OP_PARSE_FIXED64:
  4790. case OP_PARSE_FIXED32:
  4791. case OP_PARSE_BOOL:
  4792. case OP_PARSE_UINT32:
  4793. case OP_PARSE_SFIXED32:
  4794. case OP_PARSE_SFIXED64:
  4795. case OP_PARSE_SINT32:
  4796. case OP_PARSE_SINT64:
  4797. case OP_STARTSEQ:
  4798. case OP_ENDSEQ:
  4799. case OP_STARTSUBMSG:
  4800. case OP_ENDSUBMSG:
  4801. case OP_STARTSTR:
  4802. case OP_STRING:
  4803. case OP_ENDSTR:
  4804. case OP_PUSHTAGDELIM:
  4805. put32(c, op | va_arg(ap, upb_selector_t) << 8);
  4806. break;
  4807. case OP_SETBIGGROUPNUM:
  4808. put32(c, op);
  4809. put32(c, va_arg(ap, int));
  4810. break;
  4811. case OP_CALL: {
  4812. const upb_pbdecodermethod *method = va_arg(ap, upb_pbdecodermethod *);
  4813. put32(c, op | (method->code_base.ofs - (pcofs(c) + 1)) << 8);
  4814. break;
  4815. }
  4816. case OP_CHECKDELIM:
  4817. case OP_BRANCH: {
  4818. uint32_t instruction = op;
  4819. int label = va_arg(ap, int);
  4820. setofs(&instruction, labelref(c, label));
  4821. put32(c, instruction);
  4822. break;
  4823. }
  4824. case OP_TAG1:
  4825. case OP_TAG2: {
  4826. int label = va_arg(ap, int);
  4827. uint64_t tag = va_arg(ap, uint64_t);
  4828. uint32_t instruction = op | (tag << 16);
  4829. UPB_ASSERT(tag <= 0xffff);
  4830. setofs(&instruction, labelref(c, label));
  4831. put32(c, instruction);
  4832. break;
  4833. }
  4834. case OP_TAGN: {
  4835. int label = va_arg(ap, int);
  4836. uint64_t tag = va_arg(ap, uint64_t);
  4837. uint32_t instruction = op | (upb_value_size(tag) << 16);
  4838. setofs(&instruction, labelref(c, label));
  4839. put32(c, instruction);
  4840. put32(c, tag);
  4841. put32(c, tag >> 32);
  4842. break;
  4843. }
  4844. }
  4845. va_end(ap);
  4846. }
  4847. #if defined(UPB_DUMP_BYTECODE)
  4848. const char *upb_pbdecoder_getopname(unsigned int op) {
  4849. #define QUOTE(x) #x
  4850. #define EXPAND_AND_QUOTE(x) QUOTE(x)
  4851. #define OPNAME(x) OP_##x
  4852. #define OP(x) case OPNAME(x): return EXPAND_AND_QUOTE(OPNAME(x));
  4853. #define T(x) OP(PARSE_##x)
  4854. /* Keep in sync with list in decoder.int.h. */
  4855. switch ((opcode)op) {
  4856. T(DOUBLE) T(FLOAT) T(INT64) T(UINT64) T(INT32) T(FIXED64) T(FIXED32)
  4857. T(BOOL) T(UINT32) T(SFIXED32) T(SFIXED64) T(SINT32) T(SINT64)
  4858. OP(STARTMSG) OP(ENDMSG) OP(STARTSEQ) OP(ENDSEQ) OP(STARTSUBMSG)
  4859. OP(ENDSUBMSG) OP(STARTSTR) OP(STRING) OP(ENDSTR) OP(CALL) OP(RET)
  4860. OP(PUSHLENDELIM) OP(PUSHTAGDELIM) OP(SETDELIM) OP(CHECKDELIM)
  4861. OP(BRANCH) OP(TAG1) OP(TAG2) OP(TAGN) OP(SETDISPATCH) OP(POP)
  4862. OP(SETBIGGROUPNUM) OP(DISPATCH) OP(HALT)
  4863. }
  4864. return "<unknown op>";
  4865. #undef OP
  4866. #undef T
  4867. }
  4868. #endif
  4869. #ifdef UPB_DUMP_BYTECODE
  4870. static void dumpbc(uint32_t *p, uint32_t *end, FILE *f) {
  4871. uint32_t *begin = p;
  4872. while (p < end) {
  4873. fprintf(f, "%p %8tx", p, p - begin);
  4874. uint32_t instr = *p++;
  4875. uint8_t op = getop(instr);
  4876. fprintf(f, " %s", upb_pbdecoder_getopname(op));
  4877. switch ((opcode)op) {
  4878. case OP_SETDISPATCH: {
  4879. const upb_inttable *dispatch;
  4880. memcpy(&dispatch, p, sizeof(void*));
  4881. p += ptr_words;
  4882. const upb_pbdecodermethod *method =
  4883. (void *)((char *)dispatch -
  4884. offsetof(upb_pbdecodermethod, dispatch));
  4885. fprintf(f, " %s", upb_msgdef_fullname(
  4886. upb_handlers_msgdef(method->dest_handlers_)));
  4887. break;
  4888. }
  4889. case OP_DISPATCH:
  4890. case OP_STARTMSG:
  4891. case OP_ENDMSG:
  4892. case OP_PUSHLENDELIM:
  4893. case OP_POP:
  4894. case OP_SETDELIM:
  4895. case OP_HALT:
  4896. case OP_RET:
  4897. break;
  4898. case OP_PARSE_DOUBLE:
  4899. case OP_PARSE_FLOAT:
  4900. case OP_PARSE_INT64:
  4901. case OP_PARSE_UINT64:
  4902. case OP_PARSE_INT32:
  4903. case OP_PARSE_FIXED64:
  4904. case OP_PARSE_FIXED32:
  4905. case OP_PARSE_BOOL:
  4906. case OP_PARSE_UINT32:
  4907. case OP_PARSE_SFIXED32:
  4908. case OP_PARSE_SFIXED64:
  4909. case OP_PARSE_SINT32:
  4910. case OP_PARSE_SINT64:
  4911. case OP_STARTSEQ:
  4912. case OP_ENDSEQ:
  4913. case OP_STARTSUBMSG:
  4914. case OP_ENDSUBMSG:
  4915. case OP_STARTSTR:
  4916. case OP_STRING:
  4917. case OP_ENDSTR:
  4918. case OP_PUSHTAGDELIM:
  4919. fprintf(f, " %d", instr >> 8);
  4920. break;
  4921. case OP_SETBIGGROUPNUM:
  4922. fprintf(f, " %d", *p++);
  4923. break;
  4924. case OP_CHECKDELIM:
  4925. case OP_CALL:
  4926. case OP_BRANCH:
  4927. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  4928. break;
  4929. case OP_TAG1:
  4930. case OP_TAG2: {
  4931. fprintf(f, " tag:0x%x", instr >> 16);
  4932. if (getofs(instr)) {
  4933. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  4934. }
  4935. break;
  4936. }
  4937. case OP_TAGN: {
  4938. uint64_t tag = *p++;
  4939. tag |= (uint64_t)*p++ << 32;
  4940. fprintf(f, " tag:0x%llx", (long long)tag);
  4941. fprintf(f, " n:%d", instr >> 16);
  4942. if (getofs(instr)) {
  4943. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  4944. }
  4945. break;
  4946. }
  4947. }
  4948. fputs("\n", f);
  4949. }
  4950. }
  4951. #endif
  4952. static uint64_t get_encoded_tag(const upb_fielddef *f, int wire_type) {
  4953. uint32_t tag = (upb_fielddef_number(f) << 3) | wire_type;
  4954. uint64_t encoded_tag = upb_vencode32(tag);
  4955. /* No tag should be greater than 5 bytes. */
  4956. UPB_ASSERT(encoded_tag <= 0xffffffffff);
  4957. return encoded_tag;
  4958. }
  4959. static void putchecktag(compiler *c, const upb_fielddef *f,
  4960. int wire_type, int dest) {
  4961. uint64_t tag = get_encoded_tag(f, wire_type);
  4962. switch (upb_value_size(tag)) {
  4963. case 1:
  4964. putop(c, OP_TAG1, dest, tag);
  4965. break;
  4966. case 2:
  4967. putop(c, OP_TAG2, dest, tag);
  4968. break;
  4969. default:
  4970. putop(c, OP_TAGN, dest, tag);
  4971. break;
  4972. }
  4973. }
  4974. static upb_selector_t getsel(const upb_fielddef *f, upb_handlertype_t type) {
  4975. upb_selector_t selector;
  4976. bool ok = upb_handlers_getselector(f, type, &selector);
  4977. UPB_ASSERT(ok);
  4978. return selector;
  4979. }
  4980. /* Takes an existing, primary dispatch table entry and repacks it with a
  4981. * different alternate wire type. Called when we are inserting a secondary
  4982. * dispatch table entry for an alternate wire type. */
  4983. static uint64_t repack(uint64_t dispatch, int new_wt2) {
  4984. uint64_t ofs;
  4985. uint8_t wt1;
  4986. uint8_t old_wt2;
  4987. upb_pbdecoder_unpackdispatch(dispatch, &ofs, &wt1, &old_wt2);
  4988. UPB_ASSERT(old_wt2 == NO_WIRE_TYPE); /* wt2 should not be set yet. */
  4989. return upb_pbdecoder_packdispatch(ofs, wt1, new_wt2);
  4990. }
  4991. /* Marks the current bytecode position as the dispatch target for this message,
  4992. * field, and wire type. */
  4993. static void dispatchtarget(compiler *c, upb_pbdecodermethod *method,
  4994. const upb_fielddef *f, int wire_type) {
  4995. /* Offset is relative to msg base. */
  4996. uint64_t ofs = pcofs(c) - method->code_base.ofs;
  4997. uint32_t fn = upb_fielddef_number(f);
  4998. upb_inttable *d = &method->dispatch;
  4999. upb_value v;
  5000. if (upb_inttable_remove(d, fn, &v)) {
  5001. /* TODO: prioritize based on packed setting in .proto file. */
  5002. uint64_t repacked = repack(upb_value_getuint64(v), wire_type);
  5003. upb_inttable_insert(d, fn, upb_value_uint64(repacked));
  5004. upb_inttable_insert(d, fn + UPB_MAX_FIELDNUMBER, upb_value_uint64(ofs));
  5005. } else {
  5006. uint64_t val = upb_pbdecoder_packdispatch(ofs, wire_type, NO_WIRE_TYPE);
  5007. upb_inttable_insert(d, fn, upb_value_uint64(val));
  5008. }
  5009. }
  5010. static void putpush(compiler *c, const upb_fielddef *f) {
  5011. if (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE) {
  5012. putop(c, OP_PUSHLENDELIM);
  5013. } else {
  5014. uint32_t fn = upb_fielddef_number(f);
  5015. if (fn >= 1 << 24) {
  5016. putop(c, OP_PUSHTAGDELIM, 0);
  5017. putop(c, OP_SETBIGGROUPNUM, fn);
  5018. } else {
  5019. putop(c, OP_PUSHTAGDELIM, fn);
  5020. }
  5021. }
  5022. }
  5023. static upb_pbdecodermethod *find_submethod(const compiler *c,
  5024. const upb_pbdecodermethod *method,
  5025. const upb_fielddef *f) {
  5026. const upb_handlers *sub =
  5027. upb_handlers_getsubhandlers(method->dest_handlers_, f);
  5028. upb_value v;
  5029. return upb_inttable_lookupptr(&c->group->methods, sub, &v)
  5030. ? upb_value_getptr(v)
  5031. : NULL;
  5032. }
  5033. static void putsel(compiler *c, opcode op, upb_selector_t sel,
  5034. const upb_handlers *h) {
  5035. if (upb_handlers_gethandler(h, sel, NULL)) {
  5036. putop(c, op, sel);
  5037. }
  5038. }
  5039. /* Puts an opcode to call a callback, but only if a callback actually exists for
  5040. * this field and handler type. */
  5041. static void maybeput(compiler *c, opcode op, const upb_handlers *h,
  5042. const upb_fielddef *f, upb_handlertype_t type) {
  5043. putsel(c, op, getsel(f, type), h);
  5044. }
  5045. static bool haslazyhandlers(const upb_handlers *h, const upb_fielddef *f) {
  5046. if (!upb_fielddef_lazy(f))
  5047. return false;
  5048. return upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STARTSTR), NULL) ||
  5049. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STRING), NULL) ||
  5050. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_ENDSTR), NULL);
  5051. }
  5052. /* bytecode compiler code generation ******************************************/
  5053. /* Symbolic names for our local labels. */
  5054. #define LABEL_LOOPSTART 1 /* Top of a repeated field loop. */
  5055. #define LABEL_LOOPBREAK 2 /* To jump out of a repeated loop */
  5056. #define LABEL_FIELD 3 /* Jump backward to find the most recent field. */
  5057. #define LABEL_ENDMSG 4 /* To reach the OP_ENDMSG instr for this msg. */
  5058. /* Generates bytecode to parse a single non-lazy message field. */
  5059. static void generate_msgfield(compiler *c, const upb_fielddef *f,
  5060. upb_pbdecodermethod *method) {
  5061. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  5062. const upb_pbdecodermethod *sub_m = find_submethod(c, method, f);
  5063. int wire_type;
  5064. if (!sub_m) {
  5065. /* Don't emit any code for this field at all; it will be parsed as an
  5066. * unknown field.
  5067. *
  5068. * TODO(haberman): we should change this to parse it as a string field
  5069. * instead. It will probably be faster, but more importantly, once we
  5070. * start vending unknown fields, a field shouldn't be treated as unknown
  5071. * just because it doesn't have subhandlers registered. */
  5072. return;
  5073. }
  5074. label(c, LABEL_FIELD);
  5075. wire_type =
  5076. (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE)
  5077. ? UPB_WIRE_TYPE_DELIMITED
  5078. : UPB_WIRE_TYPE_START_GROUP;
  5079. if (upb_fielddef_isseq(f)) {
  5080. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5081. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  5082. dispatchtarget(c, method, f, wire_type);
  5083. putop(c, OP_PUSHTAGDELIM, 0);
  5084. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  5085. label(c, LABEL_LOOPSTART);
  5086. putpush(c, f);
  5087. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  5088. putop(c, OP_CALL, sub_m);
  5089. putop(c, OP_POP);
  5090. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  5091. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  5092. putop(c, OP_SETDELIM);
  5093. }
  5094. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5095. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  5096. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5097. label(c, LABEL_LOOPBREAK);
  5098. putop(c, OP_POP);
  5099. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  5100. } else {
  5101. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5102. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  5103. dispatchtarget(c, method, f, wire_type);
  5104. putpush(c, f);
  5105. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  5106. putop(c, OP_CALL, sub_m);
  5107. putop(c, OP_POP);
  5108. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  5109. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  5110. putop(c, OP_SETDELIM);
  5111. }
  5112. }
  5113. }
  5114. /* Generates bytecode to parse a single string or lazy submessage field. */
  5115. static void generate_delimfield(compiler *c, const upb_fielddef *f,
  5116. upb_pbdecodermethod *method) {
  5117. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  5118. label(c, LABEL_FIELD);
  5119. if (upb_fielddef_isseq(f)) {
  5120. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5121. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  5122. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  5123. putop(c, OP_PUSHTAGDELIM, 0);
  5124. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  5125. label(c, LABEL_LOOPSTART);
  5126. putop(c, OP_PUSHLENDELIM);
  5127. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  5128. /* Need to emit even if no handler to skip past the string. */
  5129. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  5130. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  5131. putop(c, OP_POP);
  5132. putop(c, OP_SETDELIM);
  5133. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5134. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_LOOPBREAK);
  5135. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5136. label(c, LABEL_LOOPBREAK);
  5137. putop(c, OP_POP);
  5138. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  5139. } else {
  5140. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5141. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  5142. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  5143. putop(c, OP_PUSHLENDELIM);
  5144. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  5145. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  5146. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  5147. putop(c, OP_POP);
  5148. putop(c, OP_SETDELIM);
  5149. }
  5150. }
  5151. /* Generates bytecode to parse a single primitive field. */
  5152. static void generate_primitivefield(compiler *c, const upb_fielddef *f,
  5153. upb_pbdecodermethod *method) {
  5154. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  5155. upb_descriptortype_t descriptor_type = upb_fielddef_descriptortype(f);
  5156. opcode parse_type;
  5157. upb_selector_t sel;
  5158. int wire_type;
  5159. label(c, LABEL_FIELD);
  5160. /* From a decoding perspective, ENUM is the same as INT32. */
  5161. if (descriptor_type == UPB_DESCRIPTOR_TYPE_ENUM)
  5162. descriptor_type = UPB_DESCRIPTOR_TYPE_INT32;
  5163. parse_type = (opcode)descriptor_type;
  5164. /* TODO(haberman): generate packed or non-packed first depending on "packed"
  5165. * setting in the fielddef. This will favor (in speed) whichever was
  5166. * specified. */
  5167. UPB_ASSERT((int)parse_type >= 0 && parse_type <= OP_MAX);
  5168. sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  5169. wire_type = upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  5170. if (upb_fielddef_isseq(f)) {
  5171. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5172. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  5173. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  5174. putop(c, OP_PUSHLENDELIM);
  5175. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); /* Packed */
  5176. label(c, LABEL_LOOPSTART);
  5177. putop(c, parse_type, sel);
  5178. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5179. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5180. dispatchtarget(c, method, f, wire_type);
  5181. putop(c, OP_PUSHTAGDELIM, 0);
  5182. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); /* Non-packed */
  5183. label(c, LABEL_LOOPSTART);
  5184. putop(c, parse_type, sel);
  5185. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5186. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  5187. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5188. label(c, LABEL_LOOPBREAK);
  5189. putop(c, OP_POP); /* Packed and non-packed join. */
  5190. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  5191. putop(c, OP_SETDELIM); /* Could remove for non-packed by dup ENDSEQ. */
  5192. } else {
  5193. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5194. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  5195. dispatchtarget(c, method, f, wire_type);
  5196. putop(c, parse_type, sel);
  5197. }
  5198. }
  5199. /* Adds bytecode for parsing the given message to the given decoderplan,
  5200. * while adding all dispatch targets to this message's dispatch table. */
  5201. static void compile_method(compiler *c, upb_pbdecodermethod *method) {
  5202. const upb_handlers *h;
  5203. const upb_msgdef *md;
  5204. uint32_t* start_pc;
  5205. upb_msg_field_iter i;
  5206. upb_value val;
  5207. UPB_ASSERT(method);
  5208. /* Clear all entries in the dispatch table. */
  5209. upb_inttable_uninit(&method->dispatch);
  5210. upb_inttable_init(&method->dispatch, UPB_CTYPE_UINT64);
  5211. h = upb_pbdecodermethod_desthandlers(method);
  5212. md = upb_handlers_msgdef(h);
  5213. method->code_base.ofs = pcofs(c);
  5214. putop(c, OP_SETDISPATCH, &method->dispatch);
  5215. putsel(c, OP_STARTMSG, UPB_STARTMSG_SELECTOR, h);
  5216. label(c, LABEL_FIELD);
  5217. start_pc = c->pc;
  5218. for(upb_msg_field_begin(&i, md);
  5219. !upb_msg_field_done(&i);
  5220. upb_msg_field_next(&i)) {
  5221. const upb_fielddef *f = upb_msg_iter_field(&i);
  5222. upb_fieldtype_t type = upb_fielddef_type(f);
  5223. if (type == UPB_TYPE_MESSAGE && !(haslazyhandlers(h, f) && c->lazy)) {
  5224. generate_msgfield(c, f, method);
  5225. } else if (type == UPB_TYPE_STRING || type == UPB_TYPE_BYTES ||
  5226. type == UPB_TYPE_MESSAGE) {
  5227. generate_delimfield(c, f, method);
  5228. } else {
  5229. generate_primitivefield(c, f, method);
  5230. }
  5231. }
  5232. /* If there were no fields, or if no handlers were defined, we need to
  5233. * generate a non-empty loop body so that we can at least dispatch for unknown
  5234. * fields and check for the end of the message. */
  5235. if (c->pc == start_pc) {
  5236. /* Check for end-of-message. */
  5237. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5238. /* Unconditionally dispatch. */
  5239. putop(c, OP_DISPATCH, 0);
  5240. }
  5241. /* For now we just loop back to the last field of the message (or if none,
  5242. * the DISPATCH opcode for the message). */
  5243. putop(c, OP_BRANCH, -LABEL_FIELD);
  5244. /* Insert both a label and a dispatch table entry for this end-of-msg. */
  5245. label(c, LABEL_ENDMSG);
  5246. val = upb_value_uint64(pcofs(c) - method->code_base.ofs);
  5247. upb_inttable_insert(&method->dispatch, DISPATCH_ENDMSG, val);
  5248. putsel(c, OP_ENDMSG, UPB_ENDMSG_SELECTOR, h);
  5249. putop(c, OP_RET);
  5250. upb_inttable_compact(&method->dispatch);
  5251. }
  5252. /* Populate "methods" with new upb_pbdecodermethod objects reachable from "h".
  5253. * Returns the method for these handlers.
  5254. *
  5255. * Generates a new method for every destination handlers reachable from "h". */
  5256. static void find_methods(compiler *c, const upb_handlers *h) {
  5257. upb_value v;
  5258. upb_msg_field_iter i;
  5259. const upb_msgdef *md;
  5260. upb_pbdecodermethod *method;
  5261. if (upb_inttable_lookupptr(&c->group->methods, h, &v))
  5262. return;
  5263. method = newmethod(h, c->group);
  5264. upb_inttable_insertptr(&c->group->methods, h, upb_value_ptr(method));
  5265. /* Find submethods. */
  5266. md = upb_handlers_msgdef(h);
  5267. for(upb_msg_field_begin(&i, md);
  5268. !upb_msg_field_done(&i);
  5269. upb_msg_field_next(&i)) {
  5270. const upb_fielddef *f = upb_msg_iter_field(&i);
  5271. const upb_handlers *sub_h;
  5272. if (upb_fielddef_type(f) == UPB_TYPE_MESSAGE &&
  5273. (sub_h = upb_handlers_getsubhandlers(h, f)) != NULL) {
  5274. /* We only generate a decoder method for submessages with handlers.
  5275. * Others will be parsed as unknown fields. */
  5276. find_methods(c, sub_h);
  5277. }
  5278. }
  5279. }
  5280. /* (Re-)compile bytecode for all messages in "msgs."
  5281. * Overwrites any existing bytecode in "c". */
  5282. static void compile_methods(compiler *c) {
  5283. upb_inttable_iter i;
  5284. /* Start over at the beginning of the bytecode. */
  5285. c->pc = c->group->bytecode;
  5286. upb_inttable_begin(&i, &c->group->methods);
  5287. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5288. upb_pbdecodermethod *method = upb_value_getptr(upb_inttable_iter_value(&i));
  5289. compile_method(c, method);
  5290. }
  5291. }
  5292. static void set_bytecode_handlers(mgroup *g) {
  5293. upb_inttable_iter i;
  5294. upb_inttable_begin(&i, &g->methods);
  5295. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5296. upb_pbdecodermethod *m = upb_value_getptr(upb_inttable_iter_value(&i));
  5297. upb_byteshandler *h = &m->input_handler_;
  5298. m->code_base.ptr = g->bytecode + m->code_base.ofs;
  5299. upb_byteshandler_setstartstr(h, upb_pbdecoder_startbc, m->code_base.ptr);
  5300. upb_byteshandler_setstring(h, upb_pbdecoder_decode, g);
  5301. upb_byteshandler_setendstr(h, upb_pbdecoder_end, m);
  5302. }
  5303. }
  5304. /* TODO(haberman): allow this to be constructed for an arbitrary set of dest
  5305. * handlers and other mgroups (but verify we have a transitive closure). */
  5306. const mgroup *mgroup_new(const upb_handlers *dest, bool allowjit, bool lazy) {
  5307. mgroup *g;
  5308. compiler *c;
  5309. UPB_UNUSED(allowjit);
  5310. g = newgroup();
  5311. c = newcompiler(g, lazy);
  5312. find_methods(c, dest);
  5313. /* We compile in two passes:
  5314. * 1. all messages are assigned relative offsets from the beginning of the
  5315. * bytecode (saved in method->code_base).
  5316. * 2. forwards OP_CALL instructions can be correctly linked since message
  5317. * offsets have been previously assigned.
  5318. *
  5319. * Could avoid the second pass by linking OP_CALL instructions somehow. */
  5320. compile_methods(c);
  5321. compile_methods(c);
  5322. g->bytecode_end = c->pc;
  5323. freecompiler(c);
  5324. #ifdef UPB_DUMP_BYTECODE
  5325. {
  5326. FILE *f = fopen("/tmp/upb-bytecode", "w");
  5327. UPB_ASSERT(f);
  5328. dumpbc(g->bytecode, g->bytecode_end, stderr);
  5329. dumpbc(g->bytecode, g->bytecode_end, f);
  5330. fclose(f);
  5331. f = fopen("/tmp/upb-bytecode.bin", "wb");
  5332. UPB_ASSERT(f);
  5333. fwrite(g->bytecode, 1, g->bytecode_end - g->bytecode, f);
  5334. fclose(f);
  5335. }
  5336. #endif
  5337. set_bytecode_handlers(g);
  5338. return g;
  5339. }
  5340. /* upb_pbcodecache ************************************************************/
  5341. upb_pbcodecache *upb_pbcodecache_new(upb_handlercache *dest) {
  5342. upb_pbcodecache *c = upb_gmalloc(sizeof(*c));
  5343. if (!c) return NULL;
  5344. c->dest = dest;
  5345. c->allow_jit = true;
  5346. c->lazy = false;
  5347. c->arena = upb_arena_new();
  5348. if (!upb_inttable_init(&c->groups, UPB_CTYPE_CONSTPTR)) return NULL;
  5349. return c;
  5350. }
  5351. void upb_pbcodecache_free(upb_pbcodecache *c) {
  5352. size_t i;
  5353. for (i = 0; i < upb_inttable_count(&c->groups); i++) {
  5354. upb_value v;
  5355. bool ok = upb_inttable_lookup(&c->groups, i, &v);
  5356. UPB_ASSERT(ok);
  5357. freegroup((void*)upb_value_getconstptr(v));
  5358. }
  5359. upb_inttable_uninit(&c->groups);
  5360. upb_arena_free(c->arena);
  5361. upb_gfree(c);
  5362. }
  5363. bool upb_pbcodecache_allowjit(const upb_pbcodecache *c) {
  5364. return c->allow_jit;
  5365. }
  5366. void upb_pbcodecache_setallowjit(upb_pbcodecache *c, bool allow) {
  5367. UPB_ASSERT(upb_inttable_count(&c->groups) == 0);
  5368. c->allow_jit = allow;
  5369. }
  5370. void upb_pbdecodermethodopts_setlazy(upb_pbcodecache *c, bool lazy) {
  5371. UPB_ASSERT(upb_inttable_count(&c->groups) == 0);
  5372. c->lazy = lazy;
  5373. }
  5374. const upb_pbdecodermethod *upb_pbcodecache_get(upb_pbcodecache *c,
  5375. const upb_msgdef *md) {
  5376. upb_value v;
  5377. bool ok;
  5378. const upb_handlers *h;
  5379. const mgroup *g;
  5380. /* Right now we build a new DecoderMethod every time.
  5381. * TODO(haberman): properly cache methods by their true key. */
  5382. h = upb_handlercache_get(c->dest, md);
  5383. g = mgroup_new(h, c->allow_jit, c->lazy);
  5384. upb_inttable_push(&c->groups, upb_value_constptr(g));
  5385. ok = upb_inttable_lookupptr(&g->methods, h, &v);
  5386. UPB_ASSERT(ok);
  5387. return upb_value_getptr(v);
  5388. }
  5389. /*
  5390. ** upb::Decoder (Bytecode Decoder VM)
  5391. **
  5392. ** Bytecode must previously have been generated using the bytecode compiler in
  5393. ** compile_decoder.c. This decoder then walks through the bytecode op-by-op to
  5394. ** parse the input.
  5395. **
  5396. ** Decoding is fully resumable; we just keep a pointer to the current bytecode
  5397. ** instruction and resume from there. A fair amount of the logic here is to
  5398. ** handle the fact that values can span buffer seams and we have to be able to
  5399. ** be capable of suspending/resuming from any byte in the stream. This
  5400. ** sometimes requires keeping a few trailing bytes from the last buffer around
  5401. ** in the "residual" buffer.
  5402. */
  5403. #include <inttypes.h>
  5404. #include <stddef.h>
  5405. #ifdef UPB_DUMP_BYTECODE
  5406. #include <stdio.h>
  5407. #endif
  5408. #define CHECK_SUSPEND(x) if (!(x)) return upb_pbdecoder_suspend(d);
  5409. /* Error messages that are shared between the bytecode and JIT decoders. */
  5410. const char *kPbDecoderStackOverflow = "Nesting too deep.";
  5411. const char *kPbDecoderSubmessageTooLong =
  5412. "Submessage end extends past enclosing submessage.";
  5413. /* Error messages shared within this file. */
  5414. static const char *kUnterminatedVarint = "Unterminated varint.";
  5415. /* upb_pbdecoder **************************************************************/
  5416. static opcode halt = OP_HALT;
  5417. /* A dummy character we can point to when the user passes us a NULL buffer.
  5418. * We need this because in C (NULL + 0) and (NULL - NULL) are undefined
  5419. * behavior, which would invalidate functions like curbufleft(). */
  5420. static const char dummy_char;
  5421. /* Whether an op consumes any of the input buffer. */
  5422. static bool consumes_input(opcode op) {
  5423. switch (op) {
  5424. case OP_SETDISPATCH:
  5425. case OP_STARTMSG:
  5426. case OP_ENDMSG:
  5427. case OP_STARTSEQ:
  5428. case OP_ENDSEQ:
  5429. case OP_STARTSUBMSG:
  5430. case OP_ENDSUBMSG:
  5431. case OP_STARTSTR:
  5432. case OP_ENDSTR:
  5433. case OP_PUSHTAGDELIM:
  5434. case OP_POP:
  5435. case OP_SETDELIM:
  5436. case OP_SETBIGGROUPNUM:
  5437. case OP_CHECKDELIM:
  5438. case OP_CALL:
  5439. case OP_RET:
  5440. case OP_BRANCH:
  5441. return false;
  5442. default:
  5443. return true;
  5444. }
  5445. }
  5446. static size_t stacksize(upb_pbdecoder *d, size_t entries) {
  5447. UPB_UNUSED(d);
  5448. return entries * sizeof(upb_pbdecoder_frame);
  5449. }
  5450. static size_t callstacksize(upb_pbdecoder *d, size_t entries) {
  5451. UPB_UNUSED(d);
  5452. #ifdef UPB_USE_JIT_X64
  5453. if (d->method_->is_native_) {
  5454. /* Each native stack frame needs two pointers, plus we need a few frames for
  5455. * the enter/exit trampolines. */
  5456. size_t ret = entries * sizeof(void*) * 2;
  5457. ret += sizeof(void*) * 10;
  5458. return ret;
  5459. }
  5460. #endif
  5461. return entries * sizeof(uint32_t*);
  5462. }
  5463. static bool in_residual_buf(const upb_pbdecoder *d, const char *p);
  5464. /* It's unfortunate that we have to micro-manage the compiler with
  5465. * UPB_FORCEINLINE and UPB_NOINLINE, especially since this tuning is necessarily
  5466. * specific to one hardware configuration. But empirically on a Core i7,
  5467. * performance increases 30-50% with these annotations. Every instance where
  5468. * these appear, gcc 4.2.1 made the wrong decision and degraded performance in
  5469. * benchmarks. */
  5470. static void seterr(upb_pbdecoder *d, const char *msg) {
  5471. upb_status_seterrmsg(d->status, msg);
  5472. }
  5473. void upb_pbdecoder_seterr(upb_pbdecoder *d, const char *msg) {
  5474. seterr(d, msg);
  5475. }
  5476. /* Buffering ******************************************************************/
  5477. /* We operate on one buffer at a time, which is either the user's buffer passed
  5478. * to our "decode" callback or some residual bytes from the previous buffer. */
  5479. /* How many bytes can be safely read from d->ptr without reading past end-of-buf
  5480. * or past the current delimited end. */
  5481. static size_t curbufleft(const upb_pbdecoder *d) {
  5482. UPB_ASSERT(d->data_end >= d->ptr);
  5483. return d->data_end - d->ptr;
  5484. }
  5485. /* How many bytes are available before end-of-buffer. */
  5486. static size_t bufleft(const upb_pbdecoder *d) {
  5487. return d->end - d->ptr;
  5488. }
  5489. /* Overall stream offset of d->ptr. */
  5490. uint64_t offset(const upb_pbdecoder *d) {
  5491. return d->bufstart_ofs + (d->ptr - d->buf);
  5492. }
  5493. /* How many bytes are available before the end of this delimited region. */
  5494. size_t delim_remaining(const upb_pbdecoder *d) {
  5495. return d->top->end_ofs - offset(d);
  5496. }
  5497. /* Advances d->ptr. */
  5498. static void advance(upb_pbdecoder *d, size_t len) {
  5499. UPB_ASSERT(curbufleft(d) >= len);
  5500. d->ptr += len;
  5501. }
  5502. static bool in_buf(const char *p, const char *buf, const char *end) {
  5503. return p >= buf && p <= end;
  5504. }
  5505. static bool in_residual_buf(const upb_pbdecoder *d, const char *p) {
  5506. return in_buf(p, d->residual, d->residual_end);
  5507. }
  5508. /* Calculates the delim_end value, which is affected by both the current buffer
  5509. * and the parsing stack, so must be called whenever either is updated. */
  5510. static void set_delim_end(upb_pbdecoder *d) {
  5511. size_t delim_ofs = d->top->end_ofs - d->bufstart_ofs;
  5512. if (delim_ofs <= (size_t)(d->end - d->buf)) {
  5513. d->delim_end = d->buf + delim_ofs;
  5514. d->data_end = d->delim_end;
  5515. } else {
  5516. d->data_end = d->end;
  5517. d->delim_end = NULL;
  5518. }
  5519. }
  5520. static void switchtobuf(upb_pbdecoder *d, const char *buf, const char *end) {
  5521. d->ptr = buf;
  5522. d->buf = buf;
  5523. d->end = end;
  5524. set_delim_end(d);
  5525. }
  5526. static void advancetobuf(upb_pbdecoder *d, const char *buf, size_t len) {
  5527. UPB_ASSERT(curbufleft(d) == 0);
  5528. d->bufstart_ofs += (d->end - d->buf);
  5529. switchtobuf(d, buf, buf + len);
  5530. }
  5531. static void checkpoint(upb_pbdecoder *d) {
  5532. /* The assertion here is in the interests of efficiency, not correctness.
  5533. * We are trying to ensure that we don't checkpoint() more often than
  5534. * necessary. */
  5535. UPB_ASSERT(d->checkpoint != d->ptr);
  5536. d->checkpoint = d->ptr;
  5537. }
  5538. /* Skips "bytes" bytes in the stream, which may be more than available. If we
  5539. * skip more bytes than are available, we return a long read count to the caller
  5540. * indicating how many bytes can be skipped over before passing actual data
  5541. * again. Skipped bytes can pass a NULL buffer and the decoder guarantees they
  5542. * won't actually be read.
  5543. */
  5544. static int32_t skip(upb_pbdecoder *d, size_t bytes) {
  5545. UPB_ASSERT(!in_residual_buf(d, d->ptr) || d->size_param == 0);
  5546. UPB_ASSERT(d->skip == 0);
  5547. if (bytes > delim_remaining(d)) {
  5548. seterr(d, "Skipped value extended beyond enclosing submessage.");
  5549. return upb_pbdecoder_suspend(d);
  5550. } else if (bufleft(d) >= bytes) {
  5551. /* Skipped data is all in current buffer, and more is still available. */
  5552. advance(d, bytes);
  5553. d->skip = 0;
  5554. return DECODE_OK;
  5555. } else {
  5556. /* Skipped data extends beyond currently available buffers. */
  5557. d->pc = d->last;
  5558. d->skip = bytes - curbufleft(d);
  5559. d->bufstart_ofs += (d->end - d->buf);
  5560. d->residual_end = d->residual;
  5561. switchtobuf(d, d->residual, d->residual_end);
  5562. return d->size_param + d->skip;
  5563. }
  5564. }
  5565. /* Resumes the decoder from an initial state or from a previous suspend. */
  5566. int32_t upb_pbdecoder_resume(upb_pbdecoder *d, void *p, const char *buf,
  5567. size_t size, const upb_bufhandle *handle) {
  5568. UPB_UNUSED(p); /* Useless; just for the benefit of the JIT. */
  5569. /* d->skip and d->residual_end could probably elegantly be represented
  5570. * as a single variable, to more easily represent this invariant. */
  5571. UPB_ASSERT(!(d->skip && d->residual_end > d->residual));
  5572. /* We need to remember the original size_param, so that the value we return
  5573. * is relative to it, even if we do some skipping first. */
  5574. d->size_param = size;
  5575. d->handle = handle;
  5576. /* Have to handle this case specially (ie. not with skip()) because the user
  5577. * is allowed to pass a NULL buffer here, which won't allow us to safely
  5578. * calculate a d->end or use our normal functions like curbufleft(). */
  5579. if (d->skip && d->skip >= size) {
  5580. d->skip -= size;
  5581. d->bufstart_ofs += size;
  5582. buf = &dummy_char;
  5583. size = 0;
  5584. /* We can't just return now, because we might need to execute some ops
  5585. * like CHECKDELIM, which could call some callbacks and pop the stack. */
  5586. }
  5587. /* We need to pretend that this was the actual buffer param, since some of the
  5588. * calculations assume that d->ptr/d->buf is relative to this. */
  5589. d->buf_param = buf;
  5590. if (!buf) {
  5591. /* NULL buf is ok if its entire span is covered by the "skip" above, but
  5592. * by this point we know that "skip" doesn't cover the buffer. */
  5593. seterr(d, "Passed NULL buffer over non-skippable region.");
  5594. return upb_pbdecoder_suspend(d);
  5595. }
  5596. if (d->residual_end > d->residual) {
  5597. /* We have residual bytes from the last buffer. */
  5598. UPB_ASSERT(d->ptr == d->residual);
  5599. } else {
  5600. switchtobuf(d, buf, buf + size);
  5601. }
  5602. d->checkpoint = d->ptr;
  5603. /* Handle skips that don't cover the whole buffer (as above). */
  5604. if (d->skip) {
  5605. size_t skip_bytes = d->skip;
  5606. d->skip = 0;
  5607. CHECK_RETURN(skip(d, skip_bytes));
  5608. checkpoint(d);
  5609. }
  5610. /* If we're inside an unknown group, continue to parse unknown values. */
  5611. if (d->top->groupnum < 0) {
  5612. CHECK_RETURN(upb_pbdecoder_skipunknown(d, -1, 0));
  5613. checkpoint(d);
  5614. }
  5615. return DECODE_OK;
  5616. }
  5617. /* Suspends the decoder at the last checkpoint, without saving any residual
  5618. * bytes. If there are any unconsumed bytes, returns a short byte count. */
  5619. size_t upb_pbdecoder_suspend(upb_pbdecoder *d) {
  5620. d->pc = d->last;
  5621. if (d->checkpoint == d->residual) {
  5622. /* Checkpoint was in residual buf; no user bytes were consumed. */
  5623. d->ptr = d->residual;
  5624. return 0;
  5625. } else {
  5626. size_t ret = d->size_param - (d->end - d->checkpoint);
  5627. UPB_ASSERT(!in_residual_buf(d, d->checkpoint));
  5628. UPB_ASSERT(d->buf == d->buf_param || d->buf == &dummy_char);
  5629. d->bufstart_ofs += (d->checkpoint - d->buf);
  5630. d->residual_end = d->residual;
  5631. switchtobuf(d, d->residual, d->residual_end);
  5632. return ret;
  5633. }
  5634. }
  5635. /* Suspends the decoder at the last checkpoint, and saves any unconsumed
  5636. * bytes in our residual buffer. This is necessary if we need more user
  5637. * bytes to form a complete value, which might not be contiguous in the
  5638. * user's buffers. Always consumes all user bytes. */
  5639. static size_t suspend_save(upb_pbdecoder *d) {
  5640. /* We hit end-of-buffer before we could parse a full value.
  5641. * Save any unconsumed bytes (if any) to the residual buffer. */
  5642. d->pc = d->last;
  5643. if (d->checkpoint == d->residual) {
  5644. /* Checkpoint was in residual buf; append user byte(s) to residual buf. */
  5645. UPB_ASSERT((d->residual_end - d->residual) + d->size_param <=
  5646. sizeof(d->residual));
  5647. if (!in_residual_buf(d, d->ptr)) {
  5648. d->bufstart_ofs -= (d->residual_end - d->residual);
  5649. }
  5650. memcpy(d->residual_end, d->buf_param, d->size_param);
  5651. d->residual_end += d->size_param;
  5652. } else {
  5653. /* Checkpoint was in user buf; old residual bytes not needed. */
  5654. size_t save;
  5655. UPB_ASSERT(!in_residual_buf(d, d->checkpoint));
  5656. d->ptr = d->checkpoint;
  5657. save = curbufleft(d);
  5658. UPB_ASSERT(save <= sizeof(d->residual));
  5659. memcpy(d->residual, d->ptr, save);
  5660. d->residual_end = d->residual + save;
  5661. d->bufstart_ofs = offset(d);
  5662. }
  5663. switchtobuf(d, d->residual, d->residual_end);
  5664. return d->size_param;
  5665. }
  5666. /* Copies the next "bytes" bytes into "buf" and advances the stream.
  5667. * Requires that this many bytes are available in the current buffer. */
  5668. UPB_FORCEINLINE static void consumebytes(upb_pbdecoder *d, void *buf,
  5669. size_t bytes) {
  5670. UPB_ASSERT(bytes <= curbufleft(d));
  5671. memcpy(buf, d->ptr, bytes);
  5672. advance(d, bytes);
  5673. }
  5674. /* Slow path for getting the next "bytes" bytes, regardless of whether they are
  5675. * available in the current buffer or not. Returns a status code as described
  5676. * in decoder.int.h. */
  5677. UPB_NOINLINE static int32_t getbytes_slow(upb_pbdecoder *d, void *buf,
  5678. size_t bytes) {
  5679. const size_t avail = curbufleft(d);
  5680. consumebytes(d, buf, avail);
  5681. bytes -= avail;
  5682. UPB_ASSERT(bytes > 0);
  5683. if (in_residual_buf(d, d->ptr)) {
  5684. advancetobuf(d, d->buf_param, d->size_param);
  5685. }
  5686. if (curbufleft(d) >= bytes) {
  5687. consumebytes(d, (char *)buf + avail, bytes);
  5688. return DECODE_OK;
  5689. } else if (d->data_end == d->delim_end) {
  5690. seterr(d, "Submessage ended in the middle of a value or group");
  5691. return upb_pbdecoder_suspend(d);
  5692. } else {
  5693. return suspend_save(d);
  5694. }
  5695. }
  5696. /* Gets the next "bytes" bytes, regardless of whether they are available in the
  5697. * current buffer or not. Returns a status code as described in decoder.int.h.
  5698. */
  5699. UPB_FORCEINLINE static int32_t getbytes(upb_pbdecoder *d, void *buf,
  5700. size_t bytes) {
  5701. if (curbufleft(d) >= bytes) {
  5702. /* Buffer has enough data to satisfy. */
  5703. consumebytes(d, buf, bytes);
  5704. return DECODE_OK;
  5705. } else {
  5706. return getbytes_slow(d, buf, bytes);
  5707. }
  5708. }
  5709. UPB_NOINLINE static size_t peekbytes_slow(upb_pbdecoder *d, void *buf,
  5710. size_t bytes) {
  5711. size_t ret = curbufleft(d);
  5712. memcpy(buf, d->ptr, ret);
  5713. if (in_residual_buf(d, d->ptr)) {
  5714. size_t copy = UPB_MIN(bytes - ret, d->size_param);
  5715. memcpy((char *)buf + ret, d->buf_param, copy);
  5716. ret += copy;
  5717. }
  5718. return ret;
  5719. }
  5720. UPB_FORCEINLINE static size_t peekbytes(upb_pbdecoder *d, void *buf,
  5721. size_t bytes) {
  5722. if (curbufleft(d) >= bytes) {
  5723. memcpy(buf, d->ptr, bytes);
  5724. return bytes;
  5725. } else {
  5726. return peekbytes_slow(d, buf, bytes);
  5727. }
  5728. }
  5729. /* Decoding of wire types *****************************************************/
  5730. /* Slow path for decoding a varint from the current buffer position.
  5731. * Returns a status code as described in decoder.int.h. */
  5732. UPB_NOINLINE int32_t upb_pbdecoder_decode_varint_slow(upb_pbdecoder *d,
  5733. uint64_t *u64) {
  5734. uint8_t byte = 0x80;
  5735. int bitpos;
  5736. *u64 = 0;
  5737. for(bitpos = 0; bitpos < 70 && (byte & 0x80); bitpos += 7) {
  5738. CHECK_RETURN(getbytes(d, &byte, 1));
  5739. *u64 |= (uint64_t)(byte & 0x7F) << bitpos;
  5740. }
  5741. if(bitpos == 70 && (byte & 0x80)) {
  5742. seterr(d, kUnterminatedVarint);
  5743. return upb_pbdecoder_suspend(d);
  5744. }
  5745. return DECODE_OK;
  5746. }
  5747. /* Decodes a varint from the current buffer position.
  5748. * Returns a status code as described in decoder.int.h. */
  5749. UPB_FORCEINLINE static int32_t decode_varint(upb_pbdecoder *d, uint64_t *u64) {
  5750. if (curbufleft(d) > 0 && !(*d->ptr & 0x80)) {
  5751. *u64 = *d->ptr;
  5752. advance(d, 1);
  5753. return DECODE_OK;
  5754. } else if (curbufleft(d) >= 10) {
  5755. /* Fast case. */
  5756. upb_decoderet r = upb_vdecode_fast(d->ptr);
  5757. if (r.p == NULL) {
  5758. seterr(d, kUnterminatedVarint);
  5759. return upb_pbdecoder_suspend(d);
  5760. }
  5761. advance(d, r.p - d->ptr);
  5762. *u64 = r.val;
  5763. return DECODE_OK;
  5764. } else {
  5765. /* Slow case -- varint spans buffer seam. */
  5766. return upb_pbdecoder_decode_varint_slow(d, u64);
  5767. }
  5768. }
  5769. /* Decodes a 32-bit varint from the current buffer position.
  5770. * Returns a status code as described in decoder.int.h. */
  5771. UPB_FORCEINLINE static int32_t decode_v32(upb_pbdecoder *d, uint32_t *u32) {
  5772. uint64_t u64;
  5773. int32_t ret = decode_varint(d, &u64);
  5774. if (ret >= 0) return ret;
  5775. if (u64 > UINT32_MAX) {
  5776. seterr(d, "Unterminated 32-bit varint");
  5777. /* TODO(haberman) guarantee that this function return is >= 0 somehow,
  5778. * so we know this path will always be treated as error by our caller.
  5779. * Right now the size_t -> int32_t can overflow and produce negative values.
  5780. */
  5781. *u32 = 0;
  5782. return upb_pbdecoder_suspend(d);
  5783. }
  5784. *u32 = u64;
  5785. return DECODE_OK;
  5786. }
  5787. /* Decodes a fixed32 from the current buffer position.
  5788. * Returns a status code as described in decoder.int.h.
  5789. * TODO: proper byte swapping for big-endian machines. */
  5790. UPB_FORCEINLINE static int32_t decode_fixed32(upb_pbdecoder *d, uint32_t *u32) {
  5791. return getbytes(d, u32, 4);
  5792. }
  5793. /* Decodes a fixed64 from the current buffer position.
  5794. * Returns a status code as described in decoder.int.h.
  5795. * TODO: proper byte swapping for big-endian machines. */
  5796. UPB_FORCEINLINE static int32_t decode_fixed64(upb_pbdecoder *d, uint64_t *u64) {
  5797. return getbytes(d, u64, 8);
  5798. }
  5799. /* Non-static versions of the above functions.
  5800. * These are called by the JIT for fallback paths. */
  5801. int32_t upb_pbdecoder_decode_f32(upb_pbdecoder *d, uint32_t *u32) {
  5802. return decode_fixed32(d, u32);
  5803. }
  5804. int32_t upb_pbdecoder_decode_f64(upb_pbdecoder *d, uint64_t *u64) {
  5805. return decode_fixed64(d, u64);
  5806. }
  5807. static double as_double(uint64_t n) { double d; memcpy(&d, &n, 8); return d; }
  5808. static float as_float(uint32_t n) { float f; memcpy(&f, &n, 4); return f; }
  5809. /* Pushes a frame onto the decoder stack. */
  5810. static bool decoder_push(upb_pbdecoder *d, uint64_t end) {
  5811. upb_pbdecoder_frame *fr = d->top;
  5812. if (end > fr->end_ofs) {
  5813. seterr(d, kPbDecoderSubmessageTooLong);
  5814. return false;
  5815. } else if (fr == d->limit) {
  5816. seterr(d, kPbDecoderStackOverflow);
  5817. return false;
  5818. }
  5819. fr++;
  5820. fr->end_ofs = end;
  5821. fr->dispatch = NULL;
  5822. fr->groupnum = 0;
  5823. d->top = fr;
  5824. return true;
  5825. }
  5826. static bool pushtagdelim(upb_pbdecoder *d, uint32_t arg) {
  5827. /* While we expect to see an "end" tag (either ENDGROUP or a non-sequence
  5828. * field number) prior to hitting any enclosing submessage end, pushing our
  5829. * existing delim end prevents us from continuing to parse values from a
  5830. * corrupt proto that doesn't give us an END tag in time. */
  5831. if (!decoder_push(d, d->top->end_ofs))
  5832. return false;
  5833. d->top->groupnum = arg;
  5834. return true;
  5835. }
  5836. /* Pops a frame from the decoder stack. */
  5837. static void decoder_pop(upb_pbdecoder *d) { d->top--; }
  5838. UPB_NOINLINE int32_t upb_pbdecoder_checktag_slow(upb_pbdecoder *d,
  5839. uint64_t expected) {
  5840. uint64_t data = 0;
  5841. size_t bytes = upb_value_size(expected);
  5842. size_t read = peekbytes(d, &data, bytes);
  5843. if (read == bytes && data == expected) {
  5844. /* Advance past matched bytes. */
  5845. int32_t ok = getbytes(d, &data, read);
  5846. UPB_ASSERT(ok < 0);
  5847. return DECODE_OK;
  5848. } else if (read < bytes && memcmp(&data, &expected, read) == 0) {
  5849. return suspend_save(d);
  5850. } else {
  5851. return DECODE_MISMATCH;
  5852. }
  5853. }
  5854. int32_t upb_pbdecoder_skipunknown(upb_pbdecoder *d, int32_t fieldnum,
  5855. uint8_t wire_type) {
  5856. if (fieldnum >= 0)
  5857. goto have_tag;
  5858. while (true) {
  5859. uint32_t tag;
  5860. CHECK_RETURN(decode_v32(d, &tag));
  5861. wire_type = tag & 0x7;
  5862. fieldnum = tag >> 3;
  5863. have_tag:
  5864. if (fieldnum == 0) {
  5865. seterr(d, "Saw invalid field number (0)");
  5866. return upb_pbdecoder_suspend(d);
  5867. }
  5868. switch (wire_type) {
  5869. case UPB_WIRE_TYPE_32BIT:
  5870. CHECK_RETURN(skip(d, 4));
  5871. break;
  5872. case UPB_WIRE_TYPE_64BIT:
  5873. CHECK_RETURN(skip(d, 8));
  5874. break;
  5875. case UPB_WIRE_TYPE_VARINT: {
  5876. uint64_t u64;
  5877. CHECK_RETURN(decode_varint(d, &u64));
  5878. break;
  5879. }
  5880. case UPB_WIRE_TYPE_DELIMITED: {
  5881. uint32_t len;
  5882. CHECK_RETURN(decode_v32(d, &len));
  5883. CHECK_RETURN(skip(d, len));
  5884. break;
  5885. }
  5886. case UPB_WIRE_TYPE_START_GROUP:
  5887. CHECK_SUSPEND(pushtagdelim(d, -fieldnum));
  5888. break;
  5889. case UPB_WIRE_TYPE_END_GROUP:
  5890. if (fieldnum == -d->top->groupnum) {
  5891. decoder_pop(d);
  5892. } else if (fieldnum == d->top->groupnum) {
  5893. return DECODE_ENDGROUP;
  5894. } else {
  5895. seterr(d, "Unmatched ENDGROUP tag.");
  5896. return upb_pbdecoder_suspend(d);
  5897. }
  5898. break;
  5899. default:
  5900. seterr(d, "Invalid wire type");
  5901. return upb_pbdecoder_suspend(d);
  5902. }
  5903. if (d->top->groupnum >= 0) {
  5904. /* TODO: More code needed for handling unknown groups. */
  5905. upb_sink_putunknown(d->top->sink, d->checkpoint, d->ptr - d->checkpoint);
  5906. return DECODE_OK;
  5907. }
  5908. /* Unknown group -- continue looping over unknown fields. */
  5909. checkpoint(d);
  5910. }
  5911. }
  5912. static void goto_endmsg(upb_pbdecoder *d) {
  5913. upb_value v;
  5914. bool found = upb_inttable_lookup32(d->top->dispatch, DISPATCH_ENDMSG, &v);
  5915. UPB_ASSERT(found);
  5916. d->pc = d->top->base + upb_value_getuint64(v);
  5917. }
  5918. /* Parses a tag and jumps to the corresponding bytecode instruction for this
  5919. * field.
  5920. *
  5921. * If the tag is unknown (or the wire type doesn't match), parses the field as
  5922. * unknown. If the tag is a valid ENDGROUP tag, jumps to the bytecode
  5923. * instruction for the end of message. */
  5924. static int32_t dispatch(upb_pbdecoder *d) {
  5925. upb_inttable *dispatch = d->top->dispatch;
  5926. uint32_t tag;
  5927. uint8_t wire_type;
  5928. uint32_t fieldnum;
  5929. upb_value val;
  5930. int32_t retval;
  5931. /* Decode tag. */
  5932. CHECK_RETURN(decode_v32(d, &tag));
  5933. wire_type = tag & 0x7;
  5934. fieldnum = tag >> 3;
  5935. /* Lookup tag. Because of packed/non-packed compatibility, we have to
  5936. * check the wire type against two possibilities. */
  5937. if (fieldnum != DISPATCH_ENDMSG &&
  5938. upb_inttable_lookup32(dispatch, fieldnum, &val)) {
  5939. uint64_t v = upb_value_getuint64(val);
  5940. if (wire_type == (v & 0xff)) {
  5941. d->pc = d->top->base + (v >> 16);
  5942. return DECODE_OK;
  5943. } else if (wire_type == ((v >> 8) & 0xff)) {
  5944. bool found =
  5945. upb_inttable_lookup(dispatch, fieldnum + UPB_MAX_FIELDNUMBER, &val);
  5946. UPB_ASSERT(found);
  5947. d->pc = d->top->base + upb_value_getuint64(val);
  5948. return DECODE_OK;
  5949. }
  5950. }
  5951. /* We have some unknown fields (or ENDGROUP) to parse. The DISPATCH or TAG
  5952. * bytecode that triggered this is preceded by a CHECKDELIM bytecode which
  5953. * we need to back up to, so that when we're done skipping unknown data we
  5954. * can re-check the delimited end. */
  5955. d->last--; /* Necessary if we get suspended */
  5956. d->pc = d->last;
  5957. UPB_ASSERT(getop(*d->last) == OP_CHECKDELIM);
  5958. /* Unknown field or ENDGROUP. */
  5959. retval = upb_pbdecoder_skipunknown(d, fieldnum, wire_type);
  5960. CHECK_RETURN(retval);
  5961. if (retval == DECODE_ENDGROUP) {
  5962. goto_endmsg(d);
  5963. return DECODE_OK;
  5964. }
  5965. return DECODE_OK;
  5966. }
  5967. /* Callers know that the stack is more than one deep because the opcodes that
  5968. * call this only occur after PUSH operations. */
  5969. upb_pbdecoder_frame *outer_frame(upb_pbdecoder *d) {
  5970. UPB_ASSERT(d->top != d->stack);
  5971. return d->top - 1;
  5972. }
  5973. /* The main decoding loop *****************************************************/
  5974. /* The main decoder VM function. Uses traditional bytecode dispatch loop with a
  5975. * switch() statement. */
  5976. size_t run_decoder_vm(upb_pbdecoder *d, const mgroup *group,
  5977. const upb_bufhandle* handle) {
  5978. #define VMCASE(op, code) \
  5979. case op: { code; if (consumes_input(op)) checkpoint(d); break; }
  5980. #define PRIMITIVE_OP(type, wt, name, convfunc, ctype) \
  5981. VMCASE(OP_PARSE_ ## type, { \
  5982. ctype val; \
  5983. CHECK_RETURN(decode_ ## wt(d, &val)); \
  5984. upb_sink_put ## name(d->top->sink, arg, (convfunc)(val)); \
  5985. })
  5986. while(1) {
  5987. int32_t instruction;
  5988. opcode op;
  5989. uint32_t arg;
  5990. int32_t longofs;
  5991. d->last = d->pc;
  5992. instruction = *d->pc++;
  5993. op = getop(instruction);
  5994. arg = instruction >> 8;
  5995. longofs = arg;
  5996. UPB_ASSERT(d->ptr != d->residual_end);
  5997. UPB_UNUSED(group);
  5998. #ifdef UPB_DUMP_BYTECODE
  5999. fprintf(stderr, "s_ofs=%d buf_ofs=%d data_rem=%d buf_rem=%d delim_rem=%d "
  6000. "%x %s (%d)\n",
  6001. (int)offset(d),
  6002. (int)(d->ptr - d->buf),
  6003. (int)(d->data_end - d->ptr),
  6004. (int)(d->end - d->ptr),
  6005. (int)((d->top->end_ofs - d->bufstart_ofs) - (d->ptr - d->buf)),
  6006. (int)(d->pc - 1 - group->bytecode),
  6007. upb_pbdecoder_getopname(op),
  6008. arg);
  6009. #endif
  6010. switch (op) {
  6011. /* Technically, we are losing data if we see a 32-bit varint that is not
  6012. * properly sign-extended. We could detect this and error about the data
  6013. * loss, but proto2 does not do this, so we pass. */
  6014. PRIMITIVE_OP(INT32, varint, int32, int32_t, uint64_t)
  6015. PRIMITIVE_OP(INT64, varint, int64, int64_t, uint64_t)
  6016. PRIMITIVE_OP(UINT32, varint, uint32, uint32_t, uint64_t)
  6017. PRIMITIVE_OP(UINT64, varint, uint64, uint64_t, uint64_t)
  6018. PRIMITIVE_OP(FIXED32, fixed32, uint32, uint32_t, uint32_t)
  6019. PRIMITIVE_OP(FIXED64, fixed64, uint64, uint64_t, uint64_t)
  6020. PRIMITIVE_OP(SFIXED32, fixed32, int32, int32_t, uint32_t)
  6021. PRIMITIVE_OP(SFIXED64, fixed64, int64, int64_t, uint64_t)
  6022. PRIMITIVE_OP(BOOL, varint, bool, bool, uint64_t)
  6023. PRIMITIVE_OP(DOUBLE, fixed64, double, as_double, uint64_t)
  6024. PRIMITIVE_OP(FLOAT, fixed32, float, as_float, uint32_t)
  6025. PRIMITIVE_OP(SINT32, varint, int32, upb_zzdec_32, uint64_t)
  6026. PRIMITIVE_OP(SINT64, varint, int64, upb_zzdec_64, uint64_t)
  6027. VMCASE(OP_SETDISPATCH,
  6028. d->top->base = d->pc - 1;
  6029. memcpy(&d->top->dispatch, d->pc, sizeof(void*));
  6030. d->pc += sizeof(void*) / sizeof(uint32_t);
  6031. )
  6032. VMCASE(OP_STARTMSG,
  6033. CHECK_SUSPEND(upb_sink_startmsg(d->top->sink));
  6034. )
  6035. VMCASE(OP_ENDMSG,
  6036. CHECK_SUSPEND(upb_sink_endmsg(d->top->sink, d->status));
  6037. )
  6038. VMCASE(OP_STARTSEQ,
  6039. upb_pbdecoder_frame *outer = outer_frame(d);
  6040. CHECK_SUSPEND(upb_sink_startseq(outer->sink, arg, &d->top->sink));
  6041. )
  6042. VMCASE(OP_ENDSEQ,
  6043. CHECK_SUSPEND(upb_sink_endseq(d->top->sink, arg));
  6044. )
  6045. VMCASE(OP_STARTSUBMSG,
  6046. upb_pbdecoder_frame *outer = outer_frame(d);
  6047. CHECK_SUSPEND(upb_sink_startsubmsg(outer->sink, arg, &d->top->sink));
  6048. )
  6049. VMCASE(OP_ENDSUBMSG,
  6050. CHECK_SUSPEND(upb_sink_endsubmsg(d->top->sink, arg));
  6051. )
  6052. VMCASE(OP_STARTSTR,
  6053. uint32_t len = delim_remaining(d);
  6054. upb_pbdecoder_frame *outer = outer_frame(d);
  6055. CHECK_SUSPEND(upb_sink_startstr(outer->sink, arg, len, &d->top->sink));
  6056. if (len == 0) {
  6057. d->pc++; /* Skip OP_STRING. */
  6058. }
  6059. )
  6060. VMCASE(OP_STRING,
  6061. uint32_t len = curbufleft(d);
  6062. size_t n = upb_sink_putstring(d->top->sink, arg, d->ptr, len, handle);
  6063. if (n > len) {
  6064. if (n > delim_remaining(d)) {
  6065. seterr(d, "Tried to skip past end of string.");
  6066. return upb_pbdecoder_suspend(d);
  6067. } else {
  6068. int32_t ret = skip(d, n);
  6069. /* This shouldn't return DECODE_OK, because n > len. */
  6070. UPB_ASSERT(ret >= 0);
  6071. return ret;
  6072. }
  6073. }
  6074. advance(d, n);
  6075. if (n < len || d->delim_end == NULL) {
  6076. /* We aren't finished with this string yet. */
  6077. d->pc--; /* Repeat OP_STRING. */
  6078. if (n > 0) checkpoint(d);
  6079. return upb_pbdecoder_suspend(d);
  6080. }
  6081. )
  6082. VMCASE(OP_ENDSTR,
  6083. CHECK_SUSPEND(upb_sink_endstr(d->top->sink, arg));
  6084. )
  6085. VMCASE(OP_PUSHTAGDELIM,
  6086. CHECK_SUSPEND(pushtagdelim(d, arg));
  6087. )
  6088. VMCASE(OP_SETBIGGROUPNUM,
  6089. d->top->groupnum = *d->pc++;
  6090. )
  6091. VMCASE(OP_POP,
  6092. UPB_ASSERT(d->top > d->stack);
  6093. decoder_pop(d);
  6094. )
  6095. VMCASE(OP_PUSHLENDELIM,
  6096. uint32_t len;
  6097. CHECK_RETURN(decode_v32(d, &len));
  6098. CHECK_SUSPEND(decoder_push(d, offset(d) + len));
  6099. set_delim_end(d);
  6100. )
  6101. VMCASE(OP_SETDELIM,
  6102. set_delim_end(d);
  6103. )
  6104. VMCASE(OP_CHECKDELIM,
  6105. /* We are guaranteed of this assert because we never allow ourselves to
  6106. * consume bytes beyond data_end, which covers delim_end when non-NULL.
  6107. */
  6108. UPB_ASSERT(!(d->delim_end && d->ptr > d->delim_end));
  6109. if (d->ptr == d->delim_end)
  6110. d->pc += longofs;
  6111. )
  6112. VMCASE(OP_CALL,
  6113. d->callstack[d->call_len++] = d->pc;
  6114. d->pc += longofs;
  6115. )
  6116. VMCASE(OP_RET,
  6117. UPB_ASSERT(d->call_len > 0);
  6118. d->pc = d->callstack[--d->call_len];
  6119. )
  6120. VMCASE(OP_BRANCH,
  6121. d->pc += longofs;
  6122. )
  6123. VMCASE(OP_TAG1,
  6124. uint8_t expected;
  6125. CHECK_SUSPEND(curbufleft(d) > 0);
  6126. expected = (arg >> 8) & 0xff;
  6127. if (*d->ptr == expected) {
  6128. advance(d, 1);
  6129. } else {
  6130. int8_t shortofs;
  6131. badtag:
  6132. shortofs = arg;
  6133. if (shortofs == LABEL_DISPATCH) {
  6134. CHECK_RETURN(dispatch(d));
  6135. } else {
  6136. d->pc += shortofs;
  6137. break; /* Avoid checkpoint(). */
  6138. }
  6139. }
  6140. )
  6141. VMCASE(OP_TAG2,
  6142. uint16_t expected;
  6143. CHECK_SUSPEND(curbufleft(d) > 0);
  6144. expected = (arg >> 8) & 0xffff;
  6145. if (curbufleft(d) >= 2) {
  6146. uint16_t actual;
  6147. memcpy(&actual, d->ptr, 2);
  6148. if (expected == actual) {
  6149. advance(d, 2);
  6150. } else {
  6151. goto badtag;
  6152. }
  6153. } else {
  6154. int32_t result = upb_pbdecoder_checktag_slow(d, expected);
  6155. if (result == DECODE_MISMATCH) goto badtag;
  6156. if (result >= 0) return result;
  6157. }
  6158. )
  6159. VMCASE(OP_TAGN, {
  6160. uint64_t expected;
  6161. int32_t result;
  6162. memcpy(&expected, d->pc, 8);
  6163. d->pc += 2;
  6164. result = upb_pbdecoder_checktag_slow(d, expected);
  6165. if (result == DECODE_MISMATCH) goto badtag;
  6166. if (result >= 0) return result;
  6167. })
  6168. VMCASE(OP_DISPATCH, {
  6169. CHECK_RETURN(dispatch(d));
  6170. })
  6171. VMCASE(OP_HALT, {
  6172. return d->size_param;
  6173. })
  6174. }
  6175. }
  6176. }
  6177. /* BytesHandler handlers ******************************************************/
  6178. void *upb_pbdecoder_startbc(void *closure, const void *pc, size_t size_hint) {
  6179. upb_pbdecoder *d = closure;
  6180. UPB_UNUSED(size_hint);
  6181. d->top->end_ofs = UINT64_MAX;
  6182. d->bufstart_ofs = 0;
  6183. d->call_len = 1;
  6184. d->callstack[0] = &halt;
  6185. d->pc = pc;
  6186. d->skip = 0;
  6187. return d;
  6188. }
  6189. void *upb_pbdecoder_startjit(void *closure, const void *hd, size_t size_hint) {
  6190. upb_pbdecoder *d = closure;
  6191. UPB_UNUSED(hd);
  6192. UPB_UNUSED(size_hint);
  6193. d->top->end_ofs = UINT64_MAX;
  6194. d->bufstart_ofs = 0;
  6195. d->call_len = 0;
  6196. d->skip = 0;
  6197. return d;
  6198. }
  6199. bool upb_pbdecoder_end(void *closure, const void *handler_data) {
  6200. upb_pbdecoder *d = closure;
  6201. const upb_pbdecodermethod *method = handler_data;
  6202. uint64_t end;
  6203. char dummy;
  6204. if (d->residual_end > d->residual) {
  6205. seterr(d, "Unexpected EOF: decoder still has buffered unparsed data");
  6206. return false;
  6207. }
  6208. if (d->skip) {
  6209. seterr(d, "Unexpected EOF inside skipped data");
  6210. return false;
  6211. }
  6212. if (d->top->end_ofs != UINT64_MAX) {
  6213. seterr(d, "Unexpected EOF inside delimited string");
  6214. return false;
  6215. }
  6216. /* The user's end() call indicates that the message ends here. */
  6217. end = offset(d);
  6218. d->top->end_ofs = end;
  6219. #ifdef UPB_USE_JIT_X64
  6220. if (method->is_native_) {
  6221. const mgroup *group = (const mgroup*)method->group;
  6222. if (d->top != d->stack)
  6223. d->stack->end_ofs = 0;
  6224. group->jit_code(closure, method->code_base.ptr, &dummy, 0, NULL);
  6225. } else
  6226. #endif
  6227. {
  6228. const uint32_t *p = d->pc;
  6229. d->stack->end_ofs = end;
  6230. /* Check the previous bytecode, but guard against beginning. */
  6231. if (p != method->code_base.ptr) p--;
  6232. if (getop(*p) == OP_CHECKDELIM) {
  6233. /* Rewind from OP_TAG* to OP_CHECKDELIM. */
  6234. UPB_ASSERT(getop(*d->pc) == OP_TAG1 ||
  6235. getop(*d->pc) == OP_TAG2 ||
  6236. getop(*d->pc) == OP_TAGN ||
  6237. getop(*d->pc) == OP_DISPATCH);
  6238. d->pc = p;
  6239. }
  6240. upb_pbdecoder_decode(closure, handler_data, &dummy, 0, NULL);
  6241. }
  6242. if (d->call_len != 0) {
  6243. seterr(d, "Unexpected EOF inside submessage or group");
  6244. return false;
  6245. }
  6246. return true;
  6247. }
  6248. size_t upb_pbdecoder_decode(void *decoder, const void *group, const char *buf,
  6249. size_t size, const upb_bufhandle *handle) {
  6250. int32_t result = upb_pbdecoder_resume(decoder, NULL, buf, size, handle);
  6251. if (result == DECODE_ENDGROUP) goto_endmsg(decoder);
  6252. CHECK_RETURN(result);
  6253. return run_decoder_vm(decoder, group, handle);
  6254. }
  6255. /* Public API *****************************************************************/
  6256. void upb_pbdecoder_reset(upb_pbdecoder *d) {
  6257. d->top = d->stack;
  6258. d->top->groupnum = 0;
  6259. d->ptr = d->residual;
  6260. d->buf = d->residual;
  6261. d->end = d->residual;
  6262. d->residual_end = d->residual;
  6263. }
  6264. upb_pbdecoder *upb_pbdecoder_create(upb_arena *a, const upb_pbdecodermethod *m,
  6265. upb_sink sink, upb_status *status) {
  6266. const size_t default_max_nesting = 64;
  6267. #ifndef NDEBUG
  6268. size_t size_before = upb_arena_bytesallocated(a);
  6269. #endif
  6270. upb_pbdecoder *d = upb_arena_malloc(a, sizeof(upb_pbdecoder));
  6271. if (!d) return NULL;
  6272. d->method_ = m;
  6273. d->callstack = upb_arena_malloc(a, callstacksize(d, default_max_nesting));
  6274. d->stack = upb_arena_malloc(a, stacksize(d, default_max_nesting));
  6275. if (!d->stack || !d->callstack) {
  6276. return NULL;
  6277. }
  6278. d->arena = a;
  6279. d->limit = d->stack + default_max_nesting - 1;
  6280. d->stack_size = default_max_nesting;
  6281. d->status = status;
  6282. upb_pbdecoder_reset(d);
  6283. upb_bytessink_reset(&d->input_, &m->input_handler_, d);
  6284. if (d->method_->dest_handlers_) {
  6285. if (sink.handlers != d->method_->dest_handlers_)
  6286. return NULL;
  6287. }
  6288. d->top->sink = sink;
  6289. /* If this fails, increase the value in decoder.h. */
  6290. UPB_ASSERT_DEBUGVAR(upb_arena_bytesallocated(a) - size_before <=
  6291. UPB_PB_DECODER_SIZE);
  6292. return d;
  6293. }
  6294. uint64_t upb_pbdecoder_bytesparsed(const upb_pbdecoder *d) {
  6295. return offset(d);
  6296. }
  6297. const upb_pbdecodermethod *upb_pbdecoder_method(const upb_pbdecoder *d) {
  6298. return d->method_;
  6299. }
  6300. upb_bytessink upb_pbdecoder_input(upb_pbdecoder *d) {
  6301. return d->input_;
  6302. }
  6303. size_t upb_pbdecoder_maxnesting(const upb_pbdecoder *d) {
  6304. return d->stack_size;
  6305. }
  6306. bool upb_pbdecoder_setmaxnesting(upb_pbdecoder *d, size_t max) {
  6307. UPB_ASSERT(d->top >= d->stack);
  6308. if (max < (size_t)(d->top - d->stack)) {
  6309. /* Can't set a limit smaller than what we are currently at. */
  6310. return false;
  6311. }
  6312. if (max > d->stack_size) {
  6313. /* Need to reallocate stack and callstack to accommodate. */
  6314. size_t old_size = stacksize(d, d->stack_size);
  6315. size_t new_size = stacksize(d, max);
  6316. void *p = upb_arena_realloc(d->arena, d->stack, old_size, new_size);
  6317. if (!p) {
  6318. return false;
  6319. }
  6320. d->stack = p;
  6321. old_size = callstacksize(d, d->stack_size);
  6322. new_size = callstacksize(d, max);
  6323. p = upb_arena_realloc(d->arena, d->callstack, old_size, new_size);
  6324. if (!p) {
  6325. return false;
  6326. }
  6327. d->callstack = p;
  6328. d->stack_size = max;
  6329. }
  6330. d->limit = d->stack + max - 1;
  6331. return true;
  6332. }
  6333. /*
  6334. ** upb::Encoder
  6335. **
  6336. ** Since we are implementing pure handlers (ie. without any out-of-band access
  6337. ** to pre-computed lengths), we have to buffer all submessages before we can
  6338. ** emit even their first byte.
  6339. **
  6340. ** Not knowing the size of submessages also means we can't write a perfect
  6341. ** zero-copy implementation, even with buffering. Lengths are stored as
  6342. ** varints, which means that we don't know how many bytes to reserve for the
  6343. ** length until we know what the length is.
  6344. **
  6345. ** This leaves us with three main choices:
  6346. **
  6347. ** 1. buffer all submessage data in a temporary buffer, then copy it exactly
  6348. ** once into the output buffer.
  6349. **
  6350. ** 2. attempt to buffer data directly into the output buffer, estimating how
  6351. ** many bytes each length will take. When our guesses are wrong, use
  6352. ** memmove() to grow or shrink the allotted space.
  6353. **
  6354. ** 3. buffer directly into the output buffer, allocating a max length
  6355. ** ahead-of-time for each submessage length. If we overallocated, we waste
  6356. ** space, but no memcpy() or memmove() is required. This approach requires
  6357. ** defining a maximum size for submessages and rejecting submessages that
  6358. ** exceed that size.
  6359. **
  6360. ** (2) and (3) have the potential to have better performance, but they are more
  6361. ** complicated and subtle to implement:
  6362. **
  6363. ** (3) requires making an arbitrary choice of the maximum message size; it
  6364. ** wastes space when submessages are shorter than this and fails
  6365. ** completely when they are longer. This makes it more finicky and
  6366. ** requires configuration based on the input. It also makes it impossible
  6367. ** to perfectly match the output of reference encoders that always use the
  6368. ** optimal amount of space for each length.
  6369. **
  6370. ** (2) requires guessing the the size upfront, and if multiple lengths are
  6371. ** guessed wrong the minimum required number of memmove() operations may
  6372. ** be complicated to compute correctly. Implemented properly, it may have
  6373. ** a useful amortized or average cost, but more investigation is required
  6374. ** to determine this and what the optimal algorithm is to achieve it.
  6375. **
  6376. ** (1) makes you always pay for exactly one copy, but its implementation is
  6377. ** the simplest and its performance is predictable.
  6378. **
  6379. ** So for now, we implement (1) only. If we wish to optimize later, we should
  6380. ** be able to do it without affecting users.
  6381. **
  6382. ** The strategy is to buffer the segments of data that do *not* depend on
  6383. ** unknown lengths in one buffer, and keep a separate buffer of segment pointers
  6384. ** and lengths. When the top-level submessage ends, we can go beginning to end,
  6385. ** alternating the writing of lengths with memcpy() of the rest of the data.
  6386. ** At the top level though, no buffering is required.
  6387. */
  6388. /* The output buffer is divided into segments; a segment is a string of data
  6389. * that is "ready to go" -- it does not need any varint lengths inserted into
  6390. * the middle. The seams between segments are where varints will be inserted
  6391. * once they are known.
  6392. *
  6393. * We also use the concept of a "run", which is a range of encoded bytes that
  6394. * occur at a single submessage level. Every segment contains one or more runs.
  6395. *
  6396. * A segment can span messages. Consider:
  6397. *
  6398. * .--Submessage lengths---------.
  6399. * | | |
  6400. * | V V
  6401. * V | |--------------- | |-----------------
  6402. * Submessages: | |-----------------------------------------------
  6403. * Top-level msg: ------------------------------------------------------------
  6404. *
  6405. * Segments: ----- ------------------- -----------------
  6406. * Runs: *---- *--------------*--- *----------------
  6407. * (* marks the start)
  6408. *
  6409. * Note that the top-level menssage is not in any segment because it does not
  6410. * have any length preceding it.
  6411. *
  6412. * A segment is only interrupted when another length needs to be inserted. So
  6413. * observe how the second segment spans both the inner submessage and part of
  6414. * the next enclosing message. */
  6415. typedef struct {
  6416. uint32_t msglen; /* The length to varint-encode before this segment. */
  6417. uint32_t seglen; /* Length of the segment. */
  6418. } upb_pb_encoder_segment;
  6419. struct upb_pb_encoder {
  6420. upb_arena *arena;
  6421. /* Our input and output. */
  6422. upb_sink input_;
  6423. upb_bytessink output_;
  6424. /* The "subclosure" -- used as the inner closure as part of the bytessink
  6425. * protocol. */
  6426. void *subc;
  6427. /* The output buffer and limit, and our current write position. "buf"
  6428. * initially points to "initbuf", but is dynamically allocated if we need to
  6429. * grow beyond the initial size. */
  6430. char *buf, *ptr, *limit;
  6431. /* The beginning of the current run, or undefined if we are at the top
  6432. * level. */
  6433. char *runbegin;
  6434. /* The list of segments we are accumulating. */
  6435. upb_pb_encoder_segment *segbuf, *segptr, *seglimit;
  6436. /* The stack of enclosing submessages. Each entry in the stack points to the
  6437. * segment where this submessage's length is being accumulated. */
  6438. int *stack, *top, *stacklimit;
  6439. /* Depth of startmsg/endmsg calls. */
  6440. int depth;
  6441. };
  6442. /* low-level buffering ********************************************************/
  6443. /* Low-level functions for interacting with the output buffer. */
  6444. /* TODO(haberman): handle pushback */
  6445. static void putbuf(upb_pb_encoder *e, const char *buf, size_t len) {
  6446. size_t n = upb_bytessink_putbuf(e->output_, e->subc, buf, len, NULL);
  6447. UPB_ASSERT(n == len);
  6448. }
  6449. static upb_pb_encoder_segment *top(upb_pb_encoder *e) {
  6450. return &e->segbuf[*e->top];
  6451. }
  6452. /* Call to ensure that at least "bytes" bytes are available for writing at
  6453. * e->ptr. Returns false if the bytes could not be allocated. */
  6454. static bool reserve(upb_pb_encoder *e, size_t bytes) {
  6455. if ((size_t)(e->limit - e->ptr) < bytes) {
  6456. /* Grow buffer. */
  6457. char *new_buf;
  6458. size_t needed = bytes + (e->ptr - e->buf);
  6459. size_t old_size = e->limit - e->buf;
  6460. size_t new_size = old_size;
  6461. while (new_size < needed) {
  6462. new_size *= 2;
  6463. }
  6464. new_buf = upb_arena_realloc(e->arena, e->buf, old_size, new_size);
  6465. if (new_buf == NULL) {
  6466. return false;
  6467. }
  6468. e->ptr = new_buf + (e->ptr - e->buf);
  6469. e->runbegin = new_buf + (e->runbegin - e->buf);
  6470. e->limit = new_buf + new_size;
  6471. e->buf = new_buf;
  6472. }
  6473. return true;
  6474. }
  6475. /* Call when "bytes" bytes have been writte at e->ptr. The caller *must* have
  6476. * previously called reserve() with at least this many bytes. */
  6477. static void encoder_advance(upb_pb_encoder *e, size_t bytes) {
  6478. UPB_ASSERT((size_t)(e->limit - e->ptr) >= bytes);
  6479. e->ptr += bytes;
  6480. }
  6481. /* Call when all of the bytes for a handler have been written. Flushes the
  6482. * bytes if possible and necessary, returning false if this failed. */
  6483. static bool commit(upb_pb_encoder *e) {
  6484. if (!e->top) {
  6485. /* We aren't inside a delimited region. Flush our accumulated bytes to
  6486. * the output.
  6487. *
  6488. * TODO(haberman): in the future we may want to delay flushing for
  6489. * efficiency reasons. */
  6490. putbuf(e, e->buf, e->ptr - e->buf);
  6491. e->ptr = e->buf;
  6492. }
  6493. return true;
  6494. }
  6495. /* Writes the given bytes to the buffer, handling reserve/advance. */
  6496. static bool encode_bytes(upb_pb_encoder *e, const void *data, size_t len) {
  6497. if (!reserve(e, len)) {
  6498. return false;
  6499. }
  6500. memcpy(e->ptr, data, len);
  6501. encoder_advance(e, len);
  6502. return true;
  6503. }
  6504. /* Finish the current run by adding the run totals to the segment and message
  6505. * length. */
  6506. static void accumulate(upb_pb_encoder *e) {
  6507. size_t run_len;
  6508. UPB_ASSERT(e->ptr >= e->runbegin);
  6509. run_len = e->ptr - e->runbegin;
  6510. e->segptr->seglen += run_len;
  6511. top(e)->msglen += run_len;
  6512. e->runbegin = e->ptr;
  6513. }
  6514. /* Call to indicate the start of delimited region for which the full length is
  6515. * not yet known. All data will be buffered until the length is known.
  6516. * Delimited regions may be nested; their lengths will all be tracked properly. */
  6517. static bool start_delim(upb_pb_encoder *e) {
  6518. if (e->top) {
  6519. /* We are already buffering, advance to the next segment and push it on the
  6520. * stack. */
  6521. accumulate(e);
  6522. if (++e->top == e->stacklimit) {
  6523. /* TODO(haberman): grow stack? */
  6524. return false;
  6525. }
  6526. if (++e->segptr == e->seglimit) {
  6527. /* Grow segment buffer. */
  6528. size_t old_size =
  6529. (e->seglimit - e->segbuf) * sizeof(upb_pb_encoder_segment);
  6530. size_t new_size = old_size * 2;
  6531. upb_pb_encoder_segment *new_buf =
  6532. upb_arena_realloc(e->arena, e->segbuf, old_size, new_size);
  6533. if (new_buf == NULL) {
  6534. return false;
  6535. }
  6536. e->segptr = new_buf + (e->segptr - e->segbuf);
  6537. e->seglimit = new_buf + (new_size / sizeof(upb_pb_encoder_segment));
  6538. e->segbuf = new_buf;
  6539. }
  6540. } else {
  6541. /* We were previously at the top level, start buffering. */
  6542. e->segptr = e->segbuf;
  6543. e->top = e->stack;
  6544. e->runbegin = e->ptr;
  6545. }
  6546. *e->top = e->segptr - e->segbuf;
  6547. e->segptr->seglen = 0;
  6548. e->segptr->msglen = 0;
  6549. return true;
  6550. }
  6551. /* Call to indicate the end of a delimited region. We now know the length of
  6552. * the delimited region. If we are not nested inside any other delimited
  6553. * regions, we can now emit all of the buffered data we accumulated. */
  6554. static bool end_delim(upb_pb_encoder *e) {
  6555. size_t msglen;
  6556. accumulate(e);
  6557. msglen = top(e)->msglen;
  6558. if (e->top == e->stack) {
  6559. /* All lengths are now available, emit all buffered data. */
  6560. char buf[UPB_PB_VARINT_MAX_LEN];
  6561. upb_pb_encoder_segment *s;
  6562. const char *ptr = e->buf;
  6563. for (s = e->segbuf; s <= e->segptr; s++) {
  6564. size_t lenbytes = upb_vencode64(s->msglen, buf);
  6565. putbuf(e, buf, lenbytes);
  6566. putbuf(e, ptr, s->seglen);
  6567. ptr += s->seglen;
  6568. }
  6569. e->ptr = e->buf;
  6570. e->top = NULL;
  6571. } else {
  6572. /* Need to keep buffering; propagate length info into enclosing
  6573. * submessages. */
  6574. --e->top;
  6575. top(e)->msglen += msglen + upb_varint_size(msglen);
  6576. }
  6577. return true;
  6578. }
  6579. /* tag_t **********************************************************************/
  6580. /* A precomputed (pre-encoded) tag and length. */
  6581. typedef struct {
  6582. uint8_t bytes;
  6583. char tag[7];
  6584. } tag_t;
  6585. /* Allocates a new tag for this field, and sets it in these handlerattr. */
  6586. static void new_tag(upb_handlers *h, const upb_fielddef *f, upb_wiretype_t wt,
  6587. upb_handlerattr *attr) {
  6588. uint32_t n = upb_fielddef_number(f);
  6589. tag_t *tag = upb_gmalloc(sizeof(tag_t));
  6590. tag->bytes = upb_vencode64((n << 3) | wt, tag->tag);
  6591. attr->handler_data = tag;
  6592. upb_handlers_addcleanup(h, tag, upb_gfree);
  6593. }
  6594. static bool encode_tag(upb_pb_encoder *e, const tag_t *tag) {
  6595. return encode_bytes(e, tag->tag, tag->bytes);
  6596. }
  6597. /* encoding of wire types *****************************************************/
  6598. static bool encode_fixed64(upb_pb_encoder *e, uint64_t val) {
  6599. /* TODO(haberman): byte-swap for big endian. */
  6600. return encode_bytes(e, &val, sizeof(uint64_t));
  6601. }
  6602. static bool encode_fixed32(upb_pb_encoder *e, uint32_t val) {
  6603. /* TODO(haberman): byte-swap for big endian. */
  6604. return encode_bytes(e, &val, sizeof(uint32_t));
  6605. }
  6606. static bool encode_varint(upb_pb_encoder *e, uint64_t val) {
  6607. if (!reserve(e, UPB_PB_VARINT_MAX_LEN)) {
  6608. return false;
  6609. }
  6610. encoder_advance(e, upb_vencode64(val, e->ptr));
  6611. return true;
  6612. }
  6613. static uint64_t dbl2uint64(double d) {
  6614. uint64_t ret;
  6615. memcpy(&ret, &d, sizeof(uint64_t));
  6616. return ret;
  6617. }
  6618. static uint32_t flt2uint32(float d) {
  6619. uint32_t ret;
  6620. memcpy(&ret, &d, sizeof(uint32_t));
  6621. return ret;
  6622. }
  6623. /* encoding of proto types ****************************************************/
  6624. static bool startmsg(void *c, const void *hd) {
  6625. upb_pb_encoder *e = c;
  6626. UPB_UNUSED(hd);
  6627. if (e->depth++ == 0) {
  6628. upb_bytessink_start(e->output_, 0, &e->subc);
  6629. }
  6630. return true;
  6631. }
  6632. static bool endmsg(void *c, const void *hd, upb_status *status) {
  6633. upb_pb_encoder *e = c;
  6634. UPB_UNUSED(hd);
  6635. UPB_UNUSED(status);
  6636. if (--e->depth == 0) {
  6637. upb_bytessink_end(e->output_);
  6638. }
  6639. return true;
  6640. }
  6641. static void *encode_startdelimfield(void *c, const void *hd) {
  6642. bool ok = encode_tag(c, hd) && commit(c) && start_delim(c);
  6643. return ok ? c : UPB_BREAK;
  6644. }
  6645. static bool encode_unknown(void *c, const void *hd, const char *buf,
  6646. size_t len) {
  6647. UPB_UNUSED(hd);
  6648. return encode_bytes(c, buf, len) && commit(c);
  6649. }
  6650. static bool encode_enddelimfield(void *c, const void *hd) {
  6651. UPB_UNUSED(hd);
  6652. return end_delim(c);
  6653. }
  6654. static void *encode_startgroup(void *c, const void *hd) {
  6655. return (encode_tag(c, hd) && commit(c)) ? c : UPB_BREAK;
  6656. }
  6657. static bool encode_endgroup(void *c, const void *hd) {
  6658. return encode_tag(c, hd) && commit(c);
  6659. }
  6660. static void *encode_startstr(void *c, const void *hd, size_t size_hint) {
  6661. UPB_UNUSED(size_hint);
  6662. return encode_startdelimfield(c, hd);
  6663. }
  6664. static size_t encode_strbuf(void *c, const void *hd, const char *buf,
  6665. size_t len, const upb_bufhandle *h) {
  6666. UPB_UNUSED(hd);
  6667. UPB_UNUSED(h);
  6668. return encode_bytes(c, buf, len) ? len : 0;
  6669. }
  6670. #define T(type, ctype, convert, encode) \
  6671. static bool encode_scalar_##type(void *e, const void *hd, ctype val) { \
  6672. return encode_tag(e, hd) && encode(e, (convert)(val)) && commit(e); \
  6673. } \
  6674. static bool encode_packed_##type(void *e, const void *hd, ctype val) { \
  6675. UPB_UNUSED(hd); \
  6676. return encode(e, (convert)(val)); \
  6677. }
  6678. T(double, double, dbl2uint64, encode_fixed64)
  6679. T(float, float, flt2uint32, encode_fixed32)
  6680. T(int64, int64_t, uint64_t, encode_varint)
  6681. T(int32, int32_t, int64_t, encode_varint)
  6682. T(fixed64, uint64_t, uint64_t, encode_fixed64)
  6683. T(fixed32, uint32_t, uint32_t, encode_fixed32)
  6684. T(bool, bool, bool, encode_varint)
  6685. T(uint32, uint32_t, uint32_t, encode_varint)
  6686. T(uint64, uint64_t, uint64_t, encode_varint)
  6687. T(enum, int32_t, uint32_t, encode_varint)
  6688. T(sfixed32, int32_t, uint32_t, encode_fixed32)
  6689. T(sfixed64, int64_t, uint64_t, encode_fixed64)
  6690. T(sint32, int32_t, upb_zzenc_32, encode_varint)
  6691. T(sint64, int64_t, upb_zzenc_64, encode_varint)
  6692. #undef T
  6693. /* code to build the handlers *************************************************/
  6694. #include <stdio.h>
  6695. static void newhandlers_callback(const void *closure, upb_handlers *h) {
  6696. const upb_msgdef *m;
  6697. upb_msg_field_iter i;
  6698. UPB_UNUSED(closure);
  6699. upb_handlers_setstartmsg(h, startmsg, NULL);
  6700. upb_handlers_setendmsg(h, endmsg, NULL);
  6701. upb_handlers_setunknown(h, encode_unknown, NULL);
  6702. m = upb_handlers_msgdef(h);
  6703. for(upb_msg_field_begin(&i, m);
  6704. !upb_msg_field_done(&i);
  6705. upb_msg_field_next(&i)) {
  6706. const upb_fielddef *f = upb_msg_iter_field(&i);
  6707. bool packed = upb_fielddef_isseq(f) && upb_fielddef_isprimitive(f) &&
  6708. upb_fielddef_packed(f);
  6709. upb_handlerattr attr = UPB_HANDLERATTR_INIT;
  6710. upb_wiretype_t wt =
  6711. packed ? UPB_WIRE_TYPE_DELIMITED
  6712. : upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  6713. /* Pre-encode the tag for this field. */
  6714. new_tag(h, f, wt, &attr);
  6715. if (packed) {
  6716. upb_handlers_setstartseq(h, f, encode_startdelimfield, &attr);
  6717. upb_handlers_setendseq(h, f, encode_enddelimfield, &attr);
  6718. }
  6719. #define T(upper, lower, upbtype) \
  6720. case UPB_DESCRIPTOR_TYPE_##upper: \
  6721. if (packed) { \
  6722. upb_handlers_set##upbtype(h, f, encode_packed_##lower, &attr); \
  6723. } else { \
  6724. upb_handlers_set##upbtype(h, f, encode_scalar_##lower, &attr); \
  6725. } \
  6726. break;
  6727. switch (upb_fielddef_descriptortype(f)) {
  6728. T(DOUBLE, double, double);
  6729. T(FLOAT, float, float);
  6730. T(INT64, int64, int64);
  6731. T(INT32, int32, int32);
  6732. T(FIXED64, fixed64, uint64);
  6733. T(FIXED32, fixed32, uint32);
  6734. T(BOOL, bool, bool);
  6735. T(UINT32, uint32, uint32);
  6736. T(UINT64, uint64, uint64);
  6737. T(ENUM, enum, int32);
  6738. T(SFIXED32, sfixed32, int32);
  6739. T(SFIXED64, sfixed64, int64);
  6740. T(SINT32, sint32, int32);
  6741. T(SINT64, sint64, int64);
  6742. case UPB_DESCRIPTOR_TYPE_STRING:
  6743. case UPB_DESCRIPTOR_TYPE_BYTES:
  6744. upb_handlers_setstartstr(h, f, encode_startstr, &attr);
  6745. upb_handlers_setendstr(h, f, encode_enddelimfield, &attr);
  6746. upb_handlers_setstring(h, f, encode_strbuf, &attr);
  6747. break;
  6748. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  6749. upb_handlers_setstartsubmsg(h, f, encode_startdelimfield, &attr);
  6750. upb_handlers_setendsubmsg(h, f, encode_enddelimfield, &attr);
  6751. break;
  6752. case UPB_DESCRIPTOR_TYPE_GROUP: {
  6753. /* Endgroup takes a different tag (wire_type = END_GROUP). */
  6754. upb_handlerattr attr2 = UPB_HANDLERATTR_INIT;
  6755. new_tag(h, f, UPB_WIRE_TYPE_END_GROUP, &attr2);
  6756. upb_handlers_setstartsubmsg(h, f, encode_startgroup, &attr);
  6757. upb_handlers_setendsubmsg(h, f, encode_endgroup, &attr2);
  6758. break;
  6759. }
  6760. }
  6761. #undef T
  6762. }
  6763. }
  6764. void upb_pb_encoder_reset(upb_pb_encoder *e) {
  6765. e->segptr = NULL;
  6766. e->top = NULL;
  6767. e->depth = 0;
  6768. }
  6769. /* public API *****************************************************************/
  6770. upb_handlercache *upb_pb_encoder_newcache(void) {
  6771. return upb_handlercache_new(newhandlers_callback, NULL);
  6772. }
  6773. upb_pb_encoder *upb_pb_encoder_create(upb_arena *arena, const upb_handlers *h,
  6774. upb_bytessink output) {
  6775. const size_t initial_bufsize = 256;
  6776. const size_t initial_segbufsize = 16;
  6777. /* TODO(haberman): make this configurable. */
  6778. const size_t stack_size = 64;
  6779. #ifndef NDEBUG
  6780. const size_t size_before = upb_arena_bytesallocated(arena);
  6781. #endif
  6782. upb_pb_encoder *e = upb_arena_malloc(arena, sizeof(upb_pb_encoder));
  6783. if (!e) return NULL;
  6784. e->buf = upb_arena_malloc(arena, initial_bufsize);
  6785. e->segbuf = upb_arena_malloc(arena, initial_segbufsize * sizeof(*e->segbuf));
  6786. e->stack = upb_arena_malloc(arena, stack_size * sizeof(*e->stack));
  6787. if (!e->buf || !e->segbuf || !e->stack) {
  6788. return NULL;
  6789. }
  6790. e->limit = e->buf + initial_bufsize;
  6791. e->seglimit = e->segbuf + initial_segbufsize;
  6792. e->stacklimit = e->stack + stack_size;
  6793. upb_pb_encoder_reset(e);
  6794. upb_sink_reset(&e->input_, h, e);
  6795. e->arena = arena;
  6796. e->output_ = output;
  6797. e->subc = output.closure;
  6798. e->ptr = e->buf;
  6799. /* If this fails, increase the value in encoder.h. */
  6800. UPB_ASSERT_DEBUGVAR(upb_arena_bytesallocated(arena) - size_before <=
  6801. UPB_PB_ENCODER_SIZE);
  6802. return e;
  6803. }
  6804. upb_sink upb_pb_encoder_input(upb_pb_encoder *e) { return e->input_; }
  6805. /*
  6806. * upb::pb::TextPrinter
  6807. *
  6808. * OPT: This is not optimized at all. It uses printf() which parses the format
  6809. * string every time, and it allocates memory for every put.
  6810. */
  6811. #include <ctype.h>
  6812. #include <float.h>
  6813. #include <inttypes.h>
  6814. #include <stdarg.h>
  6815. #include <stdio.h>
  6816. #include <string.h>
  6817. struct upb_textprinter {
  6818. upb_sink input_;
  6819. upb_bytessink output_;
  6820. int indent_depth_;
  6821. bool single_line_;
  6822. void *subc;
  6823. };
  6824. #define CHECK(x) if ((x) < 0) goto err;
  6825. static const char *shortname(const char *longname) {
  6826. const char *last = strrchr(longname, '.');
  6827. return last ? last + 1 : longname;
  6828. }
  6829. static int indent(upb_textprinter *p) {
  6830. int i;
  6831. if (!p->single_line_)
  6832. for (i = 0; i < p->indent_depth_; i++)
  6833. upb_bytessink_putbuf(p->output_, p->subc, " ", 2, NULL);
  6834. return 0;
  6835. }
  6836. static int endfield(upb_textprinter *p) {
  6837. const char ch = (p->single_line_ ? ' ' : '\n');
  6838. upb_bytessink_putbuf(p->output_, p->subc, &ch, 1, NULL);
  6839. return 0;
  6840. }
  6841. static int putescaped(upb_textprinter *p, const char *buf, size_t len,
  6842. bool preserve_utf8) {
  6843. /* Based on CEscapeInternal() from Google's protobuf release. */
  6844. char dstbuf[4096], *dst = dstbuf, *dstend = dstbuf + sizeof(dstbuf);
  6845. const char *end = buf + len;
  6846. /* I think hex is prettier and more useful, but proto2 uses octal; should
  6847. * investigate whether it can parse hex also. */
  6848. const bool use_hex = false;
  6849. bool last_hex_escape = false; /* true if last output char was \xNN */
  6850. for (; buf < end; buf++) {
  6851. bool is_hex_escape;
  6852. if (dstend - dst < 4) {
  6853. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  6854. dst = dstbuf;
  6855. }
  6856. is_hex_escape = false;
  6857. switch (*buf) {
  6858. case '\n': *(dst++) = '\\'; *(dst++) = 'n'; break;
  6859. case '\r': *(dst++) = '\\'; *(dst++) = 'r'; break;
  6860. case '\t': *(dst++) = '\\'; *(dst++) = 't'; break;
  6861. case '\"': *(dst++) = '\\'; *(dst++) = '\"'; break;
  6862. case '\'': *(dst++) = '\\'; *(dst++) = '\''; break;
  6863. case '\\': *(dst++) = '\\'; *(dst++) = '\\'; break;
  6864. default:
  6865. /* Note that if we emit \xNN and the buf character after that is a hex
  6866. * digit then that digit must be escaped too to prevent it being
  6867. * interpreted as part of the character code by C. */
  6868. if ((!preserve_utf8 || (uint8_t)*buf < 0x80) &&
  6869. (!isprint(*buf) || (last_hex_escape && isxdigit(*buf)))) {
  6870. sprintf(dst, (use_hex ? "\\x%02x" : "\\%03o"), (uint8_t)*buf);
  6871. is_hex_escape = use_hex;
  6872. dst += 4;
  6873. } else {
  6874. *(dst++) = *buf; break;
  6875. }
  6876. }
  6877. last_hex_escape = is_hex_escape;
  6878. }
  6879. /* Flush remaining data. */
  6880. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  6881. return 0;
  6882. }
  6883. bool putf(upb_textprinter *p, const char *fmt, ...) {
  6884. va_list args;
  6885. va_list args_copy;
  6886. char *str;
  6887. int written;
  6888. int len;
  6889. bool ok;
  6890. va_start(args, fmt);
  6891. /* Run once to get the length of the string. */
  6892. _upb_va_copy(args_copy, args);
  6893. len = _upb_vsnprintf(NULL, 0, fmt, args_copy);
  6894. va_end(args_copy);
  6895. /* + 1 for NULL terminator (vsprintf() requires it even if we don't). */
  6896. str = upb_gmalloc(len + 1);
  6897. if (!str) return false;
  6898. written = vsprintf(str, fmt, args);
  6899. va_end(args);
  6900. UPB_ASSERT(written == len);
  6901. ok = upb_bytessink_putbuf(p->output_, p->subc, str, len, NULL);
  6902. upb_gfree(str);
  6903. return ok;
  6904. }
  6905. /* handlers *******************************************************************/
  6906. static bool textprinter_startmsg(void *c, const void *hd) {
  6907. upb_textprinter *p = c;
  6908. UPB_UNUSED(hd);
  6909. if (p->indent_depth_ == 0) {
  6910. upb_bytessink_start(p->output_, 0, &p->subc);
  6911. }
  6912. return true;
  6913. }
  6914. static bool textprinter_endmsg(void *c, const void *hd, upb_status *s) {
  6915. upb_textprinter *p = c;
  6916. UPB_UNUSED(hd);
  6917. UPB_UNUSED(s);
  6918. if (p->indent_depth_ == 0) {
  6919. upb_bytessink_end(p->output_);
  6920. }
  6921. return true;
  6922. }
  6923. #define TYPE(name, ctype, fmt) \
  6924. static bool textprinter_put ## name(void *closure, const void *handler_data, \
  6925. ctype val) { \
  6926. upb_textprinter *p = closure; \
  6927. const upb_fielddef *f = handler_data; \
  6928. CHECK(indent(p)); \
  6929. putf(p, "%s: " fmt, upb_fielddef_name(f), val); \
  6930. CHECK(endfield(p)); \
  6931. return true; \
  6932. err: \
  6933. return false; \
  6934. }
  6935. static bool textprinter_putbool(void *closure, const void *handler_data,
  6936. bool val) {
  6937. upb_textprinter *p = closure;
  6938. const upb_fielddef *f = handler_data;
  6939. CHECK(indent(p));
  6940. putf(p, "%s: %s", upb_fielddef_name(f), val ? "true" : "false");
  6941. CHECK(endfield(p));
  6942. return true;
  6943. err:
  6944. return false;
  6945. }
  6946. #define STRINGIFY_HELPER(x) #x
  6947. #define STRINGIFY_MACROVAL(x) STRINGIFY_HELPER(x)
  6948. TYPE(int32, int32_t, "%" PRId32)
  6949. TYPE(int64, int64_t, "%" PRId64)
  6950. TYPE(uint32, uint32_t, "%" PRIu32)
  6951. TYPE(uint64, uint64_t, "%" PRIu64)
  6952. TYPE(float, float, "%." STRINGIFY_MACROVAL(FLT_DIG) "g")
  6953. TYPE(double, double, "%." STRINGIFY_MACROVAL(DBL_DIG) "g")
  6954. #undef TYPE
  6955. /* Output a symbolic value from the enum if found, else just print as int32. */
  6956. static bool textprinter_putenum(void *closure, const void *handler_data,
  6957. int32_t val) {
  6958. upb_textprinter *p = closure;
  6959. const upb_fielddef *f = handler_data;
  6960. const upb_enumdef *enum_def = upb_fielddef_enumsubdef(f);
  6961. const char *label = upb_enumdef_iton(enum_def, val);
  6962. if (label) {
  6963. indent(p);
  6964. putf(p, "%s: %s", upb_fielddef_name(f), label);
  6965. endfield(p);
  6966. } else {
  6967. if (!textprinter_putint32(closure, handler_data, val))
  6968. return false;
  6969. }
  6970. return true;
  6971. }
  6972. static void *textprinter_startstr(void *closure, const void *handler_data,
  6973. size_t size_hint) {
  6974. upb_textprinter *p = closure;
  6975. const upb_fielddef *f = handler_data;
  6976. UPB_UNUSED(size_hint);
  6977. indent(p);
  6978. putf(p, "%s: \"", upb_fielddef_name(f));
  6979. return p;
  6980. }
  6981. static bool textprinter_endstr(void *closure, const void *handler_data) {
  6982. upb_textprinter *p = closure;
  6983. UPB_UNUSED(handler_data);
  6984. putf(p, "\"");
  6985. endfield(p);
  6986. return true;
  6987. }
  6988. static size_t textprinter_putstr(void *closure, const void *hd, const char *buf,
  6989. size_t len, const upb_bufhandle *handle) {
  6990. upb_textprinter *p = closure;
  6991. const upb_fielddef *f = hd;
  6992. UPB_UNUSED(handle);
  6993. CHECK(putescaped(p, buf, len, upb_fielddef_type(f) == UPB_TYPE_STRING));
  6994. return len;
  6995. err:
  6996. return 0;
  6997. }
  6998. static void *textprinter_startsubmsg(void *closure, const void *handler_data) {
  6999. upb_textprinter *p = closure;
  7000. const char *name = handler_data;
  7001. CHECK(indent(p));
  7002. putf(p, "%s {%c", name, p->single_line_ ? ' ' : '\n');
  7003. p->indent_depth_++;
  7004. return p;
  7005. err:
  7006. return UPB_BREAK;
  7007. }
  7008. static bool textprinter_endsubmsg(void *closure, const void *handler_data) {
  7009. upb_textprinter *p = closure;
  7010. UPB_UNUSED(handler_data);
  7011. p->indent_depth_--;
  7012. CHECK(indent(p));
  7013. upb_bytessink_putbuf(p->output_, p->subc, "}", 1, NULL);
  7014. CHECK(endfield(p));
  7015. return true;
  7016. err:
  7017. return false;
  7018. }
  7019. static void onmreg(const void *c, upb_handlers *h) {
  7020. const upb_msgdef *m = upb_handlers_msgdef(h);
  7021. upb_msg_field_iter i;
  7022. UPB_UNUSED(c);
  7023. upb_handlers_setstartmsg(h, textprinter_startmsg, NULL);
  7024. upb_handlers_setendmsg(h, textprinter_endmsg, NULL);
  7025. for(upb_msg_field_begin(&i, m);
  7026. !upb_msg_field_done(&i);
  7027. upb_msg_field_next(&i)) {
  7028. upb_fielddef *f = upb_msg_iter_field(&i);
  7029. upb_handlerattr attr = UPB_HANDLERATTR_INIT;
  7030. attr.handler_data = f;
  7031. switch (upb_fielddef_type(f)) {
  7032. case UPB_TYPE_INT32:
  7033. upb_handlers_setint32(h, f, textprinter_putint32, &attr);
  7034. break;
  7035. case UPB_TYPE_INT64:
  7036. upb_handlers_setint64(h, f, textprinter_putint64, &attr);
  7037. break;
  7038. case UPB_TYPE_UINT32:
  7039. upb_handlers_setuint32(h, f, textprinter_putuint32, &attr);
  7040. break;
  7041. case UPB_TYPE_UINT64:
  7042. upb_handlers_setuint64(h, f, textprinter_putuint64, &attr);
  7043. break;
  7044. case UPB_TYPE_FLOAT:
  7045. upb_handlers_setfloat(h, f, textprinter_putfloat, &attr);
  7046. break;
  7047. case UPB_TYPE_DOUBLE:
  7048. upb_handlers_setdouble(h, f, textprinter_putdouble, &attr);
  7049. break;
  7050. case UPB_TYPE_BOOL:
  7051. upb_handlers_setbool(h, f, textprinter_putbool, &attr);
  7052. break;
  7053. case UPB_TYPE_STRING:
  7054. case UPB_TYPE_BYTES:
  7055. upb_handlers_setstartstr(h, f, textprinter_startstr, &attr);
  7056. upb_handlers_setstring(h, f, textprinter_putstr, &attr);
  7057. upb_handlers_setendstr(h, f, textprinter_endstr, &attr);
  7058. break;
  7059. case UPB_TYPE_MESSAGE: {
  7060. const char *name =
  7061. upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_GROUP
  7062. ? shortname(upb_msgdef_fullname(upb_fielddef_msgsubdef(f)))
  7063. : upb_fielddef_name(f);
  7064. attr.handler_data = name;
  7065. upb_handlers_setstartsubmsg(h, f, textprinter_startsubmsg, &attr);
  7066. upb_handlers_setendsubmsg(h, f, textprinter_endsubmsg, &attr);
  7067. break;
  7068. }
  7069. case UPB_TYPE_ENUM:
  7070. upb_handlers_setint32(h, f, textprinter_putenum, &attr);
  7071. break;
  7072. }
  7073. }
  7074. }
  7075. static void textprinter_reset(upb_textprinter *p, bool single_line) {
  7076. p->single_line_ = single_line;
  7077. p->indent_depth_ = 0;
  7078. }
  7079. /* Public API *****************************************************************/
  7080. upb_textprinter *upb_textprinter_create(upb_arena *arena, const upb_handlers *h,
  7081. upb_bytessink output) {
  7082. upb_textprinter *p = upb_arena_malloc(arena, sizeof(upb_textprinter));
  7083. if (!p) return NULL;
  7084. p->output_ = output;
  7085. upb_sink_reset(&p->input_, h, p);
  7086. textprinter_reset(p, false);
  7087. return p;
  7088. }
  7089. upb_handlercache *upb_textprinter_newcache(void) {
  7090. return upb_handlercache_new(&onmreg, NULL);
  7091. }
  7092. upb_sink upb_textprinter_input(upb_textprinter *p) { return p->input_; }
  7093. void upb_textprinter_setsingleline(upb_textprinter *p, bool single_line) {
  7094. p->single_line_ = single_line;
  7095. }
  7096. /* Index is descriptor type. */
  7097. const uint8_t upb_pb_native_wire_types[] = {
  7098. UPB_WIRE_TYPE_END_GROUP, /* ENDGROUP */
  7099. UPB_WIRE_TYPE_64BIT, /* DOUBLE */
  7100. UPB_WIRE_TYPE_32BIT, /* FLOAT */
  7101. UPB_WIRE_TYPE_VARINT, /* INT64 */
  7102. UPB_WIRE_TYPE_VARINT, /* UINT64 */
  7103. UPB_WIRE_TYPE_VARINT, /* INT32 */
  7104. UPB_WIRE_TYPE_64BIT, /* FIXED64 */
  7105. UPB_WIRE_TYPE_32BIT, /* FIXED32 */
  7106. UPB_WIRE_TYPE_VARINT, /* BOOL */
  7107. UPB_WIRE_TYPE_DELIMITED, /* STRING */
  7108. UPB_WIRE_TYPE_START_GROUP, /* GROUP */
  7109. UPB_WIRE_TYPE_DELIMITED, /* MESSAGE */
  7110. UPB_WIRE_TYPE_DELIMITED, /* BYTES */
  7111. UPB_WIRE_TYPE_VARINT, /* UINT32 */
  7112. UPB_WIRE_TYPE_VARINT, /* ENUM */
  7113. UPB_WIRE_TYPE_32BIT, /* SFIXED32 */
  7114. UPB_WIRE_TYPE_64BIT, /* SFIXED64 */
  7115. UPB_WIRE_TYPE_VARINT, /* SINT32 */
  7116. UPB_WIRE_TYPE_VARINT, /* SINT64 */
  7117. };
  7118. /* A basic branch-based decoder, uses 32-bit values to get good performance
  7119. * on 32-bit architectures (but performs well on 64-bits also).
  7120. * This scheme comes from the original Google Protobuf implementation
  7121. * (proto2). */
  7122. upb_decoderet upb_vdecode_max8_branch32(upb_decoderet r) {
  7123. upb_decoderet err = {NULL, 0};
  7124. const char *p = r.p;
  7125. uint32_t low = (uint32_t)r.val;
  7126. uint32_t high = 0;
  7127. uint32_t b;
  7128. b = *(p++); low |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  7129. b = *(p++); low |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  7130. b = *(p++); low |= (b & 0x7fU) << 28;
  7131. high = (b & 0x7fU) >> 4; if (!(b & 0x80)) goto done;
  7132. b = *(p++); high |= (b & 0x7fU) << 3; if (!(b & 0x80)) goto done;
  7133. b = *(p++); high |= (b & 0x7fU) << 10; if (!(b & 0x80)) goto done;
  7134. b = *(p++); high |= (b & 0x7fU) << 17; if (!(b & 0x80)) goto done;
  7135. b = *(p++); high |= (b & 0x7fU) << 24; if (!(b & 0x80)) goto done;
  7136. b = *(p++); high |= (b & 0x7fU) << 31; if (!(b & 0x80)) goto done;
  7137. return err;
  7138. done:
  7139. r.val = ((uint64_t)high << 32) | low;
  7140. r.p = p;
  7141. return r;
  7142. }
  7143. /* Like the previous, but uses 64-bit values. */
  7144. upb_decoderet upb_vdecode_max8_branch64(upb_decoderet r) {
  7145. const char *p = r.p;
  7146. uint64_t val = r.val;
  7147. uint64_t b;
  7148. upb_decoderet err = {NULL, 0};
  7149. b = *(p++); val |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  7150. b = *(p++); val |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  7151. b = *(p++); val |= (b & 0x7fU) << 28; if (!(b & 0x80)) goto done;
  7152. b = *(p++); val |= (b & 0x7fU) << 35; if (!(b & 0x80)) goto done;
  7153. b = *(p++); val |= (b & 0x7fU) << 42; if (!(b & 0x80)) goto done;
  7154. b = *(p++); val |= (b & 0x7fU) << 49; if (!(b & 0x80)) goto done;
  7155. b = *(p++); val |= (b & 0x7fU) << 56; if (!(b & 0x80)) goto done;
  7156. b = *(p++); val |= (b & 0x7fU) << 63; if (!(b & 0x80)) goto done;
  7157. return err;
  7158. done:
  7159. r.val = val;
  7160. r.p = p;
  7161. return r;
  7162. }
  7163. #line 1 "upb/json/parser.rl"
  7164. /*
  7165. ** upb::json::Parser (upb_json_parser)
  7166. **
  7167. ** A parser that uses the Ragel State Machine Compiler to generate
  7168. ** the finite automata.
  7169. **
  7170. ** Ragel only natively handles regular languages, but we can manually
  7171. ** program it a bit to handle context-free languages like JSON, by using
  7172. ** the "fcall" and "fret" constructs.
  7173. **
  7174. ** This parser can handle the basics, but needs several things to be fleshed
  7175. ** out:
  7176. **
  7177. ** - handling of unicode escape sequences (including high surrogate pairs).
  7178. ** - properly check and report errors for unknown fields, stack overflow,
  7179. ** improper array nesting (or lack of nesting).
  7180. ** - handling of base64 sequences with padding characters.
  7181. ** - handling of push-back (non-success returns from sink functions).
  7182. ** - handling of keys/escape-sequences/etc that span input buffers.
  7183. */
  7184. #include <ctype.h>
  7185. #include <errno.h>
  7186. #include <float.h>
  7187. #include <math.h>
  7188. #include <stdint.h>
  7189. #include <stdio.h>
  7190. #include <stdlib.h>
  7191. #include <string.h>
  7192. #include <time.h>
  7193. #define UPB_JSON_MAX_DEPTH 64
  7194. /* Type of value message */
  7195. enum {
  7196. VALUE_NULLVALUE = 0,
  7197. VALUE_NUMBERVALUE = 1,
  7198. VALUE_STRINGVALUE = 2,
  7199. VALUE_BOOLVALUE = 3,
  7200. VALUE_STRUCTVALUE = 4,
  7201. VALUE_LISTVALUE = 5
  7202. };
  7203. /* Forward declare */
  7204. static bool is_top_level(upb_json_parser *p);
  7205. static bool is_wellknown_msg(upb_json_parser *p, upb_wellknowntype_t type);
  7206. static bool is_wellknown_field(upb_json_parser *p, upb_wellknowntype_t type);
  7207. static bool is_number_wrapper_object(upb_json_parser *p);
  7208. static bool does_number_wrapper_start(upb_json_parser *p);
  7209. static bool does_number_wrapper_end(upb_json_parser *p);
  7210. static bool is_string_wrapper_object(upb_json_parser *p);
  7211. static bool does_string_wrapper_start(upb_json_parser *p);
  7212. static bool does_string_wrapper_end(upb_json_parser *p);
  7213. static bool does_fieldmask_start(upb_json_parser *p);
  7214. static bool does_fieldmask_end(upb_json_parser *p);
  7215. static void start_fieldmask_object(upb_json_parser *p);
  7216. static void end_fieldmask_object(upb_json_parser *p);
  7217. static void start_wrapper_object(upb_json_parser *p);
  7218. static void end_wrapper_object(upb_json_parser *p);
  7219. static void start_value_object(upb_json_parser *p, int value_type);
  7220. static void end_value_object(upb_json_parser *p);
  7221. static void start_listvalue_object(upb_json_parser *p);
  7222. static void end_listvalue_object(upb_json_parser *p);
  7223. static void start_structvalue_object(upb_json_parser *p);
  7224. static void end_structvalue_object(upb_json_parser *p);
  7225. static void start_object(upb_json_parser *p);
  7226. static void end_object(upb_json_parser *p);
  7227. static void start_any_object(upb_json_parser *p, const char *ptr);
  7228. static bool end_any_object(upb_json_parser *p, const char *ptr);
  7229. static bool start_subobject(upb_json_parser *p);
  7230. static void end_subobject(upb_json_parser *p);
  7231. static void start_member(upb_json_parser *p);
  7232. static void end_member(upb_json_parser *p);
  7233. static bool end_membername(upb_json_parser *p);
  7234. static void start_any_member(upb_json_parser *p, const char *ptr);
  7235. static void end_any_member(upb_json_parser *p, const char *ptr);
  7236. static bool end_any_membername(upb_json_parser *p);
  7237. size_t parse(void *closure, const void *hd, const char *buf, size_t size,
  7238. const upb_bufhandle *handle);
  7239. static bool end(void *closure, const void *hd);
  7240. static const char eof_ch = 'e';
  7241. /* stringsink */
  7242. typedef struct {
  7243. upb_byteshandler handler;
  7244. upb_bytessink sink;
  7245. char *ptr;
  7246. size_t len, size;
  7247. } upb_stringsink;
  7248. static void *stringsink_start(void *_sink, const void *hd, size_t size_hint) {
  7249. upb_stringsink *sink = _sink;
  7250. sink->len = 0;
  7251. UPB_UNUSED(hd);
  7252. UPB_UNUSED(size_hint);
  7253. return sink;
  7254. }
  7255. static size_t stringsink_string(void *_sink, const void *hd, const char *ptr,
  7256. size_t len, const upb_bufhandle *handle) {
  7257. upb_stringsink *sink = _sink;
  7258. size_t new_size = sink->size;
  7259. UPB_UNUSED(hd);
  7260. UPB_UNUSED(handle);
  7261. while (sink->len + len > new_size) {
  7262. new_size *= 2;
  7263. }
  7264. if (new_size != sink->size) {
  7265. sink->ptr = realloc(sink->ptr, new_size);
  7266. sink->size = new_size;
  7267. }
  7268. memcpy(sink->ptr + sink->len, ptr, len);
  7269. sink->len += len;
  7270. return len;
  7271. }
  7272. void upb_stringsink_init(upb_stringsink *sink) {
  7273. upb_byteshandler_init(&sink->handler);
  7274. upb_byteshandler_setstartstr(&sink->handler, stringsink_start, NULL);
  7275. upb_byteshandler_setstring(&sink->handler, stringsink_string, NULL);
  7276. upb_bytessink_reset(&sink->sink, &sink->handler, sink);
  7277. sink->size = 32;
  7278. sink->ptr = malloc(sink->size);
  7279. sink->len = 0;
  7280. }
  7281. void upb_stringsink_uninit(upb_stringsink *sink) { free(sink->ptr); }
  7282. typedef struct {
  7283. /* For encoding Any value field in binary format. */
  7284. upb_handlercache *encoder_handlercache;
  7285. upb_stringsink stringsink;
  7286. /* For decoding Any value field in json format. */
  7287. upb_json_codecache *parser_codecache;
  7288. upb_sink sink;
  7289. upb_json_parser *parser;
  7290. /* Mark the range of uninterpreted values in json input before type url. */
  7291. const char *before_type_url_start;
  7292. const char *before_type_url_end;
  7293. /* Mark the range of uninterpreted values in json input after type url. */
  7294. const char *after_type_url_start;
  7295. } upb_jsonparser_any_frame;
  7296. typedef struct {
  7297. upb_sink sink;
  7298. /* The current message in which we're parsing, and the field whose value we're
  7299. * expecting next. */
  7300. const upb_msgdef *m;
  7301. const upb_fielddef *f;
  7302. /* The table mapping json name to fielddef for this message. */
  7303. const upb_strtable *name_table;
  7304. /* We are in a repeated-field context. We need this flag to decide whether to
  7305. * handle the array as a normal repeated field or a
  7306. * google.protobuf.ListValue/google.protobuf.Value. */
  7307. bool is_repeated;
  7308. /* We are in a repeated-field context, ready to emit mapentries as
  7309. * submessages. This flag alters the start-of-object (open-brace) behavior to
  7310. * begin a sequence of mapentry messages rather than a single submessage. */
  7311. bool is_map;
  7312. /* We are in a map-entry message context. This flag is set when parsing the
  7313. * value field of a single map entry and indicates to all value-field parsers
  7314. * (subobjects, strings, numbers, and bools) that the map-entry submessage
  7315. * should end as soon as the value is parsed. */
  7316. bool is_mapentry;
  7317. /* If |is_map| or |is_mapentry| is true, |mapfield| refers to the parent
  7318. * message's map field that we're currently parsing. This differs from |f|
  7319. * because |f| is the field in the *current* message (i.e., the map-entry
  7320. * message itself), not the parent's field that leads to this map. */
  7321. const upb_fielddef *mapfield;
  7322. /* We are in an Any message context. This flag is set when parsing the Any
  7323. * message and indicates to all field parsers (subobjects, strings, numbers,
  7324. * and bools) that the parsed field should be serialized as binary data or
  7325. * cached (type url not found yet). */
  7326. bool is_any;
  7327. /* The type of packed message in Any. */
  7328. upb_jsonparser_any_frame *any_frame;
  7329. /* True if the field to be parsed is unknown. */
  7330. bool is_unknown_field;
  7331. } upb_jsonparser_frame;
  7332. static void init_frame(upb_jsonparser_frame* frame) {
  7333. frame->m = NULL;
  7334. frame->f = NULL;
  7335. frame->name_table = NULL;
  7336. frame->is_repeated = false;
  7337. frame->is_map = false;
  7338. frame->is_mapentry = false;
  7339. frame->mapfield = NULL;
  7340. frame->is_any = false;
  7341. frame->any_frame = NULL;
  7342. frame->is_unknown_field = false;
  7343. }
  7344. struct upb_json_parser {
  7345. upb_arena *arena;
  7346. const upb_json_parsermethod *method;
  7347. upb_bytessink input_;
  7348. /* Stack to track the JSON scopes we are in. */
  7349. upb_jsonparser_frame stack[UPB_JSON_MAX_DEPTH];
  7350. upb_jsonparser_frame *top;
  7351. upb_jsonparser_frame *limit;
  7352. upb_status *status;
  7353. /* Ragel's internal parsing stack for the parsing state machine. */
  7354. int current_state;
  7355. int parser_stack[UPB_JSON_MAX_DEPTH];
  7356. int parser_top;
  7357. /* The handle for the current buffer. */
  7358. const upb_bufhandle *handle;
  7359. /* Accumulate buffer. See details in parser.rl. */
  7360. const char *accumulated;
  7361. size_t accumulated_len;
  7362. char *accumulate_buf;
  7363. size_t accumulate_buf_size;
  7364. /* Multi-part text data. See details in parser.rl. */
  7365. int multipart_state;
  7366. upb_selector_t string_selector;
  7367. /* Input capture. See details in parser.rl. */
  7368. const char *capture;
  7369. /* Intermediate result of parsing a unicode escape sequence. */
  7370. uint32_t digit;
  7371. /* For resolve type url in Any. */
  7372. const upb_symtab *symtab;
  7373. /* Whether to proceed if unknown field is met. */
  7374. bool ignore_json_unknown;
  7375. /* Cache for parsing timestamp due to base and zone are handled in different
  7376. * handlers. */
  7377. struct tm tm;
  7378. };
  7379. static upb_jsonparser_frame* start_jsonparser_frame(upb_json_parser *p) {
  7380. upb_jsonparser_frame *inner;
  7381. inner = p->top + 1;
  7382. init_frame(inner);
  7383. return inner;
  7384. }
  7385. struct upb_json_codecache {
  7386. upb_arena *arena;
  7387. upb_inttable methods; /* upb_msgdef* -> upb_json_parsermethod* */
  7388. };
  7389. struct upb_json_parsermethod {
  7390. const upb_json_codecache *cache;
  7391. upb_byteshandler input_handler_;
  7392. /* Maps json_name -> fielddef */
  7393. upb_strtable name_table;
  7394. };
  7395. #define PARSER_CHECK_RETURN(x) if (!(x)) return false
  7396. static upb_jsonparser_any_frame *json_parser_any_frame_new(
  7397. upb_json_parser *p) {
  7398. upb_jsonparser_any_frame *frame;
  7399. frame = upb_arena_malloc(p->arena, sizeof(upb_jsonparser_any_frame));
  7400. frame->encoder_handlercache = upb_pb_encoder_newcache();
  7401. frame->parser_codecache = upb_json_codecache_new();
  7402. frame->parser = NULL;
  7403. frame->before_type_url_start = NULL;
  7404. frame->before_type_url_end = NULL;
  7405. frame->after_type_url_start = NULL;
  7406. upb_stringsink_init(&frame->stringsink);
  7407. return frame;
  7408. }
  7409. static void json_parser_any_frame_set_payload_type(
  7410. upb_json_parser *p,
  7411. upb_jsonparser_any_frame *frame,
  7412. const upb_msgdef *payload_type) {
  7413. const upb_handlers *h;
  7414. const upb_json_parsermethod *parser_method;
  7415. upb_pb_encoder *encoder;
  7416. /* Initialize encoder. */
  7417. h = upb_handlercache_get(frame->encoder_handlercache, payload_type);
  7418. encoder = upb_pb_encoder_create(p->arena, h, frame->stringsink.sink);
  7419. /* Initialize parser. */
  7420. parser_method = upb_json_codecache_get(frame->parser_codecache, payload_type);
  7421. upb_sink_reset(&frame->sink, h, encoder);
  7422. frame->parser =
  7423. upb_json_parser_create(p->arena, parser_method, p->symtab, frame->sink,
  7424. p->status, p->ignore_json_unknown);
  7425. }
  7426. static void json_parser_any_frame_free(upb_jsonparser_any_frame *frame) {
  7427. upb_handlercache_free(frame->encoder_handlercache);
  7428. upb_json_codecache_free(frame->parser_codecache);
  7429. upb_stringsink_uninit(&frame->stringsink);
  7430. }
  7431. static bool json_parser_any_frame_has_type_url(
  7432. upb_jsonparser_any_frame *frame) {
  7433. return frame->parser != NULL;
  7434. }
  7435. static bool json_parser_any_frame_has_value_before_type_url(
  7436. upb_jsonparser_any_frame *frame) {
  7437. return frame->before_type_url_start != frame->before_type_url_end;
  7438. }
  7439. static bool json_parser_any_frame_has_value_after_type_url(
  7440. upb_jsonparser_any_frame *frame) {
  7441. return frame->after_type_url_start != NULL;
  7442. }
  7443. static bool json_parser_any_frame_has_value(
  7444. upb_jsonparser_any_frame *frame) {
  7445. return json_parser_any_frame_has_value_before_type_url(frame) ||
  7446. json_parser_any_frame_has_value_after_type_url(frame);
  7447. }
  7448. static void json_parser_any_frame_set_before_type_url_end(
  7449. upb_jsonparser_any_frame *frame,
  7450. const char *ptr) {
  7451. if (frame->parser == NULL) {
  7452. frame->before_type_url_end = ptr;
  7453. }
  7454. }
  7455. static void json_parser_any_frame_set_after_type_url_start_once(
  7456. upb_jsonparser_any_frame *frame,
  7457. const char *ptr) {
  7458. if (json_parser_any_frame_has_type_url(frame) &&
  7459. frame->after_type_url_start == NULL) {
  7460. frame->after_type_url_start = ptr;
  7461. }
  7462. }
  7463. /* Used to signal that a capture has been suspended. */
  7464. static char suspend_capture;
  7465. static upb_selector_t getsel_for_handlertype(upb_json_parser *p,
  7466. upb_handlertype_t type) {
  7467. upb_selector_t sel;
  7468. bool ok = upb_handlers_getselector(p->top->f, type, &sel);
  7469. UPB_ASSERT(ok);
  7470. return sel;
  7471. }
  7472. static upb_selector_t parser_getsel(upb_json_parser *p) {
  7473. return getsel_for_handlertype(
  7474. p, upb_handlers_getprimitivehandlertype(p->top->f));
  7475. }
  7476. static bool check_stack(upb_json_parser *p) {
  7477. if ((p->top + 1) == p->limit) {
  7478. upb_status_seterrmsg(p->status, "Nesting too deep");
  7479. return false;
  7480. }
  7481. return true;
  7482. }
  7483. static void set_name_table(upb_json_parser *p, upb_jsonparser_frame *frame) {
  7484. upb_value v;
  7485. const upb_json_codecache *cache = p->method->cache;
  7486. bool ok;
  7487. const upb_json_parsermethod *method;
  7488. ok = upb_inttable_lookupptr(&cache->methods, frame->m, &v);
  7489. UPB_ASSERT(ok);
  7490. method = upb_value_getconstptr(v);
  7491. frame->name_table = &method->name_table;
  7492. }
  7493. /* There are GCC/Clang built-ins for overflow checking which we could start
  7494. * using if there was any performance benefit to it. */
  7495. static bool checked_add(size_t a, size_t b, size_t *c) {
  7496. if (SIZE_MAX - a < b) return false;
  7497. *c = a + b;
  7498. return true;
  7499. }
  7500. static size_t saturating_multiply(size_t a, size_t b) {
  7501. /* size_t is unsigned, so this is defined behavior even on overflow. */
  7502. size_t ret = a * b;
  7503. if (b != 0 && ret / b != a) {
  7504. ret = SIZE_MAX;
  7505. }
  7506. return ret;
  7507. }
  7508. /* Base64 decoding ************************************************************/
  7509. /* TODO(haberman): make this streaming. */
  7510. static const signed char b64table[] = {
  7511. -1, -1, -1, -1, -1, -1, -1, -1,
  7512. -1, -1, -1, -1, -1, -1, -1, -1,
  7513. -1, -1, -1, -1, -1, -1, -1, -1,
  7514. -1, -1, -1, -1, -1, -1, -1, -1,
  7515. -1, -1, -1, -1, -1, -1, -1, -1,
  7516. -1, -1, -1, 62/*+*/, -1, -1, -1, 63/*/ */,
  7517. 52/*0*/, 53/*1*/, 54/*2*/, 55/*3*/, 56/*4*/, 57/*5*/, 58/*6*/, 59/*7*/,
  7518. 60/*8*/, 61/*9*/, -1, -1, -1, -1, -1, -1,
  7519. -1, 0/*A*/, 1/*B*/, 2/*C*/, 3/*D*/, 4/*E*/, 5/*F*/, 6/*G*/,
  7520. 07/*H*/, 8/*I*/, 9/*J*/, 10/*K*/, 11/*L*/, 12/*M*/, 13/*N*/, 14/*O*/,
  7521. 15/*P*/, 16/*Q*/, 17/*R*/, 18/*S*/, 19/*T*/, 20/*U*/, 21/*V*/, 22/*W*/,
  7522. 23/*X*/, 24/*Y*/, 25/*Z*/, -1, -1, -1, -1, -1,
  7523. -1, 26/*a*/, 27/*b*/, 28/*c*/, 29/*d*/, 30/*e*/, 31/*f*/, 32/*g*/,
  7524. 33/*h*/, 34/*i*/, 35/*j*/, 36/*k*/, 37/*l*/, 38/*m*/, 39/*n*/, 40/*o*/,
  7525. 41/*p*/, 42/*q*/, 43/*r*/, 44/*s*/, 45/*t*/, 46/*u*/, 47/*v*/, 48/*w*/,
  7526. 49/*x*/, 50/*y*/, 51/*z*/, -1, -1, -1, -1, -1,
  7527. -1, -1, -1, -1, -1, -1, -1, -1,
  7528. -1, -1, -1, -1, -1, -1, -1, -1,
  7529. -1, -1, -1, -1, -1, -1, -1, -1,
  7530. -1, -1, -1, -1, -1, -1, -1, -1,
  7531. -1, -1, -1, -1, -1, -1, -1, -1,
  7532. -1, -1, -1, -1, -1, -1, -1, -1,
  7533. -1, -1, -1, -1, -1, -1, -1, -1,
  7534. -1, -1, -1, -1, -1, -1, -1, -1,
  7535. -1, -1, -1, -1, -1, -1, -1, -1,
  7536. -1, -1, -1, -1, -1, -1, -1, -1,
  7537. -1, -1, -1, -1, -1, -1, -1, -1,
  7538. -1, -1, -1, -1, -1, -1, -1, -1,
  7539. -1, -1, -1, -1, -1, -1, -1, -1,
  7540. -1, -1, -1, -1, -1, -1, -1, -1,
  7541. -1, -1, -1, -1, -1, -1, -1, -1,
  7542. -1, -1, -1, -1, -1, -1, -1, -1
  7543. };
  7544. /* Returns the table value sign-extended to 32 bits. Knowing that the upper
  7545. * bits will be 1 for unrecognized characters makes it easier to check for
  7546. * this error condition later (see below). */
  7547. int32_t b64lookup(unsigned char ch) { return b64table[ch]; }
  7548. /* Returns true if the given character is not a valid base64 character or
  7549. * padding. */
  7550. bool nonbase64(unsigned char ch) { return b64lookup(ch) == -1 && ch != '='; }
  7551. static bool base64_push(upb_json_parser *p, upb_selector_t sel, const char *ptr,
  7552. size_t len) {
  7553. const char *limit = ptr + len;
  7554. for (; ptr < limit; ptr += 4) {
  7555. uint32_t val;
  7556. char output[3];
  7557. if (limit - ptr < 4) {
  7558. upb_status_seterrf(p->status,
  7559. "Base64 input for bytes field not a multiple of 4: %s",
  7560. upb_fielddef_name(p->top->f));
  7561. return false;
  7562. }
  7563. val = b64lookup(ptr[0]) << 18 |
  7564. b64lookup(ptr[1]) << 12 |
  7565. b64lookup(ptr[2]) << 6 |
  7566. b64lookup(ptr[3]);
  7567. /* Test the upper bit; returns true if any of the characters returned -1. */
  7568. if (val & 0x80000000) {
  7569. goto otherchar;
  7570. }
  7571. output[0] = val >> 16;
  7572. output[1] = (val >> 8) & 0xff;
  7573. output[2] = val & 0xff;
  7574. upb_sink_putstring(p->top->sink, sel, output, 3, NULL);
  7575. }
  7576. return true;
  7577. otherchar:
  7578. if (nonbase64(ptr[0]) || nonbase64(ptr[1]) || nonbase64(ptr[2]) ||
  7579. nonbase64(ptr[3]) ) {
  7580. upb_status_seterrf(p->status,
  7581. "Non-base64 characters in bytes field: %s",
  7582. upb_fielddef_name(p->top->f));
  7583. return false;
  7584. } if (ptr[2] == '=') {
  7585. uint32_t val;
  7586. char output;
  7587. /* Last group contains only two input bytes, one output byte. */
  7588. if (ptr[0] == '=' || ptr[1] == '=' || ptr[3] != '=') {
  7589. goto badpadding;
  7590. }
  7591. val = b64lookup(ptr[0]) << 18 |
  7592. b64lookup(ptr[1]) << 12;
  7593. UPB_ASSERT(!(val & 0x80000000));
  7594. output = val >> 16;
  7595. upb_sink_putstring(p->top->sink, sel, &output, 1, NULL);
  7596. return true;
  7597. } else {
  7598. uint32_t val;
  7599. char output[2];
  7600. /* Last group contains only three input bytes, two output bytes. */
  7601. if (ptr[0] == '=' || ptr[1] == '=' || ptr[2] == '=') {
  7602. goto badpadding;
  7603. }
  7604. val = b64lookup(ptr[0]) << 18 |
  7605. b64lookup(ptr[1]) << 12 |
  7606. b64lookup(ptr[2]) << 6;
  7607. output[0] = val >> 16;
  7608. output[1] = (val >> 8) & 0xff;
  7609. upb_sink_putstring(p->top->sink, sel, output, 2, NULL);
  7610. return true;
  7611. }
  7612. badpadding:
  7613. upb_status_seterrf(p->status,
  7614. "Incorrect base64 padding for field: %s (%.*s)",
  7615. upb_fielddef_name(p->top->f),
  7616. 4, ptr);
  7617. return false;
  7618. }
  7619. /* Accumulate buffer **********************************************************/
  7620. /* Functionality for accumulating a buffer.
  7621. *
  7622. * Some parts of the parser need an entire value as a contiguous string. For
  7623. * example, to look up a member name in a hash table, or to turn a string into
  7624. * a number, the relevant library routines need the input string to be in
  7625. * contiguous memory, even if the value spanned two or more buffers in the
  7626. * input. These routines handle that.
  7627. *
  7628. * In the common case we can just point to the input buffer to get this
  7629. * contiguous string and avoid any actual copy. So we optimistically begin
  7630. * this way. But there are a few cases where we must instead copy into a
  7631. * separate buffer:
  7632. *
  7633. * 1. The string was not contiguous in the input (it spanned buffers).
  7634. *
  7635. * 2. The string included escape sequences that need to be interpreted to get
  7636. * the true value in a contiguous buffer. */
  7637. static void assert_accumulate_empty(upb_json_parser *p) {
  7638. UPB_ASSERT(p->accumulated == NULL);
  7639. UPB_ASSERT(p->accumulated_len == 0);
  7640. }
  7641. static void accumulate_clear(upb_json_parser *p) {
  7642. p->accumulated = NULL;
  7643. p->accumulated_len = 0;
  7644. }
  7645. /* Used internally by accumulate_append(). */
  7646. static bool accumulate_realloc(upb_json_parser *p, size_t need) {
  7647. void *mem;
  7648. size_t old_size = p->accumulate_buf_size;
  7649. size_t new_size = UPB_MAX(old_size, 128);
  7650. while (new_size < need) {
  7651. new_size = saturating_multiply(new_size, 2);
  7652. }
  7653. mem = upb_arena_realloc(p->arena, p->accumulate_buf, old_size, new_size);
  7654. if (!mem) {
  7655. upb_status_seterrmsg(p->status, "Out of memory allocating buffer.");
  7656. return false;
  7657. }
  7658. p->accumulate_buf = mem;
  7659. p->accumulate_buf_size = new_size;
  7660. return true;
  7661. }
  7662. /* Logically appends the given data to the append buffer.
  7663. * If "can_alias" is true, we will try to avoid actually copying, but the buffer
  7664. * must be valid until the next accumulate_append() call (if any). */
  7665. static bool accumulate_append(upb_json_parser *p, const char *buf, size_t len,
  7666. bool can_alias) {
  7667. size_t need;
  7668. if (!p->accumulated && can_alias) {
  7669. p->accumulated = buf;
  7670. p->accumulated_len = len;
  7671. return true;
  7672. }
  7673. if (!checked_add(p->accumulated_len, len, &need)) {
  7674. upb_status_seterrmsg(p->status, "Integer overflow.");
  7675. return false;
  7676. }
  7677. if (need > p->accumulate_buf_size && !accumulate_realloc(p, need)) {
  7678. return false;
  7679. }
  7680. if (p->accumulated != p->accumulate_buf) {
  7681. memcpy(p->accumulate_buf, p->accumulated, p->accumulated_len);
  7682. p->accumulated = p->accumulate_buf;
  7683. }
  7684. memcpy(p->accumulate_buf + p->accumulated_len, buf, len);
  7685. p->accumulated_len += len;
  7686. return true;
  7687. }
  7688. /* Returns a pointer to the data accumulated since the last accumulate_clear()
  7689. * call, and writes the length to *len. This with point either to the input
  7690. * buffer or a temporary accumulate buffer. */
  7691. static const char *accumulate_getptr(upb_json_parser *p, size_t *len) {
  7692. UPB_ASSERT(p->accumulated);
  7693. *len = p->accumulated_len;
  7694. return p->accumulated;
  7695. }
  7696. /* Mult-part text data ********************************************************/
  7697. /* When we have text data in the input, it can often come in multiple segments.
  7698. * For example, there may be some raw string data followed by an escape
  7699. * sequence. The two segments are processed with different logic. Also buffer
  7700. * seams in the input can cause multiple segments.
  7701. *
  7702. * As we see segments, there are two main cases for how we want to process them:
  7703. *
  7704. * 1. we want to push the captured input directly to string handlers.
  7705. *
  7706. * 2. we need to accumulate all the parts into a contiguous buffer for further
  7707. * processing (field name lookup, string->number conversion, etc). */
  7708. /* This is the set of states for p->multipart_state. */
  7709. enum {
  7710. /* We are not currently processing multipart data. */
  7711. MULTIPART_INACTIVE = 0,
  7712. /* We are processing multipart data by accumulating it into a contiguous
  7713. * buffer. */
  7714. MULTIPART_ACCUMULATE = 1,
  7715. /* We are processing multipart data by pushing each part directly to the
  7716. * current string handlers. */
  7717. MULTIPART_PUSHEAGERLY = 2
  7718. };
  7719. /* Start a multi-part text value where we accumulate the data for processing at
  7720. * the end. */
  7721. static void multipart_startaccum(upb_json_parser *p) {
  7722. assert_accumulate_empty(p);
  7723. UPB_ASSERT(p->multipart_state == MULTIPART_INACTIVE);
  7724. p->multipart_state = MULTIPART_ACCUMULATE;
  7725. }
  7726. /* Start a multi-part text value where we immediately push text data to a string
  7727. * value with the given selector. */
  7728. static void multipart_start(upb_json_parser *p, upb_selector_t sel) {
  7729. assert_accumulate_empty(p);
  7730. UPB_ASSERT(p->multipart_state == MULTIPART_INACTIVE);
  7731. p->multipart_state = MULTIPART_PUSHEAGERLY;
  7732. p->string_selector = sel;
  7733. }
  7734. static bool multipart_text(upb_json_parser *p, const char *buf, size_t len,
  7735. bool can_alias) {
  7736. switch (p->multipart_state) {
  7737. case MULTIPART_INACTIVE:
  7738. upb_status_seterrmsg(
  7739. p->status, "Internal error: unexpected state MULTIPART_INACTIVE");
  7740. return false;
  7741. case MULTIPART_ACCUMULATE:
  7742. if (!accumulate_append(p, buf, len, can_alias)) {
  7743. return false;
  7744. }
  7745. break;
  7746. case MULTIPART_PUSHEAGERLY: {
  7747. const upb_bufhandle *handle = can_alias ? p->handle : NULL;
  7748. upb_sink_putstring(p->top->sink, p->string_selector, buf, len, handle);
  7749. break;
  7750. }
  7751. }
  7752. return true;
  7753. }
  7754. /* Note: this invalidates the accumulate buffer! Call only after reading its
  7755. * contents. */
  7756. static void multipart_end(upb_json_parser *p) {
  7757. UPB_ASSERT(p->multipart_state != MULTIPART_INACTIVE);
  7758. p->multipart_state = MULTIPART_INACTIVE;
  7759. accumulate_clear(p);
  7760. }
  7761. /* Input capture **************************************************************/
  7762. /* Functionality for capturing a region of the input as text. Gracefully
  7763. * handles the case where a buffer seam occurs in the middle of the captured
  7764. * region. */
  7765. static void capture_begin(upb_json_parser *p, const char *ptr) {
  7766. UPB_ASSERT(p->multipart_state != MULTIPART_INACTIVE);
  7767. UPB_ASSERT(p->capture == NULL);
  7768. p->capture = ptr;
  7769. }
  7770. static bool capture_end(upb_json_parser *p, const char *ptr) {
  7771. UPB_ASSERT(p->capture);
  7772. if (multipart_text(p, p->capture, ptr - p->capture, true)) {
  7773. p->capture = NULL;
  7774. return true;
  7775. } else {
  7776. return false;
  7777. }
  7778. }
  7779. /* This is called at the end of each input buffer (ie. when we have hit a
  7780. * buffer seam). If we are in the middle of capturing the input, this
  7781. * processes the unprocessed capture region. */
  7782. static void capture_suspend(upb_json_parser *p, const char **ptr) {
  7783. if (!p->capture) return;
  7784. if (multipart_text(p, p->capture, *ptr - p->capture, false)) {
  7785. /* We use this as a signal that we were in the middle of capturing, and
  7786. * that capturing should resume at the beginning of the next buffer.
  7787. *
  7788. * We can't use *ptr here, because we have no guarantee that this pointer
  7789. * will be valid when we resume (if the underlying memory is freed, then
  7790. * using the pointer at all, even to compare to NULL, is likely undefined
  7791. * behavior). */
  7792. p->capture = &suspend_capture;
  7793. } else {
  7794. /* Need to back up the pointer to the beginning of the capture, since
  7795. * we were not able to actually preserve it. */
  7796. *ptr = p->capture;
  7797. }
  7798. }
  7799. static void capture_resume(upb_json_parser *p, const char *ptr) {
  7800. if (p->capture) {
  7801. UPB_ASSERT(p->capture == &suspend_capture);
  7802. p->capture = ptr;
  7803. }
  7804. }
  7805. /* Callbacks from the parser **************************************************/
  7806. /* These are the functions called directly from the parser itself.
  7807. * We define these in the same order as their declarations in the parser. */
  7808. static char escape_char(char in) {
  7809. switch (in) {
  7810. case 'r': return '\r';
  7811. case 't': return '\t';
  7812. case 'n': return '\n';
  7813. case 'f': return '\f';
  7814. case 'b': return '\b';
  7815. case '/': return '/';
  7816. case '"': return '"';
  7817. case '\\': return '\\';
  7818. default:
  7819. UPB_ASSERT(0);
  7820. return 'x';
  7821. }
  7822. }
  7823. static bool escape(upb_json_parser *p, const char *ptr) {
  7824. char ch = escape_char(*ptr);
  7825. return multipart_text(p, &ch, 1, false);
  7826. }
  7827. static void start_hex(upb_json_parser *p) {
  7828. p->digit = 0;
  7829. }
  7830. static void hexdigit(upb_json_parser *p, const char *ptr) {
  7831. char ch = *ptr;
  7832. p->digit <<= 4;
  7833. if (ch >= '0' && ch <= '9') {
  7834. p->digit += (ch - '0');
  7835. } else if (ch >= 'a' && ch <= 'f') {
  7836. p->digit += ((ch - 'a') + 10);
  7837. } else {
  7838. UPB_ASSERT(ch >= 'A' && ch <= 'F');
  7839. p->digit += ((ch - 'A') + 10);
  7840. }
  7841. }
  7842. static bool end_hex(upb_json_parser *p) {
  7843. uint32_t codepoint = p->digit;
  7844. /* emit the codepoint as UTF-8. */
  7845. char utf8[3]; /* support \u0000 -- \uFFFF -- need only three bytes. */
  7846. int length = 0;
  7847. if (codepoint <= 0x7F) {
  7848. utf8[0] = codepoint;
  7849. length = 1;
  7850. } else if (codepoint <= 0x07FF) {
  7851. utf8[1] = (codepoint & 0x3F) | 0x80;
  7852. codepoint >>= 6;
  7853. utf8[0] = (codepoint & 0x1F) | 0xC0;
  7854. length = 2;
  7855. } else /* codepoint <= 0xFFFF */ {
  7856. utf8[2] = (codepoint & 0x3F) | 0x80;
  7857. codepoint >>= 6;
  7858. utf8[1] = (codepoint & 0x3F) | 0x80;
  7859. codepoint >>= 6;
  7860. utf8[0] = (codepoint & 0x0F) | 0xE0;
  7861. length = 3;
  7862. }
  7863. /* TODO(haberman): Handle high surrogates: if codepoint is a high surrogate
  7864. * we have to wait for the next escape to get the full code point). */
  7865. return multipart_text(p, utf8, length, false);
  7866. }
  7867. static void start_text(upb_json_parser *p, const char *ptr) {
  7868. capture_begin(p, ptr);
  7869. }
  7870. static bool end_text(upb_json_parser *p, const char *ptr) {
  7871. return capture_end(p, ptr);
  7872. }
  7873. static bool start_number(upb_json_parser *p, const char *ptr) {
  7874. if (is_top_level(p)) {
  7875. if (is_number_wrapper_object(p)) {
  7876. start_wrapper_object(p);
  7877. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  7878. start_value_object(p, VALUE_NUMBERVALUE);
  7879. } else {
  7880. return false;
  7881. }
  7882. } else if (does_number_wrapper_start(p)) {
  7883. if (!start_subobject(p)) {
  7884. return false;
  7885. }
  7886. start_wrapper_object(p);
  7887. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  7888. if (!start_subobject(p)) {
  7889. return false;
  7890. }
  7891. start_value_object(p, VALUE_NUMBERVALUE);
  7892. }
  7893. multipart_startaccum(p);
  7894. capture_begin(p, ptr);
  7895. return true;
  7896. }
  7897. static bool parse_number(upb_json_parser *p, bool is_quoted);
  7898. static bool end_number_nontop(upb_json_parser *p, const char *ptr) {
  7899. if (!capture_end(p, ptr)) {
  7900. return false;
  7901. }
  7902. if (p->top->f == NULL) {
  7903. multipart_end(p);
  7904. return true;
  7905. }
  7906. return parse_number(p, false);
  7907. }
  7908. static bool end_number(upb_json_parser *p, const char *ptr) {
  7909. if (!end_number_nontop(p, ptr)) {
  7910. return false;
  7911. }
  7912. if (does_number_wrapper_end(p)) {
  7913. end_wrapper_object(p);
  7914. if (!is_top_level(p)) {
  7915. end_subobject(p);
  7916. }
  7917. return true;
  7918. }
  7919. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  7920. end_value_object(p);
  7921. if (!is_top_level(p)) {
  7922. end_subobject(p);
  7923. }
  7924. return true;
  7925. }
  7926. return true;
  7927. }
  7928. /* |buf| is NULL-terminated. |buf| itself will never include quotes;
  7929. * |is_quoted| tells us whether this text originally appeared inside quotes. */
  7930. static bool parse_number_from_buffer(upb_json_parser *p, const char *buf,
  7931. bool is_quoted) {
  7932. size_t len = strlen(buf);
  7933. const char *bufend = buf + len;
  7934. char *end;
  7935. upb_fieldtype_t type = upb_fielddef_type(p->top->f);
  7936. double val;
  7937. double dummy;
  7938. double inf = UPB_INFINITY;
  7939. errno = 0;
  7940. if (len == 0 || buf[0] == ' ') {
  7941. return false;
  7942. }
  7943. /* For integer types, first try parsing with integer-specific routines.
  7944. * If these succeed, they will be more accurate for int64/uint64 than
  7945. * strtod().
  7946. */
  7947. switch (type) {
  7948. case UPB_TYPE_ENUM:
  7949. case UPB_TYPE_INT32: {
  7950. long val = strtol(buf, &end, 0);
  7951. if (errno == ERANGE || end != bufend) {
  7952. break;
  7953. } else if (val > INT32_MAX || val < INT32_MIN) {
  7954. return false;
  7955. } else {
  7956. upb_sink_putint32(p->top->sink, parser_getsel(p), val);
  7957. return true;
  7958. }
  7959. }
  7960. case UPB_TYPE_UINT32: {
  7961. unsigned long val = strtoul(buf, &end, 0);
  7962. if (end != bufend) {
  7963. break;
  7964. } else if (val > UINT32_MAX || errno == ERANGE) {
  7965. return false;
  7966. } else {
  7967. upb_sink_putuint32(p->top->sink, parser_getsel(p), val);
  7968. return true;
  7969. }
  7970. }
  7971. /* XXX: We can't handle [u]int64 properly on 32-bit machines because
  7972. * strto[u]ll isn't in C89. */
  7973. case UPB_TYPE_INT64: {
  7974. long val = strtol(buf, &end, 0);
  7975. if (errno == ERANGE || end != bufend) {
  7976. break;
  7977. } else {
  7978. upb_sink_putint64(p->top->sink, parser_getsel(p), val);
  7979. return true;
  7980. }
  7981. }
  7982. case UPB_TYPE_UINT64: {
  7983. unsigned long val = strtoul(p->accumulated, &end, 0);
  7984. if (end != bufend) {
  7985. break;
  7986. } else if (errno == ERANGE) {
  7987. return false;
  7988. } else {
  7989. upb_sink_putuint64(p->top->sink, parser_getsel(p), val);
  7990. return true;
  7991. }
  7992. }
  7993. default:
  7994. break;
  7995. }
  7996. if (type != UPB_TYPE_DOUBLE && type != UPB_TYPE_FLOAT && is_quoted) {
  7997. /* Quoted numbers for integer types are not allowed to be in double form. */
  7998. return false;
  7999. }
  8000. if (len == strlen("Infinity") && strcmp(buf, "Infinity") == 0) {
  8001. /* C89 does not have an INFINITY macro. */
  8002. val = inf;
  8003. } else if (len == strlen("-Infinity") && strcmp(buf, "-Infinity") == 0) {
  8004. val = -inf;
  8005. } else {
  8006. val = strtod(buf, &end);
  8007. if (errno == ERANGE || end != bufend) {
  8008. return false;
  8009. }
  8010. }
  8011. switch (type) {
  8012. #define CASE(capitaltype, smalltype, ctype, min, max) \
  8013. case UPB_TYPE_ ## capitaltype: { \
  8014. if (modf(val, &dummy) != 0 || val > max || val < min) { \
  8015. return false; \
  8016. } else { \
  8017. upb_sink_put ## smalltype(p->top->sink, parser_getsel(p), \
  8018. (ctype)val); \
  8019. return true; \
  8020. } \
  8021. break; \
  8022. }
  8023. case UPB_TYPE_ENUM:
  8024. CASE(INT32, int32, int32_t, INT32_MIN, INT32_MAX);
  8025. CASE(INT64, int64, int64_t, INT64_MIN, INT64_MAX);
  8026. CASE(UINT32, uint32, uint32_t, 0, UINT32_MAX);
  8027. CASE(UINT64, uint64, uint64_t, 0, UINT64_MAX);
  8028. #undef CASE
  8029. case UPB_TYPE_DOUBLE:
  8030. upb_sink_putdouble(p->top->sink, parser_getsel(p), val);
  8031. return true;
  8032. case UPB_TYPE_FLOAT:
  8033. if ((val > FLT_MAX || val < -FLT_MAX) && val != inf && val != -inf) {
  8034. return false;
  8035. } else {
  8036. upb_sink_putfloat(p->top->sink, parser_getsel(p), val);
  8037. return true;
  8038. }
  8039. default:
  8040. return false;
  8041. }
  8042. }
  8043. static bool parse_number(upb_json_parser *p, bool is_quoted) {
  8044. size_t len;
  8045. const char *buf;
  8046. /* strtol() and friends unfortunately do not support specifying the length of
  8047. * the input string, so we need to force a copy into a NULL-terminated buffer. */
  8048. if (!multipart_text(p, "\0", 1, false)) {
  8049. return false;
  8050. }
  8051. buf = accumulate_getptr(p, &len);
  8052. if (parse_number_from_buffer(p, buf, is_quoted)) {
  8053. multipart_end(p);
  8054. return true;
  8055. } else {
  8056. upb_status_seterrf(p->status, "error parsing number: %s", buf);
  8057. multipart_end(p);
  8058. return false;
  8059. }
  8060. }
  8061. static bool parser_putbool(upb_json_parser *p, bool val) {
  8062. bool ok;
  8063. if (p->top->f == NULL) {
  8064. return true;
  8065. }
  8066. if (upb_fielddef_type(p->top->f) != UPB_TYPE_BOOL) {
  8067. upb_status_seterrf(p->status,
  8068. "Boolean value specified for non-bool field: %s",
  8069. upb_fielddef_name(p->top->f));
  8070. return false;
  8071. }
  8072. ok = upb_sink_putbool(p->top->sink, parser_getsel(p), val);
  8073. UPB_ASSERT(ok);
  8074. return true;
  8075. }
  8076. static bool end_bool(upb_json_parser *p, bool val) {
  8077. if (is_top_level(p)) {
  8078. if (is_wellknown_msg(p, UPB_WELLKNOWN_BOOLVALUE)) {
  8079. start_wrapper_object(p);
  8080. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8081. start_value_object(p, VALUE_BOOLVALUE);
  8082. } else {
  8083. return false;
  8084. }
  8085. } else if (is_wellknown_field(p, UPB_WELLKNOWN_BOOLVALUE)) {
  8086. if (!start_subobject(p)) {
  8087. return false;
  8088. }
  8089. start_wrapper_object(p);
  8090. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  8091. if (!start_subobject(p)) {
  8092. return false;
  8093. }
  8094. start_value_object(p, VALUE_BOOLVALUE);
  8095. }
  8096. if (p->top->is_unknown_field) {
  8097. return true;
  8098. }
  8099. if (!parser_putbool(p, val)) {
  8100. return false;
  8101. }
  8102. if (is_wellknown_msg(p, UPB_WELLKNOWN_BOOLVALUE)) {
  8103. end_wrapper_object(p);
  8104. if (!is_top_level(p)) {
  8105. end_subobject(p);
  8106. }
  8107. return true;
  8108. }
  8109. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8110. end_value_object(p);
  8111. if (!is_top_level(p)) {
  8112. end_subobject(p);
  8113. }
  8114. return true;
  8115. }
  8116. return true;
  8117. }
  8118. static bool end_null(upb_json_parser *p) {
  8119. const char *zero_ptr = "0";
  8120. if (is_top_level(p)) {
  8121. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8122. start_value_object(p, VALUE_NULLVALUE);
  8123. } else {
  8124. return true;
  8125. }
  8126. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  8127. if (!start_subobject(p)) {
  8128. return false;
  8129. }
  8130. start_value_object(p, VALUE_NULLVALUE);
  8131. } else {
  8132. return true;
  8133. }
  8134. /* Fill null_value field. */
  8135. multipart_startaccum(p);
  8136. capture_begin(p, zero_ptr);
  8137. capture_end(p, zero_ptr + 1);
  8138. parse_number(p, false);
  8139. end_value_object(p);
  8140. if (!is_top_level(p)) {
  8141. end_subobject(p);
  8142. }
  8143. return true;
  8144. }
  8145. static bool start_any_stringval(upb_json_parser *p) {
  8146. multipart_startaccum(p);
  8147. return true;
  8148. }
  8149. static bool start_stringval(upb_json_parser *p) {
  8150. if (is_top_level(p)) {
  8151. if (is_string_wrapper_object(p) ||
  8152. is_number_wrapper_object(p)) {
  8153. start_wrapper_object(p);
  8154. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_FIELDMASK)) {
  8155. start_fieldmask_object(p);
  8156. return true;
  8157. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_TIMESTAMP) ||
  8158. is_wellknown_msg(p, UPB_WELLKNOWN_DURATION)) {
  8159. start_object(p);
  8160. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8161. start_value_object(p, VALUE_STRINGVALUE);
  8162. } else {
  8163. return false;
  8164. }
  8165. } else if (does_string_wrapper_start(p) ||
  8166. does_number_wrapper_start(p)) {
  8167. if (!start_subobject(p)) {
  8168. return false;
  8169. }
  8170. start_wrapper_object(p);
  8171. } else if (does_fieldmask_start(p)) {
  8172. if (!start_subobject(p)) {
  8173. return false;
  8174. }
  8175. start_fieldmask_object(p);
  8176. return true;
  8177. } else if (is_wellknown_field(p, UPB_WELLKNOWN_TIMESTAMP) ||
  8178. is_wellknown_field(p, UPB_WELLKNOWN_DURATION)) {
  8179. if (!start_subobject(p)) {
  8180. return false;
  8181. }
  8182. start_object(p);
  8183. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  8184. if (!start_subobject(p)) {
  8185. return false;
  8186. }
  8187. start_value_object(p, VALUE_STRINGVALUE);
  8188. }
  8189. if (p->top->f == NULL) {
  8190. multipart_startaccum(p);
  8191. return true;
  8192. }
  8193. if (p->top->is_any) {
  8194. return start_any_stringval(p);
  8195. }
  8196. if (upb_fielddef_isstring(p->top->f)) {
  8197. upb_jsonparser_frame *inner;
  8198. upb_selector_t sel;
  8199. if (!check_stack(p)) return false;
  8200. /* Start a new parser frame: parser frames correspond one-to-one with
  8201. * handler frames, and string events occur in a sub-frame. */
  8202. inner = start_jsonparser_frame(p);
  8203. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  8204. upb_sink_startstr(p->top->sink, sel, 0, &inner->sink);
  8205. inner->m = p->top->m;
  8206. inner->f = p->top->f;
  8207. p->top = inner;
  8208. if (upb_fielddef_type(p->top->f) == UPB_TYPE_STRING) {
  8209. /* For STRING fields we push data directly to the handlers as it is
  8210. * parsed. We don't do this yet for BYTES fields, because our base64
  8211. * decoder is not streaming.
  8212. *
  8213. * TODO(haberman): make base64 decoding streaming also. */
  8214. multipart_start(p, getsel_for_handlertype(p, UPB_HANDLER_STRING));
  8215. return true;
  8216. } else {
  8217. multipart_startaccum(p);
  8218. return true;
  8219. }
  8220. } else if (upb_fielddef_type(p->top->f) != UPB_TYPE_BOOL &&
  8221. upb_fielddef_type(p->top->f) != UPB_TYPE_MESSAGE) {
  8222. /* No need to push a frame -- numeric values in quotes remain in the
  8223. * current parser frame. These values must accmulate so we can convert
  8224. * them all at once at the end. */
  8225. multipart_startaccum(p);
  8226. return true;
  8227. } else {
  8228. upb_status_seterrf(p->status,
  8229. "String specified for bool or submessage field: %s",
  8230. upb_fielddef_name(p->top->f));
  8231. return false;
  8232. }
  8233. }
  8234. static bool end_any_stringval(upb_json_parser *p) {
  8235. size_t len;
  8236. const char *buf = accumulate_getptr(p, &len);
  8237. /* Set type_url */
  8238. upb_selector_t sel;
  8239. upb_jsonparser_frame *inner;
  8240. if (!check_stack(p)) return false;
  8241. inner = p->top + 1;
  8242. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  8243. upb_sink_startstr(p->top->sink, sel, 0, &inner->sink);
  8244. sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
  8245. upb_sink_putstring(inner->sink, sel, buf, len, NULL);
  8246. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  8247. upb_sink_endstr(inner->sink, sel);
  8248. multipart_end(p);
  8249. /* Resolve type url */
  8250. if (strncmp(buf, "type.googleapis.com/", 20) == 0 && len > 20) {
  8251. const upb_msgdef *payload_type = NULL;
  8252. buf += 20;
  8253. len -= 20;
  8254. payload_type = upb_symtab_lookupmsg2(p->symtab, buf, len);
  8255. if (payload_type == NULL) {
  8256. upb_status_seterrf(
  8257. p->status, "Cannot find packed type: %.*s\n", (int)len, buf);
  8258. return false;
  8259. }
  8260. json_parser_any_frame_set_payload_type(p, p->top->any_frame, payload_type);
  8261. return true;
  8262. } else {
  8263. upb_status_seterrf(
  8264. p->status, "Invalid type url: %.*s\n", (int)len, buf);
  8265. return false;
  8266. }
  8267. }
  8268. static bool end_stringval_nontop(upb_json_parser *p) {
  8269. bool ok = true;
  8270. if (is_wellknown_msg(p, UPB_WELLKNOWN_TIMESTAMP) ||
  8271. is_wellknown_msg(p, UPB_WELLKNOWN_DURATION)) {
  8272. multipart_end(p);
  8273. return true;
  8274. }
  8275. if (p->top->f == NULL) {
  8276. multipart_end(p);
  8277. return true;
  8278. }
  8279. if (p->top->is_any) {
  8280. return end_any_stringval(p);
  8281. }
  8282. switch (upb_fielddef_type(p->top->f)) {
  8283. case UPB_TYPE_BYTES:
  8284. if (!base64_push(p, getsel_for_handlertype(p, UPB_HANDLER_STRING),
  8285. p->accumulated, p->accumulated_len)) {
  8286. return false;
  8287. }
  8288. /* Fall through. */
  8289. case UPB_TYPE_STRING: {
  8290. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  8291. upb_sink_endstr(p->top->sink, sel);
  8292. p->top--;
  8293. break;
  8294. }
  8295. case UPB_TYPE_ENUM: {
  8296. /* Resolve enum symbolic name to integer value. */
  8297. const upb_enumdef *enumdef = upb_fielddef_enumsubdef(p->top->f);
  8298. size_t len;
  8299. const char *buf = accumulate_getptr(p, &len);
  8300. int32_t int_val = 0;
  8301. ok = upb_enumdef_ntoi(enumdef, buf, len, &int_val);
  8302. if (ok) {
  8303. upb_selector_t sel = parser_getsel(p);
  8304. upb_sink_putint32(p->top->sink, sel, int_val);
  8305. } else {
  8306. upb_status_seterrf(p->status, "Enum value unknown: '%.*s'", len, buf);
  8307. }
  8308. break;
  8309. }
  8310. case UPB_TYPE_INT32:
  8311. case UPB_TYPE_INT64:
  8312. case UPB_TYPE_UINT32:
  8313. case UPB_TYPE_UINT64:
  8314. case UPB_TYPE_DOUBLE:
  8315. case UPB_TYPE_FLOAT:
  8316. ok = parse_number(p, true);
  8317. break;
  8318. default:
  8319. UPB_ASSERT(false);
  8320. upb_status_seterrmsg(p->status, "Internal error in JSON decoder");
  8321. ok = false;
  8322. break;
  8323. }
  8324. multipart_end(p);
  8325. return ok;
  8326. }
  8327. static bool end_stringval(upb_json_parser *p) {
  8328. /* FieldMask's stringvals have been ended when handling them. Only need to
  8329. * close FieldMask here.*/
  8330. if (does_fieldmask_end(p)) {
  8331. end_fieldmask_object(p);
  8332. if (!is_top_level(p)) {
  8333. end_subobject(p);
  8334. }
  8335. return true;
  8336. }
  8337. if (!end_stringval_nontop(p)) {
  8338. return false;
  8339. }
  8340. if (does_string_wrapper_end(p) ||
  8341. does_number_wrapper_end(p)) {
  8342. end_wrapper_object(p);
  8343. if (!is_top_level(p)) {
  8344. end_subobject(p);
  8345. }
  8346. return true;
  8347. }
  8348. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8349. end_value_object(p);
  8350. if (!is_top_level(p)) {
  8351. end_subobject(p);
  8352. }
  8353. return true;
  8354. }
  8355. if (is_wellknown_msg(p, UPB_WELLKNOWN_TIMESTAMP) ||
  8356. is_wellknown_msg(p, UPB_WELLKNOWN_DURATION) ||
  8357. is_wellknown_msg(p, UPB_WELLKNOWN_FIELDMASK)) {
  8358. end_object(p);
  8359. if (!is_top_level(p)) {
  8360. end_subobject(p);
  8361. }
  8362. return true;
  8363. }
  8364. return true;
  8365. }
  8366. static void start_duration_base(upb_json_parser *p, const char *ptr) {
  8367. capture_begin(p, ptr);
  8368. }
  8369. static bool end_duration_base(upb_json_parser *p, const char *ptr) {
  8370. size_t len;
  8371. const char *buf;
  8372. char seconds_buf[14];
  8373. char nanos_buf[12];
  8374. char *end;
  8375. int64_t seconds = 0;
  8376. int32_t nanos = 0;
  8377. double val = 0.0;
  8378. const char *seconds_membername = "seconds";
  8379. const char *nanos_membername = "nanos";
  8380. size_t fraction_start;
  8381. if (!capture_end(p, ptr)) {
  8382. return false;
  8383. }
  8384. buf = accumulate_getptr(p, &len);
  8385. memset(seconds_buf, 0, 14);
  8386. memset(nanos_buf, 0, 12);
  8387. /* Find out base end. The maximus duration is 315576000000, which cannot be
  8388. * represented by double without losing precision. Thus, we need to handle
  8389. * fraction and base separately. */
  8390. for (fraction_start = 0; fraction_start < len && buf[fraction_start] != '.';
  8391. fraction_start++);
  8392. /* Parse base */
  8393. memcpy(seconds_buf, buf, fraction_start);
  8394. seconds = strtol(seconds_buf, &end, 10);
  8395. if (errno == ERANGE || end != seconds_buf + fraction_start) {
  8396. upb_status_seterrf(p->status, "error parsing duration: %s",
  8397. seconds_buf);
  8398. return false;
  8399. }
  8400. if (seconds > 315576000000) {
  8401. upb_status_seterrf(p->status, "error parsing duration: "
  8402. "maximum acceptable value is "
  8403. "315576000000");
  8404. return false;
  8405. }
  8406. if (seconds < -315576000000) {
  8407. upb_status_seterrf(p->status, "error parsing duration: "
  8408. "minimum acceptable value is "
  8409. "-315576000000");
  8410. return false;
  8411. }
  8412. /* Parse fraction */
  8413. nanos_buf[0] = '0';
  8414. memcpy(nanos_buf + 1, buf + fraction_start, len - fraction_start);
  8415. val = strtod(nanos_buf, &end);
  8416. if (errno == ERANGE || end != nanos_buf + len - fraction_start + 1) {
  8417. upb_status_seterrf(p->status, "error parsing duration: %s",
  8418. nanos_buf);
  8419. return false;
  8420. }
  8421. nanos = val * 1000000000;
  8422. if (seconds < 0) nanos = -nanos;
  8423. /* Clean up buffer */
  8424. multipart_end(p);
  8425. /* Set seconds */
  8426. start_member(p);
  8427. capture_begin(p, seconds_membername);
  8428. capture_end(p, seconds_membername + 7);
  8429. end_membername(p);
  8430. upb_sink_putint64(p->top->sink, parser_getsel(p), seconds);
  8431. end_member(p);
  8432. /* Set nanos */
  8433. start_member(p);
  8434. capture_begin(p, nanos_membername);
  8435. capture_end(p, nanos_membername + 5);
  8436. end_membername(p);
  8437. upb_sink_putint32(p->top->sink, parser_getsel(p), nanos);
  8438. end_member(p);
  8439. /* Continue previous arena */
  8440. multipart_startaccum(p);
  8441. return true;
  8442. }
  8443. static int parse_timestamp_number(upb_json_parser *p) {
  8444. size_t len;
  8445. const char *buf;
  8446. int val;
  8447. /* atoi() and friends unfortunately do not support specifying the length of
  8448. * the input string, so we need to force a copy into a NULL-terminated buffer. */
  8449. multipart_text(p, "\0", 1, false);
  8450. buf = accumulate_getptr(p, &len);
  8451. val = atoi(buf);
  8452. multipart_end(p);
  8453. multipart_startaccum(p);
  8454. return val;
  8455. }
  8456. static void start_year(upb_json_parser *p, const char *ptr) {
  8457. capture_begin(p, ptr);
  8458. }
  8459. static bool end_year(upb_json_parser *p, const char *ptr) {
  8460. if (!capture_end(p, ptr)) {
  8461. return false;
  8462. }
  8463. p->tm.tm_year = parse_timestamp_number(p) - 1900;
  8464. return true;
  8465. }
  8466. static void start_month(upb_json_parser *p, const char *ptr) {
  8467. capture_begin(p, ptr);
  8468. }
  8469. static bool end_month(upb_json_parser *p, const char *ptr) {
  8470. if (!capture_end(p, ptr)) {
  8471. return false;
  8472. }
  8473. p->tm.tm_mon = parse_timestamp_number(p) - 1;
  8474. return true;
  8475. }
  8476. static void start_day(upb_json_parser *p, const char *ptr) {
  8477. capture_begin(p, ptr);
  8478. }
  8479. static bool end_day(upb_json_parser *p, const char *ptr) {
  8480. if (!capture_end(p, ptr)) {
  8481. return false;
  8482. }
  8483. p->tm.tm_mday = parse_timestamp_number(p);
  8484. return true;
  8485. }
  8486. static void start_hour(upb_json_parser *p, const char *ptr) {
  8487. capture_begin(p, ptr);
  8488. }
  8489. static bool end_hour(upb_json_parser *p, const char *ptr) {
  8490. if (!capture_end(p, ptr)) {
  8491. return false;
  8492. }
  8493. p->tm.tm_hour = parse_timestamp_number(p);
  8494. return true;
  8495. }
  8496. static void start_minute(upb_json_parser *p, const char *ptr) {
  8497. capture_begin(p, ptr);
  8498. }
  8499. static bool end_minute(upb_json_parser *p, const char *ptr) {
  8500. if (!capture_end(p, ptr)) {
  8501. return false;
  8502. }
  8503. p->tm.tm_min = parse_timestamp_number(p);
  8504. return true;
  8505. }
  8506. static void start_second(upb_json_parser *p, const char *ptr) {
  8507. capture_begin(p, ptr);
  8508. }
  8509. static bool end_second(upb_json_parser *p, const char *ptr) {
  8510. if (!capture_end(p, ptr)) {
  8511. return false;
  8512. }
  8513. p->tm.tm_sec = parse_timestamp_number(p);
  8514. return true;
  8515. }
  8516. static void start_timestamp_base(upb_json_parser *p) {
  8517. memset(&p->tm, 0, sizeof(struct tm));
  8518. }
  8519. static void start_timestamp_fraction(upb_json_parser *p, const char *ptr) {
  8520. capture_begin(p, ptr);
  8521. }
  8522. static bool end_timestamp_fraction(upb_json_parser *p, const char *ptr) {
  8523. size_t len;
  8524. const char *buf;
  8525. char nanos_buf[12];
  8526. char *end;
  8527. double val = 0.0;
  8528. int32_t nanos;
  8529. const char *nanos_membername = "nanos";
  8530. memset(nanos_buf, 0, 12);
  8531. if (!capture_end(p, ptr)) {
  8532. return false;
  8533. }
  8534. buf = accumulate_getptr(p, &len);
  8535. if (len > 10) {
  8536. upb_status_seterrf(p->status,
  8537. "error parsing timestamp: at most 9-digit fraction.");
  8538. return false;
  8539. }
  8540. /* Parse nanos */
  8541. nanos_buf[0] = '0';
  8542. memcpy(nanos_buf + 1, buf, len);
  8543. val = strtod(nanos_buf, &end);
  8544. if (errno == ERANGE || end != nanos_buf + len + 1) {
  8545. upb_status_seterrf(p->status, "error parsing timestamp nanos: %s",
  8546. nanos_buf);
  8547. return false;
  8548. }
  8549. nanos = val * 1000000000;
  8550. /* Clean up previous environment */
  8551. multipart_end(p);
  8552. /* Set nanos */
  8553. start_member(p);
  8554. capture_begin(p, nanos_membername);
  8555. capture_end(p, nanos_membername + 5);
  8556. end_membername(p);
  8557. upb_sink_putint32(p->top->sink, parser_getsel(p), nanos);
  8558. end_member(p);
  8559. /* Continue previous environment */
  8560. multipart_startaccum(p);
  8561. return true;
  8562. }
  8563. static void start_timestamp_zone(upb_json_parser *p, const char *ptr) {
  8564. capture_begin(p, ptr);
  8565. }
  8566. #define EPOCH_YEAR 1970
  8567. #define TM_YEAR_BASE 1900
  8568. static bool isleap(int year) {
  8569. return (year % 4) == 0 && (year % 100 != 0 || (year % 400) == 0);
  8570. }
  8571. const unsigned short int __mon_yday[2][13] = {
  8572. /* Normal years. */
  8573. { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 },
  8574. /* Leap years. */
  8575. { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }
  8576. };
  8577. int64_t epoch(int year, int yday, int hour, int min, int sec) {
  8578. int64_t years = year - EPOCH_YEAR;
  8579. int64_t leap_days = years / 4 - years / 100 + years / 400;
  8580. int64_t days = years * 365 + yday + leap_days;
  8581. int64_t hours = days * 24 + hour;
  8582. int64_t mins = hours * 60 + min;
  8583. int64_t secs = mins * 60 + sec;
  8584. return secs;
  8585. }
  8586. static int64_t upb_mktime(const struct tm *tp) {
  8587. int sec = tp->tm_sec;
  8588. int min = tp->tm_min;
  8589. int hour = tp->tm_hour;
  8590. int mday = tp->tm_mday;
  8591. int mon = tp->tm_mon;
  8592. int year = tp->tm_year + TM_YEAR_BASE;
  8593. /* Calculate day of year from year, month, and day of month. */
  8594. int mon_yday = ((__mon_yday[isleap(year)][mon]) - 1);
  8595. int yday = mon_yday + mday;
  8596. return epoch(year, yday, hour, min, sec);
  8597. }
  8598. static bool end_timestamp_zone(upb_json_parser *p, const char *ptr) {
  8599. size_t len;
  8600. const char *buf;
  8601. int hours;
  8602. int64_t seconds;
  8603. const char *seconds_membername = "seconds";
  8604. if (!capture_end(p, ptr)) {
  8605. return false;
  8606. }
  8607. buf = accumulate_getptr(p, &len);
  8608. if (buf[0] != 'Z') {
  8609. if (sscanf(buf + 1, "%2d:00", &hours) != 1) {
  8610. upb_status_seterrf(p->status, "error parsing timestamp offset");
  8611. return false;
  8612. }
  8613. if (buf[0] == '+') {
  8614. hours = -hours;
  8615. }
  8616. p->tm.tm_hour += hours;
  8617. }
  8618. /* Normalize tm */
  8619. seconds = upb_mktime(&p->tm);
  8620. /* Check timestamp boundary */
  8621. if (seconds < -62135596800) {
  8622. upb_status_seterrf(p->status, "error parsing timestamp: "
  8623. "minimum acceptable value is "
  8624. "0001-01-01T00:00:00Z");
  8625. return false;
  8626. }
  8627. /* Clean up previous environment */
  8628. multipart_end(p);
  8629. /* Set seconds */
  8630. start_member(p);
  8631. capture_begin(p, seconds_membername);
  8632. capture_end(p, seconds_membername + 7);
  8633. end_membername(p);
  8634. upb_sink_putint64(p->top->sink, parser_getsel(p), seconds);
  8635. end_member(p);
  8636. /* Continue previous environment */
  8637. multipart_startaccum(p);
  8638. return true;
  8639. }
  8640. static void start_fieldmask_path_text(upb_json_parser *p, const char *ptr) {
  8641. capture_begin(p, ptr);
  8642. }
  8643. static bool end_fieldmask_path_text(upb_json_parser *p, const char *ptr) {
  8644. return capture_end(p, ptr);
  8645. }
  8646. static bool start_fieldmask_path(upb_json_parser *p) {
  8647. upb_jsonparser_frame *inner;
  8648. upb_selector_t sel;
  8649. if (!check_stack(p)) return false;
  8650. /* Start a new parser frame: parser frames correspond one-to-one with
  8651. * handler frames, and string events occur in a sub-frame. */
  8652. inner = start_jsonparser_frame(p);
  8653. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  8654. upb_sink_startstr(p->top->sink, sel, 0, &inner->sink);
  8655. inner->m = p->top->m;
  8656. inner->f = p->top->f;
  8657. p->top = inner;
  8658. multipart_startaccum(p);
  8659. return true;
  8660. }
  8661. static bool lower_camel_push(
  8662. upb_json_parser *p, upb_selector_t sel, const char *ptr, size_t len) {
  8663. const char *limit = ptr + len;
  8664. bool first = true;
  8665. for (;ptr < limit; ptr++) {
  8666. if (*ptr >= 'A' && *ptr <= 'Z' && !first) {
  8667. char lower = tolower(*ptr);
  8668. upb_sink_putstring(p->top->sink, sel, "_", 1, NULL);
  8669. upb_sink_putstring(p->top->sink, sel, &lower, 1, NULL);
  8670. } else {
  8671. upb_sink_putstring(p->top->sink, sel, ptr, 1, NULL);
  8672. }
  8673. first = false;
  8674. }
  8675. return true;
  8676. }
  8677. static bool end_fieldmask_path(upb_json_parser *p) {
  8678. upb_selector_t sel;
  8679. if (!lower_camel_push(
  8680. p, getsel_for_handlertype(p, UPB_HANDLER_STRING),
  8681. p->accumulated, p->accumulated_len)) {
  8682. return false;
  8683. }
  8684. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  8685. upb_sink_endstr(p->top->sink, sel);
  8686. p->top--;
  8687. multipart_end(p);
  8688. return true;
  8689. }
  8690. static void start_member(upb_json_parser *p) {
  8691. UPB_ASSERT(!p->top->f);
  8692. multipart_startaccum(p);
  8693. }
  8694. /* Helper: invoked during parse_mapentry() to emit the mapentry message's key
  8695. * field based on the current contents of the accumulate buffer. */
  8696. static bool parse_mapentry_key(upb_json_parser *p) {
  8697. size_t len;
  8698. const char *buf = accumulate_getptr(p, &len);
  8699. /* Emit the key field. We do a bit of ad-hoc parsing here because the
  8700. * parser state machine has already decided that this is a string field
  8701. * name, and we are reinterpreting it as some arbitrary key type. In
  8702. * particular, integer and bool keys are quoted, so we need to parse the
  8703. * quoted string contents here. */
  8704. p->top->f = upb_msgdef_itof(p->top->m, UPB_MAPENTRY_KEY);
  8705. if (p->top->f == NULL) {
  8706. upb_status_seterrmsg(p->status, "mapentry message has no key");
  8707. return false;
  8708. }
  8709. switch (upb_fielddef_type(p->top->f)) {
  8710. case UPB_TYPE_INT32:
  8711. case UPB_TYPE_INT64:
  8712. case UPB_TYPE_UINT32:
  8713. case UPB_TYPE_UINT64:
  8714. /* Invoke end_number. The accum buffer has the number's text already. */
  8715. if (!parse_number(p, true)) {
  8716. return false;
  8717. }
  8718. break;
  8719. case UPB_TYPE_BOOL:
  8720. if (len == 4 && !strncmp(buf, "true", 4)) {
  8721. if (!parser_putbool(p, true)) {
  8722. return false;
  8723. }
  8724. } else if (len == 5 && !strncmp(buf, "false", 5)) {
  8725. if (!parser_putbool(p, false)) {
  8726. return false;
  8727. }
  8728. } else {
  8729. upb_status_seterrmsg(p->status,
  8730. "Map bool key not 'true' or 'false'");
  8731. return false;
  8732. }
  8733. multipart_end(p);
  8734. break;
  8735. case UPB_TYPE_STRING:
  8736. case UPB_TYPE_BYTES: {
  8737. upb_sink subsink;
  8738. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  8739. upb_sink_startstr(p->top->sink, sel, len, &subsink);
  8740. sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
  8741. upb_sink_putstring(subsink, sel, buf, len, NULL);
  8742. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  8743. upb_sink_endstr(subsink, sel);
  8744. multipart_end(p);
  8745. break;
  8746. }
  8747. default:
  8748. upb_status_seterrmsg(p->status, "Invalid field type for map key");
  8749. return false;
  8750. }
  8751. return true;
  8752. }
  8753. /* Helper: emit one map entry (as a submessage in the map field sequence). This
  8754. * is invoked from end_membername(), at the end of the map entry's key string,
  8755. * with the map key in the accumulate buffer. It parses the key from that
  8756. * buffer, emits the handler calls to start the mapentry submessage (setting up
  8757. * its subframe in the process), and sets up state in the subframe so that the
  8758. * value parser (invoked next) will emit the mapentry's value field and then
  8759. * end the mapentry message. */
  8760. static bool handle_mapentry(upb_json_parser *p) {
  8761. const upb_fielddef *mapfield;
  8762. const upb_msgdef *mapentrymsg;
  8763. upb_jsonparser_frame *inner;
  8764. upb_selector_t sel;
  8765. /* Map entry: p->top->sink is the seq frame, so we need to start a frame
  8766. * for the mapentry itself, and then set |f| in that frame so that the map
  8767. * value field is parsed, and also set a flag to end the frame after the
  8768. * map-entry value is parsed. */
  8769. if (!check_stack(p)) return false;
  8770. mapfield = p->top->mapfield;
  8771. mapentrymsg = upb_fielddef_msgsubdef(mapfield);
  8772. inner = start_jsonparser_frame(p);
  8773. p->top->f = mapfield;
  8774. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
  8775. upb_sink_startsubmsg(p->top->sink, sel, &inner->sink);
  8776. inner->m = mapentrymsg;
  8777. inner->mapfield = mapfield;
  8778. /* Don't set this to true *yet* -- we reuse parsing handlers below to push
  8779. * the key field value to the sink, and these handlers will pop the frame
  8780. * if they see is_mapentry (when invoked by the parser state machine, they
  8781. * would have just seen the map-entry value, not key). */
  8782. inner->is_mapentry = false;
  8783. p->top = inner;
  8784. /* send STARTMSG in submsg frame. */
  8785. upb_sink_startmsg(p->top->sink);
  8786. parse_mapentry_key(p);
  8787. /* Set up the value field to receive the map-entry value. */
  8788. p->top->f = upb_msgdef_itof(p->top->m, UPB_MAPENTRY_VALUE);
  8789. p->top->is_mapentry = true; /* set up to pop frame after value is parsed. */
  8790. p->top->mapfield = mapfield;
  8791. if (p->top->f == NULL) {
  8792. upb_status_seterrmsg(p->status, "mapentry message has no value");
  8793. return false;
  8794. }
  8795. return true;
  8796. }
  8797. static bool end_membername(upb_json_parser *p) {
  8798. UPB_ASSERT(!p->top->f);
  8799. if (!p->top->m) {
  8800. p->top->is_unknown_field = true;
  8801. multipart_end(p);
  8802. return true;
  8803. }
  8804. if (p->top->is_any) {
  8805. return end_any_membername(p);
  8806. } else if (p->top->is_map) {
  8807. return handle_mapentry(p);
  8808. } else {
  8809. size_t len;
  8810. const char *buf = accumulate_getptr(p, &len);
  8811. upb_value v;
  8812. if (upb_strtable_lookup2(p->top->name_table, buf, len, &v)) {
  8813. p->top->f = upb_value_getconstptr(v);
  8814. multipart_end(p);
  8815. return true;
  8816. } else if (p->ignore_json_unknown) {
  8817. p->top->is_unknown_field = true;
  8818. multipart_end(p);
  8819. return true;
  8820. } else {
  8821. upb_status_seterrf(p->status, "No such field: %.*s\n", (int)len, buf);
  8822. return false;
  8823. }
  8824. }
  8825. }
  8826. static bool end_any_membername(upb_json_parser *p) {
  8827. size_t len;
  8828. const char *buf = accumulate_getptr(p, &len);
  8829. upb_value v;
  8830. if (len == 5 && strncmp(buf, "@type", len) == 0) {
  8831. upb_strtable_lookup2(p->top->name_table, "type_url", 8, &v);
  8832. p->top->f = upb_value_getconstptr(v);
  8833. multipart_end(p);
  8834. return true;
  8835. } else {
  8836. p->top->is_unknown_field = true;
  8837. multipart_end(p);
  8838. return true;
  8839. }
  8840. }
  8841. static void end_member(upb_json_parser *p) {
  8842. /* If we just parsed a map-entry value, end that frame too. */
  8843. if (p->top->is_mapentry) {
  8844. upb_selector_t sel;
  8845. bool ok;
  8846. const upb_fielddef *mapfield;
  8847. UPB_ASSERT(p->top > p->stack);
  8848. /* send ENDMSG on submsg. */
  8849. upb_sink_endmsg(p->top->sink, p->status);
  8850. mapfield = p->top->mapfield;
  8851. /* send ENDSUBMSG in repeated-field-of-mapentries frame. */
  8852. p->top--;
  8853. ok = upb_handlers_getselector(mapfield, UPB_HANDLER_ENDSUBMSG, &sel);
  8854. UPB_ASSERT(ok);
  8855. upb_sink_endsubmsg(p->top->sink, sel);
  8856. }
  8857. p->top->f = NULL;
  8858. p->top->is_unknown_field = false;
  8859. }
  8860. static void start_any_member(upb_json_parser *p, const char *ptr) {
  8861. start_member(p);
  8862. json_parser_any_frame_set_after_type_url_start_once(p->top->any_frame, ptr);
  8863. }
  8864. static void end_any_member(upb_json_parser *p, const char *ptr) {
  8865. json_parser_any_frame_set_before_type_url_end(p->top->any_frame, ptr);
  8866. end_member(p);
  8867. }
  8868. static bool start_subobject(upb_json_parser *p) {
  8869. if (p->top->is_unknown_field) {
  8870. if (!check_stack(p)) return false;
  8871. p->top = start_jsonparser_frame(p);
  8872. return true;
  8873. }
  8874. if (upb_fielddef_ismap(p->top->f)) {
  8875. upb_jsonparser_frame *inner;
  8876. upb_selector_t sel;
  8877. /* Beginning of a map. Start a new parser frame in a repeated-field
  8878. * context. */
  8879. if (!check_stack(p)) return false;
  8880. inner = start_jsonparser_frame(p);
  8881. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
  8882. upb_sink_startseq(p->top->sink, sel, &inner->sink);
  8883. inner->m = upb_fielddef_msgsubdef(p->top->f);
  8884. inner->mapfield = p->top->f;
  8885. inner->is_map = true;
  8886. p->top = inner;
  8887. return true;
  8888. } else if (upb_fielddef_issubmsg(p->top->f)) {
  8889. upb_jsonparser_frame *inner;
  8890. upb_selector_t sel;
  8891. /* Beginning of a subobject. Start a new parser frame in the submsg
  8892. * context. */
  8893. if (!check_stack(p)) return false;
  8894. inner = start_jsonparser_frame(p);
  8895. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
  8896. upb_sink_startsubmsg(p->top->sink, sel, &inner->sink);
  8897. inner->m = upb_fielddef_msgsubdef(p->top->f);
  8898. set_name_table(p, inner);
  8899. p->top = inner;
  8900. if (is_wellknown_msg(p, UPB_WELLKNOWN_ANY)) {
  8901. p->top->is_any = true;
  8902. p->top->any_frame = json_parser_any_frame_new(p);
  8903. } else {
  8904. p->top->is_any = false;
  8905. p->top->any_frame = NULL;
  8906. }
  8907. return true;
  8908. } else {
  8909. upb_status_seterrf(p->status,
  8910. "Object specified for non-message/group field: %s",
  8911. upb_fielddef_name(p->top->f));
  8912. return false;
  8913. }
  8914. }
  8915. static bool start_subobject_full(upb_json_parser *p) {
  8916. if (is_top_level(p)) {
  8917. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8918. start_value_object(p, VALUE_STRUCTVALUE);
  8919. if (!start_subobject(p)) return false;
  8920. start_structvalue_object(p);
  8921. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_STRUCT)) {
  8922. start_structvalue_object(p);
  8923. } else {
  8924. return true;
  8925. }
  8926. } else if (is_wellknown_field(p, UPB_WELLKNOWN_STRUCT)) {
  8927. if (!start_subobject(p)) return false;
  8928. start_structvalue_object(p);
  8929. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  8930. if (!start_subobject(p)) return false;
  8931. start_value_object(p, VALUE_STRUCTVALUE);
  8932. if (!start_subobject(p)) return false;
  8933. start_structvalue_object(p);
  8934. }
  8935. return start_subobject(p);
  8936. }
  8937. static void end_subobject(upb_json_parser *p) {
  8938. if (is_top_level(p)) {
  8939. return;
  8940. }
  8941. if (p->top->is_map) {
  8942. upb_selector_t sel;
  8943. p->top--;
  8944. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
  8945. upb_sink_endseq(p->top->sink, sel);
  8946. } else {
  8947. upb_selector_t sel;
  8948. bool is_unknown = p->top->m == NULL;
  8949. p->top--;
  8950. if (!is_unknown) {
  8951. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSUBMSG);
  8952. upb_sink_endsubmsg(p->top->sink, sel);
  8953. }
  8954. }
  8955. }
  8956. static void end_subobject_full(upb_json_parser *p) {
  8957. end_subobject(p);
  8958. if (is_wellknown_msg(p, UPB_WELLKNOWN_STRUCT)) {
  8959. end_structvalue_object(p);
  8960. if (!is_top_level(p)) {
  8961. end_subobject(p);
  8962. }
  8963. }
  8964. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8965. end_value_object(p);
  8966. if (!is_top_level(p)) {
  8967. end_subobject(p);
  8968. }
  8969. }
  8970. }
  8971. static bool start_array(upb_json_parser *p) {
  8972. upb_jsonparser_frame *inner;
  8973. upb_selector_t sel;
  8974. if (is_top_level(p)) {
  8975. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8976. start_value_object(p, VALUE_LISTVALUE);
  8977. if (!start_subobject(p)) return false;
  8978. start_listvalue_object(p);
  8979. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_LISTVALUE)) {
  8980. start_listvalue_object(p);
  8981. } else {
  8982. return false;
  8983. }
  8984. } else if (is_wellknown_field(p, UPB_WELLKNOWN_LISTVALUE) &&
  8985. (!upb_fielddef_isseq(p->top->f) ||
  8986. p->top->is_repeated)) {
  8987. if (!start_subobject(p)) return false;
  8988. start_listvalue_object(p);
  8989. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE) &&
  8990. (!upb_fielddef_isseq(p->top->f) ||
  8991. p->top->is_repeated)) {
  8992. if (!start_subobject(p)) return false;
  8993. start_value_object(p, VALUE_LISTVALUE);
  8994. if (!start_subobject(p)) return false;
  8995. start_listvalue_object(p);
  8996. }
  8997. if (p->top->is_unknown_field) {
  8998. inner = start_jsonparser_frame(p);
  8999. inner->is_unknown_field = true;
  9000. p->top = inner;
  9001. return true;
  9002. }
  9003. if (!upb_fielddef_isseq(p->top->f)) {
  9004. upb_status_seterrf(p->status,
  9005. "Array specified for non-repeated field: %s",
  9006. upb_fielddef_name(p->top->f));
  9007. return false;
  9008. }
  9009. if (!check_stack(p)) return false;
  9010. inner = start_jsonparser_frame(p);
  9011. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
  9012. upb_sink_startseq(p->top->sink, sel, &inner->sink);
  9013. inner->m = p->top->m;
  9014. inner->f = p->top->f;
  9015. inner->is_repeated = true;
  9016. p->top = inner;
  9017. return true;
  9018. }
  9019. static void end_array(upb_json_parser *p) {
  9020. upb_selector_t sel;
  9021. UPB_ASSERT(p->top > p->stack);
  9022. p->top--;
  9023. if (p->top->is_unknown_field) {
  9024. return;
  9025. }
  9026. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
  9027. upb_sink_endseq(p->top->sink, sel);
  9028. if (is_wellknown_msg(p, UPB_WELLKNOWN_LISTVALUE)) {
  9029. end_listvalue_object(p);
  9030. if (!is_top_level(p)) {
  9031. end_subobject(p);
  9032. }
  9033. }
  9034. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  9035. end_value_object(p);
  9036. if (!is_top_level(p)) {
  9037. end_subobject(p);
  9038. }
  9039. }
  9040. }
  9041. static void start_object(upb_json_parser *p) {
  9042. if (!p->top->is_map && p->top->m != NULL) {
  9043. upb_sink_startmsg(p->top->sink);
  9044. }
  9045. }
  9046. static void end_object(upb_json_parser *p) {
  9047. if (!p->top->is_map && p->top->m != NULL) {
  9048. upb_sink_endmsg(p->top->sink, p->status);
  9049. }
  9050. }
  9051. static void start_any_object(upb_json_parser *p, const char *ptr) {
  9052. start_object(p);
  9053. p->top->any_frame->before_type_url_start = ptr;
  9054. p->top->any_frame->before_type_url_end = ptr;
  9055. }
  9056. static bool end_any_object(upb_json_parser *p, const char *ptr) {
  9057. const char *value_membername = "value";
  9058. bool is_well_known_packed = false;
  9059. const char *packed_end = ptr + 1;
  9060. upb_selector_t sel;
  9061. upb_jsonparser_frame *inner;
  9062. if (json_parser_any_frame_has_value(p->top->any_frame) &&
  9063. !json_parser_any_frame_has_type_url(p->top->any_frame)) {
  9064. upb_status_seterrmsg(p->status, "No valid type url");
  9065. return false;
  9066. }
  9067. /* Well known types data is represented as value field. */
  9068. if (upb_msgdef_wellknowntype(p->top->any_frame->parser->top->m) !=
  9069. UPB_WELLKNOWN_UNSPECIFIED) {
  9070. is_well_known_packed = true;
  9071. if (json_parser_any_frame_has_value_before_type_url(p->top->any_frame)) {
  9072. p->top->any_frame->before_type_url_start =
  9073. memchr(p->top->any_frame->before_type_url_start, ':',
  9074. p->top->any_frame->before_type_url_end -
  9075. p->top->any_frame->before_type_url_start);
  9076. if (p->top->any_frame->before_type_url_start == NULL) {
  9077. upb_status_seterrmsg(p->status, "invalid data for well known type.");
  9078. return false;
  9079. }
  9080. p->top->any_frame->before_type_url_start++;
  9081. }
  9082. if (json_parser_any_frame_has_value_after_type_url(p->top->any_frame)) {
  9083. p->top->any_frame->after_type_url_start =
  9084. memchr(p->top->any_frame->after_type_url_start, ':',
  9085. (ptr + 1) -
  9086. p->top->any_frame->after_type_url_start);
  9087. if (p->top->any_frame->after_type_url_start == NULL) {
  9088. upb_status_seterrmsg(p->status, "Invalid data for well known type.");
  9089. return false;
  9090. }
  9091. p->top->any_frame->after_type_url_start++;
  9092. packed_end = ptr;
  9093. }
  9094. }
  9095. if (json_parser_any_frame_has_value_before_type_url(p->top->any_frame)) {
  9096. if (!parse(p->top->any_frame->parser, NULL,
  9097. p->top->any_frame->before_type_url_start,
  9098. p->top->any_frame->before_type_url_end -
  9099. p->top->any_frame->before_type_url_start, NULL)) {
  9100. return false;
  9101. }
  9102. } else {
  9103. if (!is_well_known_packed) {
  9104. if (!parse(p->top->any_frame->parser, NULL, "{", 1, NULL)) {
  9105. return false;
  9106. }
  9107. }
  9108. }
  9109. if (json_parser_any_frame_has_value_before_type_url(p->top->any_frame) &&
  9110. json_parser_any_frame_has_value_after_type_url(p->top->any_frame)) {
  9111. if (!parse(p->top->any_frame->parser, NULL, ",", 1, NULL)) {
  9112. return false;
  9113. }
  9114. }
  9115. if (json_parser_any_frame_has_value_after_type_url(p->top->any_frame)) {
  9116. if (!parse(p->top->any_frame->parser, NULL,
  9117. p->top->any_frame->after_type_url_start,
  9118. packed_end - p->top->any_frame->after_type_url_start, NULL)) {
  9119. return false;
  9120. }
  9121. } else {
  9122. if (!is_well_known_packed) {
  9123. if (!parse(p->top->any_frame->parser, NULL, "}", 1, NULL)) {
  9124. return false;
  9125. }
  9126. }
  9127. }
  9128. if (!end(p->top->any_frame->parser, NULL)) {
  9129. return false;
  9130. }
  9131. p->top->is_any = false;
  9132. /* Set value */
  9133. start_member(p);
  9134. capture_begin(p, value_membername);
  9135. capture_end(p, value_membername + 5);
  9136. end_membername(p);
  9137. if (!check_stack(p)) return false;
  9138. inner = p->top + 1;
  9139. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  9140. upb_sink_startstr(p->top->sink, sel, 0, &inner->sink);
  9141. sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
  9142. upb_sink_putstring(inner->sink, sel, p->top->any_frame->stringsink.ptr,
  9143. p->top->any_frame->stringsink.len, NULL);
  9144. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  9145. upb_sink_endstr(inner->sink, sel);
  9146. end_member(p);
  9147. end_object(p);
  9148. /* Deallocate any parse frame. */
  9149. json_parser_any_frame_free(p->top->any_frame);
  9150. return true;
  9151. }
  9152. static bool is_string_wrapper(const upb_msgdef *m) {
  9153. upb_wellknowntype_t type = upb_msgdef_wellknowntype(m);
  9154. return type == UPB_WELLKNOWN_STRINGVALUE ||
  9155. type == UPB_WELLKNOWN_BYTESVALUE;
  9156. }
  9157. static bool is_fieldmask(const upb_msgdef *m) {
  9158. upb_wellknowntype_t type = upb_msgdef_wellknowntype(m);
  9159. return type == UPB_WELLKNOWN_FIELDMASK;
  9160. }
  9161. static void start_fieldmask_object(upb_json_parser *p) {
  9162. const char *membername = "paths";
  9163. start_object(p);
  9164. /* Set up context for parsing value */
  9165. start_member(p);
  9166. capture_begin(p, membername);
  9167. capture_end(p, membername + 5);
  9168. end_membername(p);
  9169. start_array(p);
  9170. }
  9171. static void end_fieldmask_object(upb_json_parser *p) {
  9172. end_array(p);
  9173. end_member(p);
  9174. end_object(p);
  9175. }
  9176. static void start_wrapper_object(upb_json_parser *p) {
  9177. const char *membername = "value";
  9178. start_object(p);
  9179. /* Set up context for parsing value */
  9180. start_member(p);
  9181. capture_begin(p, membername);
  9182. capture_end(p, membername + 5);
  9183. end_membername(p);
  9184. }
  9185. static void end_wrapper_object(upb_json_parser *p) {
  9186. end_member(p);
  9187. end_object(p);
  9188. }
  9189. static void start_value_object(upb_json_parser *p, int value_type) {
  9190. const char *nullmember = "null_value";
  9191. const char *numbermember = "number_value";
  9192. const char *stringmember = "string_value";
  9193. const char *boolmember = "bool_value";
  9194. const char *structmember = "struct_value";
  9195. const char *listmember = "list_value";
  9196. const char *membername = "";
  9197. switch (value_type) {
  9198. case VALUE_NULLVALUE:
  9199. membername = nullmember;
  9200. break;
  9201. case VALUE_NUMBERVALUE:
  9202. membername = numbermember;
  9203. break;
  9204. case VALUE_STRINGVALUE:
  9205. membername = stringmember;
  9206. break;
  9207. case VALUE_BOOLVALUE:
  9208. membername = boolmember;
  9209. break;
  9210. case VALUE_STRUCTVALUE:
  9211. membername = structmember;
  9212. break;
  9213. case VALUE_LISTVALUE:
  9214. membername = listmember;
  9215. break;
  9216. }
  9217. start_object(p);
  9218. /* Set up context for parsing value */
  9219. start_member(p);
  9220. capture_begin(p, membername);
  9221. capture_end(p, membername + strlen(membername));
  9222. end_membername(p);
  9223. }
  9224. static void end_value_object(upb_json_parser *p) {
  9225. end_member(p);
  9226. end_object(p);
  9227. }
  9228. static void start_listvalue_object(upb_json_parser *p) {
  9229. const char *membername = "values";
  9230. start_object(p);
  9231. /* Set up context for parsing value */
  9232. start_member(p);
  9233. capture_begin(p, membername);
  9234. capture_end(p, membername + strlen(membername));
  9235. end_membername(p);
  9236. }
  9237. static void end_listvalue_object(upb_json_parser *p) {
  9238. end_member(p);
  9239. end_object(p);
  9240. }
  9241. static void start_structvalue_object(upb_json_parser *p) {
  9242. const char *membername = "fields";
  9243. start_object(p);
  9244. /* Set up context for parsing value */
  9245. start_member(p);
  9246. capture_begin(p, membername);
  9247. capture_end(p, membername + strlen(membername));
  9248. end_membername(p);
  9249. }
  9250. static void end_structvalue_object(upb_json_parser *p) {
  9251. end_member(p);
  9252. end_object(p);
  9253. }
  9254. static bool is_top_level(upb_json_parser *p) {
  9255. return p->top == p->stack && p->top->f == NULL && !p->top->is_unknown_field;
  9256. }
  9257. static bool is_wellknown_msg(upb_json_parser *p, upb_wellknowntype_t type) {
  9258. return p->top->m != NULL && upb_msgdef_wellknowntype(p->top->m) == type;
  9259. }
  9260. static bool is_wellknown_field(upb_json_parser *p, upb_wellknowntype_t type) {
  9261. return p->top->f != NULL &&
  9262. upb_fielddef_issubmsg(p->top->f) &&
  9263. (upb_msgdef_wellknowntype(upb_fielddef_msgsubdef(p->top->f))
  9264. == type);
  9265. }
  9266. static bool does_number_wrapper_start(upb_json_parser *p) {
  9267. return p->top->f != NULL &&
  9268. upb_fielddef_issubmsg(p->top->f) &&
  9269. upb_msgdef_isnumberwrapper(upb_fielddef_msgsubdef(p->top->f));
  9270. }
  9271. static bool does_number_wrapper_end(upb_json_parser *p) {
  9272. return p->top->m != NULL && upb_msgdef_isnumberwrapper(p->top->m);
  9273. }
  9274. static bool is_number_wrapper_object(upb_json_parser *p) {
  9275. return p->top->m != NULL && upb_msgdef_isnumberwrapper(p->top->m);
  9276. }
  9277. static bool does_string_wrapper_start(upb_json_parser *p) {
  9278. return p->top->f != NULL &&
  9279. upb_fielddef_issubmsg(p->top->f) &&
  9280. is_string_wrapper(upb_fielddef_msgsubdef(p->top->f));
  9281. }
  9282. static bool does_string_wrapper_end(upb_json_parser *p) {
  9283. return p->top->m != NULL && is_string_wrapper(p->top->m);
  9284. }
  9285. static bool is_string_wrapper_object(upb_json_parser *p) {
  9286. return p->top->m != NULL && is_string_wrapper(p->top->m);
  9287. }
  9288. static bool does_fieldmask_start(upb_json_parser *p) {
  9289. return p->top->f != NULL &&
  9290. upb_fielddef_issubmsg(p->top->f) &&
  9291. is_fieldmask(upb_fielddef_msgsubdef(p->top->f));
  9292. }
  9293. static bool does_fieldmask_end(upb_json_parser *p) {
  9294. return p->top->m != NULL && is_fieldmask(p->top->m);
  9295. }
  9296. #define CHECK_RETURN_TOP(x) if (!(x)) goto error
  9297. /* The actual parser **********************************************************/
  9298. /* What follows is the Ragel parser itself. The language is specified in Ragel
  9299. * and the actions call our C functions above.
  9300. *
  9301. * Ragel has an extensive set of functionality, and we use only a small part of
  9302. * it. There are many action types but we only use a few:
  9303. *
  9304. * ">" -- transition into a machine
  9305. * "%" -- transition out of a machine
  9306. * "@" -- transition into a final state of a machine.
  9307. *
  9308. * "@" transitions are tricky because a machine can transition into a final
  9309. * state repeatedly. But in some cases we know this can't happen, for example
  9310. * a string which is delimited by a final '"' can only transition into its
  9311. * final state once, when the closing '"' is seen. */
  9312. #line 2794 "upb/json/parser.rl"
  9313. #line 2597 "upb/json/parser.c"
  9314. static const char _json_actions[] = {
  9315. 0, 1, 0, 1, 1, 1, 3, 1,
  9316. 4, 1, 6, 1, 7, 1, 8, 1,
  9317. 9, 1, 11, 1, 12, 1, 13, 1,
  9318. 14, 1, 15, 1, 16, 1, 17, 1,
  9319. 18, 1, 19, 1, 20, 1, 22, 1,
  9320. 23, 1, 24, 1, 35, 1, 37, 1,
  9321. 39, 1, 40, 1, 42, 1, 43, 1,
  9322. 44, 1, 46, 1, 48, 1, 49, 1,
  9323. 50, 1, 51, 1, 53, 1, 54, 2,
  9324. 4, 9, 2, 5, 6, 2, 7, 3,
  9325. 2, 7, 9, 2, 21, 26, 2, 25,
  9326. 10, 2, 27, 28, 2, 29, 30, 2,
  9327. 32, 34, 2, 33, 31, 2, 38, 36,
  9328. 2, 40, 42, 2, 45, 2, 2, 46,
  9329. 54, 2, 47, 36, 2, 49, 54, 2,
  9330. 50, 54, 2, 51, 54, 2, 52, 41,
  9331. 2, 53, 54, 3, 32, 34, 35, 4,
  9332. 21, 26, 27, 28
  9333. };
  9334. static const short _json_key_offsets[] = {
  9335. 0, 0, 12, 13, 18, 23, 28, 29,
  9336. 30, 31, 32, 33, 34, 35, 36, 37,
  9337. 38, 43, 44, 48, 53, 58, 63, 67,
  9338. 71, 74, 77, 79, 83, 87, 89, 91,
  9339. 96, 98, 100, 109, 115, 121, 127, 133,
  9340. 135, 139, 142, 144, 146, 149, 150, 154,
  9341. 156, 158, 160, 162, 163, 165, 167, 168,
  9342. 170, 172, 173, 175, 177, 178, 180, 182,
  9343. 183, 185, 187, 191, 193, 195, 196, 197,
  9344. 198, 199, 201, 206, 208, 210, 212, 221,
  9345. 222, 222, 222, 227, 232, 237, 238, 239,
  9346. 240, 241, 241, 242, 243, 244, 244, 245,
  9347. 246, 247, 247, 252, 253, 257, 262, 267,
  9348. 272, 276, 276, 279, 282, 285, 288, 291,
  9349. 294, 294, 294, 294, 294, 294
  9350. };
  9351. static const char _json_trans_keys[] = {
  9352. 32, 34, 45, 91, 102, 110, 116, 123,
  9353. 9, 13, 48, 57, 34, 32, 93, 125,
  9354. 9, 13, 32, 44, 93, 9, 13, 32,
  9355. 93, 125, 9, 13, 97, 108, 115, 101,
  9356. 117, 108, 108, 114, 117, 101, 32, 34,
  9357. 125, 9, 13, 34, 32, 58, 9, 13,
  9358. 32, 93, 125, 9, 13, 32, 44, 125,
  9359. 9, 13, 32, 44, 125, 9, 13, 32,
  9360. 34, 9, 13, 45, 48, 49, 57, 48,
  9361. 49, 57, 46, 69, 101, 48, 57, 69,
  9362. 101, 48, 57, 43, 45, 48, 57, 48,
  9363. 57, 48, 57, 46, 69, 101, 48, 57,
  9364. 34, 92, 34, 92, 34, 47, 92, 98,
  9365. 102, 110, 114, 116, 117, 48, 57, 65,
  9366. 70, 97, 102, 48, 57, 65, 70, 97,
  9367. 102, 48, 57, 65, 70, 97, 102, 48,
  9368. 57, 65, 70, 97, 102, 34, 92, 45,
  9369. 48, 49, 57, 48, 49, 57, 46, 115,
  9370. 48, 57, 115, 48, 57, 34, 46, 115,
  9371. 48, 57, 48, 57, 48, 57, 48, 57,
  9372. 48, 57, 45, 48, 57, 48, 57, 45,
  9373. 48, 57, 48, 57, 84, 48, 57, 48,
  9374. 57, 58, 48, 57, 48, 57, 58, 48,
  9375. 57, 48, 57, 43, 45, 46, 90, 48,
  9376. 57, 48, 57, 58, 48, 48, 34, 48,
  9377. 57, 43, 45, 90, 48, 57, 34, 44,
  9378. 34, 44, 34, 44, 34, 45, 91, 102,
  9379. 110, 116, 123, 48, 57, 34, 32, 93,
  9380. 125, 9, 13, 32, 44, 93, 9, 13,
  9381. 32, 93, 125, 9, 13, 97, 108, 115,
  9382. 101, 117, 108, 108, 114, 117, 101, 32,
  9383. 34, 125, 9, 13, 34, 32, 58, 9,
  9384. 13, 32, 93, 125, 9, 13, 32, 44,
  9385. 125, 9, 13, 32, 44, 125, 9, 13,
  9386. 32, 34, 9, 13, 32, 9, 13, 32,
  9387. 9, 13, 32, 9, 13, 32, 9, 13,
  9388. 32, 9, 13, 32, 9, 13, 0
  9389. };
  9390. static const char _json_single_lengths[] = {
  9391. 0, 8, 1, 3, 3, 3, 1, 1,
  9392. 1, 1, 1, 1, 1, 1, 1, 1,
  9393. 3, 1, 2, 3, 3, 3, 2, 2,
  9394. 1, 3, 0, 2, 2, 0, 0, 3,
  9395. 2, 2, 9, 0, 0, 0, 0, 2,
  9396. 2, 1, 2, 0, 1, 1, 2, 0,
  9397. 0, 0, 0, 1, 0, 0, 1, 0,
  9398. 0, 1, 0, 0, 1, 0, 0, 1,
  9399. 0, 0, 4, 0, 0, 1, 1, 1,
  9400. 1, 0, 3, 2, 2, 2, 7, 1,
  9401. 0, 0, 3, 3, 3, 1, 1, 1,
  9402. 1, 0, 1, 1, 1, 0, 1, 1,
  9403. 1, 0, 3, 1, 2, 3, 3, 3,
  9404. 2, 0, 1, 1, 1, 1, 1, 1,
  9405. 0, 0, 0, 0, 0, 0
  9406. };
  9407. static const char _json_range_lengths[] = {
  9408. 0, 2, 0, 1, 1, 1, 0, 0,
  9409. 0, 0, 0, 0, 0, 0, 0, 0,
  9410. 1, 0, 1, 1, 1, 1, 1, 1,
  9411. 1, 0, 1, 1, 1, 1, 1, 1,
  9412. 0, 0, 0, 3, 3, 3, 3, 0,
  9413. 1, 1, 0, 1, 1, 0, 1, 1,
  9414. 1, 1, 1, 0, 1, 1, 0, 1,
  9415. 1, 0, 1, 1, 0, 1, 1, 0,
  9416. 1, 1, 0, 1, 1, 0, 0, 0,
  9417. 0, 1, 1, 0, 0, 0, 1, 0,
  9418. 0, 0, 1, 1, 1, 0, 0, 0,
  9419. 0, 0, 0, 0, 0, 0, 0, 0,
  9420. 0, 0, 1, 0, 1, 1, 1, 1,
  9421. 1, 0, 1, 1, 1, 1, 1, 1,
  9422. 0, 0, 0, 0, 0, 0
  9423. };
  9424. static const short _json_index_offsets[] = {
  9425. 0, 0, 11, 13, 18, 23, 28, 30,
  9426. 32, 34, 36, 38, 40, 42, 44, 46,
  9427. 48, 53, 55, 59, 64, 69, 74, 78,
  9428. 82, 85, 89, 91, 95, 99, 101, 103,
  9429. 108, 111, 114, 124, 128, 132, 136, 140,
  9430. 143, 147, 150, 153, 155, 158, 160, 164,
  9431. 166, 168, 170, 172, 174, 176, 178, 180,
  9432. 182, 184, 186, 188, 190, 192, 194, 196,
  9433. 198, 200, 202, 207, 209, 211, 213, 215,
  9434. 217, 219, 221, 226, 229, 232, 235, 244,
  9435. 246, 247, 248, 253, 258, 263, 265, 267,
  9436. 269, 271, 272, 274, 276, 278, 279, 281,
  9437. 283, 285, 286, 291, 293, 297, 302, 307,
  9438. 312, 316, 317, 320, 323, 326, 329, 332,
  9439. 335, 336, 337, 338, 339, 340
  9440. };
  9441. static const unsigned char _json_indicies[] = {
  9442. 0, 2, 3, 4, 5, 6, 7, 8,
  9443. 0, 3, 1, 9, 1, 11, 12, 1,
  9444. 11, 10, 13, 14, 12, 13, 1, 14,
  9445. 1, 1, 14, 10, 15, 1, 16, 1,
  9446. 17, 1, 18, 1, 19, 1, 20, 1,
  9447. 21, 1, 22, 1, 23, 1, 24, 1,
  9448. 25, 26, 27, 25, 1, 28, 1, 29,
  9449. 30, 29, 1, 30, 1, 1, 30, 31,
  9450. 32, 33, 34, 32, 1, 35, 36, 27,
  9451. 35, 1, 36, 26, 36, 1, 37, 38,
  9452. 39, 1, 38, 39, 1, 41, 42, 42,
  9453. 40, 43, 1, 42, 42, 43, 40, 44,
  9454. 44, 45, 1, 45, 1, 45, 40, 41,
  9455. 42, 42, 39, 40, 47, 48, 46, 50,
  9456. 51, 49, 52, 52, 52, 52, 52, 52,
  9457. 52, 52, 53, 1, 54, 54, 54, 1,
  9458. 55, 55, 55, 1, 56, 56, 56, 1,
  9459. 57, 57, 57, 1, 59, 60, 58, 61,
  9460. 62, 63, 1, 64, 65, 1, 66, 67,
  9461. 1, 68, 1, 67, 68, 1, 69, 1,
  9462. 66, 67, 65, 1, 70, 1, 71, 1,
  9463. 72, 1, 73, 1, 74, 1, 75, 1,
  9464. 76, 1, 77, 1, 78, 1, 79, 1,
  9465. 80, 1, 81, 1, 82, 1, 83, 1,
  9466. 84, 1, 85, 1, 86, 1, 87, 1,
  9467. 88, 1, 89, 89, 90, 91, 1, 92,
  9468. 1, 93, 1, 94, 1, 95, 1, 96,
  9469. 1, 97, 1, 98, 1, 99, 99, 100,
  9470. 98, 1, 102, 1, 101, 104, 105, 103,
  9471. 1, 1, 101, 106, 107, 108, 109, 110,
  9472. 111, 112, 107, 1, 113, 1, 114, 115,
  9473. 117, 118, 1, 117, 116, 119, 120, 118,
  9474. 119, 1, 120, 1, 1, 120, 116, 121,
  9475. 1, 122, 1, 123, 1, 124, 1, 125,
  9476. 126, 1, 127, 1, 128, 1, 129, 130,
  9477. 1, 131, 1, 132, 1, 133, 134, 135,
  9478. 136, 134, 1, 137, 1, 138, 139, 138,
  9479. 1, 139, 1, 1, 139, 140, 141, 142,
  9480. 143, 141, 1, 144, 145, 136, 144, 1,
  9481. 145, 135, 145, 1, 146, 147, 147, 1,
  9482. 148, 148, 1, 149, 149, 1, 150, 150,
  9483. 1, 151, 151, 1, 152, 152, 1, 1,
  9484. 1, 1, 1, 1, 1, 0
  9485. };
  9486. static const char _json_trans_targs[] = {
  9487. 1, 0, 2, 107, 3, 6, 10, 13,
  9488. 16, 106, 4, 3, 106, 4, 5, 7,
  9489. 8, 9, 108, 11, 12, 109, 14, 15,
  9490. 110, 16, 17, 111, 18, 18, 19, 20,
  9491. 21, 22, 111, 21, 22, 24, 25, 31,
  9492. 112, 26, 28, 27, 29, 30, 33, 113,
  9493. 34, 33, 113, 34, 32, 35, 36, 37,
  9494. 38, 39, 33, 113, 34, 41, 42, 46,
  9495. 42, 46, 43, 45, 44, 114, 48, 49,
  9496. 50, 51, 52, 53, 54, 55, 56, 57,
  9497. 58, 59, 60, 61, 62, 63, 64, 65,
  9498. 66, 67, 73, 72, 68, 69, 70, 71,
  9499. 72, 115, 74, 67, 72, 76, 116, 76,
  9500. 116, 77, 79, 81, 82, 85, 90, 94,
  9501. 98, 80, 117, 117, 83, 82, 80, 83,
  9502. 84, 86, 87, 88, 89, 117, 91, 92,
  9503. 93, 117, 95, 96, 97, 117, 98, 99,
  9504. 105, 100, 100, 101, 102, 103, 104, 105,
  9505. 103, 104, 117, 106, 106, 106, 106, 106,
  9506. 106
  9507. };
  9508. static const unsigned char _json_trans_actions[] = {
  9509. 0, 0, 113, 107, 53, 0, 0, 0,
  9510. 125, 59, 45, 0, 55, 0, 0, 0,
  9511. 0, 0, 0, 0, 0, 0, 0, 0,
  9512. 0, 0, 101, 51, 47, 0, 0, 45,
  9513. 49, 49, 104, 0, 0, 0, 0, 0,
  9514. 3, 0, 0, 0, 0, 0, 5, 15,
  9515. 0, 0, 71, 7, 13, 0, 74, 9,
  9516. 9, 9, 77, 80, 11, 37, 37, 37,
  9517. 0, 0, 0, 39, 0, 41, 86, 0,
  9518. 0, 0, 17, 19, 0, 21, 23, 0,
  9519. 25, 27, 0, 29, 31, 0, 33, 35,
  9520. 0, 135, 83, 135, 0, 0, 0, 0,
  9521. 0, 92, 0, 89, 89, 98, 43, 0,
  9522. 131, 95, 113, 107, 53, 0, 0, 0,
  9523. 125, 59, 69, 110, 45, 0, 55, 0,
  9524. 0, 0, 0, 0, 0, 119, 0, 0,
  9525. 0, 122, 0, 0, 0, 116, 0, 101,
  9526. 51, 47, 0, 0, 45, 49, 49, 104,
  9527. 0, 0, 128, 0, 57, 63, 65, 61,
  9528. 67
  9529. };
  9530. static const unsigned char _json_eof_actions[] = {
  9531. 0, 0, 0, 0, 0, 0, 0, 0,
  9532. 0, 0, 0, 0, 0, 0, 0, 0,
  9533. 0, 0, 0, 0, 0, 0, 0, 0,
  9534. 0, 1, 0, 1, 0, 0, 1, 1,
  9535. 0, 0, 0, 0, 0, 0, 0, 0,
  9536. 0, 0, 0, 0, 0, 0, 0, 0,
  9537. 0, 0, 0, 0, 0, 0, 0, 0,
  9538. 0, 0, 0, 0, 0, 0, 0, 0,
  9539. 0, 0, 0, 0, 0, 0, 0, 0,
  9540. 0, 0, 0, 0, 0, 0, 0, 0,
  9541. 0, 0, 0, 0, 0, 0, 0, 0,
  9542. 0, 0, 0, 0, 0, 0, 0, 0,
  9543. 0, 0, 0, 0, 0, 0, 0, 0,
  9544. 0, 0, 0, 57, 63, 65, 61, 67,
  9545. 0, 0, 0, 0, 0, 0
  9546. };
  9547. static const int json_start = 1;
  9548. static const int json_en_number_machine = 23;
  9549. static const int json_en_string_machine = 32;
  9550. static const int json_en_duration_machine = 40;
  9551. static const int json_en_timestamp_machine = 47;
  9552. static const int json_en_fieldmask_machine = 75;
  9553. static const int json_en_value_machine = 78;
  9554. static const int json_en_main = 1;
  9555. #line 2797 "upb/json/parser.rl"
  9556. size_t parse(void *closure, const void *hd, const char *buf, size_t size,
  9557. const upb_bufhandle *handle) {
  9558. upb_json_parser *parser = closure;
  9559. /* Variables used by Ragel's generated code. */
  9560. int cs = parser->current_state;
  9561. int *stack = parser->parser_stack;
  9562. int top = parser->parser_top;
  9563. const char *p = buf;
  9564. const char *pe = buf + size;
  9565. const char *eof = &eof_ch;
  9566. parser->handle = handle;
  9567. UPB_UNUSED(hd);
  9568. UPB_UNUSED(handle);
  9569. capture_resume(parser, buf);
  9570. #line 2875 "upb/json/parser.c"
  9571. {
  9572. int _klen;
  9573. unsigned int _trans;
  9574. const char *_acts;
  9575. unsigned int _nacts;
  9576. const char *_keys;
  9577. if ( p == pe )
  9578. goto _test_eof;
  9579. if ( cs == 0 )
  9580. goto _out;
  9581. _resume:
  9582. _keys = _json_trans_keys + _json_key_offsets[cs];
  9583. _trans = _json_index_offsets[cs];
  9584. _klen = _json_single_lengths[cs];
  9585. if ( _klen > 0 ) {
  9586. const char *_lower = _keys;
  9587. const char *_mid;
  9588. const char *_upper = _keys + _klen - 1;
  9589. while (1) {
  9590. if ( _upper < _lower )
  9591. break;
  9592. _mid = _lower + ((_upper-_lower) >> 1);
  9593. if ( (*p) < *_mid )
  9594. _upper = _mid - 1;
  9595. else if ( (*p) > *_mid )
  9596. _lower = _mid + 1;
  9597. else {
  9598. _trans += (unsigned int)(_mid - _keys);
  9599. goto _match;
  9600. }
  9601. }
  9602. _keys += _klen;
  9603. _trans += _klen;
  9604. }
  9605. _klen = _json_range_lengths[cs];
  9606. if ( _klen > 0 ) {
  9607. const char *_lower = _keys;
  9608. const char *_mid;
  9609. const char *_upper = _keys + (_klen<<1) - 2;
  9610. while (1) {
  9611. if ( _upper < _lower )
  9612. break;
  9613. _mid = _lower + (((_upper-_lower) >> 1) & ~1);
  9614. if ( (*p) < _mid[0] )
  9615. _upper = _mid - 2;
  9616. else if ( (*p) > _mid[1] )
  9617. _lower = _mid + 2;
  9618. else {
  9619. _trans += (unsigned int)((_mid - _keys)>>1);
  9620. goto _match;
  9621. }
  9622. }
  9623. _trans += _klen;
  9624. }
  9625. _match:
  9626. _trans = _json_indicies[_trans];
  9627. cs = _json_trans_targs[_trans];
  9628. if ( _json_trans_actions[_trans] == 0 )
  9629. goto _again;
  9630. _acts = _json_actions + _json_trans_actions[_trans];
  9631. _nacts = (unsigned int) *_acts++;
  9632. while ( _nacts-- > 0 )
  9633. {
  9634. switch ( *_acts++ )
  9635. {
  9636. case 1:
  9637. #line 2602 "upb/json/parser.rl"
  9638. { p--; {cs = stack[--top]; goto _again;} }
  9639. break;
  9640. case 2:
  9641. #line 2604 "upb/json/parser.rl"
  9642. { p--; {stack[top++] = cs; cs = 23;goto _again;} }
  9643. break;
  9644. case 3:
  9645. #line 2608 "upb/json/parser.rl"
  9646. { start_text(parser, p); }
  9647. break;
  9648. case 4:
  9649. #line 2609 "upb/json/parser.rl"
  9650. { CHECK_RETURN_TOP(end_text(parser, p)); }
  9651. break;
  9652. case 5:
  9653. #line 2615 "upb/json/parser.rl"
  9654. { start_hex(parser); }
  9655. break;
  9656. case 6:
  9657. #line 2616 "upb/json/parser.rl"
  9658. { hexdigit(parser, p); }
  9659. break;
  9660. case 7:
  9661. #line 2617 "upb/json/parser.rl"
  9662. { CHECK_RETURN_TOP(end_hex(parser)); }
  9663. break;
  9664. case 8:
  9665. #line 2623 "upb/json/parser.rl"
  9666. { CHECK_RETURN_TOP(escape(parser, p)); }
  9667. break;
  9668. case 9:
  9669. #line 2629 "upb/json/parser.rl"
  9670. { p--; {cs = stack[--top]; goto _again;} }
  9671. break;
  9672. case 10:
  9673. #line 2634 "upb/json/parser.rl"
  9674. { start_year(parser, p); }
  9675. break;
  9676. case 11:
  9677. #line 2635 "upb/json/parser.rl"
  9678. { CHECK_RETURN_TOP(end_year(parser, p)); }
  9679. break;
  9680. case 12:
  9681. #line 2639 "upb/json/parser.rl"
  9682. { start_month(parser, p); }
  9683. break;
  9684. case 13:
  9685. #line 2640 "upb/json/parser.rl"
  9686. { CHECK_RETURN_TOP(end_month(parser, p)); }
  9687. break;
  9688. case 14:
  9689. #line 2644 "upb/json/parser.rl"
  9690. { start_day(parser, p); }
  9691. break;
  9692. case 15:
  9693. #line 2645 "upb/json/parser.rl"
  9694. { CHECK_RETURN_TOP(end_day(parser, p)); }
  9695. break;
  9696. case 16:
  9697. #line 2649 "upb/json/parser.rl"
  9698. { start_hour(parser, p); }
  9699. break;
  9700. case 17:
  9701. #line 2650 "upb/json/parser.rl"
  9702. { CHECK_RETURN_TOP(end_hour(parser, p)); }
  9703. break;
  9704. case 18:
  9705. #line 2654 "upb/json/parser.rl"
  9706. { start_minute(parser, p); }
  9707. break;
  9708. case 19:
  9709. #line 2655 "upb/json/parser.rl"
  9710. { CHECK_RETURN_TOP(end_minute(parser, p)); }
  9711. break;
  9712. case 20:
  9713. #line 2659 "upb/json/parser.rl"
  9714. { start_second(parser, p); }
  9715. break;
  9716. case 21:
  9717. #line 2660 "upb/json/parser.rl"
  9718. { CHECK_RETURN_TOP(end_second(parser, p)); }
  9719. break;
  9720. case 22:
  9721. #line 2665 "upb/json/parser.rl"
  9722. { start_duration_base(parser, p); }
  9723. break;
  9724. case 23:
  9725. #line 2666 "upb/json/parser.rl"
  9726. { CHECK_RETURN_TOP(end_duration_base(parser, p)); }
  9727. break;
  9728. case 24:
  9729. #line 2668 "upb/json/parser.rl"
  9730. { p--; {cs = stack[--top]; goto _again;} }
  9731. break;
  9732. case 25:
  9733. #line 2673 "upb/json/parser.rl"
  9734. { start_timestamp_base(parser); }
  9735. break;
  9736. case 26:
  9737. #line 2675 "upb/json/parser.rl"
  9738. { start_timestamp_fraction(parser, p); }
  9739. break;
  9740. case 27:
  9741. #line 2676 "upb/json/parser.rl"
  9742. { CHECK_RETURN_TOP(end_timestamp_fraction(parser, p)); }
  9743. break;
  9744. case 28:
  9745. #line 2678 "upb/json/parser.rl"
  9746. { start_timestamp_zone(parser, p); }
  9747. break;
  9748. case 29:
  9749. #line 2679 "upb/json/parser.rl"
  9750. { CHECK_RETURN_TOP(end_timestamp_zone(parser, p)); }
  9751. break;
  9752. case 30:
  9753. #line 2681 "upb/json/parser.rl"
  9754. { p--; {cs = stack[--top]; goto _again;} }
  9755. break;
  9756. case 31:
  9757. #line 2686 "upb/json/parser.rl"
  9758. { start_fieldmask_path_text(parser, p); }
  9759. break;
  9760. case 32:
  9761. #line 2687 "upb/json/parser.rl"
  9762. { end_fieldmask_path_text(parser, p); }
  9763. break;
  9764. case 33:
  9765. #line 2692 "upb/json/parser.rl"
  9766. { start_fieldmask_path(parser); }
  9767. break;
  9768. case 34:
  9769. #line 2693 "upb/json/parser.rl"
  9770. { end_fieldmask_path(parser); }
  9771. break;
  9772. case 35:
  9773. #line 2699 "upb/json/parser.rl"
  9774. { p--; {cs = stack[--top]; goto _again;} }
  9775. break;
  9776. case 36:
  9777. #line 2704 "upb/json/parser.rl"
  9778. {
  9779. if (is_wellknown_msg(parser, UPB_WELLKNOWN_TIMESTAMP)) {
  9780. {stack[top++] = cs; cs = 47;goto _again;}
  9781. } else if (is_wellknown_msg(parser, UPB_WELLKNOWN_DURATION)) {
  9782. {stack[top++] = cs; cs = 40;goto _again;}
  9783. } else if (is_wellknown_msg(parser, UPB_WELLKNOWN_FIELDMASK)) {
  9784. {stack[top++] = cs; cs = 75;goto _again;}
  9785. } else {
  9786. {stack[top++] = cs; cs = 32;goto _again;}
  9787. }
  9788. }
  9789. break;
  9790. case 37:
  9791. #line 2717 "upb/json/parser.rl"
  9792. { p--; {stack[top++] = cs; cs = 78;goto _again;} }
  9793. break;
  9794. case 38:
  9795. #line 2722 "upb/json/parser.rl"
  9796. {
  9797. if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
  9798. start_any_member(parser, p);
  9799. } else {
  9800. start_member(parser);
  9801. }
  9802. }
  9803. break;
  9804. case 39:
  9805. #line 2729 "upb/json/parser.rl"
  9806. { CHECK_RETURN_TOP(end_membername(parser)); }
  9807. break;
  9808. case 40:
  9809. #line 2732 "upb/json/parser.rl"
  9810. {
  9811. if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
  9812. end_any_member(parser, p);
  9813. } else {
  9814. end_member(parser);
  9815. }
  9816. }
  9817. break;
  9818. case 41:
  9819. #line 2743 "upb/json/parser.rl"
  9820. {
  9821. if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
  9822. start_any_object(parser, p);
  9823. } else {
  9824. start_object(parser);
  9825. }
  9826. }
  9827. break;
  9828. case 42:
  9829. #line 2752 "upb/json/parser.rl"
  9830. {
  9831. if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
  9832. CHECK_RETURN_TOP(end_any_object(parser, p));
  9833. } else {
  9834. end_object(parser);
  9835. }
  9836. }
  9837. break;
  9838. case 43:
  9839. #line 2764 "upb/json/parser.rl"
  9840. { CHECK_RETURN_TOP(start_array(parser)); }
  9841. break;
  9842. case 44:
  9843. #line 2768 "upb/json/parser.rl"
  9844. { end_array(parser); }
  9845. break;
  9846. case 45:
  9847. #line 2773 "upb/json/parser.rl"
  9848. { CHECK_RETURN_TOP(start_number(parser, p)); }
  9849. break;
  9850. case 46:
  9851. #line 2774 "upb/json/parser.rl"
  9852. { CHECK_RETURN_TOP(end_number(parser, p)); }
  9853. break;
  9854. case 47:
  9855. #line 2776 "upb/json/parser.rl"
  9856. { CHECK_RETURN_TOP(start_stringval(parser)); }
  9857. break;
  9858. case 48:
  9859. #line 2777 "upb/json/parser.rl"
  9860. { CHECK_RETURN_TOP(end_stringval(parser)); }
  9861. break;
  9862. case 49:
  9863. #line 2779 "upb/json/parser.rl"
  9864. { CHECK_RETURN_TOP(end_bool(parser, true)); }
  9865. break;
  9866. case 50:
  9867. #line 2781 "upb/json/parser.rl"
  9868. { CHECK_RETURN_TOP(end_bool(parser, false)); }
  9869. break;
  9870. case 51:
  9871. #line 2783 "upb/json/parser.rl"
  9872. { CHECK_RETURN_TOP(end_null(parser)); }
  9873. break;
  9874. case 52:
  9875. #line 2785 "upb/json/parser.rl"
  9876. { CHECK_RETURN_TOP(start_subobject_full(parser)); }
  9877. break;
  9878. case 53:
  9879. #line 2786 "upb/json/parser.rl"
  9880. { end_subobject_full(parser); }
  9881. break;
  9882. case 54:
  9883. #line 2791 "upb/json/parser.rl"
  9884. { p--; {cs = stack[--top]; goto _again;} }
  9885. break;
  9886. #line 3199 "upb/json/parser.c"
  9887. }
  9888. }
  9889. _again:
  9890. if ( cs == 0 )
  9891. goto _out;
  9892. if ( ++p != pe )
  9893. goto _resume;
  9894. _test_eof: {}
  9895. if ( p == eof )
  9896. {
  9897. const char *__acts = _json_actions + _json_eof_actions[cs];
  9898. unsigned int __nacts = (unsigned int) *__acts++;
  9899. while ( __nacts-- > 0 ) {
  9900. switch ( *__acts++ ) {
  9901. case 0:
  9902. #line 2600 "upb/json/parser.rl"
  9903. { p--; {cs = stack[--top]; if ( p == pe )
  9904. goto _test_eof;
  9905. goto _again;} }
  9906. break;
  9907. case 46:
  9908. #line 2774 "upb/json/parser.rl"
  9909. { CHECK_RETURN_TOP(end_number(parser, p)); }
  9910. break;
  9911. case 49:
  9912. #line 2779 "upb/json/parser.rl"
  9913. { CHECK_RETURN_TOP(end_bool(parser, true)); }
  9914. break;
  9915. case 50:
  9916. #line 2781 "upb/json/parser.rl"
  9917. { CHECK_RETURN_TOP(end_bool(parser, false)); }
  9918. break;
  9919. case 51:
  9920. #line 2783 "upb/json/parser.rl"
  9921. { CHECK_RETURN_TOP(end_null(parser)); }
  9922. break;
  9923. case 53:
  9924. #line 2786 "upb/json/parser.rl"
  9925. { end_subobject_full(parser); }
  9926. break;
  9927. #line 3241 "upb/json/parser.c"
  9928. }
  9929. }
  9930. }
  9931. _out: {}
  9932. }
  9933. #line 2819 "upb/json/parser.rl"
  9934. if (p != pe) {
  9935. upb_status_seterrf(parser->status, "Parse error at '%.*s'\n", pe - p, p);
  9936. } else {
  9937. capture_suspend(parser, &p);
  9938. }
  9939. error:
  9940. /* Save parsing state back to parser. */
  9941. parser->current_state = cs;
  9942. parser->parser_top = top;
  9943. return p - buf;
  9944. }
  9945. static bool end(void *closure, const void *hd) {
  9946. upb_json_parser *parser = closure;
  9947. /* Prevent compile warning on unused static constants. */
  9948. UPB_UNUSED(json_start);
  9949. UPB_UNUSED(json_en_duration_machine);
  9950. UPB_UNUSED(json_en_fieldmask_machine);
  9951. UPB_UNUSED(json_en_number_machine);
  9952. UPB_UNUSED(json_en_string_machine);
  9953. UPB_UNUSED(json_en_timestamp_machine);
  9954. UPB_UNUSED(json_en_value_machine);
  9955. UPB_UNUSED(json_en_main);
  9956. parse(parser, hd, &eof_ch, 0, NULL);
  9957. return parser->current_state >= 106;
  9958. }
  9959. static void json_parser_reset(upb_json_parser *p) {
  9960. int cs;
  9961. int top;
  9962. p->top = p->stack;
  9963. init_frame(p->top);
  9964. /* Emit Ragel initialization of the parser. */
  9965. #line 3292 "upb/json/parser.c"
  9966. {
  9967. cs = json_start;
  9968. top = 0;
  9969. }
  9970. #line 2861 "upb/json/parser.rl"
  9971. p->current_state = cs;
  9972. p->parser_top = top;
  9973. accumulate_clear(p);
  9974. p->multipart_state = MULTIPART_INACTIVE;
  9975. p->capture = NULL;
  9976. p->accumulated = NULL;
  9977. }
  9978. static upb_json_parsermethod *parsermethod_new(upb_json_codecache *c,
  9979. const upb_msgdef *md) {
  9980. upb_msg_field_iter i;
  9981. upb_alloc *alloc = upb_arena_alloc(c->arena);
  9982. upb_json_parsermethod *m = upb_malloc(alloc, sizeof(*m));
  9983. m->cache = c;
  9984. upb_byteshandler_init(&m->input_handler_);
  9985. upb_byteshandler_setstring(&m->input_handler_, parse, m);
  9986. upb_byteshandler_setendstr(&m->input_handler_, end, m);
  9987. upb_strtable_init2(&m->name_table, UPB_CTYPE_CONSTPTR, alloc);
  9988. /* Build name_table */
  9989. for(upb_msg_field_begin(&i, md);
  9990. !upb_msg_field_done(&i);
  9991. upb_msg_field_next(&i)) {
  9992. const upb_fielddef *f = upb_msg_iter_field(&i);
  9993. upb_value v = upb_value_constptr(f);
  9994. char *buf;
  9995. /* Add an entry for the JSON name. */
  9996. size_t len = upb_fielddef_getjsonname(f, NULL, 0);
  9997. buf = upb_malloc(alloc, len);
  9998. upb_fielddef_getjsonname(f, buf, len);
  9999. upb_strtable_insert3(&m->name_table, buf, strlen(buf), v, alloc);
  10000. if (strcmp(buf, upb_fielddef_name(f)) != 0) {
  10001. /* Since the JSON name is different from the regular field name, add an
  10002. * entry for the raw name (compliant proto3 JSON parsers must accept
  10003. * both). */
  10004. const char *name = upb_fielddef_name(f);
  10005. upb_strtable_insert3(&m->name_table, name, strlen(name), v, alloc);
  10006. }
  10007. }
  10008. return m;
  10009. }
  10010. /* Public API *****************************************************************/
  10011. upb_json_parser *upb_json_parser_create(upb_arena *arena,
  10012. const upb_json_parsermethod *method,
  10013. const upb_symtab* symtab,
  10014. upb_sink output,
  10015. upb_status *status,
  10016. bool ignore_json_unknown) {
  10017. #ifndef NDEBUG
  10018. const size_t size_before = upb_arena_bytesallocated(arena);
  10019. #endif
  10020. upb_json_parser *p = upb_arena_malloc(arena, sizeof(upb_json_parser));
  10021. if (!p) return false;
  10022. p->arena = arena;
  10023. p->method = method;
  10024. p->status = status;
  10025. p->limit = p->stack + UPB_JSON_MAX_DEPTH;
  10026. p->accumulate_buf = NULL;
  10027. p->accumulate_buf_size = 0;
  10028. upb_bytessink_reset(&p->input_, &method->input_handler_, p);
  10029. json_parser_reset(p);
  10030. p->top->sink = output;
  10031. p->top->m = upb_handlers_msgdef(output.handlers);
  10032. if (is_wellknown_msg(p, UPB_WELLKNOWN_ANY)) {
  10033. p->top->is_any = true;
  10034. p->top->any_frame = json_parser_any_frame_new(p);
  10035. } else {
  10036. p->top->is_any = false;
  10037. p->top->any_frame = NULL;
  10038. }
  10039. set_name_table(p, p->top);
  10040. p->symtab = symtab;
  10041. p->ignore_json_unknown = ignore_json_unknown;
  10042. /* If this fails, uncomment and increase the value in parser.h. */
  10043. /* fprintf(stderr, "%zd\n", upb_arena_bytesallocated(arena) - size_before); */
  10044. UPB_ASSERT_DEBUGVAR(upb_arena_bytesallocated(arena) - size_before <=
  10045. UPB_JSON_PARSER_SIZE);
  10046. return p;
  10047. }
  10048. upb_bytessink upb_json_parser_input(upb_json_parser *p) {
  10049. return p->input_;
  10050. }
  10051. const upb_byteshandler *upb_json_parsermethod_inputhandler(
  10052. const upb_json_parsermethod *m) {
  10053. return &m->input_handler_;
  10054. }
  10055. upb_json_codecache *upb_json_codecache_new(void) {
  10056. upb_alloc *alloc;
  10057. upb_json_codecache *c;
  10058. c = upb_gmalloc(sizeof(*c));
  10059. c->arena = upb_arena_new();
  10060. alloc = upb_arena_alloc(c->arena);
  10061. upb_inttable_init2(&c->methods, UPB_CTYPE_CONSTPTR, alloc);
  10062. return c;
  10063. }
  10064. void upb_json_codecache_free(upb_json_codecache *c) {
  10065. upb_arena_free(c->arena);
  10066. upb_gfree(c);
  10067. }
  10068. const upb_json_parsermethod *upb_json_codecache_get(upb_json_codecache *c,
  10069. const upb_msgdef *md) {
  10070. upb_json_parsermethod *m;
  10071. upb_value v;
  10072. upb_msg_field_iter i;
  10073. upb_alloc *alloc = upb_arena_alloc(c->arena);
  10074. if (upb_inttable_lookupptr(&c->methods, md, &v)) {
  10075. return upb_value_getconstptr(v);
  10076. }
  10077. m = parsermethod_new(c, md);
  10078. v = upb_value_constptr(m);
  10079. if (!m) return NULL;
  10080. if (!upb_inttable_insertptr2(&c->methods, md, v, alloc)) return NULL;
  10081. /* Populate parser methods for all submessages, so the name tables will
  10082. * be available during parsing. */
  10083. for(upb_msg_field_begin(&i, md);
  10084. !upb_msg_field_done(&i);
  10085. upb_msg_field_next(&i)) {
  10086. upb_fielddef *f = upb_msg_iter_field(&i);
  10087. if (upb_fielddef_issubmsg(f)) {
  10088. const upb_msgdef *subdef = upb_fielddef_msgsubdef(f);
  10089. const upb_json_parsermethod *sub_method =
  10090. upb_json_codecache_get(c, subdef);
  10091. if (!sub_method) return NULL;
  10092. }
  10093. }
  10094. return m;
  10095. }
  10096. /*
  10097. ** This currently uses snprintf() to format primitives, and could be optimized
  10098. ** further.
  10099. */
  10100. #include <ctype.h>
  10101. #include <stdint.h>
  10102. #include <string.h>
  10103. #include <time.h>
  10104. struct upb_json_printer {
  10105. upb_sink input_;
  10106. /* BytesSink closure. */
  10107. void *subc_;
  10108. upb_bytessink output_;
  10109. /* We track the depth so that we know when to emit startstr/endstr on the
  10110. * output. */
  10111. int depth_;
  10112. /* Have we emitted the first element? This state is necessary to emit commas
  10113. * without leaving a trailing comma in arrays/maps. We keep this state per
  10114. * frame depth.
  10115. *
  10116. * Why max_depth * 2? UPB_MAX_HANDLER_DEPTH counts depth as nested messages.
  10117. * We count frames (contexts in which we separate elements by commas) as both
  10118. * repeated fields and messages (maps), and the worst case is a
  10119. * message->repeated field->submessage->repeated field->... nesting. */
  10120. bool first_elem_[UPB_MAX_HANDLER_DEPTH * 2];
  10121. /* To print timestamp, printer needs to cache its seconds and nanos values
  10122. * and convert them when ending timestamp message. See comments of
  10123. * printer_sethandlers_timestamp for more detail. */
  10124. int64_t seconds;
  10125. int32_t nanos;
  10126. };
  10127. /* StringPiece; a pointer plus a length. */
  10128. typedef struct {
  10129. char *ptr;
  10130. size_t len;
  10131. } strpc;
  10132. void freestrpc(void *ptr) {
  10133. strpc *pc = ptr;
  10134. upb_gfree(pc->ptr);
  10135. upb_gfree(pc);
  10136. }
  10137. typedef struct {
  10138. bool preserve_fieldnames;
  10139. } upb_json_printercache;
  10140. /* Convert fielddef name to JSON name and return as a string piece. */
  10141. strpc *newstrpc(upb_handlers *h, const upb_fielddef *f,
  10142. bool preserve_fieldnames) {
  10143. /* TODO(haberman): handle malloc failure. */
  10144. strpc *ret = upb_gmalloc(sizeof(*ret));
  10145. if (preserve_fieldnames) {
  10146. ret->ptr = upb_gstrdup(upb_fielddef_name(f));
  10147. ret->len = strlen(ret->ptr);
  10148. } else {
  10149. size_t len;
  10150. ret->len = upb_fielddef_getjsonname(f, NULL, 0);
  10151. ret->ptr = upb_gmalloc(ret->len);
  10152. len = upb_fielddef_getjsonname(f, ret->ptr, ret->len);
  10153. UPB_ASSERT(len == ret->len);
  10154. ret->len--; /* NULL */
  10155. }
  10156. upb_handlers_addcleanup(h, ret, freestrpc);
  10157. return ret;
  10158. }
  10159. /* Convert a null-terminated const char* to a string piece. */
  10160. strpc *newstrpc_str(upb_handlers *h, const char * str) {
  10161. strpc * ret = upb_gmalloc(sizeof(*ret));
  10162. ret->ptr = upb_gstrdup(str);
  10163. ret->len = strlen(str);
  10164. upb_handlers_addcleanup(h, ret, freestrpc);
  10165. return ret;
  10166. }
  10167. /* ------------ JSON string printing: values, maps, arrays ------------------ */
  10168. static void print_data(
  10169. upb_json_printer *p, const char *buf, unsigned int len) {
  10170. /* TODO: Will need to change if we support pushback from the sink. */
  10171. size_t n = upb_bytessink_putbuf(p->output_, p->subc_, buf, len, NULL);
  10172. UPB_ASSERT(n == len);
  10173. }
  10174. static void print_comma(upb_json_printer *p) {
  10175. if (!p->first_elem_[p->depth_]) {
  10176. print_data(p, ",", 1);
  10177. }
  10178. p->first_elem_[p->depth_] = false;
  10179. }
  10180. /* Helpers that print properly formatted elements to the JSON output stream. */
  10181. /* Used for escaping control chars in strings. */
  10182. static const char kControlCharLimit = 0x20;
  10183. UPB_INLINE bool is_json_escaped(char c) {
  10184. /* See RFC 4627. */
  10185. unsigned char uc = (unsigned char)c;
  10186. return uc < kControlCharLimit || uc == '"' || uc == '\\';
  10187. }
  10188. UPB_INLINE const char* json_nice_escape(char c) {
  10189. switch (c) {
  10190. case '"': return "\\\"";
  10191. case '\\': return "\\\\";
  10192. case '\b': return "\\b";
  10193. case '\f': return "\\f";
  10194. case '\n': return "\\n";
  10195. case '\r': return "\\r";
  10196. case '\t': return "\\t";
  10197. default: return NULL;
  10198. }
  10199. }
  10200. /* Write a properly escaped string chunk. The surrounding quotes are *not*
  10201. * printed; this is so that the caller has the option of emitting the string
  10202. * content in chunks. */
  10203. static void putstring(upb_json_printer *p, const char *buf, unsigned int len) {
  10204. const char* unescaped_run = NULL;
  10205. unsigned int i;
  10206. for (i = 0; i < len; i++) {
  10207. char c = buf[i];
  10208. /* Handle escaping. */
  10209. if (is_json_escaped(c)) {
  10210. /* Use a "nice" escape, like \n, if one exists for this character. */
  10211. const char* escape = json_nice_escape(c);
  10212. /* If we don't have a specific 'nice' escape code, use a \uXXXX-style
  10213. * escape. */
  10214. char escape_buf[8];
  10215. if (!escape) {
  10216. unsigned char byte = (unsigned char)c;
  10217. _upb_snprintf(escape_buf, sizeof(escape_buf), "\\u%04x", (int)byte);
  10218. escape = escape_buf;
  10219. }
  10220. /* N.B. that we assume that the input encoding is equal to the output
  10221. * encoding (both UTF-8 for now), so for chars >= 0x20 and != \, ", we
  10222. * can simply pass the bytes through. */
  10223. /* If there's a current run of unescaped chars, print that run first. */
  10224. if (unescaped_run) {
  10225. print_data(p, unescaped_run, &buf[i] - unescaped_run);
  10226. unescaped_run = NULL;
  10227. }
  10228. /* Then print the escape code. */
  10229. print_data(p, escape, strlen(escape));
  10230. } else {
  10231. /* Add to the current unescaped run of characters. */
  10232. if (unescaped_run == NULL) {
  10233. unescaped_run = &buf[i];
  10234. }
  10235. }
  10236. }
  10237. /* If the string ended in a run of unescaped characters, print that last run. */
  10238. if (unescaped_run) {
  10239. print_data(p, unescaped_run, &buf[len] - unescaped_run);
  10240. }
  10241. }
  10242. #define CHKLENGTH(x) if (!(x)) return -1;
  10243. /* Helpers that format floating point values according to our custom formats.
  10244. * Right now we use %.8g and %.17g for float/double, respectively, to match
  10245. * proto2::util::JsonFormat's defaults. May want to change this later. */
  10246. const char neginf[] = "\"-Infinity\"";
  10247. const char inf[] = "\"Infinity\"";
  10248. static size_t fmt_double(double val, char* buf, size_t length) {
  10249. if (val == UPB_INFINITY) {
  10250. CHKLENGTH(length >= strlen(inf));
  10251. strcpy(buf, inf);
  10252. return strlen(inf);
  10253. } else if (val == -UPB_INFINITY) {
  10254. CHKLENGTH(length >= strlen(neginf));
  10255. strcpy(buf, neginf);
  10256. return strlen(neginf);
  10257. } else {
  10258. size_t n = _upb_snprintf(buf, length, "%.17g", val);
  10259. CHKLENGTH(n > 0 && n < length);
  10260. return n;
  10261. }
  10262. }
  10263. static size_t fmt_float(float val, char* buf, size_t length) {
  10264. size_t n = _upb_snprintf(buf, length, "%.8g", val);
  10265. CHKLENGTH(n > 0 && n < length);
  10266. return n;
  10267. }
  10268. static size_t fmt_bool(bool val, char* buf, size_t length) {
  10269. size_t n = _upb_snprintf(buf, length, "%s", (val ? "true" : "false"));
  10270. CHKLENGTH(n > 0 && n < length);
  10271. return n;
  10272. }
  10273. static size_t fmt_int64_as_number(long long val, char* buf, size_t length) {
  10274. size_t n = _upb_snprintf(buf, length, "%lld", val);
  10275. CHKLENGTH(n > 0 && n < length);
  10276. return n;
  10277. }
  10278. static size_t fmt_uint64_as_number(
  10279. unsigned long long val, char* buf, size_t length) {
  10280. size_t n = _upb_snprintf(buf, length, "%llu", val);
  10281. CHKLENGTH(n > 0 && n < length);
  10282. return n;
  10283. }
  10284. static size_t fmt_int64_as_string(long long val, char* buf, size_t length) {
  10285. size_t n = _upb_snprintf(buf, length, "\"%lld\"", val);
  10286. CHKLENGTH(n > 0 && n < length);
  10287. return n;
  10288. }
  10289. static size_t fmt_uint64_as_string(
  10290. unsigned long long val, char* buf, size_t length) {
  10291. size_t n = _upb_snprintf(buf, length, "\"%llu\"", val);
  10292. CHKLENGTH(n > 0 && n < length);
  10293. return n;
  10294. }
  10295. /* Print a map key given a field name. Called by scalar field handlers and by
  10296. * startseq for repeated fields. */
  10297. static bool putkey(void *closure, const void *handler_data) {
  10298. upb_json_printer *p = closure;
  10299. const strpc *key = handler_data;
  10300. print_comma(p);
  10301. print_data(p, "\"", 1);
  10302. putstring(p, key->ptr, key->len);
  10303. print_data(p, "\":", 2);
  10304. return true;
  10305. }
  10306. #define CHKFMT(val) if ((val) == (size_t)-1) return false;
  10307. #define CHK(val) if (!(val)) return false;
  10308. #define TYPE_HANDLERS(type, fmt_func) \
  10309. static bool put##type(void *closure, const void *handler_data, type val) { \
  10310. upb_json_printer *p = closure; \
  10311. char data[64]; \
  10312. size_t length = fmt_func(val, data, sizeof(data)); \
  10313. UPB_UNUSED(handler_data); \
  10314. CHKFMT(length); \
  10315. print_data(p, data, length); \
  10316. return true; \
  10317. } \
  10318. static bool scalar_##type(void *closure, const void *handler_data, \
  10319. type val) { \
  10320. CHK(putkey(closure, handler_data)); \
  10321. CHK(put##type(closure, handler_data, val)); \
  10322. return true; \
  10323. } \
  10324. static bool repeated_##type(void *closure, const void *handler_data, \
  10325. type val) { \
  10326. upb_json_printer *p = closure; \
  10327. print_comma(p); \
  10328. CHK(put##type(closure, handler_data, val)); \
  10329. return true; \
  10330. }
  10331. #define TYPE_HANDLERS_MAPKEY(type, fmt_func) \
  10332. static bool putmapkey_##type(void *closure, const void *handler_data, \
  10333. type val) { \
  10334. upb_json_printer *p = closure; \
  10335. char data[64]; \
  10336. size_t length = fmt_func(val, data, sizeof(data)); \
  10337. UPB_UNUSED(handler_data); \
  10338. print_data(p, "\"", 1); \
  10339. print_data(p, data, length); \
  10340. print_data(p, "\":", 2); \
  10341. return true; \
  10342. }
  10343. TYPE_HANDLERS(double, fmt_double)
  10344. TYPE_HANDLERS(float, fmt_float)
  10345. TYPE_HANDLERS(bool, fmt_bool)
  10346. TYPE_HANDLERS(int32_t, fmt_int64_as_number)
  10347. TYPE_HANDLERS(uint32_t, fmt_int64_as_number)
  10348. TYPE_HANDLERS(int64_t, fmt_int64_as_string)
  10349. TYPE_HANDLERS(uint64_t, fmt_uint64_as_string)
  10350. /* double and float are not allowed to be map keys. */
  10351. TYPE_HANDLERS_MAPKEY(bool, fmt_bool)
  10352. TYPE_HANDLERS_MAPKEY(int32_t, fmt_int64_as_number)
  10353. TYPE_HANDLERS_MAPKEY(uint32_t, fmt_int64_as_number)
  10354. TYPE_HANDLERS_MAPKEY(int64_t, fmt_int64_as_number)
  10355. TYPE_HANDLERS_MAPKEY(uint64_t, fmt_uint64_as_number)
  10356. #undef TYPE_HANDLERS
  10357. #undef TYPE_HANDLERS_MAPKEY
  10358. typedef struct {
  10359. void *keyname;
  10360. const upb_enumdef *enumdef;
  10361. } EnumHandlerData;
  10362. static bool scalar_enum(void *closure, const void *handler_data,
  10363. int32_t val) {
  10364. const EnumHandlerData *hd = handler_data;
  10365. upb_json_printer *p = closure;
  10366. const char *symbolic_name;
  10367. CHK(putkey(closure, hd->keyname));
  10368. symbolic_name = upb_enumdef_iton(hd->enumdef, val);
  10369. if (symbolic_name) {
  10370. print_data(p, "\"", 1);
  10371. putstring(p, symbolic_name, strlen(symbolic_name));
  10372. print_data(p, "\"", 1);
  10373. } else {
  10374. putint32_t(closure, NULL, val);
  10375. }
  10376. return true;
  10377. }
  10378. static void print_enum_symbolic_name(upb_json_printer *p,
  10379. const upb_enumdef *def,
  10380. int32_t val) {
  10381. const char *symbolic_name = upb_enumdef_iton(def, val);
  10382. if (symbolic_name) {
  10383. print_data(p, "\"", 1);
  10384. putstring(p, symbolic_name, strlen(symbolic_name));
  10385. print_data(p, "\"", 1);
  10386. } else {
  10387. putint32_t(p, NULL, val);
  10388. }
  10389. }
  10390. static bool repeated_enum(void *closure, const void *handler_data,
  10391. int32_t val) {
  10392. const EnumHandlerData *hd = handler_data;
  10393. upb_json_printer *p = closure;
  10394. print_comma(p);
  10395. print_enum_symbolic_name(p, hd->enumdef, val);
  10396. return true;
  10397. }
  10398. static bool mapvalue_enum(void *closure, const void *handler_data,
  10399. int32_t val) {
  10400. const EnumHandlerData *hd = handler_data;
  10401. upb_json_printer *p = closure;
  10402. print_enum_symbolic_name(p, hd->enumdef, val);
  10403. return true;
  10404. }
  10405. static void *scalar_startsubmsg(void *closure, const void *handler_data) {
  10406. return putkey(closure, handler_data) ? closure : UPB_BREAK;
  10407. }
  10408. static void *repeated_startsubmsg(void *closure, const void *handler_data) {
  10409. upb_json_printer *p = closure;
  10410. UPB_UNUSED(handler_data);
  10411. print_comma(p);
  10412. return closure;
  10413. }
  10414. static void start_frame(upb_json_printer *p) {
  10415. p->depth_++;
  10416. p->first_elem_[p->depth_] = true;
  10417. print_data(p, "{", 1);
  10418. }
  10419. static void end_frame(upb_json_printer *p) {
  10420. print_data(p, "}", 1);
  10421. p->depth_--;
  10422. }
  10423. static bool printer_startmsg(void *closure, const void *handler_data) {
  10424. upb_json_printer *p = closure;
  10425. UPB_UNUSED(handler_data);
  10426. if (p->depth_ == 0) {
  10427. upb_bytessink_start(p->output_, 0, &p->subc_);
  10428. }
  10429. start_frame(p);
  10430. return true;
  10431. }
  10432. static bool printer_endmsg(void *closure, const void *handler_data, upb_status *s) {
  10433. upb_json_printer *p = closure;
  10434. UPB_UNUSED(handler_data);
  10435. UPB_UNUSED(s);
  10436. end_frame(p);
  10437. if (p->depth_ == 0) {
  10438. upb_bytessink_end(p->output_);
  10439. }
  10440. return true;
  10441. }
  10442. static void *startseq(void *closure, const void *handler_data) {
  10443. upb_json_printer *p = closure;
  10444. CHK(putkey(closure, handler_data));
  10445. p->depth_++;
  10446. p->first_elem_[p->depth_] = true;
  10447. print_data(p, "[", 1);
  10448. return closure;
  10449. }
  10450. static bool endseq(void *closure, const void *handler_data) {
  10451. upb_json_printer *p = closure;
  10452. UPB_UNUSED(handler_data);
  10453. print_data(p, "]", 1);
  10454. p->depth_--;
  10455. return true;
  10456. }
  10457. static void *startmap(void *closure, const void *handler_data) {
  10458. upb_json_printer *p = closure;
  10459. CHK(putkey(closure, handler_data));
  10460. p->depth_++;
  10461. p->first_elem_[p->depth_] = true;
  10462. print_data(p, "{", 1);
  10463. return closure;
  10464. }
  10465. static bool endmap(void *closure, const void *handler_data) {
  10466. upb_json_printer *p = closure;
  10467. UPB_UNUSED(handler_data);
  10468. print_data(p, "}", 1);
  10469. p->depth_--;
  10470. return true;
  10471. }
  10472. static size_t putstr(void *closure, const void *handler_data, const char *str,
  10473. size_t len, const upb_bufhandle *handle) {
  10474. upb_json_printer *p = closure;
  10475. UPB_UNUSED(handler_data);
  10476. UPB_UNUSED(handle);
  10477. putstring(p, str, len);
  10478. return len;
  10479. }
  10480. /* This has to Base64 encode the bytes, because JSON has no "bytes" type. */
  10481. static size_t putbytes(void *closure, const void *handler_data, const char *str,
  10482. size_t len, const upb_bufhandle *handle) {
  10483. upb_json_printer *p = closure;
  10484. /* This is the regular base64, not the "web-safe" version. */
  10485. static const char base64[] =
  10486. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  10487. /* Base64-encode. */
  10488. char data[16000];
  10489. const char *limit = data + sizeof(data);
  10490. const unsigned char *from = (const unsigned char*)str;
  10491. char *to = data;
  10492. size_t remaining = len;
  10493. size_t bytes;
  10494. UPB_UNUSED(handler_data);
  10495. UPB_UNUSED(handle);
  10496. print_data(p, "\"", 1);
  10497. while (remaining > 2) {
  10498. if (limit - to < 4) {
  10499. bytes = to - data;
  10500. putstring(p, data, bytes);
  10501. to = data;
  10502. }
  10503. to[0] = base64[from[0] >> 2];
  10504. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  10505. to[2] = base64[((from[1] & 0xf) << 2) | (from[2] >> 6)];
  10506. to[3] = base64[from[2] & 0x3f];
  10507. remaining -= 3;
  10508. to += 4;
  10509. from += 3;
  10510. }
  10511. switch (remaining) {
  10512. case 2:
  10513. to[0] = base64[from[0] >> 2];
  10514. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  10515. to[2] = base64[(from[1] & 0xf) << 2];
  10516. to[3] = '=';
  10517. to += 4;
  10518. from += 2;
  10519. break;
  10520. case 1:
  10521. to[0] = base64[from[0] >> 2];
  10522. to[1] = base64[((from[0] & 0x3) << 4)];
  10523. to[2] = '=';
  10524. to[3] = '=';
  10525. to += 4;
  10526. from += 1;
  10527. break;
  10528. }
  10529. bytes = to - data;
  10530. putstring(p, data, bytes);
  10531. print_data(p, "\"", 1);
  10532. return len;
  10533. }
  10534. static void *scalar_startstr(void *closure, const void *handler_data,
  10535. size_t size_hint) {
  10536. upb_json_printer *p = closure;
  10537. UPB_UNUSED(handler_data);
  10538. UPB_UNUSED(size_hint);
  10539. CHK(putkey(closure, handler_data));
  10540. print_data(p, "\"", 1);
  10541. return p;
  10542. }
  10543. static size_t scalar_str(void *closure, const void *handler_data,
  10544. const char *str, size_t len,
  10545. const upb_bufhandle *handle) {
  10546. CHK(putstr(closure, handler_data, str, len, handle));
  10547. return len;
  10548. }
  10549. static bool scalar_endstr(void *closure, const void *handler_data) {
  10550. upb_json_printer *p = closure;
  10551. UPB_UNUSED(handler_data);
  10552. print_data(p, "\"", 1);
  10553. return true;
  10554. }
  10555. static void *repeated_startstr(void *closure, const void *handler_data,
  10556. size_t size_hint) {
  10557. upb_json_printer *p = closure;
  10558. UPB_UNUSED(handler_data);
  10559. UPB_UNUSED(size_hint);
  10560. print_comma(p);
  10561. print_data(p, "\"", 1);
  10562. return p;
  10563. }
  10564. static size_t repeated_str(void *closure, const void *handler_data,
  10565. const char *str, size_t len,
  10566. const upb_bufhandle *handle) {
  10567. CHK(putstr(closure, handler_data, str, len, handle));
  10568. return len;
  10569. }
  10570. static bool repeated_endstr(void *closure, const void *handler_data) {
  10571. upb_json_printer *p = closure;
  10572. UPB_UNUSED(handler_data);
  10573. print_data(p, "\"", 1);
  10574. return true;
  10575. }
  10576. static void *mapkeyval_startstr(void *closure, const void *handler_data,
  10577. size_t size_hint) {
  10578. upb_json_printer *p = closure;
  10579. UPB_UNUSED(handler_data);
  10580. UPB_UNUSED(size_hint);
  10581. print_data(p, "\"", 1);
  10582. return p;
  10583. }
  10584. static size_t mapkey_str(void *closure, const void *handler_data,
  10585. const char *str, size_t len,
  10586. const upb_bufhandle *handle) {
  10587. CHK(putstr(closure, handler_data, str, len, handle));
  10588. return len;
  10589. }
  10590. static bool mapkey_endstr(void *closure, const void *handler_data) {
  10591. upb_json_printer *p = closure;
  10592. UPB_UNUSED(handler_data);
  10593. print_data(p, "\":", 2);
  10594. return true;
  10595. }
  10596. static bool mapvalue_endstr(void *closure, const void *handler_data) {
  10597. upb_json_printer *p = closure;
  10598. UPB_UNUSED(handler_data);
  10599. print_data(p, "\"", 1);
  10600. return true;
  10601. }
  10602. static size_t scalar_bytes(void *closure, const void *handler_data,
  10603. const char *str, size_t len,
  10604. const upb_bufhandle *handle) {
  10605. CHK(putkey(closure, handler_data));
  10606. CHK(putbytes(closure, handler_data, str, len, handle));
  10607. return len;
  10608. }
  10609. static size_t repeated_bytes(void *closure, const void *handler_data,
  10610. const char *str, size_t len,
  10611. const upb_bufhandle *handle) {
  10612. upb_json_printer *p = closure;
  10613. print_comma(p);
  10614. CHK(putbytes(closure, handler_data, str, len, handle));
  10615. return len;
  10616. }
  10617. static size_t mapkey_bytes(void *closure, const void *handler_data,
  10618. const char *str, size_t len,
  10619. const upb_bufhandle *handle) {
  10620. upb_json_printer *p = closure;
  10621. CHK(putbytes(closure, handler_data, str, len, handle));
  10622. print_data(p, ":", 1);
  10623. return len;
  10624. }
  10625. static void set_enum_hd(upb_handlers *h,
  10626. const upb_fielddef *f,
  10627. bool preserve_fieldnames,
  10628. upb_handlerattr *attr) {
  10629. EnumHandlerData *hd = upb_gmalloc(sizeof(EnumHandlerData));
  10630. hd->enumdef = upb_fielddef_enumsubdef(f);
  10631. hd->keyname = newstrpc(h, f, preserve_fieldnames);
  10632. upb_handlers_addcleanup(h, hd, upb_gfree);
  10633. attr->handler_data = hd;
  10634. }
  10635. /* Set up handlers for a mapentry submessage (i.e., an individual key/value pair
  10636. * in a map).
  10637. *
  10638. * TODO: Handle missing key, missing value, out-of-order key/value, or repeated
  10639. * key or value cases properly. The right way to do this is to allocate a
  10640. * temporary structure at the start of a mapentry submessage, store key and
  10641. * value data in it as key and value handlers are called, and then print the
  10642. * key/value pair once at the end of the submessage. If we don't do this, we
  10643. * should at least detect the case and throw an error. However, so far all of
  10644. * our sources that emit mapentry messages do so canonically (with one key
  10645. * field, and then one value field), so this is not a pressing concern at the
  10646. * moment. */
  10647. void printer_sethandlers_mapentry(const void *closure, bool preserve_fieldnames,
  10648. upb_handlers *h) {
  10649. const upb_msgdef *md = upb_handlers_msgdef(h);
  10650. /* A mapentry message is printed simply as '"key": value'. Rather than
  10651. * special-case key and value for every type below, we just handle both
  10652. * fields explicitly here. */
  10653. const upb_fielddef* key_field = upb_msgdef_itof(md, UPB_MAPENTRY_KEY);
  10654. const upb_fielddef* value_field = upb_msgdef_itof(md, UPB_MAPENTRY_VALUE);
  10655. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  10656. UPB_UNUSED(closure);
  10657. switch (upb_fielddef_type(key_field)) {
  10658. case UPB_TYPE_INT32:
  10659. upb_handlers_setint32(h, key_field, putmapkey_int32_t, &empty_attr);
  10660. break;
  10661. case UPB_TYPE_INT64:
  10662. upb_handlers_setint64(h, key_field, putmapkey_int64_t, &empty_attr);
  10663. break;
  10664. case UPB_TYPE_UINT32:
  10665. upb_handlers_setuint32(h, key_field, putmapkey_uint32_t, &empty_attr);
  10666. break;
  10667. case UPB_TYPE_UINT64:
  10668. upb_handlers_setuint64(h, key_field, putmapkey_uint64_t, &empty_attr);
  10669. break;
  10670. case UPB_TYPE_BOOL:
  10671. upb_handlers_setbool(h, key_field, putmapkey_bool, &empty_attr);
  10672. break;
  10673. case UPB_TYPE_STRING:
  10674. upb_handlers_setstartstr(h, key_field, mapkeyval_startstr, &empty_attr);
  10675. upb_handlers_setstring(h, key_field, mapkey_str, &empty_attr);
  10676. upb_handlers_setendstr(h, key_field, mapkey_endstr, &empty_attr);
  10677. break;
  10678. case UPB_TYPE_BYTES:
  10679. upb_handlers_setstring(h, key_field, mapkey_bytes, &empty_attr);
  10680. break;
  10681. default:
  10682. UPB_ASSERT(false);
  10683. break;
  10684. }
  10685. switch (upb_fielddef_type(value_field)) {
  10686. case UPB_TYPE_INT32:
  10687. upb_handlers_setint32(h, value_field, putint32_t, &empty_attr);
  10688. break;
  10689. case UPB_TYPE_INT64:
  10690. upb_handlers_setint64(h, value_field, putint64_t, &empty_attr);
  10691. break;
  10692. case UPB_TYPE_UINT32:
  10693. upb_handlers_setuint32(h, value_field, putuint32_t, &empty_attr);
  10694. break;
  10695. case UPB_TYPE_UINT64:
  10696. upb_handlers_setuint64(h, value_field, putuint64_t, &empty_attr);
  10697. break;
  10698. case UPB_TYPE_BOOL:
  10699. upb_handlers_setbool(h, value_field, putbool, &empty_attr);
  10700. break;
  10701. case UPB_TYPE_FLOAT:
  10702. upb_handlers_setfloat(h, value_field, putfloat, &empty_attr);
  10703. break;
  10704. case UPB_TYPE_DOUBLE:
  10705. upb_handlers_setdouble(h, value_field, putdouble, &empty_attr);
  10706. break;
  10707. case UPB_TYPE_STRING:
  10708. upb_handlers_setstartstr(h, value_field, mapkeyval_startstr, &empty_attr);
  10709. upb_handlers_setstring(h, value_field, putstr, &empty_attr);
  10710. upb_handlers_setendstr(h, value_field, mapvalue_endstr, &empty_attr);
  10711. break;
  10712. case UPB_TYPE_BYTES:
  10713. upb_handlers_setstring(h, value_field, putbytes, &empty_attr);
  10714. break;
  10715. case UPB_TYPE_ENUM: {
  10716. upb_handlerattr enum_attr = UPB_HANDLERATTR_INIT;
  10717. set_enum_hd(h, value_field, preserve_fieldnames, &enum_attr);
  10718. upb_handlers_setint32(h, value_field, mapvalue_enum, &enum_attr);
  10719. break;
  10720. }
  10721. case UPB_TYPE_MESSAGE:
  10722. /* No handler necessary -- the submsg handlers will print the message
  10723. * as appropriate. */
  10724. break;
  10725. }
  10726. }
  10727. static bool putseconds(void *closure, const void *handler_data,
  10728. int64_t seconds) {
  10729. upb_json_printer *p = closure;
  10730. p->seconds = seconds;
  10731. UPB_UNUSED(handler_data);
  10732. return true;
  10733. }
  10734. static bool putnanos(void *closure, const void *handler_data,
  10735. int32_t nanos) {
  10736. upb_json_printer *p = closure;
  10737. p->nanos = nanos;
  10738. UPB_UNUSED(handler_data);
  10739. return true;
  10740. }
  10741. static void *scalar_startstr_nokey(void *closure, const void *handler_data,
  10742. size_t size_hint) {
  10743. upb_json_printer *p = closure;
  10744. UPB_UNUSED(handler_data);
  10745. UPB_UNUSED(size_hint);
  10746. print_data(p, "\"", 1);
  10747. return p;
  10748. }
  10749. static size_t putstr_nokey(void *closure, const void *handler_data,
  10750. const char *str, size_t len,
  10751. const upb_bufhandle *handle) {
  10752. upb_json_printer *p = closure;
  10753. UPB_UNUSED(handler_data);
  10754. UPB_UNUSED(handle);
  10755. print_data(p, "\"", 1);
  10756. putstring(p, str, len);
  10757. print_data(p, "\"", 1);
  10758. return len + 2;
  10759. }
  10760. static void *startseq_nokey(void *closure, const void *handler_data) {
  10761. upb_json_printer *p = closure;
  10762. UPB_UNUSED(handler_data);
  10763. p->depth_++;
  10764. p->first_elem_[p->depth_] = true;
  10765. print_data(p, "[", 1);
  10766. return closure;
  10767. }
  10768. static void *startseq_fieldmask(void *closure, const void *handler_data) {
  10769. upb_json_printer *p = closure;
  10770. UPB_UNUSED(handler_data);
  10771. p->depth_++;
  10772. p->first_elem_[p->depth_] = true;
  10773. return closure;
  10774. }
  10775. static bool endseq_fieldmask(void *closure, const void *handler_data) {
  10776. upb_json_printer *p = closure;
  10777. UPB_UNUSED(handler_data);
  10778. p->depth_--;
  10779. return true;
  10780. }
  10781. static void *repeated_startstr_fieldmask(
  10782. void *closure, const void *handler_data,
  10783. size_t size_hint) {
  10784. upb_json_printer *p = closure;
  10785. UPB_UNUSED(handler_data);
  10786. UPB_UNUSED(size_hint);
  10787. print_comma(p);
  10788. return p;
  10789. }
  10790. static size_t repeated_str_fieldmask(
  10791. void *closure, const void *handler_data,
  10792. const char *str, size_t len,
  10793. const upb_bufhandle *handle) {
  10794. const char* limit = str + len;
  10795. bool upper = false;
  10796. size_t result_len = 0;
  10797. for (; str < limit; str++) {
  10798. if (*str == '_') {
  10799. upper = true;
  10800. continue;
  10801. }
  10802. if (upper && *str >= 'a' && *str <= 'z') {
  10803. char upper_char = toupper(*str);
  10804. CHK(putstr(closure, handler_data, &upper_char, 1, handle));
  10805. } else {
  10806. CHK(putstr(closure, handler_data, str, 1, handle));
  10807. }
  10808. upper = false;
  10809. result_len++;
  10810. }
  10811. return result_len;
  10812. }
  10813. static void *startmap_nokey(void *closure, const void *handler_data) {
  10814. upb_json_printer *p = closure;
  10815. UPB_UNUSED(handler_data);
  10816. p->depth_++;
  10817. p->first_elem_[p->depth_] = true;
  10818. print_data(p, "{", 1);
  10819. return closure;
  10820. }
  10821. static bool putnull(void *closure, const void *handler_data,
  10822. int32_t null) {
  10823. upb_json_printer *p = closure;
  10824. print_data(p, "null", 4);
  10825. UPB_UNUSED(handler_data);
  10826. UPB_UNUSED(null);
  10827. return true;
  10828. }
  10829. static bool printer_startdurationmsg(void *closure, const void *handler_data) {
  10830. upb_json_printer *p = closure;
  10831. UPB_UNUSED(handler_data);
  10832. if (p->depth_ == 0) {
  10833. upb_bytessink_start(p->output_, 0, &p->subc_);
  10834. }
  10835. return true;
  10836. }
  10837. #define UPB_DURATION_MAX_JSON_LEN 23
  10838. #define UPB_DURATION_MAX_NANO_LEN 9
  10839. static bool printer_enddurationmsg(void *closure, const void *handler_data,
  10840. upb_status *s) {
  10841. upb_json_printer *p = closure;
  10842. char buffer[UPB_DURATION_MAX_JSON_LEN];
  10843. size_t base_len;
  10844. size_t curr;
  10845. size_t i;
  10846. memset(buffer, 0, UPB_DURATION_MAX_JSON_LEN);
  10847. if (p->seconds < -315576000000) {
  10848. upb_status_seterrf(s, "error parsing duration: "
  10849. "minimum acceptable value is "
  10850. "-315576000000");
  10851. return false;
  10852. }
  10853. if (p->seconds > 315576000000) {
  10854. upb_status_seterrf(s, "error serializing duration: "
  10855. "maximum acceptable value is "
  10856. "315576000000");
  10857. return false;
  10858. }
  10859. _upb_snprintf(buffer, sizeof(buffer), "%ld", (long)p->seconds);
  10860. base_len = strlen(buffer);
  10861. if (p->nanos != 0) {
  10862. char nanos_buffer[UPB_DURATION_MAX_NANO_LEN + 3];
  10863. _upb_snprintf(nanos_buffer, sizeof(nanos_buffer), "%.9f",
  10864. p->nanos / 1000000000.0);
  10865. /* Remove trailing 0. */
  10866. for (i = UPB_DURATION_MAX_NANO_LEN + 2;
  10867. nanos_buffer[i] == '0'; i--) {
  10868. nanos_buffer[i] = 0;
  10869. }
  10870. strcpy(buffer + base_len, nanos_buffer + 1);
  10871. }
  10872. curr = strlen(buffer);
  10873. strcpy(buffer + curr, "s");
  10874. p->seconds = 0;
  10875. p->nanos = 0;
  10876. print_data(p, "\"", 1);
  10877. print_data(p, buffer, strlen(buffer));
  10878. print_data(p, "\"", 1);
  10879. if (p->depth_ == 0) {
  10880. upb_bytessink_end(p->output_);
  10881. }
  10882. UPB_UNUSED(handler_data);
  10883. return true;
  10884. }
  10885. static bool printer_starttimestampmsg(void *closure, const void *handler_data) {
  10886. upb_json_printer *p = closure;
  10887. UPB_UNUSED(handler_data);
  10888. if (p->depth_ == 0) {
  10889. upb_bytessink_start(p->output_, 0, &p->subc_);
  10890. }
  10891. return true;
  10892. }
  10893. #define UPB_TIMESTAMP_MAX_JSON_LEN 31
  10894. #define UPB_TIMESTAMP_BEFORE_NANO_LEN 19
  10895. #define UPB_TIMESTAMP_MAX_NANO_LEN 9
  10896. static bool printer_endtimestampmsg(void *closure, const void *handler_data,
  10897. upb_status *s) {
  10898. upb_json_printer *p = closure;
  10899. char buffer[UPB_TIMESTAMP_MAX_JSON_LEN];
  10900. time_t time = p->seconds;
  10901. size_t curr;
  10902. size_t i;
  10903. size_t year_length =
  10904. strftime(buffer, UPB_TIMESTAMP_MAX_JSON_LEN, "%Y", gmtime(&time));
  10905. if (p->seconds < -62135596800) {
  10906. upb_status_seterrf(s, "error parsing timestamp: "
  10907. "minimum acceptable value is "
  10908. "0001-01-01T00:00:00Z");
  10909. return false;
  10910. }
  10911. if (p->seconds > 253402300799) {
  10912. upb_status_seterrf(s, "error parsing timestamp: "
  10913. "maximum acceptable value is "
  10914. "9999-12-31T23:59:59Z");
  10915. return false;
  10916. }
  10917. /* strftime doesn't guarantee 4 digits for year. Prepend 0 by ourselves. */
  10918. for (i = 0; i < 4 - year_length; i++) {
  10919. buffer[i] = '0';
  10920. }
  10921. strftime(buffer + (4 - year_length), UPB_TIMESTAMP_MAX_JSON_LEN,
  10922. "%Y-%m-%dT%H:%M:%S", gmtime(&time));
  10923. if (p->nanos != 0) {
  10924. char nanos_buffer[UPB_TIMESTAMP_MAX_NANO_LEN + 3];
  10925. _upb_snprintf(nanos_buffer, sizeof(nanos_buffer), "%.9f",
  10926. p->nanos / 1000000000.0);
  10927. /* Remove trailing 0. */
  10928. for (i = UPB_TIMESTAMP_MAX_NANO_LEN + 2;
  10929. nanos_buffer[i] == '0'; i--) {
  10930. nanos_buffer[i] = 0;
  10931. }
  10932. strcpy(buffer + UPB_TIMESTAMP_BEFORE_NANO_LEN, nanos_buffer + 1);
  10933. }
  10934. curr = strlen(buffer);
  10935. strcpy(buffer + curr, "Z");
  10936. p->seconds = 0;
  10937. p->nanos = 0;
  10938. print_data(p, "\"", 1);
  10939. print_data(p, buffer, strlen(buffer));
  10940. print_data(p, "\"", 1);
  10941. if (p->depth_ == 0) {
  10942. upb_bytessink_end(p->output_);
  10943. }
  10944. UPB_UNUSED(handler_data);
  10945. UPB_UNUSED(s);
  10946. return true;
  10947. }
  10948. static bool printer_startmsg_noframe(void *closure, const void *handler_data) {
  10949. upb_json_printer *p = closure;
  10950. UPB_UNUSED(handler_data);
  10951. if (p->depth_ == 0) {
  10952. upb_bytessink_start(p->output_, 0, &p->subc_);
  10953. }
  10954. return true;
  10955. }
  10956. static bool printer_endmsg_noframe(
  10957. void *closure, const void *handler_data, upb_status *s) {
  10958. upb_json_printer *p = closure;
  10959. UPB_UNUSED(handler_data);
  10960. UPB_UNUSED(s);
  10961. if (p->depth_ == 0) {
  10962. upb_bytessink_end(p->output_);
  10963. }
  10964. return true;
  10965. }
  10966. static bool printer_startmsg_fieldmask(
  10967. void *closure, const void *handler_data) {
  10968. upb_json_printer *p = closure;
  10969. UPB_UNUSED(handler_data);
  10970. if (p->depth_ == 0) {
  10971. upb_bytessink_start(p->output_, 0, &p->subc_);
  10972. }
  10973. print_data(p, "\"", 1);
  10974. return true;
  10975. }
  10976. static bool printer_endmsg_fieldmask(
  10977. void *closure, const void *handler_data, upb_status *s) {
  10978. upb_json_printer *p = closure;
  10979. UPB_UNUSED(handler_data);
  10980. UPB_UNUSED(s);
  10981. print_data(p, "\"", 1);
  10982. if (p->depth_ == 0) {
  10983. upb_bytessink_end(p->output_);
  10984. }
  10985. return true;
  10986. }
  10987. static void *scalar_startstr_onlykey(
  10988. void *closure, const void *handler_data, size_t size_hint) {
  10989. upb_json_printer *p = closure;
  10990. UPB_UNUSED(size_hint);
  10991. CHK(putkey(closure, handler_data));
  10992. return p;
  10993. }
  10994. /* Set up handlers for an Any submessage. */
  10995. void printer_sethandlers_any(const void *closure, upb_handlers *h) {
  10996. const upb_msgdef *md = upb_handlers_msgdef(h);
  10997. const upb_fielddef* type_field = upb_msgdef_itof(md, UPB_ANY_TYPE);
  10998. const upb_fielddef* value_field = upb_msgdef_itof(md, UPB_ANY_VALUE);
  10999. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11000. /* type_url's json name is "@type" */
  11001. upb_handlerattr type_name_attr = UPB_HANDLERATTR_INIT;
  11002. upb_handlerattr value_name_attr = UPB_HANDLERATTR_INIT;
  11003. strpc *type_url_json_name = newstrpc_str(h, "@type");
  11004. strpc *value_json_name = newstrpc_str(h, "value");
  11005. type_name_attr.handler_data = type_url_json_name;
  11006. value_name_attr.handler_data = value_json_name;
  11007. /* Set up handlers. */
  11008. upb_handlers_setstartmsg(h, printer_startmsg, &empty_attr);
  11009. upb_handlers_setendmsg(h, printer_endmsg, &empty_attr);
  11010. upb_handlers_setstartstr(h, type_field, scalar_startstr, &type_name_attr);
  11011. upb_handlers_setstring(h, type_field, scalar_str, &empty_attr);
  11012. upb_handlers_setendstr(h, type_field, scalar_endstr, &empty_attr);
  11013. /* This is not the full and correct JSON encoding for the Any value field. It
  11014. * requires further processing by the wrapper code based on the type URL.
  11015. */
  11016. upb_handlers_setstartstr(h, value_field, scalar_startstr_onlykey,
  11017. &value_name_attr);
  11018. UPB_UNUSED(closure);
  11019. }
  11020. /* Set up handlers for a fieldmask submessage. */
  11021. void printer_sethandlers_fieldmask(const void *closure, upb_handlers *h) {
  11022. const upb_msgdef *md = upb_handlers_msgdef(h);
  11023. const upb_fielddef* f = upb_msgdef_itof(md, 1);
  11024. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11025. upb_handlers_setstartseq(h, f, startseq_fieldmask, &empty_attr);
  11026. upb_handlers_setendseq(h, f, endseq_fieldmask, &empty_attr);
  11027. upb_handlers_setstartmsg(h, printer_startmsg_fieldmask, &empty_attr);
  11028. upb_handlers_setendmsg(h, printer_endmsg_fieldmask, &empty_attr);
  11029. upb_handlers_setstartstr(h, f, repeated_startstr_fieldmask, &empty_attr);
  11030. upb_handlers_setstring(h, f, repeated_str_fieldmask, &empty_attr);
  11031. UPB_UNUSED(closure);
  11032. }
  11033. /* Set up handlers for a duration submessage. */
  11034. void printer_sethandlers_duration(const void *closure, upb_handlers *h) {
  11035. const upb_msgdef *md = upb_handlers_msgdef(h);
  11036. const upb_fielddef* seconds_field =
  11037. upb_msgdef_itof(md, UPB_DURATION_SECONDS);
  11038. const upb_fielddef* nanos_field =
  11039. upb_msgdef_itof(md, UPB_DURATION_NANOS);
  11040. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11041. upb_handlers_setstartmsg(h, printer_startdurationmsg, &empty_attr);
  11042. upb_handlers_setint64(h, seconds_field, putseconds, &empty_attr);
  11043. upb_handlers_setint32(h, nanos_field, putnanos, &empty_attr);
  11044. upb_handlers_setendmsg(h, printer_enddurationmsg, &empty_attr);
  11045. UPB_UNUSED(closure);
  11046. }
  11047. /* Set up handlers for a timestamp submessage. Instead of printing fields
  11048. * separately, the json representation of timestamp follows RFC 3339 */
  11049. void printer_sethandlers_timestamp(const void *closure, upb_handlers *h) {
  11050. const upb_msgdef *md = upb_handlers_msgdef(h);
  11051. const upb_fielddef* seconds_field =
  11052. upb_msgdef_itof(md, UPB_TIMESTAMP_SECONDS);
  11053. const upb_fielddef* nanos_field =
  11054. upb_msgdef_itof(md, UPB_TIMESTAMP_NANOS);
  11055. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11056. upb_handlers_setstartmsg(h, printer_starttimestampmsg, &empty_attr);
  11057. upb_handlers_setint64(h, seconds_field, putseconds, &empty_attr);
  11058. upb_handlers_setint32(h, nanos_field, putnanos, &empty_attr);
  11059. upb_handlers_setendmsg(h, printer_endtimestampmsg, &empty_attr);
  11060. UPB_UNUSED(closure);
  11061. }
  11062. void printer_sethandlers_value(const void *closure, upb_handlers *h) {
  11063. const upb_msgdef *md = upb_handlers_msgdef(h);
  11064. upb_msg_field_iter i;
  11065. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11066. upb_handlers_setstartmsg(h, printer_startmsg_noframe, &empty_attr);
  11067. upb_handlers_setendmsg(h, printer_endmsg_noframe, &empty_attr);
  11068. upb_msg_field_begin(&i, md);
  11069. for(; !upb_msg_field_done(&i); upb_msg_field_next(&i)) {
  11070. const upb_fielddef *f = upb_msg_iter_field(&i);
  11071. switch (upb_fielddef_type(f)) {
  11072. case UPB_TYPE_ENUM:
  11073. upb_handlers_setint32(h, f, putnull, &empty_attr);
  11074. break;
  11075. case UPB_TYPE_DOUBLE:
  11076. upb_handlers_setdouble(h, f, putdouble, &empty_attr);
  11077. break;
  11078. case UPB_TYPE_STRING:
  11079. upb_handlers_setstartstr(h, f, scalar_startstr_nokey, &empty_attr);
  11080. upb_handlers_setstring(h, f, scalar_str, &empty_attr);
  11081. upb_handlers_setendstr(h, f, scalar_endstr, &empty_attr);
  11082. break;
  11083. case UPB_TYPE_BOOL:
  11084. upb_handlers_setbool(h, f, putbool, &empty_attr);
  11085. break;
  11086. case UPB_TYPE_MESSAGE:
  11087. break;
  11088. default:
  11089. UPB_ASSERT(false);
  11090. break;
  11091. }
  11092. }
  11093. UPB_UNUSED(closure);
  11094. }
  11095. #define WRAPPER_SETHANDLERS(wrapper, type, putmethod) \
  11096. void printer_sethandlers_##wrapper(const void *closure, upb_handlers *h) { \
  11097. const upb_msgdef *md = upb_handlers_msgdef(h); \
  11098. const upb_fielddef* f = upb_msgdef_itof(md, 1); \
  11099. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT; \
  11100. upb_handlers_setstartmsg(h, printer_startmsg_noframe, &empty_attr); \
  11101. upb_handlers_setendmsg(h, printer_endmsg_noframe, &empty_attr); \
  11102. upb_handlers_set##type(h, f, putmethod, &empty_attr); \
  11103. UPB_UNUSED(closure); \
  11104. }
  11105. WRAPPER_SETHANDLERS(doublevalue, double, putdouble)
  11106. WRAPPER_SETHANDLERS(floatvalue, float, putfloat)
  11107. WRAPPER_SETHANDLERS(int64value, int64, putint64_t)
  11108. WRAPPER_SETHANDLERS(uint64value, uint64, putuint64_t)
  11109. WRAPPER_SETHANDLERS(int32value, int32, putint32_t)
  11110. WRAPPER_SETHANDLERS(uint32value, uint32, putuint32_t)
  11111. WRAPPER_SETHANDLERS(boolvalue, bool, putbool)
  11112. WRAPPER_SETHANDLERS(stringvalue, string, putstr_nokey)
  11113. WRAPPER_SETHANDLERS(bytesvalue, string, putbytes)
  11114. #undef WRAPPER_SETHANDLERS
  11115. void printer_sethandlers_listvalue(const void *closure, upb_handlers *h) {
  11116. const upb_msgdef *md = upb_handlers_msgdef(h);
  11117. const upb_fielddef* f = upb_msgdef_itof(md, 1);
  11118. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11119. upb_handlers_setstartseq(h, f, startseq_nokey, &empty_attr);
  11120. upb_handlers_setendseq(h, f, endseq, &empty_attr);
  11121. upb_handlers_setstartmsg(h, printer_startmsg_noframe, &empty_attr);
  11122. upb_handlers_setendmsg(h, printer_endmsg_noframe, &empty_attr);
  11123. upb_handlers_setstartsubmsg(h, f, repeated_startsubmsg, &empty_attr);
  11124. UPB_UNUSED(closure);
  11125. }
  11126. void printer_sethandlers_structvalue(const void *closure, upb_handlers *h) {
  11127. const upb_msgdef *md = upb_handlers_msgdef(h);
  11128. const upb_fielddef* f = upb_msgdef_itof(md, 1);
  11129. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11130. upb_handlers_setstartseq(h, f, startmap_nokey, &empty_attr);
  11131. upb_handlers_setendseq(h, f, endmap, &empty_attr);
  11132. upb_handlers_setstartmsg(h, printer_startmsg_noframe, &empty_attr);
  11133. upb_handlers_setendmsg(h, printer_endmsg_noframe, &empty_attr);
  11134. upb_handlers_setstartsubmsg(h, f, repeated_startsubmsg, &empty_attr);
  11135. UPB_UNUSED(closure);
  11136. }
  11137. void printer_sethandlers(const void *closure, upb_handlers *h) {
  11138. const upb_msgdef *md = upb_handlers_msgdef(h);
  11139. bool is_mapentry = upb_msgdef_mapentry(md);
  11140. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11141. upb_msg_field_iter i;
  11142. const upb_json_printercache *cache = closure;
  11143. const bool preserve_fieldnames = cache->preserve_fieldnames;
  11144. if (is_mapentry) {
  11145. /* mapentry messages are sufficiently different that we handle them
  11146. * separately. */
  11147. printer_sethandlers_mapentry(closure, preserve_fieldnames, h);
  11148. return;
  11149. }
  11150. switch (upb_msgdef_wellknowntype(md)) {
  11151. case UPB_WELLKNOWN_UNSPECIFIED:
  11152. break;
  11153. case UPB_WELLKNOWN_ANY:
  11154. printer_sethandlers_any(closure, h);
  11155. return;
  11156. case UPB_WELLKNOWN_FIELDMASK:
  11157. printer_sethandlers_fieldmask(closure, h);
  11158. return;
  11159. case UPB_WELLKNOWN_DURATION:
  11160. printer_sethandlers_duration(closure, h);
  11161. return;
  11162. case UPB_WELLKNOWN_TIMESTAMP:
  11163. printer_sethandlers_timestamp(closure, h);
  11164. return;
  11165. case UPB_WELLKNOWN_VALUE:
  11166. printer_sethandlers_value(closure, h);
  11167. return;
  11168. case UPB_WELLKNOWN_LISTVALUE:
  11169. printer_sethandlers_listvalue(closure, h);
  11170. return;
  11171. case UPB_WELLKNOWN_STRUCT:
  11172. printer_sethandlers_structvalue(closure, h);
  11173. return;
  11174. #define WRAPPER(wellknowntype, name) \
  11175. case wellknowntype: \
  11176. printer_sethandlers_##name(closure, h); \
  11177. return; \
  11178. WRAPPER(UPB_WELLKNOWN_DOUBLEVALUE, doublevalue);
  11179. WRAPPER(UPB_WELLKNOWN_FLOATVALUE, floatvalue);
  11180. WRAPPER(UPB_WELLKNOWN_INT64VALUE, int64value);
  11181. WRAPPER(UPB_WELLKNOWN_UINT64VALUE, uint64value);
  11182. WRAPPER(UPB_WELLKNOWN_INT32VALUE, int32value);
  11183. WRAPPER(UPB_WELLKNOWN_UINT32VALUE, uint32value);
  11184. WRAPPER(UPB_WELLKNOWN_BOOLVALUE, boolvalue);
  11185. WRAPPER(UPB_WELLKNOWN_STRINGVALUE, stringvalue);
  11186. WRAPPER(UPB_WELLKNOWN_BYTESVALUE, bytesvalue);
  11187. #undef WRAPPER
  11188. }
  11189. upb_handlers_setstartmsg(h, printer_startmsg, &empty_attr);
  11190. upb_handlers_setendmsg(h, printer_endmsg, &empty_attr);
  11191. #define TYPE(type, name, ctype) \
  11192. case type: \
  11193. if (upb_fielddef_isseq(f)) { \
  11194. upb_handlers_set##name(h, f, repeated_##ctype, &empty_attr); \
  11195. } else { \
  11196. upb_handlers_set##name(h, f, scalar_##ctype, &name_attr); \
  11197. } \
  11198. break;
  11199. upb_msg_field_begin(&i, md);
  11200. for(; !upb_msg_field_done(&i); upb_msg_field_next(&i)) {
  11201. const upb_fielddef *f = upb_msg_iter_field(&i);
  11202. upb_handlerattr name_attr = UPB_HANDLERATTR_INIT;
  11203. name_attr.handler_data = newstrpc(h, f, preserve_fieldnames);
  11204. if (upb_fielddef_ismap(f)) {
  11205. upb_handlers_setstartseq(h, f, startmap, &name_attr);
  11206. upb_handlers_setendseq(h, f, endmap, &name_attr);
  11207. } else if (upb_fielddef_isseq(f)) {
  11208. upb_handlers_setstartseq(h, f, startseq, &name_attr);
  11209. upb_handlers_setendseq(h, f, endseq, &empty_attr);
  11210. }
  11211. switch (upb_fielddef_type(f)) {
  11212. TYPE(UPB_TYPE_FLOAT, float, float);
  11213. TYPE(UPB_TYPE_DOUBLE, double, double);
  11214. TYPE(UPB_TYPE_BOOL, bool, bool);
  11215. TYPE(UPB_TYPE_INT32, int32, int32_t);
  11216. TYPE(UPB_TYPE_UINT32, uint32, uint32_t);
  11217. TYPE(UPB_TYPE_INT64, int64, int64_t);
  11218. TYPE(UPB_TYPE_UINT64, uint64, uint64_t);
  11219. case UPB_TYPE_ENUM: {
  11220. /* For now, we always emit symbolic names for enums. We may want an
  11221. * option later to control this behavior, but we will wait for a real
  11222. * need first. */
  11223. upb_handlerattr enum_attr = UPB_HANDLERATTR_INIT;
  11224. set_enum_hd(h, f, preserve_fieldnames, &enum_attr);
  11225. if (upb_fielddef_isseq(f)) {
  11226. upb_handlers_setint32(h, f, repeated_enum, &enum_attr);
  11227. } else {
  11228. upb_handlers_setint32(h, f, scalar_enum, &enum_attr);
  11229. }
  11230. break;
  11231. }
  11232. case UPB_TYPE_STRING:
  11233. if (upb_fielddef_isseq(f)) {
  11234. upb_handlers_setstartstr(h, f, repeated_startstr, &empty_attr);
  11235. upb_handlers_setstring(h, f, repeated_str, &empty_attr);
  11236. upb_handlers_setendstr(h, f, repeated_endstr, &empty_attr);
  11237. } else {
  11238. upb_handlers_setstartstr(h, f, scalar_startstr, &name_attr);
  11239. upb_handlers_setstring(h, f, scalar_str, &empty_attr);
  11240. upb_handlers_setendstr(h, f, scalar_endstr, &empty_attr);
  11241. }
  11242. break;
  11243. case UPB_TYPE_BYTES:
  11244. /* XXX: this doesn't support strings that span buffers yet. The base64
  11245. * encoder will need to be made resumable for this to work properly. */
  11246. if (upb_fielddef_isseq(f)) {
  11247. upb_handlers_setstring(h, f, repeated_bytes, &empty_attr);
  11248. } else {
  11249. upb_handlers_setstring(h, f, scalar_bytes, &name_attr);
  11250. }
  11251. break;
  11252. case UPB_TYPE_MESSAGE:
  11253. if (upb_fielddef_isseq(f)) {
  11254. upb_handlers_setstartsubmsg(h, f, repeated_startsubmsg, &name_attr);
  11255. } else {
  11256. upb_handlers_setstartsubmsg(h, f, scalar_startsubmsg, &name_attr);
  11257. }
  11258. break;
  11259. }
  11260. }
  11261. #undef TYPE
  11262. }
  11263. static void json_printer_reset(upb_json_printer *p) {
  11264. p->depth_ = 0;
  11265. }
  11266. /* Public API *****************************************************************/
  11267. upb_json_printer *upb_json_printer_create(upb_arena *a, const upb_handlers *h,
  11268. upb_bytessink output) {
  11269. #ifndef NDEBUG
  11270. size_t size_before = upb_arena_bytesallocated(a);
  11271. #endif
  11272. upb_json_printer *p = upb_arena_malloc(a, sizeof(upb_json_printer));
  11273. if (!p) return NULL;
  11274. p->output_ = output;
  11275. json_printer_reset(p);
  11276. upb_sink_reset(&p->input_, h, p);
  11277. p->seconds = 0;
  11278. p->nanos = 0;
  11279. /* If this fails, increase the value in printer.h. */
  11280. UPB_ASSERT_DEBUGVAR(upb_arena_bytesallocated(a) - size_before <=
  11281. UPB_JSON_PRINTER_SIZE);
  11282. return p;
  11283. }
  11284. upb_sink upb_json_printer_input(upb_json_printer *p) {
  11285. return p->input_;
  11286. }
  11287. upb_handlercache *upb_json_printer_newcache(bool preserve_proto_fieldnames) {
  11288. upb_json_printercache *cache = upb_gmalloc(sizeof(*cache));
  11289. upb_handlercache *ret = upb_handlercache_new(printer_sethandlers, cache);
  11290. cache->preserve_fieldnames = preserve_proto_fieldnames;
  11291. upb_handlercache_addcleanup(ret, cache, upb_gfree);
  11292. return ret;
  11293. }
  11294. /* See port_def.inc. This should #undef all macros #defined there. */
  11295. #undef UPB_SIZE
  11296. #undef UPB_FIELD_AT
  11297. #undef UPB_READ_ONEOF
  11298. #undef UPB_WRITE_ONEOF
  11299. #undef UPB_INLINE
  11300. #undef UPB_FORCEINLINE
  11301. #undef UPB_NOINLINE
  11302. #undef UPB_NORETURN
  11303. #undef UPB_MAX
  11304. #undef UPB_MIN
  11305. #undef UPB_UNUSED
  11306. #undef UPB_ASSERT
  11307. #undef UPB_ASSERT_DEBUGVAR
  11308. #undef UPB_UNREACHABLE
  11309. #undef UPB_INFINITY
  11310. #undef UPB_MSVC_VSNPRINTF
  11311. #undef _upb_snprintf
  11312. #undef _upb_vsnprintf
  11313. #undef _upb_va_copy