upb.c 424 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812
  1. // Amalgamated source file
  2. #include "upb.h"
  3. #include <ctype.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. typedef struct {
  7. size_t len;
  8. char str[1]; /* Null-terminated string data follows. */
  9. } str_t;
  10. static str_t *newstr(const char *data, size_t len) {
  11. str_t *ret = upb_gmalloc(sizeof(*ret) + len);
  12. if (!ret) return NULL;
  13. ret->len = len;
  14. memcpy(ret->str, data, len);
  15. ret->str[len] = '\0';
  16. return ret;
  17. }
  18. static void freestr(str_t *s) { upb_gfree(s); }
  19. /* isalpha() etc. from <ctype.h> are locale-dependent, which we don't want. */
  20. static bool upb_isbetween(char c, char low, char high) {
  21. return c >= low && c <= high;
  22. }
  23. static bool upb_isletter(char c) {
  24. return upb_isbetween(c, 'A', 'Z') || upb_isbetween(c, 'a', 'z') || c == '_';
  25. }
  26. static bool upb_isalphanum(char c) {
  27. return upb_isletter(c) || upb_isbetween(c, '0', '9');
  28. }
  29. static bool upb_isident(const char *str, size_t len, bool full, upb_status *s) {
  30. bool start = true;
  31. size_t i;
  32. for (i = 0; i < len; i++) {
  33. char c = str[i];
  34. if (c == '.') {
  35. if (start || !full) {
  36. upb_status_seterrf(s, "invalid name: unexpected '.' (%s)", str);
  37. return false;
  38. }
  39. start = true;
  40. } else if (start) {
  41. if (!upb_isletter(c)) {
  42. upb_status_seterrf(
  43. s, "invalid name: path components must start with a letter (%s)",
  44. str);
  45. return false;
  46. }
  47. start = false;
  48. } else {
  49. if (!upb_isalphanum(c)) {
  50. upb_status_seterrf(s, "invalid name: non-alphanumeric character (%s)",
  51. str);
  52. return false;
  53. }
  54. }
  55. }
  56. return !start;
  57. }
  58. static bool upb_isoneof(const upb_refcounted *def) {
  59. return def->vtbl == &upb_oneofdef_vtbl;
  60. }
  61. static bool upb_isfield(const upb_refcounted *def) {
  62. return def->vtbl == &upb_fielddef_vtbl;
  63. }
  64. static const upb_oneofdef *upb_trygetoneof(const upb_refcounted *def) {
  65. return upb_isoneof(def) ? (const upb_oneofdef*)def : NULL;
  66. }
  67. static const upb_fielddef *upb_trygetfield(const upb_refcounted *def) {
  68. return upb_isfield(def) ? (const upb_fielddef*)def : NULL;
  69. }
  70. /* upb_def ********************************************************************/
  71. upb_deftype_t upb_def_type(const upb_def *d) { return d->type; }
  72. const char *upb_def_fullname(const upb_def *d) { return d->fullname; }
  73. const char *upb_def_name(const upb_def *d) {
  74. const char *p;
  75. if (d->fullname == NULL) {
  76. return NULL;
  77. } else if ((p = strrchr(d->fullname, '.')) == NULL) {
  78. /* No '.' in the name, return the full string. */
  79. return d->fullname;
  80. } else {
  81. /* Return one past the last '.'. */
  82. return p + 1;
  83. }
  84. }
  85. bool upb_def_setfullname(upb_def *def, const char *fullname, upb_status *s) {
  86. assert(!upb_def_isfrozen(def));
  87. if (!upb_isident(fullname, strlen(fullname), true, s)) {
  88. return false;
  89. }
  90. fullname = upb_gstrdup(fullname);
  91. if (!fullname) {
  92. upb_upberr_setoom(s);
  93. return false;
  94. }
  95. upb_gfree((void*)def->fullname);
  96. def->fullname = fullname;
  97. return true;
  98. }
  99. const upb_filedef *upb_def_file(const upb_def *d) { return d->file; }
  100. upb_def *upb_def_dup(const upb_def *def, const void *o) {
  101. switch (def->type) {
  102. case UPB_DEF_MSG:
  103. return upb_msgdef_upcast_mutable(
  104. upb_msgdef_dup(upb_downcast_msgdef(def), o));
  105. case UPB_DEF_FIELD:
  106. return upb_fielddef_upcast_mutable(
  107. upb_fielddef_dup(upb_downcast_fielddef(def), o));
  108. case UPB_DEF_ENUM:
  109. return upb_enumdef_upcast_mutable(
  110. upb_enumdef_dup(upb_downcast_enumdef(def), o));
  111. default: assert(false); return NULL;
  112. }
  113. }
  114. static bool upb_def_init(upb_def *def, upb_deftype_t type,
  115. const struct upb_refcounted_vtbl *vtbl,
  116. const void *owner) {
  117. if (!upb_refcounted_init(upb_def_upcast_mutable(def), vtbl, owner)) return false;
  118. def->type = type;
  119. def->fullname = NULL;
  120. def->came_from_user = false;
  121. def->file = NULL;
  122. return true;
  123. }
  124. static void upb_def_uninit(upb_def *def) {
  125. upb_gfree((void*)def->fullname);
  126. }
  127. static const char *msgdef_name(const upb_msgdef *m) {
  128. const char *name = upb_def_fullname(upb_msgdef_upcast(m));
  129. return name ? name : "(anonymous)";
  130. }
  131. static bool upb_validate_field(upb_fielddef *f, upb_status *s) {
  132. if (upb_fielddef_name(f) == NULL || upb_fielddef_number(f) == 0) {
  133. upb_status_seterrmsg(s, "fielddef must have name and number set");
  134. return false;
  135. }
  136. if (!f->type_is_set_) {
  137. upb_status_seterrmsg(s, "fielddef type was not initialized");
  138. return false;
  139. }
  140. if (upb_fielddef_lazy(f) &&
  141. upb_fielddef_descriptortype(f) != UPB_DESCRIPTOR_TYPE_MESSAGE) {
  142. upb_status_seterrmsg(s,
  143. "only length-delimited submessage fields may be lazy");
  144. return false;
  145. }
  146. if (upb_fielddef_hassubdef(f)) {
  147. const upb_def *subdef;
  148. if (f->subdef_is_symbolic) {
  149. upb_status_seterrf(s, "field '%s.%s' has not been resolved",
  150. msgdef_name(f->msg.def), upb_fielddef_name(f));
  151. return false;
  152. }
  153. subdef = upb_fielddef_subdef(f);
  154. if (subdef == NULL) {
  155. upb_status_seterrf(s, "field %s.%s is missing required subdef",
  156. msgdef_name(f->msg.def), upb_fielddef_name(f));
  157. return false;
  158. }
  159. if (!upb_def_isfrozen(subdef) && !subdef->came_from_user) {
  160. upb_status_seterrf(s,
  161. "subdef of field %s.%s is not frozen or being frozen",
  162. msgdef_name(f->msg.def), upb_fielddef_name(f));
  163. return false;
  164. }
  165. }
  166. if (upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  167. bool has_default_name = upb_fielddef_enumhasdefaultstr(f);
  168. bool has_default_number = upb_fielddef_enumhasdefaultint32(f);
  169. /* Previously verified by upb_validate_enumdef(). */
  170. assert(upb_enumdef_numvals(upb_fielddef_enumsubdef(f)) > 0);
  171. /* We've already validated that we have an associated enumdef and that it
  172. * has at least one member, so at least one of these should be true.
  173. * Because if the user didn't set anything, we'll pick up the enum's
  174. * default, but if the user *did* set something we should at least pick up
  175. * the one they set (int32 or string). */
  176. assert(has_default_name || has_default_number);
  177. if (!has_default_name) {
  178. upb_status_seterrf(s,
  179. "enum default for field %s.%s (%d) is not in the enum",
  180. msgdef_name(f->msg.def), upb_fielddef_name(f),
  181. upb_fielddef_defaultint32(f));
  182. return false;
  183. }
  184. if (!has_default_number) {
  185. upb_status_seterrf(s,
  186. "enum default for field %s.%s (%s) is not in the enum",
  187. msgdef_name(f->msg.def), upb_fielddef_name(f),
  188. upb_fielddef_defaultstr(f, NULL));
  189. return false;
  190. }
  191. /* Lift the effective numeric default into the field's default slot, in case
  192. * we were only getting it "by reference" from the enumdef. */
  193. upb_fielddef_setdefaultint32(f, upb_fielddef_defaultint32(f));
  194. }
  195. /* Ensure that MapEntry submessages only appear as repeated fields, not
  196. * optional/required (singular) fields. */
  197. if (upb_fielddef_type(f) == UPB_TYPE_MESSAGE &&
  198. upb_fielddef_msgsubdef(f) != NULL) {
  199. const upb_msgdef *subdef = upb_fielddef_msgsubdef(f);
  200. if (upb_msgdef_mapentry(subdef) && !upb_fielddef_isseq(f)) {
  201. upb_status_seterrf(s,
  202. "Field %s refers to mapentry message but is not "
  203. "a repeated field",
  204. upb_fielddef_name(f) ? upb_fielddef_name(f) :
  205. "(unnamed)");
  206. return false;
  207. }
  208. }
  209. return true;
  210. }
  211. static bool upb_validate_enumdef(const upb_enumdef *e, upb_status *s) {
  212. if (upb_enumdef_numvals(e) == 0) {
  213. upb_status_seterrf(s, "enum %s has no members (must have at least one)",
  214. upb_enumdef_fullname(e));
  215. return false;
  216. }
  217. return true;
  218. }
  219. /* All submessage fields are lower than all other fields.
  220. * Secondly, fields are increasing in order. */
  221. uint32_t field_rank(const upb_fielddef *f) {
  222. uint32_t ret = upb_fielddef_number(f);
  223. const uint32_t high_bit = 1 << 30;
  224. assert(ret < high_bit);
  225. if (!upb_fielddef_issubmsg(f))
  226. ret |= high_bit;
  227. return ret;
  228. }
  229. int cmp_fields(const void *p1, const void *p2) {
  230. const upb_fielddef *f1 = *(upb_fielddef*const*)p1;
  231. const upb_fielddef *f2 = *(upb_fielddef*const*)p2;
  232. return field_rank(f1) - field_rank(f2);
  233. }
  234. static bool assign_msg_indices(upb_msgdef *m, upb_status *s) {
  235. /* Sort fields. upb internally relies on UPB_TYPE_MESSAGE fields having the
  236. * lowest indexes, but we do not publicly guarantee this. */
  237. upb_msg_field_iter j;
  238. int i;
  239. uint32_t selector;
  240. int n = upb_msgdef_numfields(m);
  241. upb_fielddef **fields;
  242. if (n == 0) {
  243. m->selector_count = UPB_STATIC_SELECTOR_COUNT;
  244. m->submsg_field_count = 0;
  245. return true;
  246. }
  247. fields = upb_gmalloc(n * sizeof(*fields));
  248. if (!fields) {
  249. upb_upberr_setoom(s);
  250. return false;
  251. }
  252. m->submsg_field_count = 0;
  253. for(i = 0, upb_msg_field_begin(&j, m);
  254. !upb_msg_field_done(&j);
  255. upb_msg_field_next(&j), i++) {
  256. upb_fielddef *f = upb_msg_iter_field(&j);
  257. assert(f->msg.def == m);
  258. if (!upb_validate_field(f, s)) {
  259. upb_gfree(fields);
  260. return false;
  261. }
  262. if (upb_fielddef_issubmsg(f)) {
  263. m->submsg_field_count++;
  264. }
  265. fields[i] = f;
  266. }
  267. qsort(fields, n, sizeof(*fields), cmp_fields);
  268. selector = UPB_STATIC_SELECTOR_COUNT + m->submsg_field_count;
  269. for (i = 0; i < n; i++) {
  270. upb_fielddef *f = fields[i];
  271. f->index_ = i;
  272. f->selector_base = selector + upb_handlers_selectorbaseoffset(f);
  273. selector += upb_handlers_selectorcount(f);
  274. }
  275. m->selector_count = selector;
  276. #ifndef NDEBUG
  277. {
  278. /* Verify that all selectors for the message are distinct. */
  279. #define TRY(type) \
  280. if (upb_handlers_getselector(f, type, &sel)) upb_inttable_insert(&t, sel, v);
  281. upb_inttable t;
  282. upb_value v;
  283. upb_selector_t sel;
  284. upb_inttable_init(&t, UPB_CTYPE_BOOL);
  285. v = upb_value_bool(true);
  286. upb_inttable_insert(&t, UPB_STARTMSG_SELECTOR, v);
  287. upb_inttable_insert(&t, UPB_ENDMSG_SELECTOR, v);
  288. for(upb_msg_field_begin(&j, m);
  289. !upb_msg_field_done(&j);
  290. upb_msg_field_next(&j)) {
  291. upb_fielddef *f = upb_msg_iter_field(&j);
  292. /* These calls will assert-fail in upb_table if the value already
  293. * exists. */
  294. TRY(UPB_HANDLER_INT32);
  295. TRY(UPB_HANDLER_INT64)
  296. TRY(UPB_HANDLER_UINT32)
  297. TRY(UPB_HANDLER_UINT64)
  298. TRY(UPB_HANDLER_FLOAT)
  299. TRY(UPB_HANDLER_DOUBLE)
  300. TRY(UPB_HANDLER_BOOL)
  301. TRY(UPB_HANDLER_STARTSTR)
  302. TRY(UPB_HANDLER_STRING)
  303. TRY(UPB_HANDLER_ENDSTR)
  304. TRY(UPB_HANDLER_STARTSUBMSG)
  305. TRY(UPB_HANDLER_ENDSUBMSG)
  306. TRY(UPB_HANDLER_STARTSEQ)
  307. TRY(UPB_HANDLER_ENDSEQ)
  308. }
  309. upb_inttable_uninit(&t);
  310. }
  311. #undef TRY
  312. #endif
  313. upb_gfree(fields);
  314. return true;
  315. }
  316. bool _upb_def_validate(upb_def *const*defs, size_t n, upb_status *s) {
  317. size_t i;
  318. /* First perform validation, in two passes so we can check that we have a
  319. * transitive closure without needing to search. */
  320. for (i = 0; i < n; i++) {
  321. upb_def *def = defs[i];
  322. if (upb_def_isfrozen(def)) {
  323. /* Could relax this requirement if it's annoying. */
  324. upb_status_seterrmsg(s, "def is already frozen");
  325. goto err;
  326. } else if (def->type == UPB_DEF_FIELD) {
  327. upb_status_seterrmsg(s, "standalone fielddefs can not be frozen");
  328. goto err;
  329. } else if (def->type == UPB_DEF_ENUM) {
  330. if (!upb_validate_enumdef(upb_dyncast_enumdef(def), s)) {
  331. goto err;
  332. }
  333. } else {
  334. /* Set now to detect transitive closure in the second pass. */
  335. def->came_from_user = true;
  336. }
  337. }
  338. /* Second pass of validation. Also assign selector bases and indexes, and
  339. * compact tables. */
  340. for (i = 0; i < n; i++) {
  341. upb_def *def = defs[i];
  342. upb_msgdef *m = upb_dyncast_msgdef_mutable(def);
  343. upb_enumdef *e = upb_dyncast_enumdef_mutable(def);
  344. if (m) {
  345. upb_inttable_compact(&m->itof);
  346. if (!assign_msg_indices(m, s)) {
  347. goto err;
  348. }
  349. } else if (e) {
  350. upb_inttable_compact(&e->iton);
  351. }
  352. }
  353. return true;
  354. err:
  355. for (i = 0; i < n; i++) {
  356. upb_def *def = defs[i];
  357. def->came_from_user = false;
  358. }
  359. assert(!(s && upb_ok(s)));
  360. return false;
  361. }
  362. bool upb_def_freeze(upb_def *const* defs, size_t n, upb_status *s) {
  363. /* Def graph contains FieldDefs between each MessageDef, so double the
  364. * limit. */
  365. const size_t maxdepth = UPB_MAX_MESSAGE_DEPTH * 2;
  366. if (!_upb_def_validate(defs, n, s)) {
  367. return false;
  368. }
  369. /* Validation all passed; freeze the objects. */
  370. return upb_refcounted_freeze((upb_refcounted *const*)defs, n, s, maxdepth);
  371. }
  372. /* upb_enumdef ****************************************************************/
  373. static void upb_enumdef_free(upb_refcounted *r) {
  374. upb_enumdef *e = (upb_enumdef*)r;
  375. upb_inttable_iter i;
  376. upb_inttable_begin(&i, &e->iton);
  377. for( ; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  378. /* To clean up the upb_gstrdup() from upb_enumdef_addval(). */
  379. upb_gfree(upb_value_getcstr(upb_inttable_iter_value(&i)));
  380. }
  381. upb_strtable_uninit(&e->ntoi);
  382. upb_inttable_uninit(&e->iton);
  383. upb_def_uninit(upb_enumdef_upcast_mutable(e));
  384. upb_gfree(e);
  385. }
  386. const struct upb_refcounted_vtbl upb_enumdef_vtbl = {NULL, &upb_enumdef_free};
  387. upb_enumdef *upb_enumdef_new(const void *owner) {
  388. upb_enumdef *e = upb_gmalloc(sizeof(*e));
  389. if (!e) return NULL;
  390. if (!upb_def_init(upb_enumdef_upcast_mutable(e), UPB_DEF_ENUM,
  391. &upb_enumdef_vtbl, owner)) {
  392. goto err2;
  393. }
  394. if (!upb_strtable_init(&e->ntoi, UPB_CTYPE_INT32)) goto err2;
  395. if (!upb_inttable_init(&e->iton, UPB_CTYPE_CSTR)) goto err1;
  396. return e;
  397. err1:
  398. upb_strtable_uninit(&e->ntoi);
  399. err2:
  400. upb_gfree(e);
  401. return NULL;
  402. }
  403. upb_enumdef *upb_enumdef_dup(const upb_enumdef *e, const void *owner) {
  404. upb_enum_iter i;
  405. upb_enumdef *new_e = upb_enumdef_new(owner);
  406. if (!new_e) return NULL;
  407. for(upb_enum_begin(&i, e); !upb_enum_done(&i); upb_enum_next(&i)) {
  408. bool success = upb_enumdef_addval(
  409. new_e, upb_enum_iter_name(&i),upb_enum_iter_number(&i), NULL);
  410. if (!success) {
  411. upb_enumdef_unref(new_e, owner);
  412. return NULL;
  413. }
  414. }
  415. return new_e;
  416. }
  417. bool upb_enumdef_freeze(upb_enumdef *e, upb_status *status) {
  418. upb_def *d = upb_enumdef_upcast_mutable(e);
  419. return upb_def_freeze(&d, 1, status);
  420. }
  421. const char *upb_enumdef_fullname(const upb_enumdef *e) {
  422. return upb_def_fullname(upb_enumdef_upcast(e));
  423. }
  424. const char *upb_enumdef_name(const upb_enumdef *e) {
  425. return upb_def_name(upb_enumdef_upcast(e));
  426. }
  427. bool upb_enumdef_setfullname(upb_enumdef *e, const char *fullname,
  428. upb_status *s) {
  429. return upb_def_setfullname(upb_enumdef_upcast_mutable(e), fullname, s);
  430. }
  431. bool upb_enumdef_addval(upb_enumdef *e, const char *name, int32_t num,
  432. upb_status *status) {
  433. char *name2;
  434. if (!upb_isident(name, strlen(name), false, status)) {
  435. return false;
  436. }
  437. if (upb_enumdef_ntoiz(e, name, NULL)) {
  438. upb_status_seterrf(status, "name '%s' is already defined", name);
  439. return false;
  440. }
  441. if (!upb_strtable_insert(&e->ntoi, name, upb_value_int32(num))) {
  442. upb_status_seterrmsg(status, "out of memory");
  443. return false;
  444. }
  445. if (!upb_inttable_lookup(&e->iton, num, NULL)) {
  446. name2 = upb_gstrdup(name);
  447. if (!name2 || !upb_inttable_insert(&e->iton, num, upb_value_cstr(name2))) {
  448. upb_status_seterrmsg(status, "out of memory");
  449. upb_strtable_remove(&e->ntoi, name, NULL);
  450. return false;
  451. }
  452. }
  453. if (upb_enumdef_numvals(e) == 1) {
  454. bool ok = upb_enumdef_setdefault(e, num, NULL);
  455. UPB_ASSERT_VAR(ok, ok);
  456. }
  457. return true;
  458. }
  459. int32_t upb_enumdef_default(const upb_enumdef *e) {
  460. assert(upb_enumdef_iton(e, e->defaultval));
  461. return e->defaultval;
  462. }
  463. bool upb_enumdef_setdefault(upb_enumdef *e, int32_t val, upb_status *s) {
  464. assert(!upb_enumdef_isfrozen(e));
  465. if (!upb_enumdef_iton(e, val)) {
  466. upb_status_seterrf(s, "number '%d' is not in the enum.", val);
  467. return false;
  468. }
  469. e->defaultval = val;
  470. return true;
  471. }
  472. int upb_enumdef_numvals(const upb_enumdef *e) {
  473. return upb_strtable_count(&e->ntoi);
  474. }
  475. void upb_enum_begin(upb_enum_iter *i, const upb_enumdef *e) {
  476. /* We iterate over the ntoi table, to account for duplicate numbers. */
  477. upb_strtable_begin(i, &e->ntoi);
  478. }
  479. void upb_enum_next(upb_enum_iter *iter) { upb_strtable_next(iter); }
  480. bool upb_enum_done(upb_enum_iter *iter) { return upb_strtable_done(iter); }
  481. bool upb_enumdef_ntoi(const upb_enumdef *def, const char *name,
  482. size_t len, int32_t *num) {
  483. upb_value v;
  484. if (!upb_strtable_lookup2(&def->ntoi, name, len, &v)) {
  485. return false;
  486. }
  487. if (num) *num = upb_value_getint32(v);
  488. return true;
  489. }
  490. const char *upb_enumdef_iton(const upb_enumdef *def, int32_t num) {
  491. upb_value v;
  492. return upb_inttable_lookup32(&def->iton, num, &v) ?
  493. upb_value_getcstr(v) : NULL;
  494. }
  495. const char *upb_enum_iter_name(upb_enum_iter *iter) {
  496. return upb_strtable_iter_key(iter);
  497. }
  498. int32_t upb_enum_iter_number(upb_enum_iter *iter) {
  499. return upb_value_getint32(upb_strtable_iter_value(iter));
  500. }
  501. /* upb_fielddef ***************************************************************/
  502. static void upb_fielddef_init_default(upb_fielddef *f);
  503. static void upb_fielddef_uninit_default(upb_fielddef *f) {
  504. if (f->type_is_set_ && f->default_is_string && f->defaultval.bytes)
  505. freestr(f->defaultval.bytes);
  506. }
  507. const char *upb_fielddef_fullname(const upb_fielddef *e) {
  508. return upb_def_fullname(upb_fielddef_upcast(e));
  509. }
  510. static void visitfield(const upb_refcounted *r, upb_refcounted_visit *visit,
  511. void *closure) {
  512. const upb_fielddef *f = (const upb_fielddef*)r;
  513. if (upb_fielddef_containingtype(f)) {
  514. visit(r, upb_msgdef_upcast2(upb_fielddef_containingtype(f)), closure);
  515. }
  516. if (upb_fielddef_containingoneof(f)) {
  517. visit(r, upb_oneofdef_upcast(upb_fielddef_containingoneof(f)), closure);
  518. }
  519. if (upb_fielddef_subdef(f)) {
  520. visit(r, upb_def_upcast(upb_fielddef_subdef(f)), closure);
  521. }
  522. }
  523. static void freefield(upb_refcounted *r) {
  524. upb_fielddef *f = (upb_fielddef*)r;
  525. upb_fielddef_uninit_default(f);
  526. if (f->subdef_is_symbolic)
  527. upb_gfree(f->sub.name);
  528. upb_def_uninit(upb_fielddef_upcast_mutable(f));
  529. upb_gfree(f);
  530. }
  531. static const char *enumdefaultstr(const upb_fielddef *f) {
  532. const upb_enumdef *e;
  533. assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  534. e = upb_fielddef_enumsubdef(f);
  535. if (f->default_is_string && f->defaultval.bytes) {
  536. /* Default was explicitly set as a string. */
  537. str_t *s = f->defaultval.bytes;
  538. return s->str;
  539. } else if (e) {
  540. if (!f->default_is_string) {
  541. /* Default was explicitly set as an integer; look it up in enumdef. */
  542. const char *name = upb_enumdef_iton(e, f->defaultval.sint);
  543. if (name) {
  544. return name;
  545. }
  546. } else {
  547. /* Default is completely unset; pull enumdef default. */
  548. if (upb_enumdef_numvals(e) > 0) {
  549. const char *name = upb_enumdef_iton(e, upb_enumdef_default(e));
  550. assert(name);
  551. return name;
  552. }
  553. }
  554. }
  555. return NULL;
  556. }
  557. static bool enumdefaultint32(const upb_fielddef *f, int32_t *val) {
  558. const upb_enumdef *e;
  559. assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  560. e = upb_fielddef_enumsubdef(f);
  561. if (!f->default_is_string) {
  562. /* Default was explicitly set as an integer. */
  563. *val = f->defaultval.sint;
  564. return true;
  565. } else if (e) {
  566. if (f->defaultval.bytes) {
  567. /* Default was explicitly set as a str; try to lookup corresponding int. */
  568. str_t *s = f->defaultval.bytes;
  569. if (upb_enumdef_ntoiz(e, s->str, val)) {
  570. return true;
  571. }
  572. } else {
  573. /* Default is unset; try to pull in enumdef default. */
  574. if (upb_enumdef_numvals(e) > 0) {
  575. *val = upb_enumdef_default(e);
  576. return true;
  577. }
  578. }
  579. }
  580. return false;
  581. }
  582. const struct upb_refcounted_vtbl upb_fielddef_vtbl = {visitfield, freefield};
  583. upb_fielddef *upb_fielddef_new(const void *o) {
  584. upb_fielddef *f = upb_gmalloc(sizeof(*f));
  585. if (!f) return NULL;
  586. if (!upb_def_init(upb_fielddef_upcast_mutable(f), UPB_DEF_FIELD,
  587. &upb_fielddef_vtbl, o)) {
  588. upb_gfree(f);
  589. return NULL;
  590. }
  591. f->msg.def = NULL;
  592. f->sub.def = NULL;
  593. f->oneof = NULL;
  594. f->subdef_is_symbolic = false;
  595. f->msg_is_symbolic = false;
  596. f->label_ = UPB_LABEL_OPTIONAL;
  597. f->type_ = UPB_TYPE_INT32;
  598. f->number_ = 0;
  599. f->type_is_set_ = false;
  600. f->tagdelim = false;
  601. f->is_extension_ = false;
  602. f->lazy_ = false;
  603. f->packed_ = true;
  604. /* For the moment we default this to UPB_INTFMT_VARIABLE, since it will work
  605. * with all integer types and is in some since more "default" since the most
  606. * normal-looking proto2 types int32/int64/uint32/uint64 use variable.
  607. *
  608. * Other options to consider:
  609. * - there is no default; users must set this manually (like type).
  610. * - default signed integers to UPB_INTFMT_ZIGZAG, since it's more likely to
  611. * be an optimal default for signed integers. */
  612. f->intfmt = UPB_INTFMT_VARIABLE;
  613. return f;
  614. }
  615. upb_fielddef *upb_fielddef_dup(const upb_fielddef *f, const void *owner) {
  616. const char *srcname;
  617. upb_fielddef *newf = upb_fielddef_new(owner);
  618. if (!newf) return NULL;
  619. upb_fielddef_settype(newf, upb_fielddef_type(f));
  620. upb_fielddef_setlabel(newf, upb_fielddef_label(f));
  621. upb_fielddef_setnumber(newf, upb_fielddef_number(f), NULL);
  622. upb_fielddef_setname(newf, upb_fielddef_name(f), NULL);
  623. if (f->default_is_string && f->defaultval.bytes) {
  624. str_t *s = f->defaultval.bytes;
  625. upb_fielddef_setdefaultstr(newf, s->str, s->len, NULL);
  626. } else {
  627. newf->default_is_string = f->default_is_string;
  628. newf->defaultval = f->defaultval;
  629. }
  630. if (f->subdef_is_symbolic) {
  631. srcname = f->sub.name; /* Might be NULL. */
  632. } else {
  633. srcname = f->sub.def ? upb_def_fullname(f->sub.def) : NULL;
  634. }
  635. if (srcname) {
  636. char *newname = upb_gmalloc(strlen(f->sub.def->fullname) + 2);
  637. if (!newname) {
  638. upb_fielddef_unref(newf, owner);
  639. return NULL;
  640. }
  641. strcpy(newname, ".");
  642. strcat(newname, f->sub.def->fullname);
  643. upb_fielddef_setsubdefname(newf, newname, NULL);
  644. upb_gfree(newname);
  645. }
  646. return newf;
  647. }
  648. bool upb_fielddef_typeisset(const upb_fielddef *f) {
  649. return f->type_is_set_;
  650. }
  651. upb_fieldtype_t upb_fielddef_type(const upb_fielddef *f) {
  652. assert(f->type_is_set_);
  653. return f->type_;
  654. }
  655. uint32_t upb_fielddef_index(const upb_fielddef *f) {
  656. return f->index_;
  657. }
  658. upb_label_t upb_fielddef_label(const upb_fielddef *f) {
  659. return f->label_;
  660. }
  661. upb_intfmt_t upb_fielddef_intfmt(const upb_fielddef *f) {
  662. return f->intfmt;
  663. }
  664. bool upb_fielddef_istagdelim(const upb_fielddef *f) {
  665. return f->tagdelim;
  666. }
  667. uint32_t upb_fielddef_number(const upb_fielddef *f) {
  668. return f->number_;
  669. }
  670. bool upb_fielddef_isextension(const upb_fielddef *f) {
  671. return f->is_extension_;
  672. }
  673. bool upb_fielddef_lazy(const upb_fielddef *f) {
  674. return f->lazy_;
  675. }
  676. bool upb_fielddef_packed(const upb_fielddef *f) {
  677. return f->packed_;
  678. }
  679. const char *upb_fielddef_name(const upb_fielddef *f) {
  680. return upb_def_fullname(upb_fielddef_upcast(f));
  681. }
  682. size_t upb_fielddef_getjsonname(const upb_fielddef *f, char *buf, size_t len) {
  683. const char *name = upb_fielddef_name(f);
  684. size_t src, dst = 0;
  685. bool ucase_next = false;
  686. #define WRITE(byte) \
  687. ++dst; \
  688. if (dst < len) buf[dst - 1] = byte; \
  689. else if (dst == len) buf[dst - 1] = '\0'
  690. if (!name) {
  691. WRITE('\0');
  692. return 0;
  693. }
  694. /* Implement the transformation as described in the spec:
  695. * 1. upper case all letters after an underscore.
  696. * 2. remove all underscores.
  697. */
  698. for (src = 0; name[src]; src++) {
  699. if (name[src] == '_') {
  700. ucase_next = true;
  701. continue;
  702. }
  703. if (ucase_next) {
  704. WRITE(toupper(name[src]));
  705. ucase_next = false;
  706. } else {
  707. WRITE(name[src]);
  708. }
  709. }
  710. WRITE('\0');
  711. return dst;
  712. #undef WRITE
  713. }
  714. const upb_msgdef *upb_fielddef_containingtype(const upb_fielddef *f) {
  715. return f->msg_is_symbolic ? NULL : f->msg.def;
  716. }
  717. const upb_oneofdef *upb_fielddef_containingoneof(const upb_fielddef *f) {
  718. return f->oneof;
  719. }
  720. upb_msgdef *upb_fielddef_containingtype_mutable(upb_fielddef *f) {
  721. return (upb_msgdef*)upb_fielddef_containingtype(f);
  722. }
  723. const char *upb_fielddef_containingtypename(upb_fielddef *f) {
  724. return f->msg_is_symbolic ? f->msg.name : NULL;
  725. }
  726. static void release_containingtype(upb_fielddef *f) {
  727. if (f->msg_is_symbolic) upb_gfree(f->msg.name);
  728. }
  729. bool upb_fielddef_setcontainingtypename(upb_fielddef *f, const char *name,
  730. upb_status *s) {
  731. char *name_copy;
  732. assert(!upb_fielddef_isfrozen(f));
  733. if (upb_fielddef_containingtype(f)) {
  734. upb_status_seterrmsg(s, "field has already been added to a message.");
  735. return false;
  736. }
  737. /* TODO: validate name (upb_isident() doesn't quite work atm because this name
  738. * may have a leading "."). */
  739. name_copy = upb_gstrdup(name);
  740. if (!name_copy) {
  741. upb_upberr_setoom(s);
  742. return false;
  743. }
  744. release_containingtype(f);
  745. f->msg.name = name_copy;
  746. f->msg_is_symbolic = true;
  747. return true;
  748. }
  749. bool upb_fielddef_setname(upb_fielddef *f, const char *name, upb_status *s) {
  750. if (upb_fielddef_containingtype(f) || upb_fielddef_containingoneof(f)) {
  751. upb_status_seterrmsg(s, "Already added to message or oneof");
  752. return false;
  753. }
  754. return upb_def_setfullname(upb_fielddef_upcast_mutable(f), name, s);
  755. }
  756. static void chkdefaulttype(const upb_fielddef *f, upb_fieldtype_t type) {
  757. UPB_UNUSED(f);
  758. UPB_UNUSED(type);
  759. assert(f->type_is_set_ && upb_fielddef_type(f) == type);
  760. }
  761. int64_t upb_fielddef_defaultint64(const upb_fielddef *f) {
  762. chkdefaulttype(f, UPB_TYPE_INT64);
  763. return f->defaultval.sint;
  764. }
  765. int32_t upb_fielddef_defaultint32(const upb_fielddef *f) {
  766. if (f->type_is_set_ && upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  767. int32_t val;
  768. bool ok = enumdefaultint32(f, &val);
  769. UPB_ASSERT_VAR(ok, ok);
  770. return val;
  771. } else {
  772. chkdefaulttype(f, UPB_TYPE_INT32);
  773. return f->defaultval.sint;
  774. }
  775. }
  776. uint64_t upb_fielddef_defaultuint64(const upb_fielddef *f) {
  777. chkdefaulttype(f, UPB_TYPE_UINT64);
  778. return f->defaultval.uint;
  779. }
  780. uint32_t upb_fielddef_defaultuint32(const upb_fielddef *f) {
  781. chkdefaulttype(f, UPB_TYPE_UINT32);
  782. return f->defaultval.uint;
  783. }
  784. bool upb_fielddef_defaultbool(const upb_fielddef *f) {
  785. chkdefaulttype(f, UPB_TYPE_BOOL);
  786. return f->defaultval.uint;
  787. }
  788. float upb_fielddef_defaultfloat(const upb_fielddef *f) {
  789. chkdefaulttype(f, UPB_TYPE_FLOAT);
  790. return f->defaultval.flt;
  791. }
  792. double upb_fielddef_defaultdouble(const upb_fielddef *f) {
  793. chkdefaulttype(f, UPB_TYPE_DOUBLE);
  794. return f->defaultval.dbl;
  795. }
  796. const char *upb_fielddef_defaultstr(const upb_fielddef *f, size_t *len) {
  797. assert(f->type_is_set_);
  798. assert(upb_fielddef_type(f) == UPB_TYPE_STRING ||
  799. upb_fielddef_type(f) == UPB_TYPE_BYTES ||
  800. upb_fielddef_type(f) == UPB_TYPE_ENUM);
  801. if (upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  802. const char *ret = enumdefaultstr(f);
  803. assert(ret);
  804. /* Enum defaults can't have embedded NULLs. */
  805. if (len) *len = strlen(ret);
  806. return ret;
  807. }
  808. if (f->default_is_string) {
  809. str_t *str = f->defaultval.bytes;
  810. if (len) *len = str->len;
  811. return str->str;
  812. }
  813. return NULL;
  814. }
  815. static void upb_fielddef_init_default(upb_fielddef *f) {
  816. f->default_is_string = false;
  817. switch (upb_fielddef_type(f)) {
  818. case UPB_TYPE_DOUBLE: f->defaultval.dbl = 0; break;
  819. case UPB_TYPE_FLOAT: f->defaultval.flt = 0; break;
  820. case UPB_TYPE_INT32:
  821. case UPB_TYPE_INT64: f->defaultval.sint = 0; break;
  822. case UPB_TYPE_UINT64:
  823. case UPB_TYPE_UINT32:
  824. case UPB_TYPE_BOOL: f->defaultval.uint = 0; break;
  825. case UPB_TYPE_STRING:
  826. case UPB_TYPE_BYTES:
  827. f->defaultval.bytes = newstr("", 0);
  828. f->default_is_string = true;
  829. break;
  830. case UPB_TYPE_MESSAGE: break;
  831. case UPB_TYPE_ENUM:
  832. /* This is our special sentinel that indicates "not set" for an enum. */
  833. f->default_is_string = true;
  834. f->defaultval.bytes = NULL;
  835. break;
  836. }
  837. }
  838. const upb_def *upb_fielddef_subdef(const upb_fielddef *f) {
  839. return f->subdef_is_symbolic ? NULL : f->sub.def;
  840. }
  841. const upb_msgdef *upb_fielddef_msgsubdef(const upb_fielddef *f) {
  842. const upb_def *def = upb_fielddef_subdef(f);
  843. return def ? upb_dyncast_msgdef(def) : NULL;
  844. }
  845. const upb_enumdef *upb_fielddef_enumsubdef(const upb_fielddef *f) {
  846. const upb_def *def = upb_fielddef_subdef(f);
  847. return def ? upb_dyncast_enumdef(def) : NULL;
  848. }
  849. upb_def *upb_fielddef_subdef_mutable(upb_fielddef *f) {
  850. return (upb_def*)upb_fielddef_subdef(f);
  851. }
  852. const char *upb_fielddef_subdefname(const upb_fielddef *f) {
  853. if (f->subdef_is_symbolic) {
  854. return f->sub.name;
  855. } else if (f->sub.def) {
  856. return upb_def_fullname(f->sub.def);
  857. } else {
  858. return NULL;
  859. }
  860. }
  861. bool upb_fielddef_setnumber(upb_fielddef *f, uint32_t number, upb_status *s) {
  862. if (upb_fielddef_containingtype(f)) {
  863. upb_status_seterrmsg(
  864. s, "cannot change field number after adding to a message");
  865. return false;
  866. }
  867. if (number == 0 || number > UPB_MAX_FIELDNUMBER) {
  868. upb_status_seterrf(s, "invalid field number (%u)", number);
  869. return false;
  870. }
  871. f->number_ = number;
  872. return true;
  873. }
  874. void upb_fielddef_settype(upb_fielddef *f, upb_fieldtype_t type) {
  875. assert(!upb_fielddef_isfrozen(f));
  876. assert(upb_fielddef_checktype(type));
  877. upb_fielddef_uninit_default(f);
  878. f->type_ = type;
  879. f->type_is_set_ = true;
  880. upb_fielddef_init_default(f);
  881. }
  882. void upb_fielddef_setdescriptortype(upb_fielddef *f, int type) {
  883. assert(!upb_fielddef_isfrozen(f));
  884. switch (type) {
  885. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  886. upb_fielddef_settype(f, UPB_TYPE_DOUBLE);
  887. break;
  888. case UPB_DESCRIPTOR_TYPE_FLOAT:
  889. upb_fielddef_settype(f, UPB_TYPE_FLOAT);
  890. break;
  891. case UPB_DESCRIPTOR_TYPE_INT64:
  892. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  893. case UPB_DESCRIPTOR_TYPE_SINT64:
  894. upb_fielddef_settype(f, UPB_TYPE_INT64);
  895. break;
  896. case UPB_DESCRIPTOR_TYPE_UINT64:
  897. case UPB_DESCRIPTOR_TYPE_FIXED64:
  898. upb_fielddef_settype(f, UPB_TYPE_UINT64);
  899. break;
  900. case UPB_DESCRIPTOR_TYPE_INT32:
  901. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  902. case UPB_DESCRIPTOR_TYPE_SINT32:
  903. upb_fielddef_settype(f, UPB_TYPE_INT32);
  904. break;
  905. case UPB_DESCRIPTOR_TYPE_UINT32:
  906. case UPB_DESCRIPTOR_TYPE_FIXED32:
  907. upb_fielddef_settype(f, UPB_TYPE_UINT32);
  908. break;
  909. case UPB_DESCRIPTOR_TYPE_BOOL:
  910. upb_fielddef_settype(f, UPB_TYPE_BOOL);
  911. break;
  912. case UPB_DESCRIPTOR_TYPE_STRING:
  913. upb_fielddef_settype(f, UPB_TYPE_STRING);
  914. break;
  915. case UPB_DESCRIPTOR_TYPE_BYTES:
  916. upb_fielddef_settype(f, UPB_TYPE_BYTES);
  917. break;
  918. case UPB_DESCRIPTOR_TYPE_GROUP:
  919. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  920. upb_fielddef_settype(f, UPB_TYPE_MESSAGE);
  921. break;
  922. case UPB_DESCRIPTOR_TYPE_ENUM:
  923. upb_fielddef_settype(f, UPB_TYPE_ENUM);
  924. break;
  925. default: assert(false);
  926. }
  927. if (type == UPB_DESCRIPTOR_TYPE_FIXED64 ||
  928. type == UPB_DESCRIPTOR_TYPE_FIXED32 ||
  929. type == UPB_DESCRIPTOR_TYPE_SFIXED64 ||
  930. type == UPB_DESCRIPTOR_TYPE_SFIXED32) {
  931. upb_fielddef_setintfmt(f, UPB_INTFMT_FIXED);
  932. } else if (type == UPB_DESCRIPTOR_TYPE_SINT64 ||
  933. type == UPB_DESCRIPTOR_TYPE_SINT32) {
  934. upb_fielddef_setintfmt(f, UPB_INTFMT_ZIGZAG);
  935. } else {
  936. upb_fielddef_setintfmt(f, UPB_INTFMT_VARIABLE);
  937. }
  938. upb_fielddef_settagdelim(f, type == UPB_DESCRIPTOR_TYPE_GROUP);
  939. }
  940. upb_descriptortype_t upb_fielddef_descriptortype(const upb_fielddef *f) {
  941. switch (upb_fielddef_type(f)) {
  942. case UPB_TYPE_FLOAT: return UPB_DESCRIPTOR_TYPE_FLOAT;
  943. case UPB_TYPE_DOUBLE: return UPB_DESCRIPTOR_TYPE_DOUBLE;
  944. case UPB_TYPE_BOOL: return UPB_DESCRIPTOR_TYPE_BOOL;
  945. case UPB_TYPE_STRING: return UPB_DESCRIPTOR_TYPE_STRING;
  946. case UPB_TYPE_BYTES: return UPB_DESCRIPTOR_TYPE_BYTES;
  947. case UPB_TYPE_ENUM: return UPB_DESCRIPTOR_TYPE_ENUM;
  948. case UPB_TYPE_INT32:
  949. switch (upb_fielddef_intfmt(f)) {
  950. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_INT32;
  951. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_SFIXED32;
  952. case UPB_INTFMT_ZIGZAG: return UPB_DESCRIPTOR_TYPE_SINT32;
  953. }
  954. case UPB_TYPE_INT64:
  955. switch (upb_fielddef_intfmt(f)) {
  956. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_INT64;
  957. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_SFIXED64;
  958. case UPB_INTFMT_ZIGZAG: return UPB_DESCRIPTOR_TYPE_SINT64;
  959. }
  960. case UPB_TYPE_UINT32:
  961. switch (upb_fielddef_intfmt(f)) {
  962. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_UINT32;
  963. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_FIXED32;
  964. case UPB_INTFMT_ZIGZAG: return -1;
  965. }
  966. case UPB_TYPE_UINT64:
  967. switch (upb_fielddef_intfmt(f)) {
  968. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_UINT64;
  969. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_FIXED64;
  970. case UPB_INTFMT_ZIGZAG: return -1;
  971. }
  972. case UPB_TYPE_MESSAGE:
  973. return upb_fielddef_istagdelim(f) ?
  974. UPB_DESCRIPTOR_TYPE_GROUP : UPB_DESCRIPTOR_TYPE_MESSAGE;
  975. }
  976. return 0;
  977. }
  978. void upb_fielddef_setisextension(upb_fielddef *f, bool is_extension) {
  979. assert(!upb_fielddef_isfrozen(f));
  980. f->is_extension_ = is_extension;
  981. }
  982. void upb_fielddef_setlazy(upb_fielddef *f, bool lazy) {
  983. assert(!upb_fielddef_isfrozen(f));
  984. f->lazy_ = lazy;
  985. }
  986. void upb_fielddef_setpacked(upb_fielddef *f, bool packed) {
  987. assert(!upb_fielddef_isfrozen(f));
  988. f->packed_ = packed;
  989. }
  990. void upb_fielddef_setlabel(upb_fielddef *f, upb_label_t label) {
  991. assert(!upb_fielddef_isfrozen(f));
  992. assert(upb_fielddef_checklabel(label));
  993. f->label_ = label;
  994. }
  995. void upb_fielddef_setintfmt(upb_fielddef *f, upb_intfmt_t fmt) {
  996. assert(!upb_fielddef_isfrozen(f));
  997. assert(upb_fielddef_checkintfmt(fmt));
  998. f->intfmt = fmt;
  999. }
  1000. void upb_fielddef_settagdelim(upb_fielddef *f, bool tag_delim) {
  1001. assert(!upb_fielddef_isfrozen(f));
  1002. f->tagdelim = tag_delim;
  1003. f->tagdelim = tag_delim;
  1004. }
  1005. static bool checksetdefault(upb_fielddef *f, upb_fieldtype_t type) {
  1006. if (!f->type_is_set_ || upb_fielddef_isfrozen(f) ||
  1007. upb_fielddef_type(f) != type) {
  1008. assert(false);
  1009. return false;
  1010. }
  1011. if (f->default_is_string) {
  1012. str_t *s = f->defaultval.bytes;
  1013. assert(s || type == UPB_TYPE_ENUM);
  1014. if (s) freestr(s);
  1015. }
  1016. f->default_is_string = false;
  1017. return true;
  1018. }
  1019. void upb_fielddef_setdefaultint64(upb_fielddef *f, int64_t value) {
  1020. if (checksetdefault(f, UPB_TYPE_INT64))
  1021. f->defaultval.sint = value;
  1022. }
  1023. void upb_fielddef_setdefaultint32(upb_fielddef *f, int32_t value) {
  1024. if ((upb_fielddef_type(f) == UPB_TYPE_ENUM &&
  1025. checksetdefault(f, UPB_TYPE_ENUM)) ||
  1026. checksetdefault(f, UPB_TYPE_INT32)) {
  1027. f->defaultval.sint = value;
  1028. }
  1029. }
  1030. void upb_fielddef_setdefaultuint64(upb_fielddef *f, uint64_t value) {
  1031. if (checksetdefault(f, UPB_TYPE_UINT64))
  1032. f->defaultval.uint = value;
  1033. }
  1034. void upb_fielddef_setdefaultuint32(upb_fielddef *f, uint32_t value) {
  1035. if (checksetdefault(f, UPB_TYPE_UINT32))
  1036. f->defaultval.uint = value;
  1037. }
  1038. void upb_fielddef_setdefaultbool(upb_fielddef *f, bool value) {
  1039. if (checksetdefault(f, UPB_TYPE_BOOL))
  1040. f->defaultval.uint = value;
  1041. }
  1042. void upb_fielddef_setdefaultfloat(upb_fielddef *f, float value) {
  1043. if (checksetdefault(f, UPB_TYPE_FLOAT))
  1044. f->defaultval.flt = value;
  1045. }
  1046. void upb_fielddef_setdefaultdouble(upb_fielddef *f, double value) {
  1047. if (checksetdefault(f, UPB_TYPE_DOUBLE))
  1048. f->defaultval.dbl = value;
  1049. }
  1050. bool upb_fielddef_setdefaultstr(upb_fielddef *f, const void *str, size_t len,
  1051. upb_status *s) {
  1052. str_t *str2;
  1053. assert(upb_fielddef_isstring(f) || f->type_ == UPB_TYPE_ENUM);
  1054. if (f->type_ == UPB_TYPE_ENUM && !upb_isident(str, len, false, s))
  1055. return false;
  1056. if (f->default_is_string) {
  1057. str_t *s = f->defaultval.bytes;
  1058. assert(s || f->type_ == UPB_TYPE_ENUM);
  1059. if (s) freestr(s);
  1060. } else {
  1061. assert(f->type_ == UPB_TYPE_ENUM);
  1062. }
  1063. str2 = newstr(str, len);
  1064. f->defaultval.bytes = str2;
  1065. f->default_is_string = true;
  1066. return true;
  1067. }
  1068. void upb_fielddef_setdefaultcstr(upb_fielddef *f, const char *str,
  1069. upb_status *s) {
  1070. assert(f->type_is_set_);
  1071. upb_fielddef_setdefaultstr(f, str, str ? strlen(str) : 0, s);
  1072. }
  1073. bool upb_fielddef_enumhasdefaultint32(const upb_fielddef *f) {
  1074. int32_t val;
  1075. assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  1076. return enumdefaultint32(f, &val);
  1077. }
  1078. bool upb_fielddef_enumhasdefaultstr(const upb_fielddef *f) {
  1079. assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  1080. return enumdefaultstr(f) != NULL;
  1081. }
  1082. static bool upb_subdef_typecheck(upb_fielddef *f, const upb_def *subdef,
  1083. upb_status *s) {
  1084. if (f->type_ == UPB_TYPE_MESSAGE) {
  1085. if (upb_dyncast_msgdef(subdef)) return true;
  1086. upb_status_seterrmsg(s, "invalid subdef type for this submessage field");
  1087. return false;
  1088. } else if (f->type_ == UPB_TYPE_ENUM) {
  1089. if (upb_dyncast_enumdef(subdef)) return true;
  1090. upb_status_seterrmsg(s, "invalid subdef type for this enum field");
  1091. return false;
  1092. } else {
  1093. upb_status_seterrmsg(s, "only message and enum fields can have a subdef");
  1094. return false;
  1095. }
  1096. }
  1097. static void release_subdef(upb_fielddef *f) {
  1098. if (f->subdef_is_symbolic) {
  1099. upb_gfree(f->sub.name);
  1100. } else if (f->sub.def) {
  1101. upb_unref2(f->sub.def, f);
  1102. }
  1103. }
  1104. bool upb_fielddef_setsubdef(upb_fielddef *f, const upb_def *subdef,
  1105. upb_status *s) {
  1106. assert(!upb_fielddef_isfrozen(f));
  1107. assert(upb_fielddef_hassubdef(f));
  1108. if (subdef && !upb_subdef_typecheck(f, subdef, s)) return false;
  1109. release_subdef(f);
  1110. f->sub.def = subdef;
  1111. f->subdef_is_symbolic = false;
  1112. if (f->sub.def) upb_ref2(f->sub.def, f);
  1113. return true;
  1114. }
  1115. bool upb_fielddef_setmsgsubdef(upb_fielddef *f, const upb_msgdef *subdef,
  1116. upb_status *s) {
  1117. return upb_fielddef_setsubdef(f, upb_msgdef_upcast(subdef), s);
  1118. }
  1119. bool upb_fielddef_setenumsubdef(upb_fielddef *f, const upb_enumdef *subdef,
  1120. upb_status *s) {
  1121. return upb_fielddef_setsubdef(f, upb_enumdef_upcast(subdef), s);
  1122. }
  1123. bool upb_fielddef_setsubdefname(upb_fielddef *f, const char *name,
  1124. upb_status *s) {
  1125. char *name_copy;
  1126. assert(!upb_fielddef_isfrozen(f));
  1127. if (!upb_fielddef_hassubdef(f)) {
  1128. upb_status_seterrmsg(s, "field type does not accept a subdef");
  1129. return false;
  1130. }
  1131. name_copy = upb_gstrdup(name);
  1132. if (!name_copy) {
  1133. upb_upberr_setoom(s);
  1134. return false;
  1135. }
  1136. /* TODO: validate name (upb_isident() doesn't quite work atm because this name
  1137. * may have a leading "."). */
  1138. release_subdef(f);
  1139. f->sub.name = name_copy;
  1140. f->subdef_is_symbolic = true;
  1141. return true;
  1142. }
  1143. bool upb_fielddef_issubmsg(const upb_fielddef *f) {
  1144. return upb_fielddef_type(f) == UPB_TYPE_MESSAGE;
  1145. }
  1146. bool upb_fielddef_isstring(const upb_fielddef *f) {
  1147. return upb_fielddef_type(f) == UPB_TYPE_STRING ||
  1148. upb_fielddef_type(f) == UPB_TYPE_BYTES;
  1149. }
  1150. bool upb_fielddef_isseq(const upb_fielddef *f) {
  1151. return upb_fielddef_label(f) == UPB_LABEL_REPEATED;
  1152. }
  1153. bool upb_fielddef_isprimitive(const upb_fielddef *f) {
  1154. return !upb_fielddef_isstring(f) && !upb_fielddef_issubmsg(f);
  1155. }
  1156. bool upb_fielddef_ismap(const upb_fielddef *f) {
  1157. return upb_fielddef_isseq(f) && upb_fielddef_issubmsg(f) &&
  1158. upb_msgdef_mapentry(upb_fielddef_msgsubdef(f));
  1159. }
  1160. bool upb_fielddef_haspresence(const upb_fielddef *f) {
  1161. if (upb_fielddef_isseq(f)) return false;
  1162. if (upb_fielddef_issubmsg(f)) return true;
  1163. /* Primitive field: return true unless there is a message that specifies
  1164. * presence should not exist. */
  1165. if (f->msg_is_symbolic || !f->msg.def) return true;
  1166. return f->msg.def->syntax == UPB_SYNTAX_PROTO2;
  1167. }
  1168. bool upb_fielddef_hassubdef(const upb_fielddef *f) {
  1169. return upb_fielddef_issubmsg(f) || upb_fielddef_type(f) == UPB_TYPE_ENUM;
  1170. }
  1171. static bool between(int32_t x, int32_t low, int32_t high) {
  1172. return x >= low && x <= high;
  1173. }
  1174. bool upb_fielddef_checklabel(int32_t label) { return between(label, 1, 3); }
  1175. bool upb_fielddef_checktype(int32_t type) { return between(type, 1, 11); }
  1176. bool upb_fielddef_checkintfmt(int32_t fmt) { return between(fmt, 1, 3); }
  1177. bool upb_fielddef_checkdescriptortype(int32_t type) {
  1178. return between(type, 1, 18);
  1179. }
  1180. /* upb_msgdef *****************************************************************/
  1181. static void visitmsg(const upb_refcounted *r, upb_refcounted_visit *visit,
  1182. void *closure) {
  1183. upb_msg_oneof_iter o;
  1184. const upb_msgdef *m = (const upb_msgdef*)r;
  1185. upb_msg_field_iter i;
  1186. for(upb_msg_field_begin(&i, m);
  1187. !upb_msg_field_done(&i);
  1188. upb_msg_field_next(&i)) {
  1189. upb_fielddef *f = upb_msg_iter_field(&i);
  1190. visit(r, upb_fielddef_upcast2(f), closure);
  1191. }
  1192. for(upb_msg_oneof_begin(&o, m);
  1193. !upb_msg_oneof_done(&o);
  1194. upb_msg_oneof_next(&o)) {
  1195. upb_oneofdef *f = upb_msg_iter_oneof(&o);
  1196. visit(r, upb_oneofdef_upcast(f), closure);
  1197. }
  1198. }
  1199. static void freemsg(upb_refcounted *r) {
  1200. upb_msgdef *m = (upb_msgdef*)r;
  1201. upb_strtable_uninit(&m->ntof);
  1202. upb_inttable_uninit(&m->itof);
  1203. upb_def_uninit(upb_msgdef_upcast_mutable(m));
  1204. upb_gfree(m);
  1205. }
  1206. const struct upb_refcounted_vtbl upb_msgdef_vtbl = {visitmsg, freemsg};
  1207. upb_msgdef *upb_msgdef_new(const void *owner) {
  1208. upb_msgdef *m = upb_gmalloc(sizeof(*m));
  1209. if (!m) return NULL;
  1210. if (!upb_def_init(upb_msgdef_upcast_mutable(m), UPB_DEF_MSG, &upb_msgdef_vtbl,
  1211. owner)) {
  1212. goto err2;
  1213. }
  1214. if (!upb_inttable_init(&m->itof, UPB_CTYPE_PTR)) goto err2;
  1215. if (!upb_strtable_init(&m->ntof, UPB_CTYPE_PTR)) goto err1;
  1216. m->map_entry = false;
  1217. m->syntax = UPB_SYNTAX_PROTO2;
  1218. return m;
  1219. err1:
  1220. upb_inttable_uninit(&m->itof);
  1221. err2:
  1222. upb_gfree(m);
  1223. return NULL;
  1224. }
  1225. upb_msgdef *upb_msgdef_dup(const upb_msgdef *m, const void *owner) {
  1226. bool ok;
  1227. upb_msg_field_iter i;
  1228. upb_msg_oneof_iter o;
  1229. upb_msgdef *newm = upb_msgdef_new(owner);
  1230. if (!newm) return NULL;
  1231. ok = upb_def_setfullname(upb_msgdef_upcast_mutable(newm),
  1232. upb_def_fullname(upb_msgdef_upcast(m)),
  1233. NULL);
  1234. newm->map_entry = m->map_entry;
  1235. newm->syntax = m->syntax;
  1236. UPB_ASSERT_VAR(ok, ok);
  1237. for(upb_msg_field_begin(&i, m);
  1238. !upb_msg_field_done(&i);
  1239. upb_msg_field_next(&i)) {
  1240. upb_fielddef *f = upb_fielddef_dup(upb_msg_iter_field(&i), &f);
  1241. /* Fields in oneofs are dup'd below. */
  1242. if (upb_fielddef_containingoneof(f)) continue;
  1243. if (!f || !upb_msgdef_addfield(newm, f, &f, NULL)) {
  1244. upb_msgdef_unref(newm, owner);
  1245. return NULL;
  1246. }
  1247. }
  1248. for(upb_msg_oneof_begin(&o, m);
  1249. !upb_msg_oneof_done(&o);
  1250. upb_msg_oneof_next(&o)) {
  1251. upb_oneofdef *f = upb_oneofdef_dup(upb_msg_iter_oneof(&o), &f);
  1252. if (!f || !upb_msgdef_addoneof(newm, f, &f, NULL)) {
  1253. upb_msgdef_unref(newm, owner);
  1254. return NULL;
  1255. }
  1256. }
  1257. return newm;
  1258. }
  1259. bool upb_msgdef_freeze(upb_msgdef *m, upb_status *status) {
  1260. upb_def *d = upb_msgdef_upcast_mutable(m);
  1261. return upb_def_freeze(&d, 1, status);
  1262. }
  1263. const char *upb_msgdef_fullname(const upb_msgdef *m) {
  1264. return upb_def_fullname(upb_msgdef_upcast(m));
  1265. }
  1266. const char *upb_msgdef_name(const upb_msgdef *m) {
  1267. return upb_def_name(upb_msgdef_upcast(m));
  1268. }
  1269. bool upb_msgdef_setfullname(upb_msgdef *m, const char *fullname,
  1270. upb_status *s) {
  1271. return upb_def_setfullname(upb_msgdef_upcast_mutable(m), fullname, s);
  1272. }
  1273. bool upb_msgdef_setsyntax(upb_msgdef *m, upb_syntax_t syntax) {
  1274. if (syntax != UPB_SYNTAX_PROTO2 && syntax != UPB_SYNTAX_PROTO3) {
  1275. return false;
  1276. }
  1277. m->syntax = syntax;
  1278. return true;
  1279. }
  1280. upb_syntax_t upb_msgdef_syntax(const upb_msgdef *m) {
  1281. return m->syntax;
  1282. }
  1283. /* Helper: check that the field |f| is safe to add to msgdef |m|. Set an error
  1284. * on status |s| and return false if not. */
  1285. static bool check_field_add(const upb_msgdef *m, const upb_fielddef *f,
  1286. upb_status *s) {
  1287. if (upb_fielddef_containingtype(f) != NULL) {
  1288. upb_status_seterrmsg(s, "fielddef already belongs to a message");
  1289. return false;
  1290. } else if (upb_fielddef_name(f) == NULL || upb_fielddef_number(f) == 0) {
  1291. upb_status_seterrmsg(s, "field name or number were not set");
  1292. return false;
  1293. } else if (upb_msgdef_itof(m, upb_fielddef_number(f))) {
  1294. upb_status_seterrmsg(s, "duplicate field number");
  1295. return false;
  1296. } else if (upb_strtable_lookup(&m->ntof, upb_fielddef_name(f), NULL)) {
  1297. upb_status_seterrmsg(s, "name conflicts with existing field or oneof");
  1298. return false;
  1299. }
  1300. return true;
  1301. }
  1302. static void add_field(upb_msgdef *m, upb_fielddef *f, const void *ref_donor) {
  1303. release_containingtype(f);
  1304. f->msg.def = m;
  1305. f->msg_is_symbolic = false;
  1306. upb_inttable_insert(&m->itof, upb_fielddef_number(f), upb_value_ptr(f));
  1307. upb_strtable_insert(&m->ntof, upb_fielddef_name(f), upb_value_ptr(f));
  1308. upb_ref2(f, m);
  1309. upb_ref2(m, f);
  1310. if (ref_donor) upb_fielddef_unref(f, ref_donor);
  1311. }
  1312. bool upb_msgdef_addfield(upb_msgdef *m, upb_fielddef *f, const void *ref_donor,
  1313. upb_status *s) {
  1314. /* TODO: extensions need to have a separate namespace, because proto2 allows a
  1315. * top-level extension (ie. one not in any package) to have the same name as a
  1316. * field from the message.
  1317. *
  1318. * This also implies that there needs to be a separate lookup-by-name method
  1319. * for extensions. It seems desirable for iteration to return both extensions
  1320. * and non-extensions though.
  1321. *
  1322. * We also need to validate that the field number is in an extension range iff
  1323. * it is an extension.
  1324. *
  1325. * This method is idempotent. Check if |f| is already part of this msgdef and
  1326. * return immediately if so. */
  1327. if (upb_fielddef_containingtype(f) == m) {
  1328. return true;
  1329. }
  1330. /* Check constraints for all fields before performing any action. */
  1331. if (!check_field_add(m, f, s)) {
  1332. return false;
  1333. } else if (upb_fielddef_containingoneof(f) != NULL) {
  1334. /* Fields in a oneof can only be added by adding the oneof to the msgdef. */
  1335. upb_status_seterrmsg(s, "fielddef is part of a oneof");
  1336. return false;
  1337. }
  1338. /* Constraint checks ok, perform the action. */
  1339. add_field(m, f, ref_donor);
  1340. return true;
  1341. }
  1342. bool upb_msgdef_addoneof(upb_msgdef *m, upb_oneofdef *o, const void *ref_donor,
  1343. upb_status *s) {
  1344. upb_oneof_iter it;
  1345. /* Check various conditions that would prevent this oneof from being added. */
  1346. if (upb_oneofdef_containingtype(o)) {
  1347. upb_status_seterrmsg(s, "oneofdef already belongs to a message");
  1348. return false;
  1349. } else if (upb_oneofdef_name(o) == NULL) {
  1350. upb_status_seterrmsg(s, "oneofdef name was not set");
  1351. return false;
  1352. } else if (upb_strtable_lookup(&m->ntof, upb_oneofdef_name(o), NULL)) {
  1353. upb_status_seterrmsg(s, "name conflicts with existing field or oneof");
  1354. return false;
  1355. }
  1356. /* Check that all of the oneof's fields do not conflict with names or numbers
  1357. * of fields already in the message. */
  1358. for (upb_oneof_begin(&it, o); !upb_oneof_done(&it); upb_oneof_next(&it)) {
  1359. const upb_fielddef *f = upb_oneof_iter_field(&it);
  1360. if (!check_field_add(m, f, s)) {
  1361. return false;
  1362. }
  1363. }
  1364. /* Everything checks out -- commit now. */
  1365. /* Add oneof itself first. */
  1366. o->parent = m;
  1367. upb_strtable_insert(&m->ntof, upb_oneofdef_name(o), upb_value_ptr(o));
  1368. upb_ref2(o, m);
  1369. upb_ref2(m, o);
  1370. /* Add each field of the oneof directly to the msgdef. */
  1371. for (upb_oneof_begin(&it, o); !upb_oneof_done(&it); upb_oneof_next(&it)) {
  1372. upb_fielddef *f = upb_oneof_iter_field(&it);
  1373. add_field(m, f, NULL);
  1374. }
  1375. if (ref_donor) upb_oneofdef_unref(o, ref_donor);
  1376. return true;
  1377. }
  1378. const upb_fielddef *upb_msgdef_itof(const upb_msgdef *m, uint32_t i) {
  1379. upb_value val;
  1380. return upb_inttable_lookup32(&m->itof, i, &val) ?
  1381. upb_value_getptr(val) : NULL;
  1382. }
  1383. const upb_fielddef *upb_msgdef_ntof(const upb_msgdef *m, const char *name,
  1384. size_t len) {
  1385. upb_value val;
  1386. if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
  1387. return NULL;
  1388. }
  1389. return upb_trygetfield(upb_value_getptr(val));
  1390. }
  1391. const upb_oneofdef *upb_msgdef_ntoo(const upb_msgdef *m, const char *name,
  1392. size_t len) {
  1393. upb_value val;
  1394. if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
  1395. return NULL;
  1396. }
  1397. return upb_trygetoneof(upb_value_getptr(val));
  1398. }
  1399. bool upb_msgdef_lookupname(const upb_msgdef *m, const char *name, size_t len,
  1400. const upb_fielddef **f, const upb_oneofdef **o) {
  1401. upb_value val;
  1402. if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
  1403. return false;
  1404. }
  1405. *o = upb_trygetoneof(upb_value_getptr(val));
  1406. *f = upb_trygetfield(upb_value_getptr(val));
  1407. assert((*o != NULL) ^ (*f != NULL)); /* Exactly one of the two should be set. */
  1408. return true;
  1409. }
  1410. int upb_msgdef_numfields(const upb_msgdef *m) {
  1411. /* The number table contains only fields. */
  1412. return upb_inttable_count(&m->itof);
  1413. }
  1414. int upb_msgdef_numoneofs(const upb_msgdef *m) {
  1415. /* The name table includes oneofs, and the number table does not. */
  1416. return upb_strtable_count(&m->ntof) - upb_inttable_count(&m->itof);
  1417. }
  1418. void upb_msgdef_setmapentry(upb_msgdef *m, bool map_entry) {
  1419. assert(!upb_msgdef_isfrozen(m));
  1420. m->map_entry = map_entry;
  1421. }
  1422. bool upb_msgdef_mapentry(const upb_msgdef *m) {
  1423. return m->map_entry;
  1424. }
  1425. void upb_msg_field_begin(upb_msg_field_iter *iter, const upb_msgdef *m) {
  1426. upb_inttable_begin(iter, &m->itof);
  1427. }
  1428. void upb_msg_field_next(upb_msg_field_iter *iter) { upb_inttable_next(iter); }
  1429. bool upb_msg_field_done(const upb_msg_field_iter *iter) {
  1430. return upb_inttable_done(iter);
  1431. }
  1432. upb_fielddef *upb_msg_iter_field(const upb_msg_field_iter *iter) {
  1433. return (upb_fielddef*)upb_value_getptr(upb_inttable_iter_value(iter));
  1434. }
  1435. void upb_msg_field_iter_setdone(upb_msg_field_iter *iter) {
  1436. upb_inttable_iter_setdone(iter);
  1437. }
  1438. void upb_msg_oneof_begin(upb_msg_oneof_iter *iter, const upb_msgdef *m) {
  1439. upb_strtable_begin(iter, &m->ntof);
  1440. /* We need to skip past any initial fields. */
  1441. while (!upb_strtable_done(iter) &&
  1442. !upb_isoneof(upb_value_getptr(upb_strtable_iter_value(iter)))) {
  1443. upb_strtable_next(iter);
  1444. }
  1445. }
  1446. void upb_msg_oneof_next(upb_msg_oneof_iter *iter) {
  1447. /* We need to skip past fields to return only oneofs. */
  1448. do {
  1449. upb_strtable_next(iter);
  1450. } while (!upb_strtable_done(iter) &&
  1451. !upb_isoneof(upb_value_getptr(upb_strtable_iter_value(iter))));
  1452. }
  1453. bool upb_msg_oneof_done(const upb_msg_oneof_iter *iter) {
  1454. return upb_strtable_done(iter);
  1455. }
  1456. upb_oneofdef *upb_msg_iter_oneof(const upb_msg_oneof_iter *iter) {
  1457. return (upb_oneofdef*)upb_value_getptr(upb_strtable_iter_value(iter));
  1458. }
  1459. void upb_msg_oneof_iter_setdone(upb_msg_oneof_iter *iter) {
  1460. upb_strtable_iter_setdone(iter);
  1461. }
  1462. /* upb_oneofdef ***************************************************************/
  1463. static void visitoneof(const upb_refcounted *r, upb_refcounted_visit *visit,
  1464. void *closure) {
  1465. const upb_oneofdef *o = (const upb_oneofdef*)r;
  1466. upb_oneof_iter i;
  1467. for (upb_oneof_begin(&i, o); !upb_oneof_done(&i); upb_oneof_next(&i)) {
  1468. const upb_fielddef *f = upb_oneof_iter_field(&i);
  1469. visit(r, upb_fielddef_upcast2(f), closure);
  1470. }
  1471. if (o->parent) {
  1472. visit(r, upb_msgdef_upcast2(o->parent), closure);
  1473. }
  1474. }
  1475. static void freeoneof(upb_refcounted *r) {
  1476. upb_oneofdef *o = (upb_oneofdef*)r;
  1477. upb_strtable_uninit(&o->ntof);
  1478. upb_inttable_uninit(&o->itof);
  1479. upb_gfree((void*)o->name);
  1480. upb_gfree(o);
  1481. }
  1482. const struct upb_refcounted_vtbl upb_oneofdef_vtbl = {visitoneof, freeoneof};
  1483. upb_oneofdef *upb_oneofdef_new(const void *owner) {
  1484. upb_oneofdef *o = upb_gmalloc(sizeof(*o));
  1485. if (!o) {
  1486. return NULL;
  1487. }
  1488. o->parent = NULL;
  1489. o->name = NULL;
  1490. if (!upb_refcounted_init(upb_oneofdef_upcast_mutable(o), &upb_oneofdef_vtbl,
  1491. owner)) {
  1492. goto err2;
  1493. }
  1494. if (!upb_inttable_init(&o->itof, UPB_CTYPE_PTR)) goto err2;
  1495. if (!upb_strtable_init(&o->ntof, UPB_CTYPE_PTR)) goto err1;
  1496. return o;
  1497. err1:
  1498. upb_inttable_uninit(&o->itof);
  1499. err2:
  1500. upb_gfree(o);
  1501. return NULL;
  1502. }
  1503. upb_oneofdef *upb_oneofdef_dup(const upb_oneofdef *o, const void *owner) {
  1504. bool ok;
  1505. upb_oneof_iter i;
  1506. upb_oneofdef *newo = upb_oneofdef_new(owner);
  1507. if (!newo) return NULL;
  1508. ok = upb_oneofdef_setname(newo, upb_oneofdef_name(o), NULL);
  1509. UPB_ASSERT_VAR(ok, ok);
  1510. for (upb_oneof_begin(&i, o); !upb_oneof_done(&i); upb_oneof_next(&i)) {
  1511. upb_fielddef *f = upb_fielddef_dup(upb_oneof_iter_field(&i), &f);
  1512. if (!f || !upb_oneofdef_addfield(newo, f, &f, NULL)) {
  1513. upb_oneofdef_unref(newo, owner);
  1514. return NULL;
  1515. }
  1516. }
  1517. return newo;
  1518. }
  1519. const char *upb_oneofdef_name(const upb_oneofdef *o) { return o->name; }
  1520. bool upb_oneofdef_setname(upb_oneofdef *o, const char *name, upb_status *s) {
  1521. assert(!upb_oneofdef_isfrozen(o));
  1522. if (upb_oneofdef_containingtype(o)) {
  1523. upb_status_seterrmsg(s, "oneof already added to a message");
  1524. return false;
  1525. }
  1526. if (!upb_isident(name, strlen(name), true, s)) {
  1527. return false;
  1528. }
  1529. name = upb_gstrdup(name);
  1530. if (!name) {
  1531. upb_status_seterrmsg(s, "One of memory");
  1532. return false;
  1533. }
  1534. upb_gfree((void*)o->name);
  1535. o->name = name;
  1536. return true;
  1537. }
  1538. const upb_msgdef *upb_oneofdef_containingtype(const upb_oneofdef *o) {
  1539. return o->parent;
  1540. }
  1541. int upb_oneofdef_numfields(const upb_oneofdef *o) {
  1542. return upb_strtable_count(&o->ntof);
  1543. }
  1544. bool upb_oneofdef_addfield(upb_oneofdef *o, upb_fielddef *f,
  1545. const void *ref_donor,
  1546. upb_status *s) {
  1547. assert(!upb_oneofdef_isfrozen(o));
  1548. assert(!o->parent || !upb_msgdef_isfrozen(o->parent));
  1549. /* This method is idempotent. Check if |f| is already part of this oneofdef
  1550. * and return immediately if so. */
  1551. if (upb_fielddef_containingoneof(f) == o) {
  1552. return true;
  1553. }
  1554. /* The field must have an OPTIONAL label. */
  1555. if (upb_fielddef_label(f) != UPB_LABEL_OPTIONAL) {
  1556. upb_status_seterrmsg(s, "fields in oneof must have OPTIONAL label");
  1557. return false;
  1558. }
  1559. /* Check that no field with this name or number exists already in the oneof.
  1560. * Also check that the field is not already part of a oneof. */
  1561. if (upb_fielddef_name(f) == NULL || upb_fielddef_number(f) == 0) {
  1562. upb_status_seterrmsg(s, "field name or number were not set");
  1563. return false;
  1564. } else if (upb_oneofdef_itof(o, upb_fielddef_number(f)) ||
  1565. upb_oneofdef_ntofz(o, upb_fielddef_name(f))) {
  1566. upb_status_seterrmsg(s, "duplicate field name or number");
  1567. return false;
  1568. } else if (upb_fielddef_containingoneof(f) != NULL) {
  1569. upb_status_seterrmsg(s, "fielddef already belongs to a oneof");
  1570. return false;
  1571. }
  1572. /* We allow adding a field to the oneof either if the field is not part of a
  1573. * msgdef, or if it is and we are also part of the same msgdef. */
  1574. if (o->parent == NULL) {
  1575. /* If we're not in a msgdef, the field cannot be either. Otherwise we would
  1576. * need to magically add this oneof to a msgdef to remain consistent, which
  1577. * is surprising behavior. */
  1578. if (upb_fielddef_containingtype(f) != NULL) {
  1579. upb_status_seterrmsg(s, "fielddef already belongs to a message, but "
  1580. "oneof does not");
  1581. return false;
  1582. }
  1583. } else {
  1584. /* If we're in a msgdef, the user can add fields that either aren't in any
  1585. * msgdef (in which case they're added to our msgdef) or already a part of
  1586. * our msgdef. */
  1587. if (upb_fielddef_containingtype(f) != NULL &&
  1588. upb_fielddef_containingtype(f) != o->parent) {
  1589. upb_status_seterrmsg(s, "fielddef belongs to a different message "
  1590. "than oneof");
  1591. return false;
  1592. }
  1593. }
  1594. /* Commit phase. First add the field to our parent msgdef, if any, because
  1595. * that may fail; then add the field to our own tables. */
  1596. if (o->parent != NULL && upb_fielddef_containingtype(f) == NULL) {
  1597. if (!upb_msgdef_addfield((upb_msgdef*)o->parent, f, NULL, s)) {
  1598. return false;
  1599. }
  1600. }
  1601. release_containingtype(f);
  1602. f->oneof = o;
  1603. upb_inttable_insert(&o->itof, upb_fielddef_number(f), upb_value_ptr(f));
  1604. upb_strtable_insert(&o->ntof, upb_fielddef_name(f), upb_value_ptr(f));
  1605. upb_ref2(f, o);
  1606. upb_ref2(o, f);
  1607. if (ref_donor) upb_fielddef_unref(f, ref_donor);
  1608. return true;
  1609. }
  1610. const upb_fielddef *upb_oneofdef_ntof(const upb_oneofdef *o,
  1611. const char *name, size_t length) {
  1612. upb_value val;
  1613. return upb_strtable_lookup2(&o->ntof, name, length, &val) ?
  1614. upb_value_getptr(val) : NULL;
  1615. }
  1616. const upb_fielddef *upb_oneofdef_itof(const upb_oneofdef *o, uint32_t num) {
  1617. upb_value val;
  1618. return upb_inttable_lookup32(&o->itof, num, &val) ?
  1619. upb_value_getptr(val) : NULL;
  1620. }
  1621. void upb_oneof_begin(upb_oneof_iter *iter, const upb_oneofdef *o) {
  1622. upb_inttable_begin(iter, &o->itof);
  1623. }
  1624. void upb_oneof_next(upb_oneof_iter *iter) {
  1625. upb_inttable_next(iter);
  1626. }
  1627. bool upb_oneof_done(upb_oneof_iter *iter) {
  1628. return upb_inttable_done(iter);
  1629. }
  1630. upb_fielddef *upb_oneof_iter_field(const upb_oneof_iter *iter) {
  1631. return (upb_fielddef*)upb_value_getptr(upb_inttable_iter_value(iter));
  1632. }
  1633. void upb_oneof_iter_setdone(upb_oneof_iter *iter) {
  1634. upb_inttable_iter_setdone(iter);
  1635. }
  1636. /* upb_filedef ****************************************************************/
  1637. static void visitfiledef(const upb_refcounted *r, upb_refcounted_visit *visit,
  1638. void *closure) {
  1639. const upb_filedef *f = (const upb_filedef*)r;
  1640. size_t i;
  1641. for(i = 0; i < upb_filedef_defcount(f); i++) {
  1642. visit(r, upb_def_upcast(upb_filedef_def(f, i)), closure);
  1643. }
  1644. }
  1645. static void freefiledef(upb_refcounted *r) {
  1646. upb_filedef *f = (upb_filedef*)r;
  1647. size_t i;
  1648. for(i = 0; i < upb_filedef_depcount(f); i++) {
  1649. upb_filedef_unref(upb_filedef_dep(f, i), f);
  1650. }
  1651. upb_inttable_uninit(&f->defs);
  1652. upb_inttable_uninit(&f->deps);
  1653. upb_gfree((void*)f->name);
  1654. upb_gfree((void*)f->package);
  1655. upb_gfree(f);
  1656. }
  1657. const struct upb_refcounted_vtbl upb_filedef_vtbl = {visitfiledef, freefiledef};
  1658. upb_filedef *upb_filedef_new(const void *owner) {
  1659. upb_filedef *f = upb_gmalloc(sizeof(*f));
  1660. if (!f) {
  1661. return NULL;
  1662. }
  1663. f->package = NULL;
  1664. f->name = NULL;
  1665. f->syntax = UPB_SYNTAX_PROTO2;
  1666. if (!upb_refcounted_init(upb_filedef_upcast_mutable(f), &upb_filedef_vtbl,
  1667. owner)) {
  1668. goto err;
  1669. }
  1670. if (!upb_inttable_init(&f->defs, UPB_CTYPE_CONSTPTR)) {
  1671. goto err;
  1672. }
  1673. if (!upb_inttable_init(&f->deps, UPB_CTYPE_CONSTPTR)) {
  1674. goto err2;
  1675. }
  1676. return f;
  1677. err2:
  1678. upb_inttable_uninit(&f->defs);
  1679. err:
  1680. upb_gfree(f);
  1681. return NULL;
  1682. }
  1683. const char *upb_filedef_name(const upb_filedef *f) {
  1684. return f->name;
  1685. }
  1686. const char *upb_filedef_package(const upb_filedef *f) {
  1687. return f->package;
  1688. }
  1689. upb_syntax_t upb_filedef_syntax(const upb_filedef *f) {
  1690. return f->syntax;
  1691. }
  1692. size_t upb_filedef_defcount(const upb_filedef *f) {
  1693. return upb_inttable_count(&f->defs);
  1694. }
  1695. size_t upb_filedef_depcount(const upb_filedef *f) {
  1696. return upb_inttable_count(&f->deps);
  1697. }
  1698. const upb_def *upb_filedef_def(const upb_filedef *f, size_t i) {
  1699. upb_value v;
  1700. if (upb_inttable_lookup32(&f->defs, i, &v)) {
  1701. return upb_value_getconstptr(v);
  1702. } else {
  1703. return NULL;
  1704. }
  1705. }
  1706. const upb_filedef *upb_filedef_dep(const upb_filedef *f, size_t i) {
  1707. upb_value v;
  1708. if (upb_inttable_lookup32(&f->deps, i, &v)) {
  1709. return upb_value_getconstptr(v);
  1710. } else {
  1711. return NULL;
  1712. }
  1713. }
  1714. bool upb_filedef_setname(upb_filedef *f, const char *name, upb_status *s) {
  1715. name = upb_gstrdup(name);
  1716. if (!name) {
  1717. upb_upberr_setoom(s);
  1718. return false;
  1719. }
  1720. upb_gfree((void*)f->name);
  1721. f->name = name;
  1722. return true;
  1723. }
  1724. bool upb_filedef_setpackage(upb_filedef *f, const char *package,
  1725. upb_status *s) {
  1726. if (!upb_isident(package, strlen(package), true, s)) return false;
  1727. package = upb_gstrdup(package);
  1728. if (!package) {
  1729. upb_upberr_setoom(s);
  1730. return false;
  1731. }
  1732. upb_gfree((void*)f->package);
  1733. f->package = package;
  1734. return true;
  1735. }
  1736. bool upb_filedef_setsyntax(upb_filedef *f, upb_syntax_t syntax,
  1737. upb_status *s) {
  1738. UPB_UNUSED(s);
  1739. if (syntax != UPB_SYNTAX_PROTO2 &&
  1740. syntax != UPB_SYNTAX_PROTO3) {
  1741. upb_status_seterrmsg(s, "Unknown syntax value.");
  1742. return false;
  1743. }
  1744. f->syntax = syntax;
  1745. {
  1746. /* Set all messages in this file to match. */
  1747. size_t i;
  1748. for (i = 0; i < upb_filedef_defcount(f); i++) {
  1749. /* Casting const away is safe since all defs in mutable filedef must
  1750. * also be mutable. */
  1751. upb_def *def = (upb_def*)upb_filedef_def(f, i);
  1752. upb_msgdef *m = upb_dyncast_msgdef_mutable(def);
  1753. if (m) {
  1754. m->syntax = syntax;
  1755. }
  1756. }
  1757. }
  1758. return true;
  1759. }
  1760. bool upb_filedef_adddef(upb_filedef *f, upb_def *def, const void *ref_donor,
  1761. upb_status *s) {
  1762. if (def->file) {
  1763. upb_status_seterrmsg(s, "Def is already part of another filedef.");
  1764. return false;
  1765. }
  1766. if (upb_inttable_push(&f->defs, upb_value_constptr(def))) {
  1767. def->file = f;
  1768. upb_ref2(def, f);
  1769. if (ref_donor) upb_def_unref(def, ref_donor);
  1770. if (def->type == UPB_DEF_MSG) {
  1771. upb_downcast_msgdef_mutable(def)->syntax = f->syntax;
  1772. }
  1773. return true;
  1774. } else {
  1775. upb_upberr_setoom(s);
  1776. return false;
  1777. }
  1778. }
  1779. bool upb_filedef_adddep(upb_filedef *f, const upb_filedef *dep) {
  1780. if (upb_inttable_push(&f->deps, upb_value_constptr(dep))) {
  1781. /* Regular ref instead of ref2 because files can't form cycles. */
  1782. upb_filedef_ref(dep, f);
  1783. return true;
  1784. } else {
  1785. return false;
  1786. }
  1787. }
  1788. /*
  1789. ** TODO(haberman): it's unclear whether a lot of the consistency checks should
  1790. ** assert() or return false.
  1791. */
  1792. #include <string.h>
  1793. static void *upb_calloc(size_t size) {
  1794. void *mem = upb_gmalloc(size);
  1795. if (mem) {
  1796. memset(mem, 0, size);
  1797. }
  1798. return mem;
  1799. }
  1800. /* Defined for the sole purpose of having a unique pointer value for
  1801. * UPB_NO_CLOSURE. */
  1802. char _upb_noclosure;
  1803. static void freehandlers(upb_refcounted *r) {
  1804. upb_handlers *h = (upb_handlers*)r;
  1805. upb_inttable_iter i;
  1806. upb_inttable_begin(&i, &h->cleanup_);
  1807. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  1808. void *val = (void*)upb_inttable_iter_key(&i);
  1809. upb_value func_val = upb_inttable_iter_value(&i);
  1810. upb_handlerfree *func = upb_value_getfptr(func_val);
  1811. func(val);
  1812. }
  1813. upb_inttable_uninit(&h->cleanup_);
  1814. upb_msgdef_unref(h->msg, h);
  1815. upb_gfree(h->sub);
  1816. upb_gfree(h);
  1817. }
  1818. static void visithandlers(const upb_refcounted *r, upb_refcounted_visit *visit,
  1819. void *closure) {
  1820. const upb_handlers *h = (const upb_handlers*)r;
  1821. upb_msg_field_iter i;
  1822. for(upb_msg_field_begin(&i, h->msg);
  1823. !upb_msg_field_done(&i);
  1824. upb_msg_field_next(&i)) {
  1825. upb_fielddef *f = upb_msg_iter_field(&i);
  1826. const upb_handlers *sub;
  1827. if (!upb_fielddef_issubmsg(f)) continue;
  1828. sub = upb_handlers_getsubhandlers(h, f);
  1829. if (sub) visit(r, upb_handlers_upcast(sub), closure);
  1830. }
  1831. }
  1832. static const struct upb_refcounted_vtbl vtbl = {visithandlers, freehandlers};
  1833. typedef struct {
  1834. upb_inttable tab; /* maps upb_msgdef* -> upb_handlers*. */
  1835. upb_handlers_callback *callback;
  1836. const void *closure;
  1837. } dfs_state;
  1838. /* TODO(haberman): discard upb_handlers* objects that do not actually have any
  1839. * handlers set and cannot reach any upb_handlers* object that does. This is
  1840. * slightly tricky to do correctly. */
  1841. static upb_handlers *newformsg(const upb_msgdef *m, const void *owner,
  1842. dfs_state *s) {
  1843. upb_msg_field_iter i;
  1844. upb_handlers *h = upb_handlers_new(m, owner);
  1845. if (!h) return NULL;
  1846. if (!upb_inttable_insertptr(&s->tab, m, upb_value_ptr(h))) goto oom;
  1847. s->callback(s->closure, h);
  1848. /* For each submessage field, get or create a handlers object and set it as
  1849. * the subhandlers. */
  1850. for(upb_msg_field_begin(&i, m);
  1851. !upb_msg_field_done(&i);
  1852. upb_msg_field_next(&i)) {
  1853. upb_fielddef *f = upb_msg_iter_field(&i);
  1854. const upb_msgdef *subdef;
  1855. upb_value subm_ent;
  1856. if (!upb_fielddef_issubmsg(f)) continue;
  1857. subdef = upb_downcast_msgdef(upb_fielddef_subdef(f));
  1858. if (upb_inttable_lookupptr(&s->tab, subdef, &subm_ent)) {
  1859. upb_handlers_setsubhandlers(h, f, upb_value_getptr(subm_ent));
  1860. } else {
  1861. upb_handlers *sub_mh = newformsg(subdef, &sub_mh, s);
  1862. if (!sub_mh) goto oom;
  1863. upb_handlers_setsubhandlers(h, f, sub_mh);
  1864. upb_handlers_unref(sub_mh, &sub_mh);
  1865. }
  1866. }
  1867. return h;
  1868. oom:
  1869. upb_handlers_unref(h, owner);
  1870. return NULL;
  1871. }
  1872. /* Given a selector for a STARTSUBMSG handler, resolves to a pointer to the
  1873. * subhandlers for this submessage field. */
  1874. #define SUBH(h, selector) (h->sub[selector])
  1875. /* The selector for a submessage field is the field index. */
  1876. #define SUBH_F(h, f) SUBH(h, f->index_)
  1877. static int32_t trygetsel(upb_handlers *h, const upb_fielddef *f,
  1878. upb_handlertype_t type) {
  1879. upb_selector_t sel;
  1880. assert(!upb_handlers_isfrozen(h));
  1881. if (upb_handlers_msgdef(h) != upb_fielddef_containingtype(f)) {
  1882. upb_status_seterrf(
  1883. &h->status_, "type mismatch: field %s does not belong to message %s",
  1884. upb_fielddef_name(f), upb_msgdef_fullname(upb_handlers_msgdef(h)));
  1885. return -1;
  1886. }
  1887. if (!upb_handlers_getselector(f, type, &sel)) {
  1888. upb_status_seterrf(
  1889. &h->status_,
  1890. "type mismatch: cannot register handler type %d for field %s",
  1891. type, upb_fielddef_name(f));
  1892. return -1;
  1893. }
  1894. return sel;
  1895. }
  1896. static upb_selector_t handlers_getsel(upb_handlers *h, const upb_fielddef *f,
  1897. upb_handlertype_t type) {
  1898. int32_t sel = trygetsel(h, f, type);
  1899. assert(sel >= 0);
  1900. return sel;
  1901. }
  1902. static const void **returntype(upb_handlers *h, const upb_fielddef *f,
  1903. upb_handlertype_t type) {
  1904. return &h->table[handlers_getsel(h, f, type)].attr.return_closure_type_;
  1905. }
  1906. static bool doset(upb_handlers *h, int32_t sel, const upb_fielddef *f,
  1907. upb_handlertype_t type, upb_func *func,
  1908. upb_handlerattr *attr) {
  1909. upb_handlerattr set_attr = UPB_HANDLERATTR_INITIALIZER;
  1910. const void *closure_type;
  1911. const void **context_closure_type;
  1912. assert(!upb_handlers_isfrozen(h));
  1913. if (sel < 0) {
  1914. upb_status_seterrmsg(&h->status_,
  1915. "incorrect handler type for this field.");
  1916. return false;
  1917. }
  1918. if (h->table[sel].func) {
  1919. upb_status_seterrmsg(&h->status_,
  1920. "cannot change handler once it has been set.");
  1921. return false;
  1922. }
  1923. if (attr) {
  1924. set_attr = *attr;
  1925. }
  1926. /* Check that the given closure type matches the closure type that has been
  1927. * established for this context (if any). */
  1928. closure_type = upb_handlerattr_closuretype(&set_attr);
  1929. if (type == UPB_HANDLER_STRING) {
  1930. context_closure_type = returntype(h, f, UPB_HANDLER_STARTSTR);
  1931. } else if (f && upb_fielddef_isseq(f) &&
  1932. type != UPB_HANDLER_STARTSEQ &&
  1933. type != UPB_HANDLER_ENDSEQ) {
  1934. context_closure_type = returntype(h, f, UPB_HANDLER_STARTSEQ);
  1935. } else {
  1936. context_closure_type = &h->top_closure_type;
  1937. }
  1938. if (closure_type && *context_closure_type &&
  1939. closure_type != *context_closure_type) {
  1940. /* TODO(haberman): better message for debugging. */
  1941. if (f) {
  1942. upb_status_seterrf(&h->status_,
  1943. "closure type does not match for field %s",
  1944. upb_fielddef_name(f));
  1945. } else {
  1946. upb_status_seterrmsg(
  1947. &h->status_, "closure type does not match for message-level handler");
  1948. }
  1949. return false;
  1950. }
  1951. if (closure_type)
  1952. *context_closure_type = closure_type;
  1953. /* If this is a STARTSEQ or STARTSTR handler, check that the returned pointer
  1954. * matches any pre-existing expectations about what type is expected. */
  1955. if (type == UPB_HANDLER_STARTSEQ || type == UPB_HANDLER_STARTSTR) {
  1956. const void *return_type = upb_handlerattr_returnclosuretype(&set_attr);
  1957. const void *table_return_type =
  1958. upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  1959. if (return_type && table_return_type && return_type != table_return_type) {
  1960. upb_status_seterrmsg(&h->status_, "closure return type does not match");
  1961. return false;
  1962. }
  1963. if (table_return_type && !return_type)
  1964. upb_handlerattr_setreturnclosuretype(&set_attr, table_return_type);
  1965. }
  1966. h->table[sel].func = (upb_func*)func;
  1967. h->table[sel].attr = set_attr;
  1968. return true;
  1969. }
  1970. /* Returns the effective closure type for this handler (which will propagate
  1971. * from outer frames if this frame has no START* handler). Not implemented for
  1972. * UPB_HANDLER_STRING at the moment since this is not needed. Returns NULL is
  1973. * the effective closure type is unspecified (either no handler was registered
  1974. * to specify it or the handler that was registered did not specify the closure
  1975. * type). */
  1976. const void *effective_closure_type(upb_handlers *h, const upb_fielddef *f,
  1977. upb_handlertype_t type) {
  1978. const void *ret;
  1979. upb_selector_t sel;
  1980. assert(type != UPB_HANDLER_STRING);
  1981. ret = h->top_closure_type;
  1982. if (upb_fielddef_isseq(f) &&
  1983. type != UPB_HANDLER_STARTSEQ &&
  1984. type != UPB_HANDLER_ENDSEQ &&
  1985. h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSEQ)].func) {
  1986. ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  1987. }
  1988. if (type == UPB_HANDLER_STRING &&
  1989. h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSTR)].func) {
  1990. ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  1991. }
  1992. /* The effective type of the submessage; not used yet.
  1993. * if (type == SUBMESSAGE &&
  1994. * h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSUBMSG)].func) {
  1995. * ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  1996. * } */
  1997. return ret;
  1998. }
  1999. /* Checks whether the START* handler specified by f & type is missing even
  2000. * though it is required to convert the established type of an outer frame
  2001. * ("closure_type") into the established type of an inner frame (represented in
  2002. * the return closure type of this handler's attr. */
  2003. bool checkstart(upb_handlers *h, const upb_fielddef *f, upb_handlertype_t type,
  2004. upb_status *status) {
  2005. const void *closure_type;
  2006. const upb_handlerattr *attr;
  2007. const void *return_closure_type;
  2008. upb_selector_t sel = handlers_getsel(h, f, type);
  2009. if (h->table[sel].func) return true;
  2010. closure_type = effective_closure_type(h, f, type);
  2011. attr = &h->table[sel].attr;
  2012. return_closure_type = upb_handlerattr_returnclosuretype(attr);
  2013. if (closure_type && return_closure_type &&
  2014. closure_type != return_closure_type) {
  2015. upb_status_seterrf(status,
  2016. "expected start handler to return sub type for field %f",
  2017. upb_fielddef_name(f));
  2018. return false;
  2019. }
  2020. return true;
  2021. }
  2022. /* Public interface ***********************************************************/
  2023. upb_handlers *upb_handlers_new(const upb_msgdef *md, const void *owner) {
  2024. int extra;
  2025. upb_handlers *h;
  2026. assert(upb_msgdef_isfrozen(md));
  2027. extra = sizeof(upb_handlers_tabent) * (md->selector_count - 1);
  2028. h = upb_calloc(sizeof(*h) + extra);
  2029. if (!h) return NULL;
  2030. h->msg = md;
  2031. upb_msgdef_ref(h->msg, h);
  2032. upb_status_clear(&h->status_);
  2033. if (md->submsg_field_count > 0) {
  2034. h->sub = upb_calloc(md->submsg_field_count * sizeof(*h->sub));
  2035. if (!h->sub) goto oom;
  2036. } else {
  2037. h->sub = 0;
  2038. }
  2039. if (!upb_refcounted_init(upb_handlers_upcast_mutable(h), &vtbl, owner))
  2040. goto oom;
  2041. if (!upb_inttable_init(&h->cleanup_, UPB_CTYPE_FPTR)) goto oom;
  2042. /* calloc() above initialized all handlers to NULL. */
  2043. return h;
  2044. oom:
  2045. freehandlers(upb_handlers_upcast_mutable(h));
  2046. return NULL;
  2047. }
  2048. const upb_handlers *upb_handlers_newfrozen(const upb_msgdef *m,
  2049. const void *owner,
  2050. upb_handlers_callback *callback,
  2051. const void *closure) {
  2052. dfs_state state;
  2053. upb_handlers *ret;
  2054. bool ok;
  2055. upb_refcounted *r;
  2056. state.callback = callback;
  2057. state.closure = closure;
  2058. if (!upb_inttable_init(&state.tab, UPB_CTYPE_PTR)) return NULL;
  2059. ret = newformsg(m, owner, &state);
  2060. upb_inttable_uninit(&state.tab);
  2061. if (!ret) return NULL;
  2062. r = upb_handlers_upcast_mutable(ret);
  2063. ok = upb_refcounted_freeze(&r, 1, NULL, UPB_MAX_HANDLER_DEPTH);
  2064. UPB_ASSERT_VAR(ok, ok);
  2065. return ret;
  2066. }
  2067. const upb_status *upb_handlers_status(upb_handlers *h) {
  2068. assert(!upb_handlers_isfrozen(h));
  2069. return &h->status_;
  2070. }
  2071. void upb_handlers_clearerr(upb_handlers *h) {
  2072. assert(!upb_handlers_isfrozen(h));
  2073. upb_status_clear(&h->status_);
  2074. }
  2075. #define SETTER(name, handlerctype, handlertype) \
  2076. bool upb_handlers_set ## name(upb_handlers *h, const upb_fielddef *f, \
  2077. handlerctype func, upb_handlerattr *attr) { \
  2078. int32_t sel = trygetsel(h, f, handlertype); \
  2079. return doset(h, sel, f, handlertype, (upb_func*)func, attr); \
  2080. }
  2081. SETTER(int32, upb_int32_handlerfunc*, UPB_HANDLER_INT32)
  2082. SETTER(int64, upb_int64_handlerfunc*, UPB_HANDLER_INT64)
  2083. SETTER(uint32, upb_uint32_handlerfunc*, UPB_HANDLER_UINT32)
  2084. SETTER(uint64, upb_uint64_handlerfunc*, UPB_HANDLER_UINT64)
  2085. SETTER(float, upb_float_handlerfunc*, UPB_HANDLER_FLOAT)
  2086. SETTER(double, upb_double_handlerfunc*, UPB_HANDLER_DOUBLE)
  2087. SETTER(bool, upb_bool_handlerfunc*, UPB_HANDLER_BOOL)
  2088. SETTER(startstr, upb_startstr_handlerfunc*, UPB_HANDLER_STARTSTR)
  2089. SETTER(string, upb_string_handlerfunc*, UPB_HANDLER_STRING)
  2090. SETTER(endstr, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSTR)
  2091. SETTER(startseq, upb_startfield_handlerfunc*, UPB_HANDLER_STARTSEQ)
  2092. SETTER(startsubmsg, upb_startfield_handlerfunc*, UPB_HANDLER_STARTSUBMSG)
  2093. SETTER(endsubmsg, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSUBMSG)
  2094. SETTER(endseq, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSEQ)
  2095. #undef SETTER
  2096. bool upb_handlers_setstartmsg(upb_handlers *h, upb_startmsg_handlerfunc *func,
  2097. upb_handlerattr *attr) {
  2098. return doset(h, UPB_STARTMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
  2099. (upb_func *)func, attr);
  2100. }
  2101. bool upb_handlers_setendmsg(upb_handlers *h, upb_endmsg_handlerfunc *func,
  2102. upb_handlerattr *attr) {
  2103. assert(!upb_handlers_isfrozen(h));
  2104. return doset(h, UPB_ENDMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
  2105. (upb_func *)func, attr);
  2106. }
  2107. bool upb_handlers_setsubhandlers(upb_handlers *h, const upb_fielddef *f,
  2108. const upb_handlers *sub) {
  2109. assert(sub);
  2110. assert(!upb_handlers_isfrozen(h));
  2111. assert(upb_fielddef_issubmsg(f));
  2112. if (SUBH_F(h, f)) return false; /* Can't reset. */
  2113. if (upb_msgdef_upcast(upb_handlers_msgdef(sub)) != upb_fielddef_subdef(f)) {
  2114. return false;
  2115. }
  2116. SUBH_F(h, f) = sub;
  2117. upb_ref2(sub, h);
  2118. return true;
  2119. }
  2120. const upb_handlers *upb_handlers_getsubhandlers(const upb_handlers *h,
  2121. const upb_fielddef *f) {
  2122. assert(upb_fielddef_issubmsg(f));
  2123. return SUBH_F(h, f);
  2124. }
  2125. bool upb_handlers_getattr(const upb_handlers *h, upb_selector_t sel,
  2126. upb_handlerattr *attr) {
  2127. if (!upb_handlers_gethandler(h, sel))
  2128. return false;
  2129. *attr = h->table[sel].attr;
  2130. return true;
  2131. }
  2132. const upb_handlers *upb_handlers_getsubhandlers_sel(const upb_handlers *h,
  2133. upb_selector_t sel) {
  2134. /* STARTSUBMSG selector in sel is the field's selector base. */
  2135. return SUBH(h, sel - UPB_STATIC_SELECTOR_COUNT);
  2136. }
  2137. const upb_msgdef *upb_handlers_msgdef(const upb_handlers *h) { return h->msg; }
  2138. bool upb_handlers_addcleanup(upb_handlers *h, void *p, upb_handlerfree *func) {
  2139. bool ok;
  2140. if (upb_inttable_lookupptr(&h->cleanup_, p, NULL)) {
  2141. return false;
  2142. }
  2143. ok = upb_inttable_insertptr(&h->cleanup_, p, upb_value_fptr(func));
  2144. UPB_ASSERT_VAR(ok, ok);
  2145. return true;
  2146. }
  2147. /* "Static" methods ***********************************************************/
  2148. bool upb_handlers_freeze(upb_handlers *const*handlers, int n, upb_status *s) {
  2149. /* TODO: verify we have a transitive closure. */
  2150. int i;
  2151. for (i = 0; i < n; i++) {
  2152. upb_msg_field_iter j;
  2153. upb_handlers *h = handlers[i];
  2154. if (!upb_ok(&h->status_)) {
  2155. upb_status_seterrf(s, "handlers for message %s had error status: %s",
  2156. upb_msgdef_fullname(upb_handlers_msgdef(h)),
  2157. upb_status_errmsg(&h->status_));
  2158. return false;
  2159. }
  2160. /* Check that there are no closure mismatches due to missing Start* handlers
  2161. * or subhandlers with different type-level types. */
  2162. for(upb_msg_field_begin(&j, h->msg);
  2163. !upb_msg_field_done(&j);
  2164. upb_msg_field_next(&j)) {
  2165. const upb_fielddef *f = upb_msg_iter_field(&j);
  2166. if (upb_fielddef_isseq(f)) {
  2167. if (!checkstart(h, f, UPB_HANDLER_STARTSEQ, s))
  2168. return false;
  2169. }
  2170. if (upb_fielddef_isstring(f)) {
  2171. if (!checkstart(h, f, UPB_HANDLER_STARTSTR, s))
  2172. return false;
  2173. }
  2174. if (upb_fielddef_issubmsg(f)) {
  2175. bool hashandler = false;
  2176. if (upb_handlers_gethandler(
  2177. h, handlers_getsel(h, f, UPB_HANDLER_STARTSUBMSG)) ||
  2178. upb_handlers_gethandler(
  2179. h, handlers_getsel(h, f, UPB_HANDLER_ENDSUBMSG))) {
  2180. hashandler = true;
  2181. }
  2182. if (upb_fielddef_isseq(f) &&
  2183. (upb_handlers_gethandler(
  2184. h, handlers_getsel(h, f, UPB_HANDLER_STARTSEQ)) ||
  2185. upb_handlers_gethandler(
  2186. h, handlers_getsel(h, f, UPB_HANDLER_ENDSEQ)))) {
  2187. hashandler = true;
  2188. }
  2189. if (hashandler && !upb_handlers_getsubhandlers(h, f)) {
  2190. /* For now we add an empty subhandlers in this case. It makes the
  2191. * decoder code generator simpler, because it only has to handle two
  2192. * cases (submessage has handlers or not) as opposed to three
  2193. * (submessage has handlers in enclosing message but no subhandlers).
  2194. *
  2195. * This makes parsing less efficient in the case that we want to
  2196. * notice a submessage but skip its contents (like if we're testing
  2197. * for submessage presence or counting the number of repeated
  2198. * submessages). In this case we will end up parsing the submessage
  2199. * field by field and throwing away the results for each, instead of
  2200. * skipping the whole delimited thing at once. If this is an issue we
  2201. * can revisit it, but do remember that this only arises when you have
  2202. * handlers (startseq/startsubmsg/endsubmsg/endseq) set for the
  2203. * submessage but no subhandlers. The uses cases for this are
  2204. * limited. */
  2205. upb_handlers *sub = upb_handlers_new(upb_fielddef_msgsubdef(f), &sub);
  2206. upb_handlers_setsubhandlers(h, f, sub);
  2207. upb_handlers_unref(sub, &sub);
  2208. }
  2209. /* TODO(haberman): check type of submessage.
  2210. * This is slightly tricky; also consider whether we should check that
  2211. * they match at setsubhandlers time. */
  2212. }
  2213. }
  2214. }
  2215. if (!upb_refcounted_freeze((upb_refcounted*const*)handlers, n, s,
  2216. UPB_MAX_HANDLER_DEPTH)) {
  2217. return false;
  2218. }
  2219. return true;
  2220. }
  2221. upb_handlertype_t upb_handlers_getprimitivehandlertype(const upb_fielddef *f) {
  2222. switch (upb_fielddef_type(f)) {
  2223. case UPB_TYPE_INT32:
  2224. case UPB_TYPE_ENUM: return UPB_HANDLER_INT32;
  2225. case UPB_TYPE_INT64: return UPB_HANDLER_INT64;
  2226. case UPB_TYPE_UINT32: return UPB_HANDLER_UINT32;
  2227. case UPB_TYPE_UINT64: return UPB_HANDLER_UINT64;
  2228. case UPB_TYPE_FLOAT: return UPB_HANDLER_FLOAT;
  2229. case UPB_TYPE_DOUBLE: return UPB_HANDLER_DOUBLE;
  2230. case UPB_TYPE_BOOL: return UPB_HANDLER_BOOL;
  2231. default: assert(false); return -1; /* Invalid input. */
  2232. }
  2233. }
  2234. bool upb_handlers_getselector(const upb_fielddef *f, upb_handlertype_t type,
  2235. upb_selector_t *s) {
  2236. switch (type) {
  2237. case UPB_HANDLER_INT32:
  2238. case UPB_HANDLER_INT64:
  2239. case UPB_HANDLER_UINT32:
  2240. case UPB_HANDLER_UINT64:
  2241. case UPB_HANDLER_FLOAT:
  2242. case UPB_HANDLER_DOUBLE:
  2243. case UPB_HANDLER_BOOL:
  2244. if (!upb_fielddef_isprimitive(f) ||
  2245. upb_handlers_getprimitivehandlertype(f) != type)
  2246. return false;
  2247. *s = f->selector_base;
  2248. break;
  2249. case UPB_HANDLER_STRING:
  2250. if (upb_fielddef_isstring(f)) {
  2251. *s = f->selector_base;
  2252. } else if (upb_fielddef_lazy(f)) {
  2253. *s = f->selector_base + 3;
  2254. } else {
  2255. return false;
  2256. }
  2257. break;
  2258. case UPB_HANDLER_STARTSTR:
  2259. if (upb_fielddef_isstring(f) || upb_fielddef_lazy(f)) {
  2260. *s = f->selector_base + 1;
  2261. } else {
  2262. return false;
  2263. }
  2264. break;
  2265. case UPB_HANDLER_ENDSTR:
  2266. if (upb_fielddef_isstring(f) || upb_fielddef_lazy(f)) {
  2267. *s = f->selector_base + 2;
  2268. } else {
  2269. return false;
  2270. }
  2271. break;
  2272. case UPB_HANDLER_STARTSEQ:
  2273. if (!upb_fielddef_isseq(f)) return false;
  2274. *s = f->selector_base - 2;
  2275. break;
  2276. case UPB_HANDLER_ENDSEQ:
  2277. if (!upb_fielddef_isseq(f)) return false;
  2278. *s = f->selector_base - 1;
  2279. break;
  2280. case UPB_HANDLER_STARTSUBMSG:
  2281. if (!upb_fielddef_issubmsg(f)) return false;
  2282. /* Selectors for STARTSUBMSG are at the beginning of the table so that the
  2283. * selector can also be used as an index into the "sub" array of
  2284. * subhandlers. The indexes for the two into these two tables are the
  2285. * same, except that in the handler table the static selectors come first. */
  2286. *s = f->index_ + UPB_STATIC_SELECTOR_COUNT;
  2287. break;
  2288. case UPB_HANDLER_ENDSUBMSG:
  2289. if (!upb_fielddef_issubmsg(f)) return false;
  2290. *s = f->selector_base;
  2291. break;
  2292. }
  2293. assert((size_t)*s < upb_fielddef_containingtype(f)->selector_count);
  2294. return true;
  2295. }
  2296. uint32_t upb_handlers_selectorbaseoffset(const upb_fielddef *f) {
  2297. return upb_fielddef_isseq(f) ? 2 : 0;
  2298. }
  2299. uint32_t upb_handlers_selectorcount(const upb_fielddef *f) {
  2300. uint32_t ret = 1;
  2301. if (upb_fielddef_isseq(f)) ret += 2; /* STARTSEQ/ENDSEQ */
  2302. if (upb_fielddef_isstring(f)) ret += 2; /* [STRING]/STARTSTR/ENDSTR */
  2303. if (upb_fielddef_issubmsg(f)) {
  2304. /* ENDSUBMSG (STARTSUBMSG is at table beginning) */
  2305. ret += 0;
  2306. if (upb_fielddef_lazy(f)) {
  2307. /* STARTSTR/ENDSTR/STRING (for lazy) */
  2308. ret += 3;
  2309. }
  2310. }
  2311. return ret;
  2312. }
  2313. /* upb_handlerattr ************************************************************/
  2314. void upb_handlerattr_init(upb_handlerattr *attr) {
  2315. upb_handlerattr from = UPB_HANDLERATTR_INITIALIZER;
  2316. memcpy(attr, &from, sizeof(*attr));
  2317. }
  2318. void upb_handlerattr_uninit(upb_handlerattr *attr) {
  2319. UPB_UNUSED(attr);
  2320. }
  2321. bool upb_handlerattr_sethandlerdata(upb_handlerattr *attr, const void *hd) {
  2322. attr->handler_data_ = hd;
  2323. return true;
  2324. }
  2325. bool upb_handlerattr_setclosuretype(upb_handlerattr *attr, const void *type) {
  2326. attr->closure_type_ = type;
  2327. return true;
  2328. }
  2329. const void *upb_handlerattr_closuretype(const upb_handlerattr *attr) {
  2330. return attr->closure_type_;
  2331. }
  2332. bool upb_handlerattr_setreturnclosuretype(upb_handlerattr *attr,
  2333. const void *type) {
  2334. attr->return_closure_type_ = type;
  2335. return true;
  2336. }
  2337. const void *upb_handlerattr_returnclosuretype(const upb_handlerattr *attr) {
  2338. return attr->return_closure_type_;
  2339. }
  2340. bool upb_handlerattr_setalwaysok(upb_handlerattr *attr, bool alwaysok) {
  2341. attr->alwaysok_ = alwaysok;
  2342. return true;
  2343. }
  2344. bool upb_handlerattr_alwaysok(const upb_handlerattr *attr) {
  2345. return attr->alwaysok_;
  2346. }
  2347. /* upb_bufhandle **************************************************************/
  2348. size_t upb_bufhandle_objofs(const upb_bufhandle *h) {
  2349. return h->objofs_;
  2350. }
  2351. /* upb_byteshandler ***********************************************************/
  2352. void upb_byteshandler_init(upb_byteshandler* h) {
  2353. memset(h, 0, sizeof(*h));
  2354. }
  2355. /* For when we support handlerfree callbacks. */
  2356. void upb_byteshandler_uninit(upb_byteshandler* h) {
  2357. UPB_UNUSED(h);
  2358. }
  2359. bool upb_byteshandler_setstartstr(upb_byteshandler *h,
  2360. upb_startstr_handlerfunc *func, void *d) {
  2361. h->table[UPB_STARTSTR_SELECTOR].func = (upb_func*)func;
  2362. h->table[UPB_STARTSTR_SELECTOR].attr.handler_data_ = d;
  2363. return true;
  2364. }
  2365. bool upb_byteshandler_setstring(upb_byteshandler *h,
  2366. upb_string_handlerfunc *func, void *d) {
  2367. h->table[UPB_STRING_SELECTOR].func = (upb_func*)func;
  2368. h->table[UPB_STRING_SELECTOR].attr.handler_data_ = d;
  2369. return true;
  2370. }
  2371. bool upb_byteshandler_setendstr(upb_byteshandler *h,
  2372. upb_endfield_handlerfunc *func, void *d) {
  2373. h->table[UPB_ENDSTR_SELECTOR].func = (upb_func*)func;
  2374. h->table[UPB_ENDSTR_SELECTOR].attr.handler_data_ = d;
  2375. return true;
  2376. }
  2377. /*
  2378. ** upb::RefCounted Implementation
  2379. **
  2380. ** Our key invariants are:
  2381. ** 1. reference cycles never span groups
  2382. ** 2. for ref2(to, from), we increment to's count iff group(from) != group(to)
  2383. **
  2384. ** The previous two are how we avoid leaking cycles. Other important
  2385. ** invariants are:
  2386. ** 3. for mutable objects "from" and "to", if there exists a ref2(to, from)
  2387. ** this implies group(from) == group(to). (In practice, what we implement
  2388. ** is even stronger; "from" and "to" will share a group if there has *ever*
  2389. ** been a ref2(to, from), but all that is necessary for correctness is the
  2390. ** weaker one).
  2391. ** 4. mutable and immutable objects are never in the same group.
  2392. */
  2393. #include <setjmp.h>
  2394. static void freeobj(upb_refcounted *o);
  2395. const char untracked_val;
  2396. const void *UPB_UNTRACKED_REF = &untracked_val;
  2397. /* arch-specific atomic primitives *******************************************/
  2398. #ifdef UPB_THREAD_UNSAFE /*---------------------------------------------------*/
  2399. static void atomic_inc(uint32_t *a) { (*a)++; }
  2400. static bool atomic_dec(uint32_t *a) { return --(*a) == 0; }
  2401. #elif defined(__GNUC__) || defined(__clang__) /*------------------------------*/
  2402. static void atomic_inc(uint32_t *a) { __sync_fetch_and_add(a, 1); }
  2403. static bool atomic_dec(uint32_t *a) { return __sync_sub_and_fetch(a, 1) == 0; }
  2404. #elif defined(WIN32) /*-------------------------------------------------------*/
  2405. #include <Windows.h>
  2406. static void atomic_inc(upb_atomic_t *a) { InterlockedIncrement(&a->val); }
  2407. static bool atomic_dec(upb_atomic_t *a) {
  2408. return InterlockedDecrement(&a->val) == 0;
  2409. }
  2410. #else
  2411. #error Atomic primitives not defined for your platform/CPU. \
  2412. Implement them or compile with UPB_THREAD_UNSAFE.
  2413. #endif
  2414. /* All static objects point to this refcount.
  2415. * It is special-cased in ref/unref below. */
  2416. uint32_t static_refcount = -1;
  2417. /* We can avoid atomic ops for statically-declared objects.
  2418. * This is a minor optimization but nice since we can avoid degrading under
  2419. * contention in this case. */
  2420. static void refgroup(uint32_t *group) {
  2421. if (group != &static_refcount)
  2422. atomic_inc(group);
  2423. }
  2424. static bool unrefgroup(uint32_t *group) {
  2425. if (group == &static_refcount) {
  2426. return false;
  2427. } else {
  2428. return atomic_dec(group);
  2429. }
  2430. }
  2431. /* Reference tracking (debug only) ********************************************/
  2432. #ifdef UPB_DEBUG_REFS
  2433. #ifdef UPB_THREAD_UNSAFE
  2434. static void upb_lock() {}
  2435. static void upb_unlock() {}
  2436. #else
  2437. /* User must define functions that lock/unlock a global mutex and link this
  2438. * file against them. */
  2439. void upb_lock();
  2440. void upb_unlock();
  2441. #endif
  2442. /* UPB_DEBUG_REFS mode counts on being able to malloc() memory in some
  2443. * code-paths that can normally never fail, like upb_refcounted_ref(). Since
  2444. * we have no way to propagage out-of-memory errors back to the user, and since
  2445. * these errors can only occur in UPB_DEBUG_REFS mode, we use an allocator that
  2446. * immediately aborts on failure (avoiding the global allocator, which might
  2447. * inject failures). */
  2448. #include <stdlib.h>
  2449. static void *upb_debugrefs_allocfunc(upb_alloc *alloc, void *ptr,
  2450. size_t oldsize, size_t size) {
  2451. UPB_UNUSED(alloc);
  2452. UPB_UNUSED(oldsize);
  2453. if (size == 0) {
  2454. free(ptr);
  2455. return NULL;
  2456. } else {
  2457. void *ret = realloc(ptr, size);
  2458. if (!ret) {
  2459. abort();
  2460. }
  2461. return ret;
  2462. }
  2463. }
  2464. upb_alloc upb_alloc_debugrefs = {&upb_debugrefs_allocfunc};
  2465. typedef struct {
  2466. int count; /* How many refs there are (duplicates only allowed for ref2). */
  2467. bool is_ref2;
  2468. } trackedref;
  2469. static trackedref *trackedref_new(bool is_ref2) {
  2470. trackedref *ret = upb_malloc(&upb_alloc_debugrefs, sizeof(*ret));
  2471. ret->count = 1;
  2472. ret->is_ref2 = is_ref2;
  2473. return ret;
  2474. }
  2475. static void track(const upb_refcounted *r, const void *owner, bool ref2) {
  2476. upb_value v;
  2477. assert(owner);
  2478. if (owner == UPB_UNTRACKED_REF) return;
  2479. upb_lock();
  2480. if (upb_inttable_lookupptr(r->refs, owner, &v)) {
  2481. trackedref *ref = upb_value_getptr(v);
  2482. /* Since we allow multiple ref2's for the same to/from pair without
  2483. * allocating separate memory for each one, we lose the fine-grained
  2484. * tracking behavior we get with regular refs. Since ref2s only happen
  2485. * inside upb, we'll accept this limitation until/unless there is a really
  2486. * difficult upb-internal bug that can't be figured out without it. */
  2487. assert(ref2);
  2488. assert(ref->is_ref2);
  2489. ref->count++;
  2490. } else {
  2491. trackedref *ref = trackedref_new(ref2);
  2492. upb_inttable_insertptr2(r->refs, owner, upb_value_ptr(ref),
  2493. &upb_alloc_debugrefs);
  2494. if (ref2) {
  2495. /* We know this cast is safe when it is a ref2, because it's coming from
  2496. * another refcounted object. */
  2497. const upb_refcounted *from = owner;
  2498. assert(!upb_inttable_lookupptr(from->ref2s, r, NULL));
  2499. upb_inttable_insertptr2(from->ref2s, r, upb_value_ptr(NULL),
  2500. &upb_alloc_debugrefs);
  2501. }
  2502. }
  2503. upb_unlock();
  2504. }
  2505. static void untrack(const upb_refcounted *r, const void *owner, bool ref2) {
  2506. upb_value v;
  2507. bool found;
  2508. trackedref *ref;
  2509. assert(owner);
  2510. if (owner == UPB_UNTRACKED_REF) return;
  2511. upb_lock();
  2512. found = upb_inttable_lookupptr(r->refs, owner, &v);
  2513. /* This assert will fail if an owner attempts to release a ref it didn't have. */
  2514. UPB_ASSERT_VAR(found, found);
  2515. ref = upb_value_getptr(v);
  2516. assert(ref->is_ref2 == ref2);
  2517. if (--ref->count == 0) {
  2518. free(ref);
  2519. upb_inttable_removeptr(r->refs, owner, NULL);
  2520. if (ref2) {
  2521. /* We know this cast is safe when it is a ref2, because it's coming from
  2522. * another refcounted object. */
  2523. const upb_refcounted *from = owner;
  2524. bool removed = upb_inttable_removeptr(from->ref2s, r, NULL);
  2525. assert(removed);
  2526. }
  2527. }
  2528. upb_unlock();
  2529. }
  2530. static void checkref(const upb_refcounted *r, const void *owner, bool ref2) {
  2531. upb_value v;
  2532. bool found;
  2533. trackedref *ref;
  2534. upb_lock();
  2535. found = upb_inttable_lookupptr(r->refs, owner, &v);
  2536. UPB_ASSERT_VAR(found, found);
  2537. ref = upb_value_getptr(v);
  2538. assert(ref->is_ref2 == ref2);
  2539. upb_unlock();
  2540. }
  2541. /* Populates the given UPB_CTYPE_INT32 inttable with counts of ref2's that
  2542. * originate from the given owner. */
  2543. static void getref2s(const upb_refcounted *owner, upb_inttable *tab) {
  2544. upb_inttable_iter i;
  2545. upb_lock();
  2546. upb_inttable_begin(&i, owner->ref2s);
  2547. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  2548. upb_value v;
  2549. upb_value count;
  2550. trackedref *ref;
  2551. bool found;
  2552. upb_refcounted *to = (upb_refcounted*)upb_inttable_iter_key(&i);
  2553. /* To get the count we need to look in the target's table. */
  2554. found = upb_inttable_lookupptr(to->refs, owner, &v);
  2555. assert(found);
  2556. ref = upb_value_getptr(v);
  2557. count = upb_value_int32(ref->count);
  2558. upb_inttable_insertptr2(tab, to, count, &upb_alloc_debugrefs);
  2559. }
  2560. upb_unlock();
  2561. }
  2562. typedef struct {
  2563. upb_inttable ref2;
  2564. const upb_refcounted *obj;
  2565. } check_state;
  2566. static void visit_check(const upb_refcounted *obj, const upb_refcounted *subobj,
  2567. void *closure) {
  2568. check_state *s = closure;
  2569. upb_inttable *ref2 = &s->ref2;
  2570. upb_value v;
  2571. bool removed;
  2572. int32_t newcount;
  2573. assert(obj == s->obj);
  2574. assert(subobj);
  2575. removed = upb_inttable_removeptr(ref2, subobj, &v);
  2576. /* The following assertion will fail if the visit() function visits a subobj
  2577. * that it did not have a ref2 on, or visits the same subobj too many times. */
  2578. assert(removed);
  2579. newcount = upb_value_getint32(v) - 1;
  2580. if (newcount > 0) {
  2581. upb_inttable_insert2(ref2, (uintptr_t)subobj, upb_value_int32(newcount),
  2582. &upb_alloc_debugrefs);
  2583. }
  2584. }
  2585. static void visit(const upb_refcounted *r, upb_refcounted_visit *v,
  2586. void *closure) {
  2587. /* In DEBUG_REFS mode we know what existing ref2 refs there are, so we know
  2588. * exactly the set of nodes that visit() should visit. So we verify visit()'s
  2589. * correctness here. */
  2590. check_state state;
  2591. state.obj = r;
  2592. upb_inttable_init2(&state.ref2, UPB_CTYPE_INT32, &upb_alloc_debugrefs);
  2593. getref2s(r, &state.ref2);
  2594. /* This should visit any children in the ref2 table. */
  2595. if (r->vtbl->visit) r->vtbl->visit(r, visit_check, &state);
  2596. /* This assertion will fail if the visit() function missed any children. */
  2597. assert(upb_inttable_count(&state.ref2) == 0);
  2598. upb_inttable_uninit2(&state.ref2, &upb_alloc_debugrefs);
  2599. if (r->vtbl->visit) r->vtbl->visit(r, v, closure);
  2600. }
  2601. static void trackinit(upb_refcounted *r) {
  2602. r->refs = upb_malloc(&upb_alloc_debugrefs, sizeof(*r->refs));
  2603. r->ref2s = upb_malloc(&upb_alloc_debugrefs, sizeof(*r->ref2s));
  2604. upb_inttable_init2(r->refs, UPB_CTYPE_PTR, &upb_alloc_debugrefs);
  2605. upb_inttable_init2(r->ref2s, UPB_CTYPE_PTR, &upb_alloc_debugrefs);
  2606. }
  2607. static void trackfree(const upb_refcounted *r) {
  2608. upb_inttable_uninit2(r->refs, &upb_alloc_debugrefs);
  2609. upb_inttable_uninit2(r->ref2s, &upb_alloc_debugrefs);
  2610. upb_free(&upb_alloc_debugrefs, r->refs);
  2611. upb_free(&upb_alloc_debugrefs, r->ref2s);
  2612. }
  2613. #else
  2614. static void track(const upb_refcounted *r, const void *owner, bool ref2) {
  2615. UPB_UNUSED(r);
  2616. UPB_UNUSED(owner);
  2617. UPB_UNUSED(ref2);
  2618. }
  2619. static void untrack(const upb_refcounted *r, const void *owner, bool ref2) {
  2620. UPB_UNUSED(r);
  2621. UPB_UNUSED(owner);
  2622. UPB_UNUSED(ref2);
  2623. }
  2624. static void checkref(const upb_refcounted *r, const void *owner, bool ref2) {
  2625. UPB_UNUSED(r);
  2626. UPB_UNUSED(owner);
  2627. UPB_UNUSED(ref2);
  2628. }
  2629. static void trackinit(upb_refcounted *r) {
  2630. UPB_UNUSED(r);
  2631. }
  2632. static void trackfree(const upb_refcounted *r) {
  2633. UPB_UNUSED(r);
  2634. }
  2635. static void visit(const upb_refcounted *r, upb_refcounted_visit *v,
  2636. void *closure) {
  2637. if (r->vtbl->visit) r->vtbl->visit(r, v, closure);
  2638. }
  2639. #endif /* UPB_DEBUG_REFS */
  2640. /* freeze() *******************************************************************/
  2641. /* The freeze() operation is by far the most complicated part of this scheme.
  2642. * We compute strongly-connected components and then mutate the graph such that
  2643. * we preserve the invariants documented at the top of this file. And we must
  2644. * handle out-of-memory errors gracefully (without leaving the graph
  2645. * inconsistent), which adds to the fun. */
  2646. /* The state used by the freeze operation (shared across many functions). */
  2647. typedef struct {
  2648. int depth;
  2649. int maxdepth;
  2650. uint64_t index;
  2651. /* Maps upb_refcounted* -> attributes (color, etc). attr layout varies by
  2652. * color. */
  2653. upb_inttable objattr;
  2654. upb_inttable stack; /* stack of upb_refcounted* for Tarjan's algorithm. */
  2655. upb_inttable groups; /* array of uint32_t*, malloc'd refcounts for new groups */
  2656. upb_status *status;
  2657. jmp_buf err;
  2658. } tarjan;
  2659. static void release_ref2(const upb_refcounted *obj,
  2660. const upb_refcounted *subobj,
  2661. void *closure);
  2662. /* Node attributes -----------------------------------------------------------*/
  2663. /* After our analysis phase all nodes will be either GRAY or WHITE. */
  2664. typedef enum {
  2665. BLACK = 0, /* Object has not been seen. */
  2666. GRAY, /* Object has been found via a refgroup but may not be reachable. */
  2667. GREEN, /* Object is reachable and is currently on the Tarjan stack. */
  2668. WHITE /* Object is reachable and has been assigned a group (SCC). */
  2669. } color_t;
  2670. UPB_NORETURN static void err(tarjan *t) { longjmp(t->err, 1); }
  2671. UPB_NORETURN static void oom(tarjan *t) {
  2672. upb_status_seterrmsg(t->status, "out of memory");
  2673. err(t);
  2674. }
  2675. static uint64_t trygetattr(const tarjan *t, const upb_refcounted *r) {
  2676. upb_value v;
  2677. return upb_inttable_lookupptr(&t->objattr, r, &v) ?
  2678. upb_value_getuint64(v) : 0;
  2679. }
  2680. static uint64_t getattr(const tarjan *t, const upb_refcounted *r) {
  2681. upb_value v;
  2682. bool found = upb_inttable_lookupptr(&t->objattr, r, &v);
  2683. UPB_ASSERT_VAR(found, found);
  2684. return upb_value_getuint64(v);
  2685. }
  2686. static void setattr(tarjan *t, const upb_refcounted *r, uint64_t attr) {
  2687. upb_inttable_removeptr(&t->objattr, r, NULL);
  2688. upb_inttable_insertptr(&t->objattr, r, upb_value_uint64(attr));
  2689. }
  2690. static color_t color(tarjan *t, const upb_refcounted *r) {
  2691. return trygetattr(t, r) & 0x3; /* Color is always stored in the low 2 bits. */
  2692. }
  2693. static void set_gray(tarjan *t, const upb_refcounted *r) {
  2694. assert(color(t, r) == BLACK);
  2695. setattr(t, r, GRAY);
  2696. }
  2697. /* Pushes an obj onto the Tarjan stack and sets it to GREEN. */
  2698. static void push(tarjan *t, const upb_refcounted *r) {
  2699. assert(color(t, r) == BLACK || color(t, r) == GRAY);
  2700. /* This defines the attr layout for the GREEN state. "index" and "lowlink"
  2701. * get 31 bits, which is plenty (limit of 2B objects frozen at a time). */
  2702. setattr(t, r, GREEN | (t->index << 2) | (t->index << 33));
  2703. if (++t->index == 0x80000000) {
  2704. upb_status_seterrmsg(t->status, "too many objects to freeze");
  2705. err(t);
  2706. }
  2707. upb_inttable_push(&t->stack, upb_value_ptr((void*)r));
  2708. }
  2709. /* Pops an obj from the Tarjan stack and sets it to WHITE, with a ptr to its
  2710. * SCC group. */
  2711. static upb_refcounted *pop(tarjan *t) {
  2712. upb_refcounted *r = upb_value_getptr(upb_inttable_pop(&t->stack));
  2713. assert(color(t, r) == GREEN);
  2714. /* This defines the attr layout for nodes in the WHITE state.
  2715. * Top of group stack is [group, NULL]; we point at group. */
  2716. setattr(t, r, WHITE | (upb_inttable_count(&t->groups) - 2) << 8);
  2717. return r;
  2718. }
  2719. static void tarjan_newgroup(tarjan *t) {
  2720. uint32_t *group = upb_gmalloc(sizeof(*group));
  2721. if (!group) oom(t);
  2722. /* Push group and empty group leader (we'll fill in leader later). */
  2723. if (!upb_inttable_push(&t->groups, upb_value_ptr(group)) ||
  2724. !upb_inttable_push(&t->groups, upb_value_ptr(NULL))) {
  2725. upb_gfree(group);
  2726. oom(t);
  2727. }
  2728. *group = 0;
  2729. }
  2730. static uint32_t idx(tarjan *t, const upb_refcounted *r) {
  2731. assert(color(t, r) == GREEN);
  2732. return (getattr(t, r) >> 2) & 0x7FFFFFFF;
  2733. }
  2734. static uint32_t lowlink(tarjan *t, const upb_refcounted *r) {
  2735. if (color(t, r) == GREEN) {
  2736. return getattr(t, r) >> 33;
  2737. } else {
  2738. return UINT32_MAX;
  2739. }
  2740. }
  2741. static void set_lowlink(tarjan *t, const upb_refcounted *r, uint32_t lowlink) {
  2742. assert(color(t, r) == GREEN);
  2743. setattr(t, r, ((uint64_t)lowlink << 33) | (getattr(t, r) & 0x1FFFFFFFF));
  2744. }
  2745. static uint32_t *group(tarjan *t, upb_refcounted *r) {
  2746. uint64_t groupnum;
  2747. upb_value v;
  2748. bool found;
  2749. assert(color(t, r) == WHITE);
  2750. groupnum = getattr(t, r) >> 8;
  2751. found = upb_inttable_lookup(&t->groups, groupnum, &v);
  2752. UPB_ASSERT_VAR(found, found);
  2753. return upb_value_getptr(v);
  2754. }
  2755. /* If the group leader for this object's group has not previously been set,
  2756. * the given object is assigned to be its leader. */
  2757. static upb_refcounted *groupleader(tarjan *t, upb_refcounted *r) {
  2758. uint64_t leader_slot;
  2759. upb_value v;
  2760. bool found;
  2761. assert(color(t, r) == WHITE);
  2762. leader_slot = (getattr(t, r) >> 8) + 1;
  2763. found = upb_inttable_lookup(&t->groups, leader_slot, &v);
  2764. UPB_ASSERT_VAR(found, found);
  2765. if (upb_value_getptr(v)) {
  2766. return upb_value_getptr(v);
  2767. } else {
  2768. upb_inttable_remove(&t->groups, leader_slot, NULL);
  2769. upb_inttable_insert(&t->groups, leader_slot, upb_value_ptr(r));
  2770. return r;
  2771. }
  2772. }
  2773. /* Tarjan's algorithm --------------------------------------------------------*/
  2774. /* See:
  2775. * http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm */
  2776. static void do_tarjan(const upb_refcounted *obj, tarjan *t);
  2777. static void tarjan_visit(const upb_refcounted *obj,
  2778. const upb_refcounted *subobj,
  2779. void *closure) {
  2780. tarjan *t = closure;
  2781. if (++t->depth > t->maxdepth) {
  2782. upb_status_seterrf(t->status, "graph too deep to freeze (%d)", t->maxdepth);
  2783. err(t);
  2784. } else if (subobj->is_frozen || color(t, subobj) == WHITE) {
  2785. /* Do nothing: we don't want to visit or color already-frozen nodes,
  2786. * and WHITE nodes have already been assigned a SCC. */
  2787. } else if (color(t, subobj) < GREEN) {
  2788. /* Subdef has not yet been visited; recurse on it. */
  2789. do_tarjan(subobj, t);
  2790. set_lowlink(t, obj, UPB_MIN(lowlink(t, obj), lowlink(t, subobj)));
  2791. } else if (color(t, subobj) == GREEN) {
  2792. /* Subdef is in the stack and hence in the current SCC. */
  2793. set_lowlink(t, obj, UPB_MIN(lowlink(t, obj), idx(t, subobj)));
  2794. }
  2795. --t->depth;
  2796. }
  2797. static void do_tarjan(const upb_refcounted *obj, tarjan *t) {
  2798. if (color(t, obj) == BLACK) {
  2799. /* We haven't seen this object's group; mark the whole group GRAY. */
  2800. const upb_refcounted *o = obj;
  2801. do { set_gray(t, o); } while ((o = o->next) != obj);
  2802. }
  2803. push(t, obj);
  2804. visit(obj, tarjan_visit, t);
  2805. if (lowlink(t, obj) == idx(t, obj)) {
  2806. tarjan_newgroup(t);
  2807. while (pop(t) != obj)
  2808. ;
  2809. }
  2810. }
  2811. /* freeze() ------------------------------------------------------------------*/
  2812. static void crossref(const upb_refcounted *r, const upb_refcounted *subobj,
  2813. void *_t) {
  2814. tarjan *t = _t;
  2815. assert(color(t, r) > BLACK);
  2816. if (color(t, subobj) > BLACK && r->group != subobj->group) {
  2817. /* Previously this ref was not reflected in subobj->group because they
  2818. * were in the same group; now that they are split a ref must be taken. */
  2819. refgroup(subobj->group);
  2820. }
  2821. }
  2822. static bool freeze(upb_refcounted *const*roots, int n, upb_status *s,
  2823. int maxdepth) {
  2824. volatile bool ret = false;
  2825. int i;
  2826. upb_inttable_iter iter;
  2827. /* We run in two passes so that we can allocate all memory before performing
  2828. * any mutation of the input -- this allows us to leave the input unchanged
  2829. * in the case of memory allocation failure. */
  2830. tarjan t;
  2831. t.index = 0;
  2832. t.depth = 0;
  2833. t.maxdepth = maxdepth;
  2834. t.status = s;
  2835. if (!upb_inttable_init(&t.objattr, UPB_CTYPE_UINT64)) goto err1;
  2836. if (!upb_inttable_init(&t.stack, UPB_CTYPE_PTR)) goto err2;
  2837. if (!upb_inttable_init(&t.groups, UPB_CTYPE_PTR)) goto err3;
  2838. if (setjmp(t.err) != 0) goto err4;
  2839. for (i = 0; i < n; i++) {
  2840. if (color(&t, roots[i]) < GREEN) {
  2841. do_tarjan(roots[i], &t);
  2842. }
  2843. }
  2844. /* If we've made it this far, no further errors are possible so it's safe to
  2845. * mutate the objects without risk of leaving them in an inconsistent state. */
  2846. ret = true;
  2847. /* The transformation that follows requires care. The preconditions are:
  2848. * - all objects in attr map are WHITE or GRAY, and are in mutable groups
  2849. * (groups of all mutable objs)
  2850. * - no ref2(to, from) refs have incremented count(to) if both "to" and
  2851. * "from" are in our attr map (this follows from invariants (2) and (3)) */
  2852. /* Pass 1: we remove WHITE objects from their mutable groups, and add them to
  2853. * new groups according to the SCC's we computed. These new groups will
  2854. * consist of only frozen objects. None will be immediately collectible,
  2855. * because WHITE objects are by definition reachable from one of "roots",
  2856. * which the caller must own refs on. */
  2857. upb_inttable_begin(&iter, &t.objattr);
  2858. for(; !upb_inttable_done(&iter); upb_inttable_next(&iter)) {
  2859. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&iter);
  2860. /* Since removal from a singly-linked list requires access to the object's
  2861. * predecessor, we consider obj->next instead of obj for moving. With the
  2862. * while() loop we guarantee that we will visit every node's predecessor.
  2863. * Proof:
  2864. * 1. every node's predecessor is in our attr map.
  2865. * 2. though the loop body may change a node's predecessor, it will only
  2866. * change it to be the node we are currently operating on, so with a
  2867. * while() loop we guarantee ourselves the chance to remove each node. */
  2868. while (color(&t, obj->next) == WHITE &&
  2869. group(&t, obj->next) != obj->next->group) {
  2870. upb_refcounted *leader;
  2871. /* Remove from old group. */
  2872. upb_refcounted *move = obj->next;
  2873. if (obj == move) {
  2874. /* Removing the last object from a group. */
  2875. assert(*obj->group == obj->individual_count);
  2876. upb_gfree(obj->group);
  2877. } else {
  2878. obj->next = move->next;
  2879. /* This may decrease to zero; we'll collect GRAY objects (if any) that
  2880. * remain in the group in the third pass. */
  2881. assert(*move->group >= move->individual_count);
  2882. *move->group -= move->individual_count;
  2883. }
  2884. /* Add to new group. */
  2885. leader = groupleader(&t, move);
  2886. if (move == leader) {
  2887. /* First object added to new group is its leader. */
  2888. move->group = group(&t, move);
  2889. move->next = move;
  2890. *move->group = move->individual_count;
  2891. } else {
  2892. /* Group already has at least one object in it. */
  2893. assert(leader->group == group(&t, move));
  2894. move->group = group(&t, move);
  2895. move->next = leader->next;
  2896. leader->next = move;
  2897. *move->group += move->individual_count;
  2898. }
  2899. move->is_frozen = true;
  2900. }
  2901. }
  2902. /* Pass 2: GRAY and WHITE objects "obj" with ref2(to, obj) references must
  2903. * increment count(to) if group(obj) != group(to) (which could now be the
  2904. * case if "to" was just frozen). */
  2905. upb_inttable_begin(&iter, &t.objattr);
  2906. for(; !upb_inttable_done(&iter); upb_inttable_next(&iter)) {
  2907. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&iter);
  2908. visit(obj, crossref, &t);
  2909. }
  2910. /* Pass 3: GRAY objects are collected if their group's refcount dropped to
  2911. * zero when we removed its white nodes. This can happen if they had only
  2912. * been kept alive by virtue of sharing a group with an object that was just
  2913. * frozen.
  2914. *
  2915. * It is important that we do this last, since the GRAY object's free()
  2916. * function could call unref2() on just-frozen objects, which will decrement
  2917. * refs that were added in pass 2. */
  2918. upb_inttable_begin(&iter, &t.objattr);
  2919. for(; !upb_inttable_done(&iter); upb_inttable_next(&iter)) {
  2920. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&iter);
  2921. if (obj->group == NULL || *obj->group == 0) {
  2922. if (obj->group) {
  2923. upb_refcounted *o;
  2924. /* We eagerly free() the group's count (since we can't easily determine
  2925. * the group's remaining size it's the easiest way to ensure it gets
  2926. * done). */
  2927. upb_gfree(obj->group);
  2928. /* Visit to release ref2's (done in a separate pass since release_ref2
  2929. * depends on o->group being unmodified so it can test merged()). */
  2930. o = obj;
  2931. do { visit(o, release_ref2, NULL); } while ((o = o->next) != obj);
  2932. /* Mark "group" fields as NULL so we know to free the objects later in
  2933. * this loop, but also don't try to delete the group twice. */
  2934. o = obj;
  2935. do { o->group = NULL; } while ((o = o->next) != obj);
  2936. }
  2937. freeobj(obj);
  2938. }
  2939. }
  2940. err4:
  2941. if (!ret) {
  2942. upb_inttable_begin(&iter, &t.groups);
  2943. for(; !upb_inttable_done(&iter); upb_inttable_next(&iter))
  2944. upb_gfree(upb_value_getptr(upb_inttable_iter_value(&iter)));
  2945. }
  2946. upb_inttable_uninit(&t.groups);
  2947. err3:
  2948. upb_inttable_uninit(&t.stack);
  2949. err2:
  2950. upb_inttable_uninit(&t.objattr);
  2951. err1:
  2952. return ret;
  2953. }
  2954. /* Misc internal functions ***************************************************/
  2955. static bool merged(const upb_refcounted *r, const upb_refcounted *r2) {
  2956. return r->group == r2->group;
  2957. }
  2958. static void merge(upb_refcounted *r, upb_refcounted *from) {
  2959. upb_refcounted *base;
  2960. upb_refcounted *tmp;
  2961. if (merged(r, from)) return;
  2962. *r->group += *from->group;
  2963. upb_gfree(from->group);
  2964. base = from;
  2965. /* Set all refcount pointers in the "from" chain to the merged refcount.
  2966. *
  2967. * TODO(haberman): this linear algorithm can result in an overall O(n^2) bound
  2968. * if the user continuously extends a group by one object. Prevent this by
  2969. * using one of the techniques in this paper:
  2970. * ftp://www.ncedc.org/outgoing/geomorph/dino/orals/p245-tarjan.pdf */
  2971. do { from->group = r->group; } while ((from = from->next) != base);
  2972. /* Merge the two circularly linked lists by swapping their next pointers. */
  2973. tmp = r->next;
  2974. r->next = base->next;
  2975. base->next = tmp;
  2976. }
  2977. static void unref(const upb_refcounted *r);
  2978. static void release_ref2(const upb_refcounted *obj,
  2979. const upb_refcounted *subobj,
  2980. void *closure) {
  2981. UPB_UNUSED(closure);
  2982. untrack(subobj, obj, true);
  2983. if (!merged(obj, subobj)) {
  2984. assert(subobj->is_frozen);
  2985. unref(subobj);
  2986. }
  2987. }
  2988. static void unref(const upb_refcounted *r) {
  2989. if (unrefgroup(r->group)) {
  2990. const upb_refcounted *o;
  2991. upb_gfree(r->group);
  2992. /* In two passes, since release_ref2 needs a guarantee that any subobjs
  2993. * are alive. */
  2994. o = r;
  2995. do { visit(o, release_ref2, NULL); } while((o = o->next) != r);
  2996. o = r;
  2997. do {
  2998. const upb_refcounted *next = o->next;
  2999. assert(o->is_frozen || o->individual_count == 0);
  3000. freeobj((upb_refcounted*)o);
  3001. o = next;
  3002. } while(o != r);
  3003. }
  3004. }
  3005. static void freeobj(upb_refcounted *o) {
  3006. trackfree(o);
  3007. o->vtbl->free((upb_refcounted*)o);
  3008. }
  3009. /* Public interface ***********************************************************/
  3010. bool upb_refcounted_init(upb_refcounted *r,
  3011. const struct upb_refcounted_vtbl *vtbl,
  3012. const void *owner) {
  3013. #ifndef NDEBUG
  3014. /* Endianness check. This is unrelated to upb_refcounted, it's just a
  3015. * convenient place to put the check that we can be assured will run for
  3016. * basically every program using upb. */
  3017. const int x = 1;
  3018. #ifdef UPB_BIG_ENDIAN
  3019. assert(*(char*)&x != 1);
  3020. #else
  3021. assert(*(char*)&x == 1);
  3022. #endif
  3023. #endif
  3024. r->next = r;
  3025. r->vtbl = vtbl;
  3026. r->individual_count = 0;
  3027. r->is_frozen = false;
  3028. r->group = upb_gmalloc(sizeof(*r->group));
  3029. if (!r->group) return false;
  3030. *r->group = 0;
  3031. trackinit(r);
  3032. upb_refcounted_ref(r, owner);
  3033. return true;
  3034. }
  3035. bool upb_refcounted_isfrozen(const upb_refcounted *r) {
  3036. return r->is_frozen;
  3037. }
  3038. void upb_refcounted_ref(const upb_refcounted *r, const void *owner) {
  3039. track(r, owner, false);
  3040. if (!r->is_frozen)
  3041. ((upb_refcounted*)r)->individual_count++;
  3042. refgroup(r->group);
  3043. }
  3044. void upb_refcounted_unref(const upb_refcounted *r, const void *owner) {
  3045. untrack(r, owner, false);
  3046. if (!r->is_frozen)
  3047. ((upb_refcounted*)r)->individual_count--;
  3048. unref(r);
  3049. }
  3050. void upb_refcounted_ref2(const upb_refcounted *r, upb_refcounted *from) {
  3051. assert(!from->is_frozen); /* Non-const pointer implies this. */
  3052. track(r, from, true);
  3053. if (r->is_frozen) {
  3054. refgroup(r->group);
  3055. } else {
  3056. merge((upb_refcounted*)r, from);
  3057. }
  3058. }
  3059. void upb_refcounted_unref2(const upb_refcounted *r, upb_refcounted *from) {
  3060. assert(!from->is_frozen); /* Non-const pointer implies this. */
  3061. untrack(r, from, true);
  3062. if (r->is_frozen) {
  3063. unref(r);
  3064. } else {
  3065. assert(merged(r, from));
  3066. }
  3067. }
  3068. void upb_refcounted_donateref(
  3069. const upb_refcounted *r, const void *from, const void *to) {
  3070. assert(from != to);
  3071. if (to != NULL)
  3072. upb_refcounted_ref(r, to);
  3073. if (from != NULL)
  3074. upb_refcounted_unref(r, from);
  3075. }
  3076. void upb_refcounted_checkref(const upb_refcounted *r, const void *owner) {
  3077. checkref(r, owner, false);
  3078. }
  3079. bool upb_refcounted_freeze(upb_refcounted *const*roots, int n, upb_status *s,
  3080. int maxdepth) {
  3081. int i;
  3082. bool ret;
  3083. for (i = 0; i < n; i++) {
  3084. assert(!roots[i]->is_frozen);
  3085. }
  3086. ret = freeze(roots, n, s, maxdepth);
  3087. assert(!s || ret == upb_ok(s));
  3088. return ret;
  3089. }
  3090. /* Fallback implementation if the shim is not specialized by the JIT. */
  3091. #define SHIM_WRITER(type, ctype) \
  3092. bool upb_shim_set ## type (void *c, const void *hd, ctype val) { \
  3093. uint8_t *m = c; \
  3094. const upb_shim_data *d = hd; \
  3095. if (d->hasbit > 0) \
  3096. *(uint8_t*)&m[d->hasbit / 8] |= 1 << (d->hasbit % 8); \
  3097. *(ctype*)&m[d->offset] = val; \
  3098. return true; \
  3099. } \
  3100. SHIM_WRITER(double, double)
  3101. SHIM_WRITER(float, float)
  3102. SHIM_WRITER(int32, int32_t)
  3103. SHIM_WRITER(int64, int64_t)
  3104. SHIM_WRITER(uint32, uint32_t)
  3105. SHIM_WRITER(uint64, uint64_t)
  3106. SHIM_WRITER(bool, bool)
  3107. #undef SHIM_WRITER
  3108. bool upb_shim_set(upb_handlers *h, const upb_fielddef *f, size_t offset,
  3109. int32_t hasbit) {
  3110. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  3111. bool ok;
  3112. upb_shim_data *d = upb_gmalloc(sizeof(*d));
  3113. if (!d) return false;
  3114. d->offset = offset;
  3115. d->hasbit = hasbit;
  3116. upb_handlerattr_sethandlerdata(&attr, d);
  3117. upb_handlerattr_setalwaysok(&attr, true);
  3118. upb_handlers_addcleanup(h, d, upb_gfree);
  3119. #define TYPE(u, l) \
  3120. case UPB_TYPE_##u: \
  3121. ok = upb_handlers_set##l(h, f, upb_shim_set##l, &attr); break;
  3122. ok = false;
  3123. switch (upb_fielddef_type(f)) {
  3124. TYPE(INT64, int64);
  3125. TYPE(INT32, int32);
  3126. TYPE(ENUM, int32);
  3127. TYPE(UINT64, uint64);
  3128. TYPE(UINT32, uint32);
  3129. TYPE(DOUBLE, double);
  3130. TYPE(FLOAT, float);
  3131. TYPE(BOOL, bool);
  3132. default: assert(false); break;
  3133. }
  3134. #undef TYPE
  3135. upb_handlerattr_uninit(&attr);
  3136. return ok;
  3137. }
  3138. const upb_shim_data *upb_shim_getdata(const upb_handlers *h, upb_selector_t s,
  3139. upb_fieldtype_t *type) {
  3140. upb_func *f = upb_handlers_gethandler(h, s);
  3141. if ((upb_int64_handlerfunc*)f == upb_shim_setint64) {
  3142. *type = UPB_TYPE_INT64;
  3143. } else if ((upb_int32_handlerfunc*)f == upb_shim_setint32) {
  3144. *type = UPB_TYPE_INT32;
  3145. } else if ((upb_uint64_handlerfunc*)f == upb_shim_setuint64) {
  3146. *type = UPB_TYPE_UINT64;
  3147. } else if ((upb_uint32_handlerfunc*)f == upb_shim_setuint32) {
  3148. *type = UPB_TYPE_UINT32;
  3149. } else if ((upb_double_handlerfunc*)f == upb_shim_setdouble) {
  3150. *type = UPB_TYPE_DOUBLE;
  3151. } else if ((upb_float_handlerfunc*)f == upb_shim_setfloat) {
  3152. *type = UPB_TYPE_FLOAT;
  3153. } else if ((upb_bool_handlerfunc*)f == upb_shim_setbool) {
  3154. *type = UPB_TYPE_BOOL;
  3155. } else {
  3156. return NULL;
  3157. }
  3158. return (const upb_shim_data*)upb_handlers_gethandlerdata(h, s);
  3159. }
  3160. #include <string.h>
  3161. static void upb_symtab_free(upb_refcounted *r) {
  3162. upb_symtab *s = (upb_symtab*)r;
  3163. upb_strtable_iter i;
  3164. upb_strtable_begin(&i, &s->symtab);
  3165. for (; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  3166. const upb_def *def = upb_value_getptr(upb_strtable_iter_value(&i));
  3167. upb_def_unref(def, s);
  3168. }
  3169. upb_strtable_uninit(&s->symtab);
  3170. upb_gfree(s);
  3171. }
  3172. upb_symtab *upb_symtab_new(const void *owner) {
  3173. static const struct upb_refcounted_vtbl vtbl = {NULL, &upb_symtab_free};
  3174. upb_symtab *s = upb_gmalloc(sizeof(*s));
  3175. if (!s) {
  3176. return NULL;
  3177. }
  3178. upb_refcounted_init(upb_symtab_upcast_mutable(s), &vtbl, owner);
  3179. upb_strtable_init(&s->symtab, UPB_CTYPE_PTR);
  3180. return s;
  3181. }
  3182. void upb_symtab_freeze(upb_symtab *s) {
  3183. upb_refcounted *r;
  3184. bool ok;
  3185. assert(!upb_symtab_isfrozen(s));
  3186. r = upb_symtab_upcast_mutable(s);
  3187. /* The symtab does not take ref2's (see refcounted.h) on the defs, because
  3188. * defs cannot refer back to the table and therefore cannot create cycles. So
  3189. * 0 will suffice for maxdepth here. */
  3190. ok = upb_refcounted_freeze(&r, 1, NULL, 0);
  3191. UPB_ASSERT_VAR(ok, ok);
  3192. }
  3193. const upb_def *upb_symtab_lookup(const upb_symtab *s, const char *sym) {
  3194. upb_value v;
  3195. upb_def *ret = upb_strtable_lookup(&s->symtab, sym, &v) ?
  3196. upb_value_getptr(v) : NULL;
  3197. return ret;
  3198. }
  3199. const upb_msgdef *upb_symtab_lookupmsg(const upb_symtab *s, const char *sym) {
  3200. upb_value v;
  3201. upb_def *def = upb_strtable_lookup(&s->symtab, sym, &v) ?
  3202. upb_value_getptr(v) : NULL;
  3203. return def ? upb_dyncast_msgdef(def) : NULL;
  3204. }
  3205. const upb_enumdef *upb_symtab_lookupenum(const upb_symtab *s, const char *sym) {
  3206. upb_value v;
  3207. upb_def *def = upb_strtable_lookup(&s->symtab, sym, &v) ?
  3208. upb_value_getptr(v) : NULL;
  3209. return def ? upb_dyncast_enumdef(def) : NULL;
  3210. }
  3211. /* Given a symbol and the base symbol inside which it is defined, find the
  3212. * symbol's definition in t. */
  3213. static upb_def *upb_resolvename(const upb_strtable *t,
  3214. const char *base, const char *sym) {
  3215. if(strlen(sym) == 0) return NULL;
  3216. if(sym[0] == '.') {
  3217. /* Symbols starting with '.' are absolute, so we do a single lookup.
  3218. * Slice to omit the leading '.' */
  3219. upb_value v;
  3220. return upb_strtable_lookup(t, sym + 1, &v) ? upb_value_getptr(v) : NULL;
  3221. } else {
  3222. /* Remove components from base until we find an entry or run out.
  3223. * TODO: This branch is totally broken, but currently not used. */
  3224. (void)base;
  3225. assert(false);
  3226. return NULL;
  3227. }
  3228. }
  3229. const upb_def *upb_symtab_resolve(const upb_symtab *s, const char *base,
  3230. const char *sym) {
  3231. upb_def *ret = upb_resolvename(&s->symtab, base, sym);
  3232. return ret;
  3233. }
  3234. /* Starts a depth-first traversal at "def", recursing into any subdefs
  3235. * (ie. submessage types). Adds duplicates of existing defs to addtab
  3236. * wherever necessary, so that the resulting symtab will be consistent once
  3237. * addtab is added.
  3238. *
  3239. * More specifically, if any def D is found in the DFS that:
  3240. *
  3241. * 1. can reach a def that is being replaced by something in addtab, AND
  3242. *
  3243. * 2. is not itself being replaced already (ie. this name doesn't already
  3244. * exist in addtab)
  3245. *
  3246. * ...then a duplicate (new copy) of D will be added to addtab.
  3247. *
  3248. * Returns true if this happened for any def reachable from "def."
  3249. *
  3250. * It is slightly tricky to do this correctly in the presence of cycles. If we
  3251. * detect that our DFS has hit a cycle, we might not yet know if any SCCs on
  3252. * our stack can reach a def in addtab or not. Once we figure this out, that
  3253. * answer needs to apply to *all* defs in these SCCs, even if we visited them
  3254. * already. So a straight up one-pass cycle-detecting DFS won't work.
  3255. *
  3256. * To work around this problem, we traverse each SCC (which we already
  3257. * computed, since these defs are frozen) as a single node. We first compute
  3258. * whether the SCC as a whole can reach any def in addtab, then we dup (or not)
  3259. * the entire SCC. This requires breaking the encapsulation of upb_refcounted,
  3260. * since that is where we get the data about what SCC we are in. */
  3261. static bool upb_resolve_dfs(const upb_def *def, upb_strtable *addtab,
  3262. const void *new_owner, upb_inttable *seen,
  3263. upb_status *s) {
  3264. upb_value v;
  3265. bool need_dup;
  3266. const upb_def *base;
  3267. const void* memoize_key;
  3268. /* Memoize results of this function for efficiency (since we're traversing a
  3269. * DAG this is not needed to limit the depth of the search).
  3270. *
  3271. * We memoize by SCC instead of by individual def. */
  3272. memoize_key = def->base.group;
  3273. if (upb_inttable_lookupptr(seen, memoize_key, &v))
  3274. return upb_value_getbool(v);
  3275. /* Visit submessages for all messages in the SCC. */
  3276. need_dup = false;
  3277. base = def;
  3278. do {
  3279. upb_value v;
  3280. const upb_msgdef *m;
  3281. assert(upb_def_isfrozen(def));
  3282. if (def->type == UPB_DEF_FIELD) continue;
  3283. if (upb_strtable_lookup(addtab, upb_def_fullname(def), &v)) {
  3284. need_dup = true;
  3285. }
  3286. /* For messages, continue the recursion by visiting all subdefs, but only
  3287. * ones in different SCCs. */
  3288. m = upb_dyncast_msgdef(def);
  3289. if (m) {
  3290. upb_msg_field_iter i;
  3291. for(upb_msg_field_begin(&i, m);
  3292. !upb_msg_field_done(&i);
  3293. upb_msg_field_next(&i)) {
  3294. upb_fielddef *f = upb_msg_iter_field(&i);
  3295. const upb_def *subdef;
  3296. if (!upb_fielddef_hassubdef(f)) continue;
  3297. subdef = upb_fielddef_subdef(f);
  3298. /* Skip subdefs in this SCC. */
  3299. if (def->base.group == subdef->base.group) continue;
  3300. /* |= to avoid short-circuit; we need its side-effects. */
  3301. need_dup |= upb_resolve_dfs(subdef, addtab, new_owner, seen, s);
  3302. if (!upb_ok(s)) return false;
  3303. }
  3304. }
  3305. } while ((def = (upb_def*)def->base.next) != base);
  3306. if (need_dup) {
  3307. /* Dup all defs in this SCC that don't already have entries in addtab. */
  3308. def = base;
  3309. do {
  3310. const char *name;
  3311. if (def->type == UPB_DEF_FIELD) continue;
  3312. name = upb_def_fullname(def);
  3313. if (!upb_strtable_lookup(addtab, name, NULL)) {
  3314. upb_def *newdef = upb_def_dup(def, new_owner);
  3315. if (!newdef) goto oom;
  3316. newdef->came_from_user = false;
  3317. if (!upb_strtable_insert(addtab, name, upb_value_ptr(newdef)))
  3318. goto oom;
  3319. }
  3320. } while ((def = (upb_def*)def->base.next) != base);
  3321. }
  3322. upb_inttable_insertptr(seen, memoize_key, upb_value_bool(need_dup));
  3323. return need_dup;
  3324. oom:
  3325. upb_status_seterrmsg(s, "out of memory");
  3326. return false;
  3327. }
  3328. /* TODO(haberman): we need a lot more testing of error conditions.
  3329. * The came_from_user stuff in particular is not tested. */
  3330. static bool symtab_add(upb_symtab *s, upb_def *const*defs, size_t n,
  3331. void *ref_donor, upb_refcounted *freeze_also,
  3332. upb_status *status) {
  3333. size_t i;
  3334. size_t add_n;
  3335. size_t freeze_n;
  3336. upb_strtable_iter iter;
  3337. upb_refcounted **add_objs = NULL;
  3338. upb_def **add_defs = NULL;
  3339. size_t add_objs_size;
  3340. upb_strtable addtab;
  3341. upb_inttable seen;
  3342. if (n == 0 && !freeze_also) {
  3343. return true;
  3344. }
  3345. assert(!upb_symtab_isfrozen(s));
  3346. if (!upb_strtable_init(&addtab, UPB_CTYPE_PTR)) {
  3347. upb_status_seterrmsg(status, "out of memory");
  3348. return false;
  3349. }
  3350. /* Add new defs to our "add" set. */
  3351. for (i = 0; i < n; i++) {
  3352. upb_def *def = defs[i];
  3353. const char *fullname;
  3354. upb_fielddef *f;
  3355. if (upb_def_isfrozen(def)) {
  3356. upb_status_seterrmsg(status, "added defs must be mutable");
  3357. goto err;
  3358. }
  3359. assert(!upb_def_isfrozen(def));
  3360. fullname = upb_def_fullname(def);
  3361. if (!fullname) {
  3362. upb_status_seterrmsg(
  3363. status, "Anonymous defs cannot be added to a symtab");
  3364. goto err;
  3365. }
  3366. f = upb_dyncast_fielddef_mutable(def);
  3367. if (f) {
  3368. if (!upb_fielddef_containingtypename(f)) {
  3369. upb_status_seterrmsg(status,
  3370. "Standalone fielddefs must have a containing type "
  3371. "(extendee) name set");
  3372. goto err;
  3373. }
  3374. } else {
  3375. if (upb_strtable_lookup(&addtab, fullname, NULL)) {
  3376. upb_status_seterrf(status, "Conflicting defs named '%s'", fullname);
  3377. goto err;
  3378. }
  3379. /* We need this to back out properly, because if there is a failure we
  3380. * need to donate the ref back to the caller. */
  3381. def->came_from_user = true;
  3382. upb_def_donateref(def, ref_donor, s);
  3383. if (!upb_strtable_insert(&addtab, fullname, upb_value_ptr(def)))
  3384. goto oom_err;
  3385. }
  3386. }
  3387. /* Add standalone fielddefs (ie. extensions) to the appropriate messages.
  3388. * If the appropriate message only exists in the existing symtab, duplicate
  3389. * it so we have a mutable copy we can add the fields to. */
  3390. for (i = 0; i < n; i++) {
  3391. upb_def *def = defs[i];
  3392. upb_fielddef *f = upb_dyncast_fielddef_mutable(def);
  3393. const char *msgname;
  3394. upb_value v;
  3395. upb_msgdef *m;
  3396. if (!f) continue;
  3397. msgname = upb_fielddef_containingtypename(f);
  3398. /* We validated this earlier in this function. */
  3399. assert(msgname);
  3400. /* If the extendee name is absolutely qualified, move past the initial ".".
  3401. * TODO(haberman): it is not obvious what it would mean if this was not
  3402. * absolutely qualified. */
  3403. if (msgname[0] == '.') {
  3404. msgname++;
  3405. }
  3406. if (upb_strtable_lookup(&addtab, msgname, &v)) {
  3407. /* Extendee is in the set of defs the user asked us to add. */
  3408. m = upb_value_getptr(v);
  3409. } else {
  3410. /* Need to find and dup the extendee from the existing symtab. */
  3411. const upb_msgdef *frozen_m = upb_symtab_lookupmsg(s, msgname);
  3412. if (!frozen_m) {
  3413. upb_status_seterrf(status,
  3414. "Tried to extend message %s that does not exist "
  3415. "in this SymbolTable.",
  3416. msgname);
  3417. goto err;
  3418. }
  3419. m = upb_msgdef_dup(frozen_m, s);
  3420. if (!m) goto oom_err;
  3421. if (!upb_strtable_insert(&addtab, msgname, upb_value_ptr(m))) {
  3422. upb_msgdef_unref(m, s);
  3423. goto oom_err;
  3424. }
  3425. }
  3426. if (!upb_msgdef_addfield(m, f, ref_donor, status)) {
  3427. goto err;
  3428. }
  3429. }
  3430. /* Add dups of any existing def that can reach a def with the same name as
  3431. * anything in our "add" set. */
  3432. if (!upb_inttable_init(&seen, UPB_CTYPE_BOOL)) goto oom_err;
  3433. upb_strtable_begin(&iter, &s->symtab);
  3434. for (; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
  3435. upb_def *def = upb_value_getptr(upb_strtable_iter_value(&iter));
  3436. upb_resolve_dfs(def, &addtab, s, &seen, status);
  3437. if (!upb_ok(status)) goto err;
  3438. }
  3439. upb_inttable_uninit(&seen);
  3440. /* Now using the table, resolve symbolic references for subdefs. */
  3441. upb_strtable_begin(&iter, &addtab);
  3442. for (; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
  3443. const char *base;
  3444. upb_def *def = upb_value_getptr(upb_strtable_iter_value(&iter));
  3445. upb_msgdef *m = upb_dyncast_msgdef_mutable(def);
  3446. upb_msg_field_iter j;
  3447. if (!m) continue;
  3448. /* Type names are resolved relative to the message in which they appear. */
  3449. base = upb_msgdef_fullname(m);
  3450. for(upb_msg_field_begin(&j, m);
  3451. !upb_msg_field_done(&j);
  3452. upb_msg_field_next(&j)) {
  3453. upb_fielddef *f = upb_msg_iter_field(&j);
  3454. const char *name = upb_fielddef_subdefname(f);
  3455. if (name && !upb_fielddef_subdef(f)) {
  3456. /* Try the lookup in the current set of to-be-added defs first. If not
  3457. * there, try existing defs. */
  3458. upb_def *subdef = upb_resolvename(&addtab, base, name);
  3459. if (subdef == NULL) {
  3460. subdef = upb_resolvename(&s->symtab, base, name);
  3461. }
  3462. if (subdef == NULL) {
  3463. upb_status_seterrf(
  3464. status, "couldn't resolve name '%s' in message '%s'", name, base);
  3465. goto err;
  3466. } else if (!upb_fielddef_setsubdef(f, subdef, status)) {
  3467. goto err;
  3468. }
  3469. }
  3470. }
  3471. }
  3472. /* We need an array of the defs in addtab, for passing to
  3473. * upb_refcounted_freeze(). */
  3474. add_objs_size = upb_strtable_count(&addtab);
  3475. if (freeze_also) {
  3476. add_objs_size++;
  3477. }
  3478. add_defs = upb_gmalloc(sizeof(void*) * add_objs_size);
  3479. if (add_defs == NULL) goto oom_err;
  3480. upb_strtable_begin(&iter, &addtab);
  3481. for (add_n = 0; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
  3482. add_defs[add_n++] = upb_value_getptr(upb_strtable_iter_value(&iter));
  3483. }
  3484. /* Validate defs. */
  3485. if (!_upb_def_validate(add_defs, add_n, status)) {
  3486. goto err;
  3487. }
  3488. /* Cheat a little and give the array a new type.
  3489. * This is probably undefined behavior, but this code will be deleted soon. */
  3490. add_objs = (upb_refcounted**)add_defs;
  3491. freeze_n = add_n;
  3492. if (freeze_also) {
  3493. add_objs[freeze_n++] = freeze_also;
  3494. }
  3495. if (!upb_refcounted_freeze(add_objs, freeze_n, status,
  3496. UPB_MAX_MESSAGE_DEPTH * 2)) {
  3497. goto err;
  3498. }
  3499. /* This must be delayed until all errors have been detected, since error
  3500. * recovery code uses this table to cleanup defs. */
  3501. upb_strtable_uninit(&addtab);
  3502. /* TODO(haberman) we don't properly handle errors after this point (like
  3503. * OOM in upb_strtable_insert() below). */
  3504. for (i = 0; i < add_n; i++) {
  3505. upb_def *def = (upb_def*)add_objs[i];
  3506. const char *name = upb_def_fullname(def);
  3507. upb_value v;
  3508. bool success;
  3509. if (upb_strtable_remove(&s->symtab, name, &v)) {
  3510. const upb_def *def = upb_value_getptr(v);
  3511. upb_def_unref(def, s);
  3512. }
  3513. success = upb_strtable_insert(&s->symtab, name, upb_value_ptr(def));
  3514. UPB_ASSERT_VAR(success, success == true);
  3515. }
  3516. upb_gfree(add_defs);
  3517. return true;
  3518. oom_err:
  3519. upb_status_seterrmsg(status, "out of memory");
  3520. err: {
  3521. /* For defs the user passed in, we need to donate the refs back. For defs
  3522. * we dup'd, we need to just unref them. */
  3523. upb_strtable_begin(&iter, &addtab);
  3524. for (; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
  3525. upb_def *def = upb_value_getptr(upb_strtable_iter_value(&iter));
  3526. bool came_from_user = def->came_from_user;
  3527. def->came_from_user = false;
  3528. if (came_from_user) {
  3529. upb_def_donateref(def, s, ref_donor);
  3530. } else {
  3531. upb_def_unref(def, s);
  3532. }
  3533. }
  3534. }
  3535. upb_strtable_uninit(&addtab);
  3536. upb_gfree(add_defs);
  3537. assert(!upb_ok(status));
  3538. return false;
  3539. }
  3540. bool upb_symtab_add(upb_symtab *s, upb_def *const*defs, size_t n,
  3541. void *ref_donor, upb_status *status) {
  3542. return symtab_add(s, defs, n, ref_donor, NULL, status);
  3543. }
  3544. bool upb_symtab_addfile(upb_symtab *s, upb_filedef *file, upb_status *status) {
  3545. size_t n;
  3546. size_t i;
  3547. upb_def **defs;
  3548. bool ret;
  3549. n = upb_filedef_defcount(file);
  3550. defs = upb_gmalloc(sizeof(*defs) * n);
  3551. if (defs == NULL) {
  3552. upb_status_seterrmsg(status, "Out of memory");
  3553. return false;
  3554. }
  3555. for (i = 0; i < n; i++) {
  3556. defs[i] = upb_filedef_mutabledef(file, i);
  3557. }
  3558. ret = symtab_add(s, defs, n, NULL, upb_filedef_upcast_mutable(file), status);
  3559. upb_gfree(defs);
  3560. return ret;
  3561. }
  3562. /* Iteration. */
  3563. static void advance_to_matching(upb_symtab_iter *iter) {
  3564. if (iter->type == UPB_DEF_ANY)
  3565. return;
  3566. while (!upb_strtable_done(&iter->iter) &&
  3567. iter->type != upb_symtab_iter_def(iter)->type) {
  3568. upb_strtable_next(&iter->iter);
  3569. }
  3570. }
  3571. void upb_symtab_begin(upb_symtab_iter *iter, const upb_symtab *s,
  3572. upb_deftype_t type) {
  3573. upb_strtable_begin(&iter->iter, &s->symtab);
  3574. iter->type = type;
  3575. advance_to_matching(iter);
  3576. }
  3577. void upb_symtab_next(upb_symtab_iter *iter) {
  3578. upb_strtable_next(&iter->iter);
  3579. advance_to_matching(iter);
  3580. }
  3581. bool upb_symtab_done(const upb_symtab_iter *iter) {
  3582. return upb_strtable_done(&iter->iter);
  3583. }
  3584. const upb_def *upb_symtab_iter_def(const upb_symtab_iter *iter) {
  3585. return upb_value_getptr(upb_strtable_iter_value(&iter->iter));
  3586. }
  3587. /*
  3588. ** upb_table Implementation
  3589. **
  3590. ** Implementation is heavily inspired by Lua's ltable.c.
  3591. */
  3592. #include <string.h>
  3593. #define UPB_MAXARRSIZE 16 /* 64k. */
  3594. /* From Chromium. */
  3595. #define ARRAY_SIZE(x) \
  3596. ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x])))))
  3597. #ifdef NDEBUG
  3598. static void upb_check_alloc(upb_table *t, upb_alloc *a) {
  3599. UPB_UNUSED(t);
  3600. UPB_UNUSED(a);
  3601. }
  3602. #else
  3603. static void upb_check_alloc(upb_table *t, upb_alloc *a) {
  3604. assert(t->alloc == a);
  3605. }
  3606. #endif
  3607. static const double MAX_LOAD = 0.85;
  3608. /* The minimum utilization of the array part of a mixed hash/array table. This
  3609. * is a speed/memory-usage tradeoff (though it's not straightforward because of
  3610. * cache effects). The lower this is, the more memory we'll use. */
  3611. static const double MIN_DENSITY = 0.1;
  3612. bool is_pow2(uint64_t v) { return v == 0 || (v & (v - 1)) == 0; }
  3613. int log2ceil(uint64_t v) {
  3614. int ret = 0;
  3615. bool pow2 = is_pow2(v);
  3616. while (v >>= 1) ret++;
  3617. ret = pow2 ? ret : ret + 1; /* Ceiling. */
  3618. return UPB_MIN(UPB_MAXARRSIZE, ret);
  3619. }
  3620. char *upb_strdup(const char *s, upb_alloc *a) {
  3621. return upb_strdup2(s, strlen(s), a);
  3622. }
  3623. char *upb_strdup2(const char *s, size_t len, upb_alloc *a) {
  3624. size_t n;
  3625. char *p;
  3626. /* Prevent overflow errors. */
  3627. if (len == SIZE_MAX) return NULL;
  3628. /* Always null-terminate, even if binary data; but don't rely on the input to
  3629. * have a null-terminating byte since it may be a raw binary buffer. */
  3630. n = len + 1;
  3631. p = upb_malloc(a, n);
  3632. if (p) {
  3633. memcpy(p, s, len);
  3634. p[len] = 0;
  3635. }
  3636. return p;
  3637. }
  3638. /* A type to represent the lookup key of either a strtable or an inttable. */
  3639. typedef union {
  3640. uintptr_t num;
  3641. struct {
  3642. const char *str;
  3643. size_t len;
  3644. } str;
  3645. } lookupkey_t;
  3646. static lookupkey_t strkey2(const char *str, size_t len) {
  3647. lookupkey_t k;
  3648. k.str.str = str;
  3649. k.str.len = len;
  3650. return k;
  3651. }
  3652. static lookupkey_t intkey(uintptr_t key) {
  3653. lookupkey_t k;
  3654. k.num = key;
  3655. return k;
  3656. }
  3657. typedef uint32_t hashfunc_t(upb_tabkey key);
  3658. typedef bool eqlfunc_t(upb_tabkey k1, lookupkey_t k2);
  3659. /* Base table (shared code) ***************************************************/
  3660. /* For when we need to cast away const. */
  3661. static upb_tabent *mutable_entries(upb_table *t) {
  3662. return (upb_tabent*)t->entries;
  3663. }
  3664. static bool isfull(upb_table *t) {
  3665. if (upb_table_size(t) == 0) {
  3666. return true;
  3667. } else {
  3668. return ((double)(t->count + 1) / upb_table_size(t)) > MAX_LOAD;
  3669. }
  3670. }
  3671. static bool init(upb_table *t, upb_ctype_t ctype, uint8_t size_lg2,
  3672. upb_alloc *a) {
  3673. size_t bytes;
  3674. t->count = 0;
  3675. t->ctype = ctype;
  3676. t->size_lg2 = size_lg2;
  3677. t->mask = upb_table_size(t) ? upb_table_size(t) - 1 : 0;
  3678. #ifndef NDEBUG
  3679. t->alloc = a;
  3680. #endif
  3681. bytes = upb_table_size(t) * sizeof(upb_tabent);
  3682. if (bytes > 0) {
  3683. t->entries = upb_malloc(a, bytes);
  3684. if (!t->entries) return false;
  3685. memset(mutable_entries(t), 0, bytes);
  3686. } else {
  3687. t->entries = NULL;
  3688. }
  3689. return true;
  3690. }
  3691. static void uninit(upb_table *t, upb_alloc *a) {
  3692. upb_check_alloc(t, a);
  3693. upb_free(a, mutable_entries(t));
  3694. }
  3695. static upb_tabent *emptyent(upb_table *t) {
  3696. upb_tabent *e = mutable_entries(t) + upb_table_size(t);
  3697. while (1) { if (upb_tabent_isempty(--e)) return e; assert(e > t->entries); }
  3698. }
  3699. static upb_tabent *getentry_mutable(upb_table *t, uint32_t hash) {
  3700. return (upb_tabent*)upb_getentry(t, hash);
  3701. }
  3702. static const upb_tabent *findentry(const upb_table *t, lookupkey_t key,
  3703. uint32_t hash, eqlfunc_t *eql) {
  3704. const upb_tabent *e;
  3705. if (t->size_lg2 == 0) return NULL;
  3706. e = upb_getentry(t, hash);
  3707. if (upb_tabent_isempty(e)) return NULL;
  3708. while (1) {
  3709. if (eql(e->key, key)) return e;
  3710. if ((e = e->next) == NULL) return NULL;
  3711. }
  3712. }
  3713. static upb_tabent *findentry_mutable(upb_table *t, lookupkey_t key,
  3714. uint32_t hash, eqlfunc_t *eql) {
  3715. return (upb_tabent*)findentry(t, key, hash, eql);
  3716. }
  3717. static bool lookup(const upb_table *t, lookupkey_t key, upb_value *v,
  3718. uint32_t hash, eqlfunc_t *eql) {
  3719. const upb_tabent *e = findentry(t, key, hash, eql);
  3720. if (e) {
  3721. if (v) {
  3722. _upb_value_setval(v, e->val.val, t->ctype);
  3723. }
  3724. return true;
  3725. } else {
  3726. return false;
  3727. }
  3728. }
  3729. /* The given key must not already exist in the table. */
  3730. static void insert(upb_table *t, lookupkey_t key, upb_tabkey tabkey,
  3731. upb_value val, uint32_t hash,
  3732. hashfunc_t *hashfunc, eqlfunc_t *eql) {
  3733. upb_tabent *mainpos_e;
  3734. upb_tabent *our_e;
  3735. UPB_UNUSED(eql);
  3736. UPB_UNUSED(key);
  3737. assert(findentry(t, key, hash, eql) == NULL);
  3738. assert(val.ctype == t->ctype);
  3739. t->count++;
  3740. mainpos_e = getentry_mutable(t, hash);
  3741. our_e = mainpos_e;
  3742. if (upb_tabent_isempty(mainpos_e)) {
  3743. /* Our main position is empty; use it. */
  3744. our_e->next = NULL;
  3745. } else {
  3746. /* Collision. */
  3747. upb_tabent *new_e = emptyent(t);
  3748. /* Head of collider's chain. */
  3749. upb_tabent *chain = getentry_mutable(t, hashfunc(mainpos_e->key));
  3750. if (chain == mainpos_e) {
  3751. /* Existing ent is in its main posisiton (it has the same hash as us, and
  3752. * is the head of our chain). Insert to new ent and append to this chain. */
  3753. new_e->next = mainpos_e->next;
  3754. mainpos_e->next = new_e;
  3755. our_e = new_e;
  3756. } else {
  3757. /* Existing ent is not in its main position (it is a node in some other
  3758. * chain). This implies that no existing ent in the table has our hash.
  3759. * Evict it (updating its chain) and use its ent for head of our chain. */
  3760. *new_e = *mainpos_e; /* copies next. */
  3761. while (chain->next != mainpos_e) {
  3762. chain = (upb_tabent*)chain->next;
  3763. assert(chain);
  3764. }
  3765. chain->next = new_e;
  3766. our_e = mainpos_e;
  3767. our_e->next = NULL;
  3768. }
  3769. }
  3770. our_e->key = tabkey;
  3771. our_e->val.val = val.val;
  3772. assert(findentry(t, key, hash, eql) == our_e);
  3773. }
  3774. static bool rm(upb_table *t, lookupkey_t key, upb_value *val,
  3775. upb_tabkey *removed, uint32_t hash, eqlfunc_t *eql) {
  3776. upb_tabent *chain = getentry_mutable(t, hash);
  3777. if (upb_tabent_isempty(chain)) return false;
  3778. if (eql(chain->key, key)) {
  3779. /* Element to remove is at the head of its chain. */
  3780. t->count--;
  3781. if (val) {
  3782. _upb_value_setval(val, chain->val.val, t->ctype);
  3783. }
  3784. if (chain->next) {
  3785. upb_tabent *move = (upb_tabent*)chain->next;
  3786. *chain = *move;
  3787. if (removed) *removed = move->key;
  3788. move->key = 0; /* Make the slot empty. */
  3789. } else {
  3790. if (removed) *removed = chain->key;
  3791. chain->key = 0; /* Make the slot empty. */
  3792. }
  3793. return true;
  3794. } else {
  3795. /* Element to remove is either in a non-head position or not in the
  3796. * table. */
  3797. while (chain->next && !eql(chain->next->key, key))
  3798. chain = (upb_tabent*)chain->next;
  3799. if (chain->next) {
  3800. /* Found element to remove. */
  3801. upb_tabent *rm;
  3802. if (val) {
  3803. _upb_value_setval(val, chain->next->val.val, t->ctype);
  3804. }
  3805. rm = (upb_tabent*)chain->next;
  3806. if (removed) *removed = rm->key;
  3807. rm->key = 0;
  3808. chain->next = rm->next;
  3809. t->count--;
  3810. return true;
  3811. } else {
  3812. return false;
  3813. }
  3814. }
  3815. }
  3816. static size_t next(const upb_table *t, size_t i) {
  3817. do {
  3818. if (++i >= upb_table_size(t))
  3819. return SIZE_MAX;
  3820. } while(upb_tabent_isempty(&t->entries[i]));
  3821. return i;
  3822. }
  3823. static size_t begin(const upb_table *t) {
  3824. return next(t, -1);
  3825. }
  3826. /* upb_strtable ***************************************************************/
  3827. /* A simple "subclass" of upb_table that only adds a hash function for strings. */
  3828. static upb_tabkey strcopy(lookupkey_t k2, upb_alloc *a) {
  3829. char *str = upb_malloc(a, k2.str.len + sizeof(uint32_t) + 1);
  3830. if (str == NULL) return 0;
  3831. memcpy(str, &k2.str.len, sizeof(uint32_t));
  3832. memcpy(str + sizeof(uint32_t), k2.str.str, k2.str.len + 1);
  3833. return (uintptr_t)str;
  3834. }
  3835. static uint32_t strhash(upb_tabkey key) {
  3836. uint32_t len;
  3837. char *str = upb_tabstr(key, &len);
  3838. return MurmurHash2(str, len, 0);
  3839. }
  3840. static bool streql(upb_tabkey k1, lookupkey_t k2) {
  3841. uint32_t len;
  3842. char *str = upb_tabstr(k1, &len);
  3843. return len == k2.str.len && memcmp(str, k2.str.str, len) == 0;
  3844. }
  3845. bool upb_strtable_init2(upb_strtable *t, upb_ctype_t ctype, upb_alloc *a) {
  3846. return init(&t->t, ctype, 2, a);
  3847. }
  3848. void upb_strtable_uninit2(upb_strtable *t, upb_alloc *a) {
  3849. size_t i;
  3850. for (i = 0; i < upb_table_size(&t->t); i++)
  3851. upb_free(a, (void*)t->t.entries[i].key);
  3852. uninit(&t->t, a);
  3853. }
  3854. bool upb_strtable_resize(upb_strtable *t, size_t size_lg2, upb_alloc *a) {
  3855. upb_strtable new_table;
  3856. upb_strtable_iter i;
  3857. upb_check_alloc(&t->t, a);
  3858. if (!init(&new_table.t, t->t.ctype, size_lg2, a))
  3859. return false;
  3860. upb_strtable_begin(&i, t);
  3861. for ( ; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  3862. upb_strtable_insert3(
  3863. &new_table,
  3864. upb_strtable_iter_key(&i),
  3865. upb_strtable_iter_keylength(&i),
  3866. upb_strtable_iter_value(&i),
  3867. a);
  3868. }
  3869. upb_strtable_uninit2(t, a);
  3870. *t = new_table;
  3871. return true;
  3872. }
  3873. bool upb_strtable_insert3(upb_strtable *t, const char *k, size_t len,
  3874. upb_value v, upb_alloc *a) {
  3875. lookupkey_t key;
  3876. upb_tabkey tabkey;
  3877. uint32_t hash;
  3878. upb_check_alloc(&t->t, a);
  3879. if (isfull(&t->t)) {
  3880. /* Need to resize. New table of double the size, add old elements to it. */
  3881. if (!upb_strtable_resize(t, t->t.size_lg2 + 1, a)) {
  3882. return false;
  3883. }
  3884. }
  3885. key = strkey2(k, len);
  3886. tabkey = strcopy(key, a);
  3887. if (tabkey == 0) return false;
  3888. hash = MurmurHash2(key.str.str, key.str.len, 0);
  3889. insert(&t->t, key, tabkey, v, hash, &strhash, &streql);
  3890. return true;
  3891. }
  3892. bool upb_strtable_lookup2(const upb_strtable *t, const char *key, size_t len,
  3893. upb_value *v) {
  3894. uint32_t hash = MurmurHash2(key, len, 0);
  3895. return lookup(&t->t, strkey2(key, len), v, hash, &streql);
  3896. }
  3897. bool upb_strtable_remove3(upb_strtable *t, const char *key, size_t len,
  3898. upb_value *val, upb_alloc *alloc) {
  3899. uint32_t hash = MurmurHash2(key, strlen(key), 0);
  3900. upb_tabkey tabkey;
  3901. if (rm(&t->t, strkey2(key, len), val, &tabkey, hash, &streql)) {
  3902. upb_free(alloc, (void*)tabkey);
  3903. return true;
  3904. } else {
  3905. return false;
  3906. }
  3907. }
  3908. /* Iteration */
  3909. static const upb_tabent *str_tabent(const upb_strtable_iter *i) {
  3910. return &i->t->t.entries[i->index];
  3911. }
  3912. void upb_strtable_begin(upb_strtable_iter *i, const upb_strtable *t) {
  3913. i->t = t;
  3914. i->index = begin(&t->t);
  3915. }
  3916. void upb_strtable_next(upb_strtable_iter *i) {
  3917. i->index = next(&i->t->t, i->index);
  3918. }
  3919. bool upb_strtable_done(const upb_strtable_iter *i) {
  3920. return i->index >= upb_table_size(&i->t->t) ||
  3921. upb_tabent_isempty(str_tabent(i));
  3922. }
  3923. const char *upb_strtable_iter_key(const upb_strtable_iter *i) {
  3924. assert(!upb_strtable_done(i));
  3925. return upb_tabstr(str_tabent(i)->key, NULL);
  3926. }
  3927. size_t upb_strtable_iter_keylength(const upb_strtable_iter *i) {
  3928. uint32_t len;
  3929. assert(!upb_strtable_done(i));
  3930. upb_tabstr(str_tabent(i)->key, &len);
  3931. return len;
  3932. }
  3933. upb_value upb_strtable_iter_value(const upb_strtable_iter *i) {
  3934. assert(!upb_strtable_done(i));
  3935. return _upb_value_val(str_tabent(i)->val.val, i->t->t.ctype);
  3936. }
  3937. void upb_strtable_iter_setdone(upb_strtable_iter *i) {
  3938. i->index = SIZE_MAX;
  3939. }
  3940. bool upb_strtable_iter_isequal(const upb_strtable_iter *i1,
  3941. const upb_strtable_iter *i2) {
  3942. if (upb_strtable_done(i1) && upb_strtable_done(i2))
  3943. return true;
  3944. return i1->t == i2->t && i1->index == i2->index;
  3945. }
  3946. /* upb_inttable ***************************************************************/
  3947. /* For inttables we use a hybrid structure where small keys are kept in an
  3948. * array and large keys are put in the hash table. */
  3949. static uint32_t inthash(upb_tabkey key) { return upb_inthash(key); }
  3950. static bool inteql(upb_tabkey k1, lookupkey_t k2) {
  3951. return k1 == k2.num;
  3952. }
  3953. static upb_tabval *mutable_array(upb_inttable *t) {
  3954. return (upb_tabval*)t->array;
  3955. }
  3956. static upb_tabval *inttable_val(upb_inttable *t, uintptr_t key) {
  3957. if (key < t->array_size) {
  3958. return upb_arrhas(t->array[key]) ? &(mutable_array(t)[key]) : NULL;
  3959. } else {
  3960. upb_tabent *e =
  3961. findentry_mutable(&t->t, intkey(key), upb_inthash(key), &inteql);
  3962. return e ? &e->val : NULL;
  3963. }
  3964. }
  3965. static const upb_tabval *inttable_val_const(const upb_inttable *t,
  3966. uintptr_t key) {
  3967. return inttable_val((upb_inttable*)t, key);
  3968. }
  3969. size_t upb_inttable_count(const upb_inttable *t) {
  3970. return t->t.count + t->array_count;
  3971. }
  3972. static void check(upb_inttable *t) {
  3973. UPB_UNUSED(t);
  3974. #if defined(UPB_DEBUG_TABLE) && !defined(NDEBUG)
  3975. {
  3976. /* This check is very expensive (makes inserts/deletes O(N)). */
  3977. size_t count = 0;
  3978. upb_inttable_iter i;
  3979. upb_inttable_begin(&i, t);
  3980. for(; !upb_inttable_done(&i); upb_inttable_next(&i), count++) {
  3981. assert(upb_inttable_lookup(t, upb_inttable_iter_key(&i), NULL));
  3982. }
  3983. assert(count == upb_inttable_count(t));
  3984. }
  3985. #endif
  3986. }
  3987. bool upb_inttable_sizedinit(upb_inttable *t, upb_ctype_t ctype,
  3988. size_t asize, int hsize_lg2, upb_alloc *a) {
  3989. size_t array_bytes;
  3990. if (!init(&t->t, ctype, hsize_lg2, a)) return false;
  3991. /* Always make the array part at least 1 long, so that we know key 0
  3992. * won't be in the hash part, which simplifies things. */
  3993. t->array_size = UPB_MAX(1, asize);
  3994. t->array_count = 0;
  3995. array_bytes = t->array_size * sizeof(upb_value);
  3996. t->array = upb_malloc(a, array_bytes);
  3997. if (!t->array) {
  3998. uninit(&t->t, a);
  3999. return false;
  4000. }
  4001. memset(mutable_array(t), 0xff, array_bytes);
  4002. check(t);
  4003. return true;
  4004. }
  4005. bool upb_inttable_init2(upb_inttable *t, upb_ctype_t ctype, upb_alloc *a) {
  4006. return upb_inttable_sizedinit(t, ctype, 0, 4, a);
  4007. }
  4008. void upb_inttable_uninit2(upb_inttable *t, upb_alloc *a) {
  4009. uninit(&t->t, a);
  4010. upb_free(a, mutable_array(t));
  4011. }
  4012. bool upb_inttable_insert2(upb_inttable *t, uintptr_t key, upb_value val,
  4013. upb_alloc *a) {
  4014. upb_tabval tabval;
  4015. tabval.val = val.val;
  4016. UPB_UNUSED(tabval);
  4017. assert(upb_arrhas(tabval)); /* This will reject (uint64_t)-1. Fix this. */
  4018. upb_check_alloc(&t->t, a);
  4019. if (key < t->array_size) {
  4020. assert(!upb_arrhas(t->array[key]));
  4021. t->array_count++;
  4022. mutable_array(t)[key].val = val.val;
  4023. } else {
  4024. if (isfull(&t->t)) {
  4025. /* Need to resize the hash part, but we re-use the array part. */
  4026. size_t i;
  4027. upb_table new_table;
  4028. if (!init(&new_table, t->t.ctype, t->t.size_lg2 + 1, a)) {
  4029. return false;
  4030. }
  4031. for (i = begin(&t->t); i < upb_table_size(&t->t); i = next(&t->t, i)) {
  4032. const upb_tabent *e = &t->t.entries[i];
  4033. uint32_t hash;
  4034. upb_value v;
  4035. _upb_value_setval(&v, e->val.val, t->t.ctype);
  4036. hash = upb_inthash(e->key);
  4037. insert(&new_table, intkey(e->key), e->key, v, hash, &inthash, &inteql);
  4038. }
  4039. assert(t->t.count == new_table.count);
  4040. uninit(&t->t, a);
  4041. t->t = new_table;
  4042. }
  4043. insert(&t->t, intkey(key), key, val, upb_inthash(key), &inthash, &inteql);
  4044. }
  4045. check(t);
  4046. return true;
  4047. }
  4048. bool upb_inttable_lookup(const upb_inttable *t, uintptr_t key, upb_value *v) {
  4049. const upb_tabval *table_v = inttable_val_const(t, key);
  4050. if (!table_v) return false;
  4051. if (v) _upb_value_setval(v, table_v->val, t->t.ctype);
  4052. return true;
  4053. }
  4054. bool upb_inttable_replace(upb_inttable *t, uintptr_t key, upb_value val) {
  4055. upb_tabval *table_v = inttable_val(t, key);
  4056. if (!table_v) return false;
  4057. table_v->val = val.val;
  4058. return true;
  4059. }
  4060. bool upb_inttable_remove(upb_inttable *t, uintptr_t key, upb_value *val) {
  4061. bool success;
  4062. if (key < t->array_size) {
  4063. if (upb_arrhas(t->array[key])) {
  4064. upb_tabval empty = UPB_TABVALUE_EMPTY_INIT;
  4065. t->array_count--;
  4066. if (val) {
  4067. _upb_value_setval(val, t->array[key].val, t->t.ctype);
  4068. }
  4069. mutable_array(t)[key] = empty;
  4070. success = true;
  4071. } else {
  4072. success = false;
  4073. }
  4074. } else {
  4075. upb_tabkey removed;
  4076. uint32_t hash = upb_inthash(key);
  4077. success = rm(&t->t, intkey(key), val, &removed, hash, &inteql);
  4078. }
  4079. check(t);
  4080. return success;
  4081. }
  4082. bool upb_inttable_push2(upb_inttable *t, upb_value val, upb_alloc *a) {
  4083. upb_check_alloc(&t->t, a);
  4084. return upb_inttable_insert2(t, upb_inttable_count(t), val, a);
  4085. }
  4086. upb_value upb_inttable_pop(upb_inttable *t) {
  4087. upb_value val;
  4088. bool ok = upb_inttable_remove(t, upb_inttable_count(t) - 1, &val);
  4089. UPB_ASSERT_VAR(ok, ok);
  4090. return val;
  4091. }
  4092. bool upb_inttable_insertptr2(upb_inttable *t, const void *key, upb_value val,
  4093. upb_alloc *a) {
  4094. upb_check_alloc(&t->t, a);
  4095. return upb_inttable_insert2(t, (uintptr_t)key, val, a);
  4096. }
  4097. bool upb_inttable_lookupptr(const upb_inttable *t, const void *key,
  4098. upb_value *v) {
  4099. return upb_inttable_lookup(t, (uintptr_t)key, v);
  4100. }
  4101. bool upb_inttable_removeptr(upb_inttable *t, const void *key, upb_value *val) {
  4102. return upb_inttable_remove(t, (uintptr_t)key, val);
  4103. }
  4104. void upb_inttable_compact2(upb_inttable *t, upb_alloc *a) {
  4105. /* A power-of-two histogram of the table keys. */
  4106. size_t counts[UPB_MAXARRSIZE + 1] = {0};
  4107. /* The max key in each bucket. */
  4108. uintptr_t max[UPB_MAXARRSIZE + 1] = {0};
  4109. upb_inttable_iter i;
  4110. size_t arr_count;
  4111. int size_lg2;
  4112. upb_inttable new_t;
  4113. upb_check_alloc(&t->t, a);
  4114. upb_inttable_begin(&i, t);
  4115. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  4116. uintptr_t key = upb_inttable_iter_key(&i);
  4117. int bucket = log2ceil(key);
  4118. max[bucket] = UPB_MAX(max[bucket], key);
  4119. counts[bucket]++;
  4120. }
  4121. /* Find the largest power of two that satisfies the MIN_DENSITY
  4122. * definition (while actually having some keys). */
  4123. arr_count = upb_inttable_count(t);
  4124. for (size_lg2 = ARRAY_SIZE(counts) - 1; size_lg2 > 0; size_lg2--) {
  4125. if (counts[size_lg2] == 0) {
  4126. /* We can halve again without losing any entries. */
  4127. continue;
  4128. } else if (arr_count >= (1 << size_lg2) * MIN_DENSITY) {
  4129. break;
  4130. }
  4131. arr_count -= counts[size_lg2];
  4132. }
  4133. assert(arr_count <= upb_inttable_count(t));
  4134. {
  4135. /* Insert all elements into new, perfectly-sized table. */
  4136. size_t arr_size = max[size_lg2] + 1; /* +1 so arr[max] will fit. */
  4137. size_t hash_count = upb_inttable_count(t) - arr_count;
  4138. size_t hash_size = hash_count ? (hash_count / MAX_LOAD) + 1 : 0;
  4139. size_t hashsize_lg2 = log2ceil(hash_size);
  4140. upb_inttable_sizedinit(&new_t, t->t.ctype, arr_size, hashsize_lg2, a);
  4141. upb_inttable_begin(&i, t);
  4142. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  4143. uintptr_t k = upb_inttable_iter_key(&i);
  4144. upb_inttable_insert2(&new_t, k, upb_inttable_iter_value(&i), a);
  4145. }
  4146. assert(new_t.array_size == arr_size);
  4147. assert(new_t.t.size_lg2 == hashsize_lg2);
  4148. }
  4149. upb_inttable_uninit2(t, a);
  4150. *t = new_t;
  4151. }
  4152. /* Iteration. */
  4153. static const upb_tabent *int_tabent(const upb_inttable_iter *i) {
  4154. assert(!i->array_part);
  4155. return &i->t->t.entries[i->index];
  4156. }
  4157. static upb_tabval int_arrent(const upb_inttable_iter *i) {
  4158. assert(i->array_part);
  4159. return i->t->array[i->index];
  4160. }
  4161. void upb_inttable_begin(upb_inttable_iter *i, const upb_inttable *t) {
  4162. i->t = t;
  4163. i->index = -1;
  4164. i->array_part = true;
  4165. upb_inttable_next(i);
  4166. }
  4167. void upb_inttable_next(upb_inttable_iter *iter) {
  4168. const upb_inttable *t = iter->t;
  4169. if (iter->array_part) {
  4170. while (++iter->index < t->array_size) {
  4171. if (upb_arrhas(int_arrent(iter))) {
  4172. return;
  4173. }
  4174. }
  4175. iter->array_part = false;
  4176. iter->index = begin(&t->t);
  4177. } else {
  4178. iter->index = next(&t->t, iter->index);
  4179. }
  4180. }
  4181. bool upb_inttable_done(const upb_inttable_iter *i) {
  4182. if (i->array_part) {
  4183. return i->index >= i->t->array_size ||
  4184. !upb_arrhas(int_arrent(i));
  4185. } else {
  4186. return i->index >= upb_table_size(&i->t->t) ||
  4187. upb_tabent_isempty(int_tabent(i));
  4188. }
  4189. }
  4190. uintptr_t upb_inttable_iter_key(const upb_inttable_iter *i) {
  4191. assert(!upb_inttable_done(i));
  4192. return i->array_part ? i->index : int_tabent(i)->key;
  4193. }
  4194. upb_value upb_inttable_iter_value(const upb_inttable_iter *i) {
  4195. assert(!upb_inttable_done(i));
  4196. return _upb_value_val(
  4197. i->array_part ? i->t->array[i->index].val : int_tabent(i)->val.val,
  4198. i->t->t.ctype);
  4199. }
  4200. void upb_inttable_iter_setdone(upb_inttable_iter *i) {
  4201. i->index = SIZE_MAX;
  4202. i->array_part = false;
  4203. }
  4204. bool upb_inttable_iter_isequal(const upb_inttable_iter *i1,
  4205. const upb_inttable_iter *i2) {
  4206. if (upb_inttable_done(i1) && upb_inttable_done(i2))
  4207. return true;
  4208. return i1->t == i2->t && i1->index == i2->index &&
  4209. i1->array_part == i2->array_part;
  4210. }
  4211. #ifdef UPB_UNALIGNED_READS_OK
  4212. /* -----------------------------------------------------------------------------
  4213. * MurmurHash2, by Austin Appleby (released as public domain).
  4214. * Reformatted and C99-ified by Joshua Haberman.
  4215. * Note - This code makes a few assumptions about how your machine behaves -
  4216. * 1. We can read a 4-byte value from any address without crashing
  4217. * 2. sizeof(int) == 4 (in upb this limitation is removed by using uint32_t
  4218. * And it has a few limitations -
  4219. * 1. It will not work incrementally.
  4220. * 2. It will not produce the same results on little-endian and big-endian
  4221. * machines. */
  4222. uint32_t MurmurHash2(const void *key, size_t len, uint32_t seed) {
  4223. /* 'm' and 'r' are mixing constants generated offline.
  4224. * They're not really 'magic', they just happen to work well. */
  4225. const uint32_t m = 0x5bd1e995;
  4226. const int32_t r = 24;
  4227. /* Initialize the hash to a 'random' value */
  4228. uint32_t h = seed ^ len;
  4229. /* Mix 4 bytes at a time into the hash */
  4230. const uint8_t * data = (const uint8_t *)key;
  4231. while(len >= 4) {
  4232. uint32_t k = *(uint32_t *)data;
  4233. k *= m;
  4234. k ^= k >> r;
  4235. k *= m;
  4236. h *= m;
  4237. h ^= k;
  4238. data += 4;
  4239. len -= 4;
  4240. }
  4241. /* Handle the last few bytes of the input array */
  4242. switch(len) {
  4243. case 3: h ^= data[2] << 16;
  4244. case 2: h ^= data[1] << 8;
  4245. case 1: h ^= data[0]; h *= m;
  4246. };
  4247. /* Do a few final mixes of the hash to ensure the last few
  4248. * bytes are well-incorporated. */
  4249. h ^= h >> 13;
  4250. h *= m;
  4251. h ^= h >> 15;
  4252. return h;
  4253. }
  4254. #else /* !UPB_UNALIGNED_READS_OK */
  4255. /* -----------------------------------------------------------------------------
  4256. * MurmurHashAligned2, by Austin Appleby
  4257. * Same algorithm as MurmurHash2, but only does aligned reads - should be safer
  4258. * on certain platforms.
  4259. * Performance will be lower than MurmurHash2 */
  4260. #define MIX(h,k,m) { k *= m; k ^= k >> r; k *= m; h *= m; h ^= k; }
  4261. uint32_t MurmurHash2(const void * key, size_t len, uint32_t seed) {
  4262. const uint32_t m = 0x5bd1e995;
  4263. const int32_t r = 24;
  4264. const uint8_t * data = (const uint8_t *)key;
  4265. uint32_t h = seed ^ len;
  4266. uint8_t align = (uintptr_t)data & 3;
  4267. if(align && (len >= 4)) {
  4268. /* Pre-load the temp registers */
  4269. uint32_t t = 0, d = 0;
  4270. int32_t sl;
  4271. int32_t sr;
  4272. switch(align) {
  4273. case 1: t |= data[2] << 16;
  4274. case 2: t |= data[1] << 8;
  4275. case 3: t |= data[0];
  4276. }
  4277. t <<= (8 * align);
  4278. data += 4-align;
  4279. len -= 4-align;
  4280. sl = 8 * (4-align);
  4281. sr = 8 * align;
  4282. /* Mix */
  4283. while(len >= 4) {
  4284. uint32_t k;
  4285. d = *(uint32_t *)data;
  4286. t = (t >> sr) | (d << sl);
  4287. k = t;
  4288. MIX(h,k,m);
  4289. t = d;
  4290. data += 4;
  4291. len -= 4;
  4292. }
  4293. /* Handle leftover data in temp registers */
  4294. d = 0;
  4295. if(len >= align) {
  4296. uint32_t k;
  4297. switch(align) {
  4298. case 3: d |= data[2] << 16;
  4299. case 2: d |= data[1] << 8;
  4300. case 1: d |= data[0];
  4301. }
  4302. k = (t >> sr) | (d << sl);
  4303. MIX(h,k,m);
  4304. data += align;
  4305. len -= align;
  4306. /* ----------
  4307. * Handle tail bytes */
  4308. switch(len) {
  4309. case 3: h ^= data[2] << 16;
  4310. case 2: h ^= data[1] << 8;
  4311. case 1: h ^= data[0]; h *= m;
  4312. };
  4313. } else {
  4314. switch(len) {
  4315. case 3: d |= data[2] << 16;
  4316. case 2: d |= data[1] << 8;
  4317. case 1: d |= data[0];
  4318. case 0: h ^= (t >> sr) | (d << sl); h *= m;
  4319. }
  4320. }
  4321. h ^= h >> 13;
  4322. h *= m;
  4323. h ^= h >> 15;
  4324. return h;
  4325. } else {
  4326. while(len >= 4) {
  4327. uint32_t k = *(uint32_t *)data;
  4328. MIX(h,k,m);
  4329. data += 4;
  4330. len -= 4;
  4331. }
  4332. /* ----------
  4333. * Handle tail bytes */
  4334. switch(len) {
  4335. case 3: h ^= data[2] << 16;
  4336. case 2: h ^= data[1] << 8;
  4337. case 1: h ^= data[0]; h *= m;
  4338. };
  4339. h ^= h >> 13;
  4340. h *= m;
  4341. h ^= h >> 15;
  4342. return h;
  4343. }
  4344. }
  4345. #undef MIX
  4346. #endif /* UPB_UNALIGNED_READS_OK */
  4347. #include <errno.h>
  4348. #include <stdarg.h>
  4349. #include <stddef.h>
  4350. #include <stdint.h>
  4351. #include <stdio.h>
  4352. #include <stdlib.h>
  4353. #include <string.h>
  4354. bool upb_dumptostderr(void *closure, const upb_status* status) {
  4355. UPB_UNUSED(closure);
  4356. fprintf(stderr, "%s\n", upb_status_errmsg(status));
  4357. return false;
  4358. }
  4359. /* Guarantee null-termination and provide ellipsis truncation.
  4360. * It may be tempting to "optimize" this by initializing these final
  4361. * four bytes up-front and then being careful never to overwrite them,
  4362. * this is safer and simpler. */
  4363. static void nullz(upb_status *status) {
  4364. const char *ellipsis = "...";
  4365. size_t len = strlen(ellipsis);
  4366. assert(sizeof(status->msg) > len);
  4367. memcpy(status->msg + sizeof(status->msg) - len, ellipsis, len);
  4368. }
  4369. /* upb_upberr *****************************************************************/
  4370. upb_errorspace upb_upberr = {"upb error"};
  4371. void upb_upberr_setoom(upb_status *status) {
  4372. status->error_space_ = &upb_upberr;
  4373. upb_status_seterrmsg(status, "Out of memory");
  4374. }
  4375. /* upb_status *****************************************************************/
  4376. void upb_status_clear(upb_status *status) {
  4377. if (!status) return;
  4378. status->ok_ = true;
  4379. status->code_ = 0;
  4380. status->msg[0] = '\0';
  4381. }
  4382. bool upb_ok(const upb_status *status) { return status->ok_; }
  4383. upb_errorspace *upb_status_errspace(const upb_status *status) {
  4384. return status->error_space_;
  4385. }
  4386. int upb_status_errcode(const upb_status *status) { return status->code_; }
  4387. const char *upb_status_errmsg(const upb_status *status) { return status->msg; }
  4388. void upb_status_seterrmsg(upb_status *status, const char *msg) {
  4389. if (!status) return;
  4390. status->ok_ = false;
  4391. strncpy(status->msg, msg, sizeof(status->msg));
  4392. nullz(status);
  4393. }
  4394. void upb_status_seterrf(upb_status *status, const char *fmt, ...) {
  4395. va_list args;
  4396. va_start(args, fmt);
  4397. upb_status_vseterrf(status, fmt, args);
  4398. va_end(args);
  4399. }
  4400. void upb_status_vseterrf(upb_status *status, const char *fmt, va_list args) {
  4401. if (!status) return;
  4402. status->ok_ = false;
  4403. _upb_vsnprintf(status->msg, sizeof(status->msg), fmt, args);
  4404. nullz(status);
  4405. }
  4406. void upb_status_copy(upb_status *to, const upb_status *from) {
  4407. if (!to) return;
  4408. *to = *from;
  4409. }
  4410. /* upb_alloc ******************************************************************/
  4411. static void *upb_global_allocfunc(upb_alloc *alloc, void *ptr, size_t oldsize,
  4412. size_t size) {
  4413. UPB_UNUSED(alloc);
  4414. UPB_UNUSED(oldsize);
  4415. if (size == 0) {
  4416. free(ptr);
  4417. return NULL;
  4418. } else {
  4419. return realloc(ptr, size);
  4420. }
  4421. }
  4422. upb_alloc upb_alloc_global = {&upb_global_allocfunc};
  4423. /* upb_arena ******************************************************************/
  4424. /* Be conservative and choose 16 in case anyone is using SSE. */
  4425. static const size_t maxalign = 16;
  4426. static size_t align_up(size_t size) {
  4427. return ((size + maxalign - 1) / maxalign) * maxalign;
  4428. }
  4429. typedef struct mem_block {
  4430. struct mem_block *next;
  4431. size_t size;
  4432. size_t used;
  4433. bool owned;
  4434. /* Data follows. */
  4435. } mem_block;
  4436. typedef struct cleanup_ent {
  4437. struct cleanup_ent *next;
  4438. upb_cleanup_func *cleanup;
  4439. void *ud;
  4440. } cleanup_ent;
  4441. static void upb_arena_addblock(upb_arena *a, void *ptr, size_t size,
  4442. bool owned) {
  4443. mem_block *block = ptr;
  4444. block->next = a->block_head;
  4445. block->size = size;
  4446. block->used = align_up(sizeof(mem_block));
  4447. block->owned = owned;
  4448. a->block_head = block;
  4449. /* TODO(haberman): ASAN poison. */
  4450. }
  4451. static mem_block *upb_arena_allocblock(upb_arena *a, size_t size) {
  4452. size_t block_size = UPB_MAX(size, a->next_block_size) + sizeof(mem_block);
  4453. mem_block *block = upb_malloc(a->block_alloc, block_size);
  4454. if (!block) {
  4455. return NULL;
  4456. }
  4457. upb_arena_addblock(a, block, block_size, true);
  4458. a->next_block_size = UPB_MIN(block_size * 2, a->max_block_size);
  4459. return block;
  4460. }
  4461. static void *upb_arena_doalloc(upb_alloc *alloc, void *ptr, size_t oldsize,
  4462. size_t size) {
  4463. upb_arena *a = (upb_arena*)alloc; /* upb_alloc is initial member. */
  4464. mem_block *block = a->block_head;
  4465. void *ret;
  4466. if (size == 0) {
  4467. return NULL; /* We are an arena, don't need individual frees. */
  4468. }
  4469. size = align_up(size);
  4470. /* TODO(haberman): special-case if this is a realloc of the last alloc? */
  4471. if (!block || block->size - block->used < size) {
  4472. /* Slow path: have to allocate a new block. */
  4473. block = upb_arena_allocblock(a, size);
  4474. if (!block) {
  4475. return NULL; /* Out of memory. */
  4476. }
  4477. }
  4478. ret = (char*)block + block->used;
  4479. block->used += size;
  4480. if (oldsize > 0) {
  4481. memcpy(ret, ptr, oldsize); /* Preserve existing data. */
  4482. }
  4483. /* TODO(haberman): ASAN unpoison. */
  4484. a->bytes_allocated += size;
  4485. return ret;
  4486. }
  4487. /* Public Arena API ***********************************************************/
  4488. void upb_arena_init(upb_arena *a) {
  4489. a->alloc.func = &upb_arena_doalloc;
  4490. a->block_alloc = &upb_alloc_global;
  4491. a->bytes_allocated = 0;
  4492. a->next_block_size = 256;
  4493. a->max_block_size = 16384;
  4494. a->cleanup_head = NULL;
  4495. a->block_head = NULL;
  4496. }
  4497. void upb_arena_init2(upb_arena *a, void *mem, size_t size, upb_alloc *alloc) {
  4498. upb_arena_init(a);
  4499. if (size > sizeof(mem_block)) {
  4500. upb_arena_addblock(a, mem, size, false);
  4501. }
  4502. if (alloc) {
  4503. a->block_alloc = alloc;
  4504. }
  4505. }
  4506. void upb_arena_uninit(upb_arena *a) {
  4507. cleanup_ent *ent = a->cleanup_head;
  4508. mem_block *block = a->block_head;
  4509. while (ent) {
  4510. ent->cleanup(ent->ud);
  4511. ent = ent->next;
  4512. }
  4513. /* Must do this after running cleanup functions, because this will delete
  4514. * the memory we store our cleanup entries in! */
  4515. while (block) {
  4516. mem_block *next = block->next;
  4517. if (block->owned) {
  4518. upb_free(a->block_alloc, block);
  4519. }
  4520. block = next;
  4521. }
  4522. }
  4523. bool upb_arena_addcleanup(upb_arena *a, upb_cleanup_func *func, void *ud) {
  4524. cleanup_ent *ent = upb_malloc(&a->alloc, sizeof(cleanup_ent));
  4525. if (!ent) {
  4526. return false; /* Out of memory. */
  4527. }
  4528. ent->cleanup = func;
  4529. ent->ud = ud;
  4530. ent->next = a->cleanup_head;
  4531. a->cleanup_head = ent;
  4532. return true;
  4533. }
  4534. size_t upb_arena_bytesallocated(const upb_arena *a) {
  4535. return a->bytes_allocated;
  4536. }
  4537. /* Standard error functions ***************************************************/
  4538. static bool default_err(void *ud, const upb_status *status) {
  4539. UPB_UNUSED(ud);
  4540. UPB_UNUSED(status);
  4541. return false;
  4542. }
  4543. static bool write_err_to(void *ud, const upb_status *status) {
  4544. upb_status *copy_to = ud;
  4545. upb_status_copy(copy_to, status);
  4546. return false;
  4547. }
  4548. /* upb_env ********************************************************************/
  4549. void upb_env_initonly(upb_env *e) {
  4550. e->ok_ = true;
  4551. e->error_func_ = &default_err;
  4552. e->error_ud_ = NULL;
  4553. }
  4554. void upb_env_init(upb_env *e) {
  4555. upb_arena_init(&e->arena_);
  4556. upb_env_initonly(e);
  4557. }
  4558. void upb_env_init2(upb_env *e, void *mem, size_t n, upb_alloc *alloc) {
  4559. upb_arena_init2(&e->arena_, mem, n, alloc);
  4560. upb_env_initonly(e);
  4561. }
  4562. void upb_env_uninit(upb_env *e) {
  4563. upb_arena_uninit(&e->arena_);
  4564. }
  4565. void upb_env_seterrorfunc(upb_env *e, upb_error_func *func, void *ud) {
  4566. e->error_func_ = func;
  4567. e->error_ud_ = ud;
  4568. }
  4569. void upb_env_reporterrorsto(upb_env *e, upb_status *s) {
  4570. e->error_func_ = &write_err_to;
  4571. e->error_ud_ = s;
  4572. }
  4573. bool upb_env_reporterror(upb_env *e, const upb_status *status) {
  4574. e->ok_ = false;
  4575. return e->error_func_(e->error_ud_, status);
  4576. }
  4577. void *upb_env_malloc(upb_env *e, size_t size) {
  4578. return upb_malloc(&e->arena_.alloc, size);
  4579. }
  4580. void *upb_env_realloc(upb_env *e, void *ptr, size_t oldsize, size_t size) {
  4581. return upb_realloc(&e->arena_.alloc, ptr, oldsize, size);
  4582. }
  4583. void upb_env_free(upb_env *e, void *ptr) {
  4584. upb_free(&e->arena_.alloc, ptr);
  4585. }
  4586. bool upb_env_addcleanup(upb_env *e, upb_cleanup_func *func, void *ud) {
  4587. return upb_arena_addcleanup(&e->arena_, func, ud);
  4588. }
  4589. size_t upb_env_bytesallocated(const upb_env *e) {
  4590. return upb_arena_bytesallocated(&e->arena_);
  4591. }
  4592. /* This file was generated by upbc (the upb compiler) from the input
  4593. * file:
  4594. *
  4595. * upb/descriptor/descriptor.proto
  4596. *
  4597. * Do not edit -- your changes will be discarded when the file is
  4598. * regenerated. */
  4599. #include <assert.h>
  4600. static const upb_msgdef msgs[22];
  4601. static const upb_fielddef fields[105];
  4602. static const upb_enumdef enums[5];
  4603. static const upb_tabent strentries[236];
  4604. static const upb_tabent intentries[18];
  4605. static const upb_tabval arrays[184];
  4606. #ifdef UPB_DEBUG_REFS
  4607. static upb_inttable reftables[264];
  4608. #endif
  4609. static const upb_msgdef msgs[22] = {
  4610. UPB_MSGDEF_INIT("google.protobuf.DescriptorProto", 40, 8, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[0], 11, 10), UPB_STRTABLE_INIT(10, 15, UPB_CTYPE_PTR, 4, &strentries[0]), false, UPB_SYNTAX_PROTO2, &reftables[0], &reftables[1]),
  4611. UPB_MSGDEF_INIT("google.protobuf.DescriptorProto.ExtensionRange", 4, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[11], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[16]), false, UPB_SYNTAX_PROTO2, &reftables[2], &reftables[3]),
  4612. UPB_MSGDEF_INIT("google.protobuf.DescriptorProto.ReservedRange", 4, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[14], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[20]), false, UPB_SYNTAX_PROTO2, &reftables[4], &reftables[5]),
  4613. UPB_MSGDEF_INIT("google.protobuf.EnumDescriptorProto", 11, 2, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[17], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[24]), false, UPB_SYNTAX_PROTO2, &reftables[6], &reftables[7]),
  4614. UPB_MSGDEF_INIT("google.protobuf.EnumOptions", 8, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[0], &arrays[21], 4, 2), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[28]), false, UPB_SYNTAX_PROTO2, &reftables[8], &reftables[9]),
  4615. UPB_MSGDEF_INIT("google.protobuf.EnumValueDescriptorProto", 8, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[25], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[32]), false, UPB_SYNTAX_PROTO2, &reftables[10], &reftables[11]),
  4616. UPB_MSGDEF_INIT("google.protobuf.EnumValueOptions", 7, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[2], &arrays[29], 2, 1), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[36]), false, UPB_SYNTAX_PROTO2, &reftables[12], &reftables[13]),
  4617. UPB_MSGDEF_INIT("google.protobuf.FieldDescriptorProto", 23, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[31], 11, 10), UPB_STRTABLE_INIT(10, 15, UPB_CTYPE_PTR, 4, &strentries[40]), false, UPB_SYNTAX_PROTO2, &reftables[14], &reftables[15]),
  4618. UPB_MSGDEF_INIT("google.protobuf.FieldOptions", 12, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[4], &arrays[42], 11, 6), UPB_STRTABLE_INIT(7, 15, UPB_CTYPE_PTR, 4, &strentries[56]), false, UPB_SYNTAX_PROTO2, &reftables[16], &reftables[17]),
  4619. UPB_MSGDEF_INIT("google.protobuf.FileDescriptorProto", 42, 6, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[53], 13, 12), UPB_STRTABLE_INIT(12, 15, UPB_CTYPE_PTR, 4, &strentries[72]), false, UPB_SYNTAX_PROTO2, &reftables[18], &reftables[19]),
  4620. UPB_MSGDEF_INIT("google.protobuf.FileDescriptorSet", 6, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[66], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[88]), false, UPB_SYNTAX_PROTO2, &reftables[20], &reftables[21]),
  4621. UPB_MSGDEF_INIT("google.protobuf.FileOptions", 31, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[6], &arrays[68], 39, 15), UPB_STRTABLE_INIT(16, 31, UPB_CTYPE_PTR, 5, &strentries[92]), false, UPB_SYNTAX_PROTO2, &reftables[22], &reftables[23]),
  4622. UPB_MSGDEF_INIT("google.protobuf.MessageOptions", 10, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[8], &arrays[107], 8, 4), UPB_STRTABLE_INIT(5, 7, UPB_CTYPE_PTR, 3, &strentries[124]), false, UPB_SYNTAX_PROTO2, &reftables[24], &reftables[25]),
  4623. UPB_MSGDEF_INIT("google.protobuf.MethodDescriptorProto", 15, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[115], 7, 6), UPB_STRTABLE_INIT(6, 7, UPB_CTYPE_PTR, 3, &strentries[132]), false, UPB_SYNTAX_PROTO2, &reftables[26], &reftables[27]),
  4624. UPB_MSGDEF_INIT("google.protobuf.MethodOptions", 7, 1, UPB_INTTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &intentries[10], &arrays[122], 1, 0), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[140]), false, UPB_SYNTAX_PROTO2, &reftables[28], &reftables[29]),
  4625. UPB_MSGDEF_INIT("google.protobuf.OneofDescriptorProto", 5, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[123], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[144]), false, UPB_SYNTAX_PROTO2, &reftables[30], &reftables[31]),
  4626. UPB_MSGDEF_INIT("google.protobuf.ServiceDescriptorProto", 11, 2, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[125], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[148]), false, UPB_SYNTAX_PROTO2, &reftables[32], &reftables[33]),
  4627. UPB_MSGDEF_INIT("google.protobuf.ServiceOptions", 7, 1, UPB_INTTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &intentries[14], &arrays[129], 1, 0), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[152]), false, UPB_SYNTAX_PROTO2, &reftables[34], &reftables[35]),
  4628. UPB_MSGDEF_INIT("google.protobuf.SourceCodeInfo", 6, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[130], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[156]), false, UPB_SYNTAX_PROTO2, &reftables[36], &reftables[37]),
  4629. UPB_MSGDEF_INIT("google.protobuf.SourceCodeInfo.Location", 19, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[132], 7, 5), UPB_STRTABLE_INIT(5, 7, UPB_CTYPE_PTR, 3, &strentries[160]), false, UPB_SYNTAX_PROTO2, &reftables[38], &reftables[39]),
  4630. UPB_MSGDEF_INIT("google.protobuf.UninterpretedOption", 18, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[139], 9, 7), UPB_STRTABLE_INIT(7, 15, UPB_CTYPE_PTR, 4, &strentries[168]), false, UPB_SYNTAX_PROTO2, &reftables[40], &reftables[41]),
  4631. UPB_MSGDEF_INIT("google.protobuf.UninterpretedOption.NamePart", 6, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[148], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[184]), false, UPB_SYNTAX_PROTO2, &reftables[42], &reftables[43]),
  4632. };
  4633. static const upb_fielddef fields[105] = {
  4634. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "aggregate_value", 8, &msgs[20], NULL, 15, 6, {0},&reftables[44], &reftables[45]),
  4635. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "allow_alias", 2, &msgs[4], NULL, 6, 1, {0},&reftables[46], &reftables[47]),
  4636. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "cc_enable_arenas", 31, &msgs[11], NULL, 23, 12, {0},&reftables[48], &reftables[49]),
  4637. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "cc_generic_services", 16, &msgs[11], NULL, 17, 6, {0},&reftables[50], &reftables[51]),
  4638. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "client_streaming", 5, &msgs[13], NULL, 13, 4, {0},&reftables[52], &reftables[53]),
  4639. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "csharp_namespace", 37, &msgs[11], NULL, 27, 14, {0},&reftables[54], &reftables[55]),
  4640. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "ctype", 1, &msgs[8], (const upb_def*)(&enums[2]), 6, 1, {0},&reftables[56], &reftables[57]),
  4641. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "default_value", 7, &msgs[7], NULL, 16, 7, {0},&reftables[58], &reftables[59]),
  4642. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_STRING, 0, false, false, false, false, "dependency", 3, &msgs[9], NULL, 30, 8, {0},&reftables[60], &reftables[61]),
  4643. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[12], NULL, 8, 3, {0},&reftables[62], &reftables[63]),
  4644. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[8], NULL, 8, 3, {0},&reftables[64], &reftables[65]),
  4645. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 33, &msgs[14], NULL, 6, 1, {0},&reftables[66], &reftables[67]),
  4646. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 23, &msgs[11], NULL, 21, 10, {0},&reftables[68], &reftables[69]),
  4647. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[4], NULL, 7, 2, {0},&reftables[70], &reftables[71]),
  4648. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 33, &msgs[17], NULL, 6, 1, {0},&reftables[72], &reftables[73]),
  4649. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 1, &msgs[6], NULL, 6, 1, {0},&reftables[74], &reftables[75]),
  4650. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_DOUBLE, 0, false, false, false, false, "double_value", 6, &msgs[20], NULL, 11, 4, {0},&reftables[76], &reftables[77]),
  4651. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "end", 2, &msgs[2], NULL, 3, 1, {0},&reftables[78], &reftables[79]),
  4652. 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[80], &reftables[81]),
  4653. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "enum_type", 4, &msgs[0], (const upb_def*)(&msgs[3]), 18, 2, {0},&reftables[82], &reftables[83]),
  4654. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "enum_type", 5, &msgs[9], (const upb_def*)(&msgs[3]), 13, 1, {0},&reftables[84], &reftables[85]),
  4655. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "extendee", 2, &msgs[7], NULL, 7, 2, {0},&reftables[86], &reftables[87]),
  4656. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension", 6, &msgs[0], (const upb_def*)(&msgs[7]), 24, 4, {0},&reftables[88], &reftables[89]),
  4657. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension", 7, &msgs[9], (const upb_def*)(&msgs[7]), 19, 3, {0},&reftables[90], &reftables[91]),
  4658. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension_range", 5, &msgs[0], (const upb_def*)(&msgs[1]), 21, 3, {0},&reftables[92], &reftables[93]),
  4659. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "field", 2, &msgs[0], (const upb_def*)(&msgs[7]), 12, 0, {0},&reftables[94], &reftables[95]),
  4660. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "file", 1, &msgs[10], (const upb_def*)(&msgs[9]), 5, 0, {0},&reftables[96], &reftables[97]),
  4661. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "go_package", 11, &msgs[11], NULL, 14, 5, {0},&reftables[98], &reftables[99]),
  4662. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "identifier_value", 3, &msgs[20], NULL, 6, 1, {0},&reftables[100], &reftables[101]),
  4663. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "input_type", 2, &msgs[13], NULL, 7, 2, {0},&reftables[102], &reftables[103]),
  4664. UPB_FIELDDEF_INIT(UPB_LABEL_REQUIRED, UPB_TYPE_BOOL, 0, false, false, false, false, "is_extension", 2, &msgs[21], NULL, 5, 1, {0},&reftables[104], &reftables[105]),
  4665. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_generate_equals_and_hash", 20, &msgs[11], NULL, 20, 9, {0},&reftables[106], &reftables[107]),
  4666. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_generic_services", 17, &msgs[11], NULL, 18, 7, {0},&reftables[108], &reftables[109]),
  4667. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_multiple_files", 10, &msgs[11], NULL, 13, 4, {0},&reftables[110], &reftables[111]),
  4668. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "java_outer_classname", 8, &msgs[11], NULL, 9, 2, {0},&reftables[112], &reftables[113]),
  4669. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "java_package", 1, &msgs[11], NULL, 6, 1, {0},&reftables[114], &reftables[115]),
  4670. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_string_check_utf8", 27, &msgs[11], NULL, 22, 11, {0},&reftables[116], &reftables[117]),
  4671. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "javanano_use_deprecated_package", 38, &msgs[11], NULL, 30, 15, {0},&reftables[118], &reftables[119]),
  4672. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "json_name", 10, &msgs[7], NULL, 20, 9, {0},&reftables[120], &reftables[121]),
  4673. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "jstype", 6, &msgs[8], (const upb_def*)(&enums[3]), 10, 5, {0},&reftables[122], &reftables[123]),
  4674. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "label", 4, &msgs[7], (const upb_def*)(&enums[0]), 11, 4, {0},&reftables[124], &reftables[125]),
  4675. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "lazy", 5, &msgs[8], NULL, 9, 4, {0},&reftables[126], &reftables[127]),
  4676. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "leading_comments", 3, &msgs[19], NULL, 8, 2, {0},&reftables[128], &reftables[129]),
  4677. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_STRING, 0, false, false, false, false, "leading_detached_comments", 6, &msgs[19], NULL, 16, 4, {0},&reftables[130], &reftables[131]),
  4678. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "location", 1, &msgs[18], (const upb_def*)(&msgs[19]), 5, 0, {0},&reftables[132], &reftables[133]),
  4679. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "map_entry", 7, &msgs[12], NULL, 9, 4, {0},&reftables[134], &reftables[135]),
  4680. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "message_set_wire_format", 1, &msgs[12], NULL, 6, 1, {0},&reftables[136], &reftables[137]),
  4681. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "message_type", 4, &msgs[9], (const upb_def*)(&msgs[0]), 10, 0, {0},&reftables[138], &reftables[139]),
  4682. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "method", 2, &msgs[16], (const upb_def*)(&msgs[13]), 6, 0, {0},&reftables[140], &reftables[141]),
  4683. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[3], NULL, 8, 2, {0},&reftables[142], &reftables[143]),
  4684. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[15], NULL, 2, 0, {0},&reftables[144], &reftables[145]),
  4685. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "name", 2, &msgs[20], (const upb_def*)(&msgs[21]), 5, 0, {0},&reftables[146], &reftables[147]),
  4686. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[0], NULL, 32, 8, {0},&reftables[148], &reftables[149]),
  4687. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[5], NULL, 4, 1, {0},&reftables[150], &reftables[151]),
  4688. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[9], NULL, 22, 6, {0},&reftables[152], &reftables[153]),
  4689. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[7], NULL, 4, 1, {0},&reftables[154], &reftables[155]),
  4690. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[13], NULL, 4, 1, {0},&reftables[156], &reftables[157]),
  4691. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[16], NULL, 8, 2, {0},&reftables[158], &reftables[159]),
  4692. UPB_FIELDDEF_INIT(UPB_LABEL_REQUIRED, UPB_TYPE_STRING, 0, false, false, false, false, "name_part", 1, &msgs[21], NULL, 2, 0, {0},&reftables[160], &reftables[161]),
  4693. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT64, UPB_INTFMT_VARIABLE, false, false, false, false, "negative_int_value", 5, &msgs[20], NULL, 10, 3, {0},&reftables[162], &reftables[163]),
  4694. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "nested_type", 3, &msgs[0], (const upb_def*)(&msgs[0]), 15, 1, {0},&reftables[164], &reftables[165]),
  4695. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "no_standard_descriptor_accessor", 2, &msgs[12], NULL, 7, 2, {0},&reftables[166], &reftables[167]),
  4696. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "number", 2, &msgs[5], NULL, 7, 2, {0},&reftables[168], &reftables[169]),
  4697. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "number", 3, &msgs[7], NULL, 10, 3, {0},&reftables[170], &reftables[171]),
  4698. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "objc_class_prefix", 36, &msgs[11], NULL, 24, 13, {0},&reftables[172], &reftables[173]),
  4699. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "oneof_decl", 8, &msgs[0], (const upb_def*)(&msgs[15]), 28, 6, {0},&reftables[174], &reftables[175]),
  4700. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "oneof_index", 9, &msgs[7], NULL, 19, 8, {0},&reftables[176], &reftables[177]),
  4701. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "optimize_for", 9, &msgs[11], (const upb_def*)(&enums[4]), 12, 3, {0},&reftables[178], &reftables[179]),
  4702. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 7, &msgs[0], (const upb_def*)(&msgs[12]), 25, 5, {0},&reftables[180], &reftables[181]),
  4703. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 8, &msgs[9], (const upb_def*)(&msgs[11]), 20, 4, {0},&reftables[182], &reftables[183]),
  4704. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 4, &msgs[13], (const upb_def*)(&msgs[14]), 3, 0, {0},&reftables[184], &reftables[185]),
  4705. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 8, &msgs[7], (const upb_def*)(&msgs[8]), 3, 0, {0},&reftables[186], &reftables[187]),
  4706. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[16], (const upb_def*)(&msgs[17]), 7, 1, {0},&reftables[188], &reftables[189]),
  4707. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[5], (const upb_def*)(&msgs[6]), 3, 0, {0},&reftables[190], &reftables[191]),
  4708. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[3], (const upb_def*)(&msgs[4]), 7, 1, {0},&reftables[192], &reftables[193]),
  4709. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "output_type", 3, &msgs[13], NULL, 10, 3, {0},&reftables[194], &reftables[195]),
  4710. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "package", 2, &msgs[9], NULL, 25, 7, {0},&reftables[196], &reftables[197]),
  4711. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "packed", 2, &msgs[8], NULL, 7, 2, {0},&reftables[198], &reftables[199]),
  4712. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, true, "path", 1, &msgs[19], NULL, 4, 0, {0},&reftables[200], &reftables[201]),
  4713. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_UINT64, UPB_INTFMT_VARIABLE, false, false, false, false, "positive_int_value", 4, &msgs[20], NULL, 9, 2, {0},&reftables[202], &reftables[203]),
  4714. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "public_dependency", 10, &msgs[9], NULL, 35, 9, {0},&reftables[204], &reftables[205]),
  4715. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "py_generic_services", 18, &msgs[11], NULL, 19, 8, {0},&reftables[206], &reftables[207]),
  4716. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_STRING, 0, false, false, false, false, "reserved_name", 10, &msgs[0], NULL, 37, 9, {0},&reftables[208], &reftables[209]),
  4717. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "reserved_range", 9, &msgs[0], (const upb_def*)(&msgs[2]), 31, 7, {0},&reftables[210], &reftables[211]),
  4718. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "server_streaming", 6, &msgs[13], NULL, 14, 5, {0},&reftables[212], &reftables[213]),
  4719. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "service", 6, &msgs[9], (const upb_def*)(&msgs[16]), 16, 2, {0},&reftables[214], &reftables[215]),
  4720. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "source_code_info", 9, &msgs[9], (const upb_def*)(&msgs[18]), 21, 5, {0},&reftables[216], &reftables[217]),
  4721. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, true, "span", 2, &msgs[19], NULL, 7, 1, {0},&reftables[218], &reftables[219]),
  4722. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "start", 1, &msgs[2], NULL, 2, 0, {0},&reftables[220], &reftables[221]),
  4723. 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[222], &reftables[223]),
  4724. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BYTES, 0, false, false, false, false, "string_value", 7, &msgs[20], NULL, 12, 5, {0},&reftables[224], &reftables[225]),
  4725. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "syntax", 12, &msgs[9], NULL, 39, 11, {0},&reftables[226], &reftables[227]),
  4726. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "trailing_comments", 4, &msgs[19], NULL, 11, 3, {0},&reftables[228], &reftables[229]),
  4727. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "type", 5, &msgs[7], (const upb_def*)(&enums[1]), 12, 5, {0},&reftables[230], &reftables[231]),
  4728. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "type_name", 6, &msgs[7], NULL, 13, 6, {0},&reftables[232], &reftables[233]),
  4729. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[11], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[234], &reftables[235]),
  4730. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[12], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[236], &reftables[237]),
  4731. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[6], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[238], &reftables[239]),
  4732. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[4], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[240], &reftables[241]),
  4733. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[8], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[242], &reftables[243]),
  4734. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[14], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[244], &reftables[245]),
  4735. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[17], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[246], &reftables[247]),
  4736. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "value", 2, &msgs[3], (const upb_def*)(&msgs[5]), 6, 0, {0},&reftables[248], &reftables[249]),
  4737. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "weak", 10, &msgs[8], NULL, 11, 6, {0},&reftables[250], &reftables[251]),
  4738. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "weak_dependency", 11, &msgs[9], NULL, 38, 10, {0},&reftables[252], &reftables[253]),
  4739. };
  4740. static const upb_enumdef enums[5] = {
  4741. UPB_ENUMDEF_INIT("google.protobuf.FieldDescriptorProto.Label", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[188]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[151], 4, 3), 0, &reftables[254], &reftables[255]),
  4742. UPB_ENUMDEF_INIT("google.protobuf.FieldDescriptorProto.Type", UPB_STRTABLE_INIT(18, 31, UPB_CTYPE_INT32, 5, &strentries[192]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[155], 19, 18), 0, &reftables[256], &reftables[257]),
  4743. UPB_ENUMDEF_INIT("google.protobuf.FieldOptions.CType", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[224]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[174], 3, 3), 0, &reftables[258], &reftables[259]),
  4744. UPB_ENUMDEF_INIT("google.protobuf.FieldOptions.JSType", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[228]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[177], 3, 3), 0, &reftables[260], &reftables[261]),
  4745. UPB_ENUMDEF_INIT("google.protobuf.FileOptions.OptimizeMode", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[232]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[180], 4, 3), 0, &reftables[262], &reftables[263]),
  4746. };
  4747. static const upb_tabent strentries[236] = {
  4748. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "extension"), UPB_TABVALUE_PTR_INIT(&fields[22]), NULL},
  4749. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4750. {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "reserved_name"), UPB_TABVALUE_PTR_INIT(&fields[82]), NULL},
  4751. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[52]), NULL},
  4752. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4753. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4754. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4755. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "field"), UPB_TABVALUE_PTR_INIT(&fields[25]), &strentries[12]},
  4756. {UPB_TABKEY_STR("\017", "\000", "\000", "\000", "extension_range"), UPB_TABVALUE_PTR_INIT(&fields[24]), &strentries[14]},
  4757. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4758. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "nested_type"), UPB_TABVALUE_PTR_INIT(&fields[60]), NULL},
  4759. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4760. {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "reserved_range"), UPB_TABVALUE_PTR_INIT(&fields[83]), NULL},
  4761. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[68]), NULL},
  4762. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "oneof_decl"), UPB_TABVALUE_PTR_INIT(&fields[65]), NULL},
  4763. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "enum_type"), UPB_TABVALUE_PTR_INIT(&fields[19]), &strentries[13]},
  4764. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "start"), UPB_TABVALUE_PTR_INIT(&fields[89]), NULL},
  4765. {UPB_TABKEY_STR("\003", "\000", "\000", "\000", "end"), UPB_TABVALUE_PTR_INIT(&fields[18]), NULL},
  4766. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4767. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4768. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "start"), UPB_TABVALUE_PTR_INIT(&fields[88]), NULL},
  4769. {UPB_TABKEY_STR("\003", "\000", "\000", "\000", "end"), UPB_TABVALUE_PTR_INIT(&fields[17]), NULL},
  4770. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4771. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4772. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4773. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "value"), UPB_TABVALUE_PTR_INIT(&fields[102]), NULL},
  4774. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[74]), NULL},
  4775. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[49]), &strentries[26]},
  4776. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[98]), NULL},
  4777. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[13]), NULL},
  4778. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "allow_alias"), UPB_TABVALUE_PTR_INIT(&fields[1]), NULL},
  4779. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4780. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "number"), UPB_TABVALUE_PTR_INIT(&fields[62]), NULL},
  4781. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4782. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[73]), NULL},
  4783. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[53]), &strentries[34]},
  4784. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[97]), NULL},
  4785. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[15]), NULL},
  4786. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4787. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4788. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "oneof_index"), UPB_TABVALUE_PTR_INIT(&fields[66]), NULL},
  4789. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "label"), UPB_TABVALUE_PTR_INIT(&fields[40]), NULL},
  4790. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4791. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[55]), NULL},
  4792. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4793. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4794. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4795. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4796. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "number"), UPB_TABVALUE_PTR_INIT(&fields[63]), &strentries[53]},
  4797. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4798. {UPB_TABKEY_STR("\010", "\000", "\000", "\000", "extendee"), UPB_TABVALUE_PTR_INIT(&fields[21]), NULL},
  4799. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "type_name"), UPB_TABVALUE_PTR_INIT(&fields[94]), NULL},
  4800. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "json_name"), UPB_TABVALUE_PTR_INIT(&fields[38]), NULL},
  4801. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "type"), UPB_TABVALUE_PTR_INIT(&fields[93]), &strentries[50]},
  4802. {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "default_value"), UPB_TABVALUE_PTR_INIT(&fields[7]), NULL},
  4803. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[71]), NULL},
  4804. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[99]), NULL},
  4805. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4806. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "weak"), UPB_TABVALUE_PTR_INIT(&fields[103]), NULL},
  4807. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4808. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4809. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4810. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4811. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "packed"), UPB_TABVALUE_PTR_INIT(&fields[77]), NULL},
  4812. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "lazy"), UPB_TABVALUE_PTR_INIT(&fields[41]), NULL},
  4813. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4814. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "ctype"), UPB_TABVALUE_PTR_INIT(&fields[6]), NULL},
  4815. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4816. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "jstype"), UPB_TABVALUE_PTR_INIT(&fields[39]), NULL},
  4817. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[10]), NULL},
  4818. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4819. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4820. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "extension"), UPB_TABVALUE_PTR_INIT(&fields[23]), NULL},
  4821. {UPB_TABKEY_STR("\017", "\000", "\000", "\000", "weak_dependency"), UPB_TABVALUE_PTR_INIT(&fields[104]), NULL},
  4822. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4823. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[54]), NULL},
  4824. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "service"), UPB_TABVALUE_PTR_INIT(&fields[85]), NULL},
  4825. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4826. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "source_code_info"), UPB_TABVALUE_PTR_INIT(&fields[86]), NULL},
  4827. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4828. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4829. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "syntax"), UPB_TABVALUE_PTR_INIT(&fields[91]), NULL},
  4830. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "dependency"), UPB_TABVALUE_PTR_INIT(&fields[8]), NULL},
  4831. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "message_type"), UPB_TABVALUE_PTR_INIT(&fields[47]), NULL},
  4832. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "package"), UPB_TABVALUE_PTR_INIT(&fields[76]), NULL},
  4833. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[69]), &strentries[86]},
  4834. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "enum_type"), UPB_TABVALUE_PTR_INIT(&fields[20]), NULL},
  4835. {UPB_TABKEY_STR("\021", "\000", "\000", "\000", "public_dependency"), UPB_TABVALUE_PTR_INIT(&fields[80]), &strentries[85]},
  4836. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4837. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "file"), UPB_TABVALUE_PTR_INIT(&fields[26]), NULL},
  4838. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4839. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4840. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4841. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4842. {UPB_TABKEY_STR("\023", "\000", "\000", "\000", "cc_generic_services"), UPB_TABVALUE_PTR_INIT(&fields[3]), NULL},
  4843. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "csharp_namespace"), UPB_TABVALUE_PTR_INIT(&fields[5]), NULL},
  4844. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4845. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4846. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4847. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4848. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4849. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4850. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4851. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "go_package"), UPB_TABVALUE_PTR_INIT(&fields[27]), NULL},
  4852. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "java_package"), UPB_TABVALUE_PTR_INIT(&fields[35]), &strentries[120]},
  4853. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4854. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4855. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "java_outer_classname"), UPB_TABVALUE_PTR_INIT(&fields[34]), NULL},
  4856. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[95]), NULL},
  4857. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4858. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4859. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4860. {UPB_TABKEY_STR("\023", "\000", "\000", "\000", "java_multiple_files"), UPB_TABVALUE_PTR_INIT(&fields[33]), &strentries[117]},
  4861. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4862. {UPB_TABKEY_STR("\025", "\000", "\000", "\000", "java_generic_services"), UPB_TABVALUE_PTR_INIT(&fields[32]), &strentries[118]},
  4863. {UPB_TABKEY_STR("\035", "\000", "\000", "\000", "java_generate_equals_and_hash"), UPB_TABVALUE_PTR_INIT(&fields[31]), NULL},
  4864. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4865. {UPB_TABKEY_STR("\037", "\000", "\000", "\000", "javanano_use_deprecated_package"), UPB_TABVALUE_PTR_INIT(&fields[37]), &strentries[123]},
  4866. {UPB_TABKEY_STR("\023", "\000", "\000", "\000", "py_generic_services"), UPB_TABVALUE_PTR_INIT(&fields[81]), NULL},
  4867. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "optimize_for"), UPB_TABVALUE_PTR_INIT(&fields[67]), NULL},
  4868. {UPB_TABKEY_STR("\026", "\000", "\000", "\000", "java_string_check_utf8"), UPB_TABVALUE_PTR_INIT(&fields[36]), NULL},
  4869. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[12]), &strentries[119]},
  4870. {UPB_TABKEY_STR("\021", "\000", "\000", "\000", "objc_class_prefix"), UPB_TABVALUE_PTR_INIT(&fields[64]), NULL},
  4871. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "cc_enable_arenas"), UPB_TABVALUE_PTR_INIT(&fields[2]), NULL},
  4872. {UPB_TABKEY_STR("\027", "\000", "\000", "\000", "message_set_wire_format"), UPB_TABVALUE_PTR_INIT(&fields[46]), &strentries[128]},
  4873. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4874. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4875. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4876. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[96]), NULL},
  4877. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[9]), NULL},
  4878. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "map_entry"), UPB_TABVALUE_PTR_INIT(&fields[45]), NULL},
  4879. {UPB_TABKEY_STR("\037", "\000", "\000", "\000", "no_standard_descriptor_accessor"), UPB_TABVALUE_PTR_INIT(&fields[61]), NULL},
  4880. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4881. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "client_streaming"), UPB_TABVALUE_PTR_INIT(&fields[4]), NULL},
  4882. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "server_streaming"), UPB_TABVALUE_PTR_INIT(&fields[84]), NULL},
  4883. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[56]), NULL},
  4884. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "input_type"), UPB_TABVALUE_PTR_INIT(&fields[29]), NULL},
  4885. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4886. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "output_type"), UPB_TABVALUE_PTR_INIT(&fields[75]), NULL},
  4887. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[70]), NULL},
  4888. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[100]), NULL},
  4889. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[11]), NULL},
  4890. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4891. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4892. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4893. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4894. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4895. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[50]), NULL},
  4896. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4897. {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[72]), &strentries[150]},
  4898. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "method"), UPB_TABVALUE_PTR_INIT(&fields[48]), NULL},
  4899. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[57]), &strentries[149]},
  4900. {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[101]), NULL},
  4901. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[14]), NULL},
  4902. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4903. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4904. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4905. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4906. {UPB_TABKEY_STR("\010", "\000", "\000", "\000", "location"), UPB_TABVALUE_PTR_INIT(&fields[44]), NULL},
  4907. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4908. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4909. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4910. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4911. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "span"), UPB_TABVALUE_PTR_INIT(&fields[87]), &strentries[167]},
  4912. {UPB_TABKEY_STR("\031", "\000", "\000", "\000", "leading_detached_comments"), UPB_TABVALUE_PTR_INIT(&fields[43]), &strentries[165]},
  4913. {UPB_TABKEY_STR("\021", "\000", "\000", "\000", "trailing_comments"), UPB_TABVALUE_PTR_INIT(&fields[92]), NULL},
  4914. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "leading_comments"), UPB_TABVALUE_PTR_INIT(&fields[42]), &strentries[164]},
  4915. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "path"), UPB_TABVALUE_PTR_INIT(&fields[78]), NULL},
  4916. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "double_value"), UPB_TABVALUE_PTR_INIT(&fields[16]), NULL},
  4917. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4918. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4919. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[51]), NULL},
  4920. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4921. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4922. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4923. {UPB_TABKEY_STR("\022", "\000", "\000", "\000", "negative_int_value"), UPB_TABVALUE_PTR_INIT(&fields[59]), NULL},
  4924. {UPB_TABKEY_STR("\017", "\000", "\000", "\000", "aggregate_value"), UPB_TABVALUE_PTR_INIT(&fields[0]), NULL},
  4925. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4926. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4927. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4928. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4929. {UPB_TABKEY_STR("\022", "\000", "\000", "\000", "positive_int_value"), UPB_TABVALUE_PTR_INIT(&fields[79]), NULL},
  4930. {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "identifier_value"), UPB_TABVALUE_PTR_INIT(&fields[28]), NULL},
  4931. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "string_value"), UPB_TABVALUE_PTR_INIT(&fields[90]), &strentries[182]},
  4932. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4933. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4934. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "is_extension"), UPB_TABVALUE_PTR_INIT(&fields[30]), NULL},
  4935. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "name_part"), UPB_TABVALUE_PTR_INIT(&fields[58]), NULL},
  4936. {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "LABEL_REQUIRED"), UPB_TABVALUE_INT_INIT(2), &strentries[190]},
  4937. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4938. {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "LABEL_REPEATED"), UPB_TABVALUE_INT_INIT(3), NULL},
  4939. {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "LABEL_OPTIONAL"), UPB_TABVALUE_INT_INIT(1), NULL},
  4940. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "TYPE_FIXED64"), UPB_TABVALUE_INT_INIT(6), NULL},
  4941. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4942. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4943. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4944. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4945. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_STRING"), UPB_TABVALUE_INT_INIT(9), NULL},
  4946. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_FLOAT"), UPB_TABVALUE_INT_INIT(2), &strentries[221]},
  4947. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_DOUBLE"), UPB_TABVALUE_INT_INIT(1), NULL},
  4948. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4949. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_INT32"), UPB_TABVALUE_INT_INIT(5), NULL},
  4950. {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "TYPE_SFIXED32"), UPB_TABVALUE_INT_INIT(15), NULL},
  4951. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "TYPE_FIXED32"), UPB_TABVALUE_INT_INIT(7), NULL},
  4952. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4953. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "TYPE_MESSAGE"), UPB_TABVALUE_INT_INIT(11), &strentries[222]},
  4954. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4955. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4956. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_INT64"), UPB_TABVALUE_INT_INIT(3), &strentries[219]},
  4957. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4958. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4959. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4960. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4961. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "TYPE_ENUM"), UPB_TABVALUE_INT_INIT(14), NULL},
  4962. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_UINT32"), UPB_TABVALUE_INT_INIT(13), NULL},
  4963. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4964. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_UINT64"), UPB_TABVALUE_INT_INIT(4), &strentries[218]},
  4965. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4966. {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "TYPE_SFIXED64"), UPB_TABVALUE_INT_INIT(16), NULL},
  4967. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_BYTES"), UPB_TABVALUE_INT_INIT(12), NULL},
  4968. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_SINT64"), UPB_TABVALUE_INT_INIT(18), NULL},
  4969. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "TYPE_BOOL"), UPB_TABVALUE_INT_INIT(8), NULL},
  4970. {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_GROUP"), UPB_TABVALUE_INT_INIT(10), NULL},
  4971. {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_SINT32"), UPB_TABVALUE_INT_INIT(17), NULL},
  4972. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4973. {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "CORD"), UPB_TABVALUE_INT_INIT(1), NULL},
  4974. {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "STRING"), UPB_TABVALUE_INT_INIT(0), &strentries[225]},
  4975. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "STRING_PIECE"), UPB_TABVALUE_INT_INIT(2), NULL},
  4976. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4977. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "JS_NORMAL"), UPB_TABVALUE_INT_INIT(0), NULL},
  4978. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "JS_NUMBER"), UPB_TABVALUE_INT_INIT(2), NULL},
  4979. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "JS_STRING"), UPB_TABVALUE_INT_INIT(1), NULL},
  4980. {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "CODE_SIZE"), UPB_TABVALUE_INT_INIT(2), NULL},
  4981. {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "SPEED"), UPB_TABVALUE_INT_INIT(1), &strentries[235]},
  4982. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4983. {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "LITE_RUNTIME"), UPB_TABVALUE_INT_INIT(3), NULL},
  4984. };
  4985. static const upb_tabent intentries[18] = {
  4986. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4987. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[98]), NULL},
  4988. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4989. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[97]), NULL},
  4990. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4991. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[99]), NULL},
  4992. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4993. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[95]), NULL},
  4994. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4995. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[96]), NULL},
  4996. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4997. {UPB_TABKEY_NUM(33), UPB_TABVALUE_PTR_INIT(&fields[11]), NULL},
  4998. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  4999. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[100]), NULL},
  5000. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5001. {UPB_TABKEY_NUM(33), UPB_TABVALUE_PTR_INIT(&fields[14]), NULL},
  5002. {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
  5003. {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[101]), NULL},
  5004. };
  5005. static const upb_tabval arrays[184] = {
  5006. UPB_TABVALUE_EMPTY_INIT,
  5007. UPB_TABVALUE_PTR_INIT(&fields[52]),
  5008. UPB_TABVALUE_PTR_INIT(&fields[25]),
  5009. UPB_TABVALUE_PTR_INIT(&fields[60]),
  5010. UPB_TABVALUE_PTR_INIT(&fields[19]),
  5011. UPB_TABVALUE_PTR_INIT(&fields[24]),
  5012. UPB_TABVALUE_PTR_INIT(&fields[22]),
  5013. UPB_TABVALUE_PTR_INIT(&fields[68]),
  5014. UPB_TABVALUE_PTR_INIT(&fields[65]),
  5015. UPB_TABVALUE_PTR_INIT(&fields[83]),
  5016. UPB_TABVALUE_PTR_INIT(&fields[82]),
  5017. UPB_TABVALUE_EMPTY_INIT,
  5018. UPB_TABVALUE_PTR_INIT(&fields[89]),
  5019. UPB_TABVALUE_PTR_INIT(&fields[18]),
  5020. UPB_TABVALUE_EMPTY_INIT,
  5021. UPB_TABVALUE_PTR_INIT(&fields[88]),
  5022. UPB_TABVALUE_PTR_INIT(&fields[17]),
  5023. UPB_TABVALUE_EMPTY_INIT,
  5024. UPB_TABVALUE_PTR_INIT(&fields[49]),
  5025. UPB_TABVALUE_PTR_INIT(&fields[102]),
  5026. UPB_TABVALUE_PTR_INIT(&fields[74]),
  5027. UPB_TABVALUE_EMPTY_INIT,
  5028. UPB_TABVALUE_EMPTY_INIT,
  5029. UPB_TABVALUE_PTR_INIT(&fields[1]),
  5030. UPB_TABVALUE_PTR_INIT(&fields[13]),
  5031. UPB_TABVALUE_EMPTY_INIT,
  5032. UPB_TABVALUE_PTR_INIT(&fields[53]),
  5033. UPB_TABVALUE_PTR_INIT(&fields[62]),
  5034. UPB_TABVALUE_PTR_INIT(&fields[73]),
  5035. UPB_TABVALUE_EMPTY_INIT,
  5036. UPB_TABVALUE_PTR_INIT(&fields[15]),
  5037. UPB_TABVALUE_EMPTY_INIT,
  5038. UPB_TABVALUE_PTR_INIT(&fields[55]),
  5039. UPB_TABVALUE_PTR_INIT(&fields[21]),
  5040. UPB_TABVALUE_PTR_INIT(&fields[63]),
  5041. UPB_TABVALUE_PTR_INIT(&fields[40]),
  5042. UPB_TABVALUE_PTR_INIT(&fields[93]),
  5043. UPB_TABVALUE_PTR_INIT(&fields[94]),
  5044. UPB_TABVALUE_PTR_INIT(&fields[7]),
  5045. UPB_TABVALUE_PTR_INIT(&fields[71]),
  5046. UPB_TABVALUE_PTR_INIT(&fields[66]),
  5047. UPB_TABVALUE_PTR_INIT(&fields[38]),
  5048. UPB_TABVALUE_EMPTY_INIT,
  5049. UPB_TABVALUE_PTR_INIT(&fields[6]),
  5050. UPB_TABVALUE_PTR_INIT(&fields[77]),
  5051. UPB_TABVALUE_PTR_INIT(&fields[10]),
  5052. UPB_TABVALUE_EMPTY_INIT,
  5053. UPB_TABVALUE_PTR_INIT(&fields[41]),
  5054. UPB_TABVALUE_PTR_INIT(&fields[39]),
  5055. UPB_TABVALUE_EMPTY_INIT,
  5056. UPB_TABVALUE_EMPTY_INIT,
  5057. UPB_TABVALUE_EMPTY_INIT,
  5058. UPB_TABVALUE_PTR_INIT(&fields[103]),
  5059. UPB_TABVALUE_EMPTY_INIT,
  5060. UPB_TABVALUE_PTR_INIT(&fields[54]),
  5061. UPB_TABVALUE_PTR_INIT(&fields[76]),
  5062. UPB_TABVALUE_PTR_INIT(&fields[8]),
  5063. UPB_TABVALUE_PTR_INIT(&fields[47]),
  5064. UPB_TABVALUE_PTR_INIT(&fields[20]),
  5065. UPB_TABVALUE_PTR_INIT(&fields[85]),
  5066. UPB_TABVALUE_PTR_INIT(&fields[23]),
  5067. UPB_TABVALUE_PTR_INIT(&fields[69]),
  5068. UPB_TABVALUE_PTR_INIT(&fields[86]),
  5069. UPB_TABVALUE_PTR_INIT(&fields[80]),
  5070. UPB_TABVALUE_PTR_INIT(&fields[104]),
  5071. UPB_TABVALUE_PTR_INIT(&fields[91]),
  5072. UPB_TABVALUE_EMPTY_INIT,
  5073. UPB_TABVALUE_PTR_INIT(&fields[26]),
  5074. UPB_TABVALUE_EMPTY_INIT,
  5075. UPB_TABVALUE_PTR_INIT(&fields[35]),
  5076. UPB_TABVALUE_EMPTY_INIT,
  5077. UPB_TABVALUE_EMPTY_INIT,
  5078. UPB_TABVALUE_EMPTY_INIT,
  5079. UPB_TABVALUE_EMPTY_INIT,
  5080. UPB_TABVALUE_EMPTY_INIT,
  5081. UPB_TABVALUE_EMPTY_INIT,
  5082. UPB_TABVALUE_PTR_INIT(&fields[34]),
  5083. UPB_TABVALUE_PTR_INIT(&fields[67]),
  5084. UPB_TABVALUE_PTR_INIT(&fields[33]),
  5085. UPB_TABVALUE_PTR_INIT(&fields[27]),
  5086. UPB_TABVALUE_EMPTY_INIT,
  5087. UPB_TABVALUE_EMPTY_INIT,
  5088. UPB_TABVALUE_EMPTY_INIT,
  5089. UPB_TABVALUE_EMPTY_INIT,
  5090. UPB_TABVALUE_PTR_INIT(&fields[3]),
  5091. UPB_TABVALUE_PTR_INIT(&fields[32]),
  5092. UPB_TABVALUE_PTR_INIT(&fields[81]),
  5093. UPB_TABVALUE_EMPTY_INIT,
  5094. UPB_TABVALUE_PTR_INIT(&fields[31]),
  5095. UPB_TABVALUE_EMPTY_INIT,
  5096. UPB_TABVALUE_EMPTY_INIT,
  5097. UPB_TABVALUE_PTR_INIT(&fields[12]),
  5098. UPB_TABVALUE_EMPTY_INIT,
  5099. UPB_TABVALUE_EMPTY_INIT,
  5100. UPB_TABVALUE_EMPTY_INIT,
  5101. UPB_TABVALUE_PTR_INIT(&fields[36]),
  5102. UPB_TABVALUE_EMPTY_INIT,
  5103. UPB_TABVALUE_EMPTY_INIT,
  5104. UPB_TABVALUE_EMPTY_INIT,
  5105. UPB_TABVALUE_PTR_INIT(&fields[2]),
  5106. UPB_TABVALUE_EMPTY_INIT,
  5107. UPB_TABVALUE_EMPTY_INIT,
  5108. UPB_TABVALUE_EMPTY_INIT,
  5109. UPB_TABVALUE_EMPTY_INIT,
  5110. UPB_TABVALUE_PTR_INIT(&fields[64]),
  5111. UPB_TABVALUE_PTR_INIT(&fields[5]),
  5112. UPB_TABVALUE_PTR_INIT(&fields[37]),
  5113. UPB_TABVALUE_EMPTY_INIT,
  5114. UPB_TABVALUE_PTR_INIT(&fields[46]),
  5115. UPB_TABVALUE_PTR_INIT(&fields[61]),
  5116. UPB_TABVALUE_PTR_INIT(&fields[9]),
  5117. UPB_TABVALUE_EMPTY_INIT,
  5118. UPB_TABVALUE_EMPTY_INIT,
  5119. UPB_TABVALUE_EMPTY_INIT,
  5120. UPB_TABVALUE_PTR_INIT(&fields[45]),
  5121. UPB_TABVALUE_EMPTY_INIT,
  5122. UPB_TABVALUE_PTR_INIT(&fields[56]),
  5123. UPB_TABVALUE_PTR_INIT(&fields[29]),
  5124. UPB_TABVALUE_PTR_INIT(&fields[75]),
  5125. UPB_TABVALUE_PTR_INIT(&fields[70]),
  5126. UPB_TABVALUE_PTR_INIT(&fields[4]),
  5127. UPB_TABVALUE_PTR_INIT(&fields[84]),
  5128. UPB_TABVALUE_EMPTY_INIT,
  5129. UPB_TABVALUE_EMPTY_INIT,
  5130. UPB_TABVALUE_PTR_INIT(&fields[50]),
  5131. UPB_TABVALUE_EMPTY_INIT,
  5132. UPB_TABVALUE_PTR_INIT(&fields[57]),
  5133. UPB_TABVALUE_PTR_INIT(&fields[48]),
  5134. UPB_TABVALUE_PTR_INIT(&fields[72]),
  5135. UPB_TABVALUE_EMPTY_INIT,
  5136. UPB_TABVALUE_EMPTY_INIT,
  5137. UPB_TABVALUE_PTR_INIT(&fields[44]),
  5138. UPB_TABVALUE_EMPTY_INIT,
  5139. UPB_TABVALUE_PTR_INIT(&fields[78]),
  5140. UPB_TABVALUE_PTR_INIT(&fields[87]),
  5141. UPB_TABVALUE_PTR_INIT(&fields[42]),
  5142. UPB_TABVALUE_PTR_INIT(&fields[92]),
  5143. UPB_TABVALUE_EMPTY_INIT,
  5144. UPB_TABVALUE_PTR_INIT(&fields[43]),
  5145. UPB_TABVALUE_EMPTY_INIT,
  5146. UPB_TABVALUE_EMPTY_INIT,
  5147. UPB_TABVALUE_PTR_INIT(&fields[51]),
  5148. UPB_TABVALUE_PTR_INIT(&fields[28]),
  5149. UPB_TABVALUE_PTR_INIT(&fields[79]),
  5150. UPB_TABVALUE_PTR_INIT(&fields[59]),
  5151. UPB_TABVALUE_PTR_INIT(&fields[16]),
  5152. UPB_TABVALUE_PTR_INIT(&fields[90]),
  5153. UPB_TABVALUE_PTR_INIT(&fields[0]),
  5154. UPB_TABVALUE_EMPTY_INIT,
  5155. UPB_TABVALUE_PTR_INIT(&fields[58]),
  5156. UPB_TABVALUE_PTR_INIT(&fields[30]),
  5157. UPB_TABVALUE_EMPTY_INIT,
  5158. UPB_TABVALUE_PTR_INIT("LABEL_OPTIONAL"),
  5159. UPB_TABVALUE_PTR_INIT("LABEL_REQUIRED"),
  5160. UPB_TABVALUE_PTR_INIT("LABEL_REPEATED"),
  5161. UPB_TABVALUE_EMPTY_INIT,
  5162. UPB_TABVALUE_PTR_INIT("TYPE_DOUBLE"),
  5163. UPB_TABVALUE_PTR_INIT("TYPE_FLOAT"),
  5164. UPB_TABVALUE_PTR_INIT("TYPE_INT64"),
  5165. UPB_TABVALUE_PTR_INIT("TYPE_UINT64"),
  5166. UPB_TABVALUE_PTR_INIT("TYPE_INT32"),
  5167. UPB_TABVALUE_PTR_INIT("TYPE_FIXED64"),
  5168. UPB_TABVALUE_PTR_INIT("TYPE_FIXED32"),
  5169. UPB_TABVALUE_PTR_INIT("TYPE_BOOL"),
  5170. UPB_TABVALUE_PTR_INIT("TYPE_STRING"),
  5171. UPB_TABVALUE_PTR_INIT("TYPE_GROUP"),
  5172. UPB_TABVALUE_PTR_INIT("TYPE_MESSAGE"),
  5173. UPB_TABVALUE_PTR_INIT("TYPE_BYTES"),
  5174. UPB_TABVALUE_PTR_INIT("TYPE_UINT32"),
  5175. UPB_TABVALUE_PTR_INIT("TYPE_ENUM"),
  5176. UPB_TABVALUE_PTR_INIT("TYPE_SFIXED32"),
  5177. UPB_TABVALUE_PTR_INIT("TYPE_SFIXED64"),
  5178. UPB_TABVALUE_PTR_INIT("TYPE_SINT32"),
  5179. UPB_TABVALUE_PTR_INIT("TYPE_SINT64"),
  5180. UPB_TABVALUE_PTR_INIT("STRING"),
  5181. UPB_TABVALUE_PTR_INIT("CORD"),
  5182. UPB_TABVALUE_PTR_INIT("STRING_PIECE"),
  5183. UPB_TABVALUE_PTR_INIT("JS_NORMAL"),
  5184. UPB_TABVALUE_PTR_INIT("JS_STRING"),
  5185. UPB_TABVALUE_PTR_INIT("JS_NUMBER"),
  5186. UPB_TABVALUE_EMPTY_INIT,
  5187. UPB_TABVALUE_PTR_INIT("SPEED"),
  5188. UPB_TABVALUE_PTR_INIT("CODE_SIZE"),
  5189. UPB_TABVALUE_PTR_INIT("LITE_RUNTIME"),
  5190. };
  5191. #ifdef UPB_DEBUG_REFS
  5192. static upb_inttable reftables[264] = {
  5193. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5194. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5195. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5196. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5197. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5198. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5199. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5200. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5201. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5202. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5203. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5204. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5205. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5206. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5207. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5208. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5209. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5210. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5211. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5212. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5213. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5214. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5215. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5216. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5217. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5218. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5219. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5220. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5221. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5222. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5223. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5224. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5225. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5226. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5227. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5228. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5229. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5230. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5231. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5232. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5233. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5234. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5235. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5236. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5237. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5238. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5239. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5240. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5241. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5242. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5243. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5244. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5245. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5246. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5247. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5248. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5249. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5250. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5251. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5252. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5253. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5254. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5255. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5256. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5257. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5258. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5259. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5260. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5261. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5262. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5263. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5264. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5265. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5266. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5267. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5268. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5269. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5270. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5271. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5272. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5273. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5274. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5275. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5276. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5277. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5278. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5279. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5280. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5281. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5282. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5283. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5284. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5285. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5286. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5287. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5288. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5289. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5290. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5291. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5292. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5293. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5294. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5295. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5296. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5297. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5298. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5299. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5300. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5301. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5302. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5303. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5304. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5305. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5306. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5307. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5308. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5309. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5310. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5311. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5312. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5313. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5314. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5315. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5316. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5317. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5318. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5319. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5320. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5321. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5322. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5323. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5324. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5325. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5326. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5327. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5328. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5329. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5330. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5331. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5332. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5333. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5334. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5335. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5336. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5337. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5338. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5339. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5340. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5341. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5342. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5343. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5344. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5345. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5346. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5347. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5348. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5349. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5350. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5351. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5352. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5353. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5354. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5355. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5356. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5357. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5358. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5359. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5360. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5361. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5362. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5363. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5364. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5365. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5366. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5367. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5368. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5369. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5370. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5371. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5372. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5373. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5374. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5375. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5376. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5377. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5378. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5379. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5380. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5381. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5382. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5383. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5384. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5385. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5386. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5387. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5388. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5389. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5390. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5391. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5392. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5393. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5394. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5395. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5396. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5397. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5398. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5399. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5400. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5401. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5402. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5403. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5404. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5405. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5406. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5407. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5408. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5409. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5410. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5411. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5412. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5413. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5414. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5415. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5416. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5417. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5418. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5419. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5420. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5421. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5422. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5423. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5424. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5425. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5426. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5427. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5428. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5429. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5430. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5431. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5432. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5433. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5434. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5435. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5436. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5437. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5438. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5439. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5440. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5441. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5442. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5443. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5444. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5445. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5446. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5447. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5448. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5449. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5450. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5451. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5452. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5453. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5454. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5455. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5456. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  5457. };
  5458. #endif
  5459. static const upb_msgdef *refm(const upb_msgdef *m, const void *owner) {
  5460. upb_msgdef_ref(m, owner);
  5461. return m;
  5462. }
  5463. static const upb_enumdef *refe(const upb_enumdef *e, const void *owner) {
  5464. upb_enumdef_ref(e, owner);
  5465. return e;
  5466. }
  5467. /* Public API. */
  5468. const upb_msgdef *upbdefs_google_protobuf_DescriptorProto_get(const void *owner) { return refm(&msgs[0], owner); }
  5469. const upb_msgdef *upbdefs_google_protobuf_DescriptorProto_ExtensionRange_get(const void *owner) { return refm(&msgs[1], owner); }
  5470. const upb_msgdef *upbdefs_google_protobuf_DescriptorProto_ReservedRange_get(const void *owner) { return refm(&msgs[2], owner); }
  5471. const upb_msgdef *upbdefs_google_protobuf_EnumDescriptorProto_get(const void *owner) { return refm(&msgs[3], owner); }
  5472. const upb_msgdef *upbdefs_google_protobuf_EnumOptions_get(const void *owner) { return refm(&msgs[4], owner); }
  5473. const upb_msgdef *upbdefs_google_protobuf_EnumValueDescriptorProto_get(const void *owner) { return refm(&msgs[5], owner); }
  5474. const upb_msgdef *upbdefs_google_protobuf_EnumValueOptions_get(const void *owner) { return refm(&msgs[6], owner); }
  5475. const upb_msgdef *upbdefs_google_protobuf_FieldDescriptorProto_get(const void *owner) { return refm(&msgs[7], owner); }
  5476. const upb_msgdef *upbdefs_google_protobuf_FieldOptions_get(const void *owner) { return refm(&msgs[8], owner); }
  5477. const upb_msgdef *upbdefs_google_protobuf_FileDescriptorProto_get(const void *owner) { return refm(&msgs[9], owner); }
  5478. const upb_msgdef *upbdefs_google_protobuf_FileDescriptorSet_get(const void *owner) { return refm(&msgs[10], owner); }
  5479. const upb_msgdef *upbdefs_google_protobuf_FileOptions_get(const void *owner) { return refm(&msgs[11], owner); }
  5480. const upb_msgdef *upbdefs_google_protobuf_MessageOptions_get(const void *owner) { return refm(&msgs[12], owner); }
  5481. const upb_msgdef *upbdefs_google_protobuf_MethodDescriptorProto_get(const void *owner) { return refm(&msgs[13], owner); }
  5482. const upb_msgdef *upbdefs_google_protobuf_MethodOptions_get(const void *owner) { return refm(&msgs[14], owner); }
  5483. const upb_msgdef *upbdefs_google_protobuf_OneofDescriptorProto_get(const void *owner) { return refm(&msgs[15], owner); }
  5484. const upb_msgdef *upbdefs_google_protobuf_ServiceDescriptorProto_get(const void *owner) { return refm(&msgs[16], owner); }
  5485. const upb_msgdef *upbdefs_google_protobuf_ServiceOptions_get(const void *owner) { return refm(&msgs[17], owner); }
  5486. const upb_msgdef *upbdefs_google_protobuf_SourceCodeInfo_get(const void *owner) { return refm(&msgs[18], owner); }
  5487. const upb_msgdef *upbdefs_google_protobuf_SourceCodeInfo_Location_get(const void *owner) { return refm(&msgs[19], owner); }
  5488. const upb_msgdef *upbdefs_google_protobuf_UninterpretedOption_get(const void *owner) { return refm(&msgs[20], owner); }
  5489. const upb_msgdef *upbdefs_google_protobuf_UninterpretedOption_NamePart_get(const void *owner) { return refm(&msgs[21], owner); }
  5490. const upb_enumdef *upbdefs_google_protobuf_FieldDescriptorProto_Label_get(const void *owner) { return refe(&enums[0], owner); }
  5491. const upb_enumdef *upbdefs_google_protobuf_FieldDescriptorProto_Type_get(const void *owner) { return refe(&enums[1], owner); }
  5492. const upb_enumdef *upbdefs_google_protobuf_FieldOptions_CType_get(const void *owner) { return refe(&enums[2], owner); }
  5493. const upb_enumdef *upbdefs_google_protobuf_FieldOptions_JSType_get(const void *owner) { return refe(&enums[3], owner); }
  5494. const upb_enumdef *upbdefs_google_protobuf_FileOptions_OptimizeMode_get(const void *owner) { return refe(&enums[4], owner); }
  5495. /*
  5496. ** XXX: The routines in this file that consume a string do not currently
  5497. ** support having the string span buffers. In the future, as upb_sink and
  5498. ** its buffering/sharing functionality evolve there should be an easy and
  5499. ** idiomatic way of correctly handling this case. For now, we accept this
  5500. ** limitation since we currently only parse descriptors from single strings.
  5501. */
  5502. #include <errno.h>
  5503. #include <stdlib.h>
  5504. #include <string.h>
  5505. /* Compares a NULL-terminated string with a non-NULL-terminated string. */
  5506. static bool upb_streq(const char *str, const char *buf, size_t n) {
  5507. return strlen(str) == n && memcmp(str, buf, n) == 0;
  5508. }
  5509. /* We keep a stack of all the messages scopes we are currently in, as well as
  5510. * the top-level file scope. This is necessary to correctly qualify the
  5511. * definitions that are contained inside. "name" tracks the name of the
  5512. * message or package (a bare name -- not qualified by any enclosing scopes). */
  5513. typedef struct {
  5514. char *name;
  5515. /* Index of the first def that is under this scope. For msgdefs, the
  5516. * msgdef itself is at start-1. */
  5517. int start;
  5518. } upb_descreader_frame;
  5519. /* The maximum number of nested declarations that are allowed, ie.
  5520. * message Foo {
  5521. * message Bar {
  5522. * message Baz {
  5523. * }
  5524. * }
  5525. * }
  5526. *
  5527. * This is a resource limit that affects how big our runtime stack can grow.
  5528. * TODO: make this a runtime-settable property of the Reader instance. */
  5529. #define UPB_MAX_MESSAGE_NESTING 64
  5530. struct upb_descreader {
  5531. upb_sink sink;
  5532. upb_inttable files;
  5533. upb_filedef *file; /* The last file in files. */
  5534. upb_descreader_frame stack[UPB_MAX_MESSAGE_NESTING];
  5535. int stack_len;
  5536. uint32_t number;
  5537. char *name;
  5538. bool saw_number;
  5539. bool saw_name;
  5540. char *default_string;
  5541. upb_fielddef *f;
  5542. };
  5543. static char *upb_strndup(const char *buf, size_t n) {
  5544. char *ret = upb_gmalloc(n + 1);
  5545. if (!ret) return NULL;
  5546. memcpy(ret, buf, n);
  5547. ret[n] = '\0';
  5548. return ret;
  5549. }
  5550. /* Returns a newly allocated string that joins input strings together, for
  5551. * example:
  5552. * join("Foo.Bar", "Baz") -> "Foo.Bar.Baz"
  5553. * join("", "Baz") -> "Baz"
  5554. * Caller owns a ref on the returned string. */
  5555. static char *upb_join(const char *base, const char *name) {
  5556. if (!base || strlen(base) == 0) {
  5557. return upb_gstrdup(name);
  5558. } else {
  5559. char *ret = upb_gmalloc(strlen(base) + strlen(name) + 2);
  5560. if (!ret) {
  5561. return NULL;
  5562. }
  5563. ret[0] = '\0';
  5564. strcat(ret, base);
  5565. strcat(ret, ".");
  5566. strcat(ret, name);
  5567. return ret;
  5568. }
  5569. }
  5570. /* Qualify the defname for all defs starting with offset "start" with "str". */
  5571. static bool upb_descreader_qualify(upb_filedef *f, char *str, int32_t start) {
  5572. size_t i;
  5573. for (i = start; i < upb_filedef_defcount(f); i++) {
  5574. upb_def *def = upb_filedef_mutabledef(f, i);
  5575. char *name = upb_join(str, upb_def_fullname(def));
  5576. if (!name) {
  5577. /* Need better logic here; at this point we've qualified some names but
  5578. * not others. */
  5579. return false;
  5580. }
  5581. upb_def_setfullname(def, name, NULL);
  5582. upb_gfree(name);
  5583. }
  5584. return true;
  5585. }
  5586. /* upb_descreader ************************************************************/
  5587. static upb_msgdef *upb_descreader_top(upb_descreader *r) {
  5588. int index;
  5589. assert(r->stack_len > 1);
  5590. index = r->stack[r->stack_len-1].start - 1;
  5591. assert(index >= 0);
  5592. return upb_downcast_msgdef_mutable(upb_filedef_mutabledef(r->file, index));
  5593. }
  5594. static upb_def *upb_descreader_last(upb_descreader *r) {
  5595. return upb_filedef_mutabledef(r->file, upb_filedef_defcount(r->file) - 1);
  5596. }
  5597. /* Start/end handlers for FileDescriptorProto and DescriptorProto (the two
  5598. * entities that have names and can contain sub-definitions. */
  5599. void upb_descreader_startcontainer(upb_descreader *r) {
  5600. upb_descreader_frame *f = &r->stack[r->stack_len++];
  5601. f->start = upb_filedef_defcount(r->file);
  5602. f->name = NULL;
  5603. }
  5604. bool upb_descreader_endcontainer(upb_descreader *r) {
  5605. upb_descreader_frame *f = &r->stack[--r->stack_len];
  5606. if (!upb_descreader_qualify(r->file, f->name, f->start)) {
  5607. return false;
  5608. }
  5609. upb_gfree(f->name);
  5610. f->name = NULL;
  5611. return true;
  5612. }
  5613. void upb_descreader_setscopename(upb_descreader *r, char *str) {
  5614. upb_descreader_frame *f = &r->stack[r->stack_len-1];
  5615. upb_gfree(f->name);
  5616. f->name = str;
  5617. }
  5618. /** Handlers for google.protobuf.FileDescriptorSet. ***************************/
  5619. static void *fileset_startfile(void *closure, const void *hd) {
  5620. upb_descreader *r = closure;
  5621. UPB_UNUSED(hd);
  5622. r->file = upb_filedef_new(&r->files);
  5623. upb_inttable_push(&r->files, upb_value_ptr(r->file));
  5624. return r;
  5625. }
  5626. /** Handlers for google.protobuf.FileDescriptorProto. *************************/
  5627. static bool file_start(void *closure, const void *hd) {
  5628. upb_descreader *r = closure;
  5629. UPB_UNUSED(hd);
  5630. upb_descreader_startcontainer(r);
  5631. return true;
  5632. }
  5633. static bool file_end(void *closure, const void *hd, upb_status *status) {
  5634. upb_descreader *r = closure;
  5635. UPB_UNUSED(hd);
  5636. UPB_UNUSED(status);
  5637. return upb_descreader_endcontainer(r);
  5638. }
  5639. static size_t file_onname(void *closure, const void *hd, const char *buf,
  5640. size_t n, const upb_bufhandle *handle) {
  5641. upb_descreader *r = closure;
  5642. char *name;
  5643. bool ok;
  5644. UPB_UNUSED(hd);
  5645. UPB_UNUSED(handle);
  5646. name = upb_strndup(buf, n);
  5647. /* XXX: see comment at the top of the file. */
  5648. ok = upb_filedef_setname(r->file, name, NULL);
  5649. upb_gfree(name);
  5650. UPB_ASSERT_VAR(ok, ok);
  5651. return n;
  5652. }
  5653. static size_t file_onpackage(void *closure, const void *hd, const char *buf,
  5654. size_t n, const upb_bufhandle *handle) {
  5655. upb_descreader *r = closure;
  5656. char *package;
  5657. bool ok;
  5658. UPB_UNUSED(hd);
  5659. UPB_UNUSED(handle);
  5660. package = upb_strndup(buf, n);
  5661. /* XXX: see comment at the top of the file. */
  5662. upb_descreader_setscopename(r, package);
  5663. ok = upb_filedef_setpackage(r->file, package, NULL);
  5664. UPB_ASSERT_VAR(ok, ok);
  5665. return n;
  5666. }
  5667. static size_t file_onsyntax(void *closure, const void *hd, const char *buf,
  5668. size_t n, const upb_bufhandle *handle) {
  5669. upb_descreader *r = closure;
  5670. bool ok;
  5671. UPB_UNUSED(hd);
  5672. UPB_UNUSED(handle);
  5673. /* XXX: see comment at the top of the file. */
  5674. if (upb_streq("proto2", buf, n)) {
  5675. ok = upb_filedef_setsyntax(r->file, UPB_SYNTAX_PROTO2, NULL);
  5676. } else if (upb_streq("proto3", buf, n)) {
  5677. ok = upb_filedef_setsyntax(r->file, UPB_SYNTAX_PROTO3, NULL);
  5678. } else {
  5679. ok = false;
  5680. }
  5681. UPB_ASSERT_VAR(ok, ok);
  5682. return n;
  5683. }
  5684. static void *file_startmsg(void *closure, const void *hd) {
  5685. upb_descreader *r = closure;
  5686. upb_msgdef *m = upb_msgdef_new(&m);
  5687. bool ok = upb_filedef_addmsg(r->file, m, &m, NULL);
  5688. UPB_UNUSED(hd);
  5689. UPB_ASSERT_VAR(ok, ok);
  5690. return r;
  5691. }
  5692. static void *file_startenum(void *closure, const void *hd) {
  5693. upb_descreader *r = closure;
  5694. upb_enumdef *e = upb_enumdef_new(&e);
  5695. bool ok = upb_filedef_addenum(r->file, e, &e, NULL);
  5696. UPB_UNUSED(hd);
  5697. UPB_ASSERT_VAR(ok, ok);
  5698. return r;
  5699. }
  5700. static void *file_startext(void *closure, const void *hd) {
  5701. upb_descreader *r = closure;
  5702. bool ok;
  5703. r->f = upb_fielddef_new(r);
  5704. ok = upb_filedef_addext(r->file, r->f, r, NULL);
  5705. UPB_UNUSED(hd);
  5706. UPB_ASSERT_VAR(ok, ok);
  5707. return r;
  5708. }
  5709. /** Handlers for google.protobuf.EnumValueDescriptorProto. *********************/
  5710. static bool enumval_startmsg(void *closure, const void *hd) {
  5711. upb_descreader *r = closure;
  5712. UPB_UNUSED(hd);
  5713. r->saw_number = false;
  5714. r->saw_name = false;
  5715. return true;
  5716. }
  5717. static size_t enumval_onname(void *closure, const void *hd, const char *buf,
  5718. size_t n, const upb_bufhandle *handle) {
  5719. upb_descreader *r = closure;
  5720. UPB_UNUSED(hd);
  5721. UPB_UNUSED(handle);
  5722. /* XXX: see comment at the top of the file. */
  5723. upb_gfree(r->name);
  5724. r->name = upb_strndup(buf, n);
  5725. r->saw_name = true;
  5726. return n;
  5727. }
  5728. static bool enumval_onnumber(void *closure, const void *hd, int32_t val) {
  5729. upb_descreader *r = closure;
  5730. UPB_UNUSED(hd);
  5731. r->number = val;
  5732. r->saw_number = true;
  5733. return true;
  5734. }
  5735. static bool enumval_endmsg(void *closure, const void *hd, upb_status *status) {
  5736. upb_descreader *r = closure;
  5737. upb_enumdef *e;
  5738. UPB_UNUSED(hd);
  5739. if(!r->saw_number || !r->saw_name) {
  5740. upb_status_seterrmsg(status, "Enum value missing name or number.");
  5741. return false;
  5742. }
  5743. e = upb_downcast_enumdef_mutable(upb_descreader_last(r));
  5744. upb_enumdef_addval(e, r->name, r->number, status);
  5745. upb_gfree(r->name);
  5746. r->name = NULL;
  5747. return true;
  5748. }
  5749. /** Handlers for google.protobuf.EnumDescriptorProto. *************************/
  5750. static bool enum_endmsg(void *closure, const void *hd, upb_status *status) {
  5751. upb_descreader *r = closure;
  5752. upb_enumdef *e;
  5753. UPB_UNUSED(hd);
  5754. e = upb_downcast_enumdef_mutable(upb_descreader_last(r));
  5755. if (upb_def_fullname(upb_descreader_last(r)) == NULL) {
  5756. upb_status_seterrmsg(status, "Enum had no name.");
  5757. return false;
  5758. }
  5759. if (upb_enumdef_numvals(e) == 0) {
  5760. upb_status_seterrmsg(status, "Enum had no values.");
  5761. return false;
  5762. }
  5763. return true;
  5764. }
  5765. static size_t enum_onname(void *closure, const void *hd, const char *buf,
  5766. size_t n, const upb_bufhandle *handle) {
  5767. upb_descreader *r = closure;
  5768. char *fullname = upb_strndup(buf, n);
  5769. UPB_UNUSED(hd);
  5770. UPB_UNUSED(handle);
  5771. /* XXX: see comment at the top of the file. */
  5772. upb_def_setfullname(upb_descreader_last(r), fullname, NULL);
  5773. upb_gfree(fullname);
  5774. return n;
  5775. }
  5776. /** Handlers for google.protobuf.FieldDescriptorProto *************************/
  5777. static bool field_startmsg(void *closure, const void *hd) {
  5778. upb_descreader *r = closure;
  5779. UPB_UNUSED(hd);
  5780. assert(r->f);
  5781. upb_gfree(r->default_string);
  5782. r->default_string = NULL;
  5783. /* fielddefs default to packed, but descriptors default to non-packed. */
  5784. upb_fielddef_setpacked(r->f, false);
  5785. return true;
  5786. }
  5787. /* Converts the default value in string "str" into "d". Passes a ref on str.
  5788. * Returns true on success. */
  5789. static bool parse_default(char *str, upb_fielddef *f) {
  5790. bool success = true;
  5791. char *end;
  5792. switch (upb_fielddef_type(f)) {
  5793. case UPB_TYPE_INT32: {
  5794. long val = strtol(str, &end, 0);
  5795. if (val > INT32_MAX || val < INT32_MIN || errno == ERANGE || *end)
  5796. success = false;
  5797. else
  5798. upb_fielddef_setdefaultint32(f, val);
  5799. break;
  5800. }
  5801. case UPB_TYPE_INT64: {
  5802. /* XXX: Need to write our own strtoll, since it's not available in c89. */
  5803. long long val = strtol(str, &end, 0);
  5804. if (val > INT64_MAX || val < INT64_MIN || errno == ERANGE || *end)
  5805. success = false;
  5806. else
  5807. upb_fielddef_setdefaultint64(f, val);
  5808. break;
  5809. }
  5810. case UPB_TYPE_UINT32: {
  5811. unsigned long val = strtoul(str, &end, 0);
  5812. if (val > UINT32_MAX || errno == ERANGE || *end)
  5813. success = false;
  5814. else
  5815. upb_fielddef_setdefaultuint32(f, val);
  5816. break;
  5817. }
  5818. case UPB_TYPE_UINT64: {
  5819. /* XXX: Need to write our own strtoull, since it's not available in c89. */
  5820. unsigned long long val = strtoul(str, &end, 0);
  5821. if (val > UINT64_MAX || errno == ERANGE || *end)
  5822. success = false;
  5823. else
  5824. upb_fielddef_setdefaultuint64(f, val);
  5825. break;
  5826. }
  5827. case UPB_TYPE_DOUBLE: {
  5828. double val = strtod(str, &end);
  5829. if (errno == ERANGE || *end)
  5830. success = false;
  5831. else
  5832. upb_fielddef_setdefaultdouble(f, val);
  5833. break;
  5834. }
  5835. case UPB_TYPE_FLOAT: {
  5836. /* XXX: Need to write our own strtof, since it's not available in c89. */
  5837. float val = strtod(str, &end);
  5838. if (errno == ERANGE || *end)
  5839. success = false;
  5840. else
  5841. upb_fielddef_setdefaultfloat(f, val);
  5842. break;
  5843. }
  5844. case UPB_TYPE_BOOL: {
  5845. if (strcmp(str, "false") == 0)
  5846. upb_fielddef_setdefaultbool(f, false);
  5847. else if (strcmp(str, "true") == 0)
  5848. upb_fielddef_setdefaultbool(f, true);
  5849. else
  5850. success = false;
  5851. break;
  5852. }
  5853. default: abort();
  5854. }
  5855. return success;
  5856. }
  5857. static bool field_endmsg(void *closure, const void *hd, upb_status *status) {
  5858. upb_descreader *r = closure;
  5859. upb_fielddef *f = r->f;
  5860. UPB_UNUSED(hd);
  5861. /* TODO: verify that all required fields were present. */
  5862. assert(upb_fielddef_number(f) != 0);
  5863. assert(upb_fielddef_name(f) != NULL);
  5864. assert((upb_fielddef_subdefname(f) != NULL) == upb_fielddef_hassubdef(f));
  5865. if (r->default_string) {
  5866. if (upb_fielddef_issubmsg(f)) {
  5867. upb_status_seterrmsg(status, "Submessages cannot have defaults.");
  5868. return false;
  5869. }
  5870. if (upb_fielddef_isstring(f) || upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  5871. upb_fielddef_setdefaultcstr(f, r->default_string, NULL);
  5872. } else {
  5873. if (r->default_string && !parse_default(r->default_string, f)) {
  5874. /* We don't worry too much about giving a great error message since the
  5875. * compiler should have ensured this was correct. */
  5876. upb_status_seterrmsg(status, "Error converting default value.");
  5877. return false;
  5878. }
  5879. }
  5880. }
  5881. return true;
  5882. }
  5883. static bool field_onlazy(void *closure, const void *hd, bool val) {
  5884. upb_descreader *r = closure;
  5885. UPB_UNUSED(hd);
  5886. upb_fielddef_setlazy(r->f, val);
  5887. return true;
  5888. }
  5889. static bool field_onpacked(void *closure, const void *hd, bool val) {
  5890. upb_descreader *r = closure;
  5891. UPB_UNUSED(hd);
  5892. upb_fielddef_setpacked(r->f, val);
  5893. return true;
  5894. }
  5895. static bool field_ontype(void *closure, const void *hd, int32_t val) {
  5896. upb_descreader *r = closure;
  5897. UPB_UNUSED(hd);
  5898. upb_fielddef_setdescriptortype(r->f, val);
  5899. return true;
  5900. }
  5901. static bool field_onlabel(void *closure, const void *hd, int32_t val) {
  5902. upb_descreader *r = closure;
  5903. UPB_UNUSED(hd);
  5904. upb_fielddef_setlabel(r->f, val);
  5905. return true;
  5906. }
  5907. static bool field_onnumber(void *closure, const void *hd, int32_t val) {
  5908. upb_descreader *r = closure;
  5909. bool ok;
  5910. UPB_UNUSED(hd);
  5911. ok = upb_fielddef_setnumber(r->f, val, NULL);
  5912. UPB_ASSERT_VAR(ok, ok);
  5913. return true;
  5914. }
  5915. static size_t field_onname(void *closure, const void *hd, const char *buf,
  5916. size_t n, const upb_bufhandle *handle) {
  5917. upb_descreader *r = closure;
  5918. char *name = upb_strndup(buf, n);
  5919. UPB_UNUSED(hd);
  5920. UPB_UNUSED(handle);
  5921. /* XXX: see comment at the top of the file. */
  5922. upb_fielddef_setname(r->f, name, NULL);
  5923. upb_gfree(name);
  5924. return n;
  5925. }
  5926. static size_t field_ontypename(void *closure, const void *hd, const char *buf,
  5927. size_t n, const upb_bufhandle *handle) {
  5928. upb_descreader *r = closure;
  5929. char *name = upb_strndup(buf, n);
  5930. UPB_UNUSED(hd);
  5931. UPB_UNUSED(handle);
  5932. /* XXX: see comment at the top of the file. */
  5933. upb_fielddef_setsubdefname(r->f, name, NULL);
  5934. upb_gfree(name);
  5935. return n;
  5936. }
  5937. static size_t field_onextendee(void *closure, const void *hd, const char *buf,
  5938. size_t n, const upb_bufhandle *handle) {
  5939. upb_descreader *r = closure;
  5940. char *name = upb_strndup(buf, n);
  5941. UPB_UNUSED(hd);
  5942. UPB_UNUSED(handle);
  5943. /* XXX: see comment at the top of the file. */
  5944. upb_fielddef_setcontainingtypename(r->f, name, NULL);
  5945. upb_gfree(name);
  5946. return n;
  5947. }
  5948. static size_t field_ondefaultval(void *closure, const void *hd, const char *buf,
  5949. size_t n, const upb_bufhandle *handle) {
  5950. upb_descreader *r = closure;
  5951. UPB_UNUSED(hd);
  5952. UPB_UNUSED(handle);
  5953. /* Have to convert from string to the correct type, but we might not know the
  5954. * type yet, so we save it as a string until the end of the field.
  5955. * XXX: see comment at the top of the file. */
  5956. upb_gfree(r->default_string);
  5957. r->default_string = upb_strndup(buf, n);
  5958. return n;
  5959. }
  5960. /** Handlers for google.protobuf.DescriptorProto ******************************/
  5961. static bool msg_start(void *closure, const void *hd) {
  5962. upb_descreader *r = closure;
  5963. UPB_UNUSED(hd);
  5964. upb_descreader_startcontainer(r);
  5965. return true;
  5966. }
  5967. static bool msg_end(void *closure, const void *hd, upb_status *status) {
  5968. upb_descreader *r = closure;
  5969. upb_msgdef *m = upb_descreader_top(r);
  5970. UPB_UNUSED(hd);
  5971. if(!upb_def_fullname(upb_msgdef_upcast_mutable(m))) {
  5972. upb_status_seterrmsg(status, "Encountered message with no name.");
  5973. return false;
  5974. }
  5975. return upb_descreader_endcontainer(r);
  5976. }
  5977. static size_t msg_name(void *closure, const void *hd, const char *buf,
  5978. size_t n, const upb_bufhandle *handle) {
  5979. upb_descreader *r = closure;
  5980. upb_msgdef *m = upb_descreader_top(r);
  5981. /* XXX: see comment at the top of the file. */
  5982. char *name = upb_strndup(buf, n);
  5983. UPB_UNUSED(hd);
  5984. UPB_UNUSED(handle);
  5985. upb_def_setfullname(upb_msgdef_upcast_mutable(m), name, NULL);
  5986. upb_descreader_setscopename(r, name); /* Passes ownership of name. */
  5987. return n;
  5988. }
  5989. static void *msg_startmsg(void *closure, const void *hd) {
  5990. upb_descreader *r = closure;
  5991. upb_msgdef *m = upb_msgdef_new(&m);
  5992. bool ok = upb_filedef_addmsg(r->file, m, &m, NULL);
  5993. UPB_UNUSED(hd);
  5994. UPB_ASSERT_VAR(ok, ok);
  5995. return r;
  5996. }
  5997. static void *msg_startext(void *closure, const void *hd) {
  5998. upb_descreader *r = closure;
  5999. upb_fielddef *f = upb_fielddef_new(&f);
  6000. bool ok = upb_filedef_addext(r->file, f, &f, NULL);
  6001. UPB_UNUSED(hd);
  6002. UPB_ASSERT_VAR(ok, ok);
  6003. return r;
  6004. }
  6005. static void *msg_startfield(void *closure, const void *hd) {
  6006. upb_descreader *r = closure;
  6007. r->f = upb_fielddef_new(&r->f);
  6008. /* We can't add the new field to the message until its name/number are
  6009. * filled in. */
  6010. UPB_UNUSED(hd);
  6011. return r;
  6012. }
  6013. static bool msg_endfield(void *closure, const void *hd) {
  6014. upb_descreader *r = closure;
  6015. upb_msgdef *m = upb_descreader_top(r);
  6016. UPB_UNUSED(hd);
  6017. upb_msgdef_addfield(m, r->f, &r->f, NULL);
  6018. r->f = NULL;
  6019. return true;
  6020. }
  6021. static bool msg_onmapentry(void *closure, const void *hd, bool mapentry) {
  6022. upb_descreader *r = closure;
  6023. upb_msgdef *m = upb_descreader_top(r);
  6024. UPB_UNUSED(hd);
  6025. upb_msgdef_setmapentry(m, mapentry);
  6026. r->f = NULL;
  6027. return true;
  6028. }
  6029. /** Code to register handlers *************************************************/
  6030. #define F(msg, field) upbdefs_google_protobuf_ ## msg ## _f_ ## field(m)
  6031. static void reghandlers(const void *closure, upb_handlers *h) {
  6032. const upb_msgdef *m = upb_handlers_msgdef(h);
  6033. UPB_UNUSED(closure);
  6034. if (upbdefs_google_protobuf_FileDescriptorSet_is(m)) {
  6035. upb_handlers_setstartsubmsg(h, F(FileDescriptorSet, file),
  6036. &fileset_startfile, NULL);
  6037. } else if (upbdefs_google_protobuf_DescriptorProto_is(m)) {
  6038. upb_handlers_setstartmsg(h, &msg_start, NULL);
  6039. upb_handlers_setendmsg(h, &msg_end, NULL);
  6040. upb_handlers_setstring(h, F(DescriptorProto, name), &msg_name, NULL);
  6041. upb_handlers_setstartsubmsg(h, F(DescriptorProto, extension), &msg_startext,
  6042. NULL);
  6043. upb_handlers_setstartsubmsg(h, F(DescriptorProto, nested_type),
  6044. &msg_startmsg, NULL);
  6045. upb_handlers_setstartsubmsg(h, F(DescriptorProto, field),
  6046. &msg_startfield, NULL);
  6047. upb_handlers_setendsubmsg(h, F(DescriptorProto, field),
  6048. &msg_endfield, NULL);
  6049. upb_handlers_setstartsubmsg(h, F(DescriptorProto, enum_type),
  6050. &file_startenum, NULL);
  6051. } else if (upbdefs_google_protobuf_FileDescriptorProto_is(m)) {
  6052. upb_handlers_setstartmsg(h, &file_start, NULL);
  6053. upb_handlers_setendmsg(h, &file_end, NULL);
  6054. upb_handlers_setstring(h, F(FileDescriptorProto, name), &file_onname,
  6055. NULL);
  6056. upb_handlers_setstring(h, F(FileDescriptorProto, package), &file_onpackage,
  6057. NULL);
  6058. upb_handlers_setstring(h, F(FileDescriptorProto, syntax), &file_onsyntax,
  6059. NULL);
  6060. upb_handlers_setstartsubmsg(h, F(FileDescriptorProto, message_type),
  6061. &file_startmsg, NULL);
  6062. upb_handlers_setstartsubmsg(h, F(FileDescriptorProto, enum_type),
  6063. &file_startenum, NULL);
  6064. upb_handlers_setstartsubmsg(h, F(FileDescriptorProto, extension),
  6065. &file_startext, NULL);
  6066. } else if (upbdefs_google_protobuf_EnumValueDescriptorProto_is(m)) {
  6067. upb_handlers_setstartmsg(h, &enumval_startmsg, NULL);
  6068. upb_handlers_setendmsg(h, &enumval_endmsg, NULL);
  6069. upb_handlers_setstring(h, F(EnumValueDescriptorProto, name), &enumval_onname, NULL);
  6070. upb_handlers_setint32(h, F(EnumValueDescriptorProto, number), &enumval_onnumber,
  6071. NULL);
  6072. } else if (upbdefs_google_protobuf_EnumDescriptorProto_is(m)) {
  6073. upb_handlers_setendmsg(h, &enum_endmsg, NULL);
  6074. upb_handlers_setstring(h, F(EnumDescriptorProto, name), &enum_onname, NULL);
  6075. } else if (upbdefs_google_protobuf_FieldDescriptorProto_is(m)) {
  6076. upb_handlers_setstartmsg(h, &field_startmsg, NULL);
  6077. upb_handlers_setendmsg(h, &field_endmsg, NULL);
  6078. upb_handlers_setint32(h, F(FieldDescriptorProto, type), &field_ontype,
  6079. NULL);
  6080. upb_handlers_setint32(h, F(FieldDescriptorProto, label), &field_onlabel,
  6081. NULL);
  6082. upb_handlers_setint32(h, F(FieldDescriptorProto, number), &field_onnumber,
  6083. NULL);
  6084. upb_handlers_setstring(h, F(FieldDescriptorProto, name), &field_onname,
  6085. NULL);
  6086. upb_handlers_setstring(h, F(FieldDescriptorProto, type_name),
  6087. &field_ontypename, NULL);
  6088. upb_handlers_setstring(h, F(FieldDescriptorProto, extendee),
  6089. &field_onextendee, NULL);
  6090. upb_handlers_setstring(h, F(FieldDescriptorProto, default_value),
  6091. &field_ondefaultval, NULL);
  6092. } else if (upbdefs_google_protobuf_FieldOptions_is(m)) {
  6093. upb_handlers_setbool(h, F(FieldOptions, lazy), &field_onlazy, NULL);
  6094. upb_handlers_setbool(h, F(FieldOptions, packed), &field_onpacked, NULL);
  6095. } else if (upbdefs_google_protobuf_MessageOptions_is(m)) {
  6096. upb_handlers_setbool(h, F(MessageOptions, map_entry), &msg_onmapentry, NULL);
  6097. }
  6098. assert(upb_ok(upb_handlers_status(h)));
  6099. }
  6100. #undef F
  6101. void descreader_cleanup(void *_r) {
  6102. upb_descreader *r = _r;
  6103. size_t i;
  6104. for (i = 0; i < upb_descreader_filecount(r); i++) {
  6105. upb_filedef_unref(upb_descreader_file(r, i), &r->files);
  6106. }
  6107. upb_gfree(r->name);
  6108. upb_inttable_uninit(&r->files);
  6109. upb_gfree(r->default_string);
  6110. while (r->stack_len > 0) {
  6111. upb_descreader_frame *f = &r->stack[--r->stack_len];
  6112. upb_gfree(f->name);
  6113. }
  6114. }
  6115. /* Public API ****************************************************************/
  6116. upb_descreader *upb_descreader_create(upb_env *e, const upb_handlers *h) {
  6117. upb_descreader *r = upb_env_malloc(e, sizeof(upb_descreader));
  6118. if (!r || !upb_env_addcleanup(e, descreader_cleanup, r)) {
  6119. return NULL;
  6120. }
  6121. upb_inttable_init(&r->files, UPB_CTYPE_PTR);
  6122. upb_sink_reset(upb_descreader_input(r), h, r);
  6123. r->stack_len = 0;
  6124. r->name = NULL;
  6125. r->default_string = NULL;
  6126. return r;
  6127. }
  6128. size_t upb_descreader_filecount(const upb_descreader *r) {
  6129. return upb_inttable_count(&r->files);
  6130. }
  6131. upb_filedef *upb_descreader_file(const upb_descreader *r, size_t i) {
  6132. upb_value v;
  6133. if (upb_inttable_lookup(&r->files, i, &v)) {
  6134. return upb_value_getptr(v);
  6135. } else {
  6136. return NULL;
  6137. }
  6138. }
  6139. upb_sink *upb_descreader_input(upb_descreader *r) {
  6140. return &r->sink;
  6141. }
  6142. const upb_handlers *upb_descreader_newhandlers(const void *owner) {
  6143. const upb_msgdef *m = upbdefs_google_protobuf_FileDescriptorSet_get(&m);
  6144. const upb_handlers *h = upb_handlers_newfrozen(m, owner, reghandlers, NULL);
  6145. upb_msgdef_unref(m, &m);
  6146. return h;
  6147. }
  6148. /*
  6149. ** protobuf decoder bytecode compiler
  6150. **
  6151. ** Code to compile a upb::Handlers into bytecode for decoding a protobuf
  6152. ** according to that specific schema and destination handlers.
  6153. **
  6154. ** Compiling to bytecode is always the first step. If we are using the
  6155. ** interpreted decoder we leave it as bytecode and interpret that. If we are
  6156. ** using a JIT decoder we use a code generator to turn the bytecode into native
  6157. ** code, LLVM IR, etc.
  6158. **
  6159. ** Bytecode definition is in decoder.int.h.
  6160. */
  6161. #include <stdarg.h>
  6162. #ifdef UPB_DUMP_BYTECODE
  6163. #include <stdio.h>
  6164. #endif
  6165. #define MAXLABEL 5
  6166. #define EMPTYLABEL -1
  6167. /* mgroup *********************************************************************/
  6168. static void freegroup(upb_refcounted *r) {
  6169. mgroup *g = (mgroup*)r;
  6170. upb_inttable_uninit(&g->methods);
  6171. #ifdef UPB_USE_JIT_X64
  6172. upb_pbdecoder_freejit(g);
  6173. #endif
  6174. upb_gfree(g->bytecode);
  6175. upb_gfree(g);
  6176. }
  6177. static void visitgroup(const upb_refcounted *r, upb_refcounted_visit *visit,
  6178. void *closure) {
  6179. const mgroup *g = (const mgroup*)r;
  6180. upb_inttable_iter i;
  6181. upb_inttable_begin(&i, &g->methods);
  6182. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  6183. upb_pbdecodermethod *method = upb_value_getptr(upb_inttable_iter_value(&i));
  6184. visit(r, upb_pbdecodermethod_upcast(method), closure);
  6185. }
  6186. }
  6187. mgroup *newgroup(const void *owner) {
  6188. mgroup *g = upb_gmalloc(sizeof(*g));
  6189. static const struct upb_refcounted_vtbl vtbl = {visitgroup, freegroup};
  6190. upb_refcounted_init(mgroup_upcast_mutable(g), &vtbl, owner);
  6191. upb_inttable_init(&g->methods, UPB_CTYPE_PTR);
  6192. g->bytecode = NULL;
  6193. g->bytecode_end = NULL;
  6194. return g;
  6195. }
  6196. /* upb_pbdecodermethod ********************************************************/
  6197. static void freemethod(upb_refcounted *r) {
  6198. upb_pbdecodermethod *method = (upb_pbdecodermethod*)r;
  6199. if (method->dest_handlers_) {
  6200. upb_handlers_unref(method->dest_handlers_, method);
  6201. }
  6202. upb_inttable_uninit(&method->dispatch);
  6203. upb_gfree(method);
  6204. }
  6205. static void visitmethod(const upb_refcounted *r, upb_refcounted_visit *visit,
  6206. void *closure) {
  6207. const upb_pbdecodermethod *m = (const upb_pbdecodermethod*)r;
  6208. visit(r, m->group, closure);
  6209. }
  6210. static upb_pbdecodermethod *newmethod(const upb_handlers *dest_handlers,
  6211. mgroup *group) {
  6212. static const struct upb_refcounted_vtbl vtbl = {visitmethod, freemethod};
  6213. upb_pbdecodermethod *ret = upb_gmalloc(sizeof(*ret));
  6214. upb_refcounted_init(upb_pbdecodermethod_upcast_mutable(ret), &vtbl, &ret);
  6215. upb_byteshandler_init(&ret->input_handler_);
  6216. /* The method references the group and vice-versa, in a circular reference. */
  6217. upb_ref2(ret, group);
  6218. upb_ref2(group, ret);
  6219. upb_inttable_insertptr(&group->methods, dest_handlers, upb_value_ptr(ret));
  6220. upb_pbdecodermethod_unref(ret, &ret);
  6221. ret->group = mgroup_upcast_mutable(group);
  6222. ret->dest_handlers_ = dest_handlers;
  6223. ret->is_native_ = false; /* If we JIT, it will update this later. */
  6224. upb_inttable_init(&ret->dispatch, UPB_CTYPE_UINT64);
  6225. if (ret->dest_handlers_) {
  6226. upb_handlers_ref(ret->dest_handlers_, ret);
  6227. }
  6228. return ret;
  6229. }
  6230. const upb_handlers *upb_pbdecodermethod_desthandlers(
  6231. const upb_pbdecodermethod *m) {
  6232. return m->dest_handlers_;
  6233. }
  6234. const upb_byteshandler *upb_pbdecodermethod_inputhandler(
  6235. const upb_pbdecodermethod *m) {
  6236. return &m->input_handler_;
  6237. }
  6238. bool upb_pbdecodermethod_isnative(const upb_pbdecodermethod *m) {
  6239. return m->is_native_;
  6240. }
  6241. const upb_pbdecodermethod *upb_pbdecodermethod_new(
  6242. const upb_pbdecodermethodopts *opts, const void *owner) {
  6243. const upb_pbdecodermethod *ret;
  6244. upb_pbcodecache cache;
  6245. upb_pbcodecache_init(&cache);
  6246. ret = upb_pbcodecache_getdecodermethod(&cache, opts);
  6247. upb_pbdecodermethod_ref(ret, owner);
  6248. upb_pbcodecache_uninit(&cache);
  6249. return ret;
  6250. }
  6251. /* bytecode compiler **********************************************************/
  6252. /* Data used only at compilation time. */
  6253. typedef struct {
  6254. mgroup *group;
  6255. uint32_t *pc;
  6256. int fwd_labels[MAXLABEL];
  6257. int back_labels[MAXLABEL];
  6258. /* For fields marked "lazy", parse them lazily or eagerly? */
  6259. bool lazy;
  6260. } compiler;
  6261. static compiler *newcompiler(mgroup *group, bool lazy) {
  6262. compiler *ret = upb_gmalloc(sizeof(*ret));
  6263. int i;
  6264. ret->group = group;
  6265. ret->lazy = lazy;
  6266. for (i = 0; i < MAXLABEL; i++) {
  6267. ret->fwd_labels[i] = EMPTYLABEL;
  6268. ret->back_labels[i] = EMPTYLABEL;
  6269. }
  6270. return ret;
  6271. }
  6272. static void freecompiler(compiler *c) {
  6273. upb_gfree(c);
  6274. }
  6275. const size_t ptr_words = sizeof(void*) / sizeof(uint32_t);
  6276. /* How many words an instruction is. */
  6277. static int instruction_len(uint32_t instr) {
  6278. switch (getop(instr)) {
  6279. case OP_SETDISPATCH: return 1 + ptr_words;
  6280. case OP_TAGN: return 3;
  6281. case OP_SETBIGGROUPNUM: return 2;
  6282. default: return 1;
  6283. }
  6284. }
  6285. bool op_has_longofs(int32_t instruction) {
  6286. switch (getop(instruction)) {
  6287. case OP_CALL:
  6288. case OP_BRANCH:
  6289. case OP_CHECKDELIM:
  6290. return true;
  6291. /* The "tag" instructions only have 8 bytes available for the jump target,
  6292. * but that is ok because these opcodes only require short jumps. */
  6293. case OP_TAG1:
  6294. case OP_TAG2:
  6295. case OP_TAGN:
  6296. return false;
  6297. default:
  6298. assert(false);
  6299. return false;
  6300. }
  6301. }
  6302. static int32_t getofs(uint32_t instruction) {
  6303. if (op_has_longofs(instruction)) {
  6304. return (int32_t)instruction >> 8;
  6305. } else {
  6306. return (int8_t)(instruction >> 8);
  6307. }
  6308. }
  6309. static void setofs(uint32_t *instruction, int32_t ofs) {
  6310. if (op_has_longofs(*instruction)) {
  6311. *instruction = getop(*instruction) | ofs << 8;
  6312. } else {
  6313. *instruction = (*instruction & ~0xff00) | ((ofs & 0xff) << 8);
  6314. }
  6315. assert(getofs(*instruction) == ofs); /* Would fail in cases of overflow. */
  6316. }
  6317. static uint32_t pcofs(compiler *c) { return c->pc - c->group->bytecode; }
  6318. /* Defines a local label at the current PC location. All previous forward
  6319. * references are updated to point to this location. The location is noted
  6320. * for any future backward references. */
  6321. static void label(compiler *c, unsigned int label) {
  6322. int val;
  6323. uint32_t *codep;
  6324. assert(label < MAXLABEL);
  6325. val = c->fwd_labels[label];
  6326. codep = (val == EMPTYLABEL) ? NULL : c->group->bytecode + val;
  6327. while (codep) {
  6328. int ofs = getofs(*codep);
  6329. setofs(codep, c->pc - codep - instruction_len(*codep));
  6330. codep = ofs ? codep + ofs : NULL;
  6331. }
  6332. c->fwd_labels[label] = EMPTYLABEL;
  6333. c->back_labels[label] = pcofs(c);
  6334. }
  6335. /* Creates a reference to a numbered label; either a forward reference
  6336. * (positive arg) or backward reference (negative arg). For forward references
  6337. * the value returned now is actually a "next" pointer into a linked list of all
  6338. * instructions that use this label and will be patched later when the label is
  6339. * defined with label().
  6340. *
  6341. * The returned value is the offset that should be written into the instruction.
  6342. */
  6343. static int32_t labelref(compiler *c, int label) {
  6344. assert(label < MAXLABEL);
  6345. if (label == LABEL_DISPATCH) {
  6346. /* No resolving required. */
  6347. return 0;
  6348. } else if (label < 0) {
  6349. /* Backward local label. Relative to the next instruction. */
  6350. uint32_t from = (c->pc + 1) - c->group->bytecode;
  6351. return c->back_labels[-label] - from;
  6352. } else {
  6353. /* Forward local label: prepend to (possibly-empty) linked list. */
  6354. int *lptr = &c->fwd_labels[label];
  6355. int32_t ret = (*lptr == EMPTYLABEL) ? 0 : *lptr - pcofs(c);
  6356. *lptr = pcofs(c);
  6357. return ret;
  6358. }
  6359. }
  6360. static void put32(compiler *c, uint32_t v) {
  6361. mgroup *g = c->group;
  6362. if (c->pc == g->bytecode_end) {
  6363. int ofs = pcofs(c);
  6364. size_t oldsize = g->bytecode_end - g->bytecode;
  6365. size_t newsize = UPB_MAX(oldsize * 2, 64);
  6366. /* TODO(haberman): handle OOM. */
  6367. g->bytecode = upb_grealloc(g->bytecode, oldsize * sizeof(uint32_t),
  6368. newsize * sizeof(uint32_t));
  6369. g->bytecode_end = g->bytecode + newsize;
  6370. c->pc = g->bytecode + ofs;
  6371. }
  6372. *c->pc++ = v;
  6373. }
  6374. static void putop(compiler *c, opcode op, ...) {
  6375. va_list ap;
  6376. va_start(ap, op);
  6377. switch (op) {
  6378. case OP_SETDISPATCH: {
  6379. uintptr_t ptr = (uintptr_t)va_arg(ap, void*);
  6380. put32(c, OP_SETDISPATCH);
  6381. put32(c, ptr);
  6382. if (sizeof(uintptr_t) > sizeof(uint32_t))
  6383. put32(c, (uint64_t)ptr >> 32);
  6384. break;
  6385. }
  6386. case OP_STARTMSG:
  6387. case OP_ENDMSG:
  6388. case OP_PUSHLENDELIM:
  6389. case OP_POP:
  6390. case OP_SETDELIM:
  6391. case OP_HALT:
  6392. case OP_RET:
  6393. case OP_DISPATCH:
  6394. put32(c, op);
  6395. break;
  6396. case OP_PARSE_DOUBLE:
  6397. case OP_PARSE_FLOAT:
  6398. case OP_PARSE_INT64:
  6399. case OP_PARSE_UINT64:
  6400. case OP_PARSE_INT32:
  6401. case OP_PARSE_FIXED64:
  6402. case OP_PARSE_FIXED32:
  6403. case OP_PARSE_BOOL:
  6404. case OP_PARSE_UINT32:
  6405. case OP_PARSE_SFIXED32:
  6406. case OP_PARSE_SFIXED64:
  6407. case OP_PARSE_SINT32:
  6408. case OP_PARSE_SINT64:
  6409. case OP_STARTSEQ:
  6410. case OP_ENDSEQ:
  6411. case OP_STARTSUBMSG:
  6412. case OP_ENDSUBMSG:
  6413. case OP_STARTSTR:
  6414. case OP_STRING:
  6415. case OP_ENDSTR:
  6416. case OP_PUSHTAGDELIM:
  6417. put32(c, op | va_arg(ap, upb_selector_t) << 8);
  6418. break;
  6419. case OP_SETBIGGROUPNUM:
  6420. put32(c, op);
  6421. put32(c, va_arg(ap, int));
  6422. break;
  6423. case OP_CALL: {
  6424. const upb_pbdecodermethod *method = va_arg(ap, upb_pbdecodermethod *);
  6425. put32(c, op | (method->code_base.ofs - (pcofs(c) + 1)) << 8);
  6426. break;
  6427. }
  6428. case OP_CHECKDELIM:
  6429. case OP_BRANCH: {
  6430. uint32_t instruction = op;
  6431. int label = va_arg(ap, int);
  6432. setofs(&instruction, labelref(c, label));
  6433. put32(c, instruction);
  6434. break;
  6435. }
  6436. case OP_TAG1:
  6437. case OP_TAG2: {
  6438. int label = va_arg(ap, int);
  6439. uint64_t tag = va_arg(ap, uint64_t);
  6440. uint32_t instruction = op | (tag << 16);
  6441. assert(tag <= 0xffff);
  6442. setofs(&instruction, labelref(c, label));
  6443. put32(c, instruction);
  6444. break;
  6445. }
  6446. case OP_TAGN: {
  6447. int label = va_arg(ap, int);
  6448. uint64_t tag = va_arg(ap, uint64_t);
  6449. uint32_t instruction = op | (upb_value_size(tag) << 16);
  6450. setofs(&instruction, labelref(c, label));
  6451. put32(c, instruction);
  6452. put32(c, tag);
  6453. put32(c, tag >> 32);
  6454. break;
  6455. }
  6456. }
  6457. va_end(ap);
  6458. }
  6459. #if defined(UPB_USE_JIT_X64) || defined(UPB_DUMP_BYTECODE)
  6460. const char *upb_pbdecoder_getopname(unsigned int op) {
  6461. #define QUOTE(x) #x
  6462. #define EXPAND_AND_QUOTE(x) QUOTE(x)
  6463. #define OPNAME(x) OP_##x
  6464. #define OP(x) case OPNAME(x): return EXPAND_AND_QUOTE(OPNAME(x));
  6465. #define T(x) OP(PARSE_##x)
  6466. /* Keep in sync with list in decoder.int.h. */
  6467. switch ((opcode)op) {
  6468. T(DOUBLE) T(FLOAT) T(INT64) T(UINT64) T(INT32) T(FIXED64) T(FIXED32)
  6469. T(BOOL) T(UINT32) T(SFIXED32) T(SFIXED64) T(SINT32) T(SINT64)
  6470. OP(STARTMSG) OP(ENDMSG) OP(STARTSEQ) OP(ENDSEQ) OP(STARTSUBMSG)
  6471. OP(ENDSUBMSG) OP(STARTSTR) OP(STRING) OP(ENDSTR) OP(CALL) OP(RET)
  6472. OP(PUSHLENDELIM) OP(PUSHTAGDELIM) OP(SETDELIM) OP(CHECKDELIM)
  6473. OP(BRANCH) OP(TAG1) OP(TAG2) OP(TAGN) OP(SETDISPATCH) OP(POP)
  6474. OP(SETBIGGROUPNUM) OP(DISPATCH) OP(HALT)
  6475. }
  6476. return "<unknown op>";
  6477. #undef OP
  6478. #undef T
  6479. }
  6480. #endif
  6481. #ifdef UPB_DUMP_BYTECODE
  6482. static void dumpbc(uint32_t *p, uint32_t *end, FILE *f) {
  6483. uint32_t *begin = p;
  6484. while (p < end) {
  6485. fprintf(f, "%p %8tx", p, p - begin);
  6486. uint32_t instr = *p++;
  6487. uint8_t op = getop(instr);
  6488. fprintf(f, " %s", upb_pbdecoder_getopname(op));
  6489. switch ((opcode)op) {
  6490. case OP_SETDISPATCH: {
  6491. const upb_inttable *dispatch;
  6492. memcpy(&dispatch, p, sizeof(void*));
  6493. p += ptr_words;
  6494. const upb_pbdecodermethod *method =
  6495. (void *)((char *)dispatch -
  6496. offsetof(upb_pbdecodermethod, dispatch));
  6497. fprintf(f, " %s", upb_msgdef_fullname(
  6498. upb_handlers_msgdef(method->dest_handlers_)));
  6499. break;
  6500. }
  6501. case OP_DISPATCH:
  6502. case OP_STARTMSG:
  6503. case OP_ENDMSG:
  6504. case OP_PUSHLENDELIM:
  6505. case OP_POP:
  6506. case OP_SETDELIM:
  6507. case OP_HALT:
  6508. case OP_RET:
  6509. break;
  6510. case OP_PARSE_DOUBLE:
  6511. case OP_PARSE_FLOAT:
  6512. case OP_PARSE_INT64:
  6513. case OP_PARSE_UINT64:
  6514. case OP_PARSE_INT32:
  6515. case OP_PARSE_FIXED64:
  6516. case OP_PARSE_FIXED32:
  6517. case OP_PARSE_BOOL:
  6518. case OP_PARSE_UINT32:
  6519. case OP_PARSE_SFIXED32:
  6520. case OP_PARSE_SFIXED64:
  6521. case OP_PARSE_SINT32:
  6522. case OP_PARSE_SINT64:
  6523. case OP_STARTSEQ:
  6524. case OP_ENDSEQ:
  6525. case OP_STARTSUBMSG:
  6526. case OP_ENDSUBMSG:
  6527. case OP_STARTSTR:
  6528. case OP_STRING:
  6529. case OP_ENDSTR:
  6530. case OP_PUSHTAGDELIM:
  6531. fprintf(f, " %d", instr >> 8);
  6532. break;
  6533. case OP_SETBIGGROUPNUM:
  6534. fprintf(f, " %d", *p++);
  6535. break;
  6536. case OP_CHECKDELIM:
  6537. case OP_CALL:
  6538. case OP_BRANCH:
  6539. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  6540. break;
  6541. case OP_TAG1:
  6542. case OP_TAG2: {
  6543. fprintf(f, " tag:0x%x", instr >> 16);
  6544. if (getofs(instr)) {
  6545. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  6546. }
  6547. break;
  6548. }
  6549. case OP_TAGN: {
  6550. uint64_t tag = *p++;
  6551. tag |= (uint64_t)*p++ << 32;
  6552. fprintf(f, " tag:0x%llx", (long long)tag);
  6553. fprintf(f, " n:%d", instr >> 16);
  6554. if (getofs(instr)) {
  6555. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  6556. }
  6557. break;
  6558. }
  6559. }
  6560. fputs("\n", f);
  6561. }
  6562. }
  6563. #endif
  6564. static uint64_t get_encoded_tag(const upb_fielddef *f, int wire_type) {
  6565. uint32_t tag = (upb_fielddef_number(f) << 3) | wire_type;
  6566. uint64_t encoded_tag = upb_vencode32(tag);
  6567. /* No tag should be greater than 5 bytes. */
  6568. assert(encoded_tag <= 0xffffffffff);
  6569. return encoded_tag;
  6570. }
  6571. static void putchecktag(compiler *c, const upb_fielddef *f,
  6572. int wire_type, int dest) {
  6573. uint64_t tag = get_encoded_tag(f, wire_type);
  6574. switch (upb_value_size(tag)) {
  6575. case 1:
  6576. putop(c, OP_TAG1, dest, tag);
  6577. break;
  6578. case 2:
  6579. putop(c, OP_TAG2, dest, tag);
  6580. break;
  6581. default:
  6582. putop(c, OP_TAGN, dest, tag);
  6583. break;
  6584. }
  6585. }
  6586. static upb_selector_t getsel(const upb_fielddef *f, upb_handlertype_t type) {
  6587. upb_selector_t selector;
  6588. bool ok = upb_handlers_getselector(f, type, &selector);
  6589. UPB_ASSERT_VAR(ok, ok);
  6590. return selector;
  6591. }
  6592. /* Takes an existing, primary dispatch table entry and repacks it with a
  6593. * different alternate wire type. Called when we are inserting a secondary
  6594. * dispatch table entry for an alternate wire type. */
  6595. static uint64_t repack(uint64_t dispatch, int new_wt2) {
  6596. uint64_t ofs;
  6597. uint8_t wt1;
  6598. uint8_t old_wt2;
  6599. upb_pbdecoder_unpackdispatch(dispatch, &ofs, &wt1, &old_wt2);
  6600. assert(old_wt2 == NO_WIRE_TYPE); /* wt2 should not be set yet. */
  6601. return upb_pbdecoder_packdispatch(ofs, wt1, new_wt2);
  6602. }
  6603. /* Marks the current bytecode position as the dispatch target for this message,
  6604. * field, and wire type. */
  6605. static void dispatchtarget(compiler *c, upb_pbdecodermethod *method,
  6606. const upb_fielddef *f, int wire_type) {
  6607. /* Offset is relative to msg base. */
  6608. uint64_t ofs = pcofs(c) - method->code_base.ofs;
  6609. uint32_t fn = upb_fielddef_number(f);
  6610. upb_inttable *d = &method->dispatch;
  6611. upb_value v;
  6612. if (upb_inttable_remove(d, fn, &v)) {
  6613. /* TODO: prioritize based on packed setting in .proto file. */
  6614. uint64_t repacked = repack(upb_value_getuint64(v), wire_type);
  6615. upb_inttable_insert(d, fn, upb_value_uint64(repacked));
  6616. upb_inttable_insert(d, fn + UPB_MAX_FIELDNUMBER, upb_value_uint64(ofs));
  6617. } else {
  6618. uint64_t val = upb_pbdecoder_packdispatch(ofs, wire_type, NO_WIRE_TYPE);
  6619. upb_inttable_insert(d, fn, upb_value_uint64(val));
  6620. }
  6621. }
  6622. static void putpush(compiler *c, const upb_fielddef *f) {
  6623. if (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE) {
  6624. putop(c, OP_PUSHLENDELIM);
  6625. } else {
  6626. uint32_t fn = upb_fielddef_number(f);
  6627. if (fn >= 1 << 24) {
  6628. putop(c, OP_PUSHTAGDELIM, 0);
  6629. putop(c, OP_SETBIGGROUPNUM, fn);
  6630. } else {
  6631. putop(c, OP_PUSHTAGDELIM, fn);
  6632. }
  6633. }
  6634. }
  6635. static upb_pbdecodermethod *find_submethod(const compiler *c,
  6636. const upb_pbdecodermethod *method,
  6637. const upb_fielddef *f) {
  6638. const upb_handlers *sub =
  6639. upb_handlers_getsubhandlers(method->dest_handlers_, f);
  6640. upb_value v;
  6641. return upb_inttable_lookupptr(&c->group->methods, sub, &v)
  6642. ? upb_value_getptr(v)
  6643. : NULL;
  6644. }
  6645. static void putsel(compiler *c, opcode op, upb_selector_t sel,
  6646. const upb_handlers *h) {
  6647. if (upb_handlers_gethandler(h, sel)) {
  6648. putop(c, op, sel);
  6649. }
  6650. }
  6651. /* Puts an opcode to call a callback, but only if a callback actually exists for
  6652. * this field and handler type. */
  6653. static void maybeput(compiler *c, opcode op, const upb_handlers *h,
  6654. const upb_fielddef *f, upb_handlertype_t type) {
  6655. putsel(c, op, getsel(f, type), h);
  6656. }
  6657. static bool haslazyhandlers(const upb_handlers *h, const upb_fielddef *f) {
  6658. if (!upb_fielddef_lazy(f))
  6659. return false;
  6660. return upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STARTSTR)) ||
  6661. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STRING)) ||
  6662. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_ENDSTR));
  6663. }
  6664. /* bytecode compiler code generation ******************************************/
  6665. /* Symbolic names for our local labels. */
  6666. #define LABEL_LOOPSTART 1 /* Top of a repeated field loop. */
  6667. #define LABEL_LOOPBREAK 2 /* To jump out of a repeated loop */
  6668. #define LABEL_FIELD 3 /* Jump backward to find the most recent field. */
  6669. #define LABEL_ENDMSG 4 /* To reach the OP_ENDMSG instr for this msg. */
  6670. /* Generates bytecode to parse a single non-lazy message field. */
  6671. static void generate_msgfield(compiler *c, const upb_fielddef *f,
  6672. upb_pbdecodermethod *method) {
  6673. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  6674. const upb_pbdecodermethod *sub_m = find_submethod(c, method, f);
  6675. int wire_type;
  6676. if (!sub_m) {
  6677. /* Don't emit any code for this field at all; it will be parsed as an
  6678. * unknown field.
  6679. *
  6680. * TODO(haberman): we should change this to parse it as a string field
  6681. * instead. It will probably be faster, but more importantly, once we
  6682. * start vending unknown fields, a field shouldn't be treated as unknown
  6683. * just because it doesn't have subhandlers registered. */
  6684. return;
  6685. }
  6686. label(c, LABEL_FIELD);
  6687. wire_type =
  6688. (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE)
  6689. ? UPB_WIRE_TYPE_DELIMITED
  6690. : UPB_WIRE_TYPE_START_GROUP;
  6691. if (upb_fielddef_isseq(f)) {
  6692. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  6693. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  6694. dispatchtarget(c, method, f, wire_type);
  6695. putop(c, OP_PUSHTAGDELIM, 0);
  6696. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  6697. label(c, LABEL_LOOPSTART);
  6698. putpush(c, f);
  6699. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  6700. putop(c, OP_CALL, sub_m);
  6701. putop(c, OP_POP);
  6702. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  6703. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  6704. putop(c, OP_SETDELIM);
  6705. }
  6706. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  6707. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  6708. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  6709. label(c, LABEL_LOOPBREAK);
  6710. putop(c, OP_POP);
  6711. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  6712. } else {
  6713. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  6714. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  6715. dispatchtarget(c, method, f, wire_type);
  6716. putpush(c, f);
  6717. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  6718. putop(c, OP_CALL, sub_m);
  6719. putop(c, OP_POP);
  6720. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  6721. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  6722. putop(c, OP_SETDELIM);
  6723. }
  6724. }
  6725. }
  6726. /* Generates bytecode to parse a single string or lazy submessage field. */
  6727. static void generate_delimfield(compiler *c, const upb_fielddef *f,
  6728. upb_pbdecodermethod *method) {
  6729. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  6730. label(c, LABEL_FIELD);
  6731. if (upb_fielddef_isseq(f)) {
  6732. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  6733. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  6734. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  6735. putop(c, OP_PUSHTAGDELIM, 0);
  6736. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  6737. label(c, LABEL_LOOPSTART);
  6738. putop(c, OP_PUSHLENDELIM);
  6739. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  6740. /* Need to emit even if no handler to skip past the string. */
  6741. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  6742. putop(c, OP_POP);
  6743. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  6744. putop(c, OP_SETDELIM);
  6745. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  6746. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_LOOPBREAK);
  6747. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  6748. label(c, LABEL_LOOPBREAK);
  6749. putop(c, OP_POP);
  6750. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  6751. } else {
  6752. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  6753. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  6754. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  6755. putop(c, OP_PUSHLENDELIM);
  6756. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  6757. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  6758. putop(c, OP_POP);
  6759. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  6760. putop(c, OP_SETDELIM);
  6761. }
  6762. }
  6763. /* Generates bytecode to parse a single primitive field. */
  6764. static void generate_primitivefield(compiler *c, const upb_fielddef *f,
  6765. upb_pbdecodermethod *method) {
  6766. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  6767. upb_descriptortype_t descriptor_type = upb_fielddef_descriptortype(f);
  6768. opcode parse_type;
  6769. upb_selector_t sel;
  6770. int wire_type;
  6771. label(c, LABEL_FIELD);
  6772. /* From a decoding perspective, ENUM is the same as INT32. */
  6773. if (descriptor_type == UPB_DESCRIPTOR_TYPE_ENUM)
  6774. descriptor_type = UPB_DESCRIPTOR_TYPE_INT32;
  6775. parse_type = (opcode)descriptor_type;
  6776. /* TODO(haberman): generate packed or non-packed first depending on "packed"
  6777. * setting in the fielddef. This will favor (in speed) whichever was
  6778. * specified. */
  6779. assert((int)parse_type >= 0 && parse_type <= OP_MAX);
  6780. sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  6781. wire_type = upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  6782. if (upb_fielddef_isseq(f)) {
  6783. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  6784. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  6785. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  6786. putop(c, OP_PUSHLENDELIM);
  6787. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); /* Packed */
  6788. label(c, LABEL_LOOPSTART);
  6789. putop(c, parse_type, sel);
  6790. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  6791. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  6792. dispatchtarget(c, method, f, wire_type);
  6793. putop(c, OP_PUSHTAGDELIM, 0);
  6794. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); /* Non-packed */
  6795. label(c, LABEL_LOOPSTART);
  6796. putop(c, parse_type, sel);
  6797. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  6798. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  6799. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  6800. label(c, LABEL_LOOPBREAK);
  6801. putop(c, OP_POP); /* Packed and non-packed join. */
  6802. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  6803. putop(c, OP_SETDELIM); /* Could remove for non-packed by dup ENDSEQ. */
  6804. } else {
  6805. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  6806. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  6807. dispatchtarget(c, method, f, wire_type);
  6808. putop(c, parse_type, sel);
  6809. }
  6810. }
  6811. /* Adds bytecode for parsing the given message to the given decoderplan,
  6812. * while adding all dispatch targets to this message's dispatch table. */
  6813. static void compile_method(compiler *c, upb_pbdecodermethod *method) {
  6814. const upb_handlers *h;
  6815. const upb_msgdef *md;
  6816. uint32_t* start_pc;
  6817. upb_msg_field_iter i;
  6818. upb_value val;
  6819. assert(method);
  6820. /* Clear all entries in the dispatch table. */
  6821. upb_inttable_uninit(&method->dispatch);
  6822. upb_inttable_init(&method->dispatch, UPB_CTYPE_UINT64);
  6823. h = upb_pbdecodermethod_desthandlers(method);
  6824. md = upb_handlers_msgdef(h);
  6825. method->code_base.ofs = pcofs(c);
  6826. putop(c, OP_SETDISPATCH, &method->dispatch);
  6827. putsel(c, OP_STARTMSG, UPB_STARTMSG_SELECTOR, h);
  6828. label(c, LABEL_FIELD);
  6829. start_pc = c->pc;
  6830. for(upb_msg_field_begin(&i, md);
  6831. !upb_msg_field_done(&i);
  6832. upb_msg_field_next(&i)) {
  6833. const upb_fielddef *f = upb_msg_iter_field(&i);
  6834. upb_fieldtype_t type = upb_fielddef_type(f);
  6835. if (type == UPB_TYPE_MESSAGE && !(haslazyhandlers(h, f) && c->lazy)) {
  6836. generate_msgfield(c, f, method);
  6837. } else if (type == UPB_TYPE_STRING || type == UPB_TYPE_BYTES ||
  6838. type == UPB_TYPE_MESSAGE) {
  6839. generate_delimfield(c, f, method);
  6840. } else {
  6841. generate_primitivefield(c, f, method);
  6842. }
  6843. }
  6844. /* If there were no fields, or if no handlers were defined, we need to
  6845. * generate a non-empty loop body so that we can at least dispatch for unknown
  6846. * fields and check for the end of the message. */
  6847. if (c->pc == start_pc) {
  6848. /* Check for end-of-message. */
  6849. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  6850. /* Unconditionally dispatch. */
  6851. putop(c, OP_DISPATCH, 0);
  6852. }
  6853. /* For now we just loop back to the last field of the message (or if none,
  6854. * the DISPATCH opcode for the message). */
  6855. putop(c, OP_BRANCH, -LABEL_FIELD);
  6856. /* Insert both a label and a dispatch table entry for this end-of-msg. */
  6857. label(c, LABEL_ENDMSG);
  6858. val = upb_value_uint64(pcofs(c) - method->code_base.ofs);
  6859. upb_inttable_insert(&method->dispatch, DISPATCH_ENDMSG, val);
  6860. putsel(c, OP_ENDMSG, UPB_ENDMSG_SELECTOR, h);
  6861. putop(c, OP_RET);
  6862. upb_inttable_compact(&method->dispatch);
  6863. }
  6864. /* Populate "methods" with new upb_pbdecodermethod objects reachable from "h".
  6865. * Returns the method for these handlers.
  6866. *
  6867. * Generates a new method for every destination handlers reachable from "h". */
  6868. static void find_methods(compiler *c, const upb_handlers *h) {
  6869. upb_value v;
  6870. upb_msg_field_iter i;
  6871. const upb_msgdef *md;
  6872. if (upb_inttable_lookupptr(&c->group->methods, h, &v))
  6873. return;
  6874. newmethod(h, c->group);
  6875. /* Find submethods. */
  6876. md = upb_handlers_msgdef(h);
  6877. for(upb_msg_field_begin(&i, md);
  6878. !upb_msg_field_done(&i);
  6879. upb_msg_field_next(&i)) {
  6880. const upb_fielddef *f = upb_msg_iter_field(&i);
  6881. const upb_handlers *sub_h;
  6882. if (upb_fielddef_type(f) == UPB_TYPE_MESSAGE &&
  6883. (sub_h = upb_handlers_getsubhandlers(h, f)) != NULL) {
  6884. /* We only generate a decoder method for submessages with handlers.
  6885. * Others will be parsed as unknown fields. */
  6886. find_methods(c, sub_h);
  6887. }
  6888. }
  6889. }
  6890. /* (Re-)compile bytecode for all messages in "msgs."
  6891. * Overwrites any existing bytecode in "c". */
  6892. static void compile_methods(compiler *c) {
  6893. upb_inttable_iter i;
  6894. /* Start over at the beginning of the bytecode. */
  6895. c->pc = c->group->bytecode;
  6896. upb_inttable_begin(&i, &c->group->methods);
  6897. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  6898. upb_pbdecodermethod *method = upb_value_getptr(upb_inttable_iter_value(&i));
  6899. compile_method(c, method);
  6900. }
  6901. }
  6902. static void set_bytecode_handlers(mgroup *g) {
  6903. upb_inttable_iter i;
  6904. upb_inttable_begin(&i, &g->methods);
  6905. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  6906. upb_pbdecodermethod *m = upb_value_getptr(upb_inttable_iter_value(&i));
  6907. upb_byteshandler *h = &m->input_handler_;
  6908. m->code_base.ptr = g->bytecode + m->code_base.ofs;
  6909. upb_byteshandler_setstartstr(h, upb_pbdecoder_startbc, m->code_base.ptr);
  6910. upb_byteshandler_setstring(h, upb_pbdecoder_decode, g);
  6911. upb_byteshandler_setendstr(h, upb_pbdecoder_end, m);
  6912. }
  6913. }
  6914. /* JIT setup. *****************************************************************/
  6915. #ifdef UPB_USE_JIT_X64
  6916. static void sethandlers(mgroup *g, bool allowjit) {
  6917. g->jit_code = NULL;
  6918. if (allowjit) {
  6919. /* Compile byte-code into machine code, create handlers. */
  6920. upb_pbdecoder_jit(g);
  6921. } else {
  6922. set_bytecode_handlers(g);
  6923. }
  6924. }
  6925. #else /* UPB_USE_JIT_X64 */
  6926. static void sethandlers(mgroup *g, bool allowjit) {
  6927. /* No JIT compiled in; use bytecode handlers unconditionally. */
  6928. UPB_UNUSED(allowjit);
  6929. set_bytecode_handlers(g);
  6930. }
  6931. #endif /* UPB_USE_JIT_X64 */
  6932. /* TODO(haberman): allow this to be constructed for an arbitrary set of dest
  6933. * handlers and other mgroups (but verify we have a transitive closure). */
  6934. const mgroup *mgroup_new(const upb_handlers *dest, bool allowjit, bool lazy,
  6935. const void *owner) {
  6936. mgroup *g;
  6937. compiler *c;
  6938. UPB_UNUSED(allowjit);
  6939. assert(upb_handlers_isfrozen(dest));
  6940. g = newgroup(owner);
  6941. c = newcompiler(g, lazy);
  6942. find_methods(c, dest);
  6943. /* We compile in two passes:
  6944. * 1. all messages are assigned relative offsets from the beginning of the
  6945. * bytecode (saved in method->code_base).
  6946. * 2. forwards OP_CALL instructions can be correctly linked since message
  6947. * offsets have been previously assigned.
  6948. *
  6949. * Could avoid the second pass by linking OP_CALL instructions somehow. */
  6950. compile_methods(c);
  6951. compile_methods(c);
  6952. g->bytecode_end = c->pc;
  6953. freecompiler(c);
  6954. #ifdef UPB_DUMP_BYTECODE
  6955. {
  6956. FILE *f = fopen("/tmp/upb-bytecode", "w");
  6957. assert(f);
  6958. dumpbc(g->bytecode, g->bytecode_end, stderr);
  6959. dumpbc(g->bytecode, g->bytecode_end, f);
  6960. fclose(f);
  6961. f = fopen("/tmp/upb-bytecode.bin", "wb");
  6962. assert(f);
  6963. fwrite(g->bytecode, 1, g->bytecode_end - g->bytecode, f);
  6964. fclose(f);
  6965. }
  6966. #endif
  6967. sethandlers(g, allowjit);
  6968. return g;
  6969. }
  6970. /* upb_pbcodecache ************************************************************/
  6971. void upb_pbcodecache_init(upb_pbcodecache *c) {
  6972. upb_inttable_init(&c->groups, UPB_CTYPE_CONSTPTR);
  6973. c->allow_jit_ = true;
  6974. }
  6975. void upb_pbcodecache_uninit(upb_pbcodecache *c) {
  6976. upb_inttable_iter i;
  6977. upb_inttable_begin(&i, &c->groups);
  6978. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  6979. const mgroup *group = upb_value_getconstptr(upb_inttable_iter_value(&i));
  6980. mgroup_unref(group, c);
  6981. }
  6982. upb_inttable_uninit(&c->groups);
  6983. }
  6984. bool upb_pbcodecache_allowjit(const upb_pbcodecache *c) {
  6985. return c->allow_jit_;
  6986. }
  6987. bool upb_pbcodecache_setallowjit(upb_pbcodecache *c, bool allow) {
  6988. if (upb_inttable_count(&c->groups) > 0)
  6989. return false;
  6990. c->allow_jit_ = allow;
  6991. return true;
  6992. }
  6993. const upb_pbdecodermethod *upb_pbcodecache_getdecodermethod(
  6994. upb_pbcodecache *c, const upb_pbdecodermethodopts *opts) {
  6995. upb_value v;
  6996. bool ok;
  6997. /* Right now we build a new DecoderMethod every time.
  6998. * TODO(haberman): properly cache methods by their true key. */
  6999. const mgroup *g = mgroup_new(opts->handlers, c->allow_jit_, opts->lazy, c);
  7000. upb_inttable_push(&c->groups, upb_value_constptr(g));
  7001. ok = upb_inttable_lookupptr(&g->methods, opts->handlers, &v);
  7002. UPB_ASSERT_VAR(ok, ok);
  7003. return upb_value_getptr(v);
  7004. }
  7005. /* upb_pbdecodermethodopts ****************************************************/
  7006. void upb_pbdecodermethodopts_init(upb_pbdecodermethodopts *opts,
  7007. const upb_handlers *h) {
  7008. opts->handlers = h;
  7009. opts->lazy = false;
  7010. }
  7011. void upb_pbdecodermethodopts_setlazy(upb_pbdecodermethodopts *opts, bool lazy) {
  7012. opts->lazy = lazy;
  7013. }
  7014. /*
  7015. ** upb::Decoder (Bytecode Decoder VM)
  7016. **
  7017. ** Bytecode must previously have been generated using the bytecode compiler in
  7018. ** compile_decoder.c. This decoder then walks through the bytecode op-by-op to
  7019. ** parse the input.
  7020. **
  7021. ** Decoding is fully resumable; we just keep a pointer to the current bytecode
  7022. ** instruction and resume from there. A fair amount of the logic here is to
  7023. ** handle the fact that values can span buffer seams and we have to be able to
  7024. ** be capable of suspending/resuming from any byte in the stream. This
  7025. ** sometimes requires keeping a few trailing bytes from the last buffer around
  7026. ** in the "residual" buffer.
  7027. */
  7028. #include <inttypes.h>
  7029. #include <stddef.h>
  7030. #ifdef UPB_DUMP_BYTECODE
  7031. #include <stdio.h>
  7032. #endif
  7033. #define CHECK_SUSPEND(x) if (!(x)) return upb_pbdecoder_suspend(d);
  7034. /* Error messages that are shared between the bytecode and JIT decoders. */
  7035. const char *kPbDecoderStackOverflow = "Nesting too deep.";
  7036. const char *kPbDecoderSubmessageTooLong =
  7037. "Submessage end extends past enclosing submessage.";
  7038. /* Error messages shared within this file. */
  7039. static const char *kUnterminatedVarint = "Unterminated varint.";
  7040. /* upb_pbdecoder **************************************************************/
  7041. static opcode halt = OP_HALT;
  7042. /* A dummy character we can point to when the user passes us a NULL buffer.
  7043. * We need this because in C (NULL + 0) and (NULL - NULL) are undefined
  7044. * behavior, which would invalidate functions like curbufleft(). */
  7045. static const char dummy_char;
  7046. /* Whether an op consumes any of the input buffer. */
  7047. static bool consumes_input(opcode op) {
  7048. switch (op) {
  7049. case OP_SETDISPATCH:
  7050. case OP_STARTMSG:
  7051. case OP_ENDMSG:
  7052. case OP_STARTSEQ:
  7053. case OP_ENDSEQ:
  7054. case OP_STARTSUBMSG:
  7055. case OP_ENDSUBMSG:
  7056. case OP_STARTSTR:
  7057. case OP_ENDSTR:
  7058. case OP_PUSHTAGDELIM:
  7059. case OP_POP:
  7060. case OP_SETDELIM:
  7061. case OP_SETBIGGROUPNUM:
  7062. case OP_CHECKDELIM:
  7063. case OP_CALL:
  7064. case OP_RET:
  7065. case OP_BRANCH:
  7066. return false;
  7067. default:
  7068. return true;
  7069. }
  7070. }
  7071. static size_t stacksize(upb_pbdecoder *d, size_t entries) {
  7072. UPB_UNUSED(d);
  7073. return entries * sizeof(upb_pbdecoder_frame);
  7074. }
  7075. static size_t callstacksize(upb_pbdecoder *d, size_t entries) {
  7076. UPB_UNUSED(d);
  7077. #ifdef UPB_USE_JIT_X64
  7078. if (d->method_->is_native_) {
  7079. /* Each native stack frame needs two pointers, plus we need a few frames for
  7080. * the enter/exit trampolines. */
  7081. size_t ret = entries * sizeof(void*) * 2;
  7082. ret += sizeof(void*) * 10;
  7083. return ret;
  7084. }
  7085. #endif
  7086. return entries * sizeof(uint32_t*);
  7087. }
  7088. static bool in_residual_buf(const upb_pbdecoder *d, const char *p);
  7089. /* It's unfortunate that we have to micro-manage the compiler with
  7090. * UPB_FORCEINLINE and UPB_NOINLINE, especially since this tuning is necessarily
  7091. * specific to one hardware configuration. But empirically on a Core i7,
  7092. * performance increases 30-50% with these annotations. Every instance where
  7093. * these appear, gcc 4.2.1 made the wrong decision and degraded performance in
  7094. * benchmarks. */
  7095. static void seterr(upb_pbdecoder *d, const char *msg) {
  7096. upb_status status = UPB_STATUS_INIT;
  7097. upb_status_seterrmsg(&status, msg);
  7098. upb_env_reporterror(d->env, &status);
  7099. }
  7100. void upb_pbdecoder_seterr(upb_pbdecoder *d, const char *msg) {
  7101. seterr(d, msg);
  7102. }
  7103. /* Buffering ******************************************************************/
  7104. /* We operate on one buffer at a time, which is either the user's buffer passed
  7105. * to our "decode" callback or some residual bytes from the previous buffer. */
  7106. /* How many bytes can be safely read from d->ptr without reading past end-of-buf
  7107. * or past the current delimited end. */
  7108. static size_t curbufleft(const upb_pbdecoder *d) {
  7109. assert(d->data_end >= d->ptr);
  7110. return d->data_end - d->ptr;
  7111. }
  7112. /* How many bytes are available before end-of-buffer. */
  7113. static size_t bufleft(const upb_pbdecoder *d) {
  7114. return d->end - d->ptr;
  7115. }
  7116. /* Overall stream offset of d->ptr. */
  7117. uint64_t offset(const upb_pbdecoder *d) {
  7118. return d->bufstart_ofs + (d->ptr - d->buf);
  7119. }
  7120. /* How many bytes are available before the end of this delimited region. */
  7121. size_t delim_remaining(const upb_pbdecoder *d) {
  7122. return d->top->end_ofs - offset(d);
  7123. }
  7124. /* Advances d->ptr. */
  7125. static void advance(upb_pbdecoder *d, size_t len) {
  7126. assert(curbufleft(d) >= len);
  7127. d->ptr += len;
  7128. }
  7129. static bool in_buf(const char *p, const char *buf, const char *end) {
  7130. return p >= buf && p <= end;
  7131. }
  7132. static bool in_residual_buf(const upb_pbdecoder *d, const char *p) {
  7133. return in_buf(p, d->residual, d->residual_end);
  7134. }
  7135. /* Calculates the delim_end value, which is affected by both the current buffer
  7136. * and the parsing stack, so must be called whenever either is updated. */
  7137. static void set_delim_end(upb_pbdecoder *d) {
  7138. size_t delim_ofs = d->top->end_ofs - d->bufstart_ofs;
  7139. if (delim_ofs <= (size_t)(d->end - d->buf)) {
  7140. d->delim_end = d->buf + delim_ofs;
  7141. d->data_end = d->delim_end;
  7142. } else {
  7143. d->data_end = d->end;
  7144. d->delim_end = NULL;
  7145. }
  7146. }
  7147. static void switchtobuf(upb_pbdecoder *d, const char *buf, const char *end) {
  7148. d->ptr = buf;
  7149. d->buf = buf;
  7150. d->end = end;
  7151. set_delim_end(d);
  7152. }
  7153. static void advancetobuf(upb_pbdecoder *d, const char *buf, size_t len) {
  7154. assert(curbufleft(d) == 0);
  7155. d->bufstart_ofs += (d->end - d->buf);
  7156. switchtobuf(d, buf, buf + len);
  7157. }
  7158. static void checkpoint(upb_pbdecoder *d) {
  7159. /* The assertion here is in the interests of efficiency, not correctness.
  7160. * We are trying to ensure that we don't checkpoint() more often than
  7161. * necessary. */
  7162. assert(d->checkpoint != d->ptr);
  7163. d->checkpoint = d->ptr;
  7164. }
  7165. /* Skips "bytes" bytes in the stream, which may be more than available. If we
  7166. * skip more bytes than are available, we return a long read count to the caller
  7167. * indicating how many bytes can be skipped over before passing actual data
  7168. * again. Skipped bytes can pass a NULL buffer and the decoder guarantees they
  7169. * won't actually be read.
  7170. */
  7171. static int32_t skip(upb_pbdecoder *d, size_t bytes) {
  7172. assert(!in_residual_buf(d, d->ptr) || d->size_param == 0);
  7173. assert(d->skip == 0);
  7174. if (bytes > delim_remaining(d)) {
  7175. seterr(d, "Skipped value extended beyond enclosing submessage.");
  7176. return upb_pbdecoder_suspend(d);
  7177. } else if (bufleft(d) >= bytes) {
  7178. /* Skipped data is all in current buffer, and more is still available. */
  7179. advance(d, bytes);
  7180. d->skip = 0;
  7181. return DECODE_OK;
  7182. } else {
  7183. /* Skipped data extends beyond currently available buffers. */
  7184. d->pc = d->last;
  7185. d->skip = bytes - curbufleft(d);
  7186. d->bufstart_ofs += (d->end - d->buf);
  7187. d->residual_end = d->residual;
  7188. switchtobuf(d, d->residual, d->residual_end);
  7189. return d->size_param + d->skip;
  7190. }
  7191. }
  7192. /* Resumes the decoder from an initial state or from a previous suspend. */
  7193. int32_t upb_pbdecoder_resume(upb_pbdecoder *d, void *p, const char *buf,
  7194. size_t size, const upb_bufhandle *handle) {
  7195. UPB_UNUSED(p); /* Useless; just for the benefit of the JIT. */
  7196. /* d->skip and d->residual_end could probably elegantly be represented
  7197. * as a single variable, to more easily represent this invariant. */
  7198. assert(!(d->skip && d->residual_end > d->residual));
  7199. /* We need to remember the original size_param, so that the value we return
  7200. * is relative to it, even if we do some skipping first. */
  7201. d->size_param = size;
  7202. d->handle = handle;
  7203. /* Have to handle this case specially (ie. not with skip()) because the user
  7204. * is allowed to pass a NULL buffer here, which won't allow us to safely
  7205. * calculate a d->end or use our normal functions like curbufleft(). */
  7206. if (d->skip && d->skip >= size) {
  7207. d->skip -= size;
  7208. d->bufstart_ofs += size;
  7209. buf = &dummy_char;
  7210. size = 0;
  7211. /* We can't just return now, because we might need to execute some ops
  7212. * like CHECKDELIM, which could call some callbacks and pop the stack. */
  7213. }
  7214. /* We need to pretend that this was the actual buffer param, since some of the
  7215. * calculations assume that d->ptr/d->buf is relative to this. */
  7216. d->buf_param = buf;
  7217. if (!buf) {
  7218. /* NULL buf is ok if its entire span is covered by the "skip" above, but
  7219. * by this point we know that "skip" doesn't cover the buffer. */
  7220. seterr(d, "Passed NULL buffer over non-skippable region.");
  7221. return upb_pbdecoder_suspend(d);
  7222. }
  7223. if (d->residual_end > d->residual) {
  7224. /* We have residual bytes from the last buffer. */
  7225. assert(d->ptr == d->residual);
  7226. } else {
  7227. switchtobuf(d, buf, buf + size);
  7228. }
  7229. d->checkpoint = d->ptr;
  7230. /* Handle skips that don't cover the whole buffer (as above). */
  7231. if (d->skip) {
  7232. size_t skip_bytes = d->skip;
  7233. d->skip = 0;
  7234. CHECK_RETURN(skip(d, skip_bytes));
  7235. checkpoint(d);
  7236. }
  7237. /* If we're inside an unknown group, continue to parse unknown values. */
  7238. if (d->top->groupnum < 0) {
  7239. CHECK_RETURN(upb_pbdecoder_skipunknown(d, -1, 0));
  7240. checkpoint(d);
  7241. }
  7242. return DECODE_OK;
  7243. }
  7244. /* Suspends the decoder at the last checkpoint, without saving any residual
  7245. * bytes. If there are any unconsumed bytes, returns a short byte count. */
  7246. size_t upb_pbdecoder_suspend(upb_pbdecoder *d) {
  7247. d->pc = d->last;
  7248. if (d->checkpoint == d->residual) {
  7249. /* Checkpoint was in residual buf; no user bytes were consumed. */
  7250. d->ptr = d->residual;
  7251. return 0;
  7252. } else {
  7253. size_t ret = d->size_param - (d->end - d->checkpoint);
  7254. assert(!in_residual_buf(d, d->checkpoint));
  7255. assert(d->buf == d->buf_param || d->buf == &dummy_char);
  7256. d->bufstart_ofs += (d->checkpoint - d->buf);
  7257. d->residual_end = d->residual;
  7258. switchtobuf(d, d->residual, d->residual_end);
  7259. return ret;
  7260. }
  7261. }
  7262. /* Suspends the decoder at the last checkpoint, and saves any unconsumed
  7263. * bytes in our residual buffer. This is necessary if we need more user
  7264. * bytes to form a complete value, which might not be contiguous in the
  7265. * user's buffers. Always consumes all user bytes. */
  7266. static size_t suspend_save(upb_pbdecoder *d) {
  7267. /* We hit end-of-buffer before we could parse a full value.
  7268. * Save any unconsumed bytes (if any) to the residual buffer. */
  7269. d->pc = d->last;
  7270. if (d->checkpoint == d->residual) {
  7271. /* Checkpoint was in residual buf; append user byte(s) to residual buf. */
  7272. assert((d->residual_end - d->residual) + d->size_param <=
  7273. sizeof(d->residual));
  7274. if (!in_residual_buf(d, d->ptr)) {
  7275. d->bufstart_ofs -= (d->residual_end - d->residual);
  7276. }
  7277. memcpy(d->residual_end, d->buf_param, d->size_param);
  7278. d->residual_end += d->size_param;
  7279. } else {
  7280. /* Checkpoint was in user buf; old residual bytes not needed. */
  7281. size_t save;
  7282. assert(!in_residual_buf(d, d->checkpoint));
  7283. d->ptr = d->checkpoint;
  7284. save = curbufleft(d);
  7285. assert(save <= sizeof(d->residual));
  7286. memcpy(d->residual, d->ptr, save);
  7287. d->residual_end = d->residual + save;
  7288. d->bufstart_ofs = offset(d);
  7289. }
  7290. switchtobuf(d, d->residual, d->residual_end);
  7291. return d->size_param;
  7292. }
  7293. /* Copies the next "bytes" bytes into "buf" and advances the stream.
  7294. * Requires that this many bytes are available in the current buffer. */
  7295. UPB_FORCEINLINE static void consumebytes(upb_pbdecoder *d, void *buf,
  7296. size_t bytes) {
  7297. assert(bytes <= curbufleft(d));
  7298. memcpy(buf, d->ptr, bytes);
  7299. advance(d, bytes);
  7300. }
  7301. /* Slow path for getting the next "bytes" bytes, regardless of whether they are
  7302. * available in the current buffer or not. Returns a status code as described
  7303. * in decoder.int.h. */
  7304. UPB_NOINLINE static int32_t getbytes_slow(upb_pbdecoder *d, void *buf,
  7305. size_t bytes) {
  7306. const size_t avail = curbufleft(d);
  7307. consumebytes(d, buf, avail);
  7308. bytes -= avail;
  7309. assert(bytes > 0);
  7310. if (in_residual_buf(d, d->ptr)) {
  7311. advancetobuf(d, d->buf_param, d->size_param);
  7312. }
  7313. if (curbufleft(d) >= bytes) {
  7314. consumebytes(d, (char *)buf + avail, bytes);
  7315. return DECODE_OK;
  7316. } else if (d->data_end == d->delim_end) {
  7317. seterr(d, "Submessage ended in the middle of a value or group");
  7318. return upb_pbdecoder_suspend(d);
  7319. } else {
  7320. return suspend_save(d);
  7321. }
  7322. }
  7323. /* Gets the next "bytes" bytes, regardless of whether they are available in the
  7324. * current buffer or not. Returns a status code as described in decoder.int.h.
  7325. */
  7326. UPB_FORCEINLINE static int32_t getbytes(upb_pbdecoder *d, void *buf,
  7327. size_t bytes) {
  7328. if (curbufleft(d) >= bytes) {
  7329. /* Buffer has enough data to satisfy. */
  7330. consumebytes(d, buf, bytes);
  7331. return DECODE_OK;
  7332. } else {
  7333. return getbytes_slow(d, buf, bytes);
  7334. }
  7335. }
  7336. UPB_NOINLINE static size_t peekbytes_slow(upb_pbdecoder *d, void *buf,
  7337. size_t bytes) {
  7338. size_t ret = curbufleft(d);
  7339. memcpy(buf, d->ptr, ret);
  7340. if (in_residual_buf(d, d->ptr)) {
  7341. size_t copy = UPB_MIN(bytes - ret, d->size_param);
  7342. memcpy((char *)buf + ret, d->buf_param, copy);
  7343. ret += copy;
  7344. }
  7345. return ret;
  7346. }
  7347. UPB_FORCEINLINE static size_t peekbytes(upb_pbdecoder *d, void *buf,
  7348. size_t bytes) {
  7349. if (curbufleft(d) >= bytes) {
  7350. memcpy(buf, d->ptr, bytes);
  7351. return bytes;
  7352. } else {
  7353. return peekbytes_slow(d, buf, bytes);
  7354. }
  7355. }
  7356. /* Decoding of wire types *****************************************************/
  7357. /* Slow path for decoding a varint from the current buffer position.
  7358. * Returns a status code as described in decoder.int.h. */
  7359. UPB_NOINLINE int32_t upb_pbdecoder_decode_varint_slow(upb_pbdecoder *d,
  7360. uint64_t *u64) {
  7361. uint8_t byte = 0x80;
  7362. int bitpos;
  7363. *u64 = 0;
  7364. for(bitpos = 0; bitpos < 70 && (byte & 0x80); bitpos += 7) {
  7365. CHECK_RETURN(getbytes(d, &byte, 1));
  7366. *u64 |= (uint64_t)(byte & 0x7F) << bitpos;
  7367. }
  7368. if(bitpos == 70 && (byte & 0x80)) {
  7369. seterr(d, kUnterminatedVarint);
  7370. return upb_pbdecoder_suspend(d);
  7371. }
  7372. return DECODE_OK;
  7373. }
  7374. /* Decodes a varint from the current buffer position.
  7375. * Returns a status code as described in decoder.int.h. */
  7376. UPB_FORCEINLINE static int32_t decode_varint(upb_pbdecoder *d, uint64_t *u64) {
  7377. if (curbufleft(d) > 0 && !(*d->ptr & 0x80)) {
  7378. *u64 = *d->ptr;
  7379. advance(d, 1);
  7380. return DECODE_OK;
  7381. } else if (curbufleft(d) >= 10) {
  7382. /* Fast case. */
  7383. upb_decoderet r = upb_vdecode_fast(d->ptr);
  7384. if (r.p == NULL) {
  7385. seterr(d, kUnterminatedVarint);
  7386. return upb_pbdecoder_suspend(d);
  7387. }
  7388. advance(d, r.p - d->ptr);
  7389. *u64 = r.val;
  7390. return DECODE_OK;
  7391. } else {
  7392. /* Slow case -- varint spans buffer seam. */
  7393. return upb_pbdecoder_decode_varint_slow(d, u64);
  7394. }
  7395. }
  7396. /* Decodes a 32-bit varint from the current buffer position.
  7397. * Returns a status code as described in decoder.int.h. */
  7398. UPB_FORCEINLINE static int32_t decode_v32(upb_pbdecoder *d, uint32_t *u32) {
  7399. uint64_t u64;
  7400. int32_t ret = decode_varint(d, &u64);
  7401. if (ret >= 0) return ret;
  7402. if (u64 > UINT32_MAX) {
  7403. seterr(d, "Unterminated 32-bit varint");
  7404. /* TODO(haberman) guarantee that this function return is >= 0 somehow,
  7405. * so we know this path will always be treated as error by our caller.
  7406. * Right now the size_t -> int32_t can overflow and produce negative values.
  7407. */
  7408. *u32 = 0;
  7409. return upb_pbdecoder_suspend(d);
  7410. }
  7411. *u32 = u64;
  7412. return DECODE_OK;
  7413. }
  7414. /* Decodes a fixed32 from the current buffer position.
  7415. * Returns a status code as described in decoder.int.h.
  7416. * TODO: proper byte swapping for big-endian machines. */
  7417. UPB_FORCEINLINE static int32_t decode_fixed32(upb_pbdecoder *d, uint32_t *u32) {
  7418. return getbytes(d, u32, 4);
  7419. }
  7420. /* Decodes a fixed64 from the current buffer position.
  7421. * Returns a status code as described in decoder.int.h.
  7422. * TODO: proper byte swapping for big-endian machines. */
  7423. UPB_FORCEINLINE static int32_t decode_fixed64(upb_pbdecoder *d, uint64_t *u64) {
  7424. return getbytes(d, u64, 8);
  7425. }
  7426. /* Non-static versions of the above functions.
  7427. * These are called by the JIT for fallback paths. */
  7428. int32_t upb_pbdecoder_decode_f32(upb_pbdecoder *d, uint32_t *u32) {
  7429. return decode_fixed32(d, u32);
  7430. }
  7431. int32_t upb_pbdecoder_decode_f64(upb_pbdecoder *d, uint64_t *u64) {
  7432. return decode_fixed64(d, u64);
  7433. }
  7434. static double as_double(uint64_t n) { double d; memcpy(&d, &n, 8); return d; }
  7435. static float as_float(uint32_t n) { float f; memcpy(&f, &n, 4); return f; }
  7436. /* Pushes a frame onto the decoder stack. */
  7437. static bool decoder_push(upb_pbdecoder *d, uint64_t end) {
  7438. upb_pbdecoder_frame *fr = d->top;
  7439. if (end > fr->end_ofs) {
  7440. seterr(d, kPbDecoderSubmessageTooLong);
  7441. return false;
  7442. } else if (fr == d->limit) {
  7443. seterr(d, kPbDecoderStackOverflow);
  7444. return false;
  7445. }
  7446. fr++;
  7447. fr->end_ofs = end;
  7448. fr->dispatch = NULL;
  7449. fr->groupnum = 0;
  7450. d->top = fr;
  7451. return true;
  7452. }
  7453. static bool pushtagdelim(upb_pbdecoder *d, uint32_t arg) {
  7454. /* While we expect to see an "end" tag (either ENDGROUP or a non-sequence
  7455. * field number) prior to hitting any enclosing submessage end, pushing our
  7456. * existing delim end prevents us from continuing to parse values from a
  7457. * corrupt proto that doesn't give us an END tag in time. */
  7458. if (!decoder_push(d, d->top->end_ofs))
  7459. return false;
  7460. d->top->groupnum = arg;
  7461. return true;
  7462. }
  7463. /* Pops a frame from the decoder stack. */
  7464. static void decoder_pop(upb_pbdecoder *d) { d->top--; }
  7465. UPB_NOINLINE int32_t upb_pbdecoder_checktag_slow(upb_pbdecoder *d,
  7466. uint64_t expected) {
  7467. uint64_t data = 0;
  7468. size_t bytes = upb_value_size(expected);
  7469. size_t read = peekbytes(d, &data, bytes);
  7470. if (read == bytes && data == expected) {
  7471. /* Advance past matched bytes. */
  7472. int32_t ok = getbytes(d, &data, read);
  7473. UPB_ASSERT_VAR(ok, ok < 0);
  7474. return DECODE_OK;
  7475. } else if (read < bytes && memcmp(&data, &expected, read) == 0) {
  7476. return suspend_save(d);
  7477. } else {
  7478. return DECODE_MISMATCH;
  7479. }
  7480. }
  7481. int32_t upb_pbdecoder_skipunknown(upb_pbdecoder *d, int32_t fieldnum,
  7482. uint8_t wire_type) {
  7483. if (fieldnum >= 0)
  7484. goto have_tag;
  7485. while (true) {
  7486. uint32_t tag;
  7487. CHECK_RETURN(decode_v32(d, &tag));
  7488. wire_type = tag & 0x7;
  7489. fieldnum = tag >> 3;
  7490. have_tag:
  7491. if (fieldnum == 0) {
  7492. seterr(d, "Saw invalid field number (0)");
  7493. return upb_pbdecoder_suspend(d);
  7494. }
  7495. /* TODO: deliver to unknown field callback. */
  7496. switch (wire_type) {
  7497. case UPB_WIRE_TYPE_32BIT:
  7498. CHECK_RETURN(skip(d, 4));
  7499. break;
  7500. case UPB_WIRE_TYPE_64BIT:
  7501. CHECK_RETURN(skip(d, 8));
  7502. break;
  7503. case UPB_WIRE_TYPE_VARINT: {
  7504. uint64_t u64;
  7505. CHECK_RETURN(decode_varint(d, &u64));
  7506. break;
  7507. }
  7508. case UPB_WIRE_TYPE_DELIMITED: {
  7509. uint32_t len;
  7510. CHECK_RETURN(decode_v32(d, &len));
  7511. CHECK_RETURN(skip(d, len));
  7512. break;
  7513. }
  7514. case UPB_WIRE_TYPE_START_GROUP:
  7515. CHECK_SUSPEND(pushtagdelim(d, -fieldnum));
  7516. break;
  7517. case UPB_WIRE_TYPE_END_GROUP:
  7518. if (fieldnum == -d->top->groupnum) {
  7519. decoder_pop(d);
  7520. } else if (fieldnum == d->top->groupnum) {
  7521. return DECODE_ENDGROUP;
  7522. } else {
  7523. seterr(d, "Unmatched ENDGROUP tag.");
  7524. return upb_pbdecoder_suspend(d);
  7525. }
  7526. break;
  7527. default:
  7528. seterr(d, "Invalid wire type");
  7529. return upb_pbdecoder_suspend(d);
  7530. }
  7531. if (d->top->groupnum >= 0) {
  7532. return DECODE_OK;
  7533. }
  7534. /* Unknown group -- continue looping over unknown fields. */
  7535. checkpoint(d);
  7536. }
  7537. }
  7538. static void goto_endmsg(upb_pbdecoder *d) {
  7539. upb_value v;
  7540. bool found = upb_inttable_lookup32(d->top->dispatch, DISPATCH_ENDMSG, &v);
  7541. UPB_ASSERT_VAR(found, found);
  7542. d->pc = d->top->base + upb_value_getuint64(v);
  7543. }
  7544. /* Parses a tag and jumps to the corresponding bytecode instruction for this
  7545. * field.
  7546. *
  7547. * If the tag is unknown (or the wire type doesn't match), parses the field as
  7548. * unknown. If the tag is a valid ENDGROUP tag, jumps to the bytecode
  7549. * instruction for the end of message. */
  7550. static int32_t dispatch(upb_pbdecoder *d) {
  7551. upb_inttable *dispatch = d->top->dispatch;
  7552. uint32_t tag;
  7553. uint8_t wire_type;
  7554. uint32_t fieldnum;
  7555. upb_value val;
  7556. int32_t retval;
  7557. /* Decode tag. */
  7558. CHECK_RETURN(decode_v32(d, &tag));
  7559. wire_type = tag & 0x7;
  7560. fieldnum = tag >> 3;
  7561. /* Lookup tag. Because of packed/non-packed compatibility, we have to
  7562. * check the wire type against two possibilities. */
  7563. if (fieldnum != DISPATCH_ENDMSG &&
  7564. upb_inttable_lookup32(dispatch, fieldnum, &val)) {
  7565. uint64_t v = upb_value_getuint64(val);
  7566. if (wire_type == (v & 0xff)) {
  7567. d->pc = d->top->base + (v >> 16);
  7568. return DECODE_OK;
  7569. } else if (wire_type == ((v >> 8) & 0xff)) {
  7570. bool found =
  7571. upb_inttable_lookup(dispatch, fieldnum + UPB_MAX_FIELDNUMBER, &val);
  7572. UPB_ASSERT_VAR(found, found);
  7573. d->pc = d->top->base + upb_value_getuint64(val);
  7574. return DECODE_OK;
  7575. }
  7576. }
  7577. /* We have some unknown fields (or ENDGROUP) to parse. The DISPATCH or TAG
  7578. * bytecode that triggered this is preceded by a CHECKDELIM bytecode which
  7579. * we need to back up to, so that when we're done skipping unknown data we
  7580. * can re-check the delimited end. */
  7581. d->last--; /* Necessary if we get suspended */
  7582. d->pc = d->last;
  7583. assert(getop(*d->last) == OP_CHECKDELIM);
  7584. /* Unknown field or ENDGROUP. */
  7585. retval = upb_pbdecoder_skipunknown(d, fieldnum, wire_type);
  7586. CHECK_RETURN(retval);
  7587. if (retval == DECODE_ENDGROUP) {
  7588. goto_endmsg(d);
  7589. return DECODE_OK;
  7590. }
  7591. return DECODE_OK;
  7592. }
  7593. /* Callers know that the stack is more than one deep because the opcodes that
  7594. * call this only occur after PUSH operations. */
  7595. upb_pbdecoder_frame *outer_frame(upb_pbdecoder *d) {
  7596. assert(d->top != d->stack);
  7597. return d->top - 1;
  7598. }
  7599. /* The main decoding loop *****************************************************/
  7600. /* The main decoder VM function. Uses traditional bytecode dispatch loop with a
  7601. * switch() statement. */
  7602. size_t run_decoder_vm(upb_pbdecoder *d, const mgroup *group,
  7603. const upb_bufhandle* handle) {
  7604. #define VMCASE(op, code) \
  7605. case op: { code; if (consumes_input(op)) checkpoint(d); break; }
  7606. #define PRIMITIVE_OP(type, wt, name, convfunc, ctype) \
  7607. VMCASE(OP_PARSE_ ## type, { \
  7608. ctype val; \
  7609. CHECK_RETURN(decode_ ## wt(d, &val)); \
  7610. upb_sink_put ## name(&d->top->sink, arg, (convfunc)(val)); \
  7611. })
  7612. while(1) {
  7613. int32_t instruction;
  7614. opcode op;
  7615. uint32_t arg;
  7616. int32_t longofs;
  7617. d->last = d->pc;
  7618. instruction = *d->pc++;
  7619. op = getop(instruction);
  7620. arg = instruction >> 8;
  7621. longofs = arg;
  7622. assert(d->ptr != d->residual_end);
  7623. UPB_UNUSED(group);
  7624. #ifdef UPB_DUMP_BYTECODE
  7625. fprintf(stderr, "s_ofs=%d buf_ofs=%d data_rem=%d buf_rem=%d delim_rem=%d "
  7626. "%x %s (%d)\n",
  7627. (int)offset(d),
  7628. (int)(d->ptr - d->buf),
  7629. (int)(d->data_end - d->ptr),
  7630. (int)(d->end - d->ptr),
  7631. (int)((d->top->end_ofs - d->bufstart_ofs) - (d->ptr - d->buf)),
  7632. (int)(d->pc - 1 - group->bytecode),
  7633. upb_pbdecoder_getopname(op),
  7634. arg);
  7635. #endif
  7636. switch (op) {
  7637. /* Technically, we are losing data if we see a 32-bit varint that is not
  7638. * properly sign-extended. We could detect this and error about the data
  7639. * loss, but proto2 does not do this, so we pass. */
  7640. PRIMITIVE_OP(INT32, varint, int32, int32_t, uint64_t)
  7641. PRIMITIVE_OP(INT64, varint, int64, int64_t, uint64_t)
  7642. PRIMITIVE_OP(UINT32, varint, uint32, uint32_t, uint64_t)
  7643. PRIMITIVE_OP(UINT64, varint, uint64, uint64_t, uint64_t)
  7644. PRIMITIVE_OP(FIXED32, fixed32, uint32, uint32_t, uint32_t)
  7645. PRIMITIVE_OP(FIXED64, fixed64, uint64, uint64_t, uint64_t)
  7646. PRIMITIVE_OP(SFIXED32, fixed32, int32, int32_t, uint32_t)
  7647. PRIMITIVE_OP(SFIXED64, fixed64, int64, int64_t, uint64_t)
  7648. PRIMITIVE_OP(BOOL, varint, bool, bool, uint64_t)
  7649. PRIMITIVE_OP(DOUBLE, fixed64, double, as_double, uint64_t)
  7650. PRIMITIVE_OP(FLOAT, fixed32, float, as_float, uint32_t)
  7651. PRIMITIVE_OP(SINT32, varint, int32, upb_zzdec_32, uint64_t)
  7652. PRIMITIVE_OP(SINT64, varint, int64, upb_zzdec_64, uint64_t)
  7653. VMCASE(OP_SETDISPATCH,
  7654. d->top->base = d->pc - 1;
  7655. memcpy(&d->top->dispatch, d->pc, sizeof(void*));
  7656. d->pc += sizeof(void*) / sizeof(uint32_t);
  7657. )
  7658. VMCASE(OP_STARTMSG,
  7659. CHECK_SUSPEND(upb_sink_startmsg(&d->top->sink));
  7660. )
  7661. VMCASE(OP_ENDMSG,
  7662. CHECK_SUSPEND(upb_sink_endmsg(&d->top->sink, d->status));
  7663. )
  7664. VMCASE(OP_STARTSEQ,
  7665. upb_pbdecoder_frame *outer = outer_frame(d);
  7666. CHECK_SUSPEND(upb_sink_startseq(&outer->sink, arg, &d->top->sink));
  7667. )
  7668. VMCASE(OP_ENDSEQ,
  7669. CHECK_SUSPEND(upb_sink_endseq(&d->top->sink, arg));
  7670. )
  7671. VMCASE(OP_STARTSUBMSG,
  7672. upb_pbdecoder_frame *outer = outer_frame(d);
  7673. CHECK_SUSPEND(upb_sink_startsubmsg(&outer->sink, arg, &d->top->sink));
  7674. )
  7675. VMCASE(OP_ENDSUBMSG,
  7676. CHECK_SUSPEND(upb_sink_endsubmsg(&d->top->sink, arg));
  7677. )
  7678. VMCASE(OP_STARTSTR,
  7679. uint32_t len = delim_remaining(d);
  7680. upb_pbdecoder_frame *outer = outer_frame(d);
  7681. CHECK_SUSPEND(upb_sink_startstr(&outer->sink, arg, len, &d->top->sink));
  7682. if (len == 0) {
  7683. d->pc++; /* Skip OP_STRING. */
  7684. }
  7685. )
  7686. VMCASE(OP_STRING,
  7687. uint32_t len = curbufleft(d);
  7688. size_t n = upb_sink_putstring(&d->top->sink, arg, d->ptr, len, handle);
  7689. if (n > len) {
  7690. if (n > delim_remaining(d)) {
  7691. seterr(d, "Tried to skip past end of string.");
  7692. return upb_pbdecoder_suspend(d);
  7693. } else {
  7694. int32_t ret = skip(d, n);
  7695. /* This shouldn't return DECODE_OK, because n > len. */
  7696. assert(ret >= 0);
  7697. return ret;
  7698. }
  7699. }
  7700. advance(d, n);
  7701. if (n < len || d->delim_end == NULL) {
  7702. /* We aren't finished with this string yet. */
  7703. d->pc--; /* Repeat OP_STRING. */
  7704. if (n > 0) checkpoint(d);
  7705. return upb_pbdecoder_suspend(d);
  7706. }
  7707. )
  7708. VMCASE(OP_ENDSTR,
  7709. CHECK_SUSPEND(upb_sink_endstr(&d->top->sink, arg));
  7710. )
  7711. VMCASE(OP_PUSHTAGDELIM,
  7712. CHECK_SUSPEND(pushtagdelim(d, arg));
  7713. )
  7714. VMCASE(OP_SETBIGGROUPNUM,
  7715. d->top->groupnum = *d->pc++;
  7716. )
  7717. VMCASE(OP_POP,
  7718. assert(d->top > d->stack);
  7719. decoder_pop(d);
  7720. )
  7721. VMCASE(OP_PUSHLENDELIM,
  7722. uint32_t len;
  7723. CHECK_RETURN(decode_v32(d, &len));
  7724. CHECK_SUSPEND(decoder_push(d, offset(d) + len));
  7725. set_delim_end(d);
  7726. )
  7727. VMCASE(OP_SETDELIM,
  7728. set_delim_end(d);
  7729. )
  7730. VMCASE(OP_CHECKDELIM,
  7731. /* We are guaranteed of this assert because we never allow ourselves to
  7732. * consume bytes beyond data_end, which covers delim_end when non-NULL.
  7733. */
  7734. assert(!(d->delim_end && d->ptr > d->delim_end));
  7735. if (d->ptr == d->delim_end)
  7736. d->pc += longofs;
  7737. )
  7738. VMCASE(OP_CALL,
  7739. d->callstack[d->call_len++] = d->pc;
  7740. d->pc += longofs;
  7741. )
  7742. VMCASE(OP_RET,
  7743. assert(d->call_len > 0);
  7744. d->pc = d->callstack[--d->call_len];
  7745. )
  7746. VMCASE(OP_BRANCH,
  7747. d->pc += longofs;
  7748. )
  7749. VMCASE(OP_TAG1,
  7750. uint8_t expected;
  7751. CHECK_SUSPEND(curbufleft(d) > 0);
  7752. expected = (arg >> 8) & 0xff;
  7753. if (*d->ptr == expected) {
  7754. advance(d, 1);
  7755. } else {
  7756. int8_t shortofs;
  7757. badtag:
  7758. shortofs = arg;
  7759. if (shortofs == LABEL_DISPATCH) {
  7760. CHECK_RETURN(dispatch(d));
  7761. } else {
  7762. d->pc += shortofs;
  7763. break; /* Avoid checkpoint(). */
  7764. }
  7765. }
  7766. )
  7767. VMCASE(OP_TAG2,
  7768. uint16_t expected;
  7769. CHECK_SUSPEND(curbufleft(d) > 0);
  7770. expected = (arg >> 8) & 0xffff;
  7771. if (curbufleft(d) >= 2) {
  7772. uint16_t actual;
  7773. memcpy(&actual, d->ptr, 2);
  7774. if (expected == actual) {
  7775. advance(d, 2);
  7776. } else {
  7777. goto badtag;
  7778. }
  7779. } else {
  7780. int32_t result = upb_pbdecoder_checktag_slow(d, expected);
  7781. if (result == DECODE_MISMATCH) goto badtag;
  7782. if (result >= 0) return result;
  7783. }
  7784. )
  7785. VMCASE(OP_TAGN, {
  7786. uint64_t expected;
  7787. int32_t result;
  7788. memcpy(&expected, d->pc, 8);
  7789. d->pc += 2;
  7790. result = upb_pbdecoder_checktag_slow(d, expected);
  7791. if (result == DECODE_MISMATCH) goto badtag;
  7792. if (result >= 0) return result;
  7793. })
  7794. VMCASE(OP_DISPATCH, {
  7795. CHECK_RETURN(dispatch(d));
  7796. })
  7797. VMCASE(OP_HALT, {
  7798. return d->size_param;
  7799. })
  7800. }
  7801. }
  7802. }
  7803. /* BytesHandler handlers ******************************************************/
  7804. void *upb_pbdecoder_startbc(void *closure, const void *pc, size_t size_hint) {
  7805. upb_pbdecoder *d = closure;
  7806. UPB_UNUSED(size_hint);
  7807. d->top->end_ofs = UINT64_MAX;
  7808. d->bufstart_ofs = 0;
  7809. d->call_len = 1;
  7810. d->callstack[0] = &halt;
  7811. d->pc = pc;
  7812. d->skip = 0;
  7813. return d;
  7814. }
  7815. void *upb_pbdecoder_startjit(void *closure, const void *hd, size_t size_hint) {
  7816. upb_pbdecoder *d = closure;
  7817. UPB_UNUSED(hd);
  7818. UPB_UNUSED(size_hint);
  7819. d->top->end_ofs = UINT64_MAX;
  7820. d->bufstart_ofs = 0;
  7821. d->call_len = 0;
  7822. d->skip = 0;
  7823. return d;
  7824. }
  7825. bool upb_pbdecoder_end(void *closure, const void *handler_data) {
  7826. upb_pbdecoder *d = closure;
  7827. const upb_pbdecodermethod *method = handler_data;
  7828. uint64_t end;
  7829. char dummy;
  7830. if (d->residual_end > d->residual) {
  7831. seterr(d, "Unexpected EOF: decoder still has buffered unparsed data");
  7832. return false;
  7833. }
  7834. if (d->skip) {
  7835. seterr(d, "Unexpected EOF inside skipped data");
  7836. return false;
  7837. }
  7838. if (d->top->end_ofs != UINT64_MAX) {
  7839. seterr(d, "Unexpected EOF inside delimited string");
  7840. return false;
  7841. }
  7842. /* The user's end() call indicates that the message ends here. */
  7843. end = offset(d);
  7844. d->top->end_ofs = end;
  7845. #ifdef UPB_USE_JIT_X64
  7846. if (method->is_native_) {
  7847. const mgroup *group = (const mgroup*)method->group;
  7848. if (d->top != d->stack)
  7849. d->stack->end_ofs = 0;
  7850. group->jit_code(closure, method->code_base.ptr, &dummy, 0, NULL);
  7851. } else
  7852. #endif
  7853. {
  7854. const uint32_t *p = d->pc;
  7855. d->stack->end_ofs = end;
  7856. /* Check the previous bytecode, but guard against beginning. */
  7857. if (p != method->code_base.ptr) p--;
  7858. if (getop(*p) == OP_CHECKDELIM) {
  7859. /* Rewind from OP_TAG* to OP_CHECKDELIM. */
  7860. assert(getop(*d->pc) == OP_TAG1 ||
  7861. getop(*d->pc) == OP_TAG2 ||
  7862. getop(*d->pc) == OP_TAGN ||
  7863. getop(*d->pc) == OP_DISPATCH);
  7864. d->pc = p;
  7865. }
  7866. upb_pbdecoder_decode(closure, handler_data, &dummy, 0, NULL);
  7867. }
  7868. if (d->call_len != 0) {
  7869. seterr(d, "Unexpected EOF inside submessage or group");
  7870. return false;
  7871. }
  7872. return true;
  7873. }
  7874. size_t upb_pbdecoder_decode(void *decoder, const void *group, const char *buf,
  7875. size_t size, const upb_bufhandle *handle) {
  7876. int32_t result = upb_pbdecoder_resume(decoder, NULL, buf, size, handle);
  7877. if (result == DECODE_ENDGROUP) goto_endmsg(decoder);
  7878. CHECK_RETURN(result);
  7879. return run_decoder_vm(decoder, group, handle);
  7880. }
  7881. /* Public API *****************************************************************/
  7882. void upb_pbdecoder_reset(upb_pbdecoder *d) {
  7883. d->top = d->stack;
  7884. d->top->groupnum = 0;
  7885. d->ptr = d->residual;
  7886. d->buf = d->residual;
  7887. d->end = d->residual;
  7888. d->residual_end = d->residual;
  7889. }
  7890. upb_pbdecoder *upb_pbdecoder_create(upb_env *e, const upb_pbdecodermethod *m,
  7891. upb_sink *sink) {
  7892. const size_t default_max_nesting = 64;
  7893. #ifndef NDEBUG
  7894. size_t size_before = upb_env_bytesallocated(e);
  7895. #endif
  7896. upb_pbdecoder *d = upb_env_malloc(e, sizeof(upb_pbdecoder));
  7897. if (!d) return NULL;
  7898. d->method_ = m;
  7899. d->callstack = upb_env_malloc(e, callstacksize(d, default_max_nesting));
  7900. d->stack = upb_env_malloc(e, stacksize(d, default_max_nesting));
  7901. if (!d->stack || !d->callstack) {
  7902. return NULL;
  7903. }
  7904. d->env = e;
  7905. d->limit = d->stack + default_max_nesting - 1;
  7906. d->stack_size = default_max_nesting;
  7907. d->status = NULL;
  7908. upb_pbdecoder_reset(d);
  7909. upb_bytessink_reset(&d->input_, &m->input_handler_, d);
  7910. assert(sink);
  7911. if (d->method_->dest_handlers_) {
  7912. if (sink->handlers != d->method_->dest_handlers_)
  7913. return NULL;
  7914. }
  7915. upb_sink_reset(&d->top->sink, sink->handlers, sink->closure);
  7916. /* If this fails, increase the value in decoder.h. */
  7917. assert(upb_env_bytesallocated(e) - size_before <= UPB_PB_DECODER_SIZE);
  7918. return d;
  7919. }
  7920. uint64_t upb_pbdecoder_bytesparsed(const upb_pbdecoder *d) {
  7921. return offset(d);
  7922. }
  7923. const upb_pbdecodermethod *upb_pbdecoder_method(const upb_pbdecoder *d) {
  7924. return d->method_;
  7925. }
  7926. upb_bytessink *upb_pbdecoder_input(upb_pbdecoder *d) {
  7927. return &d->input_;
  7928. }
  7929. size_t upb_pbdecoder_maxnesting(const upb_pbdecoder *d) {
  7930. return d->stack_size;
  7931. }
  7932. bool upb_pbdecoder_setmaxnesting(upb_pbdecoder *d, size_t max) {
  7933. assert(d->top >= d->stack);
  7934. if (max < (size_t)(d->top - d->stack)) {
  7935. /* Can't set a limit smaller than what we are currently at. */
  7936. return false;
  7937. }
  7938. if (max > d->stack_size) {
  7939. /* Need to reallocate stack and callstack to accommodate. */
  7940. size_t old_size = stacksize(d, d->stack_size);
  7941. size_t new_size = stacksize(d, max);
  7942. void *p = upb_env_realloc(d->env, d->stack, old_size, new_size);
  7943. if (!p) {
  7944. return false;
  7945. }
  7946. d->stack = p;
  7947. old_size = callstacksize(d, d->stack_size);
  7948. new_size = callstacksize(d, max);
  7949. p = upb_env_realloc(d->env, d->callstack, old_size, new_size);
  7950. if (!p) {
  7951. return false;
  7952. }
  7953. d->callstack = p;
  7954. d->stack_size = max;
  7955. }
  7956. d->limit = d->stack + max - 1;
  7957. return true;
  7958. }
  7959. /*
  7960. ** upb::Encoder
  7961. **
  7962. ** Since we are implementing pure handlers (ie. without any out-of-band access
  7963. ** to pre-computed lengths), we have to buffer all submessages before we can
  7964. ** emit even their first byte.
  7965. **
  7966. ** Not knowing the size of submessages also means we can't write a perfect
  7967. ** zero-copy implementation, even with buffering. Lengths are stored as
  7968. ** varints, which means that we don't know how many bytes to reserve for the
  7969. ** length until we know what the length is.
  7970. **
  7971. ** This leaves us with three main choices:
  7972. **
  7973. ** 1. buffer all submessage data in a temporary buffer, then copy it exactly
  7974. ** once into the output buffer.
  7975. **
  7976. ** 2. attempt to buffer data directly into the output buffer, estimating how
  7977. ** many bytes each length will take. When our guesses are wrong, use
  7978. ** memmove() to grow or shrink the allotted space.
  7979. **
  7980. ** 3. buffer directly into the output buffer, allocating a max length
  7981. ** ahead-of-time for each submessage length. If we overallocated, we waste
  7982. ** space, but no memcpy() or memmove() is required. This approach requires
  7983. ** defining a maximum size for submessages and rejecting submessages that
  7984. ** exceed that size.
  7985. **
  7986. ** (2) and (3) have the potential to have better performance, but they are more
  7987. ** complicated and subtle to implement:
  7988. **
  7989. ** (3) requires making an arbitrary choice of the maximum message size; it
  7990. ** wastes space when submessages are shorter than this and fails
  7991. ** completely when they are longer. This makes it more finicky and
  7992. ** requires configuration based on the input. It also makes it impossible
  7993. ** to perfectly match the output of reference encoders that always use the
  7994. ** optimal amount of space for each length.
  7995. **
  7996. ** (2) requires guessing the the size upfront, and if multiple lengths are
  7997. ** guessed wrong the minimum required number of memmove() operations may
  7998. ** be complicated to compute correctly. Implemented properly, it may have
  7999. ** a useful amortized or average cost, but more investigation is required
  8000. ** to determine this and what the optimal algorithm is to achieve it.
  8001. **
  8002. ** (1) makes you always pay for exactly one copy, but its implementation is
  8003. ** the simplest and its performance is predictable.
  8004. **
  8005. ** So for now, we implement (1) only. If we wish to optimize later, we should
  8006. ** be able to do it without affecting users.
  8007. **
  8008. ** The strategy is to buffer the segments of data that do *not* depend on
  8009. ** unknown lengths in one buffer, and keep a separate buffer of segment pointers
  8010. ** and lengths. When the top-level submessage ends, we can go beginning to end,
  8011. ** alternating the writing of lengths with memcpy() of the rest of the data.
  8012. ** At the top level though, no buffering is required.
  8013. */
  8014. /* The output buffer is divided into segments; a segment is a string of data
  8015. * that is "ready to go" -- it does not need any varint lengths inserted into
  8016. * the middle. The seams between segments are where varints will be inserted
  8017. * once they are known.
  8018. *
  8019. * We also use the concept of a "run", which is a range of encoded bytes that
  8020. * occur at a single submessage level. Every segment contains one or more runs.
  8021. *
  8022. * A segment can span messages. Consider:
  8023. *
  8024. * .--Submessage lengths---------.
  8025. * | | |
  8026. * | V V
  8027. * V | |--------------- | |-----------------
  8028. * Submessages: | |-----------------------------------------------
  8029. * Top-level msg: ------------------------------------------------------------
  8030. *
  8031. * Segments: ----- ------------------- -----------------
  8032. * Runs: *---- *--------------*--- *----------------
  8033. * (* marks the start)
  8034. *
  8035. * Note that the top-level menssage is not in any segment because it does not
  8036. * have any length preceding it.
  8037. *
  8038. * A segment is only interrupted when another length needs to be inserted. So
  8039. * observe how the second segment spans both the inner submessage and part of
  8040. * the next enclosing message. */
  8041. typedef struct {
  8042. uint32_t msglen; /* The length to varint-encode before this segment. */
  8043. uint32_t seglen; /* Length of the segment. */
  8044. } upb_pb_encoder_segment;
  8045. struct upb_pb_encoder {
  8046. upb_env *env;
  8047. /* Our input and output. */
  8048. upb_sink input_;
  8049. upb_bytessink *output_;
  8050. /* The "subclosure" -- used as the inner closure as part of the bytessink
  8051. * protocol. */
  8052. void *subc;
  8053. /* The output buffer and limit, and our current write position. "buf"
  8054. * initially points to "initbuf", but is dynamically allocated if we need to
  8055. * grow beyond the initial size. */
  8056. char *buf, *ptr, *limit;
  8057. /* The beginning of the current run, or undefined if we are at the top
  8058. * level. */
  8059. char *runbegin;
  8060. /* The list of segments we are accumulating. */
  8061. upb_pb_encoder_segment *segbuf, *segptr, *seglimit;
  8062. /* The stack of enclosing submessages. Each entry in the stack points to the
  8063. * segment where this submessage's length is being accumulated. */
  8064. int *stack, *top, *stacklimit;
  8065. /* Depth of startmsg/endmsg calls. */
  8066. int depth;
  8067. };
  8068. /* low-level buffering ********************************************************/
  8069. /* Low-level functions for interacting with the output buffer. */
  8070. /* TODO(haberman): handle pushback */
  8071. static void putbuf(upb_pb_encoder *e, const char *buf, size_t len) {
  8072. size_t n = upb_bytessink_putbuf(e->output_, e->subc, buf, len, NULL);
  8073. UPB_ASSERT_VAR(n, n == len);
  8074. }
  8075. static upb_pb_encoder_segment *top(upb_pb_encoder *e) {
  8076. return &e->segbuf[*e->top];
  8077. }
  8078. /* Call to ensure that at least "bytes" bytes are available for writing at
  8079. * e->ptr. Returns false if the bytes could not be allocated. */
  8080. static bool reserve(upb_pb_encoder *e, size_t bytes) {
  8081. if ((size_t)(e->limit - e->ptr) < bytes) {
  8082. /* Grow buffer. */
  8083. char *new_buf;
  8084. size_t needed = bytes + (e->ptr - e->buf);
  8085. size_t old_size = e->limit - e->buf;
  8086. size_t new_size = old_size;
  8087. while (new_size < needed) {
  8088. new_size *= 2;
  8089. }
  8090. new_buf = upb_env_realloc(e->env, e->buf, old_size, new_size);
  8091. if (new_buf == NULL) {
  8092. return false;
  8093. }
  8094. e->ptr = new_buf + (e->ptr - e->buf);
  8095. e->runbegin = new_buf + (e->runbegin - e->buf);
  8096. e->limit = new_buf + new_size;
  8097. e->buf = new_buf;
  8098. }
  8099. return true;
  8100. }
  8101. /* Call when "bytes" bytes have been writte at e->ptr. The caller *must* have
  8102. * previously called reserve() with at least this many bytes. */
  8103. static void encoder_advance(upb_pb_encoder *e, size_t bytes) {
  8104. assert((size_t)(e->limit - e->ptr) >= bytes);
  8105. e->ptr += bytes;
  8106. }
  8107. /* Call when all of the bytes for a handler have been written. Flushes the
  8108. * bytes if possible and necessary, returning false if this failed. */
  8109. static bool commit(upb_pb_encoder *e) {
  8110. if (!e->top) {
  8111. /* We aren't inside a delimited region. Flush our accumulated bytes to
  8112. * the output.
  8113. *
  8114. * TODO(haberman): in the future we may want to delay flushing for
  8115. * efficiency reasons. */
  8116. putbuf(e, e->buf, e->ptr - e->buf);
  8117. e->ptr = e->buf;
  8118. }
  8119. return true;
  8120. }
  8121. /* Writes the given bytes to the buffer, handling reserve/advance. */
  8122. static bool encode_bytes(upb_pb_encoder *e, const void *data, size_t len) {
  8123. if (!reserve(e, len)) {
  8124. return false;
  8125. }
  8126. memcpy(e->ptr, data, len);
  8127. encoder_advance(e, len);
  8128. return true;
  8129. }
  8130. /* Finish the current run by adding the run totals to the segment and message
  8131. * length. */
  8132. static void accumulate(upb_pb_encoder *e) {
  8133. size_t run_len;
  8134. assert(e->ptr >= e->runbegin);
  8135. run_len = e->ptr - e->runbegin;
  8136. e->segptr->seglen += run_len;
  8137. top(e)->msglen += run_len;
  8138. e->runbegin = e->ptr;
  8139. }
  8140. /* Call to indicate the start of delimited region for which the full length is
  8141. * not yet known. All data will be buffered until the length is known.
  8142. * Delimited regions may be nested; their lengths will all be tracked properly. */
  8143. static bool start_delim(upb_pb_encoder *e) {
  8144. if (e->top) {
  8145. /* We are already buffering, advance to the next segment and push it on the
  8146. * stack. */
  8147. accumulate(e);
  8148. if (++e->top == e->stacklimit) {
  8149. /* TODO(haberman): grow stack? */
  8150. return false;
  8151. }
  8152. if (++e->segptr == e->seglimit) {
  8153. /* Grow segment buffer. */
  8154. size_t old_size =
  8155. (e->seglimit - e->segbuf) * sizeof(upb_pb_encoder_segment);
  8156. size_t new_size = old_size * 2;
  8157. upb_pb_encoder_segment *new_buf =
  8158. upb_env_realloc(e->env, e->segbuf, old_size, new_size);
  8159. if (new_buf == NULL) {
  8160. return false;
  8161. }
  8162. e->segptr = new_buf + (e->segptr - e->segbuf);
  8163. e->seglimit = new_buf + (new_size / sizeof(upb_pb_encoder_segment));
  8164. e->segbuf = new_buf;
  8165. }
  8166. } else {
  8167. /* We were previously at the top level, start buffering. */
  8168. e->segptr = e->segbuf;
  8169. e->top = e->stack;
  8170. e->runbegin = e->ptr;
  8171. }
  8172. *e->top = e->segptr - e->segbuf;
  8173. e->segptr->seglen = 0;
  8174. e->segptr->msglen = 0;
  8175. return true;
  8176. }
  8177. /* Call to indicate the end of a delimited region. We now know the length of
  8178. * the delimited region. If we are not nested inside any other delimited
  8179. * regions, we can now emit all of the buffered data we accumulated. */
  8180. static bool end_delim(upb_pb_encoder *e) {
  8181. size_t msglen;
  8182. accumulate(e);
  8183. msglen = top(e)->msglen;
  8184. if (e->top == e->stack) {
  8185. /* All lengths are now available, emit all buffered data. */
  8186. char buf[UPB_PB_VARINT_MAX_LEN];
  8187. upb_pb_encoder_segment *s;
  8188. const char *ptr = e->buf;
  8189. for (s = e->segbuf; s <= e->segptr; s++) {
  8190. size_t lenbytes = upb_vencode64(s->msglen, buf);
  8191. putbuf(e, buf, lenbytes);
  8192. putbuf(e, ptr, s->seglen);
  8193. ptr += s->seglen;
  8194. }
  8195. e->ptr = e->buf;
  8196. e->top = NULL;
  8197. } else {
  8198. /* Need to keep buffering; propagate length info into enclosing
  8199. * submessages. */
  8200. --e->top;
  8201. top(e)->msglen += msglen + upb_varint_size(msglen);
  8202. }
  8203. return true;
  8204. }
  8205. /* tag_t **********************************************************************/
  8206. /* A precomputed (pre-encoded) tag and length. */
  8207. typedef struct {
  8208. uint8_t bytes;
  8209. char tag[7];
  8210. } tag_t;
  8211. /* Allocates a new tag for this field, and sets it in these handlerattr. */
  8212. static void new_tag(upb_handlers *h, const upb_fielddef *f, upb_wiretype_t wt,
  8213. upb_handlerattr *attr) {
  8214. uint32_t n = upb_fielddef_number(f);
  8215. tag_t *tag = upb_gmalloc(sizeof(tag_t));
  8216. tag->bytes = upb_vencode64((n << 3) | wt, tag->tag);
  8217. upb_handlerattr_init(attr);
  8218. upb_handlerattr_sethandlerdata(attr, tag);
  8219. upb_handlers_addcleanup(h, tag, upb_gfree);
  8220. }
  8221. static bool encode_tag(upb_pb_encoder *e, const tag_t *tag) {
  8222. return encode_bytes(e, tag->tag, tag->bytes);
  8223. }
  8224. /* encoding of wire types *****************************************************/
  8225. static bool encode_fixed64(upb_pb_encoder *e, uint64_t val) {
  8226. /* TODO(haberman): byte-swap for big endian. */
  8227. return encode_bytes(e, &val, sizeof(uint64_t));
  8228. }
  8229. static bool encode_fixed32(upb_pb_encoder *e, uint32_t val) {
  8230. /* TODO(haberman): byte-swap for big endian. */
  8231. return encode_bytes(e, &val, sizeof(uint32_t));
  8232. }
  8233. static bool encode_varint(upb_pb_encoder *e, uint64_t val) {
  8234. if (!reserve(e, UPB_PB_VARINT_MAX_LEN)) {
  8235. return false;
  8236. }
  8237. encoder_advance(e, upb_vencode64(val, e->ptr));
  8238. return true;
  8239. }
  8240. static uint64_t dbl2uint64(double d) {
  8241. uint64_t ret;
  8242. memcpy(&ret, &d, sizeof(uint64_t));
  8243. return ret;
  8244. }
  8245. static uint32_t flt2uint32(float d) {
  8246. uint32_t ret;
  8247. memcpy(&ret, &d, sizeof(uint32_t));
  8248. return ret;
  8249. }
  8250. /* encoding of proto types ****************************************************/
  8251. static bool startmsg(void *c, const void *hd) {
  8252. upb_pb_encoder *e = c;
  8253. UPB_UNUSED(hd);
  8254. if (e->depth++ == 0) {
  8255. upb_bytessink_start(e->output_, 0, &e->subc);
  8256. }
  8257. return true;
  8258. }
  8259. static bool endmsg(void *c, const void *hd, upb_status *status) {
  8260. upb_pb_encoder *e = c;
  8261. UPB_UNUSED(hd);
  8262. UPB_UNUSED(status);
  8263. if (--e->depth == 0) {
  8264. upb_bytessink_end(e->output_);
  8265. }
  8266. return true;
  8267. }
  8268. static void *encode_startdelimfield(void *c, const void *hd) {
  8269. bool ok = encode_tag(c, hd) && commit(c) && start_delim(c);
  8270. return ok ? c : UPB_BREAK;
  8271. }
  8272. static bool encode_enddelimfield(void *c, const void *hd) {
  8273. UPB_UNUSED(hd);
  8274. return end_delim(c);
  8275. }
  8276. static void *encode_startgroup(void *c, const void *hd) {
  8277. return (encode_tag(c, hd) && commit(c)) ? c : UPB_BREAK;
  8278. }
  8279. static bool encode_endgroup(void *c, const void *hd) {
  8280. return encode_tag(c, hd) && commit(c);
  8281. }
  8282. static void *encode_startstr(void *c, const void *hd, size_t size_hint) {
  8283. UPB_UNUSED(size_hint);
  8284. return encode_startdelimfield(c, hd);
  8285. }
  8286. static size_t encode_strbuf(void *c, const void *hd, const char *buf,
  8287. size_t len, const upb_bufhandle *h) {
  8288. UPB_UNUSED(hd);
  8289. UPB_UNUSED(h);
  8290. return encode_bytes(c, buf, len) ? len : 0;
  8291. }
  8292. #define T(type, ctype, convert, encode) \
  8293. static bool encode_scalar_##type(void *e, const void *hd, ctype val) { \
  8294. return encode_tag(e, hd) && encode(e, (convert)(val)) && commit(e); \
  8295. } \
  8296. static bool encode_packed_##type(void *e, const void *hd, ctype val) { \
  8297. UPB_UNUSED(hd); \
  8298. return encode(e, (convert)(val)); \
  8299. }
  8300. T(double, double, dbl2uint64, encode_fixed64)
  8301. T(float, float, flt2uint32, encode_fixed32)
  8302. T(int64, int64_t, uint64_t, encode_varint)
  8303. T(int32, int32_t, uint32_t, encode_varint)
  8304. T(fixed64, uint64_t, uint64_t, encode_fixed64)
  8305. T(fixed32, uint32_t, uint32_t, encode_fixed32)
  8306. T(bool, bool, bool, encode_varint)
  8307. T(uint32, uint32_t, uint32_t, encode_varint)
  8308. T(uint64, uint64_t, uint64_t, encode_varint)
  8309. T(enum, int32_t, uint32_t, encode_varint)
  8310. T(sfixed32, int32_t, uint32_t, encode_fixed32)
  8311. T(sfixed64, int64_t, uint64_t, encode_fixed64)
  8312. T(sint32, int32_t, upb_zzenc_32, encode_varint)
  8313. T(sint64, int64_t, upb_zzenc_64, encode_varint)
  8314. #undef T
  8315. /* code to build the handlers *************************************************/
  8316. static void newhandlers_callback(const void *closure, upb_handlers *h) {
  8317. const upb_msgdef *m;
  8318. upb_msg_field_iter i;
  8319. UPB_UNUSED(closure);
  8320. upb_handlers_setstartmsg(h, startmsg, NULL);
  8321. upb_handlers_setendmsg(h, endmsg, NULL);
  8322. m = upb_handlers_msgdef(h);
  8323. for(upb_msg_field_begin(&i, m);
  8324. !upb_msg_field_done(&i);
  8325. upb_msg_field_next(&i)) {
  8326. const upb_fielddef *f = upb_msg_iter_field(&i);
  8327. bool packed = upb_fielddef_isseq(f) && upb_fielddef_isprimitive(f) &&
  8328. upb_fielddef_packed(f);
  8329. upb_handlerattr attr;
  8330. upb_wiretype_t wt =
  8331. packed ? UPB_WIRE_TYPE_DELIMITED
  8332. : upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  8333. /* Pre-encode the tag for this field. */
  8334. new_tag(h, f, wt, &attr);
  8335. if (packed) {
  8336. upb_handlers_setstartseq(h, f, encode_startdelimfield, &attr);
  8337. upb_handlers_setendseq(h, f, encode_enddelimfield, &attr);
  8338. }
  8339. #define T(upper, lower, upbtype) \
  8340. case UPB_DESCRIPTOR_TYPE_##upper: \
  8341. if (packed) { \
  8342. upb_handlers_set##upbtype(h, f, encode_packed_##lower, &attr); \
  8343. } else { \
  8344. upb_handlers_set##upbtype(h, f, encode_scalar_##lower, &attr); \
  8345. } \
  8346. break;
  8347. switch (upb_fielddef_descriptortype(f)) {
  8348. T(DOUBLE, double, double);
  8349. T(FLOAT, float, float);
  8350. T(INT64, int64, int64);
  8351. T(INT32, int32, int32);
  8352. T(FIXED64, fixed64, uint64);
  8353. T(FIXED32, fixed32, uint32);
  8354. T(BOOL, bool, bool);
  8355. T(UINT32, uint32, uint32);
  8356. T(UINT64, uint64, uint64);
  8357. T(ENUM, enum, int32);
  8358. T(SFIXED32, sfixed32, int32);
  8359. T(SFIXED64, sfixed64, int64);
  8360. T(SINT32, sint32, int32);
  8361. T(SINT64, sint64, int64);
  8362. case UPB_DESCRIPTOR_TYPE_STRING:
  8363. case UPB_DESCRIPTOR_TYPE_BYTES:
  8364. upb_handlers_setstartstr(h, f, encode_startstr, &attr);
  8365. upb_handlers_setendstr(h, f, encode_enddelimfield, &attr);
  8366. upb_handlers_setstring(h, f, encode_strbuf, &attr);
  8367. break;
  8368. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  8369. upb_handlers_setstartsubmsg(h, f, encode_startdelimfield, &attr);
  8370. upb_handlers_setendsubmsg(h, f, encode_enddelimfield, &attr);
  8371. break;
  8372. case UPB_DESCRIPTOR_TYPE_GROUP: {
  8373. /* Endgroup takes a different tag (wire_type = END_GROUP). */
  8374. upb_handlerattr attr2;
  8375. new_tag(h, f, UPB_WIRE_TYPE_END_GROUP, &attr2);
  8376. upb_handlers_setstartsubmsg(h, f, encode_startgroup, &attr);
  8377. upb_handlers_setendsubmsg(h, f, encode_endgroup, &attr2);
  8378. upb_handlerattr_uninit(&attr2);
  8379. break;
  8380. }
  8381. }
  8382. #undef T
  8383. upb_handlerattr_uninit(&attr);
  8384. }
  8385. }
  8386. void upb_pb_encoder_reset(upb_pb_encoder *e) {
  8387. e->segptr = NULL;
  8388. e->top = NULL;
  8389. e->depth = 0;
  8390. }
  8391. /* public API *****************************************************************/
  8392. const upb_handlers *upb_pb_encoder_newhandlers(const upb_msgdef *m,
  8393. const void *owner) {
  8394. return upb_handlers_newfrozen(m, owner, newhandlers_callback, NULL);
  8395. }
  8396. upb_pb_encoder *upb_pb_encoder_create(upb_env *env, const upb_handlers *h,
  8397. upb_bytessink *output) {
  8398. const size_t initial_bufsize = 256;
  8399. const size_t initial_segbufsize = 16;
  8400. /* TODO(haberman): make this configurable. */
  8401. const size_t stack_size = 64;
  8402. #ifndef NDEBUG
  8403. const size_t size_before = upb_env_bytesallocated(env);
  8404. #endif
  8405. upb_pb_encoder *e = upb_env_malloc(env, sizeof(upb_pb_encoder));
  8406. if (!e) return NULL;
  8407. e->buf = upb_env_malloc(env, initial_bufsize);
  8408. e->segbuf = upb_env_malloc(env, initial_segbufsize * sizeof(*e->segbuf));
  8409. e->stack = upb_env_malloc(env, stack_size * sizeof(*e->stack));
  8410. if (!e->buf || !e->segbuf || !e->stack) {
  8411. return NULL;
  8412. }
  8413. e->limit = e->buf + initial_bufsize;
  8414. e->seglimit = e->segbuf + initial_segbufsize;
  8415. e->stacklimit = e->stack + stack_size;
  8416. upb_pb_encoder_reset(e);
  8417. upb_sink_reset(&e->input_, h, e);
  8418. e->env = env;
  8419. e->output_ = output;
  8420. e->subc = output->closure;
  8421. e->ptr = e->buf;
  8422. /* If this fails, increase the value in encoder.h. */
  8423. assert(upb_env_bytesallocated(env) - size_before <= UPB_PB_ENCODER_SIZE);
  8424. return e;
  8425. }
  8426. upb_sink *upb_pb_encoder_input(upb_pb_encoder *e) { return &e->input_; }
  8427. upb_filedef **upb_loaddescriptor(const char *buf, size_t n, const void *owner,
  8428. upb_status *status) {
  8429. /* Create handlers. */
  8430. const upb_pbdecodermethod *decoder_m;
  8431. const upb_handlers *reader_h = upb_descreader_newhandlers(&reader_h);
  8432. upb_env env;
  8433. upb_pbdecodermethodopts opts;
  8434. upb_pbdecoder *decoder;
  8435. upb_descreader *reader;
  8436. bool ok;
  8437. size_t i;
  8438. upb_filedef **ret = NULL;
  8439. upb_pbdecodermethodopts_init(&opts, reader_h);
  8440. decoder_m = upb_pbdecodermethod_new(&opts, &decoder_m);
  8441. upb_env_init(&env);
  8442. upb_env_reporterrorsto(&env, status);
  8443. reader = upb_descreader_create(&env, reader_h);
  8444. decoder = upb_pbdecoder_create(&env, decoder_m, upb_descreader_input(reader));
  8445. /* Push input data. */
  8446. ok = upb_bufsrc_putbuf(buf, n, upb_pbdecoder_input(decoder));
  8447. if (!ok) {
  8448. goto cleanup;
  8449. }
  8450. ret = upb_gmalloc(sizeof (*ret) * (upb_descreader_filecount(reader) + 1));
  8451. if (!ret) {
  8452. goto cleanup;
  8453. }
  8454. for (i = 0; i < upb_descreader_filecount(reader); i++) {
  8455. ret[i] = upb_descreader_file(reader, i);
  8456. upb_filedef_ref(ret[i], owner);
  8457. }
  8458. ret[i] = NULL;
  8459. cleanup:
  8460. upb_env_uninit(&env);
  8461. upb_handlers_unref(reader_h, &reader_h);
  8462. upb_pbdecodermethod_unref(decoder_m, &decoder_m);
  8463. return ret;
  8464. }
  8465. /*
  8466. * upb::pb::TextPrinter
  8467. *
  8468. * OPT: This is not optimized at all. It uses printf() which parses the format
  8469. * string every time, and it allocates memory for every put.
  8470. */
  8471. #include <ctype.h>
  8472. #include <float.h>
  8473. #include <inttypes.h>
  8474. #include <stdarg.h>
  8475. #include <stdio.h>
  8476. #include <string.h>
  8477. struct upb_textprinter {
  8478. upb_sink input_;
  8479. upb_bytessink *output_;
  8480. int indent_depth_;
  8481. bool single_line_;
  8482. void *subc;
  8483. };
  8484. #define CHECK(x) if ((x) < 0) goto err;
  8485. static const char *shortname(const char *longname) {
  8486. const char *last = strrchr(longname, '.');
  8487. return last ? last + 1 : longname;
  8488. }
  8489. static int indent(upb_textprinter *p) {
  8490. int i;
  8491. if (!p->single_line_)
  8492. for (i = 0; i < p->indent_depth_; i++)
  8493. upb_bytessink_putbuf(p->output_, p->subc, " ", 2, NULL);
  8494. return 0;
  8495. }
  8496. static int endfield(upb_textprinter *p) {
  8497. const char ch = (p->single_line_ ? ' ' : '\n');
  8498. upb_bytessink_putbuf(p->output_, p->subc, &ch, 1, NULL);
  8499. return 0;
  8500. }
  8501. static int putescaped(upb_textprinter *p, const char *buf, size_t len,
  8502. bool preserve_utf8) {
  8503. /* Based on CEscapeInternal() from Google's protobuf release. */
  8504. char dstbuf[4096], *dst = dstbuf, *dstend = dstbuf + sizeof(dstbuf);
  8505. const char *end = buf + len;
  8506. /* I think hex is prettier and more useful, but proto2 uses octal; should
  8507. * investigate whether it can parse hex also. */
  8508. const bool use_hex = false;
  8509. bool last_hex_escape = false; /* true if last output char was \xNN */
  8510. for (; buf < end; buf++) {
  8511. bool is_hex_escape;
  8512. if (dstend - dst < 4) {
  8513. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  8514. dst = dstbuf;
  8515. }
  8516. is_hex_escape = false;
  8517. switch (*buf) {
  8518. case '\n': *(dst++) = '\\'; *(dst++) = 'n'; break;
  8519. case '\r': *(dst++) = '\\'; *(dst++) = 'r'; break;
  8520. case '\t': *(dst++) = '\\'; *(dst++) = 't'; break;
  8521. case '\"': *(dst++) = '\\'; *(dst++) = '\"'; break;
  8522. case '\'': *(dst++) = '\\'; *(dst++) = '\''; break;
  8523. case '\\': *(dst++) = '\\'; *(dst++) = '\\'; break;
  8524. default:
  8525. /* Note that if we emit \xNN and the buf character after that is a hex
  8526. * digit then that digit must be escaped too to prevent it being
  8527. * interpreted as part of the character code by C. */
  8528. if ((!preserve_utf8 || (uint8_t)*buf < 0x80) &&
  8529. (!isprint(*buf) || (last_hex_escape && isxdigit(*buf)))) {
  8530. sprintf(dst, (use_hex ? "\\x%02x" : "\\%03o"), (uint8_t)*buf);
  8531. is_hex_escape = use_hex;
  8532. dst += 4;
  8533. } else {
  8534. *(dst++) = *buf; break;
  8535. }
  8536. }
  8537. last_hex_escape = is_hex_escape;
  8538. }
  8539. /* Flush remaining data. */
  8540. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  8541. return 0;
  8542. }
  8543. bool putf(upb_textprinter *p, const char *fmt, ...) {
  8544. va_list args;
  8545. va_list args_copy;
  8546. char *str;
  8547. int written;
  8548. int len;
  8549. bool ok;
  8550. va_start(args, fmt);
  8551. /* Run once to get the length of the string. */
  8552. _upb_va_copy(args_copy, args);
  8553. len = _upb_vsnprintf(NULL, 0, fmt, args_copy);
  8554. va_end(args_copy);
  8555. /* + 1 for NULL terminator (vsprintf() requires it even if we don't). */
  8556. str = upb_gmalloc(len + 1);
  8557. if (!str) return false;
  8558. written = vsprintf(str, fmt, args);
  8559. va_end(args);
  8560. UPB_ASSERT_VAR(written, written == len);
  8561. ok = upb_bytessink_putbuf(p->output_, p->subc, str, len, NULL);
  8562. upb_gfree(str);
  8563. return ok;
  8564. }
  8565. /* handlers *******************************************************************/
  8566. static bool textprinter_startmsg(void *c, const void *hd) {
  8567. upb_textprinter *p = c;
  8568. UPB_UNUSED(hd);
  8569. if (p->indent_depth_ == 0) {
  8570. upb_bytessink_start(p->output_, 0, &p->subc);
  8571. }
  8572. return true;
  8573. }
  8574. static bool textprinter_endmsg(void *c, const void *hd, upb_status *s) {
  8575. upb_textprinter *p = c;
  8576. UPB_UNUSED(hd);
  8577. UPB_UNUSED(s);
  8578. if (p->indent_depth_ == 0) {
  8579. upb_bytessink_end(p->output_);
  8580. }
  8581. return true;
  8582. }
  8583. #define TYPE(name, ctype, fmt) \
  8584. static bool textprinter_put ## name(void *closure, const void *handler_data, \
  8585. ctype val) { \
  8586. upb_textprinter *p = closure; \
  8587. const upb_fielddef *f = handler_data; \
  8588. CHECK(indent(p)); \
  8589. putf(p, "%s: " fmt, upb_fielddef_name(f), val); \
  8590. CHECK(endfield(p)); \
  8591. return true; \
  8592. err: \
  8593. return false; \
  8594. }
  8595. static bool textprinter_putbool(void *closure, const void *handler_data,
  8596. bool val) {
  8597. upb_textprinter *p = closure;
  8598. const upb_fielddef *f = handler_data;
  8599. CHECK(indent(p));
  8600. putf(p, "%s: %s", upb_fielddef_name(f), val ? "true" : "false");
  8601. CHECK(endfield(p));
  8602. return true;
  8603. err:
  8604. return false;
  8605. }
  8606. #define STRINGIFY_HELPER(x) #x
  8607. #define STRINGIFY_MACROVAL(x) STRINGIFY_HELPER(x)
  8608. TYPE(int32, int32_t, "%" PRId32)
  8609. TYPE(int64, int64_t, "%" PRId64)
  8610. TYPE(uint32, uint32_t, "%" PRIu32)
  8611. TYPE(uint64, uint64_t, "%" PRIu64)
  8612. TYPE(float, float, "%." STRINGIFY_MACROVAL(FLT_DIG) "g")
  8613. TYPE(double, double, "%." STRINGIFY_MACROVAL(DBL_DIG) "g")
  8614. #undef TYPE
  8615. /* Output a symbolic value from the enum if found, else just print as int32. */
  8616. static bool textprinter_putenum(void *closure, const void *handler_data,
  8617. int32_t val) {
  8618. upb_textprinter *p = closure;
  8619. const upb_fielddef *f = handler_data;
  8620. const upb_enumdef *enum_def = upb_downcast_enumdef(upb_fielddef_subdef(f));
  8621. const char *label = upb_enumdef_iton(enum_def, val);
  8622. if (label) {
  8623. indent(p);
  8624. putf(p, "%s: %s", upb_fielddef_name(f), label);
  8625. endfield(p);
  8626. } else {
  8627. if (!textprinter_putint32(closure, handler_data, val))
  8628. return false;
  8629. }
  8630. return true;
  8631. }
  8632. static void *textprinter_startstr(void *closure, const void *handler_data,
  8633. size_t size_hint) {
  8634. upb_textprinter *p = closure;
  8635. const upb_fielddef *f = handler_data;
  8636. UPB_UNUSED(size_hint);
  8637. indent(p);
  8638. putf(p, "%s: \"", upb_fielddef_name(f));
  8639. return p;
  8640. }
  8641. static bool textprinter_endstr(void *closure, const void *handler_data) {
  8642. upb_textprinter *p = closure;
  8643. UPB_UNUSED(handler_data);
  8644. putf(p, "\"");
  8645. endfield(p);
  8646. return true;
  8647. }
  8648. static size_t textprinter_putstr(void *closure, const void *hd, const char *buf,
  8649. size_t len, const upb_bufhandle *handle) {
  8650. upb_textprinter *p = closure;
  8651. const upb_fielddef *f = hd;
  8652. UPB_UNUSED(handle);
  8653. CHECK(putescaped(p, buf, len, upb_fielddef_type(f) == UPB_TYPE_STRING));
  8654. return len;
  8655. err:
  8656. return 0;
  8657. }
  8658. static void *textprinter_startsubmsg(void *closure, const void *handler_data) {
  8659. upb_textprinter *p = closure;
  8660. const char *name = handler_data;
  8661. CHECK(indent(p));
  8662. putf(p, "%s {%c", name, p->single_line_ ? ' ' : '\n');
  8663. p->indent_depth_++;
  8664. return p;
  8665. err:
  8666. return UPB_BREAK;
  8667. }
  8668. static bool textprinter_endsubmsg(void *closure, const void *handler_data) {
  8669. upb_textprinter *p = closure;
  8670. UPB_UNUSED(handler_data);
  8671. p->indent_depth_--;
  8672. CHECK(indent(p));
  8673. upb_bytessink_putbuf(p->output_, p->subc, "}", 1, NULL);
  8674. CHECK(endfield(p));
  8675. return true;
  8676. err:
  8677. return false;
  8678. }
  8679. static void onmreg(const void *c, upb_handlers *h) {
  8680. const upb_msgdef *m = upb_handlers_msgdef(h);
  8681. upb_msg_field_iter i;
  8682. UPB_UNUSED(c);
  8683. upb_handlers_setstartmsg(h, textprinter_startmsg, NULL);
  8684. upb_handlers_setendmsg(h, textprinter_endmsg, NULL);
  8685. for(upb_msg_field_begin(&i, m);
  8686. !upb_msg_field_done(&i);
  8687. upb_msg_field_next(&i)) {
  8688. upb_fielddef *f = upb_msg_iter_field(&i);
  8689. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  8690. upb_handlerattr_sethandlerdata(&attr, f);
  8691. switch (upb_fielddef_type(f)) {
  8692. case UPB_TYPE_INT32:
  8693. upb_handlers_setint32(h, f, textprinter_putint32, &attr);
  8694. break;
  8695. case UPB_TYPE_INT64:
  8696. upb_handlers_setint64(h, f, textprinter_putint64, &attr);
  8697. break;
  8698. case UPB_TYPE_UINT32:
  8699. upb_handlers_setuint32(h, f, textprinter_putuint32, &attr);
  8700. break;
  8701. case UPB_TYPE_UINT64:
  8702. upb_handlers_setuint64(h, f, textprinter_putuint64, &attr);
  8703. break;
  8704. case UPB_TYPE_FLOAT:
  8705. upb_handlers_setfloat(h, f, textprinter_putfloat, &attr);
  8706. break;
  8707. case UPB_TYPE_DOUBLE:
  8708. upb_handlers_setdouble(h, f, textprinter_putdouble, &attr);
  8709. break;
  8710. case UPB_TYPE_BOOL:
  8711. upb_handlers_setbool(h, f, textprinter_putbool, &attr);
  8712. break;
  8713. case UPB_TYPE_STRING:
  8714. case UPB_TYPE_BYTES:
  8715. upb_handlers_setstartstr(h, f, textprinter_startstr, &attr);
  8716. upb_handlers_setstring(h, f, textprinter_putstr, &attr);
  8717. upb_handlers_setendstr(h, f, textprinter_endstr, &attr);
  8718. break;
  8719. case UPB_TYPE_MESSAGE: {
  8720. const char *name =
  8721. upb_fielddef_istagdelim(f)
  8722. ? shortname(upb_msgdef_fullname(upb_fielddef_msgsubdef(f)))
  8723. : upb_fielddef_name(f);
  8724. upb_handlerattr_sethandlerdata(&attr, name);
  8725. upb_handlers_setstartsubmsg(h, f, textprinter_startsubmsg, &attr);
  8726. upb_handlers_setendsubmsg(h, f, textprinter_endsubmsg, &attr);
  8727. break;
  8728. }
  8729. case UPB_TYPE_ENUM:
  8730. upb_handlers_setint32(h, f, textprinter_putenum, &attr);
  8731. break;
  8732. }
  8733. }
  8734. }
  8735. static void textprinter_reset(upb_textprinter *p, bool single_line) {
  8736. p->single_line_ = single_line;
  8737. p->indent_depth_ = 0;
  8738. }
  8739. /* Public API *****************************************************************/
  8740. upb_textprinter *upb_textprinter_create(upb_env *env, const upb_handlers *h,
  8741. upb_bytessink *output) {
  8742. upb_textprinter *p = upb_env_malloc(env, sizeof(upb_textprinter));
  8743. if (!p) return NULL;
  8744. p->output_ = output;
  8745. upb_sink_reset(&p->input_, h, p);
  8746. textprinter_reset(p, false);
  8747. return p;
  8748. }
  8749. const upb_handlers *upb_textprinter_newhandlers(const upb_msgdef *m,
  8750. const void *owner) {
  8751. return upb_handlers_newfrozen(m, owner, &onmreg, NULL);
  8752. }
  8753. upb_sink *upb_textprinter_input(upb_textprinter *p) { return &p->input_; }
  8754. void upb_textprinter_setsingleline(upb_textprinter *p, bool single_line) {
  8755. p->single_line_ = single_line;
  8756. }
  8757. /* Index is descriptor type. */
  8758. const uint8_t upb_pb_native_wire_types[] = {
  8759. UPB_WIRE_TYPE_END_GROUP, /* ENDGROUP */
  8760. UPB_WIRE_TYPE_64BIT, /* DOUBLE */
  8761. UPB_WIRE_TYPE_32BIT, /* FLOAT */
  8762. UPB_WIRE_TYPE_VARINT, /* INT64 */
  8763. UPB_WIRE_TYPE_VARINT, /* UINT64 */
  8764. UPB_WIRE_TYPE_VARINT, /* INT32 */
  8765. UPB_WIRE_TYPE_64BIT, /* FIXED64 */
  8766. UPB_WIRE_TYPE_32BIT, /* FIXED32 */
  8767. UPB_WIRE_TYPE_VARINT, /* BOOL */
  8768. UPB_WIRE_TYPE_DELIMITED, /* STRING */
  8769. UPB_WIRE_TYPE_START_GROUP, /* GROUP */
  8770. UPB_WIRE_TYPE_DELIMITED, /* MESSAGE */
  8771. UPB_WIRE_TYPE_DELIMITED, /* BYTES */
  8772. UPB_WIRE_TYPE_VARINT, /* UINT32 */
  8773. UPB_WIRE_TYPE_VARINT, /* ENUM */
  8774. UPB_WIRE_TYPE_32BIT, /* SFIXED32 */
  8775. UPB_WIRE_TYPE_64BIT, /* SFIXED64 */
  8776. UPB_WIRE_TYPE_VARINT, /* SINT32 */
  8777. UPB_WIRE_TYPE_VARINT, /* SINT64 */
  8778. };
  8779. /* A basic branch-based decoder, uses 32-bit values to get good performance
  8780. * on 32-bit architectures (but performs well on 64-bits also).
  8781. * This scheme comes from the original Google Protobuf implementation
  8782. * (proto2). */
  8783. upb_decoderet upb_vdecode_max8_branch32(upb_decoderet r) {
  8784. upb_decoderet err = {NULL, 0};
  8785. const char *p = r.p;
  8786. uint32_t low = (uint32_t)r.val;
  8787. uint32_t high = 0;
  8788. uint32_t b;
  8789. b = *(p++); low |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  8790. b = *(p++); low |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  8791. b = *(p++); low |= (b & 0x7fU) << 28;
  8792. high = (b & 0x7fU) >> 4; if (!(b & 0x80)) goto done;
  8793. b = *(p++); high |= (b & 0x7fU) << 3; if (!(b & 0x80)) goto done;
  8794. b = *(p++); high |= (b & 0x7fU) << 10; if (!(b & 0x80)) goto done;
  8795. b = *(p++); high |= (b & 0x7fU) << 17; if (!(b & 0x80)) goto done;
  8796. b = *(p++); high |= (b & 0x7fU) << 24; if (!(b & 0x80)) goto done;
  8797. b = *(p++); high |= (b & 0x7fU) << 31; if (!(b & 0x80)) goto done;
  8798. return err;
  8799. done:
  8800. r.val = ((uint64_t)high << 32) | low;
  8801. r.p = p;
  8802. return r;
  8803. }
  8804. /* Like the previous, but uses 64-bit values. */
  8805. upb_decoderet upb_vdecode_max8_branch64(upb_decoderet r) {
  8806. const char *p = r.p;
  8807. uint64_t val = r.val;
  8808. uint64_t b;
  8809. upb_decoderet err = {NULL, 0};
  8810. b = *(p++); val |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  8811. b = *(p++); val |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  8812. b = *(p++); val |= (b & 0x7fU) << 28; if (!(b & 0x80)) goto done;
  8813. b = *(p++); val |= (b & 0x7fU) << 35; if (!(b & 0x80)) goto done;
  8814. b = *(p++); val |= (b & 0x7fU) << 42; if (!(b & 0x80)) goto done;
  8815. b = *(p++); val |= (b & 0x7fU) << 49; if (!(b & 0x80)) goto done;
  8816. b = *(p++); val |= (b & 0x7fU) << 56; if (!(b & 0x80)) goto done;
  8817. b = *(p++); val |= (b & 0x7fU) << 63; if (!(b & 0x80)) goto done;
  8818. return err;
  8819. done:
  8820. r.val = val;
  8821. r.p = p;
  8822. return r;
  8823. }
  8824. /* Given an encoded varint v, returns an integer with a single bit set that
  8825. * indicates the end of the varint. Subtracting one from this value will
  8826. * yield a mask that leaves only bits that are part of the varint. Returns
  8827. * 0 if the varint is unterminated. */
  8828. static uint64_t upb_get_vstopbit(uint64_t v) {
  8829. uint64_t cbits = v | 0x7f7f7f7f7f7f7f7fULL;
  8830. return ~cbits & (cbits+1);
  8831. }
  8832. /* A branchless decoder. Credit to Pascal Massimino for the bit-twiddling. */
  8833. upb_decoderet upb_vdecode_max8_massimino(upb_decoderet r) {
  8834. uint64_t b;
  8835. uint64_t stop_bit;
  8836. upb_decoderet my_r;
  8837. memcpy(&b, r.p, sizeof(b));
  8838. stop_bit = upb_get_vstopbit(b);
  8839. b = (b & 0x7f7f7f7f7f7f7f7fULL) & (stop_bit - 1);
  8840. b += b & 0x007f007f007f007fULL;
  8841. b += 3 * (b & 0x0000ffff0000ffffULL);
  8842. b += 15 * (b & 0x00000000ffffffffULL);
  8843. if (stop_bit == 0) {
  8844. /* Error: unterminated varint. */
  8845. upb_decoderet err_r = {(void*)0, 0};
  8846. return err_r;
  8847. }
  8848. my_r = upb_decoderet_make(r.p + ((__builtin_ctzll(stop_bit) + 1) / 8),
  8849. r.val | (b << 7));
  8850. return my_r;
  8851. }
  8852. /* A branchless decoder. Credit to Daniel Wright for the bit-twiddling. */
  8853. upb_decoderet upb_vdecode_max8_wright(upb_decoderet r) {
  8854. uint64_t b;
  8855. uint64_t stop_bit;
  8856. upb_decoderet my_r;
  8857. memcpy(&b, r.p, sizeof(b));
  8858. stop_bit = upb_get_vstopbit(b);
  8859. b &= (stop_bit - 1);
  8860. b = ((b & 0x7f007f007f007f00ULL) >> 1) | (b & 0x007f007f007f007fULL);
  8861. b = ((b & 0xffff0000ffff0000ULL) >> 2) | (b & 0x0000ffff0000ffffULL);
  8862. b = ((b & 0xffffffff00000000ULL) >> 4) | (b & 0x00000000ffffffffULL);
  8863. if (stop_bit == 0) {
  8864. /* Error: unterminated varint. */
  8865. upb_decoderet err_r = {(void*)0, 0};
  8866. return err_r;
  8867. }
  8868. my_r = upb_decoderet_make(r.p + ((__builtin_ctzll(stop_bit) + 1) / 8),
  8869. r.val | (b << 14));
  8870. return my_r;
  8871. }
  8872. #line 1 "upb/json/parser.rl"
  8873. /*
  8874. ** upb::json::Parser (upb_json_parser)
  8875. **
  8876. ** A parser that uses the Ragel State Machine Compiler to generate
  8877. ** the finite automata.
  8878. **
  8879. ** Ragel only natively handles regular languages, but we can manually
  8880. ** program it a bit to handle context-free languages like JSON, by using
  8881. ** the "fcall" and "fret" constructs.
  8882. **
  8883. ** This parser can handle the basics, but needs several things to be fleshed
  8884. ** out:
  8885. **
  8886. ** - handling of unicode escape sequences (including high surrogate pairs).
  8887. ** - properly check and report errors for unknown fields, stack overflow,
  8888. ** improper array nesting (or lack of nesting).
  8889. ** - handling of base64 sequences with padding characters.
  8890. ** - handling of push-back (non-success returns from sink functions).
  8891. ** - handling of keys/escape-sequences/etc that span input buffers.
  8892. */
  8893. #include <assert.h>
  8894. #include <errno.h>
  8895. #include <stdint.h>
  8896. #include <stdlib.h>
  8897. #include <string.h>
  8898. #define UPB_JSON_MAX_DEPTH 64
  8899. typedef struct {
  8900. upb_sink sink;
  8901. /* The current message in which we're parsing, and the field whose value we're
  8902. * expecting next. */
  8903. const upb_msgdef *m;
  8904. const upb_fielddef *f;
  8905. /* The table mapping json name to fielddef for this message. */
  8906. upb_strtable *name_table;
  8907. /* We are in a repeated-field context, ready to emit mapentries as
  8908. * submessages. This flag alters the start-of-object (open-brace) behavior to
  8909. * begin a sequence of mapentry messages rather than a single submessage. */
  8910. bool is_map;
  8911. /* We are in a map-entry message context. This flag is set when parsing the
  8912. * value field of a single map entry and indicates to all value-field parsers
  8913. * (subobjects, strings, numbers, and bools) that the map-entry submessage
  8914. * should end as soon as the value is parsed. */
  8915. bool is_mapentry;
  8916. /* If |is_map| or |is_mapentry| is true, |mapfield| refers to the parent
  8917. * message's map field that we're currently parsing. This differs from |f|
  8918. * because |f| is the field in the *current* message (i.e., the map-entry
  8919. * message itself), not the parent's field that leads to this map. */
  8920. const upb_fielddef *mapfield;
  8921. } upb_jsonparser_frame;
  8922. struct upb_json_parser {
  8923. upb_env *env;
  8924. const upb_json_parsermethod *method;
  8925. upb_bytessink input_;
  8926. /* Stack to track the JSON scopes we are in. */
  8927. upb_jsonparser_frame stack[UPB_JSON_MAX_DEPTH];
  8928. upb_jsonparser_frame *top;
  8929. upb_jsonparser_frame *limit;
  8930. upb_status status;
  8931. /* Ragel's internal parsing stack for the parsing state machine. */
  8932. int current_state;
  8933. int parser_stack[UPB_JSON_MAX_DEPTH];
  8934. int parser_top;
  8935. /* The handle for the current buffer. */
  8936. const upb_bufhandle *handle;
  8937. /* Accumulate buffer. See details in parser.rl. */
  8938. const char *accumulated;
  8939. size_t accumulated_len;
  8940. char *accumulate_buf;
  8941. size_t accumulate_buf_size;
  8942. /* Multi-part text data. See details in parser.rl. */
  8943. int multipart_state;
  8944. upb_selector_t string_selector;
  8945. /* Input capture. See details in parser.rl. */
  8946. const char *capture;
  8947. /* Intermediate result of parsing a unicode escape sequence. */
  8948. uint32_t digit;
  8949. };
  8950. struct upb_json_parsermethod {
  8951. upb_refcounted base;
  8952. upb_byteshandler input_handler_;
  8953. /* Mainly for the purposes of refcounting, so all the fielddefs we point
  8954. * to stay alive. */
  8955. const upb_msgdef *msg;
  8956. /* Keys are upb_msgdef*, values are upb_strtable (json_name -> fielddef) */
  8957. upb_inttable name_tables;
  8958. };
  8959. #define PARSER_CHECK_RETURN(x) if (!(x)) return false
  8960. /* Used to signal that a capture has been suspended. */
  8961. static char suspend_capture;
  8962. static upb_selector_t getsel_for_handlertype(upb_json_parser *p,
  8963. upb_handlertype_t type) {
  8964. upb_selector_t sel;
  8965. bool ok = upb_handlers_getselector(p->top->f, type, &sel);
  8966. UPB_ASSERT_VAR(ok, ok);
  8967. return sel;
  8968. }
  8969. static upb_selector_t parser_getsel(upb_json_parser *p) {
  8970. return getsel_for_handlertype(
  8971. p, upb_handlers_getprimitivehandlertype(p->top->f));
  8972. }
  8973. static bool check_stack(upb_json_parser *p) {
  8974. if ((p->top + 1) == p->limit) {
  8975. upb_status_seterrmsg(&p->status, "Nesting too deep");
  8976. upb_env_reporterror(p->env, &p->status);
  8977. return false;
  8978. }
  8979. return true;
  8980. }
  8981. static void set_name_table(upb_json_parser *p, upb_jsonparser_frame *frame) {
  8982. upb_value v;
  8983. bool ok = upb_inttable_lookupptr(&p->method->name_tables, frame->m, &v);
  8984. UPB_ASSERT_VAR(ok, ok);
  8985. frame->name_table = upb_value_getptr(v);
  8986. }
  8987. /* There are GCC/Clang built-ins for overflow checking which we could start
  8988. * using if there was any performance benefit to it. */
  8989. static bool checked_add(size_t a, size_t b, size_t *c) {
  8990. if (SIZE_MAX - a < b) return false;
  8991. *c = a + b;
  8992. return true;
  8993. }
  8994. static size_t saturating_multiply(size_t a, size_t b) {
  8995. /* size_t is unsigned, so this is defined behavior even on overflow. */
  8996. size_t ret = a * b;
  8997. if (b != 0 && ret / b != a) {
  8998. ret = SIZE_MAX;
  8999. }
  9000. return ret;
  9001. }
  9002. /* Base64 decoding ************************************************************/
  9003. /* TODO(haberman): make this streaming. */
  9004. static const signed char b64table[] = {
  9005. -1, -1, -1, -1, -1, -1, -1, -1,
  9006. -1, -1, -1, -1, -1, -1, -1, -1,
  9007. -1, -1, -1, -1, -1, -1, -1, -1,
  9008. -1, -1, -1, -1, -1, -1, -1, -1,
  9009. -1, -1, -1, -1, -1, -1, -1, -1,
  9010. -1, -1, -1, 62/*+*/, -1, -1, -1, 63/*/ */,
  9011. 52/*0*/, 53/*1*/, 54/*2*/, 55/*3*/, 56/*4*/, 57/*5*/, 58/*6*/, 59/*7*/,
  9012. 60/*8*/, 61/*9*/, -1, -1, -1, -1, -1, -1,
  9013. -1, 0/*A*/, 1/*B*/, 2/*C*/, 3/*D*/, 4/*E*/, 5/*F*/, 6/*G*/,
  9014. 07/*H*/, 8/*I*/, 9/*J*/, 10/*K*/, 11/*L*/, 12/*M*/, 13/*N*/, 14/*O*/,
  9015. 15/*P*/, 16/*Q*/, 17/*R*/, 18/*S*/, 19/*T*/, 20/*U*/, 21/*V*/, 22/*W*/,
  9016. 23/*X*/, 24/*Y*/, 25/*Z*/, -1, -1, -1, -1, -1,
  9017. -1, 26/*a*/, 27/*b*/, 28/*c*/, 29/*d*/, 30/*e*/, 31/*f*/, 32/*g*/,
  9018. 33/*h*/, 34/*i*/, 35/*j*/, 36/*k*/, 37/*l*/, 38/*m*/, 39/*n*/, 40/*o*/,
  9019. 41/*p*/, 42/*q*/, 43/*r*/, 44/*s*/, 45/*t*/, 46/*u*/, 47/*v*/, 48/*w*/,
  9020. 49/*x*/, 50/*y*/, 51/*z*/, -1, -1, -1, -1, -1,
  9021. -1, -1, -1, -1, -1, -1, -1, -1,
  9022. -1, -1, -1, -1, -1, -1, -1, -1,
  9023. -1, -1, -1, -1, -1, -1, -1, -1,
  9024. -1, -1, -1, -1, -1, -1, -1, -1,
  9025. -1, -1, -1, -1, -1, -1, -1, -1,
  9026. -1, -1, -1, -1, -1, -1, -1, -1,
  9027. -1, -1, -1, -1, -1, -1, -1, -1,
  9028. -1, -1, -1, -1, -1, -1, -1, -1,
  9029. -1, -1, -1, -1, -1, -1, -1, -1,
  9030. -1, -1, -1, -1, -1, -1, -1, -1,
  9031. -1, -1, -1, -1, -1, -1, -1, -1,
  9032. -1, -1, -1, -1, -1, -1, -1, -1,
  9033. -1, -1, -1, -1, -1, -1, -1, -1,
  9034. -1, -1, -1, -1, -1, -1, -1, -1,
  9035. -1, -1, -1, -1, -1, -1, -1, -1,
  9036. -1, -1, -1, -1, -1, -1, -1, -1
  9037. };
  9038. /* Returns the table value sign-extended to 32 bits. Knowing that the upper
  9039. * bits will be 1 for unrecognized characters makes it easier to check for
  9040. * this error condition later (see below). */
  9041. int32_t b64lookup(unsigned char ch) { return b64table[ch]; }
  9042. /* Returns true if the given character is not a valid base64 character or
  9043. * padding. */
  9044. bool nonbase64(unsigned char ch) { return b64lookup(ch) == -1 && ch != '='; }
  9045. static bool base64_push(upb_json_parser *p, upb_selector_t sel, const char *ptr,
  9046. size_t len) {
  9047. const char *limit = ptr + len;
  9048. for (; ptr < limit; ptr += 4) {
  9049. uint32_t val;
  9050. char output[3];
  9051. if (limit - ptr < 4) {
  9052. upb_status_seterrf(&p->status,
  9053. "Base64 input for bytes field not a multiple of 4: %s",
  9054. upb_fielddef_name(p->top->f));
  9055. upb_env_reporterror(p->env, &p->status);
  9056. return false;
  9057. }
  9058. val = b64lookup(ptr[0]) << 18 |
  9059. b64lookup(ptr[1]) << 12 |
  9060. b64lookup(ptr[2]) << 6 |
  9061. b64lookup(ptr[3]);
  9062. /* Test the upper bit; returns true if any of the characters returned -1. */
  9063. if (val & 0x80000000) {
  9064. goto otherchar;
  9065. }
  9066. output[0] = val >> 16;
  9067. output[1] = (val >> 8) & 0xff;
  9068. output[2] = val & 0xff;
  9069. upb_sink_putstring(&p->top->sink, sel, output, 3, NULL);
  9070. }
  9071. return true;
  9072. otherchar:
  9073. if (nonbase64(ptr[0]) || nonbase64(ptr[1]) || nonbase64(ptr[2]) ||
  9074. nonbase64(ptr[3]) ) {
  9075. upb_status_seterrf(&p->status,
  9076. "Non-base64 characters in bytes field: %s",
  9077. upb_fielddef_name(p->top->f));
  9078. upb_env_reporterror(p->env, &p->status);
  9079. return false;
  9080. } if (ptr[2] == '=') {
  9081. uint32_t val;
  9082. char output;
  9083. /* Last group contains only two input bytes, one output byte. */
  9084. if (ptr[0] == '=' || ptr[1] == '=' || ptr[3] != '=') {
  9085. goto badpadding;
  9086. }
  9087. val = b64lookup(ptr[0]) << 18 |
  9088. b64lookup(ptr[1]) << 12;
  9089. assert(!(val & 0x80000000));
  9090. output = val >> 16;
  9091. upb_sink_putstring(&p->top->sink, sel, &output, 1, NULL);
  9092. return true;
  9093. } else {
  9094. uint32_t val;
  9095. char output[2];
  9096. /* Last group contains only three input bytes, two output bytes. */
  9097. if (ptr[0] == '=' || ptr[1] == '=' || ptr[2] == '=') {
  9098. goto badpadding;
  9099. }
  9100. val = b64lookup(ptr[0]) << 18 |
  9101. b64lookup(ptr[1]) << 12 |
  9102. b64lookup(ptr[2]) << 6;
  9103. output[0] = val >> 16;
  9104. output[1] = (val >> 8) & 0xff;
  9105. upb_sink_putstring(&p->top->sink, sel, output, 2, NULL);
  9106. return true;
  9107. }
  9108. badpadding:
  9109. upb_status_seterrf(&p->status,
  9110. "Incorrect base64 padding for field: %s (%.*s)",
  9111. upb_fielddef_name(p->top->f),
  9112. 4, ptr);
  9113. upb_env_reporterror(p->env, &p->status);
  9114. return false;
  9115. }
  9116. /* Accumulate buffer **********************************************************/
  9117. /* Functionality for accumulating a buffer.
  9118. *
  9119. * Some parts of the parser need an entire value as a contiguous string. For
  9120. * example, to look up a member name in a hash table, or to turn a string into
  9121. * a number, the relevant library routines need the input string to be in
  9122. * contiguous memory, even if the value spanned two or more buffers in the
  9123. * input. These routines handle that.
  9124. *
  9125. * In the common case we can just point to the input buffer to get this
  9126. * contiguous string and avoid any actual copy. So we optimistically begin
  9127. * this way. But there are a few cases where we must instead copy into a
  9128. * separate buffer:
  9129. *
  9130. * 1. The string was not contiguous in the input (it spanned buffers).
  9131. *
  9132. * 2. The string included escape sequences that need to be interpreted to get
  9133. * the true value in a contiguous buffer. */
  9134. static void assert_accumulate_empty(upb_json_parser *p) {
  9135. UPB_UNUSED(p);
  9136. assert(p->accumulated == NULL);
  9137. assert(p->accumulated_len == 0);
  9138. }
  9139. static void accumulate_clear(upb_json_parser *p) {
  9140. p->accumulated = NULL;
  9141. p->accumulated_len = 0;
  9142. }
  9143. /* Used internally by accumulate_append(). */
  9144. static bool accumulate_realloc(upb_json_parser *p, size_t need) {
  9145. void *mem;
  9146. size_t old_size = p->accumulate_buf_size;
  9147. size_t new_size = UPB_MAX(old_size, 128);
  9148. while (new_size < need) {
  9149. new_size = saturating_multiply(new_size, 2);
  9150. }
  9151. mem = upb_env_realloc(p->env, p->accumulate_buf, old_size, new_size);
  9152. if (!mem) {
  9153. upb_status_seterrmsg(&p->status, "Out of memory allocating buffer.");
  9154. upb_env_reporterror(p->env, &p->status);
  9155. return false;
  9156. }
  9157. p->accumulate_buf = mem;
  9158. p->accumulate_buf_size = new_size;
  9159. return true;
  9160. }
  9161. /* Logically appends the given data to the append buffer.
  9162. * If "can_alias" is true, we will try to avoid actually copying, but the buffer
  9163. * must be valid until the next accumulate_append() call (if any). */
  9164. static bool accumulate_append(upb_json_parser *p, const char *buf, size_t len,
  9165. bool can_alias) {
  9166. size_t need;
  9167. if (!p->accumulated && can_alias) {
  9168. p->accumulated = buf;
  9169. p->accumulated_len = len;
  9170. return true;
  9171. }
  9172. if (!checked_add(p->accumulated_len, len, &need)) {
  9173. upb_status_seterrmsg(&p->status, "Integer overflow.");
  9174. upb_env_reporterror(p->env, &p->status);
  9175. return false;
  9176. }
  9177. if (need > p->accumulate_buf_size && !accumulate_realloc(p, need)) {
  9178. return false;
  9179. }
  9180. if (p->accumulated != p->accumulate_buf) {
  9181. memcpy(p->accumulate_buf, p->accumulated, p->accumulated_len);
  9182. p->accumulated = p->accumulate_buf;
  9183. }
  9184. memcpy(p->accumulate_buf + p->accumulated_len, buf, len);
  9185. p->accumulated_len += len;
  9186. return true;
  9187. }
  9188. /* Returns a pointer to the data accumulated since the last accumulate_clear()
  9189. * call, and writes the length to *len. This with point either to the input
  9190. * buffer or a temporary accumulate buffer. */
  9191. static const char *accumulate_getptr(upb_json_parser *p, size_t *len) {
  9192. assert(p->accumulated);
  9193. *len = p->accumulated_len;
  9194. return p->accumulated;
  9195. }
  9196. /* Mult-part text data ********************************************************/
  9197. /* When we have text data in the input, it can often come in multiple segments.
  9198. * For example, there may be some raw string data followed by an escape
  9199. * sequence. The two segments are processed with different logic. Also buffer
  9200. * seams in the input can cause multiple segments.
  9201. *
  9202. * As we see segments, there are two main cases for how we want to process them:
  9203. *
  9204. * 1. we want to push the captured input directly to string handlers.
  9205. *
  9206. * 2. we need to accumulate all the parts into a contiguous buffer for further
  9207. * processing (field name lookup, string->number conversion, etc). */
  9208. /* This is the set of states for p->multipart_state. */
  9209. enum {
  9210. /* We are not currently processing multipart data. */
  9211. MULTIPART_INACTIVE = 0,
  9212. /* We are processing multipart data by accumulating it into a contiguous
  9213. * buffer. */
  9214. MULTIPART_ACCUMULATE = 1,
  9215. /* We are processing multipart data by pushing each part directly to the
  9216. * current string handlers. */
  9217. MULTIPART_PUSHEAGERLY = 2
  9218. };
  9219. /* Start a multi-part text value where we accumulate the data for processing at
  9220. * the end. */
  9221. static void multipart_startaccum(upb_json_parser *p) {
  9222. assert_accumulate_empty(p);
  9223. assert(p->multipart_state == MULTIPART_INACTIVE);
  9224. p->multipart_state = MULTIPART_ACCUMULATE;
  9225. }
  9226. /* Start a multi-part text value where we immediately push text data to a string
  9227. * value with the given selector. */
  9228. static void multipart_start(upb_json_parser *p, upb_selector_t sel) {
  9229. assert_accumulate_empty(p);
  9230. assert(p->multipart_state == MULTIPART_INACTIVE);
  9231. p->multipart_state = MULTIPART_PUSHEAGERLY;
  9232. p->string_selector = sel;
  9233. }
  9234. static bool multipart_text(upb_json_parser *p, const char *buf, size_t len,
  9235. bool can_alias) {
  9236. switch (p->multipart_state) {
  9237. case MULTIPART_INACTIVE:
  9238. upb_status_seterrmsg(
  9239. &p->status, "Internal error: unexpected state MULTIPART_INACTIVE");
  9240. upb_env_reporterror(p->env, &p->status);
  9241. return false;
  9242. case MULTIPART_ACCUMULATE:
  9243. if (!accumulate_append(p, buf, len, can_alias)) {
  9244. return false;
  9245. }
  9246. break;
  9247. case MULTIPART_PUSHEAGERLY: {
  9248. const upb_bufhandle *handle = can_alias ? p->handle : NULL;
  9249. upb_sink_putstring(&p->top->sink, p->string_selector, buf, len, handle);
  9250. break;
  9251. }
  9252. }
  9253. return true;
  9254. }
  9255. /* Note: this invalidates the accumulate buffer! Call only after reading its
  9256. * contents. */
  9257. static void multipart_end(upb_json_parser *p) {
  9258. assert(p->multipart_state != MULTIPART_INACTIVE);
  9259. p->multipart_state = MULTIPART_INACTIVE;
  9260. accumulate_clear(p);
  9261. }
  9262. /* Input capture **************************************************************/
  9263. /* Functionality for capturing a region of the input as text. Gracefully
  9264. * handles the case where a buffer seam occurs in the middle of the captured
  9265. * region. */
  9266. static void capture_begin(upb_json_parser *p, const char *ptr) {
  9267. assert(p->multipart_state != MULTIPART_INACTIVE);
  9268. assert(p->capture == NULL);
  9269. p->capture = ptr;
  9270. }
  9271. static bool capture_end(upb_json_parser *p, const char *ptr) {
  9272. assert(p->capture);
  9273. if (multipart_text(p, p->capture, ptr - p->capture, true)) {
  9274. p->capture = NULL;
  9275. return true;
  9276. } else {
  9277. return false;
  9278. }
  9279. }
  9280. /* This is called at the end of each input buffer (ie. when we have hit a
  9281. * buffer seam). If we are in the middle of capturing the input, this
  9282. * processes the unprocessed capture region. */
  9283. static void capture_suspend(upb_json_parser *p, const char **ptr) {
  9284. if (!p->capture) return;
  9285. if (multipart_text(p, p->capture, *ptr - p->capture, false)) {
  9286. /* We use this as a signal that we were in the middle of capturing, and
  9287. * that capturing should resume at the beginning of the next buffer.
  9288. *
  9289. * We can't use *ptr here, because we have no guarantee that this pointer
  9290. * will be valid when we resume (if the underlying memory is freed, then
  9291. * using the pointer at all, even to compare to NULL, is likely undefined
  9292. * behavior). */
  9293. p->capture = &suspend_capture;
  9294. } else {
  9295. /* Need to back up the pointer to the beginning of the capture, since
  9296. * we were not able to actually preserve it. */
  9297. *ptr = p->capture;
  9298. }
  9299. }
  9300. static void capture_resume(upb_json_parser *p, const char *ptr) {
  9301. if (p->capture) {
  9302. assert(p->capture == &suspend_capture);
  9303. p->capture = ptr;
  9304. }
  9305. }
  9306. /* Callbacks from the parser **************************************************/
  9307. /* These are the functions called directly from the parser itself.
  9308. * We define these in the same order as their declarations in the parser. */
  9309. static char escape_char(char in) {
  9310. switch (in) {
  9311. case 'r': return '\r';
  9312. case 't': return '\t';
  9313. case 'n': return '\n';
  9314. case 'f': return '\f';
  9315. case 'b': return '\b';
  9316. case '/': return '/';
  9317. case '"': return '"';
  9318. case '\\': return '\\';
  9319. default:
  9320. assert(0);
  9321. return 'x';
  9322. }
  9323. }
  9324. static bool escape(upb_json_parser *p, const char *ptr) {
  9325. char ch = escape_char(*ptr);
  9326. return multipart_text(p, &ch, 1, false);
  9327. }
  9328. static void start_hex(upb_json_parser *p) {
  9329. p->digit = 0;
  9330. }
  9331. static void hexdigit(upb_json_parser *p, const char *ptr) {
  9332. char ch = *ptr;
  9333. p->digit <<= 4;
  9334. if (ch >= '0' && ch <= '9') {
  9335. p->digit += (ch - '0');
  9336. } else if (ch >= 'a' && ch <= 'f') {
  9337. p->digit += ((ch - 'a') + 10);
  9338. } else {
  9339. assert(ch >= 'A' && ch <= 'F');
  9340. p->digit += ((ch - 'A') + 10);
  9341. }
  9342. }
  9343. static bool end_hex(upb_json_parser *p) {
  9344. uint32_t codepoint = p->digit;
  9345. /* emit the codepoint as UTF-8. */
  9346. char utf8[3]; /* support \u0000 -- \uFFFF -- need only three bytes. */
  9347. int length = 0;
  9348. if (codepoint <= 0x7F) {
  9349. utf8[0] = codepoint;
  9350. length = 1;
  9351. } else if (codepoint <= 0x07FF) {
  9352. utf8[1] = (codepoint & 0x3F) | 0x80;
  9353. codepoint >>= 6;
  9354. utf8[0] = (codepoint & 0x1F) | 0xC0;
  9355. length = 2;
  9356. } else /* codepoint <= 0xFFFF */ {
  9357. utf8[2] = (codepoint & 0x3F) | 0x80;
  9358. codepoint >>= 6;
  9359. utf8[1] = (codepoint & 0x3F) | 0x80;
  9360. codepoint >>= 6;
  9361. utf8[0] = (codepoint & 0x0F) | 0xE0;
  9362. length = 3;
  9363. }
  9364. /* TODO(haberman): Handle high surrogates: if codepoint is a high surrogate
  9365. * we have to wait for the next escape to get the full code point). */
  9366. return multipart_text(p, utf8, length, false);
  9367. }
  9368. static void start_text(upb_json_parser *p, const char *ptr) {
  9369. capture_begin(p, ptr);
  9370. }
  9371. static bool end_text(upb_json_parser *p, const char *ptr) {
  9372. return capture_end(p, ptr);
  9373. }
  9374. static void start_number(upb_json_parser *p, const char *ptr) {
  9375. multipart_startaccum(p);
  9376. capture_begin(p, ptr);
  9377. }
  9378. static bool parse_number(upb_json_parser *p);
  9379. static bool end_number(upb_json_parser *p, const char *ptr) {
  9380. if (!capture_end(p, ptr)) {
  9381. return false;
  9382. }
  9383. return parse_number(p);
  9384. }
  9385. static bool parse_number(upb_json_parser *p) {
  9386. size_t len;
  9387. const char *buf;
  9388. const char *myend;
  9389. char *end;
  9390. /* strtol() and friends unfortunately do not support specifying the length of
  9391. * the input string, so we need to force a copy into a NULL-terminated buffer. */
  9392. if (!multipart_text(p, "\0", 1, false)) {
  9393. return false;
  9394. }
  9395. buf = accumulate_getptr(p, &len);
  9396. myend = buf + len - 1; /* One for NULL. */
  9397. /* XXX: We are using strtol to parse integers, but this is wrong as even
  9398. * integers can be represented as 1e6 (for example), which strtol can't
  9399. * handle correctly.
  9400. *
  9401. * XXX: Also, we can't handle large integers properly because strto[u]ll
  9402. * isn't in C89.
  9403. *
  9404. * XXX: Also, we don't properly check floats for overflow, since strtof
  9405. * isn't in C89. */
  9406. switch (upb_fielddef_type(p->top->f)) {
  9407. case UPB_TYPE_ENUM:
  9408. case UPB_TYPE_INT32: {
  9409. long val = strtol(p->accumulated, &end, 0);
  9410. if (val > INT32_MAX || val < INT32_MIN || errno == ERANGE || end != myend)
  9411. goto err;
  9412. else
  9413. upb_sink_putint32(&p->top->sink, parser_getsel(p), val);
  9414. break;
  9415. }
  9416. case UPB_TYPE_INT64: {
  9417. long long val = strtol(p->accumulated, &end, 0);
  9418. if (val > INT64_MAX || val < INT64_MIN || errno == ERANGE || end != myend)
  9419. goto err;
  9420. else
  9421. upb_sink_putint64(&p->top->sink, parser_getsel(p), val);
  9422. break;
  9423. }
  9424. case UPB_TYPE_UINT32: {
  9425. unsigned long val = strtoul(p->accumulated, &end, 0);
  9426. if (val > UINT32_MAX || errno == ERANGE || end != myend)
  9427. goto err;
  9428. else
  9429. upb_sink_putuint32(&p->top->sink, parser_getsel(p), val);
  9430. break;
  9431. }
  9432. case UPB_TYPE_UINT64: {
  9433. unsigned long long val = strtoul(p->accumulated, &end, 0);
  9434. if (val > UINT64_MAX || errno == ERANGE || end != myend)
  9435. goto err;
  9436. else
  9437. upb_sink_putuint64(&p->top->sink, parser_getsel(p), val);
  9438. break;
  9439. }
  9440. case UPB_TYPE_DOUBLE: {
  9441. double val = strtod(p->accumulated, &end);
  9442. if (errno == ERANGE || end != myend)
  9443. goto err;
  9444. else
  9445. upb_sink_putdouble(&p->top->sink, parser_getsel(p), val);
  9446. break;
  9447. }
  9448. case UPB_TYPE_FLOAT: {
  9449. float val = strtod(p->accumulated, &end);
  9450. if (errno == ERANGE || end != myend)
  9451. goto err;
  9452. else
  9453. upb_sink_putfloat(&p->top->sink, parser_getsel(p), val);
  9454. break;
  9455. }
  9456. default:
  9457. assert(false);
  9458. }
  9459. multipart_end(p);
  9460. return true;
  9461. err:
  9462. upb_status_seterrf(&p->status, "error parsing number: %s", buf);
  9463. upb_env_reporterror(p->env, &p->status);
  9464. multipart_end(p);
  9465. return false;
  9466. }
  9467. static bool parser_putbool(upb_json_parser *p, bool val) {
  9468. bool ok;
  9469. if (upb_fielddef_type(p->top->f) != UPB_TYPE_BOOL) {
  9470. upb_status_seterrf(&p->status,
  9471. "Boolean value specified for non-bool field: %s",
  9472. upb_fielddef_name(p->top->f));
  9473. upb_env_reporterror(p->env, &p->status);
  9474. return false;
  9475. }
  9476. ok = upb_sink_putbool(&p->top->sink, parser_getsel(p), val);
  9477. UPB_ASSERT_VAR(ok, ok);
  9478. return true;
  9479. }
  9480. static bool start_stringval(upb_json_parser *p) {
  9481. assert(p->top->f);
  9482. if (upb_fielddef_isstring(p->top->f)) {
  9483. upb_jsonparser_frame *inner;
  9484. upb_selector_t sel;
  9485. if (!check_stack(p)) return false;
  9486. /* Start a new parser frame: parser frames correspond one-to-one with
  9487. * handler frames, and string events occur in a sub-frame. */
  9488. inner = p->top + 1;
  9489. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  9490. upb_sink_startstr(&p->top->sink, sel, 0, &inner->sink);
  9491. inner->m = p->top->m;
  9492. inner->f = p->top->f;
  9493. inner->name_table = NULL;
  9494. inner->is_map = false;
  9495. inner->is_mapentry = false;
  9496. p->top = inner;
  9497. if (upb_fielddef_type(p->top->f) == UPB_TYPE_STRING) {
  9498. /* For STRING fields we push data directly to the handlers as it is
  9499. * parsed. We don't do this yet for BYTES fields, because our base64
  9500. * decoder is not streaming.
  9501. *
  9502. * TODO(haberman): make base64 decoding streaming also. */
  9503. multipart_start(p, getsel_for_handlertype(p, UPB_HANDLER_STRING));
  9504. return true;
  9505. } else {
  9506. multipart_startaccum(p);
  9507. return true;
  9508. }
  9509. } else if (upb_fielddef_type(p->top->f) == UPB_TYPE_ENUM) {
  9510. /* No need to push a frame -- symbolic enum names in quotes remain in the
  9511. * current parser frame.
  9512. *
  9513. * Enum string values must accumulate so we can look up the value in a table
  9514. * once it is complete. */
  9515. multipart_startaccum(p);
  9516. return true;
  9517. } else {
  9518. upb_status_seterrf(&p->status,
  9519. "String specified for non-string/non-enum field: %s",
  9520. upb_fielddef_name(p->top->f));
  9521. upb_env_reporterror(p->env, &p->status);
  9522. return false;
  9523. }
  9524. }
  9525. static bool end_stringval(upb_json_parser *p) {
  9526. bool ok = true;
  9527. switch (upb_fielddef_type(p->top->f)) {
  9528. case UPB_TYPE_BYTES:
  9529. if (!base64_push(p, getsel_for_handlertype(p, UPB_HANDLER_STRING),
  9530. p->accumulated, p->accumulated_len)) {
  9531. return false;
  9532. }
  9533. /* Fall through. */
  9534. case UPB_TYPE_STRING: {
  9535. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  9536. p->top--;
  9537. upb_sink_endstr(&p->top->sink, sel);
  9538. break;
  9539. }
  9540. case UPB_TYPE_ENUM: {
  9541. /* Resolve enum symbolic name to integer value. */
  9542. const upb_enumdef *enumdef =
  9543. (const upb_enumdef*)upb_fielddef_subdef(p->top->f);
  9544. size_t len;
  9545. const char *buf = accumulate_getptr(p, &len);
  9546. int32_t int_val = 0;
  9547. ok = upb_enumdef_ntoi(enumdef, buf, len, &int_val);
  9548. if (ok) {
  9549. upb_selector_t sel = parser_getsel(p);
  9550. upb_sink_putint32(&p->top->sink, sel, int_val);
  9551. } else {
  9552. upb_status_seterrf(&p->status, "Enum value unknown: '%.*s'", len, buf);
  9553. upb_env_reporterror(p->env, &p->status);
  9554. }
  9555. break;
  9556. }
  9557. default:
  9558. assert(false);
  9559. upb_status_seterrmsg(&p->status, "Internal error in JSON decoder");
  9560. upb_env_reporterror(p->env, &p->status);
  9561. ok = false;
  9562. break;
  9563. }
  9564. multipart_end(p);
  9565. return ok;
  9566. }
  9567. static void start_member(upb_json_parser *p) {
  9568. assert(!p->top->f);
  9569. multipart_startaccum(p);
  9570. }
  9571. /* Helper: invoked during parse_mapentry() to emit the mapentry message's key
  9572. * field based on the current contents of the accumulate buffer. */
  9573. static bool parse_mapentry_key(upb_json_parser *p) {
  9574. size_t len;
  9575. const char *buf = accumulate_getptr(p, &len);
  9576. /* Emit the key field. We do a bit of ad-hoc parsing here because the
  9577. * parser state machine has already decided that this is a string field
  9578. * name, and we are reinterpreting it as some arbitrary key type. In
  9579. * particular, integer and bool keys are quoted, so we need to parse the
  9580. * quoted string contents here. */
  9581. p->top->f = upb_msgdef_itof(p->top->m, UPB_MAPENTRY_KEY);
  9582. if (p->top->f == NULL) {
  9583. upb_status_seterrmsg(&p->status, "mapentry message has no key");
  9584. upb_env_reporterror(p->env, &p->status);
  9585. return false;
  9586. }
  9587. switch (upb_fielddef_type(p->top->f)) {
  9588. case UPB_TYPE_INT32:
  9589. case UPB_TYPE_INT64:
  9590. case UPB_TYPE_UINT32:
  9591. case UPB_TYPE_UINT64:
  9592. /* Invoke end_number. The accum buffer has the number's text already. */
  9593. if (!parse_number(p)) {
  9594. return false;
  9595. }
  9596. break;
  9597. case UPB_TYPE_BOOL:
  9598. if (len == 4 && !strncmp(buf, "true", 4)) {
  9599. if (!parser_putbool(p, true)) {
  9600. return false;
  9601. }
  9602. } else if (len == 5 && !strncmp(buf, "false", 5)) {
  9603. if (!parser_putbool(p, false)) {
  9604. return false;
  9605. }
  9606. } else {
  9607. upb_status_seterrmsg(&p->status,
  9608. "Map bool key not 'true' or 'false'");
  9609. upb_env_reporterror(p->env, &p->status);
  9610. return false;
  9611. }
  9612. multipart_end(p);
  9613. break;
  9614. case UPB_TYPE_STRING:
  9615. case UPB_TYPE_BYTES: {
  9616. upb_sink subsink;
  9617. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  9618. upb_sink_startstr(&p->top->sink, sel, len, &subsink);
  9619. sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
  9620. upb_sink_putstring(&subsink, sel, buf, len, NULL);
  9621. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  9622. upb_sink_endstr(&p->top->sink, sel);
  9623. multipart_end(p);
  9624. break;
  9625. }
  9626. default:
  9627. upb_status_seterrmsg(&p->status, "Invalid field type for map key");
  9628. upb_env_reporterror(p->env, &p->status);
  9629. return false;
  9630. }
  9631. return true;
  9632. }
  9633. /* Helper: emit one map entry (as a submessage in the map field sequence). This
  9634. * is invoked from end_membername(), at the end of the map entry's key string,
  9635. * with the map key in the accumulate buffer. It parses the key from that
  9636. * buffer, emits the handler calls to start the mapentry submessage (setting up
  9637. * its subframe in the process), and sets up state in the subframe so that the
  9638. * value parser (invoked next) will emit the mapentry's value field and then
  9639. * end the mapentry message. */
  9640. static bool handle_mapentry(upb_json_parser *p) {
  9641. const upb_fielddef *mapfield;
  9642. const upb_msgdef *mapentrymsg;
  9643. upb_jsonparser_frame *inner;
  9644. upb_selector_t sel;
  9645. /* Map entry: p->top->sink is the seq frame, so we need to start a frame
  9646. * for the mapentry itself, and then set |f| in that frame so that the map
  9647. * value field is parsed, and also set a flag to end the frame after the
  9648. * map-entry value is parsed. */
  9649. if (!check_stack(p)) return false;
  9650. mapfield = p->top->mapfield;
  9651. mapentrymsg = upb_fielddef_msgsubdef(mapfield);
  9652. inner = p->top + 1;
  9653. p->top->f = mapfield;
  9654. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
  9655. upb_sink_startsubmsg(&p->top->sink, sel, &inner->sink);
  9656. inner->m = mapentrymsg;
  9657. inner->name_table = NULL;
  9658. inner->mapfield = mapfield;
  9659. inner->is_map = false;
  9660. /* Don't set this to true *yet* -- we reuse parsing handlers below to push
  9661. * the key field value to the sink, and these handlers will pop the frame
  9662. * if they see is_mapentry (when invoked by the parser state machine, they
  9663. * would have just seen the map-entry value, not key). */
  9664. inner->is_mapentry = false;
  9665. p->top = inner;
  9666. /* send STARTMSG in submsg frame. */
  9667. upb_sink_startmsg(&p->top->sink);
  9668. parse_mapentry_key(p);
  9669. /* Set up the value field to receive the map-entry value. */
  9670. p->top->f = upb_msgdef_itof(p->top->m, UPB_MAPENTRY_VALUE);
  9671. p->top->is_mapentry = true; /* set up to pop frame after value is parsed. */
  9672. p->top->mapfield = mapfield;
  9673. if (p->top->f == NULL) {
  9674. upb_status_seterrmsg(&p->status, "mapentry message has no value");
  9675. upb_env_reporterror(p->env, &p->status);
  9676. return false;
  9677. }
  9678. return true;
  9679. }
  9680. static bool end_membername(upb_json_parser *p) {
  9681. assert(!p->top->f);
  9682. if (p->top->is_map) {
  9683. return handle_mapentry(p);
  9684. } else {
  9685. size_t len;
  9686. const char *buf = accumulate_getptr(p, &len);
  9687. upb_value v;
  9688. if (upb_strtable_lookup2(p->top->name_table, buf, len, &v)) {
  9689. p->top->f = upb_value_getconstptr(v);
  9690. multipart_end(p);
  9691. return true;
  9692. } else {
  9693. /* TODO(haberman): Ignore unknown fields if requested/configured to do
  9694. * so. */
  9695. upb_status_seterrf(&p->status, "No such field: %.*s\n", (int)len, buf);
  9696. upb_env_reporterror(p->env, &p->status);
  9697. return false;
  9698. }
  9699. }
  9700. }
  9701. static void end_member(upb_json_parser *p) {
  9702. /* If we just parsed a map-entry value, end that frame too. */
  9703. if (p->top->is_mapentry) {
  9704. upb_status s = UPB_STATUS_INIT;
  9705. upb_selector_t sel;
  9706. bool ok;
  9707. const upb_fielddef *mapfield;
  9708. assert(p->top > p->stack);
  9709. /* send ENDMSG on submsg. */
  9710. upb_sink_endmsg(&p->top->sink, &s);
  9711. mapfield = p->top->mapfield;
  9712. /* send ENDSUBMSG in repeated-field-of-mapentries frame. */
  9713. p->top--;
  9714. ok = upb_handlers_getselector(mapfield, UPB_HANDLER_ENDSUBMSG, &sel);
  9715. UPB_ASSERT_VAR(ok, ok);
  9716. upb_sink_endsubmsg(&p->top->sink, sel);
  9717. }
  9718. p->top->f = NULL;
  9719. }
  9720. static bool start_subobject(upb_json_parser *p) {
  9721. assert(p->top->f);
  9722. if (upb_fielddef_ismap(p->top->f)) {
  9723. upb_jsonparser_frame *inner;
  9724. upb_selector_t sel;
  9725. /* Beginning of a map. Start a new parser frame in a repeated-field
  9726. * context. */
  9727. if (!check_stack(p)) return false;
  9728. inner = p->top + 1;
  9729. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
  9730. upb_sink_startseq(&p->top->sink, sel, &inner->sink);
  9731. inner->m = upb_fielddef_msgsubdef(p->top->f);
  9732. inner->name_table = NULL;
  9733. inner->mapfield = p->top->f;
  9734. inner->f = NULL;
  9735. inner->is_map = true;
  9736. inner->is_mapentry = false;
  9737. p->top = inner;
  9738. return true;
  9739. } else if (upb_fielddef_issubmsg(p->top->f)) {
  9740. upb_jsonparser_frame *inner;
  9741. upb_selector_t sel;
  9742. /* Beginning of a subobject. Start a new parser frame in the submsg
  9743. * context. */
  9744. if (!check_stack(p)) return false;
  9745. inner = p->top + 1;
  9746. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
  9747. upb_sink_startsubmsg(&p->top->sink, sel, &inner->sink);
  9748. inner->m = upb_fielddef_msgsubdef(p->top->f);
  9749. set_name_table(p, inner);
  9750. inner->f = NULL;
  9751. inner->is_map = false;
  9752. inner->is_mapentry = false;
  9753. p->top = inner;
  9754. return true;
  9755. } else {
  9756. upb_status_seterrf(&p->status,
  9757. "Object specified for non-message/group field: %s",
  9758. upb_fielddef_name(p->top->f));
  9759. upb_env_reporterror(p->env, &p->status);
  9760. return false;
  9761. }
  9762. }
  9763. static void end_subobject(upb_json_parser *p) {
  9764. if (p->top->is_map) {
  9765. upb_selector_t sel;
  9766. p->top--;
  9767. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
  9768. upb_sink_endseq(&p->top->sink, sel);
  9769. } else {
  9770. upb_selector_t sel;
  9771. p->top--;
  9772. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSUBMSG);
  9773. upb_sink_endsubmsg(&p->top->sink, sel);
  9774. }
  9775. }
  9776. static bool start_array(upb_json_parser *p) {
  9777. upb_jsonparser_frame *inner;
  9778. upb_selector_t sel;
  9779. assert(p->top->f);
  9780. if (!upb_fielddef_isseq(p->top->f)) {
  9781. upb_status_seterrf(&p->status,
  9782. "Array specified for non-repeated field: %s",
  9783. upb_fielddef_name(p->top->f));
  9784. upb_env_reporterror(p->env, &p->status);
  9785. return false;
  9786. }
  9787. if (!check_stack(p)) return false;
  9788. inner = p->top + 1;
  9789. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
  9790. upb_sink_startseq(&p->top->sink, sel, &inner->sink);
  9791. inner->m = p->top->m;
  9792. inner->name_table = NULL;
  9793. inner->f = p->top->f;
  9794. inner->is_map = false;
  9795. inner->is_mapentry = false;
  9796. p->top = inner;
  9797. return true;
  9798. }
  9799. static void end_array(upb_json_parser *p) {
  9800. upb_selector_t sel;
  9801. assert(p->top > p->stack);
  9802. p->top--;
  9803. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
  9804. upb_sink_endseq(&p->top->sink, sel);
  9805. }
  9806. static void start_object(upb_json_parser *p) {
  9807. if (!p->top->is_map) {
  9808. upb_sink_startmsg(&p->top->sink);
  9809. }
  9810. }
  9811. static void end_object(upb_json_parser *p) {
  9812. if (!p->top->is_map) {
  9813. upb_status status;
  9814. upb_status_clear(&status);
  9815. upb_sink_endmsg(&p->top->sink, &status);
  9816. if (!upb_ok(&status)) {
  9817. upb_env_reporterror(p->env, &status);
  9818. }
  9819. }
  9820. }
  9821. #define CHECK_RETURN_TOP(x) if (!(x)) goto error
  9822. /* The actual parser **********************************************************/
  9823. /* What follows is the Ragel parser itself. The language is specified in Ragel
  9824. * and the actions call our C functions above.
  9825. *
  9826. * Ragel has an extensive set of functionality, and we use only a small part of
  9827. * it. There are many action types but we only use a few:
  9828. *
  9829. * ">" -- transition into a machine
  9830. * "%" -- transition out of a machine
  9831. * "@" -- transition into a final state of a machine.
  9832. *
  9833. * "@" transitions are tricky because a machine can transition into a final
  9834. * state repeatedly. But in some cases we know this can't happen, for example
  9835. * a string which is delimited by a final '"' can only transition into its
  9836. * final state once, when the closing '"' is seen. */
  9837. #line 1245 "upb/json/parser.rl"
  9838. #line 1157 "upb/json/parser.c"
  9839. static const char _json_actions[] = {
  9840. 0, 1, 0, 1, 2, 1, 3, 1,
  9841. 5, 1, 6, 1, 7, 1, 8, 1,
  9842. 10, 1, 12, 1, 13, 1, 14, 1,
  9843. 15, 1, 16, 1, 17, 1, 21, 1,
  9844. 25, 1, 27, 2, 3, 8, 2, 4,
  9845. 5, 2, 6, 2, 2, 6, 8, 2,
  9846. 11, 9, 2, 13, 15, 2, 14, 15,
  9847. 2, 18, 1, 2, 19, 27, 2, 20,
  9848. 9, 2, 22, 27, 2, 23, 27, 2,
  9849. 24, 27, 2, 26, 27, 3, 14, 11,
  9850. 9
  9851. };
  9852. static const unsigned char _json_key_offsets[] = {
  9853. 0, 0, 4, 9, 14, 15, 19, 24,
  9854. 29, 34, 38, 42, 45, 48, 50, 54,
  9855. 58, 60, 62, 67, 69, 71, 80, 86,
  9856. 92, 98, 104, 106, 115, 116, 116, 116,
  9857. 121, 126, 131, 132, 133, 134, 135, 135,
  9858. 136, 137, 138, 138, 139, 140, 141, 141,
  9859. 146, 151, 152, 156, 161, 166, 171, 175,
  9860. 175, 178, 178, 178
  9861. };
  9862. static const char _json_trans_keys[] = {
  9863. 32, 123, 9, 13, 32, 34, 125, 9,
  9864. 13, 32, 34, 125, 9, 13, 34, 32,
  9865. 58, 9, 13, 32, 93, 125, 9, 13,
  9866. 32, 44, 125, 9, 13, 32, 44, 125,
  9867. 9, 13, 32, 34, 9, 13, 45, 48,
  9868. 49, 57, 48, 49, 57, 46, 69, 101,
  9869. 48, 57, 69, 101, 48, 57, 43, 45,
  9870. 48, 57, 48, 57, 48, 57, 46, 69,
  9871. 101, 48, 57, 34, 92, 34, 92, 34,
  9872. 47, 92, 98, 102, 110, 114, 116, 117,
  9873. 48, 57, 65, 70, 97, 102, 48, 57,
  9874. 65, 70, 97, 102, 48, 57, 65, 70,
  9875. 97, 102, 48, 57, 65, 70, 97, 102,
  9876. 34, 92, 34, 45, 91, 102, 110, 116,
  9877. 123, 48, 57, 34, 32, 93, 125, 9,
  9878. 13, 32, 44, 93, 9, 13, 32, 93,
  9879. 125, 9, 13, 97, 108, 115, 101, 117,
  9880. 108, 108, 114, 117, 101, 32, 34, 125,
  9881. 9, 13, 32, 34, 125, 9, 13, 34,
  9882. 32, 58, 9, 13, 32, 93, 125, 9,
  9883. 13, 32, 44, 125, 9, 13, 32, 44,
  9884. 125, 9, 13, 32, 34, 9, 13, 32,
  9885. 9, 13, 0
  9886. };
  9887. static const char _json_single_lengths[] = {
  9888. 0, 2, 3, 3, 1, 2, 3, 3,
  9889. 3, 2, 2, 1, 3, 0, 2, 2,
  9890. 0, 0, 3, 2, 2, 9, 0, 0,
  9891. 0, 0, 2, 7, 1, 0, 0, 3,
  9892. 3, 3, 1, 1, 1, 1, 0, 1,
  9893. 1, 1, 0, 1, 1, 1, 0, 3,
  9894. 3, 1, 2, 3, 3, 3, 2, 0,
  9895. 1, 0, 0, 0
  9896. };
  9897. static const char _json_range_lengths[] = {
  9898. 0, 1, 1, 1, 0, 1, 1, 1,
  9899. 1, 1, 1, 1, 0, 1, 1, 1,
  9900. 1, 1, 1, 0, 0, 0, 3, 3,
  9901. 3, 3, 0, 1, 0, 0, 0, 1,
  9902. 1, 1, 0, 0, 0, 0, 0, 0,
  9903. 0, 0, 0, 0, 0, 0, 0, 1,
  9904. 1, 0, 1, 1, 1, 1, 1, 0,
  9905. 1, 0, 0, 0
  9906. };
  9907. static const short _json_index_offsets[] = {
  9908. 0, 0, 4, 9, 14, 16, 20, 25,
  9909. 30, 35, 39, 43, 46, 50, 52, 56,
  9910. 60, 62, 64, 69, 72, 75, 85, 89,
  9911. 93, 97, 101, 104, 113, 115, 116, 117,
  9912. 122, 127, 132, 134, 136, 138, 140, 141,
  9913. 143, 145, 147, 148, 150, 152, 154, 155,
  9914. 160, 165, 167, 171, 176, 181, 186, 190,
  9915. 191, 194, 195, 196
  9916. };
  9917. static const char _json_indicies[] = {
  9918. 0, 2, 0, 1, 3, 4, 5, 3,
  9919. 1, 6, 7, 8, 6, 1, 9, 1,
  9920. 10, 11, 10, 1, 11, 1, 1, 11,
  9921. 12, 13, 14, 15, 13, 1, 16, 17,
  9922. 8, 16, 1, 17, 7, 17, 1, 18,
  9923. 19, 20, 1, 19, 20, 1, 22, 23,
  9924. 23, 21, 24, 1, 23, 23, 24, 21,
  9925. 25, 25, 26, 1, 26, 1, 26, 21,
  9926. 22, 23, 23, 20, 21, 28, 29, 27,
  9927. 31, 32, 30, 33, 33, 33, 33, 33,
  9928. 33, 33, 33, 34, 1, 35, 35, 35,
  9929. 1, 36, 36, 36, 1, 37, 37, 37,
  9930. 1, 38, 38, 38, 1, 40, 41, 39,
  9931. 42, 43, 44, 45, 46, 47, 48, 43,
  9932. 1, 49, 1, 50, 51, 53, 54, 1,
  9933. 53, 52, 55, 56, 54, 55, 1, 56,
  9934. 1, 1, 56, 52, 57, 1, 58, 1,
  9935. 59, 1, 60, 1, 61, 62, 1, 63,
  9936. 1, 64, 1, 65, 66, 1, 67, 1,
  9937. 68, 1, 69, 70, 71, 72, 70, 1,
  9938. 73, 74, 75, 73, 1, 76, 1, 77,
  9939. 78, 77, 1, 78, 1, 1, 78, 79,
  9940. 80, 81, 82, 80, 1, 83, 84, 75,
  9941. 83, 1, 84, 74, 84, 1, 85, 86,
  9942. 86, 1, 1, 1, 1, 0
  9943. };
  9944. static const char _json_trans_targs[] = {
  9945. 1, 0, 2, 3, 4, 56, 3, 4,
  9946. 56, 5, 5, 6, 7, 8, 9, 56,
  9947. 8, 9, 11, 12, 18, 57, 13, 15,
  9948. 14, 16, 17, 20, 58, 21, 20, 58,
  9949. 21, 19, 22, 23, 24, 25, 26, 20,
  9950. 58, 21, 28, 30, 31, 34, 39, 43,
  9951. 47, 29, 59, 59, 32, 31, 29, 32,
  9952. 33, 35, 36, 37, 38, 59, 40, 41,
  9953. 42, 59, 44, 45, 46, 59, 48, 49,
  9954. 55, 48, 49, 55, 50, 50, 51, 52,
  9955. 53, 54, 55, 53, 54, 59, 56
  9956. };
  9957. static const char _json_trans_actions[] = {
  9958. 0, 0, 0, 21, 77, 53, 0, 47,
  9959. 23, 17, 0, 0, 15, 19, 19, 50,
  9960. 0, 0, 0, 0, 0, 1, 0, 0,
  9961. 0, 0, 0, 3, 13, 0, 0, 35,
  9962. 5, 11, 0, 38, 7, 7, 7, 41,
  9963. 44, 9, 62, 56, 25, 0, 0, 0,
  9964. 31, 29, 33, 59, 15, 0, 27, 0,
  9965. 0, 0, 0, 0, 0, 68, 0, 0,
  9966. 0, 71, 0, 0, 0, 65, 21, 77,
  9967. 53, 0, 47, 23, 17, 0, 0, 15,
  9968. 19, 19, 50, 0, 0, 74, 0
  9969. };
  9970. static const int json_start = 1;
  9971. static const int json_en_number_machine = 10;
  9972. static const int json_en_string_machine = 19;
  9973. static const int json_en_value_machine = 27;
  9974. static const int json_en_main = 1;
  9975. #line 1248 "upb/json/parser.rl"
  9976. size_t parse(void *closure, const void *hd, const char *buf, size_t size,
  9977. const upb_bufhandle *handle) {
  9978. upb_json_parser *parser = closure;
  9979. /* Variables used by Ragel's generated code. */
  9980. int cs = parser->current_state;
  9981. int *stack = parser->parser_stack;
  9982. int top = parser->parser_top;
  9983. const char *p = buf;
  9984. const char *pe = buf + size;
  9985. parser->handle = handle;
  9986. UPB_UNUSED(hd);
  9987. UPB_UNUSED(handle);
  9988. capture_resume(parser, buf);
  9989. #line 1328 "upb/json/parser.c"
  9990. {
  9991. int _klen;
  9992. unsigned int _trans;
  9993. const char *_acts;
  9994. unsigned int _nacts;
  9995. const char *_keys;
  9996. if ( p == pe )
  9997. goto _test_eof;
  9998. if ( cs == 0 )
  9999. goto _out;
  10000. _resume:
  10001. _keys = _json_trans_keys + _json_key_offsets[cs];
  10002. _trans = _json_index_offsets[cs];
  10003. _klen = _json_single_lengths[cs];
  10004. if ( _klen > 0 ) {
  10005. const char *_lower = _keys;
  10006. const char *_mid;
  10007. const char *_upper = _keys + _klen - 1;
  10008. while (1) {
  10009. if ( _upper < _lower )
  10010. break;
  10011. _mid = _lower + ((_upper-_lower) >> 1);
  10012. if ( (*p) < *_mid )
  10013. _upper = _mid - 1;
  10014. else if ( (*p) > *_mid )
  10015. _lower = _mid + 1;
  10016. else {
  10017. _trans += (unsigned int)(_mid - _keys);
  10018. goto _match;
  10019. }
  10020. }
  10021. _keys += _klen;
  10022. _trans += _klen;
  10023. }
  10024. _klen = _json_range_lengths[cs];
  10025. if ( _klen > 0 ) {
  10026. const char *_lower = _keys;
  10027. const char *_mid;
  10028. const char *_upper = _keys + (_klen<<1) - 2;
  10029. while (1) {
  10030. if ( _upper < _lower )
  10031. break;
  10032. _mid = _lower + (((_upper-_lower) >> 1) & ~1);
  10033. if ( (*p) < _mid[0] )
  10034. _upper = _mid - 2;
  10035. else if ( (*p) > _mid[1] )
  10036. _lower = _mid + 2;
  10037. else {
  10038. _trans += (unsigned int)((_mid - _keys)>>1);
  10039. goto _match;
  10040. }
  10041. }
  10042. _trans += _klen;
  10043. }
  10044. _match:
  10045. _trans = _json_indicies[_trans];
  10046. cs = _json_trans_targs[_trans];
  10047. if ( _json_trans_actions[_trans] == 0 )
  10048. goto _again;
  10049. _acts = _json_actions + _json_trans_actions[_trans];
  10050. _nacts = (unsigned int) *_acts++;
  10051. while ( _nacts-- > 0 )
  10052. {
  10053. switch ( *_acts++ )
  10054. {
  10055. case 0:
  10056. #line 1160 "upb/json/parser.rl"
  10057. { p--; {cs = stack[--top]; goto _again;} }
  10058. break;
  10059. case 1:
  10060. #line 1161 "upb/json/parser.rl"
  10061. { p--; {stack[top++] = cs; cs = 10; goto _again;} }
  10062. break;
  10063. case 2:
  10064. #line 1165 "upb/json/parser.rl"
  10065. { start_text(parser, p); }
  10066. break;
  10067. case 3:
  10068. #line 1166 "upb/json/parser.rl"
  10069. { CHECK_RETURN_TOP(end_text(parser, p)); }
  10070. break;
  10071. case 4:
  10072. #line 1172 "upb/json/parser.rl"
  10073. { start_hex(parser); }
  10074. break;
  10075. case 5:
  10076. #line 1173 "upb/json/parser.rl"
  10077. { hexdigit(parser, p); }
  10078. break;
  10079. case 6:
  10080. #line 1174 "upb/json/parser.rl"
  10081. { CHECK_RETURN_TOP(end_hex(parser)); }
  10082. break;
  10083. case 7:
  10084. #line 1180 "upb/json/parser.rl"
  10085. { CHECK_RETURN_TOP(escape(parser, p)); }
  10086. break;
  10087. case 8:
  10088. #line 1186 "upb/json/parser.rl"
  10089. { p--; {cs = stack[--top]; goto _again;} }
  10090. break;
  10091. case 9:
  10092. #line 1189 "upb/json/parser.rl"
  10093. { {stack[top++] = cs; cs = 19; goto _again;} }
  10094. break;
  10095. case 10:
  10096. #line 1191 "upb/json/parser.rl"
  10097. { p--; {stack[top++] = cs; cs = 27; goto _again;} }
  10098. break;
  10099. case 11:
  10100. #line 1196 "upb/json/parser.rl"
  10101. { start_member(parser); }
  10102. break;
  10103. case 12:
  10104. #line 1197 "upb/json/parser.rl"
  10105. { CHECK_RETURN_TOP(end_membername(parser)); }
  10106. break;
  10107. case 13:
  10108. #line 1200 "upb/json/parser.rl"
  10109. { end_member(parser); }
  10110. break;
  10111. case 14:
  10112. #line 1206 "upb/json/parser.rl"
  10113. { start_object(parser); }
  10114. break;
  10115. case 15:
  10116. #line 1209 "upb/json/parser.rl"
  10117. { end_object(parser); }
  10118. break;
  10119. case 16:
  10120. #line 1215 "upb/json/parser.rl"
  10121. { CHECK_RETURN_TOP(start_array(parser)); }
  10122. break;
  10123. case 17:
  10124. #line 1219 "upb/json/parser.rl"
  10125. { end_array(parser); }
  10126. break;
  10127. case 18:
  10128. #line 1224 "upb/json/parser.rl"
  10129. { start_number(parser, p); }
  10130. break;
  10131. case 19:
  10132. #line 1225 "upb/json/parser.rl"
  10133. { CHECK_RETURN_TOP(end_number(parser, p)); }
  10134. break;
  10135. case 20:
  10136. #line 1227 "upb/json/parser.rl"
  10137. { CHECK_RETURN_TOP(start_stringval(parser)); }
  10138. break;
  10139. case 21:
  10140. #line 1228 "upb/json/parser.rl"
  10141. { CHECK_RETURN_TOP(end_stringval(parser)); }
  10142. break;
  10143. case 22:
  10144. #line 1230 "upb/json/parser.rl"
  10145. { CHECK_RETURN_TOP(parser_putbool(parser, true)); }
  10146. break;
  10147. case 23:
  10148. #line 1232 "upb/json/parser.rl"
  10149. { CHECK_RETURN_TOP(parser_putbool(parser, false)); }
  10150. break;
  10151. case 24:
  10152. #line 1234 "upb/json/parser.rl"
  10153. { /* null value */ }
  10154. break;
  10155. case 25:
  10156. #line 1236 "upb/json/parser.rl"
  10157. { CHECK_RETURN_TOP(start_subobject(parser)); }
  10158. break;
  10159. case 26:
  10160. #line 1237 "upb/json/parser.rl"
  10161. { end_subobject(parser); }
  10162. break;
  10163. case 27:
  10164. #line 1242 "upb/json/parser.rl"
  10165. { p--; {cs = stack[--top]; goto _again;} }
  10166. break;
  10167. #line 1514 "upb/json/parser.c"
  10168. }
  10169. }
  10170. _again:
  10171. if ( cs == 0 )
  10172. goto _out;
  10173. if ( ++p != pe )
  10174. goto _resume;
  10175. _test_eof: {}
  10176. _out: {}
  10177. }
  10178. #line 1269 "upb/json/parser.rl"
  10179. if (p != pe) {
  10180. upb_status_seterrf(&parser->status, "Parse error at '%.*s'\n", pe - p, p);
  10181. upb_env_reporterror(parser->env, &parser->status);
  10182. } else {
  10183. capture_suspend(parser, &p);
  10184. }
  10185. error:
  10186. /* Save parsing state back to parser. */
  10187. parser->current_state = cs;
  10188. parser->parser_top = top;
  10189. return p - buf;
  10190. }
  10191. bool end(void *closure, const void *hd) {
  10192. UPB_UNUSED(closure);
  10193. UPB_UNUSED(hd);
  10194. /* Prevent compile warning on unused static constants. */
  10195. UPB_UNUSED(json_start);
  10196. UPB_UNUSED(json_en_number_machine);
  10197. UPB_UNUSED(json_en_string_machine);
  10198. UPB_UNUSED(json_en_value_machine);
  10199. UPB_UNUSED(json_en_main);
  10200. return true;
  10201. }
  10202. static void json_parser_reset(upb_json_parser *p) {
  10203. int cs;
  10204. int top;
  10205. p->top = p->stack;
  10206. p->top->f = NULL;
  10207. p->top->is_map = false;
  10208. p->top->is_mapentry = false;
  10209. /* Emit Ragel initialization of the parser. */
  10210. #line 1568 "upb/json/parser.c"
  10211. {
  10212. cs = json_start;
  10213. top = 0;
  10214. }
  10215. #line 1309 "upb/json/parser.rl"
  10216. p->current_state = cs;
  10217. p->parser_top = top;
  10218. accumulate_clear(p);
  10219. p->multipart_state = MULTIPART_INACTIVE;
  10220. p->capture = NULL;
  10221. p->accumulated = NULL;
  10222. upb_status_clear(&p->status);
  10223. }
  10224. static void visit_json_parsermethod(const upb_refcounted *r,
  10225. upb_refcounted_visit *visit,
  10226. void *closure) {
  10227. const upb_json_parsermethod *method = (upb_json_parsermethod*)r;
  10228. visit(r, upb_msgdef_upcast2(method->msg), closure);
  10229. }
  10230. static void free_json_parsermethod(upb_refcounted *r) {
  10231. upb_json_parsermethod *method = (upb_json_parsermethod*)r;
  10232. upb_inttable_iter i;
  10233. upb_inttable_begin(&i, &method->name_tables);
  10234. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  10235. upb_value val = upb_inttable_iter_value(&i);
  10236. upb_strtable *t = upb_value_getptr(val);
  10237. upb_strtable_uninit(t);
  10238. upb_gfree(t);
  10239. }
  10240. upb_inttable_uninit(&method->name_tables);
  10241. upb_gfree(r);
  10242. }
  10243. static void add_jsonname_table(upb_json_parsermethod *m, const upb_msgdef* md) {
  10244. upb_msg_field_iter i;
  10245. upb_strtable *t;
  10246. /* It would be nice to stack-allocate this, but protobufs do not limit the
  10247. * length of fields to any reasonable limit. */
  10248. char *buf = NULL;
  10249. size_t len = 0;
  10250. if (upb_inttable_lookupptr(&m->name_tables, md, NULL)) {
  10251. return;
  10252. }
  10253. /* TODO(haberman): handle malloc failure. */
  10254. t = upb_gmalloc(sizeof(*t));
  10255. upb_strtable_init(t, UPB_CTYPE_CONSTPTR);
  10256. upb_inttable_insertptr(&m->name_tables, md, upb_value_ptr(t));
  10257. for(upb_msg_field_begin(&i, md);
  10258. !upb_msg_field_done(&i);
  10259. upb_msg_field_next(&i)) {
  10260. const upb_fielddef *f = upb_msg_iter_field(&i);
  10261. /* Add an entry for the JSON name. */
  10262. size_t field_len = upb_fielddef_getjsonname(f, buf, len);
  10263. if (field_len > len) {
  10264. size_t len2;
  10265. buf = upb_grealloc(buf, 0, field_len);
  10266. len = field_len;
  10267. len2 = upb_fielddef_getjsonname(f, buf, len);
  10268. UPB_ASSERT_VAR(len2, len == len2);
  10269. }
  10270. upb_strtable_insert(t, buf, upb_value_constptr(f));
  10271. if (strcmp(buf, upb_fielddef_name(f)) != 0) {
  10272. /* Since the JSON name is different from the regular field name, add an
  10273. * entry for the raw name (compliant proto3 JSON parsers must accept
  10274. * both). */
  10275. upb_strtable_insert(t, upb_fielddef_name(f), upb_value_constptr(f));
  10276. }
  10277. if (upb_fielddef_issubmsg(f)) {
  10278. add_jsonname_table(m, upb_fielddef_msgsubdef(f));
  10279. }
  10280. }
  10281. upb_gfree(buf);
  10282. }
  10283. /* Public API *****************************************************************/
  10284. upb_json_parser *upb_json_parser_create(upb_env *env,
  10285. const upb_json_parsermethod *method,
  10286. upb_sink *output) {
  10287. #ifndef NDEBUG
  10288. const size_t size_before = upb_env_bytesallocated(env);
  10289. #endif
  10290. upb_json_parser *p = upb_env_malloc(env, sizeof(upb_json_parser));
  10291. if (!p) return false;
  10292. p->env = env;
  10293. p->method = method;
  10294. p->limit = p->stack + UPB_JSON_MAX_DEPTH;
  10295. p->accumulate_buf = NULL;
  10296. p->accumulate_buf_size = 0;
  10297. upb_bytessink_reset(&p->input_, &method->input_handler_, p);
  10298. json_parser_reset(p);
  10299. upb_sink_reset(&p->top->sink, output->handlers, output->closure);
  10300. p->top->m = upb_handlers_msgdef(output->handlers);
  10301. set_name_table(p, p->top);
  10302. /* If this fails, uncomment and increase the value in parser.h. */
  10303. /* fprintf(stderr, "%zd\n", upb_env_bytesallocated(env) - size_before); */
  10304. assert(upb_env_bytesallocated(env) - size_before <= UPB_JSON_PARSER_SIZE);
  10305. return p;
  10306. }
  10307. upb_bytessink *upb_json_parser_input(upb_json_parser *p) {
  10308. return &p->input_;
  10309. }
  10310. upb_json_parsermethod *upb_json_parsermethod_new(const upb_msgdef* md,
  10311. const void* owner) {
  10312. static const struct upb_refcounted_vtbl vtbl = {visit_json_parsermethod,
  10313. free_json_parsermethod};
  10314. upb_json_parsermethod *ret = upb_gmalloc(sizeof(*ret));
  10315. upb_refcounted_init(upb_json_parsermethod_upcast_mutable(ret), &vtbl, owner);
  10316. ret->msg = md;
  10317. upb_ref2(md, ret);
  10318. upb_byteshandler_init(&ret->input_handler_);
  10319. upb_byteshandler_setstring(&ret->input_handler_, parse, ret);
  10320. upb_byteshandler_setendstr(&ret->input_handler_, end, ret);
  10321. upb_inttable_init(&ret->name_tables, UPB_CTYPE_PTR);
  10322. add_jsonname_table(ret, md);
  10323. return ret;
  10324. }
  10325. const upb_byteshandler *upb_json_parsermethod_inputhandler(
  10326. const upb_json_parsermethod *m) {
  10327. return &m->input_handler_;
  10328. }
  10329. /*
  10330. ** This currently uses snprintf() to format primitives, and could be optimized
  10331. ** further.
  10332. */
  10333. #include <string.h>
  10334. #include <stdint.h>
  10335. struct upb_json_printer {
  10336. upb_sink input_;
  10337. /* BytesSink closure. */
  10338. void *subc_;
  10339. upb_bytessink *output_;
  10340. /* We track the depth so that we know when to emit startstr/endstr on the
  10341. * output. */
  10342. int depth_;
  10343. /* Have we emitted the first element? This state is necessary to emit commas
  10344. * without leaving a trailing comma in arrays/maps. We keep this state per
  10345. * frame depth.
  10346. *
  10347. * Why max_depth * 2? UPB_MAX_HANDLER_DEPTH counts depth as nested messages.
  10348. * We count frames (contexts in which we separate elements by commas) as both
  10349. * repeated fields and messages (maps), and the worst case is a
  10350. * message->repeated field->submessage->repeated field->... nesting. */
  10351. bool first_elem_[UPB_MAX_HANDLER_DEPTH * 2];
  10352. };
  10353. /* StringPiece; a pointer plus a length. */
  10354. typedef struct {
  10355. char *ptr;
  10356. size_t len;
  10357. } strpc;
  10358. void freestrpc(void *ptr) {
  10359. strpc *pc = ptr;
  10360. upb_gfree(pc->ptr);
  10361. upb_gfree(pc);
  10362. }
  10363. /* Convert fielddef name to JSON name and return as a string piece. */
  10364. strpc *newstrpc(upb_handlers *h, const upb_fielddef *f,
  10365. bool preserve_fieldnames) {
  10366. /* TODO(haberman): handle malloc failure. */
  10367. strpc *ret = upb_gmalloc(sizeof(*ret));
  10368. if (preserve_fieldnames) {
  10369. ret->ptr = upb_gstrdup(upb_fielddef_name(f));
  10370. ret->len = strlen(ret->ptr);
  10371. } else {
  10372. size_t len;
  10373. ret->len = upb_fielddef_getjsonname(f, NULL, 0);
  10374. ret->ptr = upb_gmalloc(ret->len);
  10375. len = upb_fielddef_getjsonname(f, ret->ptr, ret->len);
  10376. UPB_ASSERT_VAR(len, len == ret->len);
  10377. ret->len--; /* NULL */
  10378. }
  10379. upb_handlers_addcleanup(h, ret, freestrpc);
  10380. return ret;
  10381. }
  10382. /* ------------ JSON string printing: values, maps, arrays ------------------ */
  10383. static void print_data(
  10384. upb_json_printer *p, const char *buf, unsigned int len) {
  10385. /* TODO: Will need to change if we support pushback from the sink. */
  10386. size_t n = upb_bytessink_putbuf(p->output_, p->subc_, buf, len, NULL);
  10387. UPB_ASSERT_VAR(n, n == len);
  10388. }
  10389. static void print_comma(upb_json_printer *p) {
  10390. if (!p->first_elem_[p->depth_]) {
  10391. print_data(p, ",", 1);
  10392. }
  10393. p->first_elem_[p->depth_] = false;
  10394. }
  10395. /* Helpers that print properly formatted elements to the JSON output stream. */
  10396. /* Used for escaping control chars in strings. */
  10397. static const char kControlCharLimit = 0x20;
  10398. UPB_INLINE bool is_json_escaped(char c) {
  10399. /* See RFC 4627. */
  10400. unsigned char uc = (unsigned char)c;
  10401. return uc < kControlCharLimit || uc == '"' || uc == '\\';
  10402. }
  10403. UPB_INLINE const char* json_nice_escape(char c) {
  10404. switch (c) {
  10405. case '"': return "\\\"";
  10406. case '\\': return "\\\\";
  10407. case '\b': return "\\b";
  10408. case '\f': return "\\f";
  10409. case '\n': return "\\n";
  10410. case '\r': return "\\r";
  10411. case '\t': return "\\t";
  10412. default: return NULL;
  10413. }
  10414. }
  10415. /* Write a properly escaped string chunk. The surrounding quotes are *not*
  10416. * printed; this is so that the caller has the option of emitting the string
  10417. * content in chunks. */
  10418. static void putstring(upb_json_printer *p, const char *buf, unsigned int len) {
  10419. const char* unescaped_run = NULL;
  10420. unsigned int i;
  10421. for (i = 0; i < len; i++) {
  10422. char c = buf[i];
  10423. /* Handle escaping. */
  10424. if (is_json_escaped(c)) {
  10425. /* Use a "nice" escape, like \n, if one exists for this character. */
  10426. const char* escape = json_nice_escape(c);
  10427. /* If we don't have a specific 'nice' escape code, use a \uXXXX-style
  10428. * escape. */
  10429. char escape_buf[8];
  10430. if (!escape) {
  10431. unsigned char byte = (unsigned char)c;
  10432. _upb_snprintf(escape_buf, sizeof(escape_buf), "\\u%04x", (int)byte);
  10433. escape = escape_buf;
  10434. }
  10435. /* N.B. that we assume that the input encoding is equal to the output
  10436. * encoding (both UTF-8 for now), so for chars >= 0x20 and != \, ", we
  10437. * can simply pass the bytes through. */
  10438. /* If there's a current run of unescaped chars, print that run first. */
  10439. if (unescaped_run) {
  10440. print_data(p, unescaped_run, &buf[i] - unescaped_run);
  10441. unescaped_run = NULL;
  10442. }
  10443. /* Then print the escape code. */
  10444. print_data(p, escape, strlen(escape));
  10445. } else {
  10446. /* Add to the current unescaped run of characters. */
  10447. if (unescaped_run == NULL) {
  10448. unescaped_run = &buf[i];
  10449. }
  10450. }
  10451. }
  10452. /* If the string ended in a run of unescaped characters, print that last run. */
  10453. if (unescaped_run) {
  10454. print_data(p, unescaped_run, &buf[len] - unescaped_run);
  10455. }
  10456. }
  10457. #define CHKLENGTH(x) if (!(x)) return -1;
  10458. /* Helpers that format floating point values according to our custom formats.
  10459. * Right now we use %.8g and %.17g for float/double, respectively, to match
  10460. * proto2::util::JsonFormat's defaults. May want to change this later. */
  10461. static size_t fmt_double(double val, char* buf, size_t length) {
  10462. size_t n = _upb_snprintf(buf, length, "%.17g", val);
  10463. CHKLENGTH(n > 0 && n < length);
  10464. return n;
  10465. }
  10466. static size_t fmt_float(float val, char* buf, size_t length) {
  10467. size_t n = _upb_snprintf(buf, length, "%.8g", val);
  10468. CHKLENGTH(n > 0 && n < length);
  10469. return n;
  10470. }
  10471. static size_t fmt_bool(bool val, char* buf, size_t length) {
  10472. size_t n = _upb_snprintf(buf, length, "%s", (val ? "true" : "false"));
  10473. CHKLENGTH(n > 0 && n < length);
  10474. return n;
  10475. }
  10476. static size_t fmt_int64(long val, char* buf, size_t length) {
  10477. size_t n = _upb_snprintf(buf, length, "%ld", val);
  10478. CHKLENGTH(n > 0 && n < length);
  10479. return n;
  10480. }
  10481. static size_t fmt_uint64(unsigned long long val, char* buf, size_t length) {
  10482. size_t n = _upb_snprintf(buf, length, "%llu", val);
  10483. CHKLENGTH(n > 0 && n < length);
  10484. return n;
  10485. }
  10486. /* Print a map key given a field name. Called by scalar field handlers and by
  10487. * startseq for repeated fields. */
  10488. static bool putkey(void *closure, const void *handler_data) {
  10489. upb_json_printer *p = closure;
  10490. const strpc *key = handler_data;
  10491. print_comma(p);
  10492. print_data(p, "\"", 1);
  10493. putstring(p, key->ptr, key->len);
  10494. print_data(p, "\":", 2);
  10495. return true;
  10496. }
  10497. #define CHKFMT(val) if ((val) == (size_t)-1) return false;
  10498. #define CHK(val) if (!(val)) return false;
  10499. #define TYPE_HANDLERS(type, fmt_func) \
  10500. static bool put##type(void *closure, const void *handler_data, type val) { \
  10501. upb_json_printer *p = closure; \
  10502. char data[64]; \
  10503. size_t length = fmt_func(val, data, sizeof(data)); \
  10504. UPB_UNUSED(handler_data); \
  10505. CHKFMT(length); \
  10506. print_data(p, data, length); \
  10507. return true; \
  10508. } \
  10509. static bool scalar_##type(void *closure, const void *handler_data, \
  10510. type val) { \
  10511. CHK(putkey(closure, handler_data)); \
  10512. CHK(put##type(closure, handler_data, val)); \
  10513. return true; \
  10514. } \
  10515. static bool repeated_##type(void *closure, const void *handler_data, \
  10516. type val) { \
  10517. upb_json_printer *p = closure; \
  10518. print_comma(p); \
  10519. CHK(put##type(closure, handler_data, val)); \
  10520. return true; \
  10521. }
  10522. #define TYPE_HANDLERS_MAPKEY(type, fmt_func) \
  10523. static bool putmapkey_##type(void *closure, const void *handler_data, \
  10524. type val) { \
  10525. upb_json_printer *p = closure; \
  10526. print_data(p, "\"", 1); \
  10527. CHK(put##type(closure, handler_data, val)); \
  10528. print_data(p, "\":", 2); \
  10529. return true; \
  10530. }
  10531. TYPE_HANDLERS(double, fmt_double)
  10532. TYPE_HANDLERS(float, fmt_float)
  10533. TYPE_HANDLERS(bool, fmt_bool)
  10534. TYPE_HANDLERS(int32_t, fmt_int64)
  10535. TYPE_HANDLERS(uint32_t, fmt_int64)
  10536. TYPE_HANDLERS(int64_t, fmt_int64)
  10537. TYPE_HANDLERS(uint64_t, fmt_uint64)
  10538. /* double and float are not allowed to be map keys. */
  10539. TYPE_HANDLERS_MAPKEY(bool, fmt_bool)
  10540. TYPE_HANDLERS_MAPKEY(int32_t, fmt_int64)
  10541. TYPE_HANDLERS_MAPKEY(uint32_t, fmt_int64)
  10542. TYPE_HANDLERS_MAPKEY(int64_t, fmt_int64)
  10543. TYPE_HANDLERS_MAPKEY(uint64_t, fmt_uint64)
  10544. #undef TYPE_HANDLERS
  10545. #undef TYPE_HANDLERS_MAPKEY
  10546. typedef struct {
  10547. void *keyname;
  10548. const upb_enumdef *enumdef;
  10549. } EnumHandlerData;
  10550. static bool scalar_enum(void *closure, const void *handler_data,
  10551. int32_t val) {
  10552. const EnumHandlerData *hd = handler_data;
  10553. upb_json_printer *p = closure;
  10554. const char *symbolic_name;
  10555. CHK(putkey(closure, hd->keyname));
  10556. symbolic_name = upb_enumdef_iton(hd->enumdef, val);
  10557. if (symbolic_name) {
  10558. print_data(p, "\"", 1);
  10559. putstring(p, symbolic_name, strlen(symbolic_name));
  10560. print_data(p, "\"", 1);
  10561. } else {
  10562. putint32_t(closure, NULL, val);
  10563. }
  10564. return true;
  10565. }
  10566. static void print_enum_symbolic_name(upb_json_printer *p,
  10567. const upb_enumdef *def,
  10568. int32_t val) {
  10569. const char *symbolic_name = upb_enumdef_iton(def, val);
  10570. if (symbolic_name) {
  10571. print_data(p, "\"", 1);
  10572. putstring(p, symbolic_name, strlen(symbolic_name));
  10573. print_data(p, "\"", 1);
  10574. } else {
  10575. putint32_t(p, NULL, val);
  10576. }
  10577. }
  10578. static bool repeated_enum(void *closure, const void *handler_data,
  10579. int32_t val) {
  10580. const EnumHandlerData *hd = handler_data;
  10581. upb_json_printer *p = closure;
  10582. print_comma(p);
  10583. print_enum_symbolic_name(p, hd->enumdef, val);
  10584. return true;
  10585. }
  10586. static bool mapvalue_enum(void *closure, const void *handler_data,
  10587. int32_t val) {
  10588. const EnumHandlerData *hd = handler_data;
  10589. upb_json_printer *p = closure;
  10590. print_enum_symbolic_name(p, hd->enumdef, val);
  10591. return true;
  10592. }
  10593. static void *scalar_startsubmsg(void *closure, const void *handler_data) {
  10594. return putkey(closure, handler_data) ? closure : UPB_BREAK;
  10595. }
  10596. static void *repeated_startsubmsg(void *closure, const void *handler_data) {
  10597. upb_json_printer *p = closure;
  10598. UPB_UNUSED(handler_data);
  10599. print_comma(p);
  10600. return closure;
  10601. }
  10602. static void start_frame(upb_json_printer *p) {
  10603. p->depth_++;
  10604. p->first_elem_[p->depth_] = true;
  10605. print_data(p, "{", 1);
  10606. }
  10607. static void end_frame(upb_json_printer *p) {
  10608. print_data(p, "}", 1);
  10609. p->depth_--;
  10610. }
  10611. static bool printer_startmsg(void *closure, const void *handler_data) {
  10612. upb_json_printer *p = closure;
  10613. UPB_UNUSED(handler_data);
  10614. if (p->depth_ == 0) {
  10615. upb_bytessink_start(p->output_, 0, &p->subc_);
  10616. }
  10617. start_frame(p);
  10618. return true;
  10619. }
  10620. static bool printer_endmsg(void *closure, const void *handler_data, upb_status *s) {
  10621. upb_json_printer *p = closure;
  10622. UPB_UNUSED(handler_data);
  10623. UPB_UNUSED(s);
  10624. end_frame(p);
  10625. if (p->depth_ == 0) {
  10626. upb_bytessink_end(p->output_);
  10627. }
  10628. return true;
  10629. }
  10630. static void *startseq(void *closure, const void *handler_data) {
  10631. upb_json_printer *p = closure;
  10632. CHK(putkey(closure, handler_data));
  10633. p->depth_++;
  10634. p->first_elem_[p->depth_] = true;
  10635. print_data(p, "[", 1);
  10636. return closure;
  10637. }
  10638. static bool endseq(void *closure, const void *handler_data) {
  10639. upb_json_printer *p = closure;
  10640. UPB_UNUSED(handler_data);
  10641. print_data(p, "]", 1);
  10642. p->depth_--;
  10643. return true;
  10644. }
  10645. static void *startmap(void *closure, const void *handler_data) {
  10646. upb_json_printer *p = closure;
  10647. CHK(putkey(closure, handler_data));
  10648. p->depth_++;
  10649. p->first_elem_[p->depth_] = true;
  10650. print_data(p, "{", 1);
  10651. return closure;
  10652. }
  10653. static bool endmap(void *closure, const void *handler_data) {
  10654. upb_json_printer *p = closure;
  10655. UPB_UNUSED(handler_data);
  10656. print_data(p, "}", 1);
  10657. p->depth_--;
  10658. return true;
  10659. }
  10660. static size_t putstr(void *closure, const void *handler_data, const char *str,
  10661. size_t len, const upb_bufhandle *handle) {
  10662. upb_json_printer *p = closure;
  10663. UPB_UNUSED(handler_data);
  10664. UPB_UNUSED(handle);
  10665. putstring(p, str, len);
  10666. return len;
  10667. }
  10668. /* This has to Base64 encode the bytes, because JSON has no "bytes" type. */
  10669. static size_t putbytes(void *closure, const void *handler_data, const char *str,
  10670. size_t len, const upb_bufhandle *handle) {
  10671. upb_json_printer *p = closure;
  10672. /* This is the regular base64, not the "web-safe" version. */
  10673. static const char base64[] =
  10674. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  10675. /* Base64-encode. */
  10676. char data[16000];
  10677. const char *limit = data + sizeof(data);
  10678. const unsigned char *from = (const unsigned char*)str;
  10679. char *to = data;
  10680. size_t remaining = len;
  10681. size_t bytes;
  10682. UPB_UNUSED(handler_data);
  10683. UPB_UNUSED(handle);
  10684. while (remaining > 2) {
  10685. /* TODO(haberman): handle encoded lengths > sizeof(data) */
  10686. UPB_ASSERT_VAR(limit, (limit - to) >= 4);
  10687. to[0] = base64[from[0] >> 2];
  10688. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  10689. to[2] = base64[((from[1] & 0xf) << 2) | (from[2] >> 6)];
  10690. to[3] = base64[from[2] & 0x3f];
  10691. remaining -= 3;
  10692. to += 4;
  10693. from += 3;
  10694. }
  10695. switch (remaining) {
  10696. case 2:
  10697. to[0] = base64[from[0] >> 2];
  10698. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  10699. to[2] = base64[(from[1] & 0xf) << 2];
  10700. to[3] = '=';
  10701. to += 4;
  10702. from += 2;
  10703. break;
  10704. case 1:
  10705. to[0] = base64[from[0] >> 2];
  10706. to[1] = base64[((from[0] & 0x3) << 4)];
  10707. to[2] = '=';
  10708. to[3] = '=';
  10709. to += 4;
  10710. from += 1;
  10711. break;
  10712. }
  10713. bytes = to - data;
  10714. print_data(p, "\"", 1);
  10715. putstring(p, data, bytes);
  10716. print_data(p, "\"", 1);
  10717. return len;
  10718. }
  10719. static void *scalar_startstr(void *closure, const void *handler_data,
  10720. size_t size_hint) {
  10721. upb_json_printer *p = closure;
  10722. UPB_UNUSED(handler_data);
  10723. UPB_UNUSED(size_hint);
  10724. CHK(putkey(closure, handler_data));
  10725. print_data(p, "\"", 1);
  10726. return p;
  10727. }
  10728. static size_t scalar_str(void *closure, const void *handler_data,
  10729. const char *str, size_t len,
  10730. const upb_bufhandle *handle) {
  10731. CHK(putstr(closure, handler_data, str, len, handle));
  10732. return len;
  10733. }
  10734. static bool scalar_endstr(void *closure, const void *handler_data) {
  10735. upb_json_printer *p = closure;
  10736. UPB_UNUSED(handler_data);
  10737. print_data(p, "\"", 1);
  10738. return true;
  10739. }
  10740. static void *repeated_startstr(void *closure, const void *handler_data,
  10741. size_t size_hint) {
  10742. upb_json_printer *p = closure;
  10743. UPB_UNUSED(handler_data);
  10744. UPB_UNUSED(size_hint);
  10745. print_comma(p);
  10746. print_data(p, "\"", 1);
  10747. return p;
  10748. }
  10749. static size_t repeated_str(void *closure, const void *handler_data,
  10750. const char *str, size_t len,
  10751. const upb_bufhandle *handle) {
  10752. CHK(putstr(closure, handler_data, str, len, handle));
  10753. return len;
  10754. }
  10755. static bool repeated_endstr(void *closure, const void *handler_data) {
  10756. upb_json_printer *p = closure;
  10757. UPB_UNUSED(handler_data);
  10758. print_data(p, "\"", 1);
  10759. return true;
  10760. }
  10761. static void *mapkeyval_startstr(void *closure, const void *handler_data,
  10762. size_t size_hint) {
  10763. upb_json_printer *p = closure;
  10764. UPB_UNUSED(handler_data);
  10765. UPB_UNUSED(size_hint);
  10766. print_data(p, "\"", 1);
  10767. return p;
  10768. }
  10769. static size_t mapkey_str(void *closure, const void *handler_data,
  10770. const char *str, size_t len,
  10771. const upb_bufhandle *handle) {
  10772. CHK(putstr(closure, handler_data, str, len, handle));
  10773. return len;
  10774. }
  10775. static bool mapkey_endstr(void *closure, const void *handler_data) {
  10776. upb_json_printer *p = closure;
  10777. UPB_UNUSED(handler_data);
  10778. print_data(p, "\":", 2);
  10779. return true;
  10780. }
  10781. static bool mapvalue_endstr(void *closure, const void *handler_data) {
  10782. upb_json_printer *p = closure;
  10783. UPB_UNUSED(handler_data);
  10784. print_data(p, "\"", 1);
  10785. return true;
  10786. }
  10787. static size_t scalar_bytes(void *closure, const void *handler_data,
  10788. const char *str, size_t len,
  10789. const upb_bufhandle *handle) {
  10790. CHK(putkey(closure, handler_data));
  10791. CHK(putbytes(closure, handler_data, str, len, handle));
  10792. return len;
  10793. }
  10794. static size_t repeated_bytes(void *closure, const void *handler_data,
  10795. const char *str, size_t len,
  10796. const upb_bufhandle *handle) {
  10797. upb_json_printer *p = closure;
  10798. print_comma(p);
  10799. CHK(putbytes(closure, handler_data, str, len, handle));
  10800. return len;
  10801. }
  10802. static size_t mapkey_bytes(void *closure, const void *handler_data,
  10803. const char *str, size_t len,
  10804. const upb_bufhandle *handle) {
  10805. upb_json_printer *p = closure;
  10806. CHK(putbytes(closure, handler_data, str, len, handle));
  10807. print_data(p, ":", 1);
  10808. return len;
  10809. }
  10810. static void set_enum_hd(upb_handlers *h,
  10811. const upb_fielddef *f,
  10812. bool preserve_fieldnames,
  10813. upb_handlerattr *attr) {
  10814. EnumHandlerData *hd = upb_gmalloc(sizeof(EnumHandlerData));
  10815. hd->enumdef = (const upb_enumdef *)upb_fielddef_subdef(f);
  10816. hd->keyname = newstrpc(h, f, preserve_fieldnames);
  10817. upb_handlers_addcleanup(h, hd, upb_gfree);
  10818. upb_handlerattr_sethandlerdata(attr, hd);
  10819. }
  10820. /* Set up handlers for a mapentry submessage (i.e., an individual key/value pair
  10821. * in a map).
  10822. *
  10823. * TODO: Handle missing key, missing value, out-of-order key/value, or repeated
  10824. * key or value cases properly. The right way to do this is to allocate a
  10825. * temporary structure at the start of a mapentry submessage, store key and
  10826. * value data in it as key and value handlers are called, and then print the
  10827. * key/value pair once at the end of the submessage. If we don't do this, we
  10828. * should at least detect the case and throw an error. However, so far all of
  10829. * our sources that emit mapentry messages do so canonically (with one key
  10830. * field, and then one value field), so this is not a pressing concern at the
  10831. * moment. */
  10832. void printer_sethandlers_mapentry(const void *closure, bool preserve_fieldnames,
  10833. upb_handlers *h) {
  10834. const upb_msgdef *md = upb_handlers_msgdef(h);
  10835. /* A mapentry message is printed simply as '"key": value'. Rather than
  10836. * special-case key and value for every type below, we just handle both
  10837. * fields explicitly here. */
  10838. const upb_fielddef* key_field = upb_msgdef_itof(md, UPB_MAPENTRY_KEY);
  10839. const upb_fielddef* value_field = upb_msgdef_itof(md, UPB_MAPENTRY_VALUE);
  10840. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  10841. UPB_UNUSED(closure);
  10842. switch (upb_fielddef_type(key_field)) {
  10843. case UPB_TYPE_INT32:
  10844. upb_handlers_setint32(h, key_field, putmapkey_int32_t, &empty_attr);
  10845. break;
  10846. case UPB_TYPE_INT64:
  10847. upb_handlers_setint64(h, key_field, putmapkey_int64_t, &empty_attr);
  10848. break;
  10849. case UPB_TYPE_UINT32:
  10850. upb_handlers_setuint32(h, key_field, putmapkey_uint32_t, &empty_attr);
  10851. break;
  10852. case UPB_TYPE_UINT64:
  10853. upb_handlers_setuint64(h, key_field, putmapkey_uint64_t, &empty_attr);
  10854. break;
  10855. case UPB_TYPE_BOOL:
  10856. upb_handlers_setbool(h, key_field, putmapkey_bool, &empty_attr);
  10857. break;
  10858. case UPB_TYPE_STRING:
  10859. upb_handlers_setstartstr(h, key_field, mapkeyval_startstr, &empty_attr);
  10860. upb_handlers_setstring(h, key_field, mapkey_str, &empty_attr);
  10861. upb_handlers_setendstr(h, key_field, mapkey_endstr, &empty_attr);
  10862. break;
  10863. case UPB_TYPE_BYTES:
  10864. upb_handlers_setstring(h, key_field, mapkey_bytes, &empty_attr);
  10865. break;
  10866. default:
  10867. assert(false);
  10868. break;
  10869. }
  10870. switch (upb_fielddef_type(value_field)) {
  10871. case UPB_TYPE_INT32:
  10872. upb_handlers_setint32(h, value_field, putint32_t, &empty_attr);
  10873. break;
  10874. case UPB_TYPE_INT64:
  10875. upb_handlers_setint64(h, value_field, putint64_t, &empty_attr);
  10876. break;
  10877. case UPB_TYPE_UINT32:
  10878. upb_handlers_setuint32(h, value_field, putuint32_t, &empty_attr);
  10879. break;
  10880. case UPB_TYPE_UINT64:
  10881. upb_handlers_setuint64(h, value_field, putuint64_t, &empty_attr);
  10882. break;
  10883. case UPB_TYPE_BOOL:
  10884. upb_handlers_setbool(h, value_field, putbool, &empty_attr);
  10885. break;
  10886. case UPB_TYPE_FLOAT:
  10887. upb_handlers_setfloat(h, value_field, putfloat, &empty_attr);
  10888. break;
  10889. case UPB_TYPE_DOUBLE:
  10890. upb_handlers_setdouble(h, value_field, putdouble, &empty_attr);
  10891. break;
  10892. case UPB_TYPE_STRING:
  10893. upb_handlers_setstartstr(h, value_field, mapkeyval_startstr, &empty_attr);
  10894. upb_handlers_setstring(h, value_field, putstr, &empty_attr);
  10895. upb_handlers_setendstr(h, value_field, mapvalue_endstr, &empty_attr);
  10896. break;
  10897. case UPB_TYPE_BYTES:
  10898. upb_handlers_setstring(h, value_field, putbytes, &empty_attr);
  10899. break;
  10900. case UPB_TYPE_ENUM: {
  10901. upb_handlerattr enum_attr = UPB_HANDLERATTR_INITIALIZER;
  10902. set_enum_hd(h, value_field, preserve_fieldnames, &enum_attr);
  10903. upb_handlers_setint32(h, value_field, mapvalue_enum, &enum_attr);
  10904. upb_handlerattr_uninit(&enum_attr);
  10905. break;
  10906. }
  10907. case UPB_TYPE_MESSAGE:
  10908. /* No handler necessary -- the submsg handlers will print the message
  10909. * as appropriate. */
  10910. break;
  10911. }
  10912. upb_handlerattr_uninit(&empty_attr);
  10913. }
  10914. void printer_sethandlers(const void *closure, upb_handlers *h) {
  10915. const upb_msgdef *md = upb_handlers_msgdef(h);
  10916. bool is_mapentry = upb_msgdef_mapentry(md);
  10917. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  10918. upb_msg_field_iter i;
  10919. const bool *preserve_fieldnames_ptr = closure;
  10920. const bool preserve_fieldnames = *preserve_fieldnames_ptr;
  10921. if (is_mapentry) {
  10922. /* mapentry messages are sufficiently different that we handle them
  10923. * separately. */
  10924. printer_sethandlers_mapentry(closure, preserve_fieldnames, h);
  10925. return;
  10926. }
  10927. upb_handlers_setstartmsg(h, printer_startmsg, &empty_attr);
  10928. upb_handlers_setendmsg(h, printer_endmsg, &empty_attr);
  10929. #define TYPE(type, name, ctype) \
  10930. case type: \
  10931. if (upb_fielddef_isseq(f)) { \
  10932. upb_handlers_set##name(h, f, repeated_##ctype, &empty_attr); \
  10933. } else { \
  10934. upb_handlers_set##name(h, f, scalar_##ctype, &name_attr); \
  10935. } \
  10936. break;
  10937. upb_msg_field_begin(&i, md);
  10938. for(; !upb_msg_field_done(&i); upb_msg_field_next(&i)) {
  10939. const upb_fielddef *f = upb_msg_iter_field(&i);
  10940. upb_handlerattr name_attr = UPB_HANDLERATTR_INITIALIZER;
  10941. upb_handlerattr_sethandlerdata(&name_attr,
  10942. newstrpc(h, f, preserve_fieldnames));
  10943. if (upb_fielddef_ismap(f)) {
  10944. upb_handlers_setstartseq(h, f, startmap, &name_attr);
  10945. upb_handlers_setendseq(h, f, endmap, &name_attr);
  10946. } else if (upb_fielddef_isseq(f)) {
  10947. upb_handlers_setstartseq(h, f, startseq, &name_attr);
  10948. upb_handlers_setendseq(h, f, endseq, &empty_attr);
  10949. }
  10950. switch (upb_fielddef_type(f)) {
  10951. TYPE(UPB_TYPE_FLOAT, float, float);
  10952. TYPE(UPB_TYPE_DOUBLE, double, double);
  10953. TYPE(UPB_TYPE_BOOL, bool, bool);
  10954. TYPE(UPB_TYPE_INT32, int32, int32_t);
  10955. TYPE(UPB_TYPE_UINT32, uint32, uint32_t);
  10956. TYPE(UPB_TYPE_INT64, int64, int64_t);
  10957. TYPE(UPB_TYPE_UINT64, uint64, uint64_t);
  10958. case UPB_TYPE_ENUM: {
  10959. /* For now, we always emit symbolic names for enums. We may want an
  10960. * option later to control this behavior, but we will wait for a real
  10961. * need first. */
  10962. upb_handlerattr enum_attr = UPB_HANDLERATTR_INITIALIZER;
  10963. set_enum_hd(h, f, preserve_fieldnames, &enum_attr);
  10964. if (upb_fielddef_isseq(f)) {
  10965. upb_handlers_setint32(h, f, repeated_enum, &enum_attr);
  10966. } else {
  10967. upb_handlers_setint32(h, f, scalar_enum, &enum_attr);
  10968. }
  10969. upb_handlerattr_uninit(&enum_attr);
  10970. break;
  10971. }
  10972. case UPB_TYPE_STRING:
  10973. if (upb_fielddef_isseq(f)) {
  10974. upb_handlers_setstartstr(h, f, repeated_startstr, &empty_attr);
  10975. upb_handlers_setstring(h, f, repeated_str, &empty_attr);
  10976. upb_handlers_setendstr(h, f, repeated_endstr, &empty_attr);
  10977. } else {
  10978. upb_handlers_setstartstr(h, f, scalar_startstr, &name_attr);
  10979. upb_handlers_setstring(h, f, scalar_str, &empty_attr);
  10980. upb_handlers_setendstr(h, f, scalar_endstr, &empty_attr);
  10981. }
  10982. break;
  10983. case UPB_TYPE_BYTES:
  10984. /* XXX: this doesn't support strings that span buffers yet. The base64
  10985. * encoder will need to be made resumable for this to work properly. */
  10986. if (upb_fielddef_isseq(f)) {
  10987. upb_handlers_setstring(h, f, repeated_bytes, &empty_attr);
  10988. } else {
  10989. upb_handlers_setstring(h, f, scalar_bytes, &name_attr);
  10990. }
  10991. break;
  10992. case UPB_TYPE_MESSAGE:
  10993. if (upb_fielddef_isseq(f)) {
  10994. upb_handlers_setstartsubmsg(h, f, repeated_startsubmsg, &name_attr);
  10995. } else {
  10996. upb_handlers_setstartsubmsg(h, f, scalar_startsubmsg, &name_attr);
  10997. }
  10998. break;
  10999. }
  11000. upb_handlerattr_uninit(&name_attr);
  11001. }
  11002. upb_handlerattr_uninit(&empty_attr);
  11003. #undef TYPE
  11004. }
  11005. static void json_printer_reset(upb_json_printer *p) {
  11006. p->depth_ = 0;
  11007. }
  11008. /* Public API *****************************************************************/
  11009. upb_json_printer *upb_json_printer_create(upb_env *e, const upb_handlers *h,
  11010. upb_bytessink *output) {
  11011. #ifndef NDEBUG
  11012. size_t size_before = upb_env_bytesallocated(e);
  11013. #endif
  11014. upb_json_printer *p = upb_env_malloc(e, sizeof(upb_json_printer));
  11015. if (!p) return NULL;
  11016. p->output_ = output;
  11017. json_printer_reset(p);
  11018. upb_sink_reset(&p->input_, h, p);
  11019. /* If this fails, increase the value in printer.h. */
  11020. assert(upb_env_bytesallocated(e) - size_before <= UPB_JSON_PRINTER_SIZE);
  11021. return p;
  11022. }
  11023. upb_sink *upb_json_printer_input(upb_json_printer *p) {
  11024. return &p->input_;
  11025. }
  11026. const upb_handlers *upb_json_printer_newhandlers(const upb_msgdef *md,
  11027. bool preserve_fieldnames,
  11028. const void *owner) {
  11029. return upb_handlers_newfrozen(
  11030. md, owner, printer_sethandlers, &preserve_fieldnames);
  11031. }