upb.c 337 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097
  1. // Amalgamated source file
  2. #include "upb.h"
  3. /*
  4. * upb - a minimalist implementation of protocol buffers.
  5. *
  6. * Copyright (c) 2008-2012 Google Inc. See LICENSE for details.
  7. * Author: Josh Haberman <jhaberman@gmail.com>
  8. */
  9. #include <stdlib.h>
  10. #include <string.h>
  11. typedef struct {
  12. size_t len;
  13. char str[1]; // Null-terminated string data follows.
  14. } str_t;
  15. static str_t *newstr(const char *data, size_t len) {
  16. str_t *ret = malloc(sizeof(*ret) + len);
  17. if (!ret) return NULL;
  18. ret->len = len;
  19. memcpy(ret->str, data, len);
  20. ret->str[len] = '\0';
  21. return ret;
  22. }
  23. static void freestr(str_t *s) { free(s); }
  24. // isalpha() etc. from <ctype.h> are locale-dependent, which we don't want.
  25. static bool upb_isbetween(char c, char low, char high) {
  26. return c >= low && c <= high;
  27. }
  28. static bool upb_isletter(char c) {
  29. return upb_isbetween(c, 'A', 'Z') || upb_isbetween(c, 'a', 'z') || c == '_';
  30. }
  31. static bool upb_isalphanum(char c) {
  32. return upb_isletter(c) || upb_isbetween(c, '0', '9');
  33. }
  34. static bool upb_isident(const char *str, size_t len, bool full, upb_status *s) {
  35. bool start = true;
  36. for (size_t i = 0; i < len; i++) {
  37. char c = str[i];
  38. if (c == '.') {
  39. if (start || !full) {
  40. upb_status_seterrf(s, "invalid name: unexpected '.' (%s)", str);
  41. return false;
  42. }
  43. start = true;
  44. } else if (start) {
  45. if (!upb_isletter(c)) {
  46. upb_status_seterrf(
  47. s, "invalid name: path components must start with a letter (%s)",
  48. str);
  49. return false;
  50. }
  51. start = false;
  52. } else {
  53. if (!upb_isalphanum(c)) {
  54. upb_status_seterrf(s, "invalid name: non-alphanumeric character (%s)",
  55. str);
  56. return false;
  57. }
  58. }
  59. }
  60. return !start;
  61. }
  62. /* upb_def ********************************************************************/
  63. upb_deftype_t upb_def_type(const upb_def *d) { return d->type; }
  64. const char *upb_def_fullname(const upb_def *d) { return d->fullname; }
  65. bool upb_def_setfullname(upb_def *def, const char *fullname, upb_status *s) {
  66. assert(!upb_def_isfrozen(def));
  67. if (!upb_isident(fullname, strlen(fullname), true, s)) return false;
  68. free((void*)def->fullname);
  69. def->fullname = upb_strdup(fullname);
  70. return true;
  71. }
  72. upb_def *upb_def_dup(const upb_def *def, const void *o) {
  73. switch (def->type) {
  74. case UPB_DEF_MSG:
  75. return UPB_UPCAST(upb_msgdef_dup(upb_downcast_msgdef(def), o));
  76. case UPB_DEF_FIELD:
  77. return UPB_UPCAST(upb_fielddef_dup(upb_downcast_fielddef(def), o));
  78. case UPB_DEF_ENUM:
  79. return UPB_UPCAST(upb_enumdef_dup(upb_downcast_enumdef(def), o));
  80. default: assert(false); return NULL;
  81. }
  82. }
  83. bool upb_def_isfrozen(const upb_def *def) {
  84. return upb_refcounted_isfrozen(UPB_UPCAST(def));
  85. }
  86. void upb_def_ref(const upb_def *def, const void *owner) {
  87. upb_refcounted_ref(UPB_UPCAST(def), owner);
  88. }
  89. void upb_def_unref(const upb_def *def, const void *owner) {
  90. upb_refcounted_unref(UPB_UPCAST(def), owner);
  91. }
  92. void upb_def_donateref(const upb_def *def, const void *from, const void *to) {
  93. upb_refcounted_donateref(UPB_UPCAST(def), from, to);
  94. }
  95. void upb_def_checkref(const upb_def *def, const void *owner) {
  96. upb_refcounted_checkref(UPB_UPCAST(def), owner);
  97. }
  98. static bool upb_def_init(upb_def *def, upb_deftype_t type,
  99. const struct upb_refcounted_vtbl *vtbl,
  100. const void *owner) {
  101. if (!upb_refcounted_init(UPB_UPCAST(def), vtbl, owner)) return false;
  102. def->type = type;
  103. def->fullname = NULL;
  104. def->came_from_user = false;
  105. return true;
  106. }
  107. static void upb_def_uninit(upb_def *def) {
  108. free((void*)def->fullname);
  109. }
  110. static const char *msgdef_name(const upb_msgdef *m) {
  111. const char *name = upb_def_fullname(UPB_UPCAST(m));
  112. return name ? name : "(anonymous)";
  113. }
  114. static bool upb_validate_field(upb_fielddef *f, upb_status *s) {
  115. if (upb_fielddef_name(f) == NULL || upb_fielddef_number(f) == 0) {
  116. upb_status_seterrmsg(s, "fielddef must have name and number set");
  117. return false;
  118. }
  119. if (!f->type_is_set_) {
  120. upb_status_seterrmsg(s, "fielddef type was not initialized");
  121. return false;
  122. }
  123. if (upb_fielddef_lazy(f) &&
  124. upb_fielddef_descriptortype(f) != UPB_DESCRIPTOR_TYPE_MESSAGE) {
  125. upb_status_seterrmsg(s,
  126. "only length-delimited submessage fields may be lazy");
  127. return false;
  128. }
  129. if (upb_fielddef_hassubdef(f)) {
  130. if (f->subdef_is_symbolic) {
  131. upb_status_seterrf(s, "field '%s.%s' has not been resolved",
  132. msgdef_name(f->msg.def), upb_fielddef_name(f));
  133. return false;
  134. }
  135. const upb_def *subdef = upb_fielddef_subdef(f);
  136. if (subdef == NULL) {
  137. upb_status_seterrf(s, "field %s.%s is missing required subdef",
  138. msgdef_name(f->msg.def), upb_fielddef_name(f));
  139. return false;
  140. }
  141. if (!upb_def_isfrozen(subdef) && !subdef->came_from_user) {
  142. upb_status_seterrf(s,
  143. "subdef of field %s.%s is not frozen or being frozen",
  144. msgdef_name(f->msg.def), upb_fielddef_name(f));
  145. return false;
  146. }
  147. }
  148. if (upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  149. bool has_default_name = upb_fielddef_enumhasdefaultstr(f);
  150. bool has_default_number = upb_fielddef_enumhasdefaultint32(f);
  151. // Previously verified by upb_validate_enumdef().
  152. assert(upb_enumdef_numvals(upb_fielddef_enumsubdef(f)) > 0);
  153. // We've already validated that we have an associated enumdef and that it
  154. // has at least one member, so at least one of these should be true.
  155. // Because if the user didn't set anything, we'll pick up the enum's
  156. // default, but if the user *did* set something we should at least pick up
  157. // the one they set (int32 or string).
  158. assert(has_default_name || has_default_number);
  159. if (!has_default_name) {
  160. upb_status_seterrf(s,
  161. "enum default for field %s.%s (%d) is not in the enum",
  162. msgdef_name(f->msg.def), upb_fielddef_name(f),
  163. upb_fielddef_defaultint32(f));
  164. return false;
  165. }
  166. if (!has_default_number) {
  167. upb_status_seterrf(s,
  168. "enum default for field %s.%s (%s) is not in the enum",
  169. msgdef_name(f->msg.def), upb_fielddef_name(f),
  170. upb_fielddef_defaultstr(f, NULL));
  171. return false;
  172. }
  173. // Lift the effective numeric default into the field's default slot, in case
  174. // we were only getting it "by reference" from the enumdef.
  175. upb_fielddef_setdefaultint32(f, upb_fielddef_defaultint32(f));
  176. }
  177. return true;
  178. }
  179. static bool upb_validate_enumdef(const upb_enumdef *e, upb_status *s) {
  180. if (upb_enumdef_numvals(e) == 0) {
  181. upb_status_seterrf(s, "enum %s has no members (must have at least one)",
  182. upb_enumdef_fullname(e));
  183. return false;
  184. }
  185. return true;
  186. }
  187. // All submessage fields are lower than all other fields.
  188. // Secondly, fields are increasing in order.
  189. uint32_t field_rank(const upb_fielddef *f) {
  190. uint32_t ret = upb_fielddef_number(f);
  191. const uint32_t high_bit = 1 << 30;
  192. assert(ret < high_bit);
  193. if (!upb_fielddef_issubmsg(f))
  194. ret |= high_bit;
  195. return ret;
  196. }
  197. int cmp_fields(const void *p1, const void *p2) {
  198. const upb_fielddef *f1 = *(upb_fielddef*const*)p1;
  199. const upb_fielddef *f2 = *(upb_fielddef*const*)p2;
  200. return field_rank(f1) - field_rank(f2);
  201. }
  202. static bool assign_msg_indices(upb_msgdef *m, upb_status *s) {
  203. // Sort fields. upb internally relies on UPB_TYPE_MESSAGE fields having the
  204. // lowest indexes, but we do not publicly guarantee this.
  205. int n = upb_msgdef_numfields(m);
  206. upb_fielddef **fields = malloc(n * sizeof(*fields));
  207. if (!fields) return false;
  208. upb_msg_iter j;
  209. int i;
  210. m->submsg_field_count = 0;
  211. for(i = 0, upb_msg_begin(&j, m); !upb_msg_done(&j); upb_msg_next(&j), i++) {
  212. upb_fielddef *f = upb_msg_iter_field(&j);
  213. assert(f->msg.def == m);
  214. if (!upb_validate_field(f, s)) {
  215. free(fields);
  216. return false;
  217. }
  218. if (upb_fielddef_issubmsg(f)) {
  219. m->submsg_field_count++;
  220. }
  221. fields[i] = f;
  222. }
  223. qsort(fields, n, sizeof(*fields), cmp_fields);
  224. uint32_t selector = UPB_STATIC_SELECTOR_COUNT + m->submsg_field_count;
  225. for (i = 0; i < n; i++) {
  226. upb_fielddef *f = fields[i];
  227. f->index_ = i;
  228. f->selector_base = selector + upb_handlers_selectorbaseoffset(f);
  229. selector += upb_handlers_selectorcount(f);
  230. }
  231. m->selector_count = selector;
  232. #ifndef NDEBUG
  233. // Verify that all selectors for the message are distinct.
  234. //
  235. #define TRY(type) \
  236. if (upb_handlers_getselector(f, type, &sel)) upb_inttable_insert(&t, sel, v);
  237. upb_inttable t;
  238. upb_inttable_init(&t, UPB_CTYPE_BOOL);
  239. upb_value v = upb_value_bool(true);
  240. upb_selector_t sel;
  241. upb_inttable_insert(&t, UPB_STARTMSG_SELECTOR, v);
  242. upb_inttable_insert(&t, UPB_ENDMSG_SELECTOR, v);
  243. for(upb_msg_begin(&j, m); !upb_msg_done(&j); upb_msg_next(&j)) {
  244. upb_fielddef *f = upb_msg_iter_field(&j);
  245. // These calls will assert-fail in upb_table if the value already exists.
  246. TRY(UPB_HANDLER_INT32);
  247. TRY(UPB_HANDLER_INT64)
  248. TRY(UPB_HANDLER_UINT32)
  249. TRY(UPB_HANDLER_UINT64)
  250. TRY(UPB_HANDLER_FLOAT)
  251. TRY(UPB_HANDLER_DOUBLE)
  252. TRY(UPB_HANDLER_BOOL)
  253. TRY(UPB_HANDLER_STARTSTR)
  254. TRY(UPB_HANDLER_STRING)
  255. TRY(UPB_HANDLER_ENDSTR)
  256. TRY(UPB_HANDLER_STARTSUBMSG)
  257. TRY(UPB_HANDLER_ENDSUBMSG)
  258. TRY(UPB_HANDLER_STARTSEQ)
  259. TRY(UPB_HANDLER_ENDSEQ)
  260. }
  261. upb_inttable_uninit(&t);
  262. #undef TRY
  263. #endif
  264. free(fields);
  265. return true;
  266. }
  267. bool upb_def_freeze(upb_def *const* defs, int n, upb_status *s) {
  268. upb_status_clear(s);
  269. // First perform validation, in two passes so we can check that we have a
  270. // transitive closure without needing to search.
  271. for (int i = 0; i < n; i++) {
  272. upb_def *def = defs[i];
  273. if (upb_def_isfrozen(def)) {
  274. // Could relax this requirement if it's annoying.
  275. upb_status_seterrmsg(s, "def is already frozen");
  276. goto err;
  277. } else if (def->type == UPB_DEF_FIELD) {
  278. upb_status_seterrmsg(s, "standalone fielddefs can not be frozen");
  279. goto err;
  280. } else if (def->type == UPB_DEF_ENUM) {
  281. if (!upb_validate_enumdef(upb_dyncast_enumdef(def), s)) {
  282. goto err;
  283. }
  284. } else {
  285. // Set now to detect transitive closure in the second pass.
  286. def->came_from_user = true;
  287. }
  288. }
  289. // Second pass of validation. Also assign selector bases and indexes, and
  290. // compact tables.
  291. for (int i = 0; i < n; i++) {
  292. upb_msgdef *m = upb_dyncast_msgdef_mutable(defs[i]);
  293. upb_enumdef *e = upb_dyncast_enumdef_mutable(defs[i]);
  294. if (m) {
  295. upb_inttable_compact(&m->itof);
  296. if (!assign_msg_indices(m, s)) {
  297. goto err;
  298. }
  299. } else if (e) {
  300. upb_inttable_compact(&e->iton);
  301. }
  302. }
  303. // Def graph contains FieldDefs between each MessageDef, so double the limit.
  304. int maxdepth = UPB_MAX_MESSAGE_DEPTH * 2;
  305. // Validation all passed; freeze the defs.
  306. bool ret =
  307. upb_refcounted_freeze((upb_refcounted * const *)defs, n, s, maxdepth);
  308. assert(!(s && ret != upb_ok(s)));
  309. return ret;
  310. err:
  311. for (int i = 0; i < n; i++) {
  312. defs[i]->came_from_user = false;
  313. }
  314. assert(!(s && upb_ok(s)));
  315. return false;
  316. }
  317. /* upb_enumdef ****************************************************************/
  318. static void upb_enumdef_free(upb_refcounted *r) {
  319. upb_enumdef *e = (upb_enumdef*)r;
  320. upb_inttable_iter i;
  321. upb_inttable_begin(&i, &e->iton);
  322. for( ; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  323. // To clean up the upb_strdup() from upb_enumdef_addval().
  324. free(upb_value_getcstr(upb_inttable_iter_value(&i)));
  325. }
  326. upb_strtable_uninit(&e->ntoi);
  327. upb_inttable_uninit(&e->iton);
  328. upb_def_uninit(UPB_UPCAST(e));
  329. free(e);
  330. }
  331. upb_enumdef *upb_enumdef_new(const void *owner) {
  332. static const struct upb_refcounted_vtbl vtbl = {NULL, &upb_enumdef_free};
  333. upb_enumdef *e = malloc(sizeof(*e));
  334. if (!e) return NULL;
  335. if (!upb_def_init(UPB_UPCAST(e), UPB_DEF_ENUM, &vtbl, owner)) goto err2;
  336. if (!upb_strtable_init(&e->ntoi, UPB_CTYPE_INT32)) goto err2;
  337. if (!upb_inttable_init(&e->iton, UPB_CTYPE_CSTR)) goto err1;
  338. return e;
  339. err1:
  340. upb_strtable_uninit(&e->ntoi);
  341. err2:
  342. free(e);
  343. return NULL;
  344. }
  345. upb_enumdef *upb_enumdef_dup(const upb_enumdef *e, const void *owner) {
  346. upb_enumdef *new_e = upb_enumdef_new(owner);
  347. if (!new_e) return NULL;
  348. upb_enum_iter i;
  349. for(upb_enum_begin(&i, e); !upb_enum_done(&i); upb_enum_next(&i)) {
  350. bool success = upb_enumdef_addval(
  351. new_e, upb_enum_iter_name(&i),upb_enum_iter_number(&i), NULL);
  352. if (!success) {
  353. upb_enumdef_unref(new_e, owner);
  354. return NULL;
  355. }
  356. }
  357. return new_e;
  358. }
  359. bool upb_enumdef_isfrozen(const upb_enumdef *e) {
  360. return upb_def_isfrozen(UPB_UPCAST(e));
  361. }
  362. void upb_enumdef_ref(const upb_enumdef *e, const void *owner) {
  363. upb_def_ref(UPB_UPCAST(e), owner);
  364. }
  365. void upb_enumdef_unref(const upb_enumdef *e, const void *owner) {
  366. upb_def_unref(UPB_UPCAST(e), owner);
  367. }
  368. void upb_enumdef_donateref(
  369. const upb_enumdef *e, const void *from, const void *to) {
  370. upb_def_donateref(UPB_UPCAST(e), from, to);
  371. }
  372. void upb_enumdef_checkref(const upb_enumdef *e, const void *owner) {
  373. upb_def_checkref(UPB_UPCAST(e), owner);
  374. }
  375. bool upb_enumdef_freeze(upb_enumdef *e, upb_status *status) {
  376. upb_def *d = UPB_UPCAST(e);
  377. return upb_def_freeze(&d, 1, status);
  378. }
  379. const char *upb_enumdef_fullname(const upb_enumdef *e) {
  380. return upb_def_fullname(UPB_UPCAST(e));
  381. }
  382. bool upb_enumdef_setfullname(upb_enumdef *e, const char *fullname,
  383. upb_status *s) {
  384. return upb_def_setfullname(UPB_UPCAST(e), fullname, s);
  385. }
  386. bool upb_enumdef_addval(upb_enumdef *e, const char *name, int32_t num,
  387. upb_status *status) {
  388. if (!upb_isident(name, strlen(name), false, status)) {
  389. return false;
  390. }
  391. if (upb_enumdef_ntoiz(e, name, NULL)) {
  392. upb_status_seterrf(status, "name '%s' is already defined", name);
  393. return false;
  394. }
  395. if (!upb_strtable_insert(&e->ntoi, name, upb_value_int32(num))) {
  396. upb_status_seterrmsg(status, "out of memory");
  397. return false;
  398. }
  399. if (!upb_inttable_lookup(&e->iton, num, NULL) &&
  400. !upb_inttable_insert(&e->iton, num, upb_value_cstr(upb_strdup(name)))) {
  401. upb_status_seterrmsg(status, "out of memory");
  402. upb_strtable_remove(&e->ntoi, name, NULL);
  403. return false;
  404. }
  405. if (upb_enumdef_numvals(e) == 1) {
  406. bool ok = upb_enumdef_setdefault(e, num, NULL);
  407. UPB_ASSERT_VAR(ok, ok);
  408. }
  409. return true;
  410. }
  411. int32_t upb_enumdef_default(const upb_enumdef *e) {
  412. assert(upb_enumdef_iton(e, e->defaultval));
  413. return e->defaultval;
  414. }
  415. bool upb_enumdef_setdefault(upb_enumdef *e, int32_t val, upb_status *s) {
  416. assert(!upb_enumdef_isfrozen(e));
  417. if (!upb_enumdef_iton(e, val)) {
  418. upb_status_seterrf(s, "number '%d' is not in the enum.", val);
  419. return false;
  420. }
  421. e->defaultval = val;
  422. return true;
  423. }
  424. int upb_enumdef_numvals(const upb_enumdef *e) {
  425. return upb_strtable_count(&e->ntoi);
  426. }
  427. void upb_enum_begin(upb_enum_iter *i, const upb_enumdef *e) {
  428. // We iterate over the ntoi table, to account for duplicate numbers.
  429. upb_strtable_begin(i, &e->ntoi);
  430. }
  431. void upb_enum_next(upb_enum_iter *iter) { upb_strtable_next(iter); }
  432. bool upb_enum_done(upb_enum_iter *iter) { return upb_strtable_done(iter); }
  433. bool upb_enumdef_ntoi(const upb_enumdef *def, const char *name,
  434. size_t len, int32_t *num) {
  435. upb_value v;
  436. if (!upb_strtable_lookup2(&def->ntoi, name, len, &v)) {
  437. return false;
  438. }
  439. if (num) *num = upb_value_getint32(v);
  440. return true;
  441. }
  442. const char *upb_enumdef_iton(const upb_enumdef *def, int32_t num) {
  443. upb_value v;
  444. return upb_inttable_lookup32(&def->iton, num, &v) ?
  445. upb_value_getcstr(v) : NULL;
  446. }
  447. const char *upb_enum_iter_name(upb_enum_iter *iter) {
  448. return upb_strtable_iter_key(iter);
  449. }
  450. int32_t upb_enum_iter_number(upb_enum_iter *iter) {
  451. return upb_value_getint32(upb_strtable_iter_value(iter));
  452. }
  453. /* upb_fielddef ***************************************************************/
  454. static void upb_fielddef_init_default(upb_fielddef *f);
  455. static void upb_fielddef_uninit_default(upb_fielddef *f) {
  456. if (f->type_is_set_ && f->default_is_string && f->defaultval.bytes)
  457. freestr(f->defaultval.bytes);
  458. }
  459. static void visitfield(const upb_refcounted *r, upb_refcounted_visit *visit,
  460. void *closure) {
  461. const upb_fielddef *f = (const upb_fielddef*)r;
  462. if (upb_fielddef_containingtype(f)) {
  463. visit(r, UPB_UPCAST2(upb_fielddef_containingtype(f)), closure);
  464. }
  465. if (upb_fielddef_subdef(f)) {
  466. visit(r, UPB_UPCAST(upb_fielddef_subdef(f)), closure);
  467. }
  468. }
  469. static void freefield(upb_refcounted *r) {
  470. upb_fielddef *f = (upb_fielddef*)r;
  471. upb_fielddef_uninit_default(f);
  472. if (f->subdef_is_symbolic)
  473. free(f->sub.name);
  474. upb_def_uninit(UPB_UPCAST(f));
  475. free(f);
  476. }
  477. static const char *enumdefaultstr(const upb_fielddef *f) {
  478. assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  479. const upb_enumdef *e = upb_fielddef_enumsubdef(f);
  480. if (f->default_is_string && f->defaultval.bytes) {
  481. // Default was explicitly set as a string.
  482. str_t *s = f->defaultval.bytes;
  483. return s->str;
  484. } else if (e) {
  485. if (!f->default_is_string) {
  486. // Default was explicitly set as an integer; look it up in enumdef.
  487. const char *name = upb_enumdef_iton(e, f->defaultval.sint);
  488. if (name) {
  489. return name;
  490. }
  491. } else {
  492. // Default is completely unset; pull enumdef default.
  493. if (upb_enumdef_numvals(e) > 0) {
  494. const char *name = upb_enumdef_iton(e, upb_enumdef_default(e));
  495. assert(name);
  496. return name;
  497. }
  498. }
  499. }
  500. return NULL;
  501. }
  502. static bool enumdefaultint32(const upb_fielddef *f, int32_t *val) {
  503. assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  504. const upb_enumdef *e = upb_fielddef_enumsubdef(f);
  505. if (!f->default_is_string) {
  506. // Default was explicitly set as an integer.
  507. *val = f->defaultval.sint;
  508. return true;
  509. } else if (e) {
  510. if (f->defaultval.bytes) {
  511. // Default was explicitly set as a str; try to lookup corresponding int.
  512. str_t *s = f->defaultval.bytes;
  513. if (upb_enumdef_ntoiz(e, s->str, val)) {
  514. return true;
  515. }
  516. } else {
  517. // Default is unset; try to pull in enumdef default.
  518. if (upb_enumdef_numvals(e) > 0) {
  519. *val = upb_enumdef_default(e);
  520. return true;
  521. }
  522. }
  523. }
  524. return false;
  525. }
  526. upb_fielddef *upb_fielddef_new(const void *owner) {
  527. static const struct upb_refcounted_vtbl vtbl = {visitfield, freefield};
  528. upb_fielddef *f = malloc(sizeof(*f));
  529. if (!f) return NULL;
  530. if (!upb_def_init(UPB_UPCAST(f), UPB_DEF_FIELD, &vtbl, owner)) {
  531. free(f);
  532. return NULL;
  533. }
  534. f->msg.def = NULL;
  535. f->sub.def = NULL;
  536. f->subdef_is_symbolic = false;
  537. f->msg_is_symbolic = false;
  538. f->label_ = UPB_LABEL_OPTIONAL;
  539. f->type_ = UPB_TYPE_INT32;
  540. f->number_ = 0;
  541. f->type_is_set_ = false;
  542. f->tagdelim = false;
  543. f->is_extension_ = false;
  544. f->lazy_ = false;
  545. f->packed_ = true;
  546. // For the moment we default this to UPB_INTFMT_VARIABLE, since it will work
  547. // with all integer types and is in some since more "default" since the most
  548. // normal-looking proto2 types int32/int64/uint32/uint64 use variable.
  549. //
  550. // Other options to consider:
  551. // - there is no default; users must set this manually (like type).
  552. // - default signed integers to UPB_INTFMT_ZIGZAG, since it's more likely to
  553. // be an optimal default for signed integers.
  554. f->intfmt = UPB_INTFMT_VARIABLE;
  555. return f;
  556. }
  557. upb_fielddef *upb_fielddef_dup(const upb_fielddef *f, const void *owner) {
  558. upb_fielddef *newf = upb_fielddef_new(owner);
  559. if (!newf) return NULL;
  560. upb_fielddef_settype(newf, upb_fielddef_type(f));
  561. upb_fielddef_setlabel(newf, upb_fielddef_label(f));
  562. upb_fielddef_setnumber(newf, upb_fielddef_number(f), NULL);
  563. upb_fielddef_setname(newf, upb_fielddef_name(f), NULL);
  564. if (f->default_is_string && f->defaultval.bytes) {
  565. str_t *s = f->defaultval.bytes;
  566. upb_fielddef_setdefaultstr(newf, s->str, s->len, NULL);
  567. } else {
  568. newf->default_is_string = f->default_is_string;
  569. newf->defaultval = f->defaultval;
  570. }
  571. const char *srcname;
  572. if (f->subdef_is_symbolic) {
  573. srcname = f->sub.name; // Might be NULL.
  574. } else {
  575. srcname = f->sub.def ? upb_def_fullname(f->sub.def) : NULL;
  576. }
  577. if (srcname) {
  578. char *newname = malloc(strlen(f->sub.def->fullname) + 2);
  579. if (!newname) {
  580. upb_fielddef_unref(newf, owner);
  581. return NULL;
  582. }
  583. strcpy(newname, ".");
  584. strcat(newname, f->sub.def->fullname);
  585. upb_fielddef_setsubdefname(newf, newname, NULL);
  586. free(newname);
  587. }
  588. return newf;
  589. }
  590. bool upb_fielddef_isfrozen(const upb_fielddef *f) {
  591. return upb_def_isfrozen(UPB_UPCAST(f));
  592. }
  593. void upb_fielddef_ref(const upb_fielddef *f, const void *owner) {
  594. upb_def_ref(UPB_UPCAST(f), owner);
  595. }
  596. void upb_fielddef_unref(const upb_fielddef *f, const void *owner) {
  597. upb_def_unref(UPB_UPCAST(f), owner);
  598. }
  599. void upb_fielddef_donateref(
  600. const upb_fielddef *f, const void *from, const void *to) {
  601. upb_def_donateref(UPB_UPCAST(f), from, to);
  602. }
  603. void upb_fielddef_checkref(const upb_fielddef *f, const void *owner) {
  604. upb_def_checkref(UPB_UPCAST(f), owner);
  605. }
  606. bool upb_fielddef_typeisset(const upb_fielddef *f) {
  607. return f->type_is_set_;
  608. }
  609. upb_fieldtype_t upb_fielddef_type(const upb_fielddef *f) {
  610. assert(f->type_is_set_);
  611. return f->type_;
  612. }
  613. uint32_t upb_fielddef_index(const upb_fielddef *f) {
  614. return f->index_;
  615. }
  616. upb_label_t upb_fielddef_label(const upb_fielddef *f) {
  617. return f->label_;
  618. }
  619. upb_intfmt_t upb_fielddef_intfmt(const upb_fielddef *f) {
  620. return f->intfmt;
  621. }
  622. bool upb_fielddef_istagdelim(const upb_fielddef *f) {
  623. return f->tagdelim;
  624. }
  625. uint32_t upb_fielddef_number(const upb_fielddef *f) {
  626. return f->number_;
  627. }
  628. bool upb_fielddef_isextension(const upb_fielddef *f) {
  629. return f->is_extension_;
  630. }
  631. bool upb_fielddef_lazy(const upb_fielddef *f) {
  632. return f->lazy_;
  633. }
  634. bool upb_fielddef_packed(const upb_fielddef *f) {
  635. return f->packed_;
  636. }
  637. const char *upb_fielddef_name(const upb_fielddef *f) {
  638. return upb_def_fullname(UPB_UPCAST(f));
  639. }
  640. const upb_msgdef *upb_fielddef_containingtype(const upb_fielddef *f) {
  641. return f->msg_is_symbolic ? NULL : f->msg.def;
  642. }
  643. upb_msgdef *upb_fielddef_containingtype_mutable(upb_fielddef *f) {
  644. return (upb_msgdef*)upb_fielddef_containingtype(f);
  645. }
  646. const char *upb_fielddef_containingtypename(upb_fielddef *f) {
  647. return f->msg_is_symbolic ? f->msg.name : NULL;
  648. }
  649. static void release_containingtype(upb_fielddef *f) {
  650. if (f->msg_is_symbolic) free(f->msg.name);
  651. }
  652. bool upb_fielddef_setcontainingtypename(upb_fielddef *f, const char *name,
  653. upb_status *s) {
  654. assert(!upb_fielddef_isfrozen(f));
  655. if (upb_fielddef_containingtype(f)) {
  656. upb_status_seterrmsg(s, "field has already been added to a message.");
  657. return false;
  658. }
  659. // TODO: validate name (upb_isident() doesn't quite work atm because this name
  660. // may have a leading ".").
  661. release_containingtype(f);
  662. f->msg.name = upb_strdup(name);
  663. f->msg_is_symbolic = true;
  664. return true;
  665. }
  666. bool upb_fielddef_setname(upb_fielddef *f, const char *name, upb_status *s) {
  667. return upb_def_setfullname(UPB_UPCAST(f), name, s);
  668. }
  669. static void chkdefaulttype(const upb_fielddef *f, upb_fieldtype_t type) {
  670. UPB_UNUSED(f);
  671. UPB_UNUSED(type);
  672. assert(f->type_is_set_ && upb_fielddef_type(f) == type);
  673. }
  674. int64_t upb_fielddef_defaultint64(const upb_fielddef *f) {
  675. chkdefaulttype(f, UPB_TYPE_INT64);
  676. return f->defaultval.sint;
  677. }
  678. int32_t upb_fielddef_defaultint32(const upb_fielddef *f) {
  679. if (f->type_is_set_ && upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  680. int32_t val;
  681. bool ok = enumdefaultint32(f, &val);
  682. UPB_ASSERT_VAR(ok, ok);
  683. return val;
  684. } else {
  685. chkdefaulttype(f, UPB_TYPE_INT32);
  686. return f->defaultval.sint;
  687. }
  688. }
  689. uint64_t upb_fielddef_defaultuint64(const upb_fielddef *f) {
  690. chkdefaulttype(f, UPB_TYPE_UINT64);
  691. return f->defaultval.uint;
  692. }
  693. uint32_t upb_fielddef_defaultuint32(const upb_fielddef *f) {
  694. chkdefaulttype(f, UPB_TYPE_UINT32);
  695. return f->defaultval.uint;
  696. }
  697. bool upb_fielddef_defaultbool(const upb_fielddef *f) {
  698. chkdefaulttype(f, UPB_TYPE_BOOL);
  699. return f->defaultval.uint;
  700. }
  701. float upb_fielddef_defaultfloat(const upb_fielddef *f) {
  702. chkdefaulttype(f, UPB_TYPE_FLOAT);
  703. return f->defaultval.flt;
  704. }
  705. double upb_fielddef_defaultdouble(const upb_fielddef *f) {
  706. chkdefaulttype(f, UPB_TYPE_DOUBLE);
  707. return f->defaultval.dbl;
  708. }
  709. const char *upb_fielddef_defaultstr(const upb_fielddef *f, size_t *len) {
  710. assert(f->type_is_set_);
  711. assert(upb_fielddef_type(f) == UPB_TYPE_STRING ||
  712. upb_fielddef_type(f) == UPB_TYPE_BYTES ||
  713. upb_fielddef_type(f) == UPB_TYPE_ENUM);
  714. if (upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  715. const char *ret = enumdefaultstr(f);
  716. assert(ret);
  717. // Enum defaults can't have embedded NULLs.
  718. if (len) *len = strlen(ret);
  719. return ret;
  720. }
  721. if (f->default_is_string) {
  722. str_t *str = f->defaultval.bytes;
  723. if (len) *len = str->len;
  724. return str->str;
  725. }
  726. return NULL;
  727. }
  728. static void upb_fielddef_init_default(upb_fielddef *f) {
  729. f->default_is_string = false;
  730. switch (upb_fielddef_type(f)) {
  731. case UPB_TYPE_DOUBLE: f->defaultval.dbl = 0; break;
  732. case UPB_TYPE_FLOAT: f->defaultval.flt = 0; break;
  733. case UPB_TYPE_INT32:
  734. case UPB_TYPE_INT64: f->defaultval.sint = 0; break;
  735. case UPB_TYPE_UINT64:
  736. case UPB_TYPE_UINT32:
  737. case UPB_TYPE_BOOL: f->defaultval.uint = 0; break;
  738. case UPB_TYPE_STRING:
  739. case UPB_TYPE_BYTES:
  740. f->defaultval.bytes = newstr("", 0);
  741. f->default_is_string = true;
  742. break;
  743. case UPB_TYPE_MESSAGE: break;
  744. case UPB_TYPE_ENUM:
  745. // This is our special sentinel that indicates "not set" for an enum.
  746. f->default_is_string = true;
  747. f->defaultval.bytes = NULL;
  748. break;
  749. }
  750. }
  751. const upb_def *upb_fielddef_subdef(const upb_fielddef *f) {
  752. return f->subdef_is_symbolic ? NULL : f->sub.def;
  753. }
  754. const upb_msgdef *upb_fielddef_msgsubdef(const upb_fielddef *f) {
  755. const upb_def *def = upb_fielddef_subdef(f);
  756. return def ? upb_dyncast_msgdef(def) : NULL;
  757. }
  758. const upb_enumdef *upb_fielddef_enumsubdef(const upb_fielddef *f) {
  759. const upb_def *def = upb_fielddef_subdef(f);
  760. return def ? upb_dyncast_enumdef(def) : NULL;
  761. }
  762. upb_def *upb_fielddef_subdef_mutable(upb_fielddef *f) {
  763. return (upb_def*)upb_fielddef_subdef(f);
  764. }
  765. const char *upb_fielddef_subdefname(const upb_fielddef *f) {
  766. if (f->subdef_is_symbolic) {
  767. return f->sub.name;
  768. } else if (f->sub.def) {
  769. return upb_def_fullname(f->sub.def);
  770. } else {
  771. return NULL;
  772. }
  773. }
  774. bool upb_fielddef_setnumber(upb_fielddef *f, uint32_t number, upb_status *s) {
  775. if (upb_fielddef_containingtype(f)) {
  776. upb_status_seterrmsg(
  777. s, "cannot change field number after adding to a message");
  778. return false;
  779. }
  780. if (number == 0 || number > UPB_MAX_FIELDNUMBER) {
  781. upb_status_seterrf(s, "invalid field number (%u)", number);
  782. return false;
  783. }
  784. f->number_ = number;
  785. return true;
  786. }
  787. void upb_fielddef_settype(upb_fielddef *f, upb_fieldtype_t type) {
  788. assert(!upb_fielddef_isfrozen(f));
  789. assert(upb_fielddef_checktype(type));
  790. upb_fielddef_uninit_default(f);
  791. f->type_ = type;
  792. f->type_is_set_ = true;
  793. upb_fielddef_init_default(f);
  794. }
  795. void upb_fielddef_setdescriptortype(upb_fielddef *f, int type) {
  796. assert(!upb_fielddef_isfrozen(f));
  797. switch (type) {
  798. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  799. upb_fielddef_settype(f, UPB_TYPE_DOUBLE);
  800. break;
  801. case UPB_DESCRIPTOR_TYPE_FLOAT:
  802. upb_fielddef_settype(f, UPB_TYPE_FLOAT);
  803. break;
  804. case UPB_DESCRIPTOR_TYPE_INT64:
  805. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  806. case UPB_DESCRIPTOR_TYPE_SINT64:
  807. upb_fielddef_settype(f, UPB_TYPE_INT64);
  808. break;
  809. case UPB_DESCRIPTOR_TYPE_UINT64:
  810. case UPB_DESCRIPTOR_TYPE_FIXED64:
  811. upb_fielddef_settype(f, UPB_TYPE_UINT64);
  812. break;
  813. case UPB_DESCRIPTOR_TYPE_INT32:
  814. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  815. case UPB_DESCRIPTOR_TYPE_SINT32:
  816. upb_fielddef_settype(f, UPB_TYPE_INT32);
  817. break;
  818. case UPB_DESCRIPTOR_TYPE_UINT32:
  819. case UPB_DESCRIPTOR_TYPE_FIXED32:
  820. upb_fielddef_settype(f, UPB_TYPE_UINT32);
  821. break;
  822. case UPB_DESCRIPTOR_TYPE_BOOL:
  823. upb_fielddef_settype(f, UPB_TYPE_BOOL);
  824. break;
  825. case UPB_DESCRIPTOR_TYPE_STRING:
  826. upb_fielddef_settype(f, UPB_TYPE_STRING);
  827. break;
  828. case UPB_DESCRIPTOR_TYPE_BYTES:
  829. upb_fielddef_settype(f, UPB_TYPE_BYTES);
  830. break;
  831. case UPB_DESCRIPTOR_TYPE_GROUP:
  832. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  833. upb_fielddef_settype(f, UPB_TYPE_MESSAGE);
  834. break;
  835. case UPB_DESCRIPTOR_TYPE_ENUM:
  836. upb_fielddef_settype(f, UPB_TYPE_ENUM);
  837. break;
  838. default: assert(false);
  839. }
  840. if (type == UPB_DESCRIPTOR_TYPE_FIXED64 ||
  841. type == UPB_DESCRIPTOR_TYPE_FIXED32 ||
  842. type == UPB_DESCRIPTOR_TYPE_SFIXED64 ||
  843. type == UPB_DESCRIPTOR_TYPE_SFIXED32) {
  844. upb_fielddef_setintfmt(f, UPB_INTFMT_FIXED);
  845. } else if (type == UPB_DESCRIPTOR_TYPE_SINT64 ||
  846. type == UPB_DESCRIPTOR_TYPE_SINT32) {
  847. upb_fielddef_setintfmt(f, UPB_INTFMT_ZIGZAG);
  848. } else {
  849. upb_fielddef_setintfmt(f, UPB_INTFMT_VARIABLE);
  850. }
  851. upb_fielddef_settagdelim(f, type == UPB_DESCRIPTOR_TYPE_GROUP);
  852. }
  853. upb_descriptortype_t upb_fielddef_descriptortype(const upb_fielddef *f) {
  854. switch (upb_fielddef_type(f)) {
  855. case UPB_TYPE_FLOAT: return UPB_DESCRIPTOR_TYPE_FLOAT;
  856. case UPB_TYPE_DOUBLE: return UPB_DESCRIPTOR_TYPE_DOUBLE;
  857. case UPB_TYPE_BOOL: return UPB_DESCRIPTOR_TYPE_BOOL;
  858. case UPB_TYPE_STRING: return UPB_DESCRIPTOR_TYPE_STRING;
  859. case UPB_TYPE_BYTES: return UPB_DESCRIPTOR_TYPE_BYTES;
  860. case UPB_TYPE_ENUM: return UPB_DESCRIPTOR_TYPE_ENUM;
  861. case UPB_TYPE_INT32:
  862. switch (upb_fielddef_intfmt(f)) {
  863. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_INT32;
  864. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_SFIXED32;
  865. case UPB_INTFMT_ZIGZAG: return UPB_DESCRIPTOR_TYPE_SINT32;
  866. }
  867. case UPB_TYPE_INT64:
  868. switch (upb_fielddef_intfmt(f)) {
  869. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_INT64;
  870. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_SFIXED64;
  871. case UPB_INTFMT_ZIGZAG: return UPB_DESCRIPTOR_TYPE_SINT64;
  872. }
  873. case UPB_TYPE_UINT32:
  874. switch (upb_fielddef_intfmt(f)) {
  875. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_UINT32;
  876. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_FIXED32;
  877. case UPB_INTFMT_ZIGZAG: return -1;
  878. }
  879. case UPB_TYPE_UINT64:
  880. switch (upb_fielddef_intfmt(f)) {
  881. case UPB_INTFMT_VARIABLE: return UPB_DESCRIPTOR_TYPE_UINT64;
  882. case UPB_INTFMT_FIXED: return UPB_DESCRIPTOR_TYPE_FIXED64;
  883. case UPB_INTFMT_ZIGZAG: return -1;
  884. }
  885. case UPB_TYPE_MESSAGE:
  886. return upb_fielddef_istagdelim(f) ?
  887. UPB_DESCRIPTOR_TYPE_GROUP : UPB_DESCRIPTOR_TYPE_MESSAGE;
  888. }
  889. return 0;
  890. }
  891. void upb_fielddef_setisextension(upb_fielddef *f, bool is_extension) {
  892. assert(!upb_fielddef_isfrozen(f));
  893. f->is_extension_ = is_extension;
  894. }
  895. void upb_fielddef_setlazy(upb_fielddef *f, bool lazy) {
  896. assert(!upb_fielddef_isfrozen(f));
  897. f->lazy_ = lazy;
  898. }
  899. void upb_fielddef_setpacked(upb_fielddef *f, bool packed) {
  900. assert(!upb_fielddef_isfrozen(f));
  901. f->packed_ = packed;
  902. }
  903. void upb_fielddef_setlabel(upb_fielddef *f, upb_label_t label) {
  904. assert(!upb_fielddef_isfrozen(f));
  905. assert(upb_fielddef_checklabel(label));
  906. f->label_ = label;
  907. }
  908. void upb_fielddef_setintfmt(upb_fielddef *f, upb_intfmt_t fmt) {
  909. assert(!upb_fielddef_isfrozen(f));
  910. assert(upb_fielddef_checkintfmt(fmt));
  911. f->intfmt = fmt;
  912. }
  913. void upb_fielddef_settagdelim(upb_fielddef *f, bool tag_delim) {
  914. assert(!upb_fielddef_isfrozen(f));
  915. f->tagdelim = tag_delim;
  916. f->tagdelim = tag_delim;
  917. }
  918. static bool checksetdefault(upb_fielddef *f, upb_fieldtype_t type) {
  919. if (!f->type_is_set_ || upb_fielddef_isfrozen(f) ||
  920. upb_fielddef_type(f) != type) {
  921. assert(false);
  922. return false;
  923. }
  924. if (f->default_is_string) {
  925. str_t *s = f->defaultval.bytes;
  926. assert(s || type == UPB_TYPE_ENUM);
  927. if (s) freestr(s);
  928. }
  929. f->default_is_string = false;
  930. return true;
  931. }
  932. void upb_fielddef_setdefaultint64(upb_fielddef *f, int64_t value) {
  933. if (checksetdefault(f, UPB_TYPE_INT64))
  934. f->defaultval.sint = value;
  935. }
  936. void upb_fielddef_setdefaultint32(upb_fielddef *f, int32_t value) {
  937. if ((upb_fielddef_type(f) == UPB_TYPE_ENUM &&
  938. checksetdefault(f, UPB_TYPE_ENUM)) ||
  939. checksetdefault(f, UPB_TYPE_INT32)) {
  940. f->defaultval.sint = value;
  941. }
  942. }
  943. void upb_fielddef_setdefaultuint64(upb_fielddef *f, uint64_t value) {
  944. if (checksetdefault(f, UPB_TYPE_UINT64))
  945. f->defaultval.uint = value;
  946. }
  947. void upb_fielddef_setdefaultuint32(upb_fielddef *f, uint32_t value) {
  948. if (checksetdefault(f, UPB_TYPE_UINT32))
  949. f->defaultval.uint = value;
  950. }
  951. void upb_fielddef_setdefaultbool(upb_fielddef *f, bool value) {
  952. if (checksetdefault(f, UPB_TYPE_BOOL))
  953. f->defaultval.uint = value;
  954. }
  955. void upb_fielddef_setdefaultfloat(upb_fielddef *f, float value) {
  956. if (checksetdefault(f, UPB_TYPE_FLOAT))
  957. f->defaultval.flt = value;
  958. }
  959. void upb_fielddef_setdefaultdouble(upb_fielddef *f, double value) {
  960. if (checksetdefault(f, UPB_TYPE_DOUBLE))
  961. f->defaultval.dbl = value;
  962. }
  963. bool upb_fielddef_setdefaultstr(upb_fielddef *f, const void *str, size_t len,
  964. upb_status *s) {
  965. assert(upb_fielddef_isstring(f) || f->type_ == UPB_TYPE_ENUM);
  966. if (f->type_ == UPB_TYPE_ENUM && !upb_isident(str, len, false, s))
  967. return false;
  968. if (f->default_is_string) {
  969. str_t *s = f->defaultval.bytes;
  970. assert(s || f->type_ == UPB_TYPE_ENUM);
  971. if (s) freestr(s);
  972. } else {
  973. assert(f->type_ == UPB_TYPE_ENUM);
  974. }
  975. str_t *str2 = newstr(str, len);
  976. f->defaultval.bytes = str2;
  977. f->default_is_string = true;
  978. return true;
  979. }
  980. void upb_fielddef_setdefaultcstr(upb_fielddef *f, const char *str,
  981. upb_status *s) {
  982. assert(f->type_is_set_);
  983. upb_fielddef_setdefaultstr(f, str, str ? strlen(str) : 0, s);
  984. }
  985. bool upb_fielddef_enumhasdefaultint32(const upb_fielddef *f) {
  986. assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  987. int32_t val;
  988. return enumdefaultint32(f, &val);
  989. }
  990. bool upb_fielddef_enumhasdefaultstr(const upb_fielddef *f) {
  991. assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
  992. return enumdefaultstr(f) != NULL;
  993. }
  994. static bool upb_subdef_typecheck(upb_fielddef *f, const upb_def *subdef,
  995. upb_status *s) {
  996. if (f->type_ == UPB_TYPE_MESSAGE) {
  997. if (upb_dyncast_msgdef(subdef)) return true;
  998. upb_status_seterrmsg(s, "invalid subdef type for this submessage field");
  999. return false;
  1000. } else if (f->type_ == UPB_TYPE_ENUM) {
  1001. if (upb_dyncast_enumdef(subdef)) return true;
  1002. upb_status_seterrmsg(s, "invalid subdef type for this enum field");
  1003. return false;
  1004. } else {
  1005. upb_status_seterrmsg(s, "only message and enum fields can have a subdef");
  1006. return false;
  1007. }
  1008. }
  1009. static void release_subdef(upb_fielddef *f) {
  1010. if (f->subdef_is_symbolic) {
  1011. free(f->sub.name);
  1012. } else if (f->sub.def) {
  1013. upb_unref2(f->sub.def, f);
  1014. }
  1015. }
  1016. bool upb_fielddef_setsubdef(upb_fielddef *f, const upb_def *subdef,
  1017. upb_status *s) {
  1018. assert(!upb_fielddef_isfrozen(f));
  1019. assert(upb_fielddef_hassubdef(f));
  1020. if (subdef && !upb_subdef_typecheck(f, subdef, s)) return false;
  1021. release_subdef(f);
  1022. f->sub.def = subdef;
  1023. f->subdef_is_symbolic = false;
  1024. if (f->sub.def) upb_ref2(f->sub.def, f);
  1025. return true;
  1026. }
  1027. bool upb_fielddef_setmsgsubdef(upb_fielddef *f, const upb_msgdef *subdef,
  1028. upb_status *s) {
  1029. return upb_fielddef_setsubdef(f, UPB_UPCAST(subdef), s);
  1030. }
  1031. bool upb_fielddef_setenumsubdef(upb_fielddef *f, const upb_enumdef *subdef,
  1032. upb_status *s) {
  1033. return upb_fielddef_setsubdef(f, UPB_UPCAST(subdef), s);
  1034. }
  1035. bool upb_fielddef_setsubdefname(upb_fielddef *f, const char *name,
  1036. upb_status *s) {
  1037. assert(!upb_fielddef_isfrozen(f));
  1038. if (!upb_fielddef_hassubdef(f)) {
  1039. upb_status_seterrmsg(s, "field type does not accept a subdef");
  1040. return false;
  1041. }
  1042. // TODO: validate name (upb_isident() doesn't quite work atm because this name
  1043. // may have a leading ".").
  1044. release_subdef(f);
  1045. f->sub.name = upb_strdup(name);
  1046. f->subdef_is_symbolic = true;
  1047. return true;
  1048. }
  1049. bool upb_fielddef_issubmsg(const upb_fielddef *f) {
  1050. return upb_fielddef_type(f) == UPB_TYPE_MESSAGE;
  1051. }
  1052. bool upb_fielddef_isstring(const upb_fielddef *f) {
  1053. return upb_fielddef_type(f) == UPB_TYPE_STRING ||
  1054. upb_fielddef_type(f) == UPB_TYPE_BYTES;
  1055. }
  1056. bool upb_fielddef_isseq(const upb_fielddef *f) {
  1057. return upb_fielddef_label(f) == UPB_LABEL_REPEATED;
  1058. }
  1059. bool upb_fielddef_isprimitive(const upb_fielddef *f) {
  1060. return !upb_fielddef_isstring(f) && !upb_fielddef_issubmsg(f);
  1061. }
  1062. bool upb_fielddef_hassubdef(const upb_fielddef *f) {
  1063. return upb_fielddef_issubmsg(f) || upb_fielddef_type(f) == UPB_TYPE_ENUM;
  1064. }
  1065. static bool between(int32_t x, int32_t low, int32_t high) {
  1066. return x >= low && x <= high;
  1067. }
  1068. bool upb_fielddef_checklabel(int32_t label) { return between(label, 1, 3); }
  1069. bool upb_fielddef_checktype(int32_t type) { return between(type, 1, 11); }
  1070. bool upb_fielddef_checkintfmt(int32_t fmt) { return between(fmt, 1, 3); }
  1071. bool upb_fielddef_checkdescriptortype(int32_t type) {
  1072. return between(type, 1, 18);
  1073. }
  1074. /* upb_msgdef *****************************************************************/
  1075. static void visitmsg(const upb_refcounted *r, upb_refcounted_visit *visit,
  1076. void *closure) {
  1077. const upb_msgdef *m = (const upb_msgdef*)r;
  1078. upb_msg_iter i;
  1079. for(upb_msg_begin(&i, m); !upb_msg_done(&i); upb_msg_next(&i)) {
  1080. upb_fielddef *f = upb_msg_iter_field(&i);
  1081. visit(r, UPB_UPCAST2(f), closure);
  1082. }
  1083. }
  1084. static void freemsg(upb_refcounted *r) {
  1085. upb_msgdef *m = (upb_msgdef*)r;
  1086. upb_strtable_uninit(&m->ntof);
  1087. upb_inttable_uninit(&m->itof);
  1088. upb_def_uninit(UPB_UPCAST(m));
  1089. free(m);
  1090. }
  1091. upb_msgdef *upb_msgdef_new(const void *owner) {
  1092. static const struct upb_refcounted_vtbl vtbl = {visitmsg, freemsg};
  1093. upb_msgdef *m = malloc(sizeof(*m));
  1094. if (!m) return NULL;
  1095. if (!upb_def_init(UPB_UPCAST(m), UPB_DEF_MSG, &vtbl, owner)) goto err2;
  1096. if (!upb_inttable_init(&m->itof, UPB_CTYPE_PTR)) goto err2;
  1097. if (!upb_strtable_init(&m->ntof, UPB_CTYPE_PTR)) goto err1;
  1098. m->map_entry = false;
  1099. return m;
  1100. err1:
  1101. upb_inttable_uninit(&m->itof);
  1102. err2:
  1103. free(m);
  1104. return NULL;
  1105. }
  1106. upb_msgdef *upb_msgdef_dup(const upb_msgdef *m, const void *owner) {
  1107. upb_msgdef *newm = upb_msgdef_new(owner);
  1108. if (!newm) return NULL;
  1109. bool ok = upb_def_setfullname(UPB_UPCAST(newm),
  1110. upb_def_fullname(UPB_UPCAST(m)), NULL);
  1111. newm->map_entry = m->map_entry;
  1112. UPB_ASSERT_VAR(ok, ok);
  1113. upb_msg_iter i;
  1114. for(upb_msg_begin(&i, m); !upb_msg_done(&i); upb_msg_next(&i)) {
  1115. upb_fielddef *f = upb_fielddef_dup(upb_msg_iter_field(&i), &f);
  1116. if (!f || !upb_msgdef_addfield(newm, f, &f, NULL)) {
  1117. upb_msgdef_unref(newm, owner);
  1118. return NULL;
  1119. }
  1120. }
  1121. return newm;
  1122. }
  1123. bool upb_msgdef_isfrozen(const upb_msgdef *m) {
  1124. return upb_def_isfrozen(UPB_UPCAST(m));
  1125. }
  1126. void upb_msgdef_ref(const upb_msgdef *m, const void *owner) {
  1127. upb_def_ref(UPB_UPCAST(m), owner);
  1128. }
  1129. void upb_msgdef_unref(const upb_msgdef *m, const void *owner) {
  1130. upb_def_unref(UPB_UPCAST(m), owner);
  1131. }
  1132. void upb_msgdef_donateref(
  1133. const upb_msgdef *m, const void *from, const void *to) {
  1134. upb_def_donateref(UPB_UPCAST(m), from, to);
  1135. }
  1136. void upb_msgdef_checkref(const upb_msgdef *m, const void *owner) {
  1137. upb_def_checkref(UPB_UPCAST(m), owner);
  1138. }
  1139. bool upb_msgdef_freeze(upb_msgdef *m, upb_status *status) {
  1140. upb_def *d = UPB_UPCAST(m);
  1141. return upb_def_freeze(&d, 1, status);
  1142. }
  1143. const char *upb_msgdef_fullname(const upb_msgdef *m) {
  1144. return upb_def_fullname(UPB_UPCAST(m));
  1145. }
  1146. bool upb_msgdef_setfullname(upb_msgdef *m, const char *fullname,
  1147. upb_status *s) {
  1148. return upb_def_setfullname(UPB_UPCAST(m), fullname, s);
  1149. }
  1150. bool upb_msgdef_addfield(upb_msgdef *m, upb_fielddef *f, const void *ref_donor,
  1151. upb_status *s) {
  1152. // TODO: extensions need to have a separate namespace, because proto2 allows a
  1153. // top-level extension (ie. one not in any package) to have the same name as a
  1154. // field from the message.
  1155. //
  1156. // This also implies that there needs to be a separate lookup-by-name method
  1157. // for extensions. It seems desirable for iteration to return both extensions
  1158. // and non-extensions though.
  1159. //
  1160. // We also need to validate that the field number is in an extension range iff
  1161. // it is an extension.
  1162. // Check constraints for all fields before performing any action.
  1163. if (upb_fielddef_containingtype(f) != NULL) {
  1164. upb_status_seterrmsg(s, "fielddef already belongs to a message");
  1165. return false;
  1166. } else if (upb_fielddef_name(f) == NULL || upb_fielddef_number(f) == 0) {
  1167. upb_status_seterrmsg(s, "field name or number were not set");
  1168. return false;
  1169. } else if(upb_msgdef_itof(m, upb_fielddef_number(f)) ||
  1170. upb_msgdef_ntofz(m, upb_fielddef_name(f))) {
  1171. upb_status_seterrmsg(s, "duplicate field name or number");
  1172. return false;
  1173. }
  1174. // Constraint checks ok, perform the action.
  1175. release_containingtype(f);
  1176. f->msg.def = m;
  1177. f->msg_is_symbolic = false;
  1178. upb_inttable_insert(&m->itof, upb_fielddef_number(f), upb_value_ptr(f));
  1179. upb_strtable_insert(&m->ntof, upb_fielddef_name(f), upb_value_ptr(f));
  1180. upb_ref2(f, m);
  1181. upb_ref2(m, f);
  1182. if (ref_donor) upb_fielddef_unref(f, ref_donor);
  1183. return true;
  1184. }
  1185. const upb_fielddef *upb_msgdef_itof(const upb_msgdef *m, uint32_t i) {
  1186. upb_value val;
  1187. return upb_inttable_lookup32(&m->itof, i, &val) ?
  1188. upb_value_getptr(val) : NULL;
  1189. }
  1190. const upb_fielddef *upb_msgdef_ntof(const upb_msgdef *m, const char *name,
  1191. size_t len) {
  1192. upb_value val;
  1193. return upb_strtable_lookup2(&m->ntof, name, len, &val) ?
  1194. upb_value_getptr(val) : NULL;
  1195. }
  1196. int upb_msgdef_numfields(const upb_msgdef *m) {
  1197. return upb_strtable_count(&m->ntof);
  1198. }
  1199. void upb_msgdef_setmapentry(upb_msgdef *m, bool map_entry) {
  1200. assert(!upb_msgdef_isfrozen(m));
  1201. m->map_entry = map_entry;
  1202. }
  1203. bool upb_msgdef_mapentry(const upb_msgdef *m) {
  1204. return m->map_entry;
  1205. }
  1206. void upb_msg_begin(upb_msg_iter *iter, const upb_msgdef *m) {
  1207. upb_inttable_begin(iter, &m->itof);
  1208. }
  1209. void upb_msg_next(upb_msg_iter *iter) { upb_inttable_next(iter); }
  1210. bool upb_msg_done(const upb_msg_iter *iter) { return upb_inttable_done(iter); }
  1211. upb_fielddef *upb_msg_iter_field(const upb_msg_iter *iter) {
  1212. return (upb_fielddef*)upb_value_getptr(upb_inttable_iter_value(iter));
  1213. }
  1214. void upb_msg_iter_setdone(upb_msg_iter *iter) {
  1215. upb_inttable_iter_setdone(iter);
  1216. }
  1217. /*
  1218. * upb - a minimalist implementation of protocol buffers.
  1219. *
  1220. * Copyright (c) 2011-2012 Google Inc. See LICENSE for details.
  1221. * Author: Josh Haberman <jhaberman@gmail.com>
  1222. *
  1223. * TODO(haberman): it's unclear whether a lot of the consistency checks should
  1224. * assert() or return false.
  1225. */
  1226. #include <stdlib.h>
  1227. #include <string.h>
  1228. // Defined for the sole purpose of having a unique pointer value for
  1229. // UPB_NO_CLOSURE.
  1230. char _upb_noclosure;
  1231. static void freehandlers(upb_refcounted *r) {
  1232. upb_handlers *h = (upb_handlers*)r;
  1233. upb_inttable_iter i;
  1234. upb_inttable_begin(&i, &h->cleanup_);
  1235. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  1236. void *val = (void*)upb_inttable_iter_key(&i);
  1237. upb_value func_val = upb_inttable_iter_value(&i);
  1238. upb_handlerfree *func = upb_value_getfptr(func_val);
  1239. func(val);
  1240. }
  1241. upb_inttable_uninit(&h->cleanup_);
  1242. upb_msgdef_unref(h->msg, h);
  1243. free(h->sub);
  1244. free(h);
  1245. }
  1246. static void visithandlers(const upb_refcounted *r, upb_refcounted_visit *visit,
  1247. void *closure) {
  1248. const upb_handlers *h = (const upb_handlers*)r;
  1249. upb_msg_iter i;
  1250. for(upb_msg_begin(&i, h->msg); !upb_msg_done(&i); upb_msg_next(&i)) {
  1251. upb_fielddef *f = upb_msg_iter_field(&i);
  1252. if (!upb_fielddef_issubmsg(f)) continue;
  1253. const upb_handlers *sub = upb_handlers_getsubhandlers(h, f);
  1254. if (sub) visit(r, UPB_UPCAST(sub), closure);
  1255. }
  1256. }
  1257. static const struct upb_refcounted_vtbl vtbl = {visithandlers, freehandlers};
  1258. typedef struct {
  1259. upb_inttable tab; // maps upb_msgdef* -> upb_handlers*.
  1260. upb_handlers_callback *callback;
  1261. const void *closure;
  1262. } dfs_state;
  1263. // TODO(haberman): discard upb_handlers* objects that do not actually have any
  1264. // handlers set and cannot reach any upb_handlers* object that does. This is
  1265. // slightly tricky to do correctly.
  1266. static upb_handlers *newformsg(const upb_msgdef *m, const void *owner,
  1267. dfs_state *s) {
  1268. upb_handlers *h = upb_handlers_new(m, owner);
  1269. if (!h) return NULL;
  1270. if (!upb_inttable_insertptr(&s->tab, m, upb_value_ptr(h))) goto oom;
  1271. s->callback(s->closure, h);
  1272. // For each submessage field, get or create a handlers object and set it as
  1273. // the subhandlers.
  1274. upb_msg_iter i;
  1275. for(upb_msg_begin(&i, m); !upb_msg_done(&i); upb_msg_next(&i)) {
  1276. upb_fielddef *f = upb_msg_iter_field(&i);
  1277. if (!upb_fielddef_issubmsg(f)) continue;
  1278. const upb_msgdef *subdef = upb_downcast_msgdef(upb_fielddef_subdef(f));
  1279. upb_value subm_ent;
  1280. if (upb_inttable_lookupptr(&s->tab, subdef, &subm_ent)) {
  1281. upb_handlers_setsubhandlers(h, f, upb_value_getptr(subm_ent));
  1282. } else {
  1283. upb_handlers *sub_mh = newformsg(subdef, &sub_mh, s);
  1284. if (!sub_mh) goto oom;
  1285. upb_handlers_setsubhandlers(h, f, sub_mh);
  1286. upb_handlers_unref(sub_mh, &sub_mh);
  1287. }
  1288. }
  1289. return h;
  1290. oom:
  1291. upb_handlers_unref(h, owner);
  1292. return NULL;
  1293. }
  1294. // Given a selector for a STARTSUBMSG handler, resolves to a pointer to the
  1295. // subhandlers for this submessage field.
  1296. #define SUBH(h, selector) (h->sub[selector])
  1297. // The selector for a submessage field is the field index.
  1298. #define SUBH_F(h, f) SUBH(h, f->index_)
  1299. static int32_t trygetsel(upb_handlers *h, const upb_fielddef *f,
  1300. upb_handlertype_t type) {
  1301. upb_selector_t sel;
  1302. assert(!upb_handlers_isfrozen(h));
  1303. if (upb_handlers_msgdef(h) != upb_fielddef_containingtype(f)) {
  1304. upb_status_seterrf(
  1305. &h->status_, "type mismatch: field %s does not belong to message %s",
  1306. upb_fielddef_name(f), upb_msgdef_fullname(upb_handlers_msgdef(h)));
  1307. return -1;
  1308. }
  1309. if (!upb_handlers_getselector(f, type, &sel)) {
  1310. upb_status_seterrf(
  1311. &h->status_,
  1312. "type mismatch: cannot register handler type %d for field %s",
  1313. type, upb_fielddef_name(f));
  1314. return -1;
  1315. }
  1316. return sel;
  1317. }
  1318. static upb_selector_t handlers_getsel(upb_handlers *h, const upb_fielddef *f,
  1319. upb_handlertype_t type) {
  1320. int32_t sel = trygetsel(h, f, type);
  1321. assert(sel >= 0);
  1322. return sel;
  1323. }
  1324. static const void **returntype(upb_handlers *h, const upb_fielddef *f,
  1325. upb_handlertype_t type) {
  1326. return &h->table[handlers_getsel(h, f, type)].attr.return_closure_type_;
  1327. }
  1328. static bool doset(upb_handlers *h, int32_t sel, const upb_fielddef *f,
  1329. upb_handlertype_t type, upb_func *func,
  1330. upb_handlerattr *attr) {
  1331. assert(!upb_handlers_isfrozen(h));
  1332. if (sel < 0) {
  1333. upb_status_seterrmsg(&h->status_,
  1334. "incorrect handler type for this field.");
  1335. return false;
  1336. }
  1337. if (h->table[sel].func) {
  1338. upb_status_seterrmsg(&h->status_,
  1339. "cannot change handler once it has been set.");
  1340. return false;
  1341. }
  1342. upb_handlerattr set_attr = UPB_HANDLERATTR_INITIALIZER;
  1343. if (attr) {
  1344. set_attr = *attr;
  1345. }
  1346. // Check that the given closure type matches the closure type that has been
  1347. // established for this context (if any).
  1348. const void *closure_type = upb_handlerattr_closuretype(&set_attr);
  1349. const void **context_closure_type;
  1350. if (type == UPB_HANDLER_STRING) {
  1351. context_closure_type = returntype(h, f, UPB_HANDLER_STARTSTR);
  1352. } else if (f && upb_fielddef_isseq(f) &&
  1353. type != UPB_HANDLER_STARTSEQ &&
  1354. type != UPB_HANDLER_ENDSEQ) {
  1355. context_closure_type = returntype(h, f, UPB_HANDLER_STARTSEQ);
  1356. } else {
  1357. context_closure_type = &h->top_closure_type;
  1358. }
  1359. if (closure_type && *context_closure_type &&
  1360. closure_type != *context_closure_type) {
  1361. // TODO(haberman): better message for debugging.
  1362. upb_status_seterrmsg(&h->status_, "closure type does not match");
  1363. return false;
  1364. }
  1365. if (closure_type)
  1366. *context_closure_type = closure_type;
  1367. // If this is a STARTSEQ or STARTSTR handler, check that the returned pointer
  1368. // matches any pre-existing expectations about what type is expected.
  1369. if (type == UPB_HANDLER_STARTSEQ || type == UPB_HANDLER_STARTSTR) {
  1370. const void *return_type = upb_handlerattr_returnclosuretype(&set_attr);
  1371. const void *table_return_type =
  1372. upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  1373. if (return_type && table_return_type && return_type != table_return_type) {
  1374. upb_status_seterrmsg(&h->status_, "closure return type does not match");
  1375. return false;
  1376. }
  1377. if (table_return_type && !return_type)
  1378. upb_handlerattr_setreturnclosuretype(&set_attr, table_return_type);
  1379. }
  1380. h->table[sel].func = (upb_func*)func;
  1381. h->table[sel].attr = set_attr;
  1382. return true;
  1383. }
  1384. // Returns the effective closure type for this handler (which will propagate
  1385. // from outer frames if this frame has no START* handler). Not implemented for
  1386. // UPB_HANDLER_STRING at the moment since this is not needed. Returns NULL is
  1387. // the effective closure type is unspecified (either no handler was registered
  1388. // to specify it or the handler that was registered did not specify the closure
  1389. // type).
  1390. const void *effective_closure_type(upb_handlers *h, const upb_fielddef *f,
  1391. upb_handlertype_t type) {
  1392. assert(type != UPB_HANDLER_STRING);
  1393. const void *ret = h->top_closure_type;
  1394. upb_selector_t sel;
  1395. if (upb_fielddef_isseq(f) &&
  1396. type != UPB_HANDLER_STARTSEQ &&
  1397. type != UPB_HANDLER_ENDSEQ &&
  1398. h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSEQ)].func) {
  1399. ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  1400. }
  1401. if (type == UPB_HANDLER_STRING &&
  1402. h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSTR)].func) {
  1403. ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  1404. }
  1405. // The effective type of the submessage; not used yet.
  1406. // if (type == SUBMESSAGE &&
  1407. // h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSUBMSG)].func) {
  1408. // ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
  1409. // }
  1410. return ret;
  1411. }
  1412. // Checks whether the START* handler specified by f & type is missing even
  1413. // though it is required to convert the established type of an outer frame
  1414. // ("closure_type") into the established type of an inner frame (represented in
  1415. // the return closure type of this handler's attr.
  1416. bool checkstart(upb_handlers *h, const upb_fielddef *f, upb_handlertype_t type,
  1417. upb_status *status) {
  1418. upb_selector_t sel = handlers_getsel(h, f, type);
  1419. if (h->table[sel].func) return true;
  1420. const void *closure_type = effective_closure_type(h, f, type);
  1421. const upb_handlerattr *attr = &h->table[sel].attr;
  1422. const void *return_closure_type = upb_handlerattr_returnclosuretype(attr);
  1423. if (closure_type && return_closure_type &&
  1424. closure_type != return_closure_type) {
  1425. upb_status_seterrf(status,
  1426. "expected start handler to return sub type for field %f",
  1427. upb_fielddef_name(f));
  1428. return false;
  1429. }
  1430. return true;
  1431. }
  1432. /* Public interface ***********************************************************/
  1433. bool upb_handlers_isfrozen(const upb_handlers *h) {
  1434. return upb_refcounted_isfrozen(UPB_UPCAST(h));
  1435. }
  1436. void upb_handlers_ref(const upb_handlers *h, const void *owner) {
  1437. upb_refcounted_ref(UPB_UPCAST(h), owner);
  1438. }
  1439. void upb_handlers_unref(const upb_handlers *h, const void *owner) {
  1440. upb_refcounted_unref(UPB_UPCAST(h), owner);
  1441. }
  1442. void upb_handlers_donateref(
  1443. const upb_handlers *h, const void *from, const void *to) {
  1444. upb_refcounted_donateref(UPB_UPCAST(h), from, to);
  1445. }
  1446. void upb_handlers_checkref(const upb_handlers *h, const void *owner) {
  1447. upb_refcounted_checkref(UPB_UPCAST(h), owner);
  1448. }
  1449. upb_handlers *upb_handlers_new(const upb_msgdef *md, const void *owner) {
  1450. assert(upb_msgdef_isfrozen(md));
  1451. int extra = sizeof(upb_handlers_tabent) * (md->selector_count - 1);
  1452. upb_handlers *h = calloc(sizeof(*h) + extra, 1);
  1453. if (!h) return NULL;
  1454. h->msg = md;
  1455. upb_msgdef_ref(h->msg, h);
  1456. upb_status_clear(&h->status_);
  1457. h->sub = calloc(md->submsg_field_count, sizeof(*h->sub));
  1458. if (!h->sub) goto oom;
  1459. if (!upb_refcounted_init(UPB_UPCAST(h), &vtbl, owner)) goto oom;
  1460. if (!upb_inttable_init(&h->cleanup_, UPB_CTYPE_FPTR)) goto oom;
  1461. // calloc() above initialized all handlers to NULL.
  1462. return h;
  1463. oom:
  1464. freehandlers(UPB_UPCAST(h));
  1465. return NULL;
  1466. }
  1467. const upb_handlers *upb_handlers_newfrozen(const upb_msgdef *m,
  1468. const void *owner,
  1469. upb_handlers_callback *callback,
  1470. const void *closure) {
  1471. dfs_state state;
  1472. state.callback = callback;
  1473. state.closure = closure;
  1474. if (!upb_inttable_init(&state.tab, UPB_CTYPE_PTR)) return NULL;
  1475. upb_handlers *ret = newformsg(m, owner, &state);
  1476. upb_inttable_uninit(&state.tab);
  1477. if (!ret) return NULL;
  1478. upb_refcounted *r = UPB_UPCAST(ret);
  1479. bool ok = upb_refcounted_freeze(&r, 1, NULL, UPB_MAX_HANDLER_DEPTH);
  1480. UPB_ASSERT_VAR(ok, ok);
  1481. return ret;
  1482. }
  1483. const upb_status *upb_handlers_status(upb_handlers *h) {
  1484. assert(!upb_handlers_isfrozen(h));
  1485. return &h->status_;
  1486. }
  1487. void upb_handlers_clearerr(upb_handlers *h) {
  1488. assert(!upb_handlers_isfrozen(h));
  1489. upb_status_clear(&h->status_);
  1490. }
  1491. #define SETTER(name, handlerctype, handlertype) \
  1492. bool upb_handlers_set ## name(upb_handlers *h, const upb_fielddef *f, \
  1493. handlerctype func, upb_handlerattr *attr) { \
  1494. int32_t sel = trygetsel(h, f, handlertype); \
  1495. return doset(h, sel, f, handlertype, (upb_func*)func, attr); \
  1496. }
  1497. SETTER(int32, upb_int32_handlerfunc*, UPB_HANDLER_INT32);
  1498. SETTER(int64, upb_int64_handlerfunc*, UPB_HANDLER_INT64);
  1499. SETTER(uint32, upb_uint32_handlerfunc*, UPB_HANDLER_UINT32);
  1500. SETTER(uint64, upb_uint64_handlerfunc*, UPB_HANDLER_UINT64);
  1501. SETTER(float, upb_float_handlerfunc*, UPB_HANDLER_FLOAT);
  1502. SETTER(double, upb_double_handlerfunc*, UPB_HANDLER_DOUBLE);
  1503. SETTER(bool, upb_bool_handlerfunc*, UPB_HANDLER_BOOL);
  1504. SETTER(startstr, upb_startstr_handlerfunc*, UPB_HANDLER_STARTSTR);
  1505. SETTER(string, upb_string_handlerfunc*, UPB_HANDLER_STRING);
  1506. SETTER(endstr, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSTR);
  1507. SETTER(startseq, upb_startfield_handlerfunc*, UPB_HANDLER_STARTSEQ);
  1508. SETTER(startsubmsg, upb_startfield_handlerfunc*, UPB_HANDLER_STARTSUBMSG);
  1509. SETTER(endsubmsg, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSUBMSG);
  1510. SETTER(endseq, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSEQ);
  1511. #undef SETTER
  1512. bool upb_handlers_setstartmsg(upb_handlers *h, upb_startmsg_handlerfunc *func,
  1513. upb_handlerattr *attr) {
  1514. return doset(h, UPB_STARTMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
  1515. (upb_func *)func, attr);
  1516. }
  1517. bool upb_handlers_setendmsg(upb_handlers *h, upb_endmsg_handlerfunc *func,
  1518. upb_handlerattr *attr) {
  1519. assert(!upb_handlers_isfrozen(h));
  1520. return doset(h, UPB_ENDMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
  1521. (upb_func *)func, attr);
  1522. }
  1523. bool upb_handlers_setsubhandlers(upb_handlers *h, const upb_fielddef *f,
  1524. const upb_handlers *sub) {
  1525. assert(sub);
  1526. assert(!upb_handlers_isfrozen(h));
  1527. assert(upb_fielddef_issubmsg(f));
  1528. if (SUBH_F(h, f)) return false; // Can't reset.
  1529. if (UPB_UPCAST(upb_handlers_msgdef(sub)) != upb_fielddef_subdef(f)) {
  1530. return false;
  1531. }
  1532. SUBH_F(h, f) = sub;
  1533. upb_ref2(sub, h);
  1534. return true;
  1535. }
  1536. const upb_handlers *upb_handlers_getsubhandlers(const upb_handlers *h,
  1537. const upb_fielddef *f) {
  1538. assert(upb_fielddef_issubmsg(f));
  1539. return SUBH_F(h, f);
  1540. }
  1541. bool upb_handlers_getattr(const upb_handlers *h, upb_selector_t sel,
  1542. upb_handlerattr *attr) {
  1543. if (!upb_handlers_gethandler(h, sel))
  1544. return false;
  1545. *attr = h->table[sel].attr;
  1546. return true;
  1547. }
  1548. const upb_handlers *upb_handlers_getsubhandlers_sel(const upb_handlers *h,
  1549. upb_selector_t sel) {
  1550. // STARTSUBMSG selector in sel is the field's selector base.
  1551. return SUBH(h, sel - UPB_STATIC_SELECTOR_COUNT);
  1552. }
  1553. const upb_msgdef *upb_handlers_msgdef(const upb_handlers *h) { return h->msg; }
  1554. bool upb_handlers_addcleanup(upb_handlers *h, void *p, upb_handlerfree *func) {
  1555. if (upb_inttable_lookupptr(&h->cleanup_, p, NULL)) {
  1556. return false;
  1557. }
  1558. bool ok = upb_inttable_insertptr(&h->cleanup_, p, upb_value_fptr(func));
  1559. UPB_ASSERT_VAR(ok, ok);
  1560. return true;
  1561. }
  1562. /* "Static" methods ***********************************************************/
  1563. bool upb_handlers_freeze(upb_handlers *const*handlers, int n, upb_status *s) {
  1564. // TODO: verify we have a transitive closure.
  1565. for (int i = 0; i < n; i++) {
  1566. upb_handlers *h = handlers[i];
  1567. if (!upb_ok(&h->status_)) {
  1568. upb_status_seterrf(s, "handlers for message %s had error status: %s",
  1569. upb_msgdef_fullname(upb_handlers_msgdef(h)),
  1570. upb_status_errmsg(&h->status_));
  1571. return false;
  1572. }
  1573. // Check that there are no closure mismatches due to missing Start* handlers
  1574. // or subhandlers with different type-level types.
  1575. upb_msg_iter j;
  1576. for(upb_msg_begin(&j, h->msg); !upb_msg_done(&j); upb_msg_next(&j)) {
  1577. const upb_fielddef *f = upb_msg_iter_field(&j);
  1578. if (upb_fielddef_isseq(f)) {
  1579. if (!checkstart(h, f, UPB_HANDLER_STARTSEQ, s))
  1580. return false;
  1581. }
  1582. if (upb_fielddef_isstring(f)) {
  1583. if (!checkstart(h, f, UPB_HANDLER_STARTSTR, s))
  1584. return false;
  1585. }
  1586. if (upb_fielddef_issubmsg(f)) {
  1587. bool hashandler = false;
  1588. if (upb_handlers_gethandler(
  1589. h, handlers_getsel(h, f, UPB_HANDLER_STARTSUBMSG)) ||
  1590. upb_handlers_gethandler(
  1591. h, handlers_getsel(h, f, UPB_HANDLER_ENDSUBMSG))) {
  1592. hashandler = true;
  1593. }
  1594. if (upb_fielddef_isseq(f) &&
  1595. (upb_handlers_gethandler(
  1596. h, handlers_getsel(h, f, UPB_HANDLER_STARTSEQ)) ||
  1597. upb_handlers_gethandler(
  1598. h, handlers_getsel(h, f, UPB_HANDLER_ENDSEQ)))) {
  1599. hashandler = true;
  1600. }
  1601. if (hashandler && !upb_handlers_getsubhandlers(h, f)) {
  1602. // For now we add an empty subhandlers in this case. It makes the
  1603. // decoder code generator simpler, because it only has to handle two
  1604. // cases (submessage has handlers or not) as opposed to three
  1605. // (submessage has handlers in enclosing message but no subhandlers).
  1606. //
  1607. // This makes parsing less efficient in the case that we want to
  1608. // notice a submessage but skip its contents (like if we're testing
  1609. // for submessage presence or counting the number of repeated
  1610. // submessages). In this case we will end up parsing the submessage
  1611. // field by field and throwing away the results for each, instead of
  1612. // skipping the whole delimited thing at once. If this is an issue we
  1613. // can revisit it, but do remember that this only arises when you have
  1614. // handlers (startseq/startsubmsg/endsubmsg/endseq) set for the
  1615. // submessage but no subhandlers. The uses cases for this are
  1616. // limited.
  1617. upb_handlers *sub = upb_handlers_new(upb_fielddef_msgsubdef(f), &sub);
  1618. upb_handlers_setsubhandlers(h, f, sub);
  1619. upb_handlers_unref(sub, &sub);
  1620. }
  1621. // TODO(haberman): check type of submessage.
  1622. // This is slightly tricky; also consider whether we should check that
  1623. // they match at setsubhandlers time.
  1624. }
  1625. }
  1626. }
  1627. if (!upb_refcounted_freeze((upb_refcounted*const*)handlers, n, s,
  1628. UPB_MAX_HANDLER_DEPTH)) {
  1629. return false;
  1630. }
  1631. return true;
  1632. }
  1633. upb_handlertype_t upb_handlers_getprimitivehandlertype(const upb_fielddef *f) {
  1634. switch (upb_fielddef_type(f)) {
  1635. case UPB_TYPE_INT32:
  1636. case UPB_TYPE_ENUM: return UPB_HANDLER_INT32;
  1637. case UPB_TYPE_INT64: return UPB_HANDLER_INT64;
  1638. case UPB_TYPE_UINT32: return UPB_HANDLER_UINT32;
  1639. case UPB_TYPE_UINT64: return UPB_HANDLER_UINT64;
  1640. case UPB_TYPE_FLOAT: return UPB_HANDLER_FLOAT;
  1641. case UPB_TYPE_DOUBLE: return UPB_HANDLER_DOUBLE;
  1642. case UPB_TYPE_BOOL: return UPB_HANDLER_BOOL;
  1643. default: assert(false); return -1; // Invalid input.
  1644. }
  1645. }
  1646. bool upb_handlers_getselector(const upb_fielddef *f, upb_handlertype_t type,
  1647. upb_selector_t *s) {
  1648. switch (type) {
  1649. case UPB_HANDLER_INT32:
  1650. case UPB_HANDLER_INT64:
  1651. case UPB_HANDLER_UINT32:
  1652. case UPB_HANDLER_UINT64:
  1653. case UPB_HANDLER_FLOAT:
  1654. case UPB_HANDLER_DOUBLE:
  1655. case UPB_HANDLER_BOOL:
  1656. if (!upb_fielddef_isprimitive(f) ||
  1657. upb_handlers_getprimitivehandlertype(f) != type)
  1658. return false;
  1659. *s = f->selector_base;
  1660. break;
  1661. case UPB_HANDLER_STRING:
  1662. if (upb_fielddef_isstring(f)) {
  1663. *s = f->selector_base;
  1664. } else if (upb_fielddef_lazy(f)) {
  1665. *s = f->selector_base + 3;
  1666. } else {
  1667. return false;
  1668. }
  1669. break;
  1670. case UPB_HANDLER_STARTSTR:
  1671. if (upb_fielddef_isstring(f) || upb_fielddef_lazy(f)) {
  1672. *s = f->selector_base + 1;
  1673. } else {
  1674. return false;
  1675. }
  1676. break;
  1677. case UPB_HANDLER_ENDSTR:
  1678. if (upb_fielddef_isstring(f) || upb_fielddef_lazy(f)) {
  1679. *s = f->selector_base + 2;
  1680. } else {
  1681. return false;
  1682. }
  1683. break;
  1684. case UPB_HANDLER_STARTSEQ:
  1685. if (!upb_fielddef_isseq(f)) return false;
  1686. *s = f->selector_base - 2;
  1687. break;
  1688. case UPB_HANDLER_ENDSEQ:
  1689. if (!upb_fielddef_isseq(f)) return false;
  1690. *s = f->selector_base - 1;
  1691. break;
  1692. case UPB_HANDLER_STARTSUBMSG:
  1693. if (!upb_fielddef_issubmsg(f)) return false;
  1694. // Selectors for STARTSUBMSG are at the beginning of the table so that the
  1695. // selector can also be used as an index into the "sub" array of
  1696. // subhandlers. The indexes for the two into these two tables are the
  1697. // same, except that in the handler table the static selectors come first.
  1698. *s = f->index_ + UPB_STATIC_SELECTOR_COUNT;
  1699. break;
  1700. case UPB_HANDLER_ENDSUBMSG:
  1701. if (!upb_fielddef_issubmsg(f)) return false;
  1702. *s = f->selector_base;
  1703. break;
  1704. }
  1705. assert(*s < upb_fielddef_containingtype(f)->selector_count);
  1706. return true;
  1707. }
  1708. uint32_t upb_handlers_selectorbaseoffset(const upb_fielddef *f) {
  1709. return upb_fielddef_isseq(f) ? 2 : 0;
  1710. }
  1711. uint32_t upb_handlers_selectorcount(const upb_fielddef *f) {
  1712. uint32_t ret = 1;
  1713. if (upb_fielddef_isseq(f)) ret += 2; // STARTSEQ/ENDSEQ
  1714. if (upb_fielddef_isstring(f)) ret += 2; // [STRING]/STARTSTR/ENDSTR
  1715. if (upb_fielddef_issubmsg(f)) {
  1716. // ENDSUBMSG (STARTSUBMSG is at table beginning)
  1717. ret += 0;
  1718. if (upb_fielddef_lazy(f)) {
  1719. // STARTSTR/ENDSTR/STRING (for lazy)
  1720. ret += 3;
  1721. }
  1722. }
  1723. return ret;
  1724. }
  1725. /* upb_handlerattr ************************************************************/
  1726. void upb_handlerattr_init(upb_handlerattr *attr) {
  1727. upb_handlerattr from = UPB_HANDLERATTR_INITIALIZER;
  1728. memcpy(attr, &from, sizeof(*attr));
  1729. }
  1730. void upb_handlerattr_uninit(upb_handlerattr *attr) {
  1731. UPB_UNUSED(attr);
  1732. }
  1733. bool upb_handlerattr_sethandlerdata(upb_handlerattr *attr, const void *hd) {
  1734. attr->handler_data_ = hd;
  1735. return true;
  1736. }
  1737. bool upb_handlerattr_setclosuretype(upb_handlerattr *attr, const void *type) {
  1738. attr->closure_type_ = type;
  1739. return true;
  1740. }
  1741. const void *upb_handlerattr_closuretype(const upb_handlerattr *attr) {
  1742. return attr->closure_type_;
  1743. }
  1744. bool upb_handlerattr_setreturnclosuretype(upb_handlerattr *attr,
  1745. const void *type) {
  1746. attr->return_closure_type_ = type;
  1747. return true;
  1748. }
  1749. const void *upb_handlerattr_returnclosuretype(const upb_handlerattr *attr) {
  1750. return attr->return_closure_type_;
  1751. }
  1752. bool upb_handlerattr_setalwaysok(upb_handlerattr *attr, bool alwaysok) {
  1753. attr->alwaysok_ = alwaysok;
  1754. return true;
  1755. }
  1756. bool upb_handlerattr_alwaysok(const upb_handlerattr *attr) {
  1757. return attr->alwaysok_;
  1758. }
  1759. /* upb_bufhandle **************************************************************/
  1760. size_t upb_bufhandle_objofs(const upb_bufhandle *h) {
  1761. return h->objofs_;
  1762. }
  1763. /* upb_byteshandler ***********************************************************/
  1764. void upb_byteshandler_init(upb_byteshandler* h) {
  1765. memset(h, 0, sizeof(*h));
  1766. }
  1767. // For when we support handlerfree callbacks.
  1768. void upb_byteshandler_uninit(upb_byteshandler* h) {
  1769. UPB_UNUSED(h);
  1770. }
  1771. bool upb_byteshandler_setstartstr(upb_byteshandler *h,
  1772. upb_startstr_handlerfunc *func, void *d) {
  1773. h->table[UPB_STARTSTR_SELECTOR].func = (upb_func*)func;
  1774. h->table[UPB_STARTSTR_SELECTOR].attr.handler_data_ = d;
  1775. return true;
  1776. }
  1777. bool upb_byteshandler_setstring(upb_byteshandler *h,
  1778. upb_string_handlerfunc *func, void *d) {
  1779. h->table[UPB_STRING_SELECTOR].func = (upb_func*)func;
  1780. h->table[UPB_STRING_SELECTOR].attr.handler_data_ = d;
  1781. return true;
  1782. }
  1783. bool upb_byteshandler_setendstr(upb_byteshandler *h,
  1784. upb_endfield_handlerfunc *func, void *d) {
  1785. h->table[UPB_ENDSTR_SELECTOR].func = (upb_func*)func;
  1786. h->table[UPB_ENDSTR_SELECTOR].attr.handler_data_ = d;
  1787. return true;
  1788. }
  1789. /*
  1790. * upb - a minimalist implementation of protocol buffers.
  1791. *
  1792. * Copyright (c) 2012 Google Inc. See LICENSE for details.
  1793. * Author: Josh Haberman <jhaberman@gmail.com>
  1794. *
  1795. * Our key invariants are:
  1796. * 1. reference cycles never span groups
  1797. * 2. for ref2(to, from), we increment to's count iff group(from) != group(to)
  1798. *
  1799. * The previous two are how we avoid leaking cycles. Other important
  1800. * invariants are:
  1801. * 3. for mutable objects "from" and "to", if there exists a ref2(to, from)
  1802. * this implies group(from) == group(to). (In practice, what we implement
  1803. * is even stronger; "from" and "to" will share a group if there has *ever*
  1804. * been a ref2(to, from), but all that is necessary for correctness is the
  1805. * weaker one).
  1806. * 4. mutable and immutable objects are never in the same group.
  1807. */
  1808. #include <setjmp.h>
  1809. #include <stdlib.h>
  1810. static void freeobj(upb_refcounted *o);
  1811. const char untracked_val;
  1812. const void *UPB_UNTRACKED_REF = &untracked_val;
  1813. /* arch-specific atomic primitives *******************************************/
  1814. #ifdef UPB_THREAD_UNSAFE //////////////////////////////////////////////////////
  1815. static void atomic_inc(uint32_t *a) { (*a)++; }
  1816. static bool atomic_dec(uint32_t *a) { return --(*a) == 0; }
  1817. #elif defined(__GNUC__) || defined(__clang__) //////////////////////////////////
  1818. static void atomic_inc(uint32_t *a) { __sync_fetch_and_add(a, 1); }
  1819. static bool atomic_dec(uint32_t *a) { return __sync_sub_and_fetch(a, 1) == 0; }
  1820. #elif defined(WIN32) ///////////////////////////////////////////////////////////
  1821. #include <Windows.h>
  1822. static void atomic_inc(upb_atomic_t *a) { InterlockedIncrement(&a->val); }
  1823. static bool atomic_dec(upb_atomic_t *a) {
  1824. return InterlockedDecrement(&a->val) == 0;
  1825. }
  1826. #else
  1827. #error Atomic primitives not defined for your platform/CPU. \
  1828. Implement them or compile with UPB_THREAD_UNSAFE.
  1829. #endif
  1830. // All static objects point to this refcount.
  1831. // It is special-cased in ref/unref below.
  1832. uint32_t static_refcount = -1;
  1833. // We can avoid atomic ops for statically-declared objects.
  1834. // This is a minor optimization but nice since we can avoid degrading under
  1835. // contention in this case.
  1836. static void refgroup(uint32_t *group) {
  1837. if (group != &static_refcount)
  1838. atomic_inc(group);
  1839. }
  1840. static bool unrefgroup(uint32_t *group) {
  1841. if (group == &static_refcount) {
  1842. return false;
  1843. } else {
  1844. return atomic_dec(group);
  1845. }
  1846. }
  1847. /* Reference tracking (debug only) ********************************************/
  1848. #ifdef UPB_DEBUG_REFS
  1849. #ifdef UPB_THREAD_UNSAFE
  1850. static void upb_lock() {}
  1851. static void upb_unlock() {}
  1852. #else
  1853. // User must define functions that lock/unlock a global mutex and link this
  1854. // file against them.
  1855. void upb_lock();
  1856. void upb_unlock();
  1857. #endif
  1858. // UPB_DEBUG_REFS mode counts on being able to malloc() memory in some
  1859. // code-paths that can normally never fail, like upb_refcounted_ref(). Since
  1860. // we have no way to propagage out-of-memory errors back to the user, and since
  1861. // these errors can only occur in UPB_DEBUG_REFS mode, we immediately fail.
  1862. #define CHECK_OOM(predicate) if (!(predicate)) { assert(predicate); exit(1); }
  1863. typedef struct {
  1864. int count; // How many refs there are (duplicates only allowed for ref2).
  1865. bool is_ref2;
  1866. } trackedref;
  1867. static trackedref *trackedref_new(bool is_ref2) {
  1868. trackedref *ret = malloc(sizeof(*ret));
  1869. CHECK_OOM(ret);
  1870. ret->count = 1;
  1871. ret->is_ref2 = is_ref2;
  1872. return ret;
  1873. }
  1874. static void track(const upb_refcounted *r, const void *owner, bool ref2) {
  1875. assert(owner);
  1876. if (owner == UPB_UNTRACKED_REF) return;
  1877. upb_lock();
  1878. upb_value v;
  1879. if (upb_inttable_lookupptr(r->refs, owner, &v)) {
  1880. trackedref *ref = upb_value_getptr(v);
  1881. // Since we allow multiple ref2's for the same to/from pair without
  1882. // allocating separate memory for each one, we lose the fine-grained
  1883. // tracking behavior we get with regular refs. Since ref2s only happen
  1884. // inside upb, we'll accept this limitation until/unless there is a really
  1885. // difficult upb-internal bug that can't be figured out without it.
  1886. assert(ref2);
  1887. assert(ref->is_ref2);
  1888. ref->count++;
  1889. } else {
  1890. trackedref *ref = trackedref_new(ref2);
  1891. bool ok = upb_inttable_insertptr(r->refs, owner, upb_value_ptr(ref));
  1892. CHECK_OOM(ok);
  1893. if (ref2) {
  1894. // We know this cast is safe when it is a ref2, because it's coming from
  1895. // another refcounted object.
  1896. const upb_refcounted *from = owner;
  1897. assert(!upb_inttable_lookupptr(from->ref2s, r, NULL));
  1898. ok = upb_inttable_insertptr(from->ref2s, r, upb_value_ptr(NULL));
  1899. CHECK_OOM(ok);
  1900. }
  1901. }
  1902. upb_unlock();
  1903. }
  1904. static void untrack(const upb_refcounted *r, const void *owner, bool ref2) {
  1905. assert(owner);
  1906. if (owner == UPB_UNTRACKED_REF) return;
  1907. upb_lock();
  1908. upb_value v;
  1909. bool found = upb_inttable_lookupptr(r->refs, owner, &v);
  1910. // This assert will fail if an owner attempts to release a ref it didn't have.
  1911. UPB_ASSERT_VAR(found, found);
  1912. trackedref *ref = upb_value_getptr(v);
  1913. assert(ref->is_ref2 == ref2);
  1914. if (--ref->count == 0) {
  1915. free(ref);
  1916. upb_inttable_removeptr(r->refs, owner, NULL);
  1917. if (ref2) {
  1918. // We know this cast is safe when it is a ref2, because it's coming from
  1919. // another refcounted object.
  1920. const upb_refcounted *from = owner;
  1921. bool removed = upb_inttable_removeptr(from->ref2s, r, NULL);
  1922. assert(removed);
  1923. }
  1924. }
  1925. upb_unlock();
  1926. }
  1927. static void checkref(const upb_refcounted *r, const void *owner, bool ref2) {
  1928. upb_lock();
  1929. upb_value v;
  1930. bool found = upb_inttable_lookupptr(r->refs, owner, &v);
  1931. UPB_ASSERT_VAR(found, found);
  1932. trackedref *ref = upb_value_getptr(v);
  1933. assert(ref->is_ref2 == ref2);
  1934. upb_unlock();
  1935. }
  1936. // Populates the given UPB_CTYPE_INT32 inttable with counts of ref2's that
  1937. // originate from the given owner.
  1938. static void getref2s(const upb_refcounted *owner, upb_inttable *tab) {
  1939. upb_lock();
  1940. upb_inttable_iter i;
  1941. upb_inttable_begin(&i, owner->ref2s);
  1942. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  1943. upb_refcounted *to = (upb_refcounted*)upb_inttable_iter_key(&i);
  1944. // To get the count we need to look in the target's table.
  1945. upb_value v;
  1946. bool found = upb_inttable_lookupptr(to->refs, owner, &v);
  1947. assert(found);
  1948. trackedref *ref = upb_value_getptr(v);
  1949. upb_value count = upb_value_int32(ref->count);
  1950. bool ok = upb_inttable_insertptr(tab, to, count);
  1951. CHECK_OOM(ok);
  1952. }
  1953. upb_unlock();
  1954. }
  1955. typedef struct {
  1956. upb_inttable ref2;
  1957. const upb_refcounted *obj;
  1958. } check_state;
  1959. static void visit_check(const upb_refcounted *obj, const upb_refcounted *subobj,
  1960. void *closure) {
  1961. check_state *s = closure;
  1962. assert(obj == s->obj);
  1963. assert(subobj);
  1964. upb_inttable *ref2 = &s->ref2;
  1965. upb_value v;
  1966. bool removed = upb_inttable_removeptr(ref2, subobj, &v);
  1967. // The following assertion will fail if the visit() function visits a subobj
  1968. // that it did not have a ref2 on, or visits the same subobj too many times.
  1969. assert(removed);
  1970. int32_t newcount = upb_value_getint32(v) - 1;
  1971. if (newcount > 0) {
  1972. upb_inttable_insert(ref2, (uintptr_t)subobj, upb_value_int32(newcount));
  1973. }
  1974. }
  1975. static void visit(const upb_refcounted *r, upb_refcounted_visit *v,
  1976. void *closure) {
  1977. // In DEBUG_REFS mode we know what existing ref2 refs there are, so we know
  1978. // exactly the set of nodes that visit() should visit. So we verify visit()'s
  1979. // correctness here.
  1980. check_state state;
  1981. state.obj = r;
  1982. bool ok = upb_inttable_init(&state.ref2, UPB_CTYPE_INT32);
  1983. CHECK_OOM(ok);
  1984. getref2s(r, &state.ref2);
  1985. // This should visit any children in the ref2 table.
  1986. if (r->vtbl->visit) r->vtbl->visit(r, visit_check, &state);
  1987. // This assertion will fail if the visit() function missed any children.
  1988. assert(upb_inttable_count(&state.ref2) == 0);
  1989. upb_inttable_uninit(&state.ref2);
  1990. if (r->vtbl->visit) r->vtbl->visit(r, v, closure);
  1991. }
  1992. static bool trackinit(upb_refcounted *r) {
  1993. r->refs = malloc(sizeof(*r->refs));
  1994. r->ref2s = malloc(sizeof(*r->ref2s));
  1995. if (!r->refs || !r->ref2s) goto err1;
  1996. if (!upb_inttable_init(r->refs, UPB_CTYPE_PTR)) goto err1;
  1997. if (!upb_inttable_init(r->ref2s, UPB_CTYPE_PTR)) goto err2;
  1998. return true;
  1999. err2:
  2000. upb_inttable_uninit(r->refs);
  2001. err1:
  2002. free(r->refs);
  2003. free(r->ref2s);
  2004. return false;
  2005. }
  2006. static void trackfree(const upb_refcounted *r) {
  2007. upb_inttable_uninit(r->refs);
  2008. upb_inttable_uninit(r->ref2s);
  2009. free(r->refs);
  2010. free(r->ref2s);
  2011. }
  2012. #else
  2013. static void track(const upb_refcounted *r, const void *owner, bool ref2) {
  2014. UPB_UNUSED(r);
  2015. UPB_UNUSED(owner);
  2016. UPB_UNUSED(ref2);
  2017. }
  2018. static void untrack(const upb_refcounted *r, const void *owner, bool ref2) {
  2019. UPB_UNUSED(r);
  2020. UPB_UNUSED(owner);
  2021. UPB_UNUSED(ref2);
  2022. }
  2023. static void checkref(const upb_refcounted *r, const void *owner, bool ref2) {
  2024. UPB_UNUSED(r);
  2025. UPB_UNUSED(owner);
  2026. UPB_UNUSED(ref2);
  2027. }
  2028. static bool trackinit(upb_refcounted *r) {
  2029. UPB_UNUSED(r);
  2030. return true;
  2031. }
  2032. static void trackfree(const upb_refcounted *r) {
  2033. UPB_UNUSED(r);
  2034. }
  2035. static void visit(const upb_refcounted *r, upb_refcounted_visit *v,
  2036. void *closure) {
  2037. if (r->vtbl->visit) r->vtbl->visit(r, v, closure);
  2038. }
  2039. #endif // UPB_DEBUG_REFS
  2040. /* freeze() *******************************************************************/
  2041. // The freeze() operation is by far the most complicated part of this scheme.
  2042. // We compute strongly-connected components and then mutate the graph such that
  2043. // we preserve the invariants documented at the top of this file. And we must
  2044. // handle out-of-memory errors gracefully (without leaving the graph
  2045. // inconsistent), which adds to the fun.
  2046. // The state used by the freeze operation (shared across many functions).
  2047. typedef struct {
  2048. int depth;
  2049. int maxdepth;
  2050. uint64_t index;
  2051. // Maps upb_refcounted* -> attributes (color, etc). attr layout varies by
  2052. // color.
  2053. upb_inttable objattr;
  2054. upb_inttable stack; // stack of upb_refcounted* for Tarjan's algorithm.
  2055. upb_inttable groups; // array of uint32_t*, malloc'd refcounts for new groups
  2056. upb_status *status;
  2057. jmp_buf err;
  2058. } tarjan;
  2059. static void release_ref2(const upb_refcounted *obj,
  2060. const upb_refcounted *subobj,
  2061. void *closure);
  2062. // Node attributes /////////////////////////////////////////////////////////////
  2063. // After our analysis phase all nodes will be either GRAY or WHITE.
  2064. typedef enum {
  2065. BLACK = 0, // Object has not been seen.
  2066. GRAY, // Object has been found via a refgroup but may not be reachable.
  2067. GREEN, // Object is reachable and is currently on the Tarjan stack.
  2068. WHITE, // Object is reachable and has been assigned a group (SCC).
  2069. } color_t;
  2070. UPB_NORETURN static void err(tarjan *t) { longjmp(t->err, 1); }
  2071. UPB_NORETURN static void oom(tarjan *t) {
  2072. upb_status_seterrmsg(t->status, "out of memory");
  2073. err(t);
  2074. }
  2075. static uint64_t trygetattr(const tarjan *t, const upb_refcounted *r) {
  2076. upb_value v;
  2077. return upb_inttable_lookupptr(&t->objattr, r, &v) ?
  2078. upb_value_getuint64(v) : 0;
  2079. }
  2080. static uint64_t getattr(const tarjan *t, const upb_refcounted *r) {
  2081. upb_value v;
  2082. bool found = upb_inttable_lookupptr(&t->objattr, r, &v);
  2083. UPB_ASSERT_VAR(found, found);
  2084. return upb_value_getuint64(v);
  2085. }
  2086. static void setattr(tarjan *t, const upb_refcounted *r, uint64_t attr) {
  2087. upb_inttable_removeptr(&t->objattr, r, NULL);
  2088. upb_inttable_insertptr(&t->objattr, r, upb_value_uint64(attr));
  2089. }
  2090. static color_t color(tarjan *t, const upb_refcounted *r) {
  2091. return trygetattr(t, r) & 0x3; // Color is always stored in the low 2 bits.
  2092. }
  2093. static void set_gray(tarjan *t, const upb_refcounted *r) {
  2094. assert(color(t, r) == BLACK);
  2095. setattr(t, r, GRAY);
  2096. }
  2097. // Pushes an obj onto the Tarjan stack and sets it to GREEN.
  2098. static void push(tarjan *t, const upb_refcounted *r) {
  2099. assert(color(t, r) == BLACK || color(t, r) == GRAY);
  2100. // This defines the attr layout for the GREEN state. "index" and "lowlink"
  2101. // get 31 bits, which is plenty (limit of 2B objects frozen at a time).
  2102. setattr(t, r, GREEN | (t->index << 2) | (t->index << 33));
  2103. if (++t->index == 0x80000000) {
  2104. upb_status_seterrmsg(t->status, "too many objects to freeze");
  2105. err(t);
  2106. }
  2107. upb_inttable_push(&t->stack, upb_value_ptr((void*)r));
  2108. }
  2109. // Pops an obj from the Tarjan stack and sets it to WHITE, with a ptr to its
  2110. // SCC group.
  2111. static upb_refcounted *pop(tarjan *t) {
  2112. upb_refcounted *r = upb_value_getptr(upb_inttable_pop(&t->stack));
  2113. assert(color(t, r) == GREEN);
  2114. // This defines the attr layout for nodes in the WHITE state.
  2115. // Top of group stack is [group, NULL]; we point at group.
  2116. setattr(t, r, WHITE | (upb_inttable_count(&t->groups) - 2) << 8);
  2117. return r;
  2118. }
  2119. static void tarjan_newgroup(tarjan *t) {
  2120. uint32_t *group = malloc(sizeof(*group));
  2121. if (!group) oom(t);
  2122. // Push group and empty group leader (we'll fill in leader later).
  2123. if (!upb_inttable_push(&t->groups, upb_value_ptr(group)) ||
  2124. !upb_inttable_push(&t->groups, upb_value_ptr(NULL))) {
  2125. free(group);
  2126. oom(t);
  2127. }
  2128. *group = 0;
  2129. }
  2130. static uint32_t idx(tarjan *t, const upb_refcounted *r) {
  2131. assert(color(t, r) == GREEN);
  2132. return (getattr(t, r) >> 2) & 0x7FFFFFFF;
  2133. }
  2134. static uint32_t lowlink(tarjan *t, const upb_refcounted *r) {
  2135. if (color(t, r) == GREEN) {
  2136. return getattr(t, r) >> 33;
  2137. } else {
  2138. return UINT32_MAX;
  2139. }
  2140. }
  2141. static void set_lowlink(tarjan *t, const upb_refcounted *r, uint32_t lowlink) {
  2142. assert(color(t, r) == GREEN);
  2143. setattr(t, r, ((uint64_t)lowlink << 33) | (getattr(t, r) & 0x1FFFFFFFF));
  2144. }
  2145. static uint32_t *group(tarjan *t, upb_refcounted *r) {
  2146. assert(color(t, r) == WHITE);
  2147. uint64_t groupnum = getattr(t, r) >> 8;
  2148. upb_value v;
  2149. bool found = upb_inttable_lookup(&t->groups, groupnum, &v);
  2150. UPB_ASSERT_VAR(found, found);
  2151. return upb_value_getptr(v);
  2152. }
  2153. // If the group leader for this object's group has not previously been set,
  2154. // the given object is assigned to be its leader.
  2155. static upb_refcounted *groupleader(tarjan *t, upb_refcounted *r) {
  2156. assert(color(t, r) == WHITE);
  2157. uint64_t leader_slot = (getattr(t, r) >> 8) + 1;
  2158. upb_value v;
  2159. bool found = upb_inttable_lookup(&t->groups, leader_slot, &v);
  2160. UPB_ASSERT_VAR(found, found);
  2161. if (upb_value_getptr(v)) {
  2162. return upb_value_getptr(v);
  2163. } else {
  2164. upb_inttable_remove(&t->groups, leader_slot, NULL);
  2165. upb_inttable_insert(&t->groups, leader_slot, upb_value_ptr(r));
  2166. return r;
  2167. }
  2168. }
  2169. // Tarjan's algorithm //////////////////////////////////////////////////////////
  2170. // See:
  2171. // http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
  2172. static void do_tarjan(const upb_refcounted *obj, tarjan *t);
  2173. static void tarjan_visit(const upb_refcounted *obj,
  2174. const upb_refcounted *subobj,
  2175. void *closure) {
  2176. tarjan *t = closure;
  2177. if (++t->depth > t->maxdepth) {
  2178. upb_status_seterrf(t->status, "graph too deep to freeze (%d)", t->maxdepth);
  2179. err(t);
  2180. } else if (subobj->is_frozen || color(t, subobj) == WHITE) {
  2181. // Do nothing: we don't want to visit or color already-frozen nodes,
  2182. // and WHITE nodes have already been assigned a SCC.
  2183. } else if (color(t, subobj) < GREEN) {
  2184. // Subdef has not yet been visited; recurse on it.
  2185. do_tarjan(subobj, t);
  2186. set_lowlink(t, obj, UPB_MIN(lowlink(t, obj), lowlink(t, subobj)));
  2187. } else if (color(t, subobj) == GREEN) {
  2188. // Subdef is in the stack and hence in the current SCC.
  2189. set_lowlink(t, obj, UPB_MIN(lowlink(t, obj), idx(t, subobj)));
  2190. }
  2191. --t->depth;
  2192. }
  2193. static void do_tarjan(const upb_refcounted *obj, tarjan *t) {
  2194. if (color(t, obj) == BLACK) {
  2195. // We haven't seen this object's group; mark the whole group GRAY.
  2196. const upb_refcounted *o = obj;
  2197. do { set_gray(t, o); } while ((o = o->next) != obj);
  2198. }
  2199. push(t, obj);
  2200. visit(obj, tarjan_visit, t);
  2201. if (lowlink(t, obj) == idx(t, obj)) {
  2202. tarjan_newgroup(t);
  2203. while (pop(t) != obj)
  2204. ;
  2205. }
  2206. }
  2207. // freeze() ////////////////////////////////////////////////////////////////////
  2208. static void crossref(const upb_refcounted *r, const upb_refcounted *subobj,
  2209. void *_t) {
  2210. tarjan *t = _t;
  2211. assert(color(t, r) > BLACK);
  2212. if (color(t, subobj) > BLACK && r->group != subobj->group) {
  2213. // Previously this ref was not reflected in subobj->group because they
  2214. // were in the same group; now that they are split a ref must be taken.
  2215. refgroup(subobj->group);
  2216. }
  2217. }
  2218. static bool freeze(upb_refcounted *const*roots, int n, upb_status *s,
  2219. int maxdepth) {
  2220. volatile bool ret = false;
  2221. // We run in two passes so that we can allocate all memory before performing
  2222. // any mutation of the input -- this allows us to leave the input unchanged
  2223. // in the case of memory allocation failure.
  2224. tarjan t;
  2225. t.index = 0;
  2226. t.depth = 0;
  2227. t.maxdepth = maxdepth;
  2228. t.status = s;
  2229. if (!upb_inttable_init(&t.objattr, UPB_CTYPE_UINT64)) goto err1;
  2230. if (!upb_inttable_init(&t.stack, UPB_CTYPE_PTR)) goto err2;
  2231. if (!upb_inttable_init(&t.groups, UPB_CTYPE_PTR)) goto err3;
  2232. if (setjmp(t.err) != 0) goto err4;
  2233. for (int i = 0; i < n; i++) {
  2234. if (color(&t, roots[i]) < GREEN) {
  2235. do_tarjan(roots[i], &t);
  2236. }
  2237. }
  2238. // If we've made it this far, no further errors are possible so it's safe to
  2239. // mutate the objects without risk of leaving them in an inconsistent state.
  2240. ret = true;
  2241. // The transformation that follows requires care. The preconditions are:
  2242. // - all objects in attr map are WHITE or GRAY, and are in mutable groups
  2243. // (groups of all mutable objs)
  2244. // - no ref2(to, from) refs have incremented count(to) if both "to" and
  2245. // "from" are in our attr map (this follows from invariants (2) and (3))
  2246. // Pass 1: we remove WHITE objects from their mutable groups, and add them to
  2247. // new groups according to the SCC's we computed. These new groups will
  2248. // consist of only frozen objects. None will be immediately collectible,
  2249. // because WHITE objects are by definition reachable from one of "roots",
  2250. // which the caller must own refs on.
  2251. upb_inttable_iter i;
  2252. upb_inttable_begin(&i, &t.objattr);
  2253. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  2254. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&i);
  2255. // Since removal from a singly-linked list requires access to the object's
  2256. // predecessor, we consider obj->next instead of obj for moving. With the
  2257. // while() loop we guarantee that we will visit every node's predecessor.
  2258. // Proof:
  2259. // 1. every node's predecessor is in our attr map.
  2260. // 2. though the loop body may change a node's predecessor, it will only
  2261. // change it to be the node we are currently operating on, so with a
  2262. // while() loop we guarantee ourselves the chance to remove each node.
  2263. while (color(&t, obj->next) == WHITE &&
  2264. group(&t, obj->next) != obj->next->group) {
  2265. // Remove from old group.
  2266. upb_refcounted *move = obj->next;
  2267. if (obj == move) {
  2268. // Removing the last object from a group.
  2269. assert(*obj->group == obj->individual_count);
  2270. free(obj->group);
  2271. } else {
  2272. obj->next = move->next;
  2273. // This may decrease to zero; we'll collect GRAY objects (if any) that
  2274. // remain in the group in the third pass.
  2275. assert(*move->group >= move->individual_count);
  2276. *move->group -= move->individual_count;
  2277. }
  2278. // Add to new group.
  2279. upb_refcounted *leader = groupleader(&t, move);
  2280. if (move == leader) {
  2281. // First object added to new group is its leader.
  2282. move->group = group(&t, move);
  2283. move->next = move;
  2284. *move->group = move->individual_count;
  2285. } else {
  2286. // Group already has at least one object in it.
  2287. assert(leader->group == group(&t, move));
  2288. move->group = group(&t, move);
  2289. move->next = leader->next;
  2290. leader->next = move;
  2291. *move->group += move->individual_count;
  2292. }
  2293. move->is_frozen = true;
  2294. }
  2295. }
  2296. // Pass 2: GRAY and WHITE objects "obj" with ref2(to, obj) references must
  2297. // increment count(to) if group(obj) != group(to) (which could now be the
  2298. // case if "to" was just frozen).
  2299. upb_inttable_begin(&i, &t.objattr);
  2300. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  2301. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&i);
  2302. visit(obj, crossref, &t);
  2303. }
  2304. // Pass 3: GRAY objects are collected if their group's refcount dropped to
  2305. // zero when we removed its white nodes. This can happen if they had only
  2306. // been kept alive by virtue of sharing a group with an object that was just
  2307. // frozen.
  2308. //
  2309. // It is important that we do this last, since the GRAY object's free()
  2310. // function could call unref2() on just-frozen objects, which will decrement
  2311. // refs that were added in pass 2.
  2312. upb_inttable_begin(&i, &t.objattr);
  2313. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  2314. upb_refcounted *obj = (upb_refcounted*)upb_inttable_iter_key(&i);
  2315. if (obj->group == NULL || *obj->group == 0) {
  2316. if (obj->group) {
  2317. // We eagerly free() the group's count (since we can't easily determine
  2318. // the group's remaining size it's the easiest way to ensure it gets
  2319. // done).
  2320. free(obj->group);
  2321. // Visit to release ref2's (done in a separate pass since release_ref2
  2322. // depends on o->group being unmodified so it can test merged()).
  2323. upb_refcounted *o = obj;
  2324. do { visit(o, release_ref2, NULL); } while ((o = o->next) != obj);
  2325. // Mark "group" fields as NULL so we know to free the objects later in
  2326. // this loop, but also don't try to delete the group twice.
  2327. o = obj;
  2328. do { o->group = NULL; } while ((o = o->next) != obj);
  2329. }
  2330. freeobj(obj);
  2331. }
  2332. }
  2333. err4:
  2334. if (!ret) {
  2335. upb_inttable_begin(&i, &t.groups);
  2336. for(; !upb_inttable_done(&i); upb_inttable_next(&i))
  2337. free(upb_value_getptr(upb_inttable_iter_value(&i)));
  2338. }
  2339. upb_inttable_uninit(&t.groups);
  2340. err3:
  2341. upb_inttable_uninit(&t.stack);
  2342. err2:
  2343. upb_inttable_uninit(&t.objattr);
  2344. err1:
  2345. return ret;
  2346. }
  2347. /* Misc internal functions ***************************************************/
  2348. static bool merged(const upb_refcounted *r, const upb_refcounted *r2) {
  2349. return r->group == r2->group;
  2350. }
  2351. static void merge(upb_refcounted *r, upb_refcounted *from) {
  2352. if (merged(r, from)) return;
  2353. *r->group += *from->group;
  2354. free(from->group);
  2355. upb_refcounted *base = from;
  2356. // Set all refcount pointers in the "from" chain to the merged refcount.
  2357. //
  2358. // TODO(haberman): this linear algorithm can result in an overall O(n^2) bound
  2359. // if the user continuously extends a group by one object. Prevent this by
  2360. // using one of the techniques in this paper:
  2361. // ftp://www.ncedc.org/outgoing/geomorph/dino/orals/p245-tarjan.pdf
  2362. do { from->group = r->group; } while ((from = from->next) != base);
  2363. // Merge the two circularly linked lists by swapping their next pointers.
  2364. upb_refcounted *tmp = r->next;
  2365. r->next = base->next;
  2366. base->next = tmp;
  2367. }
  2368. static void unref(const upb_refcounted *r);
  2369. static void release_ref2(const upb_refcounted *obj,
  2370. const upb_refcounted *subobj,
  2371. void *closure) {
  2372. UPB_UNUSED(closure);
  2373. untrack(subobj, obj, true);
  2374. if (!merged(obj, subobj)) {
  2375. assert(subobj->is_frozen);
  2376. unref(subobj);
  2377. }
  2378. }
  2379. static void unref(const upb_refcounted *r) {
  2380. if (unrefgroup(r->group)) {
  2381. free(r->group);
  2382. // In two passes, since release_ref2 needs a guarantee that any subobjs
  2383. // are alive.
  2384. const upb_refcounted *o = r;
  2385. do { visit(o, release_ref2, NULL); } while((o = o->next) != r);
  2386. o = r;
  2387. do {
  2388. const upb_refcounted *next = o->next;
  2389. assert(o->is_frozen || o->individual_count == 0);
  2390. freeobj((upb_refcounted*)o);
  2391. o = next;
  2392. } while(o != r);
  2393. }
  2394. }
  2395. static void freeobj(upb_refcounted *o) {
  2396. trackfree(o);
  2397. o->vtbl->free((upb_refcounted*)o);
  2398. }
  2399. /* Public interface ***********************************************************/
  2400. bool upb_refcounted_init(upb_refcounted *r,
  2401. const struct upb_refcounted_vtbl *vtbl,
  2402. const void *owner) {
  2403. r->next = r;
  2404. r->vtbl = vtbl;
  2405. r->individual_count = 0;
  2406. r->is_frozen = false;
  2407. r->group = malloc(sizeof(*r->group));
  2408. if (!r->group) return false;
  2409. *r->group = 0;
  2410. if (!trackinit(r)) {
  2411. free(r->group);
  2412. return false;
  2413. }
  2414. upb_refcounted_ref(r, owner);
  2415. return true;
  2416. }
  2417. bool upb_refcounted_isfrozen(const upb_refcounted *r) {
  2418. return r->is_frozen;
  2419. }
  2420. void upb_refcounted_ref(const upb_refcounted *r, const void *owner) {
  2421. track(r, owner, false);
  2422. if (!r->is_frozen)
  2423. ((upb_refcounted*)r)->individual_count++;
  2424. refgroup(r->group);
  2425. }
  2426. void upb_refcounted_unref(const upb_refcounted *r, const void *owner) {
  2427. untrack(r, owner, false);
  2428. if (!r->is_frozen)
  2429. ((upb_refcounted*)r)->individual_count--;
  2430. unref(r);
  2431. }
  2432. void upb_refcounted_ref2(const upb_refcounted *r, upb_refcounted *from) {
  2433. assert(!from->is_frozen); // Non-const pointer implies this.
  2434. track(r, from, true);
  2435. if (r->is_frozen) {
  2436. refgroup(r->group);
  2437. } else {
  2438. merge((upb_refcounted*)r, from);
  2439. }
  2440. }
  2441. void upb_refcounted_unref2(const upb_refcounted *r, upb_refcounted *from) {
  2442. assert(!from->is_frozen); // Non-const pointer implies this.
  2443. untrack(r, from, true);
  2444. if (r->is_frozen) {
  2445. unref(r);
  2446. } else {
  2447. assert(merged(r, from));
  2448. }
  2449. }
  2450. void upb_refcounted_donateref(
  2451. const upb_refcounted *r, const void *from, const void *to) {
  2452. assert(from != to);
  2453. if (to != NULL)
  2454. upb_refcounted_ref(r, to);
  2455. if (from != NULL)
  2456. upb_refcounted_unref(r, from);
  2457. }
  2458. void upb_refcounted_checkref(const upb_refcounted *r, const void *owner) {
  2459. checkref(r, owner, false);
  2460. }
  2461. bool upb_refcounted_freeze(upb_refcounted *const*roots, int n, upb_status *s,
  2462. int maxdepth) {
  2463. for (int i = 0; i < n; i++) {
  2464. assert(!roots[i]->is_frozen);
  2465. }
  2466. return freeze(roots, n, s, maxdepth);
  2467. }
  2468. /*
  2469. * upb - a minimalist implementation of protocol buffers.
  2470. *
  2471. * Copyright (c) 2013 Google Inc. See LICENSE for details.
  2472. * Author: Josh Haberman <jhaberman@gmail.com>
  2473. */
  2474. #include <stdlib.h>
  2475. // Fallback implementation if the shim is not specialized by the JIT.
  2476. #define SHIM_WRITER(type, ctype) \
  2477. bool upb_shim_set ## type (void *c, const void *hd, ctype val) { \
  2478. uint8_t *m = c; \
  2479. const upb_shim_data *d = hd; \
  2480. if (d->hasbit > 0) \
  2481. *(uint8_t*)&m[d->hasbit / 8] |= 1 << (d->hasbit % 8); \
  2482. *(ctype*)&m[d->offset] = val; \
  2483. return true; \
  2484. } \
  2485. SHIM_WRITER(double, double)
  2486. SHIM_WRITER(float, float)
  2487. SHIM_WRITER(int32, int32_t)
  2488. SHIM_WRITER(int64, int64_t)
  2489. SHIM_WRITER(uint32, uint32_t)
  2490. SHIM_WRITER(uint64, uint64_t)
  2491. SHIM_WRITER(bool, bool)
  2492. #undef SHIM_WRITER
  2493. bool upb_shim_set(upb_handlers *h, const upb_fielddef *f, size_t offset,
  2494. int32_t hasbit) {
  2495. upb_shim_data *d = malloc(sizeof(*d));
  2496. if (!d) return false;
  2497. d->offset = offset;
  2498. d->hasbit = hasbit;
  2499. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  2500. upb_handlerattr_sethandlerdata(&attr, d);
  2501. upb_handlerattr_setalwaysok(&attr, true);
  2502. upb_handlers_addcleanup(h, d, free);
  2503. #define TYPE(u, l) \
  2504. case UPB_TYPE_##u: \
  2505. ok = upb_handlers_set##l(h, f, upb_shim_set##l, &attr); break;
  2506. bool ok = false;
  2507. switch (upb_fielddef_type(f)) {
  2508. TYPE(INT64, int64);
  2509. TYPE(INT32, int32);
  2510. TYPE(ENUM, int32);
  2511. TYPE(UINT64, uint64);
  2512. TYPE(UINT32, uint32);
  2513. TYPE(DOUBLE, double);
  2514. TYPE(FLOAT, float);
  2515. TYPE(BOOL, bool);
  2516. default: assert(false); break;
  2517. }
  2518. #undef TYPE
  2519. upb_handlerattr_uninit(&attr);
  2520. return ok;
  2521. }
  2522. const upb_shim_data *upb_shim_getdata(const upb_handlers *h, upb_selector_t s,
  2523. upb_fieldtype_t *type) {
  2524. upb_func *f = upb_handlers_gethandler(h, s);
  2525. if ((upb_int64_handlerfunc*)f == upb_shim_setint64) {
  2526. *type = UPB_TYPE_INT64;
  2527. } else if ((upb_int32_handlerfunc*)f == upb_shim_setint32) {
  2528. *type = UPB_TYPE_INT32;
  2529. } else if ((upb_uint64_handlerfunc*)f == upb_shim_setuint64) {
  2530. *type = UPB_TYPE_UINT64;
  2531. } else if ((upb_uint32_handlerfunc*)f == upb_shim_setuint32) {
  2532. *type = UPB_TYPE_UINT32;
  2533. } else if ((upb_double_handlerfunc*)f == upb_shim_setdouble) {
  2534. *type = UPB_TYPE_DOUBLE;
  2535. } else if ((upb_float_handlerfunc*)f == upb_shim_setfloat) {
  2536. *type = UPB_TYPE_FLOAT;
  2537. } else if ((upb_bool_handlerfunc*)f == upb_shim_setbool) {
  2538. *type = UPB_TYPE_BOOL;
  2539. } else {
  2540. return NULL;
  2541. }
  2542. return (const upb_shim_data*)upb_handlers_gethandlerdata(h, s);
  2543. }
  2544. /*
  2545. * upb - a minimalist implementation of protocol buffers.
  2546. *
  2547. * Copyright (c) 2008-2012 Google Inc. See LICENSE for details.
  2548. * Author: Josh Haberman <jhaberman@gmail.com>
  2549. */
  2550. #include <stdlib.h>
  2551. #include <string.h>
  2552. bool upb_symtab_isfrozen(const upb_symtab *s) {
  2553. return upb_refcounted_isfrozen(UPB_UPCAST(s));
  2554. }
  2555. void upb_symtab_ref(const upb_symtab *s, const void *owner) {
  2556. upb_refcounted_ref(UPB_UPCAST(s), owner);
  2557. }
  2558. void upb_symtab_unref(const upb_symtab *s, const void *owner) {
  2559. upb_refcounted_unref(UPB_UPCAST(s), owner);
  2560. }
  2561. void upb_symtab_donateref(
  2562. const upb_symtab *s, const void *from, const void *to) {
  2563. upb_refcounted_donateref(UPB_UPCAST(s), from, to);
  2564. }
  2565. void upb_symtab_checkref(const upb_symtab *s, const void *owner) {
  2566. upb_refcounted_checkref(UPB_UPCAST(s), owner);
  2567. }
  2568. static void upb_symtab_free(upb_refcounted *r) {
  2569. upb_symtab *s = (upb_symtab*)r;
  2570. upb_strtable_iter i;
  2571. upb_strtable_begin(&i, &s->symtab);
  2572. for (; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  2573. const upb_def *def = upb_value_getptr(upb_strtable_iter_value(&i));
  2574. upb_def_unref(def, s);
  2575. }
  2576. upb_strtable_uninit(&s->symtab);
  2577. free(s);
  2578. }
  2579. upb_symtab *upb_symtab_new(const void *owner) {
  2580. static const struct upb_refcounted_vtbl vtbl = {NULL, &upb_symtab_free};
  2581. upb_symtab *s = malloc(sizeof(*s));
  2582. upb_refcounted_init(UPB_UPCAST(s), &vtbl, owner);
  2583. upb_strtable_init(&s->symtab, UPB_CTYPE_PTR);
  2584. return s;
  2585. }
  2586. void upb_symtab_freeze(upb_symtab *s) {
  2587. assert(!upb_symtab_isfrozen(s));
  2588. upb_refcounted *r = UPB_UPCAST(s);
  2589. // The symtab does not take ref2's (see refcounted.h) on the defs, because
  2590. // defs cannot refer back to the table and therefore cannot create cycles. So
  2591. // 0 will suffice for maxdepth here.
  2592. bool ok = upb_refcounted_freeze(&r, 1, NULL, 0);
  2593. UPB_ASSERT_VAR(ok, ok);
  2594. }
  2595. const upb_def *upb_symtab_lookup(const upb_symtab *s, const char *sym) {
  2596. upb_value v;
  2597. upb_def *ret = upb_strtable_lookup(&s->symtab, sym, &v) ?
  2598. upb_value_getptr(v) : NULL;
  2599. return ret;
  2600. }
  2601. const upb_msgdef *upb_symtab_lookupmsg(const upb_symtab *s, const char *sym) {
  2602. upb_value v;
  2603. upb_def *def = upb_strtable_lookup(&s->symtab, sym, &v) ?
  2604. upb_value_getptr(v) : NULL;
  2605. return def ? upb_dyncast_msgdef(def) : NULL;
  2606. }
  2607. const upb_enumdef *upb_symtab_lookupenum(const upb_symtab *s, const char *sym) {
  2608. upb_value v;
  2609. upb_def *def = upb_strtable_lookup(&s->symtab, sym, &v) ?
  2610. upb_value_getptr(v) : NULL;
  2611. return def ? upb_dyncast_enumdef(def) : NULL;
  2612. }
  2613. // Given a symbol and the base symbol inside which it is defined, find the
  2614. // symbol's definition in t.
  2615. static upb_def *upb_resolvename(const upb_strtable *t,
  2616. const char *base, const char *sym) {
  2617. if(strlen(sym) == 0) return NULL;
  2618. if(sym[0] == '.') {
  2619. // Symbols starting with '.' are absolute, so we do a single lookup.
  2620. // Slice to omit the leading '.'
  2621. upb_value v;
  2622. return upb_strtable_lookup(t, sym + 1, &v) ? upb_value_getptr(v) : NULL;
  2623. } else {
  2624. // Remove components from base until we find an entry or run out.
  2625. // TODO: This branch is totally broken, but currently not used.
  2626. (void)base;
  2627. assert(false);
  2628. return NULL;
  2629. }
  2630. }
  2631. const upb_def *upb_symtab_resolve(const upb_symtab *s, const char *base,
  2632. const char *sym) {
  2633. upb_def *ret = upb_resolvename(&s->symtab, base, sym);
  2634. return ret;
  2635. }
  2636. // Searches def and its children to find defs that have the same name as any
  2637. // def in "addtab." Returns true if any where found, and as a side-effect adds
  2638. // duplicates of these defs into addtab.
  2639. //
  2640. // We use a modified depth-first traversal that traverses each SCC (which we
  2641. // already computed) as if it were a single node. This allows us to traverse
  2642. // the possibly-cyclic graph as if it were a DAG and to dup the correct set of
  2643. // nodes with O(n) time.
  2644. static bool upb_resolve_dfs(const upb_def *def, upb_strtable *addtab,
  2645. const void *new_owner, upb_inttable *seen,
  2646. upb_status *s) {
  2647. // Memoize results of this function for efficiency (since we're traversing a
  2648. // DAG this is not needed to limit the depth of the search).
  2649. upb_value v;
  2650. if (upb_inttable_lookup(seen, (uintptr_t)def, &v))
  2651. return upb_value_getbool(v);
  2652. // Visit submessages for all messages in the SCC.
  2653. bool need_dup = false;
  2654. const upb_def *base = def;
  2655. do {
  2656. assert(upb_def_isfrozen(def));
  2657. if (def->type == UPB_DEF_FIELD) continue;
  2658. upb_value v;
  2659. if (upb_strtable_lookup(addtab, upb_def_fullname(def), &v)) {
  2660. need_dup = true;
  2661. }
  2662. // For messages, continue the recursion by visiting all subdefs.
  2663. const upb_msgdef *m = upb_dyncast_msgdef(def);
  2664. if (m) {
  2665. upb_msg_iter i;
  2666. for(upb_msg_begin(&i, m); !upb_msg_done(&i); upb_msg_next(&i)) {
  2667. upb_fielddef *f = upb_msg_iter_field(&i);
  2668. if (!upb_fielddef_hassubdef(f)) continue;
  2669. // |= to avoid short-circuit; we need its side-effects.
  2670. need_dup |= upb_resolve_dfs(
  2671. upb_fielddef_subdef(f), addtab, new_owner, seen, s);
  2672. if (!upb_ok(s)) return false;
  2673. }
  2674. }
  2675. } while ((def = (upb_def*)def->base.next) != base);
  2676. if (need_dup) {
  2677. // Dup any defs that don't already have entries in addtab.
  2678. def = base;
  2679. do {
  2680. if (def->type == UPB_DEF_FIELD) continue;
  2681. const char *name = upb_def_fullname(def);
  2682. if (!upb_strtable_lookup(addtab, name, NULL)) {
  2683. upb_def *newdef = upb_def_dup(def, new_owner);
  2684. if (!newdef) goto oom;
  2685. newdef->came_from_user = false;
  2686. if (!upb_strtable_insert(addtab, name, upb_value_ptr(newdef)))
  2687. goto oom;
  2688. }
  2689. } while ((def = (upb_def*)def->base.next) != base);
  2690. }
  2691. upb_inttable_insert(seen, (uintptr_t)def, upb_value_bool(need_dup));
  2692. return need_dup;
  2693. oom:
  2694. upb_status_seterrmsg(s, "out of memory");
  2695. return false;
  2696. }
  2697. // TODO(haberman): we need a lot more testing of error conditions.
  2698. // The came_from_user stuff in particular is not tested.
  2699. bool upb_symtab_add(upb_symtab *s, upb_def *const*defs, int n, void *ref_donor,
  2700. upb_status *status) {
  2701. assert(!upb_symtab_isfrozen(s));
  2702. upb_def **add_defs = NULL;
  2703. upb_strtable addtab;
  2704. if (!upb_strtable_init(&addtab, UPB_CTYPE_PTR)) {
  2705. upb_status_seterrmsg(status, "out of memory");
  2706. return false;
  2707. }
  2708. // Add new defs to our "add" set.
  2709. for (int i = 0; i < n; i++) {
  2710. upb_def *def = defs[i];
  2711. if (upb_def_isfrozen(def)) {
  2712. upb_status_seterrmsg(status, "added defs must be mutable");
  2713. goto err;
  2714. }
  2715. assert(!upb_def_isfrozen(def));
  2716. const char *fullname = upb_def_fullname(def);
  2717. if (!fullname) {
  2718. upb_status_seterrmsg(
  2719. status, "Anonymous defs cannot be added to a symtab");
  2720. goto err;
  2721. }
  2722. upb_fielddef *f = upb_dyncast_fielddef_mutable(def);
  2723. if (f) {
  2724. if (!upb_fielddef_containingtypename(f)) {
  2725. upb_status_seterrmsg(status,
  2726. "Standalone fielddefs must have a containing type "
  2727. "(extendee) name set");
  2728. goto err;
  2729. }
  2730. } else {
  2731. if (upb_strtable_lookup(&addtab, fullname, NULL)) {
  2732. upb_status_seterrf(status, "Conflicting defs named '%s'", fullname);
  2733. goto err;
  2734. }
  2735. // We need this to back out properly, because if there is a failure we
  2736. // need to donate the ref back to the caller.
  2737. def->came_from_user = true;
  2738. upb_def_donateref(def, ref_donor, s);
  2739. if (!upb_strtable_insert(&addtab, fullname, upb_value_ptr(def)))
  2740. goto oom_err;
  2741. }
  2742. }
  2743. // Add standalone fielddefs (ie. extensions) to the appropriate messages.
  2744. // If the appropriate message only exists in the existing symtab, duplicate
  2745. // it so we have a mutable copy we can add the fields to.
  2746. for (int i = 0; i < n; i++) {
  2747. upb_def *def = defs[i];
  2748. upb_fielddef *f = upb_dyncast_fielddef_mutable(def);
  2749. if (!f) continue;
  2750. const char *msgname = upb_fielddef_containingtypename(f);
  2751. // We validated this earlier in this function.
  2752. assert(msgname);
  2753. // If the extendee name is absolutely qualified, move past the initial ".".
  2754. // TODO(haberman): it is not obvious what it would mean if this was not
  2755. // absolutely qualified.
  2756. if (msgname[0] == '.') {
  2757. msgname++;
  2758. }
  2759. upb_value v;
  2760. upb_msgdef *m;
  2761. if (upb_strtable_lookup(&addtab, msgname, &v)) {
  2762. // Extendee is in the set of defs the user asked us to add.
  2763. m = upb_value_getptr(v);
  2764. } else {
  2765. // Need to find and dup the extendee from the existing symtab.
  2766. const upb_msgdef *frozen_m = upb_symtab_lookupmsg(s, msgname);
  2767. if (!frozen_m) {
  2768. upb_status_seterrf(status,
  2769. "Tried to extend message %s that does not exist "
  2770. "in this SymbolTable.",
  2771. msgname);
  2772. goto err;
  2773. }
  2774. m = upb_msgdef_dup(frozen_m, s);
  2775. if (!m) goto oom_err;
  2776. if (!upb_strtable_insert(&addtab, msgname, upb_value_ptr(m))) {
  2777. upb_msgdef_unref(m, s);
  2778. goto oom_err;
  2779. }
  2780. }
  2781. if (!upb_msgdef_addfield(m, f, ref_donor, status)) {
  2782. goto err;
  2783. }
  2784. }
  2785. // Add dups of any existing def that can reach a def with the same name as
  2786. // anything in our "add" set.
  2787. upb_inttable seen;
  2788. if (!upb_inttable_init(&seen, UPB_CTYPE_BOOL)) goto oom_err;
  2789. upb_strtable_iter i;
  2790. upb_strtable_begin(&i, &s->symtab);
  2791. for (; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  2792. upb_def *def = upb_value_getptr(upb_strtable_iter_value(&i));
  2793. upb_resolve_dfs(def, &addtab, s, &seen, status);
  2794. if (!upb_ok(status)) goto err;
  2795. }
  2796. upb_inttable_uninit(&seen);
  2797. // Now using the table, resolve symbolic references for subdefs.
  2798. upb_strtable_begin(&i, &addtab);
  2799. for (; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  2800. upb_def *def = upb_value_getptr(upb_strtable_iter_value(&i));
  2801. upb_msgdef *m = upb_dyncast_msgdef_mutable(def);
  2802. if (!m) continue;
  2803. // Type names are resolved relative to the message in which they appear.
  2804. const char *base = upb_msgdef_fullname(m);
  2805. upb_msg_iter j;
  2806. for(upb_msg_begin(&j, m); !upb_msg_done(&j); upb_msg_next(&j)) {
  2807. upb_fielddef *f = upb_msg_iter_field(&j);
  2808. const char *name = upb_fielddef_subdefname(f);
  2809. if (name && !upb_fielddef_subdef(f)) {
  2810. // Try the lookup in the current set of to-be-added defs first. If not
  2811. // there, try existing defs.
  2812. upb_def *subdef = upb_resolvename(&addtab, base, name);
  2813. if (subdef == NULL) {
  2814. subdef = upb_resolvename(&s->symtab, base, name);
  2815. }
  2816. if (subdef == NULL) {
  2817. upb_status_seterrf(
  2818. status, "couldn't resolve name '%s' in message '%s'", name, base);
  2819. goto err;
  2820. } else if (!upb_fielddef_setsubdef(f, subdef, status)) {
  2821. goto err;
  2822. }
  2823. }
  2824. }
  2825. }
  2826. // We need an array of the defs in addtab, for passing to upb_def_freeze.
  2827. add_defs = malloc(sizeof(void*) * upb_strtable_count(&addtab));
  2828. if (add_defs == NULL) goto oom_err;
  2829. upb_strtable_begin(&i, &addtab);
  2830. for (n = 0; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  2831. add_defs[n++] = upb_value_getptr(upb_strtable_iter_value(&i));
  2832. }
  2833. if (!upb_def_freeze(add_defs, n, status)) goto err;
  2834. // This must be delayed until all errors have been detected, since error
  2835. // recovery code uses this table to cleanup defs.
  2836. upb_strtable_uninit(&addtab);
  2837. // TODO(haberman) we don't properly handle errors after this point (like
  2838. // OOM in upb_strtable_insert() below).
  2839. for (int i = 0; i < n; i++) {
  2840. upb_def *def = add_defs[i];
  2841. const char *name = upb_def_fullname(def);
  2842. upb_value v;
  2843. if (upb_strtable_remove(&s->symtab, name, &v)) {
  2844. const upb_def *def = upb_value_getptr(v);
  2845. upb_def_unref(def, s);
  2846. }
  2847. bool success = upb_strtable_insert(&s->symtab, name, upb_value_ptr(def));
  2848. UPB_ASSERT_VAR(success, success == true);
  2849. }
  2850. free(add_defs);
  2851. return true;
  2852. oom_err:
  2853. upb_status_seterrmsg(status, "out of memory");
  2854. err: {
  2855. // For defs the user passed in, we need to donate the refs back. For defs
  2856. // we dup'd, we need to just unref them.
  2857. upb_strtable_iter i;
  2858. upb_strtable_begin(&i, &addtab);
  2859. for (; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  2860. upb_def *def = upb_value_getptr(upb_strtable_iter_value(&i));
  2861. bool came_from_user = def->came_from_user;
  2862. def->came_from_user = false;
  2863. if (came_from_user) {
  2864. upb_def_donateref(def, s, ref_donor);
  2865. } else {
  2866. upb_def_unref(def, s);
  2867. }
  2868. }
  2869. }
  2870. upb_strtable_uninit(&addtab);
  2871. free(add_defs);
  2872. assert(!upb_ok(status));
  2873. return false;
  2874. }
  2875. // Iteration.
  2876. static void advance_to_matching(upb_symtab_iter *iter) {
  2877. if (iter->type == UPB_DEF_ANY)
  2878. return;
  2879. while (!upb_strtable_done(&iter->iter) &&
  2880. iter->type != upb_symtab_iter_def(iter)->type) {
  2881. upb_strtable_next(&iter->iter);
  2882. }
  2883. }
  2884. void upb_symtab_begin(upb_symtab_iter *iter, const upb_symtab *s,
  2885. upb_deftype_t type) {
  2886. upb_strtable_begin(&iter->iter, &s->symtab);
  2887. iter->type = type;
  2888. advance_to_matching(iter);
  2889. }
  2890. void upb_symtab_next(upb_symtab_iter *iter) {
  2891. upb_strtable_next(&iter->iter);
  2892. advance_to_matching(iter);
  2893. }
  2894. bool upb_symtab_done(const upb_symtab_iter *iter) {
  2895. return upb_strtable_done(&iter->iter);
  2896. }
  2897. const upb_def *upb_symtab_iter_def(const upb_symtab_iter *iter) {
  2898. return upb_value_getptr(upb_strtable_iter_value(&iter->iter));
  2899. }
  2900. /*
  2901. * upb - a minimalist implementation of protocol buffers.
  2902. *
  2903. * Copyright (c) 2009 Google Inc. See LICENSE for details.
  2904. * Author: Josh Haberman <jhaberman@gmail.com>
  2905. *
  2906. * Implementation is heavily inspired by Lua's ltable.c.
  2907. */
  2908. #include <stdlib.h>
  2909. #include <string.h>
  2910. #define UPB_MAXARRSIZE 16 // 64k.
  2911. // From Chromium.
  2912. #define ARRAY_SIZE(x) \
  2913. ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x])))))
  2914. static const double MAX_LOAD = 0.85;
  2915. // The minimum utilization of the array part of a mixed hash/array table. This
  2916. // is a speed/memory-usage tradeoff (though it's not straightforward because of
  2917. // cache effects). The lower this is, the more memory we'll use.
  2918. static const double MIN_DENSITY = 0.1;
  2919. bool is_pow2(uint64_t v) { return v == 0 || (v & (v - 1)) == 0; }
  2920. int log2ceil(uint64_t v) {
  2921. int ret = 0;
  2922. bool pow2 = is_pow2(v);
  2923. while (v >>= 1) ret++;
  2924. ret = pow2 ? ret : ret + 1; // Ceiling.
  2925. return UPB_MIN(UPB_MAXARRSIZE, ret);
  2926. }
  2927. char *upb_strdup(const char *s) {
  2928. return upb_strdup2(s, strlen(s));
  2929. }
  2930. char *upb_strdup2(const char *s, size_t len) {
  2931. // Always null-terminate, even if binary data; but don't rely on the input to
  2932. // have a null-terminating byte since it may be a raw binary buffer.
  2933. size_t n = len + 1;
  2934. char *p = malloc(n);
  2935. if (p) memcpy(p, s, len);
  2936. p[len] = 0;
  2937. return p;
  2938. }
  2939. // A type to represent the lookup key of either a strtable or an inttable.
  2940. typedef struct {
  2941. upb_tabkey key;
  2942. } lookupkey_t;
  2943. static lookupkey_t strkey2(const char *str, size_t len) {
  2944. lookupkey_t k;
  2945. k.key.s.str = (char*)str;
  2946. k.key.s.length = len;
  2947. return k;
  2948. }
  2949. static lookupkey_t intkey(uintptr_t key) {
  2950. lookupkey_t k;
  2951. k.key = upb_intkey(key);
  2952. return k;
  2953. }
  2954. typedef uint32_t hashfunc_t(upb_tabkey key);
  2955. typedef bool eqlfunc_t(upb_tabkey k1, lookupkey_t k2);
  2956. /* Base table (shared code) ***************************************************/
  2957. // For when we need to cast away const.
  2958. static upb_tabent *mutable_entries(upb_table *t) {
  2959. return (upb_tabent*)t->entries;
  2960. }
  2961. static bool isfull(upb_table *t) {
  2962. return (double)(t->count + 1) / upb_table_size(t) > MAX_LOAD;
  2963. }
  2964. static bool init(upb_table *t, upb_ctype_t ctype, uint8_t size_lg2) {
  2965. t->count = 0;
  2966. t->ctype = ctype;
  2967. t->size_lg2 = size_lg2;
  2968. t->mask = upb_table_size(t) ? upb_table_size(t) - 1 : 0;
  2969. size_t bytes = upb_table_size(t) * sizeof(upb_tabent);
  2970. if (bytes > 0) {
  2971. t->entries = malloc(bytes);
  2972. if (!t->entries) return false;
  2973. memset(mutable_entries(t), 0, bytes);
  2974. } else {
  2975. t->entries = NULL;
  2976. }
  2977. return true;
  2978. }
  2979. static void uninit(upb_table *t) { free(mutable_entries(t)); }
  2980. static upb_tabent *emptyent(upb_table *t) {
  2981. upb_tabent *e = mutable_entries(t) + upb_table_size(t);
  2982. while (1) { if (upb_tabent_isempty(--e)) return e; assert(e > t->entries); }
  2983. }
  2984. static upb_tabent *getentry_mutable(upb_table *t, uint32_t hash) {
  2985. return (upb_tabent*)upb_getentry(t, hash);
  2986. }
  2987. static const upb_tabent *findentry(const upb_table *t, lookupkey_t key,
  2988. uint32_t hash, eqlfunc_t *eql) {
  2989. if (t->size_lg2 == 0) return NULL;
  2990. const upb_tabent *e = upb_getentry(t, hash);
  2991. if (upb_tabent_isempty(e)) return NULL;
  2992. while (1) {
  2993. if (eql(e->key, key)) return e;
  2994. if ((e = e->next) == NULL) return NULL;
  2995. }
  2996. }
  2997. static upb_tabent *findentry_mutable(upb_table *t, lookupkey_t key,
  2998. uint32_t hash, eqlfunc_t *eql) {
  2999. return (upb_tabent*)findentry(t, key, hash, eql);
  3000. }
  3001. static bool lookup(const upb_table *t, lookupkey_t key, upb_value *v,
  3002. uint32_t hash, eqlfunc_t *eql) {
  3003. const upb_tabent *e = findentry(t, key, hash, eql);
  3004. if (e) {
  3005. if (v) {
  3006. _upb_value_setval(v, e->val, t->ctype);
  3007. }
  3008. return true;
  3009. } else {
  3010. return false;
  3011. }
  3012. }
  3013. // The given key must not already exist in the table.
  3014. static void insert(upb_table *t, lookupkey_t key, upb_value val,
  3015. uint32_t hash, hashfunc_t *hashfunc, eqlfunc_t *eql) {
  3016. UPB_UNUSED(eql);
  3017. assert(findentry(t, key, hash, eql) == NULL);
  3018. assert(val.ctype == t->ctype);
  3019. t->count++;
  3020. upb_tabent *mainpos_e = getentry_mutable(t, hash);
  3021. upb_tabent *our_e = mainpos_e;
  3022. if (upb_tabent_isempty(mainpos_e)) {
  3023. // Our main position is empty; use it.
  3024. our_e->next = NULL;
  3025. } else {
  3026. // Collision.
  3027. upb_tabent *new_e = emptyent(t);
  3028. // Head of collider's chain.
  3029. upb_tabent *chain = getentry_mutable(t, hashfunc(mainpos_e->key));
  3030. if (chain == mainpos_e) {
  3031. // Existing ent is in its main posisiton (it has the same hash as us, and
  3032. // is the head of our chain). Insert to new ent and append to this chain.
  3033. new_e->next = mainpos_e->next;
  3034. mainpos_e->next = new_e;
  3035. our_e = new_e;
  3036. } else {
  3037. // Existing ent is not in its main position (it is a node in some other
  3038. // chain). This implies that no existing ent in the table has our hash.
  3039. // Evict it (updating its chain) and use its ent for head of our chain.
  3040. *new_e = *mainpos_e; // copies next.
  3041. while (chain->next != mainpos_e) {
  3042. chain = (upb_tabent*)chain->next;
  3043. assert(chain);
  3044. }
  3045. chain->next = new_e;
  3046. our_e = mainpos_e;
  3047. our_e->next = NULL;
  3048. }
  3049. }
  3050. our_e->key = key.key;
  3051. our_e->val = val.val;
  3052. assert(findentry(t, key, hash, eql) == our_e);
  3053. }
  3054. static bool rm(upb_table *t, lookupkey_t key, upb_value *val,
  3055. upb_tabkey *removed, uint32_t hash, eqlfunc_t *eql) {
  3056. upb_tabent *chain = getentry_mutable(t, hash);
  3057. if (upb_tabent_isempty(chain)) return false;
  3058. if (eql(chain->key, key)) {
  3059. // Element to remove is at the head of its chain.
  3060. t->count--;
  3061. if (val) {
  3062. _upb_value_setval(val, chain->val, t->ctype);
  3063. }
  3064. if (chain->next) {
  3065. upb_tabent *move = (upb_tabent*)chain->next;
  3066. *chain = *move;
  3067. if (removed) *removed = move->key;
  3068. move->key.num = 0; // Make the slot empty.
  3069. } else {
  3070. if (removed) *removed = chain->key;
  3071. chain->key.num = 0; // Make the slot empty.
  3072. }
  3073. return true;
  3074. } else {
  3075. // Element to remove is either in a non-head position or not in the table.
  3076. while (chain->next && !eql(chain->next->key, key))
  3077. chain = (upb_tabent*)chain->next;
  3078. if (chain->next) {
  3079. // Found element to remove.
  3080. if (val) {
  3081. _upb_value_setval(val, chain->next->val, t->ctype);
  3082. }
  3083. upb_tabent *rm = (upb_tabent*)chain->next;
  3084. if (removed) *removed = rm->key;
  3085. rm->key.num = 0;
  3086. chain->next = rm->next;
  3087. t->count--;
  3088. return true;
  3089. } else {
  3090. return false;
  3091. }
  3092. }
  3093. }
  3094. static size_t next(const upb_table *t, size_t i) {
  3095. do {
  3096. if (++i >= upb_table_size(t))
  3097. return SIZE_MAX;
  3098. } while(upb_tabent_isempty(&t->entries[i]));
  3099. return i;
  3100. }
  3101. static size_t begin(const upb_table *t) {
  3102. return next(t, -1);
  3103. }
  3104. /* upb_strtable ***************************************************************/
  3105. // A simple "subclass" of upb_table that only adds a hash function for strings.
  3106. static uint32_t strhash(upb_tabkey key) {
  3107. return MurmurHash2(key.s.str, key.s.length, 0);
  3108. }
  3109. static bool streql(upb_tabkey k1, lookupkey_t k2) {
  3110. return k1.s.length == k2.key.s.length &&
  3111. memcmp(k1.s.str, k2.key.s.str, k1.s.length) == 0;
  3112. }
  3113. bool upb_strtable_init(upb_strtable *t, upb_ctype_t ctype) {
  3114. return init(&t->t, ctype, 2);
  3115. }
  3116. void upb_strtable_uninit(upb_strtable *t) {
  3117. for (size_t i = 0; i < upb_table_size(&t->t); i++)
  3118. free((void*)t->t.entries[i].key.s.str);
  3119. uninit(&t->t);
  3120. }
  3121. bool upb_strtable_resize(upb_strtable *t, size_t size_lg2) {
  3122. upb_strtable new_table;
  3123. if (!init(&new_table.t, t->t.ctype, size_lg2))
  3124. return false;
  3125. upb_strtable_iter i;
  3126. upb_strtable_begin(&i, t);
  3127. for ( ; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  3128. upb_strtable_insert2(
  3129. &new_table,
  3130. upb_strtable_iter_key(&i),
  3131. upb_strtable_iter_keylength(&i),
  3132. upb_strtable_iter_value(&i));
  3133. }
  3134. upb_strtable_uninit(t);
  3135. *t = new_table;
  3136. return true;
  3137. }
  3138. bool upb_strtable_insert2(upb_strtable *t, const char *k, size_t len,
  3139. upb_value v) {
  3140. if (isfull(&t->t)) {
  3141. // Need to resize. New table of double the size, add old elements to it.
  3142. if (!upb_strtable_resize(t, t->t.size_lg2 + 1)) {
  3143. return false;
  3144. }
  3145. }
  3146. if ((k = upb_strdup2(k, len)) == NULL) return false;
  3147. lookupkey_t key = strkey2(k, len);
  3148. uint32_t hash = MurmurHash2(key.key.s.str, key.key.s.length, 0);
  3149. insert(&t->t, key, v, hash, &strhash, &streql);
  3150. return true;
  3151. }
  3152. bool upb_strtable_lookup2(const upb_strtable *t, const char *key, size_t len,
  3153. upb_value *v) {
  3154. uint32_t hash = MurmurHash2(key, len, 0);
  3155. return lookup(&t->t, strkey2(key, len), v, hash, &streql);
  3156. }
  3157. bool upb_strtable_remove2(upb_strtable *t, const char *key, size_t len,
  3158. upb_value *val) {
  3159. uint32_t hash = MurmurHash2(key, strlen(key), 0);
  3160. upb_tabkey tabkey;
  3161. if (rm(&t->t, strkey2(key, len), val, &tabkey, hash, &streql)) {
  3162. free((void*)tabkey.s.str);
  3163. return true;
  3164. } else {
  3165. return false;
  3166. }
  3167. }
  3168. // Iteration
  3169. static const upb_tabent *str_tabent(const upb_strtable_iter *i) {
  3170. return &i->t->t.entries[i->index];
  3171. }
  3172. void upb_strtable_begin(upb_strtable_iter *i, const upb_strtable *t) {
  3173. i->t = t;
  3174. i->index = begin(&t->t);
  3175. }
  3176. void upb_strtable_next(upb_strtable_iter *i) {
  3177. i->index = next(&i->t->t, i->index);
  3178. }
  3179. bool upb_strtable_done(const upb_strtable_iter *i) {
  3180. return i->index >= upb_table_size(&i->t->t) ||
  3181. upb_tabent_isempty(str_tabent(i));
  3182. }
  3183. const char *upb_strtable_iter_key(upb_strtable_iter *i) {
  3184. assert(!upb_strtable_done(i));
  3185. return str_tabent(i)->key.s.str;
  3186. }
  3187. size_t upb_strtable_iter_keylength(upb_strtable_iter *i) {
  3188. assert(!upb_strtable_done(i));
  3189. return str_tabent(i)->key.s.length;
  3190. }
  3191. upb_value upb_strtable_iter_value(const upb_strtable_iter *i) {
  3192. assert(!upb_strtable_done(i));
  3193. return _upb_value_val(str_tabent(i)->val, i->t->t.ctype);
  3194. }
  3195. void upb_strtable_iter_setdone(upb_strtable_iter *i) {
  3196. i->index = SIZE_MAX;
  3197. }
  3198. bool upb_strtable_iter_isequal(const upb_strtable_iter *i1,
  3199. const upb_strtable_iter *i2) {
  3200. if (upb_strtable_done(i1) && upb_strtable_done(i2))
  3201. return true;
  3202. return i1->t == i2->t && i1->index == i2->index;
  3203. }
  3204. /* upb_inttable ***************************************************************/
  3205. // For inttables we use a hybrid structure where small keys are kept in an
  3206. // array and large keys are put in the hash table.
  3207. static uint32_t inthash(upb_tabkey key) { return upb_inthash(key.num); }
  3208. static bool inteql(upb_tabkey k1, lookupkey_t k2) {
  3209. return k1.num == k2.key.num;
  3210. }
  3211. static _upb_value *mutable_array(upb_inttable *t) {
  3212. return (_upb_value*)t->array;
  3213. }
  3214. static _upb_value *inttable_val(upb_inttable *t, uintptr_t key) {
  3215. if (key < t->array_size) {
  3216. return upb_arrhas(t->array[key]) ? &(mutable_array(t)[key]) : NULL;
  3217. } else {
  3218. upb_tabent *e =
  3219. findentry_mutable(&t->t, intkey(key), upb_inthash(key), &inteql);
  3220. return e ? &e->val : NULL;
  3221. }
  3222. }
  3223. static const _upb_value *inttable_val_const(const upb_inttable *t,
  3224. uintptr_t key) {
  3225. return inttable_val((upb_inttable*)t, key);
  3226. }
  3227. size_t upb_inttable_count(const upb_inttable *t) {
  3228. return t->t.count + t->array_count;
  3229. }
  3230. static void check(upb_inttable *t) {
  3231. UPB_UNUSED(t);
  3232. #if defined(UPB_DEBUG_TABLE) && !defined(NDEBUG)
  3233. // This check is very expensive (makes inserts/deletes O(N)).
  3234. size_t count = 0;
  3235. upb_inttable_iter i;
  3236. upb_inttable_begin(&i, t);
  3237. for(; !upb_inttable_done(&i); upb_inttable_next(&i), count++) {
  3238. assert(upb_inttable_lookup(t, upb_inttable_iter_key(&i), NULL));
  3239. }
  3240. assert(count == upb_inttable_count(t));
  3241. #endif
  3242. }
  3243. bool upb_inttable_sizedinit(upb_inttable *t, upb_ctype_t ctype,
  3244. size_t asize, int hsize_lg2) {
  3245. if (!init(&t->t, ctype, hsize_lg2)) return false;
  3246. // Always make the array part at least 1 long, so that we know key 0
  3247. // won't be in the hash part, which simplifies things.
  3248. t->array_size = UPB_MAX(1, asize);
  3249. t->array_count = 0;
  3250. size_t array_bytes = t->array_size * sizeof(upb_value);
  3251. t->array = malloc(array_bytes);
  3252. if (!t->array) {
  3253. uninit(&t->t);
  3254. return false;
  3255. }
  3256. memset(mutable_array(t), 0xff, array_bytes);
  3257. check(t);
  3258. return true;
  3259. }
  3260. bool upb_inttable_init(upb_inttable *t, upb_ctype_t ctype) {
  3261. return upb_inttable_sizedinit(t, ctype, 0, 4);
  3262. }
  3263. void upb_inttable_uninit(upb_inttable *t) {
  3264. uninit(&t->t);
  3265. free(mutable_array(t));
  3266. }
  3267. bool upb_inttable_insert(upb_inttable *t, uintptr_t key, upb_value val) {
  3268. assert(upb_arrhas(val.val));
  3269. if (key < t->array_size) {
  3270. assert(!upb_arrhas(t->array[key]));
  3271. t->array_count++;
  3272. mutable_array(t)[key] = val.val;
  3273. } else {
  3274. if (isfull(&t->t)) {
  3275. // Need to resize the hash part, but we re-use the array part.
  3276. upb_table new_table;
  3277. if (!init(&new_table, t->t.ctype, t->t.size_lg2 + 1))
  3278. return false;
  3279. size_t i;
  3280. for (i = begin(&t->t); i < upb_table_size(&t->t); i = next(&t->t, i)) {
  3281. const upb_tabent *e = &t->t.entries[i];
  3282. upb_value v;
  3283. _upb_value_setval(&v, e->val, t->t.ctype);
  3284. uint32_t hash = upb_inthash(e->key.num);
  3285. insert(&new_table, intkey(e->key.num), v, hash, &inthash, &inteql);
  3286. }
  3287. assert(t->t.count == new_table.count);
  3288. uninit(&t->t);
  3289. t->t = new_table;
  3290. }
  3291. insert(&t->t, intkey(key), val, upb_inthash(key), &inthash, &inteql);
  3292. }
  3293. check(t);
  3294. return true;
  3295. }
  3296. bool upb_inttable_lookup(const upb_inttable *t, uintptr_t key, upb_value *v) {
  3297. const _upb_value *table_v = inttable_val_const(t, key);
  3298. if (!table_v) return false;
  3299. if (v) _upb_value_setval(v, *table_v, t->t.ctype);
  3300. return true;
  3301. }
  3302. bool upb_inttable_replace(upb_inttable *t, uintptr_t key, upb_value val) {
  3303. _upb_value *table_v = inttable_val(t, key);
  3304. if (!table_v) return false;
  3305. *table_v = val.val;
  3306. return true;
  3307. }
  3308. bool upb_inttable_remove(upb_inttable *t, uintptr_t key, upb_value *val) {
  3309. bool success;
  3310. if (key < t->array_size) {
  3311. if (upb_arrhas(t->array[key])) {
  3312. t->array_count--;
  3313. if (val) {
  3314. _upb_value_setval(val, t->array[key], t->t.ctype);
  3315. }
  3316. _upb_value empty = UPB_ARRAY_EMPTYENT;
  3317. mutable_array(t)[key] = empty;
  3318. success = true;
  3319. } else {
  3320. success = false;
  3321. }
  3322. } else {
  3323. upb_tabkey removed;
  3324. uint32_t hash = upb_inthash(key);
  3325. success = rm(&t->t, intkey(key), val, &removed, hash, &inteql);
  3326. }
  3327. check(t);
  3328. return success;
  3329. }
  3330. bool upb_inttable_push(upb_inttable *t, upb_value val) {
  3331. return upb_inttable_insert(t, upb_inttable_count(t), val);
  3332. }
  3333. upb_value upb_inttable_pop(upb_inttable *t) {
  3334. upb_value val;
  3335. bool ok = upb_inttable_remove(t, upb_inttable_count(t) - 1, &val);
  3336. UPB_ASSERT_VAR(ok, ok);
  3337. return val;
  3338. }
  3339. bool upb_inttable_insertptr(upb_inttable *t, const void *key, upb_value val) {
  3340. return upb_inttable_insert(t, (uintptr_t)key, val);
  3341. }
  3342. bool upb_inttable_lookupptr(const upb_inttable *t, const void *key,
  3343. upb_value *v) {
  3344. return upb_inttable_lookup(t, (uintptr_t)key, v);
  3345. }
  3346. bool upb_inttable_removeptr(upb_inttable *t, const void *key, upb_value *val) {
  3347. return upb_inttable_remove(t, (uintptr_t)key, val);
  3348. }
  3349. void upb_inttable_compact(upb_inttable *t) {
  3350. // Create a power-of-two histogram of the table keys.
  3351. int counts[UPB_MAXARRSIZE + 1] = {0};
  3352. uintptr_t max_key = 0;
  3353. upb_inttable_iter i;
  3354. upb_inttable_begin(&i, t);
  3355. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  3356. uintptr_t key = upb_inttable_iter_key(&i);
  3357. if (key > max_key) {
  3358. max_key = key;
  3359. }
  3360. counts[log2ceil(key)]++;
  3361. }
  3362. int arr_size;
  3363. int arr_count = upb_inttable_count(t);
  3364. if (upb_inttable_count(t) >= max_key * MIN_DENSITY) {
  3365. // We can put 100% of the entries in the array part.
  3366. arr_size = max_key + 1;
  3367. } else {
  3368. // Find the largest power of two that satisfies the MIN_DENSITY definition.
  3369. for (int size_lg2 = ARRAY_SIZE(counts) - 1; size_lg2 > 1; size_lg2--) {
  3370. arr_size = 1 << size_lg2;
  3371. arr_count -= counts[size_lg2];
  3372. if (arr_count >= arr_size * MIN_DENSITY) {
  3373. break;
  3374. }
  3375. }
  3376. }
  3377. // Array part must always be at least 1 entry large to catch lookups of key
  3378. // 0. Key 0 must always be in the array part because "0" in the hash part
  3379. // denotes an empty entry.
  3380. arr_size = UPB_MAX(arr_size, 1);
  3381. // Insert all elements into new, perfectly-sized table.
  3382. int hash_count = upb_inttable_count(t) - arr_count;
  3383. int hash_size = hash_count ? (hash_count / MAX_LOAD) + 1 : 0;
  3384. int hashsize_lg2 = log2ceil(hash_size);
  3385. assert(hash_count >= 0);
  3386. upb_inttable new_t;
  3387. upb_inttable_sizedinit(&new_t, t->t.ctype, arr_size, hashsize_lg2);
  3388. upb_inttable_begin(&i, t);
  3389. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  3390. uintptr_t k = upb_inttable_iter_key(&i);
  3391. upb_inttable_insert(&new_t, k, upb_inttable_iter_value(&i));
  3392. }
  3393. assert(new_t.array_size == arr_size);
  3394. assert(new_t.t.size_lg2 == hashsize_lg2);
  3395. upb_inttable_uninit(t);
  3396. *t = new_t;
  3397. }
  3398. // Iteration.
  3399. static const upb_tabent *int_tabent(const upb_inttable_iter *i) {
  3400. assert(!i->array_part);
  3401. return &i->t->t.entries[i->index];
  3402. }
  3403. static _upb_value int_arrent(const upb_inttable_iter *i) {
  3404. assert(i->array_part);
  3405. return i->t->array[i->index];
  3406. }
  3407. void upb_inttable_begin(upb_inttable_iter *i, const upb_inttable *t) {
  3408. i->t = t;
  3409. i->index = -1;
  3410. i->array_part = true;
  3411. upb_inttable_next(i);
  3412. }
  3413. void upb_inttable_next(upb_inttable_iter *iter) {
  3414. const upb_inttable *t = iter->t;
  3415. if (iter->array_part) {
  3416. while (++iter->index < t->array_size) {
  3417. if (upb_arrhas(int_arrent(iter))) {
  3418. return;
  3419. }
  3420. }
  3421. iter->array_part = false;
  3422. iter->index = begin(&t->t);
  3423. } else {
  3424. iter->index = next(&t->t, iter->index);
  3425. }
  3426. }
  3427. bool upb_inttable_done(const upb_inttable_iter *i) {
  3428. if (i->array_part) {
  3429. return i->index >= i->t->array_size ||
  3430. !upb_arrhas(int_arrent(i));
  3431. } else {
  3432. return i->index >= upb_table_size(&i->t->t) ||
  3433. upb_tabent_isempty(int_tabent(i));
  3434. }
  3435. }
  3436. uintptr_t upb_inttable_iter_key(const upb_inttable_iter *i) {
  3437. assert(!upb_inttable_done(i));
  3438. return i->array_part ? i->index : int_tabent(i)->key.num;
  3439. }
  3440. upb_value upb_inttable_iter_value(const upb_inttable_iter *i) {
  3441. assert(!upb_inttable_done(i));
  3442. return _upb_value_val(
  3443. i->array_part ? i->t->array[i->index] : int_tabent(i)->val,
  3444. i->t->t.ctype);
  3445. }
  3446. void upb_inttable_iter_setdone(upb_inttable_iter *i) {
  3447. i->index = SIZE_MAX;
  3448. i->array_part = false;
  3449. }
  3450. bool upb_inttable_iter_isequal(const upb_inttable_iter *i1,
  3451. const upb_inttable_iter *i2) {
  3452. if (upb_inttable_done(i1) && upb_inttable_done(i2))
  3453. return true;
  3454. return i1->t == i2->t && i1->index == i2->index &&
  3455. i1->array_part == i2->array_part;
  3456. }
  3457. #ifdef UPB_UNALIGNED_READS_OK
  3458. //-----------------------------------------------------------------------------
  3459. // MurmurHash2, by Austin Appleby (released as public domain).
  3460. // Reformatted and C99-ified by Joshua Haberman.
  3461. // Note - This code makes a few assumptions about how your machine behaves -
  3462. // 1. We can read a 4-byte value from any address without crashing
  3463. // 2. sizeof(int) == 4 (in upb this limitation is removed by using uint32_t
  3464. // And it has a few limitations -
  3465. // 1. It will not work incrementally.
  3466. // 2. It will not produce the same results on little-endian and big-endian
  3467. // machines.
  3468. uint32_t MurmurHash2(const void *key, size_t len, uint32_t seed) {
  3469. // 'm' and 'r' are mixing constants generated offline.
  3470. // They're not really 'magic', they just happen to work well.
  3471. const uint32_t m = 0x5bd1e995;
  3472. const int32_t r = 24;
  3473. // Initialize the hash to a 'random' value
  3474. uint32_t h = seed ^ len;
  3475. // Mix 4 bytes at a time into the hash
  3476. const uint8_t * data = (const uint8_t *)key;
  3477. while(len >= 4) {
  3478. uint32_t k = *(uint32_t *)data;
  3479. k *= m;
  3480. k ^= k >> r;
  3481. k *= m;
  3482. h *= m;
  3483. h ^= k;
  3484. data += 4;
  3485. len -= 4;
  3486. }
  3487. // Handle the last few bytes of the input array
  3488. switch(len) {
  3489. case 3: h ^= data[2] << 16;
  3490. case 2: h ^= data[1] << 8;
  3491. case 1: h ^= data[0]; h *= m;
  3492. };
  3493. // Do a few final mixes of the hash to ensure the last few
  3494. // bytes are well-incorporated.
  3495. h ^= h >> 13;
  3496. h *= m;
  3497. h ^= h >> 15;
  3498. return h;
  3499. }
  3500. #else // !UPB_UNALIGNED_READS_OK
  3501. //-----------------------------------------------------------------------------
  3502. // MurmurHashAligned2, by Austin Appleby
  3503. // Same algorithm as MurmurHash2, but only does aligned reads - should be safer
  3504. // on certain platforms.
  3505. // Performance will be lower than MurmurHash2
  3506. #define MIX(h,k,m) { k *= m; k ^= k >> r; k *= m; h *= m; h ^= k; }
  3507. uint32_t MurmurHash2(const void * key, size_t len, uint32_t seed) {
  3508. const uint32_t m = 0x5bd1e995;
  3509. const int32_t r = 24;
  3510. const uint8_t * data = (const uint8_t *)key;
  3511. uint32_t h = seed ^ len;
  3512. uint8_t align = (uintptr_t)data & 3;
  3513. if(align && (len >= 4)) {
  3514. // Pre-load the temp registers
  3515. uint32_t t = 0, d = 0;
  3516. switch(align) {
  3517. case 1: t |= data[2] << 16;
  3518. case 2: t |= data[1] << 8;
  3519. case 3: t |= data[0];
  3520. }
  3521. t <<= (8 * align);
  3522. data += 4-align;
  3523. len -= 4-align;
  3524. int32_t sl = 8 * (4-align);
  3525. int32_t sr = 8 * align;
  3526. // Mix
  3527. while(len >= 4) {
  3528. d = *(uint32_t *)data;
  3529. t = (t >> sr) | (d << sl);
  3530. uint32_t k = t;
  3531. MIX(h,k,m);
  3532. t = d;
  3533. data += 4;
  3534. len -= 4;
  3535. }
  3536. // Handle leftover data in temp registers
  3537. d = 0;
  3538. if(len >= align) {
  3539. switch(align) {
  3540. case 3: d |= data[2] << 16;
  3541. case 2: d |= data[1] << 8;
  3542. case 1: d |= data[0];
  3543. }
  3544. uint32_t k = (t >> sr) | (d << sl);
  3545. MIX(h,k,m);
  3546. data += align;
  3547. len -= align;
  3548. //----------
  3549. // Handle tail bytes
  3550. switch(len) {
  3551. case 3: h ^= data[2] << 16;
  3552. case 2: h ^= data[1] << 8;
  3553. case 1: h ^= data[0]; h *= m;
  3554. };
  3555. } else {
  3556. switch(len) {
  3557. case 3: d |= data[2] << 16;
  3558. case 2: d |= data[1] << 8;
  3559. case 1: d |= data[0];
  3560. case 0: h ^= (t >> sr) | (d << sl); h *= m;
  3561. }
  3562. }
  3563. h ^= h >> 13;
  3564. h *= m;
  3565. h ^= h >> 15;
  3566. return h;
  3567. } else {
  3568. while(len >= 4) {
  3569. uint32_t k = *(uint32_t *)data;
  3570. MIX(h,k,m);
  3571. data += 4;
  3572. len -= 4;
  3573. }
  3574. //----------
  3575. // Handle tail bytes
  3576. switch(len) {
  3577. case 3: h ^= data[2] << 16;
  3578. case 2: h ^= data[1] << 8;
  3579. case 1: h ^= data[0]; h *= m;
  3580. };
  3581. h ^= h >> 13;
  3582. h *= m;
  3583. h ^= h >> 15;
  3584. return h;
  3585. }
  3586. }
  3587. #undef MIX
  3588. #endif // UPB_UNALIGNED_READS_OK
  3589. /*
  3590. * upb - a minimalist implementation of protocol buffers.
  3591. *
  3592. * Copyright (c) 2009-2012 Google Inc. See LICENSE for details.
  3593. * Author: Josh Haberman <jhaberman@gmail.com>
  3594. */
  3595. #include <errno.h>
  3596. #include <stdarg.h>
  3597. #include <stddef.h>
  3598. #include <stdint.h>
  3599. #include <stdio.h>
  3600. #include <stdlib.h>
  3601. #include <string.h>
  3602. bool upb_dumptostderr(void *closure, const upb_status* status) {
  3603. UPB_UNUSED(closure);
  3604. fprintf(stderr, "%s\n", upb_status_errmsg(status));
  3605. return false;
  3606. }
  3607. // Guarantee null-termination and provide ellipsis truncation.
  3608. // It may be tempting to "optimize" this by initializing these final
  3609. // four bytes up-front and then being careful never to overwrite them,
  3610. // this is safer and simpler.
  3611. static void nullz(upb_status *status) {
  3612. const char *ellipsis = "...";
  3613. size_t len = strlen(ellipsis);
  3614. assert(sizeof(status->msg) > len);
  3615. memcpy(status->msg + sizeof(status->msg) - len, ellipsis, len);
  3616. }
  3617. void upb_status_clear(upb_status *status) {
  3618. upb_status blank = UPB_STATUS_INIT;
  3619. upb_status_copy(status, &blank);
  3620. }
  3621. bool upb_ok(const upb_status *status) { return status->ok_; }
  3622. upb_errorspace *upb_status_errspace(const upb_status *status) {
  3623. return status->error_space_;
  3624. }
  3625. int upb_status_errcode(const upb_status *status) { return status->code_; }
  3626. const char *upb_status_errmsg(const upb_status *status) { return status->msg; }
  3627. void upb_status_seterrmsg(upb_status *status, const char *msg) {
  3628. if (!status) return;
  3629. status->ok_ = false;
  3630. strncpy(status->msg, msg, sizeof(status->msg));
  3631. nullz(status);
  3632. }
  3633. void upb_status_seterrf(upb_status *status, const char *fmt, ...) {
  3634. va_list args;
  3635. va_start(args, fmt);
  3636. upb_status_vseterrf(status, fmt, args);
  3637. va_end(args);
  3638. }
  3639. void upb_status_vseterrf(upb_status *status, const char *fmt, va_list args) {
  3640. if (!status) return;
  3641. status->ok_ = false;
  3642. vsnprintf(status->msg, sizeof(status->msg), fmt, args);
  3643. nullz(status);
  3644. }
  3645. void upb_status_seterrcode(upb_status *status, upb_errorspace *space,
  3646. int code) {
  3647. if (!status) return;
  3648. status->ok_ = false;
  3649. status->error_space_ = space;
  3650. status->code_ = code;
  3651. space->set_message(status, code);
  3652. }
  3653. void upb_status_copy(upb_status *to, const upb_status *from) {
  3654. if (!to) return;
  3655. *to = *from;
  3656. }
  3657. // This file was generated by upbc (the upb compiler).
  3658. // Do not edit -- your changes will be discarded when the file is
  3659. // regenerated.
  3660. static const upb_msgdef msgs[20];
  3661. static const upb_fielddef fields[81];
  3662. static const upb_enumdef enums[4];
  3663. static const upb_tabent strentries[236];
  3664. static const upb_tabent intentries[14];
  3665. static const _upb_value arrays[232];
  3666. #ifdef UPB_DEBUG_REFS
  3667. static upb_inttable reftables[212];
  3668. #endif
  3669. static const upb_msgdef msgs[20] = {
  3670. UPB_MSGDEF_INIT("google.protobuf.DescriptorProto", 27, 6, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[0], 8, 7), UPB_STRTABLE_INIT(7, 15, UPB_CTYPE_PTR, 4, &strentries[0]),&reftables[0], &reftables[1]),
  3671. UPB_MSGDEF_INIT("google.protobuf.DescriptorProto.ExtensionRange", 4, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[8], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[16]),&reftables[2], &reftables[3]),
  3672. UPB_MSGDEF_INIT("google.protobuf.EnumDescriptorProto", 11, 2, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[11], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[20]),&reftables[4], &reftables[5]),
  3673. UPB_MSGDEF_INIT("google.protobuf.EnumOptions", 7, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[0], &arrays[15], 8, 1), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[24]),&reftables[6], &reftables[7]),
  3674. UPB_MSGDEF_INIT("google.protobuf.EnumValueDescriptorProto", 8, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[23], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[28]),&reftables[8], &reftables[9]),
  3675. UPB_MSGDEF_INIT("google.protobuf.EnumValueOptions", 6, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[2], &arrays[27], 4, 0), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[32]),&reftables[10], &reftables[11]),
  3676. UPB_MSGDEF_INIT("google.protobuf.FieldDescriptorProto", 19, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[31], 9, 8), UPB_STRTABLE_INIT(8, 15, UPB_CTYPE_PTR, 4, &strentries[36]),&reftables[12], &reftables[13]),
  3677. UPB_MSGDEF_INIT("google.protobuf.FieldOptions", 14, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[4], &arrays[40], 32, 6), UPB_STRTABLE_INIT(7, 15, UPB_CTYPE_PTR, 4, &strentries[52]),&reftables[14], &reftables[15]),
  3678. UPB_MSGDEF_INIT("google.protobuf.FileDescriptorProto", 39, 6, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[72], 12, 11), UPB_STRTABLE_INIT(11, 15, UPB_CTYPE_PTR, 4, &strentries[68]),&reftables[16], &reftables[17]),
  3679. UPB_MSGDEF_INIT("google.protobuf.FileDescriptorSet", 6, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[84], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[84]),&reftables[18], &reftables[19]),
  3680. UPB_MSGDEF_INIT("google.protobuf.FileOptions", 21, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[6], &arrays[86], 64, 9), UPB_STRTABLE_INIT(10, 15, UPB_CTYPE_PTR, 4, &strentries[88]),&reftables[20], &reftables[21]),
  3681. UPB_MSGDEF_INIT("google.protobuf.MessageOptions", 8, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[8], &arrays[150], 16, 2), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[104]),&reftables[22], &reftables[23]),
  3682. UPB_MSGDEF_INIT("google.protobuf.MethodDescriptorProto", 13, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[166], 5, 4), UPB_STRTABLE_INIT(4, 7, UPB_CTYPE_PTR, 3, &strentries[108]),&reftables[24], &reftables[25]),
  3683. UPB_MSGDEF_INIT("google.protobuf.MethodOptions", 6, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[10], &arrays[171], 4, 0), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[116]),&reftables[26], &reftables[27]),
  3684. UPB_MSGDEF_INIT("google.protobuf.ServiceDescriptorProto", 11, 2, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[175], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[120]),&reftables[28], &reftables[29]),
  3685. UPB_MSGDEF_INIT("google.protobuf.ServiceOptions", 6, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[12], &arrays[179], 4, 0), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[124]),&reftables[30], &reftables[31]),
  3686. UPB_MSGDEF_INIT("google.protobuf.SourceCodeInfo", 6, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[183], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[128]),&reftables[32], &reftables[33]),
  3687. UPB_MSGDEF_INIT("google.protobuf.SourceCodeInfo.Location", 14, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[185], 5, 4), UPB_STRTABLE_INIT(4, 7, UPB_CTYPE_PTR, 3, &strentries[132]),&reftables[34], &reftables[35]),
  3688. UPB_MSGDEF_INIT("google.protobuf.UninterpretedOption", 18, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[190], 9, 7), UPB_STRTABLE_INIT(7, 15, UPB_CTYPE_PTR, 4, &strentries[140]),&reftables[36], &reftables[37]),
  3689. UPB_MSGDEF_INIT("google.protobuf.UninterpretedOption.NamePart", 6, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[199], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[156]),&reftables[38], &reftables[39]),
  3690. };
  3691. static const upb_fielddef fields[81] = {
  3692. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "aggregate_value", 8, &msgs[18], NULL, 15, 6, {0},&reftables[40], &reftables[41]),
  3693. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "allow_alias", 2, &msgs[3], NULL, 6, 1, {0},&reftables[42], &reftables[43]),
  3694. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "cc_generic_services", 16, &msgs[10], NULL, 17, 6, {0},&reftables[44], &reftables[45]),
  3695. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "ctype", 1, &msgs[7], UPB_UPCAST(&enums[2]), 6, 1, {0},&reftables[46], &reftables[47]),
  3696. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "default_value", 7, &msgs[6], NULL, 16, 7, {0},&reftables[48], &reftables[49]),
  3697. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_STRING, 0, false, false, false, false, "dependency", 3, &msgs[8], NULL, 30, 8, {0},&reftables[50], &reftables[51]),
  3698. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[7], NULL, 8, 3, {0},&reftables[52], &reftables[53]),
  3699. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_DOUBLE, 0, false, false, false, false, "double_value", 6, &msgs[18], NULL, 11, 4, {0},&reftables[54], &reftables[55]),
  3700. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "end", 2, &msgs[1], NULL, 3, 1, {0},&reftables[56], &reftables[57]),
  3701. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "enum_type", 4, &msgs[0], UPB_UPCAST(&msgs[2]), 16, 2, {0},&reftables[58], &reftables[59]),
  3702. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "enum_type", 5, &msgs[8], UPB_UPCAST(&msgs[2]), 13, 1, {0},&reftables[60], &reftables[61]),
  3703. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "experimental_map_key", 9, &msgs[7], NULL, 10, 5, {0},&reftables[62], &reftables[63]),
  3704. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "extendee", 2, &msgs[6], NULL, 7, 2, {0},&reftables[64], &reftables[65]),
  3705. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension", 7, &msgs[8], UPB_UPCAST(&msgs[6]), 19, 3, {0},&reftables[66], &reftables[67]),
  3706. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension", 6, &msgs[0], UPB_UPCAST(&msgs[6]), 22, 4, {0},&reftables[68], &reftables[69]),
  3707. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension_range", 5, &msgs[0], UPB_UPCAST(&msgs[1]), 19, 3, {0},&reftables[70], &reftables[71]),
  3708. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "field", 2, &msgs[0], UPB_UPCAST(&msgs[6]), 10, 0, {0},&reftables[72], &reftables[73]),
  3709. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "file", 1, &msgs[9], UPB_UPCAST(&msgs[8]), 5, 0, {0},&reftables[74], &reftables[75]),
  3710. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "go_package", 11, &msgs[10], NULL, 14, 5, {0},&reftables[76], &reftables[77]),
  3711. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "identifier_value", 3, &msgs[18], NULL, 6, 1, {0},&reftables[78], &reftables[79]),
  3712. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "input_type", 2, &msgs[12], NULL, 7, 2, {0},&reftables[80], &reftables[81]),
  3713. UPB_FIELDDEF_INIT(UPB_LABEL_REQUIRED, UPB_TYPE_BOOL, 0, false, false, false, false, "is_extension", 2, &msgs[19], NULL, 5, 1, {0},&reftables[82], &reftables[83]),
  3714. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_generate_equals_and_hash", 20, &msgs[10], NULL, 20, 9, {0},&reftables[84], &reftables[85]),
  3715. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_generic_services", 17, &msgs[10], NULL, 18, 7, {0},&reftables[86], &reftables[87]),
  3716. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_multiple_files", 10, &msgs[10], NULL, 13, 4, {0},&reftables[88], &reftables[89]),
  3717. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "java_outer_classname", 8, &msgs[10], NULL, 9, 2, {0},&reftables[90], &reftables[91]),
  3718. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "java_package", 1, &msgs[10], NULL, 6, 1, {0},&reftables[92], &reftables[93]),
  3719. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "label", 4, &msgs[6], UPB_UPCAST(&enums[0]), 11, 4, {0},&reftables[94], &reftables[95]),
  3720. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "lazy", 5, &msgs[7], NULL, 9, 4, {0},&reftables[96], &reftables[97]),
  3721. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "leading_comments", 3, &msgs[17], NULL, 8, 2, {0},&reftables[98], &reftables[99]),
  3722. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "location", 1, &msgs[16], UPB_UPCAST(&msgs[17]), 5, 0, {0},&reftables[100], &reftables[101]),
  3723. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "message_set_wire_format", 1, &msgs[11], NULL, 6, 1, {0},&reftables[102], &reftables[103]),
  3724. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "message_type", 4, &msgs[8], UPB_UPCAST(&msgs[0]), 10, 0, {0},&reftables[104], &reftables[105]),
  3725. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "method", 2, &msgs[14], UPB_UPCAST(&msgs[12]), 6, 0, {0},&reftables[106], &reftables[107]),
  3726. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[8], NULL, 22, 6, {0},&reftables[108], &reftables[109]),
  3727. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[14], NULL, 8, 2, {0},&reftables[110], &reftables[111]),
  3728. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "name", 2, &msgs[18], UPB_UPCAST(&msgs[19]), 5, 0, {0},&reftables[112], &reftables[113]),
  3729. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[4], NULL, 4, 1, {0},&reftables[114], &reftables[115]),
  3730. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[0], NULL, 24, 6, {0},&reftables[116], &reftables[117]),
  3731. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[12], NULL, 4, 1, {0},&reftables[118], &reftables[119]),
  3732. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[2], NULL, 8, 2, {0},&reftables[120], &reftables[121]),
  3733. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[6], NULL, 4, 1, {0},&reftables[122], &reftables[123]),
  3734. UPB_FIELDDEF_INIT(UPB_LABEL_REQUIRED, UPB_TYPE_STRING, 0, false, false, false, false, "name_part", 1, &msgs[19], NULL, 2, 0, {0},&reftables[124], &reftables[125]),
  3735. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT64, UPB_INTFMT_VARIABLE, false, false, false, false, "negative_int_value", 5, &msgs[18], NULL, 10, 3, {0},&reftables[126], &reftables[127]),
  3736. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "nested_type", 3, &msgs[0], UPB_UPCAST(&msgs[0]), 13, 1, {0},&reftables[128], &reftables[129]),
  3737. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "no_standard_descriptor_accessor", 2, &msgs[11], NULL, 7, 2, {0},&reftables[130], &reftables[131]),
  3738. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "number", 3, &msgs[6], NULL, 10, 3, {0},&reftables[132], &reftables[133]),
  3739. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "number", 2, &msgs[4], NULL, 7, 2, {0},&reftables[134], &reftables[135]),
  3740. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "optimize_for", 9, &msgs[10], UPB_UPCAST(&enums[3]), 12, 3, {0},&reftables[136], &reftables[137]),
  3741. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 7, &msgs[0], UPB_UPCAST(&msgs[11]), 23, 5, {0},&reftables[138], &reftables[139]),
  3742. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[2], UPB_UPCAST(&msgs[3]), 7, 1, {0},&reftables[140], &reftables[141]),
  3743. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 8, &msgs[6], UPB_UPCAST(&msgs[7]), 3, 0, {0},&reftables[142], &reftables[143]),
  3744. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[4], UPB_UPCAST(&msgs[5]), 3, 0, {0},&reftables[144], &reftables[145]),
  3745. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 8, &msgs[8], UPB_UPCAST(&msgs[10]), 20, 4, {0},&reftables[146], &reftables[147]),
  3746. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[14], UPB_UPCAST(&msgs[15]), 7, 1, {0},&reftables[148], &reftables[149]),
  3747. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 4, &msgs[12], UPB_UPCAST(&msgs[13]), 3, 0, {0},&reftables[150], &reftables[151]),
  3748. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "output_type", 3, &msgs[12], NULL, 10, 3, {0},&reftables[152], &reftables[153]),
  3749. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "package", 2, &msgs[8], NULL, 25, 7, {0},&reftables[154], &reftables[155]),
  3750. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "packed", 2, &msgs[7], NULL, 7, 2, {0},&reftables[156], &reftables[157]),
  3751. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, true, "path", 1, &msgs[17], NULL, 4, 0, {0},&reftables[158], &reftables[159]),
  3752. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_UINT64, UPB_INTFMT_VARIABLE, false, false, false, false, "positive_int_value", 4, &msgs[18], NULL, 9, 2, {0},&reftables[160], &reftables[161]),
  3753. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "public_dependency", 10, &msgs[8], NULL, 35, 9, {0},&reftables[162], &reftables[163]),
  3754. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "py_generic_services", 18, &msgs[10], NULL, 19, 8, {0},&reftables[164], &reftables[165]),
  3755. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "service", 6, &msgs[8], UPB_UPCAST(&msgs[14]), 16, 2, {0},&reftables[166], &reftables[167]),
  3756. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "source_code_info", 9, &msgs[8], UPB_UPCAST(&msgs[16]), 21, 5, {0},&reftables[168], &reftables[169]),
  3757. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, true, "span", 2, &msgs[17], NULL, 7, 1, {0},&reftables[170], &reftables[171]),
  3758. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "start", 1, &msgs[1], NULL, 2, 0, {0},&reftables[172], &reftables[173]),
  3759. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BYTES, 0, false, false, false, false, "string_value", 7, &msgs[18], NULL, 12, 5, {0},&reftables[174], &reftables[175]),
  3760. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "trailing_comments", 4, &msgs[17], NULL, 11, 3, {0},&reftables[176], &reftables[177]),
  3761. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "type", 5, &msgs[6], UPB_UPCAST(&enums[1]), 12, 5, {0},&reftables[178], &reftables[179]),
  3762. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "type_name", 6, &msgs[6], NULL, 13, 6, {0},&reftables[180], &reftables[181]),
  3763. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[5], UPB_UPCAST(&msgs[18]), 5, 0, {0},&reftables[182], &reftables[183]),
  3764. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[15], UPB_UPCAST(&msgs[18]), 5, 0, {0},&reftables[184], &reftables[185]),
  3765. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[3], UPB_UPCAST(&msgs[18]), 5, 0, {0},&reftables[186], &reftables[187]),
  3766. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[13], UPB_UPCAST(&msgs[18]), 5, 0, {0},&reftables[188], &reftables[189]),
  3767. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[10], UPB_UPCAST(&msgs[18]), 5, 0, {0},&reftables[190], &reftables[191]),
  3768. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[11], UPB_UPCAST(&msgs[18]), 5, 0, {0},&reftables[192], &reftables[193]),
  3769. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[7], UPB_UPCAST(&msgs[18]), 5, 0, {0},&reftables[194], &reftables[195]),
  3770. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "value", 2, &msgs[2], UPB_UPCAST(&msgs[4]), 6, 0, {0},&reftables[196], &reftables[197]),
  3771. UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "weak", 10, &msgs[7], NULL, 13, 6, {0},&reftables[198], &reftables[199]),
  3772. UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "weak_dependency", 11, &msgs[8], NULL, 38, 10, {0},&reftables[200], &reftables[201]),
  3773. };
  3774. static const upb_enumdef enums[4] = {
  3775. UPB_ENUMDEF_INIT("google.protobuf.FieldDescriptorProto.Label", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[160]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[202], 4, 3), 0, &reftables[202], &reftables[203]),
  3776. UPB_ENUMDEF_INIT("google.protobuf.FieldDescriptorProto.Type", UPB_STRTABLE_INIT(18, 31, UPB_CTYPE_INT32, 5, &strentries[164]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[206], 19, 18), 0, &reftables[204], &reftables[205]),
  3777. UPB_ENUMDEF_INIT("google.protobuf.FieldOptions.CType", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[196]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[225], 3, 3), 0, &reftables[206], &reftables[207]),
  3778. UPB_ENUMDEF_INIT("google.protobuf.FileOptions.OptimizeMode", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[200]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[228], 4, 3), 0, &reftables[208], &reftables[209]),
  3779. };
  3780. static const upb_tabent strentries[236] = {
  3781. {UPB_TABKEY_STR("extension"), UPB_VALUE_INIT_CONSTPTR(&fields[14]), NULL},
  3782. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3783. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3784. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[38]), NULL},
  3785. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3786. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3787. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3788. {UPB_TABKEY_STR("field"), UPB_VALUE_INIT_CONSTPTR(&fields[16]), NULL},
  3789. {UPB_TABKEY_STR("extension_range"), UPB_VALUE_INIT_CONSTPTR(&fields[15]), NULL},
  3790. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3791. {UPB_TABKEY_STR("nested_type"), UPB_VALUE_INIT_CONSTPTR(&fields[44]), NULL},
  3792. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3793. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3794. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3795. {UPB_TABKEY_STR("options"), UPB_VALUE_INIT_CONSTPTR(&fields[49]), NULL},
  3796. {UPB_TABKEY_STR("enum_type"), UPB_VALUE_INIT_CONSTPTR(&fields[9]), &strentries[14]},
  3797. {UPB_TABKEY_STR("start"), UPB_VALUE_INIT_CONSTPTR(&fields[66]), NULL},
  3798. {UPB_TABKEY_STR("end"), UPB_VALUE_INIT_CONSTPTR(&fields[8]), NULL},
  3799. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3800. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3801. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3802. {UPB_TABKEY_STR("value"), UPB_VALUE_INIT_CONSTPTR(&fields[78]), NULL},
  3803. {UPB_TABKEY_STR("options"), UPB_VALUE_INIT_CONSTPTR(&fields[50]), NULL},
  3804. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[40]), &strentries[22]},
  3805. {UPB_TABKEY_STR("uninterpreted_option"), UPB_VALUE_INIT_CONSTPTR(&fields[73]), NULL},
  3806. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3807. {UPB_TABKEY_STR("allow_alias"), UPB_VALUE_INIT_CONSTPTR(&fields[1]), NULL},
  3808. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3809. {UPB_TABKEY_STR("number"), UPB_VALUE_INIT_CONSTPTR(&fields[47]), NULL},
  3810. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3811. {UPB_TABKEY_STR("options"), UPB_VALUE_INIT_CONSTPTR(&fields[52]), NULL},
  3812. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[37]), &strentries[30]},
  3813. {UPB_TABKEY_STR("uninterpreted_option"), UPB_VALUE_INIT_CONSTPTR(&fields[71]), NULL},
  3814. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3815. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3816. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3817. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3818. {UPB_TABKEY_STR("label"), UPB_VALUE_INIT_CONSTPTR(&fields[27]), NULL},
  3819. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3820. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[41]), NULL},
  3821. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3822. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3823. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3824. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3825. {UPB_TABKEY_STR("number"), UPB_VALUE_INIT_CONSTPTR(&fields[46]), &strentries[49]},
  3826. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3827. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3828. {UPB_TABKEY_STR("type_name"), UPB_VALUE_INIT_CONSTPTR(&fields[70]), NULL},
  3829. {UPB_TABKEY_STR("extendee"), UPB_VALUE_INIT_CONSTPTR(&fields[12]), NULL},
  3830. {UPB_TABKEY_STR("type"), UPB_VALUE_INIT_CONSTPTR(&fields[69]), &strentries[48]},
  3831. {UPB_TABKEY_STR("default_value"), UPB_VALUE_INIT_CONSTPTR(&fields[4]), NULL},
  3832. {UPB_TABKEY_STR("options"), UPB_VALUE_INIT_CONSTPTR(&fields[51]), NULL},
  3833. {UPB_TABKEY_STR("experimental_map_key"), UPB_VALUE_INIT_CONSTPTR(&fields[11]), &strentries[67]},
  3834. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3835. {UPB_TABKEY_STR("weak"), UPB_VALUE_INIT_CONSTPTR(&fields[79]), NULL},
  3836. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3837. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3838. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3839. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3840. {UPB_TABKEY_STR("packed"), UPB_VALUE_INIT_CONSTPTR(&fields[58]), NULL},
  3841. {UPB_TABKEY_STR("lazy"), UPB_VALUE_INIT_CONSTPTR(&fields[28]), NULL},
  3842. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3843. {UPB_TABKEY_STR("ctype"), UPB_VALUE_INIT_CONSTPTR(&fields[3]), NULL},
  3844. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3845. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3846. {UPB_TABKEY_STR("deprecated"), UPB_VALUE_INIT_CONSTPTR(&fields[6]), NULL},
  3847. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3848. {UPB_TABKEY_STR("uninterpreted_option"), UPB_VALUE_INIT_CONSTPTR(&fields[77]), NULL},
  3849. {UPB_TABKEY_STR("extension"), UPB_VALUE_INIT_CONSTPTR(&fields[13]), NULL},
  3850. {UPB_TABKEY_STR("weak_dependency"), UPB_VALUE_INIT_CONSTPTR(&fields[80]), NULL},
  3851. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3852. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[34]), NULL},
  3853. {UPB_TABKEY_STR("service"), UPB_VALUE_INIT_CONSTPTR(&fields[63]), NULL},
  3854. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3855. {UPB_TABKEY_STR("source_code_info"), UPB_VALUE_INIT_CONSTPTR(&fields[64]), NULL},
  3856. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3857. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3858. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3859. {UPB_TABKEY_STR("dependency"), UPB_VALUE_INIT_CONSTPTR(&fields[5]), NULL},
  3860. {UPB_TABKEY_STR("message_type"), UPB_VALUE_INIT_CONSTPTR(&fields[32]), NULL},
  3861. {UPB_TABKEY_STR("package"), UPB_VALUE_INIT_CONSTPTR(&fields[57]), NULL},
  3862. {UPB_TABKEY_STR("options"), UPB_VALUE_INIT_CONSTPTR(&fields[53]), &strentries[82]},
  3863. {UPB_TABKEY_STR("enum_type"), UPB_VALUE_INIT_CONSTPTR(&fields[10]), NULL},
  3864. {UPB_TABKEY_STR("public_dependency"), UPB_VALUE_INIT_CONSTPTR(&fields[61]), &strentries[81]},
  3865. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3866. {UPB_TABKEY_STR("file"), UPB_VALUE_INIT_CONSTPTR(&fields[17]), NULL},
  3867. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3868. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3869. {UPB_TABKEY_STR("uninterpreted_option"), UPB_VALUE_INIT_CONSTPTR(&fields[75]), NULL},
  3870. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3871. {UPB_TABKEY_STR("cc_generic_services"), UPB_VALUE_INIT_CONSTPTR(&fields[2]), NULL},
  3872. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3873. {UPB_TABKEY_STR("java_multiple_files"), UPB_VALUE_INIT_CONSTPTR(&fields[24]), NULL},
  3874. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3875. {UPB_TABKEY_STR("java_generic_services"), UPB_VALUE_INIT_CONSTPTR(&fields[23]), &strentries[102]},
  3876. {UPB_TABKEY_STR("java_generate_equals_and_hash"), UPB_VALUE_INIT_CONSTPTR(&fields[22]), NULL},
  3877. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3878. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3879. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3880. {UPB_TABKEY_STR("go_package"), UPB_VALUE_INIT_CONSTPTR(&fields[18]), NULL},
  3881. {UPB_TABKEY_STR("java_package"), UPB_VALUE_INIT_CONSTPTR(&fields[26]), NULL},
  3882. {UPB_TABKEY_STR("optimize_for"), UPB_VALUE_INIT_CONSTPTR(&fields[48]), NULL},
  3883. {UPB_TABKEY_STR("py_generic_services"), UPB_VALUE_INIT_CONSTPTR(&fields[62]), NULL},
  3884. {UPB_TABKEY_STR("java_outer_classname"), UPB_VALUE_INIT_CONSTPTR(&fields[25]), NULL},
  3885. {UPB_TABKEY_STR("message_set_wire_format"), UPB_VALUE_INIT_CONSTPTR(&fields[31]), &strentries[106]},
  3886. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3887. {UPB_TABKEY_STR("uninterpreted_option"), UPB_VALUE_INIT_CONSTPTR(&fields[76]), NULL},
  3888. {UPB_TABKEY_STR("no_standard_descriptor_accessor"), UPB_VALUE_INIT_CONSTPTR(&fields[45]), NULL},
  3889. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3890. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3891. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3892. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[39]), NULL},
  3893. {UPB_TABKEY_STR("input_type"), UPB_VALUE_INIT_CONSTPTR(&fields[20]), NULL},
  3894. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3895. {UPB_TABKEY_STR("output_type"), UPB_VALUE_INIT_CONSTPTR(&fields[56]), NULL},
  3896. {UPB_TABKEY_STR("options"), UPB_VALUE_INIT_CONSTPTR(&fields[55]), NULL},
  3897. {UPB_TABKEY_STR("uninterpreted_option"), UPB_VALUE_INIT_CONSTPTR(&fields[74]), NULL},
  3898. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3899. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3900. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3901. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3902. {UPB_TABKEY_STR("options"), UPB_VALUE_INIT_CONSTPTR(&fields[54]), &strentries[122]},
  3903. {UPB_TABKEY_STR("method"), UPB_VALUE_INIT_CONSTPTR(&fields[33]), NULL},
  3904. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[35]), &strentries[121]},
  3905. {UPB_TABKEY_STR("uninterpreted_option"), UPB_VALUE_INIT_CONSTPTR(&fields[72]), NULL},
  3906. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3907. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3908. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3909. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3910. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3911. {UPB_TABKEY_STR("location"), UPB_VALUE_INIT_CONSTPTR(&fields[30]), NULL},
  3912. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3913. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3914. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3915. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3916. {UPB_TABKEY_STR("span"), UPB_VALUE_INIT_CONSTPTR(&fields[65]), &strentries[139]},
  3917. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3918. {UPB_TABKEY_STR("trailing_comments"), UPB_VALUE_INIT_CONSTPTR(&fields[68]), NULL},
  3919. {UPB_TABKEY_STR("leading_comments"), UPB_VALUE_INIT_CONSTPTR(&fields[29]), &strentries[137]},
  3920. {UPB_TABKEY_STR("path"), UPB_VALUE_INIT_CONSTPTR(&fields[59]), NULL},
  3921. {UPB_TABKEY_STR("double_value"), UPB_VALUE_INIT_CONSTPTR(&fields[7]), NULL},
  3922. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3923. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3924. {UPB_TABKEY_STR("name"), UPB_VALUE_INIT_CONSTPTR(&fields[36]), NULL},
  3925. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3926. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3927. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3928. {UPB_TABKEY_STR("negative_int_value"), UPB_VALUE_INIT_CONSTPTR(&fields[43]), NULL},
  3929. {UPB_TABKEY_STR("aggregate_value"), UPB_VALUE_INIT_CONSTPTR(&fields[0]), NULL},
  3930. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3931. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3932. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3933. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3934. {UPB_TABKEY_STR("positive_int_value"), UPB_VALUE_INIT_CONSTPTR(&fields[60]), NULL},
  3935. {UPB_TABKEY_STR("identifier_value"), UPB_VALUE_INIT_CONSTPTR(&fields[19]), NULL},
  3936. {UPB_TABKEY_STR("string_value"), UPB_VALUE_INIT_CONSTPTR(&fields[67]), &strentries[154]},
  3937. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3938. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3939. {UPB_TABKEY_STR("is_extension"), UPB_VALUE_INIT_CONSTPTR(&fields[21]), NULL},
  3940. {UPB_TABKEY_STR("name_part"), UPB_VALUE_INIT_CONSTPTR(&fields[42]), NULL},
  3941. {UPB_TABKEY_STR("LABEL_REQUIRED"), UPB_VALUE_INIT_INT32(2), &strentries[162]},
  3942. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3943. {UPB_TABKEY_STR("LABEL_REPEATED"), UPB_VALUE_INIT_INT32(3), NULL},
  3944. {UPB_TABKEY_STR("LABEL_OPTIONAL"), UPB_VALUE_INIT_INT32(1), NULL},
  3945. {UPB_TABKEY_STR("TYPE_FIXED64"), UPB_VALUE_INIT_INT32(6), NULL},
  3946. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3947. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3948. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3949. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3950. {UPB_TABKEY_STR("TYPE_STRING"), UPB_VALUE_INIT_INT32(9), NULL},
  3951. {UPB_TABKEY_STR("TYPE_FLOAT"), UPB_VALUE_INIT_INT32(2), &strentries[193]},
  3952. {UPB_TABKEY_STR("TYPE_DOUBLE"), UPB_VALUE_INIT_INT32(1), NULL},
  3953. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3954. {UPB_TABKEY_STR("TYPE_INT32"), UPB_VALUE_INIT_INT32(5), NULL},
  3955. {UPB_TABKEY_STR("TYPE_SFIXED32"), UPB_VALUE_INIT_INT32(15), NULL},
  3956. {UPB_TABKEY_STR("TYPE_FIXED32"), UPB_VALUE_INIT_INT32(7), NULL},
  3957. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3958. {UPB_TABKEY_STR("TYPE_MESSAGE"), UPB_VALUE_INIT_INT32(11), &strentries[194]},
  3959. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3960. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3961. {UPB_TABKEY_STR("TYPE_INT64"), UPB_VALUE_INIT_INT32(3), &strentries[191]},
  3962. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3963. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3964. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3965. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3966. {UPB_TABKEY_STR("TYPE_ENUM"), UPB_VALUE_INIT_INT32(14), NULL},
  3967. {UPB_TABKEY_STR("TYPE_UINT32"), UPB_VALUE_INIT_INT32(13), NULL},
  3968. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3969. {UPB_TABKEY_STR("TYPE_UINT64"), UPB_VALUE_INIT_INT32(4), &strentries[190]},
  3970. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3971. {UPB_TABKEY_STR("TYPE_SFIXED64"), UPB_VALUE_INIT_INT32(16), NULL},
  3972. {UPB_TABKEY_STR("TYPE_BYTES"), UPB_VALUE_INIT_INT32(12), NULL},
  3973. {UPB_TABKEY_STR("TYPE_SINT64"), UPB_VALUE_INIT_INT32(18), NULL},
  3974. {UPB_TABKEY_STR("TYPE_BOOL"), UPB_VALUE_INIT_INT32(8), NULL},
  3975. {UPB_TABKEY_STR("TYPE_GROUP"), UPB_VALUE_INIT_INT32(10), NULL},
  3976. {UPB_TABKEY_STR("TYPE_SINT32"), UPB_VALUE_INIT_INT32(17), NULL},
  3977. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3978. {UPB_TABKEY_STR("CORD"), UPB_VALUE_INIT_INT32(1), NULL},
  3979. {UPB_TABKEY_STR("STRING"), UPB_VALUE_INIT_INT32(0), &strentries[197]},
  3980. {UPB_TABKEY_STR("STRING_PIECE"), UPB_VALUE_INIT_INT32(2), NULL},
  3981. {UPB_TABKEY_STR("CODE_SIZE"), UPB_VALUE_INIT_INT32(2), NULL},
  3982. {UPB_TABKEY_STR("SPEED"), UPB_VALUE_INIT_INT32(1), &strentries[203]},
  3983. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3984. {UPB_TABKEY_STR("LITE_RUNTIME"), UPB_VALUE_INIT_INT32(3), NULL},
  3985. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3986. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3987. {UPB_TABKEY_STR("google.protobuf.SourceCodeInfo.Location"), UPB_VALUE_INIT_CONSTPTR(&msgs[17]), NULL},
  3988. {UPB_TABKEY_STR("google.protobuf.UninterpretedOption"), UPB_VALUE_INIT_CONSTPTR(&msgs[18]), NULL},
  3989. {UPB_TABKEY_STR("google.protobuf.FileDescriptorProto"), UPB_VALUE_INIT_CONSTPTR(&msgs[8]), NULL},
  3990. {UPB_TABKEY_STR("google.protobuf.MethodDescriptorProto"), UPB_VALUE_INIT_CONSTPTR(&msgs[12]), NULL},
  3991. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3992. {UPB_TABKEY_STR("google.protobuf.EnumValueOptions"), UPB_VALUE_INIT_CONSTPTR(&msgs[5]), NULL},
  3993. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3994. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3995. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3996. {UPB_TABKEY_STR("google.protobuf.DescriptorProto"), UPB_VALUE_INIT_CONSTPTR(&msgs[0]), &strentries[228]},
  3997. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  3998. {UPB_TABKEY_STR("google.protobuf.SourceCodeInfo"), UPB_VALUE_INIT_CONSTPTR(&msgs[16]), NULL},
  3999. {UPB_TABKEY_STR("google.protobuf.FieldDescriptorProto.Type"), UPB_VALUE_INIT_CONSTPTR(&enums[1]), NULL},
  4000. {UPB_TABKEY_STR("google.protobuf.DescriptorProto.ExtensionRange"), UPB_VALUE_INIT_CONSTPTR(&msgs[1]), NULL},
  4001. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4002. {UPB_TABKEY_STR("google.protobuf.EnumValueDescriptorProto"), UPB_VALUE_INIT_CONSTPTR(&msgs[4]), NULL},
  4003. {UPB_TABKEY_STR("google.protobuf.FieldOptions"), UPB_VALUE_INIT_CONSTPTR(&msgs[7]), NULL},
  4004. {UPB_TABKEY_STR("google.protobuf.FileOptions"), UPB_VALUE_INIT_CONSTPTR(&msgs[10]), NULL},
  4005. {UPB_TABKEY_STR("google.protobuf.EnumDescriptorProto"), UPB_VALUE_INIT_CONSTPTR(&msgs[2]), &strentries[233]},
  4006. {UPB_TABKEY_STR("google.protobuf.FieldDescriptorProto.Label"), UPB_VALUE_INIT_CONSTPTR(&enums[0]), NULL},
  4007. {UPB_TABKEY_STR("google.protobuf.ServiceDescriptorProto"), UPB_VALUE_INIT_CONSTPTR(&msgs[14]), NULL},
  4008. {UPB_TABKEY_STR("google.protobuf.FieldOptions.CType"), UPB_VALUE_INIT_CONSTPTR(&enums[2]), &strentries[229]},
  4009. {UPB_TABKEY_STR("google.protobuf.FileDescriptorSet"), UPB_VALUE_INIT_CONSTPTR(&msgs[9]), &strentries[235]},
  4010. {UPB_TABKEY_STR("google.protobuf.EnumOptions"), UPB_VALUE_INIT_CONSTPTR(&msgs[3]), NULL},
  4011. {UPB_TABKEY_STR("google.protobuf.FieldDescriptorProto"), UPB_VALUE_INIT_CONSTPTR(&msgs[6]), NULL},
  4012. {UPB_TABKEY_STR("google.protobuf.FileOptions.OptimizeMode"), UPB_VALUE_INIT_CONSTPTR(&enums[3]), &strentries[221]},
  4013. {UPB_TABKEY_STR("google.protobuf.ServiceOptions"), UPB_VALUE_INIT_CONSTPTR(&msgs[15]), NULL},
  4014. {UPB_TABKEY_STR("google.protobuf.MessageOptions"), UPB_VALUE_INIT_CONSTPTR(&msgs[11]), NULL},
  4015. {UPB_TABKEY_STR("google.protobuf.MethodOptions"), UPB_VALUE_INIT_CONSTPTR(&msgs[13]), &strentries[226]},
  4016. {UPB_TABKEY_STR("google.protobuf.UninterpretedOption.NamePart"), UPB_VALUE_INIT_CONSTPTR(&msgs[19]), NULL},
  4017. };
  4018. static const upb_tabent intentries[14] = {
  4019. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4020. {UPB_TABKEY_NUM(999), UPB_VALUE_INIT_CONSTPTR(&fields[73]), NULL},
  4021. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4022. {UPB_TABKEY_NUM(999), UPB_VALUE_INIT_CONSTPTR(&fields[71]), NULL},
  4023. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4024. {UPB_TABKEY_NUM(999), UPB_VALUE_INIT_CONSTPTR(&fields[77]), NULL},
  4025. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4026. {UPB_TABKEY_NUM(999), UPB_VALUE_INIT_CONSTPTR(&fields[75]), NULL},
  4027. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4028. {UPB_TABKEY_NUM(999), UPB_VALUE_INIT_CONSTPTR(&fields[76]), NULL},
  4029. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4030. {UPB_TABKEY_NUM(999), UPB_VALUE_INIT_CONSTPTR(&fields[74]), NULL},
  4031. {UPB_TABKEY_NONE, UPB__VALUE_INIT_NONE, NULL},
  4032. {UPB_TABKEY_NUM(999), UPB_VALUE_INIT_CONSTPTR(&fields[72]), NULL},
  4033. };
  4034. static const _upb_value arrays[232] = {
  4035. UPB_ARRAY_EMPTYENT,
  4036. UPB_VALUE_INIT_CONSTPTR(&fields[38]),
  4037. UPB_VALUE_INIT_CONSTPTR(&fields[16]),
  4038. UPB_VALUE_INIT_CONSTPTR(&fields[44]),
  4039. UPB_VALUE_INIT_CONSTPTR(&fields[9]),
  4040. UPB_VALUE_INIT_CONSTPTR(&fields[15]),
  4041. UPB_VALUE_INIT_CONSTPTR(&fields[14]),
  4042. UPB_VALUE_INIT_CONSTPTR(&fields[49]),
  4043. UPB_ARRAY_EMPTYENT,
  4044. UPB_VALUE_INIT_CONSTPTR(&fields[66]),
  4045. UPB_VALUE_INIT_CONSTPTR(&fields[8]),
  4046. UPB_ARRAY_EMPTYENT,
  4047. UPB_VALUE_INIT_CONSTPTR(&fields[40]),
  4048. UPB_VALUE_INIT_CONSTPTR(&fields[78]),
  4049. UPB_VALUE_INIT_CONSTPTR(&fields[50]),
  4050. UPB_ARRAY_EMPTYENT,
  4051. UPB_ARRAY_EMPTYENT,
  4052. UPB_VALUE_INIT_CONSTPTR(&fields[1]),
  4053. UPB_ARRAY_EMPTYENT,
  4054. UPB_ARRAY_EMPTYENT,
  4055. UPB_ARRAY_EMPTYENT,
  4056. UPB_ARRAY_EMPTYENT,
  4057. UPB_ARRAY_EMPTYENT,
  4058. UPB_ARRAY_EMPTYENT,
  4059. UPB_VALUE_INIT_CONSTPTR(&fields[37]),
  4060. UPB_VALUE_INIT_CONSTPTR(&fields[47]),
  4061. UPB_VALUE_INIT_CONSTPTR(&fields[52]),
  4062. UPB_ARRAY_EMPTYENT,
  4063. UPB_ARRAY_EMPTYENT,
  4064. UPB_ARRAY_EMPTYENT,
  4065. UPB_ARRAY_EMPTYENT,
  4066. UPB_ARRAY_EMPTYENT,
  4067. UPB_VALUE_INIT_CONSTPTR(&fields[41]),
  4068. UPB_VALUE_INIT_CONSTPTR(&fields[12]),
  4069. UPB_VALUE_INIT_CONSTPTR(&fields[46]),
  4070. UPB_VALUE_INIT_CONSTPTR(&fields[27]),
  4071. UPB_VALUE_INIT_CONSTPTR(&fields[69]),
  4072. UPB_VALUE_INIT_CONSTPTR(&fields[70]),
  4073. UPB_VALUE_INIT_CONSTPTR(&fields[4]),
  4074. UPB_VALUE_INIT_CONSTPTR(&fields[51]),
  4075. UPB_ARRAY_EMPTYENT,
  4076. UPB_VALUE_INIT_CONSTPTR(&fields[3]),
  4077. UPB_VALUE_INIT_CONSTPTR(&fields[58]),
  4078. UPB_VALUE_INIT_CONSTPTR(&fields[6]),
  4079. UPB_ARRAY_EMPTYENT,
  4080. UPB_VALUE_INIT_CONSTPTR(&fields[28]),
  4081. UPB_ARRAY_EMPTYENT,
  4082. UPB_ARRAY_EMPTYENT,
  4083. UPB_ARRAY_EMPTYENT,
  4084. UPB_VALUE_INIT_CONSTPTR(&fields[11]),
  4085. UPB_VALUE_INIT_CONSTPTR(&fields[79]),
  4086. UPB_ARRAY_EMPTYENT,
  4087. UPB_ARRAY_EMPTYENT,
  4088. UPB_ARRAY_EMPTYENT,
  4089. UPB_ARRAY_EMPTYENT,
  4090. UPB_ARRAY_EMPTYENT,
  4091. UPB_ARRAY_EMPTYENT,
  4092. UPB_ARRAY_EMPTYENT,
  4093. UPB_ARRAY_EMPTYENT,
  4094. UPB_ARRAY_EMPTYENT,
  4095. UPB_ARRAY_EMPTYENT,
  4096. UPB_ARRAY_EMPTYENT,
  4097. UPB_ARRAY_EMPTYENT,
  4098. UPB_ARRAY_EMPTYENT,
  4099. UPB_ARRAY_EMPTYENT,
  4100. UPB_ARRAY_EMPTYENT,
  4101. UPB_ARRAY_EMPTYENT,
  4102. UPB_ARRAY_EMPTYENT,
  4103. UPB_ARRAY_EMPTYENT,
  4104. UPB_ARRAY_EMPTYENT,
  4105. UPB_ARRAY_EMPTYENT,
  4106. UPB_ARRAY_EMPTYENT,
  4107. UPB_ARRAY_EMPTYENT,
  4108. UPB_VALUE_INIT_CONSTPTR(&fields[34]),
  4109. UPB_VALUE_INIT_CONSTPTR(&fields[57]),
  4110. UPB_VALUE_INIT_CONSTPTR(&fields[5]),
  4111. UPB_VALUE_INIT_CONSTPTR(&fields[32]),
  4112. UPB_VALUE_INIT_CONSTPTR(&fields[10]),
  4113. UPB_VALUE_INIT_CONSTPTR(&fields[63]),
  4114. UPB_VALUE_INIT_CONSTPTR(&fields[13]),
  4115. UPB_VALUE_INIT_CONSTPTR(&fields[53]),
  4116. UPB_VALUE_INIT_CONSTPTR(&fields[64]),
  4117. UPB_VALUE_INIT_CONSTPTR(&fields[61]),
  4118. UPB_VALUE_INIT_CONSTPTR(&fields[80]),
  4119. UPB_ARRAY_EMPTYENT,
  4120. UPB_VALUE_INIT_CONSTPTR(&fields[17]),
  4121. UPB_ARRAY_EMPTYENT,
  4122. UPB_VALUE_INIT_CONSTPTR(&fields[26]),
  4123. UPB_ARRAY_EMPTYENT,
  4124. UPB_ARRAY_EMPTYENT,
  4125. UPB_ARRAY_EMPTYENT,
  4126. UPB_ARRAY_EMPTYENT,
  4127. UPB_ARRAY_EMPTYENT,
  4128. UPB_ARRAY_EMPTYENT,
  4129. UPB_VALUE_INIT_CONSTPTR(&fields[25]),
  4130. UPB_VALUE_INIT_CONSTPTR(&fields[48]),
  4131. UPB_VALUE_INIT_CONSTPTR(&fields[24]),
  4132. UPB_VALUE_INIT_CONSTPTR(&fields[18]),
  4133. UPB_ARRAY_EMPTYENT,
  4134. UPB_ARRAY_EMPTYENT,
  4135. UPB_ARRAY_EMPTYENT,
  4136. UPB_ARRAY_EMPTYENT,
  4137. UPB_VALUE_INIT_CONSTPTR(&fields[2]),
  4138. UPB_VALUE_INIT_CONSTPTR(&fields[23]),
  4139. UPB_VALUE_INIT_CONSTPTR(&fields[62]),
  4140. UPB_ARRAY_EMPTYENT,
  4141. UPB_VALUE_INIT_CONSTPTR(&fields[22]),
  4142. UPB_ARRAY_EMPTYENT,
  4143. UPB_ARRAY_EMPTYENT,
  4144. UPB_ARRAY_EMPTYENT,
  4145. UPB_ARRAY_EMPTYENT,
  4146. UPB_ARRAY_EMPTYENT,
  4147. UPB_ARRAY_EMPTYENT,
  4148. UPB_ARRAY_EMPTYENT,
  4149. UPB_ARRAY_EMPTYENT,
  4150. UPB_ARRAY_EMPTYENT,
  4151. UPB_ARRAY_EMPTYENT,
  4152. UPB_ARRAY_EMPTYENT,
  4153. UPB_ARRAY_EMPTYENT,
  4154. UPB_ARRAY_EMPTYENT,
  4155. UPB_ARRAY_EMPTYENT,
  4156. UPB_ARRAY_EMPTYENT,
  4157. UPB_ARRAY_EMPTYENT,
  4158. UPB_ARRAY_EMPTYENT,
  4159. UPB_ARRAY_EMPTYENT,
  4160. UPB_ARRAY_EMPTYENT,
  4161. UPB_ARRAY_EMPTYENT,
  4162. UPB_ARRAY_EMPTYENT,
  4163. UPB_ARRAY_EMPTYENT,
  4164. UPB_ARRAY_EMPTYENT,
  4165. UPB_ARRAY_EMPTYENT,
  4166. UPB_ARRAY_EMPTYENT,
  4167. UPB_ARRAY_EMPTYENT,
  4168. UPB_ARRAY_EMPTYENT,
  4169. UPB_ARRAY_EMPTYENT,
  4170. UPB_ARRAY_EMPTYENT,
  4171. UPB_ARRAY_EMPTYENT,
  4172. UPB_ARRAY_EMPTYENT,
  4173. UPB_ARRAY_EMPTYENT,
  4174. UPB_ARRAY_EMPTYENT,
  4175. UPB_ARRAY_EMPTYENT,
  4176. UPB_ARRAY_EMPTYENT,
  4177. UPB_ARRAY_EMPTYENT,
  4178. UPB_ARRAY_EMPTYENT,
  4179. UPB_ARRAY_EMPTYENT,
  4180. UPB_ARRAY_EMPTYENT,
  4181. UPB_ARRAY_EMPTYENT,
  4182. UPB_ARRAY_EMPTYENT,
  4183. UPB_ARRAY_EMPTYENT,
  4184. UPB_ARRAY_EMPTYENT,
  4185. UPB_ARRAY_EMPTYENT,
  4186. UPB_VALUE_INIT_CONSTPTR(&fields[31]),
  4187. UPB_VALUE_INIT_CONSTPTR(&fields[45]),
  4188. UPB_ARRAY_EMPTYENT,
  4189. UPB_ARRAY_EMPTYENT,
  4190. UPB_ARRAY_EMPTYENT,
  4191. UPB_ARRAY_EMPTYENT,
  4192. UPB_ARRAY_EMPTYENT,
  4193. UPB_ARRAY_EMPTYENT,
  4194. UPB_ARRAY_EMPTYENT,
  4195. UPB_ARRAY_EMPTYENT,
  4196. UPB_ARRAY_EMPTYENT,
  4197. UPB_ARRAY_EMPTYENT,
  4198. UPB_ARRAY_EMPTYENT,
  4199. UPB_ARRAY_EMPTYENT,
  4200. UPB_ARRAY_EMPTYENT,
  4201. UPB_ARRAY_EMPTYENT,
  4202. UPB_VALUE_INIT_CONSTPTR(&fields[39]),
  4203. UPB_VALUE_INIT_CONSTPTR(&fields[20]),
  4204. UPB_VALUE_INIT_CONSTPTR(&fields[56]),
  4205. UPB_VALUE_INIT_CONSTPTR(&fields[55]),
  4206. UPB_ARRAY_EMPTYENT,
  4207. UPB_ARRAY_EMPTYENT,
  4208. UPB_ARRAY_EMPTYENT,
  4209. UPB_ARRAY_EMPTYENT,
  4210. UPB_ARRAY_EMPTYENT,
  4211. UPB_VALUE_INIT_CONSTPTR(&fields[35]),
  4212. UPB_VALUE_INIT_CONSTPTR(&fields[33]),
  4213. UPB_VALUE_INIT_CONSTPTR(&fields[54]),
  4214. UPB_ARRAY_EMPTYENT,
  4215. UPB_ARRAY_EMPTYENT,
  4216. UPB_ARRAY_EMPTYENT,
  4217. UPB_ARRAY_EMPTYENT,
  4218. UPB_ARRAY_EMPTYENT,
  4219. UPB_VALUE_INIT_CONSTPTR(&fields[30]),
  4220. UPB_ARRAY_EMPTYENT,
  4221. UPB_VALUE_INIT_CONSTPTR(&fields[59]),
  4222. UPB_VALUE_INIT_CONSTPTR(&fields[65]),
  4223. UPB_VALUE_INIT_CONSTPTR(&fields[29]),
  4224. UPB_VALUE_INIT_CONSTPTR(&fields[68]),
  4225. UPB_ARRAY_EMPTYENT,
  4226. UPB_ARRAY_EMPTYENT,
  4227. UPB_VALUE_INIT_CONSTPTR(&fields[36]),
  4228. UPB_VALUE_INIT_CONSTPTR(&fields[19]),
  4229. UPB_VALUE_INIT_CONSTPTR(&fields[60]),
  4230. UPB_VALUE_INIT_CONSTPTR(&fields[43]),
  4231. UPB_VALUE_INIT_CONSTPTR(&fields[7]),
  4232. UPB_VALUE_INIT_CONSTPTR(&fields[67]),
  4233. UPB_VALUE_INIT_CONSTPTR(&fields[0]),
  4234. UPB_ARRAY_EMPTYENT,
  4235. UPB_VALUE_INIT_CONSTPTR(&fields[42]),
  4236. UPB_VALUE_INIT_CONSTPTR(&fields[21]),
  4237. UPB_ARRAY_EMPTYENT,
  4238. UPB_VALUE_INIT_CONSTPTR("LABEL_OPTIONAL"),
  4239. UPB_VALUE_INIT_CONSTPTR("LABEL_REQUIRED"),
  4240. UPB_VALUE_INIT_CONSTPTR("LABEL_REPEATED"),
  4241. UPB_ARRAY_EMPTYENT,
  4242. UPB_VALUE_INIT_CONSTPTR("TYPE_DOUBLE"),
  4243. UPB_VALUE_INIT_CONSTPTR("TYPE_FLOAT"),
  4244. UPB_VALUE_INIT_CONSTPTR("TYPE_INT64"),
  4245. UPB_VALUE_INIT_CONSTPTR("TYPE_UINT64"),
  4246. UPB_VALUE_INIT_CONSTPTR("TYPE_INT32"),
  4247. UPB_VALUE_INIT_CONSTPTR("TYPE_FIXED64"),
  4248. UPB_VALUE_INIT_CONSTPTR("TYPE_FIXED32"),
  4249. UPB_VALUE_INIT_CONSTPTR("TYPE_BOOL"),
  4250. UPB_VALUE_INIT_CONSTPTR("TYPE_STRING"),
  4251. UPB_VALUE_INIT_CONSTPTR("TYPE_GROUP"),
  4252. UPB_VALUE_INIT_CONSTPTR("TYPE_MESSAGE"),
  4253. UPB_VALUE_INIT_CONSTPTR("TYPE_BYTES"),
  4254. UPB_VALUE_INIT_CONSTPTR("TYPE_UINT32"),
  4255. UPB_VALUE_INIT_CONSTPTR("TYPE_ENUM"),
  4256. UPB_VALUE_INIT_CONSTPTR("TYPE_SFIXED32"),
  4257. UPB_VALUE_INIT_CONSTPTR("TYPE_SFIXED64"),
  4258. UPB_VALUE_INIT_CONSTPTR("TYPE_SINT32"),
  4259. UPB_VALUE_INIT_CONSTPTR("TYPE_SINT64"),
  4260. UPB_VALUE_INIT_CONSTPTR("STRING"),
  4261. UPB_VALUE_INIT_CONSTPTR("CORD"),
  4262. UPB_VALUE_INIT_CONSTPTR("STRING_PIECE"),
  4263. UPB_ARRAY_EMPTYENT,
  4264. UPB_VALUE_INIT_CONSTPTR("SPEED"),
  4265. UPB_VALUE_INIT_CONSTPTR("CODE_SIZE"),
  4266. UPB_VALUE_INIT_CONSTPTR("LITE_RUNTIME"),
  4267. };
  4268. static const upb_symtab symtab = UPB_SYMTAB_INIT(UPB_STRTABLE_INIT(24, 31, UPB_CTYPE_PTR, 5, &strentries[204]), &reftables[210], &reftables[211]);
  4269. const upb_symtab *upbdefs_google_protobuf_descriptor(const void *owner) {
  4270. upb_symtab_ref(&symtab, owner);
  4271. return &symtab;
  4272. }
  4273. #ifdef UPB_DEBUG_REFS
  4274. static upb_inttable reftables[212] = {
  4275. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4276. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4277. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4278. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4279. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4280. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4281. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4282. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4283. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4284. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4285. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4286. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4287. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4288. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4289. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4290. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4291. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4292. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4293. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4294. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4295. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4296. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4297. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4298. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4299. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4300. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4301. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4302. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4303. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4304. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4305. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4306. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4307. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4308. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4309. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4310. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4311. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4312. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4313. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4314. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4315. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4316. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4317. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4318. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4319. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4320. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4321. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4322. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4323. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4324. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4325. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4326. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4327. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4328. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4329. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4330. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4331. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4332. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4333. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4334. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4335. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4336. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4337. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4338. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4339. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4340. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4341. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4342. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4343. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4344. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4345. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4346. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4347. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4348. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4349. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4350. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4351. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4352. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4353. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4354. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4355. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4356. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4357. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4358. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4359. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4360. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4361. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4362. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4363. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4364. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4365. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4366. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4367. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4368. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4369. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4370. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4371. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4372. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4373. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4374. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4375. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4376. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4377. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4378. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4379. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4380. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4381. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4382. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4383. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4384. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4385. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4386. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4387. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4388. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4389. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4390. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4391. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4392. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4393. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4394. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4395. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4396. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4397. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4398. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4399. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4400. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4401. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4402. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4403. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4404. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4405. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4406. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4407. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4408. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4409. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4410. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4411. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4412. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4413. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4414. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4415. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4416. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4417. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4418. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4419. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4420. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4421. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4422. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4423. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4424. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4425. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4426. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4427. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4428. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4429. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4430. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4431. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4432. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4433. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4434. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4435. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4436. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4437. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4438. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4439. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4440. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4441. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4442. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4443. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4444. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4445. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4446. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4447. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4448. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4449. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4450. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4451. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4452. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4453. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4454. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4455. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4456. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4457. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4458. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4459. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4460. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4461. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4462. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4463. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4464. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4465. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4466. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4467. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4468. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4469. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4470. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4471. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4472. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4473. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4474. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4475. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4476. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4477. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4478. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4479. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4480. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4481. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4482. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4483. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4484. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4485. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4486. UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
  4487. };
  4488. #endif
  4489. /*
  4490. * upb - a minimalist implementation of protocol buffers.
  4491. *
  4492. * Copyright (c) 2008-2009 Google Inc. See LICENSE for details.
  4493. * Author: Josh Haberman <jhaberman@gmail.com>
  4494. *
  4495. * XXX: The routines in this file that consume a string do not currently
  4496. * support having the string span buffers. In the future, as upb_sink and
  4497. * its buffering/sharing functionality evolve there should be an easy and
  4498. * idiomatic way of correctly handling this case. For now, we accept this
  4499. * limitation since we currently only parse descriptors from single strings.
  4500. */
  4501. #include <errno.h>
  4502. #include <stdlib.h>
  4503. #include <string.h>
  4504. static char *upb_strndup(const char *buf, size_t n) {
  4505. char *ret = malloc(n + 1);
  4506. if (!ret) return NULL;
  4507. memcpy(ret, buf, n);
  4508. ret[n] = '\0';
  4509. return ret;
  4510. }
  4511. // Returns a newly allocated string that joins input strings together, for
  4512. // example:
  4513. // join("Foo.Bar", "Baz") -> "Foo.Bar.Baz"
  4514. // join("", "Baz") -> "Baz"
  4515. // Caller owns a ref on the returned string.
  4516. static char *upb_join(const char *base, const char *name) {
  4517. if (!base || strlen(base) == 0) {
  4518. return upb_strdup(name);
  4519. } else {
  4520. char *ret = malloc(strlen(base) + strlen(name) + 2);
  4521. ret[0] = '\0';
  4522. strcat(ret, base);
  4523. strcat(ret, ".");
  4524. strcat(ret, name);
  4525. return ret;
  4526. }
  4527. }
  4528. /* upb_deflist ****************************************************************/
  4529. void upb_deflist_init(upb_deflist *l) {
  4530. l->size = 0;
  4531. l->defs = NULL;
  4532. l->len = 0;
  4533. l->owned = true;
  4534. }
  4535. void upb_deflist_uninit(upb_deflist *l) {
  4536. if (l->owned)
  4537. for(size_t i = 0; i < l->len; i++)
  4538. upb_def_unref(l->defs[i], l);
  4539. free(l->defs);
  4540. }
  4541. bool upb_deflist_push(upb_deflist *l, upb_def *d) {
  4542. if(++l->len >= l->size) {
  4543. size_t new_size = UPB_MAX(l->size, 4);
  4544. new_size *= 2;
  4545. l->defs = realloc(l->defs, new_size * sizeof(void *));
  4546. if (!l->defs) return false;
  4547. l->size = new_size;
  4548. }
  4549. l->defs[l->len - 1] = d;
  4550. return true;
  4551. }
  4552. void upb_deflist_donaterefs(upb_deflist *l, void *owner) {
  4553. assert(l->owned);
  4554. for (size_t i = 0; i < l->len; i++)
  4555. upb_def_donateref(l->defs[i], l, owner);
  4556. l->owned = false;
  4557. }
  4558. static upb_def *upb_deflist_last(upb_deflist *l) {
  4559. return l->defs[l->len-1];
  4560. }
  4561. // Qualify the defname for all defs starting with offset "start" with "str".
  4562. static void upb_deflist_qualify(upb_deflist *l, char *str, int32_t start) {
  4563. for (uint32_t i = start; i < l->len; i++) {
  4564. upb_def *def = l->defs[i];
  4565. char *name = upb_join(str, upb_def_fullname(def));
  4566. upb_def_setfullname(def, name, NULL);
  4567. free(name);
  4568. }
  4569. }
  4570. /* upb_descreader ************************************************************/
  4571. void upb_descreader_init(upb_descreader *r, const upb_handlers *handlers,
  4572. upb_status *status) {
  4573. UPB_UNUSED(status);
  4574. upb_deflist_init(&r->defs);
  4575. upb_sink_reset(upb_descreader_input(r), handlers, r);
  4576. r->stack_len = 0;
  4577. r->name = NULL;
  4578. r->default_string = NULL;
  4579. }
  4580. void upb_descreader_uninit(upb_descreader *r) {
  4581. free(r->name);
  4582. upb_deflist_uninit(&r->defs);
  4583. free(r->default_string);
  4584. while (r->stack_len > 0) {
  4585. upb_descreader_frame *f = &r->stack[--r->stack_len];
  4586. free(f->name);
  4587. }
  4588. }
  4589. upb_def **upb_descreader_getdefs(upb_descreader *r, void *owner, int *n) {
  4590. *n = r->defs.len;
  4591. upb_deflist_donaterefs(&r->defs, owner);
  4592. return r->defs.defs;
  4593. }
  4594. upb_sink *upb_descreader_input(upb_descreader *r) {
  4595. return &r->sink;
  4596. }
  4597. static upb_msgdef *upb_descreader_top(upb_descreader *r) {
  4598. assert(r->stack_len > 1);
  4599. int index = r->stack[r->stack_len-1].start - 1;
  4600. assert(index >= 0);
  4601. return upb_downcast_msgdef_mutable(r->defs.defs[index]);
  4602. }
  4603. static upb_def *upb_descreader_last(upb_descreader *r) {
  4604. return upb_deflist_last(&r->defs);
  4605. }
  4606. // Start/end handlers for FileDescriptorProto and DescriptorProto (the two
  4607. // entities that have names and can contain sub-definitions.
  4608. void upb_descreader_startcontainer(upb_descreader *r) {
  4609. upb_descreader_frame *f = &r->stack[r->stack_len++];
  4610. f->start = r->defs.len;
  4611. f->name = NULL;
  4612. }
  4613. void upb_descreader_endcontainer(upb_descreader *r) {
  4614. upb_descreader_frame *f = &r->stack[--r->stack_len];
  4615. upb_deflist_qualify(&r->defs, f->name, f->start);
  4616. free(f->name);
  4617. f->name = NULL;
  4618. }
  4619. void upb_descreader_setscopename(upb_descreader *r, char *str) {
  4620. upb_descreader_frame *f = &r->stack[r->stack_len-1];
  4621. free(f->name);
  4622. f->name = str;
  4623. }
  4624. // Handlers for google.protobuf.FileDescriptorProto.
  4625. static bool file_startmsg(void *r, const void *hd) {
  4626. UPB_UNUSED(hd);
  4627. upb_descreader_startcontainer(r);
  4628. return true;
  4629. }
  4630. static bool file_endmsg(void *closure, const void *hd, upb_status *status) {
  4631. UPB_UNUSED(hd);
  4632. UPB_UNUSED(status);
  4633. upb_descreader *r = closure;
  4634. upb_descreader_endcontainer(r);
  4635. return true;
  4636. }
  4637. static size_t file_onpackage(void *closure, const void *hd, const char *buf,
  4638. size_t n, const upb_bufhandle *handle) {
  4639. UPB_UNUSED(hd);
  4640. UPB_UNUSED(handle);
  4641. upb_descreader *r = closure;
  4642. // XXX: see comment at the top of the file.
  4643. upb_descreader_setscopename(r, upb_strndup(buf, n));
  4644. return n;
  4645. }
  4646. // Handlers for google.protobuf.EnumValueDescriptorProto.
  4647. static bool enumval_startmsg(void *closure, const void *hd) {
  4648. UPB_UNUSED(hd);
  4649. upb_descreader *r = closure;
  4650. r->saw_number = false;
  4651. r->saw_name = false;
  4652. return true;
  4653. }
  4654. static size_t enumval_onname(void *closure, const void *hd, const char *buf,
  4655. size_t n, const upb_bufhandle *handle) {
  4656. UPB_UNUSED(hd);
  4657. UPB_UNUSED(handle);
  4658. upb_descreader *r = closure;
  4659. // XXX: see comment at the top of the file.
  4660. free(r->name);
  4661. r->name = upb_strndup(buf, n);
  4662. r->saw_name = true;
  4663. return n;
  4664. }
  4665. static bool enumval_onnumber(void *closure, const void *hd, int32_t val) {
  4666. UPB_UNUSED(hd);
  4667. upb_descreader *r = closure;
  4668. r->number = val;
  4669. r->saw_number = true;
  4670. return true;
  4671. }
  4672. static bool enumval_endmsg(void *closure, const void *hd, upb_status *status) {
  4673. UPB_UNUSED(hd);
  4674. upb_descreader *r = closure;
  4675. if(!r->saw_number || !r->saw_name) {
  4676. upb_status_seterrmsg(status, "Enum value missing name or number.");
  4677. return false;
  4678. }
  4679. upb_enumdef *e = upb_downcast_enumdef_mutable(upb_descreader_last(r));
  4680. upb_enumdef_addval(e, r->name, r->number, status);
  4681. free(r->name);
  4682. r->name = NULL;
  4683. return true;
  4684. }
  4685. // Handlers for google.protobuf.EnumDescriptorProto.
  4686. static bool enum_startmsg(void *closure, const void *hd) {
  4687. UPB_UNUSED(hd);
  4688. upb_descreader *r = closure;
  4689. upb_deflist_push(&r->defs, UPB_UPCAST(upb_enumdef_new(&r->defs)));
  4690. return true;
  4691. }
  4692. static bool enum_endmsg(void *closure, const void *hd, upb_status *status) {
  4693. UPB_UNUSED(hd);
  4694. upb_descreader *r = closure;
  4695. upb_enumdef *e = upb_downcast_enumdef_mutable(upb_descreader_last(r));
  4696. if (upb_def_fullname(upb_descreader_last(r)) == NULL) {
  4697. upb_status_seterrmsg(status, "Enum had no name.");
  4698. return false;
  4699. }
  4700. if (upb_enumdef_numvals(e) == 0) {
  4701. upb_status_seterrmsg(status, "Enum had no values.");
  4702. return false;
  4703. }
  4704. return true;
  4705. }
  4706. static size_t enum_onname(void *closure, const void *hd, const char *buf,
  4707. size_t n, const upb_bufhandle *handle) {
  4708. UPB_UNUSED(hd);
  4709. UPB_UNUSED(handle);
  4710. upb_descreader *r = closure;
  4711. // XXX: see comment at the top of the file.
  4712. char *fullname = upb_strndup(buf, n);
  4713. upb_def_setfullname(upb_descreader_last(r), fullname, NULL);
  4714. free(fullname);
  4715. return n;
  4716. }
  4717. // Handlers for google.protobuf.FieldDescriptorProto
  4718. static bool field_startmsg(void *closure, const void *hd) {
  4719. UPB_UNUSED(hd);
  4720. upb_descreader *r = closure;
  4721. r->f = upb_fielddef_new(&r->defs);
  4722. free(r->default_string);
  4723. r->default_string = NULL;
  4724. // fielddefs default to packed, but descriptors default to non-packed.
  4725. upb_fielddef_setpacked(r->f, false);
  4726. return true;
  4727. }
  4728. // Converts the default value in string "str" into "d". Passes a ref on str.
  4729. // Returns true on success.
  4730. static bool parse_default(char *str, upb_fielddef *f) {
  4731. bool success = true;
  4732. char *end;
  4733. switch (upb_fielddef_type(f)) {
  4734. case UPB_TYPE_INT32: {
  4735. long val = strtol(str, &end, 0);
  4736. if (val > INT32_MAX || val < INT32_MIN || errno == ERANGE || *end)
  4737. success = false;
  4738. else
  4739. upb_fielddef_setdefaultint32(f, val);
  4740. break;
  4741. }
  4742. case UPB_TYPE_INT64: {
  4743. long long val = strtoll(str, &end, 0);
  4744. if (val > INT64_MAX || val < INT64_MIN || errno == ERANGE || *end)
  4745. success = false;
  4746. else
  4747. upb_fielddef_setdefaultint64(f, val);
  4748. break;
  4749. }
  4750. case UPB_TYPE_UINT32: {
  4751. long val = strtoul(str, &end, 0);
  4752. if (val > UINT32_MAX || errno == ERANGE || *end)
  4753. success = false;
  4754. else
  4755. upb_fielddef_setdefaultuint32(f, val);
  4756. break;
  4757. }
  4758. case UPB_TYPE_UINT64: {
  4759. unsigned long long val = strtoull(str, &end, 0);
  4760. if (val > UINT64_MAX || errno == ERANGE || *end)
  4761. success = false;
  4762. else
  4763. upb_fielddef_setdefaultuint64(f, val);
  4764. break;
  4765. }
  4766. case UPB_TYPE_DOUBLE: {
  4767. double val = strtod(str, &end);
  4768. if (errno == ERANGE || *end)
  4769. success = false;
  4770. else
  4771. upb_fielddef_setdefaultdouble(f, val);
  4772. break;
  4773. }
  4774. case UPB_TYPE_FLOAT: {
  4775. float val = strtof(str, &end);
  4776. if (errno == ERANGE || *end)
  4777. success = false;
  4778. else
  4779. upb_fielddef_setdefaultfloat(f, val);
  4780. break;
  4781. }
  4782. case UPB_TYPE_BOOL: {
  4783. if (strcmp(str, "false") == 0)
  4784. upb_fielddef_setdefaultbool(f, false);
  4785. else if (strcmp(str, "true") == 0)
  4786. upb_fielddef_setdefaultbool(f, true);
  4787. else
  4788. success = false;
  4789. break;
  4790. }
  4791. default: abort();
  4792. }
  4793. return success;
  4794. }
  4795. static bool field_endmsg(void *closure, const void *hd, upb_status *status) {
  4796. UPB_UNUSED(hd);
  4797. upb_descreader *r = closure;
  4798. upb_fielddef *f = r->f;
  4799. // TODO: verify that all required fields were present.
  4800. assert(upb_fielddef_number(f) != 0);
  4801. assert(upb_fielddef_name(f) != NULL);
  4802. assert((upb_fielddef_subdefname(f) != NULL) == upb_fielddef_hassubdef(f));
  4803. if (r->default_string) {
  4804. if (upb_fielddef_issubmsg(f)) {
  4805. upb_status_seterrmsg(status, "Submessages cannot have defaults.");
  4806. return false;
  4807. }
  4808. if (upb_fielddef_isstring(f) || upb_fielddef_type(f) == UPB_TYPE_ENUM) {
  4809. upb_fielddef_setdefaultcstr(f, r->default_string, NULL);
  4810. } else {
  4811. if (r->default_string && !parse_default(r->default_string, f)) {
  4812. // We don't worry too much about giving a great error message since the
  4813. // compiler should have ensured this was correct.
  4814. upb_status_seterrmsg(status, "Error converting default value.");
  4815. return false;
  4816. }
  4817. }
  4818. }
  4819. return true;
  4820. }
  4821. static bool field_onlazy(void *closure, const void *hd, bool val) {
  4822. UPB_UNUSED(hd);
  4823. upb_descreader *r = closure;
  4824. upb_fielddef_setlazy(r->f, val);
  4825. return true;
  4826. }
  4827. static bool field_onpacked(void *closure, const void *hd, bool val) {
  4828. UPB_UNUSED(hd);
  4829. upb_descreader *r = closure;
  4830. upb_fielddef_setpacked(r->f, val);
  4831. return true;
  4832. }
  4833. static bool field_ontype(void *closure, const void *hd, int32_t val) {
  4834. UPB_UNUSED(hd);
  4835. upb_descreader *r = closure;
  4836. upb_fielddef_setdescriptortype(r->f, val);
  4837. return true;
  4838. }
  4839. static bool field_onlabel(void *closure, const void *hd, int32_t val) {
  4840. UPB_UNUSED(hd);
  4841. upb_descreader *r = closure;
  4842. upb_fielddef_setlabel(r->f, val);
  4843. return true;
  4844. }
  4845. static bool field_onnumber(void *closure, const void *hd, int32_t val) {
  4846. UPB_UNUSED(hd);
  4847. upb_descreader *r = closure;
  4848. bool ok = upb_fielddef_setnumber(r->f, val, NULL);
  4849. UPB_ASSERT_VAR(ok, ok);
  4850. return true;
  4851. }
  4852. static size_t field_onname(void *closure, const void *hd, const char *buf,
  4853. size_t n, const upb_bufhandle *handle) {
  4854. UPB_UNUSED(hd);
  4855. UPB_UNUSED(handle);
  4856. upb_descreader *r = closure;
  4857. // XXX: see comment at the top of the file.
  4858. char *name = upb_strndup(buf, n);
  4859. upb_fielddef_setname(r->f, name, NULL);
  4860. free(name);
  4861. return n;
  4862. }
  4863. static size_t field_ontypename(void *closure, const void *hd, const char *buf,
  4864. size_t n, const upb_bufhandle *handle) {
  4865. UPB_UNUSED(hd);
  4866. UPB_UNUSED(handle);
  4867. upb_descreader *r = closure;
  4868. // XXX: see comment at the top of the file.
  4869. char *name = upb_strndup(buf, n);
  4870. upb_fielddef_setsubdefname(r->f, name, NULL);
  4871. free(name);
  4872. return n;
  4873. }
  4874. static size_t field_onextendee(void *closure, const void *hd, const char *buf,
  4875. size_t n, const upb_bufhandle *handle) {
  4876. UPB_UNUSED(hd);
  4877. UPB_UNUSED(handle);
  4878. upb_descreader *r = closure;
  4879. // XXX: see comment at the top of the file.
  4880. char *name = upb_strndup(buf, n);
  4881. upb_fielddef_setcontainingtypename(r->f, name, NULL);
  4882. free(name);
  4883. return n;
  4884. }
  4885. static size_t field_ondefaultval(void *closure, const void *hd, const char *buf,
  4886. size_t n, const upb_bufhandle *handle) {
  4887. UPB_UNUSED(hd);
  4888. UPB_UNUSED(handle);
  4889. upb_descreader *r = closure;
  4890. // Have to convert from string to the correct type, but we might not know the
  4891. // type yet, so we save it as a string until the end of the field.
  4892. // XXX: see comment at the top of the file.
  4893. free(r->default_string);
  4894. r->default_string = upb_strndup(buf, n);
  4895. return n;
  4896. }
  4897. // Handlers for google.protobuf.DescriptorProto (representing a message).
  4898. static bool msg_startmsg(void *closure, const void *hd) {
  4899. UPB_UNUSED(hd);
  4900. upb_descreader *r = closure;
  4901. upb_deflist_push(&r->defs, UPB_UPCAST(upb_msgdef_new(&r->defs)));
  4902. upb_descreader_startcontainer(r);
  4903. return true;
  4904. }
  4905. static bool msg_endmsg(void *closure, const void *hd, upb_status *status) {
  4906. UPB_UNUSED(hd);
  4907. upb_descreader *r = closure;
  4908. upb_msgdef *m = upb_descreader_top(r);
  4909. if(!upb_def_fullname(UPB_UPCAST(m))) {
  4910. upb_status_seterrmsg(status, "Encountered message with no name.");
  4911. return false;
  4912. }
  4913. upb_descreader_endcontainer(r);
  4914. return true;
  4915. }
  4916. static size_t msg_onname(void *closure, const void *hd, const char *buf,
  4917. size_t n, const upb_bufhandle *handle) {
  4918. UPB_UNUSED(hd);
  4919. UPB_UNUSED(handle);
  4920. upb_descreader *r = closure;
  4921. upb_msgdef *m = upb_descreader_top(r);
  4922. // XXX: see comment at the top of the file.
  4923. char *name = upb_strndup(buf, n);
  4924. upb_def_setfullname(UPB_UPCAST(m), name, NULL);
  4925. upb_descreader_setscopename(r, name); // Passes ownership of name.
  4926. return n;
  4927. }
  4928. static bool msg_onendfield(void *closure, const void *hd) {
  4929. UPB_UNUSED(hd);
  4930. upb_descreader *r = closure;
  4931. upb_msgdef *m = upb_descreader_top(r);
  4932. upb_msgdef_addfield(m, r->f, &r->defs, NULL);
  4933. r->f = NULL;
  4934. return true;
  4935. }
  4936. static bool pushextension(void *closure, const void *hd) {
  4937. UPB_UNUSED(hd);
  4938. upb_descreader *r = closure;
  4939. assert(upb_fielddef_containingtypename(r->f));
  4940. upb_fielddef_setisextension(r->f, true);
  4941. upb_deflist_push(&r->defs, UPB_UPCAST(r->f));
  4942. r->f = NULL;
  4943. return true;
  4944. }
  4945. #define D(name) upbdefs_google_protobuf_ ## name(s)
  4946. static void reghandlers(const void *closure, upb_handlers *h) {
  4947. const upb_symtab *s = closure;
  4948. const upb_msgdef *m = upb_handlers_msgdef(h);
  4949. if (m == D(DescriptorProto)) {
  4950. upb_handlers_setstartmsg(h, &msg_startmsg, NULL);
  4951. upb_handlers_setendmsg(h, &msg_endmsg, NULL);
  4952. upb_handlers_setstring(h, D(DescriptorProto_name), &msg_onname, NULL);
  4953. upb_handlers_setendsubmsg(h, D(DescriptorProto_field), &msg_onendfield,
  4954. NULL);
  4955. upb_handlers_setendsubmsg(h, D(DescriptorProto_extension), &pushextension,
  4956. NULL);
  4957. } else if (m == D(FileDescriptorProto)) {
  4958. upb_handlers_setstartmsg(h, &file_startmsg, NULL);
  4959. upb_handlers_setendmsg(h, &file_endmsg, NULL);
  4960. upb_handlers_setstring(h, D(FileDescriptorProto_package), &file_onpackage,
  4961. NULL);
  4962. upb_handlers_setendsubmsg(h, D(FileDescriptorProto_extension), &pushextension,
  4963. NULL);
  4964. } else if (m == D(EnumValueDescriptorProto)) {
  4965. upb_handlers_setstartmsg(h, &enumval_startmsg, NULL);
  4966. upb_handlers_setendmsg(h, &enumval_endmsg, NULL);
  4967. upb_handlers_setstring(h, D(EnumValueDescriptorProto_name), &enumval_onname, NULL);
  4968. upb_handlers_setint32(h, D(EnumValueDescriptorProto_number), &enumval_onnumber,
  4969. NULL);
  4970. } else if (m == D(EnumDescriptorProto)) {
  4971. upb_handlers_setstartmsg(h, &enum_startmsg, NULL);
  4972. upb_handlers_setendmsg(h, &enum_endmsg, NULL);
  4973. upb_handlers_setstring(h, D(EnumDescriptorProto_name), &enum_onname, NULL);
  4974. } else if (m == D(FieldDescriptorProto)) {
  4975. upb_handlers_setstartmsg(h, &field_startmsg, NULL);
  4976. upb_handlers_setendmsg(h, &field_endmsg, NULL);
  4977. upb_handlers_setint32(h, D(FieldDescriptorProto_type), &field_ontype,
  4978. NULL);
  4979. upb_handlers_setint32(h, D(FieldDescriptorProto_label), &field_onlabel,
  4980. NULL);
  4981. upb_handlers_setint32(h, D(FieldDescriptorProto_number), &field_onnumber,
  4982. NULL);
  4983. upb_handlers_setstring(h, D(FieldDescriptorProto_name), &field_onname,
  4984. NULL);
  4985. upb_handlers_setstring(h, D(FieldDescriptorProto_type_name),
  4986. &field_ontypename, NULL);
  4987. upb_handlers_setstring(h, D(FieldDescriptorProto_extendee),
  4988. &field_onextendee, NULL);
  4989. upb_handlers_setstring(h, D(FieldDescriptorProto_default_value),
  4990. &field_ondefaultval, NULL);
  4991. } else if (m == D(FieldOptions)) {
  4992. upb_handlers_setbool(h, D(FieldOptions_lazy), &field_onlazy, NULL);
  4993. upb_handlers_setbool(h, D(FieldOptions_packed), &field_onpacked, NULL);
  4994. }
  4995. }
  4996. #undef D
  4997. const upb_handlers *upb_descreader_newhandlers(const void *owner) {
  4998. const upb_symtab *s = upbdefs_google_protobuf_descriptor(&s);
  4999. const upb_handlers *h = upb_handlers_newfrozen(
  5000. upbdefs_google_protobuf_FileDescriptorSet(s), owner, reghandlers, s);
  5001. upb_symtab_unref(s, &s);
  5002. return h;
  5003. }
  5004. /*
  5005. * upb - a minimalist implementation of protocol buffers.
  5006. *
  5007. * Copyright (c) 2013 Google Inc. See LICENSE for details.
  5008. * Author: Josh Haberman <jhaberman@gmail.com>
  5009. *
  5010. * Code to compile a upb::Handlers into bytecode for decoding a protobuf
  5011. * according to that specific schema and destination handlers.
  5012. *
  5013. * Compiling to bytecode is always the first step. If we are using the
  5014. * interpreted decoder we leave it as bytecode and interpret that. If we are
  5015. * using a JIT decoder we use a code generator to turn the bytecode into native
  5016. * code, LLVM IR, etc.
  5017. *
  5018. * Bytecode definition is in decoder.int.h.
  5019. */
  5020. #include <stdarg.h>
  5021. #ifdef UPB_DUMP_BYTECODE
  5022. #include <stdio.h>
  5023. #endif
  5024. #define MAXLABEL 5
  5025. #define EMPTYLABEL -1
  5026. /* mgroup *********************************************************************/
  5027. static void freegroup(upb_refcounted *r) {
  5028. mgroup *g = (mgroup*)r;
  5029. upb_inttable_uninit(&g->methods);
  5030. #ifdef UPB_USE_JIT_X64
  5031. upb_pbdecoder_freejit(g);
  5032. #endif
  5033. free(g->bytecode);
  5034. free(g);
  5035. }
  5036. static void visitgroup(const upb_refcounted *r, upb_refcounted_visit *visit,
  5037. void *closure) {
  5038. const mgroup *g = (const mgroup*)r;
  5039. upb_inttable_iter i;
  5040. upb_inttable_begin(&i, &g->methods);
  5041. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5042. upb_pbdecodermethod *method = upb_value_getptr(upb_inttable_iter_value(&i));
  5043. visit(r, UPB_UPCAST(method), closure);
  5044. }
  5045. }
  5046. mgroup *newgroup(const void *owner) {
  5047. mgroup *g = malloc(sizeof(*g));
  5048. static const struct upb_refcounted_vtbl vtbl = {visitgroup, freegroup};
  5049. upb_refcounted_init(UPB_UPCAST(g), &vtbl, owner);
  5050. upb_inttable_init(&g->methods, UPB_CTYPE_PTR);
  5051. g->bytecode = NULL;
  5052. g->bytecode_end = NULL;
  5053. return g;
  5054. }
  5055. /* upb_pbdecodermethod ********************************************************/
  5056. static void freemethod(upb_refcounted *r) {
  5057. upb_pbdecodermethod *method = (upb_pbdecodermethod*)r;
  5058. upb_byteshandler_uninit(&method->input_handler_);
  5059. if (method->dest_handlers_) {
  5060. upb_handlers_unref(method->dest_handlers_, method);
  5061. }
  5062. upb_inttable_uninit(&method->dispatch);
  5063. free(method);
  5064. }
  5065. static void visitmethod(const upb_refcounted *r, upb_refcounted_visit *visit,
  5066. void *closure) {
  5067. const upb_pbdecodermethod *m = (const upb_pbdecodermethod*)r;
  5068. visit(r, m->group, closure);
  5069. }
  5070. static upb_pbdecodermethod *newmethod(const upb_handlers *dest_handlers,
  5071. mgroup *group) {
  5072. static const struct upb_refcounted_vtbl vtbl = {visitmethod, freemethod};
  5073. upb_pbdecodermethod *ret = malloc(sizeof(*ret));
  5074. upb_refcounted_init(UPB_UPCAST(ret), &vtbl, &ret);
  5075. upb_byteshandler_init(&ret->input_handler_);
  5076. // The method references the group and vice-versa, in a circular reference.
  5077. upb_ref2(ret, group);
  5078. upb_ref2(group, ret);
  5079. upb_inttable_insertptr(&group->methods, dest_handlers, upb_value_ptr(ret));
  5080. upb_refcounted_unref(UPB_UPCAST(ret), &ret);
  5081. ret->group = UPB_UPCAST(group);
  5082. ret->dest_handlers_ = dest_handlers;
  5083. ret->is_native_ = false; // If we JIT, it will update this later.
  5084. upb_inttable_init(&ret->dispatch, UPB_CTYPE_UINT64);
  5085. if (ret->dest_handlers_) {
  5086. upb_handlers_ref(ret->dest_handlers_, ret);
  5087. }
  5088. return ret;
  5089. }
  5090. void upb_pbdecodermethod_ref(const upb_pbdecodermethod *m, const void *owner) {
  5091. upb_refcounted_ref(UPB_UPCAST(m), owner);
  5092. }
  5093. void upb_pbdecodermethod_unref(const upb_pbdecodermethod *m,
  5094. const void *owner) {
  5095. upb_refcounted_unref(UPB_UPCAST(m), owner);
  5096. }
  5097. void upb_pbdecodermethod_donateref(const upb_pbdecodermethod *m,
  5098. const void *from, const void *to) {
  5099. upb_refcounted_donateref(UPB_UPCAST(m), from, to);
  5100. }
  5101. void upb_pbdecodermethod_checkref(const upb_pbdecodermethod *m,
  5102. const void *owner) {
  5103. upb_refcounted_checkref(UPB_UPCAST(m), owner);
  5104. }
  5105. const upb_handlers *upb_pbdecodermethod_desthandlers(
  5106. const upb_pbdecodermethod *m) {
  5107. return m->dest_handlers_;
  5108. }
  5109. const upb_byteshandler *upb_pbdecodermethod_inputhandler(
  5110. const upb_pbdecodermethod *m) {
  5111. return &m->input_handler_;
  5112. }
  5113. bool upb_pbdecodermethod_isnative(const upb_pbdecodermethod *m) {
  5114. return m->is_native_;
  5115. }
  5116. const upb_pbdecodermethod *upb_pbdecodermethod_new(
  5117. const upb_pbdecodermethodopts *opts, const void *owner) {
  5118. upb_pbcodecache cache;
  5119. upb_pbcodecache_init(&cache);
  5120. const upb_pbdecodermethod *ret =
  5121. upb_pbcodecache_getdecodermethod(&cache, opts);
  5122. upb_pbdecodermethod_ref(ret, owner);
  5123. upb_pbcodecache_uninit(&cache);
  5124. return ret;
  5125. }
  5126. /* bytecode compiler **********************************************************/
  5127. // Data used only at compilation time.
  5128. typedef struct {
  5129. mgroup *group;
  5130. uint32_t *pc;
  5131. int fwd_labels[MAXLABEL];
  5132. int back_labels[MAXLABEL];
  5133. // For fields marked "lazy", parse them lazily or eagerly?
  5134. bool lazy;
  5135. } compiler;
  5136. static compiler *newcompiler(mgroup *group, bool lazy) {
  5137. compiler *ret = malloc(sizeof(*ret));
  5138. ret->group = group;
  5139. ret->lazy = lazy;
  5140. for (int i = 0; i < MAXLABEL; i++) {
  5141. ret->fwd_labels[i] = EMPTYLABEL;
  5142. ret->back_labels[i] = EMPTYLABEL;
  5143. }
  5144. return ret;
  5145. }
  5146. static void freecompiler(compiler *c) {
  5147. free(c);
  5148. }
  5149. const size_t ptr_words = sizeof(void*) / sizeof(uint32_t);
  5150. // How many words an instruction is.
  5151. static int instruction_len(uint32_t instr) {
  5152. switch (getop(instr)) {
  5153. case OP_SETDISPATCH: return 1 + ptr_words;
  5154. case OP_TAGN: return 3;
  5155. case OP_SETBIGGROUPNUM: return 2;
  5156. default: return 1;
  5157. }
  5158. }
  5159. bool op_has_longofs(int32_t instruction) {
  5160. switch (getop(instruction)) {
  5161. case OP_CALL:
  5162. case OP_BRANCH:
  5163. case OP_CHECKDELIM:
  5164. return true;
  5165. // The "tag" instructions only have 8 bytes available for the jump target,
  5166. // but that is ok because these opcodes only require short jumps.
  5167. case OP_TAG1:
  5168. case OP_TAG2:
  5169. case OP_TAGN:
  5170. return false;
  5171. default:
  5172. assert(false);
  5173. return false;
  5174. }
  5175. }
  5176. static int32_t getofs(uint32_t instruction) {
  5177. if (op_has_longofs(instruction)) {
  5178. return (int32_t)instruction >> 8;
  5179. } else {
  5180. return (int8_t)(instruction >> 8);
  5181. }
  5182. }
  5183. static void setofs(uint32_t *instruction, int32_t ofs) {
  5184. if (op_has_longofs(*instruction)) {
  5185. *instruction = getop(*instruction) | ofs << 8;
  5186. } else {
  5187. *instruction = (*instruction & ~0xff00) | ((ofs & 0xff) << 8);
  5188. }
  5189. assert(getofs(*instruction) == ofs); // Would fail in cases of overflow.
  5190. }
  5191. static uint32_t pcofs(compiler *c) { return c->pc - c->group->bytecode; }
  5192. // Defines a local label at the current PC location. All previous forward
  5193. // references are updated to point to this location. The location is noted
  5194. // for any future backward references.
  5195. static void label(compiler *c, unsigned int label) {
  5196. assert(label < MAXLABEL);
  5197. int val = c->fwd_labels[label];
  5198. uint32_t *codep = (val == EMPTYLABEL) ? NULL : c->group->bytecode + val;
  5199. while (codep) {
  5200. int ofs = getofs(*codep);
  5201. setofs(codep, c->pc - codep - instruction_len(*codep));
  5202. codep = ofs ? codep + ofs : NULL;
  5203. }
  5204. c->fwd_labels[label] = EMPTYLABEL;
  5205. c->back_labels[label] = pcofs(c);
  5206. }
  5207. // Creates a reference to a numbered label; either a forward reference
  5208. // (positive arg) or backward reference (negative arg). For forward references
  5209. // the value returned now is actually a "next" pointer into a linked list of all
  5210. // instructions that use this label and will be patched later when the label is
  5211. // defined with label().
  5212. //
  5213. // The returned value is the offset that should be written into the instruction.
  5214. static int32_t labelref(compiler *c, int label) {
  5215. assert(label < MAXLABEL);
  5216. if (label == LABEL_DISPATCH) {
  5217. // No resolving required.
  5218. return 0;
  5219. } else if (label < 0) {
  5220. // Backward local label. Relative to the next instruction.
  5221. uint32_t from = (c->pc + 1) - c->group->bytecode;
  5222. return c->back_labels[-label] - from;
  5223. } else {
  5224. // Forward local label: prepend to (possibly-empty) linked list.
  5225. int *lptr = &c->fwd_labels[label];
  5226. int32_t ret = (*lptr == EMPTYLABEL) ? 0 : *lptr - pcofs(c);
  5227. *lptr = pcofs(c);
  5228. return ret;
  5229. }
  5230. }
  5231. static void put32(compiler *c, uint32_t v) {
  5232. mgroup *g = c->group;
  5233. if (c->pc == g->bytecode_end) {
  5234. int ofs = pcofs(c);
  5235. size_t oldsize = g->bytecode_end - g->bytecode;
  5236. size_t newsize = UPB_MAX(oldsize * 2, 64);
  5237. // TODO(haberman): handle OOM.
  5238. g->bytecode = realloc(g->bytecode, newsize * sizeof(uint32_t));
  5239. g->bytecode_end = g->bytecode + newsize;
  5240. c->pc = g->bytecode + ofs;
  5241. }
  5242. *c->pc++ = v;
  5243. }
  5244. static void putop(compiler *c, opcode op, ...) {
  5245. va_list ap;
  5246. va_start(ap, op);
  5247. switch (op) {
  5248. case OP_SETDISPATCH: {
  5249. uintptr_t ptr = (uintptr_t)va_arg(ap, void*);
  5250. put32(c, OP_SETDISPATCH);
  5251. put32(c, ptr);
  5252. if (sizeof(uintptr_t) > sizeof(uint32_t))
  5253. put32(c, (uint64_t)ptr >> 32);
  5254. break;
  5255. }
  5256. case OP_STARTMSG:
  5257. case OP_ENDMSG:
  5258. case OP_PUSHLENDELIM:
  5259. case OP_POP:
  5260. case OP_SETDELIM:
  5261. case OP_HALT:
  5262. case OP_RET:
  5263. put32(c, op);
  5264. break;
  5265. case OP_PARSE_DOUBLE:
  5266. case OP_PARSE_FLOAT:
  5267. case OP_PARSE_INT64:
  5268. case OP_PARSE_UINT64:
  5269. case OP_PARSE_INT32:
  5270. case OP_PARSE_FIXED64:
  5271. case OP_PARSE_FIXED32:
  5272. case OP_PARSE_BOOL:
  5273. case OP_PARSE_UINT32:
  5274. case OP_PARSE_SFIXED32:
  5275. case OP_PARSE_SFIXED64:
  5276. case OP_PARSE_SINT32:
  5277. case OP_PARSE_SINT64:
  5278. case OP_STARTSEQ:
  5279. case OP_ENDSEQ:
  5280. case OP_STARTSUBMSG:
  5281. case OP_ENDSUBMSG:
  5282. case OP_STARTSTR:
  5283. case OP_STRING:
  5284. case OP_ENDSTR:
  5285. case OP_PUSHTAGDELIM:
  5286. put32(c, op | va_arg(ap, upb_selector_t) << 8);
  5287. break;
  5288. case OP_SETBIGGROUPNUM:
  5289. put32(c, op);
  5290. put32(c, va_arg(ap, int));
  5291. break;
  5292. case OP_CALL: {
  5293. const upb_pbdecodermethod *method = va_arg(ap, upb_pbdecodermethod *);
  5294. put32(c, op | (method->code_base.ofs - (pcofs(c) + 1)) << 8);
  5295. break;
  5296. }
  5297. case OP_CHECKDELIM:
  5298. case OP_BRANCH: {
  5299. uint32_t instruction = op;
  5300. int label = va_arg(ap, int);
  5301. setofs(&instruction, labelref(c, label));
  5302. put32(c, instruction);
  5303. break;
  5304. }
  5305. case OP_TAG1:
  5306. case OP_TAG2: {
  5307. int label = va_arg(ap, int);
  5308. uint64_t tag = va_arg(ap, uint64_t);
  5309. uint32_t instruction = op | (tag << 16);
  5310. assert(tag <= 0xffff);
  5311. setofs(&instruction, labelref(c, label));
  5312. put32(c, instruction);
  5313. break;
  5314. }
  5315. case OP_TAGN: {
  5316. int label = va_arg(ap, int);
  5317. uint64_t tag = va_arg(ap, uint64_t);
  5318. uint32_t instruction = op | (upb_value_size(tag) << 16);
  5319. setofs(&instruction, labelref(c, label));
  5320. put32(c, instruction);
  5321. put32(c, tag);
  5322. put32(c, tag >> 32);
  5323. break;
  5324. }
  5325. }
  5326. va_end(ap);
  5327. }
  5328. #if defined(UPB_USE_JIT_X64) || defined(UPB_DUMP_BYTECODE)
  5329. const char *upb_pbdecoder_getopname(unsigned int op) {
  5330. #define OP(op) [OP_ ## op] = "OP_" #op
  5331. #define T(op) OP(PARSE_##op)
  5332. static const char *names[] = {
  5333. "<no opcode>",
  5334. T(DOUBLE), T(FLOAT), T(INT64), T(UINT64), T(INT32), T(FIXED64), T(FIXED32),
  5335. T(BOOL), T(UINT32), T(SFIXED32), T(SFIXED64), T(SINT32), T(SINT64),
  5336. OP(STARTMSG), OP(ENDMSG), OP(STARTSEQ), OP(ENDSEQ), OP(STARTSUBMSG),
  5337. OP(ENDSUBMSG), OP(STARTSTR), OP(STRING), OP(ENDSTR), OP(CALL), OP(RET),
  5338. OP(PUSHLENDELIM), OP(PUSHTAGDELIM), OP(SETDELIM), OP(CHECKDELIM),
  5339. OP(BRANCH), OP(TAG1), OP(TAG2), OP(TAGN), OP(SETDISPATCH), OP(POP),
  5340. OP(SETBIGGROUPNUM), OP(HALT),
  5341. };
  5342. return op > OP_HALT ? names[0] : names[op];
  5343. #undef OP
  5344. #undef T
  5345. }
  5346. #endif
  5347. #ifdef UPB_DUMP_BYTECODE
  5348. static void dumpbc(uint32_t *p, uint32_t *end, FILE *f) {
  5349. uint32_t *begin = p;
  5350. while (p < end) {
  5351. fprintf(f, "%p %8tx", p, p - begin);
  5352. uint32_t instr = *p++;
  5353. uint8_t op = getop(instr);
  5354. fprintf(f, " %s", upb_pbdecoder_getopname(op));
  5355. switch ((opcode)op) {
  5356. case OP_SETDISPATCH: {
  5357. const upb_inttable *dispatch;
  5358. memcpy(&dispatch, p, sizeof(void*));
  5359. p += ptr_words;
  5360. const upb_pbdecodermethod *method =
  5361. (void *)((char *)dispatch -
  5362. offsetof(upb_pbdecodermethod, dispatch));
  5363. fprintf(f, " %s", upb_msgdef_fullname(
  5364. upb_handlers_msgdef(method->dest_handlers_)));
  5365. break;
  5366. }
  5367. case OP_STARTMSG:
  5368. case OP_ENDMSG:
  5369. case OP_PUSHLENDELIM:
  5370. case OP_POP:
  5371. case OP_SETDELIM:
  5372. case OP_HALT:
  5373. case OP_RET:
  5374. break;
  5375. case OP_PARSE_DOUBLE:
  5376. case OP_PARSE_FLOAT:
  5377. case OP_PARSE_INT64:
  5378. case OP_PARSE_UINT64:
  5379. case OP_PARSE_INT32:
  5380. case OP_PARSE_FIXED64:
  5381. case OP_PARSE_FIXED32:
  5382. case OP_PARSE_BOOL:
  5383. case OP_PARSE_UINT32:
  5384. case OP_PARSE_SFIXED32:
  5385. case OP_PARSE_SFIXED64:
  5386. case OP_PARSE_SINT32:
  5387. case OP_PARSE_SINT64:
  5388. case OP_STARTSEQ:
  5389. case OP_ENDSEQ:
  5390. case OP_STARTSUBMSG:
  5391. case OP_ENDSUBMSG:
  5392. case OP_STARTSTR:
  5393. case OP_STRING:
  5394. case OP_ENDSTR:
  5395. case OP_PUSHTAGDELIM:
  5396. fprintf(f, " %d", instr >> 8);
  5397. break;
  5398. case OP_SETBIGGROUPNUM:
  5399. fprintf(f, " %d", *p++);
  5400. break;
  5401. case OP_CHECKDELIM:
  5402. case OP_CALL:
  5403. case OP_BRANCH:
  5404. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  5405. break;
  5406. case OP_TAG1:
  5407. case OP_TAG2: {
  5408. fprintf(f, " tag:0x%x", instr >> 16);
  5409. if (getofs(instr)) {
  5410. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  5411. }
  5412. break;
  5413. }
  5414. case OP_TAGN: {
  5415. uint64_t tag = *p++;
  5416. tag |= (uint64_t)*p++ << 32;
  5417. fprintf(f, " tag:0x%llx", (long long)tag);
  5418. fprintf(f, " n:%d", instr >> 16);
  5419. if (getofs(instr)) {
  5420. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  5421. }
  5422. break;
  5423. }
  5424. }
  5425. fputs("\n", f);
  5426. }
  5427. }
  5428. #endif
  5429. static uint64_t get_encoded_tag(const upb_fielddef *f, int wire_type) {
  5430. uint32_t tag = (upb_fielddef_number(f) << 3) | wire_type;
  5431. uint64_t encoded_tag = upb_vencode32(tag);
  5432. // No tag should be greater than 5 bytes.
  5433. assert(encoded_tag <= 0xffffffffff);
  5434. return encoded_tag;
  5435. }
  5436. static void putchecktag(compiler *c, const upb_fielddef *f,
  5437. int wire_type, int dest) {
  5438. uint64_t tag = get_encoded_tag(f, wire_type);
  5439. switch (upb_value_size(tag)) {
  5440. case 1:
  5441. putop(c, OP_TAG1, dest, tag);
  5442. break;
  5443. case 2:
  5444. putop(c, OP_TAG2, dest, tag);
  5445. break;
  5446. default:
  5447. putop(c, OP_TAGN, dest, tag);
  5448. break;
  5449. }
  5450. }
  5451. static upb_selector_t getsel(const upb_fielddef *f, upb_handlertype_t type) {
  5452. upb_selector_t selector;
  5453. bool ok = upb_handlers_getselector(f, type, &selector);
  5454. UPB_ASSERT_VAR(ok, ok);
  5455. return selector;
  5456. }
  5457. // Takes an existing, primary dispatch table entry and repacks it with a
  5458. // different alternate wire type. Called when we are inserting a secondary
  5459. // dispatch table entry for an alternate wire type.
  5460. static uint64_t repack(uint64_t dispatch, int new_wt2) {
  5461. uint64_t ofs;
  5462. uint8_t wt1;
  5463. uint8_t old_wt2;
  5464. upb_pbdecoder_unpackdispatch(dispatch, &ofs, &wt1, &old_wt2);
  5465. assert(old_wt2 == NO_WIRE_TYPE); // wt2 should not be set yet.
  5466. return upb_pbdecoder_packdispatch(ofs, wt1, new_wt2);
  5467. }
  5468. // Marks the current bytecode position as the dispatch target for this message,
  5469. // field, and wire type.
  5470. static void dispatchtarget(compiler *c, upb_pbdecodermethod *method,
  5471. const upb_fielddef *f, int wire_type) {
  5472. // Offset is relative to msg base.
  5473. uint64_t ofs = pcofs(c) - method->code_base.ofs;
  5474. uint32_t fn = upb_fielddef_number(f);
  5475. upb_inttable *d = &method->dispatch;
  5476. upb_value v;
  5477. if (upb_inttable_remove(d, fn, &v)) {
  5478. // TODO: prioritize based on packed setting in .proto file.
  5479. uint64_t repacked = repack(upb_value_getuint64(v), wire_type);
  5480. upb_inttable_insert(d, fn, upb_value_uint64(repacked));
  5481. upb_inttable_insert(d, fn + UPB_MAX_FIELDNUMBER, upb_value_uint64(ofs));
  5482. } else {
  5483. uint64_t val = upb_pbdecoder_packdispatch(ofs, wire_type, NO_WIRE_TYPE);
  5484. upb_inttable_insert(d, fn, upb_value_uint64(val));
  5485. }
  5486. }
  5487. static void putpush(compiler *c, const upb_fielddef *f) {
  5488. if (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE) {
  5489. putop(c, OP_PUSHLENDELIM);
  5490. } else {
  5491. uint32_t fn = upb_fielddef_number(f);
  5492. if (fn >= 1 << 24) {
  5493. putop(c, OP_PUSHTAGDELIM, 0);
  5494. putop(c, OP_SETBIGGROUPNUM, fn);
  5495. } else {
  5496. putop(c, OP_PUSHTAGDELIM, fn);
  5497. }
  5498. }
  5499. }
  5500. static upb_pbdecodermethod *find_submethod(const compiler *c,
  5501. const upb_pbdecodermethod *method,
  5502. const upb_fielddef *f) {
  5503. const upb_handlers *sub =
  5504. upb_handlers_getsubhandlers(method->dest_handlers_, f);
  5505. upb_value v;
  5506. return upb_inttable_lookupptr(&c->group->methods, sub, &v)
  5507. ? upb_value_getptr(v)
  5508. : NULL;
  5509. }
  5510. static void putsel(compiler *c, opcode op, upb_selector_t sel,
  5511. const upb_handlers *h) {
  5512. if (upb_handlers_gethandler(h, sel)) {
  5513. putop(c, op, sel);
  5514. }
  5515. }
  5516. // Puts an opcode to call a callback, but only if a callback actually exists for
  5517. // this field and handler type.
  5518. static void maybeput(compiler *c, opcode op, const upb_handlers *h,
  5519. const upb_fielddef *f, upb_handlertype_t type) {
  5520. putsel(c, op, getsel(f, type), h);
  5521. }
  5522. static bool haslazyhandlers(const upb_handlers *h, const upb_fielddef *f) {
  5523. if (!upb_fielddef_lazy(f))
  5524. return false;
  5525. return upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STARTSTR)) ||
  5526. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STRING)) ||
  5527. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_ENDSTR));
  5528. }
  5529. /* bytecode compiler code generation ******************************************/
  5530. // Symbolic names for our local labels.
  5531. #define LABEL_LOOPSTART 1 // Top of a repeated field loop.
  5532. #define LABEL_LOOPBREAK 2 // To jump out of a repeated loop
  5533. #define LABEL_FIELD 3 // Jump backward to find the most recent field.
  5534. #define LABEL_ENDMSG 4 // To reach the OP_ENDMSG instr for this msg.
  5535. // Generates bytecode to parse a single non-lazy message field.
  5536. static void generate_msgfield(compiler *c, const upb_fielddef *f,
  5537. upb_pbdecodermethod *method) {
  5538. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  5539. const upb_pbdecodermethod *sub_m = find_submethod(c, method, f);
  5540. if (!sub_m) {
  5541. // Don't emit any code for this field at all; it will be parsed as an
  5542. // unknown field.
  5543. return;
  5544. }
  5545. label(c, LABEL_FIELD);
  5546. int wire_type =
  5547. (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE)
  5548. ? UPB_WIRE_TYPE_DELIMITED
  5549. : UPB_WIRE_TYPE_START_GROUP;
  5550. if (upb_fielddef_isseq(f)) {
  5551. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5552. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  5553. dispatchtarget(c, method, f, wire_type);
  5554. putop(c, OP_PUSHTAGDELIM, 0);
  5555. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  5556. label(c, LABEL_LOOPSTART);
  5557. putpush(c, f);
  5558. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  5559. putop(c, OP_CALL, sub_m);
  5560. putop(c, OP_POP);
  5561. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  5562. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  5563. putop(c, OP_SETDELIM);
  5564. }
  5565. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5566. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  5567. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5568. label(c, LABEL_LOOPBREAK);
  5569. putop(c, OP_POP);
  5570. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  5571. } else {
  5572. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5573. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  5574. dispatchtarget(c, method, f, wire_type);
  5575. putpush(c, f);
  5576. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  5577. putop(c, OP_CALL, sub_m);
  5578. putop(c, OP_POP);
  5579. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  5580. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  5581. putop(c, OP_SETDELIM);
  5582. }
  5583. }
  5584. }
  5585. // Generates bytecode to parse a single string or lazy submessage field.
  5586. static void generate_delimfield(compiler *c, const upb_fielddef *f,
  5587. upb_pbdecodermethod *method) {
  5588. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  5589. label(c, LABEL_FIELD);
  5590. if (upb_fielddef_isseq(f)) {
  5591. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5592. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  5593. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  5594. putop(c, OP_PUSHTAGDELIM, 0);
  5595. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  5596. label(c, LABEL_LOOPSTART);
  5597. putop(c, OP_PUSHLENDELIM);
  5598. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  5599. // Need to emit even if no handler to skip past the string.
  5600. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  5601. putop(c, OP_POP);
  5602. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  5603. putop(c, OP_SETDELIM);
  5604. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5605. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_LOOPBREAK);
  5606. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5607. label(c, LABEL_LOOPBREAK);
  5608. putop(c, OP_POP);
  5609. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  5610. } else {
  5611. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5612. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  5613. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  5614. putop(c, OP_PUSHLENDELIM);
  5615. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  5616. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  5617. putop(c, OP_POP);
  5618. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  5619. putop(c, OP_SETDELIM);
  5620. }
  5621. }
  5622. // Generates bytecode to parse a single primitive field.
  5623. static void generate_primitivefield(compiler *c, const upb_fielddef *f,
  5624. upb_pbdecodermethod *method) {
  5625. label(c, LABEL_FIELD);
  5626. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  5627. upb_descriptortype_t descriptor_type = upb_fielddef_descriptortype(f);
  5628. // From a decoding perspective, ENUM is the same as INT32.
  5629. if (descriptor_type == UPB_DESCRIPTOR_TYPE_ENUM)
  5630. descriptor_type = UPB_DESCRIPTOR_TYPE_INT32;
  5631. opcode parse_type = (opcode)descriptor_type;
  5632. // TODO(haberman): generate packed or non-packed first depending on "packed"
  5633. // setting in the fielddef. This will favor (in speed) whichever was
  5634. // specified.
  5635. assert((int)parse_type >= 0 && parse_type <= OP_MAX);
  5636. upb_selector_t sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  5637. int wire_type = upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  5638. if (upb_fielddef_isseq(f)) {
  5639. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5640. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  5641. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  5642. putop(c, OP_PUSHLENDELIM);
  5643. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); // Packed
  5644. label(c, LABEL_LOOPSTART);
  5645. putop(c, parse_type, sel);
  5646. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5647. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5648. dispatchtarget(c, method, f, wire_type);
  5649. putop(c, OP_PUSHTAGDELIM, 0);
  5650. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); // Non-packed
  5651. label(c, LABEL_LOOPSTART);
  5652. putop(c, parse_type, sel);
  5653. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5654. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  5655. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5656. label(c, LABEL_LOOPBREAK);
  5657. putop(c, OP_POP); // Packed and non-packed join.
  5658. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  5659. putop(c, OP_SETDELIM); // Could remove for non-packed by dup ENDSEQ.
  5660. } else {
  5661. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5662. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  5663. dispatchtarget(c, method, f, wire_type);
  5664. putop(c, parse_type, sel);
  5665. }
  5666. }
  5667. // Adds bytecode for parsing the given message to the given decoderplan,
  5668. // while adding all dispatch targets to this message's dispatch table.
  5669. static void compile_method(compiler *c, upb_pbdecodermethod *method) {
  5670. assert(method);
  5671. // Clear all entries in the dispatch table.
  5672. upb_inttable_uninit(&method->dispatch);
  5673. upb_inttable_init(&method->dispatch, UPB_CTYPE_UINT64);
  5674. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  5675. const upb_msgdef *md = upb_handlers_msgdef(h);
  5676. method->code_base.ofs = pcofs(c);
  5677. putop(c, OP_SETDISPATCH, &method->dispatch);
  5678. putsel(c, OP_STARTMSG, UPB_STARTMSG_SELECTOR, h);
  5679. label(c, LABEL_FIELD);
  5680. upb_msg_iter i;
  5681. for(upb_msg_begin(&i, md); !upb_msg_done(&i); upb_msg_next(&i)) {
  5682. const upb_fielddef *f = upb_msg_iter_field(&i);
  5683. upb_fieldtype_t type = upb_fielddef_type(f);
  5684. if (type == UPB_TYPE_MESSAGE && !(haslazyhandlers(h, f) && c->lazy)) {
  5685. generate_msgfield(c, f, method);
  5686. } else if (type == UPB_TYPE_STRING || type == UPB_TYPE_BYTES ||
  5687. type == UPB_TYPE_MESSAGE) {
  5688. generate_delimfield(c, f, method);
  5689. } else {
  5690. generate_primitivefield(c, f, method);
  5691. }
  5692. }
  5693. // For now we just loop back to the last field of the message (or if none,
  5694. // the DISPATCH opcode for the message.
  5695. putop(c, OP_BRANCH, -LABEL_FIELD);
  5696. // Insert both a label and a dispatch table entry for this end-of-msg.
  5697. label(c, LABEL_ENDMSG);
  5698. upb_value val = upb_value_uint64(pcofs(c) - method->code_base.ofs);
  5699. upb_inttable_insert(&method->dispatch, DISPATCH_ENDMSG, val);
  5700. putsel(c, OP_ENDMSG, UPB_ENDMSG_SELECTOR, h);
  5701. putop(c, OP_RET);
  5702. upb_inttable_compact(&method->dispatch);
  5703. }
  5704. // Populate "methods" with new upb_pbdecodermethod objects reachable from "h".
  5705. // Returns the method for these handlers.
  5706. //
  5707. // Generates a new method for every destination handlers reachable from "h".
  5708. static void find_methods(compiler *c, const upb_handlers *h) {
  5709. upb_value v;
  5710. if (upb_inttable_lookupptr(&c->group->methods, h, &v))
  5711. return;
  5712. newmethod(h, c->group);
  5713. // Find submethods.
  5714. upb_msg_iter i;
  5715. const upb_msgdef *md = upb_handlers_msgdef(h);
  5716. for(upb_msg_begin(&i, md); !upb_msg_done(&i); upb_msg_next(&i)) {
  5717. const upb_fielddef *f = upb_msg_iter_field(&i);
  5718. const upb_handlers *sub_h;
  5719. if (upb_fielddef_type(f) == UPB_TYPE_MESSAGE &&
  5720. (sub_h = upb_handlers_getsubhandlers(h, f)) != NULL) {
  5721. // We only generate a decoder method for submessages with handlers.
  5722. // Others will be parsed as unknown fields.
  5723. find_methods(c, sub_h);
  5724. }
  5725. }
  5726. }
  5727. // (Re-)compile bytecode for all messages in "msgs."
  5728. // Overwrites any existing bytecode in "c".
  5729. static void compile_methods(compiler *c) {
  5730. // Start over at the beginning of the bytecode.
  5731. c->pc = c->group->bytecode;
  5732. upb_inttable_iter i;
  5733. upb_inttable_begin(&i, &c->group->methods);
  5734. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5735. upb_pbdecodermethod *method = upb_value_getptr(upb_inttable_iter_value(&i));
  5736. compile_method(c, method);
  5737. }
  5738. }
  5739. static void set_bytecode_handlers(mgroup *g) {
  5740. upb_inttable_iter i;
  5741. upb_inttable_begin(&i, &g->methods);
  5742. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5743. upb_pbdecodermethod *m = upb_value_getptr(upb_inttable_iter_value(&i));
  5744. m->code_base.ptr = g->bytecode + m->code_base.ofs;
  5745. upb_byteshandler *h = &m->input_handler_;
  5746. upb_byteshandler_setstartstr(h, upb_pbdecoder_startbc, m->code_base.ptr);
  5747. upb_byteshandler_setstring(h, upb_pbdecoder_decode, g);
  5748. upb_byteshandler_setendstr(h, upb_pbdecoder_end, m);
  5749. }
  5750. }
  5751. /* JIT setup. ******************************************************************/
  5752. #ifdef UPB_USE_JIT_X64
  5753. static void sethandlers(mgroup *g, bool allowjit) {
  5754. g->jit_code = NULL;
  5755. if (allowjit) {
  5756. // Compile byte-code into machine code, create handlers.
  5757. upb_pbdecoder_jit(g);
  5758. } else {
  5759. set_bytecode_handlers(g);
  5760. }
  5761. }
  5762. #else // UPB_USE_JIT_X64
  5763. static void sethandlers(mgroup *g, bool allowjit) {
  5764. // No JIT compiled in; use bytecode handlers unconditionally.
  5765. UPB_UNUSED(allowjit);
  5766. set_bytecode_handlers(g);
  5767. }
  5768. #endif // UPB_USE_JIT_X64
  5769. // TODO(haberman): allow this to be constructed for an arbitrary set of dest
  5770. // handlers and other mgroups (but verify we have a transitive closure).
  5771. const mgroup *mgroup_new(const upb_handlers *dest, bool allowjit, bool lazy,
  5772. const void *owner) {
  5773. UPB_UNUSED(allowjit);
  5774. assert(upb_handlers_isfrozen(dest));
  5775. mgroup *g = newgroup(owner);
  5776. compiler *c = newcompiler(g, lazy);
  5777. find_methods(c, dest);
  5778. // We compile in two passes:
  5779. // 1. all messages are assigned relative offsets from the beginning of the
  5780. // bytecode (saved in method->code_base).
  5781. // 2. forwards OP_CALL instructions can be correctly linked since message
  5782. // offsets have been previously assigned.
  5783. //
  5784. // Could avoid the second pass by linking OP_CALL instructions somehow.
  5785. compile_methods(c);
  5786. compile_methods(c);
  5787. g->bytecode_end = c->pc;
  5788. freecompiler(c);
  5789. #ifdef UPB_DUMP_BYTECODE
  5790. FILE *f = fopen("/tmp/upb-bytecode", "wb");
  5791. assert(f);
  5792. dumpbc(g->bytecode, g->bytecode_end, stderr);
  5793. dumpbc(g->bytecode, g->bytecode_end, f);
  5794. fclose(f);
  5795. #endif
  5796. sethandlers(g, allowjit);
  5797. return g;
  5798. }
  5799. /* upb_pbcodecache ************************************************************/
  5800. void upb_pbcodecache_init(upb_pbcodecache *c) {
  5801. upb_inttable_init(&c->groups, UPB_CTYPE_CONSTPTR);
  5802. c->allow_jit_ = true;
  5803. }
  5804. void upb_pbcodecache_uninit(upb_pbcodecache *c) {
  5805. upb_inttable_iter i;
  5806. upb_inttable_begin(&i, &c->groups);
  5807. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5808. const mgroup *group = upb_value_getconstptr(upb_inttable_iter_value(&i));
  5809. upb_refcounted_unref(UPB_UPCAST(group), c);
  5810. }
  5811. upb_inttable_uninit(&c->groups);
  5812. }
  5813. bool upb_pbcodecache_allowjit(const upb_pbcodecache *c) {
  5814. return c->allow_jit_;
  5815. }
  5816. bool upb_pbcodecache_setallowjit(upb_pbcodecache *c, bool allow) {
  5817. if (upb_inttable_count(&c->groups) > 0)
  5818. return false;
  5819. c->allow_jit_ = allow;
  5820. return true;
  5821. }
  5822. const upb_pbdecodermethod *upb_pbcodecache_getdecodermethod(
  5823. upb_pbcodecache *c, const upb_pbdecodermethodopts *opts) {
  5824. // Right now we build a new DecoderMethod every time.
  5825. // TODO(haberman): properly cache methods by their true key.
  5826. const mgroup *g = mgroup_new(opts->handlers, c->allow_jit_, opts->lazy, c);
  5827. upb_inttable_push(&c->groups, upb_value_constptr(g));
  5828. upb_value v;
  5829. bool ok = upb_inttable_lookupptr(&g->methods, opts->handlers, &v);
  5830. UPB_ASSERT_VAR(ok, ok);
  5831. return upb_value_getptr(v);
  5832. }
  5833. /* upb_pbdecodermethodopts ****************************************************/
  5834. void upb_pbdecodermethodopts_init(upb_pbdecodermethodopts *opts,
  5835. const upb_handlers *h) {
  5836. opts->handlers = h;
  5837. opts->lazy = false;
  5838. }
  5839. void upb_pbdecodermethodopts_setlazy(upb_pbdecodermethodopts *opts, bool lazy) {
  5840. opts->lazy = lazy;
  5841. }
  5842. /*
  5843. * upb - a minimalist implementation of protocol buffers.
  5844. *
  5845. * Copyright (c) 2008-2013 Google Inc. See LICENSE for details.
  5846. * Author: Josh Haberman <jhaberman@gmail.com>
  5847. *
  5848. * This file implements a VM for the interpreted (bytecode) decoder.
  5849. *
  5850. * Bytecode must previously have been generated using the bytecode compiler in
  5851. * compile_decoder.c. This decoder then walks through the bytecode op-by-op to
  5852. * parse the input.
  5853. *
  5854. * Decoding is fully resumable; we just keep a pointer to the current bytecode
  5855. * instruction and resume from there. A fair amount of the logic here is to
  5856. * handle the fact that values can span buffer seams and we have to be able to
  5857. * be capable of suspending/resuming from any byte in the stream. This
  5858. * sometimes requires keeping a few trailing bytes from the last buffer around
  5859. * in the "residual" buffer.
  5860. */
  5861. #include <inttypes.h>
  5862. #include <setjmp.h>
  5863. #include <stdarg.h>
  5864. #include <stddef.h>
  5865. #include <stdlib.h>
  5866. #ifdef UPB_DUMP_BYTECODE
  5867. #include <stdio.h>
  5868. #endif
  5869. #define CHECK_SUSPEND(x) if (!(x)) return upb_pbdecoder_suspend(d);
  5870. // Error messages that are shared between the bytecode and JIT decoders.
  5871. const char *kPbDecoderStackOverflow = "Nesting too deep.";
  5872. // Error messages shared within this file.
  5873. static const char *kUnterminatedVarint = "Unterminated varint.";
  5874. /* upb_pbdecoder **************************************************************/
  5875. static opcode halt = OP_HALT;
  5876. // Whether an op consumes any of the input buffer.
  5877. static bool consumes_input(opcode op) {
  5878. switch (op) {
  5879. case OP_SETDISPATCH:
  5880. case OP_STARTMSG:
  5881. case OP_ENDMSG:
  5882. case OP_STARTSEQ:
  5883. case OP_ENDSEQ:
  5884. case OP_STARTSUBMSG:
  5885. case OP_ENDSUBMSG:
  5886. case OP_STARTSTR:
  5887. case OP_ENDSTR:
  5888. case OP_PUSHTAGDELIM:
  5889. case OP_POP:
  5890. case OP_SETDELIM:
  5891. case OP_SETBIGGROUPNUM:
  5892. case OP_CHECKDELIM:
  5893. case OP_CALL:
  5894. case OP_RET:
  5895. case OP_BRANCH:
  5896. return false;
  5897. default:
  5898. return true;
  5899. }
  5900. }
  5901. static bool in_residual_buf(const upb_pbdecoder *d, const char *p);
  5902. // It's unfortunate that we have to micro-manage the compiler this way,
  5903. // especially since this tuning is necessarily specific to one hardware
  5904. // configuration. But emperically on a Core i7, performance increases 30-50%
  5905. // with these annotations. Every instance where these appear, gcc 4.2.1 made
  5906. // the wrong decision and degraded performance in benchmarks.
  5907. #define FORCEINLINE static inline __attribute__((always_inline))
  5908. #define NOINLINE __attribute__((noinline))
  5909. static void seterr(upb_pbdecoder *d, const char *msg) {
  5910. // TODO(haberman): encapsulate this access to pipeline->status, but not sure
  5911. // exactly what that interface should look like.
  5912. upb_status_seterrmsg(d->status, msg);
  5913. }
  5914. void upb_pbdecoder_seterr(upb_pbdecoder *d, const char *msg) {
  5915. seterr(d, msg);
  5916. }
  5917. /* Buffering ******************************************************************/
  5918. // We operate on one buffer at a time, which is either the user's buffer passed
  5919. // to our "decode" callback or some residual bytes from the previous buffer.
  5920. // How many bytes can be safely read from d->ptr without reading past end-of-buf
  5921. // or past the current delimited end.
  5922. static size_t curbufleft(const upb_pbdecoder *d) {
  5923. assert(d->data_end >= d->ptr);
  5924. return d->data_end - d->ptr;
  5925. }
  5926. // Overall stream offset of d->ptr.
  5927. uint64_t offset(const upb_pbdecoder *d) {
  5928. return d->bufstart_ofs + (d->ptr - d->buf);
  5929. }
  5930. // Advances d->ptr.
  5931. static void advance(upb_pbdecoder *d, size_t len) {
  5932. assert(curbufleft(d) >= len);
  5933. d->ptr += len;
  5934. }
  5935. static bool in_buf(const char *p, const char *buf, const char *end) {
  5936. return p >= buf && p <= end;
  5937. }
  5938. static bool in_residual_buf(const upb_pbdecoder *d, const char *p) {
  5939. return in_buf(p, d->residual, d->residual_end);
  5940. }
  5941. // Calculates the delim_end value, which is affected by both the current buffer
  5942. // and the parsing stack, so must be called whenever either is updated.
  5943. static void set_delim_end(upb_pbdecoder *d) {
  5944. size_t delim_ofs = d->top->end_ofs - d->bufstart_ofs;
  5945. if (delim_ofs <= (d->end - d->buf)) {
  5946. d->delim_end = d->buf + delim_ofs;
  5947. d->data_end = d->delim_end;
  5948. } else {
  5949. d->data_end = d->end;
  5950. d->delim_end = NULL;
  5951. }
  5952. }
  5953. static void switchtobuf(upb_pbdecoder *d, const char *buf, const char *end) {
  5954. d->ptr = buf;
  5955. d->buf = buf;
  5956. d->end = end;
  5957. set_delim_end(d);
  5958. }
  5959. static void advancetobuf(upb_pbdecoder *d, const char *buf, size_t len) {
  5960. assert(curbufleft(d) == 0);
  5961. d->bufstart_ofs += (d->end - d->buf);
  5962. switchtobuf(d, buf, buf + len);
  5963. }
  5964. static void checkpoint(upb_pbdecoder *d) {
  5965. // The assertion here is in the interests of efficiency, not correctness.
  5966. // We are trying to ensure that we don't checkpoint() more often than
  5967. // necessary.
  5968. assert(d->checkpoint != d->ptr);
  5969. d->checkpoint = d->ptr;
  5970. }
  5971. // Resumes the decoder from an initial state or from a previous suspend.
  5972. int32_t upb_pbdecoder_resume(upb_pbdecoder *d, void *p, const char *buf,
  5973. size_t size, const upb_bufhandle *handle) {
  5974. UPB_UNUSED(p); // Useless; just for the benefit of the JIT.
  5975. d->buf_param = buf;
  5976. d->size_param = size;
  5977. d->handle = handle;
  5978. if (d->residual_end > d->residual) {
  5979. // We have residual bytes from the last buffer.
  5980. assert(d->ptr == d->residual);
  5981. } else {
  5982. switchtobuf(d, buf, buf + size);
  5983. }
  5984. d->checkpoint = d->ptr;
  5985. if (d->top->groupnum < 0) {
  5986. CHECK_RETURN(upb_pbdecoder_skipunknown(d, -1, 0));
  5987. d->checkpoint = d->ptr;
  5988. }
  5989. return DECODE_OK;
  5990. }
  5991. // Suspends the decoder at the last checkpoint, without saving any residual
  5992. // bytes. If there are any unconsumed bytes, returns a short byte count.
  5993. size_t upb_pbdecoder_suspend(upb_pbdecoder *d) {
  5994. d->pc = d->last;
  5995. if (d->checkpoint == d->residual) {
  5996. // Checkpoint was in residual buf; no user bytes were consumed.
  5997. d->ptr = d->residual;
  5998. return 0;
  5999. } else {
  6000. assert(!in_residual_buf(d, d->checkpoint));
  6001. assert(d->buf == d->buf_param);
  6002. size_t consumed = d->checkpoint - d->buf;
  6003. d->bufstart_ofs += consumed;
  6004. d->residual_end = d->residual;
  6005. switchtobuf(d, d->residual, d->residual_end);
  6006. return consumed;
  6007. }
  6008. }
  6009. // Suspends the decoder at the last checkpoint, and saves any unconsumed
  6010. // bytes in our residual buffer. This is necessary if we need more user
  6011. // bytes to form a complete value, which might not be contiguous in the
  6012. // user's buffers. Always consumes all user bytes.
  6013. static size_t suspend_save(upb_pbdecoder *d) {
  6014. // We hit end-of-buffer before we could parse a full value.
  6015. // Save any unconsumed bytes (if any) to the residual buffer.
  6016. d->pc = d->last;
  6017. if (d->checkpoint == d->residual) {
  6018. // Checkpoint was in residual buf; append user byte(s) to residual buf.
  6019. assert((d->residual_end - d->residual) + d->size_param <=
  6020. sizeof(d->residual));
  6021. if (!in_residual_buf(d, d->ptr)) {
  6022. d->bufstart_ofs -= (d->residual_end - d->residual);
  6023. }
  6024. memcpy(d->residual_end, d->buf_param, d->size_param);
  6025. d->residual_end += d->size_param;
  6026. } else {
  6027. // Checkpoint was in user buf; old residual bytes not needed.
  6028. assert(!in_residual_buf(d, d->checkpoint));
  6029. d->ptr = d->checkpoint;
  6030. size_t save = curbufleft(d);
  6031. assert(save <= sizeof(d->residual));
  6032. memcpy(d->residual, d->ptr, save);
  6033. d->residual_end = d->residual + save;
  6034. d->bufstart_ofs = offset(d);
  6035. }
  6036. switchtobuf(d, d->residual, d->residual_end);
  6037. return d->size_param;
  6038. }
  6039. // Skips "bytes" bytes in the stream, which may be more than available. If we
  6040. // skip more bytes than are available, we return a long read count to the caller
  6041. // indicating how many bytes the caller should skip before passing a new buffer.
  6042. static int32_t skip(upb_pbdecoder *d, size_t bytes) {
  6043. assert(!in_residual_buf(d, d->ptr) || d->size_param == 0);
  6044. if (curbufleft(d) >= bytes) {
  6045. // Skipped data is all in current buffer.
  6046. advance(d, bytes);
  6047. return DECODE_OK;
  6048. } else {
  6049. // Skipped data extends beyond currently available buffers.
  6050. d->pc = d->last;
  6051. size_t skip = bytes - curbufleft(d);
  6052. d->bufstart_ofs += (d->end - d->buf) + skip;
  6053. d->residual_end = d->residual;
  6054. switchtobuf(d, d->residual, d->residual_end);
  6055. return d->size_param + skip;
  6056. }
  6057. }
  6058. // Copies the next "bytes" bytes into "buf" and advances the stream.
  6059. // Requires that this many bytes are available in the current buffer.
  6060. FORCEINLINE void consumebytes(upb_pbdecoder *d, void *buf, size_t bytes) {
  6061. assert(bytes <= curbufleft(d));
  6062. memcpy(buf, d->ptr, bytes);
  6063. advance(d, bytes);
  6064. }
  6065. // Slow path for getting the next "bytes" bytes, regardless of whether they are
  6066. // available in the current buffer or not. Returns a status code as described
  6067. // in decoder.int.h.
  6068. static NOINLINE int32_t getbytes_slow(upb_pbdecoder *d, void *buf,
  6069. size_t bytes) {
  6070. const size_t avail = curbufleft(d);
  6071. consumebytes(d, buf, avail);
  6072. bytes -= avail;
  6073. assert(bytes > 0);
  6074. if (in_residual_buf(d, d->ptr)) {
  6075. advancetobuf(d, d->buf_param, d->size_param);
  6076. }
  6077. if (curbufleft(d) >= bytes) {
  6078. consumebytes(d, buf + avail, bytes);
  6079. return DECODE_OK;
  6080. } else if (d->data_end == d->delim_end) {
  6081. seterr(d, "Submessage ended in the middle of a value or group");
  6082. return upb_pbdecoder_suspend(d);
  6083. } else {
  6084. return suspend_save(d);
  6085. }
  6086. }
  6087. // Gets the next "bytes" bytes, regardless of whether they are available in the
  6088. // current buffer or not. Returns a status code as described in decoder.int.h.
  6089. FORCEINLINE int32_t getbytes(upb_pbdecoder *d, void *buf, size_t bytes) {
  6090. if (curbufleft(d) >= bytes) {
  6091. // Buffer has enough data to satisfy.
  6092. consumebytes(d, buf, bytes);
  6093. return DECODE_OK;
  6094. } else {
  6095. return getbytes_slow(d, buf, bytes);
  6096. }
  6097. }
  6098. static NOINLINE size_t peekbytes_slow(upb_pbdecoder *d, void *buf,
  6099. size_t bytes) {
  6100. size_t ret = curbufleft(d);
  6101. memcpy(buf, d->ptr, ret);
  6102. if (in_residual_buf(d, d->ptr)) {
  6103. size_t copy = UPB_MIN(bytes - ret, d->size_param);
  6104. memcpy(buf + ret, d->buf_param, copy);
  6105. ret += copy;
  6106. }
  6107. return ret;
  6108. }
  6109. FORCEINLINE size_t peekbytes(upb_pbdecoder *d, void *buf, size_t bytes) {
  6110. if (curbufleft(d) >= bytes) {
  6111. memcpy(buf, d->ptr, bytes);
  6112. return bytes;
  6113. } else {
  6114. return peekbytes_slow(d, buf, bytes);
  6115. }
  6116. }
  6117. /* Decoding of wire types *****************************************************/
  6118. // Slow path for decoding a varint from the current buffer position.
  6119. // Returns a status code as described in decoder.int.h.
  6120. NOINLINE int32_t upb_pbdecoder_decode_varint_slow(upb_pbdecoder *d,
  6121. uint64_t *u64) {
  6122. *u64 = 0;
  6123. uint8_t byte = 0x80;
  6124. int bitpos;
  6125. for(bitpos = 0; bitpos < 70 && (byte & 0x80); bitpos += 7) {
  6126. int32_t ret = getbytes(d, &byte, 1);
  6127. if (ret >= 0) return ret;
  6128. *u64 |= (uint64_t)(byte & 0x7F) << bitpos;
  6129. }
  6130. if(bitpos == 70 && (byte & 0x80)) {
  6131. seterr(d, kUnterminatedVarint);
  6132. return upb_pbdecoder_suspend(d);
  6133. }
  6134. return DECODE_OK;
  6135. }
  6136. // Decodes a varint from the current buffer position.
  6137. // Returns a status code as described in decoder.int.h.
  6138. FORCEINLINE int32_t decode_varint(upb_pbdecoder *d, uint64_t *u64) {
  6139. if (curbufleft(d) > 0 && !(*d->ptr & 0x80)) {
  6140. *u64 = *d->ptr;
  6141. advance(d, 1);
  6142. return DECODE_OK;
  6143. } else if (curbufleft(d) >= 10) {
  6144. // Fast case.
  6145. upb_decoderet r = upb_vdecode_fast(d->ptr);
  6146. if (r.p == NULL) {
  6147. seterr(d, kUnterminatedVarint);
  6148. return upb_pbdecoder_suspend(d);
  6149. }
  6150. advance(d, r.p - d->ptr);
  6151. *u64 = r.val;
  6152. return DECODE_OK;
  6153. } else {
  6154. // Slow case -- varint spans buffer seam.
  6155. return upb_pbdecoder_decode_varint_slow(d, u64);
  6156. }
  6157. }
  6158. // Decodes a 32-bit varint from the current buffer position.
  6159. // Returns a status code as described in decoder.int.h.
  6160. FORCEINLINE int32_t decode_v32(upb_pbdecoder *d, uint32_t *u32) {
  6161. uint64_t u64;
  6162. int32_t ret = decode_varint(d, &u64);
  6163. if (ret >= 0) return ret;
  6164. if (u64 > UINT32_MAX) {
  6165. seterr(d, "Unterminated 32-bit varint");
  6166. // TODO(haberman) guarantee that this function return is >= 0 somehow,
  6167. // so we know this path will always be treated as error by our caller.
  6168. // Right now the size_t -> int32_t can overflow and produce negative values.
  6169. *u32 = 0;
  6170. return upb_pbdecoder_suspend(d);
  6171. }
  6172. *u32 = u64;
  6173. return DECODE_OK;
  6174. }
  6175. // Decodes a fixed32 from the current buffer position.
  6176. // Returns a status code as described in decoder.int.h.
  6177. // TODO: proper byte swapping for big-endian machines.
  6178. FORCEINLINE int32_t decode_fixed32(upb_pbdecoder *d, uint32_t *u32) {
  6179. return getbytes(d, u32, 4);
  6180. }
  6181. // Decodes a fixed64 from the current buffer position.
  6182. // Returns a status code as described in decoder.int.h.
  6183. // TODO: proper byte swapping for big-endian machines.
  6184. FORCEINLINE int32_t decode_fixed64(upb_pbdecoder *d, uint64_t *u64) {
  6185. return getbytes(d, u64, 8);
  6186. }
  6187. // Non-static versions of the above functions.
  6188. // These are called by the JIT for fallback paths.
  6189. int32_t upb_pbdecoder_decode_f32(upb_pbdecoder *d, uint32_t *u32) {
  6190. return decode_fixed32(d, u32);
  6191. }
  6192. int32_t upb_pbdecoder_decode_f64(upb_pbdecoder *d, uint64_t *u64) {
  6193. return decode_fixed64(d, u64);
  6194. }
  6195. static double as_double(uint64_t n) { double d; memcpy(&d, &n, 8); return d; }
  6196. static float as_float(uint32_t n) { float f; memcpy(&f, &n, 4); return f; }
  6197. // Pushes a frame onto the decoder stack.
  6198. static bool decoder_push(upb_pbdecoder *d, uint64_t end) {
  6199. upb_pbdecoder_frame *fr = d->top;
  6200. if (end > fr->end_ofs) {
  6201. seterr(d, "Submessage end extends past enclosing submessage.");
  6202. return false;
  6203. } else if ((fr + 1) == d->limit) {
  6204. seterr(d, kPbDecoderStackOverflow);
  6205. return false;
  6206. }
  6207. fr++;
  6208. fr->end_ofs = end;
  6209. fr->dispatch = NULL;
  6210. fr->groupnum = 0;
  6211. d->top = fr;
  6212. return true;
  6213. }
  6214. static bool pushtagdelim(upb_pbdecoder *d, uint32_t arg) {
  6215. // While we expect to see an "end" tag (either ENDGROUP or a non-sequence
  6216. // field number) prior to hitting any enclosing submessage end, pushing our
  6217. // existing delim end prevents us from continuing to parse values from a
  6218. // corrupt proto that doesn't give us an END tag in time.
  6219. if (!decoder_push(d, d->top->end_ofs))
  6220. return false;
  6221. d->top->groupnum = arg;
  6222. return true;
  6223. }
  6224. // Pops a frame from the decoder stack.
  6225. static void decoder_pop(upb_pbdecoder *d) { d->top--; }
  6226. NOINLINE int32_t upb_pbdecoder_checktag_slow(upb_pbdecoder *d,
  6227. uint64_t expected) {
  6228. uint64_t data = 0;
  6229. size_t bytes = upb_value_size(expected);
  6230. size_t read = peekbytes(d, &data, bytes);
  6231. if (read == bytes && data == expected) {
  6232. // Advance past matched bytes.
  6233. int32_t ok = getbytes(d, &data, read);
  6234. UPB_ASSERT_VAR(ok, ok < 0);
  6235. return DECODE_OK;
  6236. } else if (read < bytes && memcmp(&data, &expected, read) == 0) {
  6237. return suspend_save(d);
  6238. } else {
  6239. return DECODE_MISMATCH;
  6240. }
  6241. }
  6242. int32_t upb_pbdecoder_skipunknown(upb_pbdecoder *d, int32_t fieldnum,
  6243. uint8_t wire_type) {
  6244. if (fieldnum >= 0)
  6245. goto have_tag;
  6246. while (true) {
  6247. uint32_t tag;
  6248. CHECK_RETURN(decode_v32(d, &tag));
  6249. wire_type = tag & 0x7;
  6250. fieldnum = tag >> 3;
  6251. have_tag:
  6252. if (fieldnum == 0) {
  6253. seterr(d, "Saw invalid field number (0)");
  6254. return upb_pbdecoder_suspend(d);
  6255. }
  6256. // TODO: deliver to unknown field callback.
  6257. switch (wire_type) {
  6258. case UPB_WIRE_TYPE_32BIT:
  6259. CHECK_RETURN(skip(d, 4));
  6260. break;
  6261. case UPB_WIRE_TYPE_64BIT:
  6262. CHECK_RETURN(skip(d, 8));
  6263. break;
  6264. case UPB_WIRE_TYPE_VARINT: {
  6265. uint64_t u64;
  6266. CHECK_RETURN(decode_varint(d, &u64));
  6267. break;
  6268. }
  6269. case UPB_WIRE_TYPE_DELIMITED: {
  6270. uint32_t len;
  6271. CHECK_RETURN(decode_v32(d, &len));
  6272. CHECK_RETURN(skip(d, len));
  6273. break;
  6274. }
  6275. case UPB_WIRE_TYPE_START_GROUP:
  6276. CHECK_SUSPEND(pushtagdelim(d, -fieldnum));
  6277. break;
  6278. case UPB_WIRE_TYPE_END_GROUP:
  6279. if (fieldnum == -d->top->groupnum) {
  6280. decoder_pop(d);
  6281. } else if (fieldnum == d->top->groupnum) {
  6282. return DECODE_ENDGROUP;
  6283. } else {
  6284. seterr(d, "Unmatched ENDGROUP tag.");
  6285. return upb_pbdecoder_suspend(d);
  6286. }
  6287. break;
  6288. default:
  6289. seterr(d, "Invalid wire type");
  6290. return upb_pbdecoder_suspend(d);
  6291. }
  6292. if (d->top->groupnum >= 0) {
  6293. return DECODE_OK;
  6294. }
  6295. if (d->ptr == d->delim_end) {
  6296. seterr(d, "Enclosing submessage ended in the middle of value or group");
  6297. // Unlike most errors we notice during parsing, right now we have consumed
  6298. // all of the user's input.
  6299. //
  6300. // There are three different options for how to handle this case:
  6301. //
  6302. // 1. decode() = short count, error = set
  6303. // 2. decode() = full count, error = set
  6304. // 3. decode() = full count, error NOT set, short count and error will
  6305. // be reported on next call to decode() (or end())
  6306. //
  6307. // (1) and (3) have the advantage that they preserve the invariant that an
  6308. // error occurs iff decode() returns a short count.
  6309. //
  6310. // (2) and (3) have the advantage of reflecting the fact that all of the
  6311. // bytes were in fact parsed (and possibly delivered to the unknown field
  6312. // handler, in the future when that is supported).
  6313. //
  6314. // (3) requires extra state in the decode (a place to store the "permanent
  6315. // error" that we should return for all subsequent attempts to decode).
  6316. // But we likely want this anyway.
  6317. //
  6318. // Right now we do (1), thanks to the fact that we checkpoint *after* this
  6319. // check. (3) may be a better choice long term; unclear at the moment.
  6320. return upb_pbdecoder_suspend(d);
  6321. }
  6322. checkpoint(d);
  6323. }
  6324. }
  6325. static void goto_endmsg(upb_pbdecoder *d) {
  6326. upb_value v;
  6327. bool found = upb_inttable_lookup32(d->top->dispatch, DISPATCH_ENDMSG, &v);
  6328. UPB_ASSERT_VAR(found, found);
  6329. d->pc = d->top->base + upb_value_getuint64(v);
  6330. }
  6331. // Parses a tag and jumps to the corresponding bytecode instruction for this
  6332. // field.
  6333. //
  6334. // If the tag is unknown (or the wire type doesn't match), parses the field as
  6335. // unknown. If the tag is a valid ENDGROUP tag, jumps to the bytecode
  6336. // instruction for the end of message.
  6337. static int32_t dispatch(upb_pbdecoder *d) {
  6338. upb_inttable *dispatch = d->top->dispatch;
  6339. // Decode tag.
  6340. uint32_t tag;
  6341. CHECK_RETURN(decode_v32(d, &tag));
  6342. uint8_t wire_type = tag & 0x7;
  6343. uint32_t fieldnum = tag >> 3;
  6344. // Lookup tag. Because of packed/non-packed compatibility, we have to
  6345. // check the wire type against two possibilities.
  6346. upb_value val;
  6347. if (fieldnum != DISPATCH_ENDMSG &&
  6348. upb_inttable_lookup32(dispatch, fieldnum, &val)) {
  6349. uint64_t v = upb_value_getuint64(val);
  6350. if (wire_type == (v & 0xff)) {
  6351. d->pc = d->top->base + (v >> 16);
  6352. return DECODE_OK;
  6353. } else if (wire_type == ((v >> 8) & 0xff)) {
  6354. bool found =
  6355. upb_inttable_lookup(dispatch, fieldnum + UPB_MAX_FIELDNUMBER, &val);
  6356. UPB_ASSERT_VAR(found, found);
  6357. d->pc = d->top->base + upb_value_getuint64(val);
  6358. return DECODE_OK;
  6359. }
  6360. }
  6361. // Unknown field or ENDGROUP.
  6362. int32_t ret = upb_pbdecoder_skipunknown(d, fieldnum, wire_type);
  6363. if (ret == DECODE_ENDGROUP) {
  6364. goto_endmsg(d);
  6365. return DECODE_OK;
  6366. } else {
  6367. d->pc = d->last - 1; // Rewind to CHECKDELIM.
  6368. return ret;
  6369. }
  6370. }
  6371. // Callers know that the stack is more than one deep because the opcodes that
  6372. // call this only occur after PUSH operations.
  6373. upb_pbdecoder_frame *outer_frame(upb_pbdecoder *d) {
  6374. assert(d->top != d->stack);
  6375. return d->top - 1;
  6376. }
  6377. /* The main decoding loop *****************************************************/
  6378. // The main decoder VM function. Uses traditional bytecode dispatch loop with a
  6379. // switch() statement.
  6380. size_t upb_pbdecoder_decode(void *closure, const void *hd, const char *buf,
  6381. size_t size, const upb_bufhandle *handle) {
  6382. upb_pbdecoder *d = closure;
  6383. const mgroup *group = hd;
  6384. assert(buf);
  6385. int32_t result = upb_pbdecoder_resume(d, NULL, buf, size, handle);
  6386. if (result == DECODE_ENDGROUP) {
  6387. goto_endmsg(d);
  6388. }
  6389. CHECK_RETURN(result);
  6390. UPB_UNUSED(group);
  6391. #define VMCASE(op, code) \
  6392. case op: { code; if (consumes_input(op)) checkpoint(d); break; }
  6393. #define PRIMITIVE_OP(type, wt, name, convfunc, ctype) \
  6394. VMCASE(OP_PARSE_ ## type, { \
  6395. ctype val; \
  6396. CHECK_RETURN(decode_ ## wt(d, &val)); \
  6397. upb_sink_put ## name(&d->top->sink, arg, (convfunc)(val)); \
  6398. })
  6399. while(1) {
  6400. d->last = d->pc;
  6401. int32_t instruction = *d->pc++;
  6402. opcode op = getop(instruction);
  6403. uint32_t arg = instruction >> 8;
  6404. int32_t longofs = arg;
  6405. assert(d->ptr != d->residual_end);
  6406. #ifdef UPB_DUMP_BYTECODE
  6407. fprintf(stderr, "s_ofs=%d buf_ofs=%d data_rem=%d buf_rem=%d delim_rem=%d "
  6408. "%x %s (%d)\n",
  6409. (int)offset(d),
  6410. (int)(d->ptr - d->buf),
  6411. (int)(d->data_end - d->ptr),
  6412. (int)(d->end - d->ptr),
  6413. (int)((d->top->end_ofs - d->bufstart_ofs) - (d->ptr - d->buf)),
  6414. (int)(d->pc - 1 - group->bytecode),
  6415. upb_pbdecoder_getopname(op),
  6416. arg);
  6417. #endif
  6418. switch (op) {
  6419. // Technically, we are losing data if we see a 32-bit varint that is not
  6420. // properly sign-extended. We could detect this and error about the data
  6421. // loss, but proto2 does not do this, so we pass.
  6422. PRIMITIVE_OP(INT32, varint, int32, int32_t, uint64_t)
  6423. PRIMITIVE_OP(INT64, varint, int64, int64_t, uint64_t)
  6424. PRIMITIVE_OP(UINT32, varint, uint32, uint32_t, uint64_t)
  6425. PRIMITIVE_OP(UINT64, varint, uint64, uint64_t, uint64_t)
  6426. PRIMITIVE_OP(FIXED32, fixed32, uint32, uint32_t, uint32_t)
  6427. PRIMITIVE_OP(FIXED64, fixed64, uint64, uint64_t, uint64_t)
  6428. PRIMITIVE_OP(SFIXED32, fixed32, int32, int32_t, uint32_t)
  6429. PRIMITIVE_OP(SFIXED64, fixed64, int64, int64_t, uint64_t)
  6430. PRIMITIVE_OP(BOOL, varint, bool, bool, uint64_t)
  6431. PRIMITIVE_OP(DOUBLE, fixed64, double, as_double, uint64_t)
  6432. PRIMITIVE_OP(FLOAT, fixed32, float, as_float, uint32_t)
  6433. PRIMITIVE_OP(SINT32, varint, int32, upb_zzdec_32, uint64_t)
  6434. PRIMITIVE_OP(SINT64, varint, int64, upb_zzdec_64, uint64_t)
  6435. VMCASE(OP_SETDISPATCH,
  6436. d->top->base = d->pc - 1;
  6437. memcpy(&d->top->dispatch, d->pc, sizeof(void*));
  6438. d->pc += sizeof(void*) / sizeof(uint32_t);
  6439. )
  6440. VMCASE(OP_STARTMSG,
  6441. CHECK_SUSPEND(upb_sink_startmsg(&d->top->sink));
  6442. )
  6443. VMCASE(OP_ENDMSG,
  6444. CHECK_SUSPEND(upb_sink_endmsg(&d->top->sink, d->status));
  6445. )
  6446. VMCASE(OP_STARTSEQ,
  6447. upb_pbdecoder_frame *outer = outer_frame(d);
  6448. CHECK_SUSPEND(upb_sink_startseq(&outer->sink, arg, &d->top->sink));
  6449. )
  6450. VMCASE(OP_ENDSEQ,
  6451. CHECK_SUSPEND(upb_sink_endseq(&d->top->sink, arg));
  6452. )
  6453. VMCASE(OP_STARTSUBMSG,
  6454. upb_pbdecoder_frame *outer = outer_frame(d);
  6455. CHECK_SUSPEND(upb_sink_startsubmsg(&outer->sink, arg, &d->top->sink));
  6456. )
  6457. VMCASE(OP_ENDSUBMSG,
  6458. CHECK_SUSPEND(upb_sink_endsubmsg(&d->top->sink, arg));
  6459. )
  6460. VMCASE(OP_STARTSTR,
  6461. uint32_t len = d->top->end_ofs - offset(d);
  6462. upb_pbdecoder_frame *outer = outer_frame(d);
  6463. CHECK_SUSPEND(upb_sink_startstr(&outer->sink, arg, len, &d->top->sink));
  6464. if (len == 0) {
  6465. d->pc++; // Skip OP_STRING.
  6466. }
  6467. )
  6468. VMCASE(OP_STRING,
  6469. uint32_t len = curbufleft(d);
  6470. size_t n = upb_sink_putstring(&d->top->sink, arg, d->ptr, len, handle);
  6471. if (n > len) {
  6472. if (n > d->top->end_ofs - offset(d)) {
  6473. seterr(d, "Tried to skip past end of string.");
  6474. return upb_pbdecoder_suspend(d);
  6475. } else {
  6476. int32_t ret = skip(d, n);
  6477. // This shouldn't return DECODE_OK, because n > len.
  6478. assert(ret >= 0);
  6479. return ret;
  6480. }
  6481. }
  6482. advance(d, n);
  6483. if (n < len || d->delim_end == NULL) {
  6484. // We aren't finished with this string yet.
  6485. d->pc--; // Repeat OP_STRING.
  6486. if (n > 0) checkpoint(d);
  6487. return upb_pbdecoder_suspend(d);
  6488. }
  6489. )
  6490. VMCASE(OP_ENDSTR,
  6491. CHECK_SUSPEND(upb_sink_endstr(&d->top->sink, arg));
  6492. )
  6493. VMCASE(OP_PUSHTAGDELIM,
  6494. CHECK_SUSPEND(pushtagdelim(d, arg));
  6495. )
  6496. VMCASE(OP_SETBIGGROUPNUM,
  6497. d->top->groupnum = *d->pc++;
  6498. )
  6499. VMCASE(OP_POP,
  6500. assert(d->top > d->stack);
  6501. decoder_pop(d);
  6502. )
  6503. VMCASE(OP_PUSHLENDELIM,
  6504. uint32_t len;
  6505. CHECK_RETURN(decode_v32(d, &len));
  6506. CHECK_SUSPEND(decoder_push(d, offset(d) + len));
  6507. set_delim_end(d);
  6508. )
  6509. VMCASE(OP_SETDELIM,
  6510. set_delim_end(d);
  6511. )
  6512. VMCASE(OP_CHECKDELIM,
  6513. // We are guaranteed of this assert because we never allow ourselves to
  6514. // consume bytes beyond data_end, which covers delim_end when non-NULL.
  6515. assert(!(d->delim_end && d->ptr > d->delim_end));
  6516. if (d->ptr == d->delim_end)
  6517. d->pc += longofs;
  6518. )
  6519. VMCASE(OP_CALL,
  6520. d->callstack[d->call_len++] = d->pc;
  6521. d->pc += longofs;
  6522. )
  6523. VMCASE(OP_RET,
  6524. assert(d->call_len > 0);
  6525. d->pc = d->callstack[--d->call_len];
  6526. )
  6527. VMCASE(OP_BRANCH,
  6528. d->pc += longofs;
  6529. )
  6530. VMCASE(OP_TAG1,
  6531. CHECK_SUSPEND(curbufleft(d) > 0);
  6532. uint8_t expected = (arg >> 8) & 0xff;
  6533. if (*d->ptr == expected) {
  6534. advance(d, 1);
  6535. } else {
  6536. int8_t shortofs;
  6537. badtag:
  6538. shortofs = arg;
  6539. if (shortofs == LABEL_DISPATCH) {
  6540. CHECK_RETURN(dispatch(d));
  6541. } else {
  6542. d->pc += shortofs;
  6543. break; // Avoid checkpoint().
  6544. }
  6545. }
  6546. )
  6547. VMCASE(OP_TAG2,
  6548. CHECK_SUSPEND(curbufleft(d) > 0);
  6549. uint16_t expected = (arg >> 8) & 0xffff;
  6550. if (curbufleft(d) >= 2) {
  6551. uint16_t actual;
  6552. memcpy(&actual, d->ptr, 2);
  6553. if (expected == actual) {
  6554. advance(d, 2);
  6555. } else {
  6556. goto badtag;
  6557. }
  6558. } else {
  6559. int32_t result = upb_pbdecoder_checktag_slow(d, expected);
  6560. if (result == DECODE_MISMATCH) goto badtag;
  6561. if (result >= 0) return result;
  6562. }
  6563. )
  6564. VMCASE(OP_TAGN, {
  6565. uint64_t expected;
  6566. memcpy(&expected, d->pc, 8);
  6567. d->pc += 2;
  6568. int32_t result = upb_pbdecoder_checktag_slow(d, expected);
  6569. if (result == DECODE_MISMATCH) goto badtag;
  6570. if (result >= 0) return result;
  6571. })
  6572. VMCASE(OP_HALT, {
  6573. return size;
  6574. })
  6575. }
  6576. }
  6577. }
  6578. void *upb_pbdecoder_startbc(void *closure, const void *pc, size_t size_hint) {
  6579. upb_pbdecoder *d = closure;
  6580. UPB_UNUSED(size_hint);
  6581. d->call_len = 1;
  6582. d->pc = pc;
  6583. return d;
  6584. }
  6585. void *upb_pbdecoder_startjit(void *closure, const void *hd, size_t size_hint) {
  6586. UPB_UNUSED(hd);
  6587. UPB_UNUSED(size_hint);
  6588. upb_pbdecoder *d = closure;
  6589. d->call_len = 0;
  6590. return d;
  6591. }
  6592. bool upb_pbdecoder_end(void *closure, const void *handler_data) {
  6593. upb_pbdecoder *d = closure;
  6594. const upb_pbdecodermethod *method = handler_data;
  6595. if (d->residual_end > d->residual) {
  6596. seterr(d, "Unexpected EOF");
  6597. return false;
  6598. }
  6599. if (d->top->end_ofs != UINT64_MAX) {
  6600. seterr(d, "Unexpected EOF inside delimited string");
  6601. return false;
  6602. }
  6603. // Message ends here.
  6604. uint64_t end = offset(d);
  6605. d->top->end_ofs = end;
  6606. char dummy;
  6607. #ifdef UPB_USE_JIT_X64
  6608. const mgroup *group = (const mgroup*)method->group;
  6609. if (group->jit_code) {
  6610. if (d->top != d->stack)
  6611. d->stack->end_ofs = 0;
  6612. group->jit_code(closure, method->code_base.ptr, &dummy, 0, NULL);
  6613. } else {
  6614. #endif
  6615. d->stack->end_ofs = end;
  6616. const uint32_t *p = d->pc;
  6617. // Check the previous bytecode, but guard against beginning.
  6618. if (p != method->code_base.ptr) p--;
  6619. if (getop(*p) == OP_CHECKDELIM) {
  6620. // Rewind from OP_TAG* to OP_CHECKDELIM.
  6621. assert(getop(*d->pc) == OP_TAG1 ||
  6622. getop(*d->pc) == OP_TAG2 ||
  6623. getop(*d->pc) == OP_TAGN);
  6624. d->pc = p;
  6625. }
  6626. upb_pbdecoder_decode(closure, handler_data, &dummy, 0, NULL);
  6627. #ifdef UPB_USE_JIT_X64
  6628. }
  6629. #endif
  6630. if (d->call_len != 0) {
  6631. seterr(d, "Unexpected EOF");
  6632. return false;
  6633. }
  6634. return true;
  6635. }
  6636. void upb_pbdecoder_init(upb_pbdecoder *d, const upb_pbdecodermethod *m,
  6637. upb_status *s) {
  6638. d->limit = &d->stack[UPB_DECODER_MAX_NESTING];
  6639. upb_bytessink_reset(&d->input_, &m->input_handler_, d);
  6640. d->method_ = m;
  6641. d->callstack[0] = &halt;
  6642. d->status = s;
  6643. upb_pbdecoder_reset(d);
  6644. }
  6645. void upb_pbdecoder_reset(upb_pbdecoder *d) {
  6646. d->top = d->stack;
  6647. d->top->end_ofs = UINT64_MAX;
  6648. d->top->groupnum = 0;
  6649. d->bufstart_ofs = 0;
  6650. d->ptr = d->residual;
  6651. d->buf = d->residual;
  6652. d->end = d->residual;
  6653. d->residual_end = d->residual;
  6654. d->call_len = 1;
  6655. }
  6656. uint64_t upb_pbdecoder_bytesparsed(const upb_pbdecoder *d) {
  6657. return offset(d);
  6658. }
  6659. // Not currently required, but to support outgrowing the static stack we need
  6660. // this.
  6661. void upb_pbdecoder_uninit(upb_pbdecoder *d) {
  6662. UPB_UNUSED(d);
  6663. }
  6664. const upb_pbdecodermethod *upb_pbdecoder_method(const upb_pbdecoder *d) {
  6665. return d->method_;
  6666. }
  6667. bool upb_pbdecoder_resetoutput(upb_pbdecoder *d, upb_sink* sink) {
  6668. // TODO(haberman): do we need to test whether the decoder is already on the
  6669. // stack (like calling this from within a callback)? Should we support
  6670. // rebinding the output at all?
  6671. assert(sink);
  6672. if (d->method_->dest_handlers_) {
  6673. if (sink->handlers != d->method_->dest_handlers_)
  6674. return false;
  6675. }
  6676. upb_sink_reset(&d->top->sink, sink->handlers, sink->closure);
  6677. return true;
  6678. }
  6679. upb_bytessink *upb_pbdecoder_input(upb_pbdecoder *d) {
  6680. return &d->input_;
  6681. }
  6682. /*
  6683. * upb - a minimalist implementation of protocol buffers.
  6684. *
  6685. * Copyright (c) 2014 Google Inc. See LICENSE for details.
  6686. * Author: Josh Haberman <jhaberman@gmail.com>
  6687. *
  6688. * Since we are implementing pure handlers (ie. without any out-of-band access
  6689. * to pre-computed lengths), we have to buffer all submessages before we can
  6690. * emit even their first byte.
  6691. *
  6692. * Not knowing the size of submessages also means we can't write a perfect
  6693. * zero-copy implementation, even with buffering. Lengths are stored as
  6694. * varints, which means that we don't know how many bytes to reserve for the
  6695. * length until we know what the length is.
  6696. *
  6697. * This leaves us with three main choices:
  6698. *
  6699. * 1. buffer all submessage data in a temporary buffer, then copy it exactly
  6700. * once into the output buffer.
  6701. *
  6702. * 2. attempt to buffer data directly into the output buffer, estimating how
  6703. * many bytes each length will take. When our guesses are wrong, use
  6704. * memmove() to grow or shrink the allotted space.
  6705. *
  6706. * 3. buffer directly into the output buffer, allocating a max length
  6707. * ahead-of-time for each submessage length. If we overallocated, we waste
  6708. * space, but no memcpy() or memmove() is required. This approach requires
  6709. * defining a maximum size for submessages and rejecting submessages that
  6710. * exceed that size.
  6711. *
  6712. * (2) and (3) have the potential to have better performance, but they are more
  6713. * complicated and subtle to implement:
  6714. *
  6715. * (3) requires making an arbitrary choice of the maximum message size; it
  6716. * wastes space when submessages are shorter than this and fails
  6717. * completely when they are longer. This makes it more finicky and
  6718. * requires configuration based on the input. It also makes it impossible
  6719. * to perfectly match the output of reference encoders that always use the
  6720. * optimal amount of space for each length.
  6721. *
  6722. * (2) requires guessing the the size upfront, and if multiple lengths are
  6723. * guessed wrong the minimum required number of memmove() operations may
  6724. * be complicated to compute correctly. Implemented properly, it may have
  6725. * a useful amortized or average cost, but more investigation is required
  6726. * to determine this and what the optimal algorithm is to achieve it.
  6727. *
  6728. * (1) makes you always pay for exactly one copy, but its implementation is
  6729. * the simplest and its performance is predictable.
  6730. *
  6731. * So for now, we implement (1) only. If we wish to optimize later, we should
  6732. * be able to do it without affecting users.
  6733. *
  6734. * The strategy is to buffer the segments of data that do *not* depend on
  6735. * unknown lengths in one buffer, and keep a separate buffer of segment pointers
  6736. * and lengths. When the top-level submessage ends, we can go beginning to end,
  6737. * alternating the writing of lengths with memcpy() of the rest of the data.
  6738. * At the top level though, no buffering is required.
  6739. */
  6740. #include <stdlib.h>
  6741. /* low-level buffering ********************************************************/
  6742. // Low-level functions for interacting with the output buffer.
  6743. // TODO(haberman): handle pushback
  6744. static void putbuf(upb_pb_encoder *e, const char *buf, size_t len) {
  6745. size_t n = upb_bytessink_putbuf(e->output_, e->subc, buf, len, NULL);
  6746. UPB_ASSERT_VAR(n, n == len);
  6747. }
  6748. static upb_pb_encoder_segment *top(upb_pb_encoder *e) {
  6749. return &e->segbuf[*e->top];
  6750. }
  6751. // Call to ensure that at least "bytes" bytes are available for writing at
  6752. // e->ptr. Returns false if the bytes could not be allocated.
  6753. static bool reserve(upb_pb_encoder *e, size_t bytes) {
  6754. if ((e->limit - e->ptr) < bytes) {
  6755. size_t needed = bytes + (e->ptr - e->buf);
  6756. size_t old_size = e->limit - e->buf;
  6757. size_t new_size = old_size;
  6758. while (new_size < needed) {
  6759. new_size *= 2;
  6760. }
  6761. char *realloc_from = (e->buf == e->initbuf) ? NULL : e->buf;
  6762. char *new_buf = realloc(realloc_from, new_size);
  6763. if (new_buf == NULL) {
  6764. return false;
  6765. }
  6766. if (realloc_from == NULL) {
  6767. memcpy(new_buf, e->initbuf, old_size);
  6768. }
  6769. e->ptr = new_buf + (e->ptr - e->buf);
  6770. e->runbegin = new_buf + (e->runbegin - e->buf);
  6771. e->limit = new_buf + new_size;
  6772. e->buf = new_buf;
  6773. }
  6774. return true;
  6775. }
  6776. // Call when "bytes" bytes have been writte at e->ptr. The caller *must* have
  6777. // previously called reserve() with at least this many bytes.
  6778. static void encoder_advance(upb_pb_encoder *e, size_t bytes) {
  6779. assert((e->limit - e->ptr) >= bytes);
  6780. e->ptr += bytes;
  6781. }
  6782. // Call when all of the bytes for a handler have been written. Flushes the
  6783. // bytes if possible and necessary, returning false if this failed.
  6784. static bool commit(upb_pb_encoder *e) {
  6785. if (!e->top) {
  6786. // We aren't inside a delimited region. Flush our accumulated bytes to
  6787. // the output.
  6788. //
  6789. // TODO(haberman): in the future we may want to delay flushing for
  6790. // efficiency reasons.
  6791. putbuf(e, e->buf, e->ptr - e->buf);
  6792. e->ptr = e->buf;
  6793. }
  6794. return true;
  6795. }
  6796. // Writes the given bytes to the buffer, handling reserve/advance.
  6797. static bool encode_bytes(upb_pb_encoder *e, const void *data, size_t len) {
  6798. if (!reserve(e, len)) {
  6799. return false;
  6800. }
  6801. memcpy(e->ptr, data, len);
  6802. encoder_advance(e, len);
  6803. return true;
  6804. }
  6805. // Finish the current run by adding the run totals to the segment and message
  6806. // length.
  6807. static void accumulate(upb_pb_encoder *e) {
  6808. assert(e->ptr >= e->runbegin);
  6809. size_t run_len = e->ptr - e->runbegin;
  6810. e->segptr->seglen += run_len;
  6811. top(e)->msglen += run_len;
  6812. e->runbegin = e->ptr;
  6813. }
  6814. // Call to indicate the start of delimited region for which the full length is
  6815. // not yet known. All data will be buffered until the length is known.
  6816. // Delimited regions may be nested; their lengths will all be tracked properly.
  6817. static bool start_delim(upb_pb_encoder *e) {
  6818. if (e->top) {
  6819. // We are already buffering, advance to the next segment and push it on the
  6820. // stack.
  6821. accumulate(e);
  6822. if (++e->top == e->stacklimit) {
  6823. // TODO(haberman): grow stack?
  6824. return false;
  6825. }
  6826. if (++e->segptr == e->seglimit) {
  6827. upb_pb_encoder_segment *realloc_from =
  6828. (e->segbuf == e->seginitbuf) ? NULL : e->segbuf;
  6829. size_t old_size =
  6830. (e->seglimit - e->segbuf) * sizeof(upb_pb_encoder_segment);
  6831. size_t new_size = old_size * 2;
  6832. upb_pb_encoder_segment *new_buf = realloc(realloc_from, new_size);
  6833. if (new_buf == NULL) {
  6834. return false;
  6835. }
  6836. if (realloc_from == NULL) {
  6837. memcpy(new_buf, e->seginitbuf, old_size);
  6838. }
  6839. e->segptr = new_buf + (e->segptr - e->segbuf);
  6840. e->seglimit = new_buf + (new_size / sizeof(upb_pb_encoder_segment));
  6841. e->segbuf = new_buf;
  6842. }
  6843. } else {
  6844. // We were previously at the top level, start buffering.
  6845. e->segptr = e->segbuf;
  6846. e->top = e->stack;
  6847. e->runbegin = e->ptr;
  6848. }
  6849. *e->top = e->segptr - e->segbuf;
  6850. e->segptr->seglen = 0;
  6851. e->segptr->msglen = 0;
  6852. return true;
  6853. }
  6854. // Call to indicate the end of a delimited region. We now know the length of
  6855. // the delimited region. If we are not nested inside any other delimited
  6856. // regions, we can now emit all of the buffered data we accumulated.
  6857. static bool end_delim(upb_pb_encoder *e) {
  6858. accumulate(e);
  6859. size_t msglen = top(e)->msglen;
  6860. if (e->top == e->stack) {
  6861. // All lengths are now available, emit all buffered data.
  6862. char buf[UPB_PB_VARINT_MAX_LEN];
  6863. upb_pb_encoder_segment *s;
  6864. const char *ptr = e->buf;
  6865. for (s = e->segbuf; s <= e->segptr; s++) {
  6866. size_t lenbytes = upb_vencode64(s->msglen, buf);
  6867. putbuf(e, buf, lenbytes);
  6868. putbuf(e, ptr, s->seglen);
  6869. ptr += s->seglen;
  6870. }
  6871. e->ptr = e->buf;
  6872. e->top = NULL;
  6873. } else {
  6874. // Need to keep buffering; propagate length info into enclosing submessages.
  6875. --e->top;
  6876. top(e)->msglen += msglen + upb_varint_size(msglen);
  6877. }
  6878. return true;
  6879. }
  6880. /* tag_t **********************************************************************/
  6881. // A precomputed (pre-encoded) tag and length.
  6882. typedef struct {
  6883. uint8_t bytes;
  6884. char tag[7];
  6885. } tag_t;
  6886. // Allocates a new tag for this field, and sets it in these handlerattr.
  6887. static void new_tag(upb_handlers *h, const upb_fielddef *f, upb_wiretype_t wt,
  6888. upb_handlerattr *attr) {
  6889. uint32_t n = upb_fielddef_number(f);
  6890. tag_t *tag = malloc(sizeof(tag_t));
  6891. tag->bytes = upb_vencode64((n << 3) | wt, tag->tag);
  6892. upb_handlerattr_init(attr);
  6893. upb_handlerattr_sethandlerdata(attr, tag);
  6894. upb_handlers_addcleanup(h, tag, free);
  6895. }
  6896. static bool encode_tag(upb_pb_encoder *e, const tag_t *tag) {
  6897. return encode_bytes(e, tag->tag, tag->bytes);
  6898. }
  6899. /* encoding of wire types *****************************************************/
  6900. static bool encode_fixed64(upb_pb_encoder *e, uint64_t val) {
  6901. // TODO(haberman): byte-swap for big endian.
  6902. return encode_bytes(e, &val, sizeof(uint64_t));
  6903. }
  6904. static bool encode_fixed32(upb_pb_encoder *e, uint32_t val) {
  6905. // TODO(haberman): byte-swap for big endian.
  6906. return encode_bytes(e, &val, sizeof(uint32_t));
  6907. }
  6908. static bool encode_varint(upb_pb_encoder *e, uint64_t val) {
  6909. if (!reserve(e, UPB_PB_VARINT_MAX_LEN)) {
  6910. return false;
  6911. }
  6912. encoder_advance(e, upb_vencode64(val, e->ptr));
  6913. return true;
  6914. }
  6915. static uint64_t dbl2uint64(double d) {
  6916. uint64_t ret;
  6917. memcpy(&ret, &d, sizeof(uint64_t));
  6918. return ret;
  6919. }
  6920. static uint32_t flt2uint32(float d) {
  6921. uint32_t ret;
  6922. memcpy(&ret, &d, sizeof(uint32_t));
  6923. return ret;
  6924. }
  6925. /* encoding of proto types ****************************************************/
  6926. static bool startmsg(void *c, const void *hd) {
  6927. upb_pb_encoder *e = c;
  6928. UPB_UNUSED(hd);
  6929. if (e->depth++ == 0) {
  6930. upb_bytessink_start(e->output_, 0, &e->subc);
  6931. }
  6932. return true;
  6933. }
  6934. static bool endmsg(void *c, const void *hd, upb_status *status) {
  6935. upb_pb_encoder *e = c;
  6936. UPB_UNUSED(hd);
  6937. UPB_UNUSED(status);
  6938. if (--e->depth == 0) {
  6939. upb_bytessink_end(e->output_);
  6940. }
  6941. return true;
  6942. }
  6943. static void *encode_startdelimfield(void *c, const void *hd) {
  6944. bool ok = encode_tag(c, hd) && commit(c) && start_delim(c);
  6945. return ok ? c : UPB_BREAK;
  6946. }
  6947. static bool encode_enddelimfield(void *c, const void *hd) {
  6948. UPB_UNUSED(hd);
  6949. return end_delim(c);
  6950. }
  6951. static void *encode_startgroup(void *c, const void *hd) {
  6952. return (encode_tag(c, hd) && commit(c)) ? c : UPB_BREAK;
  6953. }
  6954. static bool encode_endgroup(void *c, const void *hd) {
  6955. return encode_tag(c, hd) && commit(c);
  6956. }
  6957. static void *encode_startstr(void *c, const void *hd, size_t size_hint) {
  6958. UPB_UNUSED(size_hint);
  6959. return encode_startdelimfield(c, hd);
  6960. }
  6961. static size_t encode_strbuf(void *c, const void *hd, const char *buf,
  6962. size_t len, const upb_bufhandle *h) {
  6963. UPB_UNUSED(hd);
  6964. UPB_UNUSED(h);
  6965. return encode_bytes(c, buf, len) ? len : 0;
  6966. }
  6967. #define T(type, ctype, convert, encode) \
  6968. static bool encode_scalar_##type(void *e, const void *hd, ctype val) { \
  6969. return encode_tag(e, hd) && encode(e, (convert)(val)) && commit(e); \
  6970. } \
  6971. static bool encode_packed_##type(void *e, const void *hd, ctype val) { \
  6972. UPB_UNUSED(hd); \
  6973. return encode(e, (convert)(val)); \
  6974. }
  6975. T(double, double, dbl2uint64, encode_fixed64)
  6976. T(float, float, flt2uint32, encode_fixed32);
  6977. T(int64, int64_t, uint64_t, encode_varint);
  6978. T(int32, int32_t, uint32_t, encode_varint);
  6979. T(fixed64, uint64_t, uint64_t, encode_fixed64);
  6980. T(fixed32, uint32_t, uint32_t, encode_fixed32);
  6981. T(bool, bool, bool, encode_varint);
  6982. T(uint32, uint32_t, uint32_t, encode_varint);
  6983. T(uint64, uint64_t, uint64_t, encode_varint);
  6984. T(enum, int32_t, uint32_t, encode_varint);
  6985. T(sfixed32, int32_t, uint32_t, encode_fixed32);
  6986. T(sfixed64, int64_t, uint64_t, encode_fixed64);
  6987. T(sint32, int32_t, upb_zzenc_32, encode_varint);
  6988. T(sint64, int64_t, upb_zzenc_64, encode_varint);
  6989. #undef T
  6990. /* code to build the handlers *************************************************/
  6991. static void newhandlers_callback(const void *closure, upb_handlers *h) {
  6992. UPB_UNUSED(closure);
  6993. upb_handlers_setstartmsg(h, startmsg, NULL);
  6994. upb_handlers_setendmsg(h, endmsg, NULL);
  6995. const upb_msgdef *m = upb_handlers_msgdef(h);
  6996. upb_msg_iter i;
  6997. for(upb_msg_begin(&i, m); !upb_msg_done(&i); upb_msg_next(&i)) {
  6998. const upb_fielddef *f = upb_msg_iter_field(&i);
  6999. bool packed = upb_fielddef_isseq(f) && upb_fielddef_isprimitive(f) &&
  7000. upb_fielddef_packed(f);
  7001. upb_handlerattr attr;
  7002. upb_wiretype_t wt =
  7003. packed ? UPB_WIRE_TYPE_DELIMITED
  7004. : upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  7005. // Pre-encode the tag for this field.
  7006. new_tag(h, f, wt, &attr);
  7007. if (packed) {
  7008. upb_handlers_setstartseq(h, f, encode_startdelimfield, &attr);
  7009. upb_handlers_setendseq(h, f, encode_enddelimfield, &attr);
  7010. }
  7011. #define T(upper, lower, upbtype) \
  7012. case UPB_DESCRIPTOR_TYPE_##upper: \
  7013. if (packed) { \
  7014. upb_handlers_set##upbtype(h, f, encode_packed_##lower, &attr); \
  7015. } else { \
  7016. upb_handlers_set##upbtype(h, f, encode_scalar_##lower, &attr); \
  7017. } \
  7018. break;
  7019. switch (upb_fielddef_descriptortype(f)) {
  7020. T(DOUBLE, double, double);
  7021. T(FLOAT, float, float);
  7022. T(INT64, int64, int64);
  7023. T(INT32, int32, int32);
  7024. T(FIXED64, fixed64, uint64);
  7025. T(FIXED32, fixed32, uint32);
  7026. T(BOOL, bool, bool);
  7027. T(UINT32, uint32, uint32);
  7028. T(UINT64, uint64, uint64);
  7029. T(ENUM, enum, int32);
  7030. T(SFIXED32, sfixed32, int32);
  7031. T(SFIXED64, sfixed64, int64);
  7032. T(SINT32, sint32, int32);
  7033. T(SINT64, sint64, int64);
  7034. case UPB_DESCRIPTOR_TYPE_STRING:
  7035. case UPB_DESCRIPTOR_TYPE_BYTES:
  7036. upb_handlers_setstartstr(h, f, encode_startstr, &attr);
  7037. upb_handlers_setendstr(h, f, encode_enddelimfield, &attr);
  7038. upb_handlers_setstring(h, f, encode_strbuf, &attr);
  7039. break;
  7040. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  7041. upb_handlers_setstartsubmsg(h, f, encode_startdelimfield, &attr);
  7042. upb_handlers_setendsubmsg(h, f, encode_enddelimfield, &attr);
  7043. break;
  7044. case UPB_DESCRIPTOR_TYPE_GROUP: {
  7045. // Endgroup takes a different tag (wire_type = END_GROUP).
  7046. upb_handlerattr attr2;
  7047. new_tag(h, f, UPB_WIRE_TYPE_END_GROUP, &attr2);
  7048. upb_handlers_setstartsubmsg(h, f, encode_startgroup, &attr);
  7049. upb_handlers_setendsubmsg(h, f, encode_endgroup, &attr2);
  7050. upb_handlerattr_uninit(&attr2);
  7051. break;
  7052. }
  7053. }
  7054. #undef T
  7055. upb_handlerattr_uninit(&attr);
  7056. }
  7057. }
  7058. /* public API *****************************************************************/
  7059. const upb_handlers *upb_pb_encoder_newhandlers(const upb_msgdef *m,
  7060. const void *owner) {
  7061. return upb_handlers_newfrozen(m, owner, newhandlers_callback, NULL);
  7062. }
  7063. #define ARRAYSIZE(x) (sizeof(x) / sizeof(x[0]))
  7064. void upb_pb_encoder_init(upb_pb_encoder *e, const upb_handlers *h) {
  7065. e->output_ = NULL;
  7066. e->subc = NULL;
  7067. e->buf = e->initbuf;
  7068. e->ptr = e->buf;
  7069. e->limit = e->buf + ARRAYSIZE(e->initbuf);
  7070. e->segbuf = e->seginitbuf;
  7071. e->seglimit = e->segbuf + ARRAYSIZE(e->seginitbuf);
  7072. e->stacklimit = e->stack + ARRAYSIZE(e->stack);
  7073. upb_sink_reset(&e->input_, h, e);
  7074. }
  7075. void upb_pb_encoder_uninit(upb_pb_encoder *e) {
  7076. if (e->buf != e->initbuf) {
  7077. free(e->buf);
  7078. }
  7079. if (e->segbuf != e->seginitbuf) {
  7080. free(e->segbuf);
  7081. }
  7082. }
  7083. void upb_pb_encoder_resetoutput(upb_pb_encoder *e, upb_bytessink *output) {
  7084. upb_pb_encoder_reset(e);
  7085. e->output_ = output;
  7086. e->subc = output->closure;
  7087. }
  7088. void upb_pb_encoder_reset(upb_pb_encoder *e) {
  7089. e->segptr = NULL;
  7090. e->top = NULL;
  7091. e->depth = 0;
  7092. }
  7093. upb_sink *upb_pb_encoder_input(upb_pb_encoder *e) { return &e->input_; }
  7094. /*
  7095. * upb - a minimalist implementation of protocol buffers.
  7096. *
  7097. * Copyright (c) 2010-2012 Google Inc. See LICENSE for details.
  7098. * Author: Josh Haberman <jhaberman@gmail.com>
  7099. */
  7100. #include <stdio.h>
  7101. #include <stdlib.h>
  7102. #include <string.h>
  7103. upb_def **upb_load_defs_from_descriptor(const char *str, size_t len, int *n,
  7104. void *owner, upb_status *status) {
  7105. // Create handlers.
  7106. const upb_handlers *reader_h = upb_descreader_newhandlers(&reader_h);
  7107. upb_pbdecodermethodopts opts;
  7108. upb_pbdecodermethodopts_init(&opts, reader_h);
  7109. const upb_pbdecodermethod *decoder_m =
  7110. upb_pbdecodermethod_new(&opts, &decoder_m);
  7111. upb_pbdecoder decoder;
  7112. upb_descreader reader;
  7113. upb_pbdecoder_init(&decoder, decoder_m, status);
  7114. upb_descreader_init(&reader, reader_h, status);
  7115. upb_pbdecoder_resetoutput(&decoder, upb_descreader_input(&reader));
  7116. // Push input data.
  7117. bool ok = upb_bufsrc_putbuf(str, len, upb_pbdecoder_input(&decoder));
  7118. upb_def **ret = NULL;
  7119. if (!ok) goto cleanup;
  7120. upb_def **defs = upb_descreader_getdefs(&reader, owner, n);
  7121. ret = malloc(sizeof(upb_def*) * (*n));
  7122. memcpy(ret, defs, sizeof(upb_def*) * (*n));
  7123. cleanup:
  7124. upb_pbdecoder_uninit(&decoder);
  7125. upb_descreader_uninit(&reader);
  7126. upb_handlers_unref(reader_h, &reader_h);
  7127. upb_pbdecodermethod_unref(decoder_m, &decoder_m);
  7128. return ret;
  7129. }
  7130. bool upb_load_descriptor_into_symtab(upb_symtab *s, const char *str, size_t len,
  7131. upb_status *status) {
  7132. int n;
  7133. upb_def **defs = upb_load_defs_from_descriptor(str, len, &n, &defs, status);
  7134. if (!defs) return false;
  7135. bool success = upb_symtab_add(s, defs, n, &defs, status);
  7136. free(defs);
  7137. return success;
  7138. }
  7139. char *upb_readfile(const char *filename, size_t *len) {
  7140. FILE *f = fopen(filename, "rb");
  7141. if(!f) return NULL;
  7142. if(fseek(f, 0, SEEK_END) != 0) goto error;
  7143. long size = ftell(f);
  7144. if(size < 0) goto error;
  7145. if(fseek(f, 0, SEEK_SET) != 0) goto error;
  7146. char *buf = malloc(size + 1);
  7147. if(size && fread(buf, size, 1, f) != 1) goto error;
  7148. fclose(f);
  7149. if (len) *len = size;
  7150. return buf;
  7151. error:
  7152. fclose(f);
  7153. return NULL;
  7154. }
  7155. bool upb_load_descriptor_file_into_symtab(upb_symtab *symtab, const char *fname,
  7156. upb_status *status) {
  7157. size_t len;
  7158. char *data = upb_readfile(fname, &len);
  7159. if (!data) {
  7160. if (status) upb_status_seterrf(status, "Couldn't read file: %s", fname);
  7161. return false;
  7162. }
  7163. bool success = upb_load_descriptor_into_symtab(symtab, data, len, status);
  7164. free(data);
  7165. return success;
  7166. }
  7167. /*
  7168. * upb - a minimalist implementation of protocol buffers.
  7169. *
  7170. * Copyright (c) 2009 Google Inc. See LICENSE for details.
  7171. * Author: Josh Haberman <jhaberman@gmail.com>
  7172. *
  7173. * OPT: This is not optimized at all. It uses printf() which parses the format
  7174. * string every time, and it allocates memory for every put.
  7175. */
  7176. #include <ctype.h>
  7177. #include <float.h>
  7178. #include <inttypes.h>
  7179. #include <stdio.h>
  7180. #include <stdlib.h>
  7181. #include <string.h>
  7182. #define CHECK(x) if ((x) < 0) goto err;
  7183. static const char *shortname(const char *longname) {
  7184. const char *last = strrchr(longname, '.');
  7185. return last ? last + 1 : longname;
  7186. }
  7187. static int indent(upb_textprinter *p) {
  7188. int i;
  7189. if (!p->single_line_)
  7190. for (i = 0; i < p->indent_depth_; i++)
  7191. upb_bytessink_putbuf(p->output_, p->subc, " ", 2, NULL);
  7192. return 0;
  7193. }
  7194. static int endfield(upb_textprinter *p) {
  7195. const char ch = (p->single_line_ ? ' ' : '\n');
  7196. upb_bytessink_putbuf(p->output_, p->subc, &ch, 1, NULL);
  7197. return 0;
  7198. }
  7199. static int putescaped(upb_textprinter *p, const char *buf, size_t len,
  7200. bool preserve_utf8) {
  7201. // Based on CEscapeInternal() from Google's protobuf release.
  7202. char dstbuf[4096], *dst = dstbuf, *dstend = dstbuf + sizeof(dstbuf);
  7203. const char *end = buf + len;
  7204. // I think hex is prettier and more useful, but proto2 uses octal; should
  7205. // investigate whether it can parse hex also.
  7206. const bool use_hex = false;
  7207. bool last_hex_escape = false; // true if last output char was \xNN
  7208. for (; buf < end; buf++) {
  7209. if (dstend - dst < 4) {
  7210. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  7211. dst = dstbuf;
  7212. }
  7213. bool is_hex_escape = false;
  7214. switch (*buf) {
  7215. case '\n': *(dst++) = '\\'; *(dst++) = 'n'; break;
  7216. case '\r': *(dst++) = '\\'; *(dst++) = 'r'; break;
  7217. case '\t': *(dst++) = '\\'; *(dst++) = 't'; break;
  7218. case '\"': *(dst++) = '\\'; *(dst++) = '\"'; break;
  7219. case '\'': *(dst++) = '\\'; *(dst++) = '\''; break;
  7220. case '\\': *(dst++) = '\\'; *(dst++) = '\\'; break;
  7221. default:
  7222. // Note that if we emit \xNN and the buf character after that is a hex
  7223. // digit then that digit must be escaped too to prevent it being
  7224. // interpreted as part of the character code by C.
  7225. if ((!preserve_utf8 || (uint8_t)*buf < 0x80) &&
  7226. (!isprint(*buf) || (last_hex_escape && isxdigit(*buf)))) {
  7227. sprintf(dst, (use_hex ? "\\x%02x" : "\\%03o"), (uint8_t)*buf);
  7228. is_hex_escape = use_hex;
  7229. dst += 4;
  7230. } else {
  7231. *(dst++) = *buf; break;
  7232. }
  7233. }
  7234. last_hex_escape = is_hex_escape;
  7235. }
  7236. // Flush remaining data.
  7237. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  7238. return 0;
  7239. }
  7240. bool putf(upb_textprinter *p, const char *fmt, ...) {
  7241. va_list args;
  7242. va_start(args, fmt);
  7243. // Run once to get the length of the string.
  7244. va_list args_copy;
  7245. va_copy(args_copy, args);
  7246. int len = vsnprintf(NULL, 0, fmt, args_copy);
  7247. va_end(args_copy);
  7248. // + 1 for NULL terminator (vsnprintf() requires it even if we don't).
  7249. char *str = malloc(len + 1);
  7250. if (!str) return false;
  7251. int written = vsnprintf(str, len + 1, fmt, args);
  7252. va_end(args);
  7253. UPB_ASSERT_VAR(written, written == len);
  7254. bool ok = upb_bytessink_putbuf(p->output_, p->subc, str, len, NULL);
  7255. free(str);
  7256. return ok;
  7257. }
  7258. /* handlers *******************************************************************/
  7259. static bool textprinter_startmsg(void *c, const void *hd) {
  7260. UPB_UNUSED(hd);
  7261. upb_textprinter *p = c;
  7262. if (p->indent_depth_ == 0) {
  7263. upb_bytessink_start(p->output_, 0, &p->subc);
  7264. }
  7265. return true;
  7266. }
  7267. static bool textprinter_endmsg(void *c, const void *hd, upb_status *s) {
  7268. UPB_UNUSED(hd);
  7269. UPB_UNUSED(s);
  7270. upb_textprinter *p = c;
  7271. if (p->indent_depth_ == 0) {
  7272. upb_bytessink_end(p->output_);
  7273. }
  7274. return true;
  7275. }
  7276. #define TYPE(name, ctype, fmt) \
  7277. static bool textprinter_put ## name(void *closure, const void *handler_data, \
  7278. ctype val) { \
  7279. upb_textprinter *p = closure; \
  7280. const upb_fielddef *f = handler_data; \
  7281. CHECK(indent(p)); \
  7282. putf(p, "%s: " fmt, upb_fielddef_name(f), val); \
  7283. CHECK(endfield(p)); \
  7284. return true; \
  7285. err: \
  7286. return false; \
  7287. }
  7288. static bool textprinter_putbool(void *closure, const void *handler_data,
  7289. bool val) {
  7290. upb_textprinter *p = closure;
  7291. const upb_fielddef *f = handler_data;
  7292. CHECK(indent(p));
  7293. putf(p, "%s: %s", upb_fielddef_name(f), val ? "true" : "false");
  7294. CHECK(endfield(p));
  7295. return true;
  7296. err:
  7297. return false;
  7298. }
  7299. #define STRINGIFY_HELPER(x) #x
  7300. #define STRINGIFY_MACROVAL(x) STRINGIFY_HELPER(x)
  7301. TYPE(int32, int32_t, "%" PRId32)
  7302. TYPE(int64, int64_t, "%" PRId64)
  7303. TYPE(uint32, uint32_t, "%" PRIu32);
  7304. TYPE(uint64, uint64_t, "%" PRIu64)
  7305. TYPE(float, float, "%." STRINGIFY_MACROVAL(FLT_DIG) "g")
  7306. TYPE(double, double, "%." STRINGIFY_MACROVAL(DBL_DIG) "g")
  7307. #undef TYPE
  7308. // Output a symbolic value from the enum if found, else just print as int32.
  7309. static bool textprinter_putenum(void *closure, const void *handler_data,
  7310. int32_t val) {
  7311. upb_textprinter *p = closure;
  7312. const upb_fielddef *f = handler_data;
  7313. const upb_enumdef *enum_def = upb_downcast_enumdef(upb_fielddef_subdef(f));
  7314. const char *label = upb_enumdef_iton(enum_def, val);
  7315. if (label) {
  7316. indent(p);
  7317. putf(p, "%s: %s", upb_fielddef_name(f), label);
  7318. endfield(p);
  7319. } else {
  7320. if (!textprinter_putint32(closure, handler_data, val))
  7321. return false;
  7322. }
  7323. return true;
  7324. }
  7325. static void *textprinter_startstr(void *closure, const void *handler_data,
  7326. size_t size_hint) {
  7327. const upb_fielddef *f = handler_data;
  7328. UPB_UNUSED(size_hint);
  7329. upb_textprinter *p = closure;
  7330. indent(p);
  7331. putf(p, "%s: \"", upb_fielddef_name(f));
  7332. return p;
  7333. }
  7334. static bool textprinter_endstr(void *closure, const void *handler_data) {
  7335. UPB_UNUSED(handler_data);
  7336. upb_textprinter *p = closure;
  7337. putf(p, "\"");
  7338. endfield(p);
  7339. return true;
  7340. }
  7341. static size_t textprinter_putstr(void *closure, const void *hd, const char *buf,
  7342. size_t len, const upb_bufhandle *handle) {
  7343. UPB_UNUSED(handle);
  7344. upb_textprinter *p = closure;
  7345. const upb_fielddef *f = hd;
  7346. CHECK(putescaped(p, buf, len, upb_fielddef_type(f) == UPB_TYPE_STRING));
  7347. return len;
  7348. err:
  7349. return 0;
  7350. }
  7351. static void *textprinter_startsubmsg(void *closure, const void *handler_data) {
  7352. upb_textprinter *p = closure;
  7353. const char *name = handler_data;
  7354. CHECK(indent(p));
  7355. putf(p, "%s {%c", name, p->single_line_ ? ' ' : '\n');
  7356. p->indent_depth_++;
  7357. return p;
  7358. err:
  7359. return UPB_BREAK;
  7360. }
  7361. static bool textprinter_endsubmsg(void *closure, const void *handler_data) {
  7362. UPB_UNUSED(handler_data);
  7363. upb_textprinter *p = closure;
  7364. p->indent_depth_--;
  7365. CHECK(indent(p));
  7366. upb_bytessink_putbuf(p->output_, p->subc, "}", 1, NULL);
  7367. CHECK(endfield(p));
  7368. return true;
  7369. err:
  7370. return false;
  7371. }
  7372. /* Public API *****************************************************************/
  7373. void upb_textprinter_init(upb_textprinter *p, const upb_handlers *h) {
  7374. p->single_line_ = false;
  7375. p->indent_depth_ = 0;
  7376. upb_sink_reset(&p->input_, h, p);
  7377. }
  7378. void upb_textprinter_uninit(upb_textprinter *p) {
  7379. UPB_UNUSED(p);
  7380. }
  7381. void upb_textprinter_reset(upb_textprinter *p, bool single_line) {
  7382. p->single_line_ = single_line;
  7383. p->indent_depth_ = 0;
  7384. }
  7385. static void onmreg(const void *c, upb_handlers *h) {
  7386. UPB_UNUSED(c);
  7387. const upb_msgdef *m = upb_handlers_msgdef(h);
  7388. upb_handlers_setstartmsg(h, textprinter_startmsg, NULL);
  7389. upb_handlers_setendmsg(h, textprinter_endmsg, NULL);
  7390. upb_msg_iter i;
  7391. for(upb_msg_begin(&i, m); !upb_msg_done(&i); upb_msg_next(&i)) {
  7392. upb_fielddef *f = upb_msg_iter_field(&i);
  7393. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  7394. upb_handlerattr_sethandlerdata(&attr, f);
  7395. switch (upb_fielddef_type(f)) {
  7396. case UPB_TYPE_INT32:
  7397. upb_handlers_setint32(h, f, textprinter_putint32, &attr);
  7398. break;
  7399. case UPB_TYPE_INT64:
  7400. upb_handlers_setint64(h, f, textprinter_putint64, &attr);
  7401. break;
  7402. case UPB_TYPE_UINT32:
  7403. upb_handlers_setuint32(h, f, textprinter_putuint32, &attr);
  7404. break;
  7405. case UPB_TYPE_UINT64:
  7406. upb_handlers_setuint64(h, f, textprinter_putuint64, &attr);
  7407. break;
  7408. case UPB_TYPE_FLOAT:
  7409. upb_handlers_setfloat(h, f, textprinter_putfloat, &attr);
  7410. break;
  7411. case UPB_TYPE_DOUBLE:
  7412. upb_handlers_setdouble(h, f, textprinter_putdouble, &attr);
  7413. break;
  7414. case UPB_TYPE_BOOL:
  7415. upb_handlers_setbool(h, f, textprinter_putbool, &attr);
  7416. break;
  7417. case UPB_TYPE_STRING:
  7418. case UPB_TYPE_BYTES:
  7419. upb_handlers_setstartstr(h, f, textprinter_startstr, &attr);
  7420. upb_handlers_setstring(h, f, textprinter_putstr, &attr);
  7421. upb_handlers_setendstr(h, f, textprinter_endstr, &attr);
  7422. break;
  7423. case UPB_TYPE_MESSAGE: {
  7424. const char *name =
  7425. upb_fielddef_istagdelim(f)
  7426. ? shortname(upb_msgdef_fullname(upb_fielddef_msgsubdef(f)))
  7427. : upb_fielddef_name(f);
  7428. upb_handlerattr_sethandlerdata(&attr, name);
  7429. upb_handlers_setstartsubmsg(h, f, textprinter_startsubmsg, &attr);
  7430. upb_handlers_setendsubmsg(h, f, textprinter_endsubmsg, &attr);
  7431. break;
  7432. }
  7433. case UPB_TYPE_ENUM:
  7434. upb_handlers_setint32(h, f, textprinter_putenum, &attr);
  7435. break;
  7436. }
  7437. }
  7438. }
  7439. const upb_handlers *upb_textprinter_newhandlers(const upb_msgdef *m,
  7440. const void *owner) {
  7441. return upb_handlers_newfrozen(m, owner, &onmreg, NULL);
  7442. }
  7443. upb_sink *upb_textprinter_input(upb_textprinter *p) { return &p->input_; }
  7444. bool upb_textprinter_resetoutput(upb_textprinter *p, upb_bytessink *output) {
  7445. p->output_ = output;
  7446. return true;
  7447. }
  7448. void upb_textprinter_setsingleline(upb_textprinter *p, bool single_line) {
  7449. p->single_line_ = single_line;
  7450. }
  7451. /*
  7452. * upb - a minimalist implementation of protocol buffers.
  7453. *
  7454. * Copyright (c) 2011 Google Inc. See LICENSE for details.
  7455. * Author: Josh Haberman <jhaberman@gmail.com>
  7456. */
  7457. // Index is descriptor type.
  7458. const uint8_t upb_pb_native_wire_types[] = {
  7459. UPB_WIRE_TYPE_END_GROUP, // ENDGROUP
  7460. UPB_WIRE_TYPE_64BIT, // DOUBLE
  7461. UPB_WIRE_TYPE_32BIT, // FLOAT
  7462. UPB_WIRE_TYPE_VARINT, // INT64
  7463. UPB_WIRE_TYPE_VARINT, // UINT64
  7464. UPB_WIRE_TYPE_VARINT, // INT32
  7465. UPB_WIRE_TYPE_64BIT, // FIXED64
  7466. UPB_WIRE_TYPE_32BIT, // FIXED32
  7467. UPB_WIRE_TYPE_VARINT, // BOOL
  7468. UPB_WIRE_TYPE_DELIMITED, // STRING
  7469. UPB_WIRE_TYPE_START_GROUP, // GROUP
  7470. UPB_WIRE_TYPE_DELIMITED, // MESSAGE
  7471. UPB_WIRE_TYPE_DELIMITED, // BYTES
  7472. UPB_WIRE_TYPE_VARINT, // UINT32
  7473. UPB_WIRE_TYPE_VARINT, // ENUM
  7474. UPB_WIRE_TYPE_32BIT, // SFIXED32
  7475. UPB_WIRE_TYPE_64BIT, // SFIXED64
  7476. UPB_WIRE_TYPE_VARINT, // SINT32
  7477. UPB_WIRE_TYPE_VARINT, // SINT64
  7478. };
  7479. // A basic branch-based decoder, uses 32-bit values to get good performance
  7480. // on 32-bit architectures (but performs well on 64-bits also).
  7481. // This scheme comes from the original Google Protobuf implementation (proto2).
  7482. upb_decoderet upb_vdecode_max8_branch32(upb_decoderet r) {
  7483. upb_decoderet err = {NULL, 0};
  7484. const char *p = r.p;
  7485. uint32_t low = (uint32_t)r.val;
  7486. uint32_t high = 0;
  7487. uint32_t b;
  7488. b = *(p++); low |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  7489. b = *(p++); low |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  7490. b = *(p++); low |= (b & 0x7fU) << 28;
  7491. high = (b & 0x7fU) >> 4; if (!(b & 0x80)) goto done;
  7492. b = *(p++); high |= (b & 0x7fU) << 3; if (!(b & 0x80)) goto done;
  7493. b = *(p++); high |= (b & 0x7fU) << 10; if (!(b & 0x80)) goto done;
  7494. b = *(p++); high |= (b & 0x7fU) << 17; if (!(b & 0x80)) goto done;
  7495. b = *(p++); high |= (b & 0x7fU) << 24; if (!(b & 0x80)) goto done;
  7496. b = *(p++); high |= (b & 0x7fU) << 31; if (!(b & 0x80)) goto done;
  7497. return err;
  7498. done:
  7499. r.val = ((uint64_t)high << 32) | low;
  7500. r.p = p;
  7501. return r;
  7502. }
  7503. // Like the previous, but uses 64-bit values.
  7504. upb_decoderet upb_vdecode_max8_branch64(upb_decoderet r) {
  7505. const char *p = r.p;
  7506. uint64_t val = r.val;
  7507. uint64_t b;
  7508. upb_decoderet err = {NULL, 0};
  7509. b = *(p++); val |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  7510. b = *(p++); val |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  7511. b = *(p++); val |= (b & 0x7fU) << 28; if (!(b & 0x80)) goto done;
  7512. b = *(p++); val |= (b & 0x7fU) << 35; if (!(b & 0x80)) goto done;
  7513. b = *(p++); val |= (b & 0x7fU) << 42; if (!(b & 0x80)) goto done;
  7514. b = *(p++); val |= (b & 0x7fU) << 49; if (!(b & 0x80)) goto done;
  7515. b = *(p++); val |= (b & 0x7fU) << 56; if (!(b & 0x80)) goto done;
  7516. b = *(p++); val |= (b & 0x7fU) << 63; if (!(b & 0x80)) goto done;
  7517. return err;
  7518. done:
  7519. r.val = val;
  7520. r.p = p;
  7521. return r;
  7522. }
  7523. // Given an encoded varint v, returns an integer with a single bit set that
  7524. // indicates the end of the varint. Subtracting one from this value will
  7525. // yield a mask that leaves only bits that are part of the varint. Returns
  7526. // 0 if the varint is unterminated.
  7527. static uint64_t upb_get_vstopbit(uint64_t v) {
  7528. uint64_t cbits = v | 0x7f7f7f7f7f7f7f7fULL;
  7529. return ~cbits & (cbits+1);
  7530. }
  7531. // A branchless decoder. Credit to Pascal Massimino for the bit-twiddling.
  7532. upb_decoderet upb_vdecode_max8_massimino(upb_decoderet r) {
  7533. uint64_t b;
  7534. memcpy(&b, r.p, sizeof(b));
  7535. uint64_t stop_bit = upb_get_vstopbit(b);
  7536. b = (b & 0x7f7f7f7f7f7f7f7fULL) & (stop_bit - 1);
  7537. b += b & 0x007f007f007f007fULL;
  7538. b += 3 * (b & 0x0000ffff0000ffffULL);
  7539. b += 15 * (b & 0x00000000ffffffffULL);
  7540. if (stop_bit == 0) {
  7541. // Error: unterminated varint.
  7542. upb_decoderet err_r = {(void*)0, 0};
  7543. return err_r;
  7544. }
  7545. upb_decoderet my_r = {r.p + ((__builtin_ctzll(stop_bit) + 1) / 8),
  7546. r.val | (b << 7)};
  7547. return my_r;
  7548. }
  7549. // A branchless decoder. Credit to Daniel Wright for the bit-twiddling.
  7550. upb_decoderet upb_vdecode_max8_wright(upb_decoderet r) {
  7551. uint64_t b;
  7552. memcpy(&b, r.p, sizeof(b));
  7553. uint64_t stop_bit = upb_get_vstopbit(b);
  7554. b &= (stop_bit - 1);
  7555. b = ((b & 0x7f007f007f007f00ULL) >> 1) | (b & 0x007f007f007f007fULL);
  7556. b = ((b & 0xffff0000ffff0000ULL) >> 2) | (b & 0x0000ffff0000ffffULL);
  7557. b = ((b & 0xffffffff00000000ULL) >> 4) | (b & 0x00000000ffffffffULL);
  7558. if (stop_bit == 0) {
  7559. // Error: unterminated varint.
  7560. upb_decoderet err_r = {(void*)0, 0};
  7561. return err_r;
  7562. }
  7563. upb_decoderet my_r = {r.p + ((__builtin_ctzll(stop_bit) + 1) / 8),
  7564. r.val | (b << 14)};
  7565. return my_r;
  7566. }
  7567. #line 1 "upb/json/parser.rl"
  7568. /*
  7569. * upb - a minimalist implementation of protocol buffers.
  7570. *
  7571. * Copyright (c) 2014 Google Inc. See LICENSE for details.
  7572. * Author: Josh Haberman <jhaberman@gmail.com>
  7573. *
  7574. * A parser that uses the Ragel State Machine Compiler to generate
  7575. * the finite automata.
  7576. *
  7577. * Ragel only natively handles regular languages, but we can manually
  7578. * program it a bit to handle context-free languages like JSON, by using
  7579. * the "fcall" and "fret" constructs.
  7580. *
  7581. * This parser can handle the basics, but needs several things to be fleshed
  7582. * out:
  7583. *
  7584. * - handling of unicode escape sequences (including high surrogate pairs).
  7585. * - properly check and report errors for unknown fields, stack overflow,
  7586. * improper array nesting (or lack of nesting).
  7587. * - handling of base64 sequences with padding characters.
  7588. * - handling of push-back (non-success returns from sink functions).
  7589. * - handling of keys/escape-sequences/etc that span input buffers.
  7590. */
  7591. #include <stdio.h>
  7592. #include <stdint.h>
  7593. #include <assert.h>
  7594. #include <string.h>
  7595. #include <stdlib.h>
  7596. #include <errno.h>
  7597. #define PARSER_CHECK_RETURN(x) if (!(x)) return false
  7598. static upb_selector_t getsel_for_handlertype(upb_json_parser *p,
  7599. upb_handlertype_t type) {
  7600. upb_selector_t sel;
  7601. bool ok = upb_handlers_getselector(p->top->f, type, &sel);
  7602. UPB_ASSERT_VAR(ok, ok);
  7603. return sel;
  7604. }
  7605. static upb_selector_t parser_getsel(upb_json_parser *p) {
  7606. return getsel_for_handlertype(
  7607. p, upb_handlers_getprimitivehandlertype(p->top->f));
  7608. }
  7609. static void start_member(upb_json_parser *p) {
  7610. assert(!p->top->f);
  7611. assert(!p->accumulated);
  7612. p->accumulated_len = 0;
  7613. }
  7614. static bool end_member(upb_json_parser *p) {
  7615. // TODO(haberman): support keys that span buffers or have escape sequences.
  7616. assert(!p->top->f);
  7617. assert(p->accumulated);
  7618. const upb_fielddef *f =
  7619. upb_msgdef_ntof(p->top->m, p->accumulated, p->accumulated_len);
  7620. if (!f) {
  7621. // TODO(haberman): Ignore unknown fields if requested/configured to do so.
  7622. upb_status_seterrf(p->status, "No such field: %.*s\n",
  7623. (int)p->accumulated_len, p->accumulated);
  7624. return false;
  7625. }
  7626. p->top->f = f;
  7627. p->accumulated = NULL;
  7628. return true;
  7629. }
  7630. static void start_object(upb_json_parser *p) {
  7631. upb_sink_startmsg(&p->top->sink);
  7632. }
  7633. static void end_object(upb_json_parser *p) {
  7634. upb_status status;
  7635. upb_sink_endmsg(&p->top->sink, &status);
  7636. }
  7637. static bool check_stack(upb_json_parser *p) {
  7638. if ((p->top + 1) == p->limit) {
  7639. upb_status_seterrmsg(p->status, "Nesting too deep");
  7640. return false;
  7641. }
  7642. return true;
  7643. }
  7644. static bool start_subobject(upb_json_parser *p) {
  7645. assert(p->top->f);
  7646. if (!upb_fielddef_issubmsg(p->top->f)) {
  7647. upb_status_seterrf(p->status,
  7648. "Object specified for non-message/group field: %s",
  7649. upb_fielddef_name(p->top->f));
  7650. return false;
  7651. }
  7652. if (!check_stack(p)) return false;
  7653. upb_jsonparser_frame *inner = p->top + 1;
  7654. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
  7655. upb_sink_startsubmsg(&p->top->sink, sel, &inner->sink);
  7656. inner->m = upb_fielddef_msgsubdef(p->top->f);
  7657. inner->f = NULL;
  7658. p->top = inner;
  7659. return true;
  7660. }
  7661. static void end_subobject(upb_json_parser *p) {
  7662. p->top--;
  7663. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSUBMSG);
  7664. upb_sink_endsubmsg(&p->top->sink, sel);
  7665. }
  7666. static bool start_array(upb_json_parser *p) {
  7667. assert(p->top->f);
  7668. if (!upb_fielddef_isseq(p->top->f)) {
  7669. upb_status_seterrf(p->status,
  7670. "Array specified for non-repeated field: %s",
  7671. upb_fielddef_name(p->top->f));
  7672. return false;
  7673. }
  7674. if (!check_stack(p)) return false;
  7675. upb_jsonparser_frame *inner = p->top + 1;
  7676. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
  7677. upb_sink_startseq(&p->top->sink, sel, &inner->sink);
  7678. inner->m = p->top->m;
  7679. inner->f = p->top->f;
  7680. p->top = inner;
  7681. return true;
  7682. }
  7683. static void end_array(upb_json_parser *p) {
  7684. assert(p->top > p->stack);
  7685. p->top--;
  7686. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
  7687. upb_sink_endseq(&p->top->sink, sel);
  7688. }
  7689. static void clear_member(upb_json_parser *p) { p->top->f = NULL; }
  7690. static bool parser_putbool(upb_json_parser *p, bool val) {
  7691. if (upb_fielddef_type(p->top->f) != UPB_TYPE_BOOL) {
  7692. upb_status_seterrf(p->status,
  7693. "Boolean value specified for non-bool field: %s",
  7694. upb_fielddef_name(p->top->f));
  7695. return false;
  7696. }
  7697. bool ok = upb_sink_putbool(&p->top->sink, parser_getsel(p), val);
  7698. UPB_ASSERT_VAR(ok, ok);
  7699. return true;
  7700. }
  7701. static void start_text(upb_json_parser *p, const char *ptr) {
  7702. p->text_begin = ptr;
  7703. }
  7704. static const signed char b64table[] = {
  7705. -1, -1, -1, -1, -1, -1, -1, -1,
  7706. -1, -1, -1, -1, -1, -1, -1, -1,
  7707. -1, -1, -1, -1, -1, -1, -1, -1,
  7708. -1, -1, -1, -1, -1, -1, -1, -1,
  7709. -1, -1, -1, -1, -1, -1, -1, -1,
  7710. -1, -1, -1, 62/*+*/, -1, -1, -1, 63/*/ */,
  7711. 52/*0*/, 53/*1*/, 54/*2*/, 55/*3*/, 56/*4*/, 57/*5*/, 58/*6*/, 59/*7*/,
  7712. 60/*8*/, 61/*9*/, -1, -1, -1, -1, -1, -1,
  7713. -1, 0/*A*/, 1/*B*/, 2/*C*/, 3/*D*/, 4/*E*/, 5/*F*/, 6/*G*/,
  7714. 07/*H*/, 8/*I*/, 9/*J*/, 10/*K*/, 11/*L*/, 12/*M*/, 13/*N*/, 14/*O*/,
  7715. 15/*P*/, 16/*Q*/, 17/*R*/, 18/*S*/, 19/*T*/, 20/*U*/, 21/*V*/, 22/*W*/,
  7716. 23/*X*/, 24/*Y*/, 25/*Z*/, -1, -1, -1, -1, -1,
  7717. -1, 26/*a*/, 27/*b*/, 28/*c*/, 29/*d*/, 30/*e*/, 31/*f*/, 32/*g*/,
  7718. 33/*h*/, 34/*i*/, 35/*j*/, 36/*k*/, 37/*l*/, 38/*m*/, 39/*n*/, 40/*o*/,
  7719. 41/*p*/, 42/*q*/, 43/*r*/, 44/*s*/, 45/*t*/, 46/*u*/, 47/*v*/, 48/*w*/,
  7720. 49/*x*/, 50/*y*/, 51/*z*/, -1, -1, -1, -1, -1,
  7721. -1, -1, -1, -1, -1, -1, -1, -1,
  7722. -1, -1, -1, -1, -1, -1, -1, -1,
  7723. -1, -1, -1, -1, -1, -1, -1, -1,
  7724. -1, -1, -1, -1, -1, -1, -1, -1,
  7725. -1, -1, -1, -1, -1, -1, -1, -1,
  7726. -1, -1, -1, -1, -1, -1, -1, -1,
  7727. -1, -1, -1, -1, -1, -1, -1, -1,
  7728. -1, -1, -1, -1, -1, -1, -1, -1,
  7729. -1, -1, -1, -1, -1, -1, -1, -1,
  7730. -1, -1, -1, -1, -1, -1, -1, -1,
  7731. -1, -1, -1, -1, -1, -1, -1, -1,
  7732. -1, -1, -1, -1, -1, -1, -1, -1,
  7733. -1, -1, -1, -1, -1, -1, -1, -1,
  7734. -1, -1, -1, -1, -1, -1, -1, -1,
  7735. -1, -1, -1, -1, -1, -1, -1, -1,
  7736. -1, -1, -1, -1, -1, -1, -1, -1
  7737. };
  7738. // Returns the table value sign-extended to 32 bits. Knowing that the upper
  7739. // bits will be 1 for unrecognized characters makes it easier to check for
  7740. // this error condition later (see below).
  7741. int32_t b64lookup(unsigned char ch) { return b64table[ch]; }
  7742. // Returns true if the given character is not a valid base64 character or
  7743. // padding.
  7744. bool nonbase64(unsigned char ch) { return b64lookup(ch) == -1 && ch != '='; }
  7745. static bool base64_push(upb_json_parser *p, upb_selector_t sel, const char *ptr,
  7746. size_t len) {
  7747. const char *limit = ptr + len;
  7748. for (; ptr < limit; ptr += 4) {
  7749. if (limit - ptr < 4) {
  7750. upb_status_seterrf(p->status,
  7751. "Base64 input for bytes field not a multiple of 4: %s",
  7752. upb_fielddef_name(p->top->f));
  7753. return false;
  7754. }
  7755. uint32_t val = b64lookup(ptr[0]) << 18 |
  7756. b64lookup(ptr[1]) << 12 |
  7757. b64lookup(ptr[2]) << 6 |
  7758. b64lookup(ptr[3]);
  7759. // Test the upper bit; returns true if any of the characters returned -1.
  7760. if (val & 0x80000000) {
  7761. goto otherchar;
  7762. }
  7763. char output[3];
  7764. output[0] = val >> 16;
  7765. output[1] = (val >> 8) & 0xff;
  7766. output[2] = val & 0xff;
  7767. upb_sink_putstring(&p->top->sink, sel, output, 3, NULL);
  7768. }
  7769. return true;
  7770. otherchar:
  7771. if (nonbase64(ptr[0]) || nonbase64(ptr[1]) || nonbase64(ptr[2]) ||
  7772. nonbase64(ptr[3]) ) {
  7773. upb_status_seterrf(p->status,
  7774. "Non-base64 characters in bytes field: %s",
  7775. upb_fielddef_name(p->top->f));
  7776. return false;
  7777. } if (ptr[2] == '=') {
  7778. // Last group contains only two input bytes, one output byte.
  7779. if (ptr[0] == '=' || ptr[1] == '=' || ptr[3] != '=') {
  7780. goto badpadding;
  7781. }
  7782. uint32_t val = b64lookup(ptr[0]) << 18 |
  7783. b64lookup(ptr[1]) << 12;
  7784. assert(!(val & 0x80000000));
  7785. char output = val >> 16;
  7786. upb_sink_putstring(&p->top->sink, sel, &output, 1, NULL);
  7787. return true;
  7788. } else {
  7789. // Last group contains only three input bytes, two output bytes.
  7790. if (ptr[0] == '=' || ptr[1] == '=' || ptr[2] == '=') {
  7791. goto badpadding;
  7792. }
  7793. uint32_t val = b64lookup(ptr[0]) << 18 |
  7794. b64lookup(ptr[1]) << 12 |
  7795. b64lookup(ptr[2]) << 6;
  7796. char output[2];
  7797. output[0] = val >> 16;
  7798. output[1] = (val >> 8) & 0xff;
  7799. upb_sink_putstring(&p->top->sink, sel, output, 2, NULL);
  7800. return true;
  7801. }
  7802. badpadding:
  7803. upb_status_seterrf(p->status,
  7804. "Incorrect base64 padding for field: %s (%.*s)",
  7805. upb_fielddef_name(p->top->f),
  7806. 4, ptr);
  7807. return false;
  7808. }
  7809. static bool end_text(upb_json_parser *p, const char *ptr, bool is_num) {
  7810. assert(!p->accumulated); // TODO: handle this case.
  7811. p->accumulated = p->text_begin;
  7812. p->accumulated_len = ptr - p->text_begin;
  7813. if (p->top->f && upb_fielddef_isstring(p->top->f)) {
  7814. // This is a string field (as opposed to a member name).
  7815. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
  7816. if (upb_fielddef_type(p->top->f) == UPB_TYPE_BYTES) {
  7817. PARSER_CHECK_RETURN(base64_push(p, sel, p->accumulated,
  7818. p->accumulated_len));
  7819. } else {
  7820. upb_sink_putstring(&p->top->sink, sel, p->accumulated, p->accumulated_len, NULL);
  7821. }
  7822. p->accumulated = NULL;
  7823. } else if (p->top->f &&
  7824. upb_fielddef_type(p->top->f) == UPB_TYPE_ENUM &&
  7825. !is_num) {
  7826. // Enum case: resolve enum symbolic name to integer value.
  7827. const upb_enumdef *enumdef =
  7828. (const upb_enumdef*)upb_fielddef_subdef(p->top->f);
  7829. int32_t int_val = 0;
  7830. if (upb_enumdef_ntoi(enumdef, p->accumulated, p->accumulated_len,
  7831. &int_val)) {
  7832. upb_selector_t sel = parser_getsel(p);
  7833. upb_sink_putint32(&p->top->sink, sel, int_val);
  7834. } else {
  7835. upb_status_seterrmsg(p->status, "Enum value name unknown");
  7836. return false;
  7837. }
  7838. p->accumulated = NULL;
  7839. }
  7840. return true;
  7841. }
  7842. static bool start_stringval(upb_json_parser *p) {
  7843. assert(p->top->f);
  7844. if (upb_fielddef_isstring(p->top->f)) {
  7845. if (!check_stack(p)) return false;
  7846. // Start a new parser frame: parser frames correspond one-to-one with
  7847. // handler frames, and string events occur in a sub-frame.
  7848. upb_jsonparser_frame *inner = p->top + 1;
  7849. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  7850. upb_sink_startstr(&p->top->sink, sel, 0, &inner->sink);
  7851. inner->m = p->top->m;
  7852. inner->f = p->top->f;
  7853. p->top = inner;
  7854. return true;
  7855. } else if (upb_fielddef_type(p->top->f) == UPB_TYPE_ENUM) {
  7856. // Do nothing -- symbolic enum names in quotes remain in the
  7857. // current parser frame.
  7858. return true;
  7859. } else {
  7860. upb_status_seterrf(p->status,
  7861. "String specified for non-string/non-enum field: %s",
  7862. upb_fielddef_name(p->top->f));
  7863. return false;
  7864. }
  7865. }
  7866. static void end_stringval(upb_json_parser *p) {
  7867. if (upb_fielddef_isstring(p->top->f)) {
  7868. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  7869. upb_sink_endstr(&p->top->sink, sel);
  7870. p->top--;
  7871. }
  7872. }
  7873. static void start_number(upb_json_parser *p, const char *ptr) {
  7874. start_text(p, ptr);
  7875. assert(p->accumulated == NULL);
  7876. }
  7877. static void end_number(upb_json_parser *p, const char *ptr) {
  7878. end_text(p, ptr, true);
  7879. const char *myend = p->accumulated + p->accumulated_len;
  7880. char *end;
  7881. switch (upb_fielddef_type(p->top->f)) {
  7882. case UPB_TYPE_ENUM:
  7883. case UPB_TYPE_INT32: {
  7884. long val = strtol(p->accumulated, &end, 0);
  7885. if (val > INT32_MAX || val < INT32_MIN || errno == ERANGE || end != myend)
  7886. assert(false);
  7887. else
  7888. upb_sink_putint32(&p->top->sink, parser_getsel(p), val);
  7889. break;
  7890. }
  7891. case UPB_TYPE_INT64: {
  7892. long long val = strtoll(p->accumulated, &end, 0);
  7893. if (val > INT64_MAX || val < INT64_MIN || errno == ERANGE || end != myend)
  7894. assert(false);
  7895. else
  7896. upb_sink_putint64(&p->top->sink, parser_getsel(p), val);
  7897. break;
  7898. }
  7899. case UPB_TYPE_UINT32: {
  7900. unsigned long val = strtoul(p->accumulated, &end, 0);
  7901. if (val > UINT32_MAX || errno == ERANGE || end != myend)
  7902. assert(false);
  7903. else
  7904. upb_sink_putuint32(&p->top->sink, parser_getsel(p), val);
  7905. break;
  7906. }
  7907. case UPB_TYPE_UINT64: {
  7908. unsigned long long val = strtoull(p->accumulated, &end, 0);
  7909. if (val > UINT64_MAX || errno == ERANGE || end != myend)
  7910. assert(false);
  7911. else
  7912. upb_sink_putuint64(&p->top->sink, parser_getsel(p), val);
  7913. break;
  7914. }
  7915. case UPB_TYPE_DOUBLE: {
  7916. double val = strtod(p->accumulated, &end);
  7917. if (errno == ERANGE || end != myend)
  7918. assert(false);
  7919. else
  7920. upb_sink_putdouble(&p->top->sink, parser_getsel(p), val);
  7921. break;
  7922. }
  7923. case UPB_TYPE_FLOAT: {
  7924. float val = strtof(p->accumulated, &end);
  7925. if (errno == ERANGE || end != myend)
  7926. assert(false);
  7927. else
  7928. upb_sink_putfloat(&p->top->sink, parser_getsel(p), val);
  7929. break;
  7930. }
  7931. default:
  7932. assert(false);
  7933. }
  7934. p->accumulated = NULL;
  7935. }
  7936. static char escape_char(char in) {
  7937. switch (in) {
  7938. case 'r': return '\r';
  7939. case 't': return '\t';
  7940. case 'n': return '\n';
  7941. case 'f': return '\f';
  7942. case 'b': return '\b';
  7943. case '/': return '/';
  7944. case '"': return '"';
  7945. case '\\': return '\\';
  7946. default:
  7947. assert(0);
  7948. return 'x';
  7949. }
  7950. }
  7951. static void escape(upb_json_parser *p, const char *ptr) {
  7952. char ch = escape_char(*ptr);
  7953. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
  7954. upb_sink_putstring(&p->top->sink, sel, &ch, 1, NULL);
  7955. }
  7956. static uint8_t hexdigit(char ch) {
  7957. if (ch >= '0' && ch <= '9') {
  7958. return ch - '0';
  7959. } else if (ch >= 'a' && ch <= 'f') {
  7960. return ch - 'a' + 10;
  7961. } else {
  7962. assert(ch >= 'A' && ch <= 'F');
  7963. return ch - 'A' + 10;
  7964. }
  7965. }
  7966. static void start_hex(upb_json_parser *p, const char *ptr) {
  7967. start_text(p, ptr);
  7968. }
  7969. static void hex(upb_json_parser *p, const char *end) {
  7970. const char *start = p->text_begin;
  7971. UPB_ASSERT_VAR(end, end - start == 4);
  7972. uint16_t codepoint =
  7973. (hexdigit(start[0]) << 12) |
  7974. (hexdigit(start[1]) << 8) |
  7975. (hexdigit(start[2]) << 4) |
  7976. hexdigit(start[3]);
  7977. // emit the codepoint as UTF-8.
  7978. char utf8[3]; // support \u0000 -- \uFFFF -- need only three bytes.
  7979. int length = 0;
  7980. if (codepoint <= 0x7F) {
  7981. utf8[0] = codepoint;
  7982. length = 1;
  7983. } else if (codepoint <= 0x07FF) {
  7984. utf8[1] = (codepoint & 0x3F) | 0x80;
  7985. codepoint >>= 6;
  7986. utf8[0] = (codepoint & 0x1F) | 0xC0;
  7987. length = 2;
  7988. } else /* codepoint <= 0xFFFF */ {
  7989. utf8[2] = (codepoint & 0x3F) | 0x80;
  7990. codepoint >>= 6;
  7991. utf8[1] = (codepoint & 0x3F) | 0x80;
  7992. codepoint >>= 6;
  7993. utf8[0] = (codepoint & 0x0F) | 0xE0;
  7994. length = 3;
  7995. }
  7996. // TODO(haberman): Handle high surrogates: if codepoint is a high surrogate
  7997. // we have to wait for the next escape to get the full code point).
  7998. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
  7999. upb_sink_putstring(&p->top->sink, sel, utf8, length, NULL);
  8000. }
  8001. #define CHECK_RETURN_TOP(x) if (!(x)) goto error
  8002. // What follows is the Ragel parser itself. The language is specified in Ragel
  8003. // and the actions call our C functions above.
  8004. #line 596 "upb/json/parser.rl"
  8005. #line 514 "upb/json/parser.c"
  8006. static const char _json_actions[] = {
  8007. 0, 1, 0, 1, 2, 1, 3, 1,
  8008. 4, 1, 5, 1, 6, 1, 7, 1,
  8009. 9, 1, 11, 1, 12, 1, 13, 1,
  8010. 14, 1, 15, 1, 16, 1, 24, 1,
  8011. 26, 2, 3, 7, 2, 5, 2, 2,
  8012. 5, 7, 2, 10, 8, 2, 12, 14,
  8013. 2, 13, 14, 2, 17, 1, 2, 18,
  8014. 26, 2, 19, 8, 2, 20, 26, 2,
  8015. 21, 26, 2, 22, 26, 2, 23, 26,
  8016. 2, 25, 26, 3, 13, 10, 8
  8017. };
  8018. static const unsigned char _json_key_offsets[] = {
  8019. 0, 0, 4, 9, 14, 18, 22, 27,
  8020. 32, 37, 41, 45, 48, 51, 53, 57,
  8021. 61, 63, 65, 70, 72, 74, 83, 89,
  8022. 95, 101, 107, 109, 118, 118, 118, 123,
  8023. 128, 133, 133, 134, 135, 136, 137, 137,
  8024. 138, 139, 140, 140, 141, 142, 143, 143,
  8025. 148, 153, 157, 161, 166, 171, 176, 180,
  8026. 180, 183, 183, 183
  8027. };
  8028. static const char _json_trans_keys[] = {
  8029. 32, 123, 9, 13, 32, 34, 125, 9,
  8030. 13, 32, 34, 125, 9, 13, 32, 58,
  8031. 9, 13, 32, 58, 9, 13, 32, 93,
  8032. 125, 9, 13, 32, 44, 125, 9, 13,
  8033. 32, 44, 125, 9, 13, 32, 34, 9,
  8034. 13, 45, 48, 49, 57, 48, 49, 57,
  8035. 46, 69, 101, 48, 57, 69, 101, 48,
  8036. 57, 43, 45, 48, 57, 48, 57, 48,
  8037. 57, 46, 69, 101, 48, 57, 34, 92,
  8038. 34, 92, 34, 47, 92, 98, 102, 110,
  8039. 114, 116, 117, 48, 57, 65, 70, 97,
  8040. 102, 48, 57, 65, 70, 97, 102, 48,
  8041. 57, 65, 70, 97, 102, 48, 57, 65,
  8042. 70, 97, 102, 34, 92, 34, 45, 91,
  8043. 102, 110, 116, 123, 48, 57, 32, 93,
  8044. 125, 9, 13, 32, 44, 93, 9, 13,
  8045. 32, 93, 125, 9, 13, 97, 108, 115,
  8046. 101, 117, 108, 108, 114, 117, 101, 32,
  8047. 34, 125, 9, 13, 32, 34, 125, 9,
  8048. 13, 32, 58, 9, 13, 32, 58, 9,
  8049. 13, 32, 93, 125, 9, 13, 32, 44,
  8050. 125, 9, 13, 32, 44, 125, 9, 13,
  8051. 32, 34, 9, 13, 32, 9, 13, 0
  8052. };
  8053. static const char _json_single_lengths[] = {
  8054. 0, 2, 3, 3, 2, 2, 3, 3,
  8055. 3, 2, 2, 1, 3, 0, 2, 2,
  8056. 0, 0, 3, 2, 2, 9, 0, 0,
  8057. 0, 0, 2, 7, 0, 0, 3, 3,
  8058. 3, 0, 1, 1, 1, 1, 0, 1,
  8059. 1, 1, 0, 1, 1, 1, 0, 3,
  8060. 3, 2, 2, 3, 3, 3, 2, 0,
  8061. 1, 0, 0, 0
  8062. };
  8063. static const char _json_range_lengths[] = {
  8064. 0, 1, 1, 1, 1, 1, 1, 1,
  8065. 1, 1, 1, 1, 0, 1, 1, 1,
  8066. 1, 1, 1, 0, 0, 0, 3, 3,
  8067. 3, 3, 0, 1, 0, 0, 1, 1,
  8068. 1, 0, 0, 0, 0, 0, 0, 0,
  8069. 0, 0, 0, 0, 0, 0, 0, 1,
  8070. 1, 1, 1, 1, 1, 1, 1, 0,
  8071. 1, 0, 0, 0
  8072. };
  8073. static const short _json_index_offsets[] = {
  8074. 0, 0, 4, 9, 14, 18, 22, 27,
  8075. 32, 37, 41, 45, 48, 52, 54, 58,
  8076. 62, 64, 66, 71, 74, 77, 87, 91,
  8077. 95, 99, 103, 106, 115, 116, 117, 122,
  8078. 127, 132, 133, 135, 137, 139, 141, 142,
  8079. 144, 146, 148, 149, 151, 153, 155, 156,
  8080. 161, 166, 170, 174, 179, 184, 189, 193,
  8081. 194, 197, 198, 199
  8082. };
  8083. static const char _json_indicies[] = {
  8084. 0, 2, 0, 1, 3, 4, 5, 3,
  8085. 1, 6, 7, 8, 6, 1, 9, 10,
  8086. 9, 1, 11, 12, 11, 1, 12, 1,
  8087. 1, 12, 13, 14, 15, 16, 14, 1,
  8088. 17, 18, 8, 17, 1, 18, 7, 18,
  8089. 1, 19, 20, 21, 1, 20, 21, 1,
  8090. 23, 24, 24, 22, 25, 1, 24, 24,
  8091. 25, 22, 26, 26, 27, 1, 27, 1,
  8092. 27, 22, 23, 24, 24, 21, 22, 29,
  8093. 30, 28, 32, 33, 31, 34, 34, 34,
  8094. 34, 34, 34, 34, 34, 35, 1, 36,
  8095. 36, 36, 1, 37, 37, 37, 1, 38,
  8096. 38, 38, 1, 39, 39, 39, 1, 41,
  8097. 42, 40, 43, 44, 45, 46, 47, 48,
  8098. 49, 44, 1, 50, 51, 53, 54, 1,
  8099. 53, 52, 55, 56, 54, 55, 1, 56,
  8100. 1, 1, 56, 52, 57, 58, 1, 59,
  8101. 1, 60, 1, 61, 1, 62, 63, 1,
  8102. 64, 1, 65, 1, 66, 67, 1, 68,
  8103. 1, 69, 1, 70, 71, 72, 73, 71,
  8104. 1, 74, 75, 76, 74, 1, 77, 78,
  8105. 77, 1, 79, 80, 79, 1, 80, 1,
  8106. 1, 80, 81, 82, 83, 84, 82, 1,
  8107. 85, 86, 76, 85, 1, 86, 75, 86,
  8108. 1, 87, 88, 88, 1, 1, 1, 1,
  8109. 0
  8110. };
  8111. static const char _json_trans_targs[] = {
  8112. 1, 0, 2, 3, 4, 56, 3, 4,
  8113. 56, 5, 6, 5, 6, 7, 8, 9,
  8114. 56, 8, 9, 11, 12, 18, 57, 13,
  8115. 15, 14, 16, 17, 20, 58, 21, 20,
  8116. 58, 21, 19, 22, 23, 24, 25, 26,
  8117. 20, 58, 21, 28, 29, 30, 34, 39,
  8118. 43, 47, 59, 59, 31, 30, 33, 31,
  8119. 32, 59, 35, 36, 37, 38, 59, 40,
  8120. 41, 42, 59, 44, 45, 46, 59, 48,
  8121. 49, 55, 48, 49, 55, 50, 51, 50,
  8122. 51, 52, 53, 54, 55, 53, 54, 59,
  8123. 56
  8124. };
  8125. static const char _json_trans_actions[] = {
  8126. 0, 0, 0, 21, 75, 48, 0, 42,
  8127. 23, 17, 17, 0, 0, 15, 19, 19,
  8128. 45, 0, 0, 0, 0, 0, 1, 0,
  8129. 0, 0, 0, 0, 3, 13, 0, 0,
  8130. 33, 5, 11, 0, 7, 0, 0, 0,
  8131. 36, 39, 9, 57, 51, 25, 0, 0,
  8132. 0, 29, 60, 54, 15, 0, 27, 0,
  8133. 0, 31, 0, 0, 0, 0, 66, 0,
  8134. 0, 0, 69, 0, 0, 0, 63, 21,
  8135. 75, 48, 0, 42, 23, 17, 17, 0,
  8136. 0, 15, 19, 19, 45, 0, 0, 72,
  8137. 0
  8138. };
  8139. static const int json_start = 1;
  8140. static const int json_first_final = 56;
  8141. static const int json_error = 0;
  8142. static const int json_en_number_machine = 10;
  8143. static const int json_en_string_machine = 19;
  8144. static const int json_en_value_machine = 27;
  8145. static const int json_en_main = 1;
  8146. #line 599 "upb/json/parser.rl"
  8147. size_t parse(void *closure, const void *hd, const char *buf, size_t size,
  8148. const upb_bufhandle *handle) {
  8149. UPB_UNUSED(hd);
  8150. UPB_UNUSED(handle);
  8151. upb_json_parser *parser = closure;
  8152. // Variables used by Ragel's generated code.
  8153. int cs = parser->current_state;
  8154. int *stack = parser->parser_stack;
  8155. int top = parser->parser_top;
  8156. const char *p = buf;
  8157. const char *pe = buf + size;
  8158. #line 684 "upb/json/parser.c"
  8159. {
  8160. int _klen;
  8161. unsigned int _trans;
  8162. const char *_acts;
  8163. unsigned int _nacts;
  8164. const char *_keys;
  8165. if ( p == pe )
  8166. goto _test_eof;
  8167. if ( cs == 0 )
  8168. goto _out;
  8169. _resume:
  8170. _keys = _json_trans_keys + _json_key_offsets[cs];
  8171. _trans = _json_index_offsets[cs];
  8172. _klen = _json_single_lengths[cs];
  8173. if ( _klen > 0 ) {
  8174. const char *_lower = _keys;
  8175. const char *_mid;
  8176. const char *_upper = _keys + _klen - 1;
  8177. while (1) {
  8178. if ( _upper < _lower )
  8179. break;
  8180. _mid = _lower + ((_upper-_lower) >> 1);
  8181. if ( (*p) < *_mid )
  8182. _upper = _mid - 1;
  8183. else if ( (*p) > *_mid )
  8184. _lower = _mid + 1;
  8185. else {
  8186. _trans += (unsigned int)(_mid - _keys);
  8187. goto _match;
  8188. }
  8189. }
  8190. _keys += _klen;
  8191. _trans += _klen;
  8192. }
  8193. _klen = _json_range_lengths[cs];
  8194. if ( _klen > 0 ) {
  8195. const char *_lower = _keys;
  8196. const char *_mid;
  8197. const char *_upper = _keys + (_klen<<1) - 2;
  8198. while (1) {
  8199. if ( _upper < _lower )
  8200. break;
  8201. _mid = _lower + (((_upper-_lower) >> 1) & ~1);
  8202. if ( (*p) < _mid[0] )
  8203. _upper = _mid - 2;
  8204. else if ( (*p) > _mid[1] )
  8205. _lower = _mid + 2;
  8206. else {
  8207. _trans += (unsigned int)((_mid - _keys)>>1);
  8208. goto _match;
  8209. }
  8210. }
  8211. _trans += _klen;
  8212. }
  8213. _match:
  8214. _trans = _json_indicies[_trans];
  8215. cs = _json_trans_targs[_trans];
  8216. if ( _json_trans_actions[_trans] == 0 )
  8217. goto _again;
  8218. _acts = _json_actions + _json_trans_actions[_trans];
  8219. _nacts = (unsigned int) *_acts++;
  8220. while ( _nacts-- > 0 )
  8221. {
  8222. switch ( *_acts++ )
  8223. {
  8224. case 0:
  8225. #line 517 "upb/json/parser.rl"
  8226. { p--; {cs = stack[--top]; goto _again;} }
  8227. break;
  8228. case 1:
  8229. #line 518 "upb/json/parser.rl"
  8230. { p--; {stack[top++] = cs; cs = 10; goto _again;} }
  8231. break;
  8232. case 2:
  8233. #line 522 "upb/json/parser.rl"
  8234. { start_text(parser, p); }
  8235. break;
  8236. case 3:
  8237. #line 523 "upb/json/parser.rl"
  8238. { CHECK_RETURN_TOP(end_text(parser, p, false)); }
  8239. break;
  8240. case 4:
  8241. #line 529 "upb/json/parser.rl"
  8242. { start_hex(parser, p); }
  8243. break;
  8244. case 5:
  8245. #line 530 "upb/json/parser.rl"
  8246. { hex(parser, p); }
  8247. break;
  8248. case 6:
  8249. #line 536 "upb/json/parser.rl"
  8250. { escape(parser, p); }
  8251. break;
  8252. case 7:
  8253. #line 539 "upb/json/parser.rl"
  8254. { {cs = stack[--top]; goto _again;} }
  8255. break;
  8256. case 8:
  8257. #line 540 "upb/json/parser.rl"
  8258. { {stack[top++] = cs; cs = 19; goto _again;} }
  8259. break;
  8260. case 9:
  8261. #line 542 "upb/json/parser.rl"
  8262. { p--; {stack[top++] = cs; cs = 27; goto _again;} }
  8263. break;
  8264. case 10:
  8265. #line 547 "upb/json/parser.rl"
  8266. { start_member(parser); }
  8267. break;
  8268. case 11:
  8269. #line 548 "upb/json/parser.rl"
  8270. { CHECK_RETURN_TOP(end_member(parser)); }
  8271. break;
  8272. case 12:
  8273. #line 551 "upb/json/parser.rl"
  8274. { clear_member(parser); }
  8275. break;
  8276. case 13:
  8277. #line 557 "upb/json/parser.rl"
  8278. { start_object(parser); }
  8279. break;
  8280. case 14:
  8281. #line 560 "upb/json/parser.rl"
  8282. { end_object(parser); }
  8283. break;
  8284. case 15:
  8285. #line 566 "upb/json/parser.rl"
  8286. { CHECK_RETURN_TOP(start_array(parser)); }
  8287. break;
  8288. case 16:
  8289. #line 570 "upb/json/parser.rl"
  8290. { end_array(parser); }
  8291. break;
  8292. case 17:
  8293. #line 575 "upb/json/parser.rl"
  8294. { start_number(parser, p); }
  8295. break;
  8296. case 18:
  8297. #line 576 "upb/json/parser.rl"
  8298. { end_number(parser, p); }
  8299. break;
  8300. case 19:
  8301. #line 578 "upb/json/parser.rl"
  8302. { CHECK_RETURN_TOP(start_stringval(parser)); }
  8303. break;
  8304. case 20:
  8305. #line 579 "upb/json/parser.rl"
  8306. { end_stringval(parser); }
  8307. break;
  8308. case 21:
  8309. #line 581 "upb/json/parser.rl"
  8310. { CHECK_RETURN_TOP(parser_putbool(parser, true)); }
  8311. break;
  8312. case 22:
  8313. #line 583 "upb/json/parser.rl"
  8314. { CHECK_RETURN_TOP(parser_putbool(parser, false)); }
  8315. break;
  8316. case 23:
  8317. #line 585 "upb/json/parser.rl"
  8318. { /* null value */ }
  8319. break;
  8320. case 24:
  8321. #line 587 "upb/json/parser.rl"
  8322. { CHECK_RETURN_TOP(start_subobject(parser)); }
  8323. break;
  8324. case 25:
  8325. #line 588 "upb/json/parser.rl"
  8326. { end_subobject(parser); }
  8327. break;
  8328. case 26:
  8329. #line 593 "upb/json/parser.rl"
  8330. { p--; {cs = stack[--top]; goto _again;} }
  8331. break;
  8332. #line 866 "upb/json/parser.c"
  8333. }
  8334. }
  8335. _again:
  8336. if ( cs == 0 )
  8337. goto _out;
  8338. if ( ++p != pe )
  8339. goto _resume;
  8340. _test_eof: {}
  8341. _out: {}
  8342. }
  8343. #line 615 "upb/json/parser.rl"
  8344. if (p != pe) {
  8345. upb_status_seterrf(parser->status, "Parse error at %s\n", p);
  8346. }
  8347. error:
  8348. // Save parsing state back to parser.
  8349. parser->current_state = cs;
  8350. parser->parser_top = top;
  8351. return p - buf;
  8352. }
  8353. bool end(void *closure, const void *hd) {
  8354. UPB_UNUSED(closure);
  8355. UPB_UNUSED(hd);
  8356. return true;
  8357. }
  8358. void upb_json_parser_init(upb_json_parser *p, upb_status *status) {
  8359. p->limit = p->stack + UPB_JSON_MAX_DEPTH;
  8360. upb_byteshandler_init(&p->input_handler_);
  8361. upb_byteshandler_setstring(&p->input_handler_, parse, NULL);
  8362. upb_byteshandler_setendstr(&p->input_handler_, end, NULL);
  8363. upb_bytessink_reset(&p->input_, &p->input_handler_, p);
  8364. p->status = status;
  8365. }
  8366. void upb_json_parser_uninit(upb_json_parser *p) {
  8367. upb_byteshandler_uninit(&p->input_handler_);
  8368. }
  8369. void upb_json_parser_reset(upb_json_parser *p) {
  8370. p->top = p->stack;
  8371. p->top->f = NULL;
  8372. int cs;
  8373. int top;
  8374. // Emit Ragel initialization of the parser.
  8375. #line 920 "upb/json/parser.c"
  8376. {
  8377. cs = json_start;
  8378. top = 0;
  8379. }
  8380. #line 655 "upb/json/parser.rl"
  8381. p->current_state = cs;
  8382. p->parser_top = top;
  8383. p->text_begin = NULL;
  8384. p->accumulated = NULL;
  8385. p->accumulated_len = 0;
  8386. }
  8387. void upb_json_parser_resetoutput(upb_json_parser *p, upb_sink *sink) {
  8388. upb_json_parser_reset(p);
  8389. upb_sink_reset(&p->top->sink, sink->handlers, sink->closure);
  8390. p->top->m = upb_handlers_msgdef(sink->handlers);
  8391. p->accumulated = NULL;
  8392. }
  8393. upb_bytessink *upb_json_parser_input(upb_json_parser *p) {
  8394. return &p->input_;
  8395. }
  8396. /*
  8397. * upb - a minimalist implementation of protocol buffers.
  8398. *
  8399. * Copyright (c) 2014 Google Inc. See LICENSE for details.
  8400. * Author: Josh Haberman <jhaberman@gmail.com>
  8401. *
  8402. * This currently uses snprintf() to format primitives, and could be optimized
  8403. * further.
  8404. */
  8405. #include <stdlib.h>
  8406. #include <stdio.h>
  8407. #include <string.h>
  8408. #include <stdint.h>
  8409. // StringPiece; a pointer plus a length.
  8410. typedef struct {
  8411. const char *ptr;
  8412. size_t len;
  8413. } strpc;
  8414. strpc *newstrpc(upb_handlers *h, const upb_fielddef *f) {
  8415. strpc *ret = malloc(sizeof(*ret));
  8416. ret->ptr = upb_fielddef_name(f);
  8417. ret->len = strlen(ret->ptr);
  8418. upb_handlers_addcleanup(h, ret, free);
  8419. return ret;
  8420. }
  8421. // ------------ JSON string printing: values, maps, arrays --------------------
  8422. static void print_data(
  8423. upb_json_printer *p, const char *buf, unsigned int len) {
  8424. // TODO: Will need to change if we support pushback from the sink.
  8425. size_t n = upb_bytessink_putbuf(p->output_, p->subc_, buf, len, NULL);
  8426. UPB_ASSERT_VAR(n, n == len);
  8427. }
  8428. static void print_comma(upb_json_printer *p) {
  8429. if (!p->first_elem_[p->depth_]) {
  8430. print_data(p, ",", 1);
  8431. }
  8432. p->first_elem_[p->depth_] = false;
  8433. }
  8434. // Helpers that print properly formatted elements to the JSON output stream.
  8435. // Used for escaping control chars in strings.
  8436. static const char kControlCharLimit = 0x20;
  8437. static inline bool is_json_escaped(char c) {
  8438. // See RFC 4627.
  8439. unsigned char uc = (unsigned char)c;
  8440. return uc < kControlCharLimit || uc == '"' || uc == '\\';
  8441. }
  8442. static inline char* json_nice_escape(char c) {
  8443. switch (c) {
  8444. case '"': return "\\\"";
  8445. case '\\': return "\\\\";
  8446. case '\b': return "\\b";
  8447. case '\f': return "\\f";
  8448. case '\n': return "\\n";
  8449. case '\r': return "\\r";
  8450. case '\t': return "\\t";
  8451. default: return NULL;
  8452. }
  8453. }
  8454. // Write a properly escaped string chunk. The surrounding quotes are *not*
  8455. // printed; this is so that the caller has the option of emitting the string
  8456. // content in chunks.
  8457. static void putstring(upb_json_printer *p, const char *buf, unsigned int len) {
  8458. const char* unescaped_run = NULL;
  8459. for (unsigned int i = 0; i < len; i++) {
  8460. char c = buf[i];
  8461. // Handle escaping.
  8462. if (is_json_escaped(c)) {
  8463. // Use a "nice" escape, like \n, if one exists for this character.
  8464. const char* escape = json_nice_escape(c);
  8465. // If we don't have a specific 'nice' escape code, use a \uXXXX-style
  8466. // escape.
  8467. char escape_buf[8];
  8468. if (!escape) {
  8469. unsigned char byte = (unsigned char)c;
  8470. snprintf(escape_buf, sizeof(escape_buf), "\\u%04x", (int)byte);
  8471. escape = escape_buf;
  8472. }
  8473. // N.B. that we assume that the input encoding is equal to the output
  8474. // encoding (both UTF-8 for now), so for chars >= 0x20 and != \, ", we
  8475. // can simply pass the bytes through.
  8476. // If there's a current run of unescaped chars, print that run first.
  8477. if (unescaped_run) {
  8478. print_data(p, unescaped_run, &buf[i] - unescaped_run);
  8479. unescaped_run = NULL;
  8480. }
  8481. // Then print the escape code.
  8482. print_data(p, escape, strlen(escape));
  8483. } else {
  8484. // Add to the current unescaped run of characters.
  8485. if (unescaped_run == NULL) {
  8486. unescaped_run = &buf[i];
  8487. }
  8488. }
  8489. }
  8490. // If the string ended in a run of unescaped characters, print that last run.
  8491. if (unescaped_run) {
  8492. print_data(p, unescaped_run, &buf[len] - unescaped_run);
  8493. }
  8494. }
  8495. #define CHKLENGTH(x) if (!(x)) return -1;
  8496. // Helpers that format floating point values according to our custom formats.
  8497. // Right now we use %.8g and %.17g for float/double, respectively, to match
  8498. // proto2::util::JsonFormat's defaults. May want to change this later.
  8499. static size_t fmt_double(double val, char* buf, size_t length) {
  8500. size_t n = snprintf(buf, length, "%.17g", val);
  8501. CHKLENGTH(n > 0 && n < length);
  8502. return n;
  8503. }
  8504. static size_t fmt_float(float val, char* buf, size_t length) {
  8505. size_t n = snprintf(buf, length, "%.8g", val);
  8506. CHKLENGTH(n > 0 && n < length);
  8507. return n;
  8508. }
  8509. static size_t fmt_bool(bool val, char* buf, size_t length) {
  8510. size_t n = snprintf(buf, length, "%s", (val ? "true" : "false"));
  8511. CHKLENGTH(n > 0 && n < length);
  8512. return n;
  8513. }
  8514. static size_t fmt_int64(long val, char* buf, size_t length) {
  8515. size_t n = snprintf(buf, length, "%ld", val);
  8516. CHKLENGTH(n > 0 && n < length);
  8517. return n;
  8518. }
  8519. static size_t fmt_uint64(unsigned long long val, char* buf, size_t length) {
  8520. size_t n = snprintf(buf, length, "%llu", val);
  8521. CHKLENGTH(n > 0 && n < length);
  8522. return n;
  8523. }
  8524. // Print a map key given a field name. Called by scalar field handlers and by
  8525. // startseq for repeated fields.
  8526. static bool putkey(void *closure, const void *handler_data) {
  8527. upb_json_printer *p = closure;
  8528. const strpc *key = handler_data;
  8529. print_comma(p);
  8530. print_data(p, "\"", 1);
  8531. putstring(p, key->ptr, key->len);
  8532. print_data(p, "\":", 2);
  8533. return true;
  8534. }
  8535. #define CHKFMT(val) if ((val) == -1) return false;
  8536. #define CHK(val) if (!(val)) return false;
  8537. #define TYPE_HANDLERS(type, fmt_func) \
  8538. static bool put##type(void *closure, const void *handler_data, type val) { \
  8539. upb_json_printer *p = closure; \
  8540. UPB_UNUSED(handler_data); \
  8541. char data[64]; \
  8542. size_t length = fmt_func(val, data, sizeof(data)); \
  8543. CHKFMT(length); \
  8544. print_data(p, data, length); \
  8545. return true; \
  8546. } \
  8547. static bool scalar_##type(void *closure, const void *handler_data, \
  8548. type val) { \
  8549. CHK(putkey(closure, handler_data)); \
  8550. CHK(put##type(closure, handler_data, val)); \
  8551. return true; \
  8552. } \
  8553. static bool repeated_##type(void *closure, const void *handler_data, \
  8554. type val) { \
  8555. upb_json_printer *p = closure; \
  8556. print_comma(p); \
  8557. CHK(put##type(closure, handler_data, val)); \
  8558. return true; \
  8559. }
  8560. TYPE_HANDLERS(double, fmt_double);
  8561. TYPE_HANDLERS(float, fmt_float);
  8562. TYPE_HANDLERS(bool, fmt_bool);
  8563. TYPE_HANDLERS(int32_t, fmt_int64);
  8564. TYPE_HANDLERS(uint32_t, fmt_int64);
  8565. TYPE_HANDLERS(int64_t, fmt_int64);
  8566. TYPE_HANDLERS(uint64_t, fmt_uint64);
  8567. #undef TYPE_HANDLERS
  8568. typedef struct {
  8569. void *keyname;
  8570. const upb_enumdef *enumdef;
  8571. } EnumHandlerData;
  8572. static bool scalar_enum(void *closure, const void *handler_data,
  8573. int32_t val) {
  8574. const EnumHandlerData *hd = handler_data;
  8575. upb_json_printer *p = closure;
  8576. CHK(putkey(closure, hd->keyname));
  8577. const char *symbolic_name = upb_enumdef_iton(hd->enumdef, val);
  8578. if (symbolic_name) {
  8579. print_data(p, "\"", 1);
  8580. putstring(p, symbolic_name, strlen(symbolic_name));
  8581. print_data(p, "\"", 1);
  8582. } else {
  8583. putint32_t(closure, NULL, val);
  8584. }
  8585. return true;
  8586. }
  8587. static bool repeated_enum(void *closure, const void *handler_data,
  8588. int32_t val) {
  8589. const EnumHandlerData *hd = handler_data;
  8590. upb_json_printer *p = closure;
  8591. print_comma(p);
  8592. const char *symbolic_name = upb_enumdef_iton(hd->enumdef, val);
  8593. if (symbolic_name) {
  8594. print_data(p, "\"", 1);
  8595. putstring(p, symbolic_name, strlen(symbolic_name));
  8596. print_data(p, "\"", 1);
  8597. } else {
  8598. putint32_t(closure, NULL, val);
  8599. }
  8600. return true;
  8601. }
  8602. static void *scalar_startsubmsg(void *closure, const void *handler_data) {
  8603. return putkey(closure, handler_data) ? closure : UPB_BREAK;
  8604. }
  8605. static void *repeated_startsubmsg(void *closure, const void *handler_data) {
  8606. UPB_UNUSED(handler_data);
  8607. upb_json_printer *p = closure;
  8608. print_comma(p);
  8609. return closure;
  8610. }
  8611. static bool startmap(void *closure, const void *handler_data) {
  8612. UPB_UNUSED(handler_data);
  8613. upb_json_printer *p = closure;
  8614. if (p->depth_++ == 0) {
  8615. upb_bytessink_start(p->output_, 0, &p->subc_);
  8616. }
  8617. p->first_elem_[p->depth_] = true;
  8618. print_data(p, "{", 1);
  8619. return true;
  8620. }
  8621. static bool endmap(void *closure, const void *handler_data, upb_status *s) {
  8622. UPB_UNUSED(handler_data);
  8623. UPB_UNUSED(s);
  8624. upb_json_printer *p = closure;
  8625. if (--p->depth_ == 0) {
  8626. upb_bytessink_end(p->output_);
  8627. }
  8628. print_data(p, "}", 1);
  8629. return true;
  8630. }
  8631. static void *startseq(void *closure, const void *handler_data) {
  8632. upb_json_printer *p = closure;
  8633. CHK(putkey(closure, handler_data));
  8634. p->depth_++;
  8635. p->first_elem_[p->depth_] = true;
  8636. print_data(p, "[", 1);
  8637. return closure;
  8638. }
  8639. static bool endseq(void *closure, const void *handler_data) {
  8640. UPB_UNUSED(handler_data);
  8641. upb_json_printer *p = closure;
  8642. print_data(p, "]", 1);
  8643. p->depth_--;
  8644. return true;
  8645. }
  8646. static size_t putstr(void *closure, const void *handler_data, const char *str,
  8647. size_t len, const upb_bufhandle *handle) {
  8648. UPB_UNUSED(handler_data);
  8649. UPB_UNUSED(handle);
  8650. upb_json_printer *p = closure;
  8651. putstring(p, str, len);
  8652. return len;
  8653. }
  8654. // This has to Base64 encode the bytes, because JSON has no "bytes" type.
  8655. static size_t putbytes(void *closure, const void *handler_data, const char *str,
  8656. size_t len, const upb_bufhandle *handle) {
  8657. UPB_UNUSED(handler_data);
  8658. UPB_UNUSED(handle);
  8659. upb_json_printer *p = closure;
  8660. // This is the regular base64, not the "web-safe" version.
  8661. static const char base64[] =
  8662. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  8663. // Base64-encode.
  8664. char data[16000];
  8665. const char *limit = data + sizeof(data);
  8666. const unsigned char *from = (const unsigned char*)str;
  8667. char *to = data;
  8668. size_t remaining = len;
  8669. while (remaining > 2) {
  8670. // TODO(haberman): handle encoded lengths > sizeof(data)
  8671. UPB_ASSERT_VAR(limit, (limit - to) >= 4);
  8672. to[0] = base64[from[0] >> 2];
  8673. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  8674. to[2] = base64[((from[1] & 0xf) << 2) | (from[2] >> 6)];
  8675. to[3] = base64[from[2] & 0x3f];
  8676. remaining -= 3;
  8677. to += 4;
  8678. from += 3;
  8679. }
  8680. switch (remaining) {
  8681. case 2:
  8682. to[0] = base64[from[0] >> 2];
  8683. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  8684. to[2] = base64[(from[1] & 0xf) << 2];
  8685. to[3] = '=';
  8686. to += 4;
  8687. from += 2;
  8688. break;
  8689. case 1:
  8690. to[0] = base64[from[0] >> 2];
  8691. to[1] = base64[((from[0] & 0x3) << 4)];
  8692. to[2] = '=';
  8693. to[3] = '=';
  8694. to += 4;
  8695. from += 1;
  8696. break;
  8697. }
  8698. size_t bytes = to - data;
  8699. print_data(p, "\"", 1);
  8700. putstring(p, data, bytes);
  8701. print_data(p, "\"", 1);
  8702. return len;
  8703. }
  8704. static void *scalar_startstr(void *closure, const void *handler_data,
  8705. size_t size_hint) {
  8706. UPB_UNUSED(handler_data);
  8707. UPB_UNUSED(size_hint);
  8708. upb_json_printer *p = closure;
  8709. CHK(putkey(closure, handler_data));
  8710. print_data(p, "\"", 1);
  8711. return p;
  8712. }
  8713. static size_t scalar_str(void *closure, const void *handler_data,
  8714. const char *str, size_t len,
  8715. const upb_bufhandle *handle) {
  8716. CHK(putstr(closure, handler_data, str, len, handle));
  8717. return len;
  8718. }
  8719. static bool scalar_endstr(void *closure, const void *handler_data) {
  8720. UPB_UNUSED(handler_data);
  8721. upb_json_printer *p = closure;
  8722. print_data(p, "\"", 1);
  8723. return true;
  8724. }
  8725. static void *repeated_startstr(void *closure, const void *handler_data,
  8726. size_t size_hint) {
  8727. UPB_UNUSED(handler_data);
  8728. UPB_UNUSED(size_hint);
  8729. upb_json_printer *p = closure;
  8730. print_comma(p);
  8731. print_data(p, "\"", 1);
  8732. return p;
  8733. }
  8734. static size_t repeated_str(void *closure, const void *handler_data,
  8735. const char *str, size_t len,
  8736. const upb_bufhandle *handle) {
  8737. CHK(putstr(closure, handler_data, str, len, handle));
  8738. return len;
  8739. }
  8740. static bool repeated_endstr(void *closure, const void *handler_data) {
  8741. UPB_UNUSED(handler_data);
  8742. upb_json_printer *p = closure;
  8743. print_data(p, "\"", 1);
  8744. return true;
  8745. }
  8746. static size_t scalar_bytes(void *closure, const void *handler_data,
  8747. const char *str, size_t len,
  8748. const upb_bufhandle *handle) {
  8749. CHK(putkey(closure, handler_data));
  8750. CHK(putbytes(closure, handler_data, str, len, handle));
  8751. return len;
  8752. }
  8753. static size_t repeated_bytes(void *closure, const void *handler_data,
  8754. const char *str, size_t len,
  8755. const upb_bufhandle *handle) {
  8756. upb_json_printer *p = closure;
  8757. print_comma(p);
  8758. CHK(putbytes(closure, handler_data, str, len, handle));
  8759. return len;
  8760. }
  8761. void printer_sethandlers(const void *closure, upb_handlers *h) {
  8762. UPB_UNUSED(closure);
  8763. upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
  8764. upb_handlers_setstartmsg(h, startmap, &empty_attr);
  8765. upb_handlers_setendmsg(h, endmap, &empty_attr);
  8766. #define TYPE(type, name, ctype) \
  8767. case type: \
  8768. if (upb_fielddef_isseq(f)) { \
  8769. upb_handlers_set##name(h, f, repeated_##ctype, &empty_attr); \
  8770. } else { \
  8771. upb_handlers_set##name(h, f, scalar_##ctype, &name_attr); \
  8772. } \
  8773. break;
  8774. upb_msg_iter i;
  8775. upb_msg_begin(&i, upb_handlers_msgdef(h));
  8776. for(; !upb_msg_done(&i); upb_msg_next(&i)) {
  8777. const upb_fielddef *f = upb_msg_iter_field(&i);
  8778. upb_handlerattr name_attr = UPB_HANDLERATTR_INITIALIZER;
  8779. upb_handlerattr_sethandlerdata(&name_attr, newstrpc(h, f));
  8780. if (upb_fielddef_isseq(f)) {
  8781. upb_handlers_setstartseq(h, f, startseq, &name_attr);
  8782. upb_handlers_setendseq(h, f, endseq, &empty_attr);
  8783. }
  8784. switch (upb_fielddef_type(f)) {
  8785. TYPE(UPB_TYPE_FLOAT, float, float);
  8786. TYPE(UPB_TYPE_DOUBLE, double, double);
  8787. TYPE(UPB_TYPE_BOOL, bool, bool);
  8788. TYPE(UPB_TYPE_INT32, int32, int32_t);
  8789. TYPE(UPB_TYPE_UINT32, uint32, uint32_t);
  8790. TYPE(UPB_TYPE_INT64, int64, int64_t);
  8791. TYPE(UPB_TYPE_UINT64, uint64, uint64_t);
  8792. case UPB_TYPE_ENUM: {
  8793. // For now, we always emit symbolic names for enums. We may want an
  8794. // option later to control this behavior, but we will wait for a real
  8795. // need first.
  8796. EnumHandlerData *hd = malloc(sizeof(EnumHandlerData));
  8797. hd->enumdef = (const upb_enumdef *)upb_fielddef_subdef(f);
  8798. hd->keyname = newstrpc(h, f);
  8799. upb_handlers_addcleanup(h, hd, free);
  8800. upb_handlerattr enum_attr = UPB_HANDLERATTR_INITIALIZER;
  8801. upb_handlerattr_sethandlerdata(&enum_attr, hd);
  8802. if (upb_fielddef_isseq(f)) {
  8803. upb_handlers_setint32(h, f, repeated_enum, &enum_attr);
  8804. } else {
  8805. upb_handlers_setint32(h, f, scalar_enum, &enum_attr);
  8806. }
  8807. upb_handlerattr_uninit(&enum_attr);
  8808. break;
  8809. }
  8810. case UPB_TYPE_STRING:
  8811. if (upb_fielddef_isseq(f)) {
  8812. upb_handlers_setstartstr(h, f, repeated_startstr, &empty_attr);
  8813. upb_handlers_setstring(h, f, repeated_str, &empty_attr);
  8814. upb_handlers_setendstr(h, f, repeated_endstr, &empty_attr);
  8815. } else {
  8816. upb_handlers_setstartstr(h, f, scalar_startstr, &name_attr);
  8817. upb_handlers_setstring(h, f, scalar_str, &empty_attr);
  8818. upb_handlers_setendstr(h, f, scalar_endstr, &empty_attr);
  8819. }
  8820. break;
  8821. case UPB_TYPE_BYTES:
  8822. // XXX: this doesn't support strings that span buffers yet. The base64
  8823. // encoder will need to be made resumable for this to work properly.
  8824. if (upb_fielddef_isseq(f)) {
  8825. upb_handlers_setstring(h, f, repeated_bytes, &empty_attr);
  8826. } else {
  8827. upb_handlers_setstring(h, f, scalar_bytes, &name_attr);
  8828. }
  8829. break;
  8830. case UPB_TYPE_MESSAGE:
  8831. if (upb_fielddef_isseq(f)) {
  8832. upb_handlers_setstartsubmsg(h, f, repeated_startsubmsg, &name_attr);
  8833. } else {
  8834. upb_handlers_setstartsubmsg(h, f, scalar_startsubmsg, &name_attr);
  8835. }
  8836. break;
  8837. }
  8838. upb_handlerattr_uninit(&name_attr);
  8839. }
  8840. upb_handlerattr_uninit(&empty_attr);
  8841. #undef TYPE
  8842. }
  8843. /* Public API *****************************************************************/
  8844. void upb_json_printer_init(upb_json_printer *p, const upb_handlers *h) {
  8845. p->output_ = NULL;
  8846. p->depth_ = 0;
  8847. upb_sink_reset(&p->input_, h, p);
  8848. }
  8849. void upb_json_printer_uninit(upb_json_printer *p) {
  8850. UPB_UNUSED(p);
  8851. }
  8852. void upb_json_printer_reset(upb_json_printer *p) {
  8853. p->depth_ = 0;
  8854. }
  8855. void upb_json_printer_resetoutput(upb_json_printer *p, upb_bytessink *output) {
  8856. upb_json_printer_reset(p);
  8857. p->output_ = output;
  8858. }
  8859. upb_sink *upb_json_printer_input(upb_json_printer *p) {
  8860. return &p->input_;
  8861. }
  8862. const upb_handlers *upb_json_printer_newhandlers(const upb_msgdef *md,
  8863. const void *owner) {
  8864. return upb_handlers_newfrozen(md, owner, printer_sethandlers, NULL);
  8865. }