upb.c 409 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817
  1. /* Amalgamated source file */
  2. #include "upb.h"
  3. /*
  4. * This is where we define macros used across upb.
  5. *
  6. * All of these macros are undef'd in port_undef.inc to avoid leaking them to
  7. * users.
  8. *
  9. * The correct usage is:
  10. *
  11. * #include "upb/foobar.h"
  12. * #include "upb/baz.h"
  13. *
  14. * // MUST be last included header.
  15. * #include "upb/port_def.inc"
  16. *
  17. * // Code for this file.
  18. * // <...>
  19. *
  20. * // Can be omitted for .c files, required for .h.
  21. * #include "upb/port_undef.inc"
  22. *
  23. * This file is private and must not be included by users!
  24. */
  25. #include <stdint.h>
  26. #if UINTPTR_MAX == 0xffffffff
  27. #define UPB_SIZE(size32, size64) size32
  28. #else
  29. #define UPB_SIZE(size32, size64) size64
  30. #endif
  31. /* If we always read/write as a consistent type to each address, this shouldn't
  32. * violate aliasing.
  33. */
  34. #define UPB_PTR_AT(msg, ofs, type) ((type*)((char*)(msg) + (ofs)))
  35. #define UPB_READ_ONEOF(msg, fieldtype, offset, case_offset, case_val, default) \
  36. *UPB_PTR_AT(msg, case_offset, int) == case_val \
  37. ? *UPB_PTR_AT(msg, offset, fieldtype) \
  38. : default
  39. #define UPB_WRITE_ONEOF(msg, fieldtype, offset, value, case_offset, case_val) \
  40. *UPB_PTR_AT(msg, case_offset, int) = case_val; \
  41. *UPB_PTR_AT(msg, offset, fieldtype) = value;
  42. #define UPB_MAPTYPE_STRING 0
  43. /* UPB_INLINE: inline if possible, emit standalone code if required. */
  44. #ifdef __cplusplus
  45. #define UPB_INLINE inline
  46. #elif defined (__GNUC__) || defined(__clang__)
  47. #define UPB_INLINE static __inline__
  48. #else
  49. #define UPB_INLINE static
  50. #endif
  51. /* Hints to the compiler about likely/unlikely branches. */
  52. #if defined (__GNUC__) || defined(__clang__)
  53. #define UPB_LIKELY(x) __builtin_expect((x),1)
  54. #define UPB_UNLIKELY(x) __builtin_expect((x),0)
  55. #else
  56. #define UPB_LIKELY(x) (x)
  57. #define UPB_UNLIKELY(x) (x)
  58. #endif
  59. /* Define UPB_BIG_ENDIAN manually if you're on big endian and your compiler
  60. * doesn't provide these preprocessor symbols. */
  61. #if defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)
  62. #define UPB_BIG_ENDIAN
  63. #endif
  64. /* Macros for function attributes on compilers that support them. */
  65. #ifdef __GNUC__
  66. #define UPB_FORCEINLINE __inline__ __attribute__((always_inline))
  67. #define UPB_NOINLINE __attribute__((noinline))
  68. #define UPB_NORETURN __attribute__((__noreturn__))
  69. #else /* !defined(__GNUC__) */
  70. #define UPB_FORCEINLINE
  71. #define UPB_NOINLINE
  72. #define UPB_NORETURN
  73. #endif
  74. #if __STDC_VERSION__ >= 199901L || __cplusplus >= 201103L
  75. /* C99/C++11 versions. */
  76. #include <stdio.h>
  77. #define _upb_snprintf snprintf
  78. #define _upb_vsnprintf vsnprintf
  79. #define _upb_va_copy(a, b) va_copy(a, b)
  80. #elif defined(_MSC_VER)
  81. /* Microsoft C/C++ versions. */
  82. #include <stdarg.h>
  83. #include <stdio.h>
  84. #if _MSC_VER < 1900
  85. int msvc_snprintf(char* s, size_t n, const char* format, ...);
  86. int msvc_vsnprintf(char* s, size_t n, const char* format, va_list arg);
  87. #define UPB_MSVC_VSNPRINTF
  88. #define _upb_snprintf msvc_snprintf
  89. #define _upb_vsnprintf msvc_vsnprintf
  90. #else
  91. #define _upb_snprintf snprintf
  92. #define _upb_vsnprintf vsnprintf
  93. #endif
  94. #define _upb_va_copy(a, b) va_copy(a, b)
  95. #elif defined __GNUC__
  96. /* A few hacky workarounds for functions not in C89.
  97. * For internal use only!
  98. * TODO(haberman): fix these by including our own implementations, or finding
  99. * another workaround.
  100. */
  101. #define _upb_snprintf __builtin_snprintf
  102. #define _upb_vsnprintf __builtin_vsnprintf
  103. #define _upb_va_copy(a, b) __va_copy(a, b)
  104. #else
  105. #error Need implementations of [v]snprintf and va_copy
  106. #endif
  107. #ifdef __cplusplus
  108. #if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__) || \
  109. (defined(_MSC_VER) && _MSC_VER >= 1900)
  110. /* C++11 is present */
  111. #else
  112. #error upb requires C++11 for C++ support
  113. #endif
  114. #endif
  115. #define UPB_MAX(x, y) ((x) > (y) ? (x) : (y))
  116. #define UPB_MIN(x, y) ((x) < (y) ? (x) : (y))
  117. #define UPB_UNUSED(var) (void)var
  118. /* UPB_ASSUME(): in release mode, we tell the compiler to assume this is true.
  119. */
  120. #ifdef NDEBUG
  121. #ifdef __GNUC__
  122. #define UPB_ASSUME(expr) if (!(expr)) __builtin_unreachable()
  123. #else
  124. #define UPB_ASSUME(expr) do {} if (false && (expr))
  125. #endif
  126. #else
  127. #define UPB_ASSUME(expr) assert(expr)
  128. #endif
  129. /* UPB_ASSERT(): in release mode, we use the expression without letting it be
  130. * evaluated. This prevents "unused variable" warnings. */
  131. #ifdef NDEBUG
  132. #define UPB_ASSERT(expr) do {} while (false && (expr))
  133. #else
  134. #define UPB_ASSERT(expr) assert(expr)
  135. #endif
  136. /* UPB_ASSERT_DEBUGVAR(): assert that uses functions or variables that only
  137. * exist in debug mode. This turns into regular assert. */
  138. #define UPB_ASSERT_DEBUGVAR(expr) assert(expr)
  139. #if defined(__GNUC__) || defined(__clang__)
  140. #define UPB_UNREACHABLE() do { assert(0); __builtin_unreachable(); } while(0)
  141. #else
  142. #define UPB_UNREACHABLE() do { assert(0); } while(0)
  143. #endif
  144. /* UPB_INFINITY representing floating-point positive infinity. */
  145. #include <math.h>
  146. #ifdef INFINITY
  147. #define UPB_INFINITY INFINITY
  148. #else
  149. #define UPB_INFINITY (1.0 / 0.0)
  150. #endif
  151. #include <setjmp.h>
  152. #include <string.h>
  153. /* Maps descriptor type -> upb field type. */
  154. static const uint8_t desctype_to_fieldtype[] = {
  155. -1, /* invalid descriptor type */
  156. UPB_TYPE_DOUBLE, /* DOUBLE */
  157. UPB_TYPE_FLOAT, /* FLOAT */
  158. UPB_TYPE_INT64, /* INT64 */
  159. UPB_TYPE_UINT64, /* UINT64 */
  160. UPB_TYPE_INT32, /* INT32 */
  161. UPB_TYPE_UINT64, /* FIXED64 */
  162. UPB_TYPE_UINT32, /* FIXED32 */
  163. UPB_TYPE_BOOL, /* BOOL */
  164. UPB_TYPE_STRING, /* STRING */
  165. UPB_TYPE_MESSAGE, /* GROUP */
  166. UPB_TYPE_MESSAGE, /* MESSAGE */
  167. UPB_TYPE_BYTES, /* BYTES */
  168. UPB_TYPE_UINT32, /* UINT32 */
  169. UPB_TYPE_ENUM, /* ENUM */
  170. UPB_TYPE_INT32, /* SFIXED32 */
  171. UPB_TYPE_INT64, /* SFIXED64 */
  172. UPB_TYPE_INT32, /* SINT32 */
  173. UPB_TYPE_INT64, /* SINT64 */
  174. };
  175. /* Maps descriptor type -> upb map size. */
  176. static const uint8_t desctype_to_mapsize[] = {
  177. -1, /* invalid descriptor type */
  178. 8, /* DOUBLE */
  179. 4, /* FLOAT */
  180. 8, /* INT64 */
  181. 8, /* UINT64 */
  182. 4, /* INT32 */
  183. 8, /* FIXED64 */
  184. 4, /* FIXED32 */
  185. 1, /* BOOL */
  186. UPB_MAPTYPE_STRING, /* STRING */
  187. sizeof(void *), /* GROUP */
  188. sizeof(void *), /* MESSAGE */
  189. UPB_MAPTYPE_STRING, /* BYTES */
  190. 4, /* UINT32 */
  191. 4, /* ENUM */
  192. 4, /* SFIXED32 */
  193. 8, /* SFIXED64 */
  194. 4, /* SINT32 */
  195. 8, /* SINT64 */
  196. };
  197. static const unsigned fixed32_ok = (1 << UPB_DTYPE_FLOAT) |
  198. (1 << UPB_DTYPE_FIXED32) |
  199. (1 << UPB_DTYPE_SFIXED32);
  200. static const unsigned fixed64_ok = (1 << UPB_DTYPE_DOUBLE) |
  201. (1 << UPB_DTYPE_FIXED64) |
  202. (1 << UPB_DTYPE_SFIXED64);
  203. /* Op: an action to be performed for a wire-type/field-type combination. */
  204. #define OP_SCALAR_LG2(n) (n)
  205. #define OP_FIXPCK_LG2(n) (n + 4)
  206. #define OP_VARPCK_LG2(n) (n + 8)
  207. #define OP_STRING 4
  208. #define OP_SUBMSG 5
  209. static const int8_t varint_ops[19] = {
  210. -1, /* field not found */
  211. -1, /* DOUBLE */
  212. -1, /* FLOAT */
  213. OP_SCALAR_LG2(3), /* INT64 */
  214. OP_SCALAR_LG2(3), /* UINT64 */
  215. OP_SCALAR_LG2(2), /* INT32 */
  216. -1, /* FIXED64 */
  217. -1, /* FIXED32 */
  218. OP_SCALAR_LG2(0), /* BOOL */
  219. -1, /* STRING */
  220. -1, /* GROUP */
  221. -1, /* MESSAGE */
  222. -1, /* BYTES */
  223. OP_SCALAR_LG2(2), /* UINT32 */
  224. OP_SCALAR_LG2(2), /* ENUM */
  225. -1, /* SFIXED32 */
  226. -1, /* SFIXED64 */
  227. OP_SCALAR_LG2(2), /* SINT32 */
  228. OP_SCALAR_LG2(3), /* SINT64 */
  229. };
  230. static const int8_t delim_ops[37] = {
  231. /* For non-repeated field type. */
  232. -1, /* field not found */
  233. -1, /* DOUBLE */
  234. -1, /* FLOAT */
  235. -1, /* INT64 */
  236. -1, /* UINT64 */
  237. -1, /* INT32 */
  238. -1, /* FIXED64 */
  239. -1, /* FIXED32 */
  240. -1, /* BOOL */
  241. OP_STRING, /* STRING */
  242. -1, /* GROUP */
  243. OP_SUBMSG, /* MESSAGE */
  244. OP_STRING, /* BYTES */
  245. -1, /* UINT32 */
  246. -1, /* ENUM */
  247. -1, /* SFIXED32 */
  248. -1, /* SFIXED64 */
  249. -1, /* SINT32 */
  250. -1, /* SINT64 */
  251. /* For repeated field type. */
  252. OP_FIXPCK_LG2(3), /* REPEATED DOUBLE */
  253. OP_FIXPCK_LG2(2), /* REPEATED FLOAT */
  254. OP_VARPCK_LG2(3), /* REPEATED INT64 */
  255. OP_VARPCK_LG2(3), /* REPEATED UINT64 */
  256. OP_VARPCK_LG2(2), /* REPEATED INT32 */
  257. OP_FIXPCK_LG2(3), /* REPEATED FIXED64 */
  258. OP_FIXPCK_LG2(2), /* REPEATED FIXED32 */
  259. OP_VARPCK_LG2(0), /* REPEATED BOOL */
  260. OP_STRING, /* REPEATED STRING */
  261. OP_SUBMSG, /* REPEATED GROUP */
  262. OP_SUBMSG, /* REPEATED MESSAGE */
  263. OP_STRING, /* REPEATED BYTES */
  264. OP_VARPCK_LG2(2), /* REPEATED UINT32 */
  265. OP_VARPCK_LG2(2), /* REPEATED ENUM */
  266. OP_FIXPCK_LG2(2), /* REPEATED SFIXED32 */
  267. OP_FIXPCK_LG2(3), /* REPEATED SFIXED64 */
  268. OP_VARPCK_LG2(2), /* REPEATED SINT32 */
  269. OP_VARPCK_LG2(3), /* REPEATED SINT64 */
  270. };
  271. /* Data pertaining to the parse. */
  272. typedef struct {
  273. const char *limit; /* End of delimited region or end of buffer. */
  274. upb_arena *arena;
  275. int depth;
  276. uint32_t end_group; /* Set to field number of END_GROUP tag, if any. */
  277. jmp_buf err;
  278. } upb_decstate;
  279. typedef union {
  280. bool bool_val;
  281. int32_t int32_val;
  282. int64_t int64_val;
  283. uint32_t uint32_val;
  284. uint64_t uint64_val;
  285. upb_strview str_val;
  286. } wireval;
  287. static const char *decode_msg(upb_decstate *d, const char *ptr, upb_msg *msg,
  288. const upb_msglayout *layout);
  289. UPB_NORETURN static void decode_err(upb_decstate *d) { longjmp(d->err, 1); }
  290. static bool decode_reserve(upb_decstate *d, upb_array *arr, int elem) {
  291. bool need_realloc = arr->size - arr->len < elem;
  292. if (need_realloc && !_upb_array_realloc(arr, arr->len + elem, d->arena)) {
  293. decode_err(d);
  294. }
  295. return need_realloc;
  296. }
  297. UPB_NOINLINE
  298. static const char *decode_longvarint64(upb_decstate *d, const char *ptr,
  299. const char *limit, uint64_t *val) {
  300. uint8_t byte;
  301. int bitpos = 0;
  302. uint64_t out = 0;
  303. do {
  304. if (bitpos >= 70 || ptr == limit) decode_err(d);
  305. byte = *ptr;
  306. out |= (uint64_t)(byte & 0x7F) << bitpos;
  307. ptr++;
  308. bitpos += 7;
  309. } while (byte & 0x80);
  310. *val = out;
  311. return ptr;
  312. }
  313. UPB_FORCEINLINE
  314. static const char *decode_varint64(upb_decstate *d, const char *ptr,
  315. const char *limit, uint64_t *val) {
  316. if (UPB_LIKELY(ptr < limit && (*ptr & 0x80) == 0)) {
  317. *val = (uint8_t)*ptr;
  318. return ptr + 1;
  319. } else {
  320. return decode_longvarint64(d, ptr, limit, val);
  321. }
  322. }
  323. static const char *decode_varint32(upb_decstate *d, const char *ptr,
  324. const char *limit, uint32_t *val) {
  325. uint64_t u64;
  326. ptr = decode_varint64(d, ptr, limit, &u64);
  327. if (u64 > UINT32_MAX) decode_err(d);
  328. *val = (uint32_t)u64;
  329. return ptr;
  330. }
  331. static void decode_munge(int type, wireval *val) {
  332. switch (type) {
  333. case UPB_DESCRIPTOR_TYPE_BOOL:
  334. val->bool_val = val->uint64_val != 0;
  335. break;
  336. case UPB_DESCRIPTOR_TYPE_SINT32: {
  337. uint32_t n = val->uint32_val;
  338. val->int32_val = (n >> 1) ^ -(int32_t)(n & 1);
  339. break;
  340. }
  341. case UPB_DESCRIPTOR_TYPE_SINT64: {
  342. uint64_t n = val->uint64_val;
  343. val->int64_val = (n >> 1) ^ -(int64_t)(n & 1);
  344. break;
  345. }
  346. }
  347. }
  348. static const upb_msglayout_field *upb_find_field(const upb_msglayout *l,
  349. uint32_t field_number) {
  350. static upb_msglayout_field none = {0};
  351. /* Lots of optimization opportunities here. */
  352. int i;
  353. if (l == NULL) return &none;
  354. for (i = 0; i < l->field_count; i++) {
  355. if (l->fields[i].number == field_number) {
  356. return &l->fields[i];
  357. }
  358. }
  359. return &none; /* Unknown field. */
  360. }
  361. static upb_msg *decode_newsubmsg(upb_decstate *d, const upb_msglayout *layout,
  362. const upb_msglayout_field *field) {
  363. const upb_msglayout *subl = layout->submsgs[field->submsg_index];
  364. return _upb_msg_new(subl, d->arena);
  365. }
  366. static void decode_tosubmsg(upb_decstate *d, upb_msg *submsg,
  367. const upb_msglayout *layout,
  368. const upb_msglayout_field *field, upb_strview val) {
  369. const upb_msglayout *subl = layout->submsgs[field->submsg_index];
  370. const char *saved_limit = d->limit;
  371. if (--d->depth < 0) decode_err(d);
  372. d->limit = val.data + val.size;
  373. decode_msg(d, val.data, submsg, subl);
  374. d->limit = saved_limit;
  375. if (d->end_group != 0) decode_err(d);
  376. d->depth++;
  377. }
  378. static const char *decode_group(upb_decstate *d, const char *ptr,
  379. upb_msg *submsg, const upb_msglayout *subl,
  380. uint32_t number) {
  381. if (--d->depth < 0) decode_err(d);
  382. ptr = decode_msg(d, ptr, submsg, subl);
  383. if (d->end_group != number) decode_err(d);
  384. d->end_group = 0;
  385. d->depth++;
  386. return ptr;
  387. }
  388. static const char *decode_togroup(upb_decstate *d, const char *ptr,
  389. upb_msg *submsg, const upb_msglayout *layout,
  390. const upb_msglayout_field *field) {
  391. const upb_msglayout *subl = layout->submsgs[field->submsg_index];
  392. return decode_group(d, ptr, submsg, subl, field->number);
  393. }
  394. static const char *decode_toarray(upb_decstate *d, const char *ptr,
  395. upb_msg *msg, const upb_msglayout *layout,
  396. const upb_msglayout_field *field, wireval val,
  397. int op) {
  398. upb_array **arrp = UPB_PTR_AT(msg, field->offset, void);
  399. upb_array *arr = *arrp;
  400. void *mem;
  401. if (!arr) {
  402. upb_fieldtype_t type = desctype_to_fieldtype[field->descriptortype];
  403. arr = _upb_array_new(d->arena, type);
  404. if (!arr) decode_err(d);
  405. *arrp = arr;
  406. }
  407. decode_reserve(d, arr, 1);
  408. switch (op) {
  409. case OP_SCALAR_LG2(0):
  410. case OP_SCALAR_LG2(2):
  411. case OP_SCALAR_LG2(3):
  412. /* Append scalar value. */
  413. mem = UPB_PTR_AT(_upb_array_ptr(arr), arr->len << op, void);
  414. arr->len++;
  415. memcpy(mem, &val, 1 << op);
  416. return ptr;
  417. case OP_STRING:
  418. /* Append string. */
  419. mem =
  420. UPB_PTR_AT(_upb_array_ptr(arr), arr->len * sizeof(upb_strview), void);
  421. arr->len++;
  422. memcpy(mem, &val, sizeof(upb_strview));
  423. return ptr;
  424. case OP_SUBMSG: {
  425. /* Append submessage / group. */
  426. upb_msg *submsg = decode_newsubmsg(d, layout, field);
  427. *UPB_PTR_AT(_upb_array_ptr(arr), arr->len * sizeof(void *), upb_msg *) =
  428. submsg;
  429. arr->len++;
  430. if (UPB_UNLIKELY(field->descriptortype == UPB_DTYPE_GROUP)) {
  431. ptr = decode_togroup(d, ptr, submsg, layout, field);
  432. } else {
  433. decode_tosubmsg(d, submsg, layout, field, val.str_val);
  434. }
  435. return ptr;
  436. }
  437. case OP_FIXPCK_LG2(2):
  438. case OP_FIXPCK_LG2(3): {
  439. /* Fixed packed. */
  440. int lg2 = op - OP_FIXPCK_LG2(0);
  441. int mask = (1 << lg2) - 1;
  442. int count = val.str_val.size >> lg2;
  443. if ((val.str_val.size & mask) != 0) {
  444. decode_err(d); /* Length isn't a round multiple of elem size. */
  445. }
  446. decode_reserve(d, arr, count);
  447. mem = UPB_PTR_AT(_upb_array_ptr(arr), arr->len << lg2, void);
  448. arr->len += count;
  449. memcpy(mem, val.str_val.data, count << op);
  450. return ptr;
  451. }
  452. case OP_VARPCK_LG2(0):
  453. case OP_VARPCK_LG2(2):
  454. case OP_VARPCK_LG2(3): {
  455. /* Varint packed. */
  456. int lg2 = op - OP_VARPCK_LG2(0);
  457. int scale = 1 << lg2;
  458. const char *ptr = val.str_val.data;
  459. const char *end = ptr + val.str_val.size;
  460. char *out = UPB_PTR_AT(_upb_array_ptr(arr), arr->len << lg2, void);
  461. while (ptr < end) {
  462. wireval elem;
  463. ptr = decode_varint64(d, ptr, end, &elem.uint64_val);
  464. decode_munge(field->descriptortype, &elem);
  465. if (decode_reserve(d, arr, 1)) {
  466. out = UPB_PTR_AT(_upb_array_ptr(arr), arr->len << lg2, void);
  467. }
  468. arr->len++;
  469. memcpy(out, &elem, scale);
  470. out += scale;
  471. }
  472. if (ptr != end) decode_err(d);
  473. return ptr;
  474. }
  475. default:
  476. UPB_UNREACHABLE();
  477. }
  478. }
  479. static void decode_tomap(upb_decstate *d, upb_msg *msg,
  480. const upb_msglayout *layout,
  481. const upb_msglayout_field *field, wireval val) {
  482. upb_map **map_p = UPB_PTR_AT(msg, field->offset, upb_map *);
  483. upb_map *map = *map_p;
  484. upb_map_entry ent;
  485. const upb_msglayout *entry = layout->submsgs[field->submsg_index];
  486. if (!map) {
  487. /* Lazily create map. */
  488. const upb_msglayout *entry = layout->submsgs[field->submsg_index];
  489. const upb_msglayout_field *key_field = &entry->fields[0];
  490. const upb_msglayout_field *val_field = &entry->fields[1];
  491. char key_size = desctype_to_mapsize[key_field->descriptortype];
  492. char val_size = desctype_to_mapsize[val_field->descriptortype];
  493. UPB_ASSERT(key_field->offset == 0);
  494. UPB_ASSERT(val_field->offset == sizeof(upb_strview));
  495. map = _upb_map_new(d->arena, key_size, val_size);
  496. *map_p = map;
  497. }
  498. /* Parse map entry. */
  499. memset(&ent, 0, sizeof(ent));
  500. if (entry->fields[1].descriptortype == UPB_DESCRIPTOR_TYPE_MESSAGE ||
  501. entry->fields[1].descriptortype == UPB_DESCRIPTOR_TYPE_GROUP) {
  502. /* Create proactively to handle the case where it doesn't appear. */
  503. ent.v.val.val = (uint64_t)_upb_msg_new(entry->submsgs[0], d->arena);
  504. }
  505. decode_tosubmsg(d, &ent.k, layout, field, val.str_val);
  506. /* Insert into map. */
  507. _upb_map_set(map, &ent.k, map->key_size, &ent.v, map->val_size, d->arena);
  508. }
  509. static const char *decode_tomsg(upb_decstate *d, const char *ptr, upb_msg *msg,
  510. const upb_msglayout *layout,
  511. const upb_msglayout_field *field, wireval val,
  512. int op) {
  513. void *mem = UPB_PTR_AT(msg, field->offset, void);
  514. int type = field->descriptortype;
  515. /* Set presence if necessary. */
  516. if (field->presence < 0) {
  517. /* Oneof case */
  518. *UPB_PTR_AT(msg, -field->presence, int32_t) = field->number;
  519. } else if (field->presence > 0) {
  520. /* Hasbit */
  521. uint32_t hasbit = field->presence;
  522. *UPB_PTR_AT(msg, hasbit / 8, uint8_t) |= (1 << (hasbit % 8));
  523. }
  524. /* Store into message. */
  525. switch (op) {
  526. case OP_SUBMSG: {
  527. upb_msg **submsgp = mem;
  528. upb_msg *submsg = *submsgp;
  529. if (!submsg) {
  530. submsg = decode_newsubmsg(d, layout, field);
  531. *submsgp = submsg;
  532. }
  533. if (UPB_UNLIKELY(type == UPB_DTYPE_GROUP)) {
  534. ptr = decode_togroup(d, ptr, submsg, layout, field);
  535. } else {
  536. decode_tosubmsg(d, submsg, layout, field, val.str_val);
  537. }
  538. break;
  539. }
  540. case OP_STRING:
  541. memcpy(mem, &val, sizeof(upb_strview));
  542. break;
  543. case OP_SCALAR_LG2(3):
  544. memcpy(mem, &val, 8);
  545. break;
  546. case OP_SCALAR_LG2(2):
  547. memcpy(mem, &val, 4);
  548. break;
  549. case OP_SCALAR_LG2(0):
  550. memcpy(mem, &val, 1);
  551. break;
  552. default:
  553. UPB_UNREACHABLE();
  554. }
  555. return ptr;
  556. }
  557. static const char *decode_msg(upb_decstate *d, const char *ptr, upb_msg *msg,
  558. const upb_msglayout *layout) {
  559. while (ptr < d->limit) {
  560. uint32_t tag;
  561. const upb_msglayout_field *field;
  562. int field_number;
  563. int wire_type;
  564. const char *field_start = ptr;
  565. wireval val;
  566. int op;
  567. ptr = decode_varint32(d, ptr, d->limit, &tag);
  568. field_number = tag >> 3;
  569. wire_type = tag & 7;
  570. field = upb_find_field(layout, field_number);
  571. switch (wire_type) {
  572. case UPB_WIRE_TYPE_VARINT:
  573. ptr = decode_varint64(d, ptr, d->limit, &val.uint64_val);
  574. op = varint_ops[field->descriptortype];
  575. decode_munge(field->descriptortype, &val);
  576. break;
  577. case UPB_WIRE_TYPE_32BIT:
  578. if (d->limit - ptr < 4) decode_err(d);
  579. memcpy(&val, ptr, 4);
  580. ptr += 4;
  581. op = OP_SCALAR_LG2(2);
  582. if (((1 << field->descriptortype) & fixed32_ok) == 0) goto unknown;
  583. break;
  584. case UPB_WIRE_TYPE_64BIT:
  585. if (d->limit - ptr < 8) decode_err(d);
  586. memcpy(&val, ptr, 8);
  587. ptr += 8;
  588. op = OP_SCALAR_LG2(3);
  589. if (((1 << field->descriptortype) & fixed64_ok) == 0) goto unknown;
  590. break;
  591. case UPB_WIRE_TYPE_DELIMITED: {
  592. uint32_t size;
  593. int ndx = field->descriptortype;
  594. if (_upb_isrepeated(field)) ndx += 18;
  595. ptr = decode_varint32(d, ptr, d->limit, &size);
  596. if (size >= INT32_MAX || (size_t)(d->limit - ptr) < size) {
  597. decode_err(d); /* Length overflow. */
  598. }
  599. val.str_val.data = ptr;
  600. val.str_val.size = size;
  601. ptr += size;
  602. op = delim_ops[ndx];
  603. break;
  604. }
  605. case UPB_WIRE_TYPE_START_GROUP:
  606. val.int32_val = field_number;
  607. op = OP_SUBMSG;
  608. if (field->descriptortype != UPB_DTYPE_GROUP) goto unknown;
  609. break;
  610. case UPB_WIRE_TYPE_END_GROUP:
  611. d->end_group = field_number;
  612. return ptr;
  613. default:
  614. decode_err(d);
  615. }
  616. if (op >= 0) {
  617. /* Parse, using op for dispatch. */
  618. switch (field->label) {
  619. case UPB_LABEL_REPEATED:
  620. case _UPB_LABEL_PACKED:
  621. ptr = decode_toarray(d, ptr, msg, layout, field, val, op);
  622. break;
  623. case _UPB_LABEL_MAP:
  624. decode_tomap(d, msg, layout, field, val);
  625. break;
  626. default:
  627. ptr = decode_tomsg(d, ptr, msg, layout, field, val, op);
  628. break;
  629. }
  630. } else {
  631. unknown:
  632. /* Skip unknown field. */
  633. if (field_number == 0) decode_err(d);
  634. if (wire_type == UPB_WIRE_TYPE_START_GROUP) {
  635. ptr = decode_group(d, ptr, NULL, NULL, field_number);
  636. }
  637. if (msg) {
  638. if (!_upb_msg_addunknown(msg, field_start, ptr - field_start,
  639. d->arena)) {
  640. decode_err(d);
  641. }
  642. }
  643. }
  644. }
  645. if (ptr != d->limit) decode_err(d);
  646. return ptr;
  647. }
  648. bool upb_decode(const char *buf, size_t size, void *msg, const upb_msglayout *l,
  649. upb_arena *arena) {
  650. upb_decstate state;
  651. state.limit = buf + size;
  652. state.arena = arena;
  653. state.depth = 64;
  654. state.end_group = 0;
  655. if (setjmp(state.err)) return false;
  656. if (size == 0) return true;
  657. decode_msg(&state, buf, msg, l);
  658. return state.end_group == 0;
  659. }
  660. #undef OP_SCALAR_LG2
  661. #undef OP_FIXPCK_LG2
  662. #undef OP_VARPCK_LG2
  663. #undef OP_STRING
  664. #undef OP_SUBMSG
  665. /* We encode backwards, to avoid pre-computing lengths (one-pass encode). */
  666. #include <string.h>
  667. #define UPB_PB_VARINT_MAX_LEN 10
  668. #define CHK(x) do { if (!(x)) { return false; } } while(0)
  669. static size_t upb_encode_varint(uint64_t val, char *buf) {
  670. size_t i;
  671. if (val < 128) { buf[0] = val; return 1; }
  672. i = 0;
  673. while (val) {
  674. uint8_t byte = val & 0x7fU;
  675. val >>= 7;
  676. if (val) byte |= 0x80U;
  677. buf[i++] = byte;
  678. }
  679. return i;
  680. }
  681. static uint32_t upb_zzencode_32(int32_t n) { return ((uint32_t)n << 1) ^ (n >> 31); }
  682. static uint64_t upb_zzencode_64(int64_t n) { return ((uint64_t)n << 1) ^ (n >> 63); }
  683. typedef struct {
  684. upb_alloc *alloc;
  685. char *buf, *ptr, *limit;
  686. } upb_encstate;
  687. static size_t upb_roundup_pow2(size_t bytes) {
  688. size_t ret = 128;
  689. while (ret < bytes) {
  690. ret *= 2;
  691. }
  692. return ret;
  693. }
  694. static bool upb_encode_growbuffer(upb_encstate *e, size_t bytes) {
  695. size_t old_size = e->limit - e->buf;
  696. size_t new_size = upb_roundup_pow2(bytes + (e->limit - e->ptr));
  697. char *new_buf = upb_realloc(e->alloc, e->buf, old_size, new_size);
  698. CHK(new_buf);
  699. /* We want previous data at the end, realloc() put it at the beginning. */
  700. if (old_size > 0) {
  701. memmove(new_buf + new_size - old_size, e->buf, old_size);
  702. }
  703. e->ptr = new_buf + new_size - (e->limit - e->ptr);
  704. e->limit = new_buf + new_size;
  705. e->buf = new_buf;
  706. return true;
  707. }
  708. /* Call to ensure that at least "bytes" bytes are available for writing at
  709. * e->ptr. Returns false if the bytes could not be allocated. */
  710. static bool upb_encode_reserve(upb_encstate *e, size_t bytes) {
  711. CHK(UPB_LIKELY((size_t)(e->ptr - e->buf) >= bytes) ||
  712. upb_encode_growbuffer(e, bytes));
  713. e->ptr -= bytes;
  714. return true;
  715. }
  716. /* Writes the given bytes to the buffer, handling reserve/advance. */
  717. static bool upb_put_bytes(upb_encstate *e, const void *data, size_t len) {
  718. if (len == 0) return true;
  719. CHK(upb_encode_reserve(e, len));
  720. memcpy(e->ptr, data, len);
  721. return true;
  722. }
  723. static bool upb_put_fixed64(upb_encstate *e, uint64_t val) {
  724. /* TODO(haberman): byte-swap for big endian. */
  725. return upb_put_bytes(e, &val, sizeof(uint64_t));
  726. }
  727. static bool upb_put_fixed32(upb_encstate *e, uint32_t val) {
  728. /* TODO(haberman): byte-swap for big endian. */
  729. return upb_put_bytes(e, &val, sizeof(uint32_t));
  730. }
  731. static bool upb_put_varint(upb_encstate *e, uint64_t val) {
  732. size_t len;
  733. char *start;
  734. CHK(upb_encode_reserve(e, UPB_PB_VARINT_MAX_LEN));
  735. len = upb_encode_varint(val, e->ptr);
  736. start = e->ptr + UPB_PB_VARINT_MAX_LEN - len;
  737. memmove(start, e->ptr, len);
  738. e->ptr = start;
  739. return true;
  740. }
  741. static bool upb_put_double(upb_encstate *e, double d) {
  742. uint64_t u64;
  743. UPB_ASSERT(sizeof(double) == sizeof(uint64_t));
  744. memcpy(&u64, &d, sizeof(uint64_t));
  745. return upb_put_fixed64(e, u64);
  746. }
  747. static bool upb_put_float(upb_encstate *e, float d) {
  748. uint32_t u32;
  749. UPB_ASSERT(sizeof(float) == sizeof(uint32_t));
  750. memcpy(&u32, &d, sizeof(uint32_t));
  751. return upb_put_fixed32(e, u32);
  752. }
  753. static uint32_t upb_readcase(const char *msg, const upb_msglayout_field *f) {
  754. uint32_t ret;
  755. memcpy(&ret, msg - f->presence, sizeof(ret));
  756. return ret;
  757. }
  758. static bool upb_readhasbit(const char *msg, const upb_msglayout_field *f) {
  759. uint32_t hasbit = f->presence;
  760. UPB_ASSERT(f->presence > 0);
  761. return (*UPB_PTR_AT(msg, hasbit / 8, uint8_t)) & (1 << (hasbit % 8));
  762. }
  763. static bool upb_put_tag(upb_encstate *e, int field_number, int wire_type) {
  764. return upb_put_varint(e, (field_number << 3) | wire_type);
  765. }
  766. static bool upb_put_fixedarray(upb_encstate *e, const upb_array *arr,
  767. size_t elem_size, uint32_t tag) {
  768. size_t bytes = arr->len * elem_size;
  769. const char* data = _upb_array_constptr(arr);
  770. const char* ptr = data + bytes - elem_size;
  771. if (tag) {
  772. while (true) {
  773. CHK(upb_put_bytes(e, ptr, elem_size) && upb_put_varint(e, tag));
  774. if (ptr == data) break;
  775. ptr -= elem_size;
  776. }
  777. return true;
  778. } else {
  779. return upb_put_bytes(e, data, bytes) && upb_put_varint(e, bytes);
  780. }
  781. }
  782. bool upb_encode_message(upb_encstate *e, const char *msg,
  783. const upb_msglayout *m, size_t *size);
  784. static bool upb_encode_scalarfield(upb_encstate *e, const void *_field_mem,
  785. const upb_msglayout *m,
  786. const upb_msglayout_field *f,
  787. bool skip_zero_value) {
  788. const char *field_mem = _field_mem;
  789. #define CASE(ctype, type, wire_type, encodeval) do { \
  790. ctype val = *(ctype*)field_mem; \
  791. if (skip_zero_value && val == 0) { \
  792. return true; \
  793. } \
  794. return upb_put_ ## type(e, encodeval) && \
  795. upb_put_tag(e, f->number, wire_type); \
  796. } while(0)
  797. switch (f->descriptortype) {
  798. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  799. CASE(double, double, UPB_WIRE_TYPE_64BIT, val);
  800. case UPB_DESCRIPTOR_TYPE_FLOAT:
  801. CASE(float, float, UPB_WIRE_TYPE_32BIT, val);
  802. case UPB_DESCRIPTOR_TYPE_INT64:
  803. case UPB_DESCRIPTOR_TYPE_UINT64:
  804. CASE(uint64_t, varint, UPB_WIRE_TYPE_VARINT, val);
  805. case UPB_DESCRIPTOR_TYPE_UINT32:
  806. CASE(uint32_t, varint, UPB_WIRE_TYPE_VARINT, val);
  807. case UPB_DESCRIPTOR_TYPE_INT32:
  808. case UPB_DESCRIPTOR_TYPE_ENUM:
  809. CASE(int32_t, varint, UPB_WIRE_TYPE_VARINT, (int64_t)val);
  810. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  811. case UPB_DESCRIPTOR_TYPE_FIXED64:
  812. CASE(uint64_t, fixed64, UPB_WIRE_TYPE_64BIT, val);
  813. case UPB_DESCRIPTOR_TYPE_FIXED32:
  814. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  815. CASE(uint32_t, fixed32, UPB_WIRE_TYPE_32BIT, val);
  816. case UPB_DESCRIPTOR_TYPE_BOOL:
  817. CASE(bool, varint, UPB_WIRE_TYPE_VARINT, val);
  818. case UPB_DESCRIPTOR_TYPE_SINT32:
  819. CASE(int32_t, varint, UPB_WIRE_TYPE_VARINT, upb_zzencode_32(val));
  820. case UPB_DESCRIPTOR_TYPE_SINT64:
  821. CASE(int64_t, varint, UPB_WIRE_TYPE_VARINT, upb_zzencode_64(val));
  822. case UPB_DESCRIPTOR_TYPE_STRING:
  823. case UPB_DESCRIPTOR_TYPE_BYTES: {
  824. upb_strview view = *(upb_strview*)field_mem;
  825. if (skip_zero_value && view.size == 0) {
  826. return true;
  827. }
  828. return upb_put_bytes(e, view.data, view.size) &&
  829. upb_put_varint(e, view.size) &&
  830. upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED);
  831. }
  832. case UPB_DESCRIPTOR_TYPE_GROUP: {
  833. size_t size;
  834. void *submsg = *(void **)field_mem;
  835. const upb_msglayout *subm = m->submsgs[f->submsg_index];
  836. if (submsg == NULL) {
  837. return true;
  838. }
  839. return upb_put_tag(e, f->number, UPB_WIRE_TYPE_END_GROUP) &&
  840. upb_encode_message(e, submsg, subm, &size) &&
  841. upb_put_tag(e, f->number, UPB_WIRE_TYPE_START_GROUP);
  842. }
  843. case UPB_DESCRIPTOR_TYPE_MESSAGE: {
  844. size_t size;
  845. void *submsg = *(void **)field_mem;
  846. const upb_msglayout *subm = m->submsgs[f->submsg_index];
  847. if (submsg == NULL) {
  848. return true;
  849. }
  850. return upb_encode_message(e, submsg, subm, &size) &&
  851. upb_put_varint(e, size) &&
  852. upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED);
  853. }
  854. }
  855. #undef CASE
  856. UPB_UNREACHABLE();
  857. }
  858. static bool upb_encode_array(upb_encstate *e, const char *field_mem,
  859. const upb_msglayout *m,
  860. const upb_msglayout_field *f) {
  861. const upb_array *arr = *(const upb_array**)field_mem;
  862. bool packed = f->label == _UPB_LABEL_PACKED;
  863. if (arr == NULL || arr->len == 0) {
  864. return true;
  865. }
  866. #define VARINT_CASE(ctype, encode) \
  867. { \
  868. const ctype *start = _upb_array_constptr(arr); \
  869. const ctype *ptr = start + arr->len; \
  870. size_t pre_len = e->limit - e->ptr; \
  871. uint32_t tag = packed ? 0 : (f->number << 3) | UPB_WIRE_TYPE_VARINT; \
  872. do { \
  873. ptr--; \
  874. CHK(upb_put_varint(e, encode)); \
  875. if (tag) CHK(upb_put_varint(e, tag)); \
  876. } while (ptr != start); \
  877. if (!tag) CHK(upb_put_varint(e, e->limit - e->ptr - pre_len)); \
  878. } \
  879. break; \
  880. do { \
  881. ; \
  882. } while (0)
  883. #define TAG(wire_type) (packed ? 0 : (f->number << 3 | wire_type))
  884. switch (f->descriptortype) {
  885. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  886. CHK(upb_put_fixedarray(e, arr, sizeof(double), TAG(UPB_WIRE_TYPE_64BIT)));
  887. break;
  888. case UPB_DESCRIPTOR_TYPE_FLOAT:
  889. CHK(upb_put_fixedarray(e, arr, sizeof(float), TAG(UPB_WIRE_TYPE_32BIT)));
  890. break;
  891. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  892. case UPB_DESCRIPTOR_TYPE_FIXED64:
  893. CHK(upb_put_fixedarray(e, arr, sizeof(uint64_t), TAG(UPB_WIRE_TYPE_64BIT)));
  894. break;
  895. case UPB_DESCRIPTOR_TYPE_FIXED32:
  896. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  897. CHK(upb_put_fixedarray(e, arr, sizeof(uint32_t), TAG(UPB_WIRE_TYPE_32BIT)));
  898. break;
  899. case UPB_DESCRIPTOR_TYPE_INT64:
  900. case UPB_DESCRIPTOR_TYPE_UINT64:
  901. VARINT_CASE(uint64_t, *ptr);
  902. case UPB_DESCRIPTOR_TYPE_UINT32:
  903. VARINT_CASE(uint32_t, *ptr);
  904. case UPB_DESCRIPTOR_TYPE_INT32:
  905. case UPB_DESCRIPTOR_TYPE_ENUM:
  906. VARINT_CASE(int32_t, (int64_t)*ptr);
  907. case UPB_DESCRIPTOR_TYPE_BOOL:
  908. VARINT_CASE(bool, *ptr);
  909. case UPB_DESCRIPTOR_TYPE_SINT32:
  910. VARINT_CASE(int32_t, upb_zzencode_32(*ptr));
  911. case UPB_DESCRIPTOR_TYPE_SINT64:
  912. VARINT_CASE(int64_t, upb_zzencode_64(*ptr));
  913. case UPB_DESCRIPTOR_TYPE_STRING:
  914. case UPB_DESCRIPTOR_TYPE_BYTES: {
  915. const upb_strview *start = _upb_array_constptr(arr);
  916. const upb_strview *ptr = start + arr->len;
  917. do {
  918. ptr--;
  919. CHK(upb_put_bytes(e, ptr->data, ptr->size) &&
  920. upb_put_varint(e, ptr->size) &&
  921. upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
  922. } while (ptr != start);
  923. return true;
  924. }
  925. case UPB_DESCRIPTOR_TYPE_GROUP: {
  926. const void *const*start = _upb_array_constptr(arr);
  927. const void *const*ptr = start + arr->len;
  928. const upb_msglayout *subm = m->submsgs[f->submsg_index];
  929. do {
  930. size_t size;
  931. ptr--;
  932. CHK(upb_put_tag(e, f->number, UPB_WIRE_TYPE_END_GROUP) &&
  933. upb_encode_message(e, *ptr, subm, &size) &&
  934. upb_put_tag(e, f->number, UPB_WIRE_TYPE_START_GROUP));
  935. } while (ptr != start);
  936. return true;
  937. }
  938. case UPB_DESCRIPTOR_TYPE_MESSAGE: {
  939. const void *const*start = _upb_array_constptr(arr);
  940. const void *const*ptr = start + arr->len;
  941. const upb_msglayout *subm = m->submsgs[f->submsg_index];
  942. do {
  943. size_t size;
  944. ptr--;
  945. CHK(upb_encode_message(e, *ptr, subm, &size) &&
  946. upb_put_varint(e, size) &&
  947. upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
  948. } while (ptr != start);
  949. return true;
  950. }
  951. }
  952. #undef VARINT_CASE
  953. if (packed) {
  954. CHK(upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
  955. }
  956. return true;
  957. }
  958. static bool upb_encode_map(upb_encstate *e, const char *field_mem,
  959. const upb_msglayout *m,
  960. const upb_msglayout_field *f) {
  961. const upb_map *map = *(const upb_map**)field_mem;
  962. const upb_msglayout *entry = m->submsgs[f->submsg_index];
  963. const upb_msglayout_field *key_field = &entry->fields[0];
  964. const upb_msglayout_field *val_field = &entry->fields[1];
  965. upb_strtable_iter i;
  966. if (map == NULL) {
  967. return true;
  968. }
  969. upb_strtable_begin(&i, &map->table);
  970. for(; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  971. size_t pre_len = e->limit - e->ptr;
  972. size_t size;
  973. upb_strview key = upb_strtable_iter_key(&i);
  974. const upb_value val = upb_strtable_iter_value(&i);
  975. const void *keyp =
  976. map->key_size == UPB_MAPTYPE_STRING ? (void *)&key : key.data;
  977. const void *valp =
  978. map->val_size == UPB_MAPTYPE_STRING ? upb_value_getptr(val) : &val;
  979. CHK(upb_encode_scalarfield(e, valp, entry, val_field, false));
  980. CHK(upb_encode_scalarfield(e, keyp, entry, key_field, false));
  981. size = (e->limit - e->ptr) - pre_len;
  982. CHK(upb_put_varint(e, size));
  983. CHK(upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
  984. }
  985. return true;
  986. }
  987. bool upb_encode_message(upb_encstate *e, const char *msg,
  988. const upb_msglayout *m, size_t *size) {
  989. int i;
  990. size_t pre_len = e->limit - e->ptr;
  991. const char *unknown;
  992. size_t unknown_size;
  993. unknown = upb_msg_getunknown(msg, &unknown_size);
  994. if (unknown) {
  995. upb_put_bytes(e, unknown, unknown_size);
  996. }
  997. for (i = m->field_count - 1; i >= 0; i--) {
  998. const upb_msglayout_field *f = &m->fields[i];
  999. if (_upb_isrepeated(f)) {
  1000. CHK(upb_encode_array(e, msg + f->offset, m, f));
  1001. } else if (f->label == _UPB_LABEL_MAP) {
  1002. CHK(upb_encode_map(e, msg + f->offset, m, f));
  1003. } else {
  1004. bool skip_empty = false;
  1005. if (f->presence == 0) {
  1006. /* Proto3 presence. */
  1007. skip_empty = true;
  1008. } else if (f->presence > 0) {
  1009. /* Proto2 presence: hasbit. */
  1010. if (!upb_readhasbit(msg, f)) {
  1011. continue;
  1012. }
  1013. } else {
  1014. /* Field is in a oneof. */
  1015. if (upb_readcase(msg, f) != f->number) {
  1016. continue;
  1017. }
  1018. }
  1019. CHK(upb_encode_scalarfield(e, msg + f->offset, m, f, skip_empty));
  1020. }
  1021. }
  1022. *size = (e->limit - e->ptr) - pre_len;
  1023. return true;
  1024. }
  1025. char *upb_encode(const void *msg, const upb_msglayout *m, upb_arena *arena,
  1026. size_t *size) {
  1027. upb_encstate e;
  1028. e.alloc = upb_arena_alloc(arena);
  1029. e.buf = NULL;
  1030. e.limit = NULL;
  1031. e.ptr = NULL;
  1032. if (!upb_encode_message(&e, msg, m, size)) {
  1033. *size = 0;
  1034. return NULL;
  1035. }
  1036. *size = e.limit - e.ptr;
  1037. if (*size == 0) {
  1038. static char ch;
  1039. return &ch;
  1040. } else {
  1041. UPB_ASSERT(e.ptr);
  1042. return e.ptr;
  1043. }
  1044. }
  1045. #undef CHK
  1046. /** upb_msg *******************************************************************/
  1047. static const char _upb_fieldtype_to_sizelg2[12] = {
  1048. 0,
  1049. 0, /* UPB_TYPE_BOOL */
  1050. 2, /* UPB_TYPE_FLOAT */
  1051. 2, /* UPB_TYPE_INT32 */
  1052. 2, /* UPB_TYPE_UINT32 */
  1053. 2, /* UPB_TYPE_ENUM */
  1054. UPB_SIZE(2, 3), /* UPB_TYPE_MESSAGE */
  1055. 3, /* UPB_TYPE_DOUBLE */
  1056. 3, /* UPB_TYPE_INT64 */
  1057. 3, /* UPB_TYPE_UINT64 */
  1058. UPB_SIZE(3, 4), /* UPB_TYPE_STRING */
  1059. UPB_SIZE(3, 4), /* UPB_TYPE_BYTES */
  1060. };
  1061. static uintptr_t tag_arrptr(void* ptr, int elem_size_lg2) {
  1062. UPB_ASSERT(elem_size_lg2 <= 4);
  1063. return (uintptr_t)ptr | elem_size_lg2;
  1064. }
  1065. static int upb_msg_internalsize(const upb_msglayout *l) {
  1066. return sizeof(upb_msg_internal) - l->extendable * sizeof(void *);
  1067. }
  1068. static size_t upb_msg_sizeof(const upb_msglayout *l) {
  1069. return l->size + upb_msg_internalsize(l);
  1070. }
  1071. static upb_msg_internal *upb_msg_getinternal(upb_msg *msg) {
  1072. return UPB_PTR_AT(msg, -sizeof(upb_msg_internal), upb_msg_internal);
  1073. }
  1074. static const upb_msg_internal *upb_msg_getinternal_const(const upb_msg *msg) {
  1075. return UPB_PTR_AT(msg, -sizeof(upb_msg_internal), upb_msg_internal);
  1076. }
  1077. static upb_msg_internal_withext *upb_msg_getinternalwithext(
  1078. upb_msg *msg, const upb_msglayout *l) {
  1079. UPB_ASSERT(l->extendable);
  1080. return UPB_PTR_AT(msg, -sizeof(upb_msg_internal_withext),
  1081. upb_msg_internal_withext);
  1082. }
  1083. upb_msg *_upb_msg_new(const upb_msglayout *l, upb_arena *a) {
  1084. void *mem = upb_arena_malloc(a, upb_msg_sizeof(l));
  1085. upb_msg_internal *in;
  1086. upb_msg *msg;
  1087. if (!mem) {
  1088. return NULL;
  1089. }
  1090. msg = UPB_PTR_AT(mem, upb_msg_internalsize(l), upb_msg);
  1091. /* Initialize normal members. */
  1092. memset(msg, 0, l->size);
  1093. /* Initialize internal members. */
  1094. in = upb_msg_getinternal(msg);
  1095. in->unknown = NULL;
  1096. in->unknown_len = 0;
  1097. in->unknown_size = 0;
  1098. if (l->extendable) {
  1099. upb_msg_getinternalwithext(msg, l)->extdict = NULL;
  1100. }
  1101. return msg;
  1102. }
  1103. bool _upb_msg_addunknown(upb_msg *msg, const char *data, size_t len,
  1104. upb_arena *arena) {
  1105. upb_msg_internal *in = upb_msg_getinternal(msg);
  1106. if (len > in->unknown_size - in->unknown_len) {
  1107. upb_alloc *alloc = upb_arena_alloc(arena);
  1108. size_t need = in->unknown_size + len;
  1109. size_t newsize = UPB_MAX(in->unknown_size * 2, need);
  1110. void *mem = upb_realloc(alloc, in->unknown, in->unknown_size, newsize);
  1111. if (!mem) return false;
  1112. in->unknown = mem;
  1113. in->unknown_size = newsize;
  1114. }
  1115. memcpy(in->unknown + in->unknown_len, data, len);
  1116. in->unknown_len += len;
  1117. return true;
  1118. }
  1119. const char *upb_msg_getunknown(const upb_msg *msg, size_t *len) {
  1120. const upb_msg_internal *in = upb_msg_getinternal_const(msg);
  1121. *len = in->unknown_len;
  1122. return in->unknown;
  1123. }
  1124. /** upb_array *****************************************************************/
  1125. upb_array *_upb_array_new(upb_arena *a, upb_fieldtype_t type) {
  1126. upb_array *arr = upb_arena_malloc(a, sizeof(upb_array));
  1127. if (!arr) {
  1128. return NULL;
  1129. }
  1130. arr->data = tag_arrptr(NULL, _upb_fieldtype_to_sizelg2[type]);
  1131. arr->len = 0;
  1132. arr->size = 0;
  1133. return arr;
  1134. }
  1135. bool _upb_array_realloc(upb_array *arr, size_t min_size, upb_arena *arena) {
  1136. size_t new_size = UPB_MAX(arr->size, 4);
  1137. int elem_size_lg2 = arr->data & 7;
  1138. size_t old_bytes = arr->size << elem_size_lg2;
  1139. size_t new_bytes;
  1140. void* ptr = _upb_array_ptr(arr);
  1141. /* Log2 ceiling of size. */
  1142. while (new_size < min_size) new_size *= 2;
  1143. new_bytes = new_size << elem_size_lg2;
  1144. ptr = upb_arena_realloc(arena, ptr, old_bytes, new_bytes);
  1145. if (!ptr) {
  1146. return false;
  1147. }
  1148. arr->data = tag_arrptr(ptr, elem_size_lg2);
  1149. arr->size = new_size;
  1150. return true;
  1151. }
  1152. static upb_array *getorcreate_array(upb_array **arr_ptr, upb_fieldtype_t type,
  1153. upb_arena *arena) {
  1154. upb_array *arr = *arr_ptr;
  1155. if (!arr) {
  1156. arr = _upb_array_new(arena, type);
  1157. if (!arr) return NULL;
  1158. *arr_ptr = arr;
  1159. }
  1160. return arr;
  1161. }
  1162. static bool resize_array(upb_array *arr, size_t size, upb_arena *arena) {
  1163. if (size > arr->size && !_upb_array_realloc(arr, size, arena)) {
  1164. return false;
  1165. }
  1166. arr->len = size;
  1167. return true;
  1168. }
  1169. void *_upb_array_resize_fallback(upb_array **arr_ptr, size_t size,
  1170. upb_fieldtype_t type, upb_arena *arena) {
  1171. upb_array *arr = getorcreate_array(arr_ptr, type, arena);
  1172. return arr && resize_array(arr, size, arena) ? _upb_array_ptr(arr) : NULL;
  1173. }
  1174. bool _upb_array_append_fallback(upb_array **arr_ptr, const void *value,
  1175. upb_fieldtype_t type, upb_arena *arena) {
  1176. upb_array *arr = getorcreate_array(arr_ptr, type, arena);
  1177. size_t elem = arr->len;
  1178. int lg2 = _upb_fieldtype_to_sizelg2[type];
  1179. char *data;
  1180. if (!arr || !resize_array(arr, elem + 1, arena)) return false;
  1181. data = _upb_array_ptr(arr);
  1182. memcpy(data + (elem << lg2), value, 1 << lg2);
  1183. return true;
  1184. }
  1185. /** upb_map *******************************************************************/
  1186. upb_map *_upb_map_new(upb_arena *a, size_t key_size, size_t value_size) {
  1187. upb_map *map = upb_arena_malloc(a, sizeof(upb_map));
  1188. if (!map) {
  1189. return NULL;
  1190. }
  1191. upb_strtable_init2(&map->table, UPB_CTYPE_INT32, upb_arena_alloc(a));
  1192. map->key_size = key_size;
  1193. map->val_size = value_size;
  1194. return map;
  1195. }
  1196. /*
  1197. ** upb_table Implementation
  1198. **
  1199. ** Implementation is heavily inspired by Lua's ltable.c.
  1200. */
  1201. #include <string.h>
  1202. #define UPB_MAXARRSIZE 16 /* 64k. */
  1203. /* From Chromium. */
  1204. #define ARRAY_SIZE(x) \
  1205. ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x])))))
  1206. static const double MAX_LOAD = 0.85;
  1207. /* The minimum utilization of the array part of a mixed hash/array table. This
  1208. * is a speed/memory-usage tradeoff (though it's not straightforward because of
  1209. * cache effects). The lower this is, the more memory we'll use. */
  1210. static const double MIN_DENSITY = 0.1;
  1211. bool is_pow2(uint64_t v) { return v == 0 || (v & (v - 1)) == 0; }
  1212. int log2ceil(uint64_t v) {
  1213. int ret = 0;
  1214. bool pow2 = is_pow2(v);
  1215. while (v >>= 1) ret++;
  1216. ret = pow2 ? ret : ret + 1; /* Ceiling. */
  1217. return UPB_MIN(UPB_MAXARRSIZE, ret);
  1218. }
  1219. char *upb_strdup(const char *s, upb_alloc *a) {
  1220. return upb_strdup2(s, strlen(s), a);
  1221. }
  1222. char *upb_strdup2(const char *s, size_t len, upb_alloc *a) {
  1223. size_t n;
  1224. char *p;
  1225. /* Prevent overflow errors. */
  1226. if (len == SIZE_MAX) return NULL;
  1227. /* Always null-terminate, even if binary data; but don't rely on the input to
  1228. * have a null-terminating byte since it may be a raw binary buffer. */
  1229. n = len + 1;
  1230. p = upb_malloc(a, n);
  1231. if (p) {
  1232. memcpy(p, s, len);
  1233. p[len] = 0;
  1234. }
  1235. return p;
  1236. }
  1237. /* A type to represent the lookup key of either a strtable or an inttable. */
  1238. typedef union {
  1239. uintptr_t num;
  1240. struct {
  1241. const char *str;
  1242. size_t len;
  1243. } str;
  1244. } lookupkey_t;
  1245. static lookupkey_t strkey2(const char *str, size_t len) {
  1246. lookupkey_t k;
  1247. k.str.str = str;
  1248. k.str.len = len;
  1249. return k;
  1250. }
  1251. static lookupkey_t intkey(uintptr_t key) {
  1252. lookupkey_t k;
  1253. k.num = key;
  1254. return k;
  1255. }
  1256. typedef uint32_t hashfunc_t(upb_tabkey key);
  1257. typedef bool eqlfunc_t(upb_tabkey k1, lookupkey_t k2);
  1258. /* Base table (shared code) ***************************************************/
  1259. /* For when we need to cast away const. */
  1260. static upb_tabent *mutable_entries(upb_table *t) {
  1261. return (upb_tabent*)t->entries;
  1262. }
  1263. static bool isfull(upb_table *t) {
  1264. if (upb_table_size(t) == 0) {
  1265. return true;
  1266. } else {
  1267. return ((double)(t->count + 1) / upb_table_size(t)) > MAX_LOAD;
  1268. }
  1269. }
  1270. static bool init(upb_table *t, uint8_t size_lg2, upb_alloc *a) {
  1271. size_t bytes;
  1272. t->count = 0;
  1273. t->size_lg2 = size_lg2;
  1274. t->mask = upb_table_size(t) ? upb_table_size(t) - 1 : 0;
  1275. bytes = upb_table_size(t) * sizeof(upb_tabent);
  1276. if (bytes > 0) {
  1277. t->entries = upb_malloc(a, bytes);
  1278. if (!t->entries) return false;
  1279. memset(mutable_entries(t), 0, bytes);
  1280. } else {
  1281. t->entries = NULL;
  1282. }
  1283. return true;
  1284. }
  1285. static void uninit(upb_table *t, upb_alloc *a) {
  1286. upb_free(a, mutable_entries(t));
  1287. }
  1288. static upb_tabent *emptyent(upb_table *t) {
  1289. upb_tabent *e = mutable_entries(t) + upb_table_size(t);
  1290. while (1) { if (upb_tabent_isempty(--e)) return e; UPB_ASSERT(e > t->entries); }
  1291. }
  1292. static upb_tabent *getentry_mutable(upb_table *t, uint32_t hash) {
  1293. return (upb_tabent*)upb_getentry(t, hash);
  1294. }
  1295. static const upb_tabent *findentry(const upb_table *t, lookupkey_t key,
  1296. uint32_t hash, eqlfunc_t *eql) {
  1297. const upb_tabent *e;
  1298. if (t->size_lg2 == 0) return NULL;
  1299. e = upb_getentry(t, hash);
  1300. if (upb_tabent_isempty(e)) return NULL;
  1301. while (1) {
  1302. if (eql(e->key, key)) return e;
  1303. if ((e = e->next) == NULL) return NULL;
  1304. }
  1305. }
  1306. static upb_tabent *findentry_mutable(upb_table *t, lookupkey_t key,
  1307. uint32_t hash, eqlfunc_t *eql) {
  1308. return (upb_tabent*)findentry(t, key, hash, eql);
  1309. }
  1310. static bool lookup(const upb_table *t, lookupkey_t key, upb_value *v,
  1311. uint32_t hash, eqlfunc_t *eql) {
  1312. const upb_tabent *e = findentry(t, key, hash, eql);
  1313. if (e) {
  1314. if (v) {
  1315. _upb_value_setval(v, e->val.val);
  1316. }
  1317. return true;
  1318. } else {
  1319. return false;
  1320. }
  1321. }
  1322. /* The given key must not already exist in the table. */
  1323. static void insert(upb_table *t, lookupkey_t key, upb_tabkey tabkey,
  1324. upb_value val, uint32_t hash,
  1325. hashfunc_t *hashfunc, eqlfunc_t *eql) {
  1326. upb_tabent *mainpos_e;
  1327. upb_tabent *our_e;
  1328. UPB_ASSERT(findentry(t, key, hash, eql) == NULL);
  1329. t->count++;
  1330. mainpos_e = getentry_mutable(t, hash);
  1331. our_e = mainpos_e;
  1332. if (upb_tabent_isempty(mainpos_e)) {
  1333. /* Our main position is empty; use it. */
  1334. our_e->next = NULL;
  1335. } else {
  1336. /* Collision. */
  1337. upb_tabent *new_e = emptyent(t);
  1338. /* Head of collider's chain. */
  1339. upb_tabent *chain = getentry_mutable(t, hashfunc(mainpos_e->key));
  1340. if (chain == mainpos_e) {
  1341. /* Existing ent is in its main posisiton (it has the same hash as us, and
  1342. * is the head of our chain). Insert to new ent and append to this chain. */
  1343. new_e->next = mainpos_e->next;
  1344. mainpos_e->next = new_e;
  1345. our_e = new_e;
  1346. } else {
  1347. /* Existing ent is not in its main position (it is a node in some other
  1348. * chain). This implies that no existing ent in the table has our hash.
  1349. * Evict it (updating its chain) and use its ent for head of our chain. */
  1350. *new_e = *mainpos_e; /* copies next. */
  1351. while (chain->next != mainpos_e) {
  1352. chain = (upb_tabent*)chain->next;
  1353. UPB_ASSERT(chain);
  1354. }
  1355. chain->next = new_e;
  1356. our_e = mainpos_e;
  1357. our_e->next = NULL;
  1358. }
  1359. }
  1360. our_e->key = tabkey;
  1361. our_e->val.val = val.val;
  1362. UPB_ASSERT(findentry(t, key, hash, eql) == our_e);
  1363. }
  1364. static bool rm(upb_table *t, lookupkey_t key, upb_value *val,
  1365. upb_tabkey *removed, uint32_t hash, eqlfunc_t *eql) {
  1366. upb_tabent *chain = getentry_mutable(t, hash);
  1367. if (upb_tabent_isempty(chain)) return false;
  1368. if (eql(chain->key, key)) {
  1369. /* Element to remove is at the head of its chain. */
  1370. t->count--;
  1371. if (val) _upb_value_setval(val, chain->val.val);
  1372. if (removed) *removed = chain->key;
  1373. if (chain->next) {
  1374. upb_tabent *move = (upb_tabent*)chain->next;
  1375. *chain = *move;
  1376. move->key = 0; /* Make the slot empty. */
  1377. } else {
  1378. chain->key = 0; /* Make the slot empty. */
  1379. }
  1380. return true;
  1381. } else {
  1382. /* Element to remove is either in a non-head position or not in the
  1383. * table. */
  1384. while (chain->next && !eql(chain->next->key, key)) {
  1385. chain = (upb_tabent*)chain->next;
  1386. }
  1387. if (chain->next) {
  1388. /* Found element to remove. */
  1389. upb_tabent *rm = (upb_tabent*)chain->next;
  1390. t->count--;
  1391. if (val) _upb_value_setval(val, chain->next->val.val);
  1392. if (removed) *removed = rm->key;
  1393. rm->key = 0; /* Make the slot empty. */
  1394. chain->next = rm->next;
  1395. return true;
  1396. } else {
  1397. /* Element to remove is not in the table. */
  1398. return false;
  1399. }
  1400. }
  1401. }
  1402. static size_t next(const upb_table *t, size_t i) {
  1403. do {
  1404. if (++i >= upb_table_size(t))
  1405. return SIZE_MAX;
  1406. } while(upb_tabent_isempty(&t->entries[i]));
  1407. return i;
  1408. }
  1409. static size_t begin(const upb_table *t) {
  1410. return next(t, -1);
  1411. }
  1412. /* upb_strtable ***************************************************************/
  1413. /* A simple "subclass" of upb_table that only adds a hash function for strings. */
  1414. static upb_tabkey strcopy(lookupkey_t k2, upb_alloc *a) {
  1415. uint32_t len = (uint32_t) k2.str.len;
  1416. char *str = upb_malloc(a, k2.str.len + sizeof(uint32_t) + 1);
  1417. if (str == NULL) return 0;
  1418. memcpy(str, &len, sizeof(uint32_t));
  1419. memcpy(str + sizeof(uint32_t), k2.str.str, k2.str.len);
  1420. str[sizeof(uint32_t) + k2.str.len] = '\0';
  1421. return (uintptr_t)str;
  1422. }
  1423. static uint32_t strhash(upb_tabkey key) {
  1424. uint32_t len;
  1425. char *str = upb_tabstr(key, &len);
  1426. return upb_murmur_hash2(str, len, 0);
  1427. }
  1428. static bool streql(upb_tabkey k1, lookupkey_t k2) {
  1429. uint32_t len;
  1430. char *str = upb_tabstr(k1, &len);
  1431. return len == k2.str.len && memcmp(str, k2.str.str, len) == 0;
  1432. }
  1433. bool upb_strtable_init2(upb_strtable *t, upb_ctype_t ctype, upb_alloc *a) {
  1434. return init(&t->t, 2, a);
  1435. }
  1436. void upb_strtable_clear(upb_strtable *t) {
  1437. size_t bytes = upb_table_size(&t->t) * sizeof(upb_tabent);
  1438. t->t.count = 0;
  1439. memset((char*)t->t.entries, 0, bytes);
  1440. }
  1441. void upb_strtable_uninit2(upb_strtable *t, upb_alloc *a) {
  1442. size_t i;
  1443. for (i = 0; i < upb_table_size(&t->t); i++)
  1444. upb_free(a, (void*)t->t.entries[i].key);
  1445. uninit(&t->t, a);
  1446. }
  1447. bool upb_strtable_resize(upb_strtable *t, size_t size_lg2, upb_alloc *a) {
  1448. upb_strtable new_table;
  1449. upb_strtable_iter i;
  1450. if (!init(&new_table.t, size_lg2, a))
  1451. return false;
  1452. upb_strtable_begin(&i, t);
  1453. for ( ; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  1454. upb_strview key = upb_strtable_iter_key(&i);
  1455. upb_strtable_insert3(
  1456. &new_table, key.data, key.size,
  1457. upb_strtable_iter_value(&i), a);
  1458. }
  1459. upb_strtable_uninit2(t, a);
  1460. *t = new_table;
  1461. return true;
  1462. }
  1463. bool upb_strtable_insert3(upb_strtable *t, const char *k, size_t len,
  1464. upb_value v, upb_alloc *a) {
  1465. lookupkey_t key;
  1466. upb_tabkey tabkey;
  1467. uint32_t hash;
  1468. if (isfull(&t->t)) {
  1469. /* Need to resize. New table of double the size, add old elements to it. */
  1470. if (!upb_strtable_resize(t, t->t.size_lg2 + 1, a)) {
  1471. return false;
  1472. }
  1473. }
  1474. key = strkey2(k, len);
  1475. tabkey = strcopy(key, a);
  1476. if (tabkey == 0) return false;
  1477. hash = upb_murmur_hash2(key.str.str, key.str.len, 0);
  1478. insert(&t->t, key, tabkey, v, hash, &strhash, &streql);
  1479. return true;
  1480. }
  1481. bool upb_strtable_lookup2(const upb_strtable *t, const char *key, size_t len,
  1482. upb_value *v) {
  1483. uint32_t hash = upb_murmur_hash2(key, len, 0);
  1484. return lookup(&t->t, strkey2(key, len), v, hash, &streql);
  1485. }
  1486. bool upb_strtable_remove3(upb_strtable *t, const char *key, size_t len,
  1487. upb_value *val, upb_alloc *alloc) {
  1488. uint32_t hash = upb_murmur_hash2(key, len, 0);
  1489. upb_tabkey tabkey;
  1490. if (rm(&t->t, strkey2(key, len), val, &tabkey, hash, &streql)) {
  1491. if (alloc) {
  1492. /* Arena-based allocs don't need to free and won't pass this. */
  1493. upb_free(alloc, (void*)tabkey);
  1494. }
  1495. return true;
  1496. } else {
  1497. return false;
  1498. }
  1499. }
  1500. /* Iteration */
  1501. void upb_strtable_begin(upb_strtable_iter *i, const upb_strtable *t) {
  1502. i->t = t;
  1503. i->index = begin(&t->t);
  1504. }
  1505. void upb_strtable_next(upb_strtable_iter *i) {
  1506. i->index = next(&i->t->t, i->index);
  1507. }
  1508. bool upb_strtable_done(const upb_strtable_iter *i) {
  1509. if (!i->t) return true;
  1510. return i->index >= upb_table_size(&i->t->t) ||
  1511. upb_tabent_isempty(str_tabent(i));
  1512. }
  1513. upb_strview upb_strtable_iter_key(const upb_strtable_iter *i) {
  1514. upb_strview key;
  1515. uint32_t len;
  1516. UPB_ASSERT(!upb_strtable_done(i));
  1517. key.data = upb_tabstr(str_tabent(i)->key, &len);
  1518. key.size = len;
  1519. return key;
  1520. }
  1521. upb_value upb_strtable_iter_value(const upb_strtable_iter *i) {
  1522. UPB_ASSERT(!upb_strtable_done(i));
  1523. return _upb_value_val(str_tabent(i)->val.val);
  1524. }
  1525. void upb_strtable_iter_setdone(upb_strtable_iter *i) {
  1526. i->t = NULL;
  1527. i->index = SIZE_MAX;
  1528. }
  1529. bool upb_strtable_iter_isequal(const upb_strtable_iter *i1,
  1530. const upb_strtable_iter *i2) {
  1531. if (upb_strtable_done(i1) && upb_strtable_done(i2))
  1532. return true;
  1533. return i1->t == i2->t && i1->index == i2->index;
  1534. }
  1535. /* upb_inttable ***************************************************************/
  1536. /* For inttables we use a hybrid structure where small keys are kept in an
  1537. * array and large keys are put in the hash table. */
  1538. static uint32_t inthash(upb_tabkey key) { return upb_inthash(key); }
  1539. static bool inteql(upb_tabkey k1, lookupkey_t k2) {
  1540. return k1 == k2.num;
  1541. }
  1542. static upb_tabval *mutable_array(upb_inttable *t) {
  1543. return (upb_tabval*)t->array;
  1544. }
  1545. static upb_tabval *inttable_val(upb_inttable *t, uintptr_t key) {
  1546. if (key < t->array_size) {
  1547. return upb_arrhas(t->array[key]) ? &(mutable_array(t)[key]) : NULL;
  1548. } else {
  1549. upb_tabent *e =
  1550. findentry_mutable(&t->t, intkey(key), upb_inthash(key), &inteql);
  1551. return e ? &e->val : NULL;
  1552. }
  1553. }
  1554. static const upb_tabval *inttable_val_const(const upb_inttable *t,
  1555. uintptr_t key) {
  1556. return inttable_val((upb_inttable*)t, key);
  1557. }
  1558. size_t upb_inttable_count(const upb_inttable *t) {
  1559. return t->t.count + t->array_count;
  1560. }
  1561. static void check(upb_inttable *t) {
  1562. UPB_UNUSED(t);
  1563. #if defined(UPB_DEBUG_TABLE) && !defined(NDEBUG)
  1564. {
  1565. /* This check is very expensive (makes inserts/deletes O(N)). */
  1566. size_t count = 0;
  1567. upb_inttable_iter i;
  1568. upb_inttable_begin(&i, t);
  1569. for(; !upb_inttable_done(&i); upb_inttable_next(&i), count++) {
  1570. UPB_ASSERT(upb_inttable_lookup(t, upb_inttable_iter_key(&i), NULL));
  1571. }
  1572. UPB_ASSERT(count == upb_inttable_count(t));
  1573. }
  1574. #endif
  1575. }
  1576. bool upb_inttable_sizedinit(upb_inttable *t, size_t asize, int hsize_lg2,
  1577. upb_alloc *a) {
  1578. size_t array_bytes;
  1579. if (!init(&t->t, hsize_lg2, a)) return false;
  1580. /* Always make the array part at least 1 long, so that we know key 0
  1581. * won't be in the hash part, which simplifies things. */
  1582. t->array_size = UPB_MAX(1, asize);
  1583. t->array_count = 0;
  1584. array_bytes = t->array_size * sizeof(upb_value);
  1585. t->array = upb_malloc(a, array_bytes);
  1586. if (!t->array) {
  1587. uninit(&t->t, a);
  1588. return false;
  1589. }
  1590. memset(mutable_array(t), 0xff, array_bytes);
  1591. check(t);
  1592. return true;
  1593. }
  1594. bool upb_inttable_init2(upb_inttable *t, upb_ctype_t ctype, upb_alloc *a) {
  1595. return upb_inttable_sizedinit(t, 0, 4, a);
  1596. }
  1597. void upb_inttable_uninit2(upb_inttable *t, upb_alloc *a) {
  1598. uninit(&t->t, a);
  1599. upb_free(a, mutable_array(t));
  1600. }
  1601. bool upb_inttable_insert2(upb_inttable *t, uintptr_t key, upb_value val,
  1602. upb_alloc *a) {
  1603. upb_tabval tabval;
  1604. tabval.val = val.val;
  1605. UPB_ASSERT(upb_arrhas(tabval)); /* This will reject (uint64_t)-1. Fix this. */
  1606. if (key < t->array_size) {
  1607. UPB_ASSERT(!upb_arrhas(t->array[key]));
  1608. t->array_count++;
  1609. mutable_array(t)[key].val = val.val;
  1610. } else {
  1611. if (isfull(&t->t)) {
  1612. /* Need to resize the hash part, but we re-use the array part. */
  1613. size_t i;
  1614. upb_table new_table;
  1615. if (!init(&new_table, t->t.size_lg2 + 1, a)) {
  1616. return false;
  1617. }
  1618. for (i = begin(&t->t); i < upb_table_size(&t->t); i = next(&t->t, i)) {
  1619. const upb_tabent *e = &t->t.entries[i];
  1620. uint32_t hash;
  1621. upb_value v;
  1622. _upb_value_setval(&v, e->val.val);
  1623. hash = upb_inthash(e->key);
  1624. insert(&new_table, intkey(e->key), e->key, v, hash, &inthash, &inteql);
  1625. }
  1626. UPB_ASSERT(t->t.count == new_table.count);
  1627. uninit(&t->t, a);
  1628. t->t = new_table;
  1629. }
  1630. insert(&t->t, intkey(key), key, val, upb_inthash(key), &inthash, &inteql);
  1631. }
  1632. check(t);
  1633. return true;
  1634. }
  1635. bool upb_inttable_lookup(const upb_inttable *t, uintptr_t key, upb_value *v) {
  1636. const upb_tabval *table_v = inttable_val_const(t, key);
  1637. if (!table_v) return false;
  1638. if (v) _upb_value_setval(v, table_v->val);
  1639. return true;
  1640. }
  1641. bool upb_inttable_replace(upb_inttable *t, uintptr_t key, upb_value val) {
  1642. upb_tabval *table_v = inttable_val(t, key);
  1643. if (!table_v) return false;
  1644. table_v->val = val.val;
  1645. return true;
  1646. }
  1647. bool upb_inttable_remove(upb_inttable *t, uintptr_t key, upb_value *val) {
  1648. bool success;
  1649. if (key < t->array_size) {
  1650. if (upb_arrhas(t->array[key])) {
  1651. upb_tabval empty = UPB_TABVALUE_EMPTY_INIT;
  1652. t->array_count--;
  1653. if (val) {
  1654. _upb_value_setval(val, t->array[key].val);
  1655. }
  1656. mutable_array(t)[key] = empty;
  1657. success = true;
  1658. } else {
  1659. success = false;
  1660. }
  1661. } else {
  1662. success = rm(&t->t, intkey(key), val, NULL, upb_inthash(key), &inteql);
  1663. }
  1664. check(t);
  1665. return success;
  1666. }
  1667. bool upb_inttable_push2(upb_inttable *t, upb_value val, upb_alloc *a) {
  1668. return upb_inttable_insert2(t, upb_inttable_count(t), val, a);
  1669. }
  1670. upb_value upb_inttable_pop(upb_inttable *t) {
  1671. upb_value val;
  1672. bool ok = upb_inttable_remove(t, upb_inttable_count(t) - 1, &val);
  1673. UPB_ASSERT(ok);
  1674. return val;
  1675. }
  1676. bool upb_inttable_insertptr2(upb_inttable *t, const void *key, upb_value val,
  1677. upb_alloc *a) {
  1678. return upb_inttable_insert2(t, (uintptr_t)key, val, a);
  1679. }
  1680. bool upb_inttable_lookupptr(const upb_inttable *t, const void *key,
  1681. upb_value *v) {
  1682. return upb_inttable_lookup(t, (uintptr_t)key, v);
  1683. }
  1684. bool upb_inttable_removeptr(upb_inttable *t, const void *key, upb_value *val) {
  1685. return upb_inttable_remove(t, (uintptr_t)key, val);
  1686. }
  1687. void upb_inttable_compact2(upb_inttable *t, upb_alloc *a) {
  1688. /* A power-of-two histogram of the table keys. */
  1689. size_t counts[UPB_MAXARRSIZE + 1] = {0};
  1690. /* The max key in each bucket. */
  1691. uintptr_t max[UPB_MAXARRSIZE + 1] = {0};
  1692. upb_inttable_iter i;
  1693. size_t arr_count;
  1694. int size_lg2;
  1695. upb_inttable new_t;
  1696. upb_inttable_begin(&i, t);
  1697. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  1698. uintptr_t key = upb_inttable_iter_key(&i);
  1699. int bucket = log2ceil(key);
  1700. max[bucket] = UPB_MAX(max[bucket], key);
  1701. counts[bucket]++;
  1702. }
  1703. /* Find the largest power of two that satisfies the MIN_DENSITY
  1704. * definition (while actually having some keys). */
  1705. arr_count = upb_inttable_count(t);
  1706. for (size_lg2 = ARRAY_SIZE(counts) - 1; size_lg2 > 0; size_lg2--) {
  1707. if (counts[size_lg2] == 0) {
  1708. /* We can halve again without losing any entries. */
  1709. continue;
  1710. } else if (arr_count >= (1 << size_lg2) * MIN_DENSITY) {
  1711. break;
  1712. }
  1713. arr_count -= counts[size_lg2];
  1714. }
  1715. UPB_ASSERT(arr_count <= upb_inttable_count(t));
  1716. {
  1717. /* Insert all elements into new, perfectly-sized table. */
  1718. size_t arr_size = max[size_lg2] + 1; /* +1 so arr[max] will fit. */
  1719. size_t hash_count = upb_inttable_count(t) - arr_count;
  1720. size_t hash_size = hash_count ? (hash_count / MAX_LOAD) + 1 : 0;
  1721. int hashsize_lg2 = log2ceil(hash_size);
  1722. upb_inttable_sizedinit(&new_t, arr_size, hashsize_lg2, a);
  1723. upb_inttable_begin(&i, t);
  1724. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  1725. uintptr_t k = upb_inttable_iter_key(&i);
  1726. upb_inttable_insert2(&new_t, k, upb_inttable_iter_value(&i), a);
  1727. }
  1728. UPB_ASSERT(new_t.array_size == arr_size);
  1729. UPB_ASSERT(new_t.t.size_lg2 == hashsize_lg2);
  1730. }
  1731. upb_inttable_uninit2(t, a);
  1732. *t = new_t;
  1733. }
  1734. /* Iteration. */
  1735. static const upb_tabent *int_tabent(const upb_inttable_iter *i) {
  1736. UPB_ASSERT(!i->array_part);
  1737. return &i->t->t.entries[i->index];
  1738. }
  1739. static upb_tabval int_arrent(const upb_inttable_iter *i) {
  1740. UPB_ASSERT(i->array_part);
  1741. return i->t->array[i->index];
  1742. }
  1743. void upb_inttable_begin(upb_inttable_iter *i, const upb_inttable *t) {
  1744. i->t = t;
  1745. i->index = -1;
  1746. i->array_part = true;
  1747. upb_inttable_next(i);
  1748. }
  1749. void upb_inttable_next(upb_inttable_iter *iter) {
  1750. const upb_inttable *t = iter->t;
  1751. if (iter->array_part) {
  1752. while (++iter->index < t->array_size) {
  1753. if (upb_arrhas(int_arrent(iter))) {
  1754. return;
  1755. }
  1756. }
  1757. iter->array_part = false;
  1758. iter->index = begin(&t->t);
  1759. } else {
  1760. iter->index = next(&t->t, iter->index);
  1761. }
  1762. }
  1763. bool upb_inttable_done(const upb_inttable_iter *i) {
  1764. if (!i->t) return true;
  1765. if (i->array_part) {
  1766. return i->index >= i->t->array_size ||
  1767. !upb_arrhas(int_arrent(i));
  1768. } else {
  1769. return i->index >= upb_table_size(&i->t->t) ||
  1770. upb_tabent_isempty(int_tabent(i));
  1771. }
  1772. }
  1773. uintptr_t upb_inttable_iter_key(const upb_inttable_iter *i) {
  1774. UPB_ASSERT(!upb_inttable_done(i));
  1775. return i->array_part ? i->index : int_tabent(i)->key;
  1776. }
  1777. upb_value upb_inttable_iter_value(const upb_inttable_iter *i) {
  1778. UPB_ASSERT(!upb_inttable_done(i));
  1779. return _upb_value_val(
  1780. i->array_part ? i->t->array[i->index].val : int_tabent(i)->val.val);
  1781. }
  1782. void upb_inttable_iter_setdone(upb_inttable_iter *i) {
  1783. i->t = NULL;
  1784. i->index = SIZE_MAX;
  1785. i->array_part = false;
  1786. }
  1787. bool upb_inttable_iter_isequal(const upb_inttable_iter *i1,
  1788. const upb_inttable_iter *i2) {
  1789. if (upb_inttable_done(i1) && upb_inttable_done(i2))
  1790. return true;
  1791. return i1->t == i2->t && i1->index == i2->index &&
  1792. i1->array_part == i2->array_part;
  1793. }
  1794. #if defined(UPB_UNALIGNED_READS_OK) || defined(__s390x__)
  1795. /* -----------------------------------------------------------------------------
  1796. * MurmurHash2, by Austin Appleby (released as public domain).
  1797. * Reformatted and C99-ified by Joshua Haberman.
  1798. * Note - This code makes a few assumptions about how your machine behaves -
  1799. * 1. We can read a 4-byte value from any address without crashing
  1800. * 2. sizeof(int) == 4 (in upb this limitation is removed by using uint32_t
  1801. * And it has a few limitations -
  1802. * 1. It will not work incrementally.
  1803. * 2. It will not produce the same results on little-endian and big-endian
  1804. * machines. */
  1805. uint32_t upb_murmur_hash2(const void *key, size_t len, uint32_t seed) {
  1806. /* 'm' and 'r' are mixing constants generated offline.
  1807. * They're not really 'magic', they just happen to work well. */
  1808. const uint32_t m = 0x5bd1e995;
  1809. const int32_t r = 24;
  1810. /* Initialize the hash to a 'random' value */
  1811. uint32_t h = seed ^ len;
  1812. /* Mix 4 bytes at a time into the hash */
  1813. const uint8_t * data = (const uint8_t *)key;
  1814. while(len >= 4) {
  1815. uint32_t k;
  1816. memcpy(&k, data, sizeof(k));
  1817. k *= m;
  1818. k ^= k >> r;
  1819. k *= m;
  1820. h *= m;
  1821. h ^= k;
  1822. data += 4;
  1823. len -= 4;
  1824. }
  1825. /* Handle the last few bytes of the input array */
  1826. switch(len) {
  1827. case 3: h ^= data[2] << 16;
  1828. case 2: h ^= data[1] << 8;
  1829. case 1: h ^= data[0]; h *= m;
  1830. };
  1831. /* Do a few final mixes of the hash to ensure the last few
  1832. * bytes are well-incorporated. */
  1833. h ^= h >> 13;
  1834. h *= m;
  1835. h ^= h >> 15;
  1836. return h;
  1837. }
  1838. #else /* !UPB_UNALIGNED_READS_OK */
  1839. /* -----------------------------------------------------------------------------
  1840. * MurmurHashAligned2, by Austin Appleby
  1841. * Same algorithm as MurmurHash2, but only does aligned reads - should be safer
  1842. * on certain platforms.
  1843. * Performance will be lower than MurmurHash2 */
  1844. #define MIX(h,k,m) { k *= m; k ^= k >> r; k *= m; h *= m; h ^= k; }
  1845. uint32_t upb_murmur_hash2(const void * key, size_t len, uint32_t seed) {
  1846. const uint32_t m = 0x5bd1e995;
  1847. const int32_t r = 24;
  1848. const uint8_t * data = (const uint8_t *)key;
  1849. uint32_t h = (uint32_t)(seed ^ len);
  1850. uint8_t align = (uintptr_t)data & 3;
  1851. if(align && (len >= 4)) {
  1852. /* Pre-load the temp registers */
  1853. uint32_t t = 0, d = 0;
  1854. int32_t sl;
  1855. int32_t sr;
  1856. switch(align) {
  1857. case 1: t |= data[2] << 16;
  1858. case 2: t |= data[1] << 8;
  1859. case 3: t |= data[0];
  1860. }
  1861. t <<= (8 * align);
  1862. data += 4-align;
  1863. len -= 4-align;
  1864. sl = 8 * (4-align);
  1865. sr = 8 * align;
  1866. /* Mix */
  1867. while(len >= 4) {
  1868. uint32_t k;
  1869. d = *(uint32_t *)data;
  1870. t = (t >> sr) | (d << sl);
  1871. k = t;
  1872. MIX(h,k,m);
  1873. t = d;
  1874. data += 4;
  1875. len -= 4;
  1876. }
  1877. /* Handle leftover data in temp registers */
  1878. d = 0;
  1879. if(len >= align) {
  1880. uint32_t k;
  1881. switch(align) {
  1882. case 3: d |= data[2] << 16;
  1883. case 2: d |= data[1] << 8;
  1884. case 1: d |= data[0];
  1885. }
  1886. k = (t >> sr) | (d << sl);
  1887. MIX(h,k,m);
  1888. data += align;
  1889. len -= align;
  1890. /* ----------
  1891. * Handle tail bytes */
  1892. switch(len) {
  1893. case 3: h ^= data[2] << 16;
  1894. case 2: h ^= data[1] << 8;
  1895. case 1: h ^= data[0]; h *= m;
  1896. };
  1897. } else {
  1898. switch(len) {
  1899. case 3: d |= data[2] << 16;
  1900. case 2: d |= data[1] << 8;
  1901. case 1: d |= data[0];
  1902. case 0: h ^= (t >> sr) | (d << sl); h *= m;
  1903. }
  1904. }
  1905. h ^= h >> 13;
  1906. h *= m;
  1907. h ^= h >> 15;
  1908. return h;
  1909. } else {
  1910. while(len >= 4) {
  1911. uint32_t k = *(uint32_t *)data;
  1912. MIX(h,k,m);
  1913. data += 4;
  1914. len -= 4;
  1915. }
  1916. /* ----------
  1917. * Handle tail bytes */
  1918. switch(len) {
  1919. case 3: h ^= data[2] << 16;
  1920. case 2: h ^= data[1] << 8;
  1921. case 1: h ^= data[0]; h *= m;
  1922. };
  1923. h ^= h >> 13;
  1924. h *= m;
  1925. h ^= h >> 15;
  1926. return h;
  1927. }
  1928. }
  1929. #undef MIX
  1930. #endif /* UPB_UNALIGNED_READS_OK */
  1931. #include <errno.h>
  1932. #include <stdarg.h>
  1933. #include <stddef.h>
  1934. #include <stdint.h>
  1935. #include <stdio.h>
  1936. #include <stdlib.h>
  1937. #include <string.h>
  1938. /* upb_status *****************************************************************/
  1939. void upb_status_clear(upb_status *status) {
  1940. if (!status) return;
  1941. status->ok = true;
  1942. status->msg[0] = '\0';
  1943. }
  1944. bool upb_ok(const upb_status *status) { return status->ok; }
  1945. const char *upb_status_errmsg(const upb_status *status) { return status->msg; }
  1946. void upb_status_seterrmsg(upb_status *status, const char *msg) {
  1947. if (!status) return;
  1948. status->ok = false;
  1949. strncpy(status->msg, msg, UPB_STATUS_MAX_MESSAGE - 1);
  1950. status->msg[UPB_STATUS_MAX_MESSAGE - 1] = '\0';
  1951. }
  1952. void upb_status_seterrf(upb_status *status, const char *fmt, ...) {
  1953. va_list args;
  1954. va_start(args, fmt);
  1955. upb_status_vseterrf(status, fmt, args);
  1956. va_end(args);
  1957. }
  1958. void upb_status_vseterrf(upb_status *status, const char *fmt, va_list args) {
  1959. if (!status) return;
  1960. status->ok = false;
  1961. _upb_vsnprintf(status->msg, sizeof(status->msg), fmt, args);
  1962. status->msg[UPB_STATUS_MAX_MESSAGE - 1] = '\0';
  1963. }
  1964. /* upb_alloc ******************************************************************/
  1965. static void *upb_global_allocfunc(upb_alloc *alloc, void *ptr, size_t oldsize,
  1966. size_t size) {
  1967. UPB_UNUSED(alloc);
  1968. UPB_UNUSED(oldsize);
  1969. if (size == 0) {
  1970. free(ptr);
  1971. return NULL;
  1972. } else {
  1973. return realloc(ptr, size);
  1974. }
  1975. }
  1976. upb_alloc upb_alloc_global = {&upb_global_allocfunc};
  1977. /* upb_arena ******************************************************************/
  1978. /* Be conservative and choose 16 in case anyone is using SSE. */
  1979. struct upb_arena {
  1980. _upb_arena_head head;
  1981. char *start;
  1982. /* Allocator to allocate arena blocks. We are responsible for freeing these
  1983. * when we are destroyed. */
  1984. upb_alloc *block_alloc;
  1985. size_t bytes_allocated;
  1986. size_t next_block_size;
  1987. size_t max_block_size;
  1988. /* Linked list of blocks. Points to an arena_block, defined in env.c */
  1989. void *block_head;
  1990. /* Cleanup entries. Pointer to a cleanup_ent, defined in env.c */
  1991. void *cleanup_head;
  1992. };
  1993. typedef struct mem_block {
  1994. struct mem_block *next;
  1995. bool owned;
  1996. /* Data follows. */
  1997. } mem_block;
  1998. typedef struct cleanup_ent {
  1999. struct cleanup_ent *next;
  2000. upb_cleanup_func *cleanup;
  2001. void *ud;
  2002. } cleanup_ent;
  2003. static void upb_arena_addblock(upb_arena *a, void *ptr, size_t size,
  2004. bool owned) {
  2005. mem_block *block = ptr;
  2006. if (a->block_head) {
  2007. a->bytes_allocated += a->head.ptr - a->start;
  2008. }
  2009. block->next = a->block_head;
  2010. block->owned = owned;
  2011. a->block_head = block;
  2012. a->start = (char*)block + _upb_arena_alignup(sizeof(mem_block));
  2013. a->head.ptr = a->start;
  2014. a->head.end = (char*)block + size;
  2015. /* TODO(haberman): ASAN poison. */
  2016. }
  2017. static mem_block *upb_arena_allocblock(upb_arena *a, size_t size) {
  2018. size_t block_size = UPB_MAX(size, a->next_block_size) + sizeof(mem_block);
  2019. mem_block *block = upb_malloc(a->block_alloc, block_size);
  2020. if (!block) {
  2021. return NULL;
  2022. }
  2023. upb_arena_addblock(a, block, block_size, true);
  2024. a->next_block_size = UPB_MIN(block_size * 2, a->max_block_size);
  2025. return block;
  2026. }
  2027. void *_upb_arena_slowmalloc(upb_arena *a, size_t size) {
  2028. mem_block *block = upb_arena_allocblock(a, size);
  2029. if (!block) return NULL; /* Out of memory. */
  2030. return upb_arena_malloc(a, size);
  2031. }
  2032. static void *upb_arena_doalloc(upb_alloc *alloc, void *ptr, size_t oldsize,
  2033. size_t size) {
  2034. upb_arena *a = (upb_arena*)alloc; /* upb_alloc is initial member. */
  2035. void *ret;
  2036. if (size == 0) {
  2037. return NULL; /* We are an arena, don't need individual frees. */
  2038. }
  2039. ret = upb_arena_malloc(a, size);
  2040. if (!ret) return NULL;
  2041. /* TODO(haberman): special-case if this is a realloc of the last alloc? */
  2042. if (oldsize > 0) {
  2043. memcpy(ret, ptr, oldsize); /* Preserve existing data. */
  2044. }
  2045. /* TODO(haberman): ASAN unpoison. */
  2046. return ret;
  2047. }
  2048. /* Public Arena API ***********************************************************/
  2049. #define upb_alignof(type) offsetof (struct { char c; type member; }, member)
  2050. upb_arena *upb_arena_init(void *mem, size_t n, upb_alloc *alloc) {
  2051. const size_t first_block_overhead = sizeof(upb_arena) + sizeof(mem_block);
  2052. upb_arena *a;
  2053. bool owned = false;
  2054. /* Round block size down to alignof(*a) since we will allocate the arena
  2055. * itself at the end. */
  2056. n &= ~(upb_alignof(upb_arena) - 1);
  2057. if (n < first_block_overhead) {
  2058. /* We need to malloc the initial block. */
  2059. n = first_block_overhead + 256;
  2060. owned = true;
  2061. if (!alloc || !(mem = upb_malloc(alloc, n))) {
  2062. return NULL;
  2063. }
  2064. }
  2065. a = (void*)((char*)mem + n - sizeof(*a));
  2066. n -= sizeof(*a);
  2067. a->head.alloc.func = &upb_arena_doalloc;
  2068. a->head.ptr = NULL;
  2069. a->head.end = NULL;
  2070. a->start = NULL;
  2071. a->block_alloc = &upb_alloc_global;
  2072. a->bytes_allocated = 0;
  2073. a->next_block_size = 256;
  2074. a->max_block_size = 16384;
  2075. a->cleanup_head = NULL;
  2076. a->block_head = NULL;
  2077. a->block_alloc = alloc;
  2078. upb_arena_addblock(a, mem, n, owned);
  2079. return a;
  2080. }
  2081. #undef upb_alignof
  2082. void upb_arena_free(upb_arena *a) {
  2083. cleanup_ent *ent = a->cleanup_head;
  2084. mem_block *block = a->block_head;
  2085. while (ent) {
  2086. ent->cleanup(ent->ud);
  2087. ent = ent->next;
  2088. }
  2089. /* Must do this after running cleanup functions, because this will delete
  2090. * the memory we store our cleanup entries in! */
  2091. while (block) {
  2092. /* Load first since we are deleting block. */
  2093. mem_block *next = block->next;
  2094. if (block->owned) {
  2095. upb_free(a->block_alloc, block);
  2096. }
  2097. block = next;
  2098. }
  2099. }
  2100. bool upb_arena_addcleanup(upb_arena *a, void *ud, upb_cleanup_func *func) {
  2101. cleanup_ent *ent = upb_malloc(&a->head.alloc, sizeof(cleanup_ent));
  2102. if (!ent) {
  2103. return false; /* Out of memory. */
  2104. }
  2105. ent->cleanup = func;
  2106. ent->ud = ud;
  2107. ent->next = a->cleanup_head;
  2108. a->cleanup_head = ent;
  2109. return true;
  2110. }
  2111. size_t upb_arena_bytesallocated(const upb_arena *a) {
  2112. return a->bytes_allocated + (a->head.ptr - a->start);
  2113. }
  2114. /* This file was generated by upbc (the upb compiler) from the input
  2115. * file:
  2116. *
  2117. * google/protobuf/descriptor.proto
  2118. *
  2119. * Do not edit -- your changes will be discarded when the file is
  2120. * regenerated. */
  2121. #include <stddef.h>
  2122. static const upb_msglayout *const google_protobuf_FileDescriptorSet_submsgs[1] = {
  2123. &google_protobuf_FileDescriptorProto_msginit,
  2124. };
  2125. static const upb_msglayout_field google_protobuf_FileDescriptorSet__fields[1] = {
  2126. {1, UPB_SIZE(0, 0), 0, 0, 11, 3},
  2127. };
  2128. const upb_msglayout google_protobuf_FileDescriptorSet_msginit = {
  2129. &google_protobuf_FileDescriptorSet_submsgs[0],
  2130. &google_protobuf_FileDescriptorSet__fields[0],
  2131. UPB_SIZE(4, 8), 1, false,
  2132. };
  2133. static const upb_msglayout *const google_protobuf_FileDescriptorProto_submsgs[6] = {
  2134. &google_protobuf_DescriptorProto_msginit,
  2135. &google_protobuf_EnumDescriptorProto_msginit,
  2136. &google_protobuf_FieldDescriptorProto_msginit,
  2137. &google_protobuf_FileOptions_msginit,
  2138. &google_protobuf_ServiceDescriptorProto_msginit,
  2139. &google_protobuf_SourceCodeInfo_msginit,
  2140. };
  2141. static const upb_msglayout_field google_protobuf_FileDescriptorProto__fields[12] = {
  2142. {1, UPB_SIZE(4, 8), 1, 0, 9, 1},
  2143. {2, UPB_SIZE(12, 24), 2, 0, 9, 1},
  2144. {3, UPB_SIZE(36, 72), 0, 0, 9, 3},
  2145. {4, UPB_SIZE(40, 80), 0, 0, 11, 3},
  2146. {5, UPB_SIZE(44, 88), 0, 1, 11, 3},
  2147. {6, UPB_SIZE(48, 96), 0, 4, 11, 3},
  2148. {7, UPB_SIZE(52, 104), 0, 2, 11, 3},
  2149. {8, UPB_SIZE(28, 56), 4, 3, 11, 1},
  2150. {9, UPB_SIZE(32, 64), 5, 5, 11, 1},
  2151. {10, UPB_SIZE(56, 112), 0, 0, 5, 3},
  2152. {11, UPB_SIZE(60, 120), 0, 0, 5, 3},
  2153. {12, UPB_SIZE(20, 40), 3, 0, 9, 1},
  2154. };
  2155. const upb_msglayout google_protobuf_FileDescriptorProto_msginit = {
  2156. &google_protobuf_FileDescriptorProto_submsgs[0],
  2157. &google_protobuf_FileDescriptorProto__fields[0],
  2158. UPB_SIZE(64, 128), 12, false,
  2159. };
  2160. static const upb_msglayout *const google_protobuf_DescriptorProto_submsgs[8] = {
  2161. &google_protobuf_DescriptorProto_msginit,
  2162. &google_protobuf_DescriptorProto_ExtensionRange_msginit,
  2163. &google_protobuf_DescriptorProto_ReservedRange_msginit,
  2164. &google_protobuf_EnumDescriptorProto_msginit,
  2165. &google_protobuf_FieldDescriptorProto_msginit,
  2166. &google_protobuf_MessageOptions_msginit,
  2167. &google_protobuf_OneofDescriptorProto_msginit,
  2168. };
  2169. static const upb_msglayout_field google_protobuf_DescriptorProto__fields[10] = {
  2170. {1, UPB_SIZE(4, 8), 1, 0, 9, 1},
  2171. {2, UPB_SIZE(16, 32), 0, 4, 11, 3},
  2172. {3, UPB_SIZE(20, 40), 0, 0, 11, 3},
  2173. {4, UPB_SIZE(24, 48), 0, 3, 11, 3},
  2174. {5, UPB_SIZE(28, 56), 0, 1, 11, 3},
  2175. {6, UPB_SIZE(32, 64), 0, 4, 11, 3},
  2176. {7, UPB_SIZE(12, 24), 2, 5, 11, 1},
  2177. {8, UPB_SIZE(36, 72), 0, 6, 11, 3},
  2178. {9, UPB_SIZE(40, 80), 0, 2, 11, 3},
  2179. {10, UPB_SIZE(44, 88), 0, 0, 9, 3},
  2180. };
  2181. const upb_msglayout google_protobuf_DescriptorProto_msginit = {
  2182. &google_protobuf_DescriptorProto_submsgs[0],
  2183. &google_protobuf_DescriptorProto__fields[0],
  2184. UPB_SIZE(48, 96), 10, false,
  2185. };
  2186. static const upb_msglayout *const google_protobuf_DescriptorProto_ExtensionRange_submsgs[1] = {
  2187. &google_protobuf_ExtensionRangeOptions_msginit,
  2188. };
  2189. static const upb_msglayout_field google_protobuf_DescriptorProto_ExtensionRange__fields[3] = {
  2190. {1, UPB_SIZE(4, 4), 1, 0, 5, 1},
  2191. {2, UPB_SIZE(8, 8), 2, 0, 5, 1},
  2192. {3, UPB_SIZE(12, 16), 3, 0, 11, 1},
  2193. };
  2194. const upb_msglayout google_protobuf_DescriptorProto_ExtensionRange_msginit = {
  2195. &google_protobuf_DescriptorProto_ExtensionRange_submsgs[0],
  2196. &google_protobuf_DescriptorProto_ExtensionRange__fields[0],
  2197. UPB_SIZE(16, 24), 3, false,
  2198. };
  2199. static const upb_msglayout_field google_protobuf_DescriptorProto_ReservedRange__fields[2] = {
  2200. {1, UPB_SIZE(4, 4), 1, 0, 5, 1},
  2201. {2, UPB_SIZE(8, 8), 2, 0, 5, 1},
  2202. };
  2203. const upb_msglayout google_protobuf_DescriptorProto_ReservedRange_msginit = {
  2204. NULL,
  2205. &google_protobuf_DescriptorProto_ReservedRange__fields[0],
  2206. UPB_SIZE(12, 12), 2, false,
  2207. };
  2208. static const upb_msglayout *const google_protobuf_ExtensionRangeOptions_submsgs[1] = {
  2209. &google_protobuf_UninterpretedOption_msginit,
  2210. };
  2211. static const upb_msglayout_field google_protobuf_ExtensionRangeOptions__fields[1] = {
  2212. {999, UPB_SIZE(0, 0), 0, 0, 11, 3},
  2213. };
  2214. const upb_msglayout google_protobuf_ExtensionRangeOptions_msginit = {
  2215. &google_protobuf_ExtensionRangeOptions_submsgs[0],
  2216. &google_protobuf_ExtensionRangeOptions__fields[0],
  2217. UPB_SIZE(4, 8), 1, false,
  2218. };
  2219. static const upb_msglayout *const google_protobuf_FieldDescriptorProto_submsgs[1] = {
  2220. &google_protobuf_FieldOptions_msginit,
  2221. };
  2222. static const upb_msglayout_field google_protobuf_FieldDescriptorProto__fields[11] = {
  2223. {1, UPB_SIZE(36, 40), 6, 0, 9, 1},
  2224. {2, UPB_SIZE(44, 56), 7, 0, 9, 1},
  2225. {3, UPB_SIZE(24, 24), 3, 0, 5, 1},
  2226. {4, UPB_SIZE(8, 8), 1, 0, 14, 1},
  2227. {5, UPB_SIZE(16, 16), 2, 0, 14, 1},
  2228. {6, UPB_SIZE(52, 72), 8, 0, 9, 1},
  2229. {7, UPB_SIZE(60, 88), 9, 0, 9, 1},
  2230. {8, UPB_SIZE(76, 120), 11, 0, 11, 1},
  2231. {9, UPB_SIZE(28, 28), 4, 0, 5, 1},
  2232. {10, UPB_SIZE(68, 104), 10, 0, 9, 1},
  2233. {17, UPB_SIZE(32, 32), 5, 0, 8, 1},
  2234. };
  2235. const upb_msglayout google_protobuf_FieldDescriptorProto_msginit = {
  2236. &google_protobuf_FieldDescriptorProto_submsgs[0],
  2237. &google_protobuf_FieldDescriptorProto__fields[0],
  2238. UPB_SIZE(80, 128), 11, false,
  2239. };
  2240. static const upb_msglayout *const google_protobuf_OneofDescriptorProto_submsgs[1] = {
  2241. &google_protobuf_OneofOptions_msginit,
  2242. };
  2243. static const upb_msglayout_field google_protobuf_OneofDescriptorProto__fields[2] = {
  2244. {1, UPB_SIZE(4, 8), 1, 0, 9, 1},
  2245. {2, UPB_SIZE(12, 24), 2, 0, 11, 1},
  2246. };
  2247. const upb_msglayout google_protobuf_OneofDescriptorProto_msginit = {
  2248. &google_protobuf_OneofDescriptorProto_submsgs[0],
  2249. &google_protobuf_OneofDescriptorProto__fields[0],
  2250. UPB_SIZE(16, 32), 2, false,
  2251. };
  2252. static const upb_msglayout *const google_protobuf_EnumDescriptorProto_submsgs[3] = {
  2253. &google_protobuf_EnumDescriptorProto_EnumReservedRange_msginit,
  2254. &google_protobuf_EnumOptions_msginit,
  2255. &google_protobuf_EnumValueDescriptorProto_msginit,
  2256. };
  2257. static const upb_msglayout_field google_protobuf_EnumDescriptorProto__fields[5] = {
  2258. {1, UPB_SIZE(4, 8), 1, 0, 9, 1},
  2259. {2, UPB_SIZE(16, 32), 0, 2, 11, 3},
  2260. {3, UPB_SIZE(12, 24), 2, 1, 11, 1},
  2261. {4, UPB_SIZE(20, 40), 0, 0, 11, 3},
  2262. {5, UPB_SIZE(24, 48), 0, 0, 9, 3},
  2263. };
  2264. const upb_msglayout google_protobuf_EnumDescriptorProto_msginit = {
  2265. &google_protobuf_EnumDescriptorProto_submsgs[0],
  2266. &google_protobuf_EnumDescriptorProto__fields[0],
  2267. UPB_SIZE(32, 64), 5, false,
  2268. };
  2269. static const upb_msglayout_field google_protobuf_EnumDescriptorProto_EnumReservedRange__fields[2] = {
  2270. {1, UPB_SIZE(4, 4), 1, 0, 5, 1},
  2271. {2, UPB_SIZE(8, 8), 2, 0, 5, 1},
  2272. };
  2273. const upb_msglayout google_protobuf_EnumDescriptorProto_EnumReservedRange_msginit = {
  2274. NULL,
  2275. &google_protobuf_EnumDescriptorProto_EnumReservedRange__fields[0],
  2276. UPB_SIZE(12, 12), 2, false,
  2277. };
  2278. static const upb_msglayout *const google_protobuf_EnumValueDescriptorProto_submsgs[1] = {
  2279. &google_protobuf_EnumValueOptions_msginit,
  2280. };
  2281. static const upb_msglayout_field google_protobuf_EnumValueDescriptorProto__fields[3] = {
  2282. {1, UPB_SIZE(8, 8), 2, 0, 9, 1},
  2283. {2, UPB_SIZE(4, 4), 1, 0, 5, 1},
  2284. {3, UPB_SIZE(16, 24), 3, 0, 11, 1},
  2285. };
  2286. const upb_msglayout google_protobuf_EnumValueDescriptorProto_msginit = {
  2287. &google_protobuf_EnumValueDescriptorProto_submsgs[0],
  2288. &google_protobuf_EnumValueDescriptorProto__fields[0],
  2289. UPB_SIZE(24, 32), 3, false,
  2290. };
  2291. static const upb_msglayout *const google_protobuf_ServiceDescriptorProto_submsgs[2] = {
  2292. &google_protobuf_MethodDescriptorProto_msginit,
  2293. &google_protobuf_ServiceOptions_msginit,
  2294. };
  2295. static const upb_msglayout_field google_protobuf_ServiceDescriptorProto__fields[3] = {
  2296. {1, UPB_SIZE(4, 8), 1, 0, 9, 1},
  2297. {2, UPB_SIZE(16, 32), 0, 0, 11, 3},
  2298. {3, UPB_SIZE(12, 24), 2, 1, 11, 1},
  2299. };
  2300. const upb_msglayout google_protobuf_ServiceDescriptorProto_msginit = {
  2301. &google_protobuf_ServiceDescriptorProto_submsgs[0],
  2302. &google_protobuf_ServiceDescriptorProto__fields[0],
  2303. UPB_SIZE(24, 48), 3, false,
  2304. };
  2305. static const upb_msglayout *const google_protobuf_MethodDescriptorProto_submsgs[1] = {
  2306. &google_protobuf_MethodOptions_msginit,
  2307. };
  2308. static const upb_msglayout_field google_protobuf_MethodDescriptorProto__fields[6] = {
  2309. {1, UPB_SIZE(4, 8), 3, 0, 9, 1},
  2310. {2, UPB_SIZE(12, 24), 4, 0, 9, 1},
  2311. {3, UPB_SIZE(20, 40), 5, 0, 9, 1},
  2312. {4, UPB_SIZE(28, 56), 6, 0, 11, 1},
  2313. {5, UPB_SIZE(1, 1), 1, 0, 8, 1},
  2314. {6, UPB_SIZE(2, 2), 2, 0, 8, 1},
  2315. };
  2316. const upb_msglayout google_protobuf_MethodDescriptorProto_msginit = {
  2317. &google_protobuf_MethodDescriptorProto_submsgs[0],
  2318. &google_protobuf_MethodDescriptorProto__fields[0],
  2319. UPB_SIZE(32, 64), 6, false,
  2320. };
  2321. static const upb_msglayout *const google_protobuf_FileOptions_submsgs[1] = {
  2322. &google_protobuf_UninterpretedOption_msginit,
  2323. };
  2324. static const upb_msglayout_field google_protobuf_FileOptions__fields[21] = {
  2325. {1, UPB_SIZE(28, 32), 11, 0, 9, 1},
  2326. {8, UPB_SIZE(36, 48), 12, 0, 9, 1},
  2327. {9, UPB_SIZE(8, 8), 1, 0, 14, 1},
  2328. {10, UPB_SIZE(16, 16), 2, 0, 8, 1},
  2329. {11, UPB_SIZE(44, 64), 13, 0, 9, 1},
  2330. {16, UPB_SIZE(17, 17), 3, 0, 8, 1},
  2331. {17, UPB_SIZE(18, 18), 4, 0, 8, 1},
  2332. {18, UPB_SIZE(19, 19), 5, 0, 8, 1},
  2333. {20, UPB_SIZE(20, 20), 6, 0, 8, 1},
  2334. {23, UPB_SIZE(21, 21), 7, 0, 8, 1},
  2335. {27, UPB_SIZE(22, 22), 8, 0, 8, 1},
  2336. {31, UPB_SIZE(23, 23), 9, 0, 8, 1},
  2337. {36, UPB_SIZE(52, 80), 14, 0, 9, 1},
  2338. {37, UPB_SIZE(60, 96), 15, 0, 9, 1},
  2339. {39, UPB_SIZE(68, 112), 16, 0, 9, 1},
  2340. {40, UPB_SIZE(76, 128), 17, 0, 9, 1},
  2341. {41, UPB_SIZE(84, 144), 18, 0, 9, 1},
  2342. {42, UPB_SIZE(24, 24), 10, 0, 8, 1},
  2343. {44, UPB_SIZE(92, 160), 19, 0, 9, 1},
  2344. {45, UPB_SIZE(100, 176), 20, 0, 9, 1},
  2345. {999, UPB_SIZE(108, 192), 0, 0, 11, 3},
  2346. };
  2347. const upb_msglayout google_protobuf_FileOptions_msginit = {
  2348. &google_protobuf_FileOptions_submsgs[0],
  2349. &google_protobuf_FileOptions__fields[0],
  2350. UPB_SIZE(112, 208), 21, false,
  2351. };
  2352. static const upb_msglayout *const google_protobuf_MessageOptions_submsgs[1] = {
  2353. &google_protobuf_UninterpretedOption_msginit,
  2354. };
  2355. static const upb_msglayout_field google_protobuf_MessageOptions__fields[5] = {
  2356. {1, UPB_SIZE(1, 1), 1, 0, 8, 1},
  2357. {2, UPB_SIZE(2, 2), 2, 0, 8, 1},
  2358. {3, UPB_SIZE(3, 3), 3, 0, 8, 1},
  2359. {7, UPB_SIZE(4, 4), 4, 0, 8, 1},
  2360. {999, UPB_SIZE(8, 8), 0, 0, 11, 3},
  2361. };
  2362. const upb_msglayout google_protobuf_MessageOptions_msginit = {
  2363. &google_protobuf_MessageOptions_submsgs[0],
  2364. &google_protobuf_MessageOptions__fields[0],
  2365. UPB_SIZE(12, 16), 5, false,
  2366. };
  2367. static const upb_msglayout *const google_protobuf_FieldOptions_submsgs[1] = {
  2368. &google_protobuf_UninterpretedOption_msginit,
  2369. };
  2370. static const upb_msglayout_field google_protobuf_FieldOptions__fields[7] = {
  2371. {1, UPB_SIZE(8, 8), 1, 0, 14, 1},
  2372. {2, UPB_SIZE(24, 24), 3, 0, 8, 1},
  2373. {3, UPB_SIZE(25, 25), 4, 0, 8, 1},
  2374. {5, UPB_SIZE(26, 26), 5, 0, 8, 1},
  2375. {6, UPB_SIZE(16, 16), 2, 0, 14, 1},
  2376. {10, UPB_SIZE(27, 27), 6, 0, 8, 1},
  2377. {999, UPB_SIZE(28, 32), 0, 0, 11, 3},
  2378. };
  2379. const upb_msglayout google_protobuf_FieldOptions_msginit = {
  2380. &google_protobuf_FieldOptions_submsgs[0],
  2381. &google_protobuf_FieldOptions__fields[0],
  2382. UPB_SIZE(32, 40), 7, false,
  2383. };
  2384. static const upb_msglayout *const google_protobuf_OneofOptions_submsgs[1] = {
  2385. &google_protobuf_UninterpretedOption_msginit,
  2386. };
  2387. static const upb_msglayout_field google_protobuf_OneofOptions__fields[1] = {
  2388. {999, UPB_SIZE(0, 0), 0, 0, 11, 3},
  2389. };
  2390. const upb_msglayout google_protobuf_OneofOptions_msginit = {
  2391. &google_protobuf_OneofOptions_submsgs[0],
  2392. &google_protobuf_OneofOptions__fields[0],
  2393. UPB_SIZE(4, 8), 1, false,
  2394. };
  2395. static const upb_msglayout *const google_protobuf_EnumOptions_submsgs[1] = {
  2396. &google_protobuf_UninterpretedOption_msginit,
  2397. };
  2398. static const upb_msglayout_field google_protobuf_EnumOptions__fields[3] = {
  2399. {2, UPB_SIZE(1, 1), 1, 0, 8, 1},
  2400. {3, UPB_SIZE(2, 2), 2, 0, 8, 1},
  2401. {999, UPB_SIZE(4, 8), 0, 0, 11, 3},
  2402. };
  2403. const upb_msglayout google_protobuf_EnumOptions_msginit = {
  2404. &google_protobuf_EnumOptions_submsgs[0],
  2405. &google_protobuf_EnumOptions__fields[0],
  2406. UPB_SIZE(8, 16), 3, false,
  2407. };
  2408. static const upb_msglayout *const google_protobuf_EnumValueOptions_submsgs[1] = {
  2409. &google_protobuf_UninterpretedOption_msginit,
  2410. };
  2411. static const upb_msglayout_field google_protobuf_EnumValueOptions__fields[2] = {
  2412. {1, UPB_SIZE(1, 1), 1, 0, 8, 1},
  2413. {999, UPB_SIZE(4, 8), 0, 0, 11, 3},
  2414. };
  2415. const upb_msglayout google_protobuf_EnumValueOptions_msginit = {
  2416. &google_protobuf_EnumValueOptions_submsgs[0],
  2417. &google_protobuf_EnumValueOptions__fields[0],
  2418. UPB_SIZE(8, 16), 2, false,
  2419. };
  2420. static const upb_msglayout *const google_protobuf_ServiceOptions_submsgs[1] = {
  2421. &google_protobuf_UninterpretedOption_msginit,
  2422. };
  2423. static const upb_msglayout_field google_protobuf_ServiceOptions__fields[2] = {
  2424. {33, UPB_SIZE(1, 1), 1, 0, 8, 1},
  2425. {999, UPB_SIZE(4, 8), 0, 0, 11, 3},
  2426. };
  2427. const upb_msglayout google_protobuf_ServiceOptions_msginit = {
  2428. &google_protobuf_ServiceOptions_submsgs[0],
  2429. &google_protobuf_ServiceOptions__fields[0],
  2430. UPB_SIZE(8, 16), 2, false,
  2431. };
  2432. static const upb_msglayout *const google_protobuf_MethodOptions_submsgs[1] = {
  2433. &google_protobuf_UninterpretedOption_msginit,
  2434. };
  2435. static const upb_msglayout_field google_protobuf_MethodOptions__fields[3] = {
  2436. {33, UPB_SIZE(16, 16), 2, 0, 8, 1},
  2437. {34, UPB_SIZE(8, 8), 1, 0, 14, 1},
  2438. {999, UPB_SIZE(20, 24), 0, 0, 11, 3},
  2439. };
  2440. const upb_msglayout google_protobuf_MethodOptions_msginit = {
  2441. &google_protobuf_MethodOptions_submsgs[0],
  2442. &google_protobuf_MethodOptions__fields[0],
  2443. UPB_SIZE(24, 32), 3, false,
  2444. };
  2445. static const upb_msglayout *const google_protobuf_UninterpretedOption_submsgs[1] = {
  2446. &google_protobuf_UninterpretedOption_NamePart_msginit,
  2447. };
  2448. static const upb_msglayout_field google_protobuf_UninterpretedOption__fields[7] = {
  2449. {2, UPB_SIZE(56, 80), 0, 0, 11, 3},
  2450. {3, UPB_SIZE(32, 32), 4, 0, 9, 1},
  2451. {4, UPB_SIZE(8, 8), 1, 0, 4, 1},
  2452. {5, UPB_SIZE(16, 16), 2, 0, 3, 1},
  2453. {6, UPB_SIZE(24, 24), 3, 0, 1, 1},
  2454. {7, UPB_SIZE(40, 48), 5, 0, 12, 1},
  2455. {8, UPB_SIZE(48, 64), 6, 0, 9, 1},
  2456. };
  2457. const upb_msglayout google_protobuf_UninterpretedOption_msginit = {
  2458. &google_protobuf_UninterpretedOption_submsgs[0],
  2459. &google_protobuf_UninterpretedOption__fields[0],
  2460. UPB_SIZE(64, 96), 7, false,
  2461. };
  2462. static const upb_msglayout_field google_protobuf_UninterpretedOption_NamePart__fields[2] = {
  2463. {1, UPB_SIZE(4, 8), 2, 0, 9, 2},
  2464. {2, UPB_SIZE(1, 1), 1, 0, 8, 2},
  2465. };
  2466. const upb_msglayout google_protobuf_UninterpretedOption_NamePart_msginit = {
  2467. NULL,
  2468. &google_protobuf_UninterpretedOption_NamePart__fields[0],
  2469. UPB_SIZE(16, 32), 2, false,
  2470. };
  2471. static const upb_msglayout *const google_protobuf_SourceCodeInfo_submsgs[1] = {
  2472. &google_protobuf_SourceCodeInfo_Location_msginit,
  2473. };
  2474. static const upb_msglayout_field google_protobuf_SourceCodeInfo__fields[1] = {
  2475. {1, UPB_SIZE(0, 0), 0, 0, 11, 3},
  2476. };
  2477. const upb_msglayout google_protobuf_SourceCodeInfo_msginit = {
  2478. &google_protobuf_SourceCodeInfo_submsgs[0],
  2479. &google_protobuf_SourceCodeInfo__fields[0],
  2480. UPB_SIZE(4, 8), 1, false,
  2481. };
  2482. static const upb_msglayout_field google_protobuf_SourceCodeInfo_Location__fields[5] = {
  2483. {1, UPB_SIZE(20, 40), 0, 0, 5, _UPB_LABEL_PACKED},
  2484. {2, UPB_SIZE(24, 48), 0, 0, 5, _UPB_LABEL_PACKED},
  2485. {3, UPB_SIZE(4, 8), 1, 0, 9, 1},
  2486. {4, UPB_SIZE(12, 24), 2, 0, 9, 1},
  2487. {6, UPB_SIZE(28, 56), 0, 0, 9, 3},
  2488. };
  2489. const upb_msglayout google_protobuf_SourceCodeInfo_Location_msginit = {
  2490. NULL,
  2491. &google_protobuf_SourceCodeInfo_Location__fields[0],
  2492. UPB_SIZE(32, 64), 5, false,
  2493. };
  2494. static const upb_msglayout *const google_protobuf_GeneratedCodeInfo_submsgs[1] = {
  2495. &google_protobuf_GeneratedCodeInfo_Annotation_msginit,
  2496. };
  2497. static const upb_msglayout_field google_protobuf_GeneratedCodeInfo__fields[1] = {
  2498. {1, UPB_SIZE(0, 0), 0, 0, 11, 3},
  2499. };
  2500. const upb_msglayout google_protobuf_GeneratedCodeInfo_msginit = {
  2501. &google_protobuf_GeneratedCodeInfo_submsgs[0],
  2502. &google_protobuf_GeneratedCodeInfo__fields[0],
  2503. UPB_SIZE(4, 8), 1, false,
  2504. };
  2505. static const upb_msglayout_field google_protobuf_GeneratedCodeInfo_Annotation__fields[4] = {
  2506. {1, UPB_SIZE(20, 32), 0, 0, 5, _UPB_LABEL_PACKED},
  2507. {2, UPB_SIZE(12, 16), 3, 0, 9, 1},
  2508. {3, UPB_SIZE(4, 4), 1, 0, 5, 1},
  2509. {4, UPB_SIZE(8, 8), 2, 0, 5, 1},
  2510. };
  2511. const upb_msglayout google_protobuf_GeneratedCodeInfo_Annotation_msginit = {
  2512. NULL,
  2513. &google_protobuf_GeneratedCodeInfo_Annotation__fields[0],
  2514. UPB_SIZE(24, 48), 4, false,
  2515. };
  2516. #include <ctype.h>
  2517. #include <errno.h>
  2518. #include <stdlib.h>
  2519. #include <string.h>
  2520. typedef struct {
  2521. size_t len;
  2522. char str[1]; /* Null-terminated string data follows. */
  2523. } str_t;
  2524. static str_t *newstr(upb_alloc *alloc, const char *data, size_t len) {
  2525. str_t *ret = upb_malloc(alloc, sizeof(*ret) + len);
  2526. if (!ret) return NULL;
  2527. ret->len = len;
  2528. memcpy(ret->str, data, len);
  2529. ret->str[len] = '\0';
  2530. return ret;
  2531. }
  2532. struct upb_fielddef {
  2533. const upb_filedef *file;
  2534. const upb_msgdef *msgdef;
  2535. const char *full_name;
  2536. const char *json_name;
  2537. union {
  2538. int64_t sint;
  2539. uint64_t uint;
  2540. double dbl;
  2541. float flt;
  2542. bool boolean;
  2543. str_t *str;
  2544. } defaultval;
  2545. const upb_oneofdef *oneof;
  2546. union {
  2547. const upb_msgdef *msgdef;
  2548. const upb_enumdef *enumdef;
  2549. const google_protobuf_FieldDescriptorProto *unresolved;
  2550. } sub;
  2551. uint32_t number_;
  2552. uint16_t index_;
  2553. uint16_t layout_index;
  2554. uint32_t selector_base; /* Used to index into a upb::Handlers table. */
  2555. bool is_extension_;
  2556. bool lazy_;
  2557. bool packed_;
  2558. bool proto3_optional_;
  2559. upb_descriptortype_t type_;
  2560. upb_label_t label_;
  2561. };
  2562. struct upb_msgdef {
  2563. const upb_msglayout *layout;
  2564. const upb_filedef *file;
  2565. const char *full_name;
  2566. uint32_t selector_count;
  2567. uint32_t submsg_field_count;
  2568. /* Tables for looking up fields by number and name. */
  2569. upb_inttable itof;
  2570. upb_strtable ntof;
  2571. const upb_fielddef *fields;
  2572. const upb_oneofdef *oneofs;
  2573. int field_count;
  2574. int oneof_count;
  2575. int real_oneof_count;
  2576. /* Is this a map-entry message? */
  2577. bool map_entry;
  2578. upb_wellknowntype_t well_known_type;
  2579. /* TODO(haberman): proper extension ranges (there can be multiple). */
  2580. };
  2581. struct upb_enumdef {
  2582. const upb_filedef *file;
  2583. const char *full_name;
  2584. upb_strtable ntoi;
  2585. upb_inttable iton;
  2586. int32_t defaultval;
  2587. };
  2588. struct upb_oneofdef {
  2589. const upb_msgdef *parent;
  2590. const char *full_name;
  2591. uint32_t index;
  2592. upb_strtable ntof;
  2593. upb_inttable itof;
  2594. };
  2595. struct upb_filedef {
  2596. const char *name;
  2597. const char *package;
  2598. const char *phpprefix;
  2599. const char *phpnamespace;
  2600. upb_syntax_t syntax;
  2601. const upb_filedef **deps;
  2602. const upb_msgdef *msgs;
  2603. const upb_enumdef *enums;
  2604. const upb_fielddef *exts;
  2605. int dep_count;
  2606. int msg_count;
  2607. int enum_count;
  2608. int ext_count;
  2609. };
  2610. struct upb_symtab {
  2611. upb_arena *arena;
  2612. upb_strtable syms; /* full_name -> packed def ptr */
  2613. upb_strtable files; /* file_name -> upb_filedef* */
  2614. };
  2615. /* Inside a symtab we store tagged pointers to specific def types. */
  2616. typedef enum {
  2617. UPB_DEFTYPE_FIELD = 0,
  2618. /* Only inside symtab table. */
  2619. UPB_DEFTYPE_MSG = 1,
  2620. UPB_DEFTYPE_ENUM = 2,
  2621. /* Only inside message table. */
  2622. UPB_DEFTYPE_ONEOF = 1,
  2623. UPB_DEFTYPE_FIELD_JSONNAME = 2
  2624. } upb_deftype_t;
  2625. static const void *unpack_def(upb_value v, upb_deftype_t type) {
  2626. uintptr_t num = (uintptr_t)upb_value_getconstptr(v);
  2627. return (num & 3) == type ? (const void*)(num & ~3) : NULL;
  2628. }
  2629. static upb_value pack_def(const void *ptr, upb_deftype_t type) {
  2630. uintptr_t num = (uintptr_t)ptr | type;
  2631. return upb_value_constptr((const void*)num);
  2632. }
  2633. /* isalpha() etc. from <ctype.h> are locale-dependent, which we don't want. */
  2634. static bool upb_isbetween(char c, char low, char high) {
  2635. return c >= low && c <= high;
  2636. }
  2637. static bool upb_isletter(char c) {
  2638. return upb_isbetween(c, 'A', 'Z') || upb_isbetween(c, 'a', 'z') || c == '_';
  2639. }
  2640. static bool upb_isalphanum(char c) {
  2641. return upb_isletter(c) || upb_isbetween(c, '0', '9');
  2642. }
  2643. static bool upb_isident(upb_strview name, bool full, upb_status *s) {
  2644. const char *str = name.data;
  2645. size_t len = name.size;
  2646. bool start = true;
  2647. size_t i;
  2648. for (i = 0; i < len; i++) {
  2649. char c = str[i];
  2650. if (c == '.') {
  2651. if (start || !full) {
  2652. upb_status_seterrf(s, "invalid name: unexpected '.' (%s)", str);
  2653. return false;
  2654. }
  2655. start = true;
  2656. } else if (start) {
  2657. if (!upb_isletter(c)) {
  2658. upb_status_seterrf(
  2659. s, "invalid name: path components must start with a letter (%s)",
  2660. str);
  2661. return false;
  2662. }
  2663. start = false;
  2664. } else {
  2665. if (!upb_isalphanum(c)) {
  2666. upb_status_seterrf(s, "invalid name: non-alphanumeric character (%s)",
  2667. str);
  2668. return false;
  2669. }
  2670. }
  2671. }
  2672. return !start;
  2673. }
  2674. static const char *shortdefname(const char *fullname) {
  2675. const char *p;
  2676. if (fullname == NULL) {
  2677. return NULL;
  2678. } else if ((p = strrchr(fullname, '.')) == NULL) {
  2679. /* No '.' in the name, return the full string. */
  2680. return fullname;
  2681. } else {
  2682. /* Return one past the last '.'. */
  2683. return p + 1;
  2684. }
  2685. }
  2686. /* All submessage fields are lower than all other fields.
  2687. * Secondly, fields are increasing in order. */
  2688. uint32_t field_rank(const upb_fielddef *f) {
  2689. uint32_t ret = upb_fielddef_number(f);
  2690. const uint32_t high_bit = 1 << 30;
  2691. UPB_ASSERT(ret < high_bit);
  2692. if (!upb_fielddef_issubmsg(f))
  2693. ret |= high_bit;
  2694. return ret;
  2695. }
  2696. int cmp_fields(const void *p1, const void *p2) {
  2697. const upb_fielddef *f1 = *(upb_fielddef*const*)p1;
  2698. const upb_fielddef *f2 = *(upb_fielddef*const*)p2;
  2699. return field_rank(f1) - field_rank(f2);
  2700. }
  2701. /* A few implementation details of handlers. We put these here to avoid
  2702. * a def -> handlers dependency. */
  2703. #define UPB_STATIC_SELECTOR_COUNT 3 /* Warning: also in upb/handlers.h. */
  2704. static uint32_t upb_handlers_selectorbaseoffset(const upb_fielddef *f) {
  2705. return upb_fielddef_isseq(f) ? 2 : 0;
  2706. }
  2707. static uint32_t upb_handlers_selectorcount(const upb_fielddef *f) {
  2708. uint32_t ret = 1;
  2709. if (upb_fielddef_isseq(f)) ret += 2; /* STARTSEQ/ENDSEQ */
  2710. if (upb_fielddef_isstring(f)) ret += 2; /* [STRING]/STARTSTR/ENDSTR */
  2711. if (upb_fielddef_issubmsg(f)) {
  2712. /* ENDSUBMSG (STARTSUBMSG is at table beginning) */
  2713. ret += 0;
  2714. if (upb_fielddef_lazy(f)) {
  2715. /* STARTSTR/ENDSTR/STRING (for lazy) */
  2716. ret += 3;
  2717. }
  2718. }
  2719. return ret;
  2720. }
  2721. static void upb_status_setoom(upb_status *status) {
  2722. upb_status_seterrmsg(status, "out of memory");
  2723. }
  2724. static bool assign_msg_indices(upb_msgdef *m, upb_status *s) {
  2725. /* Sort fields. upb internally relies on UPB_TYPE_MESSAGE fields having the
  2726. * lowest indexes, but we do not publicly guarantee this. */
  2727. upb_msg_field_iter j;
  2728. int i;
  2729. uint32_t selector;
  2730. int n = upb_msgdef_numfields(m);
  2731. upb_fielddef **fields;
  2732. if (n == 0) {
  2733. m->selector_count = UPB_STATIC_SELECTOR_COUNT;
  2734. m->submsg_field_count = 0;
  2735. return true;
  2736. }
  2737. fields = upb_gmalloc(n * sizeof(*fields));
  2738. if (!fields) {
  2739. upb_status_setoom(s);
  2740. return false;
  2741. }
  2742. m->submsg_field_count = 0;
  2743. for(i = 0, upb_msg_field_begin(&j, m);
  2744. !upb_msg_field_done(&j);
  2745. upb_msg_field_next(&j), i++) {
  2746. upb_fielddef *f = upb_msg_iter_field(&j);
  2747. UPB_ASSERT(f->msgdef == m);
  2748. if (upb_fielddef_issubmsg(f)) {
  2749. m->submsg_field_count++;
  2750. }
  2751. fields[i] = f;
  2752. }
  2753. qsort(fields, n, sizeof(*fields), cmp_fields);
  2754. selector = UPB_STATIC_SELECTOR_COUNT + m->submsg_field_count;
  2755. for (i = 0; i < n; i++) {
  2756. upb_fielddef *f = fields[i];
  2757. f->index_ = i;
  2758. f->selector_base = selector + upb_handlers_selectorbaseoffset(f);
  2759. selector += upb_handlers_selectorcount(f);
  2760. }
  2761. m->selector_count = selector;
  2762. upb_gfree(fields);
  2763. return true;
  2764. }
  2765. static bool check_oneofs(upb_msgdef *m, upb_status *s) {
  2766. int i;
  2767. int first_synthetic = -1;
  2768. upb_oneofdef *mutable_oneofs = (upb_oneofdef*)m->oneofs;
  2769. for (i = 0; i < m->oneof_count; i++) {
  2770. mutable_oneofs[i].index = i;
  2771. if (upb_oneofdef_issynthetic(&mutable_oneofs[i])) {
  2772. if (first_synthetic == -1) {
  2773. first_synthetic = i;
  2774. }
  2775. } else {
  2776. if (first_synthetic != -1) {
  2777. upb_status_seterrf(
  2778. s, "Synthetic oneofs must be after all other oneofs: %s",
  2779. upb_oneofdef_name(&mutable_oneofs[i]));
  2780. return false;
  2781. }
  2782. }
  2783. }
  2784. if (first_synthetic == -1) {
  2785. m->real_oneof_count = m->oneof_count;
  2786. } else {
  2787. m->real_oneof_count = first_synthetic;
  2788. }
  2789. return true;
  2790. }
  2791. static void assign_msg_wellknowntype(upb_msgdef *m) {
  2792. const char *name = upb_msgdef_fullname(m);
  2793. if (name == NULL) {
  2794. m->well_known_type = UPB_WELLKNOWN_UNSPECIFIED;
  2795. return;
  2796. }
  2797. if (!strcmp(name, "google.protobuf.Any")) {
  2798. m->well_known_type = UPB_WELLKNOWN_ANY;
  2799. } else if (!strcmp(name, "google.protobuf.FieldMask")) {
  2800. m->well_known_type = UPB_WELLKNOWN_FIELDMASK;
  2801. } else if (!strcmp(name, "google.protobuf.Duration")) {
  2802. m->well_known_type = UPB_WELLKNOWN_DURATION;
  2803. } else if (!strcmp(name, "google.protobuf.Timestamp")) {
  2804. m->well_known_type = UPB_WELLKNOWN_TIMESTAMP;
  2805. } else if (!strcmp(name, "google.protobuf.DoubleValue")) {
  2806. m->well_known_type = UPB_WELLKNOWN_DOUBLEVALUE;
  2807. } else if (!strcmp(name, "google.protobuf.FloatValue")) {
  2808. m->well_known_type = UPB_WELLKNOWN_FLOATVALUE;
  2809. } else if (!strcmp(name, "google.protobuf.Int64Value")) {
  2810. m->well_known_type = UPB_WELLKNOWN_INT64VALUE;
  2811. } else if (!strcmp(name, "google.protobuf.UInt64Value")) {
  2812. m->well_known_type = UPB_WELLKNOWN_UINT64VALUE;
  2813. } else if (!strcmp(name, "google.protobuf.Int32Value")) {
  2814. m->well_known_type = UPB_WELLKNOWN_INT32VALUE;
  2815. } else if (!strcmp(name, "google.protobuf.UInt32Value")) {
  2816. m->well_known_type = UPB_WELLKNOWN_UINT32VALUE;
  2817. } else if (!strcmp(name, "google.protobuf.BoolValue")) {
  2818. m->well_known_type = UPB_WELLKNOWN_BOOLVALUE;
  2819. } else if (!strcmp(name, "google.protobuf.StringValue")) {
  2820. m->well_known_type = UPB_WELLKNOWN_STRINGVALUE;
  2821. } else if (!strcmp(name, "google.protobuf.BytesValue")) {
  2822. m->well_known_type = UPB_WELLKNOWN_BYTESVALUE;
  2823. } else if (!strcmp(name, "google.protobuf.Value")) {
  2824. m->well_known_type = UPB_WELLKNOWN_VALUE;
  2825. } else if (!strcmp(name, "google.protobuf.ListValue")) {
  2826. m->well_known_type = UPB_WELLKNOWN_LISTVALUE;
  2827. } else if (!strcmp(name, "google.protobuf.Struct")) {
  2828. m->well_known_type = UPB_WELLKNOWN_STRUCT;
  2829. } else {
  2830. m->well_known_type = UPB_WELLKNOWN_UNSPECIFIED;
  2831. }
  2832. }
  2833. /* upb_enumdef ****************************************************************/
  2834. const char *upb_enumdef_fullname(const upb_enumdef *e) {
  2835. return e->full_name;
  2836. }
  2837. const char *upb_enumdef_name(const upb_enumdef *e) {
  2838. return shortdefname(e->full_name);
  2839. }
  2840. const upb_filedef *upb_enumdef_file(const upb_enumdef *e) {
  2841. return e->file;
  2842. }
  2843. int32_t upb_enumdef_default(const upb_enumdef *e) {
  2844. UPB_ASSERT(upb_enumdef_iton(e, e->defaultval));
  2845. return e->defaultval;
  2846. }
  2847. int upb_enumdef_numvals(const upb_enumdef *e) {
  2848. return (int)upb_strtable_count(&e->ntoi);
  2849. }
  2850. void upb_enum_begin(upb_enum_iter *i, const upb_enumdef *e) {
  2851. /* We iterate over the ntoi table, to account for duplicate numbers. */
  2852. upb_strtable_begin(i, &e->ntoi);
  2853. }
  2854. void upb_enum_next(upb_enum_iter *iter) { upb_strtable_next(iter); }
  2855. bool upb_enum_done(upb_enum_iter *iter) { return upb_strtable_done(iter); }
  2856. bool upb_enumdef_ntoi(const upb_enumdef *def, const char *name,
  2857. size_t len, int32_t *num) {
  2858. upb_value v;
  2859. if (!upb_strtable_lookup2(&def->ntoi, name, len, &v)) {
  2860. return false;
  2861. }
  2862. if (num) *num = upb_value_getint32(v);
  2863. return true;
  2864. }
  2865. const char *upb_enumdef_iton(const upb_enumdef *def, int32_t num) {
  2866. upb_value v;
  2867. return upb_inttable_lookup32(&def->iton, num, &v) ?
  2868. upb_value_getcstr(v) : NULL;
  2869. }
  2870. const char *upb_enum_iter_name(upb_enum_iter *iter) {
  2871. return upb_strtable_iter_key(iter).data;
  2872. }
  2873. int32_t upb_enum_iter_number(upb_enum_iter *iter) {
  2874. return upb_value_getint32(upb_strtable_iter_value(iter));
  2875. }
  2876. /* upb_fielddef ***************************************************************/
  2877. const char *upb_fielddef_fullname(const upb_fielddef *f) {
  2878. return f->full_name;
  2879. }
  2880. upb_fieldtype_t upb_fielddef_type(const upb_fielddef *f) {
  2881. switch (f->type_) {
  2882. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  2883. return UPB_TYPE_DOUBLE;
  2884. case UPB_DESCRIPTOR_TYPE_FLOAT:
  2885. return UPB_TYPE_FLOAT;
  2886. case UPB_DESCRIPTOR_TYPE_INT64:
  2887. case UPB_DESCRIPTOR_TYPE_SINT64:
  2888. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  2889. return UPB_TYPE_INT64;
  2890. case UPB_DESCRIPTOR_TYPE_INT32:
  2891. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  2892. case UPB_DESCRIPTOR_TYPE_SINT32:
  2893. return UPB_TYPE_INT32;
  2894. case UPB_DESCRIPTOR_TYPE_UINT64:
  2895. case UPB_DESCRIPTOR_TYPE_FIXED64:
  2896. return UPB_TYPE_UINT64;
  2897. case UPB_DESCRIPTOR_TYPE_UINT32:
  2898. case UPB_DESCRIPTOR_TYPE_FIXED32:
  2899. return UPB_TYPE_UINT32;
  2900. case UPB_DESCRIPTOR_TYPE_ENUM:
  2901. return UPB_TYPE_ENUM;
  2902. case UPB_DESCRIPTOR_TYPE_BOOL:
  2903. return UPB_TYPE_BOOL;
  2904. case UPB_DESCRIPTOR_TYPE_STRING:
  2905. return UPB_TYPE_STRING;
  2906. case UPB_DESCRIPTOR_TYPE_BYTES:
  2907. return UPB_TYPE_BYTES;
  2908. case UPB_DESCRIPTOR_TYPE_GROUP:
  2909. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  2910. return UPB_TYPE_MESSAGE;
  2911. }
  2912. UPB_UNREACHABLE();
  2913. }
  2914. upb_descriptortype_t upb_fielddef_descriptortype(const upb_fielddef *f) {
  2915. return f->type_;
  2916. }
  2917. uint32_t upb_fielddef_index(const upb_fielddef *f) {
  2918. return f->index_;
  2919. }
  2920. upb_label_t upb_fielddef_label(const upb_fielddef *f) {
  2921. return f->label_;
  2922. }
  2923. uint32_t upb_fielddef_number(const upb_fielddef *f) {
  2924. return f->number_;
  2925. }
  2926. bool upb_fielddef_isextension(const upb_fielddef *f) {
  2927. return f->is_extension_;
  2928. }
  2929. bool upb_fielddef_lazy(const upb_fielddef *f) {
  2930. return f->lazy_;
  2931. }
  2932. bool upb_fielddef_packed(const upb_fielddef *f) {
  2933. return f->packed_;
  2934. }
  2935. const char *upb_fielddef_name(const upb_fielddef *f) {
  2936. return shortdefname(f->full_name);
  2937. }
  2938. const char *upb_fielddef_jsonname(const upb_fielddef *f) {
  2939. return f->json_name;
  2940. }
  2941. uint32_t upb_fielddef_selectorbase(const upb_fielddef *f) {
  2942. return f->selector_base;
  2943. }
  2944. const upb_filedef *upb_fielddef_file(const upb_fielddef *f) {
  2945. return f->file;
  2946. }
  2947. const upb_msgdef *upb_fielddef_containingtype(const upb_fielddef *f) {
  2948. return f->msgdef;
  2949. }
  2950. const upb_oneofdef *upb_fielddef_containingoneof(const upb_fielddef *f) {
  2951. return f->oneof;
  2952. }
  2953. const upb_oneofdef *upb_fielddef_realcontainingoneof(const upb_fielddef *f) {
  2954. if (!f->oneof || upb_oneofdef_issynthetic(f->oneof)) return NULL;
  2955. return f->oneof;
  2956. }
  2957. static void chkdefaulttype(const upb_fielddef *f, int ctype) {
  2958. UPB_UNUSED(f);
  2959. UPB_UNUSED(ctype);
  2960. }
  2961. int64_t upb_fielddef_defaultint64(const upb_fielddef *f) {
  2962. chkdefaulttype(f, UPB_TYPE_INT64);
  2963. return f->defaultval.sint;
  2964. }
  2965. int32_t upb_fielddef_defaultint32(const upb_fielddef *f) {
  2966. chkdefaulttype(f, UPB_TYPE_INT32);
  2967. return (int32_t)f->defaultval.sint;
  2968. }
  2969. uint64_t upb_fielddef_defaultuint64(const upb_fielddef *f) {
  2970. chkdefaulttype(f, UPB_TYPE_UINT64);
  2971. return f->defaultval.uint;
  2972. }
  2973. uint32_t upb_fielddef_defaultuint32(const upb_fielddef *f) {
  2974. chkdefaulttype(f, UPB_TYPE_UINT32);
  2975. return (uint32_t)f->defaultval.uint;
  2976. }
  2977. bool upb_fielddef_defaultbool(const upb_fielddef *f) {
  2978. chkdefaulttype(f, UPB_TYPE_BOOL);
  2979. return f->defaultval.boolean;
  2980. }
  2981. float upb_fielddef_defaultfloat(const upb_fielddef *f) {
  2982. chkdefaulttype(f, UPB_TYPE_FLOAT);
  2983. return f->defaultval.flt;
  2984. }
  2985. double upb_fielddef_defaultdouble(const upb_fielddef *f) {
  2986. chkdefaulttype(f, UPB_TYPE_DOUBLE);
  2987. return f->defaultval.dbl;
  2988. }
  2989. const char *upb_fielddef_defaultstr(const upb_fielddef *f, size_t *len) {
  2990. str_t *str = f->defaultval.str;
  2991. UPB_ASSERT(upb_fielddef_type(f) == UPB_TYPE_STRING ||
  2992. upb_fielddef_type(f) == UPB_TYPE_BYTES ||
  2993. upb_fielddef_type(f) == UPB_TYPE_ENUM);
  2994. if (str) {
  2995. if (len) *len = str->len;
  2996. return str->str;
  2997. } else {
  2998. if (len) *len = 0;
  2999. return NULL;
  3000. }
  3001. }
  3002. const upb_msgdef *upb_fielddef_msgsubdef(const upb_fielddef *f) {
  3003. UPB_ASSERT(upb_fielddef_type(f) == UPB_TYPE_MESSAGE);
  3004. return f->sub.msgdef;
  3005. }
  3006. const upb_enumdef *upb_fielddef_enumsubdef(const upb_fielddef *f) {
  3007. UPB_ASSERT(upb_fielddef_type(f) == UPB_TYPE_ENUM);
  3008. return f->sub.enumdef;
  3009. }
  3010. const upb_msglayout_field *upb_fielddef_layout(const upb_fielddef *f) {
  3011. return &f->msgdef->layout->fields[f->layout_index];
  3012. }
  3013. bool upb_fielddef_issubmsg(const upb_fielddef *f) {
  3014. return upb_fielddef_type(f) == UPB_TYPE_MESSAGE;
  3015. }
  3016. bool upb_fielddef_isstring(const upb_fielddef *f) {
  3017. return upb_fielddef_type(f) == UPB_TYPE_STRING ||
  3018. upb_fielddef_type(f) == UPB_TYPE_BYTES;
  3019. }
  3020. bool upb_fielddef_isseq(const upb_fielddef *f) {
  3021. return upb_fielddef_label(f) == UPB_LABEL_REPEATED;
  3022. }
  3023. bool upb_fielddef_isprimitive(const upb_fielddef *f) {
  3024. return !upb_fielddef_isstring(f) && !upb_fielddef_issubmsg(f);
  3025. }
  3026. bool upb_fielddef_ismap(const upb_fielddef *f) {
  3027. return upb_fielddef_isseq(f) && upb_fielddef_issubmsg(f) &&
  3028. upb_msgdef_mapentry(upb_fielddef_msgsubdef(f));
  3029. }
  3030. bool upb_fielddef_hassubdef(const upb_fielddef *f) {
  3031. return upb_fielddef_issubmsg(f) || upb_fielddef_type(f) == UPB_TYPE_ENUM;
  3032. }
  3033. bool upb_fielddef_haspresence(const upb_fielddef *f) {
  3034. if (upb_fielddef_isseq(f)) return false;
  3035. return upb_fielddef_issubmsg(f) || upb_fielddef_containingoneof(f) ||
  3036. f->file->syntax == UPB_SYNTAX_PROTO2;
  3037. }
  3038. static bool between(int32_t x, int32_t low, int32_t high) {
  3039. return x >= low && x <= high;
  3040. }
  3041. bool upb_fielddef_checklabel(int32_t label) { return between(label, 1, 3); }
  3042. bool upb_fielddef_checktype(int32_t type) { return between(type, 1, 11); }
  3043. bool upb_fielddef_checkintfmt(int32_t fmt) { return between(fmt, 1, 3); }
  3044. bool upb_fielddef_checkdescriptortype(int32_t type) {
  3045. return between(type, 1, 18);
  3046. }
  3047. /* upb_msgdef *****************************************************************/
  3048. const char *upb_msgdef_fullname(const upb_msgdef *m) {
  3049. return m->full_name;
  3050. }
  3051. const upb_filedef *upb_msgdef_file(const upb_msgdef *m) {
  3052. return m->file;
  3053. }
  3054. const char *upb_msgdef_name(const upb_msgdef *m) {
  3055. return shortdefname(m->full_name);
  3056. }
  3057. upb_syntax_t upb_msgdef_syntax(const upb_msgdef *m) {
  3058. return m->file->syntax;
  3059. }
  3060. size_t upb_msgdef_selectorcount(const upb_msgdef *m) {
  3061. return m->selector_count;
  3062. }
  3063. uint32_t upb_msgdef_submsgfieldcount(const upb_msgdef *m) {
  3064. return m->submsg_field_count;
  3065. }
  3066. const upb_fielddef *upb_msgdef_itof(const upb_msgdef *m, uint32_t i) {
  3067. upb_value val;
  3068. return upb_inttable_lookup32(&m->itof, i, &val) ?
  3069. upb_value_getconstptr(val) : NULL;
  3070. }
  3071. const upb_fielddef *upb_msgdef_ntof(const upb_msgdef *m, const char *name,
  3072. size_t len) {
  3073. upb_value val;
  3074. if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
  3075. return NULL;
  3076. }
  3077. return unpack_def(val, UPB_DEFTYPE_FIELD);
  3078. }
  3079. const upb_oneofdef *upb_msgdef_ntoo(const upb_msgdef *m, const char *name,
  3080. size_t len) {
  3081. upb_value val;
  3082. if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
  3083. return NULL;
  3084. }
  3085. return unpack_def(val, UPB_DEFTYPE_ONEOF);
  3086. }
  3087. bool upb_msgdef_lookupname(const upb_msgdef *m, const char *name, size_t len,
  3088. const upb_fielddef **f, const upb_oneofdef **o) {
  3089. upb_value val;
  3090. if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
  3091. return false;
  3092. }
  3093. *o = unpack_def(val, UPB_DEFTYPE_ONEOF);
  3094. *f = unpack_def(val, UPB_DEFTYPE_FIELD);
  3095. return *o || *f; /* False if this was a JSON name. */
  3096. }
  3097. const upb_fielddef *upb_msgdef_lookupjsonname(const upb_msgdef *m,
  3098. const char *name, size_t len) {
  3099. upb_value val;
  3100. const upb_fielddef* f;
  3101. if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
  3102. return NULL;
  3103. }
  3104. f = unpack_def(val, UPB_DEFTYPE_FIELD);
  3105. if (!f) f = unpack_def(val, UPB_DEFTYPE_FIELD_JSONNAME);
  3106. return f;
  3107. }
  3108. int upb_msgdef_numfields(const upb_msgdef *m) {
  3109. return m->field_count;
  3110. }
  3111. int upb_msgdef_numoneofs(const upb_msgdef *m) {
  3112. return m->oneof_count;
  3113. }
  3114. int upb_msgdef_numrealoneofs(const upb_msgdef *m) {
  3115. return m->real_oneof_count;
  3116. }
  3117. const upb_msglayout *upb_msgdef_layout(const upb_msgdef *m) {
  3118. return m->layout;
  3119. }
  3120. const upb_fielddef *_upb_msgdef_field(const upb_msgdef *m, int i) {
  3121. if (i >= m->field_count) return NULL;
  3122. return &m->fields[i];
  3123. }
  3124. bool upb_msgdef_mapentry(const upb_msgdef *m) {
  3125. return m->map_entry;
  3126. }
  3127. upb_wellknowntype_t upb_msgdef_wellknowntype(const upb_msgdef *m) {
  3128. return m->well_known_type;
  3129. }
  3130. bool upb_msgdef_isnumberwrapper(const upb_msgdef *m) {
  3131. upb_wellknowntype_t type = upb_msgdef_wellknowntype(m);
  3132. return type >= UPB_WELLKNOWN_DOUBLEVALUE &&
  3133. type <= UPB_WELLKNOWN_UINT32VALUE;
  3134. }
  3135. void upb_msg_field_begin(upb_msg_field_iter *iter, const upb_msgdef *m) {
  3136. upb_inttable_begin(iter, &m->itof);
  3137. }
  3138. void upb_msg_field_next(upb_msg_field_iter *iter) { upb_inttable_next(iter); }
  3139. bool upb_msg_field_done(const upb_msg_field_iter *iter) {
  3140. return upb_inttable_done(iter);
  3141. }
  3142. upb_fielddef *upb_msg_iter_field(const upb_msg_field_iter *iter) {
  3143. return (upb_fielddef *)upb_value_getconstptr(upb_inttable_iter_value(iter));
  3144. }
  3145. void upb_msg_field_iter_setdone(upb_msg_field_iter *iter) {
  3146. upb_inttable_iter_setdone(iter);
  3147. }
  3148. bool upb_msg_field_iter_isequal(const upb_msg_field_iter * iter1,
  3149. const upb_msg_field_iter * iter2) {
  3150. return upb_inttable_iter_isequal(iter1, iter2);
  3151. }
  3152. void upb_msg_oneof_begin(upb_msg_oneof_iter *iter, const upb_msgdef *m) {
  3153. upb_strtable_begin(iter, &m->ntof);
  3154. /* We need to skip past any initial fields. */
  3155. while (!upb_strtable_done(iter) &&
  3156. !unpack_def(upb_strtable_iter_value(iter), UPB_DEFTYPE_ONEOF)) {
  3157. upb_strtable_next(iter);
  3158. }
  3159. }
  3160. void upb_msg_oneof_next(upb_msg_oneof_iter *iter) {
  3161. /* We need to skip past fields to return only oneofs. */
  3162. do {
  3163. upb_strtable_next(iter);
  3164. } while (!upb_strtable_done(iter) &&
  3165. !unpack_def(upb_strtable_iter_value(iter), UPB_DEFTYPE_ONEOF));
  3166. }
  3167. bool upb_msg_oneof_done(const upb_msg_oneof_iter *iter) {
  3168. return upb_strtable_done(iter);
  3169. }
  3170. const upb_oneofdef *upb_msg_iter_oneof(const upb_msg_oneof_iter *iter) {
  3171. return unpack_def(upb_strtable_iter_value(iter), UPB_DEFTYPE_ONEOF);
  3172. }
  3173. void upb_msg_oneof_iter_setdone(upb_msg_oneof_iter *iter) {
  3174. upb_strtable_iter_setdone(iter);
  3175. }
  3176. bool upb_msg_oneof_iter_isequal(const upb_msg_oneof_iter *iter1,
  3177. const upb_msg_oneof_iter *iter2) {
  3178. return upb_strtable_iter_isequal(iter1, iter2);
  3179. }
  3180. /* upb_oneofdef ***************************************************************/
  3181. const char *upb_oneofdef_name(const upb_oneofdef *o) {
  3182. return shortdefname(o->full_name);
  3183. }
  3184. const upb_msgdef *upb_oneofdef_containingtype(const upb_oneofdef *o) {
  3185. return o->parent;
  3186. }
  3187. int upb_oneofdef_numfields(const upb_oneofdef *o) {
  3188. return (int)upb_strtable_count(&o->ntof);
  3189. }
  3190. uint32_t upb_oneofdef_index(const upb_oneofdef *o) {
  3191. return o->index;
  3192. }
  3193. bool upb_oneofdef_issynthetic(const upb_oneofdef *o) {
  3194. upb_inttable_iter iter;
  3195. const upb_fielddef *f;
  3196. upb_inttable_begin(&iter, &o->itof);
  3197. if (upb_oneofdef_numfields(o) != 1) return false;
  3198. f = upb_value_getptr(upb_inttable_iter_value(&iter));
  3199. UPB_ASSERT(f);
  3200. return f->proto3_optional_;
  3201. }
  3202. const upb_fielddef *upb_oneofdef_ntof(const upb_oneofdef *o,
  3203. const char *name, size_t length) {
  3204. upb_value val;
  3205. return upb_strtable_lookup2(&o->ntof, name, length, &val) ?
  3206. upb_value_getptr(val) : NULL;
  3207. }
  3208. const upb_fielddef *upb_oneofdef_itof(const upb_oneofdef *o, uint32_t num) {
  3209. upb_value val;
  3210. return upb_inttable_lookup32(&o->itof, num, &val) ?
  3211. upb_value_getptr(val) : NULL;
  3212. }
  3213. void upb_oneof_begin(upb_oneof_iter *iter, const upb_oneofdef *o) {
  3214. upb_inttable_begin(iter, &o->itof);
  3215. }
  3216. void upb_oneof_next(upb_oneof_iter *iter) {
  3217. upb_inttable_next(iter);
  3218. }
  3219. bool upb_oneof_done(upb_oneof_iter *iter) {
  3220. return upb_inttable_done(iter);
  3221. }
  3222. upb_fielddef *upb_oneof_iter_field(const upb_oneof_iter *iter) {
  3223. return (upb_fielddef *)upb_value_getconstptr(upb_inttable_iter_value(iter));
  3224. }
  3225. void upb_oneof_iter_setdone(upb_oneof_iter *iter) {
  3226. upb_inttable_iter_setdone(iter);
  3227. }
  3228. /* Dynamic Layout Generation. *************************************************/
  3229. static bool is_power_of_two(size_t val) {
  3230. return (val & (val - 1)) == 0;
  3231. }
  3232. /* Align up to the given power of 2. */
  3233. static size_t align_up(size_t val, size_t align) {
  3234. UPB_ASSERT(is_power_of_two(align));
  3235. return (val + align - 1) & ~(align - 1);
  3236. }
  3237. static size_t div_round_up(size_t n, size_t d) {
  3238. return (n + d - 1) / d;
  3239. }
  3240. static size_t upb_msgval_sizeof(upb_fieldtype_t type) {
  3241. switch (type) {
  3242. case UPB_TYPE_DOUBLE:
  3243. case UPB_TYPE_INT64:
  3244. case UPB_TYPE_UINT64:
  3245. return 8;
  3246. case UPB_TYPE_ENUM:
  3247. case UPB_TYPE_INT32:
  3248. case UPB_TYPE_UINT32:
  3249. case UPB_TYPE_FLOAT:
  3250. return 4;
  3251. case UPB_TYPE_BOOL:
  3252. return 1;
  3253. case UPB_TYPE_MESSAGE:
  3254. return sizeof(void*);
  3255. case UPB_TYPE_BYTES:
  3256. case UPB_TYPE_STRING:
  3257. return sizeof(upb_strview);
  3258. }
  3259. UPB_UNREACHABLE();
  3260. }
  3261. static uint8_t upb_msg_fielddefsize(const upb_fielddef *f) {
  3262. if (upb_msgdef_mapentry(upb_fielddef_containingtype(f))) {
  3263. upb_map_entry ent;
  3264. UPB_ASSERT(sizeof(ent.k) == sizeof(ent.v));
  3265. return sizeof(ent.k);
  3266. } else if (upb_fielddef_isseq(f)) {
  3267. return sizeof(void*);
  3268. } else {
  3269. return upb_msgval_sizeof(upb_fielddef_type(f));
  3270. }
  3271. }
  3272. static uint32_t upb_msglayout_place(upb_msglayout *l, size_t size) {
  3273. uint32_t ret;
  3274. l->size = align_up(l->size, size);
  3275. ret = l->size;
  3276. l->size += size;
  3277. return ret;
  3278. }
  3279. /* This function is the dynamic equivalent of message_layout.{cc,h} in upbc.
  3280. * It computes a dynamic layout for all of the fields in |m|. */
  3281. static bool make_layout(const upb_symtab *symtab, const upb_msgdef *m) {
  3282. upb_msglayout *l = (upb_msglayout*)m->layout;
  3283. upb_msg_field_iter it;
  3284. upb_msg_oneof_iter oit;
  3285. size_t hasbit;
  3286. size_t submsg_count = m->submsg_field_count;
  3287. const upb_msglayout **submsgs;
  3288. upb_msglayout_field *fields;
  3289. upb_alloc *alloc = upb_arena_alloc(symtab->arena);
  3290. memset(l, 0, sizeof(*l));
  3291. fields = upb_malloc(alloc, upb_msgdef_numfields(m) * sizeof(*fields));
  3292. submsgs = upb_malloc(alloc, submsg_count * sizeof(*submsgs));
  3293. if ((!fields && upb_msgdef_numfields(m)) ||
  3294. (!submsgs && submsg_count)) {
  3295. /* OOM. */
  3296. return false;
  3297. }
  3298. l->field_count = upb_msgdef_numfields(m);
  3299. l->fields = fields;
  3300. l->submsgs = submsgs;
  3301. if (upb_msgdef_mapentry(m)) {
  3302. /* TODO(haberman): refactor this method so this special case is more
  3303. * elegant. */
  3304. const upb_fielddef *key = upb_msgdef_itof(m, 1);
  3305. const upb_fielddef *val = upb_msgdef_itof(m, 2);
  3306. fields[0].number = 1;
  3307. fields[1].number = 2;
  3308. fields[0].label = UPB_LABEL_OPTIONAL;
  3309. fields[1].label = UPB_LABEL_OPTIONAL;
  3310. fields[0].presence = 0;
  3311. fields[1].presence = 0;
  3312. fields[0].descriptortype = upb_fielddef_descriptortype(key);
  3313. fields[1].descriptortype = upb_fielddef_descriptortype(val);
  3314. fields[0].offset = 0;
  3315. fields[1].offset = sizeof(upb_strview);
  3316. fields[1].submsg_index = 0;
  3317. if (upb_fielddef_type(val) == UPB_TYPE_MESSAGE) {
  3318. submsgs[0] = upb_fielddef_msgsubdef(val)->layout;
  3319. }
  3320. l->field_count = 2;
  3321. l->size = 2 * sizeof(upb_strview);align_up(l->size, 8);
  3322. return true;
  3323. }
  3324. /* Allocate data offsets in three stages:
  3325. *
  3326. * 1. hasbits.
  3327. * 2. regular fields.
  3328. * 3. oneof fields.
  3329. *
  3330. * OPT: There is a lot of room for optimization here to minimize the size.
  3331. */
  3332. /* Allocate hasbits and set basic field attributes. */
  3333. submsg_count = 0;
  3334. for (upb_msg_field_begin(&it, m), hasbit = 0;
  3335. !upb_msg_field_done(&it);
  3336. upb_msg_field_next(&it)) {
  3337. upb_fielddef* f = upb_msg_iter_field(&it);
  3338. upb_msglayout_field *field = &fields[upb_fielddef_index(f)];
  3339. field->number = upb_fielddef_number(f);
  3340. field->descriptortype = upb_fielddef_descriptortype(f);
  3341. field->label = upb_fielddef_label(f);
  3342. if (upb_fielddef_ismap(f)) {
  3343. field->label = _UPB_LABEL_MAP;
  3344. } else if (upb_fielddef_packed(f)) {
  3345. field->label = _UPB_LABEL_PACKED;
  3346. }
  3347. /* TODO: we probably should sort the fields by field number to match the
  3348. * output of upbc, and to improve search speed for the table parser. */
  3349. f->layout_index = f->index_;
  3350. if (upb_fielddef_issubmsg(f)) {
  3351. const upb_msgdef *subm = upb_fielddef_msgsubdef(f);
  3352. field->submsg_index = submsg_count++;
  3353. submsgs[field->submsg_index] = subm->layout;
  3354. }
  3355. if (upb_fielddef_haspresence(f) && !upb_fielddef_realcontainingoneof(f)) {
  3356. /* We don't use hasbit 0, so that 0 can indicate "no presence" in the
  3357. * table. This wastes one hasbit, but we don't worry about it for now. */
  3358. field->presence = ++hasbit;
  3359. } else {
  3360. field->presence = 0;
  3361. }
  3362. }
  3363. /* Account for space used by hasbits. */
  3364. l->size = div_round_up(hasbit, 8);
  3365. /* Allocate non-oneof fields. */
  3366. for (upb_msg_field_begin(&it, m); !upb_msg_field_done(&it);
  3367. upb_msg_field_next(&it)) {
  3368. const upb_fielddef* f = upb_msg_iter_field(&it);
  3369. size_t field_size = upb_msg_fielddefsize(f);
  3370. size_t index = upb_fielddef_index(f);
  3371. if (upb_fielddef_realcontainingoneof(f)) {
  3372. /* Oneofs are handled separately below. */
  3373. continue;
  3374. }
  3375. fields[index].offset = upb_msglayout_place(l, field_size);
  3376. }
  3377. /* Allocate oneof fields. Each oneof field consists of a uint32 for the case
  3378. * and space for the actual data. */
  3379. for (upb_msg_oneof_begin(&oit, m); !upb_msg_oneof_done(&oit);
  3380. upb_msg_oneof_next(&oit)) {
  3381. const upb_oneofdef* o = upb_msg_iter_oneof(&oit);
  3382. upb_oneof_iter fit;
  3383. if (upb_oneofdef_issynthetic(o)) continue;
  3384. size_t case_size = sizeof(uint32_t); /* Could potentially optimize this. */
  3385. size_t field_size = 0;
  3386. uint32_t case_offset;
  3387. uint32_t data_offset;
  3388. /* Calculate field size: the max of all field sizes. */
  3389. for (upb_oneof_begin(&fit, o);
  3390. !upb_oneof_done(&fit);
  3391. upb_oneof_next(&fit)) {
  3392. const upb_fielddef* f = upb_oneof_iter_field(&fit);
  3393. field_size = UPB_MAX(field_size, upb_msg_fielddefsize(f));
  3394. }
  3395. /* Align and allocate case offset. */
  3396. case_offset = upb_msglayout_place(l, case_size);
  3397. data_offset = upb_msglayout_place(l, field_size);
  3398. for (upb_oneof_begin(&fit, o);
  3399. !upb_oneof_done(&fit);
  3400. upb_oneof_next(&fit)) {
  3401. const upb_fielddef* f = upb_oneof_iter_field(&fit);
  3402. fields[upb_fielddef_index(f)].offset = data_offset;
  3403. fields[upb_fielddef_index(f)].presence = ~case_offset;
  3404. }
  3405. }
  3406. /* Size of the entire structure should be a multiple of its greatest
  3407. * alignment. TODO: track overall alignment for real? */
  3408. l->size = align_up(l->size, 8);
  3409. return true;
  3410. }
  3411. /* Code to build defs from descriptor protos. *********************************/
  3412. /* There is a question of how much validation to do here. It will be difficult
  3413. * to perfectly match the amount of validation performed by proto2. But since
  3414. * this code is used to directly build defs from Ruby (for example) we do need
  3415. * to validate important constraints like uniqueness of names and numbers. */
  3416. #define CHK(x) if (!(x)) { return false; }
  3417. #define CHK_OOM(x) if (!(x)) { upb_status_setoom(ctx->status); return false; }
  3418. typedef struct {
  3419. const upb_symtab *symtab;
  3420. upb_filedef *file; /* File we are building. */
  3421. upb_alloc *alloc; /* Allocate defs here. */
  3422. upb_alloc *tmp; /* Alloc for addtab and any other tmp data. */
  3423. upb_strtable *addtab; /* full_name -> packed def ptr for new defs */
  3424. const upb_msglayout **layouts; /* NULL if we should build layouts. */
  3425. upb_status *status; /* Record errors here. */
  3426. } symtab_addctx;
  3427. static char* strviewdup(const symtab_addctx *ctx, upb_strview view) {
  3428. return upb_strdup2(view.data, view.size, ctx->alloc);
  3429. }
  3430. static bool streql2(const char *a, size_t n, const char *b) {
  3431. return n == strlen(b) && memcmp(a, b, n) == 0;
  3432. }
  3433. static bool streql_view(upb_strview view, const char *b) {
  3434. return streql2(view.data, view.size, b);
  3435. }
  3436. static const char *makefullname(const symtab_addctx *ctx, const char *prefix,
  3437. upb_strview name) {
  3438. if (prefix) {
  3439. /* ret = prefix + '.' + name; */
  3440. size_t n = strlen(prefix);
  3441. char *ret = upb_malloc(ctx->alloc, n + name.size + 2);
  3442. CHK_OOM(ret);
  3443. strcpy(ret, prefix);
  3444. ret[n] = '.';
  3445. memcpy(&ret[n + 1], name.data, name.size);
  3446. ret[n + 1 + name.size] = '\0';
  3447. return ret;
  3448. } else {
  3449. return strviewdup(ctx, name);
  3450. }
  3451. }
  3452. size_t getjsonname(const char *name, char *buf, size_t len) {
  3453. size_t src, dst = 0;
  3454. bool ucase_next = false;
  3455. #define WRITE(byte) \
  3456. ++dst; \
  3457. if (dst < len) buf[dst - 1] = byte; \
  3458. else if (dst == len) buf[dst - 1] = '\0'
  3459. if (!name) {
  3460. WRITE('\0');
  3461. return 0;
  3462. }
  3463. /* Implement the transformation as described in the spec:
  3464. * 1. upper case all letters after an underscore.
  3465. * 2. remove all underscores.
  3466. */
  3467. for (src = 0; name[src]; src++) {
  3468. if (name[src] == '_') {
  3469. ucase_next = true;
  3470. continue;
  3471. }
  3472. if (ucase_next) {
  3473. WRITE(toupper(name[src]));
  3474. ucase_next = false;
  3475. } else {
  3476. WRITE(name[src]);
  3477. }
  3478. }
  3479. WRITE('\0');
  3480. return dst;
  3481. #undef WRITE
  3482. }
  3483. static char* makejsonname(const char* name, upb_alloc *alloc) {
  3484. size_t size = getjsonname(name, NULL, 0);
  3485. char* json_name = upb_malloc(alloc, size);
  3486. getjsonname(name, json_name, size);
  3487. return json_name;
  3488. }
  3489. static bool symtab_add(const symtab_addctx *ctx, const char *name,
  3490. upb_value v) {
  3491. upb_value tmp;
  3492. if (upb_strtable_lookup(ctx->addtab, name, &tmp) ||
  3493. upb_strtable_lookup(&ctx->symtab->syms, name, &tmp)) {
  3494. upb_status_seterrf(ctx->status, "duplicate symbol '%s'", name);
  3495. return false;
  3496. }
  3497. CHK_OOM(upb_strtable_insert3(ctx->addtab, name, strlen(name), v, ctx->tmp));
  3498. return true;
  3499. }
  3500. /* Given a symbol and the base symbol inside which it is defined, find the
  3501. * symbol's definition in t. */
  3502. static bool resolvename(const upb_strtable *t, const upb_fielddef *f,
  3503. const char *base, upb_strview sym,
  3504. upb_deftype_t type, upb_status *status,
  3505. const void **def) {
  3506. if(sym.size == 0) return NULL;
  3507. if(sym.data[0] == '.') {
  3508. /* Symbols starting with '.' are absolute, so we do a single lookup.
  3509. * Slice to omit the leading '.' */
  3510. upb_value v;
  3511. if (!upb_strtable_lookup2(t, sym.data + 1, sym.size - 1, &v)) {
  3512. return false;
  3513. }
  3514. *def = unpack_def(v, type);
  3515. if (!*def) {
  3516. upb_status_seterrf(status,
  3517. "type mismatch when resolving field %s, name %s",
  3518. f->full_name, sym.data);
  3519. return false;
  3520. }
  3521. return true;
  3522. } else {
  3523. /* Remove components from base until we find an entry or run out.
  3524. * TODO: This branch is totally broken, but currently not used. */
  3525. (void)base;
  3526. UPB_ASSERT(false);
  3527. return false;
  3528. }
  3529. }
  3530. const void *symtab_resolve(const symtab_addctx *ctx, const upb_fielddef *f,
  3531. const char *base, upb_strview sym,
  3532. upb_deftype_t type) {
  3533. const void *ret;
  3534. if (!resolvename(ctx->addtab, f, base, sym, type, ctx->status, &ret) &&
  3535. !resolvename(&ctx->symtab->syms, f, base, sym, type, ctx->status, &ret)) {
  3536. if (upb_ok(ctx->status)) {
  3537. upb_status_seterrf(ctx->status, "couldn't resolve name '%s'", sym.data);
  3538. }
  3539. return false;
  3540. }
  3541. return ret;
  3542. }
  3543. static bool create_oneofdef(
  3544. const symtab_addctx *ctx, upb_msgdef *m,
  3545. const google_protobuf_OneofDescriptorProto *oneof_proto) {
  3546. upb_oneofdef *o;
  3547. upb_strview name = google_protobuf_OneofDescriptorProto_name(oneof_proto);
  3548. upb_value v;
  3549. o = (upb_oneofdef*)&m->oneofs[m->oneof_count++];
  3550. o->parent = m;
  3551. o->full_name = makefullname(ctx, m->full_name, name);
  3552. v = pack_def(o, UPB_DEFTYPE_ONEOF);
  3553. CHK_OOM(symtab_add(ctx, o->full_name, v));
  3554. CHK_OOM(upb_strtable_insert3(&m->ntof, name.data, name.size, v, ctx->alloc));
  3555. CHK_OOM(upb_inttable_init2(&o->itof, UPB_CTYPE_CONSTPTR, ctx->alloc));
  3556. CHK_OOM(upb_strtable_init2(&o->ntof, UPB_CTYPE_CONSTPTR, ctx->alloc));
  3557. return true;
  3558. }
  3559. static bool parse_default(const symtab_addctx *ctx, const char *str, size_t len,
  3560. upb_fielddef *f) {
  3561. char *end;
  3562. char nullz[64];
  3563. errno = 0;
  3564. switch (upb_fielddef_type(f)) {
  3565. case UPB_TYPE_INT32:
  3566. case UPB_TYPE_INT64:
  3567. case UPB_TYPE_UINT32:
  3568. case UPB_TYPE_UINT64:
  3569. case UPB_TYPE_DOUBLE:
  3570. case UPB_TYPE_FLOAT:
  3571. /* Standard C number parsing functions expect null-terminated strings. */
  3572. if (len >= sizeof(nullz) - 1) {
  3573. return false;
  3574. }
  3575. memcpy(nullz, str, len);
  3576. nullz[len] = '\0';
  3577. str = nullz;
  3578. break;
  3579. default:
  3580. break;
  3581. }
  3582. switch (upb_fielddef_type(f)) {
  3583. case UPB_TYPE_INT32: {
  3584. long val = strtol(str, &end, 0);
  3585. CHK(val <= INT32_MAX && val >= INT32_MIN && errno != ERANGE && !*end);
  3586. f->defaultval.sint = val;
  3587. break;
  3588. }
  3589. case UPB_TYPE_ENUM: {
  3590. const upb_enumdef *e = f->sub.enumdef;
  3591. int32_t val;
  3592. CHK(upb_enumdef_ntoi(e, str, len, &val));
  3593. f->defaultval.sint = val;
  3594. break;
  3595. }
  3596. case UPB_TYPE_INT64: {
  3597. /* XXX: Need to write our own strtoll, since it's not available in c89. */
  3598. int64_t val = strtol(str, &end, 0);
  3599. CHK(val <= INT64_MAX && val >= INT64_MIN && errno != ERANGE && !*end);
  3600. f->defaultval.sint = val;
  3601. break;
  3602. }
  3603. case UPB_TYPE_UINT32: {
  3604. unsigned long val = strtoul(str, &end, 0);
  3605. CHK(val <= UINT32_MAX && errno != ERANGE && !*end);
  3606. f->defaultval.uint = val;
  3607. break;
  3608. }
  3609. case UPB_TYPE_UINT64: {
  3610. /* XXX: Need to write our own strtoull, since it's not available in c89. */
  3611. uint64_t val = strtoul(str, &end, 0);
  3612. CHK(val <= UINT64_MAX && errno != ERANGE && !*end);
  3613. f->defaultval.uint = val;
  3614. break;
  3615. }
  3616. case UPB_TYPE_DOUBLE: {
  3617. double val = strtod(str, &end);
  3618. CHK(errno != ERANGE && !*end);
  3619. f->defaultval.dbl = val;
  3620. break;
  3621. }
  3622. case UPB_TYPE_FLOAT: {
  3623. /* XXX: Need to write our own strtof, since it's not available in c89. */
  3624. float val = strtod(str, &end);
  3625. CHK(errno != ERANGE && !*end);
  3626. f->defaultval.flt = val;
  3627. break;
  3628. }
  3629. case UPB_TYPE_BOOL: {
  3630. if (streql2(str, len, "false")) {
  3631. f->defaultval.boolean = false;
  3632. } else if (streql2(str, len, "true")) {
  3633. f->defaultval.boolean = true;
  3634. } else {
  3635. return false;
  3636. }
  3637. break;
  3638. }
  3639. case UPB_TYPE_STRING:
  3640. f->defaultval.str = newstr(ctx->alloc, str, len);
  3641. break;
  3642. case UPB_TYPE_BYTES:
  3643. /* XXX: need to interpret the C-escaped value. */
  3644. f->defaultval.str = newstr(ctx->alloc, str, len);
  3645. break;
  3646. case UPB_TYPE_MESSAGE:
  3647. /* Should not have a default value. */
  3648. return false;
  3649. }
  3650. return true;
  3651. }
  3652. static void set_default_default(const symtab_addctx *ctx, upb_fielddef *f) {
  3653. switch (upb_fielddef_type(f)) {
  3654. case UPB_TYPE_INT32:
  3655. case UPB_TYPE_INT64:
  3656. case UPB_TYPE_ENUM:
  3657. f->defaultval.sint = 0;
  3658. break;
  3659. case UPB_TYPE_UINT64:
  3660. case UPB_TYPE_UINT32:
  3661. f->defaultval.uint = 0;
  3662. break;
  3663. case UPB_TYPE_DOUBLE:
  3664. case UPB_TYPE_FLOAT:
  3665. f->defaultval.dbl = 0;
  3666. break;
  3667. case UPB_TYPE_STRING:
  3668. case UPB_TYPE_BYTES:
  3669. f->defaultval.str = newstr(ctx->alloc, NULL, 0);
  3670. break;
  3671. case UPB_TYPE_BOOL:
  3672. f->defaultval.boolean = false;
  3673. break;
  3674. case UPB_TYPE_MESSAGE:
  3675. break;
  3676. }
  3677. }
  3678. static bool create_fielddef(
  3679. const symtab_addctx *ctx, const char *prefix, upb_msgdef *m,
  3680. const google_protobuf_FieldDescriptorProto *field_proto) {
  3681. upb_alloc *alloc = ctx->alloc;
  3682. upb_fielddef *f;
  3683. const google_protobuf_FieldOptions *options;
  3684. upb_strview name;
  3685. const char *full_name;
  3686. const char *json_name;
  3687. const char *shortname;
  3688. uint32_t field_number;
  3689. if (!google_protobuf_FieldDescriptorProto_has_name(field_proto)) {
  3690. upb_status_seterrmsg(ctx->status, "field has no name");
  3691. return false;
  3692. }
  3693. name = google_protobuf_FieldDescriptorProto_name(field_proto);
  3694. CHK(upb_isident(name, false, ctx->status));
  3695. full_name = makefullname(ctx, prefix, name);
  3696. shortname = shortdefname(full_name);
  3697. if (google_protobuf_FieldDescriptorProto_has_json_name(field_proto)) {
  3698. json_name = strviewdup(
  3699. ctx, google_protobuf_FieldDescriptorProto_json_name(field_proto));
  3700. } else {
  3701. json_name = makejsonname(shortname, ctx->alloc);
  3702. }
  3703. field_number = google_protobuf_FieldDescriptorProto_number(field_proto);
  3704. if (field_number == 0 || field_number > UPB_MAX_FIELDNUMBER) {
  3705. upb_status_seterrf(ctx->status, "invalid field number (%u)", field_number);
  3706. return false;
  3707. }
  3708. if (m) {
  3709. /* direct message field. */
  3710. upb_value v, field_v, json_v;
  3711. size_t json_size;
  3712. f = (upb_fielddef*)&m->fields[m->field_count++];
  3713. f->msgdef = m;
  3714. f->is_extension_ = false;
  3715. if (upb_strtable_lookup(&m->ntof, shortname, NULL)) {
  3716. upb_status_seterrf(ctx->status, "duplicate field name (%s)", shortname);
  3717. return false;
  3718. }
  3719. if (upb_strtable_lookup(&m->ntof, json_name, NULL)) {
  3720. upb_status_seterrf(ctx->status, "duplicate json_name (%s)", json_name);
  3721. return false;
  3722. }
  3723. if (upb_inttable_lookup(&m->itof, field_number, NULL)) {
  3724. upb_status_seterrf(ctx->status, "duplicate field number (%u)",
  3725. field_number);
  3726. return false;
  3727. }
  3728. field_v = pack_def(f, UPB_DEFTYPE_FIELD);
  3729. json_v = pack_def(f, UPB_DEFTYPE_FIELD_JSONNAME);
  3730. v = upb_value_constptr(f);
  3731. json_size = strlen(json_name);
  3732. CHK_OOM(
  3733. upb_strtable_insert3(&m->ntof, name.data, name.size, field_v, alloc));
  3734. CHK_OOM(upb_inttable_insert2(&m->itof, field_number, v, alloc));
  3735. if (strcmp(shortname, json_name) != 0) {
  3736. upb_strtable_insert3(&m->ntof, json_name, json_size, json_v, alloc);
  3737. }
  3738. if (ctx->layouts) {
  3739. const upb_msglayout_field *fields = m->layout->fields;
  3740. int count = m->layout->field_count;
  3741. bool found = false;
  3742. int i;
  3743. for (i = 0; i < count; i++) {
  3744. if (fields[i].number == field_number) {
  3745. f->layout_index = i;
  3746. found = true;
  3747. break;
  3748. }
  3749. }
  3750. UPB_ASSERT(found);
  3751. }
  3752. } else {
  3753. /* extension field. */
  3754. f = (upb_fielddef*)&ctx->file->exts[ctx->file->ext_count++];
  3755. f->is_extension_ = true;
  3756. CHK_OOM(symtab_add(ctx, full_name, pack_def(f, UPB_DEFTYPE_FIELD)));
  3757. }
  3758. f->full_name = full_name;
  3759. f->json_name = json_name;
  3760. f->file = ctx->file;
  3761. f->type_ = (int)google_protobuf_FieldDescriptorProto_type(field_proto);
  3762. f->label_ = (int)google_protobuf_FieldDescriptorProto_label(field_proto);
  3763. f->number_ = field_number;
  3764. f->oneof = NULL;
  3765. f->proto3_optional_ =
  3766. google_protobuf_FieldDescriptorProto_proto3_optional(field_proto);
  3767. /* We can't resolve the subdef or (in the case of extensions) the containing
  3768. * message yet, because it may not have been defined yet. We stash a pointer
  3769. * to the field_proto until later when we can properly resolve it. */
  3770. f->sub.unresolved = field_proto;
  3771. if (f->label_ == UPB_LABEL_REQUIRED && f->file->syntax == UPB_SYNTAX_PROTO3) {
  3772. upb_status_seterrf(ctx->status, "proto3 fields cannot be required (%s)",
  3773. f->full_name);
  3774. return false;
  3775. }
  3776. if (google_protobuf_FieldDescriptorProto_has_oneof_index(field_proto)) {
  3777. int oneof_index =
  3778. google_protobuf_FieldDescriptorProto_oneof_index(field_proto);
  3779. upb_oneofdef *oneof;
  3780. upb_value v = upb_value_constptr(f);
  3781. if (upb_fielddef_label(f) != UPB_LABEL_OPTIONAL) {
  3782. upb_status_seterrf(ctx->status,
  3783. "fields in oneof must have OPTIONAL label (%s)",
  3784. f->full_name);
  3785. return false;
  3786. }
  3787. if (!m) {
  3788. upb_status_seterrf(ctx->status,
  3789. "oneof_index provided for extension field (%s)",
  3790. f->full_name);
  3791. return false;
  3792. }
  3793. if (oneof_index >= m->oneof_count) {
  3794. upb_status_seterrf(ctx->status, "oneof_index out of range (%s)",
  3795. f->full_name);
  3796. return false;
  3797. }
  3798. oneof = (upb_oneofdef*)&m->oneofs[oneof_index];
  3799. f->oneof = oneof;
  3800. CHK(upb_inttable_insert2(&oneof->itof, f->number_, v, alloc));
  3801. CHK(upb_strtable_insert3(&oneof->ntof, name.data, name.size, v, alloc));
  3802. } else {
  3803. f->oneof = NULL;
  3804. }
  3805. if (google_protobuf_FieldDescriptorProto_has_options(field_proto)) {
  3806. options = google_protobuf_FieldDescriptorProto_options(field_proto);
  3807. f->lazy_ = google_protobuf_FieldOptions_lazy(options);
  3808. f->packed_ = google_protobuf_FieldOptions_packed(options);
  3809. } else {
  3810. f->lazy_ = false;
  3811. f->packed_ = false;
  3812. }
  3813. return true;
  3814. }
  3815. static bool create_enumdef(
  3816. const symtab_addctx *ctx, const char *prefix,
  3817. const google_protobuf_EnumDescriptorProto *enum_proto) {
  3818. upb_enumdef *e;
  3819. const google_protobuf_EnumValueDescriptorProto *const *values;
  3820. upb_strview name;
  3821. size_t i, n;
  3822. name = google_protobuf_EnumDescriptorProto_name(enum_proto);
  3823. CHK(upb_isident(name, false, ctx->status));
  3824. e = (upb_enumdef*)&ctx->file->enums[ctx->file->enum_count++];
  3825. e->full_name = makefullname(ctx, prefix, name);
  3826. CHK_OOM(symtab_add(ctx, e->full_name, pack_def(e, UPB_DEFTYPE_ENUM)));
  3827. CHK_OOM(upb_strtable_init2(&e->ntoi, UPB_CTYPE_INT32, ctx->alloc));
  3828. CHK_OOM(upb_inttable_init2(&e->iton, UPB_CTYPE_CSTR, ctx->alloc));
  3829. e->file = ctx->file;
  3830. e->defaultval = 0;
  3831. values = google_protobuf_EnumDescriptorProto_value(enum_proto, &n);
  3832. if (n == 0) {
  3833. upb_status_seterrf(ctx->status,
  3834. "enums must contain at least one value (%s)",
  3835. e->full_name);
  3836. return false;
  3837. }
  3838. for (i = 0; i < n; i++) {
  3839. const google_protobuf_EnumValueDescriptorProto *value = values[i];
  3840. upb_strview name = google_protobuf_EnumValueDescriptorProto_name(value);
  3841. char *name2 = strviewdup(ctx, name);
  3842. int32_t num = google_protobuf_EnumValueDescriptorProto_number(value);
  3843. upb_value v = upb_value_int32(num);
  3844. if (i == 0 && e->file->syntax == UPB_SYNTAX_PROTO3 && num != 0) {
  3845. upb_status_seterrf(ctx->status,
  3846. "for proto3, the first enum value must be zero (%s)",
  3847. e->full_name);
  3848. return false;
  3849. }
  3850. if (upb_strtable_lookup(&e->ntoi, name2, NULL)) {
  3851. upb_status_seterrf(ctx->status, "duplicate enum label '%s'", name2);
  3852. return false;
  3853. }
  3854. CHK_OOM(name2)
  3855. CHK_OOM(
  3856. upb_strtable_insert3(&e->ntoi, name2, strlen(name2), v, ctx->alloc));
  3857. if (!upb_inttable_lookup(&e->iton, num, NULL)) {
  3858. upb_value v = upb_value_cstr(name2);
  3859. CHK_OOM(upb_inttable_insert2(&e->iton, num, v, ctx->alloc));
  3860. }
  3861. }
  3862. upb_inttable_compact2(&e->iton, ctx->alloc);
  3863. return true;
  3864. }
  3865. static bool create_msgdef(symtab_addctx *ctx, const char *prefix,
  3866. const google_protobuf_DescriptorProto *msg_proto) {
  3867. upb_msgdef *m;
  3868. const google_protobuf_MessageOptions *options;
  3869. const google_protobuf_OneofDescriptorProto *const *oneofs;
  3870. const google_protobuf_FieldDescriptorProto *const *fields;
  3871. const google_protobuf_EnumDescriptorProto *const *enums;
  3872. const google_protobuf_DescriptorProto *const *msgs;
  3873. size_t i, n;
  3874. upb_strview name;
  3875. name = google_protobuf_DescriptorProto_name(msg_proto);
  3876. CHK(upb_isident(name, false, ctx->status));
  3877. m = (upb_msgdef*)&ctx->file->msgs[ctx->file->msg_count++];
  3878. m->full_name = makefullname(ctx, prefix, name);
  3879. CHK_OOM(symtab_add(ctx, m->full_name, pack_def(m, UPB_DEFTYPE_MSG)));
  3880. CHK_OOM(upb_inttable_init2(&m->itof, UPB_CTYPE_CONSTPTR, ctx->alloc));
  3881. CHK_OOM(upb_strtable_init2(&m->ntof, UPB_CTYPE_CONSTPTR, ctx->alloc));
  3882. m->file = ctx->file;
  3883. m->map_entry = false;
  3884. options = google_protobuf_DescriptorProto_options(msg_proto);
  3885. if (options) {
  3886. m->map_entry = google_protobuf_MessageOptions_map_entry(options);
  3887. }
  3888. if (ctx->layouts) {
  3889. m->layout = *ctx->layouts;
  3890. ctx->layouts++;
  3891. } else {
  3892. /* Allocate now (to allow cross-linking), populate later. */
  3893. m->layout = upb_malloc(ctx->alloc, sizeof(*m->layout));
  3894. }
  3895. oneofs = google_protobuf_DescriptorProto_oneof_decl(msg_proto, &n);
  3896. m->oneof_count = 0;
  3897. m->oneofs = upb_malloc(ctx->alloc, sizeof(*m->oneofs) * n);
  3898. for (i = 0; i < n; i++) {
  3899. CHK(create_oneofdef(ctx, m, oneofs[i]));
  3900. }
  3901. fields = google_protobuf_DescriptorProto_field(msg_proto, &n);
  3902. m->field_count = 0;
  3903. m->fields = upb_malloc(ctx->alloc, sizeof(*m->fields) * n);
  3904. for (i = 0; i < n; i++) {
  3905. CHK(create_fielddef(ctx, m->full_name, m, fields[i]));
  3906. }
  3907. CHK(assign_msg_indices(m, ctx->status));
  3908. CHK(check_oneofs(m, ctx->status));
  3909. assign_msg_wellknowntype(m);
  3910. upb_inttable_compact2(&m->itof, ctx->alloc);
  3911. /* This message is built. Now build nested messages and enums. */
  3912. enums = google_protobuf_DescriptorProto_enum_type(msg_proto, &n);
  3913. for (i = 0; i < n; i++) {
  3914. CHK(create_enumdef(ctx, m->full_name, enums[i]));
  3915. }
  3916. msgs = google_protobuf_DescriptorProto_nested_type(msg_proto, &n);
  3917. for (i = 0; i < n; i++) {
  3918. CHK(create_msgdef(ctx, m->full_name, msgs[i]));
  3919. }
  3920. return true;
  3921. }
  3922. typedef struct {
  3923. int msg_count;
  3924. int enum_count;
  3925. int ext_count;
  3926. } decl_counts;
  3927. static void count_types_in_msg(const google_protobuf_DescriptorProto *msg_proto,
  3928. decl_counts *counts) {
  3929. const google_protobuf_DescriptorProto *const *msgs;
  3930. size_t i, n;
  3931. counts->msg_count++;
  3932. msgs = google_protobuf_DescriptorProto_nested_type(msg_proto, &n);
  3933. for (i = 0; i < n; i++) {
  3934. count_types_in_msg(msgs[i], counts);
  3935. }
  3936. google_protobuf_DescriptorProto_enum_type(msg_proto, &n);
  3937. counts->enum_count += n;
  3938. google_protobuf_DescriptorProto_extension(msg_proto, &n);
  3939. counts->ext_count += n;
  3940. }
  3941. static void count_types_in_file(
  3942. const google_protobuf_FileDescriptorProto *file_proto,
  3943. decl_counts *counts) {
  3944. const google_protobuf_DescriptorProto *const *msgs;
  3945. size_t i, n;
  3946. msgs = google_protobuf_FileDescriptorProto_message_type(file_proto, &n);
  3947. for (i = 0; i < n; i++) {
  3948. count_types_in_msg(msgs[i], counts);
  3949. }
  3950. google_protobuf_FileDescriptorProto_enum_type(file_proto, &n);
  3951. counts->enum_count += n;
  3952. google_protobuf_FileDescriptorProto_extension(file_proto, &n);
  3953. counts->ext_count += n;
  3954. }
  3955. static bool resolve_fielddef(const symtab_addctx *ctx, const char *prefix,
  3956. upb_fielddef *f) {
  3957. upb_strview name;
  3958. const google_protobuf_FieldDescriptorProto *field_proto = f->sub.unresolved;
  3959. if (f->is_extension_) {
  3960. if (!google_protobuf_FieldDescriptorProto_has_extendee(field_proto)) {
  3961. upb_status_seterrf(ctx->status,
  3962. "extension for field '%s' had no extendee",
  3963. f->full_name);
  3964. return false;
  3965. }
  3966. name = google_protobuf_FieldDescriptorProto_extendee(field_proto);
  3967. f->msgdef = symtab_resolve(ctx, f, prefix, name, UPB_DEFTYPE_MSG);
  3968. CHK(f->msgdef);
  3969. }
  3970. if ((upb_fielddef_issubmsg(f) || f->type_ == UPB_DESCRIPTOR_TYPE_ENUM) &&
  3971. !google_protobuf_FieldDescriptorProto_has_type_name(field_proto)) {
  3972. upb_status_seterrf(ctx->status, "field '%s' is missing type name",
  3973. f->full_name);
  3974. return false;
  3975. }
  3976. name = google_protobuf_FieldDescriptorProto_type_name(field_proto);
  3977. if (upb_fielddef_issubmsg(f)) {
  3978. f->sub.msgdef = symtab_resolve(ctx, f, prefix, name, UPB_DEFTYPE_MSG);
  3979. CHK(f->sub.msgdef);
  3980. } else if (f->type_ == UPB_DESCRIPTOR_TYPE_ENUM) {
  3981. f->sub.enumdef = symtab_resolve(ctx, f, prefix, name, UPB_DEFTYPE_ENUM);
  3982. CHK(f->sub.enumdef);
  3983. }
  3984. /* Have to delay resolving of the default value until now because of the enum
  3985. * case, since enum defaults are specified with a label. */
  3986. if (google_protobuf_FieldDescriptorProto_has_default_value(field_proto)) {
  3987. upb_strview defaultval =
  3988. google_protobuf_FieldDescriptorProto_default_value(field_proto);
  3989. if (f->file->syntax == UPB_SYNTAX_PROTO3) {
  3990. upb_status_seterrf(ctx->status,
  3991. "proto3 fields cannot have explicit defaults (%s)",
  3992. f->full_name);
  3993. return false;
  3994. }
  3995. if (upb_fielddef_issubmsg(f)) {
  3996. upb_status_seterrf(ctx->status,
  3997. "message fields cannot have explicit defaults (%s)",
  3998. f->full_name);
  3999. return false;
  4000. }
  4001. if (!parse_default(ctx, defaultval.data, defaultval.size, f)) {
  4002. upb_status_seterrf(ctx->status,
  4003. "couldn't parse default '" UPB_STRVIEW_FORMAT
  4004. "' for field (%s)",
  4005. UPB_STRVIEW_ARGS(defaultval), f->full_name);
  4006. return false;
  4007. }
  4008. } else {
  4009. set_default_default(ctx, f);
  4010. }
  4011. return true;
  4012. }
  4013. static bool build_filedef(
  4014. symtab_addctx *ctx, upb_filedef *file,
  4015. const google_protobuf_FileDescriptorProto *file_proto) {
  4016. upb_alloc *alloc = ctx->alloc;
  4017. const google_protobuf_FileOptions *file_options_proto;
  4018. const google_protobuf_DescriptorProto *const *msgs;
  4019. const google_protobuf_EnumDescriptorProto *const *enums;
  4020. const google_protobuf_FieldDescriptorProto *const *exts;
  4021. const upb_strview* strs;
  4022. size_t i, n;
  4023. decl_counts counts = {0};
  4024. count_types_in_file(file_proto, &counts);
  4025. file->msgs = upb_malloc(alloc, sizeof(*file->msgs) * counts.msg_count);
  4026. file->enums = upb_malloc(alloc, sizeof(*file->enums) * counts.enum_count);
  4027. file->exts = upb_malloc(alloc, sizeof(*file->exts) * counts.ext_count);
  4028. CHK_OOM(counts.msg_count == 0 || file->msgs);
  4029. CHK_OOM(counts.enum_count == 0 || file->enums);
  4030. CHK_OOM(counts.ext_count == 0 || file->exts);
  4031. /* We increment these as defs are added. */
  4032. file->msg_count = 0;
  4033. file->enum_count = 0;
  4034. file->ext_count = 0;
  4035. if (!google_protobuf_FileDescriptorProto_has_name(file_proto)) {
  4036. upb_status_seterrmsg(ctx->status, "File has no name");
  4037. return false;
  4038. }
  4039. file->name =
  4040. strviewdup(ctx, google_protobuf_FileDescriptorProto_name(file_proto));
  4041. file->phpprefix = NULL;
  4042. file->phpnamespace = NULL;
  4043. if (google_protobuf_FileDescriptorProto_has_package(file_proto)) {
  4044. upb_strview package =
  4045. google_protobuf_FileDescriptorProto_package(file_proto);
  4046. CHK(upb_isident(package, true, ctx->status));
  4047. file->package = strviewdup(ctx, package);
  4048. } else {
  4049. file->package = NULL;
  4050. }
  4051. if (google_protobuf_FileDescriptorProto_has_syntax(file_proto)) {
  4052. upb_strview syntax =
  4053. google_protobuf_FileDescriptorProto_syntax(file_proto);
  4054. if (streql_view(syntax, "proto2")) {
  4055. file->syntax = UPB_SYNTAX_PROTO2;
  4056. } else if (streql_view(syntax, "proto3")) {
  4057. file->syntax = UPB_SYNTAX_PROTO3;
  4058. } else {
  4059. upb_status_seterrf(ctx->status, "Invalid syntax '" UPB_STRVIEW_FORMAT "'",
  4060. UPB_STRVIEW_ARGS(syntax));
  4061. return false;
  4062. }
  4063. } else {
  4064. file->syntax = UPB_SYNTAX_PROTO2;
  4065. }
  4066. /* Read options. */
  4067. file_options_proto = google_protobuf_FileDescriptorProto_options(file_proto);
  4068. if (file_options_proto) {
  4069. if (google_protobuf_FileOptions_has_php_class_prefix(file_options_proto)) {
  4070. file->phpprefix = strviewdup(
  4071. ctx,
  4072. google_protobuf_FileOptions_php_class_prefix(file_options_proto));
  4073. }
  4074. if (google_protobuf_FileOptions_has_php_namespace(file_options_proto)) {
  4075. file->phpnamespace = strviewdup(
  4076. ctx, google_protobuf_FileOptions_php_namespace(file_options_proto));
  4077. }
  4078. }
  4079. /* Verify dependencies. */
  4080. strs = google_protobuf_FileDescriptorProto_dependency(file_proto, &n);
  4081. file->deps = upb_malloc(alloc, sizeof(*file->deps) * n) ;
  4082. CHK_OOM(n == 0 || file->deps);
  4083. for (i = 0; i < n; i++) {
  4084. upb_strview dep_name = strs[i];
  4085. upb_value v;
  4086. if (!upb_strtable_lookup2(&ctx->symtab->files, dep_name.data,
  4087. dep_name.size, &v)) {
  4088. upb_status_seterrf(ctx->status,
  4089. "Depends on file '" UPB_STRVIEW_FORMAT
  4090. "', but it has not been loaded",
  4091. UPB_STRVIEW_ARGS(dep_name));
  4092. return false;
  4093. }
  4094. file->deps[i] = upb_value_getconstptr(v);
  4095. }
  4096. /* Create messages. */
  4097. msgs = google_protobuf_FileDescriptorProto_message_type(file_proto, &n);
  4098. for (i = 0; i < n; i++) {
  4099. CHK(create_msgdef(ctx, file->package, msgs[i]));
  4100. }
  4101. /* Create enums. */
  4102. enums = google_protobuf_FileDescriptorProto_enum_type(file_proto, &n);
  4103. for (i = 0; i < n; i++) {
  4104. CHK(create_enumdef(ctx, file->package, enums[i]));
  4105. }
  4106. /* Create extensions. */
  4107. exts = google_protobuf_FileDescriptorProto_extension(file_proto, &n);
  4108. file->exts = upb_malloc(alloc, sizeof(*file->exts) * n);
  4109. CHK_OOM(n == 0 || file->exts);
  4110. for (i = 0; i < n; i++) {
  4111. CHK(create_fielddef(ctx, file->package, NULL, exts[i]));
  4112. }
  4113. /* Now that all names are in the table, build layouts and resolve refs. */
  4114. for (i = 0; i < file->ext_count; i++) {
  4115. CHK(resolve_fielddef(ctx, file->package, (upb_fielddef*)&file->exts[i]));
  4116. }
  4117. for (i = 0; i < file->msg_count; i++) {
  4118. const upb_msgdef *m = &file->msgs[i];
  4119. int j;
  4120. for (j = 0; j < m->field_count; j++) {
  4121. CHK(resolve_fielddef(ctx, m->full_name, (upb_fielddef*)&m->fields[j]));
  4122. }
  4123. }
  4124. if (!ctx->layouts) {
  4125. for (i = 0; i < file->msg_count; i++) {
  4126. const upb_msgdef *m = &file->msgs[i];
  4127. make_layout(ctx->symtab, m);
  4128. }
  4129. }
  4130. return true;
  4131. }
  4132. static bool upb_symtab_addtotabs(upb_symtab *s, symtab_addctx *ctx,
  4133. upb_status *status) {
  4134. const upb_filedef *file = ctx->file;
  4135. upb_alloc *alloc = upb_arena_alloc(s->arena);
  4136. upb_strtable_iter iter;
  4137. CHK_OOM(upb_strtable_insert3(&s->files, file->name, strlen(file->name),
  4138. upb_value_constptr(file), alloc));
  4139. upb_strtable_begin(&iter, ctx->addtab);
  4140. for (; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
  4141. upb_strview key = upb_strtable_iter_key(&iter);
  4142. upb_value value = upb_strtable_iter_value(&iter);
  4143. CHK_OOM(upb_strtable_insert3(&s->syms, key.data, key.size, value, alloc));
  4144. }
  4145. return true;
  4146. }
  4147. /* upb_filedef ****************************************************************/
  4148. const char *upb_filedef_name(const upb_filedef *f) {
  4149. return f->name;
  4150. }
  4151. const char *upb_filedef_package(const upb_filedef *f) {
  4152. return f->package;
  4153. }
  4154. const char *upb_filedef_phpprefix(const upb_filedef *f) {
  4155. return f->phpprefix;
  4156. }
  4157. const char *upb_filedef_phpnamespace(const upb_filedef *f) {
  4158. return f->phpnamespace;
  4159. }
  4160. upb_syntax_t upb_filedef_syntax(const upb_filedef *f) {
  4161. return f->syntax;
  4162. }
  4163. int upb_filedef_msgcount(const upb_filedef *f) {
  4164. return f->msg_count;
  4165. }
  4166. int upb_filedef_depcount(const upb_filedef *f) {
  4167. return f->dep_count;
  4168. }
  4169. int upb_filedef_enumcount(const upb_filedef *f) {
  4170. return f->enum_count;
  4171. }
  4172. const upb_filedef *upb_filedef_dep(const upb_filedef *f, int i) {
  4173. return i < 0 || i >= f->dep_count ? NULL : f->deps[i];
  4174. }
  4175. const upb_msgdef *upb_filedef_msg(const upb_filedef *f, int i) {
  4176. return i < 0 || i >= f->msg_count ? NULL : &f->msgs[i];
  4177. }
  4178. const upb_enumdef *upb_filedef_enum(const upb_filedef *f, int i) {
  4179. return i < 0 || i >= f->enum_count ? NULL : &f->enums[i];
  4180. }
  4181. void upb_symtab_free(upb_symtab *s) {
  4182. upb_arena_free(s->arena);
  4183. upb_gfree(s);
  4184. }
  4185. upb_symtab *upb_symtab_new(void) {
  4186. upb_symtab *s = upb_gmalloc(sizeof(*s));
  4187. upb_alloc *alloc;
  4188. if (!s) {
  4189. return NULL;
  4190. }
  4191. s->arena = upb_arena_new();
  4192. alloc = upb_arena_alloc(s->arena);
  4193. if (!upb_strtable_init2(&s->syms, UPB_CTYPE_CONSTPTR, alloc) ||
  4194. !upb_strtable_init2(&s->files, UPB_CTYPE_CONSTPTR, alloc)) {
  4195. upb_arena_free(s->arena);
  4196. upb_gfree(s);
  4197. s = NULL;
  4198. }
  4199. return s;
  4200. }
  4201. const upb_msgdef *upb_symtab_lookupmsg(const upb_symtab *s, const char *sym) {
  4202. upb_value v;
  4203. return upb_strtable_lookup(&s->syms, sym, &v) ?
  4204. unpack_def(v, UPB_DEFTYPE_MSG) : NULL;
  4205. }
  4206. const upb_msgdef *upb_symtab_lookupmsg2(const upb_symtab *s, const char *sym,
  4207. size_t len) {
  4208. upb_value v;
  4209. return upb_strtable_lookup2(&s->syms, sym, len, &v) ?
  4210. unpack_def(v, UPB_DEFTYPE_MSG) : NULL;
  4211. }
  4212. const upb_enumdef *upb_symtab_lookupenum(const upb_symtab *s, const char *sym) {
  4213. upb_value v;
  4214. return upb_strtable_lookup(&s->syms, sym, &v) ?
  4215. unpack_def(v, UPB_DEFTYPE_ENUM) : NULL;
  4216. }
  4217. const upb_filedef *upb_symtab_lookupfile(const upb_symtab *s, const char *name) {
  4218. upb_value v;
  4219. return upb_strtable_lookup(&s->files, name, &v) ? upb_value_getconstptr(v)
  4220. : NULL;
  4221. }
  4222. int upb_symtab_filecount(const upb_symtab *s) {
  4223. return (int)upb_strtable_count(&s->files);
  4224. }
  4225. static const upb_filedef *_upb_symtab_addfile(
  4226. upb_symtab *s, const google_protobuf_FileDescriptorProto *file_proto,
  4227. const upb_msglayout **layouts, upb_status *status) {
  4228. upb_arena *tmparena = upb_arena_new();
  4229. upb_strtable addtab;
  4230. upb_alloc *alloc = upb_arena_alloc(s->arena);
  4231. upb_filedef *file = upb_malloc(alloc, sizeof(*file));
  4232. bool ok;
  4233. symtab_addctx ctx;
  4234. ctx.file = file;
  4235. ctx.symtab = s;
  4236. ctx.alloc = alloc;
  4237. ctx.tmp = upb_arena_alloc(tmparena);
  4238. ctx.addtab = &addtab;
  4239. ctx.layouts = layouts;
  4240. ctx.status = status;
  4241. ok = file &&
  4242. upb_strtable_init2(&addtab, UPB_CTYPE_CONSTPTR, ctx.tmp) &&
  4243. build_filedef(&ctx, file, file_proto) &&
  4244. upb_symtab_addtotabs(s, &ctx, status);
  4245. upb_arena_free(tmparena);
  4246. return ok ? file : NULL;
  4247. }
  4248. const upb_filedef *upb_symtab_addfile(
  4249. upb_symtab *s, const google_protobuf_FileDescriptorProto *file_proto,
  4250. upb_status *status) {
  4251. return _upb_symtab_addfile(s, file_proto, NULL, status);
  4252. }
  4253. /* Include here since we want most of this file to be stdio-free. */
  4254. #include <stdio.h>
  4255. bool _upb_symtab_loaddefinit(upb_symtab *s, const upb_def_init *init) {
  4256. /* Since this function should never fail (it would indicate a bug in upb) we
  4257. * print errors to stderr instead of returning error status to the user. */
  4258. upb_def_init **deps = init->deps;
  4259. google_protobuf_FileDescriptorProto *file;
  4260. upb_arena *arena;
  4261. upb_status status;
  4262. upb_status_clear(&status);
  4263. if (upb_strtable_lookup(&s->files, init->filename, NULL)) {
  4264. return true;
  4265. }
  4266. arena = upb_arena_new();
  4267. for (; *deps; deps++) {
  4268. if (!_upb_symtab_loaddefinit(s, *deps)) goto err;
  4269. }
  4270. file = google_protobuf_FileDescriptorProto_parse(
  4271. init->descriptor.data, init->descriptor.size, arena);
  4272. if (!file) {
  4273. upb_status_seterrf(
  4274. &status,
  4275. "Failed to parse compiled-in descriptor for file '%s'. This should "
  4276. "never happen.",
  4277. init->filename);
  4278. goto err;
  4279. }
  4280. if (!_upb_symtab_addfile(s, file, init->layouts, &status)) goto err;
  4281. upb_arena_free(arena);
  4282. return true;
  4283. err:
  4284. fprintf(stderr, "Error loading compiled-in descriptor: %s\n",
  4285. upb_status_errmsg(&status));
  4286. upb_arena_free(arena);
  4287. return false;
  4288. }
  4289. #undef CHK
  4290. #undef CHK_OOM
  4291. #include <string.h>
  4292. static char field_size[] = {
  4293. 0,/* 0 */
  4294. 8, /* UPB_DESCRIPTOR_TYPE_DOUBLE */
  4295. 4, /* UPB_DESCRIPTOR_TYPE_FLOAT */
  4296. 8, /* UPB_DESCRIPTOR_TYPE_INT64 */
  4297. 8, /* UPB_DESCRIPTOR_TYPE_UINT64 */
  4298. 4, /* UPB_DESCRIPTOR_TYPE_INT32 */
  4299. 8, /* UPB_DESCRIPTOR_TYPE_FIXED64 */
  4300. 4, /* UPB_DESCRIPTOR_TYPE_FIXED32 */
  4301. 1, /* UPB_DESCRIPTOR_TYPE_BOOL */
  4302. sizeof(upb_strview), /* UPB_DESCRIPTOR_TYPE_STRING */
  4303. sizeof(void*), /* UPB_DESCRIPTOR_TYPE_GROUP */
  4304. sizeof(void*), /* UPB_DESCRIPTOR_TYPE_MESSAGE */
  4305. sizeof(upb_strview), /* UPB_DESCRIPTOR_TYPE_BYTES */
  4306. 4, /* UPB_DESCRIPTOR_TYPE_UINT32 */
  4307. 4, /* UPB_DESCRIPTOR_TYPE_ENUM */
  4308. 4, /* UPB_DESCRIPTOR_TYPE_SFIXED32 */
  4309. 8, /* UPB_DESCRIPTOR_TYPE_SFIXED64 */
  4310. 4, /* UPB_DESCRIPTOR_TYPE_SINT32 */
  4311. 8, /* UPB_DESCRIPTOR_TYPE_SINT64 */
  4312. };
  4313. /* Strings/bytes are special-cased in maps. */
  4314. static char _upb_fieldtype_to_mapsize[12] = {
  4315. 0,
  4316. 1, /* UPB_TYPE_BOOL */
  4317. 4, /* UPB_TYPE_FLOAT */
  4318. 4, /* UPB_TYPE_INT32 */
  4319. 4, /* UPB_TYPE_UINT32 */
  4320. 4, /* UPB_TYPE_ENUM */
  4321. sizeof(void*), /* UPB_TYPE_MESSAGE */
  4322. 8, /* UPB_TYPE_DOUBLE */
  4323. 8, /* UPB_TYPE_INT64 */
  4324. 8, /* UPB_TYPE_UINT64 */
  4325. 0, /* UPB_TYPE_STRING */
  4326. 0, /* UPB_TYPE_BYTES */
  4327. };
  4328. /** upb_msg *******************************************************************/
  4329. upb_msg *upb_msg_new(const upb_msgdef *m, upb_arena *a) {
  4330. return _upb_msg_new(upb_msgdef_layout(m), a);
  4331. }
  4332. static bool in_oneof(const upb_msglayout_field *field) {
  4333. return field->presence < 0;
  4334. }
  4335. static uint32_t *oneofcase(const upb_msg *msg,
  4336. const upb_msglayout_field *field) {
  4337. UPB_ASSERT(in_oneof(field));
  4338. return UPB_PTR_AT(msg, -field->presence, uint32_t);
  4339. }
  4340. static upb_msgval _upb_msg_getraw(const upb_msg *msg, const upb_fielddef *f) {
  4341. const upb_msglayout_field *field = upb_fielddef_layout(f);
  4342. const char *mem = UPB_PTR_AT(msg, field->offset, char);
  4343. upb_msgval val = {0};
  4344. int size = upb_fielddef_isseq(f) ? sizeof(void *)
  4345. : field_size[field->descriptortype];
  4346. memcpy(&val, mem, size);
  4347. return val;
  4348. }
  4349. bool upb_msg_has(const upb_msg *msg, const upb_fielddef *f) {
  4350. const upb_msglayout_field *field = upb_fielddef_layout(f);
  4351. if (in_oneof(field)) {
  4352. return *oneofcase(msg, field) == field->number;
  4353. } else if (field->presence > 0) {
  4354. uint32_t hasbit = field->presence;
  4355. return *UPB_PTR_AT(msg, hasbit / 8, uint8_t) & (1 << (hasbit % 8));
  4356. } else {
  4357. UPB_ASSERT(field->descriptortype == UPB_DESCRIPTOR_TYPE_MESSAGE ||
  4358. field->descriptortype == UPB_DESCRIPTOR_TYPE_GROUP);
  4359. return _upb_msg_getraw(msg, f).msg_val != NULL;
  4360. }
  4361. }
  4362. bool upb_msg_hasoneof(const upb_msg *msg, const upb_oneofdef *o) {
  4363. upb_oneof_iter i;
  4364. const upb_fielddef *f;
  4365. const upb_msglayout_field *field;
  4366. upb_oneof_begin(&i, o);
  4367. if (upb_oneof_done(&i)) return false;
  4368. f = upb_oneof_iter_field(&i);
  4369. field = upb_fielddef_layout(f);
  4370. return *oneofcase(msg, field) != 0;
  4371. }
  4372. upb_msgval upb_msg_get(const upb_msg *msg, const upb_fielddef *f) {
  4373. if (!upb_fielddef_haspresence(f) || upb_msg_has(msg, f)) {
  4374. return _upb_msg_getraw(msg, f);
  4375. } else {
  4376. /* TODO(haberman): change upb_fielddef to not require this switch(). */
  4377. upb_msgval val = {0};
  4378. switch (upb_fielddef_type(f)) {
  4379. case UPB_TYPE_INT32:
  4380. case UPB_TYPE_ENUM:
  4381. val.int32_val = upb_fielddef_defaultint32(f);
  4382. break;
  4383. case UPB_TYPE_INT64:
  4384. val.int64_val = upb_fielddef_defaultint64(f);
  4385. break;
  4386. case UPB_TYPE_UINT32:
  4387. val.uint32_val = upb_fielddef_defaultuint32(f);
  4388. break;
  4389. case UPB_TYPE_UINT64:
  4390. val.uint64_val = upb_fielddef_defaultuint64(f);
  4391. break;
  4392. case UPB_TYPE_FLOAT:
  4393. val.float_val = upb_fielddef_defaultfloat(f);
  4394. break;
  4395. case UPB_TYPE_DOUBLE:
  4396. val.double_val = upb_fielddef_defaultdouble(f);
  4397. break;
  4398. case UPB_TYPE_BOOL:
  4399. val.double_val = upb_fielddef_defaultbool(f);
  4400. break;
  4401. case UPB_TYPE_STRING:
  4402. case UPB_TYPE_BYTES:
  4403. val.str_val.data = upb_fielddef_defaultstr(f, &val.str_val.size);
  4404. break;
  4405. case UPB_TYPE_MESSAGE:
  4406. val.msg_val = NULL;
  4407. break;
  4408. }
  4409. return val;
  4410. }
  4411. }
  4412. upb_mutmsgval upb_msg_mutable(upb_msg *msg, const upb_fielddef *f,
  4413. upb_arena *a) {
  4414. const upb_msglayout_field *field = upb_fielddef_layout(f);
  4415. upb_mutmsgval ret;
  4416. char *mem = UPB_PTR_AT(msg, field->offset, char);
  4417. bool wrong_oneof = in_oneof(field) && *oneofcase(msg, field) != field->number;
  4418. memcpy(&ret, mem, sizeof(void*));
  4419. if (a && (!ret.msg || wrong_oneof)) {
  4420. if (upb_fielddef_ismap(f)) {
  4421. const upb_msgdef *entry = upb_fielddef_msgsubdef(f);
  4422. const upb_fielddef *key = upb_msgdef_itof(entry, UPB_MAPENTRY_KEY);
  4423. const upb_fielddef *value = upb_msgdef_itof(entry, UPB_MAPENTRY_VALUE);
  4424. ret.map = upb_map_new(a, upb_fielddef_type(key), upb_fielddef_type(value));
  4425. } else if (upb_fielddef_isseq(f)) {
  4426. ret.array = upb_array_new(a, upb_fielddef_type(f));
  4427. } else {
  4428. UPB_ASSERT(upb_fielddef_issubmsg(f));
  4429. ret.msg = upb_msg_new(upb_fielddef_msgsubdef(f), a);
  4430. }
  4431. memcpy(mem, &ret, sizeof(void*));
  4432. if (wrong_oneof) {
  4433. *oneofcase(msg, field) = field->number;
  4434. }
  4435. }
  4436. return ret;
  4437. }
  4438. void upb_msg_set(upb_msg *msg, const upb_fielddef *f, upb_msgval val,
  4439. upb_arena *a) {
  4440. const upb_msglayout_field *field = upb_fielddef_layout(f);
  4441. char *mem = UPB_PTR_AT(msg, field->offset, char);
  4442. int size = upb_fielddef_isseq(f) ? sizeof(void *)
  4443. : field_size[field->descriptortype];
  4444. memcpy(mem, &val, size);
  4445. if (in_oneof(field)) {
  4446. *oneofcase(msg, field) = field->number;
  4447. }
  4448. }
  4449. bool upb_msg_next(const upb_msg *msg, const upb_msgdef *m,
  4450. const upb_symtab *ext_pool, const upb_fielddef **out_f,
  4451. upb_msgval *out_val, size_t *iter) {
  4452. size_t i = *iter;
  4453. const upb_msgval zero = {0};
  4454. const upb_fielddef *f;
  4455. while ((f = _upb_msgdef_field(m, (int)++i)) != NULL) {
  4456. upb_msgval val = _upb_msg_getraw(msg, f);
  4457. /* Skip field if unset or empty. */
  4458. if (upb_fielddef_haspresence(f)) {
  4459. if (!upb_msg_has(msg, f)) continue;
  4460. } else {
  4461. upb_msgval test = val;
  4462. if (upb_fielddef_isstring(f) && !upb_fielddef_isseq(f)) {
  4463. /* Clear string pointer, only size matters (ptr could be non-NULL). */
  4464. test.str_val.data = NULL;
  4465. }
  4466. /* Continue if NULL or 0. */
  4467. if (memcmp(&test, &zero, sizeof(test)) == 0) continue;
  4468. /* Continue on empty array or map. */
  4469. if (upb_fielddef_ismap(f)) {
  4470. if (upb_map_size(test.map_val) == 0) continue;
  4471. } else if (upb_fielddef_isseq(f)) {
  4472. if (upb_array_size(test.array_val) == 0) continue;
  4473. }
  4474. }
  4475. *out_val = val;
  4476. *out_f = f;
  4477. *iter = i;
  4478. return true;
  4479. }
  4480. *iter = i;
  4481. return false;
  4482. }
  4483. /** upb_array *****************************************************************/
  4484. upb_array *upb_array_new(upb_arena *a, upb_fieldtype_t type) {
  4485. return _upb_array_new(a, type);
  4486. }
  4487. size_t upb_array_size(const upb_array *arr) {
  4488. return arr->len;
  4489. }
  4490. upb_msgval upb_array_get(const upb_array *arr, size_t i) {
  4491. upb_msgval ret;
  4492. const char* data = _upb_array_constptr(arr);
  4493. int lg2 = arr->data & 7;
  4494. UPB_ASSERT(i < arr->len);
  4495. memcpy(&ret, data + (i << lg2), 1 << lg2);
  4496. return ret;
  4497. }
  4498. void upb_array_set(upb_array *arr, size_t i, upb_msgval val) {
  4499. char* data = _upb_array_ptr(arr);
  4500. int lg2 = arr->data & 7;
  4501. UPB_ASSERT(i < arr->len);
  4502. memcpy(data + (i << lg2), &val, 1 << lg2);
  4503. }
  4504. bool upb_array_append(upb_array *arr, upb_msgval val, upb_arena *arena) {
  4505. if (!_upb_array_realloc(arr, arr->len + 1, arena)) {
  4506. return false;
  4507. }
  4508. arr->len++;
  4509. upb_array_set(arr, arr->len - 1, val);
  4510. return true;
  4511. }
  4512. /* Resizes the array to the given size, reallocating if necessary, and returns a
  4513. * pointer to the new array elements. */
  4514. bool upb_array_resize(upb_array *arr, size_t size, upb_arena *arena) {
  4515. return _upb_array_realloc(arr, size, arena);
  4516. }
  4517. /** upb_map *******************************************************************/
  4518. upb_map *upb_map_new(upb_arena *a, upb_fieldtype_t key_type,
  4519. upb_fieldtype_t value_type) {
  4520. return _upb_map_new(a, _upb_fieldtype_to_mapsize[key_type],
  4521. _upb_fieldtype_to_mapsize[value_type]);
  4522. }
  4523. size_t upb_map_size(const upb_map *map) {
  4524. return _upb_map_size(map);
  4525. }
  4526. bool upb_map_get(const upb_map *map, upb_msgval key, upb_msgval *val) {
  4527. return _upb_map_get(map, &key, map->key_size, val, map->val_size);
  4528. }
  4529. bool upb_map_set(upb_map *map, upb_msgval key, upb_msgval val,
  4530. upb_arena *arena) {
  4531. return _upb_map_set(map, &key, map->key_size, &val, map->val_size, arena);
  4532. }
  4533. bool upb_map_delete(upb_map *map, upb_msgval key) {
  4534. return _upb_map_delete(map, &key, map->key_size);
  4535. }
  4536. bool upb_mapiter_next(const upb_map *map, size_t *iter) {
  4537. return _upb_map_next(map, iter);
  4538. }
  4539. /* Returns the key and value for this entry of the map. */
  4540. upb_msgval upb_mapiter_key(const upb_map *map, size_t iter) {
  4541. upb_strtable_iter i;
  4542. upb_msgval ret;
  4543. i.t = &map->table;
  4544. i.index = iter;
  4545. _upb_map_fromkey(upb_strtable_iter_key(&i), &ret, map->key_size);
  4546. return ret;
  4547. }
  4548. upb_msgval upb_mapiter_value(const upb_map *map, size_t iter) {
  4549. upb_strtable_iter i;
  4550. upb_msgval ret;
  4551. i.t = &map->table;
  4552. i.index = iter;
  4553. _upb_map_fromvalue(upb_strtable_iter_value(&i), &ret, map->val_size);
  4554. return ret;
  4555. }
  4556. /* void upb_mapiter_setvalue(upb_map *map, size_t iter, upb_msgval value); */
  4557. /*
  4558. ** TODO(haberman): it's unclear whether a lot of the consistency checks should
  4559. ** UPB_ASSERT() or return false.
  4560. */
  4561. #include <string.h>
  4562. struct upb_handlers {
  4563. upb_handlercache *cache;
  4564. const upb_msgdef *msg;
  4565. const upb_handlers **sub;
  4566. const void *top_closure_type;
  4567. upb_handlers_tabent table[1]; /* Dynamically-sized field handler array. */
  4568. };
  4569. static void *upb_calloc(upb_arena *arena, size_t size) {
  4570. void *mem = upb_malloc(upb_arena_alloc(arena), size);
  4571. if (mem) {
  4572. memset(mem, 0, size);
  4573. }
  4574. return mem;
  4575. }
  4576. /* Defined for the sole purpose of having a unique pointer value for
  4577. * UPB_NO_CLOSURE. */
  4578. char _upb_noclosure;
  4579. /* Given a selector for a STARTSUBMSG handler, resolves to a pointer to the
  4580. * subhandlers for this submessage field. */
  4581. #define SUBH(h, selector) (h->sub[selector])
  4582. /* The selector for a submessage field is the field index. */
  4583. #define SUBH_F(h, f) SUBH(h, upb_fielddef_index(f))
  4584. static int32_t trygetsel(upb_handlers *h, const upb_fielddef *f,
  4585. upb_handlertype_t type) {
  4586. upb_selector_t sel;
  4587. bool ok;
  4588. ok = upb_handlers_getselector(f, type, &sel);
  4589. UPB_ASSERT(upb_handlers_msgdef(h) == upb_fielddef_containingtype(f));
  4590. UPB_ASSERT(ok);
  4591. return sel;
  4592. }
  4593. static upb_selector_t handlers_getsel(upb_handlers *h, const upb_fielddef *f,
  4594. upb_handlertype_t type) {
  4595. int32_t sel = trygetsel(h, f, type);
  4596. UPB_ASSERT(sel >= 0);
  4597. return sel;
  4598. }
  4599. static const void **returntype(upb_handlers *h, const upb_fielddef *f,
  4600. upb_handlertype_t type) {
  4601. return &h->table[handlers_getsel(h, f, type)].attr.return_closure_type;
  4602. }
  4603. static bool doset(upb_handlers *h, int32_t sel, const upb_fielddef *f,
  4604. upb_handlertype_t type, upb_func *func,
  4605. const upb_handlerattr *attr) {
  4606. upb_handlerattr set_attr = UPB_HANDLERATTR_INIT;
  4607. const void *closure_type;
  4608. const void **context_closure_type;
  4609. UPB_ASSERT(!h->table[sel].func);
  4610. if (attr) {
  4611. set_attr = *attr;
  4612. }
  4613. /* Check that the given closure type matches the closure type that has been
  4614. * established for this context (if any). */
  4615. closure_type = set_attr.closure_type;
  4616. if (type == UPB_HANDLER_STRING) {
  4617. context_closure_type = returntype(h, f, UPB_HANDLER_STARTSTR);
  4618. } else if (f && upb_fielddef_isseq(f) &&
  4619. type != UPB_HANDLER_STARTSEQ &&
  4620. type != UPB_HANDLER_ENDSEQ) {
  4621. context_closure_type = returntype(h, f, UPB_HANDLER_STARTSEQ);
  4622. } else {
  4623. context_closure_type = &h->top_closure_type;
  4624. }
  4625. if (closure_type && *context_closure_type &&
  4626. closure_type != *context_closure_type) {
  4627. return false;
  4628. }
  4629. if (closure_type)
  4630. *context_closure_type = closure_type;
  4631. /* If this is a STARTSEQ or STARTSTR handler, check that the returned pointer
  4632. * matches any pre-existing expectations about what type is expected. */
  4633. if (type == UPB_HANDLER_STARTSEQ || type == UPB_HANDLER_STARTSTR) {
  4634. const void *return_type = set_attr.return_closure_type;
  4635. const void *table_return_type = h->table[sel].attr.return_closure_type;
  4636. if (return_type && table_return_type && return_type != table_return_type) {
  4637. return false;
  4638. }
  4639. if (table_return_type && !return_type) {
  4640. set_attr.return_closure_type = table_return_type;
  4641. }
  4642. }
  4643. h->table[sel].func = (upb_func*)func;
  4644. h->table[sel].attr = set_attr;
  4645. return true;
  4646. }
  4647. /* Returns the effective closure type for this handler (which will propagate
  4648. * from outer frames if this frame has no START* handler). Not implemented for
  4649. * UPB_HANDLER_STRING at the moment since this is not needed. Returns NULL is
  4650. * the effective closure type is unspecified (either no handler was registered
  4651. * to specify it or the handler that was registered did not specify the closure
  4652. * type). */
  4653. const void *effective_closure_type(upb_handlers *h, const upb_fielddef *f,
  4654. upb_handlertype_t type) {
  4655. const void *ret;
  4656. upb_selector_t sel;
  4657. UPB_ASSERT(type != UPB_HANDLER_STRING);
  4658. ret = h->top_closure_type;
  4659. if (upb_fielddef_isseq(f) &&
  4660. type != UPB_HANDLER_STARTSEQ &&
  4661. type != UPB_HANDLER_ENDSEQ &&
  4662. h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSEQ)].func) {
  4663. ret = h->table[sel].attr.return_closure_type;
  4664. }
  4665. if (type == UPB_HANDLER_STRING &&
  4666. h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSTR)].func) {
  4667. ret = h->table[sel].attr.return_closure_type;
  4668. }
  4669. /* The effective type of the submessage; not used yet.
  4670. * if (type == SUBMESSAGE &&
  4671. * h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSUBMSG)].func) {
  4672. * ret = h->table[sel].attr.return_closure_type;
  4673. * } */
  4674. return ret;
  4675. }
  4676. /* Checks whether the START* handler specified by f & type is missing even
  4677. * though it is required to convert the established type of an outer frame
  4678. * ("closure_type") into the established type of an inner frame (represented in
  4679. * the return closure type of this handler's attr. */
  4680. bool checkstart(upb_handlers *h, const upb_fielddef *f, upb_handlertype_t type,
  4681. upb_status *status) {
  4682. const void *closure_type;
  4683. const upb_handlerattr *attr;
  4684. const void *return_closure_type;
  4685. upb_selector_t sel = handlers_getsel(h, f, type);
  4686. if (h->table[sel].func) return true;
  4687. closure_type = effective_closure_type(h, f, type);
  4688. attr = &h->table[sel].attr;
  4689. return_closure_type = attr->return_closure_type;
  4690. if (closure_type && return_closure_type &&
  4691. closure_type != return_closure_type) {
  4692. return false;
  4693. }
  4694. return true;
  4695. }
  4696. static upb_handlers *upb_handlers_new(const upb_msgdef *md,
  4697. upb_handlercache *cache,
  4698. upb_arena *arena) {
  4699. int extra;
  4700. upb_handlers *h;
  4701. extra =
  4702. (int)(sizeof(upb_handlers_tabent) * (upb_msgdef_selectorcount(md) - 1));
  4703. h = upb_calloc(arena, sizeof(*h) + extra);
  4704. if (!h) return NULL;
  4705. h->cache = cache;
  4706. h->msg = md;
  4707. if (upb_msgdef_submsgfieldcount(md) > 0) {
  4708. size_t bytes = upb_msgdef_submsgfieldcount(md) * sizeof(*h->sub);
  4709. h->sub = upb_calloc(arena, bytes);
  4710. if (!h->sub) return NULL;
  4711. } else {
  4712. h->sub = 0;
  4713. }
  4714. /* calloc() above initialized all handlers to NULL. */
  4715. return h;
  4716. }
  4717. /* Public interface ***********************************************************/
  4718. #define SETTER(name, handlerctype, handlertype) \
  4719. bool upb_handlers_set##name(upb_handlers *h, const upb_fielddef *f, \
  4720. handlerctype func, \
  4721. const upb_handlerattr *attr) { \
  4722. int32_t sel = trygetsel(h, f, handlertype); \
  4723. return doset(h, sel, f, handlertype, (upb_func *)func, attr); \
  4724. }
  4725. SETTER(int32, upb_int32_handlerfunc*, UPB_HANDLER_INT32)
  4726. SETTER(int64, upb_int64_handlerfunc*, UPB_HANDLER_INT64)
  4727. SETTER(uint32, upb_uint32_handlerfunc*, UPB_HANDLER_UINT32)
  4728. SETTER(uint64, upb_uint64_handlerfunc*, UPB_HANDLER_UINT64)
  4729. SETTER(float, upb_float_handlerfunc*, UPB_HANDLER_FLOAT)
  4730. SETTER(double, upb_double_handlerfunc*, UPB_HANDLER_DOUBLE)
  4731. SETTER(bool, upb_bool_handlerfunc*, UPB_HANDLER_BOOL)
  4732. SETTER(startstr, upb_startstr_handlerfunc*, UPB_HANDLER_STARTSTR)
  4733. SETTER(string, upb_string_handlerfunc*, UPB_HANDLER_STRING)
  4734. SETTER(endstr, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSTR)
  4735. SETTER(startseq, upb_startfield_handlerfunc*, UPB_HANDLER_STARTSEQ)
  4736. SETTER(startsubmsg, upb_startfield_handlerfunc*, UPB_HANDLER_STARTSUBMSG)
  4737. SETTER(endsubmsg, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSUBMSG)
  4738. SETTER(endseq, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSEQ)
  4739. #undef SETTER
  4740. bool upb_handlers_setunknown(upb_handlers *h, upb_unknown_handlerfunc *func,
  4741. const upb_handlerattr *attr) {
  4742. return doset(h, UPB_UNKNOWN_SELECTOR, NULL, UPB_HANDLER_INT32,
  4743. (upb_func *)func, attr);
  4744. }
  4745. bool upb_handlers_setstartmsg(upb_handlers *h, upb_startmsg_handlerfunc *func,
  4746. const upb_handlerattr *attr) {
  4747. return doset(h, UPB_STARTMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
  4748. (upb_func *)func, attr);
  4749. }
  4750. bool upb_handlers_setendmsg(upb_handlers *h, upb_endmsg_handlerfunc *func,
  4751. const upb_handlerattr *attr) {
  4752. return doset(h, UPB_ENDMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
  4753. (upb_func *)func, attr);
  4754. }
  4755. bool upb_handlers_setsubhandlers(upb_handlers *h, const upb_fielddef *f,
  4756. const upb_handlers *sub) {
  4757. UPB_ASSERT(sub);
  4758. UPB_ASSERT(upb_fielddef_issubmsg(f));
  4759. if (SUBH_F(h, f)) return false; /* Can't reset. */
  4760. if (upb_handlers_msgdef(sub) != upb_fielddef_msgsubdef(f)) {
  4761. return false;
  4762. }
  4763. SUBH_F(h, f) = sub;
  4764. return true;
  4765. }
  4766. const upb_handlers *upb_handlers_getsubhandlers(const upb_handlers *h,
  4767. const upb_fielddef *f) {
  4768. UPB_ASSERT(upb_fielddef_issubmsg(f));
  4769. return SUBH_F(h, f);
  4770. }
  4771. upb_func *upb_handlers_gethandler(const upb_handlers *h, upb_selector_t s,
  4772. const void **handler_data) {
  4773. upb_func *ret = (upb_func *)h->table[s].func;
  4774. if (ret && handler_data) {
  4775. *handler_data = h->table[s].attr.handler_data;
  4776. }
  4777. return ret;
  4778. }
  4779. bool upb_handlers_getattr(const upb_handlers *h, upb_selector_t sel,
  4780. upb_handlerattr *attr) {
  4781. if (!upb_handlers_gethandler(h, sel, NULL))
  4782. return false;
  4783. *attr = h->table[sel].attr;
  4784. return true;
  4785. }
  4786. const upb_handlers *upb_handlers_getsubhandlers_sel(const upb_handlers *h,
  4787. upb_selector_t sel) {
  4788. /* STARTSUBMSG selector in sel is the field's selector base. */
  4789. return SUBH(h, sel - UPB_STATIC_SELECTOR_COUNT);
  4790. }
  4791. const upb_msgdef *upb_handlers_msgdef(const upb_handlers *h) { return h->msg; }
  4792. bool upb_handlers_addcleanup(upb_handlers *h, void *p, upb_handlerfree *func) {
  4793. return upb_handlercache_addcleanup(h->cache, p, func);
  4794. }
  4795. upb_handlertype_t upb_handlers_getprimitivehandlertype(const upb_fielddef *f) {
  4796. switch (upb_fielddef_type(f)) {
  4797. case UPB_TYPE_INT32:
  4798. case UPB_TYPE_ENUM: return UPB_HANDLER_INT32;
  4799. case UPB_TYPE_INT64: return UPB_HANDLER_INT64;
  4800. case UPB_TYPE_UINT32: return UPB_HANDLER_UINT32;
  4801. case UPB_TYPE_UINT64: return UPB_HANDLER_UINT64;
  4802. case UPB_TYPE_FLOAT: return UPB_HANDLER_FLOAT;
  4803. case UPB_TYPE_DOUBLE: return UPB_HANDLER_DOUBLE;
  4804. case UPB_TYPE_BOOL: return UPB_HANDLER_BOOL;
  4805. default: UPB_ASSERT(false); return -1; /* Invalid input. */
  4806. }
  4807. }
  4808. bool upb_handlers_getselector(const upb_fielddef *f, upb_handlertype_t type,
  4809. upb_selector_t *s) {
  4810. uint32_t selector_base = upb_fielddef_selectorbase(f);
  4811. switch (type) {
  4812. case UPB_HANDLER_INT32:
  4813. case UPB_HANDLER_INT64:
  4814. case UPB_HANDLER_UINT32:
  4815. case UPB_HANDLER_UINT64:
  4816. case UPB_HANDLER_FLOAT:
  4817. case UPB_HANDLER_DOUBLE:
  4818. case UPB_HANDLER_BOOL:
  4819. if (!upb_fielddef_isprimitive(f) ||
  4820. upb_handlers_getprimitivehandlertype(f) != type)
  4821. return false;
  4822. *s = selector_base;
  4823. break;
  4824. case UPB_HANDLER_STRING:
  4825. if (upb_fielddef_isstring(f)) {
  4826. *s = selector_base;
  4827. } else if (upb_fielddef_lazy(f)) {
  4828. *s = selector_base + 3;
  4829. } else {
  4830. return false;
  4831. }
  4832. break;
  4833. case UPB_HANDLER_STARTSTR:
  4834. if (upb_fielddef_isstring(f) || upb_fielddef_lazy(f)) {
  4835. *s = selector_base + 1;
  4836. } else {
  4837. return false;
  4838. }
  4839. break;
  4840. case UPB_HANDLER_ENDSTR:
  4841. if (upb_fielddef_isstring(f) || upb_fielddef_lazy(f)) {
  4842. *s = selector_base + 2;
  4843. } else {
  4844. return false;
  4845. }
  4846. break;
  4847. case UPB_HANDLER_STARTSEQ:
  4848. if (!upb_fielddef_isseq(f)) return false;
  4849. *s = selector_base - 2;
  4850. break;
  4851. case UPB_HANDLER_ENDSEQ:
  4852. if (!upb_fielddef_isseq(f)) return false;
  4853. *s = selector_base - 1;
  4854. break;
  4855. case UPB_HANDLER_STARTSUBMSG:
  4856. if (!upb_fielddef_issubmsg(f)) return false;
  4857. /* Selectors for STARTSUBMSG are at the beginning of the table so that the
  4858. * selector can also be used as an index into the "sub" array of
  4859. * subhandlers. The indexes for the two into these two tables are the
  4860. * same, except that in the handler table the static selectors come first. */
  4861. *s = upb_fielddef_index(f) + UPB_STATIC_SELECTOR_COUNT;
  4862. break;
  4863. case UPB_HANDLER_ENDSUBMSG:
  4864. if (!upb_fielddef_issubmsg(f)) return false;
  4865. *s = selector_base;
  4866. break;
  4867. }
  4868. UPB_ASSERT((size_t)*s < upb_msgdef_selectorcount(upb_fielddef_containingtype(f)));
  4869. return true;
  4870. }
  4871. /* upb_handlercache ***********************************************************/
  4872. struct upb_handlercache {
  4873. upb_arena *arena;
  4874. upb_inttable tab; /* maps upb_msgdef* -> upb_handlers*. */
  4875. upb_handlers_callback *callback;
  4876. const void *closure;
  4877. };
  4878. const upb_handlers *upb_handlercache_get(upb_handlercache *c,
  4879. const upb_msgdef *md) {
  4880. upb_msg_field_iter i;
  4881. upb_value v;
  4882. upb_handlers *h;
  4883. if (upb_inttable_lookupptr(&c->tab, md, &v)) {
  4884. return upb_value_getptr(v);
  4885. }
  4886. h = upb_handlers_new(md, c, c->arena);
  4887. v = upb_value_ptr(h);
  4888. if (!h) return NULL;
  4889. if (!upb_inttable_insertptr(&c->tab, md, v)) return NULL;
  4890. c->callback(c->closure, h);
  4891. /* For each submessage field, get or create a handlers object and set it as
  4892. * the subhandlers. */
  4893. for(upb_msg_field_begin(&i, md);
  4894. !upb_msg_field_done(&i);
  4895. upb_msg_field_next(&i)) {
  4896. upb_fielddef *f = upb_msg_iter_field(&i);
  4897. if (upb_fielddef_issubmsg(f)) {
  4898. const upb_msgdef *subdef = upb_fielddef_msgsubdef(f);
  4899. const upb_handlers *sub_mh = upb_handlercache_get(c, subdef);
  4900. if (!sub_mh) return NULL;
  4901. upb_handlers_setsubhandlers(h, f, sub_mh);
  4902. }
  4903. }
  4904. return h;
  4905. }
  4906. upb_handlercache *upb_handlercache_new(upb_handlers_callback *callback,
  4907. const void *closure) {
  4908. upb_handlercache *cache = upb_gmalloc(sizeof(*cache));
  4909. if (!cache) return NULL;
  4910. cache->arena = upb_arena_new();
  4911. cache->callback = callback;
  4912. cache->closure = closure;
  4913. if (!upb_inttable_init(&cache->tab, UPB_CTYPE_PTR)) goto oom;
  4914. return cache;
  4915. oom:
  4916. upb_gfree(cache);
  4917. return NULL;
  4918. }
  4919. void upb_handlercache_free(upb_handlercache *cache) {
  4920. upb_inttable_uninit(&cache->tab);
  4921. upb_arena_free(cache->arena);
  4922. upb_gfree(cache);
  4923. }
  4924. bool upb_handlercache_addcleanup(upb_handlercache *c, void *p,
  4925. upb_handlerfree *func) {
  4926. return upb_arena_addcleanup(c->arena, p, func);
  4927. }
  4928. /* upb_byteshandler ***********************************************************/
  4929. bool upb_byteshandler_setstartstr(upb_byteshandler *h,
  4930. upb_startstr_handlerfunc *func, void *d) {
  4931. h->table[UPB_STARTSTR_SELECTOR].func = (upb_func*)func;
  4932. h->table[UPB_STARTSTR_SELECTOR].attr.handler_data = d;
  4933. return true;
  4934. }
  4935. bool upb_byteshandler_setstring(upb_byteshandler *h,
  4936. upb_string_handlerfunc *func, void *d) {
  4937. h->table[UPB_STRING_SELECTOR].func = (upb_func*)func;
  4938. h->table[UPB_STRING_SELECTOR].attr.handler_data = d;
  4939. return true;
  4940. }
  4941. bool upb_byteshandler_setendstr(upb_byteshandler *h,
  4942. upb_endfield_handlerfunc *func, void *d) {
  4943. h->table[UPB_ENDSTR_SELECTOR].func = (upb_func*)func;
  4944. h->table[UPB_ENDSTR_SELECTOR].attr.handler_data = d;
  4945. return true;
  4946. }
  4947. /** Handlers for upb_msg ******************************************************/
  4948. typedef struct {
  4949. size_t offset;
  4950. int32_t hasbit;
  4951. } upb_msg_handlerdata;
  4952. /* Fallback implementation if the handler is not specialized by the producer. */
  4953. #define MSG_WRITER(type, ctype) \
  4954. bool upb_msg_set ## type (void *c, const void *hd, ctype val) { \
  4955. uint8_t *m = c; \
  4956. const upb_msg_handlerdata *d = hd; \
  4957. if (d->hasbit > 0) \
  4958. *(uint8_t*)&m[d->hasbit / 8] |= 1 << (d->hasbit % 8); \
  4959. *(ctype*)&m[d->offset] = val; \
  4960. return true; \
  4961. } \
  4962. MSG_WRITER(double, double)
  4963. MSG_WRITER(float, float)
  4964. MSG_WRITER(int32, int32_t)
  4965. MSG_WRITER(int64, int64_t)
  4966. MSG_WRITER(uint32, uint32_t)
  4967. MSG_WRITER(uint64, uint64_t)
  4968. MSG_WRITER(bool, bool)
  4969. bool upb_msg_setscalarhandler(upb_handlers *h, const upb_fielddef *f,
  4970. size_t offset, int32_t hasbit) {
  4971. upb_handlerattr attr = UPB_HANDLERATTR_INIT;
  4972. bool ok;
  4973. upb_msg_handlerdata *d = upb_gmalloc(sizeof(*d));
  4974. if (!d) return false;
  4975. d->offset = offset;
  4976. d->hasbit = hasbit;
  4977. attr.handler_data = d;
  4978. attr.alwaysok = true;
  4979. upb_handlers_addcleanup(h, d, upb_gfree);
  4980. #define TYPE(u, l) \
  4981. case UPB_TYPE_##u: \
  4982. ok = upb_handlers_set##l(h, f, upb_msg_set##l, &attr); break;
  4983. ok = false;
  4984. switch (upb_fielddef_type(f)) {
  4985. TYPE(INT64, int64);
  4986. TYPE(INT32, int32);
  4987. TYPE(ENUM, int32);
  4988. TYPE(UINT64, uint64);
  4989. TYPE(UINT32, uint32);
  4990. TYPE(DOUBLE, double);
  4991. TYPE(FLOAT, float);
  4992. TYPE(BOOL, bool);
  4993. default: UPB_ASSERT(false); break;
  4994. }
  4995. #undef TYPE
  4996. return ok;
  4997. }
  4998. bool upb_msg_getscalarhandlerdata(const upb_handlers *h,
  4999. upb_selector_t s,
  5000. upb_fieldtype_t *type,
  5001. size_t *offset,
  5002. int32_t *hasbit) {
  5003. const upb_msg_handlerdata *d;
  5004. const void *p;
  5005. upb_func *f = upb_handlers_gethandler(h, s, &p);
  5006. if ((upb_int64_handlerfunc*)f == upb_msg_setint64) {
  5007. *type = UPB_TYPE_INT64;
  5008. } else if ((upb_int32_handlerfunc*)f == upb_msg_setint32) {
  5009. *type = UPB_TYPE_INT32;
  5010. } else if ((upb_uint64_handlerfunc*)f == upb_msg_setuint64) {
  5011. *type = UPB_TYPE_UINT64;
  5012. } else if ((upb_uint32_handlerfunc*)f == upb_msg_setuint32) {
  5013. *type = UPB_TYPE_UINT32;
  5014. } else if ((upb_double_handlerfunc*)f == upb_msg_setdouble) {
  5015. *type = UPB_TYPE_DOUBLE;
  5016. } else if ((upb_float_handlerfunc*)f == upb_msg_setfloat) {
  5017. *type = UPB_TYPE_FLOAT;
  5018. } else if ((upb_bool_handlerfunc*)f == upb_msg_setbool) {
  5019. *type = UPB_TYPE_BOOL;
  5020. } else {
  5021. return false;
  5022. }
  5023. d = p;
  5024. *offset = d->offset;
  5025. *hasbit = d->hasbit;
  5026. return true;
  5027. }
  5028. bool upb_bufsrc_putbuf(const char *buf, size_t len, upb_bytessink sink) {
  5029. void *subc;
  5030. bool ret;
  5031. upb_bufhandle handle = UPB_BUFHANDLE_INIT;
  5032. handle.buf = buf;
  5033. ret = upb_bytessink_start(sink, len, &subc);
  5034. if (ret && len != 0) {
  5035. ret = (upb_bytessink_putbuf(sink, subc, buf, len, &handle) >= len);
  5036. }
  5037. if (ret) {
  5038. ret = upb_bytessink_end(sink);
  5039. }
  5040. return ret;
  5041. }
  5042. #ifdef UPB_MSVC_VSNPRINTF
  5043. /* Visual C++ earlier than 2015 doesn't have standard C99 snprintf and
  5044. * vsnprintf. To support them, missing functions are manually implemented
  5045. * using the existing secure functions. */
  5046. int msvc_vsnprintf(char* s, size_t n, const char* format, va_list arg) {
  5047. if (!s) {
  5048. return _vscprintf(format, arg);
  5049. }
  5050. int ret = _vsnprintf_s(s, n, _TRUNCATE, format, arg);
  5051. if (ret < 0) {
  5052. ret = _vscprintf(format, arg);
  5053. }
  5054. return ret;
  5055. }
  5056. int msvc_snprintf(char* s, size_t n, const char* format, ...) {
  5057. va_list arg;
  5058. va_start(arg, format);
  5059. int ret = msvc_vsnprintf(s, n, format, arg);
  5060. va_end(arg);
  5061. return ret;
  5062. }
  5063. #endif
  5064. /*
  5065. ** protobuf decoder bytecode compiler
  5066. **
  5067. ** Code to compile a upb::Handlers into bytecode for decoding a protobuf
  5068. ** according to that specific schema and destination handlers.
  5069. **
  5070. ** Bytecode definition is in decoder.int.h.
  5071. */
  5072. #include <stdarg.h>
  5073. #ifdef UPB_DUMP_BYTECODE
  5074. #include <stdio.h>
  5075. #endif
  5076. #define MAXLABEL 5
  5077. #define EMPTYLABEL -1
  5078. /* upb_pbdecodermethod ********************************************************/
  5079. static void freemethod(upb_pbdecodermethod *method) {
  5080. upb_inttable_uninit(&method->dispatch);
  5081. upb_gfree(method);
  5082. }
  5083. static upb_pbdecodermethod *newmethod(const upb_handlers *dest_handlers,
  5084. mgroup *group) {
  5085. upb_pbdecodermethod *ret = upb_gmalloc(sizeof(*ret));
  5086. upb_byteshandler_init(&ret->input_handler_);
  5087. ret->group = group;
  5088. ret->dest_handlers_ = dest_handlers;
  5089. upb_inttable_init(&ret->dispatch, UPB_CTYPE_UINT64);
  5090. return ret;
  5091. }
  5092. const upb_handlers *upb_pbdecodermethod_desthandlers(
  5093. const upb_pbdecodermethod *m) {
  5094. return m->dest_handlers_;
  5095. }
  5096. const upb_byteshandler *upb_pbdecodermethod_inputhandler(
  5097. const upb_pbdecodermethod *m) {
  5098. return &m->input_handler_;
  5099. }
  5100. bool upb_pbdecodermethod_isnative(const upb_pbdecodermethod *m) {
  5101. return m->is_native_;
  5102. }
  5103. /* mgroup *********************************************************************/
  5104. static void freegroup(mgroup *g) {
  5105. upb_inttable_iter i;
  5106. upb_inttable_begin(&i, &g->methods);
  5107. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5108. freemethod(upb_value_getptr(upb_inttable_iter_value(&i)));
  5109. }
  5110. upb_inttable_uninit(&g->methods);
  5111. upb_gfree(g->bytecode);
  5112. upb_gfree(g);
  5113. }
  5114. mgroup *newgroup(void) {
  5115. mgroup *g = upb_gmalloc(sizeof(*g));
  5116. upb_inttable_init(&g->methods, UPB_CTYPE_PTR);
  5117. g->bytecode = NULL;
  5118. g->bytecode_end = NULL;
  5119. return g;
  5120. }
  5121. /* bytecode compiler **********************************************************/
  5122. /* Data used only at compilation time. */
  5123. typedef struct {
  5124. mgroup *group;
  5125. uint32_t *pc;
  5126. int fwd_labels[MAXLABEL];
  5127. int back_labels[MAXLABEL];
  5128. /* For fields marked "lazy", parse them lazily or eagerly? */
  5129. bool lazy;
  5130. } compiler;
  5131. static compiler *newcompiler(mgroup *group, bool lazy) {
  5132. compiler *ret = upb_gmalloc(sizeof(*ret));
  5133. int i;
  5134. ret->group = group;
  5135. ret->lazy = lazy;
  5136. for (i = 0; i < MAXLABEL; i++) {
  5137. ret->fwd_labels[i] = EMPTYLABEL;
  5138. ret->back_labels[i] = EMPTYLABEL;
  5139. }
  5140. return ret;
  5141. }
  5142. static void freecompiler(compiler *c) {
  5143. upb_gfree(c);
  5144. }
  5145. const size_t ptr_words = sizeof(void*) / sizeof(uint32_t);
  5146. /* How many words an instruction is. */
  5147. static int instruction_len(uint32_t instr) {
  5148. switch (getop(instr)) {
  5149. case OP_SETDISPATCH: return 1 + ptr_words;
  5150. case OP_TAGN: return 3;
  5151. case OP_SETBIGGROUPNUM: return 2;
  5152. default: return 1;
  5153. }
  5154. }
  5155. bool op_has_longofs(int32_t instruction) {
  5156. switch (getop(instruction)) {
  5157. case OP_CALL:
  5158. case OP_BRANCH:
  5159. case OP_CHECKDELIM:
  5160. return true;
  5161. /* The "tag" instructions only have 8 bytes available for the jump target,
  5162. * but that is ok because these opcodes only require short jumps. */
  5163. case OP_TAG1:
  5164. case OP_TAG2:
  5165. case OP_TAGN:
  5166. return false;
  5167. default:
  5168. UPB_ASSERT(false);
  5169. return false;
  5170. }
  5171. }
  5172. static int32_t getofs(uint32_t instruction) {
  5173. if (op_has_longofs(instruction)) {
  5174. return (int32_t)instruction >> 8;
  5175. } else {
  5176. return (int8_t)(instruction >> 8);
  5177. }
  5178. }
  5179. static void setofs(uint32_t *instruction, int32_t ofs) {
  5180. if (op_has_longofs(*instruction)) {
  5181. *instruction = getop(*instruction) | (uint32_t)ofs << 8;
  5182. } else {
  5183. *instruction = (*instruction & ~0xff00) | ((ofs & 0xff) << 8);
  5184. }
  5185. UPB_ASSERT(getofs(*instruction) == ofs); /* Would fail in cases of overflow. */
  5186. }
  5187. static uint32_t pcofs(compiler *c) {
  5188. return (uint32_t)(c->pc - c->group->bytecode);
  5189. }
  5190. /* Defines a local label at the current PC location. All previous forward
  5191. * references are updated to point to this location. The location is noted
  5192. * for any future backward references. */
  5193. static void label(compiler *c, unsigned int label) {
  5194. int val;
  5195. uint32_t *codep;
  5196. UPB_ASSERT(label < MAXLABEL);
  5197. val = c->fwd_labels[label];
  5198. codep = (val == EMPTYLABEL) ? NULL : c->group->bytecode + val;
  5199. while (codep) {
  5200. int ofs = getofs(*codep);
  5201. setofs(codep, (int32_t)(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. */
  5215. static int32_t labelref(compiler *c, int label) {
  5216. UPB_ASSERT(label < MAXLABEL);
  5217. if (label == LABEL_DISPATCH) {
  5218. /* No resolving required. */
  5219. return 0;
  5220. } else if (label < 0) {
  5221. /* Backward local label. Relative to the next instruction. */
  5222. uint32_t from = (uint32_t)((c->pc + 1) - c->group->bytecode);
  5223. return c->back_labels[-label] - from;
  5224. } else {
  5225. /* Forward local label: prepend to (possibly-empty) linked list. */
  5226. int *lptr = &c->fwd_labels[label];
  5227. int32_t ret = (*lptr == EMPTYLABEL) ? 0 : *lptr - pcofs(c);
  5228. *lptr = pcofs(c);
  5229. return ret;
  5230. }
  5231. }
  5232. static void put32(compiler *c, uint32_t v) {
  5233. mgroup *g = c->group;
  5234. if (c->pc == g->bytecode_end) {
  5235. int ofs = pcofs(c);
  5236. size_t oldsize = g->bytecode_end - g->bytecode;
  5237. size_t newsize = UPB_MAX(oldsize * 2, 64);
  5238. /* TODO(haberman): handle OOM. */
  5239. g->bytecode = upb_grealloc(g->bytecode, oldsize * sizeof(uint32_t),
  5240. newsize * sizeof(uint32_t));
  5241. g->bytecode_end = g->bytecode + newsize;
  5242. c->pc = g->bytecode + ofs;
  5243. }
  5244. *c->pc++ = v;
  5245. }
  5246. static void putop(compiler *c, int op, ...) {
  5247. va_list ap;
  5248. va_start(ap, op);
  5249. switch (op) {
  5250. case OP_SETDISPATCH: {
  5251. uintptr_t ptr = (uintptr_t)va_arg(ap, void*);
  5252. put32(c, OP_SETDISPATCH);
  5253. put32(c, (uint32_t)ptr);
  5254. if (sizeof(uintptr_t) > sizeof(uint32_t))
  5255. put32(c, (uint64_t)ptr >> 32);
  5256. break;
  5257. }
  5258. case OP_STARTMSG:
  5259. case OP_ENDMSG:
  5260. case OP_PUSHLENDELIM:
  5261. case OP_POP:
  5262. case OP_SETDELIM:
  5263. case OP_HALT:
  5264. case OP_RET:
  5265. case OP_DISPATCH:
  5266. put32(c, op);
  5267. break;
  5268. case OP_PARSE_DOUBLE:
  5269. case OP_PARSE_FLOAT:
  5270. case OP_PARSE_INT64:
  5271. case OP_PARSE_UINT64:
  5272. case OP_PARSE_INT32:
  5273. case OP_PARSE_FIXED64:
  5274. case OP_PARSE_FIXED32:
  5275. case OP_PARSE_BOOL:
  5276. case OP_PARSE_UINT32:
  5277. case OP_PARSE_SFIXED32:
  5278. case OP_PARSE_SFIXED64:
  5279. case OP_PARSE_SINT32:
  5280. case OP_PARSE_SINT64:
  5281. case OP_STARTSEQ:
  5282. case OP_ENDSEQ:
  5283. case OP_STARTSUBMSG:
  5284. case OP_ENDSUBMSG:
  5285. case OP_STARTSTR:
  5286. case OP_STRING:
  5287. case OP_ENDSTR:
  5288. case OP_PUSHTAGDELIM:
  5289. put32(c, op | va_arg(ap, upb_selector_t) << 8);
  5290. break;
  5291. case OP_SETBIGGROUPNUM:
  5292. put32(c, op);
  5293. put32(c, va_arg(ap, int));
  5294. break;
  5295. case OP_CALL: {
  5296. const upb_pbdecodermethod *method = va_arg(ap, upb_pbdecodermethod *);
  5297. put32(c, op | (method->code_base.ofs - (pcofs(c) + 1)) << 8);
  5298. break;
  5299. }
  5300. case OP_CHECKDELIM:
  5301. case OP_BRANCH: {
  5302. uint32_t instruction = op;
  5303. int label = va_arg(ap, int);
  5304. setofs(&instruction, labelref(c, label));
  5305. put32(c, instruction);
  5306. break;
  5307. }
  5308. case OP_TAG1:
  5309. case OP_TAG2: {
  5310. int label = va_arg(ap, int);
  5311. uint64_t tag = va_arg(ap, uint64_t);
  5312. uint32_t instruction = (uint32_t)(op | (tag << 16));
  5313. UPB_ASSERT(tag <= 0xffff);
  5314. setofs(&instruction, labelref(c, label));
  5315. put32(c, instruction);
  5316. break;
  5317. }
  5318. case OP_TAGN: {
  5319. int label = va_arg(ap, int);
  5320. uint64_t tag = va_arg(ap, uint64_t);
  5321. uint32_t instruction = op | (upb_value_size(tag) << 16);
  5322. setofs(&instruction, labelref(c, label));
  5323. put32(c, instruction);
  5324. put32(c, (uint32_t)tag);
  5325. put32(c, tag >> 32);
  5326. break;
  5327. }
  5328. }
  5329. va_end(ap);
  5330. }
  5331. #if defined(UPB_DUMP_BYTECODE)
  5332. const char *upb_pbdecoder_getopname(unsigned int op) {
  5333. #define QUOTE(x) #x
  5334. #define EXPAND_AND_QUOTE(x) QUOTE(x)
  5335. #define OPNAME(x) OP_##x
  5336. #define OP(x) case OPNAME(x): return EXPAND_AND_QUOTE(OPNAME(x));
  5337. #define T(x) OP(PARSE_##x)
  5338. /* Keep in sync with list in decoder.int.h. */
  5339. switch ((opcode)op) {
  5340. T(DOUBLE) T(FLOAT) T(INT64) T(UINT64) T(INT32) T(FIXED64) T(FIXED32)
  5341. T(BOOL) T(UINT32) T(SFIXED32) T(SFIXED64) T(SINT32) T(SINT64)
  5342. OP(STARTMSG) OP(ENDMSG) OP(STARTSEQ) OP(ENDSEQ) OP(STARTSUBMSG)
  5343. OP(ENDSUBMSG) OP(STARTSTR) OP(STRING) OP(ENDSTR) OP(CALL) OP(RET)
  5344. OP(PUSHLENDELIM) OP(PUSHTAGDELIM) OP(SETDELIM) OP(CHECKDELIM)
  5345. OP(BRANCH) OP(TAG1) OP(TAG2) OP(TAGN) OP(SETDISPATCH) OP(POP)
  5346. OP(SETBIGGROUPNUM) OP(DISPATCH) OP(HALT)
  5347. }
  5348. return "<unknown op>";
  5349. #undef OP
  5350. #undef T
  5351. }
  5352. #endif
  5353. #ifdef UPB_DUMP_BYTECODE
  5354. static void dumpbc(uint32_t *p, uint32_t *end, FILE *f) {
  5355. uint32_t *begin = p;
  5356. while (p < end) {
  5357. fprintf(f, "%p %8tx", p, p - begin);
  5358. uint32_t instr = *p++;
  5359. uint8_t op = getop(instr);
  5360. fprintf(f, " %s", upb_pbdecoder_getopname(op));
  5361. switch ((opcode)op) {
  5362. case OP_SETDISPATCH: {
  5363. const upb_inttable *dispatch;
  5364. memcpy(&dispatch, p, sizeof(void*));
  5365. p += ptr_words;
  5366. const upb_pbdecodermethod *method =
  5367. (void *)((char *)dispatch -
  5368. offsetof(upb_pbdecodermethod, dispatch));
  5369. fprintf(f, " %s", upb_msgdef_fullname(
  5370. upb_handlers_msgdef(method->dest_handlers_)));
  5371. break;
  5372. }
  5373. case OP_DISPATCH:
  5374. case OP_STARTMSG:
  5375. case OP_ENDMSG:
  5376. case OP_PUSHLENDELIM:
  5377. case OP_POP:
  5378. case OP_SETDELIM:
  5379. case OP_HALT:
  5380. case OP_RET:
  5381. break;
  5382. case OP_PARSE_DOUBLE:
  5383. case OP_PARSE_FLOAT:
  5384. case OP_PARSE_INT64:
  5385. case OP_PARSE_UINT64:
  5386. case OP_PARSE_INT32:
  5387. case OP_PARSE_FIXED64:
  5388. case OP_PARSE_FIXED32:
  5389. case OP_PARSE_BOOL:
  5390. case OP_PARSE_UINT32:
  5391. case OP_PARSE_SFIXED32:
  5392. case OP_PARSE_SFIXED64:
  5393. case OP_PARSE_SINT32:
  5394. case OP_PARSE_SINT64:
  5395. case OP_STARTSEQ:
  5396. case OP_ENDSEQ:
  5397. case OP_STARTSUBMSG:
  5398. case OP_ENDSUBMSG:
  5399. case OP_STARTSTR:
  5400. case OP_STRING:
  5401. case OP_ENDSTR:
  5402. case OP_PUSHTAGDELIM:
  5403. fprintf(f, " %d", instr >> 8);
  5404. break;
  5405. case OP_SETBIGGROUPNUM:
  5406. fprintf(f, " %d", *p++);
  5407. break;
  5408. case OP_CHECKDELIM:
  5409. case OP_CALL:
  5410. case OP_BRANCH:
  5411. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  5412. break;
  5413. case OP_TAG1:
  5414. case OP_TAG2: {
  5415. fprintf(f, " tag:0x%x", instr >> 16);
  5416. if (getofs(instr)) {
  5417. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  5418. }
  5419. break;
  5420. }
  5421. case OP_TAGN: {
  5422. uint64_t tag = *p++;
  5423. tag |= (uint64_t)*p++ << 32;
  5424. fprintf(f, " tag:0x%llx", (long long)tag);
  5425. fprintf(f, " n:%d", instr >> 16);
  5426. if (getofs(instr)) {
  5427. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  5428. }
  5429. break;
  5430. }
  5431. }
  5432. fputs("\n", f);
  5433. }
  5434. }
  5435. #endif
  5436. static uint64_t get_encoded_tag(const upb_fielddef *f, int wire_type) {
  5437. uint32_t tag = (upb_fielddef_number(f) << 3) | wire_type;
  5438. uint64_t encoded_tag = upb_vencode32(tag);
  5439. /* No tag should be greater than 5 bytes. */
  5440. UPB_ASSERT(encoded_tag <= 0xffffffffff);
  5441. return encoded_tag;
  5442. }
  5443. static void putchecktag(compiler *c, const upb_fielddef *f,
  5444. int wire_type, int dest) {
  5445. uint64_t tag = get_encoded_tag(f, wire_type);
  5446. switch (upb_value_size(tag)) {
  5447. case 1:
  5448. putop(c, OP_TAG1, dest, tag);
  5449. break;
  5450. case 2:
  5451. putop(c, OP_TAG2, dest, tag);
  5452. break;
  5453. default:
  5454. putop(c, OP_TAGN, dest, tag);
  5455. break;
  5456. }
  5457. }
  5458. static upb_selector_t getsel(const upb_fielddef *f, upb_handlertype_t type) {
  5459. upb_selector_t selector;
  5460. bool ok = upb_handlers_getselector(f, type, &selector);
  5461. UPB_ASSERT(ok);
  5462. return selector;
  5463. }
  5464. /* Takes an existing, primary dispatch table entry and repacks it with a
  5465. * different alternate wire type. Called when we are inserting a secondary
  5466. * dispatch table entry for an alternate wire type. */
  5467. static uint64_t repack(uint64_t dispatch, int new_wt2) {
  5468. uint64_t ofs;
  5469. uint8_t wt1;
  5470. uint8_t old_wt2;
  5471. upb_pbdecoder_unpackdispatch(dispatch, &ofs, &wt1, &old_wt2);
  5472. UPB_ASSERT(old_wt2 == NO_WIRE_TYPE); /* wt2 should not be set yet. */
  5473. return upb_pbdecoder_packdispatch(ofs, wt1, new_wt2);
  5474. }
  5475. /* Marks the current bytecode position as the dispatch target for this message,
  5476. * field, and wire type. */
  5477. static void dispatchtarget(compiler *c, upb_pbdecodermethod *method,
  5478. const upb_fielddef *f, int wire_type) {
  5479. /* Offset is relative to msg base. */
  5480. uint64_t ofs = pcofs(c) - method->code_base.ofs;
  5481. uint32_t fn = upb_fielddef_number(f);
  5482. upb_inttable *d = &method->dispatch;
  5483. upb_value v;
  5484. if (upb_inttable_remove(d, fn, &v)) {
  5485. /* TODO: prioritize based on packed setting in .proto file. */
  5486. uint64_t repacked = repack(upb_value_getuint64(v), wire_type);
  5487. upb_inttable_insert(d, fn, upb_value_uint64(repacked));
  5488. upb_inttable_insert(d, fn + UPB_MAX_FIELDNUMBER, upb_value_uint64(ofs));
  5489. } else {
  5490. uint64_t val = upb_pbdecoder_packdispatch(ofs, wire_type, NO_WIRE_TYPE);
  5491. upb_inttable_insert(d, fn, upb_value_uint64(val));
  5492. }
  5493. }
  5494. static void putpush(compiler *c, const upb_fielddef *f) {
  5495. if (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE) {
  5496. putop(c, OP_PUSHLENDELIM);
  5497. } else {
  5498. uint32_t fn = upb_fielddef_number(f);
  5499. if (fn >= 1 << 24) {
  5500. putop(c, OP_PUSHTAGDELIM, 0);
  5501. putop(c, OP_SETBIGGROUPNUM, fn);
  5502. } else {
  5503. putop(c, OP_PUSHTAGDELIM, fn);
  5504. }
  5505. }
  5506. }
  5507. static upb_pbdecodermethod *find_submethod(const compiler *c,
  5508. const upb_pbdecodermethod *method,
  5509. const upb_fielddef *f) {
  5510. const upb_handlers *sub =
  5511. upb_handlers_getsubhandlers(method->dest_handlers_, f);
  5512. upb_value v;
  5513. return upb_inttable_lookupptr(&c->group->methods, sub, &v)
  5514. ? upb_value_getptr(v)
  5515. : NULL;
  5516. }
  5517. static void putsel(compiler *c, opcode op, upb_selector_t sel,
  5518. const upb_handlers *h) {
  5519. if (upb_handlers_gethandler(h, sel, NULL)) {
  5520. putop(c, op, sel);
  5521. }
  5522. }
  5523. /* Puts an opcode to call a callback, but only if a callback actually exists for
  5524. * this field and handler type. */
  5525. static void maybeput(compiler *c, opcode op, const upb_handlers *h,
  5526. const upb_fielddef *f, upb_handlertype_t type) {
  5527. putsel(c, op, getsel(f, type), h);
  5528. }
  5529. static bool haslazyhandlers(const upb_handlers *h, const upb_fielddef *f) {
  5530. if (!upb_fielddef_lazy(f))
  5531. return false;
  5532. return upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STARTSTR), NULL) ||
  5533. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STRING), NULL) ||
  5534. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_ENDSTR), NULL);
  5535. }
  5536. /* bytecode compiler code generation ******************************************/
  5537. /* Symbolic names for our local labels. */
  5538. #define LABEL_LOOPSTART 1 /* Top of a repeated field loop. */
  5539. #define LABEL_LOOPBREAK 2 /* To jump out of a repeated loop */
  5540. #define LABEL_FIELD 3 /* Jump backward to find the most recent field. */
  5541. #define LABEL_ENDMSG 4 /* To reach the OP_ENDMSG instr for this msg. */
  5542. /* Generates bytecode to parse a single non-lazy message field. */
  5543. static void generate_msgfield(compiler *c, const upb_fielddef *f,
  5544. upb_pbdecodermethod *method) {
  5545. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  5546. const upb_pbdecodermethod *sub_m = find_submethod(c, method, f);
  5547. int wire_type;
  5548. if (!sub_m) {
  5549. /* Don't emit any code for this field at all; it will be parsed as an
  5550. * unknown field.
  5551. *
  5552. * TODO(haberman): we should change this to parse it as a string field
  5553. * instead. It will probably be faster, but more importantly, once we
  5554. * start vending unknown fields, a field shouldn't be treated as unknown
  5555. * just because it doesn't have subhandlers registered. */
  5556. return;
  5557. }
  5558. label(c, LABEL_FIELD);
  5559. wire_type =
  5560. (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE)
  5561. ? UPB_WIRE_TYPE_DELIMITED
  5562. : UPB_WIRE_TYPE_START_GROUP;
  5563. if (upb_fielddef_isseq(f)) {
  5564. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5565. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  5566. dispatchtarget(c, method, f, wire_type);
  5567. putop(c, OP_PUSHTAGDELIM, 0);
  5568. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  5569. label(c, LABEL_LOOPSTART);
  5570. putpush(c, f);
  5571. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  5572. putop(c, OP_CALL, sub_m);
  5573. putop(c, OP_POP);
  5574. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  5575. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  5576. putop(c, OP_SETDELIM);
  5577. }
  5578. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5579. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  5580. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5581. label(c, LABEL_LOOPBREAK);
  5582. putop(c, OP_POP);
  5583. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  5584. } else {
  5585. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5586. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  5587. dispatchtarget(c, method, f, wire_type);
  5588. putpush(c, f);
  5589. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  5590. putop(c, OP_CALL, sub_m);
  5591. putop(c, OP_POP);
  5592. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  5593. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  5594. putop(c, OP_SETDELIM);
  5595. }
  5596. }
  5597. }
  5598. /* Generates bytecode to parse a single string or lazy submessage field. */
  5599. static void generate_delimfield(compiler *c, const upb_fielddef *f,
  5600. upb_pbdecodermethod *method) {
  5601. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  5602. label(c, LABEL_FIELD);
  5603. if (upb_fielddef_isseq(f)) {
  5604. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5605. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  5606. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  5607. putop(c, OP_PUSHTAGDELIM, 0);
  5608. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  5609. label(c, LABEL_LOOPSTART);
  5610. putop(c, OP_PUSHLENDELIM);
  5611. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  5612. /* Need to emit even if no handler to skip past the string. */
  5613. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  5614. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  5615. putop(c, OP_POP);
  5616. putop(c, OP_SETDELIM);
  5617. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5618. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_LOOPBREAK);
  5619. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5620. label(c, LABEL_LOOPBREAK);
  5621. putop(c, OP_POP);
  5622. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  5623. } else {
  5624. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5625. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  5626. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  5627. putop(c, OP_PUSHLENDELIM);
  5628. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  5629. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  5630. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  5631. putop(c, OP_POP);
  5632. putop(c, OP_SETDELIM);
  5633. }
  5634. }
  5635. /* Generates bytecode to parse a single primitive field. */
  5636. static void generate_primitivefield(compiler *c, const upb_fielddef *f,
  5637. upb_pbdecodermethod *method) {
  5638. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  5639. upb_descriptortype_t descriptor_type = upb_fielddef_descriptortype(f);
  5640. opcode parse_type;
  5641. upb_selector_t sel;
  5642. int wire_type;
  5643. label(c, LABEL_FIELD);
  5644. /* From a decoding perspective, ENUM is the same as INT32. */
  5645. if (descriptor_type == UPB_DESCRIPTOR_TYPE_ENUM)
  5646. descriptor_type = UPB_DESCRIPTOR_TYPE_INT32;
  5647. parse_type = (opcode)descriptor_type;
  5648. /* TODO(haberman): generate packed or non-packed first depending on "packed"
  5649. * setting in the fielddef. This will favor (in speed) whichever was
  5650. * specified. */
  5651. UPB_ASSERT((int)parse_type >= 0 && parse_type <= OP_MAX);
  5652. sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  5653. wire_type = upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  5654. if (upb_fielddef_isseq(f)) {
  5655. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5656. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  5657. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  5658. putop(c, OP_PUSHLENDELIM);
  5659. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); /* Packed */
  5660. label(c, LABEL_LOOPSTART);
  5661. putop(c, parse_type, sel);
  5662. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5663. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5664. dispatchtarget(c, method, f, wire_type);
  5665. putop(c, OP_PUSHTAGDELIM, 0);
  5666. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); /* Non-packed */
  5667. label(c, LABEL_LOOPSTART);
  5668. putop(c, parse_type, sel);
  5669. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5670. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  5671. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5672. label(c, LABEL_LOOPBREAK);
  5673. putop(c, OP_POP); /* Packed and non-packed join. */
  5674. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  5675. putop(c, OP_SETDELIM); /* Could remove for non-packed by dup ENDSEQ. */
  5676. } else {
  5677. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5678. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  5679. dispatchtarget(c, method, f, wire_type);
  5680. putop(c, parse_type, sel);
  5681. }
  5682. }
  5683. /* Adds bytecode for parsing the given message to the given decoderplan,
  5684. * while adding all dispatch targets to this message's dispatch table. */
  5685. static void compile_method(compiler *c, upb_pbdecodermethod *method) {
  5686. const upb_handlers *h;
  5687. const upb_msgdef *md;
  5688. uint32_t* start_pc;
  5689. upb_msg_field_iter i;
  5690. upb_value val;
  5691. UPB_ASSERT(method);
  5692. /* Clear all entries in the dispatch table. */
  5693. upb_inttable_uninit(&method->dispatch);
  5694. upb_inttable_init(&method->dispatch, UPB_CTYPE_UINT64);
  5695. h = upb_pbdecodermethod_desthandlers(method);
  5696. md = upb_handlers_msgdef(h);
  5697. method->code_base.ofs = pcofs(c);
  5698. putop(c, OP_SETDISPATCH, &method->dispatch);
  5699. putsel(c, OP_STARTMSG, UPB_STARTMSG_SELECTOR, h);
  5700. label(c, LABEL_FIELD);
  5701. start_pc = c->pc;
  5702. for(upb_msg_field_begin(&i, md);
  5703. !upb_msg_field_done(&i);
  5704. upb_msg_field_next(&i)) {
  5705. const upb_fielddef *f = upb_msg_iter_field(&i);
  5706. upb_fieldtype_t type = upb_fielddef_type(f);
  5707. if (type == UPB_TYPE_MESSAGE && !(haslazyhandlers(h, f) && c->lazy)) {
  5708. generate_msgfield(c, f, method);
  5709. } else if (type == UPB_TYPE_STRING || type == UPB_TYPE_BYTES ||
  5710. type == UPB_TYPE_MESSAGE) {
  5711. generate_delimfield(c, f, method);
  5712. } else {
  5713. generate_primitivefield(c, f, method);
  5714. }
  5715. }
  5716. /* If there were no fields, or if no handlers were defined, we need to
  5717. * generate a non-empty loop body so that we can at least dispatch for unknown
  5718. * fields and check for the end of the message. */
  5719. if (c->pc == start_pc) {
  5720. /* Check for end-of-message. */
  5721. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5722. /* Unconditionally dispatch. */
  5723. putop(c, OP_DISPATCH, 0);
  5724. }
  5725. /* For now we just loop back to the last field of the message (or if none,
  5726. * the DISPATCH opcode for the message). */
  5727. putop(c, OP_BRANCH, -LABEL_FIELD);
  5728. /* Insert both a label and a dispatch table entry for this end-of-msg. */
  5729. label(c, LABEL_ENDMSG);
  5730. val = upb_value_uint64(pcofs(c) - method->code_base.ofs);
  5731. upb_inttable_insert(&method->dispatch, DISPATCH_ENDMSG, val);
  5732. putsel(c, OP_ENDMSG, UPB_ENDMSG_SELECTOR, h);
  5733. putop(c, OP_RET);
  5734. upb_inttable_compact(&method->dispatch);
  5735. }
  5736. /* Populate "methods" with new upb_pbdecodermethod objects reachable from "h".
  5737. * Returns the method for these handlers.
  5738. *
  5739. * Generates a new method for every destination handlers reachable from "h". */
  5740. static void find_methods(compiler *c, const upb_handlers *h) {
  5741. upb_value v;
  5742. upb_msg_field_iter i;
  5743. const upb_msgdef *md;
  5744. upb_pbdecodermethod *method;
  5745. if (upb_inttable_lookupptr(&c->group->methods, h, &v))
  5746. return;
  5747. method = newmethod(h, c->group);
  5748. upb_inttable_insertptr(&c->group->methods, h, upb_value_ptr(method));
  5749. /* Find submethods. */
  5750. md = upb_handlers_msgdef(h);
  5751. for(upb_msg_field_begin(&i, md);
  5752. !upb_msg_field_done(&i);
  5753. upb_msg_field_next(&i)) {
  5754. const upb_fielddef *f = upb_msg_iter_field(&i);
  5755. const upb_handlers *sub_h;
  5756. if (upb_fielddef_type(f) == UPB_TYPE_MESSAGE &&
  5757. (sub_h = upb_handlers_getsubhandlers(h, f)) != NULL) {
  5758. /* We only generate a decoder method for submessages with handlers.
  5759. * Others will be parsed as unknown fields. */
  5760. find_methods(c, sub_h);
  5761. }
  5762. }
  5763. }
  5764. /* (Re-)compile bytecode for all messages in "msgs."
  5765. * Overwrites any existing bytecode in "c". */
  5766. static void compile_methods(compiler *c) {
  5767. upb_inttable_iter i;
  5768. /* Start over at the beginning of the bytecode. */
  5769. c->pc = c->group->bytecode;
  5770. upb_inttable_begin(&i, &c->group->methods);
  5771. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5772. upb_pbdecodermethod *method = upb_value_getptr(upb_inttable_iter_value(&i));
  5773. compile_method(c, method);
  5774. }
  5775. }
  5776. static void set_bytecode_handlers(mgroup *g) {
  5777. upb_inttable_iter i;
  5778. upb_inttable_begin(&i, &g->methods);
  5779. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5780. upb_pbdecodermethod *m = upb_value_getptr(upb_inttable_iter_value(&i));
  5781. upb_byteshandler *h = &m->input_handler_;
  5782. m->code_base.ptr = g->bytecode + m->code_base.ofs;
  5783. upb_byteshandler_setstartstr(h, upb_pbdecoder_startbc, m->code_base.ptr);
  5784. upb_byteshandler_setstring(h, upb_pbdecoder_decode, g);
  5785. upb_byteshandler_setendstr(h, upb_pbdecoder_end, m);
  5786. }
  5787. }
  5788. /* TODO(haberman): allow this to be constructed for an arbitrary set of dest
  5789. * handlers and other mgroups (but verify we have a transitive closure). */
  5790. const mgroup *mgroup_new(const upb_handlers *dest, bool lazy) {
  5791. mgroup *g;
  5792. compiler *c;
  5793. g = newgroup();
  5794. c = newcompiler(g, lazy);
  5795. find_methods(c, dest);
  5796. /* We compile in two passes:
  5797. * 1. all messages are assigned relative offsets from the beginning of the
  5798. * bytecode (saved in method->code_base).
  5799. * 2. forwards OP_CALL instructions can be correctly linked since message
  5800. * offsets have been previously assigned.
  5801. *
  5802. * Could avoid the second pass by linking OP_CALL instructions somehow. */
  5803. compile_methods(c);
  5804. compile_methods(c);
  5805. g->bytecode_end = c->pc;
  5806. freecompiler(c);
  5807. #ifdef UPB_DUMP_BYTECODE
  5808. {
  5809. FILE *f = fopen("/tmp/upb-bytecode", "w");
  5810. UPB_ASSERT(f);
  5811. dumpbc(g->bytecode, g->bytecode_end, stderr);
  5812. dumpbc(g->bytecode, g->bytecode_end, f);
  5813. fclose(f);
  5814. f = fopen("/tmp/upb-bytecode.bin", "wb");
  5815. UPB_ASSERT(f);
  5816. fwrite(g->bytecode, 1, g->bytecode_end - g->bytecode, f);
  5817. fclose(f);
  5818. }
  5819. #endif
  5820. set_bytecode_handlers(g);
  5821. return g;
  5822. }
  5823. /* upb_pbcodecache ************************************************************/
  5824. upb_pbcodecache *upb_pbcodecache_new(upb_handlercache *dest) {
  5825. upb_pbcodecache *c = upb_gmalloc(sizeof(*c));
  5826. if (!c) return NULL;
  5827. c->dest = dest;
  5828. c->lazy = false;
  5829. c->arena = upb_arena_new();
  5830. if (!upb_inttable_init(&c->groups, UPB_CTYPE_CONSTPTR)) return NULL;
  5831. return c;
  5832. }
  5833. void upb_pbcodecache_free(upb_pbcodecache *c) {
  5834. upb_inttable_iter i;
  5835. upb_inttable_begin(&i, &c->groups);
  5836. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5837. upb_value val = upb_inttable_iter_value(&i);
  5838. freegroup((void*)upb_value_getconstptr(val));
  5839. }
  5840. upb_inttable_uninit(&c->groups);
  5841. upb_arena_free(c->arena);
  5842. upb_gfree(c);
  5843. }
  5844. void upb_pbdecodermethodopts_setlazy(upb_pbcodecache *c, bool lazy) {
  5845. UPB_ASSERT(upb_inttable_count(&c->groups) == 0);
  5846. c->lazy = lazy;
  5847. }
  5848. const upb_pbdecodermethod *upb_pbcodecache_get(upb_pbcodecache *c,
  5849. const upb_msgdef *md) {
  5850. upb_value v;
  5851. bool ok;
  5852. const upb_handlers *h;
  5853. const mgroup *g;
  5854. h = upb_handlercache_get(c->dest, md);
  5855. if (upb_inttable_lookupptr(&c->groups, md, &v)) {
  5856. g = upb_value_getconstptr(v);
  5857. } else {
  5858. g = mgroup_new(h, c->lazy);
  5859. ok = upb_inttable_insertptr(&c->groups, md, upb_value_constptr(g));
  5860. UPB_ASSUME(ok);
  5861. }
  5862. ok = upb_inttable_lookupptr(&g->methods, h, &v);
  5863. UPB_ASSUME(ok);
  5864. return upb_value_getptr(v);
  5865. }
  5866. /*
  5867. ** upb::Decoder (Bytecode Decoder VM)
  5868. **
  5869. ** Bytecode must previously have been generated using the bytecode compiler in
  5870. ** compile_decoder.c. This decoder then walks through the bytecode op-by-op to
  5871. ** parse the input.
  5872. **
  5873. ** Decoding is fully resumable; we just keep a pointer to the current bytecode
  5874. ** instruction and resume from there. A fair amount of the logic here is to
  5875. ** handle the fact that values can span buffer seams and we have to be able to
  5876. ** be capable of suspending/resuming from any byte in the stream. This
  5877. ** sometimes requires keeping a few trailing bytes from the last buffer around
  5878. ** in the "residual" buffer.
  5879. */
  5880. #include <inttypes.h>
  5881. #include <stddef.h>
  5882. #ifdef UPB_DUMP_BYTECODE
  5883. #include <stdio.h>
  5884. #endif
  5885. #define CHECK_SUSPEND(x) if (!(x)) return upb_pbdecoder_suspend(d);
  5886. /* Error messages that are shared between the bytecode and JIT decoders. */
  5887. const char *kPbDecoderStackOverflow = "Nesting too deep.";
  5888. const char *kPbDecoderSubmessageTooLong =
  5889. "Submessage end extends past enclosing submessage.";
  5890. /* Error messages shared within this file. */
  5891. static const char *kUnterminatedVarint = "Unterminated varint.";
  5892. /* upb_pbdecoder **************************************************************/
  5893. static opcode halt = OP_HALT;
  5894. /* A dummy character we can point to when the user passes us a NULL buffer.
  5895. * We need this because in C (NULL + 0) and (NULL - NULL) are undefined
  5896. * behavior, which would invalidate functions like curbufleft(). */
  5897. static const char dummy_char;
  5898. /* Whether an op consumes any of the input buffer. */
  5899. static bool consumes_input(opcode op) {
  5900. switch (op) {
  5901. case OP_SETDISPATCH:
  5902. case OP_STARTMSG:
  5903. case OP_ENDMSG:
  5904. case OP_STARTSEQ:
  5905. case OP_ENDSEQ:
  5906. case OP_STARTSUBMSG:
  5907. case OP_ENDSUBMSG:
  5908. case OP_STARTSTR:
  5909. case OP_ENDSTR:
  5910. case OP_PUSHTAGDELIM:
  5911. case OP_POP:
  5912. case OP_SETDELIM:
  5913. case OP_SETBIGGROUPNUM:
  5914. case OP_CHECKDELIM:
  5915. case OP_CALL:
  5916. case OP_RET:
  5917. case OP_BRANCH:
  5918. return false;
  5919. default:
  5920. return true;
  5921. }
  5922. }
  5923. static size_t stacksize(upb_pbdecoder *d, size_t entries) {
  5924. UPB_UNUSED(d);
  5925. return entries * sizeof(upb_pbdecoder_frame);
  5926. }
  5927. static size_t callstacksize(upb_pbdecoder *d, size_t entries) {
  5928. UPB_UNUSED(d);
  5929. return entries * sizeof(uint32_t*);
  5930. }
  5931. static bool in_residual_buf(const upb_pbdecoder *d, const char *p);
  5932. /* It's unfortunate that we have to micro-manage the compiler with
  5933. * UPB_FORCEINLINE and UPB_NOINLINE, especially since this tuning is necessarily
  5934. * specific to one hardware configuration. But empirically on a Core i7,
  5935. * performance increases 30-50% with these annotations. Every instance where
  5936. * these appear, gcc 4.2.1 made the wrong decision and degraded performance in
  5937. * benchmarks. */
  5938. static void seterr(upb_pbdecoder *d, const char *msg) {
  5939. upb_status_seterrmsg(d->status, msg);
  5940. }
  5941. void upb_pbdecoder_seterr(upb_pbdecoder *d, const char *msg) {
  5942. seterr(d, msg);
  5943. }
  5944. /* Buffering ******************************************************************/
  5945. /* We operate on one buffer at a time, which is either the user's buffer passed
  5946. * to our "decode" callback or some residual bytes from the previous buffer. */
  5947. /* How many bytes can be safely read from d->ptr without reading past end-of-buf
  5948. * or past the current delimited end. */
  5949. static size_t curbufleft(const upb_pbdecoder *d) {
  5950. UPB_ASSERT(d->data_end >= d->ptr);
  5951. return d->data_end - d->ptr;
  5952. }
  5953. /* How many bytes are available before end-of-buffer. */
  5954. static size_t bufleft(const upb_pbdecoder *d) {
  5955. return d->end - d->ptr;
  5956. }
  5957. /* Overall stream offset of d->ptr. */
  5958. uint64_t offset(const upb_pbdecoder *d) {
  5959. return d->bufstart_ofs + (d->ptr - d->buf);
  5960. }
  5961. /* How many bytes are available before the end of this delimited region. */
  5962. size_t delim_remaining(const upb_pbdecoder *d) {
  5963. return d->top->end_ofs - offset(d);
  5964. }
  5965. /* Advances d->ptr. */
  5966. static void advance(upb_pbdecoder *d, size_t len) {
  5967. UPB_ASSERT(curbufleft(d) >= len);
  5968. d->ptr += len;
  5969. }
  5970. static bool in_buf(const char *p, const char *buf, const char *end) {
  5971. return p >= buf && p <= end;
  5972. }
  5973. static bool in_residual_buf(const upb_pbdecoder *d, const char *p) {
  5974. return in_buf(p, d->residual, d->residual_end);
  5975. }
  5976. /* Calculates the delim_end value, which is affected by both the current buffer
  5977. * and the parsing stack, so must be called whenever either is updated. */
  5978. static void set_delim_end(upb_pbdecoder *d) {
  5979. size_t delim_ofs = d->top->end_ofs - d->bufstart_ofs;
  5980. if (delim_ofs <= (size_t)(d->end - d->buf)) {
  5981. d->delim_end = d->buf + delim_ofs;
  5982. d->data_end = d->delim_end;
  5983. } else {
  5984. d->data_end = d->end;
  5985. d->delim_end = NULL;
  5986. }
  5987. }
  5988. static void switchtobuf(upb_pbdecoder *d, const char *buf, const char *end) {
  5989. d->ptr = buf;
  5990. d->buf = buf;
  5991. d->end = end;
  5992. set_delim_end(d);
  5993. }
  5994. static void advancetobuf(upb_pbdecoder *d, const char *buf, size_t len) {
  5995. UPB_ASSERT(curbufleft(d) == 0);
  5996. d->bufstart_ofs += (d->end - d->buf);
  5997. switchtobuf(d, buf, buf + len);
  5998. }
  5999. static void checkpoint(upb_pbdecoder *d) {
  6000. /* The assertion here is in the interests of efficiency, not correctness.
  6001. * We are trying to ensure that we don't checkpoint() more often than
  6002. * necessary. */
  6003. UPB_ASSERT(d->checkpoint != d->ptr);
  6004. d->checkpoint = d->ptr;
  6005. }
  6006. /* Skips "bytes" bytes in the stream, which may be more than available. If we
  6007. * skip more bytes than are available, we return a long read count to the caller
  6008. * indicating how many bytes can be skipped over before passing actual data
  6009. * again. Skipped bytes can pass a NULL buffer and the decoder guarantees they
  6010. * won't actually be read.
  6011. */
  6012. static int32_t skip(upb_pbdecoder *d, size_t bytes) {
  6013. UPB_ASSERT(!in_residual_buf(d, d->ptr) || d->size_param == 0);
  6014. UPB_ASSERT(d->skip == 0);
  6015. if (bytes > delim_remaining(d)) {
  6016. seterr(d, "Skipped value extended beyond enclosing submessage.");
  6017. return (int32_t)upb_pbdecoder_suspend(d);
  6018. } else if (bufleft(d) >= bytes) {
  6019. /* Skipped data is all in current buffer, and more is still available. */
  6020. advance(d, bytes);
  6021. d->skip = 0;
  6022. return DECODE_OK;
  6023. } else {
  6024. /* Skipped data extends beyond currently available buffers. */
  6025. d->pc = d->last;
  6026. d->skip = bytes - curbufleft(d);
  6027. d->bufstart_ofs += (d->end - d->buf);
  6028. d->residual_end = d->residual;
  6029. switchtobuf(d, d->residual, d->residual_end);
  6030. return (int32_t)(d->size_param + d->skip);
  6031. }
  6032. }
  6033. /* Resumes the decoder from an initial state or from a previous suspend. */
  6034. int32_t upb_pbdecoder_resume(upb_pbdecoder *d, void *p, const char *buf,
  6035. size_t size, const upb_bufhandle *handle) {
  6036. UPB_UNUSED(p); /* Useless; just for the benefit of the JIT. */
  6037. /* d->skip and d->residual_end could probably elegantly be represented
  6038. * as a single variable, to more easily represent this invariant. */
  6039. UPB_ASSERT(!(d->skip && d->residual_end > d->residual));
  6040. /* We need to remember the original size_param, so that the value we return
  6041. * is relative to it, even if we do some skipping first. */
  6042. d->size_param = size;
  6043. d->handle = handle;
  6044. /* Have to handle this case specially (ie. not with skip()) because the user
  6045. * is allowed to pass a NULL buffer here, which won't allow us to safely
  6046. * calculate a d->end or use our normal functions like curbufleft(). */
  6047. if (d->skip && d->skip >= size) {
  6048. d->skip -= size;
  6049. d->bufstart_ofs += size;
  6050. buf = &dummy_char;
  6051. size = 0;
  6052. /* We can't just return now, because we might need to execute some ops
  6053. * like CHECKDELIM, which could call some callbacks and pop the stack. */
  6054. }
  6055. /* We need to pretend that this was the actual buffer param, since some of the
  6056. * calculations assume that d->ptr/d->buf is relative to this. */
  6057. d->buf_param = buf;
  6058. if (!buf) {
  6059. /* NULL buf is ok if its entire span is covered by the "skip" above, but
  6060. * by this point we know that "skip" doesn't cover the buffer. */
  6061. seterr(d, "Passed NULL buffer over non-skippable region.");
  6062. return (int32_t)upb_pbdecoder_suspend(d);
  6063. }
  6064. if (d->residual_end > d->residual) {
  6065. /* We have residual bytes from the last buffer. */
  6066. UPB_ASSERT(d->ptr == d->residual);
  6067. } else {
  6068. switchtobuf(d, buf, buf + size);
  6069. }
  6070. d->checkpoint = d->ptr;
  6071. /* Handle skips that don't cover the whole buffer (as above). */
  6072. if (d->skip) {
  6073. size_t skip_bytes = d->skip;
  6074. d->skip = 0;
  6075. CHECK_RETURN(skip(d, skip_bytes));
  6076. checkpoint(d);
  6077. }
  6078. /* If we're inside an unknown group, continue to parse unknown values. */
  6079. if (d->top->groupnum < 0) {
  6080. CHECK_RETURN(upb_pbdecoder_skipunknown(d, -1, 0));
  6081. checkpoint(d);
  6082. }
  6083. return DECODE_OK;
  6084. }
  6085. /* Suspends the decoder at the last checkpoint, without saving any residual
  6086. * bytes. If there are any unconsumed bytes, returns a short byte count. */
  6087. size_t upb_pbdecoder_suspend(upb_pbdecoder *d) {
  6088. d->pc = d->last;
  6089. if (d->checkpoint == d->residual) {
  6090. /* Checkpoint was in residual buf; no user bytes were consumed. */
  6091. d->ptr = d->residual;
  6092. return 0;
  6093. } else {
  6094. size_t ret = d->size_param - (d->end - d->checkpoint);
  6095. UPB_ASSERT(!in_residual_buf(d, d->checkpoint));
  6096. UPB_ASSERT(d->buf == d->buf_param || d->buf == &dummy_char);
  6097. d->bufstart_ofs += (d->checkpoint - d->buf);
  6098. d->residual_end = d->residual;
  6099. switchtobuf(d, d->residual, d->residual_end);
  6100. return ret;
  6101. }
  6102. }
  6103. /* Suspends the decoder at the last checkpoint, and saves any unconsumed
  6104. * bytes in our residual buffer. This is necessary if we need more user
  6105. * bytes to form a complete value, which might not be contiguous in the
  6106. * user's buffers. Always consumes all user bytes. */
  6107. static size_t suspend_save(upb_pbdecoder *d) {
  6108. /* We hit end-of-buffer before we could parse a full value.
  6109. * Save any unconsumed bytes (if any) to the residual buffer. */
  6110. d->pc = d->last;
  6111. if (d->checkpoint == d->residual) {
  6112. /* Checkpoint was in residual buf; append user byte(s) to residual buf. */
  6113. UPB_ASSERT((d->residual_end - d->residual) + d->size_param <=
  6114. sizeof(d->residual));
  6115. if (!in_residual_buf(d, d->ptr)) {
  6116. d->bufstart_ofs -= (d->residual_end - d->residual);
  6117. }
  6118. memcpy(d->residual_end, d->buf_param, d->size_param);
  6119. d->residual_end += d->size_param;
  6120. } else {
  6121. /* Checkpoint was in user buf; old residual bytes not needed. */
  6122. size_t save;
  6123. UPB_ASSERT(!in_residual_buf(d, d->checkpoint));
  6124. d->ptr = d->checkpoint;
  6125. save = curbufleft(d);
  6126. UPB_ASSERT(save <= sizeof(d->residual));
  6127. memcpy(d->residual, d->ptr, save);
  6128. d->residual_end = d->residual + save;
  6129. d->bufstart_ofs = offset(d);
  6130. }
  6131. switchtobuf(d, d->residual, d->residual_end);
  6132. return d->size_param;
  6133. }
  6134. /* Copies the next "bytes" bytes into "buf" and advances the stream.
  6135. * Requires that this many bytes are available in the current buffer. */
  6136. UPB_FORCEINLINE static void consumebytes(upb_pbdecoder *d, void *buf,
  6137. size_t bytes) {
  6138. UPB_ASSERT(bytes <= curbufleft(d));
  6139. memcpy(buf, d->ptr, bytes);
  6140. advance(d, bytes);
  6141. }
  6142. /* Slow path for getting the next "bytes" bytes, regardless of whether they are
  6143. * available in the current buffer or not. Returns a status code as described
  6144. * in decoder.int.h. */
  6145. UPB_NOINLINE static int32_t getbytes_slow(upb_pbdecoder *d, void *buf,
  6146. size_t bytes) {
  6147. const size_t avail = curbufleft(d);
  6148. consumebytes(d, buf, avail);
  6149. bytes -= avail;
  6150. UPB_ASSERT(bytes > 0);
  6151. if (in_residual_buf(d, d->ptr)) {
  6152. advancetobuf(d, d->buf_param, d->size_param);
  6153. }
  6154. if (curbufleft(d) >= bytes) {
  6155. consumebytes(d, (char *)buf + avail, bytes);
  6156. return DECODE_OK;
  6157. } else if (d->data_end == d->delim_end) {
  6158. seterr(d, "Submessage ended in the middle of a value or group");
  6159. return (int32_t)upb_pbdecoder_suspend(d);
  6160. } else {
  6161. return (int32_t)suspend_save(d);
  6162. }
  6163. }
  6164. /* Gets the next "bytes" bytes, regardless of whether they are available in the
  6165. * current buffer or not. Returns a status code as described in decoder.int.h.
  6166. */
  6167. UPB_FORCEINLINE static int32_t getbytes(upb_pbdecoder *d, void *buf,
  6168. size_t bytes) {
  6169. if (curbufleft(d) >= bytes) {
  6170. /* Buffer has enough data to satisfy. */
  6171. consumebytes(d, buf, bytes);
  6172. return DECODE_OK;
  6173. } else {
  6174. return getbytes_slow(d, buf, bytes);
  6175. }
  6176. }
  6177. UPB_NOINLINE static size_t peekbytes_slow(upb_pbdecoder *d, void *buf,
  6178. size_t bytes) {
  6179. size_t ret = curbufleft(d);
  6180. memcpy(buf, d->ptr, ret);
  6181. if (in_residual_buf(d, d->ptr)) {
  6182. size_t copy = UPB_MIN(bytes - ret, d->size_param);
  6183. memcpy((char *)buf + ret, d->buf_param, copy);
  6184. ret += copy;
  6185. }
  6186. return ret;
  6187. }
  6188. UPB_FORCEINLINE static size_t peekbytes(upb_pbdecoder *d, void *buf,
  6189. size_t bytes) {
  6190. if (curbufleft(d) >= bytes) {
  6191. memcpy(buf, d->ptr, bytes);
  6192. return bytes;
  6193. } else {
  6194. return peekbytes_slow(d, buf, bytes);
  6195. }
  6196. }
  6197. /* Decoding of wire types *****************************************************/
  6198. /* Slow path for decoding a varint from the current buffer position.
  6199. * Returns a status code as described in decoder.int.h. */
  6200. UPB_NOINLINE int32_t upb_pbdecoder_decode_varint_slow(upb_pbdecoder *d,
  6201. uint64_t *u64) {
  6202. uint8_t byte = 0x80;
  6203. int bitpos;
  6204. *u64 = 0;
  6205. for(bitpos = 0; bitpos < 70 && (byte & 0x80); bitpos += 7) {
  6206. CHECK_RETURN(getbytes(d, &byte, 1));
  6207. *u64 |= (uint64_t)(byte & 0x7F) << bitpos;
  6208. }
  6209. if(bitpos == 70 && (byte & 0x80)) {
  6210. seterr(d, kUnterminatedVarint);
  6211. return (int32_t)upb_pbdecoder_suspend(d);
  6212. }
  6213. return DECODE_OK;
  6214. }
  6215. /* Decodes a varint from the current buffer position.
  6216. * Returns a status code as described in decoder.int.h. */
  6217. UPB_FORCEINLINE static int32_t decode_varint(upb_pbdecoder *d, uint64_t *u64) {
  6218. if (curbufleft(d) > 0 && !(*d->ptr & 0x80)) {
  6219. *u64 = *d->ptr;
  6220. advance(d, 1);
  6221. return DECODE_OK;
  6222. } else if (curbufleft(d) >= 10) {
  6223. /* Fast case. */
  6224. upb_decoderet r = upb_vdecode_fast(d->ptr);
  6225. if (r.p == NULL) {
  6226. seterr(d, kUnterminatedVarint);
  6227. return (int32_t)upb_pbdecoder_suspend(d);
  6228. }
  6229. advance(d, r.p - d->ptr);
  6230. *u64 = r.val;
  6231. return DECODE_OK;
  6232. } else {
  6233. /* Slow case -- varint spans buffer seam. */
  6234. return upb_pbdecoder_decode_varint_slow(d, u64);
  6235. }
  6236. }
  6237. /* Decodes a 32-bit varint from the current buffer position.
  6238. * Returns a status code as described in decoder.int.h. */
  6239. UPB_FORCEINLINE static int32_t decode_v32(upb_pbdecoder *d, uint32_t *u32) {
  6240. uint64_t u64;
  6241. int32_t ret = decode_varint(d, &u64);
  6242. if (ret >= 0) return ret;
  6243. if (u64 > UINT32_MAX) {
  6244. seterr(d, "Unterminated 32-bit varint");
  6245. /* TODO(haberman) guarantee that this function return is >= 0 somehow,
  6246. * so we know this path will always be treated as error by our caller.
  6247. * Right now the size_t -> int32_t can overflow and produce negative values.
  6248. */
  6249. *u32 = 0;
  6250. return (int32_t)upb_pbdecoder_suspend(d);
  6251. }
  6252. *u32 = (uint32_t)u64;
  6253. return DECODE_OK;
  6254. }
  6255. /* Decodes a fixed32 from the current buffer position.
  6256. * Returns a status code as described in decoder.int.h.
  6257. * TODO: proper byte swapping for big-endian machines. */
  6258. UPB_FORCEINLINE static int32_t decode_fixed32(upb_pbdecoder *d, uint32_t *u32) {
  6259. return getbytes(d, u32, 4);
  6260. }
  6261. /* Decodes a fixed64 from the current buffer position.
  6262. * Returns a status code as described in decoder.int.h.
  6263. * TODO: proper byte swapping for big-endian machines. */
  6264. UPB_FORCEINLINE static int32_t decode_fixed64(upb_pbdecoder *d, uint64_t *u64) {
  6265. return getbytes(d, u64, 8);
  6266. }
  6267. /* Non-static versions of the above functions.
  6268. * These are called by the JIT for fallback paths. */
  6269. int32_t upb_pbdecoder_decode_f32(upb_pbdecoder *d, uint32_t *u32) {
  6270. return decode_fixed32(d, u32);
  6271. }
  6272. int32_t upb_pbdecoder_decode_f64(upb_pbdecoder *d, uint64_t *u64) {
  6273. return decode_fixed64(d, u64);
  6274. }
  6275. static double as_double(uint64_t n) { double d; memcpy(&d, &n, 8); return d; }
  6276. static float as_float(uint32_t n) { float f; memcpy(&f, &n, 4); return f; }
  6277. /* Pushes a frame onto the decoder stack. */
  6278. static bool decoder_push(upb_pbdecoder *d, uint64_t end) {
  6279. upb_pbdecoder_frame *fr = d->top;
  6280. if (end > fr->end_ofs) {
  6281. seterr(d, kPbDecoderSubmessageTooLong);
  6282. return false;
  6283. } else if (fr == d->limit) {
  6284. seterr(d, kPbDecoderStackOverflow);
  6285. return false;
  6286. }
  6287. fr++;
  6288. fr->end_ofs = end;
  6289. fr->dispatch = NULL;
  6290. fr->groupnum = 0;
  6291. d->top = fr;
  6292. return true;
  6293. }
  6294. static bool pushtagdelim(upb_pbdecoder *d, uint32_t arg) {
  6295. /* While we expect to see an "end" tag (either ENDGROUP or a non-sequence
  6296. * field number) prior to hitting any enclosing submessage end, pushing our
  6297. * existing delim end prevents us from continuing to parse values from a
  6298. * corrupt proto that doesn't give us an END tag in time. */
  6299. if (!decoder_push(d, d->top->end_ofs))
  6300. return false;
  6301. d->top->groupnum = arg;
  6302. return true;
  6303. }
  6304. /* Pops a frame from the decoder stack. */
  6305. static void decoder_pop(upb_pbdecoder *d) { d->top--; }
  6306. UPB_NOINLINE int32_t upb_pbdecoder_checktag_slow(upb_pbdecoder *d,
  6307. uint64_t expected) {
  6308. uint64_t data = 0;
  6309. size_t bytes = upb_value_size(expected);
  6310. size_t read = peekbytes(d, &data, bytes);
  6311. if (read == bytes && data == expected) {
  6312. /* Advance past matched bytes. */
  6313. int32_t ok = getbytes(d, &data, read);
  6314. UPB_ASSERT(ok < 0);
  6315. return DECODE_OK;
  6316. } else if (read < bytes && memcmp(&data, &expected, read) == 0) {
  6317. return (int32_t)suspend_save(d);
  6318. } else {
  6319. return DECODE_MISMATCH;
  6320. }
  6321. }
  6322. int32_t upb_pbdecoder_skipunknown(upb_pbdecoder *d, int32_t fieldnum,
  6323. uint8_t wire_type) {
  6324. if (fieldnum >= 0)
  6325. goto have_tag;
  6326. while (true) {
  6327. uint32_t tag;
  6328. CHECK_RETURN(decode_v32(d, &tag));
  6329. wire_type = tag & 0x7;
  6330. fieldnum = tag >> 3;
  6331. have_tag:
  6332. if (fieldnum == 0) {
  6333. seterr(d, "Saw invalid field number (0)");
  6334. return (int32_t)upb_pbdecoder_suspend(d);
  6335. }
  6336. switch (wire_type) {
  6337. case UPB_WIRE_TYPE_32BIT:
  6338. CHECK_RETURN(skip(d, 4));
  6339. break;
  6340. case UPB_WIRE_TYPE_64BIT:
  6341. CHECK_RETURN(skip(d, 8));
  6342. break;
  6343. case UPB_WIRE_TYPE_VARINT: {
  6344. uint64_t u64;
  6345. CHECK_RETURN(decode_varint(d, &u64));
  6346. break;
  6347. }
  6348. case UPB_WIRE_TYPE_DELIMITED: {
  6349. uint32_t len;
  6350. CHECK_RETURN(decode_v32(d, &len));
  6351. CHECK_RETURN(skip(d, len));
  6352. break;
  6353. }
  6354. case UPB_WIRE_TYPE_START_GROUP:
  6355. if (!pushtagdelim(d, -fieldnum)) {
  6356. return (int32_t)upb_pbdecoder_suspend(d);
  6357. }
  6358. break;
  6359. case UPB_WIRE_TYPE_END_GROUP:
  6360. if (fieldnum == -d->top->groupnum) {
  6361. decoder_pop(d);
  6362. } else if (fieldnum == d->top->groupnum) {
  6363. return DECODE_ENDGROUP;
  6364. } else {
  6365. seterr(d, "Unmatched ENDGROUP tag.");
  6366. return (int32_t)upb_pbdecoder_suspend(d);
  6367. }
  6368. break;
  6369. default:
  6370. seterr(d, "Invalid wire type");
  6371. return (int32_t)upb_pbdecoder_suspend(d);
  6372. }
  6373. if (d->top->groupnum >= 0) {
  6374. /* TODO: More code needed for handling unknown groups. */
  6375. upb_sink_putunknown(d->top->sink, d->checkpoint, d->ptr - d->checkpoint);
  6376. return DECODE_OK;
  6377. }
  6378. /* Unknown group -- continue looping over unknown fields. */
  6379. checkpoint(d);
  6380. }
  6381. }
  6382. static void goto_endmsg(upb_pbdecoder *d) {
  6383. upb_value v;
  6384. bool found = upb_inttable_lookup32(d->top->dispatch, DISPATCH_ENDMSG, &v);
  6385. UPB_ASSERT(found);
  6386. d->pc = d->top->base + upb_value_getuint64(v);
  6387. }
  6388. /* Parses a tag and jumps to the corresponding bytecode instruction for this
  6389. * field.
  6390. *
  6391. * If the tag is unknown (or the wire type doesn't match), parses the field as
  6392. * unknown. If the tag is a valid ENDGROUP tag, jumps to the bytecode
  6393. * instruction for the end of message. */
  6394. static int32_t dispatch(upb_pbdecoder *d) {
  6395. upb_inttable *dispatch = d->top->dispatch;
  6396. uint32_t tag;
  6397. uint8_t wire_type;
  6398. uint32_t fieldnum;
  6399. upb_value val;
  6400. int32_t retval;
  6401. /* Decode tag. */
  6402. CHECK_RETURN(decode_v32(d, &tag));
  6403. wire_type = tag & 0x7;
  6404. fieldnum = tag >> 3;
  6405. /* Lookup tag. Because of packed/non-packed compatibility, we have to
  6406. * check the wire type against two possibilities. */
  6407. if (fieldnum != DISPATCH_ENDMSG &&
  6408. upb_inttable_lookup32(dispatch, fieldnum, &val)) {
  6409. uint64_t v = upb_value_getuint64(val);
  6410. if (wire_type == (v & 0xff)) {
  6411. d->pc = d->top->base + (v >> 16);
  6412. return DECODE_OK;
  6413. } else if (wire_type == ((v >> 8) & 0xff)) {
  6414. bool found =
  6415. upb_inttable_lookup(dispatch, fieldnum + UPB_MAX_FIELDNUMBER, &val);
  6416. UPB_ASSERT(found);
  6417. d->pc = d->top->base + upb_value_getuint64(val);
  6418. return DECODE_OK;
  6419. }
  6420. }
  6421. /* We have some unknown fields (or ENDGROUP) to parse. The DISPATCH or TAG
  6422. * bytecode that triggered this is preceded by a CHECKDELIM bytecode which
  6423. * we need to back up to, so that when we're done skipping unknown data we
  6424. * can re-check the delimited end. */
  6425. d->last--; /* Necessary if we get suspended */
  6426. d->pc = d->last;
  6427. UPB_ASSERT(getop(*d->last) == OP_CHECKDELIM);
  6428. /* Unknown field or ENDGROUP. */
  6429. retval = upb_pbdecoder_skipunknown(d, fieldnum, wire_type);
  6430. CHECK_RETURN(retval);
  6431. if (retval == DECODE_ENDGROUP) {
  6432. goto_endmsg(d);
  6433. return DECODE_OK;
  6434. }
  6435. return DECODE_OK;
  6436. }
  6437. /* Callers know that the stack is more than one deep because the opcodes that
  6438. * call this only occur after PUSH operations. */
  6439. upb_pbdecoder_frame *outer_frame(upb_pbdecoder *d) {
  6440. UPB_ASSERT(d->top != d->stack);
  6441. return d->top - 1;
  6442. }
  6443. /* The main decoding loop *****************************************************/
  6444. /* The main decoder VM function. Uses traditional bytecode dispatch loop with a
  6445. * switch() statement. */
  6446. size_t run_decoder_vm(upb_pbdecoder *d, const mgroup *group,
  6447. const upb_bufhandle* handle) {
  6448. #define VMCASE(op, code) \
  6449. case op: { code; if (consumes_input(op)) checkpoint(d); break; }
  6450. #define PRIMITIVE_OP(type, wt, name, convfunc, ctype) \
  6451. VMCASE(OP_PARSE_ ## type, { \
  6452. ctype val; \
  6453. CHECK_RETURN(decode_ ## wt(d, &val)); \
  6454. upb_sink_put ## name(d->top->sink, arg, (convfunc)(val)); \
  6455. })
  6456. while(1) {
  6457. int32_t instruction;
  6458. opcode op;
  6459. uint32_t arg;
  6460. int32_t longofs;
  6461. d->last = d->pc;
  6462. instruction = *d->pc++;
  6463. op = getop(instruction);
  6464. arg = instruction >> 8;
  6465. longofs = arg;
  6466. UPB_ASSERT(d->ptr != d->residual_end);
  6467. UPB_UNUSED(group);
  6468. #ifdef UPB_DUMP_BYTECODE
  6469. fprintf(stderr, "s_ofs=%d buf_ofs=%d data_rem=%d buf_rem=%d delim_rem=%d "
  6470. "%x %s (%d)\n",
  6471. (int)offset(d),
  6472. (int)(d->ptr - d->buf),
  6473. (int)(d->data_end - d->ptr),
  6474. (int)(d->end - d->ptr),
  6475. (int)((d->top->end_ofs - d->bufstart_ofs) - (d->ptr - d->buf)),
  6476. (int)(d->pc - 1 - group->bytecode),
  6477. upb_pbdecoder_getopname(op),
  6478. arg);
  6479. #endif
  6480. switch (op) {
  6481. /* Technically, we are losing data if we see a 32-bit varint that is not
  6482. * properly sign-extended. We could detect this and error about the data
  6483. * loss, but proto2 does not do this, so we pass. */
  6484. PRIMITIVE_OP(INT32, varint, int32, int32_t, uint64_t)
  6485. PRIMITIVE_OP(INT64, varint, int64, int64_t, uint64_t)
  6486. PRIMITIVE_OP(UINT32, varint, uint32, uint32_t, uint64_t)
  6487. PRIMITIVE_OP(UINT64, varint, uint64, uint64_t, uint64_t)
  6488. PRIMITIVE_OP(FIXED32, fixed32, uint32, uint32_t, uint32_t)
  6489. PRIMITIVE_OP(FIXED64, fixed64, uint64, uint64_t, uint64_t)
  6490. PRIMITIVE_OP(SFIXED32, fixed32, int32, int32_t, uint32_t)
  6491. PRIMITIVE_OP(SFIXED64, fixed64, int64, int64_t, uint64_t)
  6492. PRIMITIVE_OP(BOOL, varint, bool, bool, uint64_t)
  6493. PRIMITIVE_OP(DOUBLE, fixed64, double, as_double, uint64_t)
  6494. PRIMITIVE_OP(FLOAT, fixed32, float, as_float, uint32_t)
  6495. PRIMITIVE_OP(SINT32, varint, int32, upb_zzdec_32, uint64_t)
  6496. PRIMITIVE_OP(SINT64, varint, int64, upb_zzdec_64, uint64_t)
  6497. VMCASE(OP_SETDISPATCH,
  6498. d->top->base = d->pc - 1;
  6499. memcpy(&d->top->dispatch, d->pc, sizeof(void*));
  6500. d->pc += sizeof(void*) / sizeof(uint32_t);
  6501. )
  6502. VMCASE(OP_STARTMSG,
  6503. CHECK_SUSPEND(upb_sink_startmsg(d->top->sink));
  6504. )
  6505. VMCASE(OP_ENDMSG,
  6506. CHECK_SUSPEND(upb_sink_endmsg(d->top->sink, d->status));
  6507. )
  6508. VMCASE(OP_STARTSEQ,
  6509. upb_pbdecoder_frame *outer = outer_frame(d);
  6510. CHECK_SUSPEND(upb_sink_startseq(outer->sink, arg, &d->top->sink));
  6511. )
  6512. VMCASE(OP_ENDSEQ,
  6513. CHECK_SUSPEND(upb_sink_endseq(d->top->sink, arg));
  6514. )
  6515. VMCASE(OP_STARTSUBMSG,
  6516. upb_pbdecoder_frame *outer = outer_frame(d);
  6517. CHECK_SUSPEND(upb_sink_startsubmsg(outer->sink, arg, &d->top->sink));
  6518. )
  6519. VMCASE(OP_ENDSUBMSG,
  6520. upb_sink subsink = (d->top + 1)->sink;
  6521. CHECK_SUSPEND(upb_sink_endsubmsg(d->top->sink, subsink, arg));
  6522. )
  6523. VMCASE(OP_STARTSTR,
  6524. uint32_t len = (uint32_t)delim_remaining(d);
  6525. upb_pbdecoder_frame *outer = outer_frame(d);
  6526. CHECK_SUSPEND(upb_sink_startstr(outer->sink, arg, len, &d->top->sink));
  6527. if (len == 0) {
  6528. d->pc++; /* Skip OP_STRING. */
  6529. }
  6530. )
  6531. VMCASE(OP_STRING,
  6532. uint32_t len = (uint32_t)curbufleft(d);
  6533. size_t n = upb_sink_putstring(d->top->sink, arg, d->ptr, len, handle);
  6534. if (n > len) {
  6535. if (n > delim_remaining(d)) {
  6536. seterr(d, "Tried to skip past end of string.");
  6537. return upb_pbdecoder_suspend(d);
  6538. } else {
  6539. int32_t ret = skip(d, n);
  6540. /* This shouldn't return DECODE_OK, because n > len. */
  6541. UPB_ASSERT(ret >= 0);
  6542. return ret;
  6543. }
  6544. }
  6545. advance(d, n);
  6546. if (n < len || d->delim_end == NULL) {
  6547. /* We aren't finished with this string yet. */
  6548. d->pc--; /* Repeat OP_STRING. */
  6549. if (n > 0) checkpoint(d);
  6550. return upb_pbdecoder_suspend(d);
  6551. }
  6552. )
  6553. VMCASE(OP_ENDSTR,
  6554. CHECK_SUSPEND(upb_sink_endstr(d->top->sink, arg));
  6555. )
  6556. VMCASE(OP_PUSHTAGDELIM,
  6557. CHECK_SUSPEND(pushtagdelim(d, arg));
  6558. )
  6559. VMCASE(OP_SETBIGGROUPNUM,
  6560. d->top->groupnum = *d->pc++;
  6561. )
  6562. VMCASE(OP_POP,
  6563. UPB_ASSERT(d->top > d->stack);
  6564. decoder_pop(d);
  6565. )
  6566. VMCASE(OP_PUSHLENDELIM,
  6567. uint32_t len;
  6568. CHECK_RETURN(decode_v32(d, &len));
  6569. CHECK_SUSPEND(decoder_push(d, offset(d) + len));
  6570. set_delim_end(d);
  6571. )
  6572. VMCASE(OP_SETDELIM,
  6573. set_delim_end(d);
  6574. )
  6575. VMCASE(OP_CHECKDELIM,
  6576. /* We are guaranteed of this assert because we never allow ourselves to
  6577. * consume bytes beyond data_end, which covers delim_end when non-NULL.
  6578. */
  6579. UPB_ASSERT(!(d->delim_end && d->ptr > d->delim_end));
  6580. if (d->ptr == d->delim_end)
  6581. d->pc += longofs;
  6582. )
  6583. VMCASE(OP_CALL,
  6584. d->callstack[d->call_len++] = d->pc;
  6585. d->pc += longofs;
  6586. )
  6587. VMCASE(OP_RET,
  6588. UPB_ASSERT(d->call_len > 0);
  6589. d->pc = d->callstack[--d->call_len];
  6590. )
  6591. VMCASE(OP_BRANCH,
  6592. d->pc += longofs;
  6593. )
  6594. VMCASE(OP_TAG1,
  6595. uint8_t expected;
  6596. CHECK_SUSPEND(curbufleft(d) > 0);
  6597. expected = (arg >> 8) & 0xff;
  6598. if (*d->ptr == expected) {
  6599. advance(d, 1);
  6600. } else {
  6601. int8_t shortofs;
  6602. badtag:
  6603. shortofs = arg;
  6604. if (shortofs == LABEL_DISPATCH) {
  6605. CHECK_RETURN(dispatch(d));
  6606. } else {
  6607. d->pc += shortofs;
  6608. break; /* Avoid checkpoint(). */
  6609. }
  6610. }
  6611. )
  6612. VMCASE(OP_TAG2,
  6613. uint16_t expected;
  6614. CHECK_SUSPEND(curbufleft(d) > 0);
  6615. expected = (arg >> 8) & 0xffff;
  6616. if (curbufleft(d) >= 2) {
  6617. uint16_t actual;
  6618. memcpy(&actual, d->ptr, 2);
  6619. if (expected == actual) {
  6620. advance(d, 2);
  6621. } else {
  6622. goto badtag;
  6623. }
  6624. } else {
  6625. int32_t result = upb_pbdecoder_checktag_slow(d, expected);
  6626. if (result == DECODE_MISMATCH) goto badtag;
  6627. if (result >= 0) return result;
  6628. }
  6629. )
  6630. VMCASE(OP_TAGN, {
  6631. uint64_t expected;
  6632. int32_t result;
  6633. memcpy(&expected, d->pc, 8);
  6634. d->pc += 2;
  6635. result = upb_pbdecoder_checktag_slow(d, expected);
  6636. if (result == DECODE_MISMATCH) goto badtag;
  6637. if (result >= 0) return result;
  6638. })
  6639. VMCASE(OP_DISPATCH, {
  6640. CHECK_RETURN(dispatch(d));
  6641. })
  6642. VMCASE(OP_HALT, {
  6643. return d->size_param;
  6644. })
  6645. }
  6646. }
  6647. }
  6648. /* BytesHandler handlers ******************************************************/
  6649. void *upb_pbdecoder_startbc(void *closure, const void *pc, size_t size_hint) {
  6650. upb_pbdecoder *d = closure;
  6651. UPB_UNUSED(size_hint);
  6652. d->top->end_ofs = UINT64_MAX;
  6653. d->bufstart_ofs = 0;
  6654. d->call_len = 1;
  6655. d->callstack[0] = &halt;
  6656. d->pc = pc;
  6657. d->skip = 0;
  6658. return d;
  6659. }
  6660. bool upb_pbdecoder_end(void *closure, const void *handler_data) {
  6661. upb_pbdecoder *d = closure;
  6662. const upb_pbdecodermethod *method = handler_data;
  6663. uint64_t end;
  6664. char dummy;
  6665. if (d->residual_end > d->residual) {
  6666. seterr(d, "Unexpected EOF: decoder still has buffered unparsed data");
  6667. return false;
  6668. }
  6669. if (d->skip) {
  6670. seterr(d, "Unexpected EOF inside skipped data");
  6671. return false;
  6672. }
  6673. if (d->top->end_ofs != UINT64_MAX) {
  6674. seterr(d, "Unexpected EOF inside delimited string");
  6675. return false;
  6676. }
  6677. /* The user's end() call indicates that the message ends here. */
  6678. end = offset(d);
  6679. d->top->end_ofs = end;
  6680. {
  6681. const uint32_t *p = d->pc;
  6682. d->stack->end_ofs = end;
  6683. /* Check the previous bytecode, but guard against beginning. */
  6684. if (p != method->code_base.ptr) p--;
  6685. if (getop(*p) == OP_CHECKDELIM) {
  6686. /* Rewind from OP_TAG* to OP_CHECKDELIM. */
  6687. UPB_ASSERT(getop(*d->pc) == OP_TAG1 ||
  6688. getop(*d->pc) == OP_TAG2 ||
  6689. getop(*d->pc) == OP_TAGN ||
  6690. getop(*d->pc) == OP_DISPATCH);
  6691. d->pc = p;
  6692. }
  6693. upb_pbdecoder_decode(closure, handler_data, &dummy, 0, NULL);
  6694. }
  6695. if (d->call_len != 0) {
  6696. seterr(d, "Unexpected EOF inside submessage or group");
  6697. return false;
  6698. }
  6699. return true;
  6700. }
  6701. size_t upb_pbdecoder_decode(void *decoder, const void *group, const char *buf,
  6702. size_t size, const upb_bufhandle *handle) {
  6703. int32_t result = upb_pbdecoder_resume(decoder, NULL, buf, size, handle);
  6704. if (result == DECODE_ENDGROUP) goto_endmsg(decoder);
  6705. CHECK_RETURN(result);
  6706. return run_decoder_vm(decoder, group, handle);
  6707. }
  6708. /* Public API *****************************************************************/
  6709. void upb_pbdecoder_reset(upb_pbdecoder *d) {
  6710. d->top = d->stack;
  6711. d->top->groupnum = 0;
  6712. d->ptr = d->residual;
  6713. d->buf = d->residual;
  6714. d->end = d->residual;
  6715. d->residual_end = d->residual;
  6716. }
  6717. upb_pbdecoder *upb_pbdecoder_create(upb_arena *a, const upb_pbdecodermethod *m,
  6718. upb_sink sink, upb_status *status) {
  6719. const size_t default_max_nesting = 64;
  6720. #ifndef NDEBUG
  6721. size_t size_before = upb_arena_bytesallocated(a);
  6722. #endif
  6723. upb_pbdecoder *d = upb_arena_malloc(a, sizeof(upb_pbdecoder));
  6724. if (!d) return NULL;
  6725. d->method_ = m;
  6726. d->callstack = upb_arena_malloc(a, callstacksize(d, default_max_nesting));
  6727. d->stack = upb_arena_malloc(a, stacksize(d, default_max_nesting));
  6728. if (!d->stack || !d->callstack) {
  6729. return NULL;
  6730. }
  6731. d->arena = a;
  6732. d->limit = d->stack + default_max_nesting - 1;
  6733. d->stack_size = default_max_nesting;
  6734. d->status = status;
  6735. upb_pbdecoder_reset(d);
  6736. upb_bytessink_reset(&d->input_, &m->input_handler_, d);
  6737. if (d->method_->dest_handlers_) {
  6738. if (sink.handlers != d->method_->dest_handlers_)
  6739. return NULL;
  6740. }
  6741. d->top->sink = sink;
  6742. /* If this fails, increase the value in decoder.h. */
  6743. UPB_ASSERT_DEBUGVAR(upb_arena_bytesallocated(a) - size_before <=
  6744. UPB_PB_DECODER_SIZE);
  6745. return d;
  6746. }
  6747. uint64_t upb_pbdecoder_bytesparsed(const upb_pbdecoder *d) {
  6748. return offset(d);
  6749. }
  6750. const upb_pbdecodermethod *upb_pbdecoder_method(const upb_pbdecoder *d) {
  6751. return d->method_;
  6752. }
  6753. upb_bytessink upb_pbdecoder_input(upb_pbdecoder *d) {
  6754. return d->input_;
  6755. }
  6756. size_t upb_pbdecoder_maxnesting(const upb_pbdecoder *d) {
  6757. return d->stack_size;
  6758. }
  6759. bool upb_pbdecoder_setmaxnesting(upb_pbdecoder *d, size_t max) {
  6760. UPB_ASSERT(d->top >= d->stack);
  6761. if (max < (size_t)(d->top - d->stack)) {
  6762. /* Can't set a limit smaller than what we are currently at. */
  6763. return false;
  6764. }
  6765. if (max > d->stack_size) {
  6766. /* Need to reallocate stack and callstack to accommodate. */
  6767. size_t old_size = stacksize(d, d->stack_size);
  6768. size_t new_size = stacksize(d, max);
  6769. void *p = upb_arena_realloc(d->arena, d->stack, old_size, new_size);
  6770. if (!p) {
  6771. return false;
  6772. }
  6773. d->stack = p;
  6774. old_size = callstacksize(d, d->stack_size);
  6775. new_size = callstacksize(d, max);
  6776. p = upb_arena_realloc(d->arena, d->callstack, old_size, new_size);
  6777. if (!p) {
  6778. return false;
  6779. }
  6780. d->callstack = p;
  6781. d->stack_size = max;
  6782. }
  6783. d->limit = d->stack + max - 1;
  6784. return true;
  6785. }
  6786. /*
  6787. ** upb::Encoder
  6788. **
  6789. ** Since we are implementing pure handlers (ie. without any out-of-band access
  6790. ** to pre-computed lengths), we have to buffer all submessages before we can
  6791. ** emit even their first byte.
  6792. **
  6793. ** Not knowing the size of submessages also means we can't write a perfect
  6794. ** zero-copy implementation, even with buffering. Lengths are stored as
  6795. ** varints, which means that we don't know how many bytes to reserve for the
  6796. ** length until we know what the length is.
  6797. **
  6798. ** This leaves us with three main choices:
  6799. **
  6800. ** 1. buffer all submessage data in a temporary buffer, then copy it exactly
  6801. ** once into the output buffer.
  6802. **
  6803. ** 2. attempt to buffer data directly into the output buffer, estimating how
  6804. ** many bytes each length will take. When our guesses are wrong, use
  6805. ** memmove() to grow or shrink the allotted space.
  6806. **
  6807. ** 3. buffer directly into the output buffer, allocating a max length
  6808. ** ahead-of-time for each submessage length. If we overallocated, we waste
  6809. ** space, but no memcpy() or memmove() is required. This approach requires
  6810. ** defining a maximum size for submessages and rejecting submessages that
  6811. ** exceed that size.
  6812. **
  6813. ** (2) and (3) have the potential to have better performance, but they are more
  6814. ** complicated and subtle to implement:
  6815. **
  6816. ** (3) requires making an arbitrary choice of the maximum message size; it
  6817. ** wastes space when submessages are shorter than this and fails
  6818. ** completely when they are longer. This makes it more finicky and
  6819. ** requires configuration based on the input. It also makes it impossible
  6820. ** to perfectly match the output of reference encoders that always use the
  6821. ** optimal amount of space for each length.
  6822. **
  6823. ** (2) requires guessing the the size upfront, and if multiple lengths are
  6824. ** guessed wrong the minimum required number of memmove() operations may
  6825. ** be complicated to compute correctly. Implemented properly, it may have
  6826. ** a useful amortized or average cost, but more investigation is required
  6827. ** to determine this and what the optimal algorithm is to achieve it.
  6828. **
  6829. ** (1) makes you always pay for exactly one copy, but its implementation is
  6830. ** the simplest and its performance is predictable.
  6831. **
  6832. ** So for now, we implement (1) only. If we wish to optimize later, we should
  6833. ** be able to do it without affecting users.
  6834. **
  6835. ** The strategy is to buffer the segments of data that do *not* depend on
  6836. ** unknown lengths in one buffer, and keep a separate buffer of segment pointers
  6837. ** and lengths. When the top-level submessage ends, we can go beginning to end,
  6838. ** alternating the writing of lengths with memcpy() of the rest of the data.
  6839. ** At the top level though, no buffering is required.
  6840. */
  6841. /* The output buffer is divided into segments; a segment is a string of data
  6842. * that is "ready to go" -- it does not need any varint lengths inserted into
  6843. * the middle. The seams between segments are where varints will be inserted
  6844. * once they are known.
  6845. *
  6846. * We also use the concept of a "run", which is a range of encoded bytes that
  6847. * occur at a single submessage level. Every segment contains one or more runs.
  6848. *
  6849. * A segment can span messages. Consider:
  6850. *
  6851. * .--Submessage lengths---------.
  6852. * | | |
  6853. * | V V
  6854. * V | |--------------- | |-----------------
  6855. * Submessages: | |-----------------------------------------------
  6856. * Top-level msg: ------------------------------------------------------------
  6857. *
  6858. * Segments: ----- ------------------- -----------------
  6859. * Runs: *---- *--------------*--- *----------------
  6860. * (* marks the start)
  6861. *
  6862. * Note that the top-level menssage is not in any segment because it does not
  6863. * have any length preceding it.
  6864. *
  6865. * A segment is only interrupted when another length needs to be inserted. So
  6866. * observe how the second segment spans both the inner submessage and part of
  6867. * the next enclosing message. */
  6868. typedef struct {
  6869. uint32_t msglen; /* The length to varint-encode before this segment. */
  6870. uint32_t seglen; /* Length of the segment. */
  6871. } upb_pb_encoder_segment;
  6872. struct upb_pb_encoder {
  6873. upb_arena *arena;
  6874. /* Our input and output. */
  6875. upb_sink input_;
  6876. upb_bytessink output_;
  6877. /* The "subclosure" -- used as the inner closure as part of the bytessink
  6878. * protocol. */
  6879. void *subc;
  6880. /* The output buffer and limit, and our current write position. "buf"
  6881. * initially points to "initbuf", but is dynamically allocated if we need to
  6882. * grow beyond the initial size. */
  6883. char *buf, *ptr, *limit;
  6884. /* The beginning of the current run, or undefined if we are at the top
  6885. * level. */
  6886. char *runbegin;
  6887. /* The list of segments we are accumulating. */
  6888. upb_pb_encoder_segment *segbuf, *segptr, *seglimit;
  6889. /* The stack of enclosing submessages. Each entry in the stack points to the
  6890. * segment where this submessage's length is being accumulated. */
  6891. int *stack, *top, *stacklimit;
  6892. /* Depth of startmsg/endmsg calls. */
  6893. int depth;
  6894. };
  6895. /* low-level buffering ********************************************************/
  6896. /* Low-level functions for interacting with the output buffer. */
  6897. /* TODO(haberman): handle pushback */
  6898. static void putbuf(upb_pb_encoder *e, const char *buf, size_t len) {
  6899. size_t n = upb_bytessink_putbuf(e->output_, e->subc, buf, len, NULL);
  6900. UPB_ASSERT(n == len);
  6901. }
  6902. static upb_pb_encoder_segment *top(upb_pb_encoder *e) {
  6903. return &e->segbuf[*e->top];
  6904. }
  6905. /* Call to ensure that at least "bytes" bytes are available for writing at
  6906. * e->ptr. Returns false if the bytes could not be allocated. */
  6907. static bool reserve(upb_pb_encoder *e, size_t bytes) {
  6908. if ((size_t)(e->limit - e->ptr) < bytes) {
  6909. /* Grow buffer. */
  6910. char *new_buf;
  6911. size_t needed = bytes + (e->ptr - e->buf);
  6912. size_t old_size = e->limit - e->buf;
  6913. size_t new_size = old_size;
  6914. while (new_size < needed) {
  6915. new_size *= 2;
  6916. }
  6917. new_buf = upb_arena_realloc(e->arena, e->buf, old_size, new_size);
  6918. if (new_buf == NULL) {
  6919. return false;
  6920. }
  6921. e->ptr = new_buf + (e->ptr - e->buf);
  6922. e->runbegin = new_buf + (e->runbegin - e->buf);
  6923. e->limit = new_buf + new_size;
  6924. e->buf = new_buf;
  6925. }
  6926. return true;
  6927. }
  6928. /* Call when "bytes" bytes have been writte at e->ptr. The caller *must* have
  6929. * previously called reserve() with at least this many bytes. */
  6930. static void encoder_advance(upb_pb_encoder *e, size_t bytes) {
  6931. UPB_ASSERT((size_t)(e->limit - e->ptr) >= bytes);
  6932. e->ptr += bytes;
  6933. }
  6934. /* Call when all of the bytes for a handler have been written. Flushes the
  6935. * bytes if possible and necessary, returning false if this failed. */
  6936. static bool commit(upb_pb_encoder *e) {
  6937. if (!e->top) {
  6938. /* We aren't inside a delimited region. Flush our accumulated bytes to
  6939. * the output.
  6940. *
  6941. * TODO(haberman): in the future we may want to delay flushing for
  6942. * efficiency reasons. */
  6943. putbuf(e, e->buf, e->ptr - e->buf);
  6944. e->ptr = e->buf;
  6945. }
  6946. return true;
  6947. }
  6948. /* Writes the given bytes to the buffer, handling reserve/advance. */
  6949. static bool encode_bytes(upb_pb_encoder *e, const void *data, size_t len) {
  6950. if (!reserve(e, len)) {
  6951. return false;
  6952. }
  6953. memcpy(e->ptr, data, len);
  6954. encoder_advance(e, len);
  6955. return true;
  6956. }
  6957. /* Finish the current run by adding the run totals to the segment and message
  6958. * length. */
  6959. static void accumulate(upb_pb_encoder *e) {
  6960. size_t run_len;
  6961. UPB_ASSERT(e->ptr >= e->runbegin);
  6962. run_len = e->ptr - e->runbegin;
  6963. e->segptr->seglen += run_len;
  6964. top(e)->msglen += run_len;
  6965. e->runbegin = e->ptr;
  6966. }
  6967. /* Call to indicate the start of delimited region for which the full length is
  6968. * not yet known. All data will be buffered until the length is known.
  6969. * Delimited regions may be nested; their lengths will all be tracked properly. */
  6970. static bool start_delim(upb_pb_encoder *e) {
  6971. if (e->top) {
  6972. /* We are already buffering, advance to the next segment and push it on the
  6973. * stack. */
  6974. accumulate(e);
  6975. if (++e->top == e->stacklimit) {
  6976. /* TODO(haberman): grow stack? */
  6977. return false;
  6978. }
  6979. if (++e->segptr == e->seglimit) {
  6980. /* Grow segment buffer. */
  6981. size_t old_size =
  6982. (e->seglimit - e->segbuf) * sizeof(upb_pb_encoder_segment);
  6983. size_t new_size = old_size * 2;
  6984. upb_pb_encoder_segment *new_buf =
  6985. upb_arena_realloc(e->arena, e->segbuf, old_size, new_size);
  6986. if (new_buf == NULL) {
  6987. return false;
  6988. }
  6989. e->segptr = new_buf + (e->segptr - e->segbuf);
  6990. e->seglimit = new_buf + (new_size / sizeof(upb_pb_encoder_segment));
  6991. e->segbuf = new_buf;
  6992. }
  6993. } else {
  6994. /* We were previously at the top level, start buffering. */
  6995. e->segptr = e->segbuf;
  6996. e->top = e->stack;
  6997. e->runbegin = e->ptr;
  6998. }
  6999. *e->top = (int)(e->segptr - e->segbuf);
  7000. e->segptr->seglen = 0;
  7001. e->segptr->msglen = 0;
  7002. return true;
  7003. }
  7004. /* Call to indicate the end of a delimited region. We now know the length of
  7005. * the delimited region. If we are not nested inside any other delimited
  7006. * regions, we can now emit all of the buffered data we accumulated. */
  7007. static bool end_delim(upb_pb_encoder *e) {
  7008. size_t msglen;
  7009. accumulate(e);
  7010. msglen = top(e)->msglen;
  7011. if (e->top == e->stack) {
  7012. /* All lengths are now available, emit all buffered data. */
  7013. char buf[UPB_PB_VARINT_MAX_LEN];
  7014. upb_pb_encoder_segment *s;
  7015. const char *ptr = e->buf;
  7016. for (s = e->segbuf; s <= e->segptr; s++) {
  7017. size_t lenbytes = upb_vencode64(s->msglen, buf);
  7018. putbuf(e, buf, lenbytes);
  7019. putbuf(e, ptr, s->seglen);
  7020. ptr += s->seglen;
  7021. }
  7022. e->ptr = e->buf;
  7023. e->top = NULL;
  7024. } else {
  7025. /* Need to keep buffering; propagate length info into enclosing
  7026. * submessages. */
  7027. --e->top;
  7028. top(e)->msglen += msglen + upb_varint_size(msglen);
  7029. }
  7030. return true;
  7031. }
  7032. /* tag_t **********************************************************************/
  7033. /* A precomputed (pre-encoded) tag and length. */
  7034. typedef struct {
  7035. uint8_t bytes;
  7036. char tag[7];
  7037. } tag_t;
  7038. /* Allocates a new tag for this field, and sets it in these handlerattr. */
  7039. static void new_tag(upb_handlers *h, const upb_fielddef *f, upb_wiretype_t wt,
  7040. upb_handlerattr *attr) {
  7041. uint32_t n = upb_fielddef_number(f);
  7042. tag_t *tag = upb_gmalloc(sizeof(tag_t));
  7043. tag->bytes = upb_vencode64((n << 3) | wt, tag->tag);
  7044. attr->handler_data = tag;
  7045. upb_handlers_addcleanup(h, tag, upb_gfree);
  7046. }
  7047. static bool encode_tag(upb_pb_encoder *e, const tag_t *tag) {
  7048. return encode_bytes(e, tag->tag, tag->bytes);
  7049. }
  7050. /* encoding of wire types *****************************************************/
  7051. static bool encode_fixed64(upb_pb_encoder *e, uint64_t val) {
  7052. /* TODO(haberman): byte-swap for big endian. */
  7053. return encode_bytes(e, &val, sizeof(uint64_t));
  7054. }
  7055. static bool encode_fixed32(upb_pb_encoder *e, uint32_t val) {
  7056. /* TODO(haberman): byte-swap for big endian. */
  7057. return encode_bytes(e, &val, sizeof(uint32_t));
  7058. }
  7059. static bool encode_varint(upb_pb_encoder *e, uint64_t val) {
  7060. if (!reserve(e, UPB_PB_VARINT_MAX_LEN)) {
  7061. return false;
  7062. }
  7063. encoder_advance(e, upb_vencode64(val, e->ptr));
  7064. return true;
  7065. }
  7066. static uint64_t dbl2uint64(double d) {
  7067. uint64_t ret;
  7068. memcpy(&ret, &d, sizeof(uint64_t));
  7069. return ret;
  7070. }
  7071. static uint32_t flt2uint32(float d) {
  7072. uint32_t ret;
  7073. memcpy(&ret, &d, sizeof(uint32_t));
  7074. return ret;
  7075. }
  7076. /* encoding of proto types ****************************************************/
  7077. static bool startmsg(void *c, const void *hd) {
  7078. upb_pb_encoder *e = c;
  7079. UPB_UNUSED(hd);
  7080. if (e->depth++ == 0) {
  7081. upb_bytessink_start(e->output_, 0, &e->subc);
  7082. }
  7083. return true;
  7084. }
  7085. static bool endmsg(void *c, const void *hd, upb_status *status) {
  7086. upb_pb_encoder *e = c;
  7087. UPB_UNUSED(hd);
  7088. UPB_UNUSED(status);
  7089. if (--e->depth == 0) {
  7090. upb_bytessink_end(e->output_);
  7091. }
  7092. return true;
  7093. }
  7094. static void *encode_startdelimfield(void *c, const void *hd) {
  7095. bool ok = encode_tag(c, hd) && commit(c) && start_delim(c);
  7096. return ok ? c : UPB_BREAK;
  7097. }
  7098. static bool encode_unknown(void *c, const void *hd, const char *buf,
  7099. size_t len) {
  7100. UPB_UNUSED(hd);
  7101. return encode_bytes(c, buf, len) && commit(c);
  7102. }
  7103. static bool encode_enddelimfield(void *c, const void *hd) {
  7104. UPB_UNUSED(hd);
  7105. return end_delim(c);
  7106. }
  7107. static void *encode_startgroup(void *c, const void *hd) {
  7108. return (encode_tag(c, hd) && commit(c)) ? c : UPB_BREAK;
  7109. }
  7110. static bool encode_endgroup(void *c, const void *hd) {
  7111. return encode_tag(c, hd) && commit(c);
  7112. }
  7113. static void *encode_startstr(void *c, const void *hd, size_t size_hint) {
  7114. UPB_UNUSED(size_hint);
  7115. return encode_startdelimfield(c, hd);
  7116. }
  7117. static size_t encode_strbuf(void *c, const void *hd, const char *buf,
  7118. size_t len, const upb_bufhandle *h) {
  7119. UPB_UNUSED(hd);
  7120. UPB_UNUSED(h);
  7121. return encode_bytes(c, buf, len) ? len : 0;
  7122. }
  7123. #define T(type, ctype, convert, encode) \
  7124. static bool encode_scalar_##type(void *e, const void *hd, ctype val) { \
  7125. return encode_tag(e, hd) && encode(e, (convert)(val)) && commit(e); \
  7126. } \
  7127. static bool encode_packed_##type(void *e, const void *hd, ctype val) { \
  7128. UPB_UNUSED(hd); \
  7129. return encode(e, (convert)(val)); \
  7130. }
  7131. T(double, double, dbl2uint64, encode_fixed64)
  7132. T(float, float, flt2uint32, encode_fixed32)
  7133. T(int64, int64_t, uint64_t, encode_varint)
  7134. T(int32, int32_t, int64_t, encode_varint)
  7135. T(fixed64, uint64_t, uint64_t, encode_fixed64)
  7136. T(fixed32, uint32_t, uint32_t, encode_fixed32)
  7137. T(bool, bool, bool, encode_varint)
  7138. T(uint32, uint32_t, uint32_t, encode_varint)
  7139. T(uint64, uint64_t, uint64_t, encode_varint)
  7140. T(enum, int32_t, uint32_t, encode_varint)
  7141. T(sfixed32, int32_t, uint32_t, encode_fixed32)
  7142. T(sfixed64, int64_t, uint64_t, encode_fixed64)
  7143. T(sint32, int32_t, upb_zzenc_32, encode_varint)
  7144. T(sint64, int64_t, upb_zzenc_64, encode_varint)
  7145. #undef T
  7146. /* code to build the handlers *************************************************/
  7147. #include <stdio.h>
  7148. static void newhandlers_callback(const void *closure, upb_handlers *h) {
  7149. const upb_msgdef *m;
  7150. upb_msg_field_iter i;
  7151. UPB_UNUSED(closure);
  7152. upb_handlers_setstartmsg(h, startmsg, NULL);
  7153. upb_handlers_setendmsg(h, endmsg, NULL);
  7154. upb_handlers_setunknown(h, encode_unknown, NULL);
  7155. m = upb_handlers_msgdef(h);
  7156. for(upb_msg_field_begin(&i, m);
  7157. !upb_msg_field_done(&i);
  7158. upb_msg_field_next(&i)) {
  7159. const upb_fielddef *f = upb_msg_iter_field(&i);
  7160. bool packed = upb_fielddef_isseq(f) && upb_fielddef_isprimitive(f) &&
  7161. upb_fielddef_packed(f);
  7162. upb_handlerattr attr = UPB_HANDLERATTR_INIT;
  7163. upb_wiretype_t wt =
  7164. packed ? UPB_WIRE_TYPE_DELIMITED
  7165. : upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  7166. /* Pre-encode the tag for this field. */
  7167. new_tag(h, f, wt, &attr);
  7168. if (packed) {
  7169. upb_handlers_setstartseq(h, f, encode_startdelimfield, &attr);
  7170. upb_handlers_setendseq(h, f, encode_enddelimfield, &attr);
  7171. }
  7172. #define T(upper, lower, upbtype) \
  7173. case UPB_DESCRIPTOR_TYPE_##upper: \
  7174. if (packed) { \
  7175. upb_handlers_set##upbtype(h, f, encode_packed_##lower, &attr); \
  7176. } else { \
  7177. upb_handlers_set##upbtype(h, f, encode_scalar_##lower, &attr); \
  7178. } \
  7179. break;
  7180. switch (upb_fielddef_descriptortype(f)) {
  7181. T(DOUBLE, double, double);
  7182. T(FLOAT, float, float);
  7183. T(INT64, int64, int64);
  7184. T(INT32, int32, int32);
  7185. T(FIXED64, fixed64, uint64);
  7186. T(FIXED32, fixed32, uint32);
  7187. T(BOOL, bool, bool);
  7188. T(UINT32, uint32, uint32);
  7189. T(UINT64, uint64, uint64);
  7190. T(ENUM, enum, int32);
  7191. T(SFIXED32, sfixed32, int32);
  7192. T(SFIXED64, sfixed64, int64);
  7193. T(SINT32, sint32, int32);
  7194. T(SINT64, sint64, int64);
  7195. case UPB_DESCRIPTOR_TYPE_STRING:
  7196. case UPB_DESCRIPTOR_TYPE_BYTES:
  7197. upb_handlers_setstartstr(h, f, encode_startstr, &attr);
  7198. upb_handlers_setendstr(h, f, encode_enddelimfield, &attr);
  7199. upb_handlers_setstring(h, f, encode_strbuf, &attr);
  7200. break;
  7201. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  7202. upb_handlers_setstartsubmsg(h, f, encode_startdelimfield, &attr);
  7203. upb_handlers_setendsubmsg(h, f, encode_enddelimfield, &attr);
  7204. break;
  7205. case UPB_DESCRIPTOR_TYPE_GROUP: {
  7206. /* Endgroup takes a different tag (wire_type = END_GROUP). */
  7207. upb_handlerattr attr2 = UPB_HANDLERATTR_INIT;
  7208. new_tag(h, f, UPB_WIRE_TYPE_END_GROUP, &attr2);
  7209. upb_handlers_setstartsubmsg(h, f, encode_startgroup, &attr);
  7210. upb_handlers_setendsubmsg(h, f, encode_endgroup, &attr2);
  7211. break;
  7212. }
  7213. }
  7214. #undef T
  7215. }
  7216. }
  7217. void upb_pb_encoder_reset(upb_pb_encoder *e) {
  7218. e->segptr = NULL;
  7219. e->top = NULL;
  7220. e->depth = 0;
  7221. }
  7222. /* public API *****************************************************************/
  7223. upb_handlercache *upb_pb_encoder_newcache(void) {
  7224. return upb_handlercache_new(newhandlers_callback, NULL);
  7225. }
  7226. upb_pb_encoder *upb_pb_encoder_create(upb_arena *arena, const upb_handlers *h,
  7227. upb_bytessink output) {
  7228. const size_t initial_bufsize = 256;
  7229. const size_t initial_segbufsize = 16;
  7230. /* TODO(haberman): make this configurable. */
  7231. const size_t stack_size = 64;
  7232. #ifndef NDEBUG
  7233. const size_t size_before = upb_arena_bytesallocated(arena);
  7234. #endif
  7235. upb_pb_encoder *e = upb_arena_malloc(arena, sizeof(upb_pb_encoder));
  7236. if (!e) return NULL;
  7237. e->buf = upb_arena_malloc(arena, initial_bufsize);
  7238. e->segbuf = upb_arena_malloc(arena, initial_segbufsize * sizeof(*e->segbuf));
  7239. e->stack = upb_arena_malloc(arena, stack_size * sizeof(*e->stack));
  7240. if (!e->buf || !e->segbuf || !e->stack) {
  7241. return NULL;
  7242. }
  7243. e->limit = e->buf + initial_bufsize;
  7244. e->seglimit = e->segbuf + initial_segbufsize;
  7245. e->stacklimit = e->stack + stack_size;
  7246. upb_pb_encoder_reset(e);
  7247. upb_sink_reset(&e->input_, h, e);
  7248. e->arena = arena;
  7249. e->output_ = output;
  7250. e->subc = output.closure;
  7251. e->ptr = e->buf;
  7252. /* If this fails, increase the value in encoder.h. */
  7253. UPB_ASSERT_DEBUGVAR(upb_arena_bytesallocated(arena) - size_before <=
  7254. UPB_PB_ENCODER_SIZE);
  7255. return e;
  7256. }
  7257. upb_sink upb_pb_encoder_input(upb_pb_encoder *e) { return e->input_; }
  7258. /*
  7259. * upb::pb::TextPrinter
  7260. *
  7261. * OPT: This is not optimized at all. It uses printf() which parses the format
  7262. * string every time, and it allocates memory for every put.
  7263. */
  7264. #include <ctype.h>
  7265. #include <float.h>
  7266. #include <inttypes.h>
  7267. #include <stdarg.h>
  7268. #include <stdio.h>
  7269. #include <string.h>
  7270. struct upb_textprinter {
  7271. upb_sink input_;
  7272. upb_bytessink output_;
  7273. int indent_depth_;
  7274. bool single_line_;
  7275. void *subc;
  7276. };
  7277. #define CHECK(x) if ((x) < 0) goto err;
  7278. static const char *shortname(const char *longname) {
  7279. const char *last = strrchr(longname, '.');
  7280. return last ? last + 1 : longname;
  7281. }
  7282. static int indent(upb_textprinter *p) {
  7283. int i;
  7284. if (!p->single_line_)
  7285. for (i = 0; i < p->indent_depth_; i++)
  7286. upb_bytessink_putbuf(p->output_, p->subc, " ", 2, NULL);
  7287. return 0;
  7288. }
  7289. static int endfield(upb_textprinter *p) {
  7290. const char ch = (p->single_line_ ? ' ' : '\n');
  7291. upb_bytessink_putbuf(p->output_, p->subc, &ch, 1, NULL);
  7292. return 0;
  7293. }
  7294. static int putescaped(upb_textprinter *p, const char *buf, size_t len,
  7295. bool preserve_utf8) {
  7296. /* Based on CEscapeInternal() from Google's protobuf release. */
  7297. char dstbuf[4096], *dst = dstbuf, *dstend = dstbuf + sizeof(dstbuf);
  7298. const char *end = buf + len;
  7299. /* I think hex is prettier and more useful, but proto2 uses octal; should
  7300. * investigate whether it can parse hex also. */
  7301. const bool use_hex = false;
  7302. bool last_hex_escape = false; /* true if last output char was \xNN */
  7303. for (; buf < end; buf++) {
  7304. bool is_hex_escape;
  7305. if (dstend - dst < 4) {
  7306. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  7307. dst = dstbuf;
  7308. }
  7309. is_hex_escape = false;
  7310. switch (*buf) {
  7311. case '\n': *(dst++) = '\\'; *(dst++) = 'n'; break;
  7312. case '\r': *(dst++) = '\\'; *(dst++) = 'r'; break;
  7313. case '\t': *(dst++) = '\\'; *(dst++) = 't'; break;
  7314. case '\"': *(dst++) = '\\'; *(dst++) = '\"'; break;
  7315. case '\'': *(dst++) = '\\'; *(dst++) = '\''; break;
  7316. case '\\': *(dst++) = '\\'; *(dst++) = '\\'; break;
  7317. default:
  7318. /* Note that if we emit \xNN and the buf character after that is a hex
  7319. * digit then that digit must be escaped too to prevent it being
  7320. * interpreted as part of the character code by C. */
  7321. if ((!preserve_utf8 || (uint8_t)*buf < 0x80) &&
  7322. (!isprint(*buf) || (last_hex_escape && isxdigit(*buf)))) {
  7323. sprintf(dst, (use_hex ? "\\x%02x" : "\\%03o"), (uint8_t)*buf);
  7324. is_hex_escape = use_hex;
  7325. dst += 4;
  7326. } else {
  7327. *(dst++) = *buf; break;
  7328. }
  7329. }
  7330. last_hex_escape = is_hex_escape;
  7331. }
  7332. /* Flush remaining data. */
  7333. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  7334. return 0;
  7335. }
  7336. bool putf(upb_textprinter *p, const char *fmt, ...) {
  7337. va_list args;
  7338. va_list args_copy;
  7339. char *str;
  7340. int written;
  7341. int len;
  7342. bool ok;
  7343. va_start(args, fmt);
  7344. /* Run once to get the length of the string. */
  7345. _upb_va_copy(args_copy, args);
  7346. len = _upb_vsnprintf(NULL, 0, fmt, args_copy);
  7347. va_end(args_copy);
  7348. /* + 1 for NULL terminator (vsprintf() requires it even if we don't). */
  7349. str = upb_gmalloc(len + 1);
  7350. if (!str) return false;
  7351. written = vsprintf(str, fmt, args);
  7352. va_end(args);
  7353. UPB_ASSERT(written == len);
  7354. ok = upb_bytessink_putbuf(p->output_, p->subc, str, len, NULL);
  7355. upb_gfree(str);
  7356. return ok;
  7357. }
  7358. /* handlers *******************************************************************/
  7359. static bool textprinter_startmsg(void *c, const void *hd) {
  7360. upb_textprinter *p = c;
  7361. UPB_UNUSED(hd);
  7362. if (p->indent_depth_ == 0) {
  7363. upb_bytessink_start(p->output_, 0, &p->subc);
  7364. }
  7365. return true;
  7366. }
  7367. static bool textprinter_endmsg(void *c, const void *hd, upb_status *s) {
  7368. upb_textprinter *p = c;
  7369. UPB_UNUSED(hd);
  7370. UPB_UNUSED(s);
  7371. if (p->indent_depth_ == 0) {
  7372. upb_bytessink_end(p->output_);
  7373. }
  7374. return true;
  7375. }
  7376. #define TYPE(name, ctype, fmt) \
  7377. static bool textprinter_put ## name(void *closure, const void *handler_data, \
  7378. ctype val) { \
  7379. upb_textprinter *p = closure; \
  7380. const upb_fielddef *f = handler_data; \
  7381. CHECK(indent(p)); \
  7382. putf(p, "%s: " fmt, upb_fielddef_name(f), val); \
  7383. CHECK(endfield(p)); \
  7384. return true; \
  7385. err: \
  7386. return false; \
  7387. }
  7388. static bool textprinter_putbool(void *closure, const void *handler_data,
  7389. bool val) {
  7390. upb_textprinter *p = closure;
  7391. const upb_fielddef *f = handler_data;
  7392. CHECK(indent(p));
  7393. putf(p, "%s: %s", upb_fielddef_name(f), val ? "true" : "false");
  7394. CHECK(endfield(p));
  7395. return true;
  7396. err:
  7397. return false;
  7398. }
  7399. #define STRINGIFY_HELPER(x) #x
  7400. #define STRINGIFY_MACROVAL(x) STRINGIFY_HELPER(x)
  7401. TYPE(int32, int32_t, "%" PRId32)
  7402. TYPE(int64, int64_t, "%" PRId64)
  7403. TYPE(uint32, uint32_t, "%" PRIu32)
  7404. TYPE(uint64, uint64_t, "%" PRIu64)
  7405. TYPE(float, float, "%." STRINGIFY_MACROVAL(FLT_DIG) "g")
  7406. TYPE(double, double, "%." STRINGIFY_MACROVAL(DBL_DIG) "g")
  7407. #undef TYPE
  7408. /* Output a symbolic value from the enum if found, else just print as int32. */
  7409. static bool textprinter_putenum(void *closure, const void *handler_data,
  7410. int32_t val) {
  7411. upb_textprinter *p = closure;
  7412. const upb_fielddef *f = handler_data;
  7413. const upb_enumdef *enum_def = upb_fielddef_enumsubdef(f);
  7414. const char *label = upb_enumdef_iton(enum_def, val);
  7415. if (label) {
  7416. indent(p);
  7417. putf(p, "%s: %s", upb_fielddef_name(f), label);
  7418. endfield(p);
  7419. } else {
  7420. if (!textprinter_putint32(closure, handler_data, val))
  7421. return false;
  7422. }
  7423. return true;
  7424. }
  7425. static void *textprinter_startstr(void *closure, const void *handler_data,
  7426. size_t size_hint) {
  7427. upb_textprinter *p = closure;
  7428. const upb_fielddef *f = handler_data;
  7429. UPB_UNUSED(size_hint);
  7430. indent(p);
  7431. putf(p, "%s: \"", upb_fielddef_name(f));
  7432. return p;
  7433. }
  7434. static bool textprinter_endstr(void *closure, const void *handler_data) {
  7435. upb_textprinter *p = closure;
  7436. UPB_UNUSED(handler_data);
  7437. putf(p, "\"");
  7438. endfield(p);
  7439. return true;
  7440. }
  7441. static size_t textprinter_putstr(void *closure, const void *hd, const char *buf,
  7442. size_t len, const upb_bufhandle *handle) {
  7443. upb_textprinter *p = closure;
  7444. const upb_fielddef *f = hd;
  7445. UPB_UNUSED(handle);
  7446. CHECK(putescaped(p, buf, len, upb_fielddef_type(f) == UPB_TYPE_STRING));
  7447. return len;
  7448. err:
  7449. return 0;
  7450. }
  7451. static void *textprinter_startsubmsg(void *closure, const void *handler_data) {
  7452. upb_textprinter *p = closure;
  7453. const char *name = handler_data;
  7454. CHECK(indent(p));
  7455. putf(p, "%s {%c", name, p->single_line_ ? ' ' : '\n');
  7456. p->indent_depth_++;
  7457. return p;
  7458. err:
  7459. return UPB_BREAK;
  7460. }
  7461. static bool textprinter_endsubmsg(void *closure, const void *handler_data) {
  7462. upb_textprinter *p = closure;
  7463. UPB_UNUSED(handler_data);
  7464. p->indent_depth_--;
  7465. CHECK(indent(p));
  7466. upb_bytessink_putbuf(p->output_, p->subc, "}", 1, NULL);
  7467. CHECK(endfield(p));
  7468. return true;
  7469. err:
  7470. return false;
  7471. }
  7472. static void onmreg(const void *c, upb_handlers *h) {
  7473. const upb_msgdef *m = upb_handlers_msgdef(h);
  7474. upb_msg_field_iter i;
  7475. UPB_UNUSED(c);
  7476. upb_handlers_setstartmsg(h, textprinter_startmsg, NULL);
  7477. upb_handlers_setendmsg(h, textprinter_endmsg, NULL);
  7478. for(upb_msg_field_begin(&i, m);
  7479. !upb_msg_field_done(&i);
  7480. upb_msg_field_next(&i)) {
  7481. upb_fielddef *f = upb_msg_iter_field(&i);
  7482. upb_handlerattr attr = UPB_HANDLERATTR_INIT;
  7483. attr.handler_data = f;
  7484. switch (upb_fielddef_type(f)) {
  7485. case UPB_TYPE_INT32:
  7486. upb_handlers_setint32(h, f, textprinter_putint32, &attr);
  7487. break;
  7488. case UPB_TYPE_INT64:
  7489. upb_handlers_setint64(h, f, textprinter_putint64, &attr);
  7490. break;
  7491. case UPB_TYPE_UINT32:
  7492. upb_handlers_setuint32(h, f, textprinter_putuint32, &attr);
  7493. break;
  7494. case UPB_TYPE_UINT64:
  7495. upb_handlers_setuint64(h, f, textprinter_putuint64, &attr);
  7496. break;
  7497. case UPB_TYPE_FLOAT:
  7498. upb_handlers_setfloat(h, f, textprinter_putfloat, &attr);
  7499. break;
  7500. case UPB_TYPE_DOUBLE:
  7501. upb_handlers_setdouble(h, f, textprinter_putdouble, &attr);
  7502. break;
  7503. case UPB_TYPE_BOOL:
  7504. upb_handlers_setbool(h, f, textprinter_putbool, &attr);
  7505. break;
  7506. case UPB_TYPE_STRING:
  7507. case UPB_TYPE_BYTES:
  7508. upb_handlers_setstartstr(h, f, textprinter_startstr, &attr);
  7509. upb_handlers_setstring(h, f, textprinter_putstr, &attr);
  7510. upb_handlers_setendstr(h, f, textprinter_endstr, &attr);
  7511. break;
  7512. case UPB_TYPE_MESSAGE: {
  7513. const char *name =
  7514. upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_GROUP
  7515. ? shortname(upb_msgdef_fullname(upb_fielddef_msgsubdef(f)))
  7516. : upb_fielddef_name(f);
  7517. attr.handler_data = name;
  7518. upb_handlers_setstartsubmsg(h, f, textprinter_startsubmsg, &attr);
  7519. upb_handlers_setendsubmsg(h, f, textprinter_endsubmsg, &attr);
  7520. break;
  7521. }
  7522. case UPB_TYPE_ENUM:
  7523. upb_handlers_setint32(h, f, textprinter_putenum, &attr);
  7524. break;
  7525. }
  7526. }
  7527. }
  7528. static void textprinter_reset(upb_textprinter *p, bool single_line) {
  7529. p->single_line_ = single_line;
  7530. p->indent_depth_ = 0;
  7531. }
  7532. /* Public API *****************************************************************/
  7533. upb_textprinter *upb_textprinter_create(upb_arena *arena, const upb_handlers *h,
  7534. upb_bytessink output) {
  7535. upb_textprinter *p = upb_arena_malloc(arena, sizeof(upb_textprinter));
  7536. if (!p) return NULL;
  7537. p->output_ = output;
  7538. upb_sink_reset(&p->input_, h, p);
  7539. textprinter_reset(p, false);
  7540. return p;
  7541. }
  7542. upb_handlercache *upb_textprinter_newcache(void) {
  7543. return upb_handlercache_new(&onmreg, NULL);
  7544. }
  7545. upb_sink upb_textprinter_input(upb_textprinter *p) { return p->input_; }
  7546. void upb_textprinter_setsingleline(upb_textprinter *p, bool single_line) {
  7547. p->single_line_ = single_line;
  7548. }
  7549. /* Index is descriptor type. */
  7550. const uint8_t upb_pb_native_wire_types[] = {
  7551. UPB_WIRE_TYPE_END_GROUP, /* ENDGROUP */
  7552. UPB_WIRE_TYPE_64BIT, /* DOUBLE */
  7553. UPB_WIRE_TYPE_32BIT, /* FLOAT */
  7554. UPB_WIRE_TYPE_VARINT, /* INT64 */
  7555. UPB_WIRE_TYPE_VARINT, /* UINT64 */
  7556. UPB_WIRE_TYPE_VARINT, /* INT32 */
  7557. UPB_WIRE_TYPE_64BIT, /* FIXED64 */
  7558. UPB_WIRE_TYPE_32BIT, /* FIXED32 */
  7559. UPB_WIRE_TYPE_VARINT, /* BOOL */
  7560. UPB_WIRE_TYPE_DELIMITED, /* STRING */
  7561. UPB_WIRE_TYPE_START_GROUP, /* GROUP */
  7562. UPB_WIRE_TYPE_DELIMITED, /* MESSAGE */
  7563. UPB_WIRE_TYPE_DELIMITED, /* BYTES */
  7564. UPB_WIRE_TYPE_VARINT, /* UINT32 */
  7565. UPB_WIRE_TYPE_VARINT, /* ENUM */
  7566. UPB_WIRE_TYPE_32BIT, /* SFIXED32 */
  7567. UPB_WIRE_TYPE_64BIT, /* SFIXED64 */
  7568. UPB_WIRE_TYPE_VARINT, /* SINT32 */
  7569. UPB_WIRE_TYPE_VARINT, /* SINT64 */
  7570. };
  7571. /* A basic branch-based decoder, uses 32-bit values to get good performance
  7572. * on 32-bit architectures (but performs well on 64-bits also).
  7573. * This scheme comes from the original Google Protobuf implementation
  7574. * (proto2). */
  7575. upb_decoderet upb_vdecode_max8_branch32(upb_decoderet r) {
  7576. upb_decoderet err = {NULL, 0};
  7577. const char *p = r.p;
  7578. uint32_t low = (uint32_t)r.val;
  7579. uint32_t high = 0;
  7580. uint32_t b;
  7581. b = *(p++); low |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  7582. b = *(p++); low |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  7583. b = *(p++); low |= (b & 0x7fU) << 28;
  7584. high = (b & 0x7fU) >> 4; if (!(b & 0x80)) goto done;
  7585. b = *(p++); high |= (b & 0x7fU) << 3; if (!(b & 0x80)) goto done;
  7586. b = *(p++); high |= (b & 0x7fU) << 10; if (!(b & 0x80)) goto done;
  7587. b = *(p++); high |= (b & 0x7fU) << 17; if (!(b & 0x80)) goto done;
  7588. b = *(p++); high |= (b & 0x7fU) << 24; if (!(b & 0x80)) goto done;
  7589. b = *(p++); high |= (b & 0x7fU) << 31; if (!(b & 0x80)) goto done;
  7590. return err;
  7591. done:
  7592. r.val = ((uint64_t)high << 32) | low;
  7593. r.p = p;
  7594. return r;
  7595. }
  7596. /* Like the previous, but uses 64-bit values. */
  7597. upb_decoderet upb_vdecode_max8_branch64(upb_decoderet r) {
  7598. const char *p = r.p;
  7599. uint64_t val = r.val;
  7600. uint64_t b;
  7601. upb_decoderet err = {NULL, 0};
  7602. b = *(p++); val |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  7603. b = *(p++); val |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  7604. b = *(p++); val |= (b & 0x7fU) << 28; if (!(b & 0x80)) goto done;
  7605. b = *(p++); val |= (b & 0x7fU) << 35; if (!(b & 0x80)) goto done;
  7606. b = *(p++); val |= (b & 0x7fU) << 42; if (!(b & 0x80)) goto done;
  7607. b = *(p++); val |= (b & 0x7fU) << 49; if (!(b & 0x80)) goto done;
  7608. b = *(p++); val |= (b & 0x7fU) << 56; if (!(b & 0x80)) goto done;
  7609. b = *(p++); val |= (b & 0x7fU) << 63; if (!(b & 0x80)) goto done;
  7610. return err;
  7611. done:
  7612. r.val = val;
  7613. r.p = p;
  7614. return r;
  7615. }
  7616. #line 1 "upb/json/parser.rl"
  7617. /*
  7618. ** upb::json::Parser (upb_json_parser)
  7619. **
  7620. ** A parser that uses the Ragel State Machine Compiler to generate
  7621. ** the finite automata.
  7622. **
  7623. ** Ragel only natively handles regular languages, but we can manually
  7624. ** program it a bit to handle context-free languages like JSON, by using
  7625. ** the "fcall" and "fret" constructs.
  7626. **
  7627. ** This parser can handle the basics, but needs several things to be fleshed
  7628. ** out:
  7629. **
  7630. ** - handling of unicode escape sequences (including high surrogate pairs).
  7631. ** - properly check and report errors for unknown fields, stack overflow,
  7632. ** improper array nesting (or lack of nesting).
  7633. ** - handling of base64 sequences with padding characters.
  7634. ** - handling of push-back (non-success returns from sink functions).
  7635. ** - handling of keys/escape-sequences/etc that span input buffers.
  7636. */
  7637. #include <ctype.h>
  7638. #include <errno.h>
  7639. #include <float.h>
  7640. #include <math.h>
  7641. #include <stdint.h>
  7642. #include <stdio.h>
  7643. #include <stdlib.h>
  7644. #include <string.h>
  7645. #include <time.h>
  7646. #define UPB_JSON_MAX_DEPTH 64
  7647. /* Type of value message */
  7648. enum {
  7649. VALUE_NULLVALUE = 0,
  7650. VALUE_NUMBERVALUE = 1,
  7651. VALUE_STRINGVALUE = 2,
  7652. VALUE_BOOLVALUE = 3,
  7653. VALUE_STRUCTVALUE = 4,
  7654. VALUE_LISTVALUE = 5
  7655. };
  7656. /* Forward declare */
  7657. static bool is_top_level(upb_json_parser *p);
  7658. static bool is_wellknown_msg(upb_json_parser *p, upb_wellknowntype_t type);
  7659. static bool is_wellknown_field(upb_json_parser *p, upb_wellknowntype_t type);
  7660. static bool is_number_wrapper_object(upb_json_parser *p);
  7661. static bool does_number_wrapper_start(upb_json_parser *p);
  7662. static bool does_number_wrapper_end(upb_json_parser *p);
  7663. static bool is_string_wrapper_object(upb_json_parser *p);
  7664. static bool does_string_wrapper_start(upb_json_parser *p);
  7665. static bool does_string_wrapper_end(upb_json_parser *p);
  7666. static bool does_fieldmask_start(upb_json_parser *p);
  7667. static bool does_fieldmask_end(upb_json_parser *p);
  7668. static void start_fieldmask_object(upb_json_parser *p);
  7669. static void end_fieldmask_object(upb_json_parser *p);
  7670. static void start_wrapper_object(upb_json_parser *p);
  7671. static void end_wrapper_object(upb_json_parser *p);
  7672. static void start_value_object(upb_json_parser *p, int value_type);
  7673. static void end_value_object(upb_json_parser *p);
  7674. static void start_listvalue_object(upb_json_parser *p);
  7675. static void end_listvalue_object(upb_json_parser *p);
  7676. static void start_structvalue_object(upb_json_parser *p);
  7677. static void end_structvalue_object(upb_json_parser *p);
  7678. static void start_object(upb_json_parser *p);
  7679. static void end_object(upb_json_parser *p);
  7680. static void start_any_object(upb_json_parser *p, const char *ptr);
  7681. static bool end_any_object(upb_json_parser *p, const char *ptr);
  7682. static bool start_subobject(upb_json_parser *p);
  7683. static void end_subobject(upb_json_parser *p);
  7684. static void start_member(upb_json_parser *p);
  7685. static void end_member(upb_json_parser *p);
  7686. static bool end_membername(upb_json_parser *p);
  7687. static void start_any_member(upb_json_parser *p, const char *ptr);
  7688. static void end_any_member(upb_json_parser *p, const char *ptr);
  7689. static bool end_any_membername(upb_json_parser *p);
  7690. size_t parse(void *closure, const void *hd, const char *buf, size_t size,
  7691. const upb_bufhandle *handle);
  7692. static bool end(void *closure, const void *hd);
  7693. static const char eof_ch = 'e';
  7694. /* stringsink */
  7695. typedef struct {
  7696. upb_byteshandler handler;
  7697. upb_bytessink sink;
  7698. char *ptr;
  7699. size_t len, size;
  7700. } upb_stringsink;
  7701. static void *stringsink_start(void *_sink, const void *hd, size_t size_hint) {
  7702. upb_stringsink *sink = _sink;
  7703. sink->len = 0;
  7704. UPB_UNUSED(hd);
  7705. UPB_UNUSED(size_hint);
  7706. return sink;
  7707. }
  7708. static size_t stringsink_string(void *_sink, const void *hd, const char *ptr,
  7709. size_t len, const upb_bufhandle *handle) {
  7710. upb_stringsink *sink = _sink;
  7711. size_t new_size = sink->size;
  7712. UPB_UNUSED(hd);
  7713. UPB_UNUSED(handle);
  7714. while (sink->len + len > new_size) {
  7715. new_size *= 2;
  7716. }
  7717. if (new_size != sink->size) {
  7718. sink->ptr = realloc(sink->ptr, new_size);
  7719. sink->size = new_size;
  7720. }
  7721. memcpy(sink->ptr + sink->len, ptr, len);
  7722. sink->len += len;
  7723. return len;
  7724. }
  7725. void upb_stringsink_init(upb_stringsink *sink) {
  7726. upb_byteshandler_init(&sink->handler);
  7727. upb_byteshandler_setstartstr(&sink->handler, stringsink_start, NULL);
  7728. upb_byteshandler_setstring(&sink->handler, stringsink_string, NULL);
  7729. upb_bytessink_reset(&sink->sink, &sink->handler, sink);
  7730. sink->size = 32;
  7731. sink->ptr = malloc(sink->size);
  7732. sink->len = 0;
  7733. }
  7734. void upb_stringsink_uninit(upb_stringsink *sink) { free(sink->ptr); }
  7735. typedef struct {
  7736. /* For encoding Any value field in binary format. */
  7737. upb_handlercache *encoder_handlercache;
  7738. upb_stringsink stringsink;
  7739. /* For decoding Any value field in json format. */
  7740. upb_json_codecache *parser_codecache;
  7741. upb_sink sink;
  7742. upb_json_parser *parser;
  7743. /* Mark the range of uninterpreted values in json input before type url. */
  7744. const char *before_type_url_start;
  7745. const char *before_type_url_end;
  7746. /* Mark the range of uninterpreted values in json input after type url. */
  7747. const char *after_type_url_start;
  7748. } upb_jsonparser_any_frame;
  7749. typedef struct {
  7750. upb_sink sink;
  7751. /* The current message in which we're parsing, and the field whose value we're
  7752. * expecting next. */
  7753. const upb_msgdef *m;
  7754. const upb_fielddef *f;
  7755. /* The table mapping json name to fielddef for this message. */
  7756. const upb_strtable *name_table;
  7757. /* We are in a repeated-field context. We need this flag to decide whether to
  7758. * handle the array as a normal repeated field or a
  7759. * google.protobuf.ListValue/google.protobuf.Value. */
  7760. bool is_repeated;
  7761. /* We are in a repeated-field context, ready to emit mapentries as
  7762. * submessages. This flag alters the start-of-object (open-brace) behavior to
  7763. * begin a sequence of mapentry messages rather than a single submessage. */
  7764. bool is_map;
  7765. /* We are in a map-entry message context. This flag is set when parsing the
  7766. * value field of a single map entry and indicates to all value-field parsers
  7767. * (subobjects, strings, numbers, and bools) that the map-entry submessage
  7768. * should end as soon as the value is parsed. */
  7769. bool is_mapentry;
  7770. /* If |is_map| or |is_mapentry| is true, |mapfield| refers to the parent
  7771. * message's map field that we're currently parsing. This differs from |f|
  7772. * because |f| is the field in the *current* message (i.e., the map-entry
  7773. * message itself), not the parent's field that leads to this map. */
  7774. const upb_fielddef *mapfield;
  7775. /* We are in an Any message context. This flag is set when parsing the Any
  7776. * message and indicates to all field parsers (subobjects, strings, numbers,
  7777. * and bools) that the parsed field should be serialized as binary data or
  7778. * cached (type url not found yet). */
  7779. bool is_any;
  7780. /* The type of packed message in Any. */
  7781. upb_jsonparser_any_frame *any_frame;
  7782. /* True if the field to be parsed is unknown. */
  7783. bool is_unknown_field;
  7784. } upb_jsonparser_frame;
  7785. static void init_frame(upb_jsonparser_frame* frame) {
  7786. frame->m = NULL;
  7787. frame->f = NULL;
  7788. frame->name_table = NULL;
  7789. frame->is_repeated = false;
  7790. frame->is_map = false;
  7791. frame->is_mapentry = false;
  7792. frame->mapfield = NULL;
  7793. frame->is_any = false;
  7794. frame->any_frame = NULL;
  7795. frame->is_unknown_field = false;
  7796. }
  7797. struct upb_json_parser {
  7798. upb_arena *arena;
  7799. const upb_json_parsermethod *method;
  7800. upb_bytessink input_;
  7801. /* Stack to track the JSON scopes we are in. */
  7802. upb_jsonparser_frame stack[UPB_JSON_MAX_DEPTH];
  7803. upb_jsonparser_frame *top;
  7804. upb_jsonparser_frame *limit;
  7805. upb_status *status;
  7806. /* Ragel's internal parsing stack for the parsing state machine. */
  7807. int current_state;
  7808. int parser_stack[UPB_JSON_MAX_DEPTH];
  7809. int parser_top;
  7810. /* The handle for the current buffer. */
  7811. const upb_bufhandle *handle;
  7812. /* Accumulate buffer. See details in parser.rl. */
  7813. const char *accumulated;
  7814. size_t accumulated_len;
  7815. char *accumulate_buf;
  7816. size_t accumulate_buf_size;
  7817. /* Multi-part text data. See details in parser.rl. */
  7818. int multipart_state;
  7819. upb_selector_t string_selector;
  7820. /* Input capture. See details in parser.rl. */
  7821. const char *capture;
  7822. /* Intermediate result of parsing a unicode escape sequence. */
  7823. uint32_t digit;
  7824. /* For resolve type url in Any. */
  7825. const upb_symtab *symtab;
  7826. /* Whether to proceed if unknown field is met. */
  7827. bool ignore_json_unknown;
  7828. /* Cache for parsing timestamp due to base and zone are handled in different
  7829. * handlers. */
  7830. struct tm tm;
  7831. };
  7832. static upb_jsonparser_frame* start_jsonparser_frame(upb_json_parser *p) {
  7833. upb_jsonparser_frame *inner;
  7834. inner = p->top + 1;
  7835. init_frame(inner);
  7836. return inner;
  7837. }
  7838. struct upb_json_codecache {
  7839. upb_arena *arena;
  7840. upb_inttable methods; /* upb_msgdef* -> upb_json_parsermethod* */
  7841. };
  7842. struct upb_json_parsermethod {
  7843. const upb_json_codecache *cache;
  7844. upb_byteshandler input_handler_;
  7845. /* Maps json_name -> fielddef */
  7846. upb_strtable name_table;
  7847. };
  7848. #define PARSER_CHECK_RETURN(x) if (!(x)) return false
  7849. static upb_jsonparser_any_frame *json_parser_any_frame_new(
  7850. upb_json_parser *p) {
  7851. upb_jsonparser_any_frame *frame;
  7852. frame = upb_arena_malloc(p->arena, sizeof(upb_jsonparser_any_frame));
  7853. frame->encoder_handlercache = upb_pb_encoder_newcache();
  7854. frame->parser_codecache = upb_json_codecache_new();
  7855. frame->parser = NULL;
  7856. frame->before_type_url_start = NULL;
  7857. frame->before_type_url_end = NULL;
  7858. frame->after_type_url_start = NULL;
  7859. upb_stringsink_init(&frame->stringsink);
  7860. return frame;
  7861. }
  7862. static void json_parser_any_frame_set_payload_type(
  7863. upb_json_parser *p,
  7864. upb_jsonparser_any_frame *frame,
  7865. const upb_msgdef *payload_type) {
  7866. const upb_handlers *h;
  7867. const upb_json_parsermethod *parser_method;
  7868. upb_pb_encoder *encoder;
  7869. /* Initialize encoder. */
  7870. h = upb_handlercache_get(frame->encoder_handlercache, payload_type);
  7871. encoder = upb_pb_encoder_create(p->arena, h, frame->stringsink.sink);
  7872. /* Initialize parser. */
  7873. parser_method = upb_json_codecache_get(frame->parser_codecache, payload_type);
  7874. upb_sink_reset(&frame->sink, h, encoder);
  7875. frame->parser =
  7876. upb_json_parser_create(p->arena, parser_method, p->symtab, frame->sink,
  7877. p->status, p->ignore_json_unknown);
  7878. }
  7879. static void json_parser_any_frame_free(upb_jsonparser_any_frame *frame) {
  7880. upb_handlercache_free(frame->encoder_handlercache);
  7881. upb_json_codecache_free(frame->parser_codecache);
  7882. upb_stringsink_uninit(&frame->stringsink);
  7883. }
  7884. static bool json_parser_any_frame_has_type_url(
  7885. upb_jsonparser_any_frame *frame) {
  7886. return frame->parser != NULL;
  7887. }
  7888. static bool json_parser_any_frame_has_value_before_type_url(
  7889. upb_jsonparser_any_frame *frame) {
  7890. return frame->before_type_url_start != frame->before_type_url_end;
  7891. }
  7892. static bool json_parser_any_frame_has_value_after_type_url(
  7893. upb_jsonparser_any_frame *frame) {
  7894. return frame->after_type_url_start != NULL;
  7895. }
  7896. static bool json_parser_any_frame_has_value(
  7897. upb_jsonparser_any_frame *frame) {
  7898. return json_parser_any_frame_has_value_before_type_url(frame) ||
  7899. json_parser_any_frame_has_value_after_type_url(frame);
  7900. }
  7901. static void json_parser_any_frame_set_before_type_url_end(
  7902. upb_jsonparser_any_frame *frame,
  7903. const char *ptr) {
  7904. if (frame->parser == NULL) {
  7905. frame->before_type_url_end = ptr;
  7906. }
  7907. }
  7908. static void json_parser_any_frame_set_after_type_url_start_once(
  7909. upb_jsonparser_any_frame *frame,
  7910. const char *ptr) {
  7911. if (json_parser_any_frame_has_type_url(frame) &&
  7912. frame->after_type_url_start == NULL) {
  7913. frame->after_type_url_start = ptr;
  7914. }
  7915. }
  7916. /* Used to signal that a capture has been suspended. */
  7917. static char suspend_capture;
  7918. static upb_selector_t getsel_for_handlertype(upb_json_parser *p,
  7919. upb_handlertype_t type) {
  7920. upb_selector_t sel;
  7921. bool ok = upb_handlers_getselector(p->top->f, type, &sel);
  7922. UPB_ASSUME(ok);
  7923. return sel;
  7924. }
  7925. static upb_selector_t parser_getsel(upb_json_parser *p) {
  7926. return getsel_for_handlertype(
  7927. p, upb_handlers_getprimitivehandlertype(p->top->f));
  7928. }
  7929. static bool check_stack(upb_json_parser *p) {
  7930. if ((p->top + 1) == p->limit) {
  7931. upb_status_seterrmsg(p->status, "Nesting too deep");
  7932. return false;
  7933. }
  7934. return true;
  7935. }
  7936. static void set_name_table(upb_json_parser *p, upb_jsonparser_frame *frame) {
  7937. upb_value v;
  7938. const upb_json_codecache *cache = p->method->cache;
  7939. bool ok;
  7940. const upb_json_parsermethod *method;
  7941. ok = upb_inttable_lookupptr(&cache->methods, frame->m, &v);
  7942. UPB_ASSUME(ok);
  7943. method = upb_value_getconstptr(v);
  7944. frame->name_table = &method->name_table;
  7945. }
  7946. /* There are GCC/Clang built-ins for overflow checking which we could start
  7947. * using if there was any performance benefit to it. */
  7948. static bool checked_add(size_t a, size_t b, size_t *c) {
  7949. if (SIZE_MAX - a < b) return false;
  7950. *c = a + b;
  7951. return true;
  7952. }
  7953. static size_t saturating_multiply(size_t a, size_t b) {
  7954. /* size_t is unsigned, so this is defined behavior even on overflow. */
  7955. size_t ret = a * b;
  7956. if (b != 0 && ret / b != a) {
  7957. ret = SIZE_MAX;
  7958. }
  7959. return ret;
  7960. }
  7961. /* Base64 decoding ************************************************************/
  7962. /* TODO(haberman): make this streaming. */
  7963. static const signed char b64table[] = {
  7964. -1, -1, -1, -1, -1, -1, -1, -1,
  7965. -1, -1, -1, -1, -1, -1, -1, -1,
  7966. -1, -1, -1, -1, -1, -1, -1, -1,
  7967. -1, -1, -1, -1, -1, -1, -1, -1,
  7968. -1, -1, -1, -1, -1, -1, -1, -1,
  7969. -1, -1, -1, 62/*+*/, -1, -1, -1, 63/*/ */,
  7970. 52/*0*/, 53/*1*/, 54/*2*/, 55/*3*/, 56/*4*/, 57/*5*/, 58/*6*/, 59/*7*/,
  7971. 60/*8*/, 61/*9*/, -1, -1, -1, -1, -1, -1,
  7972. -1, 0/*A*/, 1/*B*/, 2/*C*/, 3/*D*/, 4/*E*/, 5/*F*/, 6/*G*/,
  7973. 07/*H*/, 8/*I*/, 9/*J*/, 10/*K*/, 11/*L*/, 12/*M*/, 13/*N*/, 14/*O*/,
  7974. 15/*P*/, 16/*Q*/, 17/*R*/, 18/*S*/, 19/*T*/, 20/*U*/, 21/*V*/, 22/*W*/,
  7975. 23/*X*/, 24/*Y*/, 25/*Z*/, -1, -1, -1, -1, -1,
  7976. -1, 26/*a*/, 27/*b*/, 28/*c*/, 29/*d*/, 30/*e*/, 31/*f*/, 32/*g*/,
  7977. 33/*h*/, 34/*i*/, 35/*j*/, 36/*k*/, 37/*l*/, 38/*m*/, 39/*n*/, 40/*o*/,
  7978. 41/*p*/, 42/*q*/, 43/*r*/, 44/*s*/, 45/*t*/, 46/*u*/, 47/*v*/, 48/*w*/,
  7979. 49/*x*/, 50/*y*/, 51/*z*/, -1, -1, -1, -1, -1,
  7980. -1, -1, -1, -1, -1, -1, -1, -1,
  7981. -1, -1, -1, -1, -1, -1, -1, -1,
  7982. -1, -1, -1, -1, -1, -1, -1, -1,
  7983. -1, -1, -1, -1, -1, -1, -1, -1,
  7984. -1, -1, -1, -1, -1, -1, -1, -1,
  7985. -1, -1, -1, -1, -1, -1, -1, -1,
  7986. -1, -1, -1, -1, -1, -1, -1, -1,
  7987. -1, -1, -1, -1, -1, -1, -1, -1,
  7988. -1, -1, -1, -1, -1, -1, -1, -1,
  7989. -1, -1, -1, -1, -1, -1, -1, -1,
  7990. -1, -1, -1, -1, -1, -1, -1, -1,
  7991. -1, -1, -1, -1, -1, -1, -1, -1,
  7992. -1, -1, -1, -1, -1, -1, -1, -1,
  7993. -1, -1, -1, -1, -1, -1, -1, -1,
  7994. -1, -1, -1, -1, -1, -1, -1, -1,
  7995. -1, -1, -1, -1, -1, -1, -1, -1
  7996. };
  7997. /* Returns the table value sign-extended to 32 bits. Knowing that the upper
  7998. * bits will be 1 for unrecognized characters makes it easier to check for
  7999. * this error condition later (see below). */
  8000. int32_t b64lookup(unsigned char ch) { return b64table[ch]; }
  8001. /* Returns true if the given character is not a valid base64 character or
  8002. * padding. */
  8003. bool nonbase64(unsigned char ch) { return b64lookup(ch) == -1 && ch != '='; }
  8004. static bool base64_push(upb_json_parser *p, upb_selector_t sel, const char *ptr,
  8005. size_t len) {
  8006. const char *limit = ptr + len;
  8007. for (; ptr < limit; ptr += 4) {
  8008. uint32_t val;
  8009. char output[3];
  8010. if (limit - ptr < 4) {
  8011. upb_status_seterrf(p->status,
  8012. "Base64 input for bytes field not a multiple of 4: %s",
  8013. upb_fielddef_name(p->top->f));
  8014. return false;
  8015. }
  8016. val = b64lookup(ptr[0]) << 18 |
  8017. b64lookup(ptr[1]) << 12 |
  8018. b64lookup(ptr[2]) << 6 |
  8019. b64lookup(ptr[3]);
  8020. /* Test the upper bit; returns true if any of the characters returned -1. */
  8021. if (val & 0x80000000) {
  8022. goto otherchar;
  8023. }
  8024. output[0] = val >> 16;
  8025. output[1] = (val >> 8) & 0xff;
  8026. output[2] = val & 0xff;
  8027. upb_sink_putstring(p->top->sink, sel, output, 3, NULL);
  8028. }
  8029. return true;
  8030. otherchar:
  8031. if (nonbase64(ptr[0]) || nonbase64(ptr[1]) || nonbase64(ptr[2]) ||
  8032. nonbase64(ptr[3]) ) {
  8033. upb_status_seterrf(p->status,
  8034. "Non-base64 characters in bytes field: %s",
  8035. upb_fielddef_name(p->top->f));
  8036. return false;
  8037. } if (ptr[2] == '=') {
  8038. uint32_t val;
  8039. char output;
  8040. /* Last group contains only two input bytes, one output byte. */
  8041. if (ptr[0] == '=' || ptr[1] == '=' || ptr[3] != '=') {
  8042. goto badpadding;
  8043. }
  8044. val = b64lookup(ptr[0]) << 18 |
  8045. b64lookup(ptr[1]) << 12;
  8046. UPB_ASSERT(!(val & 0x80000000));
  8047. output = val >> 16;
  8048. upb_sink_putstring(p->top->sink, sel, &output, 1, NULL);
  8049. return true;
  8050. } else {
  8051. uint32_t val;
  8052. char output[2];
  8053. /* Last group contains only three input bytes, two output bytes. */
  8054. if (ptr[0] == '=' || ptr[1] == '=' || ptr[2] == '=') {
  8055. goto badpadding;
  8056. }
  8057. val = b64lookup(ptr[0]) << 18 |
  8058. b64lookup(ptr[1]) << 12 |
  8059. b64lookup(ptr[2]) << 6;
  8060. output[0] = val >> 16;
  8061. output[1] = (val >> 8) & 0xff;
  8062. upb_sink_putstring(p->top->sink, sel, output, 2, NULL);
  8063. return true;
  8064. }
  8065. badpadding:
  8066. upb_status_seterrf(p->status,
  8067. "Incorrect base64 padding for field: %s (%.*s)",
  8068. upb_fielddef_name(p->top->f),
  8069. 4, ptr);
  8070. return false;
  8071. }
  8072. /* Accumulate buffer **********************************************************/
  8073. /* Functionality for accumulating a buffer.
  8074. *
  8075. * Some parts of the parser need an entire value as a contiguous string. For
  8076. * example, to look up a member name in a hash table, or to turn a string into
  8077. * a number, the relevant library routines need the input string to be in
  8078. * contiguous memory, even if the value spanned two or more buffers in the
  8079. * input. These routines handle that.
  8080. *
  8081. * In the common case we can just point to the input buffer to get this
  8082. * contiguous string and avoid any actual copy. So we optimistically begin
  8083. * this way. But there are a few cases where we must instead copy into a
  8084. * separate buffer:
  8085. *
  8086. * 1. The string was not contiguous in the input (it spanned buffers).
  8087. *
  8088. * 2. The string included escape sequences that need to be interpreted to get
  8089. * the true value in a contiguous buffer. */
  8090. static void assert_accumulate_empty(upb_json_parser *p) {
  8091. UPB_ASSERT(p->accumulated == NULL);
  8092. UPB_ASSERT(p->accumulated_len == 0);
  8093. }
  8094. static void accumulate_clear(upb_json_parser *p) {
  8095. p->accumulated = NULL;
  8096. p->accumulated_len = 0;
  8097. }
  8098. /* Used internally by accumulate_append(). */
  8099. static bool accumulate_realloc(upb_json_parser *p, size_t need) {
  8100. void *mem;
  8101. size_t old_size = p->accumulate_buf_size;
  8102. size_t new_size = UPB_MAX(old_size, 128);
  8103. while (new_size < need) {
  8104. new_size = saturating_multiply(new_size, 2);
  8105. }
  8106. mem = upb_arena_realloc(p->arena, p->accumulate_buf, old_size, new_size);
  8107. if (!mem) {
  8108. upb_status_seterrmsg(p->status, "Out of memory allocating buffer.");
  8109. return false;
  8110. }
  8111. p->accumulate_buf = mem;
  8112. p->accumulate_buf_size = new_size;
  8113. return true;
  8114. }
  8115. /* Logically appends the given data to the append buffer.
  8116. * If "can_alias" is true, we will try to avoid actually copying, but the buffer
  8117. * must be valid until the next accumulate_append() call (if any). */
  8118. static bool accumulate_append(upb_json_parser *p, const char *buf, size_t len,
  8119. bool can_alias) {
  8120. size_t need;
  8121. if (!p->accumulated && can_alias) {
  8122. p->accumulated = buf;
  8123. p->accumulated_len = len;
  8124. return true;
  8125. }
  8126. if (!checked_add(p->accumulated_len, len, &need)) {
  8127. upb_status_seterrmsg(p->status, "Integer overflow.");
  8128. return false;
  8129. }
  8130. if (need > p->accumulate_buf_size && !accumulate_realloc(p, need)) {
  8131. return false;
  8132. }
  8133. if (p->accumulated != p->accumulate_buf) {
  8134. memcpy(p->accumulate_buf, p->accumulated, p->accumulated_len);
  8135. p->accumulated = p->accumulate_buf;
  8136. }
  8137. memcpy(p->accumulate_buf + p->accumulated_len, buf, len);
  8138. p->accumulated_len += len;
  8139. return true;
  8140. }
  8141. /* Returns a pointer to the data accumulated since the last accumulate_clear()
  8142. * call, and writes the length to *len. This with point either to the input
  8143. * buffer or a temporary accumulate buffer. */
  8144. static const char *accumulate_getptr(upb_json_parser *p, size_t *len) {
  8145. UPB_ASSERT(p->accumulated);
  8146. *len = p->accumulated_len;
  8147. return p->accumulated;
  8148. }
  8149. /* Mult-part text data ********************************************************/
  8150. /* When we have text data in the input, it can often come in multiple segments.
  8151. * For example, there may be some raw string data followed by an escape
  8152. * sequence. The two segments are processed with different logic. Also buffer
  8153. * seams in the input can cause multiple segments.
  8154. *
  8155. * As we see segments, there are two main cases for how we want to process them:
  8156. *
  8157. * 1. we want to push the captured input directly to string handlers.
  8158. *
  8159. * 2. we need to accumulate all the parts into a contiguous buffer for further
  8160. * processing (field name lookup, string->number conversion, etc). */
  8161. /* This is the set of states for p->multipart_state. */
  8162. enum {
  8163. /* We are not currently processing multipart data. */
  8164. MULTIPART_INACTIVE = 0,
  8165. /* We are processing multipart data by accumulating it into a contiguous
  8166. * buffer. */
  8167. MULTIPART_ACCUMULATE = 1,
  8168. /* We are processing multipart data by pushing each part directly to the
  8169. * current string handlers. */
  8170. MULTIPART_PUSHEAGERLY = 2
  8171. };
  8172. /* Start a multi-part text value where we accumulate the data for processing at
  8173. * the end. */
  8174. static void multipart_startaccum(upb_json_parser *p) {
  8175. assert_accumulate_empty(p);
  8176. UPB_ASSERT(p->multipart_state == MULTIPART_INACTIVE);
  8177. p->multipart_state = MULTIPART_ACCUMULATE;
  8178. }
  8179. /* Start a multi-part text value where we immediately push text data to a string
  8180. * value with the given selector. */
  8181. static void multipart_start(upb_json_parser *p, upb_selector_t sel) {
  8182. assert_accumulate_empty(p);
  8183. UPB_ASSERT(p->multipart_state == MULTIPART_INACTIVE);
  8184. p->multipart_state = MULTIPART_PUSHEAGERLY;
  8185. p->string_selector = sel;
  8186. }
  8187. static bool multipart_text(upb_json_parser *p, const char *buf, size_t len,
  8188. bool can_alias) {
  8189. switch (p->multipart_state) {
  8190. case MULTIPART_INACTIVE:
  8191. upb_status_seterrmsg(
  8192. p->status, "Internal error: unexpected state MULTIPART_INACTIVE");
  8193. return false;
  8194. case MULTIPART_ACCUMULATE:
  8195. if (!accumulate_append(p, buf, len, can_alias)) {
  8196. return false;
  8197. }
  8198. break;
  8199. case MULTIPART_PUSHEAGERLY: {
  8200. const upb_bufhandle *handle = can_alias ? p->handle : NULL;
  8201. upb_sink_putstring(p->top->sink, p->string_selector, buf, len, handle);
  8202. break;
  8203. }
  8204. }
  8205. return true;
  8206. }
  8207. /* Note: this invalidates the accumulate buffer! Call only after reading its
  8208. * contents. */
  8209. static void multipart_end(upb_json_parser *p) {
  8210. /* UPB_ASSERT(p->multipart_state != MULTIPART_INACTIVE); */
  8211. p->multipart_state = MULTIPART_INACTIVE;
  8212. accumulate_clear(p);
  8213. }
  8214. /* Input capture **************************************************************/
  8215. /* Functionality for capturing a region of the input as text. Gracefully
  8216. * handles the case where a buffer seam occurs in the middle of the captured
  8217. * region. */
  8218. static void capture_begin(upb_json_parser *p, const char *ptr) {
  8219. UPB_ASSERT(p->multipart_state != MULTIPART_INACTIVE);
  8220. UPB_ASSERT(p->capture == NULL);
  8221. p->capture = ptr;
  8222. }
  8223. static bool capture_end(upb_json_parser *p, const char *ptr) {
  8224. UPB_ASSERT(p->capture);
  8225. if (multipart_text(p, p->capture, ptr - p->capture, true)) {
  8226. p->capture = NULL;
  8227. return true;
  8228. } else {
  8229. return false;
  8230. }
  8231. }
  8232. /* This is called at the end of each input buffer (ie. when we have hit a
  8233. * buffer seam). If we are in the middle of capturing the input, this
  8234. * processes the unprocessed capture region. */
  8235. static void capture_suspend(upb_json_parser *p, const char **ptr) {
  8236. if (!p->capture) return;
  8237. if (multipart_text(p, p->capture, *ptr - p->capture, false)) {
  8238. /* We use this as a signal that we were in the middle of capturing, and
  8239. * that capturing should resume at the beginning of the next buffer.
  8240. *
  8241. * We can't use *ptr here, because we have no guarantee that this pointer
  8242. * will be valid when we resume (if the underlying memory is freed, then
  8243. * using the pointer at all, even to compare to NULL, is likely undefined
  8244. * behavior). */
  8245. p->capture = &suspend_capture;
  8246. } else {
  8247. /* Need to back up the pointer to the beginning of the capture, since
  8248. * we were not able to actually preserve it. */
  8249. *ptr = p->capture;
  8250. }
  8251. }
  8252. static void capture_resume(upb_json_parser *p, const char *ptr) {
  8253. if (p->capture) {
  8254. UPB_ASSERT(p->capture == &suspend_capture);
  8255. p->capture = ptr;
  8256. }
  8257. }
  8258. /* Callbacks from the parser **************************************************/
  8259. /* These are the functions called directly from the parser itself.
  8260. * We define these in the same order as their declarations in the parser. */
  8261. static char escape_char(char in) {
  8262. switch (in) {
  8263. case 'r': return '\r';
  8264. case 't': return '\t';
  8265. case 'n': return '\n';
  8266. case 'f': return '\f';
  8267. case 'b': return '\b';
  8268. case '/': return '/';
  8269. case '"': return '"';
  8270. case '\\': return '\\';
  8271. default:
  8272. UPB_ASSERT(0);
  8273. return 'x';
  8274. }
  8275. }
  8276. static bool escape(upb_json_parser *p, const char *ptr) {
  8277. char ch = escape_char(*ptr);
  8278. return multipart_text(p, &ch, 1, false);
  8279. }
  8280. static void start_hex(upb_json_parser *p) {
  8281. p->digit = 0;
  8282. }
  8283. static void hexdigit(upb_json_parser *p, const char *ptr) {
  8284. char ch = *ptr;
  8285. p->digit <<= 4;
  8286. if (ch >= '0' && ch <= '9') {
  8287. p->digit += (ch - '0');
  8288. } else if (ch >= 'a' && ch <= 'f') {
  8289. p->digit += ((ch - 'a') + 10);
  8290. } else {
  8291. UPB_ASSERT(ch >= 'A' && ch <= 'F');
  8292. p->digit += ((ch - 'A') + 10);
  8293. }
  8294. }
  8295. static bool end_hex(upb_json_parser *p) {
  8296. uint32_t codepoint = p->digit;
  8297. /* emit the codepoint as UTF-8. */
  8298. char utf8[3]; /* support \u0000 -- \uFFFF -- need only three bytes. */
  8299. int length = 0;
  8300. if (codepoint <= 0x7F) {
  8301. utf8[0] = codepoint;
  8302. length = 1;
  8303. } else if (codepoint <= 0x07FF) {
  8304. utf8[1] = (codepoint & 0x3F) | 0x80;
  8305. codepoint >>= 6;
  8306. utf8[0] = (codepoint & 0x1F) | 0xC0;
  8307. length = 2;
  8308. } else /* codepoint <= 0xFFFF */ {
  8309. utf8[2] = (codepoint & 0x3F) | 0x80;
  8310. codepoint >>= 6;
  8311. utf8[1] = (codepoint & 0x3F) | 0x80;
  8312. codepoint >>= 6;
  8313. utf8[0] = (codepoint & 0x0F) | 0xE0;
  8314. length = 3;
  8315. }
  8316. /* TODO(haberman): Handle high surrogates: if codepoint is a high surrogate
  8317. * we have to wait for the next escape to get the full code point). */
  8318. return multipart_text(p, utf8, length, false);
  8319. }
  8320. static void start_text(upb_json_parser *p, const char *ptr) {
  8321. capture_begin(p, ptr);
  8322. }
  8323. static bool end_text(upb_json_parser *p, const char *ptr) {
  8324. return capture_end(p, ptr);
  8325. }
  8326. static bool start_number(upb_json_parser *p, const char *ptr) {
  8327. if (is_top_level(p)) {
  8328. if (is_number_wrapper_object(p)) {
  8329. start_wrapper_object(p);
  8330. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8331. start_value_object(p, VALUE_NUMBERVALUE);
  8332. } else {
  8333. return false;
  8334. }
  8335. } else if (does_number_wrapper_start(p)) {
  8336. if (!start_subobject(p)) {
  8337. return false;
  8338. }
  8339. start_wrapper_object(p);
  8340. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  8341. if (!start_subobject(p)) {
  8342. return false;
  8343. }
  8344. start_value_object(p, VALUE_NUMBERVALUE);
  8345. }
  8346. multipart_startaccum(p);
  8347. capture_begin(p, ptr);
  8348. return true;
  8349. }
  8350. static bool parse_number(upb_json_parser *p, bool is_quoted);
  8351. static bool end_number_nontop(upb_json_parser *p, const char *ptr) {
  8352. if (!capture_end(p, ptr)) {
  8353. return false;
  8354. }
  8355. if (p->top->f == NULL) {
  8356. multipart_end(p);
  8357. return true;
  8358. }
  8359. return parse_number(p, false);
  8360. }
  8361. static bool end_number(upb_json_parser *p, const char *ptr) {
  8362. if (!end_number_nontop(p, ptr)) {
  8363. return false;
  8364. }
  8365. if (does_number_wrapper_end(p)) {
  8366. end_wrapper_object(p);
  8367. if (!is_top_level(p)) {
  8368. end_subobject(p);
  8369. }
  8370. return true;
  8371. }
  8372. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8373. end_value_object(p);
  8374. if (!is_top_level(p)) {
  8375. end_subobject(p);
  8376. }
  8377. return true;
  8378. }
  8379. return true;
  8380. }
  8381. /* |buf| is NULL-terminated. |buf| itself will never include quotes;
  8382. * |is_quoted| tells us whether this text originally appeared inside quotes. */
  8383. static bool parse_number_from_buffer(upb_json_parser *p, const char *buf,
  8384. bool is_quoted) {
  8385. size_t len = strlen(buf);
  8386. const char *bufend = buf + len;
  8387. char *end;
  8388. upb_fieldtype_t type = upb_fielddef_type(p->top->f);
  8389. double val;
  8390. double dummy;
  8391. double inf = UPB_INFINITY;
  8392. errno = 0;
  8393. if (len == 0 || buf[0] == ' ') {
  8394. return false;
  8395. }
  8396. /* For integer types, first try parsing with integer-specific routines.
  8397. * If these succeed, they will be more accurate for int64/uint64 than
  8398. * strtod().
  8399. */
  8400. switch (type) {
  8401. case UPB_TYPE_ENUM:
  8402. case UPB_TYPE_INT32: {
  8403. long val = strtol(buf, &end, 0);
  8404. if (errno == ERANGE || end != bufend) {
  8405. break;
  8406. } else if (val > INT32_MAX || val < INT32_MIN) {
  8407. return false;
  8408. } else {
  8409. upb_sink_putint32(p->top->sink, parser_getsel(p), (int32_t)val);
  8410. return true;
  8411. }
  8412. }
  8413. case UPB_TYPE_UINT32: {
  8414. unsigned long val = strtoul(buf, &end, 0);
  8415. if (end != bufend) {
  8416. break;
  8417. } else if (val > UINT32_MAX || errno == ERANGE) {
  8418. return false;
  8419. } else {
  8420. upb_sink_putuint32(p->top->sink, parser_getsel(p), (uint32_t)val);
  8421. return true;
  8422. }
  8423. }
  8424. /* XXX: We can't handle [u]int64 properly on 32-bit machines because
  8425. * strto[u]ll isn't in C89. */
  8426. case UPB_TYPE_INT64: {
  8427. long val = strtol(buf, &end, 0);
  8428. if (errno == ERANGE || end != bufend) {
  8429. break;
  8430. } else {
  8431. upb_sink_putint64(p->top->sink, parser_getsel(p), val);
  8432. return true;
  8433. }
  8434. }
  8435. case UPB_TYPE_UINT64: {
  8436. unsigned long val = strtoul(p->accumulated, &end, 0);
  8437. if (end != bufend) {
  8438. break;
  8439. } else if (errno == ERANGE) {
  8440. return false;
  8441. } else {
  8442. upb_sink_putuint64(p->top->sink, parser_getsel(p), val);
  8443. return true;
  8444. }
  8445. }
  8446. default:
  8447. break;
  8448. }
  8449. if (type != UPB_TYPE_DOUBLE && type != UPB_TYPE_FLOAT && is_quoted) {
  8450. /* Quoted numbers for integer types are not allowed to be in double form. */
  8451. return false;
  8452. }
  8453. if (len == strlen("Infinity") && strcmp(buf, "Infinity") == 0) {
  8454. /* C89 does not have an INFINITY macro. */
  8455. val = inf;
  8456. } else if (len == strlen("-Infinity") && strcmp(buf, "-Infinity") == 0) {
  8457. val = -inf;
  8458. } else {
  8459. val = strtod(buf, &end);
  8460. if (errno == ERANGE || end != bufend) {
  8461. return false;
  8462. }
  8463. }
  8464. switch (type) {
  8465. #define CASE(capitaltype, smalltype, ctype, min, max) \
  8466. case UPB_TYPE_ ## capitaltype: { \
  8467. if (modf(val, &dummy) != 0 || val > max || val < min) { \
  8468. return false; \
  8469. } else { \
  8470. upb_sink_put ## smalltype(p->top->sink, parser_getsel(p), \
  8471. (ctype)val); \
  8472. return true; \
  8473. } \
  8474. break; \
  8475. }
  8476. case UPB_TYPE_ENUM:
  8477. CASE(INT32, int32, int32_t, INT32_MIN, INT32_MAX);
  8478. CASE(INT64, int64, int64_t, INT64_MIN, INT64_MAX);
  8479. CASE(UINT32, uint32, uint32_t, 0, UINT32_MAX);
  8480. CASE(UINT64, uint64, uint64_t, 0, UINT64_MAX);
  8481. #undef CASE
  8482. case UPB_TYPE_DOUBLE:
  8483. upb_sink_putdouble(p->top->sink, parser_getsel(p), val);
  8484. return true;
  8485. case UPB_TYPE_FLOAT:
  8486. if ((val > FLT_MAX || val < -FLT_MAX) && val != inf && val != -inf) {
  8487. return false;
  8488. } else {
  8489. upb_sink_putfloat(p->top->sink, parser_getsel(p), val);
  8490. return true;
  8491. }
  8492. default:
  8493. return false;
  8494. }
  8495. }
  8496. static bool parse_number(upb_json_parser *p, bool is_quoted) {
  8497. size_t len;
  8498. const char *buf;
  8499. /* strtol() and friends unfortunately do not support specifying the length of
  8500. * the input string, so we need to force a copy into a NULL-terminated buffer. */
  8501. if (!multipart_text(p, "\0", 1, false)) {
  8502. return false;
  8503. }
  8504. buf = accumulate_getptr(p, &len);
  8505. if (parse_number_from_buffer(p, buf, is_quoted)) {
  8506. multipart_end(p);
  8507. return true;
  8508. } else {
  8509. upb_status_seterrf(p->status, "error parsing number: %s", buf);
  8510. multipart_end(p);
  8511. return false;
  8512. }
  8513. }
  8514. static bool parser_putbool(upb_json_parser *p, bool val) {
  8515. bool ok;
  8516. if (p->top->f == NULL) {
  8517. return true;
  8518. }
  8519. if (upb_fielddef_type(p->top->f) != UPB_TYPE_BOOL) {
  8520. upb_status_seterrf(p->status,
  8521. "Boolean value specified for non-bool field: %s",
  8522. upb_fielddef_name(p->top->f));
  8523. return false;
  8524. }
  8525. ok = upb_sink_putbool(p->top->sink, parser_getsel(p), val);
  8526. UPB_ASSERT(ok);
  8527. return true;
  8528. }
  8529. static bool end_bool(upb_json_parser *p, bool val) {
  8530. if (is_top_level(p)) {
  8531. if (is_wellknown_msg(p, UPB_WELLKNOWN_BOOLVALUE)) {
  8532. start_wrapper_object(p);
  8533. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8534. start_value_object(p, VALUE_BOOLVALUE);
  8535. } else {
  8536. return false;
  8537. }
  8538. } else if (is_wellknown_field(p, UPB_WELLKNOWN_BOOLVALUE)) {
  8539. if (!start_subobject(p)) {
  8540. return false;
  8541. }
  8542. start_wrapper_object(p);
  8543. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  8544. if (!start_subobject(p)) {
  8545. return false;
  8546. }
  8547. start_value_object(p, VALUE_BOOLVALUE);
  8548. }
  8549. if (p->top->is_unknown_field) {
  8550. return true;
  8551. }
  8552. if (!parser_putbool(p, val)) {
  8553. return false;
  8554. }
  8555. if (is_wellknown_msg(p, UPB_WELLKNOWN_BOOLVALUE)) {
  8556. end_wrapper_object(p);
  8557. if (!is_top_level(p)) {
  8558. end_subobject(p);
  8559. }
  8560. return true;
  8561. }
  8562. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8563. end_value_object(p);
  8564. if (!is_top_level(p)) {
  8565. end_subobject(p);
  8566. }
  8567. return true;
  8568. }
  8569. return true;
  8570. }
  8571. static bool end_null(upb_json_parser *p) {
  8572. const char *zero_ptr = "0";
  8573. if (is_top_level(p)) {
  8574. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8575. start_value_object(p, VALUE_NULLVALUE);
  8576. } else {
  8577. return true;
  8578. }
  8579. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  8580. if (!start_subobject(p)) {
  8581. return false;
  8582. }
  8583. start_value_object(p, VALUE_NULLVALUE);
  8584. } else {
  8585. return true;
  8586. }
  8587. /* Fill null_value field. */
  8588. multipart_startaccum(p);
  8589. capture_begin(p, zero_ptr);
  8590. capture_end(p, zero_ptr + 1);
  8591. parse_number(p, false);
  8592. end_value_object(p);
  8593. if (!is_top_level(p)) {
  8594. end_subobject(p);
  8595. }
  8596. return true;
  8597. }
  8598. static bool start_any_stringval(upb_json_parser *p) {
  8599. multipart_startaccum(p);
  8600. return true;
  8601. }
  8602. static bool start_stringval(upb_json_parser *p) {
  8603. if (is_top_level(p)) {
  8604. if (is_string_wrapper_object(p) ||
  8605. is_number_wrapper_object(p)) {
  8606. start_wrapper_object(p);
  8607. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_FIELDMASK)) {
  8608. start_fieldmask_object(p);
  8609. return true;
  8610. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_TIMESTAMP) ||
  8611. is_wellknown_msg(p, UPB_WELLKNOWN_DURATION)) {
  8612. start_object(p);
  8613. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8614. start_value_object(p, VALUE_STRINGVALUE);
  8615. } else {
  8616. return false;
  8617. }
  8618. } else if (does_string_wrapper_start(p) ||
  8619. does_number_wrapper_start(p)) {
  8620. if (!start_subobject(p)) {
  8621. return false;
  8622. }
  8623. start_wrapper_object(p);
  8624. } else if (does_fieldmask_start(p)) {
  8625. if (!start_subobject(p)) {
  8626. return false;
  8627. }
  8628. start_fieldmask_object(p);
  8629. return true;
  8630. } else if (is_wellknown_field(p, UPB_WELLKNOWN_TIMESTAMP) ||
  8631. is_wellknown_field(p, UPB_WELLKNOWN_DURATION)) {
  8632. if (!start_subobject(p)) {
  8633. return false;
  8634. }
  8635. start_object(p);
  8636. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  8637. if (!start_subobject(p)) {
  8638. return false;
  8639. }
  8640. start_value_object(p, VALUE_STRINGVALUE);
  8641. }
  8642. if (p->top->f == NULL) {
  8643. multipart_startaccum(p);
  8644. return true;
  8645. }
  8646. if (p->top->is_any) {
  8647. return start_any_stringval(p);
  8648. }
  8649. if (upb_fielddef_isstring(p->top->f)) {
  8650. upb_jsonparser_frame *inner;
  8651. upb_selector_t sel;
  8652. if (!check_stack(p)) return false;
  8653. /* Start a new parser frame: parser frames correspond one-to-one with
  8654. * handler frames, and string events occur in a sub-frame. */
  8655. inner = start_jsonparser_frame(p);
  8656. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  8657. upb_sink_startstr(p->top->sink, sel, 0, &inner->sink);
  8658. inner->m = p->top->m;
  8659. inner->f = p->top->f;
  8660. p->top = inner;
  8661. if (upb_fielddef_type(p->top->f) == UPB_TYPE_STRING) {
  8662. /* For STRING fields we push data directly to the handlers as it is
  8663. * parsed. We don't do this yet for BYTES fields, because our base64
  8664. * decoder is not streaming.
  8665. *
  8666. * TODO(haberman): make base64 decoding streaming also. */
  8667. multipart_start(p, getsel_for_handlertype(p, UPB_HANDLER_STRING));
  8668. return true;
  8669. } else {
  8670. multipart_startaccum(p);
  8671. return true;
  8672. }
  8673. } else if (upb_fielddef_type(p->top->f) != UPB_TYPE_BOOL &&
  8674. upb_fielddef_type(p->top->f) != UPB_TYPE_MESSAGE) {
  8675. /* No need to push a frame -- numeric values in quotes remain in the
  8676. * current parser frame. These values must accmulate so we can convert
  8677. * them all at once at the end. */
  8678. multipart_startaccum(p);
  8679. return true;
  8680. } else {
  8681. upb_status_seterrf(p->status,
  8682. "String specified for bool or submessage field: %s",
  8683. upb_fielddef_name(p->top->f));
  8684. return false;
  8685. }
  8686. }
  8687. static bool end_any_stringval(upb_json_parser *p) {
  8688. size_t len;
  8689. const char *buf = accumulate_getptr(p, &len);
  8690. /* Set type_url */
  8691. upb_selector_t sel;
  8692. upb_jsonparser_frame *inner;
  8693. if (!check_stack(p)) return false;
  8694. inner = p->top + 1;
  8695. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  8696. upb_sink_startstr(p->top->sink, sel, 0, &inner->sink);
  8697. sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
  8698. upb_sink_putstring(inner->sink, sel, buf, len, NULL);
  8699. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  8700. upb_sink_endstr(inner->sink, sel);
  8701. multipart_end(p);
  8702. /* Resolve type url */
  8703. if (strncmp(buf, "type.googleapis.com/", 20) == 0 && len > 20) {
  8704. const upb_msgdef *payload_type = NULL;
  8705. buf += 20;
  8706. len -= 20;
  8707. payload_type = upb_symtab_lookupmsg2(p->symtab, buf, len);
  8708. if (payload_type == NULL) {
  8709. upb_status_seterrf(
  8710. p->status, "Cannot find packed type: %.*s\n", (int)len, buf);
  8711. return false;
  8712. }
  8713. json_parser_any_frame_set_payload_type(p, p->top->any_frame, payload_type);
  8714. return true;
  8715. } else {
  8716. upb_status_seterrf(
  8717. p->status, "Invalid type url: %.*s\n", (int)len, buf);
  8718. return false;
  8719. }
  8720. }
  8721. static bool end_stringval_nontop(upb_json_parser *p) {
  8722. bool ok = true;
  8723. if (is_wellknown_msg(p, UPB_WELLKNOWN_TIMESTAMP) ||
  8724. is_wellknown_msg(p, UPB_WELLKNOWN_DURATION)) {
  8725. multipart_end(p);
  8726. return true;
  8727. }
  8728. if (p->top->f == NULL) {
  8729. multipart_end(p);
  8730. return true;
  8731. }
  8732. if (p->top->is_any) {
  8733. return end_any_stringval(p);
  8734. }
  8735. switch (upb_fielddef_type(p->top->f)) {
  8736. case UPB_TYPE_BYTES:
  8737. if (!base64_push(p, getsel_for_handlertype(p, UPB_HANDLER_STRING),
  8738. p->accumulated, p->accumulated_len)) {
  8739. return false;
  8740. }
  8741. /* Fall through. */
  8742. case UPB_TYPE_STRING: {
  8743. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  8744. upb_sink_endstr(p->top->sink, sel);
  8745. p->top--;
  8746. break;
  8747. }
  8748. case UPB_TYPE_ENUM: {
  8749. /* Resolve enum symbolic name to integer value. */
  8750. const upb_enumdef *enumdef = upb_fielddef_enumsubdef(p->top->f);
  8751. size_t len;
  8752. const char *buf = accumulate_getptr(p, &len);
  8753. int32_t int_val = 0;
  8754. ok = upb_enumdef_ntoi(enumdef, buf, len, &int_val);
  8755. if (ok) {
  8756. upb_selector_t sel = parser_getsel(p);
  8757. upb_sink_putint32(p->top->sink, sel, int_val);
  8758. } else {
  8759. upb_status_seterrf(p->status, "Enum value unknown: '%.*s'", len, buf);
  8760. }
  8761. break;
  8762. }
  8763. case UPB_TYPE_INT32:
  8764. case UPB_TYPE_INT64:
  8765. case UPB_TYPE_UINT32:
  8766. case UPB_TYPE_UINT64:
  8767. case UPB_TYPE_DOUBLE:
  8768. case UPB_TYPE_FLOAT:
  8769. ok = parse_number(p, true);
  8770. break;
  8771. default:
  8772. UPB_ASSERT(false);
  8773. upb_status_seterrmsg(p->status, "Internal error in JSON decoder");
  8774. ok = false;
  8775. break;
  8776. }
  8777. multipart_end(p);
  8778. return ok;
  8779. }
  8780. static bool end_stringval(upb_json_parser *p) {
  8781. /* FieldMask's stringvals have been ended when handling them. Only need to
  8782. * close FieldMask here.*/
  8783. if (does_fieldmask_end(p)) {
  8784. end_fieldmask_object(p);
  8785. if (!is_top_level(p)) {
  8786. end_subobject(p);
  8787. }
  8788. return true;
  8789. }
  8790. if (!end_stringval_nontop(p)) {
  8791. return false;
  8792. }
  8793. if (does_string_wrapper_end(p) ||
  8794. does_number_wrapper_end(p)) {
  8795. end_wrapper_object(p);
  8796. if (!is_top_level(p)) {
  8797. end_subobject(p);
  8798. }
  8799. return true;
  8800. }
  8801. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8802. end_value_object(p);
  8803. if (!is_top_level(p)) {
  8804. end_subobject(p);
  8805. }
  8806. return true;
  8807. }
  8808. if (is_wellknown_msg(p, UPB_WELLKNOWN_TIMESTAMP) ||
  8809. is_wellknown_msg(p, UPB_WELLKNOWN_DURATION) ||
  8810. is_wellknown_msg(p, UPB_WELLKNOWN_FIELDMASK)) {
  8811. end_object(p);
  8812. if (!is_top_level(p)) {
  8813. end_subobject(p);
  8814. }
  8815. return true;
  8816. }
  8817. return true;
  8818. }
  8819. static void start_duration_base(upb_json_parser *p, const char *ptr) {
  8820. capture_begin(p, ptr);
  8821. }
  8822. static bool end_duration_base(upb_json_parser *p, const char *ptr) {
  8823. size_t len;
  8824. const char *buf;
  8825. char seconds_buf[14];
  8826. char nanos_buf[12];
  8827. char *end;
  8828. int64_t seconds = 0;
  8829. int32_t nanos = 0;
  8830. double val = 0.0;
  8831. const char *seconds_membername = "seconds";
  8832. const char *nanos_membername = "nanos";
  8833. size_t fraction_start;
  8834. if (!capture_end(p, ptr)) {
  8835. return false;
  8836. }
  8837. buf = accumulate_getptr(p, &len);
  8838. memset(seconds_buf, 0, 14);
  8839. memset(nanos_buf, 0, 12);
  8840. /* Find out base end. The maximus duration is 315576000000, which cannot be
  8841. * represented by double without losing precision. Thus, we need to handle
  8842. * fraction and base separately. */
  8843. for (fraction_start = 0; fraction_start < len && buf[fraction_start] != '.';
  8844. fraction_start++);
  8845. /* Parse base */
  8846. memcpy(seconds_buf, buf, fraction_start);
  8847. seconds = strtol(seconds_buf, &end, 10);
  8848. if (errno == ERANGE || end != seconds_buf + fraction_start) {
  8849. upb_status_seterrf(p->status, "error parsing duration: %s",
  8850. seconds_buf);
  8851. return false;
  8852. }
  8853. if (seconds > 315576000000) {
  8854. upb_status_seterrf(p->status, "error parsing duration: "
  8855. "maximum acceptable value is "
  8856. "315576000000");
  8857. return false;
  8858. }
  8859. if (seconds < -315576000000) {
  8860. upb_status_seterrf(p->status, "error parsing duration: "
  8861. "minimum acceptable value is "
  8862. "-315576000000");
  8863. return false;
  8864. }
  8865. /* Parse fraction */
  8866. nanos_buf[0] = '0';
  8867. memcpy(nanos_buf + 1, buf + fraction_start, len - fraction_start);
  8868. val = strtod(nanos_buf, &end);
  8869. if (errno == ERANGE || end != nanos_buf + len - fraction_start + 1) {
  8870. upb_status_seterrf(p->status, "error parsing duration: %s",
  8871. nanos_buf);
  8872. return false;
  8873. }
  8874. nanos = val * 1000000000;
  8875. if (seconds < 0) nanos = -nanos;
  8876. /* Clean up buffer */
  8877. multipart_end(p);
  8878. /* Set seconds */
  8879. start_member(p);
  8880. capture_begin(p, seconds_membername);
  8881. capture_end(p, seconds_membername + 7);
  8882. end_membername(p);
  8883. upb_sink_putint64(p->top->sink, parser_getsel(p), seconds);
  8884. end_member(p);
  8885. /* Set nanos */
  8886. start_member(p);
  8887. capture_begin(p, nanos_membername);
  8888. capture_end(p, nanos_membername + 5);
  8889. end_membername(p);
  8890. upb_sink_putint32(p->top->sink, parser_getsel(p), nanos);
  8891. end_member(p);
  8892. /* Continue previous arena */
  8893. multipart_startaccum(p);
  8894. return true;
  8895. }
  8896. static int parse_timestamp_number(upb_json_parser *p) {
  8897. size_t len;
  8898. const char *buf;
  8899. int val;
  8900. /* atoi() and friends unfortunately do not support specifying the length of
  8901. * the input string, so we need to force a copy into a NULL-terminated buffer. */
  8902. multipart_text(p, "\0", 1, false);
  8903. buf = accumulate_getptr(p, &len);
  8904. val = atoi(buf);
  8905. multipart_end(p);
  8906. multipart_startaccum(p);
  8907. return val;
  8908. }
  8909. static void start_year(upb_json_parser *p, const char *ptr) {
  8910. capture_begin(p, ptr);
  8911. }
  8912. static bool end_year(upb_json_parser *p, const char *ptr) {
  8913. if (!capture_end(p, ptr)) {
  8914. return false;
  8915. }
  8916. p->tm.tm_year = parse_timestamp_number(p) - 1900;
  8917. return true;
  8918. }
  8919. static void start_month(upb_json_parser *p, const char *ptr) {
  8920. capture_begin(p, ptr);
  8921. }
  8922. static bool end_month(upb_json_parser *p, const char *ptr) {
  8923. if (!capture_end(p, ptr)) {
  8924. return false;
  8925. }
  8926. p->tm.tm_mon = parse_timestamp_number(p) - 1;
  8927. return true;
  8928. }
  8929. static void start_day(upb_json_parser *p, const char *ptr) {
  8930. capture_begin(p, ptr);
  8931. }
  8932. static bool end_day(upb_json_parser *p, const char *ptr) {
  8933. if (!capture_end(p, ptr)) {
  8934. return false;
  8935. }
  8936. p->tm.tm_mday = parse_timestamp_number(p);
  8937. return true;
  8938. }
  8939. static void start_hour(upb_json_parser *p, const char *ptr) {
  8940. capture_begin(p, ptr);
  8941. }
  8942. static bool end_hour(upb_json_parser *p, const char *ptr) {
  8943. if (!capture_end(p, ptr)) {
  8944. return false;
  8945. }
  8946. p->tm.tm_hour = parse_timestamp_number(p);
  8947. return true;
  8948. }
  8949. static void start_minute(upb_json_parser *p, const char *ptr) {
  8950. capture_begin(p, ptr);
  8951. }
  8952. static bool end_minute(upb_json_parser *p, const char *ptr) {
  8953. if (!capture_end(p, ptr)) {
  8954. return false;
  8955. }
  8956. p->tm.tm_min = parse_timestamp_number(p);
  8957. return true;
  8958. }
  8959. static void start_second(upb_json_parser *p, const char *ptr) {
  8960. capture_begin(p, ptr);
  8961. }
  8962. static bool end_second(upb_json_parser *p, const char *ptr) {
  8963. if (!capture_end(p, ptr)) {
  8964. return false;
  8965. }
  8966. p->tm.tm_sec = parse_timestamp_number(p);
  8967. return true;
  8968. }
  8969. static void start_timestamp_base(upb_json_parser *p) {
  8970. memset(&p->tm, 0, sizeof(struct tm));
  8971. }
  8972. static void start_timestamp_fraction(upb_json_parser *p, const char *ptr) {
  8973. capture_begin(p, ptr);
  8974. }
  8975. static bool end_timestamp_fraction(upb_json_parser *p, const char *ptr) {
  8976. size_t len;
  8977. const char *buf;
  8978. char nanos_buf[12];
  8979. char *end;
  8980. double val = 0.0;
  8981. int32_t nanos;
  8982. const char *nanos_membername = "nanos";
  8983. memset(nanos_buf, 0, 12);
  8984. if (!capture_end(p, ptr)) {
  8985. return false;
  8986. }
  8987. buf = accumulate_getptr(p, &len);
  8988. if (len > 10) {
  8989. upb_status_seterrf(p->status,
  8990. "error parsing timestamp: at most 9-digit fraction.");
  8991. return false;
  8992. }
  8993. /* Parse nanos */
  8994. nanos_buf[0] = '0';
  8995. memcpy(nanos_buf + 1, buf, len);
  8996. val = strtod(nanos_buf, &end);
  8997. if (errno == ERANGE || end != nanos_buf + len + 1) {
  8998. upb_status_seterrf(p->status, "error parsing timestamp nanos: %s",
  8999. nanos_buf);
  9000. return false;
  9001. }
  9002. nanos = val * 1000000000;
  9003. /* Clean up previous environment */
  9004. multipart_end(p);
  9005. /* Set nanos */
  9006. start_member(p);
  9007. capture_begin(p, nanos_membername);
  9008. capture_end(p, nanos_membername + 5);
  9009. end_membername(p);
  9010. upb_sink_putint32(p->top->sink, parser_getsel(p), nanos);
  9011. end_member(p);
  9012. /* Continue previous environment */
  9013. multipart_startaccum(p);
  9014. return true;
  9015. }
  9016. static void start_timestamp_zone(upb_json_parser *p, const char *ptr) {
  9017. capture_begin(p, ptr);
  9018. }
  9019. static int div_round_up2(int n, int d) {
  9020. return (n + d - 1) / d;
  9021. }
  9022. /* epoch_days(1970, 1, 1) == 1970-01-01 == 0. */
  9023. static int epoch_days(int year, int month, int day) {
  9024. static const uint16_t month_yday[12] = {0, 31, 59, 90, 120, 151,
  9025. 181, 212, 243, 273, 304, 334};
  9026. int febs_since_0 = month > 2 ? year + 1 : year;
  9027. int leap_days_since_0 = div_round_up2(febs_since_0, 4) -
  9028. div_round_up2(febs_since_0, 100) +
  9029. div_round_up2(febs_since_0, 400);
  9030. int days_since_0 =
  9031. 365 * year + month_yday[month - 1] + (day - 1) + leap_days_since_0;
  9032. /* Convert from 0-epoch (0001-01-01 BC) to Unix Epoch (1970-01-01 AD).
  9033. * Since the "BC" system does not have a year zero, 1 BC == year zero. */
  9034. return days_since_0 - 719528;
  9035. }
  9036. static int64_t upb_timegm(const struct tm *tp) {
  9037. int64_t ret = epoch_days(tp->tm_year + 1900, tp->tm_mon + 1, tp->tm_mday);
  9038. ret = (ret * 24) + tp->tm_hour;
  9039. ret = (ret * 60) + tp->tm_min;
  9040. ret = (ret * 60) + tp->tm_sec;
  9041. return ret;
  9042. }
  9043. static bool end_timestamp_zone(upb_json_parser *p, const char *ptr) {
  9044. size_t len;
  9045. const char *buf;
  9046. int hours;
  9047. int64_t seconds;
  9048. const char *seconds_membername = "seconds";
  9049. if (!capture_end(p, ptr)) {
  9050. return false;
  9051. }
  9052. buf = accumulate_getptr(p, &len);
  9053. if (buf[0] != 'Z') {
  9054. if (sscanf(buf + 1, "%2d:00", &hours) != 1) {
  9055. upb_status_seterrf(p->status, "error parsing timestamp offset");
  9056. return false;
  9057. }
  9058. if (buf[0] == '+') {
  9059. hours = -hours;
  9060. }
  9061. p->tm.tm_hour += hours;
  9062. }
  9063. /* Normalize tm */
  9064. seconds = upb_timegm(&p->tm);
  9065. /* Check timestamp boundary */
  9066. if (seconds < -62135596800) {
  9067. upb_status_seterrf(p->status, "error parsing timestamp: "
  9068. "minimum acceptable value is "
  9069. "0001-01-01T00:00:00Z");
  9070. return false;
  9071. }
  9072. /* Clean up previous environment */
  9073. multipart_end(p);
  9074. /* Set seconds */
  9075. start_member(p);
  9076. capture_begin(p, seconds_membername);
  9077. capture_end(p, seconds_membername + 7);
  9078. end_membername(p);
  9079. upb_sink_putint64(p->top->sink, parser_getsel(p), seconds);
  9080. end_member(p);
  9081. /* Continue previous environment */
  9082. multipart_startaccum(p);
  9083. return true;
  9084. }
  9085. static void start_fieldmask_path_text(upb_json_parser *p, const char *ptr) {
  9086. capture_begin(p, ptr);
  9087. }
  9088. static bool end_fieldmask_path_text(upb_json_parser *p, const char *ptr) {
  9089. return capture_end(p, ptr);
  9090. }
  9091. static bool start_fieldmask_path(upb_json_parser *p) {
  9092. upb_jsonparser_frame *inner;
  9093. upb_selector_t sel;
  9094. if (!check_stack(p)) return false;
  9095. /* Start a new parser frame: parser frames correspond one-to-one with
  9096. * handler frames, and string events occur in a sub-frame. */
  9097. inner = start_jsonparser_frame(p);
  9098. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  9099. upb_sink_startstr(p->top->sink, sel, 0, &inner->sink);
  9100. inner->m = p->top->m;
  9101. inner->f = p->top->f;
  9102. p->top = inner;
  9103. multipart_startaccum(p);
  9104. return true;
  9105. }
  9106. static bool lower_camel_push(
  9107. upb_json_parser *p, upb_selector_t sel, const char *ptr, size_t len) {
  9108. const char *limit = ptr + len;
  9109. bool first = true;
  9110. for (;ptr < limit; ptr++) {
  9111. if (*ptr >= 'A' && *ptr <= 'Z' && !first) {
  9112. char lower = tolower(*ptr);
  9113. upb_sink_putstring(p->top->sink, sel, "_", 1, NULL);
  9114. upb_sink_putstring(p->top->sink, sel, &lower, 1, NULL);
  9115. } else {
  9116. upb_sink_putstring(p->top->sink, sel, ptr, 1, NULL);
  9117. }
  9118. first = false;
  9119. }
  9120. return true;
  9121. }
  9122. static bool end_fieldmask_path(upb_json_parser *p) {
  9123. upb_selector_t sel;
  9124. if (!lower_camel_push(
  9125. p, getsel_for_handlertype(p, UPB_HANDLER_STRING),
  9126. p->accumulated, p->accumulated_len)) {
  9127. return false;
  9128. }
  9129. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  9130. upb_sink_endstr(p->top->sink, sel);
  9131. p->top--;
  9132. multipart_end(p);
  9133. return true;
  9134. }
  9135. static void start_member(upb_json_parser *p) {
  9136. UPB_ASSERT(!p->top->f);
  9137. multipart_startaccum(p);
  9138. }
  9139. /* Helper: invoked during parse_mapentry() to emit the mapentry message's key
  9140. * field based on the current contents of the accumulate buffer. */
  9141. static bool parse_mapentry_key(upb_json_parser *p) {
  9142. size_t len;
  9143. const char *buf = accumulate_getptr(p, &len);
  9144. /* Emit the key field. We do a bit of ad-hoc parsing here because the
  9145. * parser state machine has already decided that this is a string field
  9146. * name, and we are reinterpreting it as some arbitrary key type. In
  9147. * particular, integer and bool keys are quoted, so we need to parse the
  9148. * quoted string contents here. */
  9149. p->top->f = upb_msgdef_itof(p->top->m, UPB_MAPENTRY_KEY);
  9150. if (p->top->f == NULL) {
  9151. upb_status_seterrmsg(p->status, "mapentry message has no key");
  9152. return false;
  9153. }
  9154. switch (upb_fielddef_type(p->top->f)) {
  9155. case UPB_TYPE_INT32:
  9156. case UPB_TYPE_INT64:
  9157. case UPB_TYPE_UINT32:
  9158. case UPB_TYPE_UINT64:
  9159. /* Invoke end_number. The accum buffer has the number's text already. */
  9160. if (!parse_number(p, true)) {
  9161. return false;
  9162. }
  9163. break;
  9164. case UPB_TYPE_BOOL:
  9165. if (len == 4 && !strncmp(buf, "true", 4)) {
  9166. if (!parser_putbool(p, true)) {
  9167. return false;
  9168. }
  9169. } else if (len == 5 && !strncmp(buf, "false", 5)) {
  9170. if (!parser_putbool(p, false)) {
  9171. return false;
  9172. }
  9173. } else {
  9174. upb_status_seterrmsg(p->status,
  9175. "Map bool key not 'true' or 'false'");
  9176. return false;
  9177. }
  9178. multipart_end(p);
  9179. break;
  9180. case UPB_TYPE_STRING:
  9181. case UPB_TYPE_BYTES: {
  9182. upb_sink subsink;
  9183. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  9184. upb_sink_startstr(p->top->sink, sel, len, &subsink);
  9185. sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
  9186. upb_sink_putstring(subsink, sel, buf, len, NULL);
  9187. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  9188. upb_sink_endstr(subsink, sel);
  9189. multipart_end(p);
  9190. break;
  9191. }
  9192. default:
  9193. upb_status_seterrmsg(p->status, "Invalid field type for map key");
  9194. return false;
  9195. }
  9196. return true;
  9197. }
  9198. /* Helper: emit one map entry (as a submessage in the map field sequence). This
  9199. * is invoked from end_membername(), at the end of the map entry's key string,
  9200. * with the map key in the accumulate buffer. It parses the key from that
  9201. * buffer, emits the handler calls to start the mapentry submessage (setting up
  9202. * its subframe in the process), and sets up state in the subframe so that the
  9203. * value parser (invoked next) will emit the mapentry's value field and then
  9204. * end the mapentry message. */
  9205. static bool handle_mapentry(upb_json_parser *p) {
  9206. const upb_fielddef *mapfield;
  9207. const upb_msgdef *mapentrymsg;
  9208. upb_jsonparser_frame *inner;
  9209. upb_selector_t sel;
  9210. /* Map entry: p->top->sink is the seq frame, so we need to start a frame
  9211. * for the mapentry itself, and then set |f| in that frame so that the map
  9212. * value field is parsed, and also set a flag to end the frame after the
  9213. * map-entry value is parsed. */
  9214. if (!check_stack(p)) return false;
  9215. mapfield = p->top->mapfield;
  9216. mapentrymsg = upb_fielddef_msgsubdef(mapfield);
  9217. inner = start_jsonparser_frame(p);
  9218. p->top->f = mapfield;
  9219. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
  9220. upb_sink_startsubmsg(p->top->sink, sel, &inner->sink);
  9221. inner->m = mapentrymsg;
  9222. inner->mapfield = mapfield;
  9223. /* Don't set this to true *yet* -- we reuse parsing handlers below to push
  9224. * the key field value to the sink, and these handlers will pop the frame
  9225. * if they see is_mapentry (when invoked by the parser state machine, they
  9226. * would have just seen the map-entry value, not key). */
  9227. inner->is_mapentry = false;
  9228. p->top = inner;
  9229. /* send STARTMSG in submsg frame. */
  9230. upb_sink_startmsg(p->top->sink);
  9231. parse_mapentry_key(p);
  9232. /* Set up the value field to receive the map-entry value. */
  9233. p->top->f = upb_msgdef_itof(p->top->m, UPB_MAPENTRY_VALUE);
  9234. p->top->is_mapentry = true; /* set up to pop frame after value is parsed. */
  9235. p->top->mapfield = mapfield;
  9236. if (p->top->f == NULL) {
  9237. upb_status_seterrmsg(p->status, "mapentry message has no value");
  9238. return false;
  9239. }
  9240. return true;
  9241. }
  9242. static bool end_membername(upb_json_parser *p) {
  9243. UPB_ASSERT(!p->top->f);
  9244. if (!p->top->m) {
  9245. p->top->is_unknown_field = true;
  9246. multipart_end(p);
  9247. return true;
  9248. }
  9249. if (p->top->is_any) {
  9250. return end_any_membername(p);
  9251. } else if (p->top->is_map) {
  9252. return handle_mapentry(p);
  9253. } else {
  9254. size_t len;
  9255. const char *buf = accumulate_getptr(p, &len);
  9256. upb_value v;
  9257. if (upb_strtable_lookup2(p->top->name_table, buf, len, &v)) {
  9258. p->top->f = upb_value_getconstptr(v);
  9259. multipart_end(p);
  9260. return true;
  9261. } else if (p->ignore_json_unknown) {
  9262. p->top->is_unknown_field = true;
  9263. multipart_end(p);
  9264. return true;
  9265. } else {
  9266. upb_status_seterrf(p->status, "No such field: %.*s\n", (int)len, buf);
  9267. return false;
  9268. }
  9269. }
  9270. }
  9271. static bool end_any_membername(upb_json_parser *p) {
  9272. size_t len;
  9273. const char *buf = accumulate_getptr(p, &len);
  9274. upb_value v;
  9275. if (len == 5 && strncmp(buf, "@type", len) == 0) {
  9276. upb_strtable_lookup2(p->top->name_table, "type_url", 8, &v);
  9277. p->top->f = upb_value_getconstptr(v);
  9278. multipart_end(p);
  9279. return true;
  9280. } else {
  9281. p->top->is_unknown_field = true;
  9282. multipart_end(p);
  9283. return true;
  9284. }
  9285. }
  9286. static void end_member(upb_json_parser *p) {
  9287. /* If we just parsed a map-entry value, end that frame too. */
  9288. if (p->top->is_mapentry) {
  9289. upb_selector_t sel;
  9290. bool ok;
  9291. const upb_fielddef *mapfield;
  9292. UPB_ASSERT(p->top > p->stack);
  9293. /* send ENDMSG on submsg. */
  9294. upb_sink_endmsg(p->top->sink, p->status);
  9295. mapfield = p->top->mapfield;
  9296. /* send ENDSUBMSG in repeated-field-of-mapentries frame. */
  9297. p->top--;
  9298. ok = upb_handlers_getselector(mapfield, UPB_HANDLER_ENDSUBMSG, &sel);
  9299. UPB_ASSUME(ok);
  9300. upb_sink_endsubmsg(p->top->sink, (p->top + 1)->sink, sel);
  9301. }
  9302. p->top->f = NULL;
  9303. p->top->is_unknown_field = false;
  9304. }
  9305. static void start_any_member(upb_json_parser *p, const char *ptr) {
  9306. start_member(p);
  9307. json_parser_any_frame_set_after_type_url_start_once(p->top->any_frame, ptr);
  9308. }
  9309. static void end_any_member(upb_json_parser *p, const char *ptr) {
  9310. json_parser_any_frame_set_before_type_url_end(p->top->any_frame, ptr);
  9311. end_member(p);
  9312. }
  9313. static bool start_subobject(upb_json_parser *p) {
  9314. if (p->top->is_unknown_field) {
  9315. if (!check_stack(p)) return false;
  9316. p->top = start_jsonparser_frame(p);
  9317. return true;
  9318. }
  9319. if (upb_fielddef_ismap(p->top->f)) {
  9320. upb_jsonparser_frame *inner;
  9321. upb_selector_t sel;
  9322. /* Beginning of a map. Start a new parser frame in a repeated-field
  9323. * context. */
  9324. if (!check_stack(p)) return false;
  9325. inner = start_jsonparser_frame(p);
  9326. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
  9327. upb_sink_startseq(p->top->sink, sel, &inner->sink);
  9328. inner->m = upb_fielddef_msgsubdef(p->top->f);
  9329. inner->mapfield = p->top->f;
  9330. inner->is_map = true;
  9331. p->top = inner;
  9332. return true;
  9333. } else if (upb_fielddef_issubmsg(p->top->f)) {
  9334. upb_jsonparser_frame *inner;
  9335. upb_selector_t sel;
  9336. /* Beginning of a subobject. Start a new parser frame in the submsg
  9337. * context. */
  9338. if (!check_stack(p)) return false;
  9339. inner = start_jsonparser_frame(p);
  9340. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
  9341. upb_sink_startsubmsg(p->top->sink, sel, &inner->sink);
  9342. inner->m = upb_fielddef_msgsubdef(p->top->f);
  9343. set_name_table(p, inner);
  9344. p->top = inner;
  9345. if (is_wellknown_msg(p, UPB_WELLKNOWN_ANY)) {
  9346. p->top->is_any = true;
  9347. p->top->any_frame = json_parser_any_frame_new(p);
  9348. } else {
  9349. p->top->is_any = false;
  9350. p->top->any_frame = NULL;
  9351. }
  9352. return true;
  9353. } else {
  9354. upb_status_seterrf(p->status,
  9355. "Object specified for non-message/group field: %s",
  9356. upb_fielddef_name(p->top->f));
  9357. return false;
  9358. }
  9359. }
  9360. static bool start_subobject_full(upb_json_parser *p) {
  9361. if (is_top_level(p)) {
  9362. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  9363. start_value_object(p, VALUE_STRUCTVALUE);
  9364. if (!start_subobject(p)) return false;
  9365. start_structvalue_object(p);
  9366. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_STRUCT)) {
  9367. start_structvalue_object(p);
  9368. } else {
  9369. return true;
  9370. }
  9371. } else if (is_wellknown_field(p, UPB_WELLKNOWN_STRUCT)) {
  9372. if (!start_subobject(p)) return false;
  9373. start_structvalue_object(p);
  9374. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  9375. if (!start_subobject(p)) return false;
  9376. start_value_object(p, VALUE_STRUCTVALUE);
  9377. if (!start_subobject(p)) return false;
  9378. start_structvalue_object(p);
  9379. }
  9380. return start_subobject(p);
  9381. }
  9382. static void end_subobject(upb_json_parser *p) {
  9383. if (is_top_level(p)) {
  9384. return;
  9385. }
  9386. if (p->top->is_map) {
  9387. upb_selector_t sel;
  9388. p->top--;
  9389. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
  9390. upb_sink_endseq(p->top->sink, sel);
  9391. } else {
  9392. upb_selector_t sel;
  9393. bool is_unknown = p->top->m == NULL;
  9394. p->top--;
  9395. if (!is_unknown) {
  9396. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSUBMSG);
  9397. upb_sink_endsubmsg(p->top->sink, (p->top + 1)->sink, sel);
  9398. }
  9399. }
  9400. }
  9401. static void end_subobject_full(upb_json_parser *p) {
  9402. end_subobject(p);
  9403. if (is_wellknown_msg(p, UPB_WELLKNOWN_STRUCT)) {
  9404. end_structvalue_object(p);
  9405. if (!is_top_level(p)) {
  9406. end_subobject(p);
  9407. }
  9408. }
  9409. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  9410. end_value_object(p);
  9411. if (!is_top_level(p)) {
  9412. end_subobject(p);
  9413. }
  9414. }
  9415. }
  9416. static bool start_array(upb_json_parser *p) {
  9417. upb_jsonparser_frame *inner;
  9418. upb_selector_t sel;
  9419. if (is_top_level(p)) {
  9420. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  9421. start_value_object(p, VALUE_LISTVALUE);
  9422. if (!start_subobject(p)) return false;
  9423. start_listvalue_object(p);
  9424. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_LISTVALUE)) {
  9425. start_listvalue_object(p);
  9426. } else {
  9427. return false;
  9428. }
  9429. } else if (is_wellknown_field(p, UPB_WELLKNOWN_LISTVALUE) &&
  9430. (!upb_fielddef_isseq(p->top->f) ||
  9431. p->top->is_repeated)) {
  9432. if (!start_subobject(p)) return false;
  9433. start_listvalue_object(p);
  9434. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE) &&
  9435. (!upb_fielddef_isseq(p->top->f) ||
  9436. p->top->is_repeated)) {
  9437. if (!start_subobject(p)) return false;
  9438. start_value_object(p, VALUE_LISTVALUE);
  9439. if (!start_subobject(p)) return false;
  9440. start_listvalue_object(p);
  9441. }
  9442. if (p->top->is_unknown_field) {
  9443. inner = start_jsonparser_frame(p);
  9444. inner->is_unknown_field = true;
  9445. p->top = inner;
  9446. return true;
  9447. }
  9448. if (!upb_fielddef_isseq(p->top->f)) {
  9449. upb_status_seterrf(p->status,
  9450. "Array specified for non-repeated field: %s",
  9451. upb_fielddef_name(p->top->f));
  9452. return false;
  9453. }
  9454. if (!check_stack(p)) return false;
  9455. inner = start_jsonparser_frame(p);
  9456. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
  9457. upb_sink_startseq(p->top->sink, sel, &inner->sink);
  9458. inner->m = p->top->m;
  9459. inner->f = p->top->f;
  9460. inner->is_repeated = true;
  9461. p->top = inner;
  9462. return true;
  9463. }
  9464. static void end_array(upb_json_parser *p) {
  9465. upb_selector_t sel;
  9466. UPB_ASSERT(p->top > p->stack);
  9467. p->top--;
  9468. if (p->top->is_unknown_field) {
  9469. return;
  9470. }
  9471. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
  9472. upb_sink_endseq(p->top->sink, sel);
  9473. if (is_wellknown_msg(p, UPB_WELLKNOWN_LISTVALUE)) {
  9474. end_listvalue_object(p);
  9475. if (!is_top_level(p)) {
  9476. end_subobject(p);
  9477. }
  9478. }
  9479. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  9480. end_value_object(p);
  9481. if (!is_top_level(p)) {
  9482. end_subobject(p);
  9483. }
  9484. }
  9485. }
  9486. static void start_object(upb_json_parser *p) {
  9487. if (!p->top->is_map && p->top->m != NULL) {
  9488. upb_sink_startmsg(p->top->sink);
  9489. }
  9490. }
  9491. static void end_object(upb_json_parser *p) {
  9492. if (!p->top->is_map && p->top->m != NULL) {
  9493. upb_sink_endmsg(p->top->sink, p->status);
  9494. }
  9495. }
  9496. static void start_any_object(upb_json_parser *p, const char *ptr) {
  9497. start_object(p);
  9498. p->top->any_frame->before_type_url_start = ptr;
  9499. p->top->any_frame->before_type_url_end = ptr;
  9500. }
  9501. static bool end_any_object(upb_json_parser *p, const char *ptr) {
  9502. const char *value_membername = "value";
  9503. bool is_well_known_packed = false;
  9504. const char *packed_end = ptr + 1;
  9505. upb_selector_t sel;
  9506. upb_jsonparser_frame *inner;
  9507. if (json_parser_any_frame_has_value(p->top->any_frame) &&
  9508. !json_parser_any_frame_has_type_url(p->top->any_frame)) {
  9509. upb_status_seterrmsg(p->status, "No valid type url");
  9510. return false;
  9511. }
  9512. /* Well known types data is represented as value field. */
  9513. if (upb_msgdef_wellknowntype(p->top->any_frame->parser->top->m) !=
  9514. UPB_WELLKNOWN_UNSPECIFIED) {
  9515. is_well_known_packed = true;
  9516. if (json_parser_any_frame_has_value_before_type_url(p->top->any_frame)) {
  9517. p->top->any_frame->before_type_url_start =
  9518. memchr(p->top->any_frame->before_type_url_start, ':',
  9519. p->top->any_frame->before_type_url_end -
  9520. p->top->any_frame->before_type_url_start);
  9521. if (p->top->any_frame->before_type_url_start == NULL) {
  9522. upb_status_seterrmsg(p->status, "invalid data for well known type.");
  9523. return false;
  9524. }
  9525. p->top->any_frame->before_type_url_start++;
  9526. }
  9527. if (json_parser_any_frame_has_value_after_type_url(p->top->any_frame)) {
  9528. p->top->any_frame->after_type_url_start =
  9529. memchr(p->top->any_frame->after_type_url_start, ':',
  9530. (ptr + 1) -
  9531. p->top->any_frame->after_type_url_start);
  9532. if (p->top->any_frame->after_type_url_start == NULL) {
  9533. upb_status_seterrmsg(p->status, "Invalid data for well known type.");
  9534. return false;
  9535. }
  9536. p->top->any_frame->after_type_url_start++;
  9537. packed_end = ptr;
  9538. }
  9539. }
  9540. if (json_parser_any_frame_has_value_before_type_url(p->top->any_frame)) {
  9541. if (!parse(p->top->any_frame->parser, NULL,
  9542. p->top->any_frame->before_type_url_start,
  9543. p->top->any_frame->before_type_url_end -
  9544. p->top->any_frame->before_type_url_start, NULL)) {
  9545. return false;
  9546. }
  9547. } else {
  9548. if (!is_well_known_packed) {
  9549. if (!parse(p->top->any_frame->parser, NULL, "{", 1, NULL)) {
  9550. return false;
  9551. }
  9552. }
  9553. }
  9554. if (json_parser_any_frame_has_value_before_type_url(p->top->any_frame) &&
  9555. json_parser_any_frame_has_value_after_type_url(p->top->any_frame)) {
  9556. if (!parse(p->top->any_frame->parser, NULL, ",", 1, NULL)) {
  9557. return false;
  9558. }
  9559. }
  9560. if (json_parser_any_frame_has_value_after_type_url(p->top->any_frame)) {
  9561. if (!parse(p->top->any_frame->parser, NULL,
  9562. p->top->any_frame->after_type_url_start,
  9563. packed_end - p->top->any_frame->after_type_url_start, NULL)) {
  9564. return false;
  9565. }
  9566. } else {
  9567. if (!is_well_known_packed) {
  9568. if (!parse(p->top->any_frame->parser, NULL, "}", 1, NULL)) {
  9569. return false;
  9570. }
  9571. }
  9572. }
  9573. if (!end(p->top->any_frame->parser, NULL)) {
  9574. return false;
  9575. }
  9576. p->top->is_any = false;
  9577. /* Set value */
  9578. start_member(p);
  9579. capture_begin(p, value_membername);
  9580. capture_end(p, value_membername + 5);
  9581. end_membername(p);
  9582. if (!check_stack(p)) return false;
  9583. inner = p->top + 1;
  9584. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  9585. upb_sink_startstr(p->top->sink, sel, 0, &inner->sink);
  9586. sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
  9587. upb_sink_putstring(inner->sink, sel, p->top->any_frame->stringsink.ptr,
  9588. p->top->any_frame->stringsink.len, NULL);
  9589. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  9590. upb_sink_endstr(inner->sink, sel);
  9591. end_member(p);
  9592. end_object(p);
  9593. /* Deallocate any parse frame. */
  9594. json_parser_any_frame_free(p->top->any_frame);
  9595. return true;
  9596. }
  9597. static bool is_string_wrapper(const upb_msgdef *m) {
  9598. upb_wellknowntype_t type = upb_msgdef_wellknowntype(m);
  9599. return type == UPB_WELLKNOWN_STRINGVALUE ||
  9600. type == UPB_WELLKNOWN_BYTESVALUE;
  9601. }
  9602. static bool is_fieldmask(const upb_msgdef *m) {
  9603. upb_wellknowntype_t type = upb_msgdef_wellknowntype(m);
  9604. return type == UPB_WELLKNOWN_FIELDMASK;
  9605. }
  9606. static void start_fieldmask_object(upb_json_parser *p) {
  9607. const char *membername = "paths";
  9608. start_object(p);
  9609. /* Set up context for parsing value */
  9610. start_member(p);
  9611. capture_begin(p, membername);
  9612. capture_end(p, membername + 5);
  9613. end_membername(p);
  9614. start_array(p);
  9615. }
  9616. static void end_fieldmask_object(upb_json_parser *p) {
  9617. end_array(p);
  9618. end_member(p);
  9619. end_object(p);
  9620. }
  9621. static void start_wrapper_object(upb_json_parser *p) {
  9622. const char *membername = "value";
  9623. start_object(p);
  9624. /* Set up context for parsing value */
  9625. start_member(p);
  9626. capture_begin(p, membername);
  9627. capture_end(p, membername + 5);
  9628. end_membername(p);
  9629. }
  9630. static void end_wrapper_object(upb_json_parser *p) {
  9631. end_member(p);
  9632. end_object(p);
  9633. }
  9634. static void start_value_object(upb_json_parser *p, int value_type) {
  9635. const char *nullmember = "null_value";
  9636. const char *numbermember = "number_value";
  9637. const char *stringmember = "string_value";
  9638. const char *boolmember = "bool_value";
  9639. const char *structmember = "struct_value";
  9640. const char *listmember = "list_value";
  9641. const char *membername = "";
  9642. switch (value_type) {
  9643. case VALUE_NULLVALUE:
  9644. membername = nullmember;
  9645. break;
  9646. case VALUE_NUMBERVALUE:
  9647. membername = numbermember;
  9648. break;
  9649. case VALUE_STRINGVALUE:
  9650. membername = stringmember;
  9651. break;
  9652. case VALUE_BOOLVALUE:
  9653. membername = boolmember;
  9654. break;
  9655. case VALUE_STRUCTVALUE:
  9656. membername = structmember;
  9657. break;
  9658. case VALUE_LISTVALUE:
  9659. membername = listmember;
  9660. break;
  9661. }
  9662. start_object(p);
  9663. /* Set up context for parsing value */
  9664. start_member(p);
  9665. capture_begin(p, membername);
  9666. capture_end(p, membername + strlen(membername));
  9667. end_membername(p);
  9668. }
  9669. static void end_value_object(upb_json_parser *p) {
  9670. end_member(p);
  9671. end_object(p);
  9672. }
  9673. static void start_listvalue_object(upb_json_parser *p) {
  9674. const char *membername = "values";
  9675. start_object(p);
  9676. /* Set up context for parsing value */
  9677. start_member(p);
  9678. capture_begin(p, membername);
  9679. capture_end(p, membername + strlen(membername));
  9680. end_membername(p);
  9681. }
  9682. static void end_listvalue_object(upb_json_parser *p) {
  9683. end_member(p);
  9684. end_object(p);
  9685. }
  9686. static void start_structvalue_object(upb_json_parser *p) {
  9687. const char *membername = "fields";
  9688. start_object(p);
  9689. /* Set up context for parsing value */
  9690. start_member(p);
  9691. capture_begin(p, membername);
  9692. capture_end(p, membername + strlen(membername));
  9693. end_membername(p);
  9694. }
  9695. static void end_structvalue_object(upb_json_parser *p) {
  9696. end_member(p);
  9697. end_object(p);
  9698. }
  9699. static bool is_top_level(upb_json_parser *p) {
  9700. return p->top == p->stack && p->top->f == NULL && !p->top->is_unknown_field;
  9701. }
  9702. static bool is_wellknown_msg(upb_json_parser *p, upb_wellknowntype_t type) {
  9703. return p->top->m != NULL && upb_msgdef_wellknowntype(p->top->m) == type;
  9704. }
  9705. static bool is_wellknown_field(upb_json_parser *p, upb_wellknowntype_t type) {
  9706. return p->top->f != NULL &&
  9707. upb_fielddef_issubmsg(p->top->f) &&
  9708. (upb_msgdef_wellknowntype(upb_fielddef_msgsubdef(p->top->f))
  9709. == type);
  9710. }
  9711. static bool does_number_wrapper_start(upb_json_parser *p) {
  9712. return p->top->f != NULL &&
  9713. upb_fielddef_issubmsg(p->top->f) &&
  9714. upb_msgdef_isnumberwrapper(upb_fielddef_msgsubdef(p->top->f));
  9715. }
  9716. static bool does_number_wrapper_end(upb_json_parser *p) {
  9717. return p->top->m != NULL && upb_msgdef_isnumberwrapper(p->top->m);
  9718. }
  9719. static bool is_number_wrapper_object(upb_json_parser *p) {
  9720. return p->top->m != NULL && upb_msgdef_isnumberwrapper(p->top->m);
  9721. }
  9722. static bool does_string_wrapper_start(upb_json_parser *p) {
  9723. return p->top->f != NULL &&
  9724. upb_fielddef_issubmsg(p->top->f) &&
  9725. is_string_wrapper(upb_fielddef_msgsubdef(p->top->f));
  9726. }
  9727. static bool does_string_wrapper_end(upb_json_parser *p) {
  9728. return p->top->m != NULL && is_string_wrapper(p->top->m);
  9729. }
  9730. static bool is_string_wrapper_object(upb_json_parser *p) {
  9731. return p->top->m != NULL && is_string_wrapper(p->top->m);
  9732. }
  9733. static bool does_fieldmask_start(upb_json_parser *p) {
  9734. return p->top->f != NULL &&
  9735. upb_fielddef_issubmsg(p->top->f) &&
  9736. is_fieldmask(upb_fielddef_msgsubdef(p->top->f));
  9737. }
  9738. static bool does_fieldmask_end(upb_json_parser *p) {
  9739. return p->top->m != NULL && is_fieldmask(p->top->m);
  9740. }
  9741. #define CHECK_RETURN_TOP(x) if (!(x)) goto error
  9742. /* The actual parser **********************************************************/
  9743. /* What follows is the Ragel parser itself. The language is specified in Ragel
  9744. * and the actions call our C functions above.
  9745. *
  9746. * Ragel has an extensive set of functionality, and we use only a small part of
  9747. * it. There are many action types but we only use a few:
  9748. *
  9749. * ">" -- transition into a machine
  9750. * "%" -- transition out of a machine
  9751. * "@" -- transition into a final state of a machine.
  9752. *
  9753. * "@" transitions are tricky because a machine can transition into a final
  9754. * state repeatedly. But in some cases we know this can't happen, for example
  9755. * a string which is delimited by a final '"' can only transition into its
  9756. * final state once, when the closing '"' is seen. */
  9757. #line 2780 "upb/json/parser.rl"
  9758. #line 2583 "upb/json/parser.c"
  9759. static const char _json_actions[] = {
  9760. 0, 1, 0, 1, 1, 1, 3, 1,
  9761. 4, 1, 6, 1, 7, 1, 8, 1,
  9762. 9, 1, 11, 1, 12, 1, 13, 1,
  9763. 14, 1, 15, 1, 16, 1, 17, 1,
  9764. 18, 1, 19, 1, 20, 1, 22, 1,
  9765. 23, 1, 24, 1, 35, 1, 37, 1,
  9766. 39, 1, 40, 1, 42, 1, 43, 1,
  9767. 44, 1, 46, 1, 48, 1, 49, 1,
  9768. 50, 1, 51, 1, 53, 1, 54, 2,
  9769. 4, 9, 2, 5, 6, 2, 7, 3,
  9770. 2, 7, 9, 2, 21, 26, 2, 25,
  9771. 10, 2, 27, 28, 2, 29, 30, 2,
  9772. 32, 34, 2, 33, 31, 2, 38, 36,
  9773. 2, 40, 42, 2, 45, 2, 2, 46,
  9774. 54, 2, 47, 36, 2, 49, 54, 2,
  9775. 50, 54, 2, 51, 54, 2, 52, 41,
  9776. 2, 53, 54, 3, 32, 34, 35, 4,
  9777. 21, 26, 27, 28
  9778. };
  9779. static const short _json_key_offsets[] = {
  9780. 0, 0, 12, 13, 18, 23, 28, 29,
  9781. 30, 31, 32, 33, 34, 35, 36, 37,
  9782. 38, 43, 44, 48, 53, 58, 63, 67,
  9783. 71, 74, 77, 79, 83, 87, 89, 91,
  9784. 96, 98, 100, 109, 115, 121, 127, 133,
  9785. 135, 139, 142, 144, 146, 149, 150, 154,
  9786. 156, 158, 160, 162, 163, 165, 167, 168,
  9787. 170, 172, 173, 175, 177, 178, 180, 182,
  9788. 183, 185, 187, 191, 193, 195, 196, 197,
  9789. 198, 199, 201, 206, 208, 210, 212, 221,
  9790. 222, 222, 222, 227, 232, 237, 238, 239,
  9791. 240, 241, 241, 242, 243, 244, 244, 245,
  9792. 246, 247, 247, 252, 253, 257, 262, 267,
  9793. 272, 276, 276, 279, 282, 285, 288, 291,
  9794. 294, 294, 294, 294, 294, 294
  9795. };
  9796. static const char _json_trans_keys[] = {
  9797. 32, 34, 45, 91, 102, 110, 116, 123,
  9798. 9, 13, 48, 57, 34, 32, 93, 125,
  9799. 9, 13, 32, 44, 93, 9, 13, 32,
  9800. 93, 125, 9, 13, 97, 108, 115, 101,
  9801. 117, 108, 108, 114, 117, 101, 32, 34,
  9802. 125, 9, 13, 34, 32, 58, 9, 13,
  9803. 32, 93, 125, 9, 13, 32, 44, 125,
  9804. 9, 13, 32, 44, 125, 9, 13, 32,
  9805. 34, 9, 13, 45, 48, 49, 57, 48,
  9806. 49, 57, 46, 69, 101, 48, 57, 69,
  9807. 101, 48, 57, 43, 45, 48, 57, 48,
  9808. 57, 48, 57, 46, 69, 101, 48, 57,
  9809. 34, 92, 34, 92, 34, 47, 92, 98,
  9810. 102, 110, 114, 116, 117, 48, 57, 65,
  9811. 70, 97, 102, 48, 57, 65, 70, 97,
  9812. 102, 48, 57, 65, 70, 97, 102, 48,
  9813. 57, 65, 70, 97, 102, 34, 92, 45,
  9814. 48, 49, 57, 48, 49, 57, 46, 115,
  9815. 48, 57, 115, 48, 57, 34, 46, 115,
  9816. 48, 57, 48, 57, 48, 57, 48, 57,
  9817. 48, 57, 45, 48, 57, 48, 57, 45,
  9818. 48, 57, 48, 57, 84, 48, 57, 48,
  9819. 57, 58, 48, 57, 48, 57, 58, 48,
  9820. 57, 48, 57, 43, 45, 46, 90, 48,
  9821. 57, 48, 57, 58, 48, 48, 34, 48,
  9822. 57, 43, 45, 90, 48, 57, 34, 44,
  9823. 34, 44, 34, 44, 34, 45, 91, 102,
  9824. 110, 116, 123, 48, 57, 34, 32, 93,
  9825. 125, 9, 13, 32, 44, 93, 9, 13,
  9826. 32, 93, 125, 9, 13, 97, 108, 115,
  9827. 101, 117, 108, 108, 114, 117, 101, 32,
  9828. 34, 125, 9, 13, 34, 32, 58, 9,
  9829. 13, 32, 93, 125, 9, 13, 32, 44,
  9830. 125, 9, 13, 32, 44, 125, 9, 13,
  9831. 32, 34, 9, 13, 32, 9, 13, 32,
  9832. 9, 13, 32, 9, 13, 32, 9, 13,
  9833. 32, 9, 13, 32, 9, 13, 0
  9834. };
  9835. static const char _json_single_lengths[] = {
  9836. 0, 8, 1, 3, 3, 3, 1, 1,
  9837. 1, 1, 1, 1, 1, 1, 1, 1,
  9838. 3, 1, 2, 3, 3, 3, 2, 2,
  9839. 1, 3, 0, 2, 2, 0, 0, 3,
  9840. 2, 2, 9, 0, 0, 0, 0, 2,
  9841. 2, 1, 2, 0, 1, 1, 2, 0,
  9842. 0, 0, 0, 1, 0, 0, 1, 0,
  9843. 0, 1, 0, 0, 1, 0, 0, 1,
  9844. 0, 0, 4, 0, 0, 1, 1, 1,
  9845. 1, 0, 3, 2, 2, 2, 7, 1,
  9846. 0, 0, 3, 3, 3, 1, 1, 1,
  9847. 1, 0, 1, 1, 1, 0, 1, 1,
  9848. 1, 0, 3, 1, 2, 3, 3, 3,
  9849. 2, 0, 1, 1, 1, 1, 1, 1,
  9850. 0, 0, 0, 0, 0, 0
  9851. };
  9852. static const char _json_range_lengths[] = {
  9853. 0, 2, 0, 1, 1, 1, 0, 0,
  9854. 0, 0, 0, 0, 0, 0, 0, 0,
  9855. 1, 0, 1, 1, 1, 1, 1, 1,
  9856. 1, 0, 1, 1, 1, 1, 1, 1,
  9857. 0, 0, 0, 3, 3, 3, 3, 0,
  9858. 1, 1, 0, 1, 1, 0, 1, 1,
  9859. 1, 1, 1, 0, 1, 1, 0, 1,
  9860. 1, 0, 1, 1, 0, 1, 1, 0,
  9861. 1, 1, 0, 1, 1, 0, 0, 0,
  9862. 0, 1, 1, 0, 0, 0, 1, 0,
  9863. 0, 0, 1, 1, 1, 0, 0, 0,
  9864. 0, 0, 0, 0, 0, 0, 0, 0,
  9865. 0, 0, 1, 0, 1, 1, 1, 1,
  9866. 1, 0, 1, 1, 1, 1, 1, 1,
  9867. 0, 0, 0, 0, 0, 0
  9868. };
  9869. static const short _json_index_offsets[] = {
  9870. 0, 0, 11, 13, 18, 23, 28, 30,
  9871. 32, 34, 36, 38, 40, 42, 44, 46,
  9872. 48, 53, 55, 59, 64, 69, 74, 78,
  9873. 82, 85, 89, 91, 95, 99, 101, 103,
  9874. 108, 111, 114, 124, 128, 132, 136, 140,
  9875. 143, 147, 150, 153, 155, 158, 160, 164,
  9876. 166, 168, 170, 172, 174, 176, 178, 180,
  9877. 182, 184, 186, 188, 190, 192, 194, 196,
  9878. 198, 200, 202, 207, 209, 211, 213, 215,
  9879. 217, 219, 221, 226, 229, 232, 235, 244,
  9880. 246, 247, 248, 253, 258, 263, 265, 267,
  9881. 269, 271, 272, 274, 276, 278, 279, 281,
  9882. 283, 285, 286, 291, 293, 297, 302, 307,
  9883. 312, 316, 317, 320, 323, 326, 329, 332,
  9884. 335, 336, 337, 338, 339, 340
  9885. };
  9886. static const unsigned char _json_indicies[] = {
  9887. 0, 2, 3, 4, 5, 6, 7, 8,
  9888. 0, 3, 1, 9, 1, 11, 12, 1,
  9889. 11, 10, 13, 14, 12, 13, 1, 14,
  9890. 1, 1, 14, 10, 15, 1, 16, 1,
  9891. 17, 1, 18, 1, 19, 1, 20, 1,
  9892. 21, 1, 22, 1, 23, 1, 24, 1,
  9893. 25, 26, 27, 25, 1, 28, 1, 29,
  9894. 30, 29, 1, 30, 1, 1, 30, 31,
  9895. 32, 33, 34, 32, 1, 35, 36, 27,
  9896. 35, 1, 36, 26, 36, 1, 37, 38,
  9897. 39, 1, 38, 39, 1, 41, 42, 42,
  9898. 40, 43, 1, 42, 42, 43, 40, 44,
  9899. 44, 45, 1, 45, 1, 45, 40, 41,
  9900. 42, 42, 39, 40, 47, 48, 46, 50,
  9901. 51, 49, 52, 52, 52, 52, 52, 52,
  9902. 52, 52, 53, 1, 54, 54, 54, 1,
  9903. 55, 55, 55, 1, 56, 56, 56, 1,
  9904. 57, 57, 57, 1, 59, 60, 58, 61,
  9905. 62, 63, 1, 64, 65, 1, 66, 67,
  9906. 1, 68, 1, 67, 68, 1, 69, 1,
  9907. 66, 67, 65, 1, 70, 1, 71, 1,
  9908. 72, 1, 73, 1, 74, 1, 75, 1,
  9909. 76, 1, 77, 1, 78, 1, 79, 1,
  9910. 80, 1, 81, 1, 82, 1, 83, 1,
  9911. 84, 1, 85, 1, 86, 1, 87, 1,
  9912. 88, 1, 89, 89, 90, 91, 1, 92,
  9913. 1, 93, 1, 94, 1, 95, 1, 96,
  9914. 1, 97, 1, 98, 1, 99, 99, 100,
  9915. 98, 1, 102, 1, 101, 104, 105, 103,
  9916. 1, 1, 101, 106, 107, 108, 109, 110,
  9917. 111, 112, 107, 1, 113, 1, 114, 115,
  9918. 117, 118, 1, 117, 116, 119, 120, 118,
  9919. 119, 1, 120, 1, 1, 120, 116, 121,
  9920. 1, 122, 1, 123, 1, 124, 1, 125,
  9921. 126, 1, 127, 1, 128, 1, 129, 130,
  9922. 1, 131, 1, 132, 1, 133, 134, 135,
  9923. 136, 134, 1, 137, 1, 138, 139, 138,
  9924. 1, 139, 1, 1, 139, 140, 141, 142,
  9925. 143, 141, 1, 144, 145, 136, 144, 1,
  9926. 145, 135, 145, 1, 146, 147, 147, 1,
  9927. 148, 148, 1, 149, 149, 1, 150, 150,
  9928. 1, 151, 151, 1, 152, 152, 1, 1,
  9929. 1, 1, 1, 1, 1, 0
  9930. };
  9931. static const char _json_trans_targs[] = {
  9932. 1, 0, 2, 107, 3, 6, 10, 13,
  9933. 16, 106, 4, 3, 106, 4, 5, 7,
  9934. 8, 9, 108, 11, 12, 109, 14, 15,
  9935. 110, 16, 17, 111, 18, 18, 19, 20,
  9936. 21, 22, 111, 21, 22, 24, 25, 31,
  9937. 112, 26, 28, 27, 29, 30, 33, 113,
  9938. 34, 33, 113, 34, 32, 35, 36, 37,
  9939. 38, 39, 33, 113, 34, 41, 42, 46,
  9940. 42, 46, 43, 45, 44, 114, 48, 49,
  9941. 50, 51, 52, 53, 54, 55, 56, 57,
  9942. 58, 59, 60, 61, 62, 63, 64, 65,
  9943. 66, 67, 73, 72, 68, 69, 70, 71,
  9944. 72, 115, 74, 67, 72, 76, 116, 76,
  9945. 116, 77, 79, 81, 82, 85, 90, 94,
  9946. 98, 80, 117, 117, 83, 82, 80, 83,
  9947. 84, 86, 87, 88, 89, 117, 91, 92,
  9948. 93, 117, 95, 96, 97, 117, 98, 99,
  9949. 105, 100, 100, 101, 102, 103, 104, 105,
  9950. 103, 104, 117, 106, 106, 106, 106, 106,
  9951. 106
  9952. };
  9953. static const unsigned char _json_trans_actions[] = {
  9954. 0, 0, 113, 107, 53, 0, 0, 0,
  9955. 125, 59, 45, 0, 55, 0, 0, 0,
  9956. 0, 0, 0, 0, 0, 0, 0, 0,
  9957. 0, 0, 101, 51, 47, 0, 0, 45,
  9958. 49, 49, 104, 0, 0, 0, 0, 0,
  9959. 3, 0, 0, 0, 0, 0, 5, 15,
  9960. 0, 0, 71, 7, 13, 0, 74, 9,
  9961. 9, 9, 77, 80, 11, 37, 37, 37,
  9962. 0, 0, 0, 39, 0, 41, 86, 0,
  9963. 0, 0, 17, 19, 0, 21, 23, 0,
  9964. 25, 27, 0, 29, 31, 0, 33, 35,
  9965. 0, 135, 83, 135, 0, 0, 0, 0,
  9966. 0, 92, 0, 89, 89, 98, 43, 0,
  9967. 131, 95, 113, 107, 53, 0, 0, 0,
  9968. 125, 59, 69, 110, 45, 0, 55, 0,
  9969. 0, 0, 0, 0, 0, 119, 0, 0,
  9970. 0, 122, 0, 0, 0, 116, 0, 101,
  9971. 51, 47, 0, 0, 45, 49, 49, 104,
  9972. 0, 0, 128, 0, 57, 63, 65, 61,
  9973. 67
  9974. };
  9975. static const unsigned char _json_eof_actions[] = {
  9976. 0, 0, 0, 0, 0, 0, 0, 0,
  9977. 0, 0, 0, 0, 0, 0, 0, 0,
  9978. 0, 0, 0, 0, 0, 0, 0, 0,
  9979. 0, 1, 0, 1, 0, 0, 1, 1,
  9980. 0, 0, 0, 0, 0, 0, 0, 0,
  9981. 0, 0, 0, 0, 0, 0, 0, 0,
  9982. 0, 0, 0, 0, 0, 0, 0, 0,
  9983. 0, 0, 0, 0, 0, 0, 0, 0,
  9984. 0, 0, 0, 0, 0, 0, 0, 0,
  9985. 0, 0, 0, 0, 0, 0, 0, 0,
  9986. 0, 0, 0, 0, 0, 0, 0, 0,
  9987. 0, 0, 0, 0, 0, 0, 0, 0,
  9988. 0, 0, 0, 0, 0, 0, 0, 0,
  9989. 0, 0, 0, 57, 63, 65, 61, 67,
  9990. 0, 0, 0, 0, 0, 0
  9991. };
  9992. static const int json_start = 1;
  9993. static const int json_en_number_machine = 23;
  9994. static const int json_en_string_machine = 32;
  9995. static const int json_en_duration_machine = 40;
  9996. static const int json_en_timestamp_machine = 47;
  9997. static const int json_en_fieldmask_machine = 75;
  9998. static const int json_en_value_machine = 78;
  9999. static const int json_en_main = 1;
  10000. #line 2783 "upb/json/parser.rl"
  10001. size_t parse(void *closure, const void *hd, const char *buf, size_t size,
  10002. const upb_bufhandle *handle) {
  10003. upb_json_parser *parser = closure;
  10004. /* Variables used by Ragel's generated code. */
  10005. int cs = parser->current_state;
  10006. int *stack = parser->parser_stack;
  10007. int top = parser->parser_top;
  10008. const char *p = buf;
  10009. const char *pe = buf + size;
  10010. const char *eof = &eof_ch;
  10011. parser->handle = handle;
  10012. UPB_UNUSED(hd);
  10013. UPB_UNUSED(handle);
  10014. capture_resume(parser, buf);
  10015. #line 2861 "upb/json/parser.c"
  10016. {
  10017. int _klen;
  10018. unsigned int _trans;
  10019. const char *_acts;
  10020. unsigned int _nacts;
  10021. const char *_keys;
  10022. if ( p == pe )
  10023. goto _test_eof;
  10024. if ( cs == 0 )
  10025. goto _out;
  10026. _resume:
  10027. _keys = _json_trans_keys + _json_key_offsets[cs];
  10028. _trans = _json_index_offsets[cs];
  10029. _klen = _json_single_lengths[cs];
  10030. if ( _klen > 0 ) {
  10031. const char *_lower = _keys;
  10032. const char *_mid;
  10033. const char *_upper = _keys + _klen - 1;
  10034. while (1) {
  10035. if ( _upper < _lower )
  10036. break;
  10037. _mid = _lower + ((_upper-_lower) >> 1);
  10038. if ( (*p) < *_mid )
  10039. _upper = _mid - 1;
  10040. else if ( (*p) > *_mid )
  10041. _lower = _mid + 1;
  10042. else {
  10043. _trans += (unsigned int)(_mid - _keys);
  10044. goto _match;
  10045. }
  10046. }
  10047. _keys += _klen;
  10048. _trans += _klen;
  10049. }
  10050. _klen = _json_range_lengths[cs];
  10051. if ( _klen > 0 ) {
  10052. const char *_lower = _keys;
  10053. const char *_mid;
  10054. const char *_upper = _keys + (_klen<<1) - 2;
  10055. while (1) {
  10056. if ( _upper < _lower )
  10057. break;
  10058. _mid = _lower + (((_upper-_lower) >> 1) & ~1);
  10059. if ( (*p) < _mid[0] )
  10060. _upper = _mid - 2;
  10061. else if ( (*p) > _mid[1] )
  10062. _lower = _mid + 2;
  10063. else {
  10064. _trans += (unsigned int)((_mid - _keys)>>1);
  10065. goto _match;
  10066. }
  10067. }
  10068. _trans += _klen;
  10069. }
  10070. _match:
  10071. _trans = _json_indicies[_trans];
  10072. cs = _json_trans_targs[_trans];
  10073. if ( _json_trans_actions[_trans] == 0 )
  10074. goto _again;
  10075. _acts = _json_actions + _json_trans_actions[_trans];
  10076. _nacts = (unsigned int) *_acts++;
  10077. while ( _nacts-- > 0 )
  10078. {
  10079. switch ( *_acts++ )
  10080. {
  10081. case 1:
  10082. #line 2588 "upb/json/parser.rl"
  10083. { p--; {cs = stack[--top]; goto _again;} }
  10084. break;
  10085. case 2:
  10086. #line 2590 "upb/json/parser.rl"
  10087. { p--; {stack[top++] = cs; cs = 23;goto _again;} }
  10088. break;
  10089. case 3:
  10090. #line 2594 "upb/json/parser.rl"
  10091. { start_text(parser, p); }
  10092. break;
  10093. case 4:
  10094. #line 2595 "upb/json/parser.rl"
  10095. { CHECK_RETURN_TOP(end_text(parser, p)); }
  10096. break;
  10097. case 5:
  10098. #line 2601 "upb/json/parser.rl"
  10099. { start_hex(parser); }
  10100. break;
  10101. case 6:
  10102. #line 2602 "upb/json/parser.rl"
  10103. { hexdigit(parser, p); }
  10104. break;
  10105. case 7:
  10106. #line 2603 "upb/json/parser.rl"
  10107. { CHECK_RETURN_TOP(end_hex(parser)); }
  10108. break;
  10109. case 8:
  10110. #line 2609 "upb/json/parser.rl"
  10111. { CHECK_RETURN_TOP(escape(parser, p)); }
  10112. break;
  10113. case 9:
  10114. #line 2615 "upb/json/parser.rl"
  10115. { p--; {cs = stack[--top]; goto _again;} }
  10116. break;
  10117. case 10:
  10118. #line 2620 "upb/json/parser.rl"
  10119. { start_year(parser, p); }
  10120. break;
  10121. case 11:
  10122. #line 2621 "upb/json/parser.rl"
  10123. { CHECK_RETURN_TOP(end_year(parser, p)); }
  10124. break;
  10125. case 12:
  10126. #line 2625 "upb/json/parser.rl"
  10127. { start_month(parser, p); }
  10128. break;
  10129. case 13:
  10130. #line 2626 "upb/json/parser.rl"
  10131. { CHECK_RETURN_TOP(end_month(parser, p)); }
  10132. break;
  10133. case 14:
  10134. #line 2630 "upb/json/parser.rl"
  10135. { start_day(parser, p); }
  10136. break;
  10137. case 15:
  10138. #line 2631 "upb/json/parser.rl"
  10139. { CHECK_RETURN_TOP(end_day(parser, p)); }
  10140. break;
  10141. case 16:
  10142. #line 2635 "upb/json/parser.rl"
  10143. { start_hour(parser, p); }
  10144. break;
  10145. case 17:
  10146. #line 2636 "upb/json/parser.rl"
  10147. { CHECK_RETURN_TOP(end_hour(parser, p)); }
  10148. break;
  10149. case 18:
  10150. #line 2640 "upb/json/parser.rl"
  10151. { start_minute(parser, p); }
  10152. break;
  10153. case 19:
  10154. #line 2641 "upb/json/parser.rl"
  10155. { CHECK_RETURN_TOP(end_minute(parser, p)); }
  10156. break;
  10157. case 20:
  10158. #line 2645 "upb/json/parser.rl"
  10159. { start_second(parser, p); }
  10160. break;
  10161. case 21:
  10162. #line 2646 "upb/json/parser.rl"
  10163. { CHECK_RETURN_TOP(end_second(parser, p)); }
  10164. break;
  10165. case 22:
  10166. #line 2651 "upb/json/parser.rl"
  10167. { start_duration_base(parser, p); }
  10168. break;
  10169. case 23:
  10170. #line 2652 "upb/json/parser.rl"
  10171. { CHECK_RETURN_TOP(end_duration_base(parser, p)); }
  10172. break;
  10173. case 24:
  10174. #line 2654 "upb/json/parser.rl"
  10175. { p--; {cs = stack[--top]; goto _again;} }
  10176. break;
  10177. case 25:
  10178. #line 2659 "upb/json/parser.rl"
  10179. { start_timestamp_base(parser); }
  10180. break;
  10181. case 26:
  10182. #line 2661 "upb/json/parser.rl"
  10183. { start_timestamp_fraction(parser, p); }
  10184. break;
  10185. case 27:
  10186. #line 2662 "upb/json/parser.rl"
  10187. { CHECK_RETURN_TOP(end_timestamp_fraction(parser, p)); }
  10188. break;
  10189. case 28:
  10190. #line 2664 "upb/json/parser.rl"
  10191. { start_timestamp_zone(parser, p); }
  10192. break;
  10193. case 29:
  10194. #line 2665 "upb/json/parser.rl"
  10195. { CHECK_RETURN_TOP(end_timestamp_zone(parser, p)); }
  10196. break;
  10197. case 30:
  10198. #line 2667 "upb/json/parser.rl"
  10199. { p--; {cs = stack[--top]; goto _again;} }
  10200. break;
  10201. case 31:
  10202. #line 2672 "upb/json/parser.rl"
  10203. { start_fieldmask_path_text(parser, p); }
  10204. break;
  10205. case 32:
  10206. #line 2673 "upb/json/parser.rl"
  10207. { end_fieldmask_path_text(parser, p); }
  10208. break;
  10209. case 33:
  10210. #line 2678 "upb/json/parser.rl"
  10211. { start_fieldmask_path(parser); }
  10212. break;
  10213. case 34:
  10214. #line 2679 "upb/json/parser.rl"
  10215. { end_fieldmask_path(parser); }
  10216. break;
  10217. case 35:
  10218. #line 2685 "upb/json/parser.rl"
  10219. { p--; {cs = stack[--top]; goto _again;} }
  10220. break;
  10221. case 36:
  10222. #line 2690 "upb/json/parser.rl"
  10223. {
  10224. if (is_wellknown_msg(parser, UPB_WELLKNOWN_TIMESTAMP)) {
  10225. {stack[top++] = cs; cs = 47;goto _again;}
  10226. } else if (is_wellknown_msg(parser, UPB_WELLKNOWN_DURATION)) {
  10227. {stack[top++] = cs; cs = 40;goto _again;}
  10228. } else if (is_wellknown_msg(parser, UPB_WELLKNOWN_FIELDMASK)) {
  10229. {stack[top++] = cs; cs = 75;goto _again;}
  10230. } else {
  10231. {stack[top++] = cs; cs = 32;goto _again;}
  10232. }
  10233. }
  10234. break;
  10235. case 37:
  10236. #line 2703 "upb/json/parser.rl"
  10237. { p--; {stack[top++] = cs; cs = 78;goto _again;} }
  10238. break;
  10239. case 38:
  10240. #line 2708 "upb/json/parser.rl"
  10241. {
  10242. if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
  10243. start_any_member(parser, p);
  10244. } else {
  10245. start_member(parser);
  10246. }
  10247. }
  10248. break;
  10249. case 39:
  10250. #line 2715 "upb/json/parser.rl"
  10251. { CHECK_RETURN_TOP(end_membername(parser)); }
  10252. break;
  10253. case 40:
  10254. #line 2718 "upb/json/parser.rl"
  10255. {
  10256. if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
  10257. end_any_member(parser, p);
  10258. } else {
  10259. end_member(parser);
  10260. }
  10261. }
  10262. break;
  10263. case 41:
  10264. #line 2729 "upb/json/parser.rl"
  10265. {
  10266. if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
  10267. start_any_object(parser, p);
  10268. } else {
  10269. start_object(parser);
  10270. }
  10271. }
  10272. break;
  10273. case 42:
  10274. #line 2738 "upb/json/parser.rl"
  10275. {
  10276. if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
  10277. CHECK_RETURN_TOP(end_any_object(parser, p));
  10278. } else {
  10279. end_object(parser);
  10280. }
  10281. }
  10282. break;
  10283. case 43:
  10284. #line 2750 "upb/json/parser.rl"
  10285. { CHECK_RETURN_TOP(start_array(parser)); }
  10286. break;
  10287. case 44:
  10288. #line 2754 "upb/json/parser.rl"
  10289. { end_array(parser); }
  10290. break;
  10291. case 45:
  10292. #line 2759 "upb/json/parser.rl"
  10293. { CHECK_RETURN_TOP(start_number(parser, p)); }
  10294. break;
  10295. case 46:
  10296. #line 2760 "upb/json/parser.rl"
  10297. { CHECK_RETURN_TOP(end_number(parser, p)); }
  10298. break;
  10299. case 47:
  10300. #line 2762 "upb/json/parser.rl"
  10301. { CHECK_RETURN_TOP(start_stringval(parser)); }
  10302. break;
  10303. case 48:
  10304. #line 2763 "upb/json/parser.rl"
  10305. { CHECK_RETURN_TOP(end_stringval(parser)); }
  10306. break;
  10307. case 49:
  10308. #line 2765 "upb/json/parser.rl"
  10309. { CHECK_RETURN_TOP(end_bool(parser, true)); }
  10310. break;
  10311. case 50:
  10312. #line 2767 "upb/json/parser.rl"
  10313. { CHECK_RETURN_TOP(end_bool(parser, false)); }
  10314. break;
  10315. case 51:
  10316. #line 2769 "upb/json/parser.rl"
  10317. { CHECK_RETURN_TOP(end_null(parser)); }
  10318. break;
  10319. case 52:
  10320. #line 2771 "upb/json/parser.rl"
  10321. { CHECK_RETURN_TOP(start_subobject_full(parser)); }
  10322. break;
  10323. case 53:
  10324. #line 2772 "upb/json/parser.rl"
  10325. { end_subobject_full(parser); }
  10326. break;
  10327. case 54:
  10328. #line 2777 "upb/json/parser.rl"
  10329. { p--; {cs = stack[--top]; goto _again;} }
  10330. break;
  10331. #line 3185 "upb/json/parser.c"
  10332. }
  10333. }
  10334. _again:
  10335. if ( cs == 0 )
  10336. goto _out;
  10337. if ( ++p != pe )
  10338. goto _resume;
  10339. _test_eof: {}
  10340. if ( p == eof )
  10341. {
  10342. const char *__acts = _json_actions + _json_eof_actions[cs];
  10343. unsigned int __nacts = (unsigned int) *__acts++;
  10344. while ( __nacts-- > 0 ) {
  10345. switch ( *__acts++ ) {
  10346. case 0:
  10347. #line 2586 "upb/json/parser.rl"
  10348. { p--; {cs = stack[--top]; if ( p == pe )
  10349. goto _test_eof;
  10350. goto _again;} }
  10351. break;
  10352. case 46:
  10353. #line 2760 "upb/json/parser.rl"
  10354. { CHECK_RETURN_TOP(end_number(parser, p)); }
  10355. break;
  10356. case 49:
  10357. #line 2765 "upb/json/parser.rl"
  10358. { CHECK_RETURN_TOP(end_bool(parser, true)); }
  10359. break;
  10360. case 50:
  10361. #line 2767 "upb/json/parser.rl"
  10362. { CHECK_RETURN_TOP(end_bool(parser, false)); }
  10363. break;
  10364. case 51:
  10365. #line 2769 "upb/json/parser.rl"
  10366. { CHECK_RETURN_TOP(end_null(parser)); }
  10367. break;
  10368. case 53:
  10369. #line 2772 "upb/json/parser.rl"
  10370. { end_subobject_full(parser); }
  10371. break;
  10372. #line 3227 "upb/json/parser.c"
  10373. }
  10374. }
  10375. }
  10376. _out: {}
  10377. }
  10378. #line 2805 "upb/json/parser.rl"
  10379. if (p != pe) {
  10380. upb_status_seterrf(parser->status, "Parse error at '%.*s'\n", pe - p, p);
  10381. } else {
  10382. capture_suspend(parser, &p);
  10383. }
  10384. error:
  10385. /* Save parsing state back to parser. */
  10386. parser->current_state = cs;
  10387. parser->parser_top = top;
  10388. return p - buf;
  10389. }
  10390. static bool end(void *closure, const void *hd) {
  10391. upb_json_parser *parser = closure;
  10392. /* Prevent compile warning on unused static constants. */
  10393. UPB_UNUSED(json_start);
  10394. UPB_UNUSED(json_en_duration_machine);
  10395. UPB_UNUSED(json_en_fieldmask_machine);
  10396. UPB_UNUSED(json_en_number_machine);
  10397. UPB_UNUSED(json_en_string_machine);
  10398. UPB_UNUSED(json_en_timestamp_machine);
  10399. UPB_UNUSED(json_en_value_machine);
  10400. UPB_UNUSED(json_en_main);
  10401. parse(parser, hd, &eof_ch, 0, NULL);
  10402. return parser->current_state >= 106;
  10403. }
  10404. static void json_parser_reset(upb_json_parser *p) {
  10405. int cs;
  10406. int top;
  10407. p->top = p->stack;
  10408. init_frame(p->top);
  10409. /* Emit Ragel initialization of the parser. */
  10410. #line 3278 "upb/json/parser.c"
  10411. {
  10412. cs = json_start;
  10413. top = 0;
  10414. }
  10415. #line 2847 "upb/json/parser.rl"
  10416. p->current_state = cs;
  10417. p->parser_top = top;
  10418. accumulate_clear(p);
  10419. p->multipart_state = MULTIPART_INACTIVE;
  10420. p->capture = NULL;
  10421. p->accumulated = NULL;
  10422. }
  10423. static upb_json_parsermethod *parsermethod_new(upb_json_codecache *c,
  10424. const upb_msgdef *md) {
  10425. upb_msg_field_iter i;
  10426. upb_alloc *alloc = upb_arena_alloc(c->arena);
  10427. upb_json_parsermethod *m = upb_malloc(alloc, sizeof(*m));
  10428. m->cache = c;
  10429. upb_byteshandler_init(&m->input_handler_);
  10430. upb_byteshandler_setstring(&m->input_handler_, parse, m);
  10431. upb_byteshandler_setendstr(&m->input_handler_, end, m);
  10432. upb_strtable_init2(&m->name_table, UPB_CTYPE_CONSTPTR, alloc);
  10433. /* Build name_table */
  10434. for(upb_msg_field_begin(&i, md);
  10435. !upb_msg_field_done(&i);
  10436. upb_msg_field_next(&i)) {
  10437. const upb_fielddef *f = upb_msg_iter_field(&i);
  10438. upb_value v = upb_value_constptr(f);
  10439. const char *name;
  10440. /* Add an entry for the JSON name. */
  10441. name = upb_fielddef_jsonname(f);
  10442. upb_strtable_insert3(&m->name_table, name, strlen(name), v, alloc);
  10443. if (strcmp(name, upb_fielddef_name(f)) != 0) {
  10444. /* Since the JSON name is different from the regular field name, add an
  10445. * entry for the raw name (compliant proto3 JSON parsers must accept
  10446. * both). */
  10447. const char *name = upb_fielddef_name(f);
  10448. upb_strtable_insert3(&m->name_table, name, strlen(name), v, alloc);
  10449. }
  10450. }
  10451. return m;
  10452. }
  10453. /* Public API *****************************************************************/
  10454. upb_json_parser *upb_json_parser_create(upb_arena *arena,
  10455. const upb_json_parsermethod *method,
  10456. const upb_symtab* symtab,
  10457. upb_sink output,
  10458. upb_status *status,
  10459. bool ignore_json_unknown) {
  10460. #ifndef NDEBUG
  10461. const size_t size_before = upb_arena_bytesallocated(arena);
  10462. #endif
  10463. upb_json_parser *p = upb_arena_malloc(arena, sizeof(upb_json_parser));
  10464. if (!p) return false;
  10465. p->arena = arena;
  10466. p->method = method;
  10467. p->status = status;
  10468. p->limit = p->stack + UPB_JSON_MAX_DEPTH;
  10469. p->accumulate_buf = NULL;
  10470. p->accumulate_buf_size = 0;
  10471. upb_bytessink_reset(&p->input_, &method->input_handler_, p);
  10472. json_parser_reset(p);
  10473. p->top->sink = output;
  10474. p->top->m = upb_handlers_msgdef(output.handlers);
  10475. if (is_wellknown_msg(p, UPB_WELLKNOWN_ANY)) {
  10476. p->top->is_any = true;
  10477. p->top->any_frame = json_parser_any_frame_new(p);
  10478. } else {
  10479. p->top->is_any = false;
  10480. p->top->any_frame = NULL;
  10481. }
  10482. set_name_table(p, p->top);
  10483. p->symtab = symtab;
  10484. p->ignore_json_unknown = ignore_json_unknown;
  10485. /* If this fails, uncomment and increase the value in parser.h. */
  10486. /* fprintf(stderr, "%zd\n", upb_arena_bytesallocated(arena) - size_before); */
  10487. UPB_ASSERT_DEBUGVAR(upb_arena_bytesallocated(arena) - size_before <=
  10488. UPB_JSON_PARSER_SIZE);
  10489. return p;
  10490. }
  10491. upb_bytessink upb_json_parser_input(upb_json_parser *p) {
  10492. return p->input_;
  10493. }
  10494. const upb_byteshandler *upb_json_parsermethod_inputhandler(
  10495. const upb_json_parsermethod *m) {
  10496. return &m->input_handler_;
  10497. }
  10498. upb_json_codecache *upb_json_codecache_new(void) {
  10499. upb_alloc *alloc;
  10500. upb_json_codecache *c;
  10501. c = upb_gmalloc(sizeof(*c));
  10502. c->arena = upb_arena_new();
  10503. alloc = upb_arena_alloc(c->arena);
  10504. upb_inttable_init2(&c->methods, UPB_CTYPE_CONSTPTR, alloc);
  10505. return c;
  10506. }
  10507. void upb_json_codecache_free(upb_json_codecache *c) {
  10508. upb_arena_free(c->arena);
  10509. upb_gfree(c);
  10510. }
  10511. const upb_json_parsermethod *upb_json_codecache_get(upb_json_codecache *c,
  10512. const upb_msgdef *md) {
  10513. upb_json_parsermethod *m;
  10514. upb_value v;
  10515. upb_msg_field_iter i;
  10516. upb_alloc *alloc = upb_arena_alloc(c->arena);
  10517. if (upb_inttable_lookupptr(&c->methods, md, &v)) {
  10518. return upb_value_getconstptr(v);
  10519. }
  10520. m = parsermethod_new(c, md);
  10521. v = upb_value_constptr(m);
  10522. if (!m) return NULL;
  10523. if (!upb_inttable_insertptr2(&c->methods, md, v, alloc)) return NULL;
  10524. /* Populate parser methods for all submessages, so the name tables will
  10525. * be available during parsing. */
  10526. for(upb_msg_field_begin(&i, md);
  10527. !upb_msg_field_done(&i);
  10528. upb_msg_field_next(&i)) {
  10529. upb_fielddef *f = upb_msg_iter_field(&i);
  10530. if (upb_fielddef_issubmsg(f)) {
  10531. const upb_msgdef *subdef = upb_fielddef_msgsubdef(f);
  10532. const upb_json_parsermethod *sub_method =
  10533. upb_json_codecache_get(c, subdef);
  10534. if (!sub_method) return NULL;
  10535. }
  10536. }
  10537. return m;
  10538. }
  10539. /*
  10540. ** This currently uses snprintf() to format primitives, and could be optimized
  10541. ** further.
  10542. */
  10543. #include <ctype.h>
  10544. #include <inttypes.h>
  10545. #include <stdint.h>
  10546. #include <string.h>
  10547. #include <time.h>
  10548. struct upb_json_printer {
  10549. upb_sink input_;
  10550. /* BytesSink closure. */
  10551. void *subc_;
  10552. upb_bytessink output_;
  10553. /* We track the depth so that we know when to emit startstr/endstr on the
  10554. * output. */
  10555. int depth_;
  10556. /* Have we emitted the first element? This state is necessary to emit commas
  10557. * without leaving a trailing comma in arrays/maps. We keep this state per
  10558. * frame depth.
  10559. *
  10560. * Why max_depth * 2? UPB_MAX_HANDLER_DEPTH counts depth as nested messages.
  10561. * We count frames (contexts in which we separate elements by commas) as both
  10562. * repeated fields and messages (maps), and the worst case is a
  10563. * message->repeated field->submessage->repeated field->... nesting. */
  10564. bool first_elem_[UPB_MAX_HANDLER_DEPTH * 2];
  10565. /* To print timestamp, printer needs to cache its seconds and nanos values
  10566. * and convert them when ending timestamp message. See comments of
  10567. * printer_sethandlers_timestamp for more detail. */
  10568. int64_t seconds;
  10569. int32_t nanos;
  10570. };
  10571. /* StringPiece; a pointer plus a length. */
  10572. typedef struct {
  10573. char *ptr;
  10574. size_t len;
  10575. } strpc;
  10576. void freestrpc(void *ptr) {
  10577. strpc *pc = ptr;
  10578. upb_gfree(pc->ptr);
  10579. upb_gfree(pc);
  10580. }
  10581. typedef struct {
  10582. bool preserve_fieldnames;
  10583. } upb_json_printercache;
  10584. /* Convert fielddef name to JSON name and return as a string piece. */
  10585. strpc *newstrpc(upb_handlers *h, const upb_fielddef *f,
  10586. bool preserve_fieldnames) {
  10587. /* TODO(haberman): handle malloc failure. */
  10588. strpc *ret = upb_gmalloc(sizeof(*ret));
  10589. if (preserve_fieldnames) {
  10590. ret->ptr = upb_gstrdup(upb_fielddef_name(f));
  10591. ret->len = strlen(ret->ptr);
  10592. } else {
  10593. ret->ptr = upb_gstrdup(upb_fielddef_jsonname(f));
  10594. ret->len = strlen(ret->ptr);
  10595. }
  10596. upb_handlers_addcleanup(h, ret, freestrpc);
  10597. return ret;
  10598. }
  10599. /* Convert a null-terminated const char* to a string piece. */
  10600. strpc *newstrpc_str(upb_handlers *h, const char * str) {
  10601. strpc * ret = upb_gmalloc(sizeof(*ret));
  10602. ret->ptr = upb_gstrdup(str);
  10603. ret->len = strlen(str);
  10604. upb_handlers_addcleanup(h, ret, freestrpc);
  10605. return ret;
  10606. }
  10607. /* ------------ JSON string printing: values, maps, arrays ------------------ */
  10608. static void print_data(
  10609. upb_json_printer *p, const char *buf, size_t len) {
  10610. /* TODO: Will need to change if we support pushback from the sink. */
  10611. size_t n = upb_bytessink_putbuf(p->output_, p->subc_, buf, len, NULL);
  10612. UPB_ASSERT(n == len);
  10613. }
  10614. static void print_comma(upb_json_printer *p) {
  10615. if (!p->first_elem_[p->depth_]) {
  10616. print_data(p, ",", 1);
  10617. }
  10618. p->first_elem_[p->depth_] = false;
  10619. }
  10620. /* Helpers that print properly formatted elements to the JSON output stream. */
  10621. /* Used for escaping control chars in strings. */
  10622. static const char kControlCharLimit = 0x20;
  10623. UPB_INLINE bool is_json_escaped(char c) {
  10624. /* See RFC 4627. */
  10625. unsigned char uc = (unsigned char)c;
  10626. return uc < kControlCharLimit || uc == '"' || uc == '\\';
  10627. }
  10628. UPB_INLINE const char* json_nice_escape(char c) {
  10629. switch (c) {
  10630. case '"': return "\\\"";
  10631. case '\\': return "\\\\";
  10632. case '\b': return "\\b";
  10633. case '\f': return "\\f";
  10634. case '\n': return "\\n";
  10635. case '\r': return "\\r";
  10636. case '\t': return "\\t";
  10637. default: return NULL;
  10638. }
  10639. }
  10640. /* Write a properly escaped string chunk. The surrounding quotes are *not*
  10641. * printed; this is so that the caller has the option of emitting the string
  10642. * content in chunks. */
  10643. static void putstring(upb_json_printer *p, const char *buf, size_t len) {
  10644. const char* unescaped_run = NULL;
  10645. unsigned int i;
  10646. for (i = 0; i < len; i++) {
  10647. char c = buf[i];
  10648. /* Handle escaping. */
  10649. if (is_json_escaped(c)) {
  10650. /* Use a "nice" escape, like \n, if one exists for this character. */
  10651. const char* escape = json_nice_escape(c);
  10652. /* If we don't have a specific 'nice' escape code, use a \uXXXX-style
  10653. * escape. */
  10654. char escape_buf[8];
  10655. if (!escape) {
  10656. unsigned char byte = (unsigned char)c;
  10657. _upb_snprintf(escape_buf, sizeof(escape_buf), "\\u%04x", (int)byte);
  10658. escape = escape_buf;
  10659. }
  10660. /* N.B. that we assume that the input encoding is equal to the output
  10661. * encoding (both UTF-8 for now), so for chars >= 0x20 and != \, ", we
  10662. * can simply pass the bytes through. */
  10663. /* If there's a current run of unescaped chars, print that run first. */
  10664. if (unescaped_run) {
  10665. print_data(p, unescaped_run, &buf[i] - unescaped_run);
  10666. unescaped_run = NULL;
  10667. }
  10668. /* Then print the escape code. */
  10669. print_data(p, escape, strlen(escape));
  10670. } else {
  10671. /* Add to the current unescaped run of characters. */
  10672. if (unescaped_run == NULL) {
  10673. unescaped_run = &buf[i];
  10674. }
  10675. }
  10676. }
  10677. /* If the string ended in a run of unescaped characters, print that last run. */
  10678. if (unescaped_run) {
  10679. print_data(p, unescaped_run, &buf[len] - unescaped_run);
  10680. }
  10681. }
  10682. #define CHKLENGTH(x) if (!(x)) return -1;
  10683. /* Helpers that format floating point values according to our custom formats.
  10684. * Right now we use %.8g and %.17g for float/double, respectively, to match
  10685. * proto2::util::JsonFormat's defaults. May want to change this later. */
  10686. const char neginf[] = "\"-Infinity\"";
  10687. const char inf[] = "\"Infinity\"";
  10688. static size_t fmt_double(double val, char* buf, size_t length) {
  10689. if (val == UPB_INFINITY) {
  10690. CHKLENGTH(length >= strlen(inf));
  10691. strcpy(buf, inf);
  10692. return strlen(inf);
  10693. } else if (val == -UPB_INFINITY) {
  10694. CHKLENGTH(length >= strlen(neginf));
  10695. strcpy(buf, neginf);
  10696. return strlen(neginf);
  10697. } else {
  10698. size_t n = _upb_snprintf(buf, length, "%.17g", val);
  10699. CHKLENGTH(n > 0 && n < length);
  10700. return n;
  10701. }
  10702. }
  10703. static size_t fmt_float(float val, char* buf, size_t length) {
  10704. size_t n = _upb_snprintf(buf, length, "%.8g", val);
  10705. CHKLENGTH(n > 0 && n < length);
  10706. return n;
  10707. }
  10708. static size_t fmt_bool(bool val, char* buf, size_t length) {
  10709. size_t n = _upb_snprintf(buf, length, "%s", (val ? "true" : "false"));
  10710. CHKLENGTH(n > 0 && n < length);
  10711. return n;
  10712. }
  10713. static size_t fmt_int64_as_number(int64_t val, char* buf, size_t length) {
  10714. size_t n = _upb_snprintf(buf, length, "%" PRId64, val);
  10715. CHKLENGTH(n > 0 && n < length);
  10716. return n;
  10717. }
  10718. static size_t fmt_uint64_as_number(uint64_t val, char* buf, size_t length) {
  10719. size_t n = _upb_snprintf(buf, length, "%" PRIu64, val);
  10720. CHKLENGTH(n > 0 && n < length);
  10721. return n;
  10722. }
  10723. static size_t fmt_int64_as_string(int64_t val, char* buf, size_t length) {
  10724. size_t n = _upb_snprintf(buf, length, "\"%" PRId64 "\"", val);
  10725. CHKLENGTH(n > 0 && n < length);
  10726. return n;
  10727. }
  10728. static size_t fmt_uint64_as_string(uint64_t val, char* buf, size_t length) {
  10729. size_t n = _upb_snprintf(buf, length, "\"%" PRIu64 "\"", val);
  10730. CHKLENGTH(n > 0 && n < length);
  10731. return n;
  10732. }
  10733. /* Print a map key given a field name. Called by scalar field handlers and by
  10734. * startseq for repeated fields. */
  10735. static bool putkey(void *closure, const void *handler_data) {
  10736. upb_json_printer *p = closure;
  10737. const strpc *key = handler_data;
  10738. print_comma(p);
  10739. print_data(p, "\"", 1);
  10740. putstring(p, key->ptr, key->len);
  10741. print_data(p, "\":", 2);
  10742. return true;
  10743. }
  10744. #define CHKFMT(val) if ((val) == (size_t)-1) return false;
  10745. #define CHK(val) if (!(val)) return false;
  10746. #define TYPE_HANDLERS(type, fmt_func) \
  10747. static bool put##type(void *closure, const void *handler_data, type val) { \
  10748. upb_json_printer *p = closure; \
  10749. char data[64]; \
  10750. size_t length = fmt_func(val, data, sizeof(data)); \
  10751. UPB_UNUSED(handler_data); \
  10752. CHKFMT(length); \
  10753. print_data(p, data, length); \
  10754. return true; \
  10755. } \
  10756. static bool scalar_##type(void *closure, const void *handler_data, \
  10757. type val) { \
  10758. CHK(putkey(closure, handler_data)); \
  10759. CHK(put##type(closure, handler_data, val)); \
  10760. return true; \
  10761. } \
  10762. static bool repeated_##type(void *closure, const void *handler_data, \
  10763. type val) { \
  10764. upb_json_printer *p = closure; \
  10765. print_comma(p); \
  10766. CHK(put##type(closure, handler_data, val)); \
  10767. return true; \
  10768. }
  10769. #define TYPE_HANDLERS_MAPKEY(type, fmt_func) \
  10770. static bool putmapkey_##type(void *closure, const void *handler_data, \
  10771. type val) { \
  10772. upb_json_printer *p = closure; \
  10773. char data[64]; \
  10774. size_t length = fmt_func(val, data, sizeof(data)); \
  10775. UPB_UNUSED(handler_data); \
  10776. print_data(p, "\"", 1); \
  10777. print_data(p, data, length); \
  10778. print_data(p, "\":", 2); \
  10779. return true; \
  10780. }
  10781. TYPE_HANDLERS(double, fmt_double)
  10782. TYPE_HANDLERS(float, fmt_float)
  10783. TYPE_HANDLERS(bool, fmt_bool)
  10784. TYPE_HANDLERS(int32_t, fmt_int64_as_number)
  10785. TYPE_HANDLERS(uint32_t, fmt_int64_as_number)
  10786. TYPE_HANDLERS(int64_t, fmt_int64_as_string)
  10787. TYPE_HANDLERS(uint64_t, fmt_uint64_as_string)
  10788. /* double and float are not allowed to be map keys. */
  10789. TYPE_HANDLERS_MAPKEY(bool, fmt_bool)
  10790. TYPE_HANDLERS_MAPKEY(int32_t, fmt_int64_as_number)
  10791. TYPE_HANDLERS_MAPKEY(uint32_t, fmt_int64_as_number)
  10792. TYPE_HANDLERS_MAPKEY(int64_t, fmt_int64_as_number)
  10793. TYPE_HANDLERS_MAPKEY(uint64_t, fmt_uint64_as_number)
  10794. #undef TYPE_HANDLERS
  10795. #undef TYPE_HANDLERS_MAPKEY
  10796. typedef struct {
  10797. void *keyname;
  10798. const upb_enumdef *enumdef;
  10799. } EnumHandlerData;
  10800. static bool scalar_enum(void *closure, const void *handler_data,
  10801. int32_t val) {
  10802. const EnumHandlerData *hd = handler_data;
  10803. upb_json_printer *p = closure;
  10804. const char *symbolic_name;
  10805. CHK(putkey(closure, hd->keyname));
  10806. symbolic_name = upb_enumdef_iton(hd->enumdef, val);
  10807. if (symbolic_name) {
  10808. print_data(p, "\"", 1);
  10809. putstring(p, symbolic_name, strlen(symbolic_name));
  10810. print_data(p, "\"", 1);
  10811. } else {
  10812. putint32_t(closure, NULL, val);
  10813. }
  10814. return true;
  10815. }
  10816. static void print_enum_symbolic_name(upb_json_printer *p,
  10817. const upb_enumdef *def,
  10818. int32_t val) {
  10819. const char *symbolic_name = upb_enumdef_iton(def, val);
  10820. if (symbolic_name) {
  10821. print_data(p, "\"", 1);
  10822. putstring(p, symbolic_name, strlen(symbolic_name));
  10823. print_data(p, "\"", 1);
  10824. } else {
  10825. putint32_t(p, NULL, val);
  10826. }
  10827. }
  10828. static bool repeated_enum(void *closure, const void *handler_data,
  10829. int32_t val) {
  10830. const EnumHandlerData *hd = handler_data;
  10831. upb_json_printer *p = closure;
  10832. print_comma(p);
  10833. print_enum_symbolic_name(p, hd->enumdef, val);
  10834. return true;
  10835. }
  10836. static bool mapvalue_enum(void *closure, const void *handler_data,
  10837. int32_t val) {
  10838. const EnumHandlerData *hd = handler_data;
  10839. upb_json_printer *p = closure;
  10840. print_enum_symbolic_name(p, hd->enumdef, val);
  10841. return true;
  10842. }
  10843. static void *scalar_startsubmsg(void *closure, const void *handler_data) {
  10844. return putkey(closure, handler_data) ? closure : UPB_BREAK;
  10845. }
  10846. static void *repeated_startsubmsg(void *closure, const void *handler_data) {
  10847. upb_json_printer *p = closure;
  10848. UPB_UNUSED(handler_data);
  10849. print_comma(p);
  10850. return closure;
  10851. }
  10852. static void start_frame(upb_json_printer *p) {
  10853. p->depth_++;
  10854. p->first_elem_[p->depth_] = true;
  10855. print_data(p, "{", 1);
  10856. }
  10857. static void end_frame(upb_json_printer *p) {
  10858. print_data(p, "}", 1);
  10859. p->depth_--;
  10860. }
  10861. static bool printer_startmsg(void *closure, const void *handler_data) {
  10862. upb_json_printer *p = closure;
  10863. UPB_UNUSED(handler_data);
  10864. if (p->depth_ == 0) {
  10865. upb_bytessink_start(p->output_, 0, &p->subc_);
  10866. }
  10867. start_frame(p);
  10868. return true;
  10869. }
  10870. static bool printer_endmsg(void *closure, const void *handler_data, upb_status *s) {
  10871. upb_json_printer *p = closure;
  10872. UPB_UNUSED(handler_data);
  10873. UPB_UNUSED(s);
  10874. end_frame(p);
  10875. if (p->depth_ == 0) {
  10876. upb_bytessink_end(p->output_);
  10877. }
  10878. return true;
  10879. }
  10880. static void *startseq(void *closure, const void *handler_data) {
  10881. upb_json_printer *p = closure;
  10882. CHK(putkey(closure, handler_data));
  10883. p->depth_++;
  10884. p->first_elem_[p->depth_] = true;
  10885. print_data(p, "[", 1);
  10886. return closure;
  10887. }
  10888. static bool endseq(void *closure, const void *handler_data) {
  10889. upb_json_printer *p = closure;
  10890. UPB_UNUSED(handler_data);
  10891. print_data(p, "]", 1);
  10892. p->depth_--;
  10893. return true;
  10894. }
  10895. static void *startmap(void *closure, const void *handler_data) {
  10896. upb_json_printer *p = closure;
  10897. CHK(putkey(closure, handler_data));
  10898. p->depth_++;
  10899. p->first_elem_[p->depth_] = true;
  10900. print_data(p, "{", 1);
  10901. return closure;
  10902. }
  10903. static bool endmap(void *closure, const void *handler_data) {
  10904. upb_json_printer *p = closure;
  10905. UPB_UNUSED(handler_data);
  10906. print_data(p, "}", 1);
  10907. p->depth_--;
  10908. return true;
  10909. }
  10910. static size_t putstr(void *closure, const void *handler_data, const char *str,
  10911. size_t len, const upb_bufhandle *handle) {
  10912. upb_json_printer *p = closure;
  10913. UPB_UNUSED(handler_data);
  10914. UPB_UNUSED(handle);
  10915. putstring(p, str, len);
  10916. return len;
  10917. }
  10918. /* This has to Base64 encode the bytes, because JSON has no "bytes" type. */
  10919. static size_t putbytes(void *closure, const void *handler_data, const char *str,
  10920. size_t len, const upb_bufhandle *handle) {
  10921. upb_json_printer *p = closure;
  10922. /* This is the regular base64, not the "web-safe" version. */
  10923. static const char base64[] =
  10924. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  10925. /* Base64-encode. */
  10926. char data[16000];
  10927. const char *limit = data + sizeof(data);
  10928. const unsigned char *from = (const unsigned char*)str;
  10929. char *to = data;
  10930. size_t remaining = len;
  10931. size_t bytes;
  10932. UPB_UNUSED(handler_data);
  10933. UPB_UNUSED(handle);
  10934. print_data(p, "\"", 1);
  10935. while (remaining > 2) {
  10936. if (limit - to < 4) {
  10937. bytes = to - data;
  10938. putstring(p, data, bytes);
  10939. to = data;
  10940. }
  10941. to[0] = base64[from[0] >> 2];
  10942. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  10943. to[2] = base64[((from[1] & 0xf) << 2) | (from[2] >> 6)];
  10944. to[3] = base64[from[2] & 0x3f];
  10945. remaining -= 3;
  10946. to += 4;
  10947. from += 3;
  10948. }
  10949. switch (remaining) {
  10950. case 2:
  10951. to[0] = base64[from[0] >> 2];
  10952. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  10953. to[2] = base64[(from[1] & 0xf) << 2];
  10954. to[3] = '=';
  10955. to += 4;
  10956. from += 2;
  10957. break;
  10958. case 1:
  10959. to[0] = base64[from[0] >> 2];
  10960. to[1] = base64[((from[0] & 0x3) << 4)];
  10961. to[2] = '=';
  10962. to[3] = '=';
  10963. to += 4;
  10964. from += 1;
  10965. break;
  10966. }
  10967. bytes = to - data;
  10968. putstring(p, data, bytes);
  10969. print_data(p, "\"", 1);
  10970. return len;
  10971. }
  10972. static void *scalar_startstr(void *closure, const void *handler_data,
  10973. size_t size_hint) {
  10974. upb_json_printer *p = closure;
  10975. UPB_UNUSED(handler_data);
  10976. UPB_UNUSED(size_hint);
  10977. CHK(putkey(closure, handler_data));
  10978. print_data(p, "\"", 1);
  10979. return p;
  10980. }
  10981. static size_t scalar_str(void *closure, const void *handler_data,
  10982. const char *str, size_t len,
  10983. const upb_bufhandle *handle) {
  10984. CHK(putstr(closure, handler_data, str, len, handle));
  10985. return len;
  10986. }
  10987. static bool scalar_endstr(void *closure, const void *handler_data) {
  10988. upb_json_printer *p = closure;
  10989. UPB_UNUSED(handler_data);
  10990. print_data(p, "\"", 1);
  10991. return true;
  10992. }
  10993. static void *repeated_startstr(void *closure, const void *handler_data,
  10994. size_t size_hint) {
  10995. upb_json_printer *p = closure;
  10996. UPB_UNUSED(handler_data);
  10997. UPB_UNUSED(size_hint);
  10998. print_comma(p);
  10999. print_data(p, "\"", 1);
  11000. return p;
  11001. }
  11002. static size_t repeated_str(void *closure, const void *handler_data,
  11003. const char *str, size_t len,
  11004. const upb_bufhandle *handle) {
  11005. CHK(putstr(closure, handler_data, str, len, handle));
  11006. return len;
  11007. }
  11008. static bool repeated_endstr(void *closure, const void *handler_data) {
  11009. upb_json_printer *p = closure;
  11010. UPB_UNUSED(handler_data);
  11011. print_data(p, "\"", 1);
  11012. return true;
  11013. }
  11014. static void *mapkeyval_startstr(void *closure, const void *handler_data,
  11015. size_t size_hint) {
  11016. upb_json_printer *p = closure;
  11017. UPB_UNUSED(handler_data);
  11018. UPB_UNUSED(size_hint);
  11019. print_data(p, "\"", 1);
  11020. return p;
  11021. }
  11022. static size_t mapkey_str(void *closure, const void *handler_data,
  11023. const char *str, size_t len,
  11024. const upb_bufhandle *handle) {
  11025. CHK(putstr(closure, handler_data, str, len, handle));
  11026. return len;
  11027. }
  11028. static bool mapkey_endstr(void *closure, const void *handler_data) {
  11029. upb_json_printer *p = closure;
  11030. UPB_UNUSED(handler_data);
  11031. print_data(p, "\":", 2);
  11032. return true;
  11033. }
  11034. static bool mapvalue_endstr(void *closure, const void *handler_data) {
  11035. upb_json_printer *p = closure;
  11036. UPB_UNUSED(handler_data);
  11037. print_data(p, "\"", 1);
  11038. return true;
  11039. }
  11040. static size_t scalar_bytes(void *closure, const void *handler_data,
  11041. const char *str, size_t len,
  11042. const upb_bufhandle *handle) {
  11043. CHK(putkey(closure, handler_data));
  11044. CHK(putbytes(closure, handler_data, str, len, handle));
  11045. return len;
  11046. }
  11047. static size_t repeated_bytes(void *closure, const void *handler_data,
  11048. const char *str, size_t len,
  11049. const upb_bufhandle *handle) {
  11050. upb_json_printer *p = closure;
  11051. print_comma(p);
  11052. CHK(putbytes(closure, handler_data, str, len, handle));
  11053. return len;
  11054. }
  11055. static size_t mapkey_bytes(void *closure, const void *handler_data,
  11056. const char *str, size_t len,
  11057. const upb_bufhandle *handle) {
  11058. upb_json_printer *p = closure;
  11059. CHK(putbytes(closure, handler_data, str, len, handle));
  11060. print_data(p, ":", 1);
  11061. return len;
  11062. }
  11063. static void set_enum_hd(upb_handlers *h,
  11064. const upb_fielddef *f,
  11065. bool preserve_fieldnames,
  11066. upb_handlerattr *attr) {
  11067. EnumHandlerData *hd = upb_gmalloc(sizeof(EnumHandlerData));
  11068. hd->enumdef = upb_fielddef_enumsubdef(f);
  11069. hd->keyname = newstrpc(h, f, preserve_fieldnames);
  11070. upb_handlers_addcleanup(h, hd, upb_gfree);
  11071. attr->handler_data = hd;
  11072. }
  11073. /* Set up handlers for a mapentry submessage (i.e., an individual key/value pair
  11074. * in a map).
  11075. *
  11076. * TODO: Handle missing key, missing value, out-of-order key/value, or repeated
  11077. * key or value cases properly. The right way to do this is to allocate a
  11078. * temporary structure at the start of a mapentry submessage, store key and
  11079. * value data in it as key and value handlers are called, and then print the
  11080. * key/value pair once at the end of the submessage. If we don't do this, we
  11081. * should at least detect the case and throw an error. However, so far all of
  11082. * our sources that emit mapentry messages do so canonically (with one key
  11083. * field, and then one value field), so this is not a pressing concern at the
  11084. * moment. */
  11085. void printer_sethandlers_mapentry(const void *closure, bool preserve_fieldnames,
  11086. upb_handlers *h) {
  11087. const upb_msgdef *md = upb_handlers_msgdef(h);
  11088. /* A mapentry message is printed simply as '"key": value'. Rather than
  11089. * special-case key and value for every type below, we just handle both
  11090. * fields explicitly here. */
  11091. const upb_fielddef* key_field = upb_msgdef_itof(md, UPB_MAPENTRY_KEY);
  11092. const upb_fielddef* value_field = upb_msgdef_itof(md, UPB_MAPENTRY_VALUE);
  11093. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11094. UPB_UNUSED(closure);
  11095. switch (upb_fielddef_type(key_field)) {
  11096. case UPB_TYPE_INT32:
  11097. upb_handlers_setint32(h, key_field, putmapkey_int32_t, &empty_attr);
  11098. break;
  11099. case UPB_TYPE_INT64:
  11100. upb_handlers_setint64(h, key_field, putmapkey_int64_t, &empty_attr);
  11101. break;
  11102. case UPB_TYPE_UINT32:
  11103. upb_handlers_setuint32(h, key_field, putmapkey_uint32_t, &empty_attr);
  11104. break;
  11105. case UPB_TYPE_UINT64:
  11106. upb_handlers_setuint64(h, key_field, putmapkey_uint64_t, &empty_attr);
  11107. break;
  11108. case UPB_TYPE_BOOL:
  11109. upb_handlers_setbool(h, key_field, putmapkey_bool, &empty_attr);
  11110. break;
  11111. case UPB_TYPE_STRING:
  11112. upb_handlers_setstartstr(h, key_field, mapkeyval_startstr, &empty_attr);
  11113. upb_handlers_setstring(h, key_field, mapkey_str, &empty_attr);
  11114. upb_handlers_setendstr(h, key_field, mapkey_endstr, &empty_attr);
  11115. break;
  11116. case UPB_TYPE_BYTES:
  11117. upb_handlers_setstring(h, key_field, mapkey_bytes, &empty_attr);
  11118. break;
  11119. default:
  11120. UPB_ASSERT(false);
  11121. break;
  11122. }
  11123. switch (upb_fielddef_type(value_field)) {
  11124. case UPB_TYPE_INT32:
  11125. upb_handlers_setint32(h, value_field, putint32_t, &empty_attr);
  11126. break;
  11127. case UPB_TYPE_INT64:
  11128. upb_handlers_setint64(h, value_field, putint64_t, &empty_attr);
  11129. break;
  11130. case UPB_TYPE_UINT32:
  11131. upb_handlers_setuint32(h, value_field, putuint32_t, &empty_attr);
  11132. break;
  11133. case UPB_TYPE_UINT64:
  11134. upb_handlers_setuint64(h, value_field, putuint64_t, &empty_attr);
  11135. break;
  11136. case UPB_TYPE_BOOL:
  11137. upb_handlers_setbool(h, value_field, putbool, &empty_attr);
  11138. break;
  11139. case UPB_TYPE_FLOAT:
  11140. upb_handlers_setfloat(h, value_field, putfloat, &empty_attr);
  11141. break;
  11142. case UPB_TYPE_DOUBLE:
  11143. upb_handlers_setdouble(h, value_field, putdouble, &empty_attr);
  11144. break;
  11145. case UPB_TYPE_STRING:
  11146. upb_handlers_setstartstr(h, value_field, mapkeyval_startstr, &empty_attr);
  11147. upb_handlers_setstring(h, value_field, putstr, &empty_attr);
  11148. upb_handlers_setendstr(h, value_field, mapvalue_endstr, &empty_attr);
  11149. break;
  11150. case UPB_TYPE_BYTES:
  11151. upb_handlers_setstring(h, value_field, putbytes, &empty_attr);
  11152. break;
  11153. case UPB_TYPE_ENUM: {
  11154. upb_handlerattr enum_attr = UPB_HANDLERATTR_INIT;
  11155. set_enum_hd(h, value_field, preserve_fieldnames, &enum_attr);
  11156. upb_handlers_setint32(h, value_field, mapvalue_enum, &enum_attr);
  11157. break;
  11158. }
  11159. case UPB_TYPE_MESSAGE:
  11160. /* No handler necessary -- the submsg handlers will print the message
  11161. * as appropriate. */
  11162. break;
  11163. }
  11164. }
  11165. static bool putseconds(void *closure, const void *handler_data,
  11166. int64_t seconds) {
  11167. upb_json_printer *p = closure;
  11168. p->seconds = seconds;
  11169. UPB_UNUSED(handler_data);
  11170. return true;
  11171. }
  11172. static bool putnanos(void *closure, const void *handler_data,
  11173. int32_t nanos) {
  11174. upb_json_printer *p = closure;
  11175. p->nanos = nanos;
  11176. UPB_UNUSED(handler_data);
  11177. return true;
  11178. }
  11179. static void *scalar_startstr_nokey(void *closure, const void *handler_data,
  11180. size_t size_hint) {
  11181. upb_json_printer *p = closure;
  11182. UPB_UNUSED(handler_data);
  11183. UPB_UNUSED(size_hint);
  11184. print_data(p, "\"", 1);
  11185. return p;
  11186. }
  11187. static size_t putstr_nokey(void *closure, const void *handler_data,
  11188. const char *str, size_t len,
  11189. const upb_bufhandle *handle) {
  11190. upb_json_printer *p = closure;
  11191. UPB_UNUSED(handler_data);
  11192. UPB_UNUSED(handle);
  11193. print_data(p, "\"", 1);
  11194. putstring(p, str, len);
  11195. print_data(p, "\"", 1);
  11196. return len + 2;
  11197. }
  11198. static void *startseq_nokey(void *closure, const void *handler_data) {
  11199. upb_json_printer *p = closure;
  11200. UPB_UNUSED(handler_data);
  11201. p->depth_++;
  11202. p->first_elem_[p->depth_] = true;
  11203. print_data(p, "[", 1);
  11204. return closure;
  11205. }
  11206. static void *startseq_fieldmask(void *closure, const void *handler_data) {
  11207. upb_json_printer *p = closure;
  11208. UPB_UNUSED(handler_data);
  11209. p->depth_++;
  11210. p->first_elem_[p->depth_] = true;
  11211. return closure;
  11212. }
  11213. static bool endseq_fieldmask(void *closure, const void *handler_data) {
  11214. upb_json_printer *p = closure;
  11215. UPB_UNUSED(handler_data);
  11216. p->depth_--;
  11217. return true;
  11218. }
  11219. static void *repeated_startstr_fieldmask(
  11220. void *closure, const void *handler_data,
  11221. size_t size_hint) {
  11222. upb_json_printer *p = closure;
  11223. UPB_UNUSED(handler_data);
  11224. UPB_UNUSED(size_hint);
  11225. print_comma(p);
  11226. return p;
  11227. }
  11228. static size_t repeated_str_fieldmask(
  11229. void *closure, const void *handler_data,
  11230. const char *str, size_t len,
  11231. const upb_bufhandle *handle) {
  11232. const char* limit = str + len;
  11233. bool upper = false;
  11234. size_t result_len = 0;
  11235. for (; str < limit; str++) {
  11236. if (*str == '_') {
  11237. upper = true;
  11238. continue;
  11239. }
  11240. if (upper && *str >= 'a' && *str <= 'z') {
  11241. char upper_char = toupper(*str);
  11242. CHK(putstr(closure, handler_data, &upper_char, 1, handle));
  11243. } else {
  11244. CHK(putstr(closure, handler_data, str, 1, handle));
  11245. }
  11246. upper = false;
  11247. result_len++;
  11248. }
  11249. return result_len;
  11250. }
  11251. static void *startmap_nokey(void *closure, const void *handler_data) {
  11252. upb_json_printer *p = closure;
  11253. UPB_UNUSED(handler_data);
  11254. p->depth_++;
  11255. p->first_elem_[p->depth_] = true;
  11256. print_data(p, "{", 1);
  11257. return closure;
  11258. }
  11259. static bool putnull(void *closure, const void *handler_data,
  11260. int32_t null) {
  11261. upb_json_printer *p = closure;
  11262. print_data(p, "null", 4);
  11263. UPB_UNUSED(handler_data);
  11264. UPB_UNUSED(null);
  11265. return true;
  11266. }
  11267. static bool printer_startdurationmsg(void *closure, const void *handler_data) {
  11268. upb_json_printer *p = closure;
  11269. UPB_UNUSED(handler_data);
  11270. if (p->depth_ == 0) {
  11271. upb_bytessink_start(p->output_, 0, &p->subc_);
  11272. }
  11273. return true;
  11274. }
  11275. #define UPB_DURATION_MAX_JSON_LEN 23
  11276. #define UPB_DURATION_MAX_NANO_LEN 9
  11277. static bool printer_enddurationmsg(void *closure, const void *handler_data,
  11278. upb_status *s) {
  11279. upb_json_printer *p = closure;
  11280. char buffer[UPB_DURATION_MAX_JSON_LEN];
  11281. size_t base_len;
  11282. size_t curr;
  11283. size_t i;
  11284. memset(buffer, 0, UPB_DURATION_MAX_JSON_LEN);
  11285. if (p->seconds < -315576000000) {
  11286. upb_status_seterrf(s, "error parsing duration: "
  11287. "minimum acceptable value is "
  11288. "-315576000000");
  11289. return false;
  11290. }
  11291. if (p->seconds > 315576000000) {
  11292. upb_status_seterrf(s, "error serializing duration: "
  11293. "maximum acceptable value is "
  11294. "315576000000");
  11295. return false;
  11296. }
  11297. _upb_snprintf(buffer, sizeof(buffer), "%ld", (long)p->seconds);
  11298. base_len = strlen(buffer);
  11299. if (p->nanos != 0) {
  11300. char nanos_buffer[UPB_DURATION_MAX_NANO_LEN + 3];
  11301. _upb_snprintf(nanos_buffer, sizeof(nanos_buffer), "%.9f",
  11302. p->nanos / 1000000000.0);
  11303. /* Remove trailing 0. */
  11304. for (i = UPB_DURATION_MAX_NANO_LEN + 2;
  11305. nanos_buffer[i] == '0'; i--) {
  11306. nanos_buffer[i] = 0;
  11307. }
  11308. strcpy(buffer + base_len, nanos_buffer + 1);
  11309. }
  11310. curr = strlen(buffer);
  11311. strcpy(buffer + curr, "s");
  11312. p->seconds = 0;
  11313. p->nanos = 0;
  11314. print_data(p, "\"", 1);
  11315. print_data(p, buffer, strlen(buffer));
  11316. print_data(p, "\"", 1);
  11317. if (p->depth_ == 0) {
  11318. upb_bytessink_end(p->output_);
  11319. }
  11320. UPB_UNUSED(handler_data);
  11321. return true;
  11322. }
  11323. static bool printer_starttimestampmsg(void *closure, const void *handler_data) {
  11324. upb_json_printer *p = closure;
  11325. UPB_UNUSED(handler_data);
  11326. if (p->depth_ == 0) {
  11327. upb_bytessink_start(p->output_, 0, &p->subc_);
  11328. }
  11329. return true;
  11330. }
  11331. #define UPB_TIMESTAMP_MAX_JSON_LEN 31
  11332. #define UPB_TIMESTAMP_BEFORE_NANO_LEN 19
  11333. #define UPB_TIMESTAMP_MAX_NANO_LEN 9
  11334. static bool printer_endtimestampmsg(void *closure, const void *handler_data,
  11335. upb_status *s) {
  11336. upb_json_printer *p = closure;
  11337. char buffer[UPB_TIMESTAMP_MAX_JSON_LEN];
  11338. time_t time = p->seconds;
  11339. size_t curr;
  11340. size_t i;
  11341. size_t year_length =
  11342. strftime(buffer, UPB_TIMESTAMP_MAX_JSON_LEN, "%Y", gmtime(&time));
  11343. if (p->seconds < -62135596800) {
  11344. upb_status_seterrf(s, "error parsing timestamp: "
  11345. "minimum acceptable value is "
  11346. "0001-01-01T00:00:00Z");
  11347. return false;
  11348. }
  11349. if (p->seconds > 253402300799) {
  11350. upb_status_seterrf(s, "error parsing timestamp: "
  11351. "maximum acceptable value is "
  11352. "9999-12-31T23:59:59Z");
  11353. return false;
  11354. }
  11355. /* strftime doesn't guarantee 4 digits for year. Prepend 0 by ourselves. */
  11356. for (i = 0; i < 4 - year_length; i++) {
  11357. buffer[i] = '0';
  11358. }
  11359. strftime(buffer + (4 - year_length), UPB_TIMESTAMP_MAX_JSON_LEN,
  11360. "%Y-%m-%dT%H:%M:%S", gmtime(&time));
  11361. if (p->nanos != 0) {
  11362. char nanos_buffer[UPB_TIMESTAMP_MAX_NANO_LEN + 3];
  11363. _upb_snprintf(nanos_buffer, sizeof(nanos_buffer), "%.9f",
  11364. p->nanos / 1000000000.0);
  11365. /* Remove trailing 0. */
  11366. for (i = UPB_TIMESTAMP_MAX_NANO_LEN + 2;
  11367. nanos_buffer[i] == '0'; i--) {
  11368. nanos_buffer[i] = 0;
  11369. }
  11370. strcpy(buffer + UPB_TIMESTAMP_BEFORE_NANO_LEN, nanos_buffer + 1);
  11371. }
  11372. curr = strlen(buffer);
  11373. strcpy(buffer + curr, "Z");
  11374. p->seconds = 0;
  11375. p->nanos = 0;
  11376. print_data(p, "\"", 1);
  11377. print_data(p, buffer, strlen(buffer));
  11378. print_data(p, "\"", 1);
  11379. if (p->depth_ == 0) {
  11380. upb_bytessink_end(p->output_);
  11381. }
  11382. UPB_UNUSED(handler_data);
  11383. UPB_UNUSED(s);
  11384. return true;
  11385. }
  11386. static bool printer_startmsg_noframe(void *closure, const void *handler_data) {
  11387. upb_json_printer *p = closure;
  11388. UPB_UNUSED(handler_data);
  11389. if (p->depth_ == 0) {
  11390. upb_bytessink_start(p->output_, 0, &p->subc_);
  11391. }
  11392. return true;
  11393. }
  11394. static bool printer_endmsg_noframe(
  11395. void *closure, const void *handler_data, upb_status *s) {
  11396. upb_json_printer *p = closure;
  11397. UPB_UNUSED(handler_data);
  11398. UPB_UNUSED(s);
  11399. if (p->depth_ == 0) {
  11400. upb_bytessink_end(p->output_);
  11401. }
  11402. return true;
  11403. }
  11404. static bool printer_startmsg_fieldmask(
  11405. void *closure, const void *handler_data) {
  11406. upb_json_printer *p = closure;
  11407. UPB_UNUSED(handler_data);
  11408. if (p->depth_ == 0) {
  11409. upb_bytessink_start(p->output_, 0, &p->subc_);
  11410. }
  11411. print_data(p, "\"", 1);
  11412. return true;
  11413. }
  11414. static bool printer_endmsg_fieldmask(
  11415. void *closure, const void *handler_data, upb_status *s) {
  11416. upb_json_printer *p = closure;
  11417. UPB_UNUSED(handler_data);
  11418. UPB_UNUSED(s);
  11419. print_data(p, "\"", 1);
  11420. if (p->depth_ == 0) {
  11421. upb_bytessink_end(p->output_);
  11422. }
  11423. return true;
  11424. }
  11425. static void *scalar_startstr_onlykey(
  11426. void *closure, const void *handler_data, size_t size_hint) {
  11427. upb_json_printer *p = closure;
  11428. UPB_UNUSED(size_hint);
  11429. CHK(putkey(closure, handler_data));
  11430. return p;
  11431. }
  11432. /* Set up handlers for an Any submessage. */
  11433. void printer_sethandlers_any(const void *closure, upb_handlers *h) {
  11434. const upb_msgdef *md = upb_handlers_msgdef(h);
  11435. const upb_fielddef* type_field = upb_msgdef_itof(md, UPB_ANY_TYPE);
  11436. const upb_fielddef* value_field = upb_msgdef_itof(md, UPB_ANY_VALUE);
  11437. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11438. /* type_url's json name is "@type" */
  11439. upb_handlerattr type_name_attr = UPB_HANDLERATTR_INIT;
  11440. upb_handlerattr value_name_attr = UPB_HANDLERATTR_INIT;
  11441. strpc *type_url_json_name = newstrpc_str(h, "@type");
  11442. strpc *value_json_name = newstrpc_str(h, "value");
  11443. type_name_attr.handler_data = type_url_json_name;
  11444. value_name_attr.handler_data = value_json_name;
  11445. /* Set up handlers. */
  11446. upb_handlers_setstartmsg(h, printer_startmsg, &empty_attr);
  11447. upb_handlers_setendmsg(h, printer_endmsg, &empty_attr);
  11448. upb_handlers_setstartstr(h, type_field, scalar_startstr, &type_name_attr);
  11449. upb_handlers_setstring(h, type_field, scalar_str, &empty_attr);
  11450. upb_handlers_setendstr(h, type_field, scalar_endstr, &empty_attr);
  11451. /* This is not the full and correct JSON encoding for the Any value field. It
  11452. * requires further processing by the wrapper code based on the type URL.
  11453. */
  11454. upb_handlers_setstartstr(h, value_field, scalar_startstr_onlykey,
  11455. &value_name_attr);
  11456. UPB_UNUSED(closure);
  11457. }
  11458. /* Set up handlers for a fieldmask submessage. */
  11459. void printer_sethandlers_fieldmask(const void *closure, upb_handlers *h) {
  11460. const upb_msgdef *md = upb_handlers_msgdef(h);
  11461. const upb_fielddef* f = upb_msgdef_itof(md, 1);
  11462. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11463. upb_handlers_setstartseq(h, f, startseq_fieldmask, &empty_attr);
  11464. upb_handlers_setendseq(h, f, endseq_fieldmask, &empty_attr);
  11465. upb_handlers_setstartmsg(h, printer_startmsg_fieldmask, &empty_attr);
  11466. upb_handlers_setendmsg(h, printer_endmsg_fieldmask, &empty_attr);
  11467. upb_handlers_setstartstr(h, f, repeated_startstr_fieldmask, &empty_attr);
  11468. upb_handlers_setstring(h, f, repeated_str_fieldmask, &empty_attr);
  11469. UPB_UNUSED(closure);
  11470. }
  11471. /* Set up handlers for a duration submessage. */
  11472. void printer_sethandlers_duration(const void *closure, upb_handlers *h) {
  11473. const upb_msgdef *md = upb_handlers_msgdef(h);
  11474. const upb_fielddef* seconds_field =
  11475. upb_msgdef_itof(md, UPB_DURATION_SECONDS);
  11476. const upb_fielddef* nanos_field =
  11477. upb_msgdef_itof(md, UPB_DURATION_NANOS);
  11478. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11479. upb_handlers_setstartmsg(h, printer_startdurationmsg, &empty_attr);
  11480. upb_handlers_setint64(h, seconds_field, putseconds, &empty_attr);
  11481. upb_handlers_setint32(h, nanos_field, putnanos, &empty_attr);
  11482. upb_handlers_setendmsg(h, printer_enddurationmsg, &empty_attr);
  11483. UPB_UNUSED(closure);
  11484. }
  11485. /* Set up handlers for a timestamp submessage. Instead of printing fields
  11486. * separately, the json representation of timestamp follows RFC 3339 */
  11487. void printer_sethandlers_timestamp(const void *closure, upb_handlers *h) {
  11488. const upb_msgdef *md = upb_handlers_msgdef(h);
  11489. const upb_fielddef* seconds_field =
  11490. upb_msgdef_itof(md, UPB_TIMESTAMP_SECONDS);
  11491. const upb_fielddef* nanos_field =
  11492. upb_msgdef_itof(md, UPB_TIMESTAMP_NANOS);
  11493. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11494. upb_handlers_setstartmsg(h, printer_starttimestampmsg, &empty_attr);
  11495. upb_handlers_setint64(h, seconds_field, putseconds, &empty_attr);
  11496. upb_handlers_setint32(h, nanos_field, putnanos, &empty_attr);
  11497. upb_handlers_setendmsg(h, printer_endtimestampmsg, &empty_attr);
  11498. UPB_UNUSED(closure);
  11499. }
  11500. void printer_sethandlers_value(const void *closure, upb_handlers *h) {
  11501. const upb_msgdef *md = upb_handlers_msgdef(h);
  11502. upb_msg_field_iter i;
  11503. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11504. upb_handlers_setstartmsg(h, printer_startmsg_noframe, &empty_attr);
  11505. upb_handlers_setendmsg(h, printer_endmsg_noframe, &empty_attr);
  11506. upb_msg_field_begin(&i, md);
  11507. for(; !upb_msg_field_done(&i); upb_msg_field_next(&i)) {
  11508. const upb_fielddef *f = upb_msg_iter_field(&i);
  11509. switch (upb_fielddef_type(f)) {
  11510. case UPB_TYPE_ENUM:
  11511. upb_handlers_setint32(h, f, putnull, &empty_attr);
  11512. break;
  11513. case UPB_TYPE_DOUBLE:
  11514. upb_handlers_setdouble(h, f, putdouble, &empty_attr);
  11515. break;
  11516. case UPB_TYPE_STRING:
  11517. upb_handlers_setstartstr(h, f, scalar_startstr_nokey, &empty_attr);
  11518. upb_handlers_setstring(h, f, scalar_str, &empty_attr);
  11519. upb_handlers_setendstr(h, f, scalar_endstr, &empty_attr);
  11520. break;
  11521. case UPB_TYPE_BOOL:
  11522. upb_handlers_setbool(h, f, putbool, &empty_attr);
  11523. break;
  11524. case UPB_TYPE_MESSAGE:
  11525. break;
  11526. default:
  11527. UPB_ASSERT(false);
  11528. break;
  11529. }
  11530. }
  11531. UPB_UNUSED(closure);
  11532. }
  11533. #define WRAPPER_SETHANDLERS(wrapper, type, putmethod) \
  11534. void printer_sethandlers_##wrapper(const void *closure, upb_handlers *h) { \
  11535. const upb_msgdef *md = upb_handlers_msgdef(h); \
  11536. const upb_fielddef* f = upb_msgdef_itof(md, 1); \
  11537. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT; \
  11538. upb_handlers_setstartmsg(h, printer_startmsg_noframe, &empty_attr); \
  11539. upb_handlers_setendmsg(h, printer_endmsg_noframe, &empty_attr); \
  11540. upb_handlers_set##type(h, f, putmethod, &empty_attr); \
  11541. UPB_UNUSED(closure); \
  11542. }
  11543. WRAPPER_SETHANDLERS(doublevalue, double, putdouble)
  11544. WRAPPER_SETHANDLERS(floatvalue, float, putfloat)
  11545. WRAPPER_SETHANDLERS(int64value, int64, putint64_t)
  11546. WRAPPER_SETHANDLERS(uint64value, uint64, putuint64_t)
  11547. WRAPPER_SETHANDLERS(int32value, int32, putint32_t)
  11548. WRAPPER_SETHANDLERS(uint32value, uint32, putuint32_t)
  11549. WRAPPER_SETHANDLERS(boolvalue, bool, putbool)
  11550. WRAPPER_SETHANDLERS(stringvalue, string, putstr_nokey)
  11551. WRAPPER_SETHANDLERS(bytesvalue, string, putbytes)
  11552. #undef WRAPPER_SETHANDLERS
  11553. void printer_sethandlers_listvalue(const void *closure, upb_handlers *h) {
  11554. const upb_msgdef *md = upb_handlers_msgdef(h);
  11555. const upb_fielddef* f = upb_msgdef_itof(md, 1);
  11556. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11557. upb_handlers_setstartseq(h, f, startseq_nokey, &empty_attr);
  11558. upb_handlers_setendseq(h, f, endseq, &empty_attr);
  11559. upb_handlers_setstartmsg(h, printer_startmsg_noframe, &empty_attr);
  11560. upb_handlers_setendmsg(h, printer_endmsg_noframe, &empty_attr);
  11561. upb_handlers_setstartsubmsg(h, f, repeated_startsubmsg, &empty_attr);
  11562. UPB_UNUSED(closure);
  11563. }
  11564. void printer_sethandlers_structvalue(const void *closure, upb_handlers *h) {
  11565. const upb_msgdef *md = upb_handlers_msgdef(h);
  11566. const upb_fielddef* f = upb_msgdef_itof(md, 1);
  11567. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11568. upb_handlers_setstartseq(h, f, startmap_nokey, &empty_attr);
  11569. upb_handlers_setendseq(h, f, endmap, &empty_attr);
  11570. upb_handlers_setstartmsg(h, printer_startmsg_noframe, &empty_attr);
  11571. upb_handlers_setendmsg(h, printer_endmsg_noframe, &empty_attr);
  11572. upb_handlers_setstartsubmsg(h, f, repeated_startsubmsg, &empty_attr);
  11573. UPB_UNUSED(closure);
  11574. }
  11575. void printer_sethandlers(const void *closure, upb_handlers *h) {
  11576. const upb_msgdef *md = upb_handlers_msgdef(h);
  11577. bool is_mapentry = upb_msgdef_mapentry(md);
  11578. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11579. upb_msg_field_iter i;
  11580. const upb_json_printercache *cache = closure;
  11581. const bool preserve_fieldnames = cache->preserve_fieldnames;
  11582. if (is_mapentry) {
  11583. /* mapentry messages are sufficiently different that we handle them
  11584. * separately. */
  11585. printer_sethandlers_mapentry(closure, preserve_fieldnames, h);
  11586. return;
  11587. }
  11588. switch (upb_msgdef_wellknowntype(md)) {
  11589. case UPB_WELLKNOWN_UNSPECIFIED:
  11590. break;
  11591. case UPB_WELLKNOWN_ANY:
  11592. printer_sethandlers_any(closure, h);
  11593. return;
  11594. case UPB_WELLKNOWN_FIELDMASK:
  11595. printer_sethandlers_fieldmask(closure, h);
  11596. return;
  11597. case UPB_WELLKNOWN_DURATION:
  11598. printer_sethandlers_duration(closure, h);
  11599. return;
  11600. case UPB_WELLKNOWN_TIMESTAMP:
  11601. printer_sethandlers_timestamp(closure, h);
  11602. return;
  11603. case UPB_WELLKNOWN_VALUE:
  11604. printer_sethandlers_value(closure, h);
  11605. return;
  11606. case UPB_WELLKNOWN_LISTVALUE:
  11607. printer_sethandlers_listvalue(closure, h);
  11608. return;
  11609. case UPB_WELLKNOWN_STRUCT:
  11610. printer_sethandlers_structvalue(closure, h);
  11611. return;
  11612. #define WRAPPER(wellknowntype, name) \
  11613. case wellknowntype: \
  11614. printer_sethandlers_##name(closure, h); \
  11615. return; \
  11616. WRAPPER(UPB_WELLKNOWN_DOUBLEVALUE, doublevalue);
  11617. WRAPPER(UPB_WELLKNOWN_FLOATVALUE, floatvalue);
  11618. WRAPPER(UPB_WELLKNOWN_INT64VALUE, int64value);
  11619. WRAPPER(UPB_WELLKNOWN_UINT64VALUE, uint64value);
  11620. WRAPPER(UPB_WELLKNOWN_INT32VALUE, int32value);
  11621. WRAPPER(UPB_WELLKNOWN_UINT32VALUE, uint32value);
  11622. WRAPPER(UPB_WELLKNOWN_BOOLVALUE, boolvalue);
  11623. WRAPPER(UPB_WELLKNOWN_STRINGVALUE, stringvalue);
  11624. WRAPPER(UPB_WELLKNOWN_BYTESVALUE, bytesvalue);
  11625. #undef WRAPPER
  11626. }
  11627. upb_handlers_setstartmsg(h, printer_startmsg, &empty_attr);
  11628. upb_handlers_setendmsg(h, printer_endmsg, &empty_attr);
  11629. #define TYPE(type, name, ctype) \
  11630. case type: \
  11631. if (upb_fielddef_isseq(f)) { \
  11632. upb_handlers_set##name(h, f, repeated_##ctype, &empty_attr); \
  11633. } else { \
  11634. upb_handlers_set##name(h, f, scalar_##ctype, &name_attr); \
  11635. } \
  11636. break;
  11637. upb_msg_field_begin(&i, md);
  11638. for(; !upb_msg_field_done(&i); upb_msg_field_next(&i)) {
  11639. const upb_fielddef *f = upb_msg_iter_field(&i);
  11640. upb_handlerattr name_attr = UPB_HANDLERATTR_INIT;
  11641. name_attr.handler_data = newstrpc(h, f, preserve_fieldnames);
  11642. if (upb_fielddef_ismap(f)) {
  11643. upb_handlers_setstartseq(h, f, startmap, &name_attr);
  11644. upb_handlers_setendseq(h, f, endmap, &name_attr);
  11645. } else if (upb_fielddef_isseq(f)) {
  11646. upb_handlers_setstartseq(h, f, startseq, &name_attr);
  11647. upb_handlers_setendseq(h, f, endseq, &empty_attr);
  11648. }
  11649. switch (upb_fielddef_type(f)) {
  11650. TYPE(UPB_TYPE_FLOAT, float, float);
  11651. TYPE(UPB_TYPE_DOUBLE, double, double);
  11652. TYPE(UPB_TYPE_BOOL, bool, bool);
  11653. TYPE(UPB_TYPE_INT32, int32, int32_t);
  11654. TYPE(UPB_TYPE_UINT32, uint32, uint32_t);
  11655. TYPE(UPB_TYPE_INT64, int64, int64_t);
  11656. TYPE(UPB_TYPE_UINT64, uint64, uint64_t);
  11657. case UPB_TYPE_ENUM: {
  11658. /* For now, we always emit symbolic names for enums. We may want an
  11659. * option later to control this behavior, but we will wait for a real
  11660. * need first. */
  11661. upb_handlerattr enum_attr = UPB_HANDLERATTR_INIT;
  11662. set_enum_hd(h, f, preserve_fieldnames, &enum_attr);
  11663. if (upb_fielddef_isseq(f)) {
  11664. upb_handlers_setint32(h, f, repeated_enum, &enum_attr);
  11665. } else {
  11666. upb_handlers_setint32(h, f, scalar_enum, &enum_attr);
  11667. }
  11668. break;
  11669. }
  11670. case UPB_TYPE_STRING:
  11671. if (upb_fielddef_isseq(f)) {
  11672. upb_handlers_setstartstr(h, f, repeated_startstr, &empty_attr);
  11673. upb_handlers_setstring(h, f, repeated_str, &empty_attr);
  11674. upb_handlers_setendstr(h, f, repeated_endstr, &empty_attr);
  11675. } else {
  11676. upb_handlers_setstartstr(h, f, scalar_startstr, &name_attr);
  11677. upb_handlers_setstring(h, f, scalar_str, &empty_attr);
  11678. upb_handlers_setendstr(h, f, scalar_endstr, &empty_attr);
  11679. }
  11680. break;
  11681. case UPB_TYPE_BYTES:
  11682. /* XXX: this doesn't support strings that span buffers yet. The base64
  11683. * encoder will need to be made resumable for this to work properly. */
  11684. if (upb_fielddef_isseq(f)) {
  11685. upb_handlers_setstring(h, f, repeated_bytes, &empty_attr);
  11686. } else {
  11687. upb_handlers_setstring(h, f, scalar_bytes, &name_attr);
  11688. }
  11689. break;
  11690. case UPB_TYPE_MESSAGE:
  11691. if (upb_fielddef_isseq(f)) {
  11692. upb_handlers_setstartsubmsg(h, f, repeated_startsubmsg, &name_attr);
  11693. } else {
  11694. upb_handlers_setstartsubmsg(h, f, scalar_startsubmsg, &name_attr);
  11695. }
  11696. break;
  11697. }
  11698. }
  11699. #undef TYPE
  11700. }
  11701. static void json_printer_reset(upb_json_printer *p) {
  11702. p->depth_ = 0;
  11703. }
  11704. /* Public API *****************************************************************/
  11705. upb_json_printer *upb_json_printer_create(upb_arena *a, const upb_handlers *h,
  11706. upb_bytessink output) {
  11707. #ifndef NDEBUG
  11708. size_t size_before = upb_arena_bytesallocated(a);
  11709. #endif
  11710. upb_json_printer *p = upb_arena_malloc(a, sizeof(upb_json_printer));
  11711. if (!p) return NULL;
  11712. p->output_ = output;
  11713. json_printer_reset(p);
  11714. upb_sink_reset(&p->input_, h, p);
  11715. p->seconds = 0;
  11716. p->nanos = 0;
  11717. /* If this fails, increase the value in printer.h. */
  11718. UPB_ASSERT_DEBUGVAR(upb_arena_bytesallocated(a) - size_before <=
  11719. UPB_JSON_PRINTER_SIZE);
  11720. return p;
  11721. }
  11722. upb_sink upb_json_printer_input(upb_json_printer *p) {
  11723. return p->input_;
  11724. }
  11725. upb_handlercache *upb_json_printer_newcache(bool preserve_proto_fieldnames) {
  11726. upb_json_printercache *cache = upb_gmalloc(sizeof(*cache));
  11727. upb_handlercache *ret = upb_handlercache_new(printer_sethandlers, cache);
  11728. cache->preserve_fieldnames = preserve_proto_fieldnames;
  11729. upb_handlercache_addcleanup(ret, cache, upb_gfree);
  11730. return ret;
  11731. }
  11732. /* See port_def.inc. This should #undef all macros #defined there. */
  11733. #undef UPB_MAPTYPE_STRING
  11734. #undef UPB_SIZE
  11735. #undef UPB_PTR_AT
  11736. #undef UPB_READ_ONEOF
  11737. #undef UPB_WRITE_ONEOF
  11738. #undef UPB_INLINE
  11739. #undef UPB_FORCEINLINE
  11740. #undef UPB_NOINLINE
  11741. #undef UPB_NORETURN
  11742. #undef UPB_MAX
  11743. #undef UPB_MIN
  11744. #undef UPB_UNUSED
  11745. #undef UPB_ASSUME
  11746. #undef UPB_ASSERT
  11747. #undef UPB_ASSERT_DEBUGVAR
  11748. #undef UPB_UNREACHABLE
  11749. #undef UPB_INFINITY
  11750. #undef UPB_MSVC_VSNPRINTF
  11751. #undef _upb_snprintf
  11752. #undef _upb_vsnprintf
  11753. #undef _upb_va_copy