upb.c 395 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984
  1. // Amalgamated source file
  2. #include "upb.h"
  3. /*
  4. * upb - a minimalist implementation of protocol buffers.
  5. *
  6. * Copyright (c) 2008-2012 Google Inc. See LICENSE for details.
  7. * Author: Josh Haberman <jhaberman@gmail.com>
  8. */
  9. #include <stdlib.h>
  10. #include <string.h>
  11. typedef struct {
  12. size_t len;
  13. char str[1]; /* Null-terminated string data follows. */
  14. } str_t;
  15. static str_t *newstr(const char *data, size_t len) {
  16. str_t *ret = malloc(sizeof(*ret) + len);
  17. if (!ret) return NULL;
  18. ret->len = len;
  19. memcpy(ret->str, data, len);
  20. ret->str[len] = '\0';
  21. return ret;
  22. }
  23. static void freestr(str_t *s) { free(s); }
  24. /* isalpha() etc. from <ctype.h> are locale-dependent, which we don't want. */
  25. static bool upb_isbetween(char c, char low, char high) {
  26. return c >= low && c <= high;
  27. }
  28. static bool upb_isletter(char c) {
  29. return upb_isbetween(c, 'A', 'Z') || upb_isbetween(c, 'a', 'z') || c == '_';
  30. }
  31. static bool upb_isalphanum(char c) {
  32. return upb_isletter(c) || upb_isbetween(c, '0', '9');
  33. }
  34. static bool upb_isident(const char *str, size_t len, bool full, upb_status *s) {
  35. bool start = true;
  36. size_t i;
  37. for (i = 0; i < len; i++) {
  38. char c = str[i];
  39. if (c == '.') {
  40. if (start || !full) {
  41. upb_status_seterrf(s, "invalid name: unexpected '.' (%s)", str);
  42. return false;
  43. }
  44. start = true;
  45. } else if (start) {
  46. if (!upb_isletter(c)) {
  47. upb_status_seterrf(
  48. s, "invalid name: path components must start with a letter (%s)",
  49. str);
  50. return false;
  51. }
  52. start = false;
  53. } else {
  54. if (!upb_isalphanum(c)) {
  55. upb_status_seterrf(s, "invalid name: non-alphanumeric character (%s)",
  56. str);
  57. return false;
  58. }
  59. }
  60. }
  61. return !start;
  62. }
  63. /* upb_def ********************************************************************/
  64. upb_deftype_t upb_def_type(const upb_def *d) { return d->type; }
  65. const char *upb_def_fullname(const upb_def *d) { return d->fullname; }
  66. bool upb_def_setfullname(upb_def *def, const char *fullname, upb_status *s) {
  67. assert(!upb_def_isfrozen(def));
  68. if (!upb_isident(fullname, strlen(fullname), true, s)) return false;
  69. free((void*)def->fullname);
  70. def->fullname = upb_strdup(fullname);
  71. return true;
  72. }
  73. upb_def *upb_def_dup(const upb_def *def, const void *o) {
  74. switch (def->type) {
  75. case UPB_DEF_MSG:
  76. return upb_msgdef_upcast_mutable(
  77. upb_msgdef_dup(upb_downcast_msgdef(def), o));
  78. case UPB_DEF_FIELD:
  79. return upb_fielddef_upcast_mutable(
  80. upb_fielddef_dup(upb_downcast_fielddef(def), o));
  81. case UPB_DEF_ENUM:
  82. return upb_enumdef_upcast_mutable(
  83. upb_enumdef_dup(upb_downcast_enumdef(def), o));
  84. default: assert(false); return NULL;
  85. }
  86. }
  87. static bool upb_def_init(upb_def *def, upb_deftype_t type,
  88. const struct upb_refcounted_vtbl *vtbl,
  89. const void *owner) {
  90. if (!upb_refcounted_init(upb_def_upcast_mutable(def), vtbl, owner)) return false;
  91. def->type = type;
  92. def->fullname = NULL;
  93. def->came_from_user = false;
  94. return true;
  95. }
  96. static void upb_def_uninit(upb_def *def) {
  97. free((void*)def->fullname);
  98. }
  99. static const char *msgdef_name(const upb_msgdef *m) {
  100. const char *name = upb_def_fullname(upb_msgdef_upcast(m));
  101. return name ? name : "(anonymous)";
  102. }
  103. static bool upb_validate_field(upb_fielddef *f, upb_status *s) {
  104. if (upb_fielddef_name(f) == NULL || upb_fielddef_number(f) == 0) {
  105. upb_status_seterrmsg(s, "fielddef must have name and number set");
  106. return false;
  107. }
  108. if (!f->type_is_set_) {
  109. upb_status_seterrmsg(s, "fielddef type was not initialized");
  110. return false;
  111. }
  112. if (upb_fielddef_lazy(f) &&
  113. upb_fielddef_descriptortype(f) != UPB_DESCRIPTOR_TYPE_MESSAGE) {
  114. upb_status_seterrmsg(s,
  115. "only length-delimited submessage fields may be lazy");
  116. return false;
  117. }
  118. if (upb_fielddef_hassubdef(f)) {
  119. const upb_def *subdef;
  120. if (f->subdef_is_symbolic) {
  121. upb_status_seterrf(s, "field '%s.%s' has not been resolved",
  122. msgdef_name(f->msg.def), upb_fielddef_name(f));
  123. return false;
  124. }
  125. subdef = upb_fielddef_subdef(f);
  126. if (subdef == NULL) {
  127. upb_status_seterrf(s, "field %s.%s is missing required subdef",
  128. msgdef_name(f->msg.def), upb_fielddef_name(f));
  129. return false;
  130. }
  131. if (!upb_def_isfrozen(subdef) && !subdef->came_from_user) {
  132. upb_status_seterrf(s,
  133. "subdef of field %s.%s is not frozen or being frozen",
  134. msgdef_name(f->msg.def), upb_fielddef_name(f));
  135. return false;
  136. }
  137. }
  138. if (upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  139. bool has_default_name = upb_fielddef_enumhasdefaultstr(f);
  140. bool has_default_number = upb_fielddef_enumhasdefaultint32(f);
  141. /* Previously verified by upb_validate_enumdef(). */
  142. assert(upb_enumdef_numvals(upb_fielddef_enumsubdef(f)) > 0);
  143. /* We've already validated that we have an associated enumdef and that it
  144. * has at least one member, so at least one of these should be true.
  145. * Because if the user didn't set anything, we'll pick up the enum's
  146. * default, but if the user *did* set something we should at least pick up
  147. * the one they set (int32 or string). */
  148. assert(has_default_name || has_default_number);
  149. if (!has_default_name) {
  150. upb_status_seterrf(s,
  151. "enum default for field %s.%s (%d) is not in the enum",
  152. msgdef_name(f->msg.def), upb_fielddef_name(f),
  153. upb_fielddef_defaultint32(f));
  154. return false;
  155. }
  156. if (!has_default_number) {
  157. upb_status_seterrf(s,
  158. "enum default for field %s.%s (%s) is not in the enum",
  159. msgdef_name(f->msg.def), upb_fielddef_name(f),
  160. upb_fielddef_defaultstr(f, NULL));
  161. return false;
  162. }
  163. /* Lift the effective numeric default into the field's default slot, in case
  164. * we were only getting it "by reference" from the enumdef. */
  165. upb_fielddef_setdefaultint32(f, upb_fielddef_defaultint32(f));
  166. }
  167. /* Ensure that MapEntry submessages only appear as repeated fields, not
  168. * optional/required (singular) fields. */
  169. if (upb_fielddef_type(f) == UPB_TYPE_MESSAGE &&
  170. upb_fielddef_msgsubdef(f) != NULL) {
  171. const upb_msgdef *subdef = upb_fielddef_msgsubdef(f);
  172. if (upb_msgdef_mapentry(subdef) && !upb_fielddef_isseq(f)) {
  173. upb_status_seterrf(s,
  174. "Field %s refers to mapentry message but is not "
  175. "a repeated field",
  176. upb_fielddef_name(f) ? upb_fielddef_name(f) :
  177. "(unnamed)");
  178. return false;
  179. }
  180. }
  181. return true;
  182. }
  183. static bool upb_validate_enumdef(const upb_enumdef *e, upb_status *s) {
  184. if (upb_enumdef_numvals(e) == 0) {
  185. upb_status_seterrf(s, "enum %s has no members (must have at least one)",
  186. upb_enumdef_fullname(e));
  187. return false;
  188. }
  189. return true;
  190. }
  191. /* All submessage fields are lower than all other fields.
  192. * Secondly, fields are increasing in order. */
  193. uint32_t field_rank(const upb_fielddef *f) {
  194. uint32_t ret = upb_fielddef_number(f);
  195. const uint32_t high_bit = 1 << 30;
  196. assert(ret < high_bit);
  197. if (!upb_fielddef_issubmsg(f))
  198. ret |= high_bit;
  199. return ret;
  200. }
  201. int cmp_fields(const void *p1, const void *p2) {
  202. const upb_fielddef *f1 = *(upb_fielddef*const*)p1;
  203. const upb_fielddef *f2 = *(upb_fielddef*const*)p2;
  204. return field_rank(f1) - field_rank(f2);
  205. }
  206. static bool assign_msg_indices(upb_msgdef *m, upb_status *s) {
  207. /* Sort fields. upb internally relies on UPB_TYPE_MESSAGE fields having the
  208. * lowest indexes, but we do not publicly guarantee this. */
  209. upb_msg_field_iter j;
  210. int i;
  211. uint32_t selector;
  212. int n = upb_msgdef_numfields(m);
  213. upb_fielddef **fields = malloc(n * sizeof(*fields));
  214. if (!fields) return false;
  215. m->submsg_field_count = 0;
  216. for(i = 0, upb_msg_field_begin(&j, m);
  217. !upb_msg_field_done(&j);
  218. upb_msg_field_next(&j), i++) {
  219. upb_fielddef *f = upb_msg_iter_field(&j);
  220. assert(f->msg.def == m);
  221. if (!upb_validate_field(f, s)) {
  222. free(fields);
  223. return false;
  224. }
  225. if (upb_fielddef_issubmsg(f)) {
  226. m->submsg_field_count++;
  227. }
  228. fields[i] = f;
  229. }
  230. qsort(fields, n, sizeof(*fields), cmp_fields);
  231. selector = UPB_STATIC_SELECTOR_COUNT + m->submsg_field_count;
  232. for (i = 0; i < n; i++) {
  233. upb_fielddef *f = fields[i];
  234. f->index_ = i;
  235. f->selector_base = selector + upb_handlers_selectorbaseoffset(f);
  236. selector += upb_handlers_selectorcount(f);
  237. }
  238. m->selector_count = selector;
  239. #ifndef NDEBUG
  240. {
  241. /* Verify that all selectors for the message are distinct. */
  242. #define TRY(type) \
  243. if (upb_handlers_getselector(f, type, &sel)) upb_inttable_insert(&t, sel, v);
  244. upb_inttable t;
  245. upb_value v;
  246. upb_selector_t sel;
  247. upb_inttable_init(&t, UPB_CTYPE_BOOL);
  248. v = upb_value_bool(true);
  249. upb_inttable_insert(&t, UPB_STARTMSG_SELECTOR, v);
  250. upb_inttable_insert(&t, UPB_ENDMSG_SELECTOR, v);
  251. for(upb_msg_field_begin(&j, m);
  252. !upb_msg_field_done(&j);
  253. upb_msg_field_next(&j)) {
  254. upb_fielddef *f = upb_msg_iter_field(&j);
  255. /* These calls will assert-fail in upb_table if the value already
  256. * exists. */
  257. TRY(UPB_HANDLER_INT32);
  258. TRY(UPB_HANDLER_INT64)
  259. TRY(UPB_HANDLER_UINT32)
  260. TRY(UPB_HANDLER_UINT64)
  261. TRY(UPB_HANDLER_FLOAT)
  262. TRY(UPB_HANDLER_DOUBLE)
  263. TRY(UPB_HANDLER_BOOL)
  264. TRY(UPB_HANDLER_STARTSTR)
  265. TRY(UPB_HANDLER_STRING)
  266. TRY(UPB_HANDLER_ENDSTR)
  267. TRY(UPB_HANDLER_STARTSUBMSG)
  268. TRY(UPB_HANDLER_ENDSUBMSG)
  269. TRY(UPB_HANDLER_STARTSEQ)
  270. TRY(UPB_HANDLER_ENDSEQ)
  271. }
  272. upb_inttable_uninit(&t);
  273. }
  274. #undef TRY
  275. #endif
  276. free(fields);
  277. return true;
  278. }
  279. bool upb_def_freeze(upb_def *const* defs, int n, upb_status *s) {
  280. int i;
  281. int maxdepth;
  282. bool ret;
  283. upb_status_clear(s);
  284. /* First perform validation, in two passes so we can check that we have a
  285. * transitive closure without needing to search. */
  286. for (i = 0; i < n; i++) {
  287. upb_def *def = defs[i];
  288. if (upb_def_isfrozen(def)) {
  289. /* Could relax this requirement if it's annoying. */
  290. upb_status_seterrmsg(s, "def is already frozen");
  291. goto err;
  292. } else if (def->type == UPB_DEF_FIELD) {
  293. upb_status_seterrmsg(s, "standalone fielddefs can not be frozen");
  294. goto err;
  295. } else if (def->type == UPB_DEF_ENUM) {
  296. if (!upb_validate_enumdef(upb_dyncast_enumdef(def), s)) {
  297. goto err;
  298. }
  299. } else {
  300. /* Set now to detect transitive closure in the second pass. */
  301. def->came_from_user = true;
  302. }
  303. }
  304. /* Second pass of validation. Also assign selector bases and indexes, and
  305. * compact tables. */
  306. for (i = 0; i < n; i++) {
  307. upb_msgdef *m = upb_dyncast_msgdef_mutable(defs[i]);
  308. upb_enumdef *e = upb_dyncast_enumdef_mutable(defs[i]);
  309. if (m) {
  310. upb_inttable_compact(&m->itof);
  311. if (!assign_msg_indices(m, s)) {
  312. goto err;
  313. }
  314. } else if (e) {
  315. upb_inttable_compact(&e->iton);
  316. }
  317. }
  318. /* Def graph contains FieldDefs between each MessageDef, so double the
  319. * limit. */
  320. maxdepth = UPB_MAX_MESSAGE_DEPTH * 2;
  321. /* Validation all passed; freeze the defs. */
  322. ret = upb_refcounted_freeze((upb_refcounted * const *)defs, n, s, maxdepth);
  323. assert(!(s && ret != upb_ok(s)));
  324. return ret;
  325. err:
  326. for (i = 0; i < n; i++) {
  327. defs[i]->came_from_user = false;
  328. }
  329. assert(!(s && upb_ok(s)));
  330. return false;
  331. }
  332. /* upb_enumdef ****************************************************************/
  333. static void upb_enumdef_free(upb_refcounted *r) {
  334. upb_enumdef *e = (upb_enumdef*)r;
  335. upb_inttable_iter i;
  336. upb_inttable_begin(&i, &e->iton);
  337. for( ; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  338. /* To clean up the upb_strdup() from upb_enumdef_addval(). */
  339. free(upb_value_getcstr(upb_inttable_iter_value(&i)));
  340. }
  341. upb_strtable_uninit(&e->ntoi);
  342. upb_inttable_uninit(&e->iton);
  343. upb_def_uninit(upb_enumdef_upcast_mutable(e));
  344. free(e);
  345. }
  346. upb_enumdef *upb_enumdef_new(const void *owner) {
  347. static const struct upb_refcounted_vtbl vtbl = {NULL, &upb_enumdef_free};
  348. upb_enumdef *e = malloc(sizeof(*e));
  349. if (!e) return NULL;
  350. if (!upb_def_init(upb_enumdef_upcast_mutable(e), UPB_DEF_ENUM, &vtbl, owner))
  351. goto err2;
  352. if (!upb_strtable_init(&e->ntoi, UPB_CTYPE_INT32)) goto err2;
  353. if (!upb_inttable_init(&e->iton, UPB_CTYPE_CSTR)) goto err1;
  354. return e;
  355. err1:
  356. upb_strtable_uninit(&e->ntoi);
  357. err2:
  358. free(e);
  359. return NULL;
  360. }
  361. upb_enumdef *upb_enumdef_dup(const upb_enumdef *e, const void *owner) {
  362. upb_enum_iter i;
  363. upb_enumdef *new_e = upb_enumdef_new(owner);
  364. if (!new_e) return NULL;
  365. for(upb_enum_begin(&i, e); !upb_enum_done(&i); upb_enum_next(&i)) {
  366. bool success = upb_enumdef_addval(
  367. new_e, upb_enum_iter_name(&i),upb_enum_iter_number(&i), NULL);
  368. if (!success) {
  369. upb_enumdef_unref(new_e, owner);
  370. return NULL;
  371. }
  372. }
  373. return new_e;
  374. }
  375. bool upb_enumdef_freeze(upb_enumdef *e, upb_status *status) {
  376. upb_def *d = upb_enumdef_upcast_mutable(e);
  377. return upb_def_freeze(&d, 1, status);
  378. }
  379. const char *upb_enumdef_fullname(const upb_enumdef *e) {
  380. return upb_def_fullname(upb_enumdef_upcast(e));
  381. }
  382. bool upb_enumdef_setfullname(upb_enumdef *e, const char *fullname,
  383. upb_status *s) {
  384. return upb_def_setfullname(upb_enumdef_upcast_mutable(e), fullname, s);
  385. }
  386. bool upb_enumdef_addval(upb_enumdef *e, const char *name, int32_t num,
  387. upb_status *status) {
  388. if (!upb_isident(name, strlen(name), false, status)) {
  389. return false;
  390. }
  391. if (upb_enumdef_ntoiz(e, name, NULL)) {
  392. upb_status_seterrf(status, "name '%s' is already defined", name);
  393. return false;
  394. }
  395. if (!upb_strtable_insert(&e->ntoi, name, upb_value_int32(num))) {
  396. upb_status_seterrmsg(status, "out of memory");
  397. return false;
  398. }
  399. if (!upb_inttable_lookup(&e->iton, num, NULL) &&
  400. !upb_inttable_insert(&e->iton, num, upb_value_cstr(upb_strdup(name)))) {
  401. upb_status_seterrmsg(status, "out of memory");
  402. upb_strtable_remove(&e->ntoi, name, NULL);
  403. return false;
  404. }
  405. if (upb_enumdef_numvals(e) == 1) {
  406. bool ok = upb_enumdef_setdefault(e, num, NULL);
  407. UPB_ASSERT_VAR(ok, ok);
  408. }
  409. return true;
  410. }
  411. int32_t upb_enumdef_default(const upb_enumdef *e) {
  412. assert(upb_enumdef_iton(e, e->defaultval));
  413. return e->defaultval;
  414. }
  415. bool upb_enumdef_setdefault(upb_enumdef *e, int32_t val, upb_status *s) {
  416. assert(!upb_enumdef_isfrozen(e));
  417. if (!upb_enumdef_iton(e, val)) {
  418. upb_status_seterrf(s, "number '%d' is not in the enum.", val);
  419. return false;
  420. }
  421. e->defaultval = val;
  422. return true;
  423. }
  424. int upb_enumdef_numvals(const upb_enumdef *e) {
  425. return upb_strtable_count(&e->ntoi);
  426. }
  427. void upb_enum_begin(upb_enum_iter *i, const upb_enumdef *e) {
  428. /* We iterate over the ntoi table, to account for duplicate numbers. */
  429. upb_strtable_begin(i, &e->ntoi);
  430. }
  431. void upb_enum_next(upb_enum_iter *iter) { upb_strtable_next(iter); }
  432. bool upb_enum_done(upb_enum_iter *iter) { return upb_strtable_done(iter); }
  433. bool upb_enumdef_ntoi(const upb_enumdef *def, const char *name,
  434. size_t len, int32_t *num) {
  435. upb_value v;
  436. if (!upb_strtable_lookup2(&def->ntoi, name, len, &v)) {
  437. return false;
  438. }
  439. if (num) *num = upb_value_getint32(v);
  440. return true;
  441. }
  442. const char *upb_enumdef_iton(const upb_enumdef *def, int32_t num) {
  443. upb_value v;
  444. return upb_inttable_lookup32(&def->iton, num, &v) ?
  445. upb_value_getcstr(v) : NULL;
  446. }
  447. const char *upb_enum_iter_name(upb_enum_iter *iter) {
  448. return upb_strtable_iter_key(iter);
  449. }
  450. int32_t upb_enum_iter_number(upb_enum_iter *iter) {
  451. return upb_value_getint32(upb_strtable_iter_value(iter));
  452. }
  453. /* upb_fielddef ***************************************************************/
  454. static void upb_fielddef_init_default(upb_fielddef *f);
  455. static void upb_fielddef_uninit_default(upb_fielddef *f) {
  456. if (f->type_is_set_ && f->default_is_string && f->defaultval.bytes)
  457. freestr(f->defaultval.bytes);
  458. }
  459. static void visitfield(const upb_refcounted *r, upb_refcounted_visit *visit,
  460. void *closure) {
  461. const upb_fielddef *f = (const upb_fielddef*)r;
  462. if (upb_fielddef_containingtype(f)) {
  463. visit(r, upb_msgdef_upcast2(upb_fielddef_containingtype(f)), closure);
  464. }
  465. if (upb_fielddef_containingoneof(f)) {
  466. visit(r, upb_oneofdef_upcast2(upb_fielddef_containingoneof(f)), closure);
  467. }
  468. if (upb_fielddef_subdef(f)) {
  469. visit(r, upb_def_upcast(upb_fielddef_subdef(f)), closure);
  470. }
  471. }
  472. static void freefield(upb_refcounted *r) {
  473. upb_fielddef *f = (upb_fielddef*)r;
  474. upb_fielddef_uninit_default(f);
  475. if (f->subdef_is_symbolic)
  476. free(f->sub.name);
  477. upb_def_uninit(upb_fielddef_upcast_mutable(f));
  478. free(f);
  479. }
  480. static const char *enumdefaultstr(const upb_fielddef *f) {
  481. const upb_enumdef *e;
  482. assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  483. e = upb_fielddef_enumsubdef(f);
  484. if (f->default_is_string && f->defaultval.bytes) {
  485. /* Default was explicitly set as a string. */
  486. str_t *s = f->defaultval.bytes;
  487. return s->str;
  488. } else if (e) {
  489. if (!f->default_is_string) {
  490. /* Default was explicitly set as an integer; look it up in enumdef. */
  491. const char *name = upb_enumdef_iton(e, f->defaultval.sint);
  492. if (name) {
  493. return name;
  494. }
  495. } else {
  496. /* Default is completely unset; pull enumdef default. */
  497. if (upb_enumdef_numvals(e) > 0) {
  498. const char *name = upb_enumdef_iton(e, upb_enumdef_default(e));
  499. assert(name);
  500. return name;
  501. }
  502. }
  503. }
  504. return NULL;
  505. }
  506. static bool enumdefaultint32(const upb_fielddef *f, int32_t *val) {
  507. const upb_enumdef *e;
  508. assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  509. e = upb_fielddef_enumsubdef(f);
  510. if (!f->default_is_string) {
  511. /* Default was explicitly set as an integer. */
  512. *val = f->defaultval.sint;
  513. return true;
  514. } else if (e) {
  515. if (f->defaultval.bytes) {
  516. /* Default was explicitly set as a str; try to lookup corresponding int. */
  517. str_t *s = f->defaultval.bytes;
  518. if (upb_enumdef_ntoiz(e, s->str, val)) {
  519. return true;
  520. }
  521. } else {
  522. /* Default is unset; try to pull in enumdef default. */
  523. if (upb_enumdef_numvals(e) > 0) {
  524. *val = upb_enumdef_default(e);
  525. return true;
  526. }
  527. }
  528. }
  529. return false;
  530. }
  531. upb_fielddef *upb_fielddef_new(const void *o) {
  532. static const struct upb_refcounted_vtbl vtbl = {visitfield, freefield};
  533. upb_fielddef *f = malloc(sizeof(*f));
  534. if (!f) return NULL;
  535. if (!upb_def_init(upb_fielddef_upcast_mutable(f), UPB_DEF_FIELD, &vtbl, o)) {
  536. free(f);
  537. return NULL;
  538. }
  539. f->msg.def = NULL;
  540. f->sub.def = NULL;
  541. f->oneof = NULL;
  542. f->subdef_is_symbolic = false;
  543. f->msg_is_symbolic = false;
  544. f->label_ = UPB_LABEL_OPTIONAL;
  545. f->type_ = UPB_TYPE_INT32;
  546. f->number_ = 0;
  547. f->type_is_set_ = false;
  548. f->tagdelim = false;
  549. f->is_extension_ = false;
  550. f->lazy_ = false;
  551. f->packed_ = true;
  552. /* For the moment we default this to UPB_INTFMT_VARIABLE, since it will work
  553. * with all integer types and is in some since more "default" since the most
  554. * normal-looking proto2 types int32/int64/uint32/uint64 use variable.
  555. *
  556. * Other options to consider:
  557. * - there is no default; users must set this manually (like type).
  558. * - default signed integers to UPB_INTFMT_ZIGZAG, since it's more likely to
  559. * be an optimal default for signed integers. */
  560. f->intfmt = UPB_INTFMT_VARIABLE;
  561. return f;
  562. }
  563. upb_fielddef *upb_fielddef_dup(const upb_fielddef *f, const void *owner) {
  564. const char *srcname;
  565. upb_fielddef *newf = upb_fielddef_new(owner);
  566. if (!newf) return NULL;
  567. upb_fielddef_settype(newf, upb_fielddef_type(f));
  568. upb_fielddef_setlabel(newf, upb_fielddef_label(f));
  569. upb_fielddef_setnumber(newf, upb_fielddef_number(f), NULL);
  570. upb_fielddef_setname(newf, upb_fielddef_name(f), NULL);
  571. if (f->default_is_string && f->defaultval.bytes) {
  572. str_t *s = f->defaultval.bytes;
  573. upb_fielddef_setdefaultstr(newf, s->str, s->len, NULL);
  574. } else {
  575. newf->default_is_string = f->default_is_string;
  576. newf->defaultval = f->defaultval;
  577. }
  578. if (f->subdef_is_symbolic) {
  579. srcname = f->sub.name; /* Might be NULL. */
  580. } else {
  581. srcname = f->sub.def ? upb_def_fullname(f->sub.def) : NULL;
  582. }
  583. if (srcname) {
  584. char *newname = malloc(strlen(f->sub.def->fullname) + 2);
  585. if (!newname) {
  586. upb_fielddef_unref(newf, owner);
  587. return NULL;
  588. }
  589. strcpy(newname, ".");
  590. strcat(newname, f->sub.def->fullname);
  591. upb_fielddef_setsubdefname(newf, newname, NULL);
  592. free(newname);
  593. }
  594. return newf;
  595. }
  596. bool upb_fielddef_typeisset(const upb_fielddef *f) {
  597. return f->type_is_set_;
  598. }
  599. upb_fieldtype_t upb_fielddef_type(const upb_fielddef *f) {
  600. assert(f->type_is_set_);
  601. return f->type_;
  602. }
  603. uint32_t upb_fielddef_index(const upb_fielddef *f) {
  604. return f->index_;
  605. }
  606. upb_label_t upb_fielddef_label(const upb_fielddef *f) {
  607. return f->label_;
  608. }
  609. upb_intfmt_t upb_fielddef_intfmt(const upb_fielddef *f) {
  610. return f->intfmt;
  611. }
  612. bool upb_fielddef_istagdelim(const upb_fielddef *f) {
  613. return f->tagdelim;
  614. }
  615. uint32_t upb_fielddef_number(const upb_fielddef *f) {
  616. return f->number_;
  617. }
  618. bool upb_fielddef_isextension(const upb_fielddef *f) {
  619. return f->is_extension_;
  620. }
  621. bool upb_fielddef_lazy(const upb_fielddef *f) {
  622. return f->lazy_;
  623. }
  624. bool upb_fielddef_packed(const upb_fielddef *f) {
  625. return f->packed_;
  626. }
  627. const char *upb_fielddef_name(const upb_fielddef *f) {
  628. return upb_def_fullname(upb_fielddef_upcast(f));
  629. }
  630. const upb_msgdef *upb_fielddef_containingtype(const upb_fielddef *f) {
  631. return f->msg_is_symbolic ? NULL : f->msg.def;
  632. }
  633. const upb_oneofdef *upb_fielddef_containingoneof(const upb_fielddef *f) {
  634. return f->oneof;
  635. }
  636. upb_msgdef *upb_fielddef_containingtype_mutable(upb_fielddef *f) {
  637. return (upb_msgdef*)upb_fielddef_containingtype(f);
  638. }
  639. const char *upb_fielddef_containingtypename(upb_fielddef *f) {
  640. return f->msg_is_symbolic ? f->msg.name : NULL;
  641. }
  642. static void release_containingtype(upb_fielddef *f) {
  643. if (f->msg_is_symbolic) free(f->msg.name);
  644. }
  645. bool upb_fielddef_setcontainingtypename(upb_fielddef *f, const char *name,
  646. upb_status *s) {
  647. assert(!upb_fielddef_isfrozen(f));
  648. if (upb_fielddef_containingtype(f)) {
  649. upb_status_seterrmsg(s, "field has already been added to a message.");
  650. return false;
  651. }
  652. /* TODO: validate name (upb_isident() doesn't quite work atm because this name
  653. * may have a leading "."). */
  654. release_containingtype(f);
  655. f->msg.name = upb_strdup(name);
  656. f->msg_is_symbolic = true;
  657. return true;
  658. }
  659. bool upb_fielddef_setname(upb_fielddef *f, const char *name, upb_status *s) {
  660. if (upb_fielddef_containingtype(f) || upb_fielddef_containingoneof(f)) {
  661. upb_status_seterrmsg(s, "Already added to message or oneof");
  662. return false;
  663. }
  664. return upb_def_setfullname(upb_fielddef_upcast_mutable(f), name, s);
  665. }
  666. static void chkdefaulttype(const upb_fielddef *f, upb_fieldtype_t type) {
  667. UPB_UNUSED(f);
  668. UPB_UNUSED(type);
  669. assert(f->type_is_set_ && upb_fielddef_type(f) == type);
  670. }
  671. int64_t upb_fielddef_defaultint64(const upb_fielddef *f) {
  672. chkdefaulttype(f, UPB_TYPE_INT64);
  673. return f->defaultval.sint;
  674. }
  675. int32_t upb_fielddef_defaultint32(const upb_fielddef *f) {
  676. if (f->type_is_set_ && upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  677. int32_t val;
  678. bool ok = enumdefaultint32(f, &val);
  679. UPB_ASSERT_VAR(ok, ok);
  680. return val;
  681. } else {
  682. chkdefaulttype(f, UPB_TYPE_INT32);
  683. return f->defaultval.sint;
  684. }
  685. }
  686. uint64_t upb_fielddef_defaultuint64(const upb_fielddef *f) {
  687. chkdefaulttype(f, UPB_TYPE_UINT64);
  688. return f->defaultval.uint;
  689. }
  690. uint32_t upb_fielddef_defaultuint32(const upb_fielddef *f) {
  691. chkdefaulttype(f, UPB_TYPE_UINT32);
  692. return f->defaultval.uint;
  693. }
  694. bool upb_fielddef_defaultbool(const upb_fielddef *f) {
  695. chkdefaulttype(f, UPB_TYPE_BOOL);
  696. return f->defaultval.uint;
  697. }
  698. float upb_fielddef_defaultfloat(const upb_fielddef *f) {
  699. chkdefaulttype(f, UPB_TYPE_FLOAT);
  700. return f->defaultval.flt;
  701. }
  702. double upb_fielddef_defaultdouble(const upb_fielddef *f) {
  703. chkdefaulttype(f, UPB_TYPE_DOUBLE);
  704. return f->defaultval.dbl;
  705. }
  706. const char *upb_fielddef_defaultstr(const upb_fielddef *f, size_t *len) {
  707. assert(f->type_is_set_);
  708. assert(upb_fielddef_type(f) == UPB_TYPE_STRING ||
  709. upb_fielddef_type(f) == UPB_TYPE_BYTES ||
  710. upb_fielddef_type(f) == UPB_TYPE_ENUM);
  711. if (upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  712. const char *ret = enumdefaultstr(f);
  713. assert(ret);
  714. /* Enum defaults can't have embedded NULLs. */
  715. if (len) *len = strlen(ret);
  716. return ret;
  717. }
  718. if (f->default_is_string) {
  719. str_t *str = f->defaultval.bytes;
  720. if (len) *len = str->len;
  721. return str->str;
  722. }
  723. return NULL;
  724. }
  725. static void upb_fielddef_init_default(upb_fielddef *f) {
  726. f->default_is_string = false;
  727. switch (upb_fielddef_type(f)) {
  728. case UPB_TYPE_DOUBLE: f->defaultval.dbl = 0; break;
  729. case UPB_TYPE_FLOAT: f->defaultval.flt = 0; break;
  730. case UPB_TYPE_INT32:
  731. case UPB_TYPE_INT64: f->defaultval.sint = 0; break;
  732. case UPB_TYPE_UINT64:
  733. case UPB_TYPE_UINT32:
  734. case UPB_TYPE_BOOL: f->defaultval.uint = 0; break;
  735. case UPB_TYPE_STRING:
  736. case UPB_TYPE_BYTES:
  737. f->defaultval.bytes = newstr("", 0);
  738. f->default_is_string = true;
  739. break;
  740. case UPB_TYPE_MESSAGE: break;
  741. case UPB_TYPE_ENUM:
  742. /* This is our special sentinel that indicates "not set" for an enum. */
  743. f->default_is_string = true;
  744. f->defaultval.bytes = NULL;
  745. break;
  746. }
  747. }
  748. const upb_def *upb_fielddef_subdef(const upb_fielddef *f) {
  749. return f->subdef_is_symbolic ? NULL : f->sub.def;
  750. }
  751. const upb_msgdef *upb_fielddef_msgsubdef(const upb_fielddef *f) {
  752. const upb_def *def = upb_fielddef_subdef(f);
  753. return def ? upb_dyncast_msgdef(def) : NULL;
  754. }
  755. const upb_enumdef *upb_fielddef_enumsubdef(const upb_fielddef *f) {
  756. const upb_def *def = upb_fielddef_subdef(f);
  757. return def ? upb_dyncast_enumdef(def) : NULL;
  758. }
  759. upb_def *upb_fielddef_subdef_mutable(upb_fielddef *f) {
  760. return (upb_def*)upb_fielddef_subdef(f);
  761. }
  762. const char *upb_fielddef_subdefname(const upb_fielddef *f) {
  763. if (f->subdef_is_symbolic) {
  764. return f->sub.name;
  765. } else if (f->sub.def) {
  766. return upb_def_fullname(f->sub.def);
  767. } else {
  768. return NULL;
  769. }
  770. }
  771. bool upb_fielddef_setnumber(upb_fielddef *f, uint32_t number, upb_status *s) {
  772. if (upb_fielddef_containingtype(f)) {
  773. upb_status_seterrmsg(
  774. s, "cannot change field number after adding to a message");
  775. return false;
  776. }
  777. if (number == 0 || number > UPB_MAX_FIELDNUMBER) {
  778. upb_status_seterrf(s, "invalid field number (%u)", number);
  779. return false;
  780. }
  781. f->number_ = number;
  782. return true;
  783. }
  784. void upb_fielddef_settype(upb_fielddef *f, upb_fieldtype_t type) {
  785. assert(!upb_fielddef_isfrozen(f));
  786. assert(upb_fielddef_checktype(type));
  787. upb_fielddef_uninit_default(f);
  788. f->type_ = type;
  789. f->type_is_set_ = true;
  790. upb_fielddef_init_default(f);
  791. }
  792. void upb_fielddef_setdescriptortype(upb_fielddef *f, int type) {
  793. assert(!upb_fielddef_isfrozen(f));
  794. switch (type) {
  795. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  796. upb_fielddef_settype(f, UPB_TYPE_DOUBLE);
  797. break;
  798. case UPB_DESCRIPTOR_TYPE_FLOAT:
  799. upb_fielddef_settype(f, UPB_TYPE_FLOAT);
  800. break;
  801. case UPB_DESCRIPTOR_TYPE_INT64:
  802. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  803. case UPB_DESCRIPTOR_TYPE_SINT64:
  804. upb_fielddef_settype(f, UPB_TYPE_INT64);
  805. break;
  806. case UPB_DESCRIPTOR_TYPE_UINT64:
  807. case UPB_DESCRIPTOR_TYPE_FIXED64:
  808. upb_fielddef_settype(f, UPB_TYPE_UINT64);
  809. break;
  810. case UPB_DESCRIPTOR_TYPE_INT32:
  811. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  812. case UPB_DESCRIPTOR_TYPE_SINT32:
  813. upb_fielddef_settype(f, UPB_TYPE_INT32);
  814. break;
  815. case UPB_DESCRIPTOR_TYPE_UINT32:
  816. case UPB_DESCRIPTOR_TYPE_FIXED32:
  817. upb_fielddef_settype(f, UPB_TYPE_UINT32);
  818. break;
  819. case UPB_DESCRIPTOR_TYPE_BOOL:
  820. upb_fielddef_settype(f, UPB_TYPE_BOOL);
  821. break;
  822. case UPB_DESCRIPTOR_TYPE_STRING:
  823. upb_fielddef_settype(f, UPB_TYPE_STRING);
  824. break;
  825. case UPB_DESCRIPTOR_TYPE_BYTES:
  826. upb_fielddef_settype(f, UPB_TYPE_BYTES);
  827. break;
  828. case UPB_DESCRIPTOR_TYPE_GROUP:
  829. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  830. upb_fielddef_settype(f, UPB_TYPE_MESSAGE);
  831. break;
  832. case UPB_DESCRIPTOR_TYPE_ENUM:
  833. upb_fielddef_settype(f, UPB_TYPE_ENUM);
  834. break;
  835. default: assert(false);
  836. }
  837. if (type == UPB_DESCRIPTOR_TYPE_FIXED64 ||
  838. type == UPB_DESCRIPTOR_TYPE_FIXED32 ||
  839. type == UPB_DESCRIPTOR_TYPE_SFIXED64 ||
  840. type == UPB_DESCRIPTOR_TYPE_SFIXED32) {
  841. upb_fielddef_setintfmt(f, UPB_INTFMT_FIXED);
  842. } else if (type == UPB_DESCRIPTOR_TYPE_SINT64 ||
  843. type == UPB_DESCRIPTOR_TYPE_SINT32) {
  844. upb_fielddef_setintfmt(f, UPB_INTFMT_ZIGZAG);
  845. } else {
  846. upb_fielddef_setintfmt(f, UPB_INTFMT_VARIABLE);
  847. }
  848. upb_fielddef_settagdelim(f, type == UPB_DESCRIPTOR_TYPE_GROUP);
  849. }
  850. upb_descriptortype_t upb_fielddef_descriptortype(const upb_fielddef *f) {
  851. switch (upb_fielddef_type(f)) {
  852. case UPB_TYPE_FLOAT: return UPB_DESCRIPTOR_TYPE_FLOAT;
  853. case UPB_TYPE_DOUBLE: return UPB_DESCRIPTOR_TYPE_DOUBLE;
  854. case UPB_TYPE_BOOL: return UPB_DESCRIPTOR_TYPE_BOOL;
  855. case UPB_TYPE_STRING: return UPB_DESCRIPTOR_TYPE_STRING;
  856. case UPB_TYPE_BYTES: return UPB_DESCRIPTOR_TYPE_BYTES;
  857. case UPB_TYPE_ENUM: return UPB_DESCRIPTOR_TYPE_ENUM;
  858. case UPB_TYPE_INT32:
  859. switch (upb_fielddef_intfmt(f)) {
  860. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_INT32;
  861. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_SFIXED32;
  862. case UPB_INTFMT_ZIGZAG: return UPB_DESCRIPTOR_TYPE_SINT32;
  863. }
  864. case UPB_TYPE_INT64:
  865. switch (upb_fielddef_intfmt(f)) {
  866. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_INT64;
  867. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_SFIXED64;
  868. case UPB_INTFMT_ZIGZAG: return UPB_DESCRIPTOR_TYPE_SINT64;
  869. }
  870. case UPB_TYPE_UINT32:
  871. switch (upb_fielddef_intfmt(f)) {
  872. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_UINT32;
  873. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_FIXED32;
  874. case UPB_INTFMT_ZIGZAG: return -1;
  875. }
  876. case UPB_TYPE_UINT64:
  877. switch (upb_fielddef_intfmt(f)) {
  878. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_UINT64;
  879. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_FIXED64;
  880. case UPB_INTFMT_ZIGZAG: return -1;
  881. }
  882. case UPB_TYPE_MESSAGE:
  883. return upb_fielddef_istagdelim(f) ?
  884. UPB_DESCRIPTOR_TYPE_GROUP : UPB_DESCRIPTOR_TYPE_MESSAGE;
  885. }
  886. return 0;
  887. }
  888. void upb_fielddef_setisextension(upb_fielddef *f, bool is_extension) {
  889. assert(!upb_fielddef_isfrozen(f));
  890. f->is_extension_ = is_extension;
  891. }
  892. void upb_fielddef_setlazy(upb_fielddef *f, bool lazy) {
  893. assert(!upb_fielddef_isfrozen(f));
  894. f->lazy_ = lazy;
  895. }
  896. void upb_fielddef_setpacked(upb_fielddef *f, bool packed) {
  897. assert(!upb_fielddef_isfrozen(f));
  898. f->packed_ = packed;
  899. }
  900. void upb_fielddef_setlabel(upb_fielddef *f, upb_label_t label) {
  901. assert(!upb_fielddef_isfrozen(f));
  902. assert(upb_fielddef_checklabel(label));
  903. f->label_ = label;
  904. }
  905. void upb_fielddef_setintfmt(upb_fielddef *f, upb_intfmt_t fmt) {
  906. assert(!upb_fielddef_isfrozen(f));
  907. assert(upb_fielddef_checkintfmt(fmt));
  908. f->intfmt = fmt;
  909. }
  910. void upb_fielddef_settagdelim(upb_fielddef *f, bool tag_delim) {
  911. assert(!upb_fielddef_isfrozen(f));
  912. f->tagdelim = tag_delim;
  913. f->tagdelim = tag_delim;
  914. }
  915. static bool checksetdefault(upb_fielddef *f, upb_fieldtype_t type) {
  916. if (!f->type_is_set_ || upb_fielddef_isfrozen(f) ||
  917. upb_fielddef_type(f) != type) {
  918. assert(false);
  919. return false;
  920. }
  921. if (f->default_is_string) {
  922. str_t *s = f->defaultval.bytes;
  923. assert(s || type == UPB_TYPE_ENUM);
  924. if (s) freestr(s);
  925. }
  926. f->default_is_string = false;
  927. return true;
  928. }
  929. void upb_fielddef_setdefaultint64(upb_fielddef *f, int64_t value) {
  930. if (checksetdefault(f, UPB_TYPE_INT64))
  931. f->defaultval.sint = value;
  932. }
  933. void upb_fielddef_setdefaultint32(upb_fielddef *f, int32_t value) {
  934. if ((upb_fielddef_type(f) == UPB_TYPE_ENUM &&
  935. checksetdefault(f, UPB_TYPE_ENUM)) ||
  936. checksetdefault(f, UPB_TYPE_INT32)) {
  937. f->defaultval.sint = value;
  938. }
  939. }
  940. void upb_fielddef_setdefaultuint64(upb_fielddef *f, uint64_t value) {
  941. if (checksetdefault(f, UPB_TYPE_UINT64))
  942. f->defaultval.uint = value;
  943. }
  944. void upb_fielddef_setdefaultuint32(upb_fielddef *f, uint32_t value) {
  945. if (checksetdefault(f, UPB_TYPE_UINT32))
  946. f->defaultval.uint = value;
  947. }
  948. void upb_fielddef_setdefaultbool(upb_fielddef *f, bool value) {
  949. if (checksetdefault(f, UPB_TYPE_BOOL))
  950. f->defaultval.uint = value;
  951. }
  952. void upb_fielddef_setdefaultfloat(upb_fielddef *f, float value) {
  953. if (checksetdefault(f, UPB_TYPE_FLOAT))
  954. f->defaultval.flt = value;
  955. }
  956. void upb_fielddef_setdefaultdouble(upb_fielddef *f, double value) {
  957. if (checksetdefault(f, UPB_TYPE_DOUBLE))
  958. f->defaultval.dbl = value;
  959. }
  960. bool upb_fielddef_setdefaultstr(upb_fielddef *f, const void *str, size_t len,
  961. upb_status *s) {
  962. str_t *str2;
  963. assert(upb_fielddef_isstring(f) || f->type_ == UPB_TYPE_ENUM);
  964. if (f->type_ == UPB_TYPE_ENUM && !upb_isident(str, len, false, s))
  965. return false;
  966. if (f->default_is_string) {
  967. str_t *s = f->defaultval.bytes;
  968. assert(s || f->type_ == UPB_TYPE_ENUM);
  969. if (s) freestr(s);
  970. } else {
  971. assert(f->type_ == UPB_TYPE_ENUM);
  972. }
  973. str2 = newstr(str, len);
  974. f->defaultval.bytes = str2;
  975. f->default_is_string = true;
  976. return true;
  977. }
  978. void upb_fielddef_setdefaultcstr(upb_fielddef *f, const char *str,
  979. upb_status *s) {
  980. assert(f->type_is_set_);
  981. upb_fielddef_setdefaultstr(f, str, str ? strlen(str) : 0, s);
  982. }
  983. bool upb_fielddef_enumhasdefaultint32(const upb_fielddef *f) {
  984. int32_t val;
  985. assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  986. return enumdefaultint32(f, &val);
  987. }
  988. bool upb_fielddef_enumhasdefaultstr(const upb_fielddef *f) {
  989. assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  990. return enumdefaultstr(f) != NULL;
  991. }
  992. static bool upb_subdef_typecheck(upb_fielddef *f, const upb_def *subdef,
  993. upb_status *s) {
  994. if (f->type_ == UPB_TYPE_MESSAGE) {
  995. if (upb_dyncast_msgdef(subdef)) return true;
  996. upb_status_seterrmsg(s, "invalid subdef type for this submessage field");
  997. return false;
  998. } else if (f->type_ == UPB_TYPE_ENUM) {
  999. if (upb_dyncast_enumdef(subdef)) return true;
  1000. upb_status_seterrmsg(s, "invalid subdef type for this enum field");
  1001. return false;
  1002. } else {
  1003. upb_status_seterrmsg(s, "only message and enum fields can have a subdef");
  1004. return false;
  1005. }
  1006. }
  1007. static void release_subdef(upb_fielddef *f) {
  1008. if (f->subdef_is_symbolic) {
  1009. free(f->sub.name);
  1010. } else if (f->sub.def) {
  1011. upb_unref2(f->sub.def, f);
  1012. }
  1013. }
  1014. bool upb_fielddef_setsubdef(upb_fielddef *f, const upb_def *subdef,
  1015. upb_status *s) {
  1016. assert(!upb_fielddef_isfrozen(f));
  1017. assert(upb_fielddef_hassubdef(f));
  1018. if (subdef && !upb_subdef_typecheck(f, subdef, s)) return false;
  1019. release_subdef(f);
  1020. f->sub.def = subdef;
  1021. f->subdef_is_symbolic = false;
  1022. if (f->sub.def) upb_ref2(f->sub.def, f);
  1023. return true;
  1024. }
  1025. bool upb_fielddef_setmsgsubdef(upb_fielddef *f, const upb_msgdef *subdef,
  1026. upb_status *s) {
  1027. return upb_fielddef_setsubdef(f, upb_msgdef_upcast(subdef), s);
  1028. }
  1029. bool upb_fielddef_setenumsubdef(upb_fielddef *f, const upb_enumdef *subdef,
  1030. upb_status *s) {
  1031. return upb_fielddef_setsubdef(f, upb_enumdef_upcast(subdef), s);
  1032. }
  1033. bool upb_fielddef_setsubdefname(upb_fielddef *f, const char *name,
  1034. upb_status *s) {
  1035. assert(!upb_fielddef_isfrozen(f));
  1036. if (!upb_fielddef_hassubdef(f)) {
  1037. upb_status_seterrmsg(s, "field type does not accept a subdef");
  1038. return false;
  1039. }
  1040. /* TODO: validate name (upb_isident() doesn't quite work atm because this name
  1041. * may have a leading "."). */
  1042. release_subdef(f);
  1043. f->sub.name = upb_strdup(name);
  1044. f->subdef_is_symbolic = true;
  1045. return true;
  1046. }
  1047. bool upb_fielddef_issubmsg(const upb_fielddef *f) {
  1048. return upb_fielddef_type(f) == UPB_TYPE_MESSAGE;
  1049. }
  1050. bool upb_fielddef_isstring(const upb_fielddef *f) {
  1051. return upb_fielddef_type(f) == UPB_TYPE_STRING ||
  1052. upb_fielddef_type(f) == UPB_TYPE_BYTES;
  1053. }
  1054. bool upb_fielddef_isseq(const upb_fielddef *f) {
  1055. return upb_fielddef_label(f) == UPB_LABEL_REPEATED;
  1056. }
  1057. bool upb_fielddef_isprimitive(const upb_fielddef *f) {
  1058. return !upb_fielddef_isstring(f) && !upb_fielddef_issubmsg(f);
  1059. }
  1060. bool upb_fielddef_ismap(const upb_fielddef *f) {
  1061. return upb_fielddef_isseq(f) && upb_fielddef_issubmsg(f) &&
  1062. upb_msgdef_mapentry(upb_fielddef_msgsubdef(f));
  1063. }
  1064. bool upb_fielddef_hassubdef(const upb_fielddef *f) {
  1065. return upb_fielddef_issubmsg(f) || upb_fielddef_type(f) == UPB_TYPE_ENUM;
  1066. }
  1067. static bool between(int32_t x, int32_t low, int32_t high) {
  1068. return x >= low && x <= high;
  1069. }
  1070. bool upb_fielddef_checklabel(int32_t label) { return between(label, 1, 3); }
  1071. bool upb_fielddef_checktype(int32_t type) { return between(type, 1, 11); }
  1072. bool upb_fielddef_checkintfmt(int32_t fmt) { return between(fmt, 1, 3); }
  1073. bool upb_fielddef_checkdescriptortype(int32_t type) {
  1074. return between(type, 1, 18);
  1075. }
  1076. /* upb_msgdef *****************************************************************/
  1077. static void visitmsg(const upb_refcounted *r, upb_refcounted_visit *visit,
  1078. void *closure) {
  1079. upb_msg_oneof_iter o;
  1080. const upb_msgdef *m = (const upb_msgdef*)r;
  1081. upb_msg_field_iter i;
  1082. for(upb_msg_field_begin(&i, m);
  1083. !upb_msg_field_done(&i);
  1084. upb_msg_field_next(&i)) {
  1085. upb_fielddef *f = upb_msg_iter_field(&i);
  1086. visit(r, upb_fielddef_upcast2(f), closure);
  1087. }
  1088. for(upb_msg_oneof_begin(&o, m);
  1089. !upb_msg_oneof_done(&o);
  1090. upb_msg_oneof_next(&o)) {
  1091. upb_oneofdef *f = upb_msg_iter_oneof(&o);
  1092. visit(r, upb_oneofdef_upcast2(f), closure);
  1093. }
  1094. }
  1095. static void freemsg(upb_refcounted *r) {
  1096. upb_msgdef *m = (upb_msgdef*)r;
  1097. upb_strtable_uninit(&m->ntoo);
  1098. upb_strtable_uninit(&m->ntof);
  1099. upb_inttable_uninit(&m->itof);
  1100. upb_def_uninit(upb_msgdef_upcast_mutable(m));
  1101. free(m);
  1102. }
  1103. upb_msgdef *upb_msgdef_new(const void *owner) {
  1104. static const struct upb_refcounted_vtbl vtbl = {visitmsg, freemsg};
  1105. upb_msgdef *m = malloc(sizeof(*m));
  1106. if (!m) return NULL;
  1107. if (!upb_def_init(upb_msgdef_upcast_mutable(m), UPB_DEF_MSG, &vtbl, owner))
  1108. goto err2;
  1109. if (!upb_inttable_init(&m->itof, UPB_CTYPE_PTR)) goto err3;
  1110. if (!upb_strtable_init(&m->ntof, UPB_CTYPE_PTR)) goto err2;
  1111. if (!upb_strtable_init(&m->ntoo, UPB_CTYPE_PTR)) goto err1;
  1112. m->map_entry = false;
  1113. return m;
  1114. err1:
  1115. upb_strtable_uninit(&m->ntof);
  1116. err2:
  1117. upb_inttable_uninit(&m->itof);
  1118. err3:
  1119. free(m);
  1120. return NULL;
  1121. }
  1122. upb_msgdef *upb_msgdef_dup(const upb_msgdef *m, const void *owner) {
  1123. bool ok;
  1124. upb_msg_field_iter i;
  1125. upb_msg_oneof_iter o;
  1126. upb_msgdef *newm = upb_msgdef_new(owner);
  1127. if (!newm) return NULL;
  1128. ok = upb_def_setfullname(upb_msgdef_upcast_mutable(newm),
  1129. upb_def_fullname(upb_msgdef_upcast(m)),
  1130. NULL);
  1131. newm->map_entry = m->map_entry;
  1132. UPB_ASSERT_VAR(ok, ok);
  1133. for(upb_msg_field_begin(&i, m);
  1134. !upb_msg_field_done(&i);
  1135. upb_msg_field_next(&i)) {
  1136. upb_fielddef *f = upb_fielddef_dup(upb_msg_iter_field(&i), &f);
  1137. /* Fields in oneofs are dup'd below. */
  1138. if (upb_fielddef_containingoneof(f)) continue;
  1139. if (!f || !upb_msgdef_addfield(newm, f, &f, NULL)) {
  1140. upb_msgdef_unref(newm, owner);
  1141. return NULL;
  1142. }
  1143. }
  1144. for(upb_msg_oneof_begin(&o, m);
  1145. !upb_msg_oneof_done(&o);
  1146. upb_msg_oneof_next(&o)) {
  1147. upb_oneofdef *f = upb_oneofdef_dup(upb_msg_iter_oneof(&o), &f);
  1148. if (!f || !upb_msgdef_addoneof(newm, f, &f, NULL)) {
  1149. upb_msgdef_unref(newm, owner);
  1150. return NULL;
  1151. }
  1152. }
  1153. return newm;
  1154. }
  1155. bool upb_msgdef_freeze(upb_msgdef *m, upb_status *status) {
  1156. upb_def *d = upb_msgdef_upcast_mutable(m);
  1157. return upb_def_freeze(&d, 1, status);
  1158. }
  1159. const char *upb_msgdef_fullname(const upb_msgdef *m) {
  1160. return upb_def_fullname(upb_msgdef_upcast(m));
  1161. }
  1162. bool upb_msgdef_setfullname(upb_msgdef *m, const char *fullname,
  1163. upb_status *s) {
  1164. return upb_def_setfullname(upb_msgdef_upcast_mutable(m), fullname, s);
  1165. }
  1166. /* Helper: check that the field |f| is safe to add to msgdef |m|. Set an error
  1167. * on status |s| and return false if not. */
  1168. static bool check_field_add(const upb_msgdef *m, const upb_fielddef *f,
  1169. upb_status *s) {
  1170. if (upb_fielddef_containingtype(f) != NULL) {
  1171. upb_status_seterrmsg(s, "fielddef already belongs to a message");
  1172. return false;
  1173. } else if (upb_fielddef_name(f) == NULL || upb_fielddef_number(f) == 0) {
  1174. upb_status_seterrmsg(s, "field name or number were not set");
  1175. return false;
  1176. } else if (upb_msgdef_ntofz(m, upb_fielddef_name(f)) ||
  1177. upb_msgdef_itof(m, upb_fielddef_number(f))) {
  1178. upb_status_seterrmsg(s, "duplicate field name or number for field");
  1179. return false;
  1180. }
  1181. return true;
  1182. }
  1183. static void add_field(upb_msgdef *m, upb_fielddef *f, const void *ref_donor) {
  1184. release_containingtype(f);
  1185. f->msg.def = m;
  1186. f->msg_is_symbolic = false;
  1187. upb_inttable_insert(&m->itof, upb_fielddef_number(f), upb_value_ptr(f));
  1188. upb_strtable_insert(&m->ntof, upb_fielddef_name(f), upb_value_ptr(f));
  1189. upb_ref2(f, m);
  1190. upb_ref2(m, f);
  1191. if (ref_donor) upb_fielddef_unref(f, ref_donor);
  1192. }
  1193. bool upb_msgdef_addfield(upb_msgdef *m, upb_fielddef *f, const void *ref_donor,
  1194. upb_status *s) {
  1195. /* TODO: extensions need to have a separate namespace, because proto2 allows a
  1196. * top-level extension (ie. one not in any package) to have the same name as a
  1197. * field from the message.
  1198. *
  1199. * This also implies that there needs to be a separate lookup-by-name method
  1200. * for extensions. It seems desirable for iteration to return both extensions
  1201. * and non-extensions though.
  1202. *
  1203. * We also need to validate that the field number is in an extension range iff
  1204. * it is an extension.
  1205. *
  1206. * This method is idempotent. Check if |f| is already part of this msgdef and
  1207. * return immediately if so. */
  1208. if (upb_fielddef_containingtype(f) == m) {
  1209. return true;
  1210. }
  1211. /* Check constraints for all fields before performing any action. */
  1212. if (!check_field_add(m, f, s)) {
  1213. return false;
  1214. } else if (upb_fielddef_containingoneof(f) != NULL) {
  1215. /* Fields in a oneof can only be added by adding the oneof to the msgdef. */
  1216. upb_status_seterrmsg(s, "fielddef is part of a oneof");
  1217. return false;
  1218. }
  1219. /* Constraint checks ok, perform the action. */
  1220. add_field(m, f, ref_donor);
  1221. return true;
  1222. }
  1223. bool upb_msgdef_addoneof(upb_msgdef *m, upb_oneofdef *o, const void *ref_donor,
  1224. upb_status *s) {
  1225. upb_oneof_iter it;
  1226. /* Check various conditions that would prevent this oneof from being added. */
  1227. if (upb_oneofdef_containingtype(o)) {
  1228. upb_status_seterrmsg(s, "oneofdef already belongs to a message");
  1229. return false;
  1230. } else if (upb_oneofdef_name(o) == NULL) {
  1231. upb_status_seterrmsg(s, "oneofdef name was not set");
  1232. return false;
  1233. } else if (upb_msgdef_ntooz(m, upb_oneofdef_name(o))) {
  1234. upb_status_seterrmsg(s, "duplicate oneof name");
  1235. return false;
  1236. }
  1237. /* Check that all of the oneof's fields do not conflict with names or numbers
  1238. * of fields already in the message. */
  1239. for (upb_oneof_begin(&it, o); !upb_oneof_done(&it); upb_oneof_next(&it)) {
  1240. const upb_fielddef *f = upb_oneof_iter_field(&it);
  1241. if (!check_field_add(m, f, s)) {
  1242. return false;
  1243. }
  1244. }
  1245. /* Everything checks out -- commit now. */
  1246. /* Add oneof itself first. */
  1247. o->parent = m;
  1248. upb_strtable_insert(&m->ntoo, upb_oneofdef_name(o), upb_value_ptr(o));
  1249. upb_ref2(o, m);
  1250. upb_ref2(m, o);
  1251. /* Add each field of the oneof directly to the msgdef. */
  1252. for (upb_oneof_begin(&it, o); !upb_oneof_done(&it); upb_oneof_next(&it)) {
  1253. upb_fielddef *f = upb_oneof_iter_field(&it);
  1254. add_field(m, f, NULL);
  1255. }
  1256. if (ref_donor) upb_oneofdef_unref(o, ref_donor);
  1257. return true;
  1258. }
  1259. const upb_fielddef *upb_msgdef_itof(const upb_msgdef *m, uint32_t i) {
  1260. upb_value val;
  1261. return upb_inttable_lookup32(&m->itof, i, &val) ?
  1262. upb_value_getptr(val) : NULL;
  1263. }
  1264. const upb_fielddef *upb_msgdef_ntof(const upb_msgdef *m, const char *name,
  1265. size_t len) {
  1266. upb_value val;
  1267. return upb_strtable_lookup2(&m->ntof, name, len, &val) ?
  1268. upb_value_getptr(val) : NULL;
  1269. }
  1270. const upb_oneofdef *upb_msgdef_ntoo(const upb_msgdef *m, const char *name,
  1271. size_t len) {
  1272. upb_value val;
  1273. return upb_strtable_lookup2(&m->ntoo, name, len, &val) ?
  1274. upb_value_getptr(val) : NULL;
  1275. }
  1276. int upb_msgdef_numfields(const upb_msgdef *m) {
  1277. return upb_strtable_count(&m->ntof);
  1278. }
  1279. int upb_msgdef_numoneofs(const upb_msgdef *m) {
  1280. return upb_strtable_count(&m->ntoo);
  1281. }
  1282. void upb_msgdef_setmapentry(upb_msgdef *m, bool map_entry) {
  1283. assert(!upb_msgdef_isfrozen(m));
  1284. m->map_entry = map_entry;
  1285. }
  1286. bool upb_msgdef_mapentry(const upb_msgdef *m) {
  1287. return m->map_entry;
  1288. }
  1289. void upb_msg_field_begin(upb_msg_field_iter *iter, const upb_msgdef *m) {
  1290. upb_inttable_begin(iter, &m->itof);
  1291. }
  1292. void upb_msg_field_next(upb_msg_field_iter *iter) { upb_inttable_next(iter); }
  1293. bool upb_msg_field_done(const upb_msg_field_iter *iter) {
  1294. return upb_inttable_done(iter);
  1295. }
  1296. upb_fielddef *upb_msg_iter_field(const upb_msg_field_iter *iter) {
  1297. return (upb_fielddef*)upb_value_getptr(upb_inttable_iter_value(iter));
  1298. }
  1299. void upb_msg_field_iter_setdone(upb_msg_field_iter *iter) {
  1300. upb_inttable_iter_setdone(iter);
  1301. }
  1302. void upb_msg_oneof_begin(upb_msg_oneof_iter *iter, const upb_msgdef *m) {
  1303. upb_strtable_begin(iter, &m->ntoo);
  1304. }
  1305. void upb_msg_oneof_next(upb_msg_oneof_iter *iter) { upb_strtable_next(iter); }
  1306. bool upb_msg_oneof_done(const upb_msg_oneof_iter *iter) {
  1307. return upb_strtable_done(iter);
  1308. }
  1309. upb_oneofdef *upb_msg_iter_oneof(const upb_msg_oneof_iter *iter) {
  1310. return (upb_oneofdef*)upb_value_getptr(upb_strtable_iter_value(iter));
  1311. }
  1312. void upb_msg_oneof_iter_setdone(upb_msg_oneof_iter *iter) {
  1313. upb_strtable_iter_setdone(iter);
  1314. }
  1315. /* upb_oneofdef ***************************************************************/
  1316. static void visitoneof(const upb_refcounted *r, upb_refcounted_visit *visit,
  1317. void *closure) {
  1318. const upb_oneofdef *o = (const upb_oneofdef*)r;
  1319. upb_oneof_iter i;
  1320. for (upb_oneof_begin(&i, o); !upb_oneof_done(&i); upb_oneof_next(&i)) {
  1321. const upb_fielddef *f = upb_oneof_iter_field(&i);
  1322. visit(r, upb_fielddef_upcast2(f), closure);
  1323. }
  1324. if (o->parent) {
  1325. visit(r, upb_msgdef_upcast2(o->parent), closure);
  1326. }
  1327. }
  1328. static void freeoneof(upb_refcounted *r) {
  1329. upb_oneofdef *o = (upb_oneofdef*)r;
  1330. upb_strtable_uninit(&o->ntof);
  1331. upb_inttable_uninit(&o->itof);
  1332. upb_def_uninit(upb_oneofdef_upcast_mutable(o));
  1333. free(o);
  1334. }
  1335. upb_oneofdef *upb_oneofdef_new(const void *owner) {
  1336. static const struct upb_refcounted_vtbl vtbl = {visitoneof, freeoneof};
  1337. upb_oneofdef *o = malloc(sizeof(*o));
  1338. o->parent = NULL;
  1339. if (!o) return NULL;
  1340. if (!upb_def_init(upb_oneofdef_upcast_mutable(o), UPB_DEF_ONEOF, &vtbl,
  1341. owner))
  1342. goto err2;
  1343. if (!upb_inttable_init(&o->itof, UPB_CTYPE_PTR)) goto err2;
  1344. if (!upb_strtable_init(&o->ntof, UPB_CTYPE_PTR)) goto err1;
  1345. return o;
  1346. err1:
  1347. upb_inttable_uninit(&o->itof);
  1348. err2:
  1349. free(o);
  1350. return NULL;
  1351. }
  1352. upb_oneofdef *upb_oneofdef_dup(const upb_oneofdef *o, const void *owner) {
  1353. bool ok;
  1354. upb_oneof_iter i;
  1355. upb_oneofdef *newo = upb_oneofdef_new(owner);
  1356. if (!newo) return NULL;
  1357. ok = upb_def_setfullname(upb_oneofdef_upcast_mutable(newo),
  1358. upb_def_fullname(upb_oneofdef_upcast(o)), NULL);
  1359. UPB_ASSERT_VAR(ok, ok);
  1360. for (upb_oneof_begin(&i, o); !upb_oneof_done(&i); upb_oneof_next(&i)) {
  1361. upb_fielddef *f = upb_fielddef_dup(upb_oneof_iter_field(&i), &f);
  1362. if (!f || !upb_oneofdef_addfield(newo, f, &f, NULL)) {
  1363. upb_oneofdef_unref(newo, owner);
  1364. return NULL;
  1365. }
  1366. }
  1367. return newo;
  1368. }
  1369. const char *upb_oneofdef_name(const upb_oneofdef *o) {
  1370. return upb_def_fullname(upb_oneofdef_upcast(o));
  1371. }
  1372. bool upb_oneofdef_setname(upb_oneofdef *o, const char *fullname,
  1373. upb_status *s) {
  1374. if (upb_oneofdef_containingtype(o)) {
  1375. upb_status_seterrmsg(s, "oneof already added to a message");
  1376. return false;
  1377. }
  1378. return upb_def_setfullname(upb_oneofdef_upcast_mutable(o), fullname, s);
  1379. }
  1380. const upb_msgdef *upb_oneofdef_containingtype(const upb_oneofdef *o) {
  1381. return o->parent;
  1382. }
  1383. int upb_oneofdef_numfields(const upb_oneofdef *o) {
  1384. return upb_strtable_count(&o->ntof);
  1385. }
  1386. bool upb_oneofdef_addfield(upb_oneofdef *o, upb_fielddef *f,
  1387. const void *ref_donor,
  1388. upb_status *s) {
  1389. assert(!upb_oneofdef_isfrozen(o));
  1390. assert(!o->parent || !upb_msgdef_isfrozen(o->parent));
  1391. /* This method is idempotent. Check if |f| is already part of this oneofdef
  1392. * and return immediately if so. */
  1393. if (upb_fielddef_containingoneof(f) == o) {
  1394. return true;
  1395. }
  1396. /* The field must have an OPTIONAL label. */
  1397. if (upb_fielddef_label(f) != UPB_LABEL_OPTIONAL) {
  1398. upb_status_seterrmsg(s, "fields in oneof must have OPTIONAL label");
  1399. return false;
  1400. }
  1401. /* Check that no field with this name or number exists already in the oneof.
  1402. * Also check that the field is not already part of a oneof. */
  1403. if (upb_fielddef_name(f) == NULL || upb_fielddef_number(f) == 0) {
  1404. upb_status_seterrmsg(s, "field name or number were not set");
  1405. return false;
  1406. } else if (upb_oneofdef_itof(o, upb_fielddef_number(f)) ||
  1407. upb_oneofdef_ntofz(o, upb_fielddef_name(f))) {
  1408. upb_status_seterrmsg(s, "duplicate field name or number");
  1409. return false;
  1410. } else if (upb_fielddef_containingoneof(f) != NULL) {
  1411. upb_status_seterrmsg(s, "fielddef already belongs to a oneof");
  1412. return false;
  1413. }
  1414. /* We allow adding a field to the oneof either if the field is not part of a
  1415. * msgdef, or if it is and we are also part of the same msgdef. */
  1416. if (o->parent == NULL) {
  1417. /* If we're not in a msgdef, the field cannot be either. Otherwise we would
  1418. * need to magically add this oneof to a msgdef to remain consistent, which
  1419. * is surprising behavior. */
  1420. if (upb_fielddef_containingtype(f) != NULL) {
  1421. upb_status_seterrmsg(s, "fielddef already belongs to a message, but "
  1422. "oneof does not");
  1423. return false;
  1424. }
  1425. } else {
  1426. /* If we're in a msgdef, the user can add fields that either aren't in any
  1427. * msgdef (in which case they're added to our msgdef) or already a part of
  1428. * our msgdef. */
  1429. if (upb_fielddef_containingtype(f) != NULL &&
  1430. upb_fielddef_containingtype(f) != o->parent) {
  1431. upb_status_seterrmsg(s, "fielddef belongs to a different message "
  1432. "than oneof");
  1433. return false;
  1434. }
  1435. }
  1436. /* Commit phase. First add the field to our parent msgdef, if any, because
  1437. * that may fail; then add the field to our own tables. */
  1438. if (o->parent != NULL && upb_fielddef_containingtype(f) == NULL) {
  1439. if (!upb_msgdef_addfield((upb_msgdef*)o->parent, f, NULL, s)) {
  1440. return false;
  1441. }
  1442. }
  1443. release_containingtype(f);
  1444. f->oneof = o;
  1445. upb_inttable_insert(&o->itof, upb_fielddef_number(f), upb_value_ptr(f));
  1446. upb_strtable_insert(&o->ntof, upb_fielddef_name(f), upb_value_ptr(f));
  1447. upb_ref2(f, o);
  1448. upb_ref2(o, f);
  1449. if (ref_donor) upb_fielddef_unref(f, ref_donor);
  1450. return true;
  1451. }
  1452. const upb_fielddef *upb_oneofdef_ntof(const upb_oneofdef *o,
  1453. const char *name, size_t length) {
  1454. upb_value val;
  1455. return upb_strtable_lookup2(&o->ntof, name, length, &val) ?
  1456. upb_value_getptr(val) : NULL;
  1457. }
  1458. const upb_fielddef *upb_oneofdef_itof(const upb_oneofdef *o, uint32_t num) {
  1459. upb_value val;
  1460. return upb_inttable_lookup32(&o->itof, num, &val) ?
  1461. upb_value_getptr(val) : NULL;
  1462. }
  1463. void upb_oneof_begin(upb_oneof_iter *iter, const upb_oneofdef *o) {
  1464. upb_inttable_begin(iter, &o->itof);
  1465. }
  1466. void upb_oneof_next(upb_oneof_iter *iter) {
  1467. upb_inttable_next(iter);
  1468. }
  1469. bool upb_oneof_done(upb_oneof_iter *iter) {
  1470. return upb_inttable_done(iter);
  1471. }
  1472. upb_fielddef *upb_oneof_iter_field(const upb_oneof_iter *iter) {
  1473. return (upb_fielddef*)upb_value_getptr(upb_inttable_iter_value(iter));
  1474. }
  1475. void upb_oneof_iter_setdone(upb_oneof_iter *iter) {
  1476. upb_inttable_iter_setdone(iter);
  1477. }
  1478. /*
  1479. * upb - a minimalist implementation of protocol buffers.
  1480. *
  1481. * Copyright (c) 2014 Google Inc. See LICENSE for details.
  1482. * Author: Josh Haberman <jhaberman@gmail.com>
  1483. */
  1484. #include <stdlib.h>
  1485. #include <stdio.h>
  1486. #include <string.h>
  1487. typedef struct cleanup_ent {
  1488. upb_cleanup_func *cleanup;
  1489. void *ud;
  1490. struct cleanup_ent *next;
  1491. } cleanup_ent;
  1492. static void *seeded_alloc(void *ud, void *ptr, size_t oldsize, size_t size);
  1493. /* Default allocator **********************************************************/
  1494. /* Just use realloc, keeping all allocated blocks in a linked list to destroy at
  1495. * the end. */
  1496. typedef struct mem_block {
  1497. /* List is doubly-linked, because in cases where realloc() moves an existing
  1498. * block, we need to be able to remove the old pointer from the list
  1499. * efficiently. */
  1500. struct mem_block *prev, *next;
  1501. #ifndef NDEBUG
  1502. size_t size; /* Doesn't include mem_block structure. */
  1503. #endif
  1504. } mem_block;
  1505. typedef struct {
  1506. mem_block *head;
  1507. } default_alloc_ud;
  1508. static void *default_alloc(void *_ud, void *ptr, size_t oldsize, size_t size) {
  1509. default_alloc_ud *ud = _ud;
  1510. mem_block *from, *block;
  1511. void *ret;
  1512. UPB_UNUSED(oldsize);
  1513. from = ptr ? (void*)((char*)ptr - sizeof(mem_block)) : NULL;
  1514. #ifndef NDEBUG
  1515. if (from) {
  1516. assert(oldsize <= from->size);
  1517. }
  1518. #endif
  1519. /* TODO(haberman): we probably need to provide even better alignment here,
  1520. * like 16-byte alignment of the returned data pointer. */
  1521. block = realloc(from, size + sizeof(mem_block));
  1522. if (!block) return NULL;
  1523. ret = (char*)block + sizeof(*block);
  1524. #ifndef NDEBUG
  1525. block->size = size;
  1526. #endif
  1527. if (from) {
  1528. if (block != from) {
  1529. /* The block was moved, so pointers in next and prev blocks must be
  1530. * updated to its new location. */
  1531. if (block->next) block->next->prev = block;
  1532. if (block->prev) block->prev->next = block;
  1533. }
  1534. } else {
  1535. /* Insert at head of linked list. */
  1536. block->prev = NULL;
  1537. block->next = ud->head;
  1538. if (block->next) block->next->prev = block;
  1539. ud->head = block;
  1540. }
  1541. return ret;
  1542. }
  1543. static void default_alloc_cleanup(void *_ud) {
  1544. default_alloc_ud *ud = _ud;
  1545. mem_block *block = ud->head;
  1546. while (block) {
  1547. void *to_free = block;
  1548. block = block->next;
  1549. free(to_free);
  1550. }
  1551. }
  1552. /* Standard error functions ***************************************************/
  1553. static bool default_err(void *ud, const upb_status *status) {
  1554. UPB_UNUSED(ud);
  1555. fprintf(stderr, "upb error: %s\n", upb_status_errmsg(status));
  1556. return false;
  1557. }
  1558. static bool write_err_to(void *ud, const upb_status *status) {
  1559. upb_status *copy_to = ud;
  1560. upb_status_copy(copy_to, status);
  1561. return false;
  1562. }
  1563. /* upb_env ********************************************************************/
  1564. void upb_env_init(upb_env *e) {
  1565. default_alloc_ud *ud = (default_alloc_ud*)&e->default_alloc_ud;
  1566. e->ok_ = true;
  1567. e->bytes_allocated = 0;
  1568. e->cleanup_head = NULL;
  1569. ud->head = NULL;
  1570. /* Set default functions. */
  1571. upb_env_setallocfunc(e, default_alloc, ud);
  1572. upb_env_seterrorfunc(e, default_err, NULL);
  1573. }
  1574. void upb_env_uninit(upb_env *e) {
  1575. cleanup_ent *ent = e->cleanup_head;
  1576. while (ent) {
  1577. ent->cleanup(ent->ud);
  1578. ent = ent->next;
  1579. }
  1580. /* Must do this after running cleanup functions, because this will delete
  1581. the memory we store our cleanup entries in! */
  1582. if (e->alloc == default_alloc) {
  1583. default_alloc_cleanup(e->alloc_ud);
  1584. }
  1585. }
  1586. UPB_FORCEINLINE void upb_env_setallocfunc(upb_env *e, upb_alloc_func *alloc,
  1587. void *ud) {
  1588. e->alloc = alloc;
  1589. e->alloc_ud = ud;
  1590. }
  1591. UPB_FORCEINLINE void upb_env_seterrorfunc(upb_env *e, upb_error_func *func,
  1592. void *ud) {
  1593. e->err = func;
  1594. e->err_ud = ud;
  1595. }
  1596. void upb_env_reporterrorsto(upb_env *e, upb_status *status) {
  1597. e->err = write_err_to;
  1598. e->err_ud = status;
  1599. }
  1600. bool upb_env_ok(const upb_env *e) {
  1601. return e->ok_;
  1602. }
  1603. bool upb_env_reporterror(upb_env *e, const upb_status *status) {
  1604. e->ok_ = false;
  1605. return e->err(e->err_ud, status);
  1606. }
  1607. bool upb_env_addcleanup(upb_env *e, upb_cleanup_func *func, void *ud) {
  1608. cleanup_ent *ent = upb_env_malloc(e, sizeof(cleanup_ent));
  1609. if (!ent) return false;
  1610. ent->cleanup = func;
  1611. ent->ud = ud;
  1612. ent->next = e->cleanup_head;
  1613. e->cleanup_head = ent;
  1614. return true;
  1615. }
  1616. void *upb_env_malloc(upb_env *e, size_t size) {
  1617. e->bytes_allocated += size;
  1618. if (e->alloc == seeded_alloc) {
  1619. /* This is equivalent to the next branch, but allows inlining for a
  1620. * measurable perf benefit. */
  1621. return seeded_alloc(e->alloc_ud, NULL, 0, size);
  1622. } else {
  1623. return e->alloc(e->alloc_ud, NULL, 0, size);
  1624. }
  1625. }
  1626. void *upb_env_realloc(upb_env *e, void *ptr, size_t oldsize, size_t size) {
  1627. char *ret;
  1628. assert(oldsize <= size);
  1629. ret = e->alloc(e->alloc_ud, ptr, oldsize, size);
  1630. #ifndef NDEBUG
  1631. /* Overwrite non-preserved memory to ensure callers are passing the oldsize
  1632. * that they truly require. */
  1633. memset(ret + oldsize, 0xff, size - oldsize);
  1634. #endif
  1635. return ret;
  1636. }
  1637. size_t upb_env_bytesallocated(const upb_env *e) {
  1638. return e->bytes_allocated;
  1639. }
  1640. /* upb_seededalloc ************************************************************/
  1641. /* Be conservative and choose 16 in case anyone is using SSE. */
  1642. static const size_t maxalign = 16;
  1643. static size_t align_up(size_t size) {
  1644. return ((size + maxalign - 1) / maxalign) * maxalign;
  1645. }
  1646. UPB_FORCEINLINE static void *seeded_alloc(void *ud, void *ptr, size_t oldsize,
  1647. size_t size) {
  1648. upb_seededalloc *a = ud;
  1649. UPB_UNUSED(ptr);
  1650. size = align_up(size);
  1651. assert(a->mem_limit >= a->mem_ptr);
  1652. if (oldsize == 0 && size <= (size_t)(a->mem_limit - a->mem_ptr)) {
  1653. /* Fast path: we can satisfy from the initial allocation. */
  1654. void *ret = a->mem_ptr;
  1655. a->mem_ptr += size;
  1656. return ret;
  1657. } else {
  1658. char *chptr = ptr;
  1659. /* Slow path: fallback to other allocator. */
  1660. a->need_cleanup = true;
  1661. /* Is `ptr` part of the user-provided initial block? Don't pass it to the
  1662. * default allocator if so; otherwise, it may try to realloc() the block. */
  1663. if (chptr >= a->mem_base && chptr < a->mem_limit) {
  1664. return a->alloc(a->alloc_ud, NULL, 0, size);
  1665. } else {
  1666. return a->alloc(a->alloc_ud, ptr, oldsize, size);
  1667. }
  1668. }
  1669. }
  1670. void upb_seededalloc_init(upb_seededalloc *a, void *mem, size_t len) {
  1671. default_alloc_ud *ud = (default_alloc_ud*)&a->default_alloc_ud;
  1672. a->mem_base = mem;
  1673. a->mem_ptr = mem;
  1674. a->mem_limit = (char*)mem + len;
  1675. a->need_cleanup = false;
  1676. a->returned_allocfunc = false;
  1677. ud->head = NULL;
  1678. upb_seededalloc_setfallbackalloc(a, default_alloc, ud);
  1679. }
  1680. void upb_seededalloc_uninit(upb_seededalloc *a) {
  1681. if (a->alloc == default_alloc && a->need_cleanup) {
  1682. default_alloc_cleanup(a->alloc_ud);
  1683. }
  1684. }
  1685. UPB_FORCEINLINE void upb_seededalloc_setfallbackalloc(upb_seededalloc *a,
  1686. upb_alloc_func *alloc,
  1687. void *ud) {
  1688. assert(!a->returned_allocfunc);
  1689. a->alloc = alloc;
  1690. a->alloc_ud = ud;
  1691. }
  1692. upb_alloc_func *upb_seededalloc_getallocfunc(upb_seededalloc *a) {
  1693. a->returned_allocfunc = true;
  1694. return seeded_alloc;
  1695. }
  1696. /*
  1697. * upb - a minimalist implementation of protocol buffers.
  1698. *
  1699. * Copyright (c) 2011-2012 Google Inc. See LICENSE for details.
  1700. * Author: Josh Haberman <jhaberman@gmail.com>
  1701. *
  1702. * TODO(haberman): it's unclear whether a lot of the consistency checks should
  1703. * assert() or return false.
  1704. */
  1705. #include <stdlib.h>
  1706. #include <string.h>
  1707. /* Defined for the sole purpose of having a unique pointer value for
  1708. * UPB_NO_CLOSURE. */
  1709. char _upb_noclosure;
  1710. static void freehandlers(upb_refcounted *r) {
  1711. upb_handlers *h = (upb_handlers*)r;
  1712. upb_inttable_iter i;
  1713. upb_inttable_begin(&i, &h->cleanup_);
  1714. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  1715. void *val = (void*)upb_inttable_iter_key(&i);
  1716. upb_value func_val = upb_inttable_iter_value(&i);
  1717. upb_handlerfree *func = upb_value_getfptr(func_val);
  1718. func(val);
  1719. }
  1720. upb_inttable_uninit(&h->cleanup_);
  1721. upb_msgdef_unref(h->msg, h);
  1722. free(h->sub);
  1723. free(h);
  1724. }
  1725. static void visithandlers(const upb_refcounted *r, upb_refcounted_visit *visit,
  1726. void *closure) {
  1727. const upb_handlers *h = (const upb_handlers*)r;
  1728. upb_msg_field_iter i;
  1729. for(upb_msg_field_begin(&i, h->msg);
  1730. !upb_msg_field_done(&i);
  1731. upb_msg_field_next(&i)) {
  1732. upb_fielddef *f = upb_msg_iter_field(&i);
  1733. const upb_handlers *sub;
  1734. if (!upb_fielddef_issubmsg(f)) continue;
  1735. sub = upb_handlers_getsubhandlers(h, f);
  1736. if (sub) visit(r, upb_handlers_upcast(sub), closure);
  1737. }
  1738. }
  1739. static const struct upb_refcounted_vtbl vtbl = {visithandlers, freehandlers};
  1740. typedef struct {
  1741. upb_inttable tab; /* maps upb_msgdef* -> upb_handlers*. */
  1742. upb_handlers_callback *callback;
  1743. const void *closure;
  1744. } dfs_state;
  1745. /* TODO(haberman): discard upb_handlers* objects that do not actually have any
  1746. * handlers set and cannot reach any upb_handlers* object that does. This is
  1747. * slightly tricky to do correctly. */
  1748. static upb_handlers *newformsg(const upb_msgdef *m, const void *owner,
  1749. dfs_state *s) {
  1750. upb_msg_field_iter i;
  1751. upb_handlers *h = upb_handlers_new(m, owner);
  1752. if (!h) return NULL;
  1753. if (!upb_inttable_insertptr(&s->tab, m, upb_value_ptr(h))) goto oom;
  1754. s->callback(s->closure, h);
  1755. /* For each submessage field, get or create a handlers object and set it as
  1756. * the subhandlers. */
  1757. for(upb_msg_field_begin(&i, m);
  1758. !upb_msg_field_done(&i);
  1759. upb_msg_field_next(&i)) {
  1760. upb_fielddef *f = upb_msg_iter_field(&i);
  1761. const upb_msgdef *subdef;
  1762. upb_value subm_ent;
  1763. if (!upb_fielddef_issubmsg(f)) continue;
  1764. subdef = upb_downcast_msgdef(upb_fielddef_subdef(f));
  1765. if (upb_inttable_lookupptr(&s->tab, subdef, &subm_ent)) {
  1766. upb_handlers_setsubhandlers(h, f, upb_value_getptr(subm_ent));
  1767. } else {
  1768. upb_handlers *sub_mh = newformsg(subdef, &sub_mh, s);
  1769. if (!sub_mh) goto oom;
  1770. upb_handlers_setsubhandlers(h, f, sub_mh);
  1771. upb_handlers_unref(sub_mh, &sub_mh);
  1772. }
  1773. }
  1774. return h;
  1775. oom:
  1776. upb_handlers_unref(h, owner);
  1777. return NULL;
  1778. }
  1779. /* Given a selector for a STARTSUBMSG handler, resolves to a pointer to the
  1780. * subhandlers for this submessage field. */
  1781. #define SUBH(h, selector) (h->sub[selector])
  1782. /* The selector for a submessage field is the field index. */
  1783. #define SUBH_F(h, f) SUBH(h, f->index_)
  1784. static int32_t trygetsel(upb_handlers *h, const upb_fielddef *f,
  1785. upb_handlertype_t type) {
  1786. upb_selector_t sel;
  1787. assert(!upb_handlers_isfrozen(h));
  1788. if (upb_handlers_msgdef(h) != upb_fielddef_containingtype(f)) {
  1789. upb_status_seterrf(
  1790. &h->status_, "type mismatch: field %s does not belong to message %s",
  1791. upb_fielddef_name(f), upb_msgdef_fullname(upb_handlers_msgdef(h)));
  1792. return -1;
  1793. }
  1794. if (!upb_handlers_getselector(f, type, &sel)) {
  1795. upb_status_seterrf(
  1796. &h->status_,
  1797. "type mismatch: cannot register handler type %d for field %s",
  1798. type, upb_fielddef_name(f));
  1799. return -1;
  1800. }
  1801. return sel;
  1802. }
  1803. static upb_selector_t handlers_getsel(upb_handlers *h, const upb_fielddef *f,
  1804. upb_handlertype_t type) {
  1805. int32_t sel = trygetsel(h, f, type);
  1806. assert(sel >= 0);
  1807. return sel;
  1808. }
  1809. static const void **returntype(upb_handlers *h, const upb_fielddef *f,
  1810. upb_handlertype_t type) {
  1811. return &h->table[handlers_getsel(h, f, type)].attr.return_closure_type_;
  1812. }
  1813. static bool doset(upb_handlers *h, int32_t sel, const upb_fielddef *f,
  1814. upb_handlertype_t type, upb_func *func,
  1815. upb_handlerattr *attr) {
  1816. upb_handlerattr set_attr = UPB_HANDLERATTR_INITIALIZER;
  1817. const void *closure_type;
  1818. const void **context_closure_type;
  1819. assert(!upb_handlers_isfrozen(h));
  1820. if (sel < 0) {
  1821. upb_status_seterrmsg(&h->status_,
  1822. "incorrect handler type for this field.");
  1823. return false;
  1824. }
  1825. if (h->table[sel].func) {
  1826. upb_status_seterrmsg(&h->status_,
  1827. "cannot change handler once it has been set.");
  1828. return false;
  1829. }
  1830. if (attr) {
  1831. set_attr = *attr;
  1832. }
  1833. /* Check that the given closure type matches the closure type that has been
  1834. * established for this context (if any). */
  1835. closure_type = upb_handlerattr_closuretype(&set_attr);
  1836. if (type == UPB_HANDLER_STRING) {
  1837. context_closure_type = returntype(h, f, UPB_HANDLER_STARTSTR);
  1838. } else if (f && upb_fielddef_isseq(f) &&
  1839. type != UPB_HANDLER_STARTSEQ &&
  1840. type != UPB_HANDLER_ENDSEQ) {
  1841. context_closure_type = returntype(h, f, UPB_HANDLER_STARTSEQ);
  1842. } else {
  1843. context_closure_type = &h->top_closure_type;
  1844. }
  1845. if (closure_type && *context_closure_type &&
  1846. closure_type != *context_closure_type) {
  1847. /* TODO(haberman): better message for debugging. */
  1848. if (f) {
  1849. upb_status_seterrf(&h->status_,
  1850. "closure type does not match for field %s",
  1851. upb_fielddef_name(f));
  1852. } else {
  1853. upb_status_seterrmsg(
  1854. &h->status_, "closure type does not match for message-level handler");
  1855. }
  1856. return false;
  1857. }
  1858. if (closure_type)
  1859. *context_closure_type = closure_type;
  1860. /* If this is a STARTSEQ or STARTSTR handler, check that the returned pointer
  1861. * matches any pre-existing expectations about what type is expected. */
  1862. if (type == UPB_HANDLER_STARTSEQ || type == UPB_HANDLER_STARTSTR) {
  1863. const void *return_type = upb_handlerattr_returnclosuretype(&set_attr);
  1864. const void *table_return_type =
  1865. upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  1866. if (return_type && table_return_type && return_type != table_return_type) {
  1867. upb_status_seterrmsg(&h->status_, "closure return type does not match");
  1868. return false;
  1869. }
  1870. if (table_return_type && !return_type)
  1871. upb_handlerattr_setreturnclosuretype(&set_attr, table_return_type);
  1872. }
  1873. h->table[sel].func = (upb_func*)func;
  1874. h->table[sel].attr = set_attr;
  1875. return true;
  1876. }
  1877. /* Returns the effective closure type for this handler (which will propagate
  1878. * from outer frames if this frame has no START* handler). Not implemented for
  1879. * UPB_HANDLER_STRING at the moment since this is not needed. Returns NULL is
  1880. * the effective closure type is unspecified (either no handler was registered
  1881. * to specify it or the handler that was registered did not specify the closure
  1882. * type). */
  1883. const void *effective_closure_type(upb_handlers *h, const upb_fielddef *f,
  1884. upb_handlertype_t type) {
  1885. const void *ret;
  1886. upb_selector_t sel;
  1887. assert(type != UPB_HANDLER_STRING);
  1888. ret = h->top_closure_type;
  1889. if (upb_fielddef_isseq(f) &&
  1890. type != UPB_HANDLER_STARTSEQ &&
  1891. type != UPB_HANDLER_ENDSEQ &&
  1892. h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSEQ)].func) {
  1893. ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  1894. }
  1895. if (type == UPB_HANDLER_STRING &&
  1896. h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSTR)].func) {
  1897. ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  1898. }
  1899. /* The effective type of the submessage; not used yet.
  1900. * if (type == SUBMESSAGE &&
  1901. * h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSUBMSG)].func) {
  1902. * ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  1903. * } */
  1904. return ret;
  1905. }
  1906. /* Checks whether the START* handler specified by f & type is missing even
  1907. * though it is required to convert the established type of an outer frame
  1908. * ("closure_type") into the established type of an inner frame (represented in
  1909. * the return closure type of this handler's attr. */
  1910. bool checkstart(upb_handlers *h, const upb_fielddef *f, upb_handlertype_t type,
  1911. upb_status *status) {
  1912. const void *closure_type;
  1913. const upb_handlerattr *attr;
  1914. const void *return_closure_type;
  1915. upb_selector_t sel = handlers_getsel(h, f, type);
  1916. if (h->table[sel].func) return true;
  1917. closure_type = effective_closure_type(h, f, type);
  1918. attr = &h->table[sel].attr;
  1919. return_closure_type = upb_handlerattr_returnclosuretype(attr);
  1920. if (closure_type && return_closure_type &&
  1921. closure_type != return_closure_type) {
  1922. upb_status_seterrf(status,
  1923. "expected start handler to return sub type for field %f",
  1924. upb_fielddef_name(f));
  1925. return false;
  1926. }
  1927. return true;
  1928. }
  1929. /* Public interface ***********************************************************/
  1930. upb_handlers *upb_handlers_new(const upb_msgdef *md, const void *owner) {
  1931. int extra;
  1932. upb_handlers *h;
  1933. assert(upb_msgdef_isfrozen(md));
  1934. extra = sizeof(upb_handlers_tabent) * (md->selector_count - 1);
  1935. h = calloc(sizeof(*h) + extra, 1);
  1936. if (!h) return NULL;
  1937. h->msg = md;
  1938. upb_msgdef_ref(h->msg, h);
  1939. upb_status_clear(&h->status_);
  1940. h->sub = calloc(md->submsg_field_count, sizeof(*h->sub));
  1941. if (!h->sub) goto oom;
  1942. if (!upb_refcounted_init(upb_handlers_upcast_mutable(h), &vtbl, owner))
  1943. goto oom;
  1944. if (!upb_inttable_init(&h->cleanup_, UPB_CTYPE_FPTR)) goto oom;
  1945. /* calloc() above initialized all handlers to NULL. */
  1946. return h;
  1947. oom:
  1948. freehandlers(upb_handlers_upcast_mutable(h));
  1949. return NULL;
  1950. }
  1951. const upb_handlers *upb_handlers_newfrozen(const upb_msgdef *m,
  1952. const void *owner,
  1953. upb_handlers_callback *callback,
  1954. const void *closure) {
  1955. dfs_state state;
  1956. upb_handlers *ret;
  1957. bool ok;
  1958. upb_refcounted *r;
  1959. state.callback = callback;
  1960. state.closure = closure;
  1961. if (!upb_inttable_init(&state.tab, UPB_CTYPE_PTR)) return NULL;
  1962. ret = newformsg(m, owner, &state);
  1963. upb_inttable_uninit(&state.tab);
  1964. if (!ret) return NULL;
  1965. r = upb_handlers_upcast_mutable(ret);
  1966. ok = upb_refcounted_freeze(&r, 1, NULL, UPB_MAX_HANDLER_DEPTH);
  1967. UPB_ASSERT_VAR(ok, ok);
  1968. return ret;
  1969. }
  1970. const upb_status *upb_handlers_status(upb_handlers *h) {
  1971. assert(!upb_handlers_isfrozen(h));
  1972. return &h->status_;
  1973. }
  1974. void upb_handlers_clearerr(upb_handlers *h) {
  1975. assert(!upb_handlers_isfrozen(h));
  1976. upb_status_clear(&h->status_);
  1977. }
  1978. #define SETTER(name, handlerctype, handlertype) \
  1979. bool upb_handlers_set ## name(upb_handlers *h, const upb_fielddef *f, \
  1980. handlerctype func, upb_handlerattr *attr) { \
  1981. int32_t sel = trygetsel(h, f, handlertype); \
  1982. return doset(h, sel, f, handlertype, (upb_func*)func, attr); \
  1983. }
  1984. SETTER(int32, upb_int32_handlerfunc*, UPB_HANDLER_INT32)
  1985. SETTER(int64, upb_int64_handlerfunc*, UPB_HANDLER_INT64)
  1986. SETTER(uint32, upb_uint32_handlerfunc*, UPB_HANDLER_UINT32)
  1987. SETTER(uint64, upb_uint64_handlerfunc*, UPB_HANDLER_UINT64)
  1988. SETTER(float, upb_float_handlerfunc*, UPB_HANDLER_FLOAT)
  1989. SETTER(double, upb_double_handlerfunc*, UPB_HANDLER_DOUBLE)
  1990. SETTER(bool, upb_bool_handlerfunc*, UPB_HANDLER_BOOL)
  1991. SETTER(startstr, upb_startstr_handlerfunc*, UPB_HANDLER_STARTSTR)
  1992. SETTER(string, upb_string_handlerfunc*, UPB_HANDLER_STRING)
  1993. SETTER(endstr, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSTR)
  1994. SETTER(startseq, upb_startfield_handlerfunc*, UPB_HANDLER_STARTSEQ)
  1995. SETTER(startsubmsg, upb_startfield_handlerfunc*, UPB_HANDLER_STARTSUBMSG)
  1996. SETTER(endsubmsg, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSUBMSG)
  1997. SETTER(endseq, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSEQ)
  1998. #undef SETTER
  1999. bool upb_handlers_setstartmsg(upb_handlers *h, upb_startmsg_handlerfunc *func,
  2000. upb_handlerattr *attr) {
  2001. return doset(h, UPB_STARTMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
  2002. (upb_func *)func, attr);
  2003. }
  2004. bool upb_handlers_setendmsg(upb_handlers *h, upb_endmsg_handlerfunc *func,
  2005. upb_handlerattr *attr) {
  2006. assert(!upb_handlers_isfrozen(h));
  2007. return doset(h, UPB_ENDMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
  2008. (upb_func *)func, attr);
  2009. }
  2010. bool upb_handlers_setsubhandlers(upb_handlers *h, const upb_fielddef *f,
  2011. const upb_handlers *sub) {
  2012. assert(sub);
  2013. assert(!upb_handlers_isfrozen(h));
  2014. assert(upb_fielddef_issubmsg(f));
  2015. if (SUBH_F(h, f)) return false; /* Can't reset. */
  2016. if (upb_msgdef_upcast(upb_handlers_msgdef(sub)) != upb_fielddef_subdef(f)) {
  2017. return false;
  2018. }
  2019. SUBH_F(h, f) = sub;
  2020. upb_ref2(sub, h);
  2021. return true;
  2022. }
  2023. const upb_handlers *upb_handlers_getsubhandlers(const upb_handlers *h,
  2024. const upb_fielddef *f) {
  2025. assert(upb_fielddef_issubmsg(f));
  2026. return SUBH_F(h, f);
  2027. }
  2028. bool upb_handlers_getattr(const upb_handlers *h, upb_selector_t sel,
  2029. upb_handlerattr *attr) {
  2030. if (!upb_handlers_gethandler(h, sel))
  2031. return false;
  2032. *attr = h->table[sel].attr;
  2033. return true;
  2034. }
  2035. const upb_handlers *upb_handlers_getsubhandlers_sel(const upb_handlers *h,
  2036. upb_selector_t sel) {
  2037. /* STARTSUBMSG selector in sel is the field's selector base. */
  2038. return SUBH(h, sel - UPB_STATIC_SELECTOR_COUNT);
  2039. }
  2040. const upb_msgdef *upb_handlers_msgdef(const upb_handlers *h) { return h->msg; }
  2041. bool upb_handlers_addcleanup(upb_handlers *h, void *p, upb_handlerfree *func) {
  2042. bool ok;
  2043. if (upb_inttable_lookupptr(&h->cleanup_, p, NULL)) {
  2044. return false;
  2045. }
  2046. ok = upb_inttable_insertptr(&h->cleanup_, p, upb_value_fptr(func));
  2047. UPB_ASSERT_VAR(ok, ok);
  2048. return true;
  2049. }
  2050. /* "Static" methods ***********************************************************/
  2051. bool upb_handlers_freeze(upb_handlers *const*handlers, int n, upb_status *s) {
  2052. /* TODO: verify we have a transitive closure. */
  2053. int i;
  2054. for (i = 0; i < n; i++) {
  2055. upb_msg_field_iter j;
  2056. upb_handlers *h = handlers[i];
  2057. if (!upb_ok(&h->status_)) {
  2058. upb_status_seterrf(s, "handlers for message %s had error status: %s",
  2059. upb_msgdef_fullname(upb_handlers_msgdef(h)),
  2060. upb_status_errmsg(&h->status_));
  2061. return false;
  2062. }
  2063. /* Check that there are no closure mismatches due to missing Start* handlers
  2064. * or subhandlers with different type-level types. */
  2065. for(upb_msg_field_begin(&j, h->msg);
  2066. !upb_msg_field_done(&j);
  2067. upb_msg_field_next(&j)) {
  2068. const upb_fielddef *f = upb_msg_iter_field(&j);
  2069. if (upb_fielddef_isseq(f)) {
  2070. if (!checkstart(h, f, UPB_HANDLER_STARTSEQ, s))
  2071. return false;
  2072. }
  2073. if (upb_fielddef_isstring(f)) {
  2074. if (!checkstart(h, f, UPB_HANDLER_STARTSTR, s))
  2075. return false;
  2076. }
  2077. if (upb_fielddef_issubmsg(f)) {
  2078. bool hashandler = false;
  2079. if (upb_handlers_gethandler(
  2080. h, handlers_getsel(h, f, UPB_HANDLER_STARTSUBMSG)) ||
  2081. upb_handlers_gethandler(
  2082. h, handlers_getsel(h, f, UPB_HANDLER_ENDSUBMSG))) {
  2083. hashandler = true;
  2084. }
  2085. if (upb_fielddef_isseq(f) &&
  2086. (upb_handlers_gethandler(
  2087. h, handlers_getsel(h, f, UPB_HANDLER_STARTSEQ)) ||
  2088. upb_handlers_gethandler(
  2089. h, handlers_getsel(h, f, UPB_HANDLER_ENDSEQ)))) {
  2090. hashandler = true;
  2091. }
  2092. if (hashandler && !upb_handlers_getsubhandlers(h, f)) {
  2093. /* For now we add an empty subhandlers in this case. It makes the
  2094. * decoder code generator simpler, because it only has to handle two
  2095. * cases (submessage has handlers or not) as opposed to three
  2096. * (submessage has handlers in enclosing message but no subhandlers).
  2097. *
  2098. * This makes parsing less efficient in the case that we want to
  2099. * notice a submessage but skip its contents (like if we're testing
  2100. * for submessage presence or counting the number of repeated
  2101. * submessages). In this case we will end up parsing the submessage
  2102. * field by field and throwing away the results for each, instead of
  2103. * skipping the whole delimited thing at once. If this is an issue we
  2104. * can revisit it, but do remember that this only arises when you have
  2105. * handlers (startseq/startsubmsg/endsubmsg/endseq) set for the
  2106. * submessage but no subhandlers. The uses cases for this are
  2107. * limited. */
  2108. upb_handlers *sub = upb_handlers_new(upb_fielddef_msgsubdef(f), &sub);
  2109. upb_handlers_setsubhandlers(h, f, sub);
  2110. upb_handlers_unref(sub, &sub);
  2111. }
  2112. /* TODO(haberman): check type of submessage.
  2113. * This is slightly tricky; also consider whether we should check that
  2114. * they match at setsubhandlers time. */
  2115. }
  2116. }
  2117. }
  2118. if (!upb_refcounted_freeze((upb_refcounted*const*)handlers, n, s,
  2119. UPB_MAX_HANDLER_DEPTH)) {
  2120. return false;
  2121. }
  2122. return true;
  2123. }
  2124. upb_handlertype_t upb_handlers_getprimitivehandlertype(const upb_fielddef *f) {
  2125. switch (upb_fielddef_type(f)) {
  2126. case UPB_TYPE_INT32:
  2127. case UPB_TYPE_ENUM: return UPB_HANDLER_INT32;
  2128. case UPB_TYPE_INT64: return UPB_HANDLER_INT64;
  2129. case UPB_TYPE_UINT32: return UPB_HANDLER_UINT32;
  2130. case UPB_TYPE_UINT64: return UPB_HANDLER_UINT64;
  2131. case UPB_TYPE_FLOAT: return UPB_HANDLER_FLOAT;
  2132. case UPB_TYPE_DOUBLE: return UPB_HANDLER_DOUBLE;
  2133. case UPB_TYPE_BOOL: return UPB_HANDLER_BOOL;
  2134. default: assert(false); return -1; /* Invalid input. */
  2135. }
  2136. }
  2137. bool upb_handlers_getselector(const upb_fielddef *f, upb_handlertype_t type,
  2138. upb_selector_t *s) {
  2139. switch (type) {
  2140. case UPB_HANDLER_INT32:
  2141. case UPB_HANDLER_INT64:
  2142. case UPB_HANDLER_UINT32:
  2143. case UPB_HANDLER_UINT64:
  2144. case UPB_HANDLER_FLOAT:
  2145. case UPB_HANDLER_DOUBLE:
  2146. case UPB_HANDLER_BOOL:
  2147. if (!upb_fielddef_isprimitive(f) ||
  2148. upb_handlers_getprimitivehandlertype(f) != type)
  2149. return false;
  2150. *s = f->selector_base;
  2151. break;
  2152. case UPB_HANDLER_STRING:
  2153. if (upb_fielddef_isstring(f)) {
  2154. *s = f->selector_base;
  2155. } else if (upb_fielddef_lazy(f)) {
  2156. *s = f->selector_base + 3;
  2157. } else {
  2158. return false;
  2159. }
  2160. break;
  2161. case UPB_HANDLER_STARTSTR:
  2162. if (upb_fielddef_isstring(f) || upb_fielddef_lazy(f)) {
  2163. *s = f->selector_base + 1;
  2164. } else {
  2165. return false;
  2166. }
  2167. break;
  2168. case UPB_HANDLER_ENDSTR:
  2169. if (upb_fielddef_isstring(f) || upb_fielddef_lazy(f)) {
  2170. *s = f->selector_base + 2;
  2171. } else {
  2172. return false;
  2173. }
  2174. break;
  2175. case UPB_HANDLER_STARTSEQ:
  2176. if (!upb_fielddef_isseq(f)) return false;
  2177. *s = f->selector_base - 2;
  2178. break;
  2179. case UPB_HANDLER_ENDSEQ:
  2180. if (!upb_fielddef_isseq(f)) return false;
  2181. *s = f->selector_base - 1;
  2182. break;
  2183. case UPB_HANDLER_STARTSUBMSG:
  2184. if (!upb_fielddef_issubmsg(f)) return false;
  2185. /* Selectors for STARTSUBMSG are at the beginning of the table so that the
  2186. * selector can also be used as an index into the "sub" array of
  2187. * subhandlers. The indexes for the two into these two tables are the
  2188. * same, except that in the handler table the static selectors come first. */
  2189. *s = f->index_ + UPB_STATIC_SELECTOR_COUNT;
  2190. break;
  2191. case UPB_HANDLER_ENDSUBMSG:
  2192. if (!upb_fielddef_issubmsg(f)) return false;
  2193. *s = f->selector_base;
  2194. break;
  2195. }
  2196. assert((size_t)*s < upb_fielddef_containingtype(f)->selector_count);
  2197. return true;
  2198. }
  2199. uint32_t upb_handlers_selectorbaseoffset(const upb_fielddef *f) {
  2200. return upb_fielddef_isseq(f) ? 2 : 0;
  2201. }
  2202. uint32_t upb_handlers_selectorcount(const upb_fielddef *f) {
  2203. uint32_t ret = 1;
  2204. if (upb_fielddef_isseq(f)) ret += 2; /* STARTSEQ/ENDSEQ */
  2205. if (upb_fielddef_isstring(f)) ret += 2; /* [STRING]/STARTSTR/ENDSTR */
  2206. if (upb_fielddef_issubmsg(f)) {
  2207. /* ENDSUBMSG (STARTSUBMSG is at table beginning) */
  2208. ret += 0;
  2209. if (upb_fielddef_lazy(f)) {
  2210. /* STARTSTR/ENDSTR/STRING (for lazy) */
  2211. ret += 3;
  2212. }
  2213. }
  2214. return ret;
  2215. }
  2216. /* upb_handlerattr ************************************************************/
  2217. void upb_handlerattr_init(upb_handlerattr *attr) {
  2218. upb_handlerattr from = UPB_HANDLERATTR_INITIALIZER;
  2219. memcpy(attr, &from, sizeof(*attr));
  2220. }
  2221. void upb_handlerattr_uninit(upb_handlerattr *attr) {
  2222. UPB_UNUSED(attr);
  2223. }
  2224. bool upb_handlerattr_sethandlerdata(upb_handlerattr *attr, const void *hd) {
  2225. attr->handler_data_ = hd;
  2226. return true;
  2227. }
  2228. bool upb_handlerattr_setclosuretype(upb_handlerattr *attr, const void *type) {
  2229. attr->closure_type_ = type;
  2230. return true;
  2231. }
  2232. const void *upb_handlerattr_closuretype(const upb_handlerattr *attr) {
  2233. return attr->closure_type_;
  2234. }
  2235. bool upb_handlerattr_setreturnclosuretype(upb_handlerattr *attr,
  2236. const void *type) {
  2237. attr->return_closure_type_ = type;
  2238. return true;
  2239. }
  2240. const void *upb_handlerattr_returnclosuretype(const upb_handlerattr *attr) {
  2241. return attr->return_closure_type_;
  2242. }
  2243. bool upb_handlerattr_setalwaysok(upb_handlerattr *attr, bool alwaysok) {
  2244. attr->alwaysok_ = alwaysok;
  2245. return true;
  2246. }
  2247. bool upb_handlerattr_alwaysok(const upb_handlerattr *attr) {
  2248. return attr->alwaysok_;
  2249. }
  2250. /* upb_bufhandle **************************************************************/
  2251. size_t upb_bufhandle_objofs(const upb_bufhandle *h) {
  2252. return h->objofs_;
  2253. }
  2254. /* upb_byteshandler ***********************************************************/
  2255. void upb_byteshandler_init(upb_byteshandler* h) {
  2256. memset(h, 0, sizeof(*h));
  2257. }
  2258. /* For when we support handlerfree callbacks. */
  2259. void upb_byteshandler_uninit(upb_byteshandler* h) {
  2260. UPB_UNUSED(h);
  2261. }
  2262. bool upb_byteshandler_setstartstr(upb_byteshandler *h,
  2263. upb_startstr_handlerfunc *func, void *d) {
  2264. h->table[UPB_STARTSTR_SELECTOR].func = (upb_func*)func;
  2265. h->table[UPB_STARTSTR_SELECTOR].attr.handler_data_ = d;
  2266. return true;
  2267. }
  2268. bool upb_byteshandler_setstring(upb_byteshandler *h,
  2269. upb_string_handlerfunc *func, void *d) {
  2270. h->table[UPB_STRING_SELECTOR].func = (upb_func*)func;
  2271. h->table[UPB_STRING_SELECTOR].attr.handler_data_ = d;
  2272. return true;
  2273. }
  2274. bool upb_byteshandler_setendstr(upb_byteshandler *h,
  2275. upb_endfield_handlerfunc *func, void *d) {
  2276. h->table[UPB_ENDSTR_SELECTOR].func = (upb_func*)func;
  2277. h->table[UPB_ENDSTR_SELECTOR].attr.handler_data_ = d;
  2278. return true;
  2279. }
  2280. /*
  2281. * upb - a minimalist implementation of protocol buffers.
  2282. *
  2283. * Copyright (c) 2012 Google Inc. See LICENSE for details.
  2284. * Author: Josh Haberman <jhaberman@gmail.com>
  2285. *
  2286. * Our key invariants are:
  2287. * 1. reference cycles never span groups
  2288. * 2. for ref2(to, from), we increment to's count iff group(from) != group(to)
  2289. *
  2290. * The previous two are how we avoid leaking cycles. Other important
  2291. * invariants are:
  2292. * 3. for mutable objects "from" and "to", if there exists a ref2(to, from)
  2293. * this implies group(from) == group(to). (In practice, what we implement
  2294. * is even stronger; "from" and "to" will share a group if there has *ever*
  2295. * been a ref2(to, from), but all that is necessary for correctness is the
  2296. * weaker one).
  2297. * 4. mutable and immutable objects are never in the same group.
  2298. */
  2299. #include <setjmp.h>
  2300. #include <stdlib.h>
  2301. static void freeobj(upb_refcounted *o);
  2302. const char untracked_val;
  2303. const void *UPB_UNTRACKED_REF = &untracked_val;
  2304. /* arch-specific atomic primitives *******************************************/
  2305. #ifdef UPB_THREAD_UNSAFE /*---------------------------------------------------*/
  2306. static void atomic_inc(uint32_t *a) { (*a)++; }
  2307. static bool atomic_dec(uint32_t *a) { return --(*a) == 0; }
  2308. #elif defined(__GNUC__) || defined(__clang__) /*------------------------------*/
  2309. static void atomic_inc(uint32_t *a) { __sync_fetch_and_add(a, 1); }
  2310. static bool atomic_dec(uint32_t *a) { return __sync_sub_and_fetch(a, 1) == 0; }
  2311. #elif defined(WIN32) /*-------------------------------------------------------*/
  2312. #include <Windows.h>
  2313. static void atomic_inc(upb_atomic_t *a) { InterlockedIncrement(&a->val); }
  2314. static bool atomic_dec(upb_atomic_t *a) {
  2315. return InterlockedDecrement(&a->val) == 0;
  2316. }
  2317. #else
  2318. #error Atomic primitives not defined for your platform/CPU. \
  2319. Implement them or compile with UPB_THREAD_UNSAFE.
  2320. #endif
  2321. /* All static objects point to this refcount.
  2322. * It is special-cased in ref/unref below. */
  2323. uint32_t static_refcount = -1;
  2324. /* We can avoid atomic ops for statically-declared objects.
  2325. * This is a minor optimization but nice since we can avoid degrading under
  2326. * contention in this case. */
  2327. static void refgroup(uint32_t *group) {
  2328. if (group != &static_refcount)
  2329. atomic_inc(group);
  2330. }
  2331. static bool unrefgroup(uint32_t *group) {
  2332. if (group == &static_refcount) {
  2333. return false;
  2334. } else {
  2335. return atomic_dec(group);
  2336. }
  2337. }
  2338. /* Reference tracking (debug only) ********************************************/
  2339. #ifdef UPB_DEBUG_REFS
  2340. #ifdef UPB_THREAD_UNSAFE
  2341. static void upb_lock() {}
  2342. static void upb_unlock() {}
  2343. #else
  2344. /* User must define functions that lock/unlock a global mutex and link this
  2345. * file against them. */
  2346. void upb_lock();
  2347. void upb_unlock();
  2348. #endif
  2349. /* UPB_DEBUG_REFS mode counts on being able to malloc() memory in some
  2350. * code-paths that can normally never fail, like upb_refcounted_ref(). Since
  2351. * we have no way to propagage out-of-memory errors back to the user, and since
  2352. * these errors can only occur in UPB_DEBUG_REFS mode, we immediately fail. */
  2353. #define CHECK_OOM(predicate) if (!(predicate)) { assert(predicate); exit(1); }
  2354. typedef struct {
  2355. int count; /* How many refs there are (duplicates only allowed for ref2). */
  2356. bool is_ref2;
  2357. } trackedref;
  2358. static trackedref *trackedref_new(bool is_ref2) {
  2359. trackedref *ret = malloc(sizeof(*ret));
  2360. CHECK_OOM(ret);
  2361. ret->count = 1;
  2362. ret->is_ref2 = is_ref2;
  2363. return ret;
  2364. }
  2365. static void track(const upb_refcounted *r, const void *owner, bool ref2) {
  2366. upb_value v;
  2367. assert(owner);
  2368. if (owner == UPB_UNTRACKED_REF) return;
  2369. upb_lock();
  2370. if (upb_inttable_lookupptr(r->refs, owner, &v)) {
  2371. trackedref *ref = upb_value_getptr(v);
  2372. /* Since we allow multiple ref2's for the same to/from pair without
  2373. * allocating separate memory for each one, we lose the fine-grained
  2374. * tracking behavior we get with regular refs. Since ref2s only happen
  2375. * inside upb, we'll accept this limitation until/unless there is a really
  2376. * difficult upb-internal bug that can't be figured out without it. */
  2377. assert(ref2);
  2378. assert(ref->is_ref2);
  2379. ref->count++;
  2380. } else {
  2381. trackedref *ref = trackedref_new(ref2);
  2382. bool ok = upb_inttable_insertptr(r->refs, owner, upb_value_ptr(ref));
  2383. CHECK_OOM(ok);
  2384. if (ref2) {
  2385. /* We know this cast is safe when it is a ref2, because it's coming from
  2386. * another refcounted object. */
  2387. const upb_refcounted *from = owner;
  2388. assert(!upb_inttable_lookupptr(from->ref2s, r, NULL));
  2389. ok = upb_inttable_insertptr(from->ref2s, r, upb_value_ptr(NULL));
  2390. CHECK_OOM(ok);
  2391. }
  2392. }
  2393. upb_unlock();
  2394. }
  2395. static void untrack(const upb_refcounted *r, const void *owner, bool ref2) {
  2396. upb_value v;
  2397. bool found;
  2398. trackedref *ref;
  2399. assert(owner);
  2400. if (owner == UPB_UNTRACKED_REF) return;
  2401. upb_lock();
  2402. found = upb_inttable_lookupptr(r->refs, owner, &v);
  2403. /* This assert will fail if an owner attempts to release a ref it didn't have. */
  2404. UPB_ASSERT_VAR(found, found);
  2405. ref = upb_value_getptr(v);
  2406. assert(ref->is_ref2 == ref2);
  2407. if (--ref->count == 0) {
  2408. free(ref);
  2409. upb_inttable_removeptr(r->refs, owner, NULL);
  2410. if (ref2) {
  2411. /* We know this cast is safe when it is a ref2, because it's coming from
  2412. * another refcounted object. */
  2413. const upb_refcounted *from = owner;
  2414. bool removed = upb_inttable_removeptr(from->ref2s, r, NULL);
  2415. assert(removed);
  2416. }
  2417. }
  2418. upb_unlock();
  2419. }
  2420. static void checkref(const upb_refcounted *r, const void *owner, bool ref2) {
  2421. upb_value v;
  2422. bool found;
  2423. trackedref *ref;
  2424. upb_lock();
  2425. found = upb_inttable_lookupptr(r->refs, owner, &v);
  2426. UPB_ASSERT_VAR(found, found);
  2427. ref = upb_value_getptr(v);
  2428. assert(ref->is_ref2 == ref2);
  2429. upb_unlock();
  2430. }
  2431. /* Populates the given UPB_CTYPE_INT32 inttable with counts of ref2's that
  2432. * originate from the given owner. */
  2433. static void getref2s(const upb_refcounted *owner, upb_inttable *tab) {
  2434. upb_inttable_iter i;
  2435. upb_lock();
  2436. upb_inttable_begin(&i, owner->ref2s);
  2437. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  2438. upb_value v;
  2439. upb_value count;
  2440. trackedref *ref;
  2441. bool ok;
  2442. bool found;
  2443. upb_refcounted *to = (upb_refcounted*)upb_inttable_iter_key(&i);
  2444. /* To get the count we need to look in the target's table. */
  2445. found = upb_inttable_lookupptr(to->refs, owner, &v);
  2446. assert(found);
  2447. ref = upb_value_getptr(v);
  2448. count = upb_value_int32(ref->count);
  2449. ok = upb_inttable_insertptr(tab, to, count);
  2450. CHECK_OOM(ok);
  2451. }
  2452. upb_unlock();
  2453. }
  2454. typedef struct {
  2455. upb_inttable ref2;
  2456. const upb_refcounted *obj;
  2457. } check_state;
  2458. static void visit_check(const upb_refcounted *obj, const upb_refcounted *subobj,
  2459. void *closure) {
  2460. check_state *s = closure;
  2461. upb_inttable *ref2 = &s->ref2;
  2462. upb_value v;
  2463. bool removed;
  2464. int32_t newcount;
  2465. assert(obj == s->obj);
  2466. assert(subobj);
  2467. removed = upb_inttable_removeptr(ref2, subobj, &v);
  2468. /* The following assertion will fail if the visit() function visits a subobj
  2469. * that it did not have a ref2 on, or visits the same subobj too many times. */
  2470. assert(removed);
  2471. newcount = upb_value_getint32(v) - 1;
  2472. if (newcount > 0) {
  2473. upb_inttable_insert(ref2, (uintptr_t)subobj, upb_value_int32(newcount));
  2474. }
  2475. }
  2476. static void visit(const upb_refcounted *r, upb_refcounted_visit *v,
  2477. void *closure) {
  2478. bool ok;
  2479. /* In DEBUG_REFS mode we know what existing ref2 refs there are, so we know
  2480. * exactly the set of nodes that visit() should visit. So we verify visit()'s
  2481. * correctness here. */
  2482. check_state state;
  2483. state.obj = r;
  2484. ok = upb_inttable_init(&state.ref2, UPB_CTYPE_INT32);
  2485. CHECK_OOM(ok);
  2486. getref2s(r, &state.ref2);
  2487. /* This should visit any children in the ref2 table. */
  2488. if (r->vtbl->visit) r->vtbl->visit(r, visit_check, &state);
  2489. /* This assertion will fail if the visit() function missed any children. */
  2490. assert(upb_inttable_count(&state.ref2) == 0);
  2491. upb_inttable_uninit(&state.ref2);
  2492. if (r->vtbl->visit) r->vtbl->visit(r, v, closure);
  2493. }
  2494. static bool trackinit(upb_refcounted *r) {
  2495. r->refs = malloc(sizeof(*r->refs));
  2496. r->ref2s = malloc(sizeof(*r->ref2s));
  2497. if (!r->refs || !r->ref2s) goto err1;
  2498. if (!upb_inttable_init(r->refs, UPB_CTYPE_PTR)) goto err1;
  2499. if (!upb_inttable_init(r->ref2s, UPB_CTYPE_PTR)) goto err2;
  2500. return true;
  2501. err2:
  2502. upb_inttable_uninit(r->refs);
  2503. err1:
  2504. free(r->refs);
  2505. free(r->ref2s);
  2506. return false;
  2507. }
  2508. static void trackfree(const upb_refcounted *r) {
  2509. upb_inttable_uninit(r->refs);
  2510. upb_inttable_uninit(r->ref2s);
  2511. free(r->refs);
  2512. free(r->ref2s);
  2513. }
  2514. #else
  2515. static void track(const upb_refcounted *r, const void *owner, bool ref2) {
  2516. UPB_UNUSED(r);
  2517. UPB_UNUSED(owner);
  2518. UPB_UNUSED(ref2);
  2519. }
  2520. static void untrack(const upb_refcounted *r, const void *owner, bool ref2) {
  2521. UPB_UNUSED(r);
  2522. UPB_UNUSED(owner);
  2523. UPB_UNUSED(ref2);
  2524. }
  2525. static void checkref(const upb_refcounted *r, const void *owner, bool ref2) {
  2526. UPB_UNUSED(r);
  2527. UPB_UNUSED(owner);
  2528. UPB_UNUSED(ref2);
  2529. }
  2530. static bool trackinit(upb_refcounted *r) {
  2531. UPB_UNUSED(r);
  2532. return true;
  2533. }
  2534. static void trackfree(const upb_refcounted *r) {
  2535. UPB_UNUSED(r);
  2536. }
  2537. static void visit(const upb_refcounted *r, upb_refcounted_visit *v,
  2538. void *closure) {
  2539. if (r->vtbl->visit) r->vtbl->visit(r, v, closure);
  2540. }
  2541. #endif /* UPB_DEBUG_REFS */
  2542. /* freeze() *******************************************************************/
  2543. /* The freeze() operation is by far the most complicated part of this scheme.
  2544. * We compute strongly-connected components and then mutate the graph such that
  2545. * we preserve the invariants documented at the top of this file. And we must
  2546. * handle out-of-memory errors gracefully (without leaving the graph
  2547. * inconsistent), which adds to the fun. */
  2548. /* The state used by the freeze operation (shared across many functions). */
  2549. typedef struct {
  2550. int depth;
  2551. int maxdepth;
  2552. uint64_t index;
  2553. /* Maps upb_refcounted* -> attributes (color, etc). attr layout varies by
  2554. * color. */
  2555. upb_inttable objattr;
  2556. upb_inttable stack; /* stack of upb_refcounted* for Tarjan's algorithm. */
  2557. upb_inttable groups; /* array of uint32_t*, malloc'd refcounts for new groups */
  2558. upb_status *status;
  2559. jmp_buf err;
  2560. } tarjan;
  2561. static void release_ref2(const upb_refcounted *obj,
  2562. const upb_refcounted *subobj,
  2563. void *closure);
  2564. /* Node attributes -----------------------------------------------------------*/
  2565. /* After our analysis phase all nodes will be either GRAY or WHITE. */
  2566. typedef enum {
  2567. BLACK = 0, /* Object has not been seen. */
  2568. GRAY, /* Object has been found via a refgroup but may not be reachable. */
  2569. GREEN, /* Object is reachable and is currently on the Tarjan stack. */
  2570. WHITE /* Object is reachable and has been assigned a group (SCC). */
  2571. } color_t;
  2572. UPB_NORETURN static void err(tarjan *t) { longjmp(t->err, 1); }
  2573. UPB_NORETURN static void oom(tarjan *t) {
  2574. upb_status_seterrmsg(t->status, "out of memory");
  2575. err(t);
  2576. }
  2577. static uint64_t trygetattr(const tarjan *t, const upb_refcounted *r) {
  2578. upb_value v;
  2579. return upb_inttable_lookupptr(&t->objattr, r, &v) ?
  2580. upb_value_getuint64(v) : 0;
  2581. }
  2582. static uint64_t getattr(const tarjan *t, const upb_refcounted *r) {
  2583. upb_value v;
  2584. bool found = upb_inttable_lookupptr(&t->objattr, r, &v);
  2585. UPB_ASSERT_VAR(found, found);
  2586. return upb_value_getuint64(v);
  2587. }
  2588. static void setattr(tarjan *t, const upb_refcounted *r, uint64_t attr) {
  2589. upb_inttable_removeptr(&t->objattr, r, NULL);
  2590. upb_inttable_insertptr(&t->objattr, r, upb_value_uint64(attr));
  2591. }
  2592. static color_t color(tarjan *t, const upb_refcounted *r) {
  2593. return trygetattr(t, r) & 0x3; /* Color is always stored in the low 2 bits. */
  2594. }
  2595. static void set_gray(tarjan *t, const upb_refcounted *r) {
  2596. assert(color(t, r) == BLACK);
  2597. setattr(t, r, GRAY);
  2598. }
  2599. /* Pushes an obj onto the Tarjan stack and sets it to GREEN. */
  2600. static void push(tarjan *t, const upb_refcounted *r) {
  2601. assert(color(t, r) == BLACK || color(t, r) == GRAY);
  2602. /* This defines the attr layout for the GREEN state. "index" and "lowlink"
  2603. * get 31 bits, which is plenty (limit of 2B objects frozen at a time). */
  2604. setattr(t, r, GREEN | (t->index << 2) | (t->index << 33));
  2605. if (++t->index == 0x80000000) {
  2606. upb_status_seterrmsg(t->status, "too many objects to freeze");
  2607. err(t);
  2608. }
  2609. upb_inttable_push(&t->stack, upb_value_ptr((void*)r));
  2610. }
  2611. /* Pops an obj from the Tarjan stack and sets it to WHITE, with a ptr to its
  2612. * SCC group. */
  2613. static upb_refcounted *pop(tarjan *t) {
  2614. upb_refcounted *r = upb_value_getptr(upb_inttable_pop(&t->stack));
  2615. assert(color(t, r) == GREEN);
  2616. /* This defines the attr layout for nodes in the WHITE state.
  2617. * Top of group stack is [group, NULL]; we point at group. */
  2618. setattr(t, r, WHITE | (upb_inttable_count(&t->groups) - 2) << 8);
  2619. return r;
  2620. }
  2621. static void tarjan_newgroup(tarjan *t) {
  2622. uint32_t *group = malloc(sizeof(*group));
  2623. if (!group) oom(t);
  2624. /* Push group and empty group leader (we'll fill in leader later). */
  2625. if (!upb_inttable_push(&t->groups, upb_value_ptr(group)) ||
  2626. !upb_inttable_push(&t->groups, upb_value_ptr(NULL))) {
  2627. free(group);
  2628. oom(t);
  2629. }
  2630. *group = 0;
  2631. }
  2632. static uint32_t idx(tarjan *t, const upb_refcounted *r) {
  2633. assert(color(t, r) == GREEN);
  2634. return (getattr(t, r) >> 2) & 0x7FFFFFFF;
  2635. }
  2636. static uint32_t lowlink(tarjan *t, const upb_refcounted *r) {
  2637. if (color(t, r) == GREEN) {
  2638. return getattr(t, r) >> 33;
  2639. } else {
  2640. return UINT32_MAX;
  2641. }
  2642. }
  2643. static void set_lowlink(tarjan *t, const upb_refcounted *r, uint32_t lowlink) {
  2644. assert(color(t, r) == GREEN);
  2645. setattr(t, r, ((uint64_t)lowlink << 33) | (getattr(t, r) & 0x1FFFFFFFF));
  2646. }
  2647. static uint32_t *group(tarjan *t, upb_refcounted *r) {
  2648. uint64_t groupnum;
  2649. upb_value v;
  2650. bool found;
  2651. assert(color(t, r) == WHITE);
  2652. groupnum = getattr(t, r) >> 8;
  2653. found = upb_inttable_lookup(&t->groups, groupnum, &v);
  2654. UPB_ASSERT_VAR(found, found);
  2655. return upb_value_getptr(v);
  2656. }
  2657. /* If the group leader for this object's group has not previously been set,
  2658. * the given object is assigned to be its leader. */
  2659. static upb_refcounted *groupleader(tarjan *t, upb_refcounted *r) {
  2660. uint64_t leader_slot;
  2661. upb_value v;
  2662. bool found;
  2663. assert(color(t, r) == WHITE);
  2664. leader_slot = (getattr(t, r) >> 8) + 1;
  2665. found = upb_inttable_lookup(&t->groups, leader_slot, &v);
  2666. UPB_ASSERT_VAR(found, found);
  2667. if (upb_value_getptr(v)) {
  2668. return upb_value_getptr(v);
  2669. } else {
  2670. upb_inttable_remove(&t->groups, leader_slot, NULL);
  2671. upb_inttable_insert(&t->groups, leader_slot, upb_value_ptr(r));
  2672. return r;
  2673. }
  2674. }
  2675. /* Tarjan's algorithm --------------------------------------------------------*/
  2676. /* See:
  2677. * http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm */
  2678. static void do_tarjan(const upb_refcounted *obj, tarjan *t);
  2679. static void tarjan_visit(const upb_refcounted *obj,
  2680. const upb_refcounted *subobj,
  2681. void *closure) {
  2682. tarjan *t = closure;
  2683. if (++t->depth > t->maxdepth) {
  2684. upb_status_seterrf(t->status, "graph too deep to freeze (%d)", t->maxdepth);
  2685. err(t);
  2686. } else if (subobj->is_frozen || color(t, subobj) == WHITE) {
  2687. /* Do nothing: we don't want to visit or color already-frozen nodes,
  2688. * and WHITE nodes have already been assigned a SCC. */
  2689. } else if (color(t, subobj) < GREEN) {
  2690. /* Subdef has not yet been visited; recurse on it. */
  2691. do_tarjan(subobj, t);
  2692. set_lowlink(t, obj, UPB_MIN(lowlink(t, obj), lowlink(t, subobj)));
  2693. } else if (color(t, subobj) == GREEN) {
  2694. /* Subdef is in the stack and hence in the current SCC. */
  2695. set_lowlink(t, obj, UPB_MIN(lowlink(t, obj), idx(t, subobj)));
  2696. }
  2697. --t->depth;
  2698. }
  2699. static void do_tarjan(const upb_refcounted *obj, tarjan *t) {
  2700. if (color(t, obj) == BLACK) {
  2701. /* We haven't seen this object's group; mark the whole group GRAY. */
  2702. const upb_refcounted *o = obj;
  2703. do { set_gray(t, o); } while ((o = o->next) != obj);
  2704. }
  2705. push(t, obj);
  2706. visit(obj, tarjan_visit, t);
  2707. if (lowlink(t, obj) == idx(t, obj)) {
  2708. tarjan_newgroup(t);
  2709. while (pop(t) != obj)
  2710. ;
  2711. }
  2712. }
  2713. /* freeze() ------------------------------------------------------------------*/
  2714. static void crossref(const upb_refcounted *r, const upb_refcounted *subobj,
  2715. void *_t) {
  2716. tarjan *t = _t;
  2717. assert(color(t, r) > BLACK);
  2718. if (color(t, subobj) > BLACK && r->group != subobj->group) {
  2719. /* Previously this ref was not reflected in subobj->group because they
  2720. * were in the same group; now that they are split a ref must be taken. */
  2721. refgroup(subobj->group);
  2722. }
  2723. }
  2724. static bool freeze(upb_refcounted *const*roots, int n, upb_status *s,
  2725. int maxdepth) {
  2726. volatile bool ret = false;
  2727. int i;
  2728. upb_inttable_iter iter;
  2729. /* We run in two passes so that we can allocate all memory before performing
  2730. * any mutation of the input -- this allows us to leave the input unchanged
  2731. * in the case of memory allocation failure. */
  2732. tarjan t;
  2733. t.index = 0;
  2734. t.depth = 0;
  2735. t.maxdepth = maxdepth;
  2736. t.status = s;
  2737. if (!upb_inttable_init(&t.objattr, UPB_CTYPE_UINT64)) goto err1;
  2738. if (!upb_inttable_init(&t.stack, UPB_CTYPE_PTR)) goto err2;
  2739. if (!upb_inttable_init(&t.groups, UPB_CTYPE_PTR)) goto err3;
  2740. if (setjmp(t.err) != 0) goto err4;
  2741. for (i = 0; i < n; i++) {
  2742. if (color(&t, roots[i]) < GREEN) {
  2743. do_tarjan(roots[i], &t);
  2744. }
  2745. }
  2746. /* If we've made it this far, no further errors are possible so it's safe to
  2747. * mutate the objects without risk of leaving them in an inconsistent state. */
  2748. ret = true;
  2749. /* The transformation that follows requires care. The preconditions are:
  2750. * - all objects in attr map are WHITE or GRAY, and are in mutable groups
  2751. * (groups of all mutable objs)
  2752. * - no ref2(to, from) refs have incremented count(to) if both "to" and
  2753. * "from" are in our attr map (this follows from invariants (2) and (3)) */
  2754. /* Pass 1: we remove WHITE objects from their mutable groups, and add them to
  2755. * new groups according to the SCC's we computed. These new groups will
  2756. * consist of only frozen objects. None will be immediately collectible,
  2757. * because WHITE objects are by definition reachable from one of "roots",
  2758. * which the caller must own refs on. */
  2759. upb_inttable_begin(&iter, &t.objattr);
  2760. for(; !upb_inttable_done(&iter); upb_inttable_next(&iter)) {
  2761. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&iter);
  2762. /* Since removal from a singly-linked list requires access to the object's
  2763. * predecessor, we consider obj->next instead of obj for moving. With the
  2764. * while() loop we guarantee that we will visit every node's predecessor.
  2765. * Proof:
  2766. * 1. every node's predecessor is in our attr map.
  2767. * 2. though the loop body may change a node's predecessor, it will only
  2768. * change it to be the node we are currently operating on, so with a
  2769. * while() loop we guarantee ourselves the chance to remove each node. */
  2770. while (color(&t, obj->next) == WHITE &&
  2771. group(&t, obj->next) != obj->next->group) {
  2772. upb_refcounted *leader;
  2773. /* Remove from old group. */
  2774. upb_refcounted *move = obj->next;
  2775. if (obj == move) {
  2776. /* Removing the last object from a group. */
  2777. assert(*obj->group == obj->individual_count);
  2778. free(obj->group);
  2779. } else {
  2780. obj->next = move->next;
  2781. /* This may decrease to zero; we'll collect GRAY objects (if any) that
  2782. * remain in the group in the third pass. */
  2783. assert(*move->group >= move->individual_count);
  2784. *move->group -= move->individual_count;
  2785. }
  2786. /* Add to new group. */
  2787. leader = groupleader(&t, move);
  2788. if (move == leader) {
  2789. /* First object added to new group is its leader. */
  2790. move->group = group(&t, move);
  2791. move->next = move;
  2792. *move->group = move->individual_count;
  2793. } else {
  2794. /* Group already has at least one object in it. */
  2795. assert(leader->group == group(&t, move));
  2796. move->group = group(&t, move);
  2797. move->next = leader->next;
  2798. leader->next = move;
  2799. *move->group += move->individual_count;
  2800. }
  2801. move->is_frozen = true;
  2802. }
  2803. }
  2804. /* Pass 2: GRAY and WHITE objects "obj" with ref2(to, obj) references must
  2805. * increment count(to) if group(obj) != group(to) (which could now be the
  2806. * case if "to" was just frozen). */
  2807. upb_inttable_begin(&iter, &t.objattr);
  2808. for(; !upb_inttable_done(&iter); upb_inttable_next(&iter)) {
  2809. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&iter);
  2810. visit(obj, crossref, &t);
  2811. }
  2812. /* Pass 3: GRAY objects are collected if their group's refcount dropped to
  2813. * zero when we removed its white nodes. This can happen if they had only
  2814. * been kept alive by virtue of sharing a group with an object that was just
  2815. * frozen.
  2816. *
  2817. * It is important that we do this last, since the GRAY object's free()
  2818. * function could call unref2() on just-frozen objects, which will decrement
  2819. * refs that were added in pass 2. */
  2820. upb_inttable_begin(&iter, &t.objattr);
  2821. for(; !upb_inttable_done(&iter); upb_inttable_next(&iter)) {
  2822. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&iter);
  2823. if (obj->group == NULL || *obj->group == 0) {
  2824. if (obj->group) {
  2825. upb_refcounted *o;
  2826. /* We eagerly free() the group's count (since we can't easily determine
  2827. * the group's remaining size it's the easiest way to ensure it gets
  2828. * done). */
  2829. free(obj->group);
  2830. /* Visit to release ref2's (done in a separate pass since release_ref2
  2831. * depends on o->group being unmodified so it can test merged()). */
  2832. o = obj;
  2833. do { visit(o, release_ref2, NULL); } while ((o = o->next) != obj);
  2834. /* Mark "group" fields as NULL so we know to free the objects later in
  2835. * this loop, but also don't try to delete the group twice. */
  2836. o = obj;
  2837. do { o->group = NULL; } while ((o = o->next) != obj);
  2838. }
  2839. freeobj(obj);
  2840. }
  2841. }
  2842. err4:
  2843. if (!ret) {
  2844. upb_inttable_begin(&iter, &t.groups);
  2845. for(; !upb_inttable_done(&iter); upb_inttable_next(&iter))
  2846. free(upb_value_getptr(upb_inttable_iter_value(&iter)));
  2847. }
  2848. upb_inttable_uninit(&t.groups);
  2849. err3:
  2850. upb_inttable_uninit(&t.stack);
  2851. err2:
  2852. upb_inttable_uninit(&t.objattr);
  2853. err1:
  2854. return ret;
  2855. }
  2856. /* Misc internal functions ***************************************************/
  2857. static bool merged(const upb_refcounted *r, const upb_refcounted *r2) {
  2858. return r->group == r2->group;
  2859. }
  2860. static void merge(upb_refcounted *r, upb_refcounted *from) {
  2861. upb_refcounted *base;
  2862. upb_refcounted *tmp;
  2863. if (merged(r, from)) return;
  2864. *r->group += *from->group;
  2865. free(from->group);
  2866. base = from;
  2867. /* Set all refcount pointers in the "from" chain to the merged refcount.
  2868. *
  2869. * TODO(haberman): this linear algorithm can result in an overall O(n^2) bound
  2870. * if the user continuously extends a group by one object. Prevent this by
  2871. * using one of the techniques in this paper:
  2872. * ftp://www.ncedc.org/outgoing/geomorph/dino/orals/p245-tarjan.pdf */
  2873. do { from->group = r->group; } while ((from = from->next) != base);
  2874. /* Merge the two circularly linked lists by swapping their next pointers. */
  2875. tmp = r->next;
  2876. r->next = base->next;
  2877. base->next = tmp;
  2878. }
  2879. static void unref(const upb_refcounted *r);
  2880. static void release_ref2(const upb_refcounted *obj,
  2881. const upb_refcounted *subobj,
  2882. void *closure) {
  2883. UPB_UNUSED(closure);
  2884. untrack(subobj, obj, true);
  2885. if (!merged(obj, subobj)) {
  2886. assert(subobj->is_frozen);
  2887. unref(subobj);
  2888. }
  2889. }
  2890. static void unref(const upb_refcounted *r) {
  2891. if (unrefgroup(r->group)) {
  2892. const upb_refcounted *o;
  2893. free(r->group);
  2894. /* In two passes, since release_ref2 needs a guarantee that any subobjs
  2895. * are alive. */
  2896. o = r;
  2897. do { visit(o, release_ref2, NULL); } while((o = o->next) != r);
  2898. o = r;
  2899. do {
  2900. const upb_refcounted *next = o->next;
  2901. assert(o->is_frozen || o->individual_count == 0);
  2902. freeobj((upb_refcounted*)o);
  2903. o = next;
  2904. } while(o != r);
  2905. }
  2906. }
  2907. static void freeobj(upb_refcounted *o) {
  2908. trackfree(o);
  2909. o->vtbl->free((upb_refcounted*)o);
  2910. }
  2911. /* Public interface ***********************************************************/
  2912. bool upb_refcounted_init(upb_refcounted *r,
  2913. const struct upb_refcounted_vtbl *vtbl,
  2914. const void *owner) {
  2915. #ifndef NDEBUG
  2916. /* Endianness check. This is unrelated to upb_refcounted, it's just a
  2917. * convenient place to put the check that we can be assured will run for
  2918. * basically every program using upb. */
  2919. const int x = 1;
  2920. #ifdef UPB_BIG_ENDIAN
  2921. assert(*(char*)&x != 1);
  2922. #else
  2923. assert(*(char*)&x == 1);
  2924. #endif
  2925. #endif
  2926. r->next = r;
  2927. r->vtbl = vtbl;
  2928. r->individual_count = 0;
  2929. r->is_frozen = false;
  2930. r->group = malloc(sizeof(*r->group));
  2931. if (!r->group) return false;
  2932. *r->group = 0;
  2933. if (!trackinit(r)) {
  2934. free(r->group);
  2935. return false;
  2936. }
  2937. upb_refcounted_ref(r, owner);
  2938. return true;
  2939. }
  2940. bool upb_refcounted_isfrozen(const upb_refcounted *r) {
  2941. return r->is_frozen;
  2942. }
  2943. void upb_refcounted_ref(const upb_refcounted *r, const void *owner) {
  2944. track(r, owner, false);
  2945. if (!r->is_frozen)
  2946. ((upb_refcounted*)r)->individual_count++;
  2947. refgroup(r->group);
  2948. }
  2949. void upb_refcounted_unref(const upb_refcounted *r, const void *owner) {
  2950. untrack(r, owner, false);
  2951. if (!r->is_frozen)
  2952. ((upb_refcounted*)r)->individual_count--;
  2953. unref(r);
  2954. }
  2955. void upb_refcounted_ref2(const upb_refcounted *r, upb_refcounted *from) {
  2956. assert(!from->is_frozen); /* Non-const pointer implies this. */
  2957. track(r, from, true);
  2958. if (r->is_frozen) {
  2959. refgroup(r->group);
  2960. } else {
  2961. merge((upb_refcounted*)r, from);
  2962. }
  2963. }
  2964. void upb_refcounted_unref2(const upb_refcounted *r, upb_refcounted *from) {
  2965. assert(!from->is_frozen); /* Non-const pointer implies this. */
  2966. untrack(r, from, true);
  2967. if (r->is_frozen) {
  2968. unref(r);
  2969. } else {
  2970. assert(merged(r, from));
  2971. }
  2972. }
  2973. void upb_refcounted_donateref(
  2974. const upb_refcounted *r, const void *from, const void *to) {
  2975. assert(from != to);
  2976. if (to != NULL)
  2977. upb_refcounted_ref(r, to);
  2978. if (from != NULL)
  2979. upb_refcounted_unref(r, from);
  2980. }
  2981. void upb_refcounted_checkref(const upb_refcounted *r, const void *owner) {
  2982. checkref(r, owner, false);
  2983. }
  2984. bool upb_refcounted_freeze(upb_refcounted *const*roots, int n, upb_status *s,
  2985. int maxdepth) {
  2986. int i;
  2987. for (i = 0; i < n; i++) {
  2988. assert(!roots[i]->is_frozen);
  2989. }
  2990. return freeze(roots, n, s, maxdepth);
  2991. }
  2992. /*
  2993. * upb - a minimalist implementation of protocol buffers.
  2994. *
  2995. * Copyright (c) 2013 Google Inc. See LICENSE for details.
  2996. * Author: Josh Haberman <jhaberman@gmail.com>
  2997. */
  2998. #include <stdlib.h>
  2999. /* Fallback implementation if the shim is not specialized by the JIT. */
  3000. #define SHIM_WRITER(type, ctype) \
  3001. bool upb_shim_set ## type (void *c, const void *hd, ctype val) { \
  3002. uint8_t *m = c; \
  3003. const upb_shim_data *d = hd; \
  3004. if (d->hasbit > 0) \
  3005. *(uint8_t*)&m[d->hasbit / 8] |= 1 << (d->hasbit % 8); \
  3006. *(ctype*)&m[d->offset] = val; \
  3007. return true; \
  3008. } \
  3009. SHIM_WRITER(double, double)
  3010. SHIM_WRITER(float, float)
  3011. SHIM_WRITER(int32, int32_t)
  3012. SHIM_WRITER(int64, int64_t)
  3013. SHIM_WRITER(uint32, uint32_t)
  3014. SHIM_WRITER(uint64, uint64_t)
  3015. SHIM_WRITER(bool, bool)
  3016. #undef SHIM_WRITER
  3017. bool upb_shim_set(upb_handlers *h, const upb_fielddef *f, size_t offset,
  3018. int32_t hasbit) {
  3019. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  3020. bool ok;
  3021. upb_shim_data *d = malloc(sizeof(*d));
  3022. if (!d) return false;
  3023. d->offset = offset;
  3024. d->hasbit = hasbit;
  3025. upb_handlerattr_sethandlerdata(&attr, d);
  3026. upb_handlerattr_setalwaysok(&attr, true);
  3027. upb_handlers_addcleanup(h, d, free);
  3028. #define TYPE(u, l) \
  3029. case UPB_TYPE_##u: \
  3030. ok = upb_handlers_set##l(h, f, upb_shim_set##l, &attr); break;
  3031. ok = false;
  3032. switch (upb_fielddef_type(f)) {
  3033. TYPE(INT64, int64);
  3034. TYPE(INT32, int32);
  3035. TYPE(ENUM, int32);
  3036. TYPE(UINT64, uint64);
  3037. TYPE(UINT32, uint32);
  3038. TYPE(DOUBLE, double);
  3039. TYPE(FLOAT, float);
  3040. TYPE(BOOL, bool);
  3041. default: assert(false); break;
  3042. }
  3043. #undef TYPE
  3044. upb_handlerattr_uninit(&attr);
  3045. return ok;
  3046. }
  3047. const upb_shim_data *upb_shim_getdata(const upb_handlers *h, upb_selector_t s,
  3048. upb_fieldtype_t *type) {
  3049. upb_func *f = upb_handlers_gethandler(h, s);
  3050. if ((upb_int64_handlerfunc*)f == upb_shim_setint64) {
  3051. *type = UPB_TYPE_INT64;
  3052. } else if ((upb_int32_handlerfunc*)f == upb_shim_setint32) {
  3053. *type = UPB_TYPE_INT32;
  3054. } else if ((upb_uint64_handlerfunc*)f == upb_shim_setuint64) {
  3055. *type = UPB_TYPE_UINT64;
  3056. } else if ((upb_uint32_handlerfunc*)f == upb_shim_setuint32) {
  3057. *type = UPB_TYPE_UINT32;
  3058. } else if ((upb_double_handlerfunc*)f == upb_shim_setdouble) {
  3059. *type = UPB_TYPE_DOUBLE;
  3060. } else if ((upb_float_handlerfunc*)f == upb_shim_setfloat) {
  3061. *type = UPB_TYPE_FLOAT;
  3062. } else if ((upb_bool_handlerfunc*)f == upb_shim_setbool) {
  3063. *type = UPB_TYPE_BOOL;
  3064. } else {
  3065. return NULL;
  3066. }
  3067. return (const upb_shim_data*)upb_handlers_gethandlerdata(h, s);
  3068. }
  3069. /*
  3070. * upb - a minimalist implementation of protocol buffers.
  3071. *
  3072. * Copyright (c) 2008-2012 Google Inc. See LICENSE for details.
  3073. * Author: Josh Haberman <jhaberman@gmail.com>
  3074. */
  3075. #include <stdlib.h>
  3076. #include <string.h>
  3077. static void upb_symtab_free(upb_refcounted *r) {
  3078. upb_symtab *s = (upb_symtab*)r;
  3079. upb_strtable_iter i;
  3080. upb_strtable_begin(&i, &s->symtab);
  3081. for (; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  3082. const upb_def *def = upb_value_getptr(upb_strtable_iter_value(&i));
  3083. upb_def_unref(def, s);
  3084. }
  3085. upb_strtable_uninit(&s->symtab);
  3086. free(s);
  3087. }
  3088. upb_symtab *upb_symtab_new(const void *owner) {
  3089. static const struct upb_refcounted_vtbl vtbl = {NULL, &upb_symtab_free};
  3090. upb_symtab *s = malloc(sizeof(*s));
  3091. upb_refcounted_init(upb_symtab_upcast_mutable(s), &vtbl, owner);
  3092. upb_strtable_init(&s->symtab, UPB_CTYPE_PTR);
  3093. return s;
  3094. }
  3095. void upb_symtab_freeze(upb_symtab *s) {
  3096. upb_refcounted *r;
  3097. bool ok;
  3098. assert(!upb_symtab_isfrozen(s));
  3099. r = upb_symtab_upcast_mutable(s);
  3100. /* The symtab does not take ref2's (see refcounted.h) on the defs, because
  3101. * defs cannot refer back to the table and therefore cannot create cycles. So
  3102. * 0 will suffice for maxdepth here. */
  3103. ok = upb_refcounted_freeze(&r, 1, NULL, 0);
  3104. UPB_ASSERT_VAR(ok, ok);
  3105. }
  3106. const upb_def *upb_symtab_lookup(const upb_symtab *s, const char *sym) {
  3107. upb_value v;
  3108. upb_def *ret = upb_strtable_lookup(&s->symtab, sym, &v) ?
  3109. upb_value_getptr(v) : NULL;
  3110. return ret;
  3111. }
  3112. const upb_msgdef *upb_symtab_lookupmsg(const upb_symtab *s, const char *sym) {
  3113. upb_value v;
  3114. upb_def *def = upb_strtable_lookup(&s->symtab, sym, &v) ?
  3115. upb_value_getptr(v) : NULL;
  3116. return def ? upb_dyncast_msgdef(def) : NULL;
  3117. }
  3118. const upb_enumdef *upb_symtab_lookupenum(const upb_symtab *s, const char *sym) {
  3119. upb_value v;
  3120. upb_def *def = upb_strtable_lookup(&s->symtab, sym, &v) ?
  3121. upb_value_getptr(v) : NULL;
  3122. return def ? upb_dyncast_enumdef(def) : NULL;
  3123. }
  3124. /* Given a symbol and the base symbol inside which it is defined, find the
  3125. * symbol's definition in t. */
  3126. static upb_def *upb_resolvename(const upb_strtable *t,
  3127. const char *base, const char *sym) {
  3128. if(strlen(sym) == 0) return NULL;
  3129. if(sym[0] == '.') {
  3130. /* Symbols starting with '.' are absolute, so we do a single lookup.
  3131. * Slice to omit the leading '.' */
  3132. upb_value v;
  3133. return upb_strtable_lookup(t, sym + 1, &v) ? upb_value_getptr(v) : NULL;
  3134. } else {
  3135. /* Remove components from base until we find an entry or run out.
  3136. * TODO: This branch is totally broken, but currently not used. */
  3137. (void)base;
  3138. assert(false);
  3139. return NULL;
  3140. }
  3141. }
  3142. const upb_def *upb_symtab_resolve(const upb_symtab *s, const char *base,
  3143. const char *sym) {
  3144. upb_def *ret = upb_resolvename(&s->symtab, base, sym);
  3145. return ret;
  3146. }
  3147. /* Searches def and its children to find defs that have the same name as any
  3148. * def in "addtab." Returns true if any where found, and as a side-effect adds
  3149. * duplicates of these defs into addtab.
  3150. *
  3151. * We use a modified depth-first traversal that traverses each SCC (which we
  3152. * already computed) as if it were a single node. This allows us to traverse
  3153. * the possibly-cyclic graph as if it were a DAG and to dup the correct set of
  3154. * nodes with O(n) time. */
  3155. static bool upb_resolve_dfs(const upb_def *def, upb_strtable *addtab,
  3156. const void *new_owner, upb_inttable *seen,
  3157. upb_status *s) {
  3158. /* Memoize results of this function for efficiency (since we're traversing a
  3159. * DAG this is not needed to limit the depth of the search). */
  3160. upb_value v;
  3161. bool need_dup;
  3162. const upb_def *base;
  3163. if (upb_inttable_lookup(seen, (uintptr_t)def, &v))
  3164. return upb_value_getbool(v);
  3165. /* Visit submessages for all messages in the SCC. */
  3166. need_dup = false;
  3167. base = def;
  3168. do {
  3169. upb_value v;
  3170. const upb_msgdef *m;
  3171. assert(upb_def_isfrozen(def));
  3172. if (def->type == UPB_DEF_FIELD) continue;
  3173. if (upb_strtable_lookup(addtab, upb_def_fullname(def), &v)) {
  3174. need_dup = true;
  3175. }
  3176. /* For messages, continue the recursion by visiting all subdefs. */
  3177. m = upb_dyncast_msgdef(def);
  3178. if (m) {
  3179. upb_msg_field_iter i;
  3180. for(upb_msg_field_begin(&i, m);
  3181. !upb_msg_field_done(&i);
  3182. upb_msg_field_next(&i)) {
  3183. upb_fielddef *f = upb_msg_iter_field(&i);
  3184. if (!upb_fielddef_hassubdef(f)) continue;
  3185. /* |= to avoid short-circuit; we need its side-effects. */
  3186. need_dup |= upb_resolve_dfs(
  3187. upb_fielddef_subdef(f), addtab, new_owner, seen, s);
  3188. if (!upb_ok(s)) return false;
  3189. }
  3190. }
  3191. } while ((def = (upb_def*)def->base.next) != base);
  3192. if (need_dup) {
  3193. /* Dup any defs that don't already have entries in addtab. */
  3194. def = base;
  3195. do {
  3196. const char *name;
  3197. if (def->type == UPB_DEF_FIELD) continue;
  3198. name = upb_def_fullname(def);
  3199. if (!upb_strtable_lookup(addtab, name, NULL)) {
  3200. upb_def *newdef = upb_def_dup(def, new_owner);
  3201. if (!newdef) goto oom;
  3202. newdef->came_from_user = false;
  3203. if (!upb_strtable_insert(addtab, name, upb_value_ptr(newdef)))
  3204. goto oom;
  3205. }
  3206. } while ((def = (upb_def*)def->base.next) != base);
  3207. }
  3208. upb_inttable_insert(seen, (uintptr_t)def, upb_value_bool(need_dup));
  3209. return need_dup;
  3210. oom:
  3211. upb_status_seterrmsg(s, "out of memory");
  3212. return false;
  3213. }
  3214. /* TODO(haberman): we need a lot more testing of error conditions.
  3215. * The came_from_user stuff in particular is not tested. */
  3216. bool upb_symtab_add(upb_symtab *s, upb_def *const*defs, int n, void *ref_donor,
  3217. upb_status *status) {
  3218. int i;
  3219. upb_strtable_iter iter;
  3220. upb_def **add_defs = NULL;
  3221. upb_strtable addtab;
  3222. upb_inttable seen;
  3223. assert(!upb_symtab_isfrozen(s));
  3224. if (!upb_strtable_init(&addtab, UPB_CTYPE_PTR)) {
  3225. upb_status_seterrmsg(status, "out of memory");
  3226. return false;
  3227. }
  3228. /* Add new defs to our "add" set. */
  3229. for (i = 0; i < n; i++) {
  3230. upb_def *def = defs[i];
  3231. const char *fullname;
  3232. upb_fielddef *f;
  3233. if (upb_def_isfrozen(def)) {
  3234. upb_status_seterrmsg(status, "added defs must be mutable");
  3235. goto err;
  3236. }
  3237. assert(!upb_def_isfrozen(def));
  3238. fullname = upb_def_fullname(def);
  3239. if (!fullname) {
  3240. upb_status_seterrmsg(
  3241. status, "Anonymous defs cannot be added to a symtab");
  3242. goto err;
  3243. }
  3244. f = upb_dyncast_fielddef_mutable(def);
  3245. if (f) {
  3246. if (!upb_fielddef_containingtypename(f)) {
  3247. upb_status_seterrmsg(status,
  3248. "Standalone fielddefs must have a containing type "
  3249. "(extendee) name set");
  3250. goto err;
  3251. }
  3252. } else {
  3253. if (upb_strtable_lookup(&addtab, fullname, NULL)) {
  3254. upb_status_seterrf(status, "Conflicting defs named '%s'", fullname);
  3255. goto err;
  3256. }
  3257. /* We need this to back out properly, because if there is a failure we
  3258. * need to donate the ref back to the caller. */
  3259. def->came_from_user = true;
  3260. upb_def_donateref(def, ref_donor, s);
  3261. if (!upb_strtable_insert(&addtab, fullname, upb_value_ptr(def)))
  3262. goto oom_err;
  3263. }
  3264. }
  3265. /* Add standalone fielddefs (ie. extensions) to the appropriate messages.
  3266. * If the appropriate message only exists in the existing symtab, duplicate
  3267. * it so we have a mutable copy we can add the fields to. */
  3268. for (i = 0; i < n; i++) {
  3269. upb_def *def = defs[i];
  3270. upb_fielddef *f = upb_dyncast_fielddef_mutable(def);
  3271. const char *msgname;
  3272. upb_value v;
  3273. upb_msgdef *m;
  3274. if (!f) continue;
  3275. msgname = upb_fielddef_containingtypename(f);
  3276. /* We validated this earlier in this function. */
  3277. assert(msgname);
  3278. /* If the extendee name is absolutely qualified, move past the initial ".".
  3279. * TODO(haberman): it is not obvious what it would mean if this was not
  3280. * absolutely qualified. */
  3281. if (msgname[0] == '.') {
  3282. msgname++;
  3283. }
  3284. if (upb_strtable_lookup(&addtab, msgname, &v)) {
  3285. /* Extendee is in the set of defs the user asked us to add. */
  3286. m = upb_value_getptr(v);
  3287. } else {
  3288. /* Need to find and dup the extendee from the existing symtab. */
  3289. const upb_msgdef *frozen_m = upb_symtab_lookupmsg(s, msgname);
  3290. if (!frozen_m) {
  3291. upb_status_seterrf(status,
  3292. "Tried to extend message %s that does not exist "
  3293. "in this SymbolTable.",
  3294. msgname);
  3295. goto err;
  3296. }
  3297. m = upb_msgdef_dup(frozen_m, s);
  3298. if (!m) goto oom_err;
  3299. if (!upb_strtable_insert(&addtab, msgname, upb_value_ptr(m))) {
  3300. upb_msgdef_unref(m, s);
  3301. goto oom_err;
  3302. }
  3303. }
  3304. if (!upb_msgdef_addfield(m, f, ref_donor, status)) {
  3305. goto err;
  3306. }
  3307. }
  3308. /* Add dups of any existing def that can reach a def with the same name as
  3309. * anything in our "add" set. */
  3310. if (!upb_inttable_init(&seen, UPB_CTYPE_BOOL)) goto oom_err;
  3311. upb_strtable_begin(&iter, &s->symtab);
  3312. for (; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
  3313. upb_def *def = upb_value_getptr(upb_strtable_iter_value(&iter));
  3314. upb_resolve_dfs(def, &addtab, s, &seen, status);
  3315. if (!upb_ok(status)) goto err;
  3316. }
  3317. upb_inttable_uninit(&seen);
  3318. /* Now using the table, resolve symbolic references for subdefs. */
  3319. upb_strtable_begin(&iter, &addtab);
  3320. for (; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
  3321. const char *base;
  3322. upb_def *def = upb_value_getptr(upb_strtable_iter_value(&iter));
  3323. upb_msgdef *m = upb_dyncast_msgdef_mutable(def);
  3324. upb_msg_field_iter j;
  3325. if (!m) continue;
  3326. /* Type names are resolved relative to the message in which they appear. */
  3327. base = upb_msgdef_fullname(m);
  3328. for(upb_msg_field_begin(&j, m);
  3329. !upb_msg_field_done(&j);
  3330. upb_msg_field_next(&j)) {
  3331. upb_fielddef *f = upb_msg_iter_field(&j);
  3332. const char *name = upb_fielddef_subdefname(f);
  3333. if (name && !upb_fielddef_subdef(f)) {
  3334. /* Try the lookup in the current set of to-be-added defs first. If not
  3335. * there, try existing defs. */
  3336. upb_def *subdef = upb_resolvename(&addtab, base, name);
  3337. if (subdef == NULL) {
  3338. subdef = upb_resolvename(&s->symtab, base, name);
  3339. }
  3340. if (subdef == NULL) {
  3341. upb_status_seterrf(
  3342. status, "couldn't resolve name '%s' in message '%s'", name, base);
  3343. goto err;
  3344. } else if (!upb_fielddef_setsubdef(f, subdef, status)) {
  3345. goto err;
  3346. }
  3347. }
  3348. }
  3349. }
  3350. /* We need an array of the defs in addtab, for passing to upb_def_freeze. */
  3351. add_defs = malloc(sizeof(void*) * upb_strtable_count(&addtab));
  3352. if (add_defs == NULL) goto oom_err;
  3353. upb_strtable_begin(&iter, &addtab);
  3354. for (n = 0; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
  3355. add_defs[n++] = upb_value_getptr(upb_strtable_iter_value(&iter));
  3356. }
  3357. if (!upb_def_freeze(add_defs, n, status)) goto err;
  3358. /* This must be delayed until all errors have been detected, since error
  3359. * recovery code uses this table to cleanup defs. */
  3360. upb_strtable_uninit(&addtab);
  3361. /* TODO(haberman) we don't properly handle errors after this point (like
  3362. * OOM in upb_strtable_insert() below). */
  3363. for (i = 0; i < n; i++) {
  3364. upb_def *def = add_defs[i];
  3365. const char *name = upb_def_fullname(def);
  3366. upb_value v;
  3367. bool success;
  3368. if (upb_strtable_remove(&s->symtab, name, &v)) {
  3369. const upb_def *def = upb_value_getptr(v);
  3370. upb_def_unref(def, s);
  3371. }
  3372. success = upb_strtable_insert(&s->symtab, name, upb_value_ptr(def));
  3373. UPB_ASSERT_VAR(success, success == true);
  3374. }
  3375. free(add_defs);
  3376. return true;
  3377. oom_err:
  3378. upb_status_seterrmsg(status, "out of memory");
  3379. err: {
  3380. /* For defs the user passed in, we need to donate the refs back. For defs
  3381. * we dup'd, we need to just unref them. */
  3382. upb_strtable_begin(&iter, &addtab);
  3383. for (; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
  3384. upb_def *def = upb_value_getptr(upb_strtable_iter_value(&iter));
  3385. bool came_from_user = def->came_from_user;
  3386. def->came_from_user = false;
  3387. if (came_from_user) {
  3388. upb_def_donateref(def, s, ref_donor);
  3389. } else {
  3390. upb_def_unref(def, s);
  3391. }
  3392. }
  3393. }
  3394. upb_strtable_uninit(&addtab);
  3395. free(add_defs);
  3396. assert(!upb_ok(status));
  3397. return false;
  3398. }
  3399. /* Iteration. */
  3400. static void advance_to_matching(upb_symtab_iter *iter) {
  3401. if (iter->type == UPB_DEF_ANY)
  3402. return;
  3403. while (!upb_strtable_done(&iter->iter) &&
  3404. iter->type != upb_symtab_iter_def(iter)->type) {
  3405. upb_strtable_next(&iter->iter);
  3406. }
  3407. }
  3408. void upb_symtab_begin(upb_symtab_iter *iter, const upb_symtab *s,
  3409. upb_deftype_t type) {
  3410. upb_strtable_begin(&iter->iter, &s->symtab);
  3411. iter->type = type;
  3412. advance_to_matching(iter);
  3413. }
  3414. void upb_symtab_next(upb_symtab_iter *iter) {
  3415. upb_strtable_next(&iter->iter);
  3416. advance_to_matching(iter);
  3417. }
  3418. bool upb_symtab_done(const upb_symtab_iter *iter) {
  3419. return upb_strtable_done(&iter->iter);
  3420. }
  3421. const upb_def *upb_symtab_iter_def(const upb_symtab_iter *iter) {
  3422. return upb_value_getptr(upb_strtable_iter_value(&iter->iter));
  3423. }
  3424. /*
  3425. * upb - a minimalist implementation of protocol buffers.
  3426. *
  3427. * Copyright (c) 2009 Google Inc. See LICENSE for details.
  3428. * Author: Josh Haberman <jhaberman@gmail.com>
  3429. *
  3430. * Implementation is heavily inspired by Lua's ltable.c.
  3431. */
  3432. #include <stdlib.h>
  3433. #include <string.h>
  3434. #define UPB_MAXARRSIZE 16 /* 64k. */
  3435. /* From Chromium. */
  3436. #define ARRAY_SIZE(x) \
  3437. ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x])))))
  3438. static const double MAX_LOAD = 0.85;
  3439. /* The minimum utilization of the array part of a mixed hash/array table. This
  3440. * is a speed/memory-usage tradeoff (though it's not straightforward because of
  3441. * cache effects). The lower this is, the more memory we'll use. */
  3442. static const double MIN_DENSITY = 0.1;
  3443. bool is_pow2(uint64_t v) { return v == 0 || (v & (v - 1)) == 0; }
  3444. int log2ceil(uint64_t v) {
  3445. int ret = 0;
  3446. bool pow2 = is_pow2(v);
  3447. while (v >>= 1) ret++;
  3448. ret = pow2 ? ret : ret + 1; /* Ceiling. */
  3449. return UPB_MIN(UPB_MAXARRSIZE, ret);
  3450. }
  3451. char *upb_strdup(const char *s) {
  3452. return upb_strdup2(s, strlen(s));
  3453. }
  3454. char *upb_strdup2(const char *s, size_t len) {
  3455. size_t n;
  3456. char *p;
  3457. /* Prevent overflow errors. */
  3458. if (len == SIZE_MAX) return NULL;
  3459. /* Always null-terminate, even if binary data; but don't rely on the input to
  3460. * have a null-terminating byte since it may be a raw binary buffer. */
  3461. n = len + 1;
  3462. p = malloc(n);
  3463. if (p) {
  3464. memcpy(p, s, len);
  3465. p[len] = 0;
  3466. }
  3467. return p;
  3468. }
  3469. /* A type to represent the lookup key of either a strtable or an inttable. */
  3470. typedef union {
  3471. uintptr_t num;
  3472. struct {
  3473. const char *str;
  3474. size_t len;
  3475. } str;
  3476. } lookupkey_t;
  3477. static lookupkey_t strkey2(const char *str, size_t len) {
  3478. lookupkey_t k;
  3479. k.str.str = str;
  3480. k.str.len = len;
  3481. return k;
  3482. }
  3483. static lookupkey_t intkey(uintptr_t key) {
  3484. lookupkey_t k;
  3485. k.num = key;
  3486. return k;
  3487. }
  3488. typedef uint32_t hashfunc_t(upb_tabkey key);
  3489. typedef bool eqlfunc_t(upb_tabkey k1, lookupkey_t k2);
  3490. /* Base table (shared code) ***************************************************/
  3491. /* For when we need to cast away const. */
  3492. static upb_tabent *mutable_entries(upb_table *t) {
  3493. return (upb_tabent*)t->entries;
  3494. }
  3495. static bool isfull(upb_table *t) {
  3496. return (double)(t->count + 1) / upb_table_size(t) > MAX_LOAD;
  3497. }
  3498. static bool init(upb_table *t, upb_ctype_t ctype, uint8_t size_lg2) {
  3499. size_t bytes;
  3500. t->count = 0;
  3501. t->ctype = ctype;
  3502. t->size_lg2 = size_lg2;
  3503. t->mask = upb_table_size(t) ? upb_table_size(t) - 1 : 0;
  3504. bytes = upb_table_size(t) * sizeof(upb_tabent);
  3505. if (bytes > 0) {
  3506. t->entries = malloc(bytes);
  3507. if (!t->entries) return false;
  3508. memset(mutable_entries(t), 0, bytes);
  3509. } else {
  3510. t->entries = NULL;
  3511. }
  3512. return true;
  3513. }
  3514. static void uninit(upb_table *t) { free(mutable_entries(t)); }
  3515. static upb_tabent *emptyent(upb_table *t) {
  3516. upb_tabent *e = mutable_entries(t) + upb_table_size(t);
  3517. while (1) { if (upb_tabent_isempty(--e)) return e; assert(e > t->entries); }
  3518. }
  3519. static upb_tabent *getentry_mutable(upb_table *t, uint32_t hash) {
  3520. return (upb_tabent*)upb_getentry(t, hash);
  3521. }
  3522. static const upb_tabent *findentry(const upb_table *t, lookupkey_t key,
  3523. uint32_t hash, eqlfunc_t *eql) {
  3524. const upb_tabent *e;
  3525. if (t->size_lg2 == 0) return NULL;
  3526. e = upb_getentry(t, hash);
  3527. if (upb_tabent_isempty(e)) return NULL;
  3528. while (1) {
  3529. if (eql(e->key, key)) return e;
  3530. if ((e = e->next) == NULL) return NULL;
  3531. }
  3532. }
  3533. static upb_tabent *findentry_mutable(upb_table *t, lookupkey_t key,
  3534. uint32_t hash, eqlfunc_t *eql) {
  3535. return (upb_tabent*)findentry(t, key, hash, eql);
  3536. }
  3537. static bool lookup(const upb_table *t, lookupkey_t key, upb_value *v,
  3538. uint32_t hash, eqlfunc_t *eql) {
  3539. const upb_tabent *e = findentry(t, key, hash, eql);
  3540. if (e) {
  3541. if (v) {
  3542. _upb_value_setval(v, e->val.val, t->ctype);
  3543. }
  3544. return true;
  3545. } else {
  3546. return false;
  3547. }
  3548. }
  3549. /* The given key must not already exist in the table. */
  3550. static void insert(upb_table *t, lookupkey_t key, upb_tabkey tabkey,
  3551. upb_value val, uint32_t hash,
  3552. hashfunc_t *hashfunc, eqlfunc_t *eql) {
  3553. upb_tabent *mainpos_e;
  3554. upb_tabent *our_e;
  3555. UPB_UNUSED(eql);
  3556. UPB_UNUSED(key);
  3557. assert(findentry(t, key, hash, eql) == NULL);
  3558. assert(val.ctype == t->ctype);
  3559. t->count++;
  3560. mainpos_e = getentry_mutable(t, hash);
  3561. our_e = mainpos_e;
  3562. if (upb_tabent_isempty(mainpos_e)) {
  3563. /* Our main position is empty; use it. */
  3564. our_e->next = NULL;
  3565. } else {
  3566. /* Collision. */
  3567. upb_tabent *new_e = emptyent(t);
  3568. /* Head of collider's chain. */
  3569. upb_tabent *chain = getentry_mutable(t, hashfunc(mainpos_e->key));
  3570. if (chain == mainpos_e) {
  3571. /* Existing ent is in its main posisiton (it has the same hash as us, and
  3572. * is the head of our chain). Insert to new ent and append to this chain. */
  3573. new_e->next = mainpos_e->next;
  3574. mainpos_e->next = new_e;
  3575. our_e = new_e;
  3576. } else {
  3577. /* Existing ent is not in its main position (it is a node in some other
  3578. * chain). This implies that no existing ent in the table has our hash.
  3579. * Evict it (updating its chain) and use its ent for head of our chain. */
  3580. *new_e = *mainpos_e; /* copies next. */
  3581. while (chain->next != mainpos_e) {
  3582. chain = (upb_tabent*)chain->next;
  3583. assert(chain);
  3584. }
  3585. chain->next = new_e;
  3586. our_e = mainpos_e;
  3587. our_e->next = NULL;
  3588. }
  3589. }
  3590. our_e->key = tabkey;
  3591. our_e->val.val = val.val;
  3592. assert(findentry(t, key, hash, eql) == our_e);
  3593. }
  3594. static bool rm(upb_table *t, lookupkey_t key, upb_value *val,
  3595. upb_tabkey *removed, uint32_t hash, eqlfunc_t *eql) {
  3596. upb_tabent *chain = getentry_mutable(t, hash);
  3597. if (upb_tabent_isempty(chain)) return false;
  3598. if (eql(chain->key, key)) {
  3599. /* Element to remove is at the head of its chain. */
  3600. t->count--;
  3601. if (val) {
  3602. _upb_value_setval(val, chain->val.val, t->ctype);
  3603. }
  3604. if (chain->next) {
  3605. upb_tabent *move = (upb_tabent*)chain->next;
  3606. *chain = *move;
  3607. if (removed) *removed = move->key;
  3608. move->key = 0; /* Make the slot empty. */
  3609. } else {
  3610. if (removed) *removed = chain->key;
  3611. chain->key = 0; /* Make the slot empty. */
  3612. }
  3613. return true;
  3614. } else {
  3615. /* Element to remove is either in a non-head position or not in the
  3616. * table. */
  3617. while (chain->next && !eql(chain->next->key, key))
  3618. chain = (upb_tabent*)chain->next;
  3619. if (chain->next) {
  3620. /* Found element to remove. */
  3621. upb_tabent *rm;
  3622. if (val) {
  3623. _upb_value_setval(val, chain->next->val.val, t->ctype);
  3624. }
  3625. rm = (upb_tabent*)chain->next;
  3626. if (removed) *removed = rm->key;
  3627. rm->key = 0;
  3628. chain->next = rm->next;
  3629. t->count--;
  3630. return true;
  3631. } else {
  3632. return false;
  3633. }
  3634. }
  3635. }
  3636. static size_t next(const upb_table *t, size_t i) {
  3637. do {
  3638. if (++i >= upb_table_size(t))
  3639. return SIZE_MAX;
  3640. } while(upb_tabent_isempty(&t->entries[i]));
  3641. return i;
  3642. }
  3643. static size_t begin(const upb_table *t) {
  3644. return next(t, -1);
  3645. }
  3646. /* upb_strtable ***************************************************************/
  3647. /* A simple "subclass" of upb_table that only adds a hash function for strings. */
  3648. static upb_tabkey strcopy(lookupkey_t k2) {
  3649. char *str = malloc(k2.str.len + sizeof(uint32_t) + 1);
  3650. if (str == NULL) return 0;
  3651. memcpy(str, &k2.str.len, sizeof(uint32_t));
  3652. memcpy(str + sizeof(uint32_t), k2.str.str, k2.str.len + 1);
  3653. return (uintptr_t)str;
  3654. }
  3655. static uint32_t strhash(upb_tabkey key) {
  3656. uint32_t len;
  3657. char *str = upb_tabstr(key, &len);
  3658. return MurmurHash2(str, len, 0);
  3659. }
  3660. static bool streql(upb_tabkey k1, lookupkey_t k2) {
  3661. uint32_t len;
  3662. char *str = upb_tabstr(k1, &len);
  3663. return len == k2.str.len && memcmp(str, k2.str.str, len) == 0;
  3664. }
  3665. bool upb_strtable_init(upb_strtable *t, upb_ctype_t ctype) {
  3666. return init(&t->t, ctype, 2);
  3667. }
  3668. void upb_strtable_uninit(upb_strtable *t) {
  3669. size_t i;
  3670. for (i = 0; i < upb_table_size(&t->t); i++)
  3671. free((void*)t->t.entries[i].key);
  3672. uninit(&t->t);
  3673. }
  3674. bool upb_strtable_resize(upb_strtable *t, size_t size_lg2) {
  3675. upb_strtable new_table;
  3676. upb_strtable_iter i;
  3677. if (!init(&new_table.t, t->t.ctype, size_lg2))
  3678. return false;
  3679. upb_strtable_begin(&i, t);
  3680. for ( ; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  3681. upb_strtable_insert2(
  3682. &new_table,
  3683. upb_strtable_iter_key(&i),
  3684. upb_strtable_iter_keylength(&i),
  3685. upb_strtable_iter_value(&i));
  3686. }
  3687. upb_strtable_uninit(t);
  3688. *t = new_table;
  3689. return true;
  3690. }
  3691. bool upb_strtable_insert2(upb_strtable *t, const char *k, size_t len,
  3692. upb_value v) {
  3693. lookupkey_t key;
  3694. upb_tabkey tabkey;
  3695. uint32_t hash;
  3696. if (isfull(&t->t)) {
  3697. /* Need to resize. New table of double the size, add old elements to it. */
  3698. if (!upb_strtable_resize(t, t->t.size_lg2 + 1)) {
  3699. return false;
  3700. }
  3701. }
  3702. key = strkey2(k, len);
  3703. tabkey = strcopy(key);
  3704. if (tabkey == 0) return false;
  3705. hash = MurmurHash2(key.str.str, key.str.len, 0);
  3706. insert(&t->t, key, tabkey, v, hash, &strhash, &streql);
  3707. return true;
  3708. }
  3709. bool upb_strtable_lookup2(const upb_strtable *t, const char *key, size_t len,
  3710. upb_value *v) {
  3711. uint32_t hash = MurmurHash2(key, len, 0);
  3712. return lookup(&t->t, strkey2(key, len), v, hash, &streql);
  3713. }
  3714. bool upb_strtable_remove2(upb_strtable *t, const char *key, size_t len,
  3715. upb_value *val) {
  3716. uint32_t hash = MurmurHash2(key, strlen(key), 0);
  3717. upb_tabkey tabkey;
  3718. if (rm(&t->t, strkey2(key, len), val, &tabkey, hash, &streql)) {
  3719. free((void*)tabkey);
  3720. return true;
  3721. } else {
  3722. return false;
  3723. }
  3724. }
  3725. /* Iteration */
  3726. static const upb_tabent *str_tabent(const upb_strtable_iter *i) {
  3727. return &i->t->t.entries[i->index];
  3728. }
  3729. void upb_strtable_begin(upb_strtable_iter *i, const upb_strtable *t) {
  3730. i->t = t;
  3731. i->index = begin(&t->t);
  3732. }
  3733. void upb_strtable_next(upb_strtable_iter *i) {
  3734. i->index = next(&i->t->t, i->index);
  3735. }
  3736. bool upb_strtable_done(const upb_strtable_iter *i) {
  3737. return i->index >= upb_table_size(&i->t->t) ||
  3738. upb_tabent_isempty(str_tabent(i));
  3739. }
  3740. const char *upb_strtable_iter_key(upb_strtable_iter *i) {
  3741. assert(!upb_strtable_done(i));
  3742. return upb_tabstr(str_tabent(i)->key, NULL);
  3743. }
  3744. size_t upb_strtable_iter_keylength(upb_strtable_iter *i) {
  3745. uint32_t len;
  3746. assert(!upb_strtable_done(i));
  3747. upb_tabstr(str_tabent(i)->key, &len);
  3748. return len;
  3749. }
  3750. upb_value upb_strtable_iter_value(const upb_strtable_iter *i) {
  3751. assert(!upb_strtable_done(i));
  3752. return _upb_value_val(str_tabent(i)->val.val, i->t->t.ctype);
  3753. }
  3754. void upb_strtable_iter_setdone(upb_strtable_iter *i) {
  3755. i->index = SIZE_MAX;
  3756. }
  3757. bool upb_strtable_iter_isequal(const upb_strtable_iter *i1,
  3758. const upb_strtable_iter *i2) {
  3759. if (upb_strtable_done(i1) && upb_strtable_done(i2))
  3760. return true;
  3761. return i1->t == i2->t && i1->index == i2->index;
  3762. }
  3763. /* upb_inttable ***************************************************************/
  3764. /* For inttables we use a hybrid structure where small keys are kept in an
  3765. * array and large keys are put in the hash table. */
  3766. static uint32_t inthash(upb_tabkey key) { return upb_inthash(key); }
  3767. static bool inteql(upb_tabkey k1, lookupkey_t k2) {
  3768. return k1 == k2.num;
  3769. }
  3770. static upb_tabval *mutable_array(upb_inttable *t) {
  3771. return (upb_tabval*)t->array;
  3772. }
  3773. static upb_tabval *inttable_val(upb_inttable *t, uintptr_t key) {
  3774. if (key < t->array_size) {
  3775. return upb_arrhas(t->array[key]) ? &(mutable_array(t)[key]) : NULL;
  3776. } else {
  3777. upb_tabent *e =
  3778. findentry_mutable(&t->t, intkey(key), upb_inthash(key), &inteql);
  3779. return e ? &e->val : NULL;
  3780. }
  3781. }
  3782. static const upb_tabval *inttable_val_const(const upb_inttable *t,
  3783. uintptr_t key) {
  3784. return inttable_val((upb_inttable*)t, key);
  3785. }
  3786. size_t upb_inttable_count(const upb_inttable *t) {
  3787. return t->t.count + t->array_count;
  3788. }
  3789. static void check(upb_inttable *t) {
  3790. UPB_UNUSED(t);
  3791. #if defined(UPB_DEBUG_TABLE) && !defined(NDEBUG)
  3792. {
  3793. /* This check is very expensive (makes inserts/deletes O(N)). */
  3794. size_t count = 0;
  3795. upb_inttable_iter i;
  3796. upb_inttable_begin(&i, t);
  3797. for(; !upb_inttable_done(&i); upb_inttable_next(&i), count++) {
  3798. assert(upb_inttable_lookup(t, upb_inttable_iter_key(&i), NULL));
  3799. }
  3800. assert(count == upb_inttable_count(t));
  3801. }
  3802. #endif
  3803. }
  3804. bool upb_inttable_sizedinit(upb_inttable *t, upb_ctype_t ctype,
  3805. size_t asize, int hsize_lg2) {
  3806. size_t array_bytes;
  3807. if (!init(&t->t, ctype, hsize_lg2)) return false;
  3808. /* Always make the array part at least 1 long, so that we know key 0
  3809. * won't be in the hash part, which simplifies things. */
  3810. t->array_size = UPB_MAX(1, asize);
  3811. t->array_count = 0;
  3812. array_bytes = t->array_size * sizeof(upb_value);
  3813. t->array = malloc(array_bytes);
  3814. if (!t->array) {
  3815. uninit(&t->t);
  3816. return false;
  3817. }
  3818. memset(mutable_array(t), 0xff, array_bytes);
  3819. check(t);
  3820. return true;
  3821. }
  3822. bool upb_inttable_init(upb_inttable *t, upb_ctype_t ctype) {
  3823. return upb_inttable_sizedinit(t, ctype, 0, 4);
  3824. }
  3825. void upb_inttable_uninit(upb_inttable *t) {
  3826. uninit(&t->t);
  3827. free(mutable_array(t));
  3828. }
  3829. bool upb_inttable_insert(upb_inttable *t, uintptr_t key, upb_value val) {
  3830. /* XXX: Table can't store value (uint64_t)-1. Need to somehow statically
  3831. * guarantee that this is not necessary, or fix the limitation. */
  3832. upb_tabval tabval;
  3833. tabval.val = val.val;
  3834. UPB_UNUSED(tabval);
  3835. assert(upb_arrhas(tabval));
  3836. if (key < t->array_size) {
  3837. assert(!upb_arrhas(t->array[key]));
  3838. t->array_count++;
  3839. mutable_array(t)[key].val = val.val;
  3840. } else {
  3841. if (isfull(&t->t)) {
  3842. /* Need to resize the hash part, but we re-use the array part. */
  3843. size_t i;
  3844. upb_table new_table;
  3845. if (!init(&new_table, t->t.ctype, t->t.size_lg2 + 1))
  3846. return false;
  3847. for (i = begin(&t->t); i < upb_table_size(&t->t); i = next(&t->t, i)) {
  3848. const upb_tabent *e = &t->t.entries[i];
  3849. uint32_t hash;
  3850. upb_value v;
  3851. _upb_value_setval(&v, e->val.val, t->t.ctype);
  3852. hash = upb_inthash(e->key);
  3853. insert(&new_table, intkey(e->key), e->key, v, hash, &inthash, &inteql);
  3854. }
  3855. assert(t->t.count == new_table.count);
  3856. uninit(&t->t);
  3857. t->t = new_table;
  3858. }
  3859. insert(&t->t, intkey(key), key, val, upb_inthash(key), &inthash, &inteql);
  3860. }
  3861. check(t);
  3862. return true;
  3863. }
  3864. bool upb_inttable_lookup(const upb_inttable *t, uintptr_t key, upb_value *v) {
  3865. const upb_tabval *table_v = inttable_val_const(t, key);
  3866. if (!table_v) return false;
  3867. if (v) _upb_value_setval(v, table_v->val, t->t.ctype);
  3868. return true;
  3869. }
  3870. bool upb_inttable_replace(upb_inttable *t, uintptr_t key, upb_value val) {
  3871. upb_tabval *table_v = inttable_val(t, key);
  3872. if (!table_v) return false;
  3873. table_v->val = val.val;
  3874. return true;
  3875. }
  3876. bool upb_inttable_remove(upb_inttable *t, uintptr_t key, upb_value *val) {
  3877. bool success;
  3878. if (key < t->array_size) {
  3879. if (upb_arrhas(t->array[key])) {
  3880. upb_tabval empty = UPB_TABVALUE_EMPTY_INIT;
  3881. t->array_count--;
  3882. if (val) {
  3883. _upb_value_setval(val, t->array[key].val, t->t.ctype);
  3884. }
  3885. mutable_array(t)[key] = empty;
  3886. success = true;
  3887. } else {
  3888. success = false;
  3889. }
  3890. } else {
  3891. upb_tabkey removed;
  3892. uint32_t hash = upb_inthash(key);
  3893. success = rm(&t->t, intkey(key), val, &removed, hash, &inteql);
  3894. }
  3895. check(t);
  3896. return success;
  3897. }
  3898. bool upb_inttable_push(upb_inttable *t, upb_value val) {
  3899. return upb_inttable_insert(t, upb_inttable_count(t), val);
  3900. }
  3901. upb_value upb_inttable_pop(upb_inttable *t) {
  3902. upb_value val;
  3903. bool ok = upb_inttable_remove(t, upb_inttable_count(t) - 1, &val);
  3904. UPB_ASSERT_VAR(ok, ok);
  3905. return val;
  3906. }
  3907. bool upb_inttable_insertptr(upb_inttable *t, const void *key, upb_value val) {
  3908. return upb_inttable_insert(t, (uintptr_t)key, val);
  3909. }
  3910. bool upb_inttable_lookupptr(const upb_inttable *t, const void *key,
  3911. upb_value *v) {
  3912. return upb_inttable_lookup(t, (uintptr_t)key, v);
  3913. }
  3914. bool upb_inttable_removeptr(upb_inttable *t, const void *key, upb_value *val) {
  3915. return upb_inttable_remove(t, (uintptr_t)key, val);
  3916. }
  3917. void upb_inttable_compact(upb_inttable *t) {
  3918. /* Create a power-of-two histogram of the table keys. */
  3919. int counts[UPB_MAXARRSIZE + 1] = {0};
  3920. uintptr_t max_key = 0;
  3921. upb_inttable_iter i;
  3922. size_t arr_size;
  3923. int arr_count;
  3924. upb_inttable new_t;
  3925. upb_inttable_begin(&i, t);
  3926. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  3927. uintptr_t key = upb_inttable_iter_key(&i);
  3928. if (key > max_key) {
  3929. max_key = key;
  3930. }
  3931. counts[log2ceil(key)]++;
  3932. }
  3933. arr_size = 1;
  3934. arr_count = upb_inttable_count(t);
  3935. if (upb_inttable_count(t) >= max_key * MIN_DENSITY) {
  3936. /* We can put 100% of the entries in the array part. */
  3937. arr_size = max_key + 1;
  3938. } else {
  3939. /* Find the largest power of two that satisfies the MIN_DENSITY
  3940. * definition. */
  3941. int size_lg2;
  3942. for (size_lg2 = ARRAY_SIZE(counts) - 1; size_lg2 > 1; size_lg2--) {
  3943. arr_size = 1 << size_lg2;
  3944. arr_count -= counts[size_lg2];
  3945. if (arr_count >= arr_size * MIN_DENSITY) {
  3946. break;
  3947. }
  3948. }
  3949. }
  3950. /* Array part must always be at least 1 entry large to catch lookups of key
  3951. * 0. Key 0 must always be in the array part because "0" in the hash part
  3952. * denotes an empty entry. */
  3953. arr_size = UPB_MAX(arr_size, 1);
  3954. {
  3955. /* Insert all elements into new, perfectly-sized table. */
  3956. int hash_count = upb_inttable_count(t) - arr_count;
  3957. int hash_size = hash_count ? (hash_count / MAX_LOAD) + 1 : 0;
  3958. int hashsize_lg2 = log2ceil(hash_size);
  3959. assert(hash_count >= 0);
  3960. upb_inttable_sizedinit(&new_t, t->t.ctype, arr_size, hashsize_lg2);
  3961. upb_inttable_begin(&i, t);
  3962. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  3963. uintptr_t k = upb_inttable_iter_key(&i);
  3964. upb_inttable_insert(&new_t, k, upb_inttable_iter_value(&i));
  3965. }
  3966. assert(new_t.array_size == arr_size);
  3967. assert(new_t.t.size_lg2 == hashsize_lg2);
  3968. }
  3969. upb_inttable_uninit(t);
  3970. *t = new_t;
  3971. }
  3972. /* Iteration. */
  3973. static const upb_tabent *int_tabent(const upb_inttable_iter *i) {
  3974. assert(!i->array_part);
  3975. return &i->t->t.entries[i->index];
  3976. }
  3977. static upb_tabval int_arrent(const upb_inttable_iter *i) {
  3978. assert(i->array_part);
  3979. return i->t->array[i->index];
  3980. }
  3981. void upb_inttable_begin(upb_inttable_iter *i, const upb_inttable *t) {
  3982. i->t = t;
  3983. i->index = -1;
  3984. i->array_part = true;
  3985. upb_inttable_next(i);
  3986. }
  3987. void upb_inttable_next(upb_inttable_iter *iter) {
  3988. const upb_inttable *t = iter->t;
  3989. if (iter->array_part) {
  3990. while (++iter->index < t->array_size) {
  3991. if (upb_arrhas(int_arrent(iter))) {
  3992. return;
  3993. }
  3994. }
  3995. iter->array_part = false;
  3996. iter->index = begin(&t->t);
  3997. } else {
  3998. iter->index = next(&t->t, iter->index);
  3999. }
  4000. }
  4001. bool upb_inttable_done(const upb_inttable_iter *i) {
  4002. if (i->array_part) {
  4003. return i->index >= i->t->array_size ||
  4004. !upb_arrhas(int_arrent(i));
  4005. } else {
  4006. return i->index >= upb_table_size(&i->t->t) ||
  4007. upb_tabent_isempty(int_tabent(i));
  4008. }
  4009. }
  4010. uintptr_t upb_inttable_iter_key(const upb_inttable_iter *i) {
  4011. assert(!upb_inttable_done(i));
  4012. return i->array_part ? i->index : int_tabent(i)->key;
  4013. }
  4014. upb_value upb_inttable_iter_value(const upb_inttable_iter *i) {
  4015. assert(!upb_inttable_done(i));
  4016. return _upb_value_val(
  4017. i->array_part ? i->t->array[i->index].val : int_tabent(i)->val.val,
  4018. i->t->t.ctype);
  4019. }
  4020. void upb_inttable_iter_setdone(upb_inttable_iter *i) {
  4021. i->index = SIZE_MAX;
  4022. i->array_part = false;
  4023. }
  4024. bool upb_inttable_iter_isequal(const upb_inttable_iter *i1,
  4025. const upb_inttable_iter *i2) {
  4026. if (upb_inttable_done(i1) && upb_inttable_done(i2))
  4027. return true;
  4028. return i1->t == i2->t && i1->index == i2->index &&
  4029. i1->array_part == i2->array_part;
  4030. }
  4031. #ifdef UPB_UNALIGNED_READS_OK
  4032. /* -----------------------------------------------------------------------------
  4033. * MurmurHash2, by Austin Appleby (released as public domain).
  4034. * Reformatted and C99-ified by Joshua Haberman.
  4035. * Note - This code makes a few assumptions about how your machine behaves -
  4036. * 1. We can read a 4-byte value from any address without crashing
  4037. * 2. sizeof(int) == 4 (in upb this limitation is removed by using uint32_t
  4038. * And it has a few limitations -
  4039. * 1. It will not work incrementally.
  4040. * 2. It will not produce the same results on little-endian and big-endian
  4041. * machines. */
  4042. uint32_t MurmurHash2(const void *key, size_t len, uint32_t seed) {
  4043. /* 'm' and 'r' are mixing constants generated offline.
  4044. * They're not really 'magic', they just happen to work well. */
  4045. const uint32_t m = 0x5bd1e995;
  4046. const int32_t r = 24;
  4047. /* Initialize the hash to a 'random' value */
  4048. uint32_t h = seed ^ len;
  4049. /* Mix 4 bytes at a time into the hash */
  4050. const uint8_t * data = (const uint8_t *)key;
  4051. while(len >= 4) {
  4052. uint32_t k = *(uint32_t *)data;
  4053. k *= m;
  4054. k ^= k >> r;
  4055. k *= m;
  4056. h *= m;
  4057. h ^= k;
  4058. data += 4;
  4059. len -= 4;
  4060. }
  4061. /* Handle the last few bytes of the input array */
  4062. switch(len) {
  4063. case 3: h ^= data[2] << 16;
  4064. case 2: h ^= data[1] << 8;
  4065. case 1: h ^= data[0]; h *= m;
  4066. };
  4067. /* Do a few final mixes of the hash to ensure the last few
  4068. * bytes are well-incorporated. */
  4069. h ^= h >> 13;
  4070. h *= m;
  4071. h ^= h >> 15;
  4072. return h;
  4073. }
  4074. #else /* !UPB_UNALIGNED_READS_OK */
  4075. /* -----------------------------------------------------------------------------
  4076. * MurmurHashAligned2, by Austin Appleby
  4077. * Same algorithm as MurmurHash2, but only does aligned reads - should be safer
  4078. * on certain platforms.
  4079. * Performance will be lower than MurmurHash2 */
  4080. #define MIX(h,k,m) { k *= m; k ^= k >> r; k *= m; h *= m; h ^= k; }
  4081. uint32_t MurmurHash2(const void * key, size_t len, uint32_t seed) {
  4082. const uint32_t m = 0x5bd1e995;
  4083. const int32_t r = 24;
  4084. const uint8_t * data = (const uint8_t *)key;
  4085. uint32_t h = seed ^ len;
  4086. uint8_t align = (uintptr_t)data & 3;
  4087. if(align && (len >= 4)) {
  4088. /* Pre-load the temp registers */
  4089. uint32_t t = 0, d = 0;
  4090. int32_t sl;
  4091. int32_t sr;
  4092. switch(align) {
  4093. case 1: t |= data[2] << 16;
  4094. case 2: t |= data[1] << 8;
  4095. case 3: t |= data[0];
  4096. }
  4097. t <<= (8 * align);
  4098. data += 4-align;
  4099. len -= 4-align;
  4100. sl = 8 * (4-align);
  4101. sr = 8 * align;
  4102. /* Mix */
  4103. while(len >= 4) {
  4104. uint32_t k;
  4105. d = *(uint32_t *)data;
  4106. t = (t >> sr) | (d << sl);
  4107. k = t;
  4108. MIX(h,k,m);
  4109. t = d;
  4110. data += 4;
  4111. len -= 4;
  4112. }
  4113. /* Handle leftover data in temp registers */
  4114. d = 0;
  4115. if(len >= align) {
  4116. uint32_t k;
  4117. switch(align) {
  4118. case 3: d |= data[2] << 16;
  4119. case 2: d |= data[1] << 8;
  4120. case 1: d |= data[0];
  4121. }
  4122. k = (t >> sr) | (d << sl);
  4123. MIX(h,k,m);
  4124. data += align;
  4125. len -= align;
  4126. /* ----------
  4127. * Handle tail bytes */
  4128. switch(len) {
  4129. case 3: h ^= data[2] << 16;
  4130. case 2: h ^= data[1] << 8;
  4131. case 1: h ^= data[0]; h *= m;
  4132. };
  4133. } else {
  4134. switch(len) {
  4135. case 3: d |= data[2] << 16;
  4136. case 2: d |= data[1] << 8;
  4137. case 1: d |= data[0];
  4138. case 0: h ^= (t >> sr) | (d << sl); h *= m;
  4139. }
  4140. }
  4141. h ^= h >> 13;
  4142. h *= m;
  4143. h ^= h >> 15;
  4144. return h;
  4145. } else {
  4146. while(len >= 4) {
  4147. uint32_t k = *(uint32_t *)data;
  4148. MIX(h,k,m);
  4149. data += 4;
  4150. len -= 4;
  4151. }
  4152. /* ----------
  4153. * Handle tail bytes */
  4154. switch(len) {
  4155. case 3: h ^= data[2] << 16;
  4156. case 2: h ^= data[1] << 8;
  4157. case 1: h ^= data[0]; h *= m;
  4158. };
  4159. h ^= h >> 13;
  4160. h *= m;
  4161. h ^= h >> 15;
  4162. return h;
  4163. }
  4164. }
  4165. #undef MIX
  4166. #endif /* UPB_UNALIGNED_READS_OK */
  4167. /*
  4168. * upb - a minimalist implementation of protocol buffers.
  4169. *
  4170. * Copyright (c) 2009-2012 Google Inc. See LICENSE for details.
  4171. * Author: Josh Haberman <jhaberman@gmail.com>
  4172. */
  4173. #include <errno.h>
  4174. #include <stdarg.h>
  4175. #include <stddef.h>
  4176. #include <stdint.h>
  4177. #include <stdio.h>
  4178. #include <stdlib.h>
  4179. #include <string.h>
  4180. bool upb_dumptostderr(void *closure, const upb_status* status) {
  4181. UPB_UNUSED(closure);
  4182. fprintf(stderr, "%s\n", upb_status_errmsg(status));
  4183. return false;
  4184. }
  4185. /* Guarantee null-termination and provide ellipsis truncation.
  4186. * It may be tempting to "optimize" this by initializing these final
  4187. * four bytes up-front and then being careful never to overwrite them,
  4188. * this is safer and simpler. */
  4189. static void nullz(upb_status *status) {
  4190. const char *ellipsis = "...";
  4191. size_t len = strlen(ellipsis);
  4192. assert(sizeof(status->msg) > len);
  4193. memcpy(status->msg + sizeof(status->msg) - len, ellipsis, len);
  4194. }
  4195. void upb_status_clear(upb_status *status) {
  4196. if (!status) return;
  4197. status->ok_ = true;
  4198. status->code_ = 0;
  4199. status->msg[0] = '\0';
  4200. }
  4201. bool upb_ok(const upb_status *status) { return status->ok_; }
  4202. upb_errorspace *upb_status_errspace(const upb_status *status) {
  4203. return status->error_space_;
  4204. }
  4205. int upb_status_errcode(const upb_status *status) { return status->code_; }
  4206. const char *upb_status_errmsg(const upb_status *status) { return status->msg; }
  4207. void upb_status_seterrmsg(upb_status *status, const char *msg) {
  4208. if (!status) return;
  4209. status->ok_ = false;
  4210. strncpy(status->msg, msg, sizeof(status->msg));
  4211. nullz(status);
  4212. }
  4213. void upb_status_seterrf(upb_status *status, const char *fmt, ...) {
  4214. va_list args;
  4215. va_start(args, fmt);
  4216. upb_status_vseterrf(status, fmt, args);
  4217. va_end(args);
  4218. }
  4219. void upb_status_vseterrf(upb_status *status, const char *fmt, va_list args) {
  4220. if (!status) return;
  4221. status->ok_ = false;
  4222. _upb_vsnprintf(status->msg, sizeof(status->msg), fmt, args);
  4223. nullz(status);
  4224. }
  4225. void upb_status_seterrcode(upb_status *status, upb_errorspace *space,
  4226. int code) {
  4227. if (!status) return;
  4228. status->ok_ = false;
  4229. status->error_space_ = space;
  4230. status->code_ = code;
  4231. space->set_message(status, code);
  4232. }
  4233. void upb_status_copy(upb_status *to, const upb_status *from) {
  4234. if (!to) return;
  4235. *to = *from;
  4236. }
  4237. /* This file was generated by upbc (the upb compiler).
  4238. * Do not edit -- your changes will be discarded when the file is
  4239. * regenerated. */
  4240. static const upb_msgdef msgs[20];
  4241. static const upb_fielddef fields[81];
  4242. static const upb_enumdef enums[4];
  4243. static const upb_tabent strentries[236];
  4244. static const upb_tabent intentries[14];
  4245. static const upb_tabval arrays[232];
  4246. #ifdef UPB_DEBUG_REFS
  4247. static upb_inttable reftables[212];
  4248. #endif
  4249. static const upb_msgdef msgs[20] = {
  4250. UPB_MSGDEF_INIT("google.protobuf.DescriptorProto", 27, 6, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[0], 8, 7), UPB_STRTABLE_INIT(7, 15, UPB_CTYPE_PTR, 4, &strentries[0]),&reftables[0], &reftables[1]),
  4251. UPB_MSGDEF_INIT("google.protobuf.DescriptorProto.ExtensionRange", 4, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[8], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[16]),&reftables[2], &reftables[3]),
  4252. UPB_MSGDEF_INIT("google.protobuf.EnumDescriptorProto", 11, 2, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[11], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[20]),&reftables[4], &reftables[5]),
  4253. UPB_MSGDEF_INIT("google.protobuf.EnumOptions", 7, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[0], &arrays[15], 8, 1), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[24]),&reftables[6], &reftables[7]),
  4254. UPB_MSGDEF_INIT("google.protobuf.EnumValueDescriptorProto", 8, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[23], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[28]),&reftables[8], &reftables[9]),
  4255. UPB_MSGDEF_INIT("google.protobuf.EnumValueOptions", 6, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[2], &arrays[27], 4, 0), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[32]),&reftables[10], &reftables[11]),
  4256. UPB_MSGDEF_INIT("google.protobuf.FieldDescriptorProto", 19, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[31], 9, 8), UPB_STRTABLE_INIT(8, 15, UPB_CTYPE_PTR, 4, &strentries[36]),&reftables[12], &reftables[13]),
  4257. UPB_MSGDEF_INIT("google.protobuf.FieldOptions", 14, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[4], &arrays[40], 32, 6), UPB_STRTABLE_INIT(7, 15, UPB_CTYPE_PTR, 4, &strentries[52]),&reftables[14], &reftables[15]),
  4258. UPB_MSGDEF_INIT("google.protobuf.FileDescriptorProto", 39, 6, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[72], 12, 11), UPB_STRTABLE_INIT(11, 15, UPB_CTYPE_PTR, 4, &strentries[68]),&reftables[16], &reftables[17]),
  4259. UPB_MSGDEF_INIT("google.protobuf.FileDescriptorSet", 6, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[84], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[84]),&reftables[18], &reftables[19]),
  4260. UPB_MSGDEF_INIT("google.protobuf.FileOptions", 21, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[6], &arrays[86], 64, 9), UPB_STRTABLE_INIT(10, 15, UPB_CTYPE_PTR, 4, &strentries[88]),&reftables[20], &reftables[21]),
  4261. UPB_MSGDEF_INIT("google.protobuf.MessageOptions", 8, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[8], &arrays[150], 16, 2), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[104]),&reftables[22], &reftables[23]),
  4262. UPB_MSGDEF_INIT("google.protobuf.MethodDescriptorProto", 13, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[166], 5, 4), UPB_STRTABLE_INIT(4, 7, UPB_CTYPE_PTR, 3, &strentries[108]),&reftables[24], &reftables[25]),
  4263. UPB_MSGDEF_INIT("google.protobuf.MethodOptions", 6, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[10], &arrays[171], 4, 0), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[116]),&reftables[26], &reftables[27]),
  4264. UPB_MSGDEF_INIT("google.protobuf.ServiceDescriptorProto", 11, 2, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[175], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[120]),&reftables[28], &reftables[29]),
  4265. UPB_MSGDEF_INIT("google.protobuf.ServiceOptions", 6, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[12], &arrays[179], 4, 0), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[124]),&reftables[30], &reftables[31]),
  4266. UPB_MSGDEF_INIT("google.protobuf.SourceCodeInfo", 6, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[183], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[128]),&reftables[32], &reftables[33]),
  4267. UPB_MSGDEF_INIT("google.protobuf.SourceCodeInfo.Location", 14, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[185], 5, 4), UPB_STRTABLE_INIT(4, 7, UPB_CTYPE_PTR, 3, &strentries[132]),&reftables[34], &reftables[35]),
  4268. UPB_MSGDEF_INIT("google.protobuf.UninterpretedOption", 18, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[190], 9, 7), UPB_STRTABLE_INIT(7, 15, UPB_CTYPE_PTR, 4, &strentries[140]),&reftables[36], &reftables[37]),
  4269. UPB_MSGDEF_INIT("google.protobuf.UninterpretedOption.NamePart", 6, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[199], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[156]),&reftables[38], &reftables[39]),
  4270. };
  4271. static const upb_fielddef fields[81] = {
  4272. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "aggregate_value", 8, &msgs[18], NULL, 15, 6, {0},&reftables[40], &reftables[41]),
  4273. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "allow_alias", 2, &msgs[3], NULL, 6, 1, {0},&reftables[42], &reftables[43]),
  4274. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "cc_generic_services", 16, &msgs[10], NULL, 17, 6, {0},&reftables[44], &reftables[45]),
  4275. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "ctype", 1, &msgs[7], (const upb_def*)(&enums[2]), 6, 1, {0},&reftables[46], &reftables[47]),
  4276. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "default_value", 7, &msgs[6], NULL, 16, 7, {0},&reftables[48], &reftables[49]),
  4277. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_STRING, 0, false, false, false, false, "dependency", 3, &msgs[8], NULL, 30, 8, {0},&reftables[50], &reftables[51]),
  4278. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[7], NULL, 8, 3, {0},&reftables[52], &reftables[53]),
  4279. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_DOUBLE, 0, false, false, false, false, "double_value", 6, &msgs[18], NULL, 11, 4, {0},&reftables[54], &reftables[55]),
  4280. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "end", 2, &msgs[1], NULL, 3, 1, {0},&reftables[56], &reftables[57]),
  4281. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "enum_type", 4, &msgs[0], (const upb_def*)(&msgs[2]), 16, 2, {0},&reftables[58], &reftables[59]),
  4282. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "enum_type", 5, &msgs[8], (const upb_def*)(&msgs[2]), 13, 1, {0},&reftables[60], &reftables[61]),
  4283. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "experimental_map_key", 9, &msgs[7], NULL, 10, 5, {0},&reftables[62], &reftables[63]),
  4284. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "extendee", 2, &msgs[6], NULL, 7, 2, {0},&reftables[64], &reftables[65]),
  4285. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension", 7, &msgs[8], (const upb_def*)(&msgs[6]), 19, 3, {0},&reftables[66], &reftables[67]),
  4286. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension", 6, &msgs[0], (const upb_def*)(&msgs[6]), 22, 4, {0},&reftables[68], &reftables[69]),
  4287. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension_range", 5, &msgs[0], (const upb_def*)(&msgs[1]), 19, 3, {0},&reftables[70], &reftables[71]),
  4288. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "field", 2, &msgs[0], (const upb_def*)(&msgs[6]), 10, 0, {0},&reftables[72], &reftables[73]),
  4289. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "file", 1, &msgs[9], (const upb_def*)(&msgs[8]), 5, 0, {0},&reftables[74], &reftables[75]),
  4290. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "go_package", 11, &msgs[10], NULL, 14, 5, {0},&reftables[76], &reftables[77]),
  4291. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "identifier_value", 3, &msgs[18], NULL, 6, 1, {0},&reftables[78], &reftables[79]),
  4292. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "input_type", 2, &msgs[12], NULL, 7, 2, {0},&reftables[80], &reftables[81]),
  4293. UPB_FIELDDEF_INIT(UPB_LABEL_REQUIRED, UPB_TYPE_BOOL, 0, false, false, false, false, "is_extension", 2, &msgs[19], NULL, 5, 1, {0},&reftables[82], &reftables[83]),
  4294. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_generate_equals_and_hash", 20, &msgs[10], NULL, 20, 9, {0},&reftables[84], &reftables[85]),
  4295. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_generic_services", 17, &msgs[10], NULL, 18, 7, {0},&reftables[86], &reftables[87]),
  4296. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_multiple_files", 10, &msgs[10], NULL, 13, 4, {0},&reftables[88], &reftables[89]),
  4297. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "java_outer_classname", 8, &msgs[10], NULL, 9, 2, {0},&reftables[90], &reftables[91]),
  4298. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "java_package", 1, &msgs[10], NULL, 6, 1, {0},&reftables[92], &reftables[93]),
  4299. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "label", 4, &msgs[6], (const upb_def*)(&enums[0]), 11, 4, {0},&reftables[94], &reftables[95]),
  4300. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "lazy", 5, &msgs[7], NULL, 9, 4, {0},&reftables[96], &reftables[97]),
  4301. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "leading_comments", 3, &msgs[17], NULL, 8, 2, {0},&reftables[98], &reftables[99]),
  4302. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "location", 1, &msgs[16], (const upb_def*)(&msgs[17]), 5, 0, {0},&reftables[100], &reftables[101]),
  4303. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "message_set_wire_format", 1, &msgs[11], NULL, 6, 1, {0},&reftables[102], &reftables[103]),
  4304. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "message_type", 4, &msgs[8], (const upb_def*)(&msgs[0]), 10, 0, {0},&reftables[104], &reftables[105]),
  4305. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "method", 2, &msgs[14], (const upb_def*)(&msgs[12]), 6, 0, {0},&reftables[106], &reftables[107]),
  4306. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[8], NULL, 22, 6, {0},&reftables[108], &reftables[109]),
  4307. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[14], NULL, 8, 2, {0},&reftables[110], &reftables[111]),
  4308. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "name", 2, &msgs[18], (const upb_def*)(&msgs[19]), 5, 0, {0},&reftables[112], &reftables[113]),
  4309. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[4], NULL, 4, 1, {0},&reftables[114], &reftables[115]),
  4310. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[0], NULL, 24, 6, {0},&reftables[116], &reftables[117]),
  4311. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[12], NULL, 4, 1, {0},&reftables[118], &reftables[119]),
  4312. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[2], NULL, 8, 2, {0},&reftables[120], &reftables[121]),
  4313. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[6], NULL, 4, 1, {0},&reftables[122], &reftables[123]),
  4314. UPB_FIELDDEF_INIT(UPB_LABEL_REQUIRED, UPB_TYPE_STRING, 0, false, false, false, false, "name_part", 1, &msgs[19], NULL, 2, 0, {0},&reftables[124], &reftables[125]),
  4315. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT64, UPB_INTFMT_VARIABLE, false, false, false, false, "negative_int_value", 5, &msgs[18], NULL, 10, 3, {0},&reftables[126], &reftables[127]),
  4316. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "nested_type", 3, &msgs[0], (const upb_def*)(&msgs[0]), 13, 1, {0},&reftables[128], &reftables[129]),
  4317. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "no_standard_descriptor_accessor", 2, &msgs[11], NULL, 7, 2, {0},&reftables[130], &reftables[131]),
  4318. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "number", 3, &msgs[6], NULL, 10, 3, {0},&reftables[132], &reftables[133]),
  4319. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "number", 2, &msgs[4], NULL, 7, 2, {0},&reftables[134], &reftables[135]),
  4320. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "optimize_for", 9, &msgs[10], (const upb_def*)(&enums[3]), 12, 3, {0},&reftables[136], &reftables[137]),
  4321. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 7, &msgs[0], (const upb_def*)(&msgs[11]), 23, 5, {0},&reftables[138], &reftables[139]),
  4322. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[2], (const upb_def*)(&msgs[3]), 7, 1, {0},&reftables[140], &reftables[141]),
  4323. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 8, &msgs[6], (const upb_def*)(&msgs[7]), 3, 0, {0},&reftables[142], &reftables[143]),
  4324. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[4], (const upb_def*)(&msgs[5]), 3, 0, {0},&reftables[144], &reftables[145]),
  4325. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 8, &msgs[8], (const upb_def*)(&msgs[10]), 20, 4, {0},&reftables[146], &reftables[147]),
  4326. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[14], (const upb_def*)(&msgs[15]), 7, 1, {0},&reftables[148], &reftables[149]),
  4327. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 4, &msgs[12], (const upb_def*)(&msgs[13]), 3, 0, {0},&reftables[150], &reftables[151]),
  4328. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "output_type", 3, &msgs[12], NULL, 10, 3, {0},&reftables[152], &reftables[153]),
  4329. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "package", 2, &msgs[8], NULL, 25, 7, {0},&reftables[154], &reftables[155]),
  4330. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "packed", 2, &msgs[7], NULL, 7, 2, {0},&reftables[156], &reftables[157]),
  4331. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, true, "path", 1, &msgs[17], NULL, 4, 0, {0},&reftables[158], &reftables[159]),
  4332. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_UINT64, UPB_INTFMT_VARIABLE, false, false, false, false, "positive_int_value", 4, &msgs[18], NULL, 9, 2, {0},&reftables[160], &reftables[161]),
  4333. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "public_dependency", 10, &msgs[8], NULL, 35, 9, {0},&reftables[162], &reftables[163]),
  4334. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "py_generic_services", 18, &msgs[10], NULL, 19, 8, {0},&reftables[164], &reftables[165]),
  4335. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "service", 6, &msgs[8], (const upb_def*)(&msgs[14]), 16, 2, {0},&reftables[166], &reftables[167]),
  4336. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "source_code_info", 9, &msgs[8], (const upb_def*)(&msgs[16]), 21, 5, {0},&reftables[168], &reftables[169]),
  4337. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, true, "span", 2, &msgs[17], NULL, 7, 1, {0},&reftables[170], &reftables[171]),
  4338. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "start", 1, &msgs[1], NULL, 2, 0, {0},&reftables[172], &reftables[173]),
  4339. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BYTES, 0, false, false, false, false, "string_value", 7, &msgs[18], NULL, 12, 5, {0},&reftables[174], &reftables[175]),
  4340. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "trailing_comments", 4, &msgs[17], NULL, 11, 3, {0},&reftables[176], &reftables[177]),
  4341. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "type", 5, &msgs[6], (const upb_def*)(&enums[1]), 12, 5, {0},&reftables[178], &reftables[179]),
  4342. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "type_name", 6, &msgs[6], NULL, 13, 6, {0},&reftables[180], &reftables[181]),
  4343. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[5], (const upb_def*)(&msgs[18]), 5, 0, {0},&reftables[182], &reftables[183]),
  4344. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[15], (const upb_def*)(&msgs[18]), 5, 0, {0},&reftables[184], &reftables[185]),
  4345. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[3], (const upb_def*)(&msgs[18]), 5, 0, {0},&reftables[186], &reftables[187]),
  4346. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[13], (const upb_def*)(&msgs[18]), 5, 0, {0},&reftables[188], &reftables[189]),
  4347. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[10], (const upb_def*)(&msgs[18]), 5, 0, {0},&reftables[190], &reftables[191]),
  4348. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[11], (const upb_def*)(&msgs[18]), 5, 0, {0},&reftables[192], &reftables[193]),
  4349. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[7], (const upb_def*)(&msgs[18]), 5, 0, {0},&reftables[194], &reftables[195]),
  4350. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "value", 2, &msgs[2], (const upb_def*)(&msgs[4]), 6, 0, {0},&reftables[196], &reftables[197]),
  4351. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "weak", 10, &msgs[7], NULL, 13, 6, {0},&reftables[198], &reftables[199]),
  4352. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "weak_dependency", 11, &msgs[8], NULL, 38, 10, {0},&reftables[200], &reftables[201]),
  4353. };
  4354. static const upb_enumdef enums[4] = {
  4355. UPB_ENUMDEF_INIT("google.protobuf.FieldDescriptorProto.Label", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[160]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[202], 4, 3), 0, &reftables[202], &reftables[203]),
  4356. UPB_ENUMDEF_INIT("google.protobuf.FieldDescriptorProto.Type", UPB_STRTABLE_INIT(18, 31, UPB_CTYPE_INT32, 5, &strentries[164]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[206], 19, 18), 0, &reftables[204], &reftables[205]),
  4357. UPB_ENUMDEF_INIT("google.protobuf.FieldOptions.CType", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[196]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[225], 3, 3), 0, &reftables[206], &reftables[207]),
  4358. UPB_ENUMDEF_INIT("google.protobuf.FileOptions.OptimizeMode", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[200]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[228], 4, 3), 0, &reftables[208], &reftables[209]),
  4359. };
  4360. static const upb_tabent strentries[236] = {
  4361. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "extension"), UPB_TABVALUE_PTR_INIT(&fields[14]), NULL},
  4362. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4363. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4364. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[38]), NULL},
  4365. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4366. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4367. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4368. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "field"), UPB_TABVALUE_PTR_INIT(&fields[16]), NULL},
  4369. {UPB_TABKEY_STR("\017", "\000", "\000", "\000", "extension_range"), UPB_TABVALUE_PTR_INIT(&fields[15]), NULL},
  4370. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4371. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "nested_type"), UPB_TABVALUE_PTR_INIT(&fields[44]), NULL},
  4372. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4373. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4374. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4375. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[49]), NULL},
  4376. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "enum_type"), UPB_TABVALUE_PTR_INIT(&fields[9]), &strentries[14]},
  4377. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "start"), UPB_TABVALUE_PTR_INIT(&fields[66]), NULL},
  4378. {UPB_TABKEY_STR("\003", "\000", "\000", "\000", "end"), UPB_TABVALUE_PTR_INIT(&fields[8]), NULL},
  4379. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4380. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4381. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4382. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "value"), UPB_TABVALUE_PTR_INIT(&fields[78]), NULL},
  4383. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[50]), NULL},
  4384. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[40]), &strentries[22]},
  4385. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[73]), NULL},
  4386. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4387. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "allow_alias"), UPB_TABVALUE_PTR_INIT(&fields[1]), NULL},
  4388. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4389. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "number"), UPB_TABVALUE_PTR_INIT(&fields[47]), NULL},
  4390. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4391. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[52]), NULL},
  4392. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[37]), &strentries[30]},
  4393. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[71]), NULL},
  4394. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4395. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4396. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4397. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4398. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "label"), UPB_TABVALUE_PTR_INIT(&fields[27]), NULL},
  4399. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4400. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[41]), NULL},
  4401. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4402. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4403. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4404. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4405. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "number"), UPB_TABVALUE_PTR_INIT(&fields[46]), &strentries[49]},
  4406. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4407. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4408. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "type_name"), UPB_TABVALUE_PTR_INIT(&fields[70]), NULL},
  4409. {UPB_TABKEY_STR("\010", "\000", "\000", "\000", "extendee"), UPB_TABVALUE_PTR_INIT(&fields[12]), NULL},
  4410. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "type"), UPB_TABVALUE_PTR_INIT(&fields[69]), &strentries[48]},
  4411. {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "default_value"), UPB_TABVALUE_PTR_INIT(&fields[4]), NULL},
  4412. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[51]), NULL},
  4413. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "experimental_map_key"), UPB_TABVALUE_PTR_INIT(&fields[11]), &strentries[67]},
  4414. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4415. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "weak"), UPB_TABVALUE_PTR_INIT(&fields[79]), NULL},
  4416. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4417. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4418. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4419. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4420. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "packed"), UPB_TABVALUE_PTR_INIT(&fields[58]), NULL},
  4421. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "lazy"), UPB_TABVALUE_PTR_INIT(&fields[28]), NULL},
  4422. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4423. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "ctype"), UPB_TABVALUE_PTR_INIT(&fields[3]), NULL},
  4424. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4425. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4426. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[6]), NULL},
  4427. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4428. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[77]), NULL},
  4429. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "extension"), UPB_TABVALUE_PTR_INIT(&fields[13]), NULL},
  4430. {UPB_TABKEY_STR("\017", "\000", "\000", "\000", "weak_dependency"), UPB_TABVALUE_PTR_INIT(&fields[80]), NULL},
  4431. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4432. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[34]), NULL},
  4433. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "service"), UPB_TABVALUE_PTR_INIT(&fields[63]), NULL},
  4434. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4435. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "source_code_info"), UPB_TABVALUE_PTR_INIT(&fields[64]), NULL},
  4436. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4437. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4438. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4439. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "dependency"), UPB_TABVALUE_PTR_INIT(&fields[5]), NULL},
  4440. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "message_type"), UPB_TABVALUE_PTR_INIT(&fields[32]), NULL},
  4441. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "package"), UPB_TABVALUE_PTR_INIT(&fields[57]), NULL},
  4442. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[53]), &strentries[82]},
  4443. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "enum_type"), UPB_TABVALUE_PTR_INIT(&fields[10]), NULL},
  4444. {UPB_TABKEY_STR("\021", "\000", "\000", "\000", "public_dependency"), UPB_TABVALUE_PTR_INIT(&fields[61]), &strentries[81]},
  4445. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4446. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "file"), UPB_TABVALUE_PTR_INIT(&fields[17]), NULL},
  4447. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4448. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4449. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[75]), NULL},
  4450. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4451. {UPB_TABKEY_STR("\023", "\000", "\000", "\000", "cc_generic_services"), UPB_TABVALUE_PTR_INIT(&fields[2]), NULL},
  4452. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4453. {UPB_TABKEY_STR("\023", "\000", "\000", "\000", "java_multiple_files"), UPB_TABVALUE_PTR_INIT(&fields[24]), NULL},
  4454. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4455. {UPB_TABKEY_STR("\025", "\000", "\000", "\000", "java_generic_services"), UPB_TABVALUE_PTR_INIT(&fields[23]), &strentries[102]},
  4456. {UPB_TABKEY_STR("\035", "\000", "\000", "\000", "java_generate_equals_and_hash"), UPB_TABVALUE_PTR_INIT(&fields[22]), NULL},
  4457. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4458. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4459. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4460. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "go_package"), UPB_TABVALUE_PTR_INIT(&fields[18]), NULL},
  4461. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "java_package"), UPB_TABVALUE_PTR_INIT(&fields[26]), NULL},
  4462. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "optimize_for"), UPB_TABVALUE_PTR_INIT(&fields[48]), NULL},
  4463. {UPB_TABKEY_STR("\023", "\000", "\000", "\000", "py_generic_services"), UPB_TABVALUE_PTR_INIT(&fields[62]), NULL},
  4464. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "java_outer_classname"), UPB_TABVALUE_PTR_INIT(&fields[25]), NULL},
  4465. {UPB_TABKEY_STR("\027", "\000", "\000", "\000", "message_set_wire_format"), UPB_TABVALUE_PTR_INIT(&fields[31]), &strentries[106]},
  4466. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4467. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[76]), NULL},
  4468. {UPB_TABKEY_STR("\037", "\000", "\000", "\000", "no_standard_descriptor_accessor"), UPB_TABVALUE_PTR_INIT(&fields[45]), NULL},
  4469. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4470. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4471. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4472. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[39]), NULL},
  4473. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "input_type"), UPB_TABVALUE_PTR_INIT(&fields[20]), NULL},
  4474. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4475. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "output_type"), UPB_TABVALUE_PTR_INIT(&fields[56]), NULL},
  4476. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[55]), NULL},
  4477. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[74]), NULL},
  4478. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4479. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4480. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4481. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4482. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[54]), &strentries[122]},
  4483. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "method"), UPB_TABVALUE_PTR_INIT(&fields[33]), NULL},
  4484. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[35]), &strentries[121]},
  4485. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[72]), NULL},
  4486. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4487. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4488. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4489. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4490. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4491. {UPB_TABKEY_STR("\010", "\000", "\000", "\000", "location"), UPB_TABVALUE_PTR_INIT(&fields[30]), NULL},
  4492. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4493. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4494. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4495. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4496. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "span"), UPB_TABVALUE_PTR_INIT(&fields[65]), &strentries[139]},
  4497. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4498. {UPB_TABKEY_STR("\021", "\000", "\000", "\000", "trailing_comments"), UPB_TABVALUE_PTR_INIT(&fields[68]), NULL},
  4499. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "leading_comments"), UPB_TABVALUE_PTR_INIT(&fields[29]), &strentries[137]},
  4500. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "path"), UPB_TABVALUE_PTR_INIT(&fields[59]), NULL},
  4501. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "double_value"), UPB_TABVALUE_PTR_INIT(&fields[7]), NULL},
  4502. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4503. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4504. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[36]), NULL},
  4505. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4506. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4507. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4508. {UPB_TABKEY_STR("\022", "\000", "\000", "\000", "negative_int_value"), UPB_TABVALUE_PTR_INIT(&fields[43]), NULL},
  4509. {UPB_TABKEY_STR("\017", "\000", "\000", "\000", "aggregate_value"), UPB_TABVALUE_PTR_INIT(&fields[0]), NULL},
  4510. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4511. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4512. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4513. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4514. {UPB_TABKEY_STR("\022", "\000", "\000", "\000", "positive_int_value"), UPB_TABVALUE_PTR_INIT(&fields[60]), NULL},
  4515. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "identifier_value"), UPB_TABVALUE_PTR_INIT(&fields[19]), NULL},
  4516. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "string_value"), UPB_TABVALUE_PTR_INIT(&fields[67]), &strentries[154]},
  4517. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4518. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4519. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "is_extension"), UPB_TABVALUE_PTR_INIT(&fields[21]), NULL},
  4520. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "name_part"), UPB_TABVALUE_PTR_INIT(&fields[42]), NULL},
  4521. {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "LABEL_REQUIRED"), UPB_TABVALUE_INT_INIT(2), &strentries[162]},
  4522. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4523. {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "LABEL_REPEATED"), UPB_TABVALUE_INT_INIT(3), NULL},
  4524. {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "LABEL_OPTIONAL"), UPB_TABVALUE_INT_INIT(1), NULL},
  4525. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "TYPE_FIXED64"), UPB_TABVALUE_INT_INIT(6), NULL},
  4526. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4527. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4528. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4529. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4530. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_STRING"), UPB_TABVALUE_INT_INIT(9), NULL},
  4531. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_FLOAT"), UPB_TABVALUE_INT_INIT(2), &strentries[193]},
  4532. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_DOUBLE"), UPB_TABVALUE_INT_INIT(1), NULL},
  4533. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4534. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_INT32"), UPB_TABVALUE_INT_INIT(5), NULL},
  4535. {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "TYPE_SFIXED32"), UPB_TABVALUE_INT_INIT(15), NULL},
  4536. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "TYPE_FIXED32"), UPB_TABVALUE_INT_INIT(7), NULL},
  4537. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4538. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "TYPE_MESSAGE"), UPB_TABVALUE_INT_INIT(11), &strentries[194]},
  4539. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4540. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4541. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_INT64"), UPB_TABVALUE_INT_INIT(3), &strentries[191]},
  4542. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4543. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4544. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4545. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4546. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "TYPE_ENUM"), UPB_TABVALUE_INT_INIT(14), NULL},
  4547. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_UINT32"), UPB_TABVALUE_INT_INIT(13), NULL},
  4548. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4549. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_UINT64"), UPB_TABVALUE_INT_INIT(4), &strentries[190]},
  4550. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4551. {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "TYPE_SFIXED64"), UPB_TABVALUE_INT_INIT(16), NULL},
  4552. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_BYTES"), UPB_TABVALUE_INT_INIT(12), NULL},
  4553. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_SINT64"), UPB_TABVALUE_INT_INIT(18), NULL},
  4554. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "TYPE_BOOL"), UPB_TABVALUE_INT_INIT(8), NULL},
  4555. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_GROUP"), UPB_TABVALUE_INT_INIT(10), NULL},
  4556. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_SINT32"), UPB_TABVALUE_INT_INIT(17), NULL},
  4557. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4558. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "CORD"), UPB_TABVALUE_INT_INIT(1), NULL},
  4559. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "STRING"), UPB_TABVALUE_INT_INIT(0), &strentries[197]},
  4560. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "STRING_PIECE"), UPB_TABVALUE_INT_INIT(2), NULL},
  4561. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "CODE_SIZE"), UPB_TABVALUE_INT_INIT(2), NULL},
  4562. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "SPEED"), UPB_TABVALUE_INT_INIT(1), &strentries[203]},
  4563. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4564. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "LITE_RUNTIME"), UPB_TABVALUE_INT_INIT(3), NULL},
  4565. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4566. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4567. {UPB_TABKEY_STR("\047", "\000", "\000", "\000", "google.protobuf.SourceCodeInfo.Location"), UPB_TABVALUE_PTR_INIT(&msgs[17]), NULL},
  4568. {UPB_TABKEY_STR("\043", "\000", "\000", "\000", "google.protobuf.UninterpretedOption"), UPB_TABVALUE_PTR_INIT(&msgs[18]), NULL},
  4569. {UPB_TABKEY_STR("\043", "\000", "\000", "\000", "google.protobuf.FileDescriptorProto"), UPB_TABVALUE_PTR_INIT(&msgs[8]), NULL},
  4570. {UPB_TABKEY_STR("\045", "\000", "\000", "\000", "google.protobuf.MethodDescriptorProto"), UPB_TABVALUE_PTR_INIT(&msgs[12]), NULL},
  4571. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4572. {UPB_TABKEY_STR("\040", "\000", "\000", "\000", "google.protobuf.EnumValueOptions"), UPB_TABVALUE_PTR_INIT(&msgs[5]), NULL},
  4573. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4574. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4575. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4576. {UPB_TABKEY_STR("\037", "\000", "\000", "\000", "google.protobuf.DescriptorProto"), UPB_TABVALUE_PTR_INIT(&msgs[0]), &strentries[228]},
  4577. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4578. {UPB_TABKEY_STR("\036", "\000", "\000", "\000", "google.protobuf.SourceCodeInfo"), UPB_TABVALUE_PTR_INIT(&msgs[16]), NULL},
  4579. {UPB_TABKEY_STR("\051", "\000", "\000", "\000", "google.protobuf.FieldDescriptorProto.Type"), UPB_TABVALUE_PTR_INIT(&enums[1]), NULL},
  4580. {UPB_TABKEY_STR("\056", "\000", "\000", "\000", "google.protobuf.DescriptorProto.ExtensionRange"), UPB_TABVALUE_PTR_INIT(&msgs[1]), NULL},
  4581. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4582. {UPB_TABKEY_STR("\050", "\000", "\000", "\000", "google.protobuf.EnumValueDescriptorProto"), UPB_TABVALUE_PTR_INIT(&msgs[4]), NULL},
  4583. {UPB_TABKEY_STR("\034", "\000", "\000", "\000", "google.protobuf.FieldOptions"), UPB_TABVALUE_PTR_INIT(&msgs[7]), NULL},
  4584. {UPB_TABKEY_STR("\033", "\000", "\000", "\000", "google.protobuf.FileOptions"), UPB_TABVALUE_PTR_INIT(&msgs[10]), NULL},
  4585. {UPB_TABKEY_STR("\043", "\000", "\000", "\000", "google.protobuf.EnumDescriptorProto"), UPB_TABVALUE_PTR_INIT(&msgs[2]), &strentries[233]},
  4586. {UPB_TABKEY_STR("\052", "\000", "\000", "\000", "google.protobuf.FieldDescriptorProto.Label"), UPB_TABVALUE_PTR_INIT(&enums[0]), NULL},
  4587. {UPB_TABKEY_STR("\046", "\000", "\000", "\000", "google.protobuf.ServiceDescriptorProto"), UPB_TABVALUE_PTR_INIT(&msgs[14]), NULL},
  4588. {UPB_TABKEY_STR("\042", "\000", "\000", "\000", "google.protobuf.FieldOptions.CType"), UPB_TABVALUE_PTR_INIT(&enums[2]), &strentries[229]},
  4589. {UPB_TABKEY_STR("\041", "\000", "\000", "\000", "google.protobuf.FileDescriptorSet"), UPB_TABVALUE_PTR_INIT(&msgs[9]), &strentries[235]},
  4590. {UPB_TABKEY_STR("\033", "\000", "\000", "\000", "google.protobuf.EnumOptions"), UPB_TABVALUE_PTR_INIT(&msgs[3]), NULL},
  4591. {UPB_TABKEY_STR("\044", "\000", "\000", "\000", "google.protobuf.FieldDescriptorProto"), UPB_TABVALUE_PTR_INIT(&msgs[6]), NULL},
  4592. {UPB_TABKEY_STR("\050", "\000", "\000", "\000", "google.protobuf.FileOptions.OptimizeMode"), UPB_TABVALUE_PTR_INIT(&enums[3]), &strentries[221]},
  4593. {UPB_TABKEY_STR("\036", "\000", "\000", "\000", "google.protobuf.ServiceOptions"), UPB_TABVALUE_PTR_INIT(&msgs[15]), NULL},
  4594. {UPB_TABKEY_STR("\036", "\000", "\000", "\000", "google.protobuf.MessageOptions"), UPB_TABVALUE_PTR_INIT(&msgs[11]), NULL},
  4595. {UPB_TABKEY_STR("\035", "\000", "\000", "\000", "google.protobuf.MethodOptions"), UPB_TABVALUE_PTR_INIT(&msgs[13]), &strentries[226]},
  4596. {UPB_TABKEY_STR("\054", "\000", "\000", "\000", "google.protobuf.UninterpretedOption.NamePart"), UPB_TABVALUE_PTR_INIT(&msgs[19]), NULL},
  4597. };
  4598. static const upb_tabent intentries[14] = {
  4599. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4600. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[73]), NULL},
  4601. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4602. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[71]), NULL},
  4603. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4604. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[77]), NULL},
  4605. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4606. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[75]), NULL},
  4607. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4608. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[76]), NULL},
  4609. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4610. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[74]), NULL},
  4611. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4612. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[72]), NULL},
  4613. };
  4614. static const upb_tabval arrays[232] = {
  4615. UPB_TABVALUE_EMPTY_INIT,
  4616. UPB_TABVALUE_PTR_INIT(&fields[38]),
  4617. UPB_TABVALUE_PTR_INIT(&fields[16]),
  4618. UPB_TABVALUE_PTR_INIT(&fields[44]),
  4619. UPB_TABVALUE_PTR_INIT(&fields[9]),
  4620. UPB_TABVALUE_PTR_INIT(&fields[15]),
  4621. UPB_TABVALUE_PTR_INIT(&fields[14]),
  4622. UPB_TABVALUE_PTR_INIT(&fields[49]),
  4623. UPB_TABVALUE_EMPTY_INIT,
  4624. UPB_TABVALUE_PTR_INIT(&fields[66]),
  4625. UPB_TABVALUE_PTR_INIT(&fields[8]),
  4626. UPB_TABVALUE_EMPTY_INIT,
  4627. UPB_TABVALUE_PTR_INIT(&fields[40]),
  4628. UPB_TABVALUE_PTR_INIT(&fields[78]),
  4629. UPB_TABVALUE_PTR_INIT(&fields[50]),
  4630. UPB_TABVALUE_EMPTY_INIT,
  4631. UPB_TABVALUE_EMPTY_INIT,
  4632. UPB_TABVALUE_PTR_INIT(&fields[1]),
  4633. UPB_TABVALUE_EMPTY_INIT,
  4634. UPB_TABVALUE_EMPTY_INIT,
  4635. UPB_TABVALUE_EMPTY_INIT,
  4636. UPB_TABVALUE_EMPTY_INIT,
  4637. UPB_TABVALUE_EMPTY_INIT,
  4638. UPB_TABVALUE_EMPTY_INIT,
  4639. UPB_TABVALUE_PTR_INIT(&fields[37]),
  4640. UPB_TABVALUE_PTR_INIT(&fields[47]),
  4641. UPB_TABVALUE_PTR_INIT(&fields[52]),
  4642. UPB_TABVALUE_EMPTY_INIT,
  4643. UPB_TABVALUE_EMPTY_INIT,
  4644. UPB_TABVALUE_EMPTY_INIT,
  4645. UPB_TABVALUE_EMPTY_INIT,
  4646. UPB_TABVALUE_EMPTY_INIT,
  4647. UPB_TABVALUE_PTR_INIT(&fields[41]),
  4648. UPB_TABVALUE_PTR_INIT(&fields[12]),
  4649. UPB_TABVALUE_PTR_INIT(&fields[46]),
  4650. UPB_TABVALUE_PTR_INIT(&fields[27]),
  4651. UPB_TABVALUE_PTR_INIT(&fields[69]),
  4652. UPB_TABVALUE_PTR_INIT(&fields[70]),
  4653. UPB_TABVALUE_PTR_INIT(&fields[4]),
  4654. UPB_TABVALUE_PTR_INIT(&fields[51]),
  4655. UPB_TABVALUE_EMPTY_INIT,
  4656. UPB_TABVALUE_PTR_INIT(&fields[3]),
  4657. UPB_TABVALUE_PTR_INIT(&fields[58]),
  4658. UPB_TABVALUE_PTR_INIT(&fields[6]),
  4659. UPB_TABVALUE_EMPTY_INIT,
  4660. UPB_TABVALUE_PTR_INIT(&fields[28]),
  4661. UPB_TABVALUE_EMPTY_INIT,
  4662. UPB_TABVALUE_EMPTY_INIT,
  4663. UPB_TABVALUE_EMPTY_INIT,
  4664. UPB_TABVALUE_PTR_INIT(&fields[11]),
  4665. UPB_TABVALUE_PTR_INIT(&fields[79]),
  4666. UPB_TABVALUE_EMPTY_INIT,
  4667. UPB_TABVALUE_EMPTY_INIT,
  4668. UPB_TABVALUE_EMPTY_INIT,
  4669. UPB_TABVALUE_EMPTY_INIT,
  4670. UPB_TABVALUE_EMPTY_INIT,
  4671. UPB_TABVALUE_EMPTY_INIT,
  4672. UPB_TABVALUE_EMPTY_INIT,
  4673. UPB_TABVALUE_EMPTY_INIT,
  4674. UPB_TABVALUE_EMPTY_INIT,
  4675. UPB_TABVALUE_EMPTY_INIT,
  4676. UPB_TABVALUE_EMPTY_INIT,
  4677. UPB_TABVALUE_EMPTY_INIT,
  4678. UPB_TABVALUE_EMPTY_INIT,
  4679. UPB_TABVALUE_EMPTY_INIT,
  4680. UPB_TABVALUE_EMPTY_INIT,
  4681. UPB_TABVALUE_EMPTY_INIT,
  4682. UPB_TABVALUE_EMPTY_INIT,
  4683. UPB_TABVALUE_EMPTY_INIT,
  4684. UPB_TABVALUE_EMPTY_INIT,
  4685. UPB_TABVALUE_EMPTY_INIT,
  4686. UPB_TABVALUE_EMPTY_INIT,
  4687. UPB_TABVALUE_EMPTY_INIT,
  4688. UPB_TABVALUE_PTR_INIT(&fields[34]),
  4689. UPB_TABVALUE_PTR_INIT(&fields[57]),
  4690. UPB_TABVALUE_PTR_INIT(&fields[5]),
  4691. UPB_TABVALUE_PTR_INIT(&fields[32]),
  4692. UPB_TABVALUE_PTR_INIT(&fields[10]),
  4693. UPB_TABVALUE_PTR_INIT(&fields[63]),
  4694. UPB_TABVALUE_PTR_INIT(&fields[13]),
  4695. UPB_TABVALUE_PTR_INIT(&fields[53]),
  4696. UPB_TABVALUE_PTR_INIT(&fields[64]),
  4697. UPB_TABVALUE_PTR_INIT(&fields[61]),
  4698. UPB_TABVALUE_PTR_INIT(&fields[80]),
  4699. UPB_TABVALUE_EMPTY_INIT,
  4700. UPB_TABVALUE_PTR_INIT(&fields[17]),
  4701. UPB_TABVALUE_EMPTY_INIT,
  4702. UPB_TABVALUE_PTR_INIT(&fields[26]),
  4703. UPB_TABVALUE_EMPTY_INIT,
  4704. UPB_TABVALUE_EMPTY_INIT,
  4705. UPB_TABVALUE_EMPTY_INIT,
  4706. UPB_TABVALUE_EMPTY_INIT,
  4707. UPB_TABVALUE_EMPTY_INIT,
  4708. UPB_TABVALUE_EMPTY_INIT,
  4709. UPB_TABVALUE_PTR_INIT(&fields[25]),
  4710. UPB_TABVALUE_PTR_INIT(&fields[48]),
  4711. UPB_TABVALUE_PTR_INIT(&fields[24]),
  4712. UPB_TABVALUE_PTR_INIT(&fields[18]),
  4713. UPB_TABVALUE_EMPTY_INIT,
  4714. UPB_TABVALUE_EMPTY_INIT,
  4715. UPB_TABVALUE_EMPTY_INIT,
  4716. UPB_TABVALUE_EMPTY_INIT,
  4717. UPB_TABVALUE_PTR_INIT(&fields[2]),
  4718. UPB_TABVALUE_PTR_INIT(&fields[23]),
  4719. UPB_TABVALUE_PTR_INIT(&fields[62]),
  4720. UPB_TABVALUE_EMPTY_INIT,
  4721. UPB_TABVALUE_PTR_INIT(&fields[22]),
  4722. UPB_TABVALUE_EMPTY_INIT,
  4723. UPB_TABVALUE_EMPTY_INIT,
  4724. UPB_TABVALUE_EMPTY_INIT,
  4725. UPB_TABVALUE_EMPTY_INIT,
  4726. UPB_TABVALUE_EMPTY_INIT,
  4727. UPB_TABVALUE_EMPTY_INIT,
  4728. UPB_TABVALUE_EMPTY_INIT,
  4729. UPB_TABVALUE_EMPTY_INIT,
  4730. UPB_TABVALUE_EMPTY_INIT,
  4731. UPB_TABVALUE_EMPTY_INIT,
  4732. UPB_TABVALUE_EMPTY_INIT,
  4733. UPB_TABVALUE_EMPTY_INIT,
  4734. UPB_TABVALUE_EMPTY_INIT,
  4735. UPB_TABVALUE_EMPTY_INIT,
  4736. UPB_TABVALUE_EMPTY_INIT,
  4737. UPB_TABVALUE_EMPTY_INIT,
  4738. UPB_TABVALUE_EMPTY_INIT,
  4739. UPB_TABVALUE_EMPTY_INIT,
  4740. UPB_TABVALUE_EMPTY_INIT,
  4741. UPB_TABVALUE_EMPTY_INIT,
  4742. UPB_TABVALUE_EMPTY_INIT,
  4743. UPB_TABVALUE_EMPTY_INIT,
  4744. UPB_TABVALUE_EMPTY_INIT,
  4745. UPB_TABVALUE_EMPTY_INIT,
  4746. UPB_TABVALUE_EMPTY_INIT,
  4747. UPB_TABVALUE_EMPTY_INIT,
  4748. UPB_TABVALUE_EMPTY_INIT,
  4749. UPB_TABVALUE_EMPTY_INIT,
  4750. UPB_TABVALUE_EMPTY_INIT,
  4751. UPB_TABVALUE_EMPTY_INIT,
  4752. UPB_TABVALUE_EMPTY_INIT,
  4753. UPB_TABVALUE_EMPTY_INIT,
  4754. UPB_TABVALUE_EMPTY_INIT,
  4755. UPB_TABVALUE_EMPTY_INIT,
  4756. UPB_TABVALUE_EMPTY_INIT,
  4757. UPB_TABVALUE_EMPTY_INIT,
  4758. UPB_TABVALUE_EMPTY_INIT,
  4759. UPB_TABVALUE_EMPTY_INIT,
  4760. UPB_TABVALUE_EMPTY_INIT,
  4761. UPB_TABVALUE_EMPTY_INIT,
  4762. UPB_TABVALUE_EMPTY_INIT,
  4763. UPB_TABVALUE_EMPTY_INIT,
  4764. UPB_TABVALUE_EMPTY_INIT,
  4765. UPB_TABVALUE_EMPTY_INIT,
  4766. UPB_TABVALUE_PTR_INIT(&fields[31]),
  4767. UPB_TABVALUE_PTR_INIT(&fields[45]),
  4768. UPB_TABVALUE_EMPTY_INIT,
  4769. UPB_TABVALUE_EMPTY_INIT,
  4770. UPB_TABVALUE_EMPTY_INIT,
  4771. UPB_TABVALUE_EMPTY_INIT,
  4772. UPB_TABVALUE_EMPTY_INIT,
  4773. UPB_TABVALUE_EMPTY_INIT,
  4774. UPB_TABVALUE_EMPTY_INIT,
  4775. UPB_TABVALUE_EMPTY_INIT,
  4776. UPB_TABVALUE_EMPTY_INIT,
  4777. UPB_TABVALUE_EMPTY_INIT,
  4778. UPB_TABVALUE_EMPTY_INIT,
  4779. UPB_TABVALUE_EMPTY_INIT,
  4780. UPB_TABVALUE_EMPTY_INIT,
  4781. UPB_TABVALUE_EMPTY_INIT,
  4782. UPB_TABVALUE_PTR_INIT(&fields[39]),
  4783. UPB_TABVALUE_PTR_INIT(&fields[20]),
  4784. UPB_TABVALUE_PTR_INIT(&fields[56]),
  4785. UPB_TABVALUE_PTR_INIT(&fields[55]),
  4786. UPB_TABVALUE_EMPTY_INIT,
  4787. UPB_TABVALUE_EMPTY_INIT,
  4788. UPB_TABVALUE_EMPTY_INIT,
  4789. UPB_TABVALUE_EMPTY_INIT,
  4790. UPB_TABVALUE_EMPTY_INIT,
  4791. UPB_TABVALUE_PTR_INIT(&fields[35]),
  4792. UPB_TABVALUE_PTR_INIT(&fields[33]),
  4793. UPB_TABVALUE_PTR_INIT(&fields[54]),
  4794. UPB_TABVALUE_EMPTY_INIT,
  4795. UPB_TABVALUE_EMPTY_INIT,
  4796. UPB_TABVALUE_EMPTY_INIT,
  4797. UPB_TABVALUE_EMPTY_INIT,
  4798. UPB_TABVALUE_EMPTY_INIT,
  4799. UPB_TABVALUE_PTR_INIT(&fields[30]),
  4800. UPB_TABVALUE_EMPTY_INIT,
  4801. UPB_TABVALUE_PTR_INIT(&fields[59]),
  4802. UPB_TABVALUE_PTR_INIT(&fields[65]),
  4803. UPB_TABVALUE_PTR_INIT(&fields[29]),
  4804. UPB_TABVALUE_PTR_INIT(&fields[68]),
  4805. UPB_TABVALUE_EMPTY_INIT,
  4806. UPB_TABVALUE_EMPTY_INIT,
  4807. UPB_TABVALUE_PTR_INIT(&fields[36]),
  4808. UPB_TABVALUE_PTR_INIT(&fields[19]),
  4809. UPB_TABVALUE_PTR_INIT(&fields[60]),
  4810. UPB_TABVALUE_PTR_INIT(&fields[43]),
  4811. UPB_TABVALUE_PTR_INIT(&fields[7]),
  4812. UPB_TABVALUE_PTR_INIT(&fields[67]),
  4813. UPB_TABVALUE_PTR_INIT(&fields[0]),
  4814. UPB_TABVALUE_EMPTY_INIT,
  4815. UPB_TABVALUE_PTR_INIT(&fields[42]),
  4816. UPB_TABVALUE_PTR_INIT(&fields[21]),
  4817. UPB_TABVALUE_EMPTY_INIT,
  4818. UPB_TABVALUE_PTR_INIT("LABEL_OPTIONAL"),
  4819. UPB_TABVALUE_PTR_INIT("LABEL_REQUIRED"),
  4820. UPB_TABVALUE_PTR_INIT("LABEL_REPEATED"),
  4821. UPB_TABVALUE_EMPTY_INIT,
  4822. UPB_TABVALUE_PTR_INIT("TYPE_DOUBLE"),
  4823. UPB_TABVALUE_PTR_INIT("TYPE_FLOAT"),
  4824. UPB_TABVALUE_PTR_INIT("TYPE_INT64"),
  4825. UPB_TABVALUE_PTR_INIT("TYPE_UINT64"),
  4826. UPB_TABVALUE_PTR_INIT("TYPE_INT32"),
  4827. UPB_TABVALUE_PTR_INIT("TYPE_FIXED64"),
  4828. UPB_TABVALUE_PTR_INIT("TYPE_FIXED32"),
  4829. UPB_TABVALUE_PTR_INIT("TYPE_BOOL"),
  4830. UPB_TABVALUE_PTR_INIT("TYPE_STRING"),
  4831. UPB_TABVALUE_PTR_INIT("TYPE_GROUP"),
  4832. UPB_TABVALUE_PTR_INIT("TYPE_MESSAGE"),
  4833. UPB_TABVALUE_PTR_INIT("TYPE_BYTES"),
  4834. UPB_TABVALUE_PTR_INIT("TYPE_UINT32"),
  4835. UPB_TABVALUE_PTR_INIT("TYPE_ENUM"),
  4836. UPB_TABVALUE_PTR_INIT("TYPE_SFIXED32"),
  4837. UPB_TABVALUE_PTR_INIT("TYPE_SFIXED64"),
  4838. UPB_TABVALUE_PTR_INIT("TYPE_SINT32"),
  4839. UPB_TABVALUE_PTR_INIT("TYPE_SINT64"),
  4840. UPB_TABVALUE_PTR_INIT("STRING"),
  4841. UPB_TABVALUE_PTR_INIT("CORD"),
  4842. UPB_TABVALUE_PTR_INIT("STRING_PIECE"),
  4843. UPB_TABVALUE_EMPTY_INIT,
  4844. UPB_TABVALUE_PTR_INIT("SPEED"),
  4845. UPB_TABVALUE_PTR_INIT("CODE_SIZE"),
  4846. UPB_TABVALUE_PTR_INIT("LITE_RUNTIME"),
  4847. };
  4848. static const upb_symtab symtab = UPB_SYMTAB_INIT(UPB_STRTABLE_INIT(24, 31, UPB_CTYPE_PTR, 5, &strentries[204]), &reftables[210], &reftables[211]);
  4849. const upb_symtab *upbdefs_google_protobuf_descriptor(const void *owner) {
  4850. upb_symtab_ref(&symtab, owner);
  4851. return &symtab;
  4852. }
  4853. #ifdef UPB_DEBUG_REFS
  4854. static upb_inttable reftables[212] = {
  4855. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4856. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4857. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4858. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4859. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4860. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4861. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4862. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4863. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4864. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4865. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4866. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4867. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4868. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4869. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4870. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4871. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4872. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4873. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4874. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4875. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4876. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4877. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4878. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4879. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4880. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4881. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4882. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4883. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4884. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4885. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4886. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4887. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4888. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4889. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4890. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4891. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4892. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4893. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4894. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4895. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4896. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4897. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4898. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4899. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4900. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4901. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4902. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4903. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4904. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4905. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4906. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4907. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4908. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4909. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4910. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4911. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4912. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4913. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4914. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4915. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4916. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4917. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4918. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4919. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4920. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4921. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4922. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4923. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4924. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4925. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4926. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4927. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4928. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4929. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4930. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4931. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4932. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4933. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4934. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4935. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4936. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4937. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4938. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4939. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4940. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4941. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4942. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4943. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4944. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4945. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4946. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4947. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4948. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4949. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4950. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4951. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4952. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4953. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4954. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4955. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4956. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4957. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4958. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4959. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4960. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4961. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4962. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4963. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4964. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4965. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4966. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4967. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4968. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4969. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4970. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4971. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4972. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4973. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4974. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4975. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4976. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4977. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4978. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4979. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4980. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4981. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4982. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4983. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4984. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4985. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4986. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4987. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4988. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4989. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4990. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4991. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4992. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4993. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4994. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4995. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4996. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4997. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4998. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4999. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5000. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5001. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5002. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5003. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5004. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5005. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5006. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5007. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5008. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5009. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5010. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5011. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5012. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5013. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5014. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5015. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5016. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5017. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5018. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5019. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5020. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5021. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5022. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5023. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5024. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5025. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5026. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5027. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5028. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5029. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5030. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5031. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5032. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5033. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5034. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5035. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5036. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5037. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5038. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5039. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5040. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5041. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5042. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5043. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5044. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5045. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5046. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5047. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5048. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5049. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5050. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5051. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5052. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5053. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5054. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5055. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5056. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5057. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5058. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5059. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5060. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5061. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5062. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5063. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5064. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5065. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5066. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5067. };
  5068. #endif
  5069. /*
  5070. * upb - a minimalist implementation of protocol buffers.
  5071. *
  5072. * Copyright (c) 2008-2009 Google Inc. See LICENSE for details.
  5073. * Author: Josh Haberman <jhaberman@gmail.com>
  5074. *
  5075. * XXX: The routines in this file that consume a string do not currently
  5076. * support having the string span buffers. In the future, as upb_sink and
  5077. * its buffering/sharing functionality evolve there should be an easy and
  5078. * idiomatic way of correctly handling this case. For now, we accept this
  5079. * limitation since we currently only parse descriptors from single strings.
  5080. */
  5081. #include <errno.h>
  5082. #include <stdlib.h>
  5083. #include <string.h>
  5084. /* upb_deflist is an internal-only dynamic array for storing a growing list of
  5085. * upb_defs. */
  5086. typedef struct {
  5087. upb_def **defs;
  5088. size_t len;
  5089. size_t size;
  5090. bool owned;
  5091. } upb_deflist;
  5092. /* We keep a stack of all the messages scopes we are currently in, as well as
  5093. * the top-level file scope. This is necessary to correctly qualify the
  5094. * definitions that are contained inside. "name" tracks the name of the
  5095. * message or package (a bare name -- not qualified by any enclosing scopes). */
  5096. typedef struct {
  5097. char *name;
  5098. /* Index of the first def that is under this scope. For msgdefs, the
  5099. * msgdef itself is at start-1. */
  5100. int start;
  5101. } upb_descreader_frame;
  5102. /* The maximum number of nested declarations that are allowed, ie.
  5103. * message Foo {
  5104. * message Bar {
  5105. * message Baz {
  5106. * }
  5107. * }
  5108. * }
  5109. *
  5110. * This is a resource limit that affects how big our runtime stack can grow.
  5111. * TODO: make this a runtime-settable property of the Reader instance. */
  5112. #define UPB_MAX_MESSAGE_NESTING 64
  5113. struct upb_descreader {
  5114. upb_sink sink;
  5115. upb_deflist defs;
  5116. upb_descreader_frame stack[UPB_MAX_MESSAGE_NESTING];
  5117. int stack_len;
  5118. uint32_t number;
  5119. char *name;
  5120. bool saw_number;
  5121. bool saw_name;
  5122. char *default_string;
  5123. upb_fielddef *f;
  5124. };
  5125. static char *upb_strndup(const char *buf, size_t n) {
  5126. char *ret = malloc(n + 1);
  5127. if (!ret) return NULL;
  5128. memcpy(ret, buf, n);
  5129. ret[n] = '\0';
  5130. return ret;
  5131. }
  5132. /* Returns a newly allocated string that joins input strings together, for
  5133. * example:
  5134. * join("Foo.Bar", "Baz") -> "Foo.Bar.Baz"
  5135. * join("", "Baz") -> "Baz"
  5136. * Caller owns a ref on the returned string. */
  5137. static char *upb_join(const char *base, const char *name) {
  5138. if (!base || strlen(base) == 0) {
  5139. return upb_strdup(name);
  5140. } else {
  5141. char *ret = malloc(strlen(base) + strlen(name) + 2);
  5142. ret[0] = '\0';
  5143. strcat(ret, base);
  5144. strcat(ret, ".");
  5145. strcat(ret, name);
  5146. return ret;
  5147. }
  5148. }
  5149. /* upb_deflist ****************************************************************/
  5150. void upb_deflist_init(upb_deflist *l) {
  5151. l->size = 0;
  5152. l->defs = NULL;
  5153. l->len = 0;
  5154. l->owned = true;
  5155. }
  5156. void upb_deflist_uninit(upb_deflist *l) {
  5157. size_t i;
  5158. if (l->owned)
  5159. for(i = 0; i < l->len; i++)
  5160. upb_def_unref(l->defs[i], l);
  5161. free(l->defs);
  5162. }
  5163. bool upb_deflist_push(upb_deflist *l, upb_def *d) {
  5164. if(++l->len >= l->size) {
  5165. size_t new_size = UPB_MAX(l->size, 4);
  5166. new_size *= 2;
  5167. l->defs = realloc(l->defs, new_size * sizeof(void *));
  5168. if (!l->defs) return false;
  5169. l->size = new_size;
  5170. }
  5171. l->defs[l->len - 1] = d;
  5172. return true;
  5173. }
  5174. void upb_deflist_donaterefs(upb_deflist *l, void *owner) {
  5175. size_t i;
  5176. assert(l->owned);
  5177. for (i = 0; i < l->len; i++)
  5178. upb_def_donateref(l->defs[i], l, owner);
  5179. l->owned = false;
  5180. }
  5181. static upb_def *upb_deflist_last(upb_deflist *l) {
  5182. return l->defs[l->len-1];
  5183. }
  5184. /* Qualify the defname for all defs starting with offset "start" with "str". */
  5185. static void upb_deflist_qualify(upb_deflist *l, char *str, int32_t start) {
  5186. uint32_t i;
  5187. for (i = start; i < l->len; i++) {
  5188. upb_def *def = l->defs[i];
  5189. char *name = upb_join(str, upb_def_fullname(def));
  5190. upb_def_setfullname(def, name, NULL);
  5191. free(name);
  5192. }
  5193. }
  5194. /* upb_descreader ************************************************************/
  5195. static upb_msgdef *upb_descreader_top(upb_descreader *r) {
  5196. int index;
  5197. assert(r->stack_len > 1);
  5198. index = r->stack[r->stack_len-1].start - 1;
  5199. assert(index >= 0);
  5200. return upb_downcast_msgdef_mutable(r->defs.defs[index]);
  5201. }
  5202. static upb_def *upb_descreader_last(upb_descreader *r) {
  5203. return upb_deflist_last(&r->defs);
  5204. }
  5205. /* Start/end handlers for FileDescriptorProto and DescriptorProto (the two
  5206. * entities that have names and can contain sub-definitions. */
  5207. void upb_descreader_startcontainer(upb_descreader *r) {
  5208. upb_descreader_frame *f = &r->stack[r->stack_len++];
  5209. f->start = r->defs.len;
  5210. f->name = NULL;
  5211. }
  5212. void upb_descreader_endcontainer(upb_descreader *r) {
  5213. upb_descreader_frame *f = &r->stack[--r->stack_len];
  5214. upb_deflist_qualify(&r->defs, f->name, f->start);
  5215. free(f->name);
  5216. f->name = NULL;
  5217. }
  5218. void upb_descreader_setscopename(upb_descreader *r, char *str) {
  5219. upb_descreader_frame *f = &r->stack[r->stack_len-1];
  5220. free(f->name);
  5221. f->name = str;
  5222. }
  5223. /* Handlers for google.protobuf.FileDescriptorProto. */
  5224. static bool file_startmsg(void *r, const void *hd) {
  5225. UPB_UNUSED(hd);
  5226. upb_descreader_startcontainer(r);
  5227. return true;
  5228. }
  5229. static bool file_endmsg(void *closure, const void *hd, upb_status *status) {
  5230. upb_descreader *r = closure;
  5231. UPB_UNUSED(hd);
  5232. UPB_UNUSED(status);
  5233. upb_descreader_endcontainer(r);
  5234. return true;
  5235. }
  5236. static size_t file_onpackage(void *closure, const void *hd, const char *buf,
  5237. size_t n, const upb_bufhandle *handle) {
  5238. upb_descreader *r = closure;
  5239. UPB_UNUSED(hd);
  5240. UPB_UNUSED(handle);
  5241. /* XXX: see comment at the top of the file. */
  5242. upb_descreader_setscopename(r, upb_strndup(buf, n));
  5243. return n;
  5244. }
  5245. /* Handlers for google.protobuf.EnumValueDescriptorProto. */
  5246. static bool enumval_startmsg(void *closure, const void *hd) {
  5247. upb_descreader *r = closure;
  5248. UPB_UNUSED(hd);
  5249. r->saw_number = false;
  5250. r->saw_name = false;
  5251. return true;
  5252. }
  5253. static size_t enumval_onname(void *closure, const void *hd, const char *buf,
  5254. size_t n, const upb_bufhandle *handle) {
  5255. upb_descreader *r = closure;
  5256. UPB_UNUSED(hd);
  5257. UPB_UNUSED(handle);
  5258. /* XXX: see comment at the top of the file. */
  5259. free(r->name);
  5260. r->name = upb_strndup(buf, n);
  5261. r->saw_name = true;
  5262. return n;
  5263. }
  5264. static bool enumval_onnumber(void *closure, const void *hd, int32_t val) {
  5265. upb_descreader *r = closure;
  5266. UPB_UNUSED(hd);
  5267. r->number = val;
  5268. r->saw_number = true;
  5269. return true;
  5270. }
  5271. static bool enumval_endmsg(void *closure, const void *hd, upb_status *status) {
  5272. upb_descreader *r = closure;
  5273. upb_enumdef *e;
  5274. UPB_UNUSED(hd);
  5275. if(!r->saw_number || !r->saw_name) {
  5276. upb_status_seterrmsg(status, "Enum value missing name or number.");
  5277. return false;
  5278. }
  5279. e = upb_downcast_enumdef_mutable(upb_descreader_last(r));
  5280. upb_enumdef_addval(e, r->name, r->number, status);
  5281. free(r->name);
  5282. r->name = NULL;
  5283. return true;
  5284. }
  5285. /* Handlers for google.protobuf.EnumDescriptorProto. */
  5286. static bool enum_startmsg(void *closure, const void *hd) {
  5287. upb_descreader *r = closure;
  5288. UPB_UNUSED(hd);
  5289. upb_deflist_push(&r->defs,
  5290. upb_enumdef_upcast_mutable(upb_enumdef_new(&r->defs)));
  5291. return true;
  5292. }
  5293. static bool enum_endmsg(void *closure, const void *hd, upb_status *status) {
  5294. upb_descreader *r = closure;
  5295. upb_enumdef *e;
  5296. UPB_UNUSED(hd);
  5297. e = upb_downcast_enumdef_mutable(upb_descreader_last(r));
  5298. if (upb_def_fullname(upb_descreader_last(r)) == NULL) {
  5299. upb_status_seterrmsg(status, "Enum had no name.");
  5300. return false;
  5301. }
  5302. if (upb_enumdef_numvals(e) == 0) {
  5303. upb_status_seterrmsg(status, "Enum had no values.");
  5304. return false;
  5305. }
  5306. return true;
  5307. }
  5308. static size_t enum_onname(void *closure, const void *hd, const char *buf,
  5309. size_t n, const upb_bufhandle *handle) {
  5310. upb_descreader *r = closure;
  5311. char *fullname = upb_strndup(buf, n);
  5312. UPB_UNUSED(hd);
  5313. UPB_UNUSED(handle);
  5314. /* XXX: see comment at the top of the file. */
  5315. upb_def_setfullname(upb_descreader_last(r), fullname, NULL);
  5316. free(fullname);
  5317. return n;
  5318. }
  5319. /* Handlers for google.protobuf.FieldDescriptorProto */
  5320. static bool field_startmsg(void *closure, const void *hd) {
  5321. upb_descreader *r = closure;
  5322. UPB_UNUSED(hd);
  5323. r->f = upb_fielddef_new(&r->defs);
  5324. free(r->default_string);
  5325. r->default_string = NULL;
  5326. /* fielddefs default to packed, but descriptors default to non-packed. */
  5327. upb_fielddef_setpacked(r->f, false);
  5328. return true;
  5329. }
  5330. /* Converts the default value in string "str" into "d". Passes a ref on str.
  5331. * Returns true on success. */
  5332. static bool parse_default(char *str, upb_fielddef *f) {
  5333. bool success = true;
  5334. char *end;
  5335. switch (upb_fielddef_type(f)) {
  5336. case UPB_TYPE_INT32: {
  5337. long val = strtol(str, &end, 0);
  5338. if (val > INT32_MAX || val < INT32_MIN || errno == ERANGE || *end)
  5339. success = false;
  5340. else
  5341. upb_fielddef_setdefaultint32(f, val);
  5342. break;
  5343. }
  5344. case UPB_TYPE_INT64: {
  5345. /* XXX: Need to write our own strtoll, since it's not available in c89. */
  5346. long long val = strtol(str, &end, 0);
  5347. if (val > INT64_MAX || val < INT64_MIN || errno == ERANGE || *end)
  5348. success = false;
  5349. else
  5350. upb_fielddef_setdefaultint64(f, val);
  5351. break;
  5352. }
  5353. case UPB_TYPE_UINT32: {
  5354. unsigned long val = strtoul(str, &end, 0);
  5355. if (val > UINT32_MAX || errno == ERANGE || *end)
  5356. success = false;
  5357. else
  5358. upb_fielddef_setdefaultuint32(f, val);
  5359. break;
  5360. }
  5361. case UPB_TYPE_UINT64: {
  5362. /* XXX: Need to write our own strtoull, since it's not available in c89. */
  5363. unsigned long long val = strtoul(str, &end, 0);
  5364. if (val > UINT64_MAX || errno == ERANGE || *end)
  5365. success = false;
  5366. else
  5367. upb_fielddef_setdefaultuint64(f, val);
  5368. break;
  5369. }
  5370. case UPB_TYPE_DOUBLE: {
  5371. double val = strtod(str, &end);
  5372. if (errno == ERANGE || *end)
  5373. success = false;
  5374. else
  5375. upb_fielddef_setdefaultdouble(f, val);
  5376. break;
  5377. }
  5378. case UPB_TYPE_FLOAT: {
  5379. /* XXX: Need to write our own strtof, since it's not available in c89. */
  5380. float val = strtod(str, &end);
  5381. if (errno == ERANGE || *end)
  5382. success = false;
  5383. else
  5384. upb_fielddef_setdefaultfloat(f, val);
  5385. break;
  5386. }
  5387. case UPB_TYPE_BOOL: {
  5388. if (strcmp(str, "false") == 0)
  5389. upb_fielddef_setdefaultbool(f, false);
  5390. else if (strcmp(str, "true") == 0)
  5391. upb_fielddef_setdefaultbool(f, true);
  5392. else
  5393. success = false;
  5394. break;
  5395. }
  5396. default: abort();
  5397. }
  5398. return success;
  5399. }
  5400. static bool field_endmsg(void *closure, const void *hd, upb_status *status) {
  5401. upb_descreader *r = closure;
  5402. upb_fielddef *f = r->f;
  5403. UPB_UNUSED(hd);
  5404. /* TODO: verify that all required fields were present. */
  5405. assert(upb_fielddef_number(f) != 0);
  5406. assert(upb_fielddef_name(f) != NULL);
  5407. assert((upb_fielddef_subdefname(f) != NULL) == upb_fielddef_hassubdef(f));
  5408. if (r->default_string) {
  5409. if (upb_fielddef_issubmsg(f)) {
  5410. upb_status_seterrmsg(status, "Submessages cannot have defaults.");
  5411. return false;
  5412. }
  5413. if (upb_fielddef_isstring(f) || upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  5414. upb_fielddef_setdefaultcstr(f, r->default_string, NULL);
  5415. } else {
  5416. if (r->default_string && !parse_default(r->default_string, f)) {
  5417. /* We don't worry too much about giving a great error message since the
  5418. * compiler should have ensured this was correct. */
  5419. upb_status_seterrmsg(status, "Error converting default value.");
  5420. return false;
  5421. }
  5422. }
  5423. }
  5424. return true;
  5425. }
  5426. static bool field_onlazy(void *closure, const void *hd, bool val) {
  5427. upb_descreader *r = closure;
  5428. UPB_UNUSED(hd);
  5429. upb_fielddef_setlazy(r->f, val);
  5430. return true;
  5431. }
  5432. static bool field_onpacked(void *closure, const void *hd, bool val) {
  5433. upb_descreader *r = closure;
  5434. UPB_UNUSED(hd);
  5435. upb_fielddef_setpacked(r->f, val);
  5436. return true;
  5437. }
  5438. static bool field_ontype(void *closure, const void *hd, int32_t val) {
  5439. upb_descreader *r = closure;
  5440. UPB_UNUSED(hd);
  5441. upb_fielddef_setdescriptortype(r->f, val);
  5442. return true;
  5443. }
  5444. static bool field_onlabel(void *closure, const void *hd, int32_t val) {
  5445. upb_descreader *r = closure;
  5446. UPB_UNUSED(hd);
  5447. upb_fielddef_setlabel(r->f, val);
  5448. return true;
  5449. }
  5450. static bool field_onnumber(void *closure, const void *hd, int32_t val) {
  5451. upb_descreader *r = closure;
  5452. bool ok = upb_fielddef_setnumber(r->f, val, NULL);
  5453. UPB_UNUSED(hd);
  5454. UPB_ASSERT_VAR(ok, ok);
  5455. return true;
  5456. }
  5457. static size_t field_onname(void *closure, const void *hd, const char *buf,
  5458. size_t n, const upb_bufhandle *handle) {
  5459. upb_descreader *r = closure;
  5460. char *name = upb_strndup(buf, n);
  5461. UPB_UNUSED(hd);
  5462. UPB_UNUSED(handle);
  5463. /* XXX: see comment at the top of the file. */
  5464. upb_fielddef_setname(r->f, name, NULL);
  5465. free(name);
  5466. return n;
  5467. }
  5468. static size_t field_ontypename(void *closure, const void *hd, const char *buf,
  5469. size_t n, const upb_bufhandle *handle) {
  5470. upb_descreader *r = closure;
  5471. char *name = upb_strndup(buf, n);
  5472. UPB_UNUSED(hd);
  5473. UPB_UNUSED(handle);
  5474. /* XXX: see comment at the top of the file. */
  5475. upb_fielddef_setsubdefname(r->f, name, NULL);
  5476. free(name);
  5477. return n;
  5478. }
  5479. static size_t field_onextendee(void *closure, const void *hd, const char *buf,
  5480. size_t n, const upb_bufhandle *handle) {
  5481. upb_descreader *r = closure;
  5482. char *name = upb_strndup(buf, n);
  5483. UPB_UNUSED(hd);
  5484. UPB_UNUSED(handle);
  5485. /* XXX: see comment at the top of the file. */
  5486. upb_fielddef_setcontainingtypename(r->f, name, NULL);
  5487. free(name);
  5488. return n;
  5489. }
  5490. static size_t field_ondefaultval(void *closure, const void *hd, const char *buf,
  5491. size_t n, const upb_bufhandle *handle) {
  5492. upb_descreader *r = closure;
  5493. UPB_UNUSED(hd);
  5494. UPB_UNUSED(handle);
  5495. /* Have to convert from string to the correct type, but we might not know the
  5496. * type yet, so we save it as a string until the end of the field.
  5497. * XXX: see comment at the top of the file. */
  5498. free(r->default_string);
  5499. r->default_string = upb_strndup(buf, n);
  5500. return n;
  5501. }
  5502. /* Handlers for google.protobuf.DescriptorProto (representing a message). */
  5503. static bool msg_startmsg(void *closure, const void *hd) {
  5504. upb_descreader *r = closure;
  5505. UPB_UNUSED(hd);
  5506. upb_deflist_push(&r->defs,
  5507. upb_msgdef_upcast_mutable(upb_msgdef_new(&r->defs)));
  5508. upb_descreader_startcontainer(r);
  5509. return true;
  5510. }
  5511. static bool msg_endmsg(void *closure, const void *hd, upb_status *status) {
  5512. upb_descreader *r = closure;
  5513. upb_msgdef *m = upb_descreader_top(r);
  5514. UPB_UNUSED(hd);
  5515. if(!upb_def_fullname(upb_msgdef_upcast_mutable(m))) {
  5516. upb_status_seterrmsg(status, "Encountered message with no name.");
  5517. return false;
  5518. }
  5519. upb_descreader_endcontainer(r);
  5520. return true;
  5521. }
  5522. static size_t msg_onname(void *closure, const void *hd, const char *buf,
  5523. size_t n, const upb_bufhandle *handle) {
  5524. upb_descreader *r = closure;
  5525. upb_msgdef *m = upb_descreader_top(r);
  5526. /* XXX: see comment at the top of the file. */
  5527. char *name = upb_strndup(buf, n);
  5528. UPB_UNUSED(hd);
  5529. UPB_UNUSED(handle);
  5530. upb_def_setfullname(upb_msgdef_upcast_mutable(m), name, NULL);
  5531. upb_descreader_setscopename(r, name); /* Passes ownership of name. */
  5532. return n;
  5533. }
  5534. static bool msg_onendfield(void *closure, const void *hd) {
  5535. upb_descreader *r = closure;
  5536. upb_msgdef *m = upb_descreader_top(r);
  5537. UPB_UNUSED(hd);
  5538. upb_msgdef_addfield(m, r->f, &r->defs, NULL);
  5539. r->f = NULL;
  5540. return true;
  5541. }
  5542. static bool pushextension(void *closure, const void *hd) {
  5543. upb_descreader *r = closure;
  5544. UPB_UNUSED(hd);
  5545. assert(upb_fielddef_containingtypename(r->f));
  5546. upb_fielddef_setisextension(r->f, true);
  5547. upb_deflist_push(&r->defs, upb_fielddef_upcast_mutable(r->f));
  5548. r->f = NULL;
  5549. return true;
  5550. }
  5551. #define D(name) upbdefs_google_protobuf_ ## name(s)
  5552. static void reghandlers(const void *closure, upb_handlers *h) {
  5553. const upb_symtab *s = closure;
  5554. const upb_msgdef *m = upb_handlers_msgdef(h);
  5555. if (m == D(DescriptorProto)) {
  5556. upb_handlers_setstartmsg(h, &msg_startmsg, NULL);
  5557. upb_handlers_setendmsg(h, &msg_endmsg, NULL);
  5558. upb_handlers_setstring(h, D(DescriptorProto_name), &msg_onname, NULL);
  5559. upb_handlers_setendsubmsg(h, D(DescriptorProto_field), &msg_onendfield,
  5560. NULL);
  5561. upb_handlers_setendsubmsg(h, D(DescriptorProto_extension), &pushextension,
  5562. NULL);
  5563. } else if (m == D(FileDescriptorProto)) {
  5564. upb_handlers_setstartmsg(h, &file_startmsg, NULL);
  5565. upb_handlers_setendmsg(h, &file_endmsg, NULL);
  5566. upb_handlers_setstring(h, D(FileDescriptorProto_package), &file_onpackage,
  5567. NULL);
  5568. upb_handlers_setendsubmsg(h, D(FileDescriptorProto_extension), &pushextension,
  5569. NULL);
  5570. } else if (m == D(EnumValueDescriptorProto)) {
  5571. upb_handlers_setstartmsg(h, &enumval_startmsg, NULL);
  5572. upb_handlers_setendmsg(h, &enumval_endmsg, NULL);
  5573. upb_handlers_setstring(h, D(EnumValueDescriptorProto_name), &enumval_onname, NULL);
  5574. upb_handlers_setint32(h, D(EnumValueDescriptorProto_number), &enumval_onnumber,
  5575. NULL);
  5576. } else if (m == D(EnumDescriptorProto)) {
  5577. upb_handlers_setstartmsg(h, &enum_startmsg, NULL);
  5578. upb_handlers_setendmsg(h, &enum_endmsg, NULL);
  5579. upb_handlers_setstring(h, D(EnumDescriptorProto_name), &enum_onname, NULL);
  5580. } else if (m == D(FieldDescriptorProto)) {
  5581. upb_handlers_setstartmsg(h, &field_startmsg, NULL);
  5582. upb_handlers_setendmsg(h, &field_endmsg, NULL);
  5583. upb_handlers_setint32(h, D(FieldDescriptorProto_type), &field_ontype,
  5584. NULL);
  5585. upb_handlers_setint32(h, D(FieldDescriptorProto_label), &field_onlabel,
  5586. NULL);
  5587. upb_handlers_setint32(h, D(FieldDescriptorProto_number), &field_onnumber,
  5588. NULL);
  5589. upb_handlers_setstring(h, D(FieldDescriptorProto_name), &field_onname,
  5590. NULL);
  5591. upb_handlers_setstring(h, D(FieldDescriptorProto_type_name),
  5592. &field_ontypename, NULL);
  5593. upb_handlers_setstring(h, D(FieldDescriptorProto_extendee),
  5594. &field_onextendee, NULL);
  5595. upb_handlers_setstring(h, D(FieldDescriptorProto_default_value),
  5596. &field_ondefaultval, NULL);
  5597. } else if (m == D(FieldOptions)) {
  5598. upb_handlers_setbool(h, D(FieldOptions_lazy), &field_onlazy, NULL);
  5599. upb_handlers_setbool(h, D(FieldOptions_packed), &field_onpacked, NULL);
  5600. }
  5601. }
  5602. #undef D
  5603. void descreader_cleanup(void *_r) {
  5604. upb_descreader *r = _r;
  5605. free(r->name);
  5606. upb_deflist_uninit(&r->defs);
  5607. free(r->default_string);
  5608. while (r->stack_len > 0) {
  5609. upb_descreader_frame *f = &r->stack[--r->stack_len];
  5610. free(f->name);
  5611. }
  5612. }
  5613. /* Public API ****************************************************************/
  5614. upb_descreader *upb_descreader_create(upb_env *e, const upb_handlers *h) {
  5615. upb_descreader *r = upb_env_malloc(e, sizeof(upb_descreader));
  5616. if (!r || !upb_env_addcleanup(e, descreader_cleanup, r)) {
  5617. return NULL;
  5618. }
  5619. upb_deflist_init(&r->defs);
  5620. upb_sink_reset(upb_descreader_input(r), h, r);
  5621. r->stack_len = 0;
  5622. r->name = NULL;
  5623. r->default_string = NULL;
  5624. return r;
  5625. }
  5626. upb_def **upb_descreader_getdefs(upb_descreader *r, void *owner, int *n) {
  5627. *n = r->defs.len;
  5628. upb_deflist_donaterefs(&r->defs, owner);
  5629. return r->defs.defs;
  5630. }
  5631. upb_sink *upb_descreader_input(upb_descreader *r) {
  5632. return &r->sink;
  5633. }
  5634. const upb_handlers *upb_descreader_newhandlers(const void *owner) {
  5635. const upb_symtab *s = upbdefs_google_protobuf_descriptor(&s);
  5636. const upb_handlers *h = upb_handlers_newfrozen(
  5637. upbdefs_google_protobuf_FileDescriptorSet(s), owner, reghandlers, s);
  5638. upb_symtab_unref(s, &s);
  5639. return h;
  5640. }
  5641. /*
  5642. * upb - a minimalist implementation of protocol buffers.
  5643. *
  5644. * Copyright (c) 2013 Google Inc. See LICENSE for details.
  5645. * Author: Josh Haberman <jhaberman@gmail.com>
  5646. *
  5647. * Code to compile a upb::Handlers into bytecode for decoding a protobuf
  5648. * according to that specific schema and destination handlers.
  5649. *
  5650. * Compiling to bytecode is always the first step. If we are using the
  5651. * interpreted decoder we leave it as bytecode and interpret that. If we are
  5652. * using a JIT decoder we use a code generator to turn the bytecode into native
  5653. * code, LLVM IR, etc.
  5654. *
  5655. * Bytecode definition is in decoder.int.h.
  5656. */
  5657. #include <stdarg.h>
  5658. #ifdef UPB_DUMP_BYTECODE
  5659. #include <stdio.h>
  5660. #endif
  5661. #define MAXLABEL 5
  5662. #define EMPTYLABEL -1
  5663. /* mgroup *********************************************************************/
  5664. static void freegroup(upb_refcounted *r) {
  5665. mgroup *g = (mgroup*)r;
  5666. upb_inttable_uninit(&g->methods);
  5667. #ifdef UPB_USE_JIT_X64
  5668. upb_pbdecoder_freejit(g);
  5669. #endif
  5670. free(g->bytecode);
  5671. free(g);
  5672. }
  5673. static void visitgroup(const upb_refcounted *r, upb_refcounted_visit *visit,
  5674. void *closure) {
  5675. const mgroup *g = (const mgroup*)r;
  5676. upb_inttable_iter i;
  5677. upb_inttable_begin(&i, &g->methods);
  5678. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5679. upb_pbdecodermethod *method = upb_value_getptr(upb_inttable_iter_value(&i));
  5680. visit(r, upb_pbdecodermethod_upcast(method), closure);
  5681. }
  5682. }
  5683. mgroup *newgroup(const void *owner) {
  5684. mgroup *g = malloc(sizeof(*g));
  5685. static const struct upb_refcounted_vtbl vtbl = {visitgroup, freegroup};
  5686. upb_refcounted_init(mgroup_upcast_mutable(g), &vtbl, owner);
  5687. upb_inttable_init(&g->methods, UPB_CTYPE_PTR);
  5688. g->bytecode = NULL;
  5689. g->bytecode_end = NULL;
  5690. return g;
  5691. }
  5692. /* upb_pbdecodermethod ********************************************************/
  5693. static void freemethod(upb_refcounted *r) {
  5694. upb_pbdecodermethod *method = (upb_pbdecodermethod*)r;
  5695. if (method->dest_handlers_) {
  5696. upb_handlers_unref(method->dest_handlers_, method);
  5697. }
  5698. upb_inttable_uninit(&method->dispatch);
  5699. free(method);
  5700. }
  5701. static void visitmethod(const upb_refcounted *r, upb_refcounted_visit *visit,
  5702. void *closure) {
  5703. const upb_pbdecodermethod *m = (const upb_pbdecodermethod*)r;
  5704. visit(r, m->group, closure);
  5705. }
  5706. static upb_pbdecodermethod *newmethod(const upb_handlers *dest_handlers,
  5707. mgroup *group) {
  5708. static const struct upb_refcounted_vtbl vtbl = {visitmethod, freemethod};
  5709. upb_pbdecodermethod *ret = malloc(sizeof(*ret));
  5710. upb_refcounted_init(upb_pbdecodermethod_upcast_mutable(ret), &vtbl, &ret);
  5711. upb_byteshandler_init(&ret->input_handler_);
  5712. /* The method references the group and vice-versa, in a circular reference. */
  5713. upb_ref2(ret, group);
  5714. upb_ref2(group, ret);
  5715. upb_inttable_insertptr(&group->methods, dest_handlers, upb_value_ptr(ret));
  5716. upb_pbdecodermethod_unref(ret, &ret);
  5717. ret->group = mgroup_upcast_mutable(group);
  5718. ret->dest_handlers_ = dest_handlers;
  5719. ret->is_native_ = false; /* If we JIT, it will update this later. */
  5720. upb_inttable_init(&ret->dispatch, UPB_CTYPE_UINT64);
  5721. if (ret->dest_handlers_) {
  5722. upb_handlers_ref(ret->dest_handlers_, ret);
  5723. }
  5724. return ret;
  5725. }
  5726. const upb_handlers *upb_pbdecodermethod_desthandlers(
  5727. const upb_pbdecodermethod *m) {
  5728. return m->dest_handlers_;
  5729. }
  5730. const upb_byteshandler *upb_pbdecodermethod_inputhandler(
  5731. const upb_pbdecodermethod *m) {
  5732. return &m->input_handler_;
  5733. }
  5734. bool upb_pbdecodermethod_isnative(const upb_pbdecodermethod *m) {
  5735. return m->is_native_;
  5736. }
  5737. const upb_pbdecodermethod *upb_pbdecodermethod_new(
  5738. const upb_pbdecodermethodopts *opts, const void *owner) {
  5739. const upb_pbdecodermethod *ret;
  5740. upb_pbcodecache cache;
  5741. upb_pbcodecache_init(&cache);
  5742. ret = upb_pbcodecache_getdecodermethod(&cache, opts);
  5743. upb_pbdecodermethod_ref(ret, owner);
  5744. upb_pbcodecache_uninit(&cache);
  5745. return ret;
  5746. }
  5747. /* bytecode compiler **********************************************************/
  5748. /* Data used only at compilation time. */
  5749. typedef struct {
  5750. mgroup *group;
  5751. uint32_t *pc;
  5752. int fwd_labels[MAXLABEL];
  5753. int back_labels[MAXLABEL];
  5754. /* For fields marked "lazy", parse them lazily or eagerly? */
  5755. bool lazy;
  5756. } compiler;
  5757. static compiler *newcompiler(mgroup *group, bool lazy) {
  5758. compiler *ret = malloc(sizeof(*ret));
  5759. int i;
  5760. ret->group = group;
  5761. ret->lazy = lazy;
  5762. for (i = 0; i < MAXLABEL; i++) {
  5763. ret->fwd_labels[i] = EMPTYLABEL;
  5764. ret->back_labels[i] = EMPTYLABEL;
  5765. }
  5766. return ret;
  5767. }
  5768. static void freecompiler(compiler *c) {
  5769. free(c);
  5770. }
  5771. const size_t ptr_words = sizeof(void*) / sizeof(uint32_t);
  5772. /* How many words an instruction is. */
  5773. static int instruction_len(uint32_t instr) {
  5774. switch (getop(instr)) {
  5775. case OP_SETDISPATCH: return 1 + ptr_words;
  5776. case OP_TAGN: return 3;
  5777. case OP_SETBIGGROUPNUM: return 2;
  5778. default: return 1;
  5779. }
  5780. }
  5781. bool op_has_longofs(int32_t instruction) {
  5782. switch (getop(instruction)) {
  5783. case OP_CALL:
  5784. case OP_BRANCH:
  5785. case OP_CHECKDELIM:
  5786. return true;
  5787. /* The "tag" instructions only have 8 bytes available for the jump target,
  5788. * but that is ok because these opcodes only require short jumps. */
  5789. case OP_TAG1:
  5790. case OP_TAG2:
  5791. case OP_TAGN:
  5792. return false;
  5793. default:
  5794. assert(false);
  5795. return false;
  5796. }
  5797. }
  5798. static int32_t getofs(uint32_t instruction) {
  5799. if (op_has_longofs(instruction)) {
  5800. return (int32_t)instruction >> 8;
  5801. } else {
  5802. return (int8_t)(instruction >> 8);
  5803. }
  5804. }
  5805. static void setofs(uint32_t *instruction, int32_t ofs) {
  5806. if (op_has_longofs(*instruction)) {
  5807. *instruction = getop(*instruction) | ofs << 8;
  5808. } else {
  5809. *instruction = (*instruction & ~0xff00) | ((ofs & 0xff) << 8);
  5810. }
  5811. assert(getofs(*instruction) == ofs); /* Would fail in cases of overflow. */
  5812. }
  5813. static uint32_t pcofs(compiler *c) { return c->pc - c->group->bytecode; }
  5814. /* Defines a local label at the current PC location. All previous forward
  5815. * references are updated to point to this location. The location is noted
  5816. * for any future backward references. */
  5817. static void label(compiler *c, unsigned int label) {
  5818. int val;
  5819. uint32_t *codep;
  5820. assert(label < MAXLABEL);
  5821. val = c->fwd_labels[label];
  5822. codep = (val == EMPTYLABEL) ? NULL : c->group->bytecode + val;
  5823. while (codep) {
  5824. int ofs = getofs(*codep);
  5825. setofs(codep, c->pc - codep - instruction_len(*codep));
  5826. codep = ofs ? codep + ofs : NULL;
  5827. }
  5828. c->fwd_labels[label] = EMPTYLABEL;
  5829. c->back_labels[label] = pcofs(c);
  5830. }
  5831. /* Creates a reference to a numbered label; either a forward reference
  5832. * (positive arg) or backward reference (negative arg). For forward references
  5833. * the value returned now is actually a "next" pointer into a linked list of all
  5834. * instructions that use this label and will be patched later when the label is
  5835. * defined with label().
  5836. *
  5837. * The returned value is the offset that should be written into the instruction.
  5838. */
  5839. static int32_t labelref(compiler *c, int label) {
  5840. assert(label < MAXLABEL);
  5841. if (label == LABEL_DISPATCH) {
  5842. /* No resolving required. */
  5843. return 0;
  5844. } else if (label < 0) {
  5845. /* Backward local label. Relative to the next instruction. */
  5846. uint32_t from = (c->pc + 1) - c->group->bytecode;
  5847. return c->back_labels[-label] - from;
  5848. } else {
  5849. /* Forward local label: prepend to (possibly-empty) linked list. */
  5850. int *lptr = &c->fwd_labels[label];
  5851. int32_t ret = (*lptr == EMPTYLABEL) ? 0 : *lptr - pcofs(c);
  5852. *lptr = pcofs(c);
  5853. return ret;
  5854. }
  5855. }
  5856. static void put32(compiler *c, uint32_t v) {
  5857. mgroup *g = c->group;
  5858. if (c->pc == g->bytecode_end) {
  5859. int ofs = pcofs(c);
  5860. size_t oldsize = g->bytecode_end - g->bytecode;
  5861. size_t newsize = UPB_MAX(oldsize * 2, 64);
  5862. /* TODO(haberman): handle OOM. */
  5863. g->bytecode = realloc(g->bytecode, newsize * sizeof(uint32_t));
  5864. g->bytecode_end = g->bytecode + newsize;
  5865. c->pc = g->bytecode + ofs;
  5866. }
  5867. *c->pc++ = v;
  5868. }
  5869. static void putop(compiler *c, opcode op, ...) {
  5870. va_list ap;
  5871. va_start(ap, op);
  5872. switch (op) {
  5873. case OP_SETDISPATCH: {
  5874. uintptr_t ptr = (uintptr_t)va_arg(ap, void*);
  5875. put32(c, OP_SETDISPATCH);
  5876. put32(c, ptr);
  5877. if (sizeof(uintptr_t) > sizeof(uint32_t))
  5878. put32(c, (uint64_t)ptr >> 32);
  5879. break;
  5880. }
  5881. case OP_STARTMSG:
  5882. case OP_ENDMSG:
  5883. case OP_PUSHLENDELIM:
  5884. case OP_POP:
  5885. case OP_SETDELIM:
  5886. case OP_HALT:
  5887. case OP_RET:
  5888. case OP_DISPATCH:
  5889. put32(c, op);
  5890. break;
  5891. case OP_PARSE_DOUBLE:
  5892. case OP_PARSE_FLOAT:
  5893. case OP_PARSE_INT64:
  5894. case OP_PARSE_UINT64:
  5895. case OP_PARSE_INT32:
  5896. case OP_PARSE_FIXED64:
  5897. case OP_PARSE_FIXED32:
  5898. case OP_PARSE_BOOL:
  5899. case OP_PARSE_UINT32:
  5900. case OP_PARSE_SFIXED32:
  5901. case OP_PARSE_SFIXED64:
  5902. case OP_PARSE_SINT32:
  5903. case OP_PARSE_SINT64:
  5904. case OP_STARTSEQ:
  5905. case OP_ENDSEQ:
  5906. case OP_STARTSUBMSG:
  5907. case OP_ENDSUBMSG:
  5908. case OP_STARTSTR:
  5909. case OP_STRING:
  5910. case OP_ENDSTR:
  5911. case OP_PUSHTAGDELIM:
  5912. put32(c, op | va_arg(ap, upb_selector_t) << 8);
  5913. break;
  5914. case OP_SETBIGGROUPNUM:
  5915. put32(c, op);
  5916. put32(c, va_arg(ap, int));
  5917. break;
  5918. case OP_CALL: {
  5919. const upb_pbdecodermethod *method = va_arg(ap, upb_pbdecodermethod *);
  5920. put32(c, op | (method->code_base.ofs - (pcofs(c) + 1)) << 8);
  5921. break;
  5922. }
  5923. case OP_CHECKDELIM:
  5924. case OP_BRANCH: {
  5925. uint32_t instruction = op;
  5926. int label = va_arg(ap, int);
  5927. setofs(&instruction, labelref(c, label));
  5928. put32(c, instruction);
  5929. break;
  5930. }
  5931. case OP_TAG1:
  5932. case OP_TAG2: {
  5933. int label = va_arg(ap, int);
  5934. uint64_t tag = va_arg(ap, uint64_t);
  5935. uint32_t instruction = op | (tag << 16);
  5936. assert(tag <= 0xffff);
  5937. setofs(&instruction, labelref(c, label));
  5938. put32(c, instruction);
  5939. break;
  5940. }
  5941. case OP_TAGN: {
  5942. int label = va_arg(ap, int);
  5943. uint64_t tag = va_arg(ap, uint64_t);
  5944. uint32_t instruction = op | (upb_value_size(tag) << 16);
  5945. setofs(&instruction, labelref(c, label));
  5946. put32(c, instruction);
  5947. put32(c, tag);
  5948. put32(c, tag >> 32);
  5949. break;
  5950. }
  5951. }
  5952. va_end(ap);
  5953. }
  5954. #if defined(UPB_USE_JIT_X64) || defined(UPB_DUMP_BYTECODE)
  5955. const char *upb_pbdecoder_getopname(unsigned int op) {
  5956. #define QUOTE(x) #x
  5957. #define EXPAND_AND_QUOTE(x) QUOTE(x)
  5958. #define OPNAME(x) OP_##x
  5959. #define OP(x) case OPNAME(x): return EXPAND_AND_QUOTE(OPNAME(x));
  5960. #define T(x) OP(PARSE_##x)
  5961. /* Keep in sync with list in decoder.int.h. */
  5962. switch ((opcode)op) {
  5963. T(DOUBLE) T(FLOAT) T(INT64) T(UINT64) T(INT32) T(FIXED64) T(FIXED32)
  5964. T(BOOL) T(UINT32) T(SFIXED32) T(SFIXED64) T(SINT32) T(SINT64)
  5965. OP(STARTMSG) OP(ENDMSG) OP(STARTSEQ) OP(ENDSEQ) OP(STARTSUBMSG)
  5966. OP(ENDSUBMSG) OP(STARTSTR) OP(STRING) OP(ENDSTR) OP(CALL) OP(RET)
  5967. OP(PUSHLENDELIM) OP(PUSHTAGDELIM) OP(SETDELIM) OP(CHECKDELIM)
  5968. OP(BRANCH) OP(TAG1) OP(TAG2) OP(TAGN) OP(SETDISPATCH) OP(POP)
  5969. OP(SETBIGGROUPNUM) OP(DISPATCH) OP(HALT)
  5970. }
  5971. return "<unknown op>";
  5972. #undef OP
  5973. #undef T
  5974. }
  5975. #endif
  5976. #ifdef UPB_DUMP_BYTECODE
  5977. static void dumpbc(uint32_t *p, uint32_t *end, FILE *f) {
  5978. uint32_t *begin = p;
  5979. while (p < end) {
  5980. fprintf(f, "%p %8tx", p, p - begin);
  5981. uint32_t instr = *p++;
  5982. uint8_t op = getop(instr);
  5983. fprintf(f, " %s", upb_pbdecoder_getopname(op));
  5984. switch ((opcode)op) {
  5985. case OP_SETDISPATCH: {
  5986. const upb_inttable *dispatch;
  5987. memcpy(&dispatch, p, sizeof(void*));
  5988. p += ptr_words;
  5989. const upb_pbdecodermethod *method =
  5990. (void *)((char *)dispatch -
  5991. offsetof(upb_pbdecodermethod, dispatch));
  5992. fprintf(f, " %s", upb_msgdef_fullname(
  5993. upb_handlers_msgdef(method->dest_handlers_)));
  5994. break;
  5995. }
  5996. case OP_DISPATCH:
  5997. case OP_STARTMSG:
  5998. case OP_ENDMSG:
  5999. case OP_PUSHLENDELIM:
  6000. case OP_POP:
  6001. case OP_SETDELIM:
  6002. case OP_HALT:
  6003. case OP_RET:
  6004. break;
  6005. case OP_PARSE_DOUBLE:
  6006. case OP_PARSE_FLOAT:
  6007. case OP_PARSE_INT64:
  6008. case OP_PARSE_UINT64:
  6009. case OP_PARSE_INT32:
  6010. case OP_PARSE_FIXED64:
  6011. case OP_PARSE_FIXED32:
  6012. case OP_PARSE_BOOL:
  6013. case OP_PARSE_UINT32:
  6014. case OP_PARSE_SFIXED32:
  6015. case OP_PARSE_SFIXED64:
  6016. case OP_PARSE_SINT32:
  6017. case OP_PARSE_SINT64:
  6018. case OP_STARTSEQ:
  6019. case OP_ENDSEQ:
  6020. case OP_STARTSUBMSG:
  6021. case OP_ENDSUBMSG:
  6022. case OP_STARTSTR:
  6023. case OP_STRING:
  6024. case OP_ENDSTR:
  6025. case OP_PUSHTAGDELIM:
  6026. fprintf(f, " %d", instr >> 8);
  6027. break;
  6028. case OP_SETBIGGROUPNUM:
  6029. fprintf(f, " %d", *p++);
  6030. break;
  6031. case OP_CHECKDELIM:
  6032. case OP_CALL:
  6033. case OP_BRANCH:
  6034. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  6035. break;
  6036. case OP_TAG1:
  6037. case OP_TAG2: {
  6038. fprintf(f, " tag:0x%x", instr >> 16);
  6039. if (getofs(instr)) {
  6040. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  6041. }
  6042. break;
  6043. }
  6044. case OP_TAGN: {
  6045. uint64_t tag = *p++;
  6046. tag |= (uint64_t)*p++ << 32;
  6047. fprintf(f, " tag:0x%llx", (long long)tag);
  6048. fprintf(f, " n:%d", instr >> 16);
  6049. if (getofs(instr)) {
  6050. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  6051. }
  6052. break;
  6053. }
  6054. }
  6055. fputs("\n", f);
  6056. }
  6057. }
  6058. #endif
  6059. static uint64_t get_encoded_tag(const upb_fielddef *f, int wire_type) {
  6060. uint32_t tag = (upb_fielddef_number(f) << 3) | wire_type;
  6061. uint64_t encoded_tag = upb_vencode32(tag);
  6062. /* No tag should be greater than 5 bytes. */
  6063. assert(encoded_tag <= 0xffffffffff);
  6064. return encoded_tag;
  6065. }
  6066. static void putchecktag(compiler *c, const upb_fielddef *f,
  6067. int wire_type, int dest) {
  6068. uint64_t tag = get_encoded_tag(f, wire_type);
  6069. switch (upb_value_size(tag)) {
  6070. case 1:
  6071. putop(c, OP_TAG1, dest, tag);
  6072. break;
  6073. case 2:
  6074. putop(c, OP_TAG2, dest, tag);
  6075. break;
  6076. default:
  6077. putop(c, OP_TAGN, dest, tag);
  6078. break;
  6079. }
  6080. }
  6081. static upb_selector_t getsel(const upb_fielddef *f, upb_handlertype_t type) {
  6082. upb_selector_t selector;
  6083. bool ok = upb_handlers_getselector(f, type, &selector);
  6084. UPB_ASSERT_VAR(ok, ok);
  6085. return selector;
  6086. }
  6087. /* Takes an existing, primary dispatch table entry and repacks it with a
  6088. * different alternate wire type. Called when we are inserting a secondary
  6089. * dispatch table entry for an alternate wire type. */
  6090. static uint64_t repack(uint64_t dispatch, int new_wt2) {
  6091. uint64_t ofs;
  6092. uint8_t wt1;
  6093. uint8_t old_wt2;
  6094. upb_pbdecoder_unpackdispatch(dispatch, &ofs, &wt1, &old_wt2);
  6095. assert(old_wt2 == NO_WIRE_TYPE); /* wt2 should not be set yet. */
  6096. return upb_pbdecoder_packdispatch(ofs, wt1, new_wt2);
  6097. }
  6098. /* Marks the current bytecode position as the dispatch target for this message,
  6099. * field, and wire type. */
  6100. static void dispatchtarget(compiler *c, upb_pbdecodermethod *method,
  6101. const upb_fielddef *f, int wire_type) {
  6102. /* Offset is relative to msg base. */
  6103. uint64_t ofs = pcofs(c) - method->code_base.ofs;
  6104. uint32_t fn = upb_fielddef_number(f);
  6105. upb_inttable *d = &method->dispatch;
  6106. upb_value v;
  6107. if (upb_inttable_remove(d, fn, &v)) {
  6108. /* TODO: prioritize based on packed setting in .proto file. */
  6109. uint64_t repacked = repack(upb_value_getuint64(v), wire_type);
  6110. upb_inttable_insert(d, fn, upb_value_uint64(repacked));
  6111. upb_inttable_insert(d, fn + UPB_MAX_FIELDNUMBER, upb_value_uint64(ofs));
  6112. } else {
  6113. uint64_t val = upb_pbdecoder_packdispatch(ofs, wire_type, NO_WIRE_TYPE);
  6114. upb_inttable_insert(d, fn, upb_value_uint64(val));
  6115. }
  6116. }
  6117. static void putpush(compiler *c, const upb_fielddef *f) {
  6118. if (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE) {
  6119. putop(c, OP_PUSHLENDELIM);
  6120. } else {
  6121. uint32_t fn = upb_fielddef_number(f);
  6122. if (fn >= 1 << 24) {
  6123. putop(c, OP_PUSHTAGDELIM, 0);
  6124. putop(c, OP_SETBIGGROUPNUM, fn);
  6125. } else {
  6126. putop(c, OP_PUSHTAGDELIM, fn);
  6127. }
  6128. }
  6129. }
  6130. static upb_pbdecodermethod *find_submethod(const compiler *c,
  6131. const upb_pbdecodermethod *method,
  6132. const upb_fielddef *f) {
  6133. const upb_handlers *sub =
  6134. upb_handlers_getsubhandlers(method->dest_handlers_, f);
  6135. upb_value v;
  6136. return upb_inttable_lookupptr(&c->group->methods, sub, &v)
  6137. ? upb_value_getptr(v)
  6138. : NULL;
  6139. }
  6140. static void putsel(compiler *c, opcode op, upb_selector_t sel,
  6141. const upb_handlers *h) {
  6142. if (upb_handlers_gethandler(h, sel)) {
  6143. putop(c, op, sel);
  6144. }
  6145. }
  6146. /* Puts an opcode to call a callback, but only if a callback actually exists for
  6147. * this field and handler type. */
  6148. static void maybeput(compiler *c, opcode op, const upb_handlers *h,
  6149. const upb_fielddef *f, upb_handlertype_t type) {
  6150. putsel(c, op, getsel(f, type), h);
  6151. }
  6152. static bool haslazyhandlers(const upb_handlers *h, const upb_fielddef *f) {
  6153. if (!upb_fielddef_lazy(f))
  6154. return false;
  6155. return upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STARTSTR)) ||
  6156. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STRING)) ||
  6157. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_ENDSTR));
  6158. }
  6159. /* bytecode compiler code generation ******************************************/
  6160. /* Symbolic names for our local labels. */
  6161. #define LABEL_LOOPSTART 1 /* Top of a repeated field loop. */
  6162. #define LABEL_LOOPBREAK 2 /* To jump out of a repeated loop */
  6163. #define LABEL_FIELD 3 /* Jump backward to find the most recent field. */
  6164. #define LABEL_ENDMSG 4 /* To reach the OP_ENDMSG instr for this msg. */
  6165. /* Generates bytecode to parse a single non-lazy message field. */
  6166. static void generate_msgfield(compiler *c, const upb_fielddef *f,
  6167. upb_pbdecodermethod *method) {
  6168. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  6169. const upb_pbdecodermethod *sub_m = find_submethod(c, method, f);
  6170. int wire_type;
  6171. if (!sub_m) {
  6172. /* Don't emit any code for this field at all; it will be parsed as an
  6173. * unknown field. */
  6174. return;
  6175. }
  6176. label(c, LABEL_FIELD);
  6177. wire_type =
  6178. (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE)
  6179. ? UPB_WIRE_TYPE_DELIMITED
  6180. : UPB_WIRE_TYPE_START_GROUP;
  6181. if (upb_fielddef_isseq(f)) {
  6182. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  6183. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  6184. dispatchtarget(c, method, f, wire_type);
  6185. putop(c, OP_PUSHTAGDELIM, 0);
  6186. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  6187. label(c, LABEL_LOOPSTART);
  6188. putpush(c, f);
  6189. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  6190. putop(c, OP_CALL, sub_m);
  6191. putop(c, OP_POP);
  6192. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  6193. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  6194. putop(c, OP_SETDELIM);
  6195. }
  6196. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  6197. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  6198. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  6199. label(c, LABEL_LOOPBREAK);
  6200. putop(c, OP_POP);
  6201. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  6202. } else {
  6203. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  6204. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  6205. dispatchtarget(c, method, f, wire_type);
  6206. putpush(c, f);
  6207. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  6208. putop(c, OP_CALL, sub_m);
  6209. putop(c, OP_POP);
  6210. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  6211. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  6212. putop(c, OP_SETDELIM);
  6213. }
  6214. }
  6215. }
  6216. /* Generates bytecode to parse a single string or lazy submessage field. */
  6217. static void generate_delimfield(compiler *c, const upb_fielddef *f,
  6218. upb_pbdecodermethod *method) {
  6219. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  6220. label(c, LABEL_FIELD);
  6221. if (upb_fielddef_isseq(f)) {
  6222. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  6223. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  6224. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  6225. putop(c, OP_PUSHTAGDELIM, 0);
  6226. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  6227. label(c, LABEL_LOOPSTART);
  6228. putop(c, OP_PUSHLENDELIM);
  6229. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  6230. /* Need to emit even if no handler to skip past the string. */
  6231. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  6232. putop(c, OP_POP);
  6233. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  6234. putop(c, OP_SETDELIM);
  6235. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  6236. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_LOOPBREAK);
  6237. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  6238. label(c, LABEL_LOOPBREAK);
  6239. putop(c, OP_POP);
  6240. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  6241. } else {
  6242. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  6243. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  6244. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  6245. putop(c, OP_PUSHLENDELIM);
  6246. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  6247. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  6248. putop(c, OP_POP);
  6249. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  6250. putop(c, OP_SETDELIM);
  6251. }
  6252. }
  6253. /* Generates bytecode to parse a single primitive field. */
  6254. static void generate_primitivefield(compiler *c, const upb_fielddef *f,
  6255. upb_pbdecodermethod *method) {
  6256. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  6257. upb_descriptortype_t descriptor_type = upb_fielddef_descriptortype(f);
  6258. opcode parse_type;
  6259. upb_selector_t sel;
  6260. int wire_type;
  6261. label(c, LABEL_FIELD);
  6262. /* From a decoding perspective, ENUM is the same as INT32. */
  6263. if (descriptor_type == UPB_DESCRIPTOR_TYPE_ENUM)
  6264. descriptor_type = UPB_DESCRIPTOR_TYPE_INT32;
  6265. parse_type = (opcode)descriptor_type;
  6266. /* TODO(haberman): generate packed or non-packed first depending on "packed"
  6267. * setting in the fielddef. This will favor (in speed) whichever was
  6268. * specified. */
  6269. assert((int)parse_type >= 0 && parse_type <= OP_MAX);
  6270. sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  6271. wire_type = upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  6272. if (upb_fielddef_isseq(f)) {
  6273. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  6274. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  6275. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  6276. putop(c, OP_PUSHLENDELIM);
  6277. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); /* Packed */
  6278. label(c, LABEL_LOOPSTART);
  6279. putop(c, parse_type, sel);
  6280. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  6281. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  6282. dispatchtarget(c, method, f, wire_type);
  6283. putop(c, OP_PUSHTAGDELIM, 0);
  6284. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); /* Non-packed */
  6285. label(c, LABEL_LOOPSTART);
  6286. putop(c, parse_type, sel);
  6287. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  6288. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  6289. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  6290. label(c, LABEL_LOOPBREAK);
  6291. putop(c, OP_POP); /* Packed and non-packed join. */
  6292. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  6293. putop(c, OP_SETDELIM); /* Could remove for non-packed by dup ENDSEQ. */
  6294. } else {
  6295. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  6296. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  6297. dispatchtarget(c, method, f, wire_type);
  6298. putop(c, parse_type, sel);
  6299. }
  6300. }
  6301. /* Adds bytecode for parsing the given message to the given decoderplan,
  6302. * while adding all dispatch targets to this message's dispatch table. */
  6303. static void compile_method(compiler *c, upb_pbdecodermethod *method) {
  6304. const upb_handlers *h;
  6305. const upb_msgdef *md;
  6306. uint32_t* start_pc;
  6307. upb_msg_field_iter i;
  6308. upb_value val;
  6309. assert(method);
  6310. /* Clear all entries in the dispatch table. */
  6311. upb_inttable_uninit(&method->dispatch);
  6312. upb_inttable_init(&method->dispatch, UPB_CTYPE_UINT64);
  6313. h = upb_pbdecodermethod_desthandlers(method);
  6314. md = upb_handlers_msgdef(h);
  6315. method->code_base.ofs = pcofs(c);
  6316. putop(c, OP_SETDISPATCH, &method->dispatch);
  6317. putsel(c, OP_STARTMSG, UPB_STARTMSG_SELECTOR, h);
  6318. label(c, LABEL_FIELD);
  6319. start_pc = c->pc;
  6320. for(upb_msg_field_begin(&i, md);
  6321. !upb_msg_field_done(&i);
  6322. upb_msg_field_next(&i)) {
  6323. const upb_fielddef *f = upb_msg_iter_field(&i);
  6324. upb_fieldtype_t type = upb_fielddef_type(f);
  6325. if (type == UPB_TYPE_MESSAGE && !(haslazyhandlers(h, f) && c->lazy)) {
  6326. generate_msgfield(c, f, method);
  6327. } else if (type == UPB_TYPE_STRING || type == UPB_TYPE_BYTES ||
  6328. type == UPB_TYPE_MESSAGE) {
  6329. generate_delimfield(c, f, method);
  6330. } else {
  6331. generate_primitivefield(c, f, method);
  6332. }
  6333. }
  6334. /* If there were no fields, or if no handlers were defined, we need to
  6335. * generate a non-empty loop body so that we can at least dispatch for unknown
  6336. * fields and check for the end of the message. */
  6337. if (c->pc == start_pc) {
  6338. /* Check for end-of-message. */
  6339. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  6340. /* Unconditionally dispatch. */
  6341. putop(c, OP_DISPATCH, 0);
  6342. }
  6343. /* For now we just loop back to the last field of the message (or if none,
  6344. * the DISPATCH opcode for the message). */
  6345. putop(c, OP_BRANCH, -LABEL_FIELD);
  6346. /* Insert both a label and a dispatch table entry for this end-of-msg. */
  6347. label(c, LABEL_ENDMSG);
  6348. val = upb_value_uint64(pcofs(c) - method->code_base.ofs);
  6349. upb_inttable_insert(&method->dispatch, DISPATCH_ENDMSG, val);
  6350. putsel(c, OP_ENDMSG, UPB_ENDMSG_SELECTOR, h);
  6351. putop(c, OP_RET);
  6352. upb_inttable_compact(&method->dispatch);
  6353. }
  6354. /* Populate "methods" with new upb_pbdecodermethod objects reachable from "h".
  6355. * Returns the method for these handlers.
  6356. *
  6357. * Generates a new method for every destination handlers reachable from "h". */
  6358. static void find_methods(compiler *c, const upb_handlers *h) {
  6359. upb_value v;
  6360. upb_msg_field_iter i;
  6361. const upb_msgdef *md;
  6362. if (upb_inttable_lookupptr(&c->group->methods, h, &v))
  6363. return;
  6364. newmethod(h, c->group);
  6365. /* Find submethods. */
  6366. md = upb_handlers_msgdef(h);
  6367. for(upb_msg_field_begin(&i, md);
  6368. !upb_msg_field_done(&i);
  6369. upb_msg_field_next(&i)) {
  6370. const upb_fielddef *f = upb_msg_iter_field(&i);
  6371. const upb_handlers *sub_h;
  6372. if (upb_fielddef_type(f) == UPB_TYPE_MESSAGE &&
  6373. (sub_h = upb_handlers_getsubhandlers(h, f)) != NULL) {
  6374. /* We only generate a decoder method for submessages with handlers.
  6375. * Others will be parsed as unknown fields. */
  6376. find_methods(c, sub_h);
  6377. }
  6378. }
  6379. }
  6380. /* (Re-)compile bytecode for all messages in "msgs."
  6381. * Overwrites any existing bytecode in "c". */
  6382. static void compile_methods(compiler *c) {
  6383. upb_inttable_iter i;
  6384. /* Start over at the beginning of the bytecode. */
  6385. c->pc = c->group->bytecode;
  6386. upb_inttable_begin(&i, &c->group->methods);
  6387. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  6388. upb_pbdecodermethod *method = upb_value_getptr(upb_inttable_iter_value(&i));
  6389. compile_method(c, method);
  6390. }
  6391. }
  6392. static void set_bytecode_handlers(mgroup *g) {
  6393. upb_inttable_iter i;
  6394. upb_inttable_begin(&i, &g->methods);
  6395. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  6396. upb_pbdecodermethod *m = upb_value_getptr(upb_inttable_iter_value(&i));
  6397. upb_byteshandler *h = &m->input_handler_;
  6398. m->code_base.ptr = g->bytecode + m->code_base.ofs;
  6399. upb_byteshandler_setstartstr(h, upb_pbdecoder_startbc, m->code_base.ptr);
  6400. upb_byteshandler_setstring(h, upb_pbdecoder_decode, g);
  6401. upb_byteshandler_setendstr(h, upb_pbdecoder_end, m);
  6402. }
  6403. }
  6404. /* JIT setup. *****************************************************************/
  6405. #ifdef UPB_USE_JIT_X64
  6406. static void sethandlers(mgroup *g, bool allowjit) {
  6407. g->jit_code = NULL;
  6408. if (allowjit) {
  6409. /* Compile byte-code into machine code, create handlers. */
  6410. upb_pbdecoder_jit(g);
  6411. } else {
  6412. set_bytecode_handlers(g);
  6413. }
  6414. }
  6415. #else /* UPB_USE_JIT_X64 */
  6416. static void sethandlers(mgroup *g, bool allowjit) {
  6417. /* No JIT compiled in; use bytecode handlers unconditionally. */
  6418. UPB_UNUSED(allowjit);
  6419. set_bytecode_handlers(g);
  6420. }
  6421. #endif /* UPB_USE_JIT_X64 */
  6422. /* TODO(haberman): allow this to be constructed for an arbitrary set of dest
  6423. * handlers and other mgroups (but verify we have a transitive closure). */
  6424. const mgroup *mgroup_new(const upb_handlers *dest, bool allowjit, bool lazy,
  6425. const void *owner) {
  6426. mgroup *g;
  6427. compiler *c;
  6428. UPB_UNUSED(allowjit);
  6429. assert(upb_handlers_isfrozen(dest));
  6430. g = newgroup(owner);
  6431. c = newcompiler(g, lazy);
  6432. find_methods(c, dest);
  6433. /* We compile in two passes:
  6434. * 1. all messages are assigned relative offsets from the beginning of the
  6435. * bytecode (saved in method->code_base).
  6436. * 2. forwards OP_CALL instructions can be correctly linked since message
  6437. * offsets have been previously assigned.
  6438. *
  6439. * Could avoid the second pass by linking OP_CALL instructions somehow. */
  6440. compile_methods(c);
  6441. compile_methods(c);
  6442. g->bytecode_end = c->pc;
  6443. freecompiler(c);
  6444. #ifdef UPB_DUMP_BYTECODE
  6445. {
  6446. FILE *f = fopen("/tmp/upb-bytecode", "wb");
  6447. assert(f);
  6448. dumpbc(g->bytecode, g->bytecode_end, stderr);
  6449. dumpbc(g->bytecode, g->bytecode_end, f);
  6450. fclose(f);
  6451. }
  6452. #endif
  6453. sethandlers(g, allowjit);
  6454. return g;
  6455. }
  6456. /* upb_pbcodecache ************************************************************/
  6457. void upb_pbcodecache_init(upb_pbcodecache *c) {
  6458. upb_inttable_init(&c->groups, UPB_CTYPE_CONSTPTR);
  6459. c->allow_jit_ = true;
  6460. }
  6461. void upb_pbcodecache_uninit(upb_pbcodecache *c) {
  6462. upb_inttable_iter i;
  6463. upb_inttable_begin(&i, &c->groups);
  6464. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  6465. const mgroup *group = upb_value_getconstptr(upb_inttable_iter_value(&i));
  6466. mgroup_unref(group, c);
  6467. }
  6468. upb_inttable_uninit(&c->groups);
  6469. }
  6470. bool upb_pbcodecache_allowjit(const upb_pbcodecache *c) {
  6471. return c->allow_jit_;
  6472. }
  6473. bool upb_pbcodecache_setallowjit(upb_pbcodecache *c, bool allow) {
  6474. if (upb_inttable_count(&c->groups) > 0)
  6475. return false;
  6476. c->allow_jit_ = allow;
  6477. return true;
  6478. }
  6479. const upb_pbdecodermethod *upb_pbcodecache_getdecodermethod(
  6480. upb_pbcodecache *c, const upb_pbdecodermethodopts *opts) {
  6481. upb_value v;
  6482. bool ok;
  6483. /* Right now we build a new DecoderMethod every time.
  6484. * TODO(haberman): properly cache methods by their true key. */
  6485. const mgroup *g = mgroup_new(opts->handlers, c->allow_jit_, opts->lazy, c);
  6486. upb_inttable_push(&c->groups, upb_value_constptr(g));
  6487. ok = upb_inttable_lookupptr(&g->methods, opts->handlers, &v);
  6488. UPB_ASSERT_VAR(ok, ok);
  6489. return upb_value_getptr(v);
  6490. }
  6491. /* upb_pbdecodermethodopts ****************************************************/
  6492. void upb_pbdecodermethodopts_init(upb_pbdecodermethodopts *opts,
  6493. const upb_handlers *h) {
  6494. opts->handlers = h;
  6495. opts->lazy = false;
  6496. }
  6497. void upb_pbdecodermethodopts_setlazy(upb_pbdecodermethodopts *opts, bool lazy) {
  6498. opts->lazy = lazy;
  6499. }
  6500. /*
  6501. * upb - a minimalist implementation of protocol buffers.
  6502. *
  6503. * Copyright (c) 2008-2013 Google Inc. See LICENSE for details.
  6504. * Author: Josh Haberman <jhaberman@gmail.com>
  6505. *
  6506. * This file implements a VM for the interpreted (bytecode) decoder.
  6507. *
  6508. * Bytecode must previously have been generated using the bytecode compiler in
  6509. * compile_decoder.c. This decoder then walks through the bytecode op-by-op to
  6510. * parse the input.
  6511. *
  6512. * Decoding is fully resumable; we just keep a pointer to the current bytecode
  6513. * instruction and resume from there. A fair amount of the logic here is to
  6514. * handle the fact that values can span buffer seams and we have to be able to
  6515. * be capable of suspending/resuming from any byte in the stream. This
  6516. * sometimes requires keeping a few trailing bytes from the last buffer around
  6517. * in the "residual" buffer.
  6518. */
  6519. #include <inttypes.h>
  6520. #include <stddef.h>
  6521. #ifdef UPB_DUMP_BYTECODE
  6522. #include <stdio.h>
  6523. #endif
  6524. #define CHECK_SUSPEND(x) if (!(x)) return upb_pbdecoder_suspend(d);
  6525. /* Error messages that are shared between the bytecode and JIT decoders. */
  6526. const char *kPbDecoderStackOverflow = "Nesting too deep.";
  6527. /* Error messages shared within this file. */
  6528. static const char *kUnterminatedVarint = "Unterminated varint.";
  6529. /* upb_pbdecoder **************************************************************/
  6530. static opcode halt = OP_HALT;
  6531. /* Whether an op consumes any of the input buffer. */
  6532. static bool consumes_input(opcode op) {
  6533. switch (op) {
  6534. case OP_SETDISPATCH:
  6535. case OP_STARTMSG:
  6536. case OP_ENDMSG:
  6537. case OP_STARTSEQ:
  6538. case OP_ENDSEQ:
  6539. case OP_STARTSUBMSG:
  6540. case OP_ENDSUBMSG:
  6541. case OP_STARTSTR:
  6542. case OP_ENDSTR:
  6543. case OP_PUSHTAGDELIM:
  6544. case OP_POP:
  6545. case OP_SETDELIM:
  6546. case OP_SETBIGGROUPNUM:
  6547. case OP_CHECKDELIM:
  6548. case OP_CALL:
  6549. case OP_RET:
  6550. case OP_BRANCH:
  6551. return false;
  6552. default:
  6553. return true;
  6554. }
  6555. }
  6556. static bool in_residual_buf(const upb_pbdecoder *d, const char *p);
  6557. /* It's unfortunate that we have to micro-manage the compiler with
  6558. * UPB_FORCEINLINE and UPB_NOINLINE, especially since this tuning is necessarily
  6559. * specific to one hardware configuration. But empirically on a Core i7,
  6560. * performance increases 30-50% with these annotations. Every instance where
  6561. * these appear, gcc 4.2.1 made the wrong decision and degraded performance in
  6562. * benchmarks. */
  6563. static void seterr(upb_pbdecoder *d, const char *msg) {
  6564. upb_status status = UPB_STATUS_INIT;
  6565. upb_status_seterrmsg(&status, msg);
  6566. upb_env_reporterror(d->env, &status);
  6567. }
  6568. void upb_pbdecoder_seterr(upb_pbdecoder *d, const char *msg) {
  6569. seterr(d, msg);
  6570. }
  6571. /* Buffering ******************************************************************/
  6572. /* We operate on one buffer at a time, which is either the user's buffer passed
  6573. * to our "decode" callback or some residual bytes from the previous buffer. */
  6574. /* How many bytes can be safely read from d->ptr without reading past end-of-buf
  6575. * or past the current delimited end. */
  6576. static size_t curbufleft(const upb_pbdecoder *d) {
  6577. assert(d->data_end >= d->ptr);
  6578. return d->data_end - d->ptr;
  6579. }
  6580. /* Overall stream offset of d->ptr. */
  6581. uint64_t offset(const upb_pbdecoder *d) {
  6582. return d->bufstart_ofs + (d->ptr - d->buf);
  6583. }
  6584. /* Advances d->ptr. */
  6585. static void advance(upb_pbdecoder *d, size_t len) {
  6586. assert(curbufleft(d) >= len);
  6587. d->ptr += len;
  6588. }
  6589. static bool in_buf(const char *p, const char *buf, const char *end) {
  6590. return p >= buf && p <= end;
  6591. }
  6592. static bool in_residual_buf(const upb_pbdecoder *d, const char *p) {
  6593. return in_buf(p, d->residual, d->residual_end);
  6594. }
  6595. /* Calculates the delim_end value, which is affected by both the current buffer
  6596. * and the parsing stack, so must be called whenever either is updated. */
  6597. static void set_delim_end(upb_pbdecoder *d) {
  6598. size_t delim_ofs = d->top->end_ofs - d->bufstart_ofs;
  6599. if (delim_ofs <= (size_t)(d->end - d->buf)) {
  6600. d->delim_end = d->buf + delim_ofs;
  6601. d->data_end = d->delim_end;
  6602. } else {
  6603. d->data_end = d->end;
  6604. d->delim_end = NULL;
  6605. }
  6606. }
  6607. static void switchtobuf(upb_pbdecoder *d, const char *buf, const char *end) {
  6608. d->ptr = buf;
  6609. d->buf = buf;
  6610. d->end = end;
  6611. set_delim_end(d);
  6612. }
  6613. static void advancetobuf(upb_pbdecoder *d, const char *buf, size_t len) {
  6614. assert(curbufleft(d) == 0);
  6615. d->bufstart_ofs += (d->end - d->buf);
  6616. switchtobuf(d, buf, buf + len);
  6617. }
  6618. static void checkpoint(upb_pbdecoder *d) {
  6619. /* The assertion here is in the interests of efficiency, not correctness.
  6620. * We are trying to ensure that we don't checkpoint() more often than
  6621. * necessary. */
  6622. assert(d->checkpoint != d->ptr);
  6623. d->checkpoint = d->ptr;
  6624. }
  6625. /* Resumes the decoder from an initial state or from a previous suspend. */
  6626. int32_t upb_pbdecoder_resume(upb_pbdecoder *d, void *p, const char *buf,
  6627. size_t size, const upb_bufhandle *handle) {
  6628. UPB_UNUSED(p); /* Useless; just for the benefit of the JIT. */
  6629. d->buf_param = buf;
  6630. d->size_param = size;
  6631. d->handle = handle;
  6632. if (d->residual_end > d->residual) {
  6633. /* We have residual bytes from the last buffer. */
  6634. assert(d->ptr == d->residual);
  6635. } else {
  6636. switchtobuf(d, buf, buf + size);
  6637. }
  6638. d->checkpoint = d->ptr;
  6639. if (d->top->groupnum < 0) {
  6640. CHECK_RETURN(upb_pbdecoder_skipunknown(d, -1, 0));
  6641. d->checkpoint = d->ptr;
  6642. }
  6643. return DECODE_OK;
  6644. }
  6645. /* Suspends the decoder at the last checkpoint, without saving any residual
  6646. * bytes. If there are any unconsumed bytes, returns a short byte count. */
  6647. size_t upb_pbdecoder_suspend(upb_pbdecoder *d) {
  6648. d->pc = d->last;
  6649. if (d->checkpoint == d->residual) {
  6650. /* Checkpoint was in residual buf; no user bytes were consumed. */
  6651. d->ptr = d->residual;
  6652. return 0;
  6653. } else {
  6654. size_t consumed;
  6655. assert(!in_residual_buf(d, d->checkpoint));
  6656. assert(d->buf == d->buf_param);
  6657. consumed = d->checkpoint - d->buf;
  6658. d->bufstart_ofs += consumed;
  6659. d->residual_end = d->residual;
  6660. switchtobuf(d, d->residual, d->residual_end);
  6661. return consumed;
  6662. }
  6663. }
  6664. /* Suspends the decoder at the last checkpoint, and saves any unconsumed
  6665. * bytes in our residual buffer. This is necessary if we need more user
  6666. * bytes to form a complete value, which might not be contiguous in the
  6667. * user's buffers. Always consumes all user bytes. */
  6668. static size_t suspend_save(upb_pbdecoder *d) {
  6669. /* We hit end-of-buffer before we could parse a full value.
  6670. * Save any unconsumed bytes (if any) to the residual buffer. */
  6671. d->pc = d->last;
  6672. if (d->checkpoint == d->residual) {
  6673. /* Checkpoint was in residual buf; append user byte(s) to residual buf. */
  6674. assert((d->residual_end - d->residual) + d->size_param <=
  6675. sizeof(d->residual));
  6676. if (!in_residual_buf(d, d->ptr)) {
  6677. d->bufstart_ofs -= (d->residual_end - d->residual);
  6678. }
  6679. memcpy(d->residual_end, d->buf_param, d->size_param);
  6680. d->residual_end += d->size_param;
  6681. } else {
  6682. /* Checkpoint was in user buf; old residual bytes not needed. */
  6683. size_t save;
  6684. assert(!in_residual_buf(d, d->checkpoint));
  6685. d->ptr = d->checkpoint;
  6686. save = curbufleft(d);
  6687. assert(save <= sizeof(d->residual));
  6688. memcpy(d->residual, d->ptr, save);
  6689. d->residual_end = d->residual + save;
  6690. d->bufstart_ofs = offset(d);
  6691. }
  6692. switchtobuf(d, d->residual, d->residual_end);
  6693. return d->size_param;
  6694. }
  6695. /* Skips "bytes" bytes in the stream, which may be more than available. If we
  6696. * skip more bytes than are available, we return a long read count to the caller
  6697. * indicating how many bytes the caller should skip before passing a new buffer.
  6698. */
  6699. static int32_t skip(upb_pbdecoder *d, size_t bytes) {
  6700. assert(!in_residual_buf(d, d->ptr) || d->size_param == 0);
  6701. if (curbufleft(d) >= bytes) {
  6702. /* Skipped data is all in current buffer. */
  6703. advance(d, bytes);
  6704. return DECODE_OK;
  6705. } else {
  6706. /* Skipped data extends beyond currently available buffers. */
  6707. size_t skip;
  6708. d->pc = d->last;
  6709. skip = bytes - curbufleft(d);
  6710. d->bufstart_ofs += (d->end - d->buf) + skip;
  6711. d->residual_end = d->residual;
  6712. switchtobuf(d, d->residual, d->residual_end);
  6713. return d->size_param + skip;
  6714. }
  6715. }
  6716. /* Copies the next "bytes" bytes into "buf" and advances the stream.
  6717. * Requires that this many bytes are available in the current buffer. */
  6718. UPB_FORCEINLINE static void consumebytes(upb_pbdecoder *d, void *buf,
  6719. size_t bytes) {
  6720. assert(bytes <= curbufleft(d));
  6721. memcpy(buf, d->ptr, bytes);
  6722. advance(d, bytes);
  6723. }
  6724. /* Slow path for getting the next "bytes" bytes, regardless of whether they are
  6725. * available in the current buffer or not. Returns a status code as described
  6726. * in decoder.int.h. */
  6727. UPB_NOINLINE static int32_t getbytes_slow(upb_pbdecoder *d, void *buf,
  6728. size_t bytes) {
  6729. const size_t avail = curbufleft(d);
  6730. consumebytes(d, buf, avail);
  6731. bytes -= avail;
  6732. assert(bytes > 0);
  6733. if (in_residual_buf(d, d->ptr)) {
  6734. advancetobuf(d, d->buf_param, d->size_param);
  6735. }
  6736. if (curbufleft(d) >= bytes) {
  6737. consumebytes(d, (char *)buf + avail, bytes);
  6738. return DECODE_OK;
  6739. } else if (d->data_end == d->delim_end) {
  6740. seterr(d, "Submessage ended in the middle of a value or group");
  6741. return upb_pbdecoder_suspend(d);
  6742. } else {
  6743. return suspend_save(d);
  6744. }
  6745. }
  6746. /* Gets the next "bytes" bytes, regardless of whether they are available in the
  6747. * current buffer or not. Returns a status code as described in decoder.int.h.
  6748. */
  6749. UPB_FORCEINLINE static int32_t getbytes(upb_pbdecoder *d, void *buf,
  6750. size_t bytes) {
  6751. if (curbufleft(d) >= bytes) {
  6752. /* Buffer has enough data to satisfy. */
  6753. consumebytes(d, buf, bytes);
  6754. return DECODE_OK;
  6755. } else {
  6756. return getbytes_slow(d, buf, bytes);
  6757. }
  6758. }
  6759. UPB_NOINLINE static size_t peekbytes_slow(upb_pbdecoder *d, void *buf,
  6760. size_t bytes) {
  6761. size_t ret = curbufleft(d);
  6762. memcpy(buf, d->ptr, ret);
  6763. if (in_residual_buf(d, d->ptr)) {
  6764. size_t copy = UPB_MIN(bytes - ret, d->size_param);
  6765. memcpy((char *)buf + ret, d->buf_param, copy);
  6766. ret += copy;
  6767. }
  6768. return ret;
  6769. }
  6770. UPB_FORCEINLINE static size_t peekbytes(upb_pbdecoder *d, void *buf,
  6771. size_t bytes) {
  6772. if (curbufleft(d) >= bytes) {
  6773. memcpy(buf, d->ptr, bytes);
  6774. return bytes;
  6775. } else {
  6776. return peekbytes_slow(d, buf, bytes);
  6777. }
  6778. }
  6779. /* Decoding of wire types *****************************************************/
  6780. /* Slow path for decoding a varint from the current buffer position.
  6781. * Returns a status code as described in decoder.int.h. */
  6782. UPB_NOINLINE int32_t upb_pbdecoder_decode_varint_slow(upb_pbdecoder *d,
  6783. uint64_t *u64) {
  6784. uint8_t byte = 0x80;
  6785. int bitpos;
  6786. *u64 = 0;
  6787. for(bitpos = 0; bitpos < 70 && (byte & 0x80); bitpos += 7) {
  6788. int32_t ret = getbytes(d, &byte, 1);
  6789. if (ret >= 0) return ret;
  6790. *u64 |= (uint64_t)(byte & 0x7F) << bitpos;
  6791. }
  6792. if(bitpos == 70 && (byte & 0x80)) {
  6793. seterr(d, kUnterminatedVarint);
  6794. return upb_pbdecoder_suspend(d);
  6795. }
  6796. return DECODE_OK;
  6797. }
  6798. /* Decodes a varint from the current buffer position.
  6799. * Returns a status code as described in decoder.int.h. */
  6800. UPB_FORCEINLINE static int32_t decode_varint(upb_pbdecoder *d, uint64_t *u64) {
  6801. if (curbufleft(d) > 0 && !(*d->ptr & 0x80)) {
  6802. *u64 = *d->ptr;
  6803. advance(d, 1);
  6804. return DECODE_OK;
  6805. } else if (curbufleft(d) >= 10) {
  6806. /* Fast case. */
  6807. upb_decoderet r = upb_vdecode_fast(d->ptr);
  6808. if (r.p == NULL) {
  6809. seterr(d, kUnterminatedVarint);
  6810. return upb_pbdecoder_suspend(d);
  6811. }
  6812. advance(d, r.p - d->ptr);
  6813. *u64 = r.val;
  6814. return DECODE_OK;
  6815. } else {
  6816. /* Slow case -- varint spans buffer seam. */
  6817. return upb_pbdecoder_decode_varint_slow(d, u64);
  6818. }
  6819. }
  6820. /* Decodes a 32-bit varint from the current buffer position.
  6821. * Returns a status code as described in decoder.int.h. */
  6822. UPB_FORCEINLINE static int32_t decode_v32(upb_pbdecoder *d, uint32_t *u32) {
  6823. uint64_t u64;
  6824. int32_t ret = decode_varint(d, &u64);
  6825. if (ret >= 0) return ret;
  6826. if (u64 > UINT32_MAX) {
  6827. seterr(d, "Unterminated 32-bit varint");
  6828. /* TODO(haberman) guarantee that this function return is >= 0 somehow,
  6829. * so we know this path will always be treated as error by our caller.
  6830. * Right now the size_t -> int32_t can overflow and produce negative values.
  6831. */
  6832. *u32 = 0;
  6833. return upb_pbdecoder_suspend(d);
  6834. }
  6835. *u32 = u64;
  6836. return DECODE_OK;
  6837. }
  6838. /* Decodes a fixed32 from the current buffer position.
  6839. * Returns a status code as described in decoder.int.h.
  6840. * TODO: proper byte swapping for big-endian machines. */
  6841. UPB_FORCEINLINE static int32_t decode_fixed32(upb_pbdecoder *d, uint32_t *u32) {
  6842. return getbytes(d, u32, 4);
  6843. }
  6844. /* Decodes a fixed64 from the current buffer position.
  6845. * Returns a status code as described in decoder.int.h.
  6846. * TODO: proper byte swapping for big-endian machines. */
  6847. UPB_FORCEINLINE static int32_t decode_fixed64(upb_pbdecoder *d, uint64_t *u64) {
  6848. return getbytes(d, u64, 8);
  6849. }
  6850. /* Non-static versions of the above functions.
  6851. * These are called by the JIT for fallback paths. */
  6852. int32_t upb_pbdecoder_decode_f32(upb_pbdecoder *d, uint32_t *u32) {
  6853. return decode_fixed32(d, u32);
  6854. }
  6855. int32_t upb_pbdecoder_decode_f64(upb_pbdecoder *d, uint64_t *u64) {
  6856. return decode_fixed64(d, u64);
  6857. }
  6858. static double as_double(uint64_t n) { double d; memcpy(&d, &n, 8); return d; }
  6859. static float as_float(uint32_t n) { float f; memcpy(&f, &n, 4); return f; }
  6860. /* Pushes a frame onto the decoder stack. */
  6861. static bool decoder_push(upb_pbdecoder *d, uint64_t end) {
  6862. upb_pbdecoder_frame *fr = d->top;
  6863. if (end > fr->end_ofs) {
  6864. seterr(d, "Submessage end extends past enclosing submessage.");
  6865. return false;
  6866. } else if (fr == d->limit) {
  6867. seterr(d, kPbDecoderStackOverflow);
  6868. return false;
  6869. }
  6870. fr++;
  6871. fr->end_ofs = end;
  6872. fr->dispatch = NULL;
  6873. fr->groupnum = 0;
  6874. d->top = fr;
  6875. return true;
  6876. }
  6877. static bool pushtagdelim(upb_pbdecoder *d, uint32_t arg) {
  6878. /* While we expect to see an "end" tag (either ENDGROUP or a non-sequence
  6879. * field number) prior to hitting any enclosing submessage end, pushing our
  6880. * existing delim end prevents us from continuing to parse values from a
  6881. * corrupt proto that doesn't give us an END tag in time. */
  6882. if (!decoder_push(d, d->top->end_ofs))
  6883. return false;
  6884. d->top->groupnum = arg;
  6885. return true;
  6886. }
  6887. /* Pops a frame from the decoder stack. */
  6888. static void decoder_pop(upb_pbdecoder *d) { d->top--; }
  6889. UPB_NOINLINE int32_t upb_pbdecoder_checktag_slow(upb_pbdecoder *d,
  6890. uint64_t expected) {
  6891. uint64_t data = 0;
  6892. size_t bytes = upb_value_size(expected);
  6893. size_t read = peekbytes(d, &data, bytes);
  6894. if (read == bytes && data == expected) {
  6895. /* Advance past matched bytes. */
  6896. int32_t ok = getbytes(d, &data, read);
  6897. UPB_ASSERT_VAR(ok, ok < 0);
  6898. return DECODE_OK;
  6899. } else if (read < bytes && memcmp(&data, &expected, read) == 0) {
  6900. return suspend_save(d);
  6901. } else {
  6902. return DECODE_MISMATCH;
  6903. }
  6904. }
  6905. int32_t upb_pbdecoder_skipunknown(upb_pbdecoder *d, int32_t fieldnum,
  6906. uint8_t wire_type) {
  6907. if (fieldnum >= 0)
  6908. goto have_tag;
  6909. while (true) {
  6910. uint32_t tag;
  6911. CHECK_RETURN(decode_v32(d, &tag));
  6912. wire_type = tag & 0x7;
  6913. fieldnum = tag >> 3;
  6914. have_tag:
  6915. if (fieldnum == 0) {
  6916. seterr(d, "Saw invalid field number (0)");
  6917. return upb_pbdecoder_suspend(d);
  6918. }
  6919. /* TODO: deliver to unknown field callback. */
  6920. switch (wire_type) {
  6921. case UPB_WIRE_TYPE_32BIT:
  6922. CHECK_RETURN(skip(d, 4));
  6923. break;
  6924. case UPB_WIRE_TYPE_64BIT:
  6925. CHECK_RETURN(skip(d, 8));
  6926. break;
  6927. case UPB_WIRE_TYPE_VARINT: {
  6928. uint64_t u64;
  6929. CHECK_RETURN(decode_varint(d, &u64));
  6930. break;
  6931. }
  6932. case UPB_WIRE_TYPE_DELIMITED: {
  6933. uint32_t len;
  6934. CHECK_RETURN(decode_v32(d, &len));
  6935. CHECK_RETURN(skip(d, len));
  6936. break;
  6937. }
  6938. case UPB_WIRE_TYPE_START_GROUP:
  6939. CHECK_SUSPEND(pushtagdelim(d, -fieldnum));
  6940. break;
  6941. case UPB_WIRE_TYPE_END_GROUP:
  6942. if (fieldnum == -d->top->groupnum) {
  6943. decoder_pop(d);
  6944. } else if (fieldnum == d->top->groupnum) {
  6945. return DECODE_ENDGROUP;
  6946. } else {
  6947. seterr(d, "Unmatched ENDGROUP tag.");
  6948. return upb_pbdecoder_suspend(d);
  6949. }
  6950. break;
  6951. default:
  6952. seterr(d, "Invalid wire type");
  6953. return upb_pbdecoder_suspend(d);
  6954. }
  6955. if (d->top->groupnum >= 0) {
  6956. return DECODE_OK;
  6957. }
  6958. if (d->ptr == d->delim_end) {
  6959. seterr(d, "Enclosing submessage ended in the middle of value or group");
  6960. /* Unlike most errors we notice during parsing, right now we have consumed
  6961. * all of the user's input.
  6962. *
  6963. * There are three different options for how to handle this case:
  6964. *
  6965. * 1. decode() = short count, error = set
  6966. * 2. decode() = full count, error = set
  6967. * 3. decode() = full count, error NOT set, short count and error will
  6968. * be reported on next call to decode() (or end())
  6969. *
  6970. * (1) and (3) have the advantage that they preserve the invariant that an
  6971. * error occurs iff decode() returns a short count.
  6972. *
  6973. * (2) and (3) have the advantage of reflecting the fact that all of the
  6974. * bytes were in fact parsed (and possibly delivered to the unknown field
  6975. * handler, in the future when that is supported).
  6976. *
  6977. * (3) requires extra state in the decode (a place to store the "permanent
  6978. * error" that we should return for all subsequent attempts to decode).
  6979. * But we likely want this anyway.
  6980. *
  6981. * Right now we do (1), thanks to the fact that we checkpoint *after* this
  6982. * check. (3) may be a better choice long term; unclear at the moment. */
  6983. return upb_pbdecoder_suspend(d);
  6984. }
  6985. checkpoint(d);
  6986. }
  6987. }
  6988. static void goto_endmsg(upb_pbdecoder *d) {
  6989. upb_value v;
  6990. bool found = upb_inttable_lookup32(d->top->dispatch, DISPATCH_ENDMSG, &v);
  6991. UPB_ASSERT_VAR(found, found);
  6992. d->pc = d->top->base + upb_value_getuint64(v);
  6993. }
  6994. /* Parses a tag and jumps to the corresponding bytecode instruction for this
  6995. * field.
  6996. *
  6997. * If the tag is unknown (or the wire type doesn't match), parses the field as
  6998. * unknown. If the tag is a valid ENDGROUP tag, jumps to the bytecode
  6999. * instruction for the end of message. */
  7000. static int32_t dispatch(upb_pbdecoder *d) {
  7001. upb_inttable *dispatch = d->top->dispatch;
  7002. uint32_t tag;
  7003. uint8_t wire_type;
  7004. uint32_t fieldnum;
  7005. upb_value val;
  7006. int32_t ret;
  7007. /* Decode tag. */
  7008. CHECK_RETURN(decode_v32(d, &tag));
  7009. wire_type = tag & 0x7;
  7010. fieldnum = tag >> 3;
  7011. /* Lookup tag. Because of packed/non-packed compatibility, we have to
  7012. * check the wire type against two possibilities. */
  7013. if (fieldnum != DISPATCH_ENDMSG &&
  7014. upb_inttable_lookup32(dispatch, fieldnum, &val)) {
  7015. uint64_t v = upb_value_getuint64(val);
  7016. if (wire_type == (v & 0xff)) {
  7017. d->pc = d->top->base + (v >> 16);
  7018. return DECODE_OK;
  7019. } else if (wire_type == ((v >> 8) & 0xff)) {
  7020. bool found =
  7021. upb_inttable_lookup(dispatch, fieldnum + UPB_MAX_FIELDNUMBER, &val);
  7022. UPB_ASSERT_VAR(found, found);
  7023. d->pc = d->top->base + upb_value_getuint64(val);
  7024. return DECODE_OK;
  7025. }
  7026. }
  7027. /* Unknown field or ENDGROUP. */
  7028. ret = upb_pbdecoder_skipunknown(d, fieldnum, wire_type);
  7029. if (ret == DECODE_ENDGROUP) {
  7030. goto_endmsg(d);
  7031. return DECODE_OK;
  7032. } else if (ret == DECODE_OK) {
  7033. /* We just consumed some input, so we might now have consumed all the data
  7034. * in the delmited region. Since every opcode that can trigger dispatch is
  7035. * directly preceded by OP_CHECKDELIM, rewind to it now to re-check the
  7036. * delimited end. */
  7037. d->pc = d->last - 1;
  7038. assert(getop(*d->pc) == OP_CHECKDELIM);
  7039. return DECODE_OK;
  7040. }
  7041. return ret;
  7042. }
  7043. /* Callers know that the stack is more than one deep because the opcodes that
  7044. * call this only occur after PUSH operations. */
  7045. upb_pbdecoder_frame *outer_frame(upb_pbdecoder *d) {
  7046. assert(d->top != d->stack);
  7047. return d->top - 1;
  7048. }
  7049. /* The main decoding loop *****************************************************/
  7050. /* The main decoder VM function. Uses traditional bytecode dispatch loop with a
  7051. * switch() statement. */
  7052. size_t upb_pbdecoder_decode(void *closure, const void *hd, const char *buf,
  7053. size_t size, const upb_bufhandle *handle) {
  7054. upb_pbdecoder *d = closure;
  7055. const mgroup *group = hd;
  7056. int32_t result;
  7057. assert(buf);
  7058. result = upb_pbdecoder_resume(d, NULL, buf, size, handle);
  7059. if (result == DECODE_ENDGROUP) {
  7060. goto_endmsg(d);
  7061. }
  7062. CHECK_RETURN(result);
  7063. UPB_UNUSED(group);
  7064. #define VMCASE(op, code) \
  7065. case op: { code; if (consumes_input(op)) checkpoint(d); break; }
  7066. #define PRIMITIVE_OP(type, wt, name, convfunc, ctype) \
  7067. VMCASE(OP_PARSE_ ## type, { \
  7068. ctype val; \
  7069. CHECK_RETURN(decode_ ## wt(d, &val)); \
  7070. upb_sink_put ## name(&d->top->sink, arg, (convfunc)(val)); \
  7071. })
  7072. while(1) {
  7073. int32_t instruction;
  7074. opcode op;
  7075. uint32_t arg;
  7076. int32_t longofs;
  7077. d->last = d->pc;
  7078. instruction = *d->pc++;
  7079. op = getop(instruction);
  7080. arg = instruction >> 8;
  7081. longofs = arg;
  7082. assert(d->ptr != d->residual_end);
  7083. #ifdef UPB_DUMP_BYTECODE
  7084. fprintf(stderr, "s_ofs=%d buf_ofs=%d data_rem=%d buf_rem=%d delim_rem=%d "
  7085. "%x %s (%d)\n",
  7086. (int)offset(d),
  7087. (int)(d->ptr - d->buf),
  7088. (int)(d->data_end - d->ptr),
  7089. (int)(d->end - d->ptr),
  7090. (int)((d->top->end_ofs - d->bufstart_ofs) - (d->ptr - d->buf)),
  7091. (int)(d->pc - 1 - group->bytecode),
  7092. upb_pbdecoder_getopname(op),
  7093. arg);
  7094. #endif
  7095. switch (op) {
  7096. /* Technically, we are losing data if we see a 32-bit varint that is not
  7097. * properly sign-extended. We could detect this and error about the data
  7098. * loss, but proto2 does not do this, so we pass. */
  7099. PRIMITIVE_OP(INT32, varint, int32, int32_t, uint64_t)
  7100. PRIMITIVE_OP(INT64, varint, int64, int64_t, uint64_t)
  7101. PRIMITIVE_OP(UINT32, varint, uint32, uint32_t, uint64_t)
  7102. PRIMITIVE_OP(UINT64, varint, uint64, uint64_t, uint64_t)
  7103. PRIMITIVE_OP(FIXED32, fixed32, uint32, uint32_t, uint32_t)
  7104. PRIMITIVE_OP(FIXED64, fixed64, uint64, uint64_t, uint64_t)
  7105. PRIMITIVE_OP(SFIXED32, fixed32, int32, int32_t, uint32_t)
  7106. PRIMITIVE_OP(SFIXED64, fixed64, int64, int64_t, uint64_t)
  7107. PRIMITIVE_OP(BOOL, varint, bool, bool, uint64_t)
  7108. PRIMITIVE_OP(DOUBLE, fixed64, double, as_double, uint64_t)
  7109. PRIMITIVE_OP(FLOAT, fixed32, float, as_float, uint32_t)
  7110. PRIMITIVE_OP(SINT32, varint, int32, upb_zzdec_32, uint64_t)
  7111. PRIMITIVE_OP(SINT64, varint, int64, upb_zzdec_64, uint64_t)
  7112. VMCASE(OP_SETDISPATCH,
  7113. d->top->base = d->pc - 1;
  7114. memcpy(&d->top->dispatch, d->pc, sizeof(void*));
  7115. d->pc += sizeof(void*) / sizeof(uint32_t);
  7116. )
  7117. VMCASE(OP_STARTMSG,
  7118. CHECK_SUSPEND(upb_sink_startmsg(&d->top->sink));
  7119. )
  7120. VMCASE(OP_ENDMSG,
  7121. CHECK_SUSPEND(upb_sink_endmsg(&d->top->sink, d->status));
  7122. )
  7123. VMCASE(OP_STARTSEQ,
  7124. upb_pbdecoder_frame *outer = outer_frame(d);
  7125. CHECK_SUSPEND(upb_sink_startseq(&outer->sink, arg, &d->top->sink));
  7126. )
  7127. VMCASE(OP_ENDSEQ,
  7128. CHECK_SUSPEND(upb_sink_endseq(&d->top->sink, arg));
  7129. )
  7130. VMCASE(OP_STARTSUBMSG,
  7131. upb_pbdecoder_frame *outer = outer_frame(d);
  7132. CHECK_SUSPEND(upb_sink_startsubmsg(&outer->sink, arg, &d->top->sink));
  7133. )
  7134. VMCASE(OP_ENDSUBMSG,
  7135. CHECK_SUSPEND(upb_sink_endsubmsg(&d->top->sink, arg));
  7136. )
  7137. VMCASE(OP_STARTSTR,
  7138. uint32_t len = d->top->end_ofs - offset(d);
  7139. upb_pbdecoder_frame *outer = outer_frame(d);
  7140. CHECK_SUSPEND(upb_sink_startstr(&outer->sink, arg, len, &d->top->sink));
  7141. if (len == 0) {
  7142. d->pc++; /* Skip OP_STRING. */
  7143. }
  7144. )
  7145. VMCASE(OP_STRING,
  7146. uint32_t len = curbufleft(d);
  7147. size_t n = upb_sink_putstring(&d->top->sink, arg, d->ptr, len, handle);
  7148. if (n > len) {
  7149. if (n > d->top->end_ofs - offset(d)) {
  7150. seterr(d, "Tried to skip past end of string.");
  7151. return upb_pbdecoder_suspend(d);
  7152. } else {
  7153. int32_t ret = skip(d, n);
  7154. /* This shouldn't return DECODE_OK, because n > len. */
  7155. assert(ret >= 0);
  7156. return ret;
  7157. }
  7158. }
  7159. advance(d, n);
  7160. if (n < len || d->delim_end == NULL) {
  7161. /* We aren't finished with this string yet. */
  7162. d->pc--; /* Repeat OP_STRING. */
  7163. if (n > 0) checkpoint(d);
  7164. return upb_pbdecoder_suspend(d);
  7165. }
  7166. )
  7167. VMCASE(OP_ENDSTR,
  7168. CHECK_SUSPEND(upb_sink_endstr(&d->top->sink, arg));
  7169. )
  7170. VMCASE(OP_PUSHTAGDELIM,
  7171. CHECK_SUSPEND(pushtagdelim(d, arg));
  7172. )
  7173. VMCASE(OP_SETBIGGROUPNUM,
  7174. d->top->groupnum = *d->pc++;
  7175. )
  7176. VMCASE(OP_POP,
  7177. assert(d->top > d->stack);
  7178. decoder_pop(d);
  7179. )
  7180. VMCASE(OP_PUSHLENDELIM,
  7181. uint32_t len;
  7182. CHECK_RETURN(decode_v32(d, &len));
  7183. CHECK_SUSPEND(decoder_push(d, offset(d) + len));
  7184. set_delim_end(d);
  7185. )
  7186. VMCASE(OP_SETDELIM,
  7187. set_delim_end(d);
  7188. )
  7189. VMCASE(OP_CHECKDELIM,
  7190. /* We are guaranteed of this assert because we never allow ourselves to
  7191. * consume bytes beyond data_end, which covers delim_end when non-NULL.
  7192. */
  7193. assert(!(d->delim_end && d->ptr > d->delim_end));
  7194. if (d->ptr == d->delim_end)
  7195. d->pc += longofs;
  7196. )
  7197. VMCASE(OP_CALL,
  7198. d->callstack[d->call_len++] = d->pc;
  7199. d->pc += longofs;
  7200. )
  7201. VMCASE(OP_RET,
  7202. assert(d->call_len > 0);
  7203. d->pc = d->callstack[--d->call_len];
  7204. )
  7205. VMCASE(OP_BRANCH,
  7206. d->pc += longofs;
  7207. )
  7208. VMCASE(OP_TAG1,
  7209. uint8_t expected;
  7210. CHECK_SUSPEND(curbufleft(d) > 0);
  7211. expected = (arg >> 8) & 0xff;
  7212. if (*d->ptr == expected) {
  7213. advance(d, 1);
  7214. } else {
  7215. int8_t shortofs;
  7216. badtag:
  7217. shortofs = arg;
  7218. if (shortofs == LABEL_DISPATCH) {
  7219. CHECK_RETURN(dispatch(d));
  7220. } else {
  7221. d->pc += shortofs;
  7222. break; /* Avoid checkpoint(). */
  7223. }
  7224. }
  7225. )
  7226. VMCASE(OP_TAG2,
  7227. uint16_t expected;
  7228. CHECK_SUSPEND(curbufleft(d) > 0);
  7229. expected = (arg >> 8) & 0xffff;
  7230. if (curbufleft(d) >= 2) {
  7231. uint16_t actual;
  7232. memcpy(&actual, d->ptr, 2);
  7233. if (expected == actual) {
  7234. advance(d, 2);
  7235. } else {
  7236. goto badtag;
  7237. }
  7238. } else {
  7239. int32_t result = upb_pbdecoder_checktag_slow(d, expected);
  7240. if (result == DECODE_MISMATCH) goto badtag;
  7241. if (result >= 0) return result;
  7242. }
  7243. )
  7244. VMCASE(OP_TAGN, {
  7245. uint64_t expected;
  7246. int32_t result;
  7247. memcpy(&expected, d->pc, 8);
  7248. d->pc += 2;
  7249. result = upb_pbdecoder_checktag_slow(d, expected);
  7250. if (result == DECODE_MISMATCH) goto badtag;
  7251. if (result >= 0) return result;
  7252. })
  7253. VMCASE(OP_DISPATCH, {
  7254. CHECK_RETURN(dispatch(d));
  7255. })
  7256. VMCASE(OP_HALT, {
  7257. return size;
  7258. })
  7259. }
  7260. }
  7261. }
  7262. void *upb_pbdecoder_startbc(void *closure, const void *pc, size_t size_hint) {
  7263. upb_pbdecoder *d = closure;
  7264. UPB_UNUSED(size_hint);
  7265. d->top->end_ofs = UINT64_MAX;
  7266. d->bufstart_ofs = 0;
  7267. d->call_len = 1;
  7268. d->callstack[0] = &halt;
  7269. d->pc = pc;
  7270. return d;
  7271. }
  7272. void *upb_pbdecoder_startjit(void *closure, const void *hd, size_t size_hint) {
  7273. upb_pbdecoder *d = closure;
  7274. UPB_UNUSED(hd);
  7275. UPB_UNUSED(size_hint);
  7276. d->top->end_ofs = UINT64_MAX;
  7277. d->bufstart_ofs = 0;
  7278. d->call_len = 0;
  7279. return d;
  7280. }
  7281. bool upb_pbdecoder_end(void *closure, const void *handler_data) {
  7282. upb_pbdecoder *d = closure;
  7283. const upb_pbdecodermethod *method = handler_data;
  7284. uint64_t end;
  7285. char dummy;
  7286. #ifdef UPB_USE_JIT_X64
  7287. const mgroup *group = (const mgroup*)method->group;
  7288. #endif
  7289. if (d->residual_end > d->residual) {
  7290. seterr(d, "Unexpected EOF");
  7291. return false;
  7292. }
  7293. if (d->top->end_ofs != UINT64_MAX) {
  7294. seterr(d, "Unexpected EOF inside delimited string");
  7295. return false;
  7296. }
  7297. /* Message ends here. */
  7298. end = offset(d);
  7299. d->top->end_ofs = end;
  7300. #ifdef UPB_USE_JIT_X64
  7301. if (group->jit_code) {
  7302. if (d->top != d->stack)
  7303. d->stack->end_ofs = 0;
  7304. group->jit_code(closure, method->code_base.ptr, &dummy, 0, NULL);
  7305. } else
  7306. #endif
  7307. {
  7308. const uint32_t *p = d->pc;
  7309. d->stack->end_ofs = end;
  7310. /* Check the previous bytecode, but guard against beginning. */
  7311. if (p != method->code_base.ptr) p--;
  7312. if (getop(*p) == OP_CHECKDELIM) {
  7313. /* Rewind from OP_TAG* to OP_CHECKDELIM. */
  7314. assert(getop(*d->pc) == OP_TAG1 ||
  7315. getop(*d->pc) == OP_TAG2 ||
  7316. getop(*d->pc) == OP_TAGN ||
  7317. getop(*d->pc) == OP_DISPATCH);
  7318. d->pc = p;
  7319. }
  7320. upb_pbdecoder_decode(closure, handler_data, &dummy, 0, NULL);
  7321. }
  7322. if (d->call_len != 0) {
  7323. seterr(d, "Unexpected EOF");
  7324. return false;
  7325. }
  7326. return true;
  7327. }
  7328. void upb_pbdecoder_reset(upb_pbdecoder *d) {
  7329. d->top = d->stack;
  7330. d->top->groupnum = 0;
  7331. d->ptr = d->residual;
  7332. d->buf = d->residual;
  7333. d->end = d->residual;
  7334. d->residual_end = d->residual;
  7335. }
  7336. static size_t stacksize(upb_pbdecoder *d, size_t entries) {
  7337. UPB_UNUSED(d);
  7338. return entries * sizeof(upb_pbdecoder_frame);
  7339. }
  7340. static size_t callstacksize(upb_pbdecoder *d, size_t entries) {
  7341. UPB_UNUSED(d);
  7342. #ifdef UPB_USE_JIT_X64
  7343. if (d->method_->is_native_) {
  7344. /* Each native stack frame needs two pointers, plus we need a few frames for
  7345. * the enter/exit trampolines. */
  7346. size_t ret = entries * sizeof(void*) * 2;
  7347. ret += sizeof(void*) * 10;
  7348. return ret;
  7349. }
  7350. #endif
  7351. return entries * sizeof(uint32_t*);
  7352. }
  7353. upb_pbdecoder *upb_pbdecoder_create(upb_env *e, const upb_pbdecodermethod *m,
  7354. upb_sink *sink) {
  7355. const size_t default_max_nesting = 64;
  7356. #ifndef NDEBUG
  7357. size_t size_before = upb_env_bytesallocated(e);
  7358. #endif
  7359. upb_pbdecoder *d = upb_env_malloc(e, sizeof(upb_pbdecoder));
  7360. if (!d) return NULL;
  7361. d->method_ = m;
  7362. d->callstack = upb_env_malloc(e, callstacksize(d, default_max_nesting));
  7363. d->stack = upb_env_malloc(e, stacksize(d, default_max_nesting));
  7364. if (!d->stack || !d->callstack) {
  7365. return NULL;
  7366. }
  7367. d->env = e;
  7368. d->limit = d->stack + default_max_nesting - 1;
  7369. d->stack_size = default_max_nesting;
  7370. upb_pbdecoder_reset(d);
  7371. upb_bytessink_reset(&d->input_, &m->input_handler_, d);
  7372. assert(sink);
  7373. if (d->method_->dest_handlers_) {
  7374. if (sink->handlers != d->method_->dest_handlers_)
  7375. return NULL;
  7376. }
  7377. upb_sink_reset(&d->top->sink, sink->handlers, sink->closure);
  7378. /* If this fails, increase the value in decoder.h. */
  7379. assert(upb_env_bytesallocated(e) - size_before <= UPB_PB_DECODER_SIZE);
  7380. return d;
  7381. }
  7382. uint64_t upb_pbdecoder_bytesparsed(const upb_pbdecoder *d) {
  7383. return offset(d);
  7384. }
  7385. const upb_pbdecodermethod *upb_pbdecoder_method(const upb_pbdecoder *d) {
  7386. return d->method_;
  7387. }
  7388. upb_bytessink *upb_pbdecoder_input(upb_pbdecoder *d) {
  7389. return &d->input_;
  7390. }
  7391. size_t upb_pbdecoder_maxnesting(const upb_pbdecoder *d) {
  7392. return d->stack_size;
  7393. }
  7394. bool upb_pbdecoder_setmaxnesting(upb_pbdecoder *d, size_t max) {
  7395. assert(d->top >= d->stack);
  7396. if (max < (size_t)(d->top - d->stack)) {
  7397. /* Can't set a limit smaller than what we are currently at. */
  7398. return false;
  7399. }
  7400. if (max > d->stack_size) {
  7401. /* Need to reallocate stack and callstack to accommodate. */
  7402. size_t old_size = stacksize(d, d->stack_size);
  7403. size_t new_size = stacksize(d, max);
  7404. void *p = upb_env_realloc(d->env, d->stack, old_size, new_size);
  7405. if (!p) {
  7406. return false;
  7407. }
  7408. d->stack = p;
  7409. old_size = callstacksize(d, d->stack_size);
  7410. new_size = callstacksize(d, max);
  7411. p = upb_env_realloc(d->env, d->callstack, old_size, new_size);
  7412. if (!p) {
  7413. return false;
  7414. }
  7415. d->callstack = p;
  7416. d->stack_size = max;
  7417. }
  7418. d->limit = d->stack + max - 1;
  7419. return true;
  7420. }
  7421. /*
  7422. * upb - a minimalist implementation of protocol buffers.
  7423. *
  7424. * Copyright (c) 2014 Google Inc. See LICENSE for details.
  7425. * Author: Josh Haberman <jhaberman@gmail.com>
  7426. *
  7427. * Since we are implementing pure handlers (ie. without any out-of-band access
  7428. * to pre-computed lengths), we have to buffer all submessages before we can
  7429. * emit even their first byte.
  7430. *
  7431. * Not knowing the size of submessages also means we can't write a perfect
  7432. * zero-copy implementation, even with buffering. Lengths are stored as
  7433. * varints, which means that we don't know how many bytes to reserve for the
  7434. * length until we know what the length is.
  7435. *
  7436. * This leaves us with three main choices:
  7437. *
  7438. * 1. buffer all submessage data in a temporary buffer, then copy it exactly
  7439. * once into the output buffer.
  7440. *
  7441. * 2. attempt to buffer data directly into the output buffer, estimating how
  7442. * many bytes each length will take. When our guesses are wrong, use
  7443. * memmove() to grow or shrink the allotted space.
  7444. *
  7445. * 3. buffer directly into the output buffer, allocating a max length
  7446. * ahead-of-time for each submessage length. If we overallocated, we waste
  7447. * space, but no memcpy() or memmove() is required. This approach requires
  7448. * defining a maximum size for submessages and rejecting submessages that
  7449. * exceed that size.
  7450. *
  7451. * (2) and (3) have the potential to have better performance, but they are more
  7452. * complicated and subtle to implement:
  7453. *
  7454. * (3) requires making an arbitrary choice of the maximum message size; it
  7455. * wastes space when submessages are shorter than this and fails
  7456. * completely when they are longer. This makes it more finicky and
  7457. * requires configuration based on the input. It also makes it impossible
  7458. * to perfectly match the output of reference encoders that always use the
  7459. * optimal amount of space for each length.
  7460. *
  7461. * (2) requires guessing the the size upfront, and if multiple lengths are
  7462. * guessed wrong the minimum required number of memmove() operations may
  7463. * be complicated to compute correctly. Implemented properly, it may have
  7464. * a useful amortized or average cost, but more investigation is required
  7465. * to determine this and what the optimal algorithm is to achieve it.
  7466. *
  7467. * (1) makes you always pay for exactly one copy, but its implementation is
  7468. * the simplest and its performance is predictable.
  7469. *
  7470. * So for now, we implement (1) only. If we wish to optimize later, we should
  7471. * be able to do it without affecting users.
  7472. *
  7473. * The strategy is to buffer the segments of data that do *not* depend on
  7474. * unknown lengths in one buffer, and keep a separate buffer of segment pointers
  7475. * and lengths. When the top-level submessage ends, we can go beginning to end,
  7476. * alternating the writing of lengths with memcpy() of the rest of the data.
  7477. * At the top level though, no buffering is required.
  7478. */
  7479. #include <stdlib.h>
  7480. /* The output buffer is divided into segments; a segment is a string of data
  7481. * that is "ready to go" -- it does not need any varint lengths inserted into
  7482. * the middle. The seams between segments are where varints will be inserted
  7483. * once they are known.
  7484. *
  7485. * We also use the concept of a "run", which is a range of encoded bytes that
  7486. * occur at a single submessage level. Every segment contains one or more runs.
  7487. *
  7488. * A segment can span messages. Consider:
  7489. *
  7490. * .--Submessage lengths---------.
  7491. * | | |
  7492. * | V V
  7493. * V | |--------------- | |-----------------
  7494. * Submessages: | |-----------------------------------------------
  7495. * Top-level msg: ------------------------------------------------------------
  7496. *
  7497. * Segments: ----- ------------------- -----------------
  7498. * Runs: *---- *--------------*--- *----------------
  7499. * (* marks the start)
  7500. *
  7501. * Note that the top-level menssage is not in any segment because it does not
  7502. * have any length preceding it.
  7503. *
  7504. * A segment is only interrupted when another length needs to be inserted. So
  7505. * observe how the second segment spans both the inner submessage and part of
  7506. * the next enclosing message. */
  7507. typedef struct {
  7508. uint32_t msglen; /* The length to varint-encode before this segment. */
  7509. uint32_t seglen; /* Length of the segment. */
  7510. } upb_pb_encoder_segment;
  7511. struct upb_pb_encoder {
  7512. upb_env *env;
  7513. /* Our input and output. */
  7514. upb_sink input_;
  7515. upb_bytessink *output_;
  7516. /* The "subclosure" -- used as the inner closure as part of the bytessink
  7517. * protocol. */
  7518. void *subc;
  7519. /* The output buffer and limit, and our current write position. "buf"
  7520. * initially points to "initbuf", but is dynamically allocated if we need to
  7521. * grow beyond the initial size. */
  7522. char *buf, *ptr, *limit;
  7523. /* The beginning of the current run, or undefined if we are at the top
  7524. * level. */
  7525. char *runbegin;
  7526. /* The list of segments we are accumulating. */
  7527. upb_pb_encoder_segment *segbuf, *segptr, *seglimit;
  7528. /* The stack of enclosing submessages. Each entry in the stack points to the
  7529. * segment where this submessage's length is being accumulated. */
  7530. int *stack, *top, *stacklimit;
  7531. /* Depth of startmsg/endmsg calls. */
  7532. int depth;
  7533. };
  7534. /* low-level buffering ********************************************************/
  7535. /* Low-level functions for interacting with the output buffer. */
  7536. /* TODO(haberman): handle pushback */
  7537. static void putbuf(upb_pb_encoder *e, const char *buf, size_t len) {
  7538. size_t n = upb_bytessink_putbuf(e->output_, e->subc, buf, len, NULL);
  7539. UPB_ASSERT_VAR(n, n == len);
  7540. }
  7541. static upb_pb_encoder_segment *top(upb_pb_encoder *e) {
  7542. return &e->segbuf[*e->top];
  7543. }
  7544. /* Call to ensure that at least "bytes" bytes are available for writing at
  7545. * e->ptr. Returns false if the bytes could not be allocated. */
  7546. static bool reserve(upb_pb_encoder *e, size_t bytes) {
  7547. if ((size_t)(e->limit - e->ptr) < bytes) {
  7548. /* Grow buffer. */
  7549. char *new_buf;
  7550. size_t needed = bytes + (e->ptr - e->buf);
  7551. size_t old_size = e->limit - e->buf;
  7552. size_t new_size = old_size;
  7553. while (new_size < needed) {
  7554. new_size *= 2;
  7555. }
  7556. new_buf = upb_env_realloc(e->env, e->buf, old_size, new_size);
  7557. if (new_buf == NULL) {
  7558. return false;
  7559. }
  7560. e->ptr = new_buf + (e->ptr - e->buf);
  7561. e->runbegin = new_buf + (e->runbegin - e->buf);
  7562. e->limit = new_buf + new_size;
  7563. e->buf = new_buf;
  7564. }
  7565. return true;
  7566. }
  7567. /* Call when "bytes" bytes have been writte at e->ptr. The caller *must* have
  7568. * previously called reserve() with at least this many bytes. */
  7569. static void encoder_advance(upb_pb_encoder *e, size_t bytes) {
  7570. assert((size_t)(e->limit - e->ptr) >= bytes);
  7571. e->ptr += bytes;
  7572. }
  7573. /* Call when all of the bytes for a handler have been written. Flushes the
  7574. * bytes if possible and necessary, returning false if this failed. */
  7575. static bool commit(upb_pb_encoder *e) {
  7576. if (!e->top) {
  7577. /* We aren't inside a delimited region. Flush our accumulated bytes to
  7578. * the output.
  7579. *
  7580. * TODO(haberman): in the future we may want to delay flushing for
  7581. * efficiency reasons. */
  7582. putbuf(e, e->buf, e->ptr - e->buf);
  7583. e->ptr = e->buf;
  7584. }
  7585. return true;
  7586. }
  7587. /* Writes the given bytes to the buffer, handling reserve/advance. */
  7588. static bool encode_bytes(upb_pb_encoder *e, const void *data, size_t len) {
  7589. if (!reserve(e, len)) {
  7590. return false;
  7591. }
  7592. memcpy(e->ptr, data, len);
  7593. encoder_advance(e, len);
  7594. return true;
  7595. }
  7596. /* Finish the current run by adding the run totals to the segment and message
  7597. * length. */
  7598. static void accumulate(upb_pb_encoder *e) {
  7599. size_t run_len;
  7600. assert(e->ptr >= e->runbegin);
  7601. run_len = e->ptr - e->runbegin;
  7602. e->segptr->seglen += run_len;
  7603. top(e)->msglen += run_len;
  7604. e->runbegin = e->ptr;
  7605. }
  7606. /* Call to indicate the start of delimited region for which the full length is
  7607. * not yet known. All data will be buffered until the length is known.
  7608. * Delimited regions may be nested; their lengths will all be tracked properly. */
  7609. static bool start_delim(upb_pb_encoder *e) {
  7610. if (e->top) {
  7611. /* We are already buffering, advance to the next segment and push it on the
  7612. * stack. */
  7613. accumulate(e);
  7614. if (++e->top == e->stacklimit) {
  7615. /* TODO(haberman): grow stack? */
  7616. return false;
  7617. }
  7618. if (++e->segptr == e->seglimit) {
  7619. /* Grow segment buffer. */
  7620. size_t old_size =
  7621. (e->seglimit - e->segbuf) * sizeof(upb_pb_encoder_segment);
  7622. size_t new_size = old_size * 2;
  7623. upb_pb_encoder_segment *new_buf =
  7624. upb_env_realloc(e->env, e->segbuf, old_size, new_size);
  7625. if (new_buf == NULL) {
  7626. return false;
  7627. }
  7628. e->segptr = new_buf + (e->segptr - e->segbuf);
  7629. e->seglimit = new_buf + (new_size / sizeof(upb_pb_encoder_segment));
  7630. e->segbuf = new_buf;
  7631. }
  7632. } else {
  7633. /* We were previously at the top level, start buffering. */
  7634. e->segptr = e->segbuf;
  7635. e->top = e->stack;
  7636. e->runbegin = e->ptr;
  7637. }
  7638. *e->top = e->segptr - e->segbuf;
  7639. e->segptr->seglen = 0;
  7640. e->segptr->msglen = 0;
  7641. return true;
  7642. }
  7643. /* Call to indicate the end of a delimited region. We now know the length of
  7644. * the delimited region. If we are not nested inside any other delimited
  7645. * regions, we can now emit all of the buffered data we accumulated. */
  7646. static bool end_delim(upb_pb_encoder *e) {
  7647. size_t msglen;
  7648. accumulate(e);
  7649. msglen = top(e)->msglen;
  7650. if (e->top == e->stack) {
  7651. /* All lengths are now available, emit all buffered data. */
  7652. char buf[UPB_PB_VARINT_MAX_LEN];
  7653. upb_pb_encoder_segment *s;
  7654. const char *ptr = e->buf;
  7655. for (s = e->segbuf; s <= e->segptr; s++) {
  7656. size_t lenbytes = upb_vencode64(s->msglen, buf);
  7657. putbuf(e, buf, lenbytes);
  7658. putbuf(e, ptr, s->seglen);
  7659. ptr += s->seglen;
  7660. }
  7661. e->ptr = e->buf;
  7662. e->top = NULL;
  7663. } else {
  7664. /* Need to keep buffering; propagate length info into enclosing
  7665. * submessages. */
  7666. --e->top;
  7667. top(e)->msglen += msglen + upb_varint_size(msglen);
  7668. }
  7669. return true;
  7670. }
  7671. /* tag_t **********************************************************************/
  7672. /* A precomputed (pre-encoded) tag and length. */
  7673. typedef struct {
  7674. uint8_t bytes;
  7675. char tag[7];
  7676. } tag_t;
  7677. /* Allocates a new tag for this field, and sets it in these handlerattr. */
  7678. static void new_tag(upb_handlers *h, const upb_fielddef *f, upb_wiretype_t wt,
  7679. upb_handlerattr *attr) {
  7680. uint32_t n = upb_fielddef_number(f);
  7681. tag_t *tag = malloc(sizeof(tag_t));
  7682. tag->bytes = upb_vencode64((n << 3) | wt, tag->tag);
  7683. upb_handlerattr_init(attr);
  7684. upb_handlerattr_sethandlerdata(attr, tag);
  7685. upb_handlers_addcleanup(h, tag, free);
  7686. }
  7687. static bool encode_tag(upb_pb_encoder *e, const tag_t *tag) {
  7688. return encode_bytes(e, tag->tag, tag->bytes);
  7689. }
  7690. /* encoding of wire types *****************************************************/
  7691. static bool encode_fixed64(upb_pb_encoder *e, uint64_t val) {
  7692. /* TODO(haberman): byte-swap for big endian. */
  7693. return encode_bytes(e, &val, sizeof(uint64_t));
  7694. }
  7695. static bool encode_fixed32(upb_pb_encoder *e, uint32_t val) {
  7696. /* TODO(haberman): byte-swap for big endian. */
  7697. return encode_bytes(e, &val, sizeof(uint32_t));
  7698. }
  7699. static bool encode_varint(upb_pb_encoder *e, uint64_t val) {
  7700. if (!reserve(e, UPB_PB_VARINT_MAX_LEN)) {
  7701. return false;
  7702. }
  7703. encoder_advance(e, upb_vencode64(val, e->ptr));
  7704. return true;
  7705. }
  7706. static uint64_t dbl2uint64(double d) {
  7707. uint64_t ret;
  7708. memcpy(&ret, &d, sizeof(uint64_t));
  7709. return ret;
  7710. }
  7711. static uint32_t flt2uint32(float d) {
  7712. uint32_t ret;
  7713. memcpy(&ret, &d, sizeof(uint32_t));
  7714. return ret;
  7715. }
  7716. /* encoding of proto types ****************************************************/
  7717. static bool startmsg(void *c, const void *hd) {
  7718. upb_pb_encoder *e = c;
  7719. UPB_UNUSED(hd);
  7720. if (e->depth++ == 0) {
  7721. upb_bytessink_start(e->output_, 0, &e->subc);
  7722. }
  7723. return true;
  7724. }
  7725. static bool endmsg(void *c, const void *hd, upb_status *status) {
  7726. upb_pb_encoder *e = c;
  7727. UPB_UNUSED(hd);
  7728. UPB_UNUSED(status);
  7729. if (--e->depth == 0) {
  7730. upb_bytessink_end(e->output_);
  7731. }
  7732. return true;
  7733. }
  7734. static void *encode_startdelimfield(void *c, const void *hd) {
  7735. bool ok = encode_tag(c, hd) && commit(c) && start_delim(c);
  7736. return ok ? c : UPB_BREAK;
  7737. }
  7738. static bool encode_enddelimfield(void *c, const void *hd) {
  7739. UPB_UNUSED(hd);
  7740. return end_delim(c);
  7741. }
  7742. static void *encode_startgroup(void *c, const void *hd) {
  7743. return (encode_tag(c, hd) && commit(c)) ? c : UPB_BREAK;
  7744. }
  7745. static bool encode_endgroup(void *c, const void *hd) {
  7746. return encode_tag(c, hd) && commit(c);
  7747. }
  7748. static void *encode_startstr(void *c, const void *hd, size_t size_hint) {
  7749. UPB_UNUSED(size_hint);
  7750. return encode_startdelimfield(c, hd);
  7751. }
  7752. static size_t encode_strbuf(void *c, const void *hd, const char *buf,
  7753. size_t len, const upb_bufhandle *h) {
  7754. UPB_UNUSED(hd);
  7755. UPB_UNUSED(h);
  7756. return encode_bytes(c, buf, len) ? len : 0;
  7757. }
  7758. #define T(type, ctype, convert, encode) \
  7759. static bool encode_scalar_##type(void *e, const void *hd, ctype val) { \
  7760. return encode_tag(e, hd) && encode(e, (convert)(val)) && commit(e); \
  7761. } \
  7762. static bool encode_packed_##type(void *e, const void *hd, ctype val) { \
  7763. UPB_UNUSED(hd); \
  7764. return encode(e, (convert)(val)); \
  7765. }
  7766. T(double, double, dbl2uint64, encode_fixed64)
  7767. T(float, float, flt2uint32, encode_fixed32)
  7768. T(int64, int64_t, uint64_t, encode_varint)
  7769. T(int32, int32_t, uint32_t, encode_varint)
  7770. T(fixed64, uint64_t, uint64_t, encode_fixed64)
  7771. T(fixed32, uint32_t, uint32_t, encode_fixed32)
  7772. T(bool, bool, bool, encode_varint)
  7773. T(uint32, uint32_t, uint32_t, encode_varint)
  7774. T(uint64, uint64_t, uint64_t, encode_varint)
  7775. T(enum, int32_t, uint32_t, encode_varint)
  7776. T(sfixed32, int32_t, uint32_t, encode_fixed32)
  7777. T(sfixed64, int64_t, uint64_t, encode_fixed64)
  7778. T(sint32, int32_t, upb_zzenc_32, encode_varint)
  7779. T(sint64, int64_t, upb_zzenc_64, encode_varint)
  7780. #undef T
  7781. /* code to build the handlers *************************************************/
  7782. static void newhandlers_callback(const void *closure, upb_handlers *h) {
  7783. const upb_msgdef *m;
  7784. upb_msg_field_iter i;
  7785. UPB_UNUSED(closure);
  7786. upb_handlers_setstartmsg(h, startmsg, NULL);
  7787. upb_handlers_setendmsg(h, endmsg, NULL);
  7788. m = upb_handlers_msgdef(h);
  7789. for(upb_msg_field_begin(&i, m);
  7790. !upb_msg_field_done(&i);
  7791. upb_msg_field_next(&i)) {
  7792. const upb_fielddef *f = upb_msg_iter_field(&i);
  7793. bool packed = upb_fielddef_isseq(f) && upb_fielddef_isprimitive(f) &&
  7794. upb_fielddef_packed(f);
  7795. upb_handlerattr attr;
  7796. upb_wiretype_t wt =
  7797. packed ? UPB_WIRE_TYPE_DELIMITED
  7798. : upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  7799. /* Pre-encode the tag for this field. */
  7800. new_tag(h, f, wt, &attr);
  7801. if (packed) {
  7802. upb_handlers_setstartseq(h, f, encode_startdelimfield, &attr);
  7803. upb_handlers_setendseq(h, f, encode_enddelimfield, &attr);
  7804. }
  7805. #define T(upper, lower, upbtype) \
  7806. case UPB_DESCRIPTOR_TYPE_##upper: \
  7807. if (packed) { \
  7808. upb_handlers_set##upbtype(h, f, encode_packed_##lower, &attr); \
  7809. } else { \
  7810. upb_handlers_set##upbtype(h, f, encode_scalar_##lower, &attr); \
  7811. } \
  7812. break;
  7813. switch (upb_fielddef_descriptortype(f)) {
  7814. T(DOUBLE, double, double);
  7815. T(FLOAT, float, float);
  7816. T(INT64, int64, int64);
  7817. T(INT32, int32, int32);
  7818. T(FIXED64, fixed64, uint64);
  7819. T(FIXED32, fixed32, uint32);
  7820. T(BOOL, bool, bool);
  7821. T(UINT32, uint32, uint32);
  7822. T(UINT64, uint64, uint64);
  7823. T(ENUM, enum, int32);
  7824. T(SFIXED32, sfixed32, int32);
  7825. T(SFIXED64, sfixed64, int64);
  7826. T(SINT32, sint32, int32);
  7827. T(SINT64, sint64, int64);
  7828. case UPB_DESCRIPTOR_TYPE_STRING:
  7829. case UPB_DESCRIPTOR_TYPE_BYTES:
  7830. upb_handlers_setstartstr(h, f, encode_startstr, &attr);
  7831. upb_handlers_setendstr(h, f, encode_enddelimfield, &attr);
  7832. upb_handlers_setstring(h, f, encode_strbuf, &attr);
  7833. break;
  7834. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  7835. upb_handlers_setstartsubmsg(h, f, encode_startdelimfield, &attr);
  7836. upb_handlers_setendsubmsg(h, f, encode_enddelimfield, &attr);
  7837. break;
  7838. case UPB_DESCRIPTOR_TYPE_GROUP: {
  7839. /* Endgroup takes a different tag (wire_type = END_GROUP). */
  7840. upb_handlerattr attr2;
  7841. new_tag(h, f, UPB_WIRE_TYPE_END_GROUP, &attr2);
  7842. upb_handlers_setstartsubmsg(h, f, encode_startgroup, &attr);
  7843. upb_handlers_setendsubmsg(h, f, encode_endgroup, &attr2);
  7844. upb_handlerattr_uninit(&attr2);
  7845. break;
  7846. }
  7847. }
  7848. #undef T
  7849. upb_handlerattr_uninit(&attr);
  7850. }
  7851. }
  7852. void upb_pb_encoder_reset(upb_pb_encoder *e) {
  7853. e->segptr = NULL;
  7854. e->top = NULL;
  7855. e->depth = 0;
  7856. }
  7857. /* public API *****************************************************************/
  7858. const upb_handlers *upb_pb_encoder_newhandlers(const upb_msgdef *m,
  7859. const void *owner) {
  7860. return upb_handlers_newfrozen(m, owner, newhandlers_callback, NULL);
  7861. }
  7862. upb_pb_encoder *upb_pb_encoder_create(upb_env *env, const upb_handlers *h,
  7863. upb_bytessink *output) {
  7864. const size_t initial_bufsize = 256;
  7865. const size_t initial_segbufsize = 16;
  7866. /* TODO(haberman): make this configurable. */
  7867. const size_t stack_size = 64;
  7868. #ifndef NDEBUG
  7869. const size_t size_before = upb_env_bytesallocated(env);
  7870. #endif
  7871. upb_pb_encoder *e = upb_env_malloc(env, sizeof(upb_pb_encoder));
  7872. if (!e) return NULL;
  7873. e->buf = upb_env_malloc(env, initial_bufsize);
  7874. e->segbuf = upb_env_malloc(env, initial_segbufsize * sizeof(*e->segbuf));
  7875. e->stack = upb_env_malloc(env, stack_size * sizeof(*e->stack));
  7876. if (!e->buf || !e->segbuf || !e->stack) {
  7877. return NULL;
  7878. }
  7879. e->limit = e->buf + initial_bufsize;
  7880. e->seglimit = e->segbuf + initial_segbufsize;
  7881. e->stacklimit = e->stack + stack_size;
  7882. upb_pb_encoder_reset(e);
  7883. upb_sink_reset(&e->input_, h, e);
  7884. e->env = env;
  7885. e->output_ = output;
  7886. e->subc = output->closure;
  7887. e->ptr = e->buf;
  7888. /* If this fails, increase the value in encoder.h. */
  7889. assert(upb_env_bytesallocated(env) - size_before <= UPB_PB_ENCODER_SIZE);
  7890. return e;
  7891. }
  7892. upb_sink *upb_pb_encoder_input(upb_pb_encoder *e) { return &e->input_; }
  7893. /*
  7894. * upb - a minimalist implementation of protocol buffers.
  7895. *
  7896. * Copyright (c) 2010-2012 Google Inc. See LICENSE for details.
  7897. * Author: Josh Haberman <jhaberman@gmail.com>
  7898. */
  7899. #include <stdio.h>
  7900. #include <stdlib.h>
  7901. #include <string.h>
  7902. upb_def **upb_load_defs_from_descriptor(const char *str, size_t len, int *n,
  7903. void *owner, upb_status *status) {
  7904. /* Create handlers. */
  7905. const upb_pbdecodermethod *decoder_m;
  7906. const upb_handlers *reader_h = upb_descreader_newhandlers(&reader_h);
  7907. upb_env env;
  7908. upb_pbdecodermethodopts opts;
  7909. upb_pbdecoder *decoder;
  7910. upb_descreader *reader;
  7911. bool ok;
  7912. upb_def **ret = NULL;
  7913. upb_def **defs;
  7914. upb_pbdecodermethodopts_init(&opts, reader_h);
  7915. decoder_m = upb_pbdecodermethod_new(&opts, &decoder_m);
  7916. upb_env_init(&env);
  7917. upb_env_reporterrorsto(&env, status);
  7918. reader = upb_descreader_create(&env, reader_h);
  7919. decoder = upb_pbdecoder_create(&env, decoder_m, upb_descreader_input(reader));
  7920. /* Push input data. */
  7921. ok = upb_bufsrc_putbuf(str, len, upb_pbdecoder_input(decoder));
  7922. if (!ok) goto cleanup;
  7923. defs = upb_descreader_getdefs(reader, owner, n);
  7924. ret = malloc(sizeof(upb_def*) * (*n));
  7925. memcpy(ret, defs, sizeof(upb_def*) * (*n));
  7926. cleanup:
  7927. upb_env_uninit(&env);
  7928. upb_handlers_unref(reader_h, &reader_h);
  7929. upb_pbdecodermethod_unref(decoder_m, &decoder_m);
  7930. return ret;
  7931. }
  7932. bool upb_load_descriptor_into_symtab(upb_symtab *s, const char *str, size_t len,
  7933. upb_status *status) {
  7934. int n;
  7935. bool success;
  7936. upb_def **defs = upb_load_defs_from_descriptor(str, len, &n, &defs, status);
  7937. if (!defs) return false;
  7938. success = upb_symtab_add(s, defs, n, &defs, status);
  7939. free(defs);
  7940. return success;
  7941. }
  7942. char *upb_readfile(const char *filename, size_t *len) {
  7943. long size;
  7944. char *buf;
  7945. FILE *f = fopen(filename, "rb");
  7946. if(!f) return NULL;
  7947. if(fseek(f, 0, SEEK_END) != 0) goto error;
  7948. size = ftell(f);
  7949. if(size < 0) goto error;
  7950. if(fseek(f, 0, SEEK_SET) != 0) goto error;
  7951. buf = malloc(size + 1);
  7952. if(size && fread(buf, size, 1, f) != 1) goto error;
  7953. fclose(f);
  7954. if (len) *len = size;
  7955. return buf;
  7956. error:
  7957. fclose(f);
  7958. return NULL;
  7959. }
  7960. bool upb_load_descriptor_file_into_symtab(upb_symtab *symtab, const char *fname,
  7961. upb_status *status) {
  7962. size_t len;
  7963. bool success;
  7964. char *data = upb_readfile(fname, &len);
  7965. if (!data) {
  7966. if (status) upb_status_seterrf(status, "Couldn't read file: %s", fname);
  7967. return false;
  7968. }
  7969. success = upb_load_descriptor_into_symtab(symtab, data, len, status);
  7970. free(data);
  7971. return success;
  7972. }
  7973. /*
  7974. * upb - a minimalist implementation of protocol buffers.
  7975. *
  7976. * Copyright (c) 2009 Google Inc. See LICENSE for details.
  7977. * Author: Josh Haberman <jhaberman@gmail.com>
  7978. *
  7979. * OPT: This is not optimized at all. It uses printf() which parses the format
  7980. * string every time, and it allocates memory for every put.
  7981. */
  7982. #include <ctype.h>
  7983. #include <float.h>
  7984. #include <inttypes.h>
  7985. #include <stdarg.h>
  7986. #include <stdio.h>
  7987. #include <stdlib.h>
  7988. #include <string.h>
  7989. struct upb_textprinter {
  7990. upb_sink input_;
  7991. upb_bytessink *output_;
  7992. int indent_depth_;
  7993. bool single_line_;
  7994. void *subc;
  7995. };
  7996. #define CHECK(x) if ((x) < 0) goto err;
  7997. static const char *shortname(const char *longname) {
  7998. const char *last = strrchr(longname, '.');
  7999. return last ? last + 1 : longname;
  8000. }
  8001. static int indent(upb_textprinter *p) {
  8002. int i;
  8003. if (!p->single_line_)
  8004. for (i = 0; i < p->indent_depth_; i++)
  8005. upb_bytessink_putbuf(p->output_, p->subc, " ", 2, NULL);
  8006. return 0;
  8007. }
  8008. static int endfield(upb_textprinter *p) {
  8009. const char ch = (p->single_line_ ? ' ' : '\n');
  8010. upb_bytessink_putbuf(p->output_, p->subc, &ch, 1, NULL);
  8011. return 0;
  8012. }
  8013. static int putescaped(upb_textprinter *p, const char *buf, size_t len,
  8014. bool preserve_utf8) {
  8015. /* Based on CEscapeInternal() from Google's protobuf release. */
  8016. char dstbuf[4096], *dst = dstbuf, *dstend = dstbuf + sizeof(dstbuf);
  8017. const char *end = buf + len;
  8018. /* I think hex is prettier and more useful, but proto2 uses octal; should
  8019. * investigate whether it can parse hex also. */
  8020. const bool use_hex = false;
  8021. bool last_hex_escape = false; /* true if last output char was \xNN */
  8022. for (; buf < end; buf++) {
  8023. bool is_hex_escape;
  8024. if (dstend - dst < 4) {
  8025. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  8026. dst = dstbuf;
  8027. }
  8028. is_hex_escape = false;
  8029. switch (*buf) {
  8030. case '\n': *(dst++) = '\\'; *(dst++) = 'n'; break;
  8031. case '\r': *(dst++) = '\\'; *(dst++) = 'r'; break;
  8032. case '\t': *(dst++) = '\\'; *(dst++) = 't'; break;
  8033. case '\"': *(dst++) = '\\'; *(dst++) = '\"'; break;
  8034. case '\'': *(dst++) = '\\'; *(dst++) = '\''; break;
  8035. case '\\': *(dst++) = '\\'; *(dst++) = '\\'; break;
  8036. default:
  8037. /* Note that if we emit \xNN and the buf character after that is a hex
  8038. * digit then that digit must be escaped too to prevent it being
  8039. * interpreted as part of the character code by C. */
  8040. if ((!preserve_utf8 || (uint8_t)*buf < 0x80) &&
  8041. (!isprint(*buf) || (last_hex_escape && isxdigit(*buf)))) {
  8042. sprintf(dst, (use_hex ? "\\x%02x" : "\\%03o"), (uint8_t)*buf);
  8043. is_hex_escape = use_hex;
  8044. dst += 4;
  8045. } else {
  8046. *(dst++) = *buf; break;
  8047. }
  8048. }
  8049. last_hex_escape = is_hex_escape;
  8050. }
  8051. /* Flush remaining data. */
  8052. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  8053. return 0;
  8054. }
  8055. bool putf(upb_textprinter *p, const char *fmt, ...) {
  8056. va_list args;
  8057. va_list args_copy;
  8058. char *str;
  8059. int written;
  8060. int len;
  8061. bool ok;
  8062. va_start(args, fmt);
  8063. /* Run once to get the length of the string. */
  8064. _upb_va_copy(args_copy, args);
  8065. len = _upb_vsnprintf(NULL, 0, fmt, args_copy);
  8066. va_end(args_copy);
  8067. /* + 1 for NULL terminator (vsprintf() requires it even if we don't). */
  8068. str = malloc(len + 1);
  8069. if (!str) return false;
  8070. written = vsprintf(str, fmt, args);
  8071. va_end(args);
  8072. UPB_ASSERT_VAR(written, written == len);
  8073. ok = upb_bytessink_putbuf(p->output_, p->subc, str, len, NULL);
  8074. free(str);
  8075. return ok;
  8076. }
  8077. /* handlers *******************************************************************/
  8078. static bool textprinter_startmsg(void *c, const void *hd) {
  8079. upb_textprinter *p = c;
  8080. UPB_UNUSED(hd);
  8081. if (p->indent_depth_ == 0) {
  8082. upb_bytessink_start(p->output_, 0, &p->subc);
  8083. }
  8084. return true;
  8085. }
  8086. static bool textprinter_endmsg(void *c, const void *hd, upb_status *s) {
  8087. upb_textprinter *p = c;
  8088. UPB_UNUSED(hd);
  8089. UPB_UNUSED(s);
  8090. if (p->indent_depth_ == 0) {
  8091. upb_bytessink_end(p->output_);
  8092. }
  8093. return true;
  8094. }
  8095. #define TYPE(name, ctype, fmt) \
  8096. static bool textprinter_put ## name(void *closure, const void *handler_data, \
  8097. ctype val) { \
  8098. upb_textprinter *p = closure; \
  8099. const upb_fielddef *f = handler_data; \
  8100. CHECK(indent(p)); \
  8101. putf(p, "%s: " fmt, upb_fielddef_name(f), val); \
  8102. CHECK(endfield(p)); \
  8103. return true; \
  8104. err: \
  8105. return false; \
  8106. }
  8107. static bool textprinter_putbool(void *closure, const void *handler_data,
  8108. bool val) {
  8109. upb_textprinter *p = closure;
  8110. const upb_fielddef *f = handler_data;
  8111. CHECK(indent(p));
  8112. putf(p, "%s: %s", upb_fielddef_name(f), val ? "true" : "false");
  8113. CHECK(endfield(p));
  8114. return true;
  8115. err:
  8116. return false;
  8117. }
  8118. #define STRINGIFY_HELPER(x) #x
  8119. #define STRINGIFY_MACROVAL(x) STRINGIFY_HELPER(x)
  8120. TYPE(int32, int32_t, "%" PRId32)
  8121. TYPE(int64, int64_t, "%" PRId64)
  8122. TYPE(uint32, uint32_t, "%" PRIu32)
  8123. TYPE(uint64, uint64_t, "%" PRIu64)
  8124. TYPE(float, float, "%." STRINGIFY_MACROVAL(FLT_DIG) "g")
  8125. TYPE(double, double, "%." STRINGIFY_MACROVAL(DBL_DIG) "g")
  8126. #undef TYPE
  8127. /* Output a symbolic value from the enum if found, else just print as int32. */
  8128. static bool textprinter_putenum(void *closure, const void *handler_data,
  8129. int32_t val) {
  8130. upb_textprinter *p = closure;
  8131. const upb_fielddef *f = handler_data;
  8132. const upb_enumdef *enum_def = upb_downcast_enumdef(upb_fielddef_subdef(f));
  8133. const char *label = upb_enumdef_iton(enum_def, val);
  8134. if (label) {
  8135. indent(p);
  8136. putf(p, "%s: %s", upb_fielddef_name(f), label);
  8137. endfield(p);
  8138. } else {
  8139. if (!textprinter_putint32(closure, handler_data, val))
  8140. return false;
  8141. }
  8142. return true;
  8143. }
  8144. static void *textprinter_startstr(void *closure, const void *handler_data,
  8145. size_t size_hint) {
  8146. upb_textprinter *p = closure;
  8147. const upb_fielddef *f = handler_data;
  8148. UPB_UNUSED(size_hint);
  8149. indent(p);
  8150. putf(p, "%s: \"", upb_fielddef_name(f));
  8151. return p;
  8152. }
  8153. static bool textprinter_endstr(void *closure, const void *handler_data) {
  8154. upb_textprinter *p = closure;
  8155. UPB_UNUSED(handler_data);
  8156. putf(p, "\"");
  8157. endfield(p);
  8158. return true;
  8159. }
  8160. static size_t textprinter_putstr(void *closure, const void *hd, const char *buf,
  8161. size_t len, const upb_bufhandle *handle) {
  8162. upb_textprinter *p = closure;
  8163. const upb_fielddef *f = hd;
  8164. UPB_UNUSED(handle);
  8165. CHECK(putescaped(p, buf, len, upb_fielddef_type(f) == UPB_TYPE_STRING));
  8166. return len;
  8167. err:
  8168. return 0;
  8169. }
  8170. static void *textprinter_startsubmsg(void *closure, const void *handler_data) {
  8171. upb_textprinter *p = closure;
  8172. const char *name = handler_data;
  8173. CHECK(indent(p));
  8174. putf(p, "%s {%c", name, p->single_line_ ? ' ' : '\n');
  8175. p->indent_depth_++;
  8176. return p;
  8177. err:
  8178. return UPB_BREAK;
  8179. }
  8180. static bool textprinter_endsubmsg(void *closure, const void *handler_data) {
  8181. upb_textprinter *p = closure;
  8182. UPB_UNUSED(handler_data);
  8183. p->indent_depth_--;
  8184. CHECK(indent(p));
  8185. upb_bytessink_putbuf(p->output_, p->subc, "}", 1, NULL);
  8186. CHECK(endfield(p));
  8187. return true;
  8188. err:
  8189. return false;
  8190. }
  8191. static void onmreg(const void *c, upb_handlers *h) {
  8192. const upb_msgdef *m = upb_handlers_msgdef(h);
  8193. upb_msg_field_iter i;
  8194. UPB_UNUSED(c);
  8195. upb_handlers_setstartmsg(h, textprinter_startmsg, NULL);
  8196. upb_handlers_setendmsg(h, textprinter_endmsg, NULL);
  8197. for(upb_msg_field_begin(&i, m);
  8198. !upb_msg_field_done(&i);
  8199. upb_msg_field_next(&i)) {
  8200. upb_fielddef *f = upb_msg_iter_field(&i);
  8201. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  8202. upb_handlerattr_sethandlerdata(&attr, f);
  8203. switch (upb_fielddef_type(f)) {
  8204. case UPB_TYPE_INT32:
  8205. upb_handlers_setint32(h, f, textprinter_putint32, &attr);
  8206. break;
  8207. case UPB_TYPE_INT64:
  8208. upb_handlers_setint64(h, f, textprinter_putint64, &attr);
  8209. break;
  8210. case UPB_TYPE_UINT32:
  8211. upb_handlers_setuint32(h, f, textprinter_putuint32, &attr);
  8212. break;
  8213. case UPB_TYPE_UINT64:
  8214. upb_handlers_setuint64(h, f, textprinter_putuint64, &attr);
  8215. break;
  8216. case UPB_TYPE_FLOAT:
  8217. upb_handlers_setfloat(h, f, textprinter_putfloat, &attr);
  8218. break;
  8219. case UPB_TYPE_DOUBLE:
  8220. upb_handlers_setdouble(h, f, textprinter_putdouble, &attr);
  8221. break;
  8222. case UPB_TYPE_BOOL:
  8223. upb_handlers_setbool(h, f, textprinter_putbool, &attr);
  8224. break;
  8225. case UPB_TYPE_STRING:
  8226. case UPB_TYPE_BYTES:
  8227. upb_handlers_setstartstr(h, f, textprinter_startstr, &attr);
  8228. upb_handlers_setstring(h, f, textprinter_putstr, &attr);
  8229. upb_handlers_setendstr(h, f, textprinter_endstr, &attr);
  8230. break;
  8231. case UPB_TYPE_MESSAGE: {
  8232. const char *name =
  8233. upb_fielddef_istagdelim(f)
  8234. ? shortname(upb_msgdef_fullname(upb_fielddef_msgsubdef(f)))
  8235. : upb_fielddef_name(f);
  8236. upb_handlerattr_sethandlerdata(&attr, name);
  8237. upb_handlers_setstartsubmsg(h, f, textprinter_startsubmsg, &attr);
  8238. upb_handlers_setendsubmsg(h, f, textprinter_endsubmsg, &attr);
  8239. break;
  8240. }
  8241. case UPB_TYPE_ENUM:
  8242. upb_handlers_setint32(h, f, textprinter_putenum, &attr);
  8243. break;
  8244. }
  8245. }
  8246. }
  8247. static void textprinter_reset(upb_textprinter *p, bool single_line) {
  8248. p->single_line_ = single_line;
  8249. p->indent_depth_ = 0;
  8250. }
  8251. /* Public API *****************************************************************/
  8252. upb_textprinter *upb_textprinter_create(upb_env *env, const upb_handlers *h,
  8253. upb_bytessink *output) {
  8254. upb_textprinter *p = upb_env_malloc(env, sizeof(upb_textprinter));
  8255. if (!p) return NULL;
  8256. p->output_ = output;
  8257. upb_sink_reset(&p->input_, h, p);
  8258. textprinter_reset(p, false);
  8259. return p;
  8260. }
  8261. const upb_handlers *upb_textprinter_newhandlers(const upb_msgdef *m,
  8262. const void *owner) {
  8263. return upb_handlers_newfrozen(m, owner, &onmreg, NULL);
  8264. }
  8265. upb_sink *upb_textprinter_input(upb_textprinter *p) { return &p->input_; }
  8266. void upb_textprinter_setsingleline(upb_textprinter *p, bool single_line) {
  8267. p->single_line_ = single_line;
  8268. }
  8269. /*
  8270. * upb - a minimalist implementation of protocol buffers.
  8271. *
  8272. * Copyright (c) 2011 Google Inc. See LICENSE for details.
  8273. * Author: Josh Haberman <jhaberman@gmail.com>
  8274. */
  8275. /* Index is descriptor type. */
  8276. const uint8_t upb_pb_native_wire_types[] = {
  8277. UPB_WIRE_TYPE_END_GROUP, /* ENDGROUP */
  8278. UPB_WIRE_TYPE_64BIT, /* DOUBLE */
  8279. UPB_WIRE_TYPE_32BIT, /* FLOAT */
  8280. UPB_WIRE_TYPE_VARINT, /* INT64 */
  8281. UPB_WIRE_TYPE_VARINT, /* UINT64 */
  8282. UPB_WIRE_TYPE_VARINT, /* INT32 */
  8283. UPB_WIRE_TYPE_64BIT, /* FIXED64 */
  8284. UPB_WIRE_TYPE_32BIT, /* FIXED32 */
  8285. UPB_WIRE_TYPE_VARINT, /* BOOL */
  8286. UPB_WIRE_TYPE_DELIMITED, /* STRING */
  8287. UPB_WIRE_TYPE_START_GROUP, /* GROUP */
  8288. UPB_WIRE_TYPE_DELIMITED, /* MESSAGE */
  8289. UPB_WIRE_TYPE_DELIMITED, /* BYTES */
  8290. UPB_WIRE_TYPE_VARINT, /* UINT32 */
  8291. UPB_WIRE_TYPE_VARINT, /* ENUM */
  8292. UPB_WIRE_TYPE_32BIT, /* SFIXED32 */
  8293. UPB_WIRE_TYPE_64BIT, /* SFIXED64 */
  8294. UPB_WIRE_TYPE_VARINT, /* SINT32 */
  8295. UPB_WIRE_TYPE_VARINT, /* SINT64 */
  8296. };
  8297. /* A basic branch-based decoder, uses 32-bit values to get good performance
  8298. * on 32-bit architectures (but performs well on 64-bits also).
  8299. * This scheme comes from the original Google Protobuf implementation
  8300. * (proto2). */
  8301. upb_decoderet upb_vdecode_max8_branch32(upb_decoderet r) {
  8302. upb_decoderet err = {NULL, 0};
  8303. const char *p = r.p;
  8304. uint32_t low = (uint32_t)r.val;
  8305. uint32_t high = 0;
  8306. uint32_t b;
  8307. b = *(p++); low |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  8308. b = *(p++); low |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  8309. b = *(p++); low |= (b & 0x7fU) << 28;
  8310. high = (b & 0x7fU) >> 4; if (!(b & 0x80)) goto done;
  8311. b = *(p++); high |= (b & 0x7fU) << 3; if (!(b & 0x80)) goto done;
  8312. b = *(p++); high |= (b & 0x7fU) << 10; if (!(b & 0x80)) goto done;
  8313. b = *(p++); high |= (b & 0x7fU) << 17; if (!(b & 0x80)) goto done;
  8314. b = *(p++); high |= (b & 0x7fU) << 24; if (!(b & 0x80)) goto done;
  8315. b = *(p++); high |= (b & 0x7fU) << 31; if (!(b & 0x80)) goto done;
  8316. return err;
  8317. done:
  8318. r.val = ((uint64_t)high << 32) | low;
  8319. r.p = p;
  8320. return r;
  8321. }
  8322. /* Like the previous, but uses 64-bit values. */
  8323. upb_decoderet upb_vdecode_max8_branch64(upb_decoderet r) {
  8324. const char *p = r.p;
  8325. uint64_t val = r.val;
  8326. uint64_t b;
  8327. upb_decoderet err = {NULL, 0};
  8328. b = *(p++); val |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  8329. b = *(p++); val |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  8330. b = *(p++); val |= (b & 0x7fU) << 28; if (!(b & 0x80)) goto done;
  8331. b = *(p++); val |= (b & 0x7fU) << 35; if (!(b & 0x80)) goto done;
  8332. b = *(p++); val |= (b & 0x7fU) << 42; if (!(b & 0x80)) goto done;
  8333. b = *(p++); val |= (b & 0x7fU) << 49; if (!(b & 0x80)) goto done;
  8334. b = *(p++); val |= (b & 0x7fU) << 56; if (!(b & 0x80)) goto done;
  8335. b = *(p++); val |= (b & 0x7fU) << 63; if (!(b & 0x80)) goto done;
  8336. return err;
  8337. done:
  8338. r.val = val;
  8339. r.p = p;
  8340. return r;
  8341. }
  8342. /* Given an encoded varint v, returns an integer with a single bit set that
  8343. * indicates the end of the varint. Subtracting one from this value will
  8344. * yield a mask that leaves only bits that are part of the varint. Returns
  8345. * 0 if the varint is unterminated. */
  8346. static uint64_t upb_get_vstopbit(uint64_t v) {
  8347. uint64_t cbits = v | 0x7f7f7f7f7f7f7f7fULL;
  8348. return ~cbits & (cbits+1);
  8349. }
  8350. /* A branchless decoder. Credit to Pascal Massimino for the bit-twiddling. */
  8351. upb_decoderet upb_vdecode_max8_massimino(upb_decoderet r) {
  8352. uint64_t b;
  8353. uint64_t stop_bit;
  8354. upb_decoderet my_r;
  8355. memcpy(&b, r.p, sizeof(b));
  8356. stop_bit = upb_get_vstopbit(b);
  8357. b = (b & 0x7f7f7f7f7f7f7f7fULL) & (stop_bit - 1);
  8358. b += b & 0x007f007f007f007fULL;
  8359. b += 3 * (b & 0x0000ffff0000ffffULL);
  8360. b += 15 * (b & 0x00000000ffffffffULL);
  8361. if (stop_bit == 0) {
  8362. /* Error: unterminated varint. */
  8363. upb_decoderet err_r = {(void*)0, 0};
  8364. return err_r;
  8365. }
  8366. my_r = upb_decoderet_make(r.p + ((__builtin_ctzll(stop_bit) + 1) / 8),
  8367. r.val | (b << 7));
  8368. return my_r;
  8369. }
  8370. /* A branchless decoder. Credit to Daniel Wright for the bit-twiddling. */
  8371. upb_decoderet upb_vdecode_max8_wright(upb_decoderet r) {
  8372. uint64_t b;
  8373. uint64_t stop_bit;
  8374. upb_decoderet my_r;
  8375. memcpy(&b, r.p, sizeof(b));
  8376. stop_bit = upb_get_vstopbit(b);
  8377. b &= (stop_bit - 1);
  8378. b = ((b & 0x7f007f007f007f00ULL) >> 1) | (b & 0x007f007f007f007fULL);
  8379. b = ((b & 0xffff0000ffff0000ULL) >> 2) | (b & 0x0000ffff0000ffffULL);
  8380. b = ((b & 0xffffffff00000000ULL) >> 4) | (b & 0x00000000ffffffffULL);
  8381. if (stop_bit == 0) {
  8382. /* Error: unterminated varint. */
  8383. upb_decoderet err_r = {(void*)0, 0};
  8384. return err_r;
  8385. }
  8386. my_r = upb_decoderet_make(r.p + ((__builtin_ctzll(stop_bit) + 1) / 8),
  8387. r.val | (b << 14));
  8388. return my_r;
  8389. }
  8390. #line 1 "upb/json/parser.rl"
  8391. /*
  8392. * upb - a minimalist implementation of protocol buffers.
  8393. *
  8394. * Copyright (c) 2014 Google Inc. See LICENSE for details.
  8395. * Author: Josh Haberman <jhaberman@gmail.com>
  8396. *
  8397. * A parser that uses the Ragel State Machine Compiler to generate
  8398. * the finite automata.
  8399. *
  8400. * Ragel only natively handles regular languages, but we can manually
  8401. * program it a bit to handle context-free languages like JSON, by using
  8402. * the "fcall" and "fret" constructs.
  8403. *
  8404. * This parser can handle the basics, but needs several things to be fleshed
  8405. * out:
  8406. *
  8407. * - handling of unicode escape sequences (including high surrogate pairs).
  8408. * - properly check and report errors for unknown fields, stack overflow,
  8409. * improper array nesting (or lack of nesting).
  8410. * - handling of base64 sequences with padding characters.
  8411. * - handling of push-back (non-success returns from sink functions).
  8412. * - handling of keys/escape-sequences/etc that span input buffers.
  8413. */
  8414. #include <stdio.h>
  8415. #include <stdint.h>
  8416. #include <assert.h>
  8417. #include <string.h>
  8418. #include <stdlib.h>
  8419. #include <errno.h>
  8420. #define UPB_JSON_MAX_DEPTH 64
  8421. typedef struct {
  8422. upb_sink sink;
  8423. /* The current message in which we're parsing, and the field whose value we're
  8424. * expecting next. */
  8425. const upb_msgdef *m;
  8426. const upb_fielddef *f;
  8427. /* We are in a repeated-field context, ready to emit mapentries as
  8428. * submessages. This flag alters the start-of-object (open-brace) behavior to
  8429. * begin a sequence of mapentry messages rather than a single submessage. */
  8430. bool is_map;
  8431. /* We are in a map-entry message context. This flag is set when parsing the
  8432. * value field of a single map entry and indicates to all value-field parsers
  8433. * (subobjects, strings, numbers, and bools) that the map-entry submessage
  8434. * should end as soon as the value is parsed. */
  8435. bool is_mapentry;
  8436. /* If |is_map| or |is_mapentry| is true, |mapfield| refers to the parent
  8437. * message's map field that we're currently parsing. This differs from |f|
  8438. * because |f| is the field in the *current* message (i.e., the map-entry
  8439. * message itself), not the parent's field that leads to this map. */
  8440. const upb_fielddef *mapfield;
  8441. } upb_jsonparser_frame;
  8442. struct upb_json_parser {
  8443. upb_env *env;
  8444. upb_byteshandler input_handler_;
  8445. upb_bytessink input_;
  8446. /* Stack to track the JSON scopes we are in. */
  8447. upb_jsonparser_frame stack[UPB_JSON_MAX_DEPTH];
  8448. upb_jsonparser_frame *top;
  8449. upb_jsonparser_frame *limit;
  8450. upb_status *status;
  8451. /* Ragel's internal parsing stack for the parsing state machine. */
  8452. int current_state;
  8453. int parser_stack[UPB_JSON_MAX_DEPTH];
  8454. int parser_top;
  8455. /* The handle for the current buffer. */
  8456. const upb_bufhandle *handle;
  8457. /* Accumulate buffer. See details in parser.rl. */
  8458. const char *accumulated;
  8459. size_t accumulated_len;
  8460. char *accumulate_buf;
  8461. size_t accumulate_buf_size;
  8462. /* Multi-part text data. See details in parser.rl. */
  8463. int multipart_state;
  8464. upb_selector_t string_selector;
  8465. /* Input capture. See details in parser.rl. */
  8466. const char *capture;
  8467. /* Intermediate result of parsing a unicode escape sequence. */
  8468. uint32_t digit;
  8469. };
  8470. #define PARSER_CHECK_RETURN(x) if (!(x)) return false
  8471. /* Used to signal that a capture has been suspended. */
  8472. static char suspend_capture;
  8473. static upb_selector_t getsel_for_handlertype(upb_json_parser *p,
  8474. upb_handlertype_t type) {
  8475. upb_selector_t sel;
  8476. bool ok = upb_handlers_getselector(p->top->f, type, &sel);
  8477. UPB_ASSERT_VAR(ok, ok);
  8478. return sel;
  8479. }
  8480. static upb_selector_t parser_getsel(upb_json_parser *p) {
  8481. return getsel_for_handlertype(
  8482. p, upb_handlers_getprimitivehandlertype(p->top->f));
  8483. }
  8484. static bool check_stack(upb_json_parser *p) {
  8485. if ((p->top + 1) == p->limit) {
  8486. upb_status_seterrmsg(p->status, "Nesting too deep");
  8487. return false;
  8488. }
  8489. return true;
  8490. }
  8491. /* There are GCC/Clang built-ins for overflow checking which we could start
  8492. * using if there was any performance benefit to it. */
  8493. static bool checked_add(size_t a, size_t b, size_t *c) {
  8494. if (SIZE_MAX - a < b) return false;
  8495. *c = a + b;
  8496. return true;
  8497. }
  8498. static size_t saturating_multiply(size_t a, size_t b) {
  8499. /* size_t is unsigned, so this is defined behavior even on overflow. */
  8500. size_t ret = a * b;
  8501. if (b != 0 && ret / b != a) {
  8502. ret = SIZE_MAX;
  8503. }
  8504. return ret;
  8505. }
  8506. /* Base64 decoding ************************************************************/
  8507. /* TODO(haberman): make this streaming. */
  8508. static const signed char b64table[] = {
  8509. -1, -1, -1, -1, -1, -1, -1, -1,
  8510. -1, -1, -1, -1, -1, -1, -1, -1,
  8511. -1, -1, -1, -1, -1, -1, -1, -1,
  8512. -1, -1, -1, -1, -1, -1, -1, -1,
  8513. -1, -1, -1, -1, -1, -1, -1, -1,
  8514. -1, -1, -1, 62/*+*/, -1, -1, -1, 63/*/ */,
  8515. 52/*0*/, 53/*1*/, 54/*2*/, 55/*3*/, 56/*4*/, 57/*5*/, 58/*6*/, 59/*7*/,
  8516. 60/*8*/, 61/*9*/, -1, -1, -1, -1, -1, -1,
  8517. -1, 0/*A*/, 1/*B*/, 2/*C*/, 3/*D*/, 4/*E*/, 5/*F*/, 6/*G*/,
  8518. 07/*H*/, 8/*I*/, 9/*J*/, 10/*K*/, 11/*L*/, 12/*M*/, 13/*N*/, 14/*O*/,
  8519. 15/*P*/, 16/*Q*/, 17/*R*/, 18/*S*/, 19/*T*/, 20/*U*/, 21/*V*/, 22/*W*/,
  8520. 23/*X*/, 24/*Y*/, 25/*Z*/, -1, -1, -1, -1, -1,
  8521. -1, 26/*a*/, 27/*b*/, 28/*c*/, 29/*d*/, 30/*e*/, 31/*f*/, 32/*g*/,
  8522. 33/*h*/, 34/*i*/, 35/*j*/, 36/*k*/, 37/*l*/, 38/*m*/, 39/*n*/, 40/*o*/,
  8523. 41/*p*/, 42/*q*/, 43/*r*/, 44/*s*/, 45/*t*/, 46/*u*/, 47/*v*/, 48/*w*/,
  8524. 49/*x*/, 50/*y*/, 51/*z*/, -1, -1, -1, -1, -1,
  8525. -1, -1, -1, -1, -1, -1, -1, -1,
  8526. -1, -1, -1, -1, -1, -1, -1, -1,
  8527. -1, -1, -1, -1, -1, -1, -1, -1,
  8528. -1, -1, -1, -1, -1, -1, -1, -1,
  8529. -1, -1, -1, -1, -1, -1, -1, -1,
  8530. -1, -1, -1, -1, -1, -1, -1, -1,
  8531. -1, -1, -1, -1, -1, -1, -1, -1,
  8532. -1, -1, -1, -1, -1, -1, -1, -1,
  8533. -1, -1, -1, -1, -1, -1, -1, -1,
  8534. -1, -1, -1, -1, -1, -1, -1, -1,
  8535. -1, -1, -1, -1, -1, -1, -1, -1,
  8536. -1, -1, -1, -1, -1, -1, -1, -1,
  8537. -1, -1, -1, -1, -1, -1, -1, -1,
  8538. -1, -1, -1, -1, -1, -1, -1, -1,
  8539. -1, -1, -1, -1, -1, -1, -1, -1,
  8540. -1, -1, -1, -1, -1, -1, -1, -1
  8541. };
  8542. /* Returns the table value sign-extended to 32 bits. Knowing that the upper
  8543. * bits will be 1 for unrecognized characters makes it easier to check for
  8544. * this error condition later (see below). */
  8545. int32_t b64lookup(unsigned char ch) { return b64table[ch]; }
  8546. /* Returns true if the given character is not a valid base64 character or
  8547. * padding. */
  8548. bool nonbase64(unsigned char ch) { return b64lookup(ch) == -1 && ch != '='; }
  8549. static bool base64_push(upb_json_parser *p, upb_selector_t sel, const char *ptr,
  8550. size_t len) {
  8551. const char *limit = ptr + len;
  8552. for (; ptr < limit; ptr += 4) {
  8553. uint32_t val;
  8554. char output[3];
  8555. if (limit - ptr < 4) {
  8556. upb_status_seterrf(p->status,
  8557. "Base64 input for bytes field not a multiple of 4: %s",
  8558. upb_fielddef_name(p->top->f));
  8559. return false;
  8560. }
  8561. val = b64lookup(ptr[0]) << 18 |
  8562. b64lookup(ptr[1]) << 12 |
  8563. b64lookup(ptr[2]) << 6 |
  8564. b64lookup(ptr[3]);
  8565. /* Test the upper bit; returns true if any of the characters returned -1. */
  8566. if (val & 0x80000000) {
  8567. goto otherchar;
  8568. }
  8569. output[0] = val >> 16;
  8570. output[1] = (val >> 8) & 0xff;
  8571. output[2] = val & 0xff;
  8572. upb_sink_putstring(&p->top->sink, sel, output, 3, NULL);
  8573. }
  8574. return true;
  8575. otherchar:
  8576. if (nonbase64(ptr[0]) || nonbase64(ptr[1]) || nonbase64(ptr[2]) ||
  8577. nonbase64(ptr[3]) ) {
  8578. upb_status_seterrf(p->status,
  8579. "Non-base64 characters in bytes field: %s",
  8580. upb_fielddef_name(p->top->f));
  8581. return false;
  8582. } if (ptr[2] == '=') {
  8583. uint32_t val;
  8584. char output;
  8585. /* Last group contains only two input bytes, one output byte. */
  8586. if (ptr[0] == '=' || ptr[1] == '=' || ptr[3] != '=') {
  8587. goto badpadding;
  8588. }
  8589. val = b64lookup(ptr[0]) << 18 |
  8590. b64lookup(ptr[1]) << 12;
  8591. assert(!(val & 0x80000000));
  8592. output = val >> 16;
  8593. upb_sink_putstring(&p->top->sink, sel, &output, 1, NULL);
  8594. return true;
  8595. } else {
  8596. uint32_t val;
  8597. char output[2];
  8598. /* Last group contains only three input bytes, two output bytes. */
  8599. if (ptr[0] == '=' || ptr[1] == '=' || ptr[2] == '=') {
  8600. goto badpadding;
  8601. }
  8602. val = b64lookup(ptr[0]) << 18 |
  8603. b64lookup(ptr[1]) << 12 |
  8604. b64lookup(ptr[2]) << 6;
  8605. output[0] = val >> 16;
  8606. output[1] = (val >> 8) & 0xff;
  8607. upb_sink_putstring(&p->top->sink, sel, output, 2, NULL);
  8608. return true;
  8609. }
  8610. badpadding:
  8611. upb_status_seterrf(p->status,
  8612. "Incorrect base64 padding for field: %s (%.*s)",
  8613. upb_fielddef_name(p->top->f),
  8614. 4, ptr);
  8615. return false;
  8616. }
  8617. /* Accumulate buffer **********************************************************/
  8618. /* Functionality for accumulating a buffer.
  8619. *
  8620. * Some parts of the parser need an entire value as a contiguous string. For
  8621. * example, to look up a member name in a hash table, or to turn a string into
  8622. * a number, the relevant library routines need the input string to be in
  8623. * contiguous memory, even if the value spanned two or more buffers in the
  8624. * input. These routines handle that.
  8625. *
  8626. * In the common case we can just point to the input buffer to get this
  8627. * contiguous string and avoid any actual copy. So we optimistically begin
  8628. * this way. But there are a few cases where we must instead copy into a
  8629. * separate buffer:
  8630. *
  8631. * 1. The string was not contiguous in the input (it spanned buffers).
  8632. *
  8633. * 2. The string included escape sequences that need to be interpreted to get
  8634. * the true value in a contiguous buffer. */
  8635. static void assert_accumulate_empty(upb_json_parser *p) {
  8636. UPB_UNUSED(p);
  8637. assert(p->accumulated == NULL);
  8638. assert(p->accumulated_len == 0);
  8639. }
  8640. static void accumulate_clear(upb_json_parser *p) {
  8641. p->accumulated = NULL;
  8642. p->accumulated_len = 0;
  8643. }
  8644. /* Used internally by accumulate_append(). */
  8645. static bool accumulate_realloc(upb_json_parser *p, size_t need) {
  8646. void *mem;
  8647. size_t old_size = p->accumulate_buf_size;
  8648. size_t new_size = UPB_MAX(old_size, 128);
  8649. while (new_size < need) {
  8650. new_size = saturating_multiply(new_size, 2);
  8651. }
  8652. mem = upb_env_realloc(p->env, p->accumulate_buf, old_size, new_size);
  8653. if (!mem) {
  8654. upb_status_seterrmsg(p->status, "Out of memory allocating buffer.");
  8655. return false;
  8656. }
  8657. p->accumulate_buf = mem;
  8658. p->accumulate_buf_size = new_size;
  8659. return true;
  8660. }
  8661. /* Logically appends the given data to the append buffer.
  8662. * If "can_alias" is true, we will try to avoid actually copying, but the buffer
  8663. * must be valid until the next accumulate_append() call (if any). */
  8664. static bool accumulate_append(upb_json_parser *p, const char *buf, size_t len,
  8665. bool can_alias) {
  8666. size_t need;
  8667. if (!p->accumulated && can_alias) {
  8668. p->accumulated = buf;
  8669. p->accumulated_len = len;
  8670. return true;
  8671. }
  8672. if (!checked_add(p->accumulated_len, len, &need)) {
  8673. upb_status_seterrmsg(p->status, "Integer overflow.");
  8674. return false;
  8675. }
  8676. if (need > p->accumulate_buf_size && !accumulate_realloc(p, need)) {
  8677. return false;
  8678. }
  8679. if (p->accumulated != p->accumulate_buf) {
  8680. memcpy(p->accumulate_buf, p->accumulated, p->accumulated_len);
  8681. p->accumulated = p->accumulate_buf;
  8682. }
  8683. memcpy(p->accumulate_buf + p->accumulated_len, buf, len);
  8684. p->accumulated_len += len;
  8685. return true;
  8686. }
  8687. /* Returns a pointer to the data accumulated since the last accumulate_clear()
  8688. * call, and writes the length to *len. This with point either to the input
  8689. * buffer or a temporary accumulate buffer. */
  8690. static const char *accumulate_getptr(upb_json_parser *p, size_t *len) {
  8691. assert(p->accumulated);
  8692. *len = p->accumulated_len;
  8693. return p->accumulated;
  8694. }
  8695. /* Mult-part text data ********************************************************/
  8696. /* When we have text data in the input, it can often come in multiple segments.
  8697. * For example, there may be some raw string data followed by an escape
  8698. * sequence. The two segments are processed with different logic. Also buffer
  8699. * seams in the input can cause multiple segments.
  8700. *
  8701. * As we see segments, there are two main cases for how we want to process them:
  8702. *
  8703. * 1. we want to push the captured input directly to string handlers.
  8704. *
  8705. * 2. we need to accumulate all the parts into a contiguous buffer for further
  8706. * processing (field name lookup, string->number conversion, etc). */
  8707. /* This is the set of states for p->multipart_state. */
  8708. enum {
  8709. /* We are not currently processing multipart data. */
  8710. MULTIPART_INACTIVE = 0,
  8711. /* We are processing multipart data by accumulating it into a contiguous
  8712. * buffer. */
  8713. MULTIPART_ACCUMULATE = 1,
  8714. /* We are processing multipart data by pushing each part directly to the
  8715. * current string handlers. */
  8716. MULTIPART_PUSHEAGERLY = 2
  8717. };
  8718. /* Start a multi-part text value where we accumulate the data for processing at
  8719. * the end. */
  8720. static void multipart_startaccum(upb_json_parser *p) {
  8721. assert_accumulate_empty(p);
  8722. assert(p->multipart_state == MULTIPART_INACTIVE);
  8723. p->multipart_state = MULTIPART_ACCUMULATE;
  8724. }
  8725. /* Start a multi-part text value where we immediately push text data to a string
  8726. * value with the given selector. */
  8727. static void multipart_start(upb_json_parser *p, upb_selector_t sel) {
  8728. assert_accumulate_empty(p);
  8729. assert(p->multipart_state == MULTIPART_INACTIVE);
  8730. p->multipart_state = MULTIPART_PUSHEAGERLY;
  8731. p->string_selector = sel;
  8732. }
  8733. static bool multipart_text(upb_json_parser *p, const char *buf, size_t len,
  8734. bool can_alias) {
  8735. switch (p->multipart_state) {
  8736. case MULTIPART_INACTIVE:
  8737. upb_status_seterrmsg(
  8738. p->status, "Internal error: unexpected state MULTIPART_INACTIVE");
  8739. return false;
  8740. case MULTIPART_ACCUMULATE:
  8741. if (!accumulate_append(p, buf, len, can_alias)) {
  8742. return false;
  8743. }
  8744. break;
  8745. case MULTIPART_PUSHEAGERLY: {
  8746. const upb_bufhandle *handle = can_alias ? p->handle : NULL;
  8747. upb_sink_putstring(&p->top->sink, p->string_selector, buf, len, handle);
  8748. break;
  8749. }
  8750. }
  8751. return true;
  8752. }
  8753. /* Note: this invalidates the accumulate buffer! Call only after reading its
  8754. * contents. */
  8755. static void multipart_end(upb_json_parser *p) {
  8756. assert(p->multipart_state != MULTIPART_INACTIVE);
  8757. p->multipart_state = MULTIPART_INACTIVE;
  8758. accumulate_clear(p);
  8759. }
  8760. /* Input capture **************************************************************/
  8761. /* Functionality for capturing a region of the input as text. Gracefully
  8762. * handles the case where a buffer seam occurs in the middle of the captured
  8763. * region. */
  8764. static void capture_begin(upb_json_parser *p, const char *ptr) {
  8765. assert(p->multipart_state != MULTIPART_INACTIVE);
  8766. assert(p->capture == NULL);
  8767. p->capture = ptr;
  8768. }
  8769. static bool capture_end(upb_json_parser *p, const char *ptr) {
  8770. assert(p->capture);
  8771. if (multipart_text(p, p->capture, ptr - p->capture, true)) {
  8772. p->capture = NULL;
  8773. return true;
  8774. } else {
  8775. return false;
  8776. }
  8777. }
  8778. /* This is called at the end of each input buffer (ie. when we have hit a
  8779. * buffer seam). If we are in the middle of capturing the input, this
  8780. * processes the unprocessed capture region. */
  8781. static void capture_suspend(upb_json_parser *p, const char **ptr) {
  8782. if (!p->capture) return;
  8783. if (multipart_text(p, p->capture, *ptr - p->capture, false)) {
  8784. /* We use this as a signal that we were in the middle of capturing, and
  8785. * that capturing should resume at the beginning of the next buffer.
  8786. *
  8787. * We can't use *ptr here, because we have no guarantee that this pointer
  8788. * will be valid when we resume (if the underlying memory is freed, then
  8789. * using the pointer at all, even to compare to NULL, is likely undefined
  8790. * behavior). */
  8791. p->capture = &suspend_capture;
  8792. } else {
  8793. /* Need to back up the pointer to the beginning of the capture, since
  8794. * we were not able to actually preserve it. */
  8795. *ptr = p->capture;
  8796. }
  8797. }
  8798. static void capture_resume(upb_json_parser *p, const char *ptr) {
  8799. if (p->capture) {
  8800. assert(p->capture == &suspend_capture);
  8801. p->capture = ptr;
  8802. }
  8803. }
  8804. /* Callbacks from the parser **************************************************/
  8805. /* These are the functions called directly from the parser itself.
  8806. * We define these in the same order as their declarations in the parser. */
  8807. static char escape_char(char in) {
  8808. switch (in) {
  8809. case 'r': return '\r';
  8810. case 't': return '\t';
  8811. case 'n': return '\n';
  8812. case 'f': return '\f';
  8813. case 'b': return '\b';
  8814. case '/': return '/';
  8815. case '"': return '"';
  8816. case '\\': return '\\';
  8817. default:
  8818. assert(0);
  8819. return 'x';
  8820. }
  8821. }
  8822. static bool escape(upb_json_parser *p, const char *ptr) {
  8823. char ch = escape_char(*ptr);
  8824. return multipart_text(p, &ch, 1, false);
  8825. }
  8826. static void start_hex(upb_json_parser *p) {
  8827. p->digit = 0;
  8828. }
  8829. static void hexdigit(upb_json_parser *p, const char *ptr) {
  8830. char ch = *ptr;
  8831. p->digit <<= 4;
  8832. if (ch >= '0' && ch <= '9') {
  8833. p->digit += (ch - '0');
  8834. } else if (ch >= 'a' && ch <= 'f') {
  8835. p->digit += ((ch - 'a') + 10);
  8836. } else {
  8837. assert(ch >= 'A' && ch <= 'F');
  8838. p->digit += ((ch - 'A') + 10);
  8839. }
  8840. }
  8841. static bool end_hex(upb_json_parser *p) {
  8842. uint32_t codepoint = p->digit;
  8843. /* emit the codepoint as UTF-8. */
  8844. char utf8[3]; /* support \u0000 -- \uFFFF -- need only three bytes. */
  8845. int length = 0;
  8846. if (codepoint <= 0x7F) {
  8847. utf8[0] = codepoint;
  8848. length = 1;
  8849. } else if (codepoint <= 0x07FF) {
  8850. utf8[1] = (codepoint & 0x3F) | 0x80;
  8851. codepoint >>= 6;
  8852. utf8[0] = (codepoint & 0x1F) | 0xC0;
  8853. length = 2;
  8854. } else /* codepoint <= 0xFFFF */ {
  8855. utf8[2] = (codepoint & 0x3F) | 0x80;
  8856. codepoint >>= 6;
  8857. utf8[1] = (codepoint & 0x3F) | 0x80;
  8858. codepoint >>= 6;
  8859. utf8[0] = (codepoint & 0x0F) | 0xE0;
  8860. length = 3;
  8861. }
  8862. /* TODO(haberman): Handle high surrogates: if codepoint is a high surrogate
  8863. * we have to wait for the next escape to get the full code point). */
  8864. return multipart_text(p, utf8, length, false);
  8865. }
  8866. static void start_text(upb_json_parser *p, const char *ptr) {
  8867. capture_begin(p, ptr);
  8868. }
  8869. static bool end_text(upb_json_parser *p, const char *ptr) {
  8870. return capture_end(p, ptr);
  8871. }
  8872. static void start_number(upb_json_parser *p, const char *ptr) {
  8873. multipart_startaccum(p);
  8874. capture_begin(p, ptr);
  8875. }
  8876. static bool parse_number(upb_json_parser *p);
  8877. static bool end_number(upb_json_parser *p, const char *ptr) {
  8878. if (!capture_end(p, ptr)) {
  8879. return false;
  8880. }
  8881. return parse_number(p);
  8882. }
  8883. static bool parse_number(upb_json_parser *p) {
  8884. size_t len;
  8885. const char *buf;
  8886. const char *myend;
  8887. char *end;
  8888. /* strtol() and friends unfortunately do not support specifying the length of
  8889. * the input string, so we need to force a copy into a NULL-terminated buffer. */
  8890. if (!multipart_text(p, "\0", 1, false)) {
  8891. return false;
  8892. }
  8893. buf = accumulate_getptr(p, &len);
  8894. myend = buf + len - 1; /* One for NULL. */
  8895. /* XXX: We are using strtol to parse integers, but this is wrong as even
  8896. * integers can be represented as 1e6 (for example), which strtol can't
  8897. * handle correctly.
  8898. *
  8899. * XXX: Also, we can't handle large integers properly because strto[u]ll
  8900. * isn't in C89.
  8901. *
  8902. * XXX: Also, we don't properly check floats for overflow, since strtof
  8903. * isn't in C89. */
  8904. switch (upb_fielddef_type(p->top->f)) {
  8905. case UPB_TYPE_ENUM:
  8906. case UPB_TYPE_INT32: {
  8907. long val = strtol(p->accumulated, &end, 0);
  8908. if (val > INT32_MAX || val < INT32_MIN || errno == ERANGE || end != myend)
  8909. goto err;
  8910. else
  8911. upb_sink_putint32(&p->top->sink, parser_getsel(p), val);
  8912. break;
  8913. }
  8914. case UPB_TYPE_INT64: {
  8915. long long val = strtol(p->accumulated, &end, 0);
  8916. if (val > INT64_MAX || val < INT64_MIN || errno == ERANGE || end != myend)
  8917. goto err;
  8918. else
  8919. upb_sink_putint64(&p->top->sink, parser_getsel(p), val);
  8920. break;
  8921. }
  8922. case UPB_TYPE_UINT32: {
  8923. unsigned long val = strtoul(p->accumulated, &end, 0);
  8924. if (val > UINT32_MAX || errno == ERANGE || end != myend)
  8925. goto err;
  8926. else
  8927. upb_sink_putuint32(&p->top->sink, parser_getsel(p), val);
  8928. break;
  8929. }
  8930. case UPB_TYPE_UINT64: {
  8931. unsigned long long val = strtoul(p->accumulated, &end, 0);
  8932. if (val > UINT64_MAX || errno == ERANGE || end != myend)
  8933. goto err;
  8934. else
  8935. upb_sink_putuint64(&p->top->sink, parser_getsel(p), val);
  8936. break;
  8937. }
  8938. case UPB_TYPE_DOUBLE: {
  8939. double val = strtod(p->accumulated, &end);
  8940. if (errno == ERANGE || end != myend)
  8941. goto err;
  8942. else
  8943. upb_sink_putdouble(&p->top->sink, parser_getsel(p), val);
  8944. break;
  8945. }
  8946. case UPB_TYPE_FLOAT: {
  8947. float val = strtod(p->accumulated, &end);
  8948. if (errno == ERANGE || end != myend)
  8949. goto err;
  8950. else
  8951. upb_sink_putfloat(&p->top->sink, parser_getsel(p), val);
  8952. break;
  8953. }
  8954. default:
  8955. assert(false);
  8956. }
  8957. multipart_end(p);
  8958. return true;
  8959. err:
  8960. upb_status_seterrf(p->status, "error parsing number: %s", buf);
  8961. multipart_end(p);
  8962. return false;
  8963. }
  8964. static bool parser_putbool(upb_json_parser *p, bool val) {
  8965. bool ok;
  8966. if (upb_fielddef_type(p->top->f) != UPB_TYPE_BOOL) {
  8967. upb_status_seterrf(p->status,
  8968. "Boolean value specified for non-bool field: %s",
  8969. upb_fielddef_name(p->top->f));
  8970. return false;
  8971. }
  8972. ok = upb_sink_putbool(&p->top->sink, parser_getsel(p), val);
  8973. UPB_ASSERT_VAR(ok, ok);
  8974. return true;
  8975. }
  8976. static bool start_stringval(upb_json_parser *p) {
  8977. assert(p->top->f);
  8978. if (upb_fielddef_isstring(p->top->f)) {
  8979. upb_jsonparser_frame *inner;
  8980. upb_selector_t sel;
  8981. if (!check_stack(p)) return false;
  8982. /* Start a new parser frame: parser frames correspond one-to-one with
  8983. * handler frames, and string events occur in a sub-frame. */
  8984. inner = p->top + 1;
  8985. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  8986. upb_sink_startstr(&p->top->sink, sel, 0, &inner->sink);
  8987. inner->m = p->top->m;
  8988. inner->f = p->top->f;
  8989. inner->is_map = false;
  8990. inner->is_mapentry = false;
  8991. p->top = inner;
  8992. if (upb_fielddef_type(p->top->f) == UPB_TYPE_STRING) {
  8993. /* For STRING fields we push data directly to the handlers as it is
  8994. * parsed. We don't do this yet for BYTES fields, because our base64
  8995. * decoder is not streaming.
  8996. *
  8997. * TODO(haberman): make base64 decoding streaming also. */
  8998. multipart_start(p, getsel_for_handlertype(p, UPB_HANDLER_STRING));
  8999. return true;
  9000. } else {
  9001. multipart_startaccum(p);
  9002. return true;
  9003. }
  9004. } else if (upb_fielddef_type(p->top->f) == UPB_TYPE_ENUM) {
  9005. /* No need to push a frame -- symbolic enum names in quotes remain in the
  9006. * current parser frame.
  9007. *
  9008. * Enum string values must accumulate so we can look up the value in a table
  9009. * once it is complete. */
  9010. multipart_startaccum(p);
  9011. return true;
  9012. } else {
  9013. upb_status_seterrf(p->status,
  9014. "String specified for non-string/non-enum field: %s",
  9015. upb_fielddef_name(p->top->f));
  9016. return false;
  9017. }
  9018. }
  9019. static bool end_stringval(upb_json_parser *p) {
  9020. bool ok = true;
  9021. switch (upb_fielddef_type(p->top->f)) {
  9022. case UPB_TYPE_BYTES:
  9023. if (!base64_push(p, getsel_for_handlertype(p, UPB_HANDLER_STRING),
  9024. p->accumulated, p->accumulated_len)) {
  9025. return false;
  9026. }
  9027. /* Fall through. */
  9028. case UPB_TYPE_STRING: {
  9029. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  9030. upb_sink_endstr(&p->top->sink, sel);
  9031. p->top--;
  9032. break;
  9033. }
  9034. case UPB_TYPE_ENUM: {
  9035. /* Resolve enum symbolic name to integer value. */
  9036. const upb_enumdef *enumdef =
  9037. (const upb_enumdef*)upb_fielddef_subdef(p->top->f);
  9038. size_t len;
  9039. const char *buf = accumulate_getptr(p, &len);
  9040. int32_t int_val = 0;
  9041. ok = upb_enumdef_ntoi(enumdef, buf, len, &int_val);
  9042. if (ok) {
  9043. upb_selector_t sel = parser_getsel(p);
  9044. upb_sink_putint32(&p->top->sink, sel, int_val);
  9045. } else {
  9046. upb_status_seterrf(p->status, "Enum value unknown: '%.*s'", len, buf);
  9047. }
  9048. break;
  9049. }
  9050. default:
  9051. assert(false);
  9052. upb_status_seterrmsg(p->status, "Internal error in JSON decoder");
  9053. ok = false;
  9054. break;
  9055. }
  9056. multipart_end(p);
  9057. return ok;
  9058. }
  9059. static void start_member(upb_json_parser *p) {
  9060. assert(!p->top->f);
  9061. multipart_startaccum(p);
  9062. }
  9063. /* Helper: invoked during parse_mapentry() to emit the mapentry message's key
  9064. * field based on the current contents of the accumulate buffer. */
  9065. static bool parse_mapentry_key(upb_json_parser *p) {
  9066. size_t len;
  9067. const char *buf = accumulate_getptr(p, &len);
  9068. /* Emit the key field. We do a bit of ad-hoc parsing here because the
  9069. * parser state machine has already decided that this is a string field
  9070. * name, and we are reinterpreting it as some arbitrary key type. In
  9071. * particular, integer and bool keys are quoted, so we need to parse the
  9072. * quoted string contents here. */
  9073. p->top->f = upb_msgdef_itof(p->top->m, UPB_MAPENTRY_KEY);
  9074. if (p->top->f == NULL) {
  9075. upb_status_seterrmsg(p->status, "mapentry message has no key");
  9076. return false;
  9077. }
  9078. switch (upb_fielddef_type(p->top->f)) {
  9079. case UPB_TYPE_INT32:
  9080. case UPB_TYPE_INT64:
  9081. case UPB_TYPE_UINT32:
  9082. case UPB_TYPE_UINT64:
  9083. /* Invoke end_number. The accum buffer has the number's text already. */
  9084. if (!parse_number(p)) {
  9085. return false;
  9086. }
  9087. break;
  9088. case UPB_TYPE_BOOL:
  9089. if (len == 4 && !strncmp(buf, "true", 4)) {
  9090. if (!parser_putbool(p, true)) {
  9091. return false;
  9092. }
  9093. } else if (len == 5 && !strncmp(buf, "false", 5)) {
  9094. if (!parser_putbool(p, false)) {
  9095. return false;
  9096. }
  9097. } else {
  9098. upb_status_seterrmsg(p->status,
  9099. "Map bool key not 'true' or 'false'");
  9100. return false;
  9101. }
  9102. multipart_end(p);
  9103. break;
  9104. case UPB_TYPE_STRING:
  9105. case UPB_TYPE_BYTES: {
  9106. upb_sink subsink;
  9107. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  9108. upb_sink_startstr(&p->top->sink, sel, len, &subsink);
  9109. sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
  9110. upb_sink_putstring(&subsink, sel, buf, len, NULL);
  9111. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  9112. upb_sink_endstr(&subsink, sel);
  9113. multipart_end(p);
  9114. break;
  9115. }
  9116. default:
  9117. upb_status_seterrmsg(p->status, "Invalid field type for map key");
  9118. return false;
  9119. }
  9120. return true;
  9121. }
  9122. /* Helper: emit one map entry (as a submessage in the map field sequence). This
  9123. * is invoked from end_membername(), at the end of the map entry's key string,
  9124. * with the map key in the accumulate buffer. It parses the key from that
  9125. * buffer, emits the handler calls to start the mapentry submessage (setting up
  9126. * its subframe in the process), and sets up state in the subframe so that the
  9127. * value parser (invoked next) will emit the mapentry's value field and then
  9128. * end the mapentry message. */
  9129. static bool handle_mapentry(upb_json_parser *p) {
  9130. const upb_fielddef *mapfield;
  9131. const upb_msgdef *mapentrymsg;
  9132. upb_jsonparser_frame *inner;
  9133. upb_selector_t sel;
  9134. /* Map entry: p->top->sink is the seq frame, so we need to start a frame
  9135. * for the mapentry itself, and then set |f| in that frame so that the map
  9136. * value field is parsed, and also set a flag to end the frame after the
  9137. * map-entry value is parsed. */
  9138. if (!check_stack(p)) return false;
  9139. mapfield = p->top->mapfield;
  9140. mapentrymsg = upb_fielddef_msgsubdef(mapfield);
  9141. inner = p->top + 1;
  9142. p->top->f = mapfield;
  9143. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
  9144. upb_sink_startsubmsg(&p->top->sink, sel, &inner->sink);
  9145. inner->m = mapentrymsg;
  9146. inner->mapfield = mapfield;
  9147. inner->is_map = false;
  9148. /* Don't set this to true *yet* -- we reuse parsing handlers below to push
  9149. * the key field value to the sink, and these handlers will pop the frame
  9150. * if they see is_mapentry (when invoked by the parser state machine, they
  9151. * would have just seen the map-entry value, not key). */
  9152. inner->is_mapentry = false;
  9153. p->top = inner;
  9154. /* send STARTMSG in submsg frame. */
  9155. upb_sink_startmsg(&p->top->sink);
  9156. parse_mapentry_key(p);
  9157. /* Set up the value field to receive the map-entry value. */
  9158. p->top->f = upb_msgdef_itof(p->top->m, UPB_MAPENTRY_VALUE);
  9159. p->top->is_mapentry = true; /* set up to pop frame after value is parsed. */
  9160. p->top->mapfield = mapfield;
  9161. if (p->top->f == NULL) {
  9162. upb_status_seterrmsg(p->status, "mapentry message has no value");
  9163. return false;
  9164. }
  9165. return true;
  9166. }
  9167. static bool end_membername(upb_json_parser *p) {
  9168. assert(!p->top->f);
  9169. if (p->top->is_map) {
  9170. return handle_mapentry(p);
  9171. } else {
  9172. size_t len;
  9173. const char *buf = accumulate_getptr(p, &len);
  9174. const upb_fielddef *f = upb_msgdef_ntof(p->top->m, buf, len);
  9175. if (!f) {
  9176. /* TODO(haberman): Ignore unknown fields if requested/configured to do
  9177. * so. */
  9178. upb_status_seterrf(p->status, "No such field: %.*s\n", (int)len, buf);
  9179. return false;
  9180. }
  9181. p->top->f = f;
  9182. multipart_end(p);
  9183. return true;
  9184. }
  9185. }
  9186. static void end_member(upb_json_parser *p) {
  9187. /* If we just parsed a map-entry value, end that frame too. */
  9188. if (p->top->is_mapentry) {
  9189. upb_status s = UPB_STATUS_INIT;
  9190. upb_selector_t sel;
  9191. bool ok;
  9192. const upb_fielddef *mapfield;
  9193. assert(p->top > p->stack);
  9194. /* send ENDMSG on submsg. */
  9195. upb_sink_endmsg(&p->top->sink, &s);
  9196. mapfield = p->top->mapfield;
  9197. /* send ENDSUBMSG in repeated-field-of-mapentries frame. */
  9198. p->top--;
  9199. ok = upb_handlers_getselector(mapfield, UPB_HANDLER_ENDSUBMSG, &sel);
  9200. UPB_ASSERT_VAR(ok, ok);
  9201. upb_sink_endsubmsg(&p->top->sink, sel);
  9202. }
  9203. p->top->f = NULL;
  9204. }
  9205. static bool start_subobject(upb_json_parser *p) {
  9206. assert(p->top->f);
  9207. if (upb_fielddef_ismap(p->top->f)) {
  9208. upb_jsonparser_frame *inner;
  9209. upb_selector_t sel;
  9210. /* Beginning of a map. Start a new parser frame in a repeated-field
  9211. * context. */
  9212. if (!check_stack(p)) return false;
  9213. inner = p->top + 1;
  9214. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
  9215. upb_sink_startseq(&p->top->sink, sel, &inner->sink);
  9216. inner->m = upb_fielddef_msgsubdef(p->top->f);
  9217. inner->mapfield = p->top->f;
  9218. inner->f = NULL;
  9219. inner->is_map = true;
  9220. inner->is_mapentry = false;
  9221. p->top = inner;
  9222. return true;
  9223. } else if (upb_fielddef_issubmsg(p->top->f)) {
  9224. upb_jsonparser_frame *inner;
  9225. upb_selector_t sel;
  9226. /* Beginning of a subobject. Start a new parser frame in the submsg
  9227. * context. */
  9228. if (!check_stack(p)) return false;
  9229. inner = p->top + 1;
  9230. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
  9231. upb_sink_startsubmsg(&p->top->sink, sel, &inner->sink);
  9232. inner->m = upb_fielddef_msgsubdef(p->top->f);
  9233. inner->f = NULL;
  9234. inner->is_map = false;
  9235. inner->is_mapentry = false;
  9236. p->top = inner;
  9237. return true;
  9238. } else {
  9239. upb_status_seterrf(p->status,
  9240. "Object specified for non-message/group field: %s",
  9241. upb_fielddef_name(p->top->f));
  9242. return false;
  9243. }
  9244. }
  9245. static void end_subobject(upb_json_parser *p) {
  9246. if (p->top->is_map) {
  9247. upb_selector_t sel;
  9248. p->top--;
  9249. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
  9250. upb_sink_endseq(&p->top->sink, sel);
  9251. } else {
  9252. upb_selector_t sel;
  9253. p->top--;
  9254. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSUBMSG);
  9255. upb_sink_endsubmsg(&p->top->sink, sel);
  9256. }
  9257. }
  9258. static bool start_array(upb_json_parser *p) {
  9259. upb_jsonparser_frame *inner;
  9260. upb_selector_t sel;
  9261. assert(p->top->f);
  9262. if (!upb_fielddef_isseq(p->top->f)) {
  9263. upb_status_seterrf(p->status,
  9264. "Array specified for non-repeated field: %s",
  9265. upb_fielddef_name(p->top->f));
  9266. return false;
  9267. }
  9268. if (!check_stack(p)) return false;
  9269. inner = p->top + 1;
  9270. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
  9271. upb_sink_startseq(&p->top->sink, sel, &inner->sink);
  9272. inner->m = p->top->m;
  9273. inner->f = p->top->f;
  9274. inner->is_map = false;
  9275. inner->is_mapentry = false;
  9276. p->top = inner;
  9277. return true;
  9278. }
  9279. static void end_array(upb_json_parser *p) {
  9280. upb_selector_t sel;
  9281. assert(p->top > p->stack);
  9282. p->top--;
  9283. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
  9284. upb_sink_endseq(&p->top->sink, sel);
  9285. }
  9286. static void start_object(upb_json_parser *p) {
  9287. if (!p->top->is_map) {
  9288. upb_sink_startmsg(&p->top->sink);
  9289. }
  9290. }
  9291. static void end_object(upb_json_parser *p) {
  9292. if (!p->top->is_map) {
  9293. upb_status status;
  9294. upb_sink_endmsg(&p->top->sink, &status);
  9295. }
  9296. }
  9297. #define CHECK_RETURN_TOP(x) if (!(x)) goto error
  9298. /* The actual parser **********************************************************/
  9299. /* What follows is the Ragel parser itself. The language is specified in Ragel
  9300. * and the actions call our C functions above.
  9301. *
  9302. * Ragel has an extensive set of functionality, and we use only a small part of
  9303. * it. There are many action types but we only use a few:
  9304. *
  9305. * ">" -- transition into a machine
  9306. * "%" -- transition out of a machine
  9307. * "@" -- transition into a final state of a machine.
  9308. *
  9309. * "@" transitions are tricky because a machine can transition into a final
  9310. * state repeatedly. But in some cases we know this can't happen, for example
  9311. * a string which is delimited by a final '"' can only transition into its
  9312. * final state once, when the closing '"' is seen. */
  9313. #line 1198 "upb/json/parser.rl"
  9314. #line 1110 "upb/json/parser.c"
  9315. static const char _json_actions[] = {
  9316. 0, 1, 0, 1, 2, 1, 3, 1,
  9317. 5, 1, 6, 1, 7, 1, 8, 1,
  9318. 10, 1, 12, 1, 13, 1, 14, 1,
  9319. 15, 1, 16, 1, 17, 1, 21, 1,
  9320. 25, 1, 27, 2, 3, 8, 2, 4,
  9321. 5, 2, 6, 2, 2, 6, 8, 2,
  9322. 11, 9, 2, 13, 15, 2, 14, 15,
  9323. 2, 18, 1, 2, 19, 27, 2, 20,
  9324. 9, 2, 22, 27, 2, 23, 27, 2,
  9325. 24, 27, 2, 26, 27, 3, 14, 11,
  9326. 9
  9327. };
  9328. static const unsigned char _json_key_offsets[] = {
  9329. 0, 0, 4, 9, 14, 15, 19, 24,
  9330. 29, 34, 38, 42, 45, 48, 50, 54,
  9331. 58, 60, 62, 67, 69, 71, 80, 86,
  9332. 92, 98, 104, 106, 115, 116, 116, 116,
  9333. 121, 126, 131, 132, 133, 134, 135, 135,
  9334. 136, 137, 138, 138, 139, 140, 141, 141,
  9335. 146, 151, 152, 156, 161, 166, 171, 175,
  9336. 175, 178, 178, 178
  9337. };
  9338. static const char _json_trans_keys[] = {
  9339. 32, 123, 9, 13, 32, 34, 125, 9,
  9340. 13, 32, 34, 125, 9, 13, 34, 32,
  9341. 58, 9, 13, 32, 93, 125, 9, 13,
  9342. 32, 44, 125, 9, 13, 32, 44, 125,
  9343. 9, 13, 32, 34, 9, 13, 45, 48,
  9344. 49, 57, 48, 49, 57, 46, 69, 101,
  9345. 48, 57, 69, 101, 48, 57, 43, 45,
  9346. 48, 57, 48, 57, 48, 57, 46, 69,
  9347. 101, 48, 57, 34, 92, 34, 92, 34,
  9348. 47, 92, 98, 102, 110, 114, 116, 117,
  9349. 48, 57, 65, 70, 97, 102, 48, 57,
  9350. 65, 70, 97, 102, 48, 57, 65, 70,
  9351. 97, 102, 48, 57, 65, 70, 97, 102,
  9352. 34, 92, 34, 45, 91, 102, 110, 116,
  9353. 123, 48, 57, 34, 32, 93, 125, 9,
  9354. 13, 32, 44, 93, 9, 13, 32, 93,
  9355. 125, 9, 13, 97, 108, 115, 101, 117,
  9356. 108, 108, 114, 117, 101, 32, 34, 125,
  9357. 9, 13, 32, 34, 125, 9, 13, 34,
  9358. 32, 58, 9, 13, 32, 93, 125, 9,
  9359. 13, 32, 44, 125, 9, 13, 32, 44,
  9360. 125, 9, 13, 32, 34, 9, 13, 32,
  9361. 9, 13, 0
  9362. };
  9363. static const char _json_single_lengths[] = {
  9364. 0, 2, 3, 3, 1, 2, 3, 3,
  9365. 3, 2, 2, 1, 3, 0, 2, 2,
  9366. 0, 0, 3, 2, 2, 9, 0, 0,
  9367. 0, 0, 2, 7, 1, 0, 0, 3,
  9368. 3, 3, 1, 1, 1, 1, 0, 1,
  9369. 1, 1, 0, 1, 1, 1, 0, 3,
  9370. 3, 1, 2, 3, 3, 3, 2, 0,
  9371. 1, 0, 0, 0
  9372. };
  9373. static const char _json_range_lengths[] = {
  9374. 0, 1, 1, 1, 0, 1, 1, 1,
  9375. 1, 1, 1, 1, 0, 1, 1, 1,
  9376. 1, 1, 1, 0, 0, 0, 3, 3,
  9377. 3, 3, 0, 1, 0, 0, 0, 1,
  9378. 1, 1, 0, 0, 0, 0, 0, 0,
  9379. 0, 0, 0, 0, 0, 0, 0, 1,
  9380. 1, 0, 1, 1, 1, 1, 1, 0,
  9381. 1, 0, 0, 0
  9382. };
  9383. static const short _json_index_offsets[] = {
  9384. 0, 0, 4, 9, 14, 16, 20, 25,
  9385. 30, 35, 39, 43, 46, 50, 52, 56,
  9386. 60, 62, 64, 69, 72, 75, 85, 89,
  9387. 93, 97, 101, 104, 113, 115, 116, 117,
  9388. 122, 127, 132, 134, 136, 138, 140, 141,
  9389. 143, 145, 147, 148, 150, 152, 154, 155,
  9390. 160, 165, 167, 171, 176, 181, 186, 190,
  9391. 191, 194, 195, 196
  9392. };
  9393. static const char _json_indicies[] = {
  9394. 0, 2, 0, 1, 3, 4, 5, 3,
  9395. 1, 6, 7, 8, 6, 1, 9, 1,
  9396. 10, 11, 10, 1, 11, 1, 1, 11,
  9397. 12, 13, 14, 15, 13, 1, 16, 17,
  9398. 8, 16, 1, 17, 7, 17, 1, 18,
  9399. 19, 20, 1, 19, 20, 1, 22, 23,
  9400. 23, 21, 24, 1, 23, 23, 24, 21,
  9401. 25, 25, 26, 1, 26, 1, 26, 21,
  9402. 22, 23, 23, 20, 21, 28, 29, 27,
  9403. 31, 32, 30, 33, 33, 33, 33, 33,
  9404. 33, 33, 33, 34, 1, 35, 35, 35,
  9405. 1, 36, 36, 36, 1, 37, 37, 37,
  9406. 1, 38, 38, 38, 1, 40, 41, 39,
  9407. 42, 43, 44, 45, 46, 47, 48, 43,
  9408. 1, 49, 1, 50, 51, 53, 54, 1,
  9409. 53, 52, 55, 56, 54, 55, 1, 56,
  9410. 1, 1, 56, 52, 57, 1, 58, 1,
  9411. 59, 1, 60, 1, 61, 62, 1, 63,
  9412. 1, 64, 1, 65, 66, 1, 67, 1,
  9413. 68, 1, 69, 70, 71, 72, 70, 1,
  9414. 73, 74, 75, 73, 1, 76, 1, 77,
  9415. 78, 77, 1, 78, 1, 1, 78, 79,
  9416. 80, 81, 82, 80, 1, 83, 84, 75,
  9417. 83, 1, 84, 74, 84, 1, 85, 86,
  9418. 86, 1, 1, 1, 1, 0
  9419. };
  9420. static const char _json_trans_targs[] = {
  9421. 1, 0, 2, 3, 4, 56, 3, 4,
  9422. 56, 5, 5, 6, 7, 8, 9, 56,
  9423. 8, 9, 11, 12, 18, 57, 13, 15,
  9424. 14, 16, 17, 20, 58, 21, 20, 58,
  9425. 21, 19, 22, 23, 24, 25, 26, 20,
  9426. 58, 21, 28, 30, 31, 34, 39, 43,
  9427. 47, 29, 59, 59, 32, 31, 29, 32,
  9428. 33, 35, 36, 37, 38, 59, 40, 41,
  9429. 42, 59, 44, 45, 46, 59, 48, 49,
  9430. 55, 48, 49, 55, 50, 50, 51, 52,
  9431. 53, 54, 55, 53, 54, 59, 56
  9432. };
  9433. static const char _json_trans_actions[] = {
  9434. 0, 0, 0, 21, 77, 53, 0, 47,
  9435. 23, 17, 0, 0, 15, 19, 19, 50,
  9436. 0, 0, 0, 0, 0, 1, 0, 0,
  9437. 0, 0, 0, 3, 13, 0, 0, 35,
  9438. 5, 11, 0, 38, 7, 7, 7, 41,
  9439. 44, 9, 62, 56, 25, 0, 0, 0,
  9440. 31, 29, 33, 59, 15, 0, 27, 0,
  9441. 0, 0, 0, 0, 0, 68, 0, 0,
  9442. 0, 71, 0, 0, 0, 65, 21, 77,
  9443. 53, 0, 47, 23, 17, 0, 0, 15,
  9444. 19, 19, 50, 0, 0, 74, 0
  9445. };
  9446. static const int json_start = 1;
  9447. static const int json_en_number_machine = 10;
  9448. static const int json_en_string_machine = 19;
  9449. static const int json_en_value_machine = 27;
  9450. static const int json_en_main = 1;
  9451. #line 1201 "upb/json/parser.rl"
  9452. size_t parse(void *closure, const void *hd, const char *buf, size_t size,
  9453. const upb_bufhandle *handle) {
  9454. upb_json_parser *parser = closure;
  9455. /* Variables used by Ragel's generated code. */
  9456. int cs = parser->current_state;
  9457. int *stack = parser->parser_stack;
  9458. int top = parser->parser_top;
  9459. const char *p = buf;
  9460. const char *pe = buf + size;
  9461. parser->handle = handle;
  9462. UPB_UNUSED(hd);
  9463. UPB_UNUSED(handle);
  9464. capture_resume(parser, buf);
  9465. #line 1281 "upb/json/parser.c"
  9466. {
  9467. int _klen;
  9468. unsigned int _trans;
  9469. const char *_acts;
  9470. unsigned int _nacts;
  9471. const char *_keys;
  9472. if ( p == pe )
  9473. goto _test_eof;
  9474. if ( cs == 0 )
  9475. goto _out;
  9476. _resume:
  9477. _keys = _json_trans_keys + _json_key_offsets[cs];
  9478. _trans = _json_index_offsets[cs];
  9479. _klen = _json_single_lengths[cs];
  9480. if ( _klen > 0 ) {
  9481. const char *_lower = _keys;
  9482. const char *_mid;
  9483. const char *_upper = _keys + _klen - 1;
  9484. while (1) {
  9485. if ( _upper < _lower )
  9486. break;
  9487. _mid = _lower + ((_upper-_lower) >> 1);
  9488. if ( (*p) < *_mid )
  9489. _upper = _mid - 1;
  9490. else if ( (*p) > *_mid )
  9491. _lower = _mid + 1;
  9492. else {
  9493. _trans += (unsigned int)(_mid - _keys);
  9494. goto _match;
  9495. }
  9496. }
  9497. _keys += _klen;
  9498. _trans += _klen;
  9499. }
  9500. _klen = _json_range_lengths[cs];
  9501. if ( _klen > 0 ) {
  9502. const char *_lower = _keys;
  9503. const char *_mid;
  9504. const char *_upper = _keys + (_klen<<1) - 2;
  9505. while (1) {
  9506. if ( _upper < _lower )
  9507. break;
  9508. _mid = _lower + (((_upper-_lower) >> 1) & ~1);
  9509. if ( (*p) < _mid[0] )
  9510. _upper = _mid - 2;
  9511. else if ( (*p) > _mid[1] )
  9512. _lower = _mid + 2;
  9513. else {
  9514. _trans += (unsigned int)((_mid - _keys)>>1);
  9515. goto _match;
  9516. }
  9517. }
  9518. _trans += _klen;
  9519. }
  9520. _match:
  9521. _trans = _json_indicies[_trans];
  9522. cs = _json_trans_targs[_trans];
  9523. if ( _json_trans_actions[_trans] == 0 )
  9524. goto _again;
  9525. _acts = _json_actions + _json_trans_actions[_trans];
  9526. _nacts = (unsigned int) *_acts++;
  9527. while ( _nacts-- > 0 )
  9528. {
  9529. switch ( *_acts++ )
  9530. {
  9531. case 0:
  9532. #line 1113 "upb/json/parser.rl"
  9533. { p--; {cs = stack[--top]; goto _again;} }
  9534. break;
  9535. case 1:
  9536. #line 1114 "upb/json/parser.rl"
  9537. { p--; {stack[top++] = cs; cs = 10; goto _again;} }
  9538. break;
  9539. case 2:
  9540. #line 1118 "upb/json/parser.rl"
  9541. { start_text(parser, p); }
  9542. break;
  9543. case 3:
  9544. #line 1119 "upb/json/parser.rl"
  9545. { CHECK_RETURN_TOP(end_text(parser, p)); }
  9546. break;
  9547. case 4:
  9548. #line 1125 "upb/json/parser.rl"
  9549. { start_hex(parser); }
  9550. break;
  9551. case 5:
  9552. #line 1126 "upb/json/parser.rl"
  9553. { hexdigit(parser, p); }
  9554. break;
  9555. case 6:
  9556. #line 1127 "upb/json/parser.rl"
  9557. { CHECK_RETURN_TOP(end_hex(parser)); }
  9558. break;
  9559. case 7:
  9560. #line 1133 "upb/json/parser.rl"
  9561. { CHECK_RETURN_TOP(escape(parser, p)); }
  9562. break;
  9563. case 8:
  9564. #line 1139 "upb/json/parser.rl"
  9565. { p--; {cs = stack[--top]; goto _again;} }
  9566. break;
  9567. case 9:
  9568. #line 1142 "upb/json/parser.rl"
  9569. { {stack[top++] = cs; cs = 19; goto _again;} }
  9570. break;
  9571. case 10:
  9572. #line 1144 "upb/json/parser.rl"
  9573. { p--; {stack[top++] = cs; cs = 27; goto _again;} }
  9574. break;
  9575. case 11:
  9576. #line 1149 "upb/json/parser.rl"
  9577. { start_member(parser); }
  9578. break;
  9579. case 12:
  9580. #line 1150 "upb/json/parser.rl"
  9581. { CHECK_RETURN_TOP(end_membername(parser)); }
  9582. break;
  9583. case 13:
  9584. #line 1153 "upb/json/parser.rl"
  9585. { end_member(parser); }
  9586. break;
  9587. case 14:
  9588. #line 1159 "upb/json/parser.rl"
  9589. { start_object(parser); }
  9590. break;
  9591. case 15:
  9592. #line 1162 "upb/json/parser.rl"
  9593. { end_object(parser); }
  9594. break;
  9595. case 16:
  9596. #line 1168 "upb/json/parser.rl"
  9597. { CHECK_RETURN_TOP(start_array(parser)); }
  9598. break;
  9599. case 17:
  9600. #line 1172 "upb/json/parser.rl"
  9601. { end_array(parser); }
  9602. break;
  9603. case 18:
  9604. #line 1177 "upb/json/parser.rl"
  9605. { start_number(parser, p); }
  9606. break;
  9607. case 19:
  9608. #line 1178 "upb/json/parser.rl"
  9609. { CHECK_RETURN_TOP(end_number(parser, p)); }
  9610. break;
  9611. case 20:
  9612. #line 1180 "upb/json/parser.rl"
  9613. { CHECK_RETURN_TOP(start_stringval(parser)); }
  9614. break;
  9615. case 21:
  9616. #line 1181 "upb/json/parser.rl"
  9617. { CHECK_RETURN_TOP(end_stringval(parser)); }
  9618. break;
  9619. case 22:
  9620. #line 1183 "upb/json/parser.rl"
  9621. { CHECK_RETURN_TOP(parser_putbool(parser, true)); }
  9622. break;
  9623. case 23:
  9624. #line 1185 "upb/json/parser.rl"
  9625. { CHECK_RETURN_TOP(parser_putbool(parser, false)); }
  9626. break;
  9627. case 24:
  9628. #line 1187 "upb/json/parser.rl"
  9629. { /* null value */ }
  9630. break;
  9631. case 25:
  9632. #line 1189 "upb/json/parser.rl"
  9633. { CHECK_RETURN_TOP(start_subobject(parser)); }
  9634. break;
  9635. case 26:
  9636. #line 1190 "upb/json/parser.rl"
  9637. { end_subobject(parser); }
  9638. break;
  9639. case 27:
  9640. #line 1195 "upb/json/parser.rl"
  9641. { p--; {cs = stack[--top]; goto _again;} }
  9642. break;
  9643. #line 1467 "upb/json/parser.c"
  9644. }
  9645. }
  9646. _again:
  9647. if ( cs == 0 )
  9648. goto _out;
  9649. if ( ++p != pe )
  9650. goto _resume;
  9651. _test_eof: {}
  9652. _out: {}
  9653. }
  9654. #line 1222 "upb/json/parser.rl"
  9655. if (p != pe) {
  9656. upb_status_seterrf(parser->status, "Parse error at %s\n", p);
  9657. } else {
  9658. capture_suspend(parser, &p);
  9659. }
  9660. error:
  9661. /* Save parsing state back to parser. */
  9662. parser->current_state = cs;
  9663. parser->parser_top = top;
  9664. return p - buf;
  9665. }
  9666. bool end(void *closure, const void *hd) {
  9667. UPB_UNUSED(closure);
  9668. UPB_UNUSED(hd);
  9669. /* Prevent compile warning on unused static constants. */
  9670. UPB_UNUSED(json_start);
  9671. UPB_UNUSED(json_en_number_machine);
  9672. UPB_UNUSED(json_en_string_machine);
  9673. UPB_UNUSED(json_en_value_machine);
  9674. UPB_UNUSED(json_en_main);
  9675. return true;
  9676. }
  9677. static void json_parser_reset(upb_json_parser *p) {
  9678. int cs;
  9679. int top;
  9680. p->top = p->stack;
  9681. p->top->f = NULL;
  9682. p->top->is_map = false;
  9683. p->top->is_mapentry = false;
  9684. /* Emit Ragel initialization of the parser. */
  9685. #line 1520 "upb/json/parser.c"
  9686. {
  9687. cs = json_start;
  9688. top = 0;
  9689. }
  9690. #line 1261 "upb/json/parser.rl"
  9691. p->current_state = cs;
  9692. p->parser_top = top;
  9693. accumulate_clear(p);
  9694. p->multipart_state = MULTIPART_INACTIVE;
  9695. p->capture = NULL;
  9696. p->accumulated = NULL;
  9697. }
  9698. /* Public API *****************************************************************/
  9699. upb_json_parser *upb_json_parser_create(upb_env *env, upb_sink *output) {
  9700. #ifndef NDEBUG
  9701. const size_t size_before = upb_env_bytesallocated(env);
  9702. #endif
  9703. upb_json_parser *p = upb_env_malloc(env, sizeof(upb_json_parser));
  9704. if (!p) return false;
  9705. p->env = env;
  9706. p->limit = p->stack + UPB_JSON_MAX_DEPTH;
  9707. p->accumulate_buf = NULL;
  9708. p->accumulate_buf_size = 0;
  9709. upb_byteshandler_init(&p->input_handler_);
  9710. upb_byteshandler_setstring(&p->input_handler_, parse, NULL);
  9711. upb_byteshandler_setendstr(&p->input_handler_, end, NULL);
  9712. upb_bytessink_reset(&p->input_, &p->input_handler_, p);
  9713. json_parser_reset(p);
  9714. upb_sink_reset(&p->top->sink, output->handlers, output->closure);
  9715. p->top->m = upb_handlers_msgdef(output->handlers);
  9716. /* If this fails, uncomment and increase the value in parser.h.
  9717. * fprintf(stderr, "%zd\n", upb_env_bytesallocated(env) - size_before); */
  9718. assert(upb_env_bytesallocated(env) - size_before <= UPB_JSON_PARSER_SIZE);
  9719. return p;
  9720. }
  9721. upb_bytessink *upb_json_parser_input(upb_json_parser *p) {
  9722. return &p->input_;
  9723. }
  9724. /*
  9725. * upb - a minimalist implementation of protocol buffers.
  9726. *
  9727. * Copyright (c) 2014 Google Inc. See LICENSE for details.
  9728. * Author: Josh Haberman <jhaberman@gmail.com>
  9729. *
  9730. * This currently uses snprintf() to format primitives, and could be optimized
  9731. * further.
  9732. */
  9733. #include <stdlib.h>
  9734. #include <stdio.h>
  9735. #include <string.h>
  9736. #include <stdint.h>
  9737. struct upb_json_printer {
  9738. upb_sink input_;
  9739. /* BytesSink closure. */
  9740. void *subc_;
  9741. upb_bytessink *output_;
  9742. /* We track the depth so that we know when to emit startstr/endstr on the
  9743. * output. */
  9744. int depth_;
  9745. /* Have we emitted the first element? This state is necessary to emit commas
  9746. * without leaving a trailing comma in arrays/maps. We keep this state per
  9747. * frame depth.
  9748. *
  9749. * Why max_depth * 2? UPB_MAX_HANDLER_DEPTH counts depth as nested messages.
  9750. * We count frames (contexts in which we separate elements by commas) as both
  9751. * repeated fields and messages (maps), and the worst case is a
  9752. * message->repeated field->submessage->repeated field->... nesting. */
  9753. bool first_elem_[UPB_MAX_HANDLER_DEPTH * 2];
  9754. };
  9755. /* StringPiece; a pointer plus a length. */
  9756. typedef struct {
  9757. const char *ptr;
  9758. size_t len;
  9759. } strpc;
  9760. strpc *newstrpc(upb_handlers *h, const upb_fielddef *f) {
  9761. strpc *ret = malloc(sizeof(*ret));
  9762. ret->ptr = upb_fielddef_name(f);
  9763. ret->len = strlen(ret->ptr);
  9764. upb_handlers_addcleanup(h, ret, free);
  9765. return ret;
  9766. }
  9767. /* ------------ JSON string printing: values, maps, arrays ------------------ */
  9768. static void print_data(
  9769. upb_json_printer *p, const char *buf, unsigned int len) {
  9770. /* TODO: Will need to change if we support pushback from the sink. */
  9771. size_t n = upb_bytessink_putbuf(p->output_, p->subc_, buf, len, NULL);
  9772. UPB_ASSERT_VAR(n, n == len);
  9773. }
  9774. static void print_comma(upb_json_printer *p) {
  9775. if (!p->first_elem_[p->depth_]) {
  9776. print_data(p, ",", 1);
  9777. }
  9778. p->first_elem_[p->depth_] = false;
  9779. }
  9780. /* Helpers that print properly formatted elements to the JSON output stream. */
  9781. /* Used for escaping control chars in strings. */
  9782. static const char kControlCharLimit = 0x20;
  9783. UPB_INLINE bool is_json_escaped(char c) {
  9784. /* See RFC 4627. */
  9785. unsigned char uc = (unsigned char)c;
  9786. return uc < kControlCharLimit || uc == '"' || uc == '\\';
  9787. }
  9788. UPB_INLINE char* json_nice_escape(char c) {
  9789. switch (c) {
  9790. case '"': return "\\\"";
  9791. case '\\': return "\\\\";
  9792. case '\b': return "\\b";
  9793. case '\f': return "\\f";
  9794. case '\n': return "\\n";
  9795. case '\r': return "\\r";
  9796. case '\t': return "\\t";
  9797. default: return NULL;
  9798. }
  9799. }
  9800. /* Write a properly escaped string chunk. The surrounding quotes are *not*
  9801. * printed; this is so that the caller has the option of emitting the string
  9802. * content in chunks. */
  9803. static void putstring(upb_json_printer *p, const char *buf, unsigned int len) {
  9804. const char* unescaped_run = NULL;
  9805. unsigned int i;
  9806. for (i = 0; i < len; i++) {
  9807. char c = buf[i];
  9808. /* Handle escaping. */
  9809. if (is_json_escaped(c)) {
  9810. /* Use a "nice" escape, like \n, if one exists for this character. */
  9811. const char* escape = json_nice_escape(c);
  9812. /* If we don't have a specific 'nice' escape code, use a \uXXXX-style
  9813. * escape. */
  9814. char escape_buf[8];
  9815. if (!escape) {
  9816. unsigned char byte = (unsigned char)c;
  9817. _upb_snprintf(escape_buf, sizeof(escape_buf), "\\u%04x", (int)byte);
  9818. escape = escape_buf;
  9819. }
  9820. /* N.B. that we assume that the input encoding is equal to the output
  9821. * encoding (both UTF-8 for now), so for chars >= 0x20 and != \, ", we
  9822. * can simply pass the bytes through. */
  9823. /* If there's a current run of unescaped chars, print that run first. */
  9824. if (unescaped_run) {
  9825. print_data(p, unescaped_run, &buf[i] - unescaped_run);
  9826. unescaped_run = NULL;
  9827. }
  9828. /* Then print the escape code. */
  9829. print_data(p, escape, strlen(escape));
  9830. } else {
  9831. /* Add to the current unescaped run of characters. */
  9832. if (unescaped_run == NULL) {
  9833. unescaped_run = &buf[i];
  9834. }
  9835. }
  9836. }
  9837. /* If the string ended in a run of unescaped characters, print that last run. */
  9838. if (unescaped_run) {
  9839. print_data(p, unescaped_run, &buf[len] - unescaped_run);
  9840. }
  9841. }
  9842. #define CHKLENGTH(x) if (!(x)) return -1;
  9843. /* Helpers that format floating point values according to our custom formats.
  9844. * Right now we use %.8g and %.17g for float/double, respectively, to match
  9845. * proto2::util::JsonFormat's defaults. May want to change this later. */
  9846. static size_t fmt_double(double val, char* buf, size_t length) {
  9847. size_t n = _upb_snprintf(buf, length, "%.17g", val);
  9848. CHKLENGTH(n > 0 && n < length);
  9849. return n;
  9850. }
  9851. static size_t fmt_float(float val, char* buf, size_t length) {
  9852. size_t n = _upb_snprintf(buf, length, "%.8g", val);
  9853. CHKLENGTH(n > 0 && n < length);
  9854. return n;
  9855. }
  9856. static size_t fmt_bool(bool val, char* buf, size_t length) {
  9857. size_t n = _upb_snprintf(buf, length, "%s", (val ? "true" : "false"));
  9858. CHKLENGTH(n > 0 && n < length);
  9859. return n;
  9860. }
  9861. static size_t fmt_int64(long val, char* buf, size_t length) {
  9862. size_t n = _upb_snprintf(buf, length, "%ld", val);
  9863. CHKLENGTH(n > 0 && n < length);
  9864. return n;
  9865. }
  9866. static size_t fmt_uint64(unsigned long long val, char* buf, size_t length) {
  9867. size_t n = _upb_snprintf(buf, length, "%llu", val);
  9868. CHKLENGTH(n > 0 && n < length);
  9869. return n;
  9870. }
  9871. /* Print a map key given a field name. Called by scalar field handlers and by
  9872. * startseq for repeated fields. */
  9873. static bool putkey(void *closure, const void *handler_data) {
  9874. upb_json_printer *p = closure;
  9875. const strpc *key = handler_data;
  9876. print_comma(p);
  9877. print_data(p, "\"", 1);
  9878. putstring(p, key->ptr, key->len);
  9879. print_data(p, "\":", 2);
  9880. return true;
  9881. }
  9882. #define CHKFMT(val) if ((val) == (size_t)-1) return false;
  9883. #define CHK(val) if (!(val)) return false;
  9884. #define TYPE_HANDLERS(type, fmt_func) \
  9885. static bool put##type(void *closure, const void *handler_data, type val) { \
  9886. upb_json_printer *p = closure; \
  9887. char data[64]; \
  9888. size_t length = fmt_func(val, data, sizeof(data)); \
  9889. UPB_UNUSED(handler_data); \
  9890. CHKFMT(length); \
  9891. print_data(p, data, length); \
  9892. return true; \
  9893. } \
  9894. static bool scalar_##type(void *closure, const void *handler_data, \
  9895. type val) { \
  9896. CHK(putkey(closure, handler_data)); \
  9897. CHK(put##type(closure, handler_data, val)); \
  9898. return true; \
  9899. } \
  9900. static bool repeated_##type(void *closure, const void *handler_data, \
  9901. type val) { \
  9902. upb_json_printer *p = closure; \
  9903. print_comma(p); \
  9904. CHK(put##type(closure, handler_data, val)); \
  9905. return true; \
  9906. }
  9907. #define TYPE_HANDLERS_MAPKEY(type, fmt_func) \
  9908. static bool putmapkey_##type(void *closure, const void *handler_data, \
  9909. type val) { \
  9910. upb_json_printer *p = closure; \
  9911. print_data(p, "\"", 1); \
  9912. CHK(put##type(closure, handler_data, val)); \
  9913. print_data(p, "\":", 2); \
  9914. return true; \
  9915. }
  9916. TYPE_HANDLERS(double, fmt_double)
  9917. TYPE_HANDLERS(float, fmt_float)
  9918. TYPE_HANDLERS(bool, fmt_bool)
  9919. TYPE_HANDLERS(int32_t, fmt_int64)
  9920. TYPE_HANDLERS(uint32_t, fmt_int64)
  9921. TYPE_HANDLERS(int64_t, fmt_int64)
  9922. TYPE_HANDLERS(uint64_t, fmt_uint64)
  9923. /* double and float are not allowed to be map keys. */
  9924. TYPE_HANDLERS_MAPKEY(bool, fmt_bool)
  9925. TYPE_HANDLERS_MAPKEY(int32_t, fmt_int64)
  9926. TYPE_HANDLERS_MAPKEY(uint32_t, fmt_int64)
  9927. TYPE_HANDLERS_MAPKEY(int64_t, fmt_int64)
  9928. TYPE_HANDLERS_MAPKEY(uint64_t, fmt_uint64)
  9929. #undef TYPE_HANDLERS
  9930. #undef TYPE_HANDLERS_MAPKEY
  9931. typedef struct {
  9932. void *keyname;
  9933. const upb_enumdef *enumdef;
  9934. } EnumHandlerData;
  9935. static bool scalar_enum(void *closure, const void *handler_data,
  9936. int32_t val) {
  9937. const EnumHandlerData *hd = handler_data;
  9938. upb_json_printer *p = closure;
  9939. const char *symbolic_name;
  9940. CHK(putkey(closure, hd->keyname));
  9941. symbolic_name = upb_enumdef_iton(hd->enumdef, val);
  9942. if (symbolic_name) {
  9943. print_data(p, "\"", 1);
  9944. putstring(p, symbolic_name, strlen(symbolic_name));
  9945. print_data(p, "\"", 1);
  9946. } else {
  9947. putint32_t(closure, NULL, val);
  9948. }
  9949. return true;
  9950. }
  9951. static void print_enum_symbolic_name(upb_json_printer *p,
  9952. const upb_enumdef *def,
  9953. int32_t val) {
  9954. const char *symbolic_name = upb_enumdef_iton(def, val);
  9955. if (symbolic_name) {
  9956. print_data(p, "\"", 1);
  9957. putstring(p, symbolic_name, strlen(symbolic_name));
  9958. print_data(p, "\"", 1);
  9959. } else {
  9960. putint32_t(p, NULL, val);
  9961. }
  9962. }
  9963. static bool repeated_enum(void *closure, const void *handler_data,
  9964. int32_t val) {
  9965. const EnumHandlerData *hd = handler_data;
  9966. upb_json_printer *p = closure;
  9967. print_comma(p);
  9968. print_enum_symbolic_name(p, hd->enumdef, val);
  9969. return true;
  9970. }
  9971. static bool mapvalue_enum(void *closure, const void *handler_data,
  9972. int32_t val) {
  9973. const EnumHandlerData *hd = handler_data;
  9974. upb_json_printer *p = closure;
  9975. print_enum_symbolic_name(p, hd->enumdef, val);
  9976. return true;
  9977. }
  9978. static void *scalar_startsubmsg(void *closure, const void *handler_data) {
  9979. return putkey(closure, handler_data) ? closure : UPB_BREAK;
  9980. }
  9981. static void *repeated_startsubmsg(void *closure, const void *handler_data) {
  9982. upb_json_printer *p = closure;
  9983. UPB_UNUSED(handler_data);
  9984. print_comma(p);
  9985. return closure;
  9986. }
  9987. static void start_frame(upb_json_printer *p) {
  9988. p->depth_++;
  9989. p->first_elem_[p->depth_] = true;
  9990. print_data(p, "{", 1);
  9991. }
  9992. static void end_frame(upb_json_printer *p) {
  9993. print_data(p, "}", 1);
  9994. p->depth_--;
  9995. }
  9996. static bool printer_startmsg(void *closure, const void *handler_data) {
  9997. upb_json_printer *p = closure;
  9998. UPB_UNUSED(handler_data);
  9999. if (p->depth_ == 0) {
  10000. upb_bytessink_start(p->output_, 0, &p->subc_);
  10001. }
  10002. start_frame(p);
  10003. return true;
  10004. }
  10005. static bool printer_endmsg(void *closure, const void *handler_data, upb_status *s) {
  10006. upb_json_printer *p = closure;
  10007. UPB_UNUSED(handler_data);
  10008. UPB_UNUSED(s);
  10009. end_frame(p);
  10010. if (p->depth_ == 0) {
  10011. upb_bytessink_end(p->output_);
  10012. }
  10013. return true;
  10014. }
  10015. static void *startseq(void *closure, const void *handler_data) {
  10016. upb_json_printer *p = closure;
  10017. CHK(putkey(closure, handler_data));
  10018. p->depth_++;
  10019. p->first_elem_[p->depth_] = true;
  10020. print_data(p, "[", 1);
  10021. return closure;
  10022. }
  10023. static bool endseq(void *closure, const void *handler_data) {
  10024. upb_json_printer *p = closure;
  10025. UPB_UNUSED(handler_data);
  10026. print_data(p, "]", 1);
  10027. p->depth_--;
  10028. return true;
  10029. }
  10030. static void *startmap(void *closure, const void *handler_data) {
  10031. upb_json_printer *p = closure;
  10032. CHK(putkey(closure, handler_data));
  10033. p->depth_++;
  10034. p->first_elem_[p->depth_] = true;
  10035. print_data(p, "{", 1);
  10036. return closure;
  10037. }
  10038. static bool endmap(void *closure, const void *handler_data) {
  10039. upb_json_printer *p = closure;
  10040. UPB_UNUSED(handler_data);
  10041. print_data(p, "}", 1);
  10042. p->depth_--;
  10043. return true;
  10044. }
  10045. static size_t putstr(void *closure, const void *handler_data, const char *str,
  10046. size_t len, const upb_bufhandle *handle) {
  10047. upb_json_printer *p = closure;
  10048. UPB_UNUSED(handler_data);
  10049. UPB_UNUSED(handle);
  10050. putstring(p, str, len);
  10051. return len;
  10052. }
  10053. /* This has to Base64 encode the bytes, because JSON has no "bytes" type. */
  10054. static size_t putbytes(void *closure, const void *handler_data, const char *str,
  10055. size_t len, const upb_bufhandle *handle) {
  10056. upb_json_printer *p = closure;
  10057. /* This is the regular base64, not the "web-safe" version. */
  10058. static const char base64[] =
  10059. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  10060. /* Base64-encode. */
  10061. char data[16000];
  10062. const char *limit = data + sizeof(data);
  10063. const unsigned char *from = (const unsigned char*)str;
  10064. char *to = data;
  10065. size_t remaining = len;
  10066. size_t bytes;
  10067. UPB_UNUSED(handler_data);
  10068. UPB_UNUSED(handle);
  10069. while (remaining > 2) {
  10070. /* TODO(haberman): handle encoded lengths > sizeof(data) */
  10071. UPB_ASSERT_VAR(limit, (limit - to) >= 4);
  10072. to[0] = base64[from[0] >> 2];
  10073. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  10074. to[2] = base64[((from[1] & 0xf) << 2) | (from[2] >> 6)];
  10075. to[3] = base64[from[2] & 0x3f];
  10076. remaining -= 3;
  10077. to += 4;
  10078. from += 3;
  10079. }
  10080. switch (remaining) {
  10081. case 2:
  10082. to[0] = base64[from[0] >> 2];
  10083. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  10084. to[2] = base64[(from[1] & 0xf) << 2];
  10085. to[3] = '=';
  10086. to += 4;
  10087. from += 2;
  10088. break;
  10089. case 1:
  10090. to[0] = base64[from[0] >> 2];
  10091. to[1] = base64[((from[0] & 0x3) << 4)];
  10092. to[2] = '=';
  10093. to[3] = '=';
  10094. to += 4;
  10095. from += 1;
  10096. break;
  10097. }
  10098. bytes = to - data;
  10099. print_data(p, "\"", 1);
  10100. putstring(p, data, bytes);
  10101. print_data(p, "\"", 1);
  10102. return len;
  10103. }
  10104. static void *scalar_startstr(void *closure, const void *handler_data,
  10105. size_t size_hint) {
  10106. upb_json_printer *p = closure;
  10107. UPB_UNUSED(handler_data);
  10108. UPB_UNUSED(size_hint);
  10109. CHK(putkey(closure, handler_data));
  10110. print_data(p, "\"", 1);
  10111. return p;
  10112. }
  10113. static size_t scalar_str(void *closure, const void *handler_data,
  10114. const char *str, size_t len,
  10115. const upb_bufhandle *handle) {
  10116. CHK(putstr(closure, handler_data, str, len, handle));
  10117. return len;
  10118. }
  10119. static bool scalar_endstr(void *closure, const void *handler_data) {
  10120. upb_json_printer *p = closure;
  10121. UPB_UNUSED(handler_data);
  10122. print_data(p, "\"", 1);
  10123. return true;
  10124. }
  10125. static void *repeated_startstr(void *closure, const void *handler_data,
  10126. size_t size_hint) {
  10127. upb_json_printer *p = closure;
  10128. UPB_UNUSED(handler_data);
  10129. UPB_UNUSED(size_hint);
  10130. print_comma(p);
  10131. print_data(p, "\"", 1);
  10132. return p;
  10133. }
  10134. static size_t repeated_str(void *closure, const void *handler_data,
  10135. const char *str, size_t len,
  10136. const upb_bufhandle *handle) {
  10137. CHK(putstr(closure, handler_data, str, len, handle));
  10138. return len;
  10139. }
  10140. static bool repeated_endstr(void *closure, const void *handler_data) {
  10141. upb_json_printer *p = closure;
  10142. UPB_UNUSED(handler_data);
  10143. print_data(p, "\"", 1);
  10144. return true;
  10145. }
  10146. static void *mapkeyval_startstr(void *closure, const void *handler_data,
  10147. size_t size_hint) {
  10148. upb_json_printer *p = closure;
  10149. UPB_UNUSED(handler_data);
  10150. UPB_UNUSED(size_hint);
  10151. print_data(p, "\"", 1);
  10152. return p;
  10153. }
  10154. static size_t mapkey_str(void *closure, const void *handler_data,
  10155. const char *str, size_t len,
  10156. const upb_bufhandle *handle) {
  10157. CHK(putstr(closure, handler_data, str, len, handle));
  10158. return len;
  10159. }
  10160. static bool mapkey_endstr(void *closure, const void *handler_data) {
  10161. upb_json_printer *p = closure;
  10162. UPB_UNUSED(handler_data);
  10163. print_data(p, "\":", 2);
  10164. return true;
  10165. }
  10166. static bool mapvalue_endstr(void *closure, const void *handler_data) {
  10167. upb_json_printer *p = closure;
  10168. UPB_UNUSED(handler_data);
  10169. print_data(p, "\"", 1);
  10170. return true;
  10171. }
  10172. static size_t scalar_bytes(void *closure, const void *handler_data,
  10173. const char *str, size_t len,
  10174. const upb_bufhandle *handle) {
  10175. CHK(putkey(closure, handler_data));
  10176. CHK(putbytes(closure, handler_data, str, len, handle));
  10177. return len;
  10178. }
  10179. static size_t repeated_bytes(void *closure, const void *handler_data,
  10180. const char *str, size_t len,
  10181. const upb_bufhandle *handle) {
  10182. upb_json_printer *p = closure;
  10183. print_comma(p);
  10184. CHK(putbytes(closure, handler_data, str, len, handle));
  10185. return len;
  10186. }
  10187. static size_t mapkey_bytes(void *closure, const void *handler_data,
  10188. const char *str, size_t len,
  10189. const upb_bufhandle *handle) {
  10190. upb_json_printer *p = closure;
  10191. CHK(putbytes(closure, handler_data, str, len, handle));
  10192. print_data(p, ":", 1);
  10193. return len;
  10194. }
  10195. static void set_enum_hd(upb_handlers *h,
  10196. const upb_fielddef *f,
  10197. upb_handlerattr *attr) {
  10198. EnumHandlerData *hd = malloc(sizeof(EnumHandlerData));
  10199. hd->enumdef = (const upb_enumdef *)upb_fielddef_subdef(f);
  10200. hd->keyname = newstrpc(h, f);
  10201. upb_handlers_addcleanup(h, hd, free);
  10202. upb_handlerattr_sethandlerdata(attr, hd);
  10203. }
  10204. /* Set up handlers for a mapentry submessage (i.e., an individual key/value pair
  10205. * in a map).
  10206. *
  10207. * TODO: Handle missing key, missing value, out-of-order key/value, or repeated
  10208. * key or value cases properly. The right way to do this is to allocate a
  10209. * temporary structure at the start of a mapentry submessage, store key and
  10210. * value data in it as key and value handlers are called, and then print the
  10211. * key/value pair once at the end of the submessage. If we don't do this, we
  10212. * should at least detect the case and throw an error. However, so far all of
  10213. * our sources that emit mapentry messages do so canonically (with one key
  10214. * field, and then one value field), so this is not a pressing concern at the
  10215. * moment. */
  10216. void printer_sethandlers_mapentry(const void *closure, upb_handlers *h) {
  10217. const upb_msgdef *md = upb_handlers_msgdef(h);
  10218. /* A mapentry message is printed simply as '"key": value'. Rather than
  10219. * special-case key and value for every type below, we just handle both
  10220. * fields explicitly here. */
  10221. const upb_fielddef* key_field = upb_msgdef_itof(md, UPB_MAPENTRY_KEY);
  10222. const upb_fielddef* value_field = upb_msgdef_itof(md, UPB_MAPENTRY_VALUE);
  10223. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  10224. UPB_UNUSED(closure);
  10225. switch (upb_fielddef_type(key_field)) {
  10226. case UPB_TYPE_INT32:
  10227. upb_handlers_setint32(h, key_field, putmapkey_int32_t, &empty_attr);
  10228. break;
  10229. case UPB_TYPE_INT64:
  10230. upb_handlers_setint64(h, key_field, putmapkey_int64_t, &empty_attr);
  10231. break;
  10232. case UPB_TYPE_UINT32:
  10233. upb_handlers_setuint32(h, key_field, putmapkey_uint32_t, &empty_attr);
  10234. break;
  10235. case UPB_TYPE_UINT64:
  10236. upb_handlers_setuint64(h, key_field, putmapkey_uint64_t, &empty_attr);
  10237. break;
  10238. case UPB_TYPE_BOOL:
  10239. upb_handlers_setbool(h, key_field, putmapkey_bool, &empty_attr);
  10240. break;
  10241. case UPB_TYPE_STRING:
  10242. upb_handlers_setstartstr(h, key_field, mapkeyval_startstr, &empty_attr);
  10243. upb_handlers_setstring(h, key_field, mapkey_str, &empty_attr);
  10244. upb_handlers_setendstr(h, key_field, mapkey_endstr, &empty_attr);
  10245. break;
  10246. case UPB_TYPE_BYTES:
  10247. upb_handlers_setstring(h, key_field, mapkey_bytes, &empty_attr);
  10248. break;
  10249. default:
  10250. assert(false);
  10251. break;
  10252. }
  10253. switch (upb_fielddef_type(value_field)) {
  10254. case UPB_TYPE_INT32:
  10255. upb_handlers_setint32(h, value_field, putint32_t, &empty_attr);
  10256. break;
  10257. case UPB_TYPE_INT64:
  10258. upb_handlers_setint64(h, value_field, putint64_t, &empty_attr);
  10259. break;
  10260. case UPB_TYPE_UINT32:
  10261. upb_handlers_setuint32(h, value_field, putuint32_t, &empty_attr);
  10262. break;
  10263. case UPB_TYPE_UINT64:
  10264. upb_handlers_setuint64(h, value_field, putuint64_t, &empty_attr);
  10265. break;
  10266. case UPB_TYPE_BOOL:
  10267. upb_handlers_setbool(h, value_field, putbool, &empty_attr);
  10268. break;
  10269. case UPB_TYPE_FLOAT:
  10270. upb_handlers_setfloat(h, value_field, putfloat, &empty_attr);
  10271. break;
  10272. case UPB_TYPE_DOUBLE:
  10273. upb_handlers_setdouble(h, value_field, putdouble, &empty_attr);
  10274. break;
  10275. case UPB_TYPE_STRING:
  10276. upb_handlers_setstartstr(h, value_field, mapkeyval_startstr, &empty_attr);
  10277. upb_handlers_setstring(h, value_field, putstr, &empty_attr);
  10278. upb_handlers_setendstr(h, value_field, mapvalue_endstr, &empty_attr);
  10279. break;
  10280. case UPB_TYPE_BYTES:
  10281. upb_handlers_setstring(h, value_field, putbytes, &empty_attr);
  10282. break;
  10283. case UPB_TYPE_ENUM: {
  10284. upb_handlerattr enum_attr = UPB_HANDLERATTR_INITIALIZER;
  10285. set_enum_hd(h, value_field, &enum_attr);
  10286. upb_handlers_setint32(h, value_field, mapvalue_enum, &enum_attr);
  10287. upb_handlerattr_uninit(&enum_attr);
  10288. break;
  10289. }
  10290. case UPB_TYPE_MESSAGE:
  10291. /* No handler necessary -- the submsg handlers will print the message
  10292. * as appropriate. */
  10293. break;
  10294. }
  10295. upb_handlerattr_uninit(&empty_attr);
  10296. }
  10297. void printer_sethandlers(const void *closure, upb_handlers *h) {
  10298. const upb_msgdef *md = upb_handlers_msgdef(h);
  10299. bool is_mapentry = upb_msgdef_mapentry(md);
  10300. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  10301. upb_msg_field_iter i;
  10302. UPB_UNUSED(closure);
  10303. if (is_mapentry) {
  10304. /* mapentry messages are sufficiently different that we handle them
  10305. * separately. */
  10306. printer_sethandlers_mapentry(closure, h);
  10307. return;
  10308. }
  10309. upb_handlers_setstartmsg(h, printer_startmsg, &empty_attr);
  10310. upb_handlers_setendmsg(h, printer_endmsg, &empty_attr);
  10311. #define TYPE(type, name, ctype) \
  10312. case type: \
  10313. if (upb_fielddef_isseq(f)) { \
  10314. upb_handlers_set##name(h, f, repeated_##ctype, &empty_attr); \
  10315. } else { \
  10316. upb_handlers_set##name(h, f, scalar_##ctype, &name_attr); \
  10317. } \
  10318. break;
  10319. upb_msg_field_begin(&i, md);
  10320. for(; !upb_msg_field_done(&i); upb_msg_field_next(&i)) {
  10321. const upb_fielddef *f = upb_msg_iter_field(&i);
  10322. upb_handlerattr name_attr = UPB_HANDLERATTR_INITIALIZER;
  10323. upb_handlerattr_sethandlerdata(&name_attr, newstrpc(h, f));
  10324. if (upb_fielddef_ismap(f)) {
  10325. upb_handlers_setstartseq(h, f, startmap, &name_attr);
  10326. upb_handlers_setendseq(h, f, endmap, &name_attr);
  10327. } else if (upb_fielddef_isseq(f)) {
  10328. upb_handlers_setstartseq(h, f, startseq, &name_attr);
  10329. upb_handlers_setendseq(h, f, endseq, &empty_attr);
  10330. }
  10331. switch (upb_fielddef_type(f)) {
  10332. TYPE(UPB_TYPE_FLOAT, float, float);
  10333. TYPE(UPB_TYPE_DOUBLE, double, double);
  10334. TYPE(UPB_TYPE_BOOL, bool, bool);
  10335. TYPE(UPB_TYPE_INT32, int32, int32_t);
  10336. TYPE(UPB_TYPE_UINT32, uint32, uint32_t);
  10337. TYPE(UPB_TYPE_INT64, int64, int64_t);
  10338. TYPE(UPB_TYPE_UINT64, uint64, uint64_t);
  10339. case UPB_TYPE_ENUM: {
  10340. /* For now, we always emit symbolic names for enums. We may want an
  10341. * option later to control this behavior, but we will wait for a real
  10342. * need first. */
  10343. upb_handlerattr enum_attr = UPB_HANDLERATTR_INITIALIZER;
  10344. set_enum_hd(h, f, &enum_attr);
  10345. if (upb_fielddef_isseq(f)) {
  10346. upb_handlers_setint32(h, f, repeated_enum, &enum_attr);
  10347. } else {
  10348. upb_handlers_setint32(h, f, scalar_enum, &enum_attr);
  10349. }
  10350. upb_handlerattr_uninit(&enum_attr);
  10351. break;
  10352. }
  10353. case UPB_TYPE_STRING:
  10354. if (upb_fielddef_isseq(f)) {
  10355. upb_handlers_setstartstr(h, f, repeated_startstr, &empty_attr);
  10356. upb_handlers_setstring(h, f, repeated_str, &empty_attr);
  10357. upb_handlers_setendstr(h, f, repeated_endstr, &empty_attr);
  10358. } else {
  10359. upb_handlers_setstartstr(h, f, scalar_startstr, &name_attr);
  10360. upb_handlers_setstring(h, f, scalar_str, &empty_attr);
  10361. upb_handlers_setendstr(h, f, scalar_endstr, &empty_attr);
  10362. }
  10363. break;
  10364. case UPB_TYPE_BYTES:
  10365. /* XXX: this doesn't support strings that span buffers yet. The base64
  10366. * encoder will need to be made resumable for this to work properly. */
  10367. if (upb_fielddef_isseq(f)) {
  10368. upb_handlers_setstring(h, f, repeated_bytes, &empty_attr);
  10369. } else {
  10370. upb_handlers_setstring(h, f, scalar_bytes, &name_attr);
  10371. }
  10372. break;
  10373. case UPB_TYPE_MESSAGE:
  10374. if (upb_fielddef_isseq(f)) {
  10375. upb_handlers_setstartsubmsg(h, f, repeated_startsubmsg, &name_attr);
  10376. } else {
  10377. upb_handlers_setstartsubmsg(h, f, scalar_startsubmsg, &name_attr);
  10378. }
  10379. break;
  10380. }
  10381. upb_handlerattr_uninit(&name_attr);
  10382. }
  10383. upb_handlerattr_uninit(&empty_attr);
  10384. #undef TYPE
  10385. }
  10386. static void json_printer_reset(upb_json_printer *p) {
  10387. p->depth_ = 0;
  10388. }
  10389. /* Public API *****************************************************************/
  10390. upb_json_printer *upb_json_printer_create(upb_env *e, const upb_handlers *h,
  10391. upb_bytessink *output) {
  10392. #ifndef NDEBUG
  10393. size_t size_before = upb_env_bytesallocated(e);
  10394. #endif
  10395. upb_json_printer *p = upb_env_malloc(e, sizeof(upb_json_printer));
  10396. if (!p) return NULL;
  10397. p->output_ = output;
  10398. json_printer_reset(p);
  10399. upb_sink_reset(&p->input_, h, p);
  10400. /* If this fails, increase the value in printer.h. */
  10401. assert(upb_env_bytesallocated(e) - size_before <= UPB_JSON_PRINTER_SIZE);
  10402. return p;
  10403. }
  10404. upb_sink *upb_json_printer_input(upb_json_printer *p) {
  10405. return &p->input_;
  10406. }
  10407. const upb_handlers *upb_json_printer_newhandlers(const upb_msgdef *md,
  10408. const void *owner) {
  10409. return upb_handlers_newfrozen(md, owner, printer_sethandlers, NULL);
  10410. }