upb.c 391 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289
  1. /* Amalgamated source file */
  2. #include "upb.h"
  3. /*
  4. * This is where we define macros used across upb.
  5. *
  6. * All of these macros are undef'd in port_undef.inc to avoid leaking them to
  7. * users.
  8. *
  9. * The correct usage is:
  10. *
  11. * #include "upb/foobar.h"
  12. * #include "upb/baz.h"
  13. *
  14. * // MUST be last included header.
  15. * #include "upb/port_def.inc"
  16. *
  17. * // Code for this file.
  18. * // <...>
  19. *
  20. * // Can be omitted for .c files, required for .h.
  21. * #include "upb/port_undef.inc"
  22. *
  23. * This file is private and must not be included by users!
  24. */
  25. #ifndef UINTPTR_MAX
  26. #error must include stdint.h first
  27. #endif
  28. #if UINTPTR_MAX == 0xffffffff
  29. #define UPB_SIZE(size32, size64) size32
  30. #else
  31. #define UPB_SIZE(size32, size64) size64
  32. #endif
  33. #define UPB_FIELD_AT(msg, fieldtype, offset) \
  34. *(fieldtype*)((const char*)(msg) + offset)
  35. #define UPB_READ_ONEOF(msg, fieldtype, offset, case_offset, case_val, default) \
  36. UPB_FIELD_AT(msg, int, case_offset) == case_val \
  37. ? UPB_FIELD_AT(msg, fieldtype, offset) \
  38. : default
  39. #define UPB_WRITE_ONEOF(msg, fieldtype, offset, value, case_offset, case_val) \
  40. UPB_FIELD_AT(msg, int, case_offset) = case_val; \
  41. UPB_FIELD_AT(msg, fieldtype, offset) = value;
  42. /* UPB_INLINE: inline if possible, emit standalone code if required. */
  43. #ifdef __cplusplus
  44. #define UPB_INLINE inline
  45. #elif defined (__GNUC__) || defined(__clang__)
  46. #define UPB_INLINE static __inline__
  47. #else
  48. #define UPB_INLINE static
  49. #endif
  50. /* Hints to the compiler about likely/unlikely branches. */
  51. #if defined (__GNUC__) || defined(__clang__)
  52. #define UPB_LIKELY(x) __builtin_expect((x),1)
  53. #define UPB_UNLIKELY(x) __builtin_expect((x),0)
  54. #else
  55. #define UPB_LIKELY(x) (x)
  56. #define UPB_UNLIKELY(x) (x)
  57. #endif
  58. /* Define UPB_BIG_ENDIAN manually if you're on big endian and your compiler
  59. * doesn't provide these preprocessor symbols. */
  60. #if defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)
  61. #define UPB_BIG_ENDIAN
  62. #endif
  63. /* Macros for function attributes on compilers that support them. */
  64. #ifdef __GNUC__
  65. #define UPB_FORCEINLINE __inline__ __attribute__((always_inline))
  66. #define UPB_NOINLINE __attribute__((noinline))
  67. #define UPB_NORETURN __attribute__((__noreturn__))
  68. #else /* !defined(__GNUC__) */
  69. #define UPB_FORCEINLINE
  70. #define UPB_NOINLINE
  71. #define UPB_NORETURN
  72. #endif
  73. #if __STDC_VERSION__ >= 199901L || __cplusplus >= 201103L
  74. /* C99/C++11 versions. */
  75. #include <stdio.h>
  76. #define _upb_snprintf snprintf
  77. #define _upb_vsnprintf vsnprintf
  78. #define _upb_va_copy(a, b) va_copy(a, b)
  79. #elif defined(_MSC_VER)
  80. /* Microsoft C/C++ versions. */
  81. #include <stdarg.h>
  82. #include <stdio.h>
  83. #if _MSC_VER < 1900
  84. int msvc_snprintf(char* s, size_t n, const char* format, ...);
  85. int msvc_vsnprintf(char* s, size_t n, const char* format, va_list arg);
  86. #define UPB_MSVC_VSNPRINTF
  87. #define _upb_snprintf msvc_snprintf
  88. #define _upb_vsnprintf msvc_vsnprintf
  89. #else
  90. #define _upb_snprintf snprintf
  91. #define _upb_vsnprintf vsnprintf
  92. #endif
  93. #define _upb_va_copy(a, b) va_copy(a, b)
  94. #elif defined __GNUC__
  95. /* A few hacky workarounds for functions not in C89.
  96. * For internal use only!
  97. * TODO(haberman): fix these by including our own implementations, or finding
  98. * another workaround.
  99. */
  100. #define _upb_snprintf __builtin_snprintf
  101. #define _upb_vsnprintf __builtin_vsnprintf
  102. #define _upb_va_copy(a, b) __va_copy(a, b)
  103. #else
  104. #error Need implementations of [v]snprintf and va_copy
  105. #endif
  106. #ifdef __cplusplus
  107. #if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__) || \
  108. (defined(_MSC_VER) && _MSC_VER >= 1900)
  109. // C++11 is present
  110. #else
  111. #error upb requires C++11 for C++ support
  112. #endif
  113. #endif
  114. #define UPB_MAX(x, y) ((x) > (y) ? (x) : (y))
  115. #define UPB_MIN(x, y) ((x) < (y) ? (x) : (y))
  116. #define UPB_UNUSED(var) (void)var
  117. /* UPB_ASSERT(): in release mode, we use the expression without letting it be
  118. * evaluated. This prevents "unused variable" warnings. */
  119. #ifdef NDEBUG
  120. #define UPB_ASSERT(expr) do {} while (false && (expr))
  121. #else
  122. #define UPB_ASSERT(expr) assert(expr)
  123. #endif
  124. /* UPB_ASSERT_DEBUGVAR(): assert that uses functions or variables that only
  125. * exist in debug mode. This turns into regular assert. */
  126. #define UPB_ASSERT_DEBUGVAR(expr) assert(expr)
  127. #if defined(__GNUC__) || defined(__clang__)
  128. #define UPB_UNREACHABLE() do { assert(0); __builtin_unreachable(); } while(0)
  129. #else
  130. #define UPB_UNREACHABLE() do { assert(0); } while(0)
  131. #endif
  132. /* UPB_INFINITY representing floating-point positive infinity. */
  133. #include <math.h>
  134. #ifdef INFINITY
  135. #define UPB_INFINITY INFINITY
  136. #else
  137. #define UPB_INFINITY (1.0 / 0.0)
  138. #endif
  139. #include <string.h>
  140. /* Maps descriptor type -> upb field type. */
  141. const uint8_t upb_desctype_to_fieldtype[] = {
  142. UPB_WIRE_TYPE_END_GROUP, /* ENDGROUP */
  143. UPB_TYPE_DOUBLE, /* DOUBLE */
  144. UPB_TYPE_FLOAT, /* FLOAT */
  145. UPB_TYPE_INT64, /* INT64 */
  146. UPB_TYPE_UINT64, /* UINT64 */
  147. UPB_TYPE_INT32, /* INT32 */
  148. UPB_TYPE_UINT64, /* FIXED64 */
  149. UPB_TYPE_UINT32, /* FIXED32 */
  150. UPB_TYPE_BOOL, /* BOOL */
  151. UPB_TYPE_STRING, /* STRING */
  152. UPB_TYPE_MESSAGE, /* GROUP */
  153. UPB_TYPE_MESSAGE, /* MESSAGE */
  154. UPB_TYPE_BYTES, /* BYTES */
  155. UPB_TYPE_UINT32, /* UINT32 */
  156. UPB_TYPE_ENUM, /* ENUM */
  157. UPB_TYPE_INT32, /* SFIXED32 */
  158. UPB_TYPE_INT64, /* SFIXED64 */
  159. UPB_TYPE_INT32, /* SINT32 */
  160. UPB_TYPE_INT64, /* SINT64 */
  161. };
  162. /* Data pertaining to the parse. */
  163. typedef struct {
  164. const char *ptr; /* Current parsing position. */
  165. const char *field_start; /* Start of this field. */
  166. const char *limit; /* End of delimited region or end of buffer. */
  167. upb_arena *arena;
  168. int depth;
  169. uint32_t end_group; /* Set to field number of END_GROUP tag, if any. */
  170. } upb_decstate;
  171. /* Data passed by value to each parsing function. */
  172. typedef struct {
  173. char *msg;
  174. const upb_msglayout *layout;
  175. upb_decstate *state;
  176. } upb_decframe;
  177. #define CHK(x) if (!(x)) { return 0; }
  178. static bool upb_skip_unknowngroup(upb_decstate *d, int field_number);
  179. static bool upb_decode_message(upb_decstate *d, char *msg,
  180. const upb_msglayout *l);
  181. static bool upb_decode_varint(const char **ptr, const char *limit,
  182. uint64_t *val) {
  183. uint8_t byte;
  184. int bitpos = 0;
  185. const char *p = *ptr;
  186. *val = 0;
  187. do {
  188. CHK(bitpos < 70 && p < limit);
  189. byte = *p;
  190. *val |= (uint64_t)(byte & 0x7F) << bitpos;
  191. p++;
  192. bitpos += 7;
  193. } while (byte & 0x80);
  194. *ptr = p;
  195. return true;
  196. }
  197. static bool upb_decode_varint32(const char **ptr, const char *limit,
  198. uint32_t *val) {
  199. uint64_t u64;
  200. CHK(upb_decode_varint(ptr, limit, &u64) && u64 <= UINT32_MAX);
  201. *val = (uint32_t)u64;
  202. return true;
  203. }
  204. static bool upb_decode_64bit(const char **ptr, const char *limit,
  205. uint64_t *val) {
  206. CHK(limit - *ptr >= 8);
  207. memcpy(val, *ptr, 8);
  208. *ptr += 8;
  209. return true;
  210. }
  211. static bool upb_decode_32bit(const char **ptr, const char *limit,
  212. uint32_t *val) {
  213. CHK(limit - *ptr >= 4);
  214. memcpy(val, *ptr, 4);
  215. *ptr += 4;
  216. return true;
  217. }
  218. static int32_t upb_zzdecode_32(uint32_t n) {
  219. return (n >> 1) ^ -(int32_t)(n & 1);
  220. }
  221. static int64_t upb_zzdecode_64(uint64_t n) {
  222. return (n >> 1) ^ -(int64_t)(n & 1);
  223. }
  224. static bool upb_decode_string(const char **ptr, const char *limit,
  225. int *outlen) {
  226. uint32_t len;
  227. CHK(upb_decode_varint32(ptr, limit, &len) &&
  228. len < INT32_MAX &&
  229. limit - *ptr >= (int32_t)len);
  230. *outlen = len;
  231. return true;
  232. }
  233. static void upb_set32(void *msg, size_t ofs, uint32_t val) {
  234. memcpy((char*)msg + ofs, &val, sizeof(val));
  235. }
  236. static bool upb_append_unknown(upb_decstate *d, upb_decframe *frame) {
  237. upb_msg_addunknown(frame->msg, d->field_start, d->ptr - d->field_start,
  238. d->arena);
  239. return true;
  240. }
  241. static bool upb_skip_unknownfielddata(upb_decstate *d, uint32_t tag,
  242. uint32_t group_fieldnum) {
  243. switch (tag & 7) {
  244. case UPB_WIRE_TYPE_VARINT: {
  245. uint64_t val;
  246. return upb_decode_varint(&d->ptr, d->limit, &val);
  247. }
  248. case UPB_WIRE_TYPE_32BIT: {
  249. uint32_t val;
  250. return upb_decode_32bit(&d->ptr, d->limit, &val);
  251. }
  252. case UPB_WIRE_TYPE_64BIT: {
  253. uint64_t val;
  254. return upb_decode_64bit(&d->ptr, d->limit, &val);
  255. }
  256. case UPB_WIRE_TYPE_DELIMITED: {
  257. int len;
  258. CHK(upb_decode_string(&d->ptr, d->limit, &len));
  259. d->ptr += len;
  260. return true;
  261. }
  262. case UPB_WIRE_TYPE_START_GROUP:
  263. return upb_skip_unknowngroup(d, tag >> 3);
  264. case UPB_WIRE_TYPE_END_GROUP:
  265. return (tag >> 3) == group_fieldnum;
  266. }
  267. return false;
  268. }
  269. static bool upb_skip_unknowngroup(upb_decstate *d, int field_number) {
  270. while (d->ptr < d->limit && d->end_group == 0) {
  271. uint32_t tag = 0;
  272. CHK(upb_decode_varint32(&d->ptr, d->limit, &tag));
  273. CHK(upb_skip_unknownfielddata(d, tag, field_number));
  274. }
  275. CHK(d->end_group == field_number);
  276. d->end_group = 0;
  277. return true;
  278. }
  279. static bool upb_array_grow(upb_array *arr, size_t elements, size_t elem_size,
  280. upb_arena *arena) {
  281. size_t needed = arr->len + elements;
  282. size_t new_size = UPB_MAX(arr->size, 8);
  283. size_t new_bytes;
  284. size_t old_bytes;
  285. void *new_data;
  286. upb_alloc *alloc = upb_arena_alloc(arena);
  287. while (new_size < needed) {
  288. new_size *= 2;
  289. }
  290. old_bytes = arr->len * elem_size;
  291. new_bytes = new_size * elem_size;
  292. new_data = upb_realloc(alloc, arr->data, old_bytes, new_bytes);
  293. CHK(new_data);
  294. arr->data = new_data;
  295. arr->size = new_size;
  296. return true;
  297. }
  298. static void *upb_array_reserve(upb_array *arr, size_t elements,
  299. size_t elem_size, upb_arena *arena) {
  300. if (arr->size - arr->len < elements) {
  301. CHK(upb_array_grow(arr, elements, elem_size, arena));
  302. }
  303. return (char*)arr->data + (arr->len * elem_size);
  304. }
  305. bool upb_array_add(upb_array *arr, size_t elements, size_t elem_size,
  306. const void *data, upb_arena *arena) {
  307. void *dest = upb_array_reserve(arr, elements, elem_size, arena);
  308. CHK(dest);
  309. arr->len += elements;
  310. memcpy(dest, data, elements * elem_size);
  311. return true;
  312. }
  313. static upb_array *upb_getarr(upb_decframe *frame,
  314. const upb_msglayout_field *field) {
  315. UPB_ASSERT(field->label == UPB_LABEL_REPEATED);
  316. return *(upb_array**)&frame->msg[field->offset];
  317. }
  318. static upb_array *upb_getorcreatearr(upb_decframe *frame,
  319. const upb_msglayout_field *field) {
  320. upb_array *arr = upb_getarr(frame, field);
  321. if (!arr) {
  322. arr = upb_array_new(frame->state->arena);
  323. CHK(arr);
  324. *(upb_array**)&frame->msg[field->offset] = arr;
  325. }
  326. return arr;
  327. }
  328. static upb_msg *upb_getorcreatemsg(upb_decframe *frame,
  329. const upb_msglayout_field *field,
  330. const upb_msglayout **subm) {
  331. upb_msg **submsg = (void*)(frame->msg + field->offset);
  332. *subm = frame->layout->submsgs[field->submsg_index];
  333. UPB_ASSERT(field->label != UPB_LABEL_REPEATED);
  334. if (!*submsg) {
  335. *submsg = upb_msg_new(*subm, frame->state->arena);
  336. CHK(*submsg);
  337. }
  338. return *submsg;
  339. }
  340. static upb_msg *upb_addmsg(upb_decframe *frame,
  341. const upb_msglayout_field *field,
  342. const upb_msglayout **subm) {
  343. upb_msg *submsg;
  344. upb_array *arr = upb_getorcreatearr(frame, field);
  345. *subm = frame->layout->submsgs[field->submsg_index];
  346. submsg = upb_msg_new(*subm, frame->state->arena);
  347. CHK(submsg);
  348. upb_array_add(arr, 1, sizeof(submsg), &submsg, frame->state->arena);
  349. return submsg;
  350. }
  351. static void upb_sethasbit(upb_decframe *frame,
  352. const upb_msglayout_field *field) {
  353. int32_t hasbit = field->presence;
  354. UPB_ASSERT(field->presence > 0);
  355. frame->msg[hasbit / 8] |= (1 << (hasbit % 8));
  356. }
  357. static void upb_setoneofcase(upb_decframe *frame,
  358. const upb_msglayout_field *field) {
  359. UPB_ASSERT(field->presence < 0);
  360. upb_set32(frame->msg, ~field->presence, field->number);
  361. }
  362. static bool upb_decode_addval(upb_decframe *frame,
  363. const upb_msglayout_field *field, void *val,
  364. size_t size) {
  365. char *field_mem = frame->msg + field->offset;
  366. upb_array *arr;
  367. if (field->label == UPB_LABEL_REPEATED) {
  368. arr = upb_getorcreatearr(frame, field);
  369. CHK(arr);
  370. field_mem = upb_array_reserve(arr, 1, size, frame->state->arena);
  371. CHK(field_mem);
  372. }
  373. memcpy(field_mem, val, size);
  374. return true;
  375. }
  376. static void upb_decode_setpresent(upb_decframe *frame,
  377. const upb_msglayout_field *field) {
  378. if (field->label == UPB_LABEL_REPEATED) {
  379. upb_array *arr = upb_getarr(frame, field);
  380. UPB_ASSERT(arr->len < arr->size);
  381. arr->len++;
  382. } else if (field->presence < 0) {
  383. upb_setoneofcase(frame, field);
  384. } else if (field->presence > 0) {
  385. upb_sethasbit(frame, field);
  386. }
  387. }
  388. static bool upb_decode_msgfield(upb_decstate *d, upb_msg *msg,
  389. const upb_msglayout *layout, int limit) {
  390. const char* saved_limit = d->limit;
  391. d->limit = d->ptr + limit;
  392. CHK(--d->depth >= 0);
  393. upb_decode_message(d, msg, layout);
  394. d->depth++;
  395. d->limit = saved_limit;
  396. CHK(d->end_group == 0);
  397. return true;
  398. }
  399. static bool upb_decode_groupfield(upb_decstate *d, upb_msg *msg,
  400. const upb_msglayout *layout,
  401. int field_number) {
  402. CHK(--d->depth >= 0);
  403. upb_decode_message(d, msg, layout);
  404. d->depth++;
  405. CHK(d->end_group == field_number);
  406. d->end_group = 0;
  407. return true;
  408. }
  409. static bool upb_decode_varintfield(upb_decstate *d, upb_decframe *frame,
  410. const upb_msglayout_field *field) {
  411. uint64_t val;
  412. CHK(upb_decode_varint(&d->ptr, d->limit, &val));
  413. switch (field->descriptortype) {
  414. case UPB_DESCRIPTOR_TYPE_INT64:
  415. case UPB_DESCRIPTOR_TYPE_UINT64:
  416. CHK(upb_decode_addval(frame, field, &val, sizeof(val)));
  417. break;
  418. case UPB_DESCRIPTOR_TYPE_INT32:
  419. case UPB_DESCRIPTOR_TYPE_UINT32:
  420. case UPB_DESCRIPTOR_TYPE_ENUM: {
  421. uint32_t val32 = (uint32_t)val;
  422. CHK(upb_decode_addval(frame, field, &val32, sizeof(val32)));
  423. break;
  424. }
  425. case UPB_DESCRIPTOR_TYPE_BOOL: {
  426. bool valbool = val != 0;
  427. CHK(upb_decode_addval(frame, field, &valbool, sizeof(valbool)));
  428. break;
  429. }
  430. case UPB_DESCRIPTOR_TYPE_SINT32: {
  431. int32_t decoded = upb_zzdecode_32((uint32_t)val);
  432. CHK(upb_decode_addval(frame, field, &decoded, sizeof(decoded)));
  433. break;
  434. }
  435. case UPB_DESCRIPTOR_TYPE_SINT64: {
  436. int64_t decoded = upb_zzdecode_64(val);
  437. CHK(upb_decode_addval(frame, field, &decoded, sizeof(decoded)));
  438. break;
  439. }
  440. default:
  441. return upb_append_unknown(d, frame);
  442. }
  443. upb_decode_setpresent(frame, field);
  444. return true;
  445. }
  446. static bool upb_decode_64bitfield(upb_decstate *d, upb_decframe *frame,
  447. const upb_msglayout_field *field) {
  448. uint64_t val;
  449. CHK(upb_decode_64bit(&d->ptr, d->limit, &val));
  450. switch (field->descriptortype) {
  451. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  452. case UPB_DESCRIPTOR_TYPE_FIXED64:
  453. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  454. CHK(upb_decode_addval(frame, field, &val, sizeof(val)));
  455. break;
  456. default:
  457. return upb_append_unknown(d, frame);
  458. }
  459. upb_decode_setpresent(frame, field);
  460. return true;
  461. }
  462. static bool upb_decode_32bitfield(upb_decstate *d, upb_decframe *frame,
  463. const upb_msglayout_field *field) {
  464. uint32_t val;
  465. CHK(upb_decode_32bit(&d->ptr, d->limit, &val));
  466. switch (field->descriptortype) {
  467. case UPB_DESCRIPTOR_TYPE_FLOAT:
  468. case UPB_DESCRIPTOR_TYPE_FIXED32:
  469. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  470. CHK(upb_decode_addval(frame, field, &val, sizeof(val)));
  471. break;
  472. default:
  473. return upb_append_unknown(d, frame);
  474. }
  475. upb_decode_setpresent(frame, field);
  476. return true;
  477. }
  478. static bool upb_decode_fixedpacked(upb_decstate *d, upb_array *arr,
  479. uint32_t len, int elem_size) {
  480. size_t elements = len / elem_size;
  481. CHK((size_t)(elements * elem_size) == len);
  482. CHK(upb_array_add(arr, elements, elem_size, d->ptr, d->arena));
  483. d->ptr += len;
  484. return true;
  485. }
  486. static upb_strview upb_decode_strfield(upb_decstate *d, uint32_t len) {
  487. upb_strview ret;
  488. ret.data = d->ptr;
  489. ret.size = len;
  490. d->ptr += len;
  491. return ret;
  492. }
  493. static bool upb_decode_toarray(upb_decstate *d, upb_decframe *frame,
  494. const upb_msglayout_field *field, int len) {
  495. upb_array *arr = upb_getorcreatearr(frame, field);
  496. CHK(arr);
  497. #define VARINT_CASE(ctype, decode) \
  498. VARINT_CASE_EX(ctype, decode, decode)
  499. #define VARINT_CASE_EX(ctype, decode, dtype) \
  500. { \
  501. const char *ptr = d->ptr; \
  502. const char *limit = ptr + len; \
  503. while (ptr < limit) { \
  504. uint64_t val; \
  505. ctype decoded; \
  506. CHK(upb_decode_varint(&ptr, limit, &val)); \
  507. decoded = (decode)((dtype)val); \
  508. CHK(upb_array_add(arr, 1, sizeof(decoded), &decoded, d->arena)); \
  509. } \
  510. d->ptr = ptr; \
  511. return true; \
  512. }
  513. switch (field->descriptortype) {
  514. case UPB_DESCRIPTOR_TYPE_STRING:
  515. case UPB_DESCRIPTOR_TYPE_BYTES: {
  516. upb_strview str = upb_decode_strfield(d, len);
  517. return upb_array_add(arr, 1, sizeof(str), &str, d->arena);
  518. }
  519. case UPB_DESCRIPTOR_TYPE_FLOAT:
  520. case UPB_DESCRIPTOR_TYPE_FIXED32:
  521. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  522. return upb_decode_fixedpacked(d, arr, len, sizeof(int32_t));
  523. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  524. case UPB_DESCRIPTOR_TYPE_FIXED64:
  525. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  526. return upb_decode_fixedpacked(d, arr, len, sizeof(int64_t));
  527. case UPB_DESCRIPTOR_TYPE_INT32:
  528. case UPB_DESCRIPTOR_TYPE_UINT32:
  529. case UPB_DESCRIPTOR_TYPE_ENUM:
  530. VARINT_CASE(uint32_t, uint32_t);
  531. case UPB_DESCRIPTOR_TYPE_INT64:
  532. case UPB_DESCRIPTOR_TYPE_UINT64:
  533. VARINT_CASE(uint64_t, uint64_t);
  534. case UPB_DESCRIPTOR_TYPE_BOOL:
  535. VARINT_CASE(bool, bool);
  536. case UPB_DESCRIPTOR_TYPE_SINT32:
  537. VARINT_CASE_EX(int32_t, upb_zzdecode_32, uint32_t);
  538. case UPB_DESCRIPTOR_TYPE_SINT64:
  539. VARINT_CASE_EX(int64_t, upb_zzdecode_64, uint64_t);
  540. case UPB_DESCRIPTOR_TYPE_MESSAGE: {
  541. const upb_msglayout *subm;
  542. upb_msg *submsg = upb_addmsg(frame, field, &subm);
  543. CHK(submsg);
  544. return upb_decode_msgfield(d, submsg, subm, len);
  545. }
  546. case UPB_DESCRIPTOR_TYPE_GROUP:
  547. return upb_append_unknown(d, frame);
  548. }
  549. #undef VARINT_CASE
  550. UPB_UNREACHABLE();
  551. }
  552. static bool upb_decode_delimitedfield(upb_decstate *d, upb_decframe *frame,
  553. const upb_msglayout_field *field) {
  554. int len;
  555. CHK(upb_decode_string(&d->ptr, d->limit, &len));
  556. if (field->label == UPB_LABEL_REPEATED) {
  557. return upb_decode_toarray(d, frame, field, len);
  558. } else {
  559. switch (field->descriptortype) {
  560. case UPB_DESCRIPTOR_TYPE_STRING:
  561. case UPB_DESCRIPTOR_TYPE_BYTES: {
  562. upb_strview str = upb_decode_strfield(d, len);
  563. CHK(upb_decode_addval(frame, field, &str, sizeof(str)));
  564. break;
  565. }
  566. case UPB_DESCRIPTOR_TYPE_MESSAGE: {
  567. const upb_msglayout *subm;
  568. upb_msg *submsg = upb_getorcreatemsg(frame, field, &subm);
  569. CHK(submsg);
  570. CHK(upb_decode_msgfield(d, submsg, subm, len));
  571. break;
  572. }
  573. default:
  574. /* TODO(haberman): should we accept the last element of a packed? */
  575. d->ptr += len;
  576. return upb_append_unknown(d, frame);
  577. }
  578. upb_decode_setpresent(frame, field);
  579. return true;
  580. }
  581. }
  582. static const upb_msglayout_field *upb_find_field(const upb_msglayout *l,
  583. uint32_t field_number) {
  584. /* Lots of optimization opportunities here. */
  585. int i;
  586. for (i = 0; i < l->field_count; i++) {
  587. if (l->fields[i].number == field_number) {
  588. return &l->fields[i];
  589. }
  590. }
  591. return NULL; /* Unknown field. */
  592. }
  593. static bool upb_decode_field(upb_decstate *d, upb_decframe *frame) {
  594. uint32_t tag;
  595. const upb_msglayout_field *field;
  596. int field_number;
  597. d->field_start = d->ptr;
  598. CHK(upb_decode_varint32(&d->ptr, d->limit, &tag));
  599. field_number = tag >> 3;
  600. field = upb_find_field(frame->layout, field_number);
  601. if (field) {
  602. switch (tag & 7) {
  603. case UPB_WIRE_TYPE_VARINT:
  604. return upb_decode_varintfield(d, frame, field);
  605. case UPB_WIRE_TYPE_32BIT:
  606. return upb_decode_32bitfield(d, frame, field);
  607. case UPB_WIRE_TYPE_64BIT:
  608. return upb_decode_64bitfield(d, frame, field);
  609. case UPB_WIRE_TYPE_DELIMITED:
  610. return upb_decode_delimitedfield(d, frame, field);
  611. case UPB_WIRE_TYPE_START_GROUP: {
  612. const upb_msglayout *layout;
  613. upb_msg *group;
  614. if (field->label == UPB_LABEL_REPEATED) {
  615. group = upb_addmsg(frame, field, &layout);
  616. } else {
  617. group = upb_getorcreatemsg(frame, field, &layout);
  618. }
  619. return upb_decode_groupfield(d, group, layout, field_number);
  620. }
  621. case UPB_WIRE_TYPE_END_GROUP:
  622. d->end_group = field_number;
  623. return true;
  624. default:
  625. CHK(false);
  626. }
  627. } else {
  628. CHK(field_number != 0);
  629. CHK(upb_skip_unknownfielddata(d, tag, -1));
  630. CHK(upb_append_unknown(d, frame));
  631. return true;
  632. }
  633. }
  634. static bool upb_decode_message(upb_decstate *d, char *msg, const upb_msglayout *l) {
  635. upb_decframe frame;
  636. frame.msg = msg;
  637. frame.layout = l;
  638. frame.state = d;
  639. while (d->ptr < d->limit) {
  640. CHK(upb_decode_field(d, &frame));
  641. }
  642. return true;
  643. }
  644. bool upb_decode(const char *buf, size_t size, void *msg, const upb_msglayout *l,
  645. upb_arena *arena) {
  646. upb_decstate state;
  647. state.ptr = buf;
  648. state.limit = buf + size;
  649. state.arena = arena;
  650. state.depth = 64;
  651. state.end_group = 0;
  652. CHK(upb_decode_message(&state, msg, l));
  653. return state.end_group == 0;
  654. }
  655. #undef CHK
  656. /* We encode backwards, to avoid pre-computing lengths (one-pass encode). */
  657. #include <string.h>
  658. #define UPB_PB_VARINT_MAX_LEN 10
  659. #define CHK(x) do { if (!(x)) { return false; } } while(0)
  660. static size_t upb_encode_varint(uint64_t val, char *buf) {
  661. size_t i;
  662. if (val < 128) { buf[0] = val; return 1; }
  663. i = 0;
  664. while (val) {
  665. uint8_t byte = val & 0x7fU;
  666. val >>= 7;
  667. if (val) byte |= 0x80U;
  668. buf[i++] = byte;
  669. }
  670. return i;
  671. }
  672. static uint32_t upb_zzencode_32(int32_t n) { return ((uint32_t)n << 1) ^ (n >> 31); }
  673. static uint64_t upb_zzencode_64(int64_t n) { return ((uint64_t)n << 1) ^ (n >> 63); }
  674. typedef struct {
  675. upb_alloc *alloc;
  676. char *buf, *ptr, *limit;
  677. } upb_encstate;
  678. static size_t upb_roundup_pow2(size_t bytes) {
  679. size_t ret = 128;
  680. while (ret < bytes) {
  681. ret *= 2;
  682. }
  683. return ret;
  684. }
  685. static bool upb_encode_growbuffer(upb_encstate *e, size_t bytes) {
  686. size_t old_size = e->limit - e->buf;
  687. size_t new_size = upb_roundup_pow2(bytes + (e->limit - e->ptr));
  688. char *new_buf = upb_realloc(e->alloc, e->buf, old_size, new_size);
  689. CHK(new_buf);
  690. /* We want previous data at the end, realloc() put it at the beginning. */
  691. if (old_size > 0) {
  692. memmove(new_buf + new_size - old_size, e->buf, old_size);
  693. }
  694. e->ptr = new_buf + new_size - (e->limit - e->ptr);
  695. e->limit = new_buf + new_size;
  696. e->buf = new_buf;
  697. return true;
  698. }
  699. /* Call to ensure that at least "bytes" bytes are available for writing at
  700. * e->ptr. Returns false if the bytes could not be allocated. */
  701. static bool upb_encode_reserve(upb_encstate *e, size_t bytes) {
  702. CHK(UPB_LIKELY((size_t)(e->ptr - e->buf) >= bytes) ||
  703. upb_encode_growbuffer(e, bytes));
  704. e->ptr -= bytes;
  705. return true;
  706. }
  707. /* Writes the given bytes to the buffer, handling reserve/advance. */
  708. static bool upb_put_bytes(upb_encstate *e, const void *data, size_t len) {
  709. CHK(upb_encode_reserve(e, len));
  710. memcpy(e->ptr, data, len);
  711. return true;
  712. }
  713. static bool upb_put_fixed64(upb_encstate *e, uint64_t val) {
  714. /* TODO(haberman): byte-swap for big endian. */
  715. return upb_put_bytes(e, &val, sizeof(uint64_t));
  716. }
  717. static bool upb_put_fixed32(upb_encstate *e, uint32_t val) {
  718. /* TODO(haberman): byte-swap for big endian. */
  719. return upb_put_bytes(e, &val, sizeof(uint32_t));
  720. }
  721. static bool upb_put_varint(upb_encstate *e, uint64_t val) {
  722. size_t len;
  723. char *start;
  724. CHK(upb_encode_reserve(e, UPB_PB_VARINT_MAX_LEN));
  725. len = upb_encode_varint(val, e->ptr);
  726. start = e->ptr + UPB_PB_VARINT_MAX_LEN - len;
  727. memmove(start, e->ptr, len);
  728. e->ptr = start;
  729. return true;
  730. }
  731. static bool upb_put_double(upb_encstate *e, double d) {
  732. uint64_t u64;
  733. UPB_ASSERT(sizeof(double) == sizeof(uint64_t));
  734. memcpy(&u64, &d, sizeof(uint64_t));
  735. return upb_put_fixed64(e, u64);
  736. }
  737. static bool upb_put_float(upb_encstate *e, float d) {
  738. uint32_t u32;
  739. UPB_ASSERT(sizeof(float) == sizeof(uint32_t));
  740. memcpy(&u32, &d, sizeof(uint32_t));
  741. return upb_put_fixed32(e, u32);
  742. }
  743. static uint32_t upb_readcase(const char *msg, const upb_msglayout_field *f) {
  744. uint32_t ret;
  745. uint32_t offset = ~f->presence;
  746. memcpy(&ret, msg + offset, sizeof(ret));
  747. return ret;
  748. }
  749. static bool upb_readhasbit(const char *msg, const upb_msglayout_field *f) {
  750. uint32_t hasbit = f->presence;
  751. UPB_ASSERT(f->presence > 0);
  752. return msg[hasbit / 8] & (1 << (hasbit % 8));
  753. }
  754. static bool upb_put_tag(upb_encstate *e, int field_number, int wire_type) {
  755. return upb_put_varint(e, (field_number << 3) | wire_type);
  756. }
  757. static bool upb_put_fixedarray(upb_encstate *e, const upb_array *arr,
  758. size_t size) {
  759. size_t bytes = arr->len * size;
  760. return upb_put_bytes(e, arr->data, bytes) && upb_put_varint(e, bytes);
  761. }
  762. bool upb_encode_message(upb_encstate *e, const char *msg,
  763. const upb_msglayout *m, size_t *size);
  764. static bool upb_encode_array(upb_encstate *e, const char *field_mem,
  765. const upb_msglayout *m,
  766. const upb_msglayout_field *f) {
  767. const upb_array *arr = *(const upb_array**)field_mem;
  768. if (arr == NULL || arr->len == 0) {
  769. return true;
  770. }
  771. #define VARINT_CASE(ctype, encode) { \
  772. ctype *start = arr->data; \
  773. ctype *ptr = start + arr->len; \
  774. size_t pre_len = e->limit - e->ptr; \
  775. do { \
  776. ptr--; \
  777. CHK(upb_put_varint(e, encode)); \
  778. } while (ptr != start); \
  779. CHK(upb_put_varint(e, e->limit - e->ptr - pre_len)); \
  780. } \
  781. break; \
  782. do { ; } while(0)
  783. switch (f->descriptortype) {
  784. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  785. CHK(upb_put_fixedarray(e, arr, sizeof(double)));
  786. break;
  787. case UPB_DESCRIPTOR_TYPE_FLOAT:
  788. CHK(upb_put_fixedarray(e, arr, sizeof(float)));
  789. break;
  790. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  791. case UPB_DESCRIPTOR_TYPE_FIXED64:
  792. CHK(upb_put_fixedarray(e, arr, sizeof(uint64_t)));
  793. break;
  794. case UPB_DESCRIPTOR_TYPE_FIXED32:
  795. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  796. CHK(upb_put_fixedarray(e, arr, sizeof(uint32_t)));
  797. break;
  798. case UPB_DESCRIPTOR_TYPE_INT64:
  799. case UPB_DESCRIPTOR_TYPE_UINT64:
  800. VARINT_CASE(uint64_t, *ptr);
  801. case UPB_DESCRIPTOR_TYPE_UINT32:
  802. VARINT_CASE(uint32_t, *ptr);
  803. case UPB_DESCRIPTOR_TYPE_INT32:
  804. case UPB_DESCRIPTOR_TYPE_ENUM:
  805. VARINT_CASE(int32_t, (int64_t)*ptr);
  806. case UPB_DESCRIPTOR_TYPE_BOOL:
  807. VARINT_CASE(bool, *ptr);
  808. case UPB_DESCRIPTOR_TYPE_SINT32:
  809. VARINT_CASE(int32_t, upb_zzencode_32(*ptr));
  810. case UPB_DESCRIPTOR_TYPE_SINT64:
  811. VARINT_CASE(int64_t, upb_zzencode_64(*ptr));
  812. case UPB_DESCRIPTOR_TYPE_STRING:
  813. case UPB_DESCRIPTOR_TYPE_BYTES: {
  814. upb_strview *start = arr->data;
  815. upb_strview *ptr = start + arr->len;
  816. do {
  817. ptr--;
  818. CHK(upb_put_bytes(e, ptr->data, ptr->size) &&
  819. upb_put_varint(e, ptr->size) &&
  820. upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
  821. } while (ptr != start);
  822. return true;
  823. }
  824. case UPB_DESCRIPTOR_TYPE_GROUP: {
  825. void **start = arr->data;
  826. void **ptr = start + arr->len;
  827. const upb_msglayout *subm = m->submsgs[f->submsg_index];
  828. do {
  829. size_t size;
  830. ptr--;
  831. CHK(upb_put_tag(e, f->number, UPB_WIRE_TYPE_END_GROUP) &&
  832. upb_encode_message(e, *ptr, subm, &size) &&
  833. upb_put_tag(e, f->number, UPB_WIRE_TYPE_START_GROUP));
  834. } while (ptr != start);
  835. return true;
  836. }
  837. case UPB_DESCRIPTOR_TYPE_MESSAGE: {
  838. void **start = arr->data;
  839. void **ptr = start + arr->len;
  840. const upb_msglayout *subm = m->submsgs[f->submsg_index];
  841. do {
  842. size_t size;
  843. ptr--;
  844. CHK(upb_encode_message(e, *ptr, subm, &size) &&
  845. upb_put_varint(e, size) &&
  846. upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
  847. } while (ptr != start);
  848. return true;
  849. }
  850. }
  851. #undef VARINT_CASE
  852. /* We encode all primitive arrays as packed, regardless of what was specified
  853. * in the .proto file. Could special case 1-sized arrays. */
  854. CHK(upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
  855. return true;
  856. }
  857. static bool upb_encode_scalarfield(upb_encstate *e, const char *field_mem,
  858. const upb_msglayout *m,
  859. const upb_msglayout_field *f,
  860. bool skip_zero_value) {
  861. #define CASE(ctype, type, wire_type, encodeval) do { \
  862. ctype val = *(ctype*)field_mem; \
  863. if (skip_zero_value && val == 0) { \
  864. return true; \
  865. } \
  866. return upb_put_ ## type(e, encodeval) && \
  867. upb_put_tag(e, f->number, wire_type); \
  868. } while(0)
  869. switch (f->descriptortype) {
  870. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  871. CASE(double, double, UPB_WIRE_TYPE_64BIT, val);
  872. case UPB_DESCRIPTOR_TYPE_FLOAT:
  873. CASE(float, float, UPB_WIRE_TYPE_32BIT, val);
  874. case UPB_DESCRIPTOR_TYPE_INT64:
  875. case UPB_DESCRIPTOR_TYPE_UINT64:
  876. CASE(uint64_t, varint, UPB_WIRE_TYPE_VARINT, val);
  877. case UPB_DESCRIPTOR_TYPE_UINT32:
  878. CASE(uint32_t, varint, UPB_WIRE_TYPE_VARINT, val);
  879. case UPB_DESCRIPTOR_TYPE_INT32:
  880. case UPB_DESCRIPTOR_TYPE_ENUM:
  881. CASE(int32_t, varint, UPB_WIRE_TYPE_VARINT, (int64_t)val);
  882. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  883. case UPB_DESCRIPTOR_TYPE_FIXED64:
  884. CASE(uint64_t, fixed64, UPB_WIRE_TYPE_64BIT, val);
  885. case UPB_DESCRIPTOR_TYPE_FIXED32:
  886. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  887. CASE(uint32_t, fixed32, UPB_WIRE_TYPE_32BIT, val);
  888. case UPB_DESCRIPTOR_TYPE_BOOL:
  889. CASE(bool, varint, UPB_WIRE_TYPE_VARINT, val);
  890. case UPB_DESCRIPTOR_TYPE_SINT32:
  891. CASE(int32_t, varint, UPB_WIRE_TYPE_VARINT, upb_zzencode_32(val));
  892. case UPB_DESCRIPTOR_TYPE_SINT64:
  893. CASE(int64_t, varint, UPB_WIRE_TYPE_VARINT, upb_zzencode_64(val));
  894. case UPB_DESCRIPTOR_TYPE_STRING:
  895. case UPB_DESCRIPTOR_TYPE_BYTES: {
  896. upb_strview view = *(upb_strview*)field_mem;
  897. if (skip_zero_value && view.size == 0) {
  898. return true;
  899. }
  900. return upb_put_bytes(e, view.data, view.size) &&
  901. upb_put_varint(e, view.size) &&
  902. upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED);
  903. }
  904. case UPB_DESCRIPTOR_TYPE_GROUP: {
  905. size_t size;
  906. void *submsg = *(void **)field_mem;
  907. const upb_msglayout *subm = m->submsgs[f->submsg_index];
  908. if (submsg == NULL) {
  909. return true;
  910. }
  911. return upb_put_tag(e, f->number, UPB_WIRE_TYPE_END_GROUP) &&
  912. upb_encode_message(e, submsg, subm, &size) &&
  913. upb_put_tag(e, f->number, UPB_WIRE_TYPE_START_GROUP);
  914. }
  915. case UPB_DESCRIPTOR_TYPE_MESSAGE: {
  916. size_t size;
  917. void *submsg = *(void **)field_mem;
  918. const upb_msglayout *subm = m->submsgs[f->submsg_index];
  919. if (submsg == NULL) {
  920. return true;
  921. }
  922. return upb_encode_message(e, submsg, subm, &size) &&
  923. upb_put_varint(e, size) &&
  924. upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED);
  925. }
  926. }
  927. #undef CASE
  928. UPB_UNREACHABLE();
  929. }
  930. bool upb_encode_message(upb_encstate *e, const char *msg,
  931. const upb_msglayout *m, size_t *size) {
  932. int i;
  933. size_t pre_len = e->limit - e->ptr;
  934. const char *unknown;
  935. size_t unknown_size;
  936. for (i = m->field_count - 1; i >= 0; i--) {
  937. const upb_msglayout_field *f = &m->fields[i];
  938. if (f->label == UPB_LABEL_REPEATED) {
  939. CHK(upb_encode_array(e, msg + f->offset, m, f));
  940. } else {
  941. bool skip_empty = false;
  942. if (f->presence == 0) {
  943. /* Proto3 presence. */
  944. skip_empty = true;
  945. } else if (f->presence > 0) {
  946. /* Proto2 presence: hasbit. */
  947. if (!upb_readhasbit(msg, f)) {
  948. continue;
  949. }
  950. } else {
  951. /* Field is in a oneof. */
  952. if (upb_readcase(msg, f) != f->number) {
  953. continue;
  954. }
  955. }
  956. CHK(upb_encode_scalarfield(e, msg + f->offset, m, f, skip_empty));
  957. }
  958. }
  959. unknown = upb_msg_getunknown(msg, &unknown_size);
  960. if (unknown) {
  961. upb_put_bytes(e, unknown, unknown_size);
  962. }
  963. *size = (e->limit - e->ptr) - pre_len;
  964. return true;
  965. }
  966. char *upb_encode(const void *msg, const upb_msglayout *m, upb_arena *arena,
  967. size_t *size) {
  968. upb_encstate e;
  969. e.alloc = upb_arena_alloc(arena);
  970. e.buf = NULL;
  971. e.limit = NULL;
  972. e.ptr = NULL;
  973. if (!upb_encode_message(&e, msg, m, size)) {
  974. *size = 0;
  975. return NULL;
  976. }
  977. *size = e.limit - e.ptr;
  978. if (*size == 0) {
  979. static char ch;
  980. return &ch;
  981. } else {
  982. UPB_ASSERT(e.ptr);
  983. return e.ptr;
  984. }
  985. }
  986. #undef CHK
  987. #define VOIDPTR_AT(msg, ofs) (void*)((char*)msg + (int)ofs)
  988. /* Internal members of a upb_msg. We can change this without breaking binary
  989. * compatibility. We put these before the user's data. The user's upb_msg*
  990. * points after the upb_msg_internal. */
  991. /* Used when a message is not extendable. */
  992. typedef struct {
  993. char *unknown;
  994. size_t unknown_len;
  995. size_t unknown_size;
  996. } upb_msg_internal;
  997. /* Used when a message is extendable. */
  998. typedef struct {
  999. upb_inttable *extdict;
  1000. upb_msg_internal base;
  1001. } upb_msg_internal_withext;
  1002. static int upb_msg_internalsize(const upb_msglayout *l) {
  1003. return sizeof(upb_msg_internal) - l->extendable * sizeof(void *);
  1004. }
  1005. static size_t upb_msg_sizeof(const upb_msglayout *l) {
  1006. return l->size + upb_msg_internalsize(l);
  1007. }
  1008. static upb_msg_internal *upb_msg_getinternal(upb_msg *msg) {
  1009. return VOIDPTR_AT(msg, -sizeof(upb_msg_internal));
  1010. }
  1011. static const upb_msg_internal *upb_msg_getinternal_const(const upb_msg *msg) {
  1012. return VOIDPTR_AT(msg, -sizeof(upb_msg_internal));
  1013. }
  1014. static upb_msg_internal_withext *upb_msg_getinternalwithext(
  1015. upb_msg *msg, const upb_msglayout *l) {
  1016. UPB_ASSERT(l->extendable);
  1017. return VOIDPTR_AT(msg, -sizeof(upb_msg_internal_withext));
  1018. }
  1019. upb_msg *upb_msg_new(const upb_msglayout *l, upb_arena *a) {
  1020. upb_alloc *alloc = upb_arena_alloc(a);
  1021. void *mem = upb_malloc(alloc, upb_msg_sizeof(l));
  1022. upb_msg_internal *in;
  1023. upb_msg *msg;
  1024. if (!mem) {
  1025. return NULL;
  1026. }
  1027. msg = VOIDPTR_AT(mem, upb_msg_internalsize(l));
  1028. /* Initialize normal members. */
  1029. memset(msg, 0, l->size);
  1030. /* Initialize internal members. */
  1031. in = upb_msg_getinternal(msg);
  1032. in->unknown = NULL;
  1033. in->unknown_len = 0;
  1034. in->unknown_size = 0;
  1035. if (l->extendable) {
  1036. upb_msg_getinternalwithext(msg, l)->extdict = NULL;
  1037. }
  1038. return msg;
  1039. }
  1040. upb_array *upb_array_new(upb_arena *a) {
  1041. upb_array *ret = upb_arena_malloc(a, sizeof(upb_array));
  1042. if (!ret) {
  1043. return NULL;
  1044. }
  1045. ret->data = NULL;
  1046. ret->len = 0;
  1047. ret->size = 0;
  1048. return ret;
  1049. }
  1050. void upb_msg_addunknown(upb_msg *msg, const char *data, size_t len,
  1051. upb_arena *arena) {
  1052. upb_msg_internal *in = upb_msg_getinternal(msg);
  1053. if (len > in->unknown_size - in->unknown_len) {
  1054. upb_alloc *alloc = upb_arena_alloc(arena);
  1055. size_t need = in->unknown_size + len;
  1056. size_t newsize = UPB_MAX(in->unknown_size * 2, need);
  1057. in->unknown = upb_realloc(alloc, in->unknown, in->unknown_size, newsize);
  1058. in->unknown_size = newsize;
  1059. }
  1060. memcpy(in->unknown + in->unknown_len, data, len);
  1061. in->unknown_len += len;
  1062. }
  1063. const char *upb_msg_getunknown(const upb_msg *msg, size_t *len) {
  1064. const upb_msg_internal* in = upb_msg_getinternal_const(msg);
  1065. *len = in->unknown_len;
  1066. return in->unknown;
  1067. }
  1068. #undef VOIDPTR_AT
  1069. #ifdef UPB_MSVC_VSNPRINTF
  1070. /* Visual C++ earlier than 2015 doesn't have standard C99 snprintf and
  1071. * vsnprintf. To support them, missing functions are manually implemented
  1072. * using the existing secure functions. */
  1073. int msvc_vsnprintf(char* s, size_t n, const char* format, va_list arg) {
  1074. if (!s) {
  1075. return _vscprintf(format, arg);
  1076. }
  1077. int ret = _vsnprintf_s(s, n, _TRUNCATE, format, arg);
  1078. if (ret < 0) {
  1079. ret = _vscprintf(format, arg);
  1080. }
  1081. return ret;
  1082. }
  1083. int msvc_snprintf(char* s, size_t n, const char* format, ...) {
  1084. va_list arg;
  1085. va_start(arg, format);
  1086. int ret = msvc_vsnprintf(s, n, format, arg);
  1087. va_end(arg);
  1088. return ret;
  1089. }
  1090. #endif
  1091. /*
  1092. ** upb_table Implementation
  1093. **
  1094. ** Implementation is heavily inspired by Lua's ltable.c.
  1095. */
  1096. #include <string.h>
  1097. #define UPB_MAXARRSIZE 16 /* 64k. */
  1098. /* From Chromium. */
  1099. #define ARRAY_SIZE(x) \
  1100. ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x])))))
  1101. static void upb_check_alloc(upb_table *t, upb_alloc *a) {
  1102. UPB_UNUSED(t);
  1103. UPB_UNUSED(a);
  1104. UPB_ASSERT_DEBUGVAR(t->alloc == a);
  1105. }
  1106. static const double MAX_LOAD = 0.85;
  1107. /* The minimum utilization of the array part of a mixed hash/array table. This
  1108. * is a speed/memory-usage tradeoff (though it's not straightforward because of
  1109. * cache effects). The lower this is, the more memory we'll use. */
  1110. static const double MIN_DENSITY = 0.1;
  1111. bool is_pow2(uint64_t v) { return v == 0 || (v & (v - 1)) == 0; }
  1112. int log2ceil(uint64_t v) {
  1113. int ret = 0;
  1114. bool pow2 = is_pow2(v);
  1115. while (v >>= 1) ret++;
  1116. ret = pow2 ? ret : ret + 1; /* Ceiling. */
  1117. return UPB_MIN(UPB_MAXARRSIZE, ret);
  1118. }
  1119. char *upb_strdup(const char *s, upb_alloc *a) {
  1120. return upb_strdup2(s, strlen(s), a);
  1121. }
  1122. char *upb_strdup2(const char *s, size_t len, upb_alloc *a) {
  1123. size_t n;
  1124. char *p;
  1125. /* Prevent overflow errors. */
  1126. if (len == SIZE_MAX) return NULL;
  1127. /* Always null-terminate, even if binary data; but don't rely on the input to
  1128. * have a null-terminating byte since it may be a raw binary buffer. */
  1129. n = len + 1;
  1130. p = upb_malloc(a, n);
  1131. if (p) {
  1132. memcpy(p, s, len);
  1133. p[len] = 0;
  1134. }
  1135. return p;
  1136. }
  1137. /* A type to represent the lookup key of either a strtable or an inttable. */
  1138. typedef union {
  1139. uintptr_t num;
  1140. struct {
  1141. const char *str;
  1142. size_t len;
  1143. } str;
  1144. } lookupkey_t;
  1145. static lookupkey_t strkey2(const char *str, size_t len) {
  1146. lookupkey_t k;
  1147. k.str.str = str;
  1148. k.str.len = len;
  1149. return k;
  1150. }
  1151. static lookupkey_t intkey(uintptr_t key) {
  1152. lookupkey_t k;
  1153. k.num = key;
  1154. return k;
  1155. }
  1156. typedef uint32_t hashfunc_t(upb_tabkey key);
  1157. typedef bool eqlfunc_t(upb_tabkey k1, lookupkey_t k2);
  1158. /* Base table (shared code) ***************************************************/
  1159. /* For when we need to cast away const. */
  1160. static upb_tabent *mutable_entries(upb_table *t) {
  1161. return (upb_tabent*)t->entries;
  1162. }
  1163. static bool isfull(upb_table *t) {
  1164. if (upb_table_size(t) == 0) {
  1165. return true;
  1166. } else {
  1167. return ((double)(t->count + 1) / upb_table_size(t)) > MAX_LOAD;
  1168. }
  1169. }
  1170. static bool init(upb_table *t, upb_ctype_t ctype, uint8_t size_lg2,
  1171. upb_alloc *a) {
  1172. size_t bytes;
  1173. t->count = 0;
  1174. t->ctype = ctype;
  1175. t->size_lg2 = size_lg2;
  1176. t->mask = upb_table_size(t) ? upb_table_size(t) - 1 : 0;
  1177. #ifndef NDEBUG
  1178. t->alloc = a;
  1179. #endif
  1180. bytes = upb_table_size(t) * sizeof(upb_tabent);
  1181. if (bytes > 0) {
  1182. t->entries = upb_malloc(a, bytes);
  1183. if (!t->entries) return false;
  1184. memset(mutable_entries(t), 0, bytes);
  1185. } else {
  1186. t->entries = NULL;
  1187. }
  1188. return true;
  1189. }
  1190. static void uninit(upb_table *t, upb_alloc *a) {
  1191. upb_check_alloc(t, a);
  1192. upb_free(a, mutable_entries(t));
  1193. }
  1194. static upb_tabent *emptyent(upb_table *t) {
  1195. upb_tabent *e = mutable_entries(t) + upb_table_size(t);
  1196. while (1) { if (upb_tabent_isempty(--e)) return e; UPB_ASSERT(e > t->entries); }
  1197. }
  1198. static upb_tabent *getentry_mutable(upb_table *t, uint32_t hash) {
  1199. return (upb_tabent*)upb_getentry(t, hash);
  1200. }
  1201. static const upb_tabent *findentry(const upb_table *t, lookupkey_t key,
  1202. uint32_t hash, eqlfunc_t *eql) {
  1203. const upb_tabent *e;
  1204. if (t->size_lg2 == 0) return NULL;
  1205. e = upb_getentry(t, hash);
  1206. if (upb_tabent_isempty(e)) return NULL;
  1207. while (1) {
  1208. if (eql(e->key, key)) return e;
  1209. if ((e = e->next) == NULL) return NULL;
  1210. }
  1211. }
  1212. static upb_tabent *findentry_mutable(upb_table *t, lookupkey_t key,
  1213. uint32_t hash, eqlfunc_t *eql) {
  1214. return (upb_tabent*)findentry(t, key, hash, eql);
  1215. }
  1216. static bool lookup(const upb_table *t, lookupkey_t key, upb_value *v,
  1217. uint32_t hash, eqlfunc_t *eql) {
  1218. const upb_tabent *e = findentry(t, key, hash, eql);
  1219. if (e) {
  1220. if (v) {
  1221. _upb_value_setval(v, e->val.val, t->ctype);
  1222. }
  1223. return true;
  1224. } else {
  1225. return false;
  1226. }
  1227. }
  1228. /* The given key must not already exist in the table. */
  1229. static void insert(upb_table *t, lookupkey_t key, upb_tabkey tabkey,
  1230. upb_value val, uint32_t hash,
  1231. hashfunc_t *hashfunc, eqlfunc_t *eql) {
  1232. upb_tabent *mainpos_e;
  1233. upb_tabent *our_e;
  1234. UPB_ASSERT(findentry(t, key, hash, eql) == NULL);
  1235. UPB_ASSERT_DEBUGVAR(val.ctype == t->ctype);
  1236. t->count++;
  1237. mainpos_e = getentry_mutable(t, hash);
  1238. our_e = mainpos_e;
  1239. if (upb_tabent_isempty(mainpos_e)) {
  1240. /* Our main position is empty; use it. */
  1241. our_e->next = NULL;
  1242. } else {
  1243. /* Collision. */
  1244. upb_tabent *new_e = emptyent(t);
  1245. /* Head of collider's chain. */
  1246. upb_tabent *chain = getentry_mutable(t, hashfunc(mainpos_e->key));
  1247. if (chain == mainpos_e) {
  1248. /* Existing ent is in its main posisiton (it has the same hash as us, and
  1249. * is the head of our chain). Insert to new ent and append to this chain. */
  1250. new_e->next = mainpos_e->next;
  1251. mainpos_e->next = new_e;
  1252. our_e = new_e;
  1253. } else {
  1254. /* Existing ent is not in its main position (it is a node in some other
  1255. * chain). This implies that no existing ent in the table has our hash.
  1256. * Evict it (updating its chain) and use its ent for head of our chain. */
  1257. *new_e = *mainpos_e; /* copies next. */
  1258. while (chain->next != mainpos_e) {
  1259. chain = (upb_tabent*)chain->next;
  1260. UPB_ASSERT(chain);
  1261. }
  1262. chain->next = new_e;
  1263. our_e = mainpos_e;
  1264. our_e->next = NULL;
  1265. }
  1266. }
  1267. our_e->key = tabkey;
  1268. our_e->val.val = val.val;
  1269. UPB_ASSERT(findentry(t, key, hash, eql) == our_e);
  1270. }
  1271. static bool rm(upb_table *t, lookupkey_t key, upb_value *val,
  1272. upb_tabkey *removed, uint32_t hash, eqlfunc_t *eql) {
  1273. upb_tabent *chain = getentry_mutable(t, hash);
  1274. if (upb_tabent_isempty(chain)) return false;
  1275. if (eql(chain->key, key)) {
  1276. /* Element to remove is at the head of its chain. */
  1277. t->count--;
  1278. if (val) _upb_value_setval(val, chain->val.val, t->ctype);
  1279. if (removed) *removed = chain->key;
  1280. if (chain->next) {
  1281. upb_tabent *move = (upb_tabent*)chain->next;
  1282. *chain = *move;
  1283. move->key = 0; /* Make the slot empty. */
  1284. } else {
  1285. chain->key = 0; /* Make the slot empty. */
  1286. }
  1287. return true;
  1288. } else {
  1289. /* Element to remove is either in a non-head position or not in the
  1290. * table. */
  1291. while (chain->next && !eql(chain->next->key, key)) {
  1292. chain = (upb_tabent*)chain->next;
  1293. }
  1294. if (chain->next) {
  1295. /* Found element to remove. */
  1296. upb_tabent *rm = (upb_tabent*)chain->next;
  1297. t->count--;
  1298. if (val) _upb_value_setval(val, chain->next->val.val, t->ctype);
  1299. if (removed) *removed = rm->key;
  1300. rm->key = 0; /* Make the slot empty. */
  1301. chain->next = rm->next;
  1302. return true;
  1303. } else {
  1304. /* Element to remove is not in the table. */
  1305. return false;
  1306. }
  1307. }
  1308. }
  1309. static size_t next(const upb_table *t, size_t i) {
  1310. do {
  1311. if (++i >= upb_table_size(t))
  1312. return SIZE_MAX;
  1313. } while(upb_tabent_isempty(&t->entries[i]));
  1314. return i;
  1315. }
  1316. static size_t begin(const upb_table *t) {
  1317. return next(t, -1);
  1318. }
  1319. /* upb_strtable ***************************************************************/
  1320. /* A simple "subclass" of upb_table that only adds a hash function for strings. */
  1321. static upb_tabkey strcopy(lookupkey_t k2, upb_alloc *a) {
  1322. uint32_t len = (uint32_t) k2.str.len;
  1323. char *str = upb_malloc(a, k2.str.len + sizeof(uint32_t) + 1);
  1324. if (str == NULL) return 0;
  1325. memcpy(str, &len, sizeof(uint32_t));
  1326. memcpy(str + sizeof(uint32_t), k2.str.str, k2.str.len);
  1327. str[sizeof(uint32_t) + k2.str.len] = '\0';
  1328. return (uintptr_t)str;
  1329. }
  1330. static uint32_t strhash(upb_tabkey key) {
  1331. uint32_t len;
  1332. char *str = upb_tabstr(key, &len);
  1333. return upb_murmur_hash2(str, len, 0);
  1334. }
  1335. static bool streql(upb_tabkey k1, lookupkey_t k2) {
  1336. uint32_t len;
  1337. char *str = upb_tabstr(k1, &len);
  1338. return len == k2.str.len && memcmp(str, k2.str.str, len) == 0;
  1339. }
  1340. bool upb_strtable_init2(upb_strtable *t, upb_ctype_t ctype, upb_alloc *a) {
  1341. return init(&t->t, ctype, 2, a);
  1342. }
  1343. void upb_strtable_uninit2(upb_strtable *t, upb_alloc *a) {
  1344. size_t i;
  1345. for (i = 0; i < upb_table_size(&t->t); i++)
  1346. upb_free(a, (void*)t->t.entries[i].key);
  1347. uninit(&t->t, a);
  1348. }
  1349. bool upb_strtable_resize(upb_strtable *t, size_t size_lg2, upb_alloc *a) {
  1350. upb_strtable new_table;
  1351. upb_strtable_iter i;
  1352. upb_check_alloc(&t->t, a);
  1353. if (!init(&new_table.t, t->t.ctype, size_lg2, a))
  1354. return false;
  1355. upb_strtable_begin(&i, t);
  1356. for ( ; !upb_strtable_done(&i); upb_strtable_next(&i)) {
  1357. upb_strtable_insert3(
  1358. &new_table,
  1359. upb_strtable_iter_key(&i),
  1360. upb_strtable_iter_keylength(&i),
  1361. upb_strtable_iter_value(&i),
  1362. a);
  1363. }
  1364. upb_strtable_uninit2(t, a);
  1365. *t = new_table;
  1366. return true;
  1367. }
  1368. bool upb_strtable_insert3(upb_strtable *t, const char *k, size_t len,
  1369. upb_value v, upb_alloc *a) {
  1370. lookupkey_t key;
  1371. upb_tabkey tabkey;
  1372. uint32_t hash;
  1373. upb_check_alloc(&t->t, a);
  1374. if (isfull(&t->t)) {
  1375. /* Need to resize. New table of double the size, add old elements to it. */
  1376. if (!upb_strtable_resize(t, t->t.size_lg2 + 1, a)) {
  1377. return false;
  1378. }
  1379. }
  1380. key = strkey2(k, len);
  1381. tabkey = strcopy(key, a);
  1382. if (tabkey == 0) return false;
  1383. hash = upb_murmur_hash2(key.str.str, key.str.len, 0);
  1384. insert(&t->t, key, tabkey, v, hash, &strhash, &streql);
  1385. return true;
  1386. }
  1387. bool upb_strtable_lookup2(const upb_strtable *t, const char *key, size_t len,
  1388. upb_value *v) {
  1389. uint32_t hash = upb_murmur_hash2(key, len, 0);
  1390. return lookup(&t->t, strkey2(key, len), v, hash, &streql);
  1391. }
  1392. bool upb_strtable_remove3(upb_strtable *t, const char *key, size_t len,
  1393. upb_value *val, upb_alloc *alloc) {
  1394. uint32_t hash = upb_murmur_hash2(key, len, 0);
  1395. upb_tabkey tabkey;
  1396. if (rm(&t->t, strkey2(key, len), val, &tabkey, hash, &streql)) {
  1397. upb_free(alloc, (void*)tabkey);
  1398. return true;
  1399. } else {
  1400. return false;
  1401. }
  1402. }
  1403. /* Iteration */
  1404. static const upb_tabent *str_tabent(const upb_strtable_iter *i) {
  1405. return &i->t->t.entries[i->index];
  1406. }
  1407. void upb_strtable_begin(upb_strtable_iter *i, const upb_strtable *t) {
  1408. i->t = t;
  1409. i->index = begin(&t->t);
  1410. }
  1411. void upb_strtable_next(upb_strtable_iter *i) {
  1412. i->index = next(&i->t->t, i->index);
  1413. }
  1414. bool upb_strtable_done(const upb_strtable_iter *i) {
  1415. if (!i->t) return true;
  1416. return i->index >= upb_table_size(&i->t->t) ||
  1417. upb_tabent_isempty(str_tabent(i));
  1418. }
  1419. const char *upb_strtable_iter_key(const upb_strtable_iter *i) {
  1420. UPB_ASSERT(!upb_strtable_done(i));
  1421. return upb_tabstr(str_tabent(i)->key, NULL);
  1422. }
  1423. size_t upb_strtable_iter_keylength(const upb_strtable_iter *i) {
  1424. uint32_t len;
  1425. UPB_ASSERT(!upb_strtable_done(i));
  1426. upb_tabstr(str_tabent(i)->key, &len);
  1427. return len;
  1428. }
  1429. upb_value upb_strtable_iter_value(const upb_strtable_iter *i) {
  1430. UPB_ASSERT(!upb_strtable_done(i));
  1431. return _upb_value_val(str_tabent(i)->val.val, i->t->t.ctype);
  1432. }
  1433. void upb_strtable_iter_setdone(upb_strtable_iter *i) {
  1434. i->t = NULL;
  1435. i->index = SIZE_MAX;
  1436. }
  1437. bool upb_strtable_iter_isequal(const upb_strtable_iter *i1,
  1438. const upb_strtable_iter *i2) {
  1439. if (upb_strtable_done(i1) && upb_strtable_done(i2))
  1440. return true;
  1441. return i1->t == i2->t && i1->index == i2->index;
  1442. }
  1443. /* upb_inttable ***************************************************************/
  1444. /* For inttables we use a hybrid structure where small keys are kept in an
  1445. * array and large keys are put in the hash table. */
  1446. static uint32_t inthash(upb_tabkey key) { return upb_inthash(key); }
  1447. static bool inteql(upb_tabkey k1, lookupkey_t k2) {
  1448. return k1 == k2.num;
  1449. }
  1450. static upb_tabval *mutable_array(upb_inttable *t) {
  1451. return (upb_tabval*)t->array;
  1452. }
  1453. static upb_tabval *inttable_val(upb_inttable *t, uintptr_t key) {
  1454. if (key < t->array_size) {
  1455. return upb_arrhas(t->array[key]) ? &(mutable_array(t)[key]) : NULL;
  1456. } else {
  1457. upb_tabent *e =
  1458. findentry_mutable(&t->t, intkey(key), upb_inthash(key), &inteql);
  1459. return e ? &e->val : NULL;
  1460. }
  1461. }
  1462. static const upb_tabval *inttable_val_const(const upb_inttable *t,
  1463. uintptr_t key) {
  1464. return inttable_val((upb_inttable*)t, key);
  1465. }
  1466. size_t upb_inttable_count(const upb_inttable *t) {
  1467. return t->t.count + t->array_count;
  1468. }
  1469. static void check(upb_inttable *t) {
  1470. UPB_UNUSED(t);
  1471. #if defined(UPB_DEBUG_TABLE) && !defined(NDEBUG)
  1472. {
  1473. /* This check is very expensive (makes inserts/deletes O(N)). */
  1474. size_t count = 0;
  1475. upb_inttable_iter i;
  1476. upb_inttable_begin(&i, t);
  1477. for(; !upb_inttable_done(&i); upb_inttable_next(&i), count++) {
  1478. UPB_ASSERT(upb_inttable_lookup(t, upb_inttable_iter_key(&i), NULL));
  1479. }
  1480. UPB_ASSERT(count == upb_inttable_count(t));
  1481. }
  1482. #endif
  1483. }
  1484. bool upb_inttable_sizedinit(upb_inttable *t, upb_ctype_t ctype,
  1485. size_t asize, int hsize_lg2, upb_alloc *a) {
  1486. size_t array_bytes;
  1487. if (!init(&t->t, ctype, hsize_lg2, a)) return false;
  1488. /* Always make the array part at least 1 long, so that we know key 0
  1489. * won't be in the hash part, which simplifies things. */
  1490. t->array_size = UPB_MAX(1, asize);
  1491. t->array_count = 0;
  1492. array_bytes = t->array_size * sizeof(upb_value);
  1493. t->array = upb_malloc(a, array_bytes);
  1494. if (!t->array) {
  1495. uninit(&t->t, a);
  1496. return false;
  1497. }
  1498. memset(mutable_array(t), 0xff, array_bytes);
  1499. check(t);
  1500. return true;
  1501. }
  1502. bool upb_inttable_init2(upb_inttable *t, upb_ctype_t ctype, upb_alloc *a) {
  1503. return upb_inttable_sizedinit(t, ctype, 0, 4, a);
  1504. }
  1505. void upb_inttable_uninit2(upb_inttable *t, upb_alloc *a) {
  1506. uninit(&t->t, a);
  1507. upb_free(a, mutable_array(t));
  1508. }
  1509. bool upb_inttable_insert2(upb_inttable *t, uintptr_t key, upb_value val,
  1510. upb_alloc *a) {
  1511. upb_tabval tabval;
  1512. tabval.val = val.val;
  1513. UPB_ASSERT(upb_arrhas(tabval)); /* This will reject (uint64_t)-1. Fix this. */
  1514. upb_check_alloc(&t->t, a);
  1515. if (key < t->array_size) {
  1516. UPB_ASSERT(!upb_arrhas(t->array[key]));
  1517. t->array_count++;
  1518. mutable_array(t)[key].val = val.val;
  1519. } else {
  1520. if (isfull(&t->t)) {
  1521. /* Need to resize the hash part, but we re-use the array part. */
  1522. size_t i;
  1523. upb_table new_table;
  1524. if (!init(&new_table, t->t.ctype, t->t.size_lg2 + 1, a)) {
  1525. return false;
  1526. }
  1527. for (i = begin(&t->t); i < upb_table_size(&t->t); i = next(&t->t, i)) {
  1528. const upb_tabent *e = &t->t.entries[i];
  1529. uint32_t hash;
  1530. upb_value v;
  1531. _upb_value_setval(&v, e->val.val, t->t.ctype);
  1532. hash = upb_inthash(e->key);
  1533. insert(&new_table, intkey(e->key), e->key, v, hash, &inthash, &inteql);
  1534. }
  1535. UPB_ASSERT(t->t.count == new_table.count);
  1536. uninit(&t->t, a);
  1537. t->t = new_table;
  1538. }
  1539. insert(&t->t, intkey(key), key, val, upb_inthash(key), &inthash, &inteql);
  1540. }
  1541. check(t);
  1542. return true;
  1543. }
  1544. bool upb_inttable_lookup(const upb_inttable *t, uintptr_t key, upb_value *v) {
  1545. const upb_tabval *table_v = inttable_val_const(t, key);
  1546. if (!table_v) return false;
  1547. if (v) _upb_value_setval(v, table_v->val, t->t.ctype);
  1548. return true;
  1549. }
  1550. bool upb_inttable_replace(upb_inttable *t, uintptr_t key, upb_value val) {
  1551. upb_tabval *table_v = inttable_val(t, key);
  1552. if (!table_v) return false;
  1553. table_v->val = val.val;
  1554. return true;
  1555. }
  1556. bool upb_inttable_remove(upb_inttable *t, uintptr_t key, upb_value *val) {
  1557. bool success;
  1558. if (key < t->array_size) {
  1559. if (upb_arrhas(t->array[key])) {
  1560. upb_tabval empty = UPB_TABVALUE_EMPTY_INIT;
  1561. t->array_count--;
  1562. if (val) {
  1563. _upb_value_setval(val, t->array[key].val, t->t.ctype);
  1564. }
  1565. mutable_array(t)[key] = empty;
  1566. success = true;
  1567. } else {
  1568. success = false;
  1569. }
  1570. } else {
  1571. success = rm(&t->t, intkey(key), val, NULL, upb_inthash(key), &inteql);
  1572. }
  1573. check(t);
  1574. return success;
  1575. }
  1576. bool upb_inttable_push2(upb_inttable *t, upb_value val, upb_alloc *a) {
  1577. upb_check_alloc(&t->t, a);
  1578. return upb_inttable_insert2(t, upb_inttable_count(t), val, a);
  1579. }
  1580. upb_value upb_inttable_pop(upb_inttable *t) {
  1581. upb_value val;
  1582. bool ok = upb_inttable_remove(t, upb_inttable_count(t) - 1, &val);
  1583. UPB_ASSERT(ok);
  1584. return val;
  1585. }
  1586. bool upb_inttable_insertptr2(upb_inttable *t, const void *key, upb_value val,
  1587. upb_alloc *a) {
  1588. upb_check_alloc(&t->t, a);
  1589. return upb_inttable_insert2(t, (uintptr_t)key, val, a);
  1590. }
  1591. bool upb_inttable_lookupptr(const upb_inttable *t, const void *key,
  1592. upb_value *v) {
  1593. return upb_inttable_lookup(t, (uintptr_t)key, v);
  1594. }
  1595. bool upb_inttable_removeptr(upb_inttable *t, const void *key, upb_value *val) {
  1596. return upb_inttable_remove(t, (uintptr_t)key, val);
  1597. }
  1598. void upb_inttable_compact2(upb_inttable *t, upb_alloc *a) {
  1599. /* A power-of-two histogram of the table keys. */
  1600. size_t counts[UPB_MAXARRSIZE + 1] = {0};
  1601. /* The max key in each bucket. */
  1602. uintptr_t max[UPB_MAXARRSIZE + 1] = {0};
  1603. upb_inttable_iter i;
  1604. size_t arr_count;
  1605. int size_lg2;
  1606. upb_inttable new_t;
  1607. upb_check_alloc(&t->t, a);
  1608. upb_inttable_begin(&i, t);
  1609. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  1610. uintptr_t key = upb_inttable_iter_key(&i);
  1611. int bucket = log2ceil(key);
  1612. max[bucket] = UPB_MAX(max[bucket], key);
  1613. counts[bucket]++;
  1614. }
  1615. /* Find the largest power of two that satisfies the MIN_DENSITY
  1616. * definition (while actually having some keys). */
  1617. arr_count = upb_inttable_count(t);
  1618. for (size_lg2 = ARRAY_SIZE(counts) - 1; size_lg2 > 0; size_lg2--) {
  1619. if (counts[size_lg2] == 0) {
  1620. /* We can halve again without losing any entries. */
  1621. continue;
  1622. } else if (arr_count >= (1 << size_lg2) * MIN_DENSITY) {
  1623. break;
  1624. }
  1625. arr_count -= counts[size_lg2];
  1626. }
  1627. UPB_ASSERT(arr_count <= upb_inttable_count(t));
  1628. {
  1629. /* Insert all elements into new, perfectly-sized table. */
  1630. size_t arr_size = max[size_lg2] + 1; /* +1 so arr[max] will fit. */
  1631. size_t hash_count = upb_inttable_count(t) - arr_count;
  1632. size_t hash_size = hash_count ? (hash_count / MAX_LOAD) + 1 : 0;
  1633. int hashsize_lg2 = log2ceil(hash_size);
  1634. upb_inttable_sizedinit(&new_t, t->t.ctype, arr_size, hashsize_lg2, a);
  1635. upb_inttable_begin(&i, t);
  1636. for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  1637. uintptr_t k = upb_inttable_iter_key(&i);
  1638. upb_inttable_insert2(&new_t, k, upb_inttable_iter_value(&i), a);
  1639. }
  1640. UPB_ASSERT(new_t.array_size == arr_size);
  1641. UPB_ASSERT(new_t.t.size_lg2 == hashsize_lg2);
  1642. }
  1643. upb_inttable_uninit2(t, a);
  1644. *t = new_t;
  1645. }
  1646. /* Iteration. */
  1647. static const upb_tabent *int_tabent(const upb_inttable_iter *i) {
  1648. UPB_ASSERT(!i->array_part);
  1649. return &i->t->t.entries[i->index];
  1650. }
  1651. static upb_tabval int_arrent(const upb_inttable_iter *i) {
  1652. UPB_ASSERT(i->array_part);
  1653. return i->t->array[i->index];
  1654. }
  1655. void upb_inttable_begin(upb_inttable_iter *i, const upb_inttable *t) {
  1656. i->t = t;
  1657. i->index = -1;
  1658. i->array_part = true;
  1659. upb_inttable_next(i);
  1660. }
  1661. void upb_inttable_next(upb_inttable_iter *iter) {
  1662. const upb_inttable *t = iter->t;
  1663. if (iter->array_part) {
  1664. while (++iter->index < t->array_size) {
  1665. if (upb_arrhas(int_arrent(iter))) {
  1666. return;
  1667. }
  1668. }
  1669. iter->array_part = false;
  1670. iter->index = begin(&t->t);
  1671. } else {
  1672. iter->index = next(&t->t, iter->index);
  1673. }
  1674. }
  1675. bool upb_inttable_done(const upb_inttable_iter *i) {
  1676. if (!i->t) return true;
  1677. if (i->array_part) {
  1678. return i->index >= i->t->array_size ||
  1679. !upb_arrhas(int_arrent(i));
  1680. } else {
  1681. return i->index >= upb_table_size(&i->t->t) ||
  1682. upb_tabent_isempty(int_tabent(i));
  1683. }
  1684. }
  1685. uintptr_t upb_inttable_iter_key(const upb_inttable_iter *i) {
  1686. UPB_ASSERT(!upb_inttable_done(i));
  1687. return i->array_part ? i->index : int_tabent(i)->key;
  1688. }
  1689. upb_value upb_inttable_iter_value(const upb_inttable_iter *i) {
  1690. UPB_ASSERT(!upb_inttable_done(i));
  1691. return _upb_value_val(
  1692. i->array_part ? i->t->array[i->index].val : int_tabent(i)->val.val,
  1693. i->t->t.ctype);
  1694. }
  1695. void upb_inttable_iter_setdone(upb_inttable_iter *i) {
  1696. i->t = NULL;
  1697. i->index = SIZE_MAX;
  1698. i->array_part = false;
  1699. }
  1700. bool upb_inttable_iter_isequal(const upb_inttable_iter *i1,
  1701. const upb_inttable_iter *i2) {
  1702. if (upb_inttable_done(i1) && upb_inttable_done(i2))
  1703. return true;
  1704. return i1->t == i2->t && i1->index == i2->index &&
  1705. i1->array_part == i2->array_part;
  1706. }
  1707. #if defined(UPB_UNALIGNED_READS_OK) || defined(__s390x__)
  1708. /* -----------------------------------------------------------------------------
  1709. * MurmurHash2, by Austin Appleby (released as public domain).
  1710. * Reformatted and C99-ified by Joshua Haberman.
  1711. * Note - This code makes a few assumptions about how your machine behaves -
  1712. * 1. We can read a 4-byte value from any address without crashing
  1713. * 2. sizeof(int) == 4 (in upb this limitation is removed by using uint32_t
  1714. * And it has a few limitations -
  1715. * 1. It will not work incrementally.
  1716. * 2. It will not produce the same results on little-endian and big-endian
  1717. * machines. */
  1718. uint32_t upb_murmur_hash2(const void *key, size_t len, uint32_t seed) {
  1719. /* 'm' and 'r' are mixing constants generated offline.
  1720. * They're not really 'magic', they just happen to work well. */
  1721. const uint32_t m = 0x5bd1e995;
  1722. const int32_t r = 24;
  1723. /* Initialize the hash to a 'random' value */
  1724. uint32_t h = seed ^ len;
  1725. /* Mix 4 bytes at a time into the hash */
  1726. const uint8_t * data = (const uint8_t *)key;
  1727. while(len >= 4) {
  1728. uint32_t k = *(uint32_t *)data;
  1729. k *= m;
  1730. k ^= k >> r;
  1731. k *= m;
  1732. h *= m;
  1733. h ^= k;
  1734. data += 4;
  1735. len -= 4;
  1736. }
  1737. /* Handle the last few bytes of the input array */
  1738. switch(len) {
  1739. case 3: h ^= data[2] << 16;
  1740. case 2: h ^= data[1] << 8;
  1741. case 1: h ^= data[0]; h *= m;
  1742. };
  1743. /* Do a few final mixes of the hash to ensure the last few
  1744. * bytes are well-incorporated. */
  1745. h ^= h >> 13;
  1746. h *= m;
  1747. h ^= h >> 15;
  1748. return h;
  1749. }
  1750. #else /* !UPB_UNALIGNED_READS_OK */
  1751. /* -----------------------------------------------------------------------------
  1752. * MurmurHashAligned2, by Austin Appleby
  1753. * Same algorithm as MurmurHash2, but only does aligned reads - should be safer
  1754. * on certain platforms.
  1755. * Performance will be lower than MurmurHash2 */
  1756. #define MIX(h,k,m) { k *= m; k ^= k >> r; k *= m; h *= m; h ^= k; }
  1757. uint32_t upb_murmur_hash2(const void * key, size_t len, uint32_t seed) {
  1758. const uint32_t m = 0x5bd1e995;
  1759. const int32_t r = 24;
  1760. const uint8_t * data = (const uint8_t *)key;
  1761. uint32_t h = (uint32_t)(seed ^ len);
  1762. uint8_t align = (uintptr_t)data & 3;
  1763. if(align && (len >= 4)) {
  1764. /* Pre-load the temp registers */
  1765. uint32_t t = 0, d = 0;
  1766. int32_t sl;
  1767. int32_t sr;
  1768. switch(align) {
  1769. case 1: t |= data[2] << 16;
  1770. case 2: t |= data[1] << 8;
  1771. case 3: t |= data[0];
  1772. }
  1773. t <<= (8 * align);
  1774. data += 4-align;
  1775. len -= 4-align;
  1776. sl = 8 * (4-align);
  1777. sr = 8 * align;
  1778. /* Mix */
  1779. while(len >= 4) {
  1780. uint32_t k;
  1781. d = *(uint32_t *)data;
  1782. t = (t >> sr) | (d << sl);
  1783. k = t;
  1784. MIX(h,k,m);
  1785. t = d;
  1786. data += 4;
  1787. len -= 4;
  1788. }
  1789. /* Handle leftover data in temp registers */
  1790. d = 0;
  1791. if(len >= align) {
  1792. uint32_t k;
  1793. switch(align) {
  1794. case 3: d |= data[2] << 16;
  1795. case 2: d |= data[1] << 8;
  1796. case 1: d |= data[0];
  1797. }
  1798. k = (t >> sr) | (d << sl);
  1799. MIX(h,k,m);
  1800. data += align;
  1801. len -= align;
  1802. /* ----------
  1803. * Handle tail bytes */
  1804. switch(len) {
  1805. case 3: h ^= data[2] << 16;
  1806. case 2: h ^= data[1] << 8;
  1807. case 1: h ^= data[0]; h *= m;
  1808. };
  1809. } else {
  1810. switch(len) {
  1811. case 3: d |= data[2] << 16;
  1812. case 2: d |= data[1] << 8;
  1813. case 1: d |= data[0];
  1814. case 0: h ^= (t >> sr) | (d << sl); h *= m;
  1815. }
  1816. }
  1817. h ^= h >> 13;
  1818. h *= m;
  1819. h ^= h >> 15;
  1820. return h;
  1821. } else {
  1822. while(len >= 4) {
  1823. uint32_t k = *(uint32_t *)data;
  1824. MIX(h,k,m);
  1825. data += 4;
  1826. len -= 4;
  1827. }
  1828. /* ----------
  1829. * Handle tail bytes */
  1830. switch(len) {
  1831. case 3: h ^= data[2] << 16;
  1832. case 2: h ^= data[1] << 8;
  1833. case 1: h ^= data[0]; h *= m;
  1834. };
  1835. h ^= h >> 13;
  1836. h *= m;
  1837. h ^= h >> 15;
  1838. return h;
  1839. }
  1840. }
  1841. #undef MIX
  1842. #endif /* UPB_UNALIGNED_READS_OK */
  1843. #include <errno.h>
  1844. #include <stdarg.h>
  1845. #include <stddef.h>
  1846. #include <stdint.h>
  1847. #include <stdio.h>
  1848. #include <stdlib.h>
  1849. #include <string.h>
  1850. /* Guarantee null-termination and provide ellipsis truncation.
  1851. * It may be tempting to "optimize" this by initializing these final
  1852. * four bytes up-front and then being careful never to overwrite them,
  1853. * this is safer and simpler. */
  1854. static void nullz(upb_status *status) {
  1855. const char *ellipsis = "...";
  1856. size_t len = strlen(ellipsis);
  1857. UPB_ASSERT(sizeof(status->msg) > len);
  1858. memcpy(status->msg + sizeof(status->msg) - len, ellipsis, len);
  1859. }
  1860. /* upb_status *****************************************************************/
  1861. void upb_status_clear(upb_status *status) {
  1862. if (!status) return;
  1863. status->ok = true;
  1864. status->msg[0] = '\0';
  1865. }
  1866. bool upb_ok(const upb_status *status) { return status->ok; }
  1867. const char *upb_status_errmsg(const upb_status *status) { return status->msg; }
  1868. void upb_status_seterrmsg(upb_status *status, const char *msg) {
  1869. if (!status) return;
  1870. status->ok = false;
  1871. strncpy(status->msg, msg, sizeof(status->msg));
  1872. nullz(status);
  1873. }
  1874. void upb_status_seterrf(upb_status *status, const char *fmt, ...) {
  1875. va_list args;
  1876. va_start(args, fmt);
  1877. upb_status_vseterrf(status, fmt, args);
  1878. va_end(args);
  1879. }
  1880. void upb_status_vseterrf(upb_status *status, const char *fmt, va_list args) {
  1881. if (!status) return;
  1882. status->ok = false;
  1883. _upb_vsnprintf(status->msg, sizeof(status->msg), fmt, args);
  1884. nullz(status);
  1885. }
  1886. /* upb_alloc ******************************************************************/
  1887. static void *upb_global_allocfunc(upb_alloc *alloc, void *ptr, size_t oldsize,
  1888. size_t size) {
  1889. UPB_UNUSED(alloc);
  1890. UPB_UNUSED(oldsize);
  1891. if (size == 0) {
  1892. free(ptr);
  1893. return NULL;
  1894. } else {
  1895. return realloc(ptr, size);
  1896. }
  1897. }
  1898. upb_alloc upb_alloc_global = {&upb_global_allocfunc};
  1899. /* upb_arena ******************************************************************/
  1900. /* Be conservative and choose 16 in case anyone is using SSE. */
  1901. static const size_t maxalign = 16;
  1902. static size_t align_up_max(size_t size) {
  1903. return ((size + maxalign - 1) / maxalign) * maxalign;
  1904. }
  1905. struct upb_arena {
  1906. /* We implement the allocator interface.
  1907. * This must be the first member of upb_arena! */
  1908. upb_alloc alloc;
  1909. /* Allocator to allocate arena blocks. We are responsible for freeing these
  1910. * when we are destroyed. */
  1911. upb_alloc *block_alloc;
  1912. size_t bytes_allocated;
  1913. size_t next_block_size;
  1914. size_t max_block_size;
  1915. /* Linked list of blocks. Points to an arena_block, defined in env.c */
  1916. void *block_head;
  1917. /* Cleanup entries. Pointer to a cleanup_ent, defined in env.c */
  1918. void *cleanup_head;
  1919. };
  1920. typedef struct mem_block {
  1921. struct mem_block *next;
  1922. size_t size;
  1923. size_t used;
  1924. bool owned;
  1925. /* Data follows. */
  1926. } mem_block;
  1927. typedef struct cleanup_ent {
  1928. struct cleanup_ent *next;
  1929. upb_cleanup_func *cleanup;
  1930. void *ud;
  1931. } cleanup_ent;
  1932. static void upb_arena_addblock(upb_arena *a, void *ptr, size_t size,
  1933. bool owned) {
  1934. mem_block *block = ptr;
  1935. block->next = a->block_head;
  1936. block->size = size;
  1937. block->used = align_up_max(sizeof(mem_block));
  1938. block->owned = owned;
  1939. a->block_head = block;
  1940. /* TODO(haberman): ASAN poison. */
  1941. }
  1942. static mem_block *upb_arena_allocblock(upb_arena *a, size_t size) {
  1943. size_t block_size = UPB_MAX(size, a->next_block_size) + sizeof(mem_block);
  1944. mem_block *block = upb_malloc(a->block_alloc, block_size);
  1945. if (!block) {
  1946. return NULL;
  1947. }
  1948. upb_arena_addblock(a, block, block_size, true);
  1949. a->next_block_size = UPB_MIN(block_size * 2, a->max_block_size);
  1950. return block;
  1951. }
  1952. static void *upb_arena_doalloc(upb_alloc *alloc, void *ptr, size_t oldsize,
  1953. size_t size) {
  1954. upb_arena *a = (upb_arena*)alloc; /* upb_alloc is initial member. */
  1955. mem_block *block = a->block_head;
  1956. void *ret;
  1957. if (size == 0) {
  1958. return NULL; /* We are an arena, don't need individual frees. */
  1959. }
  1960. size = align_up_max(size);
  1961. /* TODO(haberman): special-case if this is a realloc of the last alloc? */
  1962. if (!block || block->size - block->used < size) {
  1963. /* Slow path: have to allocate a new block. */
  1964. block = upb_arena_allocblock(a, size);
  1965. if (!block) {
  1966. return NULL; /* Out of memory. */
  1967. }
  1968. }
  1969. ret = (char*)block + block->used;
  1970. block->used += size;
  1971. if (oldsize > 0) {
  1972. memcpy(ret, ptr, oldsize); /* Preserve existing data. */
  1973. }
  1974. /* TODO(haberman): ASAN unpoison. */
  1975. a->bytes_allocated += size;
  1976. return ret;
  1977. }
  1978. /* Public Arena API ***********************************************************/
  1979. #define upb_alignof(type) offsetof (struct { char c; type member; }, member)
  1980. upb_arena *upb_arena_init(void *mem, size_t n, upb_alloc *alloc) {
  1981. const size_t first_block_overhead = sizeof(upb_arena) + sizeof(mem_block);
  1982. upb_arena *a;
  1983. bool owned = false;
  1984. /* Round block size down to alignof(*a) since we will allocate the arena
  1985. * itself at the end. */
  1986. n &= ~(upb_alignof(upb_arena) - 1);
  1987. if (n < first_block_overhead) {
  1988. /* We need to malloc the initial block. */
  1989. n = first_block_overhead + 256;
  1990. owned = true;
  1991. if (!alloc || !(mem = upb_malloc(alloc, n))) {
  1992. return NULL;
  1993. }
  1994. }
  1995. a = (void*)((char*)mem + n - sizeof(*a));
  1996. n -= sizeof(*a);
  1997. a->alloc.func = &upb_arena_doalloc;
  1998. a->block_alloc = &upb_alloc_global;
  1999. a->bytes_allocated = 0;
  2000. a->next_block_size = 256;
  2001. a->max_block_size = 16384;
  2002. a->cleanup_head = NULL;
  2003. a->block_head = NULL;
  2004. a->block_alloc = alloc;
  2005. upb_arena_addblock(a, mem, n, owned);
  2006. return a;
  2007. }
  2008. #undef upb_alignof
  2009. void upb_arena_free(upb_arena *a) {
  2010. cleanup_ent *ent = a->cleanup_head;
  2011. mem_block *block = a->block_head;
  2012. while (ent) {
  2013. ent->cleanup(ent->ud);
  2014. ent = ent->next;
  2015. }
  2016. /* Must do this after running cleanup functions, because this will delete
  2017. * the memory we store our cleanup entries in! */
  2018. while (block) {
  2019. /* Load first since we are deleting block. */
  2020. mem_block *next = block->next;
  2021. if (block->owned) {
  2022. upb_free(a->block_alloc, block);
  2023. }
  2024. block = next;
  2025. }
  2026. }
  2027. bool upb_arena_addcleanup(upb_arena *a, void *ud, upb_cleanup_func *func) {
  2028. cleanup_ent *ent = upb_malloc(&a->alloc, sizeof(cleanup_ent));
  2029. if (!ent) {
  2030. return false; /* Out of memory. */
  2031. }
  2032. ent->cleanup = func;
  2033. ent->ud = ud;
  2034. ent->next = a->cleanup_head;
  2035. a->cleanup_head = ent;
  2036. return true;
  2037. }
  2038. size_t upb_arena_bytesallocated(const upb_arena *a) {
  2039. return a->bytes_allocated;
  2040. }
  2041. /* This file was generated by upbc (the upb compiler) from the input
  2042. * file:
  2043. *
  2044. * google/protobuf/descriptor.proto
  2045. *
  2046. * Do not edit -- your changes will be discarded when the file is
  2047. * regenerated. */
  2048. #include <stddef.h>
  2049. static const upb_msglayout *const google_protobuf_FileDescriptorSet_submsgs[1] = {
  2050. &google_protobuf_FileDescriptorProto_msginit,
  2051. };
  2052. static const upb_msglayout_field google_protobuf_FileDescriptorSet__fields[1] = {
  2053. {1, UPB_SIZE(0, 0), 0, 0, 11, 3},
  2054. };
  2055. const upb_msglayout google_protobuf_FileDescriptorSet_msginit = {
  2056. &google_protobuf_FileDescriptorSet_submsgs[0],
  2057. &google_protobuf_FileDescriptorSet__fields[0],
  2058. UPB_SIZE(4, 8), 1, false,
  2059. };
  2060. static const upb_msglayout *const google_protobuf_FileDescriptorProto_submsgs[6] = {
  2061. &google_protobuf_DescriptorProto_msginit,
  2062. &google_protobuf_EnumDescriptorProto_msginit,
  2063. &google_protobuf_FieldDescriptorProto_msginit,
  2064. &google_protobuf_FileOptions_msginit,
  2065. &google_protobuf_ServiceDescriptorProto_msginit,
  2066. &google_protobuf_SourceCodeInfo_msginit,
  2067. };
  2068. static const upb_msglayout_field google_protobuf_FileDescriptorProto__fields[12] = {
  2069. {1, UPB_SIZE(4, 8), 1, 0, 9, 1},
  2070. {2, UPB_SIZE(12, 24), 2, 0, 9, 1},
  2071. {3, UPB_SIZE(36, 72), 0, 0, 9, 3},
  2072. {4, UPB_SIZE(40, 80), 0, 0, 11, 3},
  2073. {5, UPB_SIZE(44, 88), 0, 1, 11, 3},
  2074. {6, UPB_SIZE(48, 96), 0, 4, 11, 3},
  2075. {7, UPB_SIZE(52, 104), 0, 2, 11, 3},
  2076. {8, UPB_SIZE(28, 56), 4, 3, 11, 1},
  2077. {9, UPB_SIZE(32, 64), 5, 5, 11, 1},
  2078. {10, UPB_SIZE(56, 112), 0, 0, 5, 3},
  2079. {11, UPB_SIZE(60, 120), 0, 0, 5, 3},
  2080. {12, UPB_SIZE(20, 40), 3, 0, 9, 1},
  2081. };
  2082. const upb_msglayout google_protobuf_FileDescriptorProto_msginit = {
  2083. &google_protobuf_FileDescriptorProto_submsgs[0],
  2084. &google_protobuf_FileDescriptorProto__fields[0],
  2085. UPB_SIZE(64, 128), 12, false,
  2086. };
  2087. static const upb_msglayout *const google_protobuf_DescriptorProto_submsgs[8] = {
  2088. &google_protobuf_DescriptorProto_msginit,
  2089. &google_protobuf_DescriptorProto_ExtensionRange_msginit,
  2090. &google_protobuf_DescriptorProto_ReservedRange_msginit,
  2091. &google_protobuf_EnumDescriptorProto_msginit,
  2092. &google_protobuf_FieldDescriptorProto_msginit,
  2093. &google_protobuf_MessageOptions_msginit,
  2094. &google_protobuf_OneofDescriptorProto_msginit,
  2095. };
  2096. static const upb_msglayout_field google_protobuf_DescriptorProto__fields[10] = {
  2097. {1, UPB_SIZE(4, 8), 1, 0, 9, 1},
  2098. {2, UPB_SIZE(16, 32), 0, 4, 11, 3},
  2099. {3, UPB_SIZE(20, 40), 0, 0, 11, 3},
  2100. {4, UPB_SIZE(24, 48), 0, 3, 11, 3},
  2101. {5, UPB_SIZE(28, 56), 0, 1, 11, 3},
  2102. {6, UPB_SIZE(32, 64), 0, 4, 11, 3},
  2103. {7, UPB_SIZE(12, 24), 2, 5, 11, 1},
  2104. {8, UPB_SIZE(36, 72), 0, 6, 11, 3},
  2105. {9, UPB_SIZE(40, 80), 0, 2, 11, 3},
  2106. {10, UPB_SIZE(44, 88), 0, 0, 9, 3},
  2107. };
  2108. const upb_msglayout google_protobuf_DescriptorProto_msginit = {
  2109. &google_protobuf_DescriptorProto_submsgs[0],
  2110. &google_protobuf_DescriptorProto__fields[0],
  2111. UPB_SIZE(48, 96), 10, false,
  2112. };
  2113. static const upb_msglayout *const google_protobuf_DescriptorProto_ExtensionRange_submsgs[1] = {
  2114. &google_protobuf_ExtensionRangeOptions_msginit,
  2115. };
  2116. static const upb_msglayout_field google_protobuf_DescriptorProto_ExtensionRange__fields[3] = {
  2117. {1, UPB_SIZE(4, 4), 1, 0, 5, 1},
  2118. {2, UPB_SIZE(8, 8), 2, 0, 5, 1},
  2119. {3, UPB_SIZE(12, 16), 3, 0, 11, 1},
  2120. };
  2121. const upb_msglayout google_protobuf_DescriptorProto_ExtensionRange_msginit = {
  2122. &google_protobuf_DescriptorProto_ExtensionRange_submsgs[0],
  2123. &google_protobuf_DescriptorProto_ExtensionRange__fields[0],
  2124. UPB_SIZE(16, 24), 3, false,
  2125. };
  2126. static const upb_msglayout_field google_protobuf_DescriptorProto_ReservedRange__fields[2] = {
  2127. {1, UPB_SIZE(4, 4), 1, 0, 5, 1},
  2128. {2, UPB_SIZE(8, 8), 2, 0, 5, 1},
  2129. };
  2130. const upb_msglayout google_protobuf_DescriptorProto_ReservedRange_msginit = {
  2131. NULL,
  2132. &google_protobuf_DescriptorProto_ReservedRange__fields[0],
  2133. UPB_SIZE(12, 12), 2, false,
  2134. };
  2135. static const upb_msglayout *const google_protobuf_ExtensionRangeOptions_submsgs[1] = {
  2136. &google_protobuf_UninterpretedOption_msginit,
  2137. };
  2138. static const upb_msglayout_field google_protobuf_ExtensionRangeOptions__fields[1] = {
  2139. {999, UPB_SIZE(0, 0), 0, 0, 11, 3},
  2140. };
  2141. const upb_msglayout google_protobuf_ExtensionRangeOptions_msginit = {
  2142. &google_protobuf_ExtensionRangeOptions_submsgs[0],
  2143. &google_protobuf_ExtensionRangeOptions__fields[0],
  2144. UPB_SIZE(4, 8), 1, false,
  2145. };
  2146. static const upb_msglayout *const google_protobuf_FieldDescriptorProto_submsgs[1] = {
  2147. &google_protobuf_FieldOptions_msginit,
  2148. };
  2149. static const upb_msglayout_field google_protobuf_FieldDescriptorProto__fields[10] = {
  2150. {1, UPB_SIZE(32, 32), 5, 0, 9, 1},
  2151. {2, UPB_SIZE(40, 48), 6, 0, 9, 1},
  2152. {3, UPB_SIZE(24, 24), 3, 0, 5, 1},
  2153. {4, UPB_SIZE(8, 8), 1, 0, 14, 1},
  2154. {5, UPB_SIZE(16, 16), 2, 0, 14, 1},
  2155. {6, UPB_SIZE(48, 64), 7, 0, 9, 1},
  2156. {7, UPB_SIZE(56, 80), 8, 0, 9, 1},
  2157. {8, UPB_SIZE(72, 112), 10, 0, 11, 1},
  2158. {9, UPB_SIZE(28, 28), 4, 0, 5, 1},
  2159. {10, UPB_SIZE(64, 96), 9, 0, 9, 1},
  2160. };
  2161. const upb_msglayout google_protobuf_FieldDescriptorProto_msginit = {
  2162. &google_protobuf_FieldDescriptorProto_submsgs[0],
  2163. &google_protobuf_FieldDescriptorProto__fields[0],
  2164. UPB_SIZE(80, 128), 10, false,
  2165. };
  2166. static const upb_msglayout *const google_protobuf_OneofDescriptorProto_submsgs[1] = {
  2167. &google_protobuf_OneofOptions_msginit,
  2168. };
  2169. static const upb_msglayout_field google_protobuf_OneofDescriptorProto__fields[2] = {
  2170. {1, UPB_SIZE(4, 8), 1, 0, 9, 1},
  2171. {2, UPB_SIZE(12, 24), 2, 0, 11, 1},
  2172. };
  2173. const upb_msglayout google_protobuf_OneofDescriptorProto_msginit = {
  2174. &google_protobuf_OneofDescriptorProto_submsgs[0],
  2175. &google_protobuf_OneofDescriptorProto__fields[0],
  2176. UPB_SIZE(16, 32), 2, false,
  2177. };
  2178. static const upb_msglayout *const google_protobuf_EnumDescriptorProto_submsgs[3] = {
  2179. &google_protobuf_EnumDescriptorProto_EnumReservedRange_msginit,
  2180. &google_protobuf_EnumOptions_msginit,
  2181. &google_protobuf_EnumValueDescriptorProto_msginit,
  2182. };
  2183. static const upb_msglayout_field google_protobuf_EnumDescriptorProto__fields[5] = {
  2184. {1, UPB_SIZE(4, 8), 1, 0, 9, 1},
  2185. {2, UPB_SIZE(16, 32), 0, 2, 11, 3},
  2186. {3, UPB_SIZE(12, 24), 2, 1, 11, 1},
  2187. {4, UPB_SIZE(20, 40), 0, 0, 11, 3},
  2188. {5, UPB_SIZE(24, 48), 0, 0, 9, 3},
  2189. };
  2190. const upb_msglayout google_protobuf_EnumDescriptorProto_msginit = {
  2191. &google_protobuf_EnumDescriptorProto_submsgs[0],
  2192. &google_protobuf_EnumDescriptorProto__fields[0],
  2193. UPB_SIZE(32, 64), 5, false,
  2194. };
  2195. static const upb_msglayout_field google_protobuf_EnumDescriptorProto_EnumReservedRange__fields[2] = {
  2196. {1, UPB_SIZE(4, 4), 1, 0, 5, 1},
  2197. {2, UPB_SIZE(8, 8), 2, 0, 5, 1},
  2198. };
  2199. const upb_msglayout google_protobuf_EnumDescriptorProto_EnumReservedRange_msginit = {
  2200. NULL,
  2201. &google_protobuf_EnumDescriptorProto_EnumReservedRange__fields[0],
  2202. UPB_SIZE(12, 12), 2, false,
  2203. };
  2204. static const upb_msglayout *const google_protobuf_EnumValueDescriptorProto_submsgs[1] = {
  2205. &google_protobuf_EnumValueOptions_msginit,
  2206. };
  2207. static const upb_msglayout_field google_protobuf_EnumValueDescriptorProto__fields[3] = {
  2208. {1, UPB_SIZE(8, 8), 2, 0, 9, 1},
  2209. {2, UPB_SIZE(4, 4), 1, 0, 5, 1},
  2210. {3, UPB_SIZE(16, 24), 3, 0, 11, 1},
  2211. };
  2212. const upb_msglayout google_protobuf_EnumValueDescriptorProto_msginit = {
  2213. &google_protobuf_EnumValueDescriptorProto_submsgs[0],
  2214. &google_protobuf_EnumValueDescriptorProto__fields[0],
  2215. UPB_SIZE(24, 32), 3, false,
  2216. };
  2217. static const upb_msglayout *const google_protobuf_ServiceDescriptorProto_submsgs[2] = {
  2218. &google_protobuf_MethodDescriptorProto_msginit,
  2219. &google_protobuf_ServiceOptions_msginit,
  2220. };
  2221. static const upb_msglayout_field google_protobuf_ServiceDescriptorProto__fields[3] = {
  2222. {1, UPB_SIZE(4, 8), 1, 0, 9, 1},
  2223. {2, UPB_SIZE(16, 32), 0, 0, 11, 3},
  2224. {3, UPB_SIZE(12, 24), 2, 1, 11, 1},
  2225. };
  2226. const upb_msglayout google_protobuf_ServiceDescriptorProto_msginit = {
  2227. &google_protobuf_ServiceDescriptorProto_submsgs[0],
  2228. &google_protobuf_ServiceDescriptorProto__fields[0],
  2229. UPB_SIZE(24, 48), 3, false,
  2230. };
  2231. static const upb_msglayout *const google_protobuf_MethodDescriptorProto_submsgs[1] = {
  2232. &google_protobuf_MethodOptions_msginit,
  2233. };
  2234. static const upb_msglayout_field google_protobuf_MethodDescriptorProto__fields[6] = {
  2235. {1, UPB_SIZE(4, 8), 3, 0, 9, 1},
  2236. {2, UPB_SIZE(12, 24), 4, 0, 9, 1},
  2237. {3, UPB_SIZE(20, 40), 5, 0, 9, 1},
  2238. {4, UPB_SIZE(28, 56), 6, 0, 11, 1},
  2239. {5, UPB_SIZE(1, 1), 1, 0, 8, 1},
  2240. {6, UPB_SIZE(2, 2), 2, 0, 8, 1},
  2241. };
  2242. const upb_msglayout google_protobuf_MethodDescriptorProto_msginit = {
  2243. &google_protobuf_MethodDescriptorProto_submsgs[0],
  2244. &google_protobuf_MethodDescriptorProto__fields[0],
  2245. UPB_SIZE(32, 64), 6, false,
  2246. };
  2247. static const upb_msglayout *const google_protobuf_FileOptions_submsgs[1] = {
  2248. &google_protobuf_UninterpretedOption_msginit,
  2249. };
  2250. static const upb_msglayout_field google_protobuf_FileOptions__fields[21] = {
  2251. {1, UPB_SIZE(28, 32), 11, 0, 9, 1},
  2252. {8, UPB_SIZE(36, 48), 12, 0, 9, 1},
  2253. {9, UPB_SIZE(8, 8), 1, 0, 14, 1},
  2254. {10, UPB_SIZE(16, 16), 2, 0, 8, 1},
  2255. {11, UPB_SIZE(44, 64), 13, 0, 9, 1},
  2256. {16, UPB_SIZE(17, 17), 3, 0, 8, 1},
  2257. {17, UPB_SIZE(18, 18), 4, 0, 8, 1},
  2258. {18, UPB_SIZE(19, 19), 5, 0, 8, 1},
  2259. {20, UPB_SIZE(20, 20), 6, 0, 8, 1},
  2260. {23, UPB_SIZE(21, 21), 7, 0, 8, 1},
  2261. {27, UPB_SIZE(22, 22), 8, 0, 8, 1},
  2262. {31, UPB_SIZE(23, 23), 9, 0, 8, 1},
  2263. {36, UPB_SIZE(52, 80), 14, 0, 9, 1},
  2264. {37, UPB_SIZE(60, 96), 15, 0, 9, 1},
  2265. {39, UPB_SIZE(68, 112), 16, 0, 9, 1},
  2266. {40, UPB_SIZE(76, 128), 17, 0, 9, 1},
  2267. {41, UPB_SIZE(84, 144), 18, 0, 9, 1},
  2268. {42, UPB_SIZE(24, 24), 10, 0, 8, 1},
  2269. {44, UPB_SIZE(92, 160), 19, 0, 9, 1},
  2270. {45, UPB_SIZE(100, 176), 20, 0, 9, 1},
  2271. {999, UPB_SIZE(108, 192), 0, 0, 11, 3},
  2272. };
  2273. const upb_msglayout google_protobuf_FileOptions_msginit = {
  2274. &google_protobuf_FileOptions_submsgs[0],
  2275. &google_protobuf_FileOptions__fields[0],
  2276. UPB_SIZE(112, 208), 21, false,
  2277. };
  2278. static const upb_msglayout *const google_protobuf_MessageOptions_submsgs[1] = {
  2279. &google_protobuf_UninterpretedOption_msginit,
  2280. };
  2281. static const upb_msglayout_field google_protobuf_MessageOptions__fields[5] = {
  2282. {1, UPB_SIZE(1, 1), 1, 0, 8, 1},
  2283. {2, UPB_SIZE(2, 2), 2, 0, 8, 1},
  2284. {3, UPB_SIZE(3, 3), 3, 0, 8, 1},
  2285. {7, UPB_SIZE(4, 4), 4, 0, 8, 1},
  2286. {999, UPB_SIZE(8, 8), 0, 0, 11, 3},
  2287. };
  2288. const upb_msglayout google_protobuf_MessageOptions_msginit = {
  2289. &google_protobuf_MessageOptions_submsgs[0],
  2290. &google_protobuf_MessageOptions__fields[0],
  2291. UPB_SIZE(12, 16), 5, false,
  2292. };
  2293. static const upb_msglayout *const google_protobuf_FieldOptions_submsgs[1] = {
  2294. &google_protobuf_UninterpretedOption_msginit,
  2295. };
  2296. static const upb_msglayout_field google_protobuf_FieldOptions__fields[7] = {
  2297. {1, UPB_SIZE(8, 8), 1, 0, 14, 1},
  2298. {2, UPB_SIZE(24, 24), 3, 0, 8, 1},
  2299. {3, UPB_SIZE(25, 25), 4, 0, 8, 1},
  2300. {5, UPB_SIZE(26, 26), 5, 0, 8, 1},
  2301. {6, UPB_SIZE(16, 16), 2, 0, 14, 1},
  2302. {10, UPB_SIZE(27, 27), 6, 0, 8, 1},
  2303. {999, UPB_SIZE(28, 32), 0, 0, 11, 3},
  2304. };
  2305. const upb_msglayout google_protobuf_FieldOptions_msginit = {
  2306. &google_protobuf_FieldOptions_submsgs[0],
  2307. &google_protobuf_FieldOptions__fields[0],
  2308. UPB_SIZE(32, 40), 7, false,
  2309. };
  2310. static const upb_msglayout *const google_protobuf_OneofOptions_submsgs[1] = {
  2311. &google_protobuf_UninterpretedOption_msginit,
  2312. };
  2313. static const upb_msglayout_field google_protobuf_OneofOptions__fields[1] = {
  2314. {999, UPB_SIZE(0, 0), 0, 0, 11, 3},
  2315. };
  2316. const upb_msglayout google_protobuf_OneofOptions_msginit = {
  2317. &google_protobuf_OneofOptions_submsgs[0],
  2318. &google_protobuf_OneofOptions__fields[0],
  2319. UPB_SIZE(4, 8), 1, false,
  2320. };
  2321. static const upb_msglayout *const google_protobuf_EnumOptions_submsgs[1] = {
  2322. &google_protobuf_UninterpretedOption_msginit,
  2323. };
  2324. static const upb_msglayout_field google_protobuf_EnumOptions__fields[3] = {
  2325. {2, UPB_SIZE(1, 1), 1, 0, 8, 1},
  2326. {3, UPB_SIZE(2, 2), 2, 0, 8, 1},
  2327. {999, UPB_SIZE(4, 8), 0, 0, 11, 3},
  2328. };
  2329. const upb_msglayout google_protobuf_EnumOptions_msginit = {
  2330. &google_protobuf_EnumOptions_submsgs[0],
  2331. &google_protobuf_EnumOptions__fields[0],
  2332. UPB_SIZE(8, 16), 3, false,
  2333. };
  2334. static const upb_msglayout *const google_protobuf_EnumValueOptions_submsgs[1] = {
  2335. &google_protobuf_UninterpretedOption_msginit,
  2336. };
  2337. static const upb_msglayout_field google_protobuf_EnumValueOptions__fields[2] = {
  2338. {1, UPB_SIZE(1, 1), 1, 0, 8, 1},
  2339. {999, UPB_SIZE(4, 8), 0, 0, 11, 3},
  2340. };
  2341. const upb_msglayout google_protobuf_EnumValueOptions_msginit = {
  2342. &google_protobuf_EnumValueOptions_submsgs[0],
  2343. &google_protobuf_EnumValueOptions__fields[0],
  2344. UPB_SIZE(8, 16), 2, false,
  2345. };
  2346. static const upb_msglayout *const google_protobuf_ServiceOptions_submsgs[1] = {
  2347. &google_protobuf_UninterpretedOption_msginit,
  2348. };
  2349. static const upb_msglayout_field google_protobuf_ServiceOptions__fields[2] = {
  2350. {33, UPB_SIZE(1, 1), 1, 0, 8, 1},
  2351. {999, UPB_SIZE(4, 8), 0, 0, 11, 3},
  2352. };
  2353. const upb_msglayout google_protobuf_ServiceOptions_msginit = {
  2354. &google_protobuf_ServiceOptions_submsgs[0],
  2355. &google_protobuf_ServiceOptions__fields[0],
  2356. UPB_SIZE(8, 16), 2, false,
  2357. };
  2358. static const upb_msglayout *const google_protobuf_MethodOptions_submsgs[1] = {
  2359. &google_protobuf_UninterpretedOption_msginit,
  2360. };
  2361. static const upb_msglayout_field google_protobuf_MethodOptions__fields[3] = {
  2362. {33, UPB_SIZE(16, 16), 2, 0, 8, 1},
  2363. {34, UPB_SIZE(8, 8), 1, 0, 14, 1},
  2364. {999, UPB_SIZE(20, 24), 0, 0, 11, 3},
  2365. };
  2366. const upb_msglayout google_protobuf_MethodOptions_msginit = {
  2367. &google_protobuf_MethodOptions_submsgs[0],
  2368. &google_protobuf_MethodOptions__fields[0],
  2369. UPB_SIZE(24, 32), 3, false,
  2370. };
  2371. static const upb_msglayout *const google_protobuf_UninterpretedOption_submsgs[1] = {
  2372. &google_protobuf_UninterpretedOption_NamePart_msginit,
  2373. };
  2374. static const upb_msglayout_field google_protobuf_UninterpretedOption__fields[7] = {
  2375. {2, UPB_SIZE(56, 80), 0, 0, 11, 3},
  2376. {3, UPB_SIZE(32, 32), 4, 0, 9, 1},
  2377. {4, UPB_SIZE(8, 8), 1, 0, 4, 1},
  2378. {5, UPB_SIZE(16, 16), 2, 0, 3, 1},
  2379. {6, UPB_SIZE(24, 24), 3, 0, 1, 1},
  2380. {7, UPB_SIZE(40, 48), 5, 0, 12, 1},
  2381. {8, UPB_SIZE(48, 64), 6, 0, 9, 1},
  2382. };
  2383. const upb_msglayout google_protobuf_UninterpretedOption_msginit = {
  2384. &google_protobuf_UninterpretedOption_submsgs[0],
  2385. &google_protobuf_UninterpretedOption__fields[0],
  2386. UPB_SIZE(64, 96), 7, false,
  2387. };
  2388. static const upb_msglayout_field google_protobuf_UninterpretedOption_NamePart__fields[2] = {
  2389. {1, UPB_SIZE(4, 8), 2, 0, 9, 2},
  2390. {2, UPB_SIZE(1, 1), 1, 0, 8, 2},
  2391. };
  2392. const upb_msglayout google_protobuf_UninterpretedOption_NamePart_msginit = {
  2393. NULL,
  2394. &google_protobuf_UninterpretedOption_NamePart__fields[0],
  2395. UPB_SIZE(16, 32), 2, false,
  2396. };
  2397. static const upb_msglayout *const google_protobuf_SourceCodeInfo_submsgs[1] = {
  2398. &google_protobuf_SourceCodeInfo_Location_msginit,
  2399. };
  2400. static const upb_msglayout_field google_protobuf_SourceCodeInfo__fields[1] = {
  2401. {1, UPB_SIZE(0, 0), 0, 0, 11, 3},
  2402. };
  2403. const upb_msglayout google_protobuf_SourceCodeInfo_msginit = {
  2404. &google_protobuf_SourceCodeInfo_submsgs[0],
  2405. &google_protobuf_SourceCodeInfo__fields[0],
  2406. UPB_SIZE(4, 8), 1, false,
  2407. };
  2408. static const upb_msglayout_field google_protobuf_SourceCodeInfo_Location__fields[5] = {
  2409. {1, UPB_SIZE(20, 40), 0, 0, 5, 3},
  2410. {2, UPB_SIZE(24, 48), 0, 0, 5, 3},
  2411. {3, UPB_SIZE(4, 8), 1, 0, 9, 1},
  2412. {4, UPB_SIZE(12, 24), 2, 0, 9, 1},
  2413. {6, UPB_SIZE(28, 56), 0, 0, 9, 3},
  2414. };
  2415. const upb_msglayout google_protobuf_SourceCodeInfo_Location_msginit = {
  2416. NULL,
  2417. &google_protobuf_SourceCodeInfo_Location__fields[0],
  2418. UPB_SIZE(32, 64), 5, false,
  2419. };
  2420. static const upb_msglayout *const google_protobuf_GeneratedCodeInfo_submsgs[1] = {
  2421. &google_protobuf_GeneratedCodeInfo_Annotation_msginit,
  2422. };
  2423. static const upb_msglayout_field google_protobuf_GeneratedCodeInfo__fields[1] = {
  2424. {1, UPB_SIZE(0, 0), 0, 0, 11, 3},
  2425. };
  2426. const upb_msglayout google_protobuf_GeneratedCodeInfo_msginit = {
  2427. &google_protobuf_GeneratedCodeInfo_submsgs[0],
  2428. &google_protobuf_GeneratedCodeInfo__fields[0],
  2429. UPB_SIZE(4, 8), 1, false,
  2430. };
  2431. static const upb_msglayout_field google_protobuf_GeneratedCodeInfo_Annotation__fields[4] = {
  2432. {1, UPB_SIZE(20, 32), 0, 0, 5, 3},
  2433. {2, UPB_SIZE(12, 16), 3, 0, 9, 1},
  2434. {3, UPB_SIZE(4, 4), 1, 0, 5, 1},
  2435. {4, UPB_SIZE(8, 8), 2, 0, 5, 1},
  2436. };
  2437. const upb_msglayout google_protobuf_GeneratedCodeInfo_Annotation_msginit = {
  2438. NULL,
  2439. &google_protobuf_GeneratedCodeInfo_Annotation__fields[0],
  2440. UPB_SIZE(24, 48), 4, false,
  2441. };
  2442. #include <ctype.h>
  2443. #include <errno.h>
  2444. #include <stdlib.h>
  2445. #include <string.h>
  2446. typedef struct {
  2447. size_t len;
  2448. char str[1]; /* Null-terminated string data follows. */
  2449. } str_t;
  2450. static str_t *newstr(upb_alloc *alloc, const char *data, size_t len) {
  2451. str_t *ret = upb_malloc(alloc, sizeof(*ret) + len);
  2452. if (!ret) return NULL;
  2453. ret->len = len;
  2454. memcpy(ret->str, data, len);
  2455. ret->str[len] = '\0';
  2456. return ret;
  2457. }
  2458. struct upb_fielddef {
  2459. const upb_filedef *file;
  2460. const upb_msgdef *msgdef;
  2461. const char *full_name;
  2462. union {
  2463. int64_t sint;
  2464. uint64_t uint;
  2465. double dbl;
  2466. float flt;
  2467. bool boolean;
  2468. str_t *str;
  2469. } defaultval;
  2470. const upb_oneofdef *oneof;
  2471. union {
  2472. const upb_msgdef *msgdef;
  2473. const upb_enumdef *enumdef;
  2474. const google_protobuf_FieldDescriptorProto *unresolved;
  2475. } sub;
  2476. uint32_t number_;
  2477. uint32_t index_;
  2478. uint32_t selector_base; /* Used to index into a upb::Handlers table. */
  2479. bool is_extension_;
  2480. bool lazy_;
  2481. bool packed_;
  2482. upb_descriptortype_t type_;
  2483. upb_label_t label_;
  2484. };
  2485. struct upb_msgdef {
  2486. const upb_filedef *file;
  2487. const char *full_name;
  2488. uint32_t selector_count;
  2489. uint32_t submsg_field_count;
  2490. /* Tables for looking up fields by number and name. */
  2491. upb_inttable itof;
  2492. upb_strtable ntof;
  2493. const upb_fielddef *fields;
  2494. const upb_oneofdef *oneofs;
  2495. int field_count;
  2496. int oneof_count;
  2497. /* Is this a map-entry message? */
  2498. bool map_entry;
  2499. upb_wellknowntype_t well_known_type;
  2500. /* TODO(haberman): proper extension ranges (there can be multiple). */
  2501. };
  2502. struct upb_enumdef {
  2503. const upb_filedef *file;
  2504. const char *full_name;
  2505. upb_strtable ntoi;
  2506. upb_inttable iton;
  2507. int32_t defaultval;
  2508. };
  2509. struct upb_oneofdef {
  2510. const upb_msgdef *parent;
  2511. const char *full_name;
  2512. uint32_t index;
  2513. upb_strtable ntof;
  2514. upb_inttable itof;
  2515. };
  2516. struct upb_filedef {
  2517. const char *name;
  2518. const char *package;
  2519. const char *phpprefix;
  2520. const char *phpnamespace;
  2521. upb_syntax_t syntax;
  2522. const upb_filedef **deps;
  2523. const upb_msgdef *msgs;
  2524. const upb_enumdef *enums;
  2525. const upb_fielddef *exts;
  2526. int dep_count;
  2527. int msg_count;
  2528. int enum_count;
  2529. int ext_count;
  2530. };
  2531. struct upb_symtab {
  2532. upb_arena *arena;
  2533. upb_strtable syms; /* full_name -> packed def ptr */
  2534. upb_strtable files; /* file_name -> upb_filedef* */
  2535. };
  2536. /* Inside a symtab we store tagged pointers to specific def types. */
  2537. typedef enum {
  2538. UPB_DEFTYPE_MSG = 0,
  2539. UPB_DEFTYPE_ENUM = 1,
  2540. UPB_DEFTYPE_FIELD = 2,
  2541. UPB_DEFTYPE_ONEOF = 3
  2542. } upb_deftype_t;
  2543. static const void *unpack_def(upb_value v, upb_deftype_t type) {
  2544. uintptr_t num = (uintptr_t)upb_value_getconstptr(v);
  2545. return (num & 3) == type ? (const void*)(num & ~3) : NULL;
  2546. }
  2547. static upb_value pack_def(const void *ptr, upb_deftype_t type) {
  2548. uintptr_t num = (uintptr_t)ptr | type;
  2549. return upb_value_constptr((const void*)num);
  2550. }
  2551. /* isalpha() etc. from <ctype.h> are locale-dependent, which we don't want. */
  2552. static bool upb_isbetween(char c, char low, char high) {
  2553. return c >= low && c <= high;
  2554. }
  2555. static bool upb_isletter(char c) {
  2556. return upb_isbetween(c, 'A', 'Z') || upb_isbetween(c, 'a', 'z') || c == '_';
  2557. }
  2558. static bool upb_isalphanum(char c) {
  2559. return upb_isletter(c) || upb_isbetween(c, '0', '9');
  2560. }
  2561. static bool upb_isident(upb_strview name, bool full, upb_status *s) {
  2562. const char *str = name.data;
  2563. size_t len = name.size;
  2564. bool start = true;
  2565. size_t i;
  2566. for (i = 0; i < len; i++) {
  2567. char c = str[i];
  2568. if (c == '.') {
  2569. if (start || !full) {
  2570. upb_status_seterrf(s, "invalid name: unexpected '.' (%s)", str);
  2571. return false;
  2572. }
  2573. start = true;
  2574. } else if (start) {
  2575. if (!upb_isletter(c)) {
  2576. upb_status_seterrf(
  2577. s, "invalid name: path components must start with a letter (%s)",
  2578. str);
  2579. return false;
  2580. }
  2581. start = false;
  2582. } else {
  2583. if (!upb_isalphanum(c)) {
  2584. upb_status_seterrf(s, "invalid name: non-alphanumeric character (%s)",
  2585. str);
  2586. return false;
  2587. }
  2588. }
  2589. }
  2590. return !start;
  2591. }
  2592. static const char *shortdefname(const char *fullname) {
  2593. const char *p;
  2594. if (fullname == NULL) {
  2595. return NULL;
  2596. } else if ((p = strrchr(fullname, '.')) == NULL) {
  2597. /* No '.' in the name, return the full string. */
  2598. return fullname;
  2599. } else {
  2600. /* Return one past the last '.'. */
  2601. return p + 1;
  2602. }
  2603. }
  2604. /* All submessage fields are lower than all other fields.
  2605. * Secondly, fields are increasing in order. */
  2606. uint32_t field_rank(const upb_fielddef *f) {
  2607. uint32_t ret = upb_fielddef_number(f);
  2608. const uint32_t high_bit = 1 << 30;
  2609. UPB_ASSERT(ret < high_bit);
  2610. if (!upb_fielddef_issubmsg(f))
  2611. ret |= high_bit;
  2612. return ret;
  2613. }
  2614. int cmp_fields(const void *p1, const void *p2) {
  2615. const upb_fielddef *f1 = *(upb_fielddef*const*)p1;
  2616. const upb_fielddef *f2 = *(upb_fielddef*const*)p2;
  2617. return field_rank(f1) - field_rank(f2);
  2618. }
  2619. /* A few implementation details of handlers. We put these here to avoid
  2620. * a def -> handlers dependency. */
  2621. #define UPB_STATIC_SELECTOR_COUNT 3 /* Warning: also in upb/handlers.h. */
  2622. static uint32_t upb_handlers_selectorbaseoffset(const upb_fielddef *f) {
  2623. return upb_fielddef_isseq(f) ? 2 : 0;
  2624. }
  2625. static uint32_t upb_handlers_selectorcount(const upb_fielddef *f) {
  2626. uint32_t ret = 1;
  2627. if (upb_fielddef_isseq(f)) ret += 2; /* STARTSEQ/ENDSEQ */
  2628. if (upb_fielddef_isstring(f)) ret += 2; /* [STRING]/STARTSTR/ENDSTR */
  2629. if (upb_fielddef_issubmsg(f)) {
  2630. /* ENDSUBMSG (STARTSUBMSG is at table beginning) */
  2631. ret += 0;
  2632. if (upb_fielddef_lazy(f)) {
  2633. /* STARTSTR/ENDSTR/STRING (for lazy) */
  2634. ret += 3;
  2635. }
  2636. }
  2637. return ret;
  2638. }
  2639. static bool assign_msg_indices(upb_msgdef *m, upb_status *s) {
  2640. /* Sort fields. upb internally relies on UPB_TYPE_MESSAGE fields having the
  2641. * lowest indexes, but we do not publicly guarantee this. */
  2642. upb_msg_field_iter j;
  2643. upb_msg_oneof_iter k;
  2644. int i;
  2645. uint32_t selector;
  2646. int n = upb_msgdef_numfields(m);
  2647. upb_fielddef **fields;
  2648. if (n == 0) {
  2649. m->selector_count = UPB_STATIC_SELECTOR_COUNT;
  2650. m->submsg_field_count = 0;
  2651. return true;
  2652. }
  2653. fields = upb_gmalloc(n * sizeof(*fields));
  2654. if (!fields) {
  2655. upb_status_setoom(s);
  2656. return false;
  2657. }
  2658. m->submsg_field_count = 0;
  2659. for(i = 0, upb_msg_field_begin(&j, m);
  2660. !upb_msg_field_done(&j);
  2661. upb_msg_field_next(&j), i++) {
  2662. upb_fielddef *f = upb_msg_iter_field(&j);
  2663. UPB_ASSERT(f->msgdef == m);
  2664. if (upb_fielddef_issubmsg(f)) {
  2665. m->submsg_field_count++;
  2666. }
  2667. fields[i] = f;
  2668. }
  2669. qsort(fields, n, sizeof(*fields), cmp_fields);
  2670. selector = UPB_STATIC_SELECTOR_COUNT + m->submsg_field_count;
  2671. for (i = 0; i < n; i++) {
  2672. upb_fielddef *f = fields[i];
  2673. f->index_ = i;
  2674. f->selector_base = selector + upb_handlers_selectorbaseoffset(f);
  2675. selector += upb_handlers_selectorcount(f);
  2676. }
  2677. m->selector_count = selector;
  2678. for(upb_msg_oneof_begin(&k, m), i = 0;
  2679. !upb_msg_oneof_done(&k);
  2680. upb_msg_oneof_next(&k), i++) {
  2681. upb_oneofdef *o = (upb_oneofdef*)upb_msg_iter_oneof(&k);
  2682. o->index = i;
  2683. }
  2684. upb_gfree(fields);
  2685. return true;
  2686. }
  2687. static void assign_msg_wellknowntype(upb_msgdef *m) {
  2688. const char *name = upb_msgdef_fullname(m);
  2689. if (name == NULL) {
  2690. m->well_known_type = UPB_WELLKNOWN_UNSPECIFIED;
  2691. return;
  2692. }
  2693. if (!strcmp(name, "google.protobuf.Any")) {
  2694. m->well_known_type = UPB_WELLKNOWN_ANY;
  2695. } else if (!strcmp(name, "google.protobuf.FieldMask")) {
  2696. m->well_known_type = UPB_WELLKNOWN_FIELDMASK;
  2697. } else if (!strcmp(name, "google.protobuf.Duration")) {
  2698. m->well_known_type = UPB_WELLKNOWN_DURATION;
  2699. } else if (!strcmp(name, "google.protobuf.Timestamp")) {
  2700. m->well_known_type = UPB_WELLKNOWN_TIMESTAMP;
  2701. } else if (!strcmp(name, "google.protobuf.DoubleValue")) {
  2702. m->well_known_type = UPB_WELLKNOWN_DOUBLEVALUE;
  2703. } else if (!strcmp(name, "google.protobuf.FloatValue")) {
  2704. m->well_known_type = UPB_WELLKNOWN_FLOATVALUE;
  2705. } else if (!strcmp(name, "google.protobuf.Int64Value")) {
  2706. m->well_known_type = UPB_WELLKNOWN_INT64VALUE;
  2707. } else if (!strcmp(name, "google.protobuf.UInt64Value")) {
  2708. m->well_known_type = UPB_WELLKNOWN_UINT64VALUE;
  2709. } else if (!strcmp(name, "google.protobuf.Int32Value")) {
  2710. m->well_known_type = UPB_WELLKNOWN_INT32VALUE;
  2711. } else if (!strcmp(name, "google.protobuf.UInt32Value")) {
  2712. m->well_known_type = UPB_WELLKNOWN_UINT32VALUE;
  2713. } else if (!strcmp(name, "google.protobuf.BoolValue")) {
  2714. m->well_known_type = UPB_WELLKNOWN_BOOLVALUE;
  2715. } else if (!strcmp(name, "google.protobuf.StringValue")) {
  2716. m->well_known_type = UPB_WELLKNOWN_STRINGVALUE;
  2717. } else if (!strcmp(name, "google.protobuf.BytesValue")) {
  2718. m->well_known_type = UPB_WELLKNOWN_BYTESVALUE;
  2719. } else if (!strcmp(name, "google.protobuf.Value")) {
  2720. m->well_known_type = UPB_WELLKNOWN_VALUE;
  2721. } else if (!strcmp(name, "google.protobuf.ListValue")) {
  2722. m->well_known_type = UPB_WELLKNOWN_LISTVALUE;
  2723. } else if (!strcmp(name, "google.protobuf.Struct")) {
  2724. m->well_known_type = UPB_WELLKNOWN_STRUCT;
  2725. } else {
  2726. m->well_known_type = UPB_WELLKNOWN_UNSPECIFIED;
  2727. }
  2728. }
  2729. /* upb_enumdef ****************************************************************/
  2730. const char *upb_enumdef_fullname(const upb_enumdef *e) {
  2731. return e->full_name;
  2732. }
  2733. const char *upb_enumdef_name(const upb_enumdef *e) {
  2734. return shortdefname(e->full_name);
  2735. }
  2736. const upb_filedef *upb_enumdef_file(const upb_enumdef *e) {
  2737. return e->file;
  2738. }
  2739. int32_t upb_enumdef_default(const upb_enumdef *e) {
  2740. UPB_ASSERT(upb_enumdef_iton(e, e->defaultval));
  2741. return e->defaultval;
  2742. }
  2743. int upb_enumdef_numvals(const upb_enumdef *e) {
  2744. return upb_strtable_count(&e->ntoi);
  2745. }
  2746. void upb_enum_begin(upb_enum_iter *i, const upb_enumdef *e) {
  2747. /* We iterate over the ntoi table, to account for duplicate numbers. */
  2748. upb_strtable_begin(i, &e->ntoi);
  2749. }
  2750. void upb_enum_next(upb_enum_iter *iter) { upb_strtable_next(iter); }
  2751. bool upb_enum_done(upb_enum_iter *iter) { return upb_strtable_done(iter); }
  2752. bool upb_enumdef_ntoi(const upb_enumdef *def, const char *name,
  2753. size_t len, int32_t *num) {
  2754. upb_value v;
  2755. if (!upb_strtable_lookup2(&def->ntoi, name, len, &v)) {
  2756. return false;
  2757. }
  2758. if (num) *num = upb_value_getint32(v);
  2759. return true;
  2760. }
  2761. const char *upb_enumdef_iton(const upb_enumdef *def, int32_t num) {
  2762. upb_value v;
  2763. return upb_inttable_lookup32(&def->iton, num, &v) ?
  2764. upb_value_getcstr(v) : NULL;
  2765. }
  2766. const char *upb_enum_iter_name(upb_enum_iter *iter) {
  2767. return upb_strtable_iter_key(iter);
  2768. }
  2769. int32_t upb_enum_iter_number(upb_enum_iter *iter) {
  2770. return upb_value_getint32(upb_strtable_iter_value(iter));
  2771. }
  2772. /* upb_fielddef ***************************************************************/
  2773. const char *upb_fielddef_fullname(const upb_fielddef *f) {
  2774. return f->full_name;
  2775. }
  2776. upb_fieldtype_t upb_fielddef_type(const upb_fielddef *f) {
  2777. switch (f->type_) {
  2778. case UPB_DESCRIPTOR_TYPE_DOUBLE:
  2779. return UPB_TYPE_DOUBLE;
  2780. case UPB_DESCRIPTOR_TYPE_FLOAT:
  2781. return UPB_TYPE_FLOAT;
  2782. case UPB_DESCRIPTOR_TYPE_INT64:
  2783. case UPB_DESCRIPTOR_TYPE_SINT64:
  2784. case UPB_DESCRIPTOR_TYPE_SFIXED64:
  2785. return UPB_TYPE_INT64;
  2786. case UPB_DESCRIPTOR_TYPE_INT32:
  2787. case UPB_DESCRIPTOR_TYPE_SFIXED32:
  2788. case UPB_DESCRIPTOR_TYPE_SINT32:
  2789. return UPB_TYPE_INT32;
  2790. case UPB_DESCRIPTOR_TYPE_UINT64:
  2791. case UPB_DESCRIPTOR_TYPE_FIXED64:
  2792. return UPB_TYPE_UINT64;
  2793. case UPB_DESCRIPTOR_TYPE_UINT32:
  2794. case UPB_DESCRIPTOR_TYPE_FIXED32:
  2795. return UPB_TYPE_UINT32;
  2796. case UPB_DESCRIPTOR_TYPE_ENUM:
  2797. return UPB_TYPE_ENUM;
  2798. case UPB_DESCRIPTOR_TYPE_BOOL:
  2799. return UPB_TYPE_BOOL;
  2800. case UPB_DESCRIPTOR_TYPE_STRING:
  2801. return UPB_TYPE_STRING;
  2802. case UPB_DESCRIPTOR_TYPE_BYTES:
  2803. return UPB_TYPE_BYTES;
  2804. case UPB_DESCRIPTOR_TYPE_GROUP:
  2805. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  2806. return UPB_TYPE_MESSAGE;
  2807. }
  2808. UPB_UNREACHABLE();
  2809. }
  2810. upb_descriptortype_t upb_fielddef_descriptortype(const upb_fielddef *f) {
  2811. return f->type_;
  2812. }
  2813. uint32_t upb_fielddef_index(const upb_fielddef *f) {
  2814. return f->index_;
  2815. }
  2816. upb_label_t upb_fielddef_label(const upb_fielddef *f) {
  2817. return f->label_;
  2818. }
  2819. uint32_t upb_fielddef_number(const upb_fielddef *f) {
  2820. return f->number_;
  2821. }
  2822. bool upb_fielddef_isextension(const upb_fielddef *f) {
  2823. return f->is_extension_;
  2824. }
  2825. bool upb_fielddef_lazy(const upb_fielddef *f) {
  2826. return f->lazy_;
  2827. }
  2828. bool upb_fielddef_packed(const upb_fielddef *f) {
  2829. return f->packed_;
  2830. }
  2831. const char *upb_fielddef_name(const upb_fielddef *f) {
  2832. return shortdefname(f->full_name);
  2833. }
  2834. uint32_t upb_fielddef_selectorbase(const upb_fielddef *f) {
  2835. return f->selector_base;
  2836. }
  2837. size_t upb_fielddef_getjsonname(const upb_fielddef *f, char *buf, size_t len) {
  2838. const char *name = upb_fielddef_name(f);
  2839. size_t src, dst = 0;
  2840. bool ucase_next = false;
  2841. #define WRITE(byte) \
  2842. ++dst; \
  2843. if (dst < len) buf[dst - 1] = byte; \
  2844. else if (dst == len) buf[dst - 1] = '\0'
  2845. if (!name) {
  2846. WRITE('\0');
  2847. return 0;
  2848. }
  2849. /* Implement the transformation as described in the spec:
  2850. * 1. upper case all letters after an underscore.
  2851. * 2. remove all underscores.
  2852. */
  2853. for (src = 0; name[src]; src++) {
  2854. if (name[src] == '_') {
  2855. ucase_next = true;
  2856. continue;
  2857. }
  2858. if (ucase_next) {
  2859. WRITE(toupper(name[src]));
  2860. ucase_next = false;
  2861. } else {
  2862. WRITE(name[src]);
  2863. }
  2864. }
  2865. WRITE('\0');
  2866. return dst;
  2867. #undef WRITE
  2868. }
  2869. const upb_msgdef *upb_fielddef_containingtype(const upb_fielddef *f) {
  2870. return f->msgdef;
  2871. }
  2872. const upb_oneofdef *upb_fielddef_containingoneof(const upb_fielddef *f) {
  2873. return f->oneof;
  2874. }
  2875. static void chkdefaulttype(const upb_fielddef *f, int ctype) {
  2876. UPB_UNUSED(f);
  2877. UPB_UNUSED(ctype);
  2878. }
  2879. int64_t upb_fielddef_defaultint64(const upb_fielddef *f) {
  2880. chkdefaulttype(f, UPB_TYPE_INT64);
  2881. return f->defaultval.sint;
  2882. }
  2883. int32_t upb_fielddef_defaultint32(const upb_fielddef *f) {
  2884. chkdefaulttype(f, UPB_TYPE_INT32);
  2885. return f->defaultval.sint;
  2886. }
  2887. uint64_t upb_fielddef_defaultuint64(const upb_fielddef *f) {
  2888. chkdefaulttype(f, UPB_TYPE_UINT64);
  2889. return f->defaultval.uint;
  2890. }
  2891. uint32_t upb_fielddef_defaultuint32(const upb_fielddef *f) {
  2892. chkdefaulttype(f, UPB_TYPE_UINT32);
  2893. return f->defaultval.uint;
  2894. }
  2895. bool upb_fielddef_defaultbool(const upb_fielddef *f) {
  2896. chkdefaulttype(f, UPB_TYPE_BOOL);
  2897. return f->defaultval.boolean;
  2898. }
  2899. float upb_fielddef_defaultfloat(const upb_fielddef *f) {
  2900. chkdefaulttype(f, UPB_TYPE_FLOAT);
  2901. return f->defaultval.flt;
  2902. }
  2903. double upb_fielddef_defaultdouble(const upb_fielddef *f) {
  2904. chkdefaulttype(f, UPB_TYPE_DOUBLE);
  2905. return f->defaultval.dbl;
  2906. }
  2907. const char *upb_fielddef_defaultstr(const upb_fielddef *f, size_t *len) {
  2908. str_t *str = f->defaultval.str;
  2909. UPB_ASSERT(upb_fielddef_type(f) == UPB_TYPE_STRING ||
  2910. upb_fielddef_type(f) == UPB_TYPE_BYTES ||
  2911. upb_fielddef_type(f) == UPB_TYPE_ENUM);
  2912. if (str) {
  2913. if (len) *len = str->len;
  2914. return str->str;
  2915. } else {
  2916. if (len) *len = 0;
  2917. return NULL;
  2918. }
  2919. }
  2920. const upb_msgdef *upb_fielddef_msgsubdef(const upb_fielddef *f) {
  2921. UPB_ASSERT(upb_fielddef_type(f) == UPB_TYPE_MESSAGE);
  2922. return f->sub.msgdef;
  2923. }
  2924. const upb_enumdef *upb_fielddef_enumsubdef(const upb_fielddef *f) {
  2925. UPB_ASSERT(upb_fielddef_type(f) == UPB_TYPE_ENUM);
  2926. return f->sub.enumdef;
  2927. }
  2928. bool upb_fielddef_issubmsg(const upb_fielddef *f) {
  2929. return upb_fielddef_type(f) == UPB_TYPE_MESSAGE;
  2930. }
  2931. bool upb_fielddef_isstring(const upb_fielddef *f) {
  2932. return upb_fielddef_type(f) == UPB_TYPE_STRING ||
  2933. upb_fielddef_type(f) == UPB_TYPE_BYTES;
  2934. }
  2935. bool upb_fielddef_isseq(const upb_fielddef *f) {
  2936. return upb_fielddef_label(f) == UPB_LABEL_REPEATED;
  2937. }
  2938. bool upb_fielddef_isprimitive(const upb_fielddef *f) {
  2939. return !upb_fielddef_isstring(f) && !upb_fielddef_issubmsg(f);
  2940. }
  2941. bool upb_fielddef_ismap(const upb_fielddef *f) {
  2942. return upb_fielddef_isseq(f) && upb_fielddef_issubmsg(f) &&
  2943. upb_msgdef_mapentry(upb_fielddef_msgsubdef(f));
  2944. }
  2945. bool upb_fielddef_hassubdef(const upb_fielddef *f) {
  2946. return upb_fielddef_issubmsg(f) || upb_fielddef_type(f) == UPB_TYPE_ENUM;
  2947. }
  2948. bool upb_fielddef_haspresence(const upb_fielddef *f) {
  2949. if (upb_fielddef_isseq(f)) return false;
  2950. if (upb_fielddef_issubmsg(f)) return true;
  2951. return f->file->syntax == UPB_SYNTAX_PROTO2;
  2952. }
  2953. static bool between(int32_t x, int32_t low, int32_t high) {
  2954. return x >= low && x <= high;
  2955. }
  2956. bool upb_fielddef_checklabel(int32_t label) { return between(label, 1, 3); }
  2957. bool upb_fielddef_checktype(int32_t type) { return between(type, 1, 11); }
  2958. bool upb_fielddef_checkintfmt(int32_t fmt) { return between(fmt, 1, 3); }
  2959. bool upb_fielddef_checkdescriptortype(int32_t type) {
  2960. return between(type, 1, 18);
  2961. }
  2962. /* upb_msgdef *****************************************************************/
  2963. const char *upb_msgdef_fullname(const upb_msgdef *m) {
  2964. return m->full_name;
  2965. }
  2966. const upb_filedef *upb_msgdef_file(const upb_msgdef *m) {
  2967. return m->file;
  2968. }
  2969. const char *upb_msgdef_name(const upb_msgdef *m) {
  2970. return shortdefname(m->full_name);
  2971. }
  2972. upb_syntax_t upb_msgdef_syntax(const upb_msgdef *m) {
  2973. return m->file->syntax;
  2974. }
  2975. size_t upb_msgdef_selectorcount(const upb_msgdef *m) {
  2976. return m->selector_count;
  2977. }
  2978. uint32_t upb_msgdef_submsgfieldcount(const upb_msgdef *m) {
  2979. return m->submsg_field_count;
  2980. }
  2981. const upb_fielddef *upb_msgdef_itof(const upb_msgdef *m, uint32_t i) {
  2982. upb_value val;
  2983. return upb_inttable_lookup32(&m->itof, i, &val) ?
  2984. upb_value_getconstptr(val) : NULL;
  2985. }
  2986. const upb_fielddef *upb_msgdef_ntof(const upb_msgdef *m, const char *name,
  2987. size_t len) {
  2988. upb_value val;
  2989. if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
  2990. return NULL;
  2991. }
  2992. return unpack_def(val, UPB_DEFTYPE_FIELD);
  2993. }
  2994. const upb_oneofdef *upb_msgdef_ntoo(const upb_msgdef *m, const char *name,
  2995. size_t len) {
  2996. upb_value val;
  2997. if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
  2998. return NULL;
  2999. }
  3000. return unpack_def(val, UPB_DEFTYPE_ONEOF);
  3001. }
  3002. bool upb_msgdef_lookupname(const upb_msgdef *m, const char *name, size_t len,
  3003. const upb_fielddef **f, const upb_oneofdef **o) {
  3004. upb_value val;
  3005. if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
  3006. return false;
  3007. }
  3008. *o = unpack_def(val, UPB_DEFTYPE_ONEOF);
  3009. *f = unpack_def(val, UPB_DEFTYPE_FIELD);
  3010. UPB_ASSERT((*o != NULL) ^ (*f != NULL)); /* Exactly one of the two should be set. */
  3011. return true;
  3012. }
  3013. int upb_msgdef_numfields(const upb_msgdef *m) {
  3014. /* The number table contains only fields. */
  3015. return upb_inttable_count(&m->itof);
  3016. }
  3017. int upb_msgdef_numoneofs(const upb_msgdef *m) {
  3018. /* The name table includes oneofs, and the number table does not. */
  3019. return upb_strtable_count(&m->ntof) - upb_inttable_count(&m->itof);
  3020. }
  3021. bool upb_msgdef_mapentry(const upb_msgdef *m) {
  3022. return m->map_entry;
  3023. }
  3024. upb_wellknowntype_t upb_msgdef_wellknowntype(const upb_msgdef *m) {
  3025. return m->well_known_type;
  3026. }
  3027. bool upb_msgdef_isnumberwrapper(const upb_msgdef *m) {
  3028. upb_wellknowntype_t type = upb_msgdef_wellknowntype(m);
  3029. return type >= UPB_WELLKNOWN_DOUBLEVALUE &&
  3030. type <= UPB_WELLKNOWN_UINT32VALUE;
  3031. }
  3032. void upb_msg_field_begin(upb_msg_field_iter *iter, const upb_msgdef *m) {
  3033. upb_inttable_begin(iter, &m->itof);
  3034. }
  3035. void upb_msg_field_next(upb_msg_field_iter *iter) { upb_inttable_next(iter); }
  3036. bool upb_msg_field_done(const upb_msg_field_iter *iter) {
  3037. return upb_inttable_done(iter);
  3038. }
  3039. upb_fielddef *upb_msg_iter_field(const upb_msg_field_iter *iter) {
  3040. return (upb_fielddef *)upb_value_getconstptr(upb_inttable_iter_value(iter));
  3041. }
  3042. void upb_msg_field_iter_setdone(upb_msg_field_iter *iter) {
  3043. upb_inttable_iter_setdone(iter);
  3044. }
  3045. bool upb_msg_field_iter_isequal(const upb_msg_field_iter * iter1,
  3046. const upb_msg_field_iter * iter2) {
  3047. return upb_inttable_iter_isequal(iter1, iter2);
  3048. }
  3049. void upb_msg_oneof_begin(upb_msg_oneof_iter *iter, const upb_msgdef *m) {
  3050. upb_strtable_begin(iter, &m->ntof);
  3051. /* We need to skip past any initial fields. */
  3052. while (!upb_strtable_done(iter) &&
  3053. !unpack_def(upb_strtable_iter_value(iter), UPB_DEFTYPE_ONEOF)) {
  3054. upb_strtable_next(iter);
  3055. }
  3056. }
  3057. void upb_msg_oneof_next(upb_msg_oneof_iter *iter) {
  3058. /* We need to skip past fields to return only oneofs. */
  3059. do {
  3060. upb_strtable_next(iter);
  3061. } while (!upb_strtable_done(iter) &&
  3062. !unpack_def(upb_strtable_iter_value(iter), UPB_DEFTYPE_ONEOF));
  3063. }
  3064. bool upb_msg_oneof_done(const upb_msg_oneof_iter *iter) {
  3065. return upb_strtable_done(iter);
  3066. }
  3067. const upb_oneofdef *upb_msg_iter_oneof(const upb_msg_oneof_iter *iter) {
  3068. return unpack_def(upb_strtable_iter_value(iter), UPB_DEFTYPE_ONEOF);
  3069. }
  3070. void upb_msg_oneof_iter_setdone(upb_msg_oneof_iter *iter) {
  3071. upb_strtable_iter_setdone(iter);
  3072. }
  3073. bool upb_msg_oneof_iter_isequal(const upb_msg_oneof_iter *iter1,
  3074. const upb_msg_oneof_iter *iter2) {
  3075. return upb_strtable_iter_isequal(iter1, iter2);
  3076. }
  3077. /* upb_oneofdef ***************************************************************/
  3078. const char *upb_oneofdef_name(const upb_oneofdef *o) {
  3079. return shortdefname(o->full_name);
  3080. }
  3081. const upb_msgdef *upb_oneofdef_containingtype(const upb_oneofdef *o) {
  3082. return o->parent;
  3083. }
  3084. int upb_oneofdef_numfields(const upb_oneofdef *o) {
  3085. return upb_strtable_count(&o->ntof);
  3086. }
  3087. uint32_t upb_oneofdef_index(const upb_oneofdef *o) {
  3088. return o->index;
  3089. }
  3090. const upb_fielddef *upb_oneofdef_ntof(const upb_oneofdef *o,
  3091. const char *name, size_t length) {
  3092. upb_value val;
  3093. return upb_strtable_lookup2(&o->ntof, name, length, &val) ?
  3094. upb_value_getptr(val) : NULL;
  3095. }
  3096. const upb_fielddef *upb_oneofdef_itof(const upb_oneofdef *o, uint32_t num) {
  3097. upb_value val;
  3098. return upb_inttable_lookup32(&o->itof, num, &val) ?
  3099. upb_value_getptr(val) : NULL;
  3100. }
  3101. void upb_oneof_begin(upb_oneof_iter *iter, const upb_oneofdef *o) {
  3102. upb_inttable_begin(iter, &o->itof);
  3103. }
  3104. void upb_oneof_next(upb_oneof_iter *iter) {
  3105. upb_inttable_next(iter);
  3106. }
  3107. bool upb_oneof_done(upb_oneof_iter *iter) {
  3108. return upb_inttable_done(iter);
  3109. }
  3110. upb_fielddef *upb_oneof_iter_field(const upb_oneof_iter *iter) {
  3111. return (upb_fielddef *)upb_value_getconstptr(upb_inttable_iter_value(iter));
  3112. }
  3113. void upb_oneof_iter_setdone(upb_oneof_iter *iter) {
  3114. upb_inttable_iter_setdone(iter);
  3115. }
  3116. /* Code to build defs from descriptor protos. *********************************/
  3117. /* There is a question of how much validation to do here. It will be difficult
  3118. * to perfectly match the amount of validation performed by proto2. But since
  3119. * this code is used to directly build defs from Ruby (for example) we do need
  3120. * to validate important constraints like uniqueness of names and numbers. */
  3121. #define CHK(x) if (!(x)) { return false; }
  3122. #define CHK_OOM(x) if (!(x)) { upb_status_setoom(ctx->status); return false; }
  3123. typedef struct {
  3124. const upb_symtab *symtab;
  3125. upb_filedef *file; /* File we are building. */
  3126. upb_alloc *alloc; /* Allocate defs here. */
  3127. upb_alloc *tmp; /* Alloc for addtab and any other tmp data. */
  3128. upb_strtable *addtab; /* full_name -> packed def ptr for new defs. */
  3129. upb_status *status; /* Record errors here. */
  3130. } symtab_addctx;
  3131. static char* strviewdup(const symtab_addctx *ctx, upb_strview view) {
  3132. return upb_strdup2(view.data, view.size, ctx->alloc);
  3133. }
  3134. static bool streql2(const char *a, size_t n, const char *b) {
  3135. return n == strlen(b) && memcmp(a, b, n) == 0;
  3136. }
  3137. static bool streql_view(upb_strview view, const char *b) {
  3138. return streql2(view.data, view.size, b);
  3139. }
  3140. static const char *makefullname(const symtab_addctx *ctx, const char *prefix,
  3141. upb_strview name) {
  3142. if (prefix) {
  3143. /* ret = prefix + '.' + name; */
  3144. size_t n = strlen(prefix);
  3145. char *ret = upb_malloc(ctx->alloc, n + name.size + 2);
  3146. CHK_OOM(ret);
  3147. strcpy(ret, prefix);
  3148. ret[n] = '.';
  3149. memcpy(&ret[n + 1], name.data, name.size);
  3150. ret[n + 1 + name.size] = '\0';
  3151. return ret;
  3152. } else {
  3153. return strviewdup(ctx, name);
  3154. }
  3155. }
  3156. static bool symtab_add(const symtab_addctx *ctx, const char *name,
  3157. upb_value v) {
  3158. upb_value tmp;
  3159. if (upb_strtable_lookup(ctx->addtab, name, &tmp) ||
  3160. upb_strtable_lookup(&ctx->symtab->syms, name, &tmp)) {
  3161. upb_status_seterrf(ctx->status, "duplicate symbol '%s'", name);
  3162. return false;
  3163. }
  3164. CHK_OOM(upb_strtable_insert3(ctx->addtab, name, strlen(name), v, ctx->tmp));
  3165. return true;
  3166. }
  3167. /* Given a symbol and the base symbol inside which it is defined, find the
  3168. * symbol's definition in t. */
  3169. static bool resolvename(const upb_strtable *t, const upb_fielddef *f,
  3170. const char *base, upb_strview sym,
  3171. upb_deftype_t type, upb_status *status,
  3172. const void **def) {
  3173. if(sym.size == 0) return NULL;
  3174. if(sym.data[0] == '.') {
  3175. /* Symbols starting with '.' are absolute, so we do a single lookup.
  3176. * Slice to omit the leading '.' */
  3177. upb_value v;
  3178. if (!upb_strtable_lookup2(t, sym.data + 1, sym.size - 1, &v)) {
  3179. return false;
  3180. }
  3181. *def = unpack_def(v, type);
  3182. if (!*def) {
  3183. upb_status_seterrf(status,
  3184. "type mismatch when resolving field %s, name %s",
  3185. f->full_name, sym.data);
  3186. return false;
  3187. }
  3188. return true;
  3189. } else {
  3190. /* Remove components from base until we find an entry or run out.
  3191. * TODO: This branch is totally broken, but currently not used. */
  3192. (void)base;
  3193. UPB_ASSERT(false);
  3194. return false;
  3195. }
  3196. }
  3197. const void *symtab_resolve(const symtab_addctx *ctx, const upb_fielddef *f,
  3198. const char *base, upb_strview sym,
  3199. upb_deftype_t type) {
  3200. const void *ret;
  3201. if (!resolvename(ctx->addtab, f, base, sym, type, ctx->status, &ret) &&
  3202. !resolvename(&ctx->symtab->syms, f, base, sym, type, ctx->status, &ret)) {
  3203. if (upb_ok(ctx->status)) {
  3204. upb_status_seterrf(ctx->status, "couldn't resolve name '%s'", sym.data);
  3205. }
  3206. return false;
  3207. }
  3208. return ret;
  3209. }
  3210. static bool create_oneofdef(
  3211. const symtab_addctx *ctx, upb_msgdef *m,
  3212. const google_protobuf_OneofDescriptorProto *oneof_proto) {
  3213. upb_oneofdef *o;
  3214. upb_strview name = google_protobuf_OneofDescriptorProto_name(oneof_proto);
  3215. upb_value v;
  3216. o = (upb_oneofdef*)&m->oneofs[m->oneof_count++];
  3217. o->parent = m;
  3218. o->full_name = makefullname(ctx, m->full_name, name);
  3219. v = pack_def(o, UPB_DEFTYPE_ONEOF);
  3220. CHK_OOM(symtab_add(ctx, o->full_name, v));
  3221. CHK_OOM(upb_strtable_insert3(&m->ntof, name.data, name.size, v, ctx->alloc));
  3222. CHK_OOM(upb_inttable_init2(&o->itof, UPB_CTYPE_CONSTPTR, ctx->alloc));
  3223. CHK_OOM(upb_strtable_init2(&o->ntof, UPB_CTYPE_CONSTPTR, ctx->alloc));
  3224. return true;
  3225. }
  3226. static bool parse_default(const symtab_addctx *ctx, const char *str, size_t len,
  3227. upb_fielddef *f) {
  3228. char *end;
  3229. char nullz[64];
  3230. errno = 0;
  3231. switch (upb_fielddef_type(f)) {
  3232. case UPB_TYPE_INT32:
  3233. case UPB_TYPE_INT64:
  3234. case UPB_TYPE_UINT32:
  3235. case UPB_TYPE_UINT64:
  3236. case UPB_TYPE_DOUBLE:
  3237. case UPB_TYPE_FLOAT:
  3238. /* Standard C number parsing functions expect null-terminated strings. */
  3239. if (len >= sizeof(nullz) - 1) {
  3240. return false;
  3241. }
  3242. memcpy(nullz, str, len);
  3243. nullz[len] = '\0';
  3244. str = nullz;
  3245. break;
  3246. default:
  3247. break;
  3248. }
  3249. switch (upb_fielddef_type(f)) {
  3250. case UPB_TYPE_INT32: {
  3251. long val = strtol(str, &end, 0);
  3252. CHK(val <= INT32_MAX && val >= INT32_MIN && errno != ERANGE && !*end);
  3253. f->defaultval.sint = val;
  3254. break;
  3255. }
  3256. case UPB_TYPE_ENUM: {
  3257. const upb_enumdef *e = f->sub.enumdef;
  3258. int32_t val;
  3259. CHK(upb_enumdef_ntoi(e, str, len, &val));
  3260. f->defaultval.sint = val;
  3261. break;
  3262. }
  3263. case UPB_TYPE_INT64: {
  3264. /* XXX: Need to write our own strtoll, since it's not available in c89. */
  3265. long long val = strtol(str, &end, 0);
  3266. CHK(val <= INT64_MAX && val >= INT64_MIN && errno != ERANGE && !*end);
  3267. f->defaultval.sint = val;
  3268. break;
  3269. }
  3270. case UPB_TYPE_UINT32: {
  3271. unsigned long val = strtoul(str, &end, 0);
  3272. CHK(val <= UINT32_MAX && errno != ERANGE && !*end);
  3273. f->defaultval.uint = val;
  3274. break;
  3275. }
  3276. case UPB_TYPE_UINT64: {
  3277. /* XXX: Need to write our own strtoull, since it's not available in c89. */
  3278. unsigned long long val = strtoul(str, &end, 0);
  3279. CHK(val <= UINT64_MAX && errno != ERANGE && !*end);
  3280. f->defaultval.uint = val;
  3281. break;
  3282. }
  3283. case UPB_TYPE_DOUBLE: {
  3284. double val = strtod(str, &end);
  3285. CHK(errno != ERANGE && !*end);
  3286. f->defaultval.dbl = val;
  3287. break;
  3288. }
  3289. case UPB_TYPE_FLOAT: {
  3290. /* XXX: Need to write our own strtof, since it's not available in c89. */
  3291. float val = strtod(str, &end);
  3292. CHK(errno != ERANGE && !*end);
  3293. f->defaultval.flt = val;
  3294. break;
  3295. }
  3296. case UPB_TYPE_BOOL: {
  3297. if (streql2(str, len, "false")) {
  3298. f->defaultval.boolean = false;
  3299. } else if (streql2(str, len, "true")) {
  3300. f->defaultval.boolean = true;
  3301. } else {
  3302. return false;
  3303. }
  3304. break;
  3305. }
  3306. case UPB_TYPE_STRING:
  3307. f->defaultval.str = newstr(ctx->alloc, str, len);
  3308. break;
  3309. case UPB_TYPE_BYTES:
  3310. /* XXX: need to interpret the C-escaped value. */
  3311. f->defaultval.str = newstr(ctx->alloc, str, len);
  3312. break;
  3313. case UPB_TYPE_MESSAGE:
  3314. /* Should not have a default value. */
  3315. return false;
  3316. }
  3317. return true;
  3318. }
  3319. static void set_default_default(const symtab_addctx *ctx, upb_fielddef *f) {
  3320. switch (upb_fielddef_type(f)) {
  3321. case UPB_TYPE_INT32:
  3322. case UPB_TYPE_INT64:
  3323. case UPB_TYPE_ENUM:
  3324. f->defaultval.sint = 0;
  3325. break;
  3326. case UPB_TYPE_UINT64:
  3327. case UPB_TYPE_UINT32:
  3328. f->defaultval.uint = 0;
  3329. break;
  3330. case UPB_TYPE_DOUBLE:
  3331. case UPB_TYPE_FLOAT:
  3332. f->defaultval.dbl = 0;
  3333. break;
  3334. case UPB_TYPE_STRING:
  3335. case UPB_TYPE_BYTES:
  3336. f->defaultval.str = newstr(ctx->alloc, NULL, 0);
  3337. break;
  3338. case UPB_TYPE_BOOL:
  3339. f->defaultval.boolean = false;
  3340. break;
  3341. case UPB_TYPE_MESSAGE:
  3342. break;
  3343. }
  3344. }
  3345. static bool create_fielddef(
  3346. const symtab_addctx *ctx, const char *prefix, upb_msgdef *m,
  3347. const google_protobuf_FieldDescriptorProto *field_proto) {
  3348. upb_alloc *alloc = ctx->alloc;
  3349. upb_fielddef *f;
  3350. const google_protobuf_FieldOptions *options;
  3351. upb_strview name;
  3352. const char *full_name;
  3353. const char *shortname;
  3354. uint32_t field_number;
  3355. if (!google_protobuf_FieldDescriptorProto_has_name(field_proto)) {
  3356. upb_status_seterrmsg(ctx->status, "field has no name");
  3357. return false;
  3358. }
  3359. name = google_protobuf_FieldDescriptorProto_name(field_proto);
  3360. CHK(upb_isident(name, false, ctx->status));
  3361. full_name = makefullname(ctx, prefix, name);
  3362. shortname = shortdefname(full_name);
  3363. field_number = google_protobuf_FieldDescriptorProto_number(field_proto);
  3364. if (field_number == 0 || field_number > UPB_MAX_FIELDNUMBER) {
  3365. upb_status_seterrf(ctx->status, "invalid field number (%u)", field_number);
  3366. return false;
  3367. }
  3368. if (m) {
  3369. /* direct message field. */
  3370. upb_value v, packed_v;
  3371. f = (upb_fielddef*)&m->fields[m->field_count++];
  3372. f->msgdef = m;
  3373. f->is_extension_ = false;
  3374. packed_v = pack_def(f, UPB_DEFTYPE_FIELD);
  3375. v = upb_value_constptr(f);
  3376. if (!upb_strtable_insert3(&m->ntof, name.data, name.size, packed_v, alloc)) {
  3377. upb_status_seterrf(ctx->status, "duplicate field name (%s)", shortname);
  3378. return false;
  3379. }
  3380. if (!upb_inttable_insert2(&m->itof, field_number, v, alloc)) {
  3381. upb_status_seterrf(ctx->status, "duplicate field number (%u)",
  3382. field_number);
  3383. return false;
  3384. }
  3385. } else {
  3386. /* extension field. */
  3387. f = (upb_fielddef*)&ctx->file->exts[ctx->file->ext_count];
  3388. f->is_extension_ = true;
  3389. CHK_OOM(symtab_add(ctx, full_name, pack_def(f, UPB_DEFTYPE_FIELD)));
  3390. }
  3391. f->full_name = full_name;
  3392. f->file = ctx->file;
  3393. f->type_ = (int)google_protobuf_FieldDescriptorProto_type(field_proto);
  3394. f->label_ = (int)google_protobuf_FieldDescriptorProto_label(field_proto);
  3395. f->number_ = field_number;
  3396. f->oneof = NULL;
  3397. /* We can't resolve the subdef or (in the case of extensions) the containing
  3398. * message yet, because it may not have been defined yet. We stash a pointer
  3399. * to the field_proto until later when we can properly resolve it. */
  3400. f->sub.unresolved = field_proto;
  3401. if (f->label_ == UPB_LABEL_REQUIRED && f->file->syntax == UPB_SYNTAX_PROTO3) {
  3402. upb_status_seterrf(ctx->status, "proto3 fields cannot be required (%s)",
  3403. f->full_name);
  3404. return false;
  3405. }
  3406. if (google_protobuf_FieldDescriptorProto_has_oneof_index(field_proto)) {
  3407. int oneof_index =
  3408. google_protobuf_FieldDescriptorProto_oneof_index(field_proto);
  3409. upb_oneofdef *oneof;
  3410. upb_value v = upb_value_constptr(f);
  3411. if (upb_fielddef_label(f) != UPB_LABEL_OPTIONAL) {
  3412. upb_status_seterrf(ctx->status,
  3413. "fields in oneof must have OPTIONAL label (%s)",
  3414. f->full_name);
  3415. return false;
  3416. }
  3417. if (!m) {
  3418. upb_status_seterrf(ctx->status,
  3419. "oneof_index provided for extension field (%s)",
  3420. f->full_name);
  3421. return false;
  3422. }
  3423. if (oneof_index >= m->oneof_count) {
  3424. upb_status_seterrf(ctx->status, "oneof_index out of range (%s)",
  3425. f->full_name);
  3426. return false;
  3427. }
  3428. oneof = (upb_oneofdef*)&m->oneofs[oneof_index];
  3429. f->oneof = oneof;
  3430. CHK(upb_inttable_insert2(&oneof->itof, f->number_, v, alloc));
  3431. CHK(upb_strtable_insert3(&oneof->ntof, name.data, name.size, v, alloc));
  3432. } else {
  3433. f->oneof = NULL;
  3434. }
  3435. if (google_protobuf_FieldDescriptorProto_has_options(field_proto)) {
  3436. options = google_protobuf_FieldDescriptorProto_options(field_proto);
  3437. f->lazy_ = google_protobuf_FieldOptions_lazy(options);
  3438. f->packed_ = google_protobuf_FieldOptions_packed(options);
  3439. } else {
  3440. f->lazy_ = false;
  3441. f->packed_ = false;
  3442. }
  3443. return true;
  3444. }
  3445. static bool create_enumdef(
  3446. const symtab_addctx *ctx, const char *prefix,
  3447. const google_protobuf_EnumDescriptorProto *enum_proto) {
  3448. upb_enumdef *e;
  3449. const google_protobuf_EnumValueDescriptorProto *const *values;
  3450. upb_strview name;
  3451. size_t i, n;
  3452. name = google_protobuf_EnumDescriptorProto_name(enum_proto);
  3453. CHK(upb_isident(name, false, ctx->status));
  3454. e = (upb_enumdef*)&ctx->file->enums[ctx->file->enum_count++];
  3455. e->full_name = makefullname(ctx, prefix, name);
  3456. CHK_OOM(symtab_add(ctx, e->full_name, pack_def(e, UPB_DEFTYPE_ENUM)));
  3457. CHK_OOM(upb_strtable_init2(&e->ntoi, UPB_CTYPE_INT32, ctx->alloc));
  3458. CHK_OOM(upb_inttable_init2(&e->iton, UPB_CTYPE_CSTR, ctx->alloc));
  3459. e->file = ctx->file;
  3460. e->defaultval = 0;
  3461. values = google_protobuf_EnumDescriptorProto_value(enum_proto, &n);
  3462. if (n == 0) {
  3463. upb_status_seterrf(ctx->status,
  3464. "enums must contain at least one value (%s)",
  3465. e->full_name);
  3466. return false;
  3467. }
  3468. for (i = 0; i < n; i++) {
  3469. const google_protobuf_EnumValueDescriptorProto *value = values[i];
  3470. upb_strview name = google_protobuf_EnumValueDescriptorProto_name(value);
  3471. char *name2 = strviewdup(ctx, name);
  3472. int32_t num = google_protobuf_EnumValueDescriptorProto_number(value);
  3473. upb_value v = upb_value_int32(num);
  3474. if (i == 0 && e->file->syntax == UPB_SYNTAX_PROTO3 && num != 0) {
  3475. upb_status_seterrf(ctx->status,
  3476. "for proto3, the first enum value must be zero (%s)",
  3477. e->full_name);
  3478. return false;
  3479. }
  3480. if (upb_strtable_lookup(&e->ntoi, name2, NULL)) {
  3481. upb_status_seterrf(ctx->status, "duplicate enum label '%s'", name2);
  3482. return false;
  3483. }
  3484. CHK_OOM(name2)
  3485. CHK_OOM(
  3486. upb_strtable_insert3(&e->ntoi, name2, strlen(name2), v, ctx->alloc));
  3487. if (!upb_inttable_lookup(&e->iton, num, NULL)) {
  3488. upb_value v = upb_value_cstr(name2);
  3489. CHK_OOM(upb_inttable_insert2(&e->iton, num, v, ctx->alloc));
  3490. }
  3491. }
  3492. upb_inttable_compact2(&e->iton, ctx->alloc);
  3493. return true;
  3494. }
  3495. static bool create_msgdef(const symtab_addctx *ctx, const char *prefix,
  3496. const google_protobuf_DescriptorProto *msg_proto) {
  3497. upb_msgdef *m;
  3498. const google_protobuf_MessageOptions *options;
  3499. const google_protobuf_OneofDescriptorProto *const *oneofs;
  3500. const google_protobuf_FieldDescriptorProto *const *fields;
  3501. const google_protobuf_EnumDescriptorProto *const *enums;
  3502. const google_protobuf_DescriptorProto *const *msgs;
  3503. size_t i, n;
  3504. upb_strview name;
  3505. name = google_protobuf_DescriptorProto_name(msg_proto);
  3506. CHK(upb_isident(name, false, ctx->status));
  3507. m = (upb_msgdef*)&ctx->file->msgs[ctx->file->msg_count++];
  3508. m->full_name = makefullname(ctx, prefix, name);
  3509. CHK_OOM(symtab_add(ctx, m->full_name, pack_def(m, UPB_DEFTYPE_MSG)));
  3510. CHK_OOM(upb_inttable_init2(&m->itof, UPB_CTYPE_CONSTPTR, ctx->alloc));
  3511. CHK_OOM(upb_strtable_init2(&m->ntof, UPB_CTYPE_CONSTPTR, ctx->alloc));
  3512. m->file = ctx->file;
  3513. m->map_entry = false;
  3514. options = google_protobuf_DescriptorProto_options(msg_proto);
  3515. if (options) {
  3516. m->map_entry = google_protobuf_MessageOptions_map_entry(options);
  3517. }
  3518. oneofs = google_protobuf_DescriptorProto_oneof_decl(msg_proto, &n);
  3519. m->oneof_count = 0;
  3520. m->oneofs = upb_malloc(ctx->alloc, sizeof(*m->oneofs) * n);
  3521. for (i = 0; i < n; i++) {
  3522. CHK(create_oneofdef(ctx, m, oneofs[i]));
  3523. }
  3524. fields = google_protobuf_DescriptorProto_field(msg_proto, &n);
  3525. m->field_count = 0;
  3526. m->fields = upb_malloc(ctx->alloc, sizeof(*m->fields) * n);
  3527. for (i = 0; i < n; i++) {
  3528. CHK(create_fielddef(ctx, m->full_name, m, fields[i]));
  3529. }
  3530. CHK(assign_msg_indices(m, ctx->status));
  3531. assign_msg_wellknowntype(m);
  3532. upb_inttable_compact2(&m->itof, ctx->alloc);
  3533. /* This message is built. Now build nested messages and enums. */
  3534. enums = google_protobuf_DescriptorProto_enum_type(msg_proto, &n);
  3535. for (i = 0; i < n; i++) {
  3536. CHK(create_enumdef(ctx, m->full_name, enums[i]));
  3537. }
  3538. msgs = google_protobuf_DescriptorProto_nested_type(msg_proto, &n);
  3539. for (i = 0; i < n; i++) {
  3540. CHK(create_msgdef(ctx, m->full_name, msgs[i]));
  3541. }
  3542. return true;
  3543. }
  3544. typedef struct {
  3545. int msg_count;
  3546. int enum_count;
  3547. int ext_count;
  3548. } decl_counts;
  3549. static void count_types_in_msg(const google_protobuf_DescriptorProto *msg_proto,
  3550. decl_counts *counts) {
  3551. const google_protobuf_DescriptorProto *const *msgs;
  3552. size_t i, n;
  3553. counts->msg_count++;
  3554. msgs = google_protobuf_DescriptorProto_nested_type(msg_proto, &n);
  3555. for (i = 0; i < n; i++) {
  3556. count_types_in_msg(msgs[i], counts);
  3557. }
  3558. google_protobuf_DescriptorProto_enum_type(msg_proto, &n);
  3559. counts->enum_count += n;
  3560. google_protobuf_DescriptorProto_extension(msg_proto, &n);
  3561. counts->ext_count += n;
  3562. }
  3563. static void count_types_in_file(
  3564. const google_protobuf_FileDescriptorProto *file_proto,
  3565. decl_counts *counts) {
  3566. const google_protobuf_DescriptorProto *const *msgs;
  3567. size_t i, n;
  3568. msgs = google_protobuf_FileDescriptorProto_message_type(file_proto, &n);
  3569. for (i = 0; i < n; i++) {
  3570. count_types_in_msg(msgs[i], counts);
  3571. }
  3572. google_protobuf_FileDescriptorProto_enum_type(file_proto, &n);
  3573. counts->enum_count += n;
  3574. google_protobuf_FileDescriptorProto_extension(file_proto, &n);
  3575. counts->ext_count += n;
  3576. }
  3577. static bool resolve_fielddef(const symtab_addctx *ctx, const char *prefix,
  3578. upb_fielddef *f) {
  3579. upb_strview name;
  3580. const google_protobuf_FieldDescriptorProto *field_proto = f->sub.unresolved;
  3581. if (f->is_extension_) {
  3582. if (!google_protobuf_FieldDescriptorProto_has_extendee(field_proto)) {
  3583. upb_status_seterrf(ctx->status,
  3584. "extension for field '%s' had no extendee",
  3585. f->full_name);
  3586. return false;
  3587. }
  3588. name = google_protobuf_FieldDescriptorProto_extendee(field_proto);
  3589. f->msgdef = symtab_resolve(ctx, f, prefix, name, UPB_DEFTYPE_MSG);
  3590. CHK(f->msgdef);
  3591. }
  3592. if ((upb_fielddef_issubmsg(f) || f->type_ == UPB_DESCRIPTOR_TYPE_ENUM) &&
  3593. !google_protobuf_FieldDescriptorProto_has_type_name(field_proto)) {
  3594. upb_status_seterrf(ctx->status, "field '%s' is missing type name",
  3595. f->full_name);
  3596. return false;
  3597. }
  3598. name = google_protobuf_FieldDescriptorProto_type_name(field_proto);
  3599. if (upb_fielddef_issubmsg(f)) {
  3600. f->sub.msgdef = symtab_resolve(ctx, f, prefix, name, UPB_DEFTYPE_MSG);
  3601. CHK(f->sub.msgdef);
  3602. } else if (f->type_ == UPB_DESCRIPTOR_TYPE_ENUM) {
  3603. f->sub.enumdef = symtab_resolve(ctx, f, prefix, name, UPB_DEFTYPE_ENUM);
  3604. CHK(f->sub.enumdef);
  3605. }
  3606. /* Have to delay resolving of the default value until now because of the enum
  3607. * case, since enum defaults are specified with a label. */
  3608. if (google_protobuf_FieldDescriptorProto_has_default_value(field_proto)) {
  3609. upb_strview defaultval =
  3610. google_protobuf_FieldDescriptorProto_default_value(field_proto);
  3611. if (f->file->syntax == UPB_SYNTAX_PROTO3) {
  3612. upb_status_seterrf(ctx->status,
  3613. "proto3 fields cannot have explicit defaults (%s)",
  3614. f->full_name);
  3615. return false;
  3616. }
  3617. if (upb_fielddef_issubmsg(f)) {
  3618. upb_status_seterrf(ctx->status,
  3619. "message fields cannot have explicit defaults (%s)",
  3620. f->full_name);
  3621. return false;
  3622. }
  3623. if (!parse_default(ctx, defaultval.data, defaultval.size, f)) {
  3624. upb_status_seterrf(ctx->status,
  3625. "couldn't parse default '" UPB_STRVIEW_FORMAT
  3626. "' for field (%s)",
  3627. UPB_STRVIEW_ARGS(defaultval), f->full_name);
  3628. return false;
  3629. }
  3630. } else {
  3631. set_default_default(ctx, f);
  3632. }
  3633. return true;
  3634. }
  3635. static bool build_filedef(
  3636. const symtab_addctx *ctx, upb_filedef *file,
  3637. const google_protobuf_FileDescriptorProto *file_proto) {
  3638. upb_alloc *alloc = ctx->alloc;
  3639. const google_protobuf_FileOptions *file_options_proto;
  3640. const google_protobuf_DescriptorProto *const *msgs;
  3641. const google_protobuf_EnumDescriptorProto *const *enums;
  3642. const google_protobuf_FieldDescriptorProto *const *exts;
  3643. const upb_strview* strs;
  3644. size_t i, n;
  3645. decl_counts counts = {0};
  3646. count_types_in_file(file_proto, &counts);
  3647. file->msgs = upb_malloc(alloc, sizeof(*file->msgs) * counts.msg_count);
  3648. file->enums = upb_malloc(alloc, sizeof(*file->enums) * counts.enum_count);
  3649. file->exts = upb_malloc(alloc, sizeof(*file->exts) * counts.ext_count);
  3650. CHK_OOM(counts.msg_count == 0 || file->msgs);
  3651. CHK_OOM(counts.enum_count == 0 || file->enums);
  3652. CHK_OOM(counts.ext_count == 0 || file->exts);
  3653. /* We increment these as defs are added. */
  3654. file->msg_count = 0;
  3655. file->enum_count = 0;
  3656. file->ext_count = 0;
  3657. if (!google_protobuf_FileDescriptorProto_has_name(file_proto)) {
  3658. upb_status_seterrmsg(ctx->status, "File has no name");
  3659. return false;
  3660. }
  3661. file->name =
  3662. strviewdup(ctx, google_protobuf_FileDescriptorProto_name(file_proto));
  3663. file->phpprefix = NULL;
  3664. file->phpnamespace = NULL;
  3665. if (google_protobuf_FileDescriptorProto_has_package(file_proto)) {
  3666. upb_strview package =
  3667. google_protobuf_FileDescriptorProto_package(file_proto);
  3668. CHK(upb_isident(package, true, ctx->status));
  3669. file->package = strviewdup(ctx, package);
  3670. } else {
  3671. file->package = NULL;
  3672. }
  3673. if (google_protobuf_FileDescriptorProto_has_syntax(file_proto)) {
  3674. upb_strview syntax =
  3675. google_protobuf_FileDescriptorProto_syntax(file_proto);
  3676. if (streql_view(syntax, "proto2")) {
  3677. file->syntax = UPB_SYNTAX_PROTO2;
  3678. } else if (streql_view(syntax, "proto3")) {
  3679. file->syntax = UPB_SYNTAX_PROTO3;
  3680. } else {
  3681. upb_status_seterrf(ctx->status, "Invalid syntax '%s'", syntax);
  3682. return false;
  3683. }
  3684. } else {
  3685. file->syntax = UPB_SYNTAX_PROTO2;
  3686. }
  3687. /* Read options. */
  3688. file_options_proto = google_protobuf_FileDescriptorProto_options(file_proto);
  3689. if (file_options_proto) {
  3690. if (google_protobuf_FileOptions_has_php_class_prefix(file_options_proto)) {
  3691. file->phpprefix = strviewdup(
  3692. ctx,
  3693. google_protobuf_FileOptions_php_class_prefix(file_options_proto));
  3694. }
  3695. if (google_protobuf_FileOptions_has_php_namespace(file_options_proto)) {
  3696. file->phpnamespace = strviewdup(
  3697. ctx, google_protobuf_FileOptions_php_namespace(file_options_proto));
  3698. }
  3699. }
  3700. /* Verify dependencies. */
  3701. strs = google_protobuf_FileDescriptorProto_dependency(file_proto, &n);
  3702. file->deps = upb_malloc(alloc, sizeof(*file->deps) * n) ;
  3703. CHK_OOM(n == 0 || file->deps);
  3704. for (i = 0; i < n; i++) {
  3705. upb_strview dep_name = strs[i];
  3706. upb_value v;
  3707. if (!upb_strtable_lookup2(&ctx->symtab->files, dep_name.data,
  3708. dep_name.size, &v)) {
  3709. upb_status_seterrf(ctx->status,
  3710. "Depends on file '" UPB_STRVIEW_FORMAT
  3711. "', but it has not been loaded",
  3712. UPB_STRVIEW_ARGS(dep_name));
  3713. return false;
  3714. }
  3715. file->deps[i] = upb_value_getconstptr(v);
  3716. }
  3717. /* Create messages. */
  3718. msgs = google_protobuf_FileDescriptorProto_message_type(file_proto, &n);
  3719. for (i = 0; i < n; i++) {
  3720. CHK(create_msgdef(ctx, file->package, msgs[i]));
  3721. }
  3722. /* Create enums. */
  3723. enums = google_protobuf_FileDescriptorProto_enum_type(file_proto, &n);
  3724. for (i = 0; i < n; i++) {
  3725. CHK(create_enumdef(ctx, file->package, enums[i]));
  3726. }
  3727. /* Create extensions. */
  3728. exts = google_protobuf_FileDescriptorProto_extension(file_proto, &n);
  3729. file->exts = upb_malloc(alloc, sizeof(*file->exts) * n);
  3730. CHK_OOM(n == 0 || file->exts);
  3731. for (i = 0; i < n; i++) {
  3732. CHK(create_fielddef(ctx, file->package, NULL, exts[i]));
  3733. }
  3734. /* Now that all names are in the table, resolve references. */
  3735. for (i = 0; i < file->ext_count; i++) {
  3736. CHK(resolve_fielddef(ctx, file->package, (upb_fielddef*)&file->exts[i]));
  3737. }
  3738. for (i = 0; i < file->msg_count; i++) {
  3739. const upb_msgdef *m = &file->msgs[i];
  3740. int j;
  3741. for (j = 0; j < m->field_count; j++) {
  3742. CHK(resolve_fielddef(ctx, m->full_name, (upb_fielddef*)&m->fields[j]));
  3743. }
  3744. }
  3745. return true;
  3746. }
  3747. static bool upb_symtab_addtotabs(upb_symtab *s, symtab_addctx *ctx,
  3748. upb_status *status) {
  3749. const upb_filedef *file = ctx->file;
  3750. upb_alloc *alloc = upb_arena_alloc(s->arena);
  3751. upb_strtable_iter iter;
  3752. CHK_OOM(upb_strtable_insert3(&s->files, file->name, strlen(file->name),
  3753. upb_value_constptr(file), alloc));
  3754. upb_strtable_begin(&iter, ctx->addtab);
  3755. for (; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
  3756. const char *key = upb_strtable_iter_key(&iter);
  3757. size_t keylen = upb_strtable_iter_keylength(&iter);
  3758. upb_value value = upb_strtable_iter_value(&iter);
  3759. CHK_OOM(upb_strtable_insert3(&s->syms, key, keylen, value, alloc));
  3760. }
  3761. return true;
  3762. }
  3763. /* upb_filedef ****************************************************************/
  3764. const char *upb_filedef_name(const upb_filedef *f) {
  3765. return f->name;
  3766. }
  3767. const char *upb_filedef_package(const upb_filedef *f) {
  3768. return f->package;
  3769. }
  3770. const char *upb_filedef_phpprefix(const upb_filedef *f) {
  3771. return f->phpprefix;
  3772. }
  3773. const char *upb_filedef_phpnamespace(const upb_filedef *f) {
  3774. return f->phpnamespace;
  3775. }
  3776. upb_syntax_t upb_filedef_syntax(const upb_filedef *f) {
  3777. return f->syntax;
  3778. }
  3779. int upb_filedef_msgcount(const upb_filedef *f) {
  3780. return f->msg_count;
  3781. }
  3782. int upb_filedef_depcount(const upb_filedef *f) {
  3783. return f->dep_count;
  3784. }
  3785. int upb_filedef_enumcount(const upb_filedef *f) {
  3786. return f->enum_count;
  3787. }
  3788. const upb_filedef *upb_filedef_dep(const upb_filedef *f, int i) {
  3789. return i < 0 || i >= f->dep_count ? NULL : f->deps[i];
  3790. }
  3791. const upb_msgdef *upb_filedef_msg(const upb_filedef *f, int i) {
  3792. return i < 0 || i >= f->msg_count ? NULL : &f->msgs[i];
  3793. }
  3794. const upb_enumdef *upb_filedef_enum(const upb_filedef *f, int i) {
  3795. return i < 0 || i >= f->enum_count ? NULL : &f->enums[i];
  3796. }
  3797. void upb_symtab_free(upb_symtab *s) {
  3798. upb_arena_free(s->arena);
  3799. upb_gfree(s);
  3800. }
  3801. upb_symtab *upb_symtab_new(void) {
  3802. upb_symtab *s = upb_gmalloc(sizeof(*s));
  3803. upb_alloc *alloc;
  3804. if (!s) {
  3805. return NULL;
  3806. }
  3807. s->arena = upb_arena_new();
  3808. alloc = upb_arena_alloc(s->arena);
  3809. if (!upb_strtable_init2(&s->syms, UPB_CTYPE_CONSTPTR, alloc) ||
  3810. !upb_strtable_init2(&s->files, UPB_CTYPE_CONSTPTR, alloc)) {
  3811. upb_arena_free(s->arena);
  3812. upb_gfree(s);
  3813. s = NULL;
  3814. }
  3815. return s;
  3816. }
  3817. const upb_msgdef *upb_symtab_lookupmsg(const upb_symtab *s, const char *sym) {
  3818. upb_value v;
  3819. return upb_strtable_lookup(&s->syms, sym, &v) ?
  3820. unpack_def(v, UPB_DEFTYPE_MSG) : NULL;
  3821. }
  3822. const upb_msgdef *upb_symtab_lookupmsg2(const upb_symtab *s, const char *sym,
  3823. size_t len) {
  3824. upb_value v;
  3825. return upb_strtable_lookup2(&s->syms, sym, len, &v) ?
  3826. unpack_def(v, UPB_DEFTYPE_MSG) : NULL;
  3827. }
  3828. const upb_enumdef *upb_symtab_lookupenum(const upb_symtab *s, const char *sym) {
  3829. upb_value v;
  3830. return upb_strtable_lookup(&s->syms, sym, &v) ?
  3831. unpack_def(v, UPB_DEFTYPE_ENUM) : NULL;
  3832. }
  3833. const upb_filedef *upb_symtab_lookupfile(const upb_symtab *s, const char *name) {
  3834. upb_value v;
  3835. return upb_strtable_lookup(&s->files, name, &v) ? upb_value_getconstptr(v)
  3836. : NULL;
  3837. }
  3838. const upb_filedef *upb_symtab_addfile(
  3839. upb_symtab *s, const google_protobuf_FileDescriptorProto *file_proto,
  3840. upb_status *status) {
  3841. upb_arena *tmparena = upb_arena_new();
  3842. upb_strtable addtab;
  3843. upb_alloc *alloc = upb_arena_alloc(s->arena);
  3844. upb_filedef *file = upb_malloc(alloc, sizeof(*file));
  3845. bool ok;
  3846. symtab_addctx ctx;
  3847. ctx.file = file;
  3848. ctx.symtab = s;
  3849. ctx.alloc = alloc;
  3850. ctx.tmp = upb_arena_alloc(tmparena);
  3851. ctx.addtab = &addtab;
  3852. ctx.status = status;
  3853. ok = file &&
  3854. upb_strtable_init2(&addtab, UPB_CTYPE_CONSTPTR, ctx.tmp) &&
  3855. build_filedef(&ctx, file, file_proto) &&
  3856. upb_symtab_addtotabs(s, &ctx, status);
  3857. upb_arena_free(tmparena);
  3858. return ok ? file : NULL;
  3859. }
  3860. /* Include here since we want most of this file to be stdio-free. */
  3861. #include <stdio.h>
  3862. bool _upb_symtab_loaddefinit(upb_symtab *s, const upb_def_init *init) {
  3863. /* Since this function should never fail (it would indicate a bug in upb) we
  3864. * print errors to stderr instead of returning error status to the user. */
  3865. upb_def_init **deps = init->deps;
  3866. google_protobuf_FileDescriptorProto *file;
  3867. upb_arena *arena;
  3868. upb_status status;
  3869. upb_status_clear(&status);
  3870. if (upb_strtable_lookup(&s->files, init->filename, NULL)) {
  3871. return true;
  3872. }
  3873. arena = upb_arena_new();
  3874. for (; *deps; deps++) {
  3875. if (!_upb_symtab_loaddefinit(s, *deps)) goto err;
  3876. }
  3877. file = google_protobuf_FileDescriptorProto_parse(
  3878. init->descriptor.data, init->descriptor.size, arena);
  3879. if (!file) {
  3880. upb_status_seterrf(
  3881. &status,
  3882. "Failed to parse compiled-in descriptor for file '%s'. This should "
  3883. "never happen.",
  3884. init->filename);
  3885. goto err;
  3886. }
  3887. if (!upb_symtab_addfile(s, file, &status)) goto err;
  3888. upb_arena_free(arena);
  3889. return true;
  3890. err:
  3891. fprintf(stderr, "Error loading compiled-in descriptor: %s\n",
  3892. upb_status_errmsg(&status));
  3893. upb_arena_free(arena);
  3894. return false;
  3895. }
  3896. #undef CHK
  3897. #undef CHK_OOM
  3898. static bool is_power_of_two(size_t val) {
  3899. return (val & (val - 1)) == 0;
  3900. }
  3901. /* Align up to the given power of 2. */
  3902. static size_t align_up(size_t val, size_t align) {
  3903. UPB_ASSERT(is_power_of_two(align));
  3904. return (val + align - 1) & ~(align - 1);
  3905. }
  3906. static size_t div_round_up(size_t n, size_t d) {
  3907. return (n + d - 1) / d;
  3908. }
  3909. static size_t upb_msgval_sizeof2(upb_fieldtype_t type) {
  3910. switch (type) {
  3911. case UPB_TYPE_DOUBLE:
  3912. case UPB_TYPE_INT64:
  3913. case UPB_TYPE_UINT64:
  3914. return 8;
  3915. case UPB_TYPE_ENUM:
  3916. case UPB_TYPE_INT32:
  3917. case UPB_TYPE_UINT32:
  3918. case UPB_TYPE_FLOAT:
  3919. return 4;
  3920. case UPB_TYPE_BOOL:
  3921. return 1;
  3922. case UPB_TYPE_MESSAGE:
  3923. return sizeof(void*);
  3924. case UPB_TYPE_BYTES:
  3925. case UPB_TYPE_STRING:
  3926. return sizeof(upb_strview);
  3927. }
  3928. UPB_UNREACHABLE();
  3929. }
  3930. static uint8_t upb_msg_fielddefsize(const upb_fielddef *f) {
  3931. if (upb_fielddef_isseq(f)) {
  3932. return sizeof(void*);
  3933. } else {
  3934. return upb_msgval_sizeof2(upb_fielddef_type(f));
  3935. }
  3936. }
  3937. /** upb_msglayout *************************************************************/
  3938. static void upb_msglayout_free(upb_msglayout *l) {
  3939. upb_gfree(l);
  3940. }
  3941. static size_t upb_msglayout_place(upb_msglayout *l, size_t size) {
  3942. size_t ret;
  3943. l->size = align_up(l->size, size);
  3944. ret = l->size;
  3945. l->size += size;
  3946. return ret;
  3947. }
  3948. static bool upb_msglayout_init(const upb_msgdef *m,
  3949. upb_msglayout *l,
  3950. upb_msgfactory *factory) {
  3951. upb_msg_field_iter it;
  3952. upb_msg_oneof_iter oit;
  3953. size_t hasbit;
  3954. size_t submsg_count = 0;
  3955. const upb_msglayout **submsgs;
  3956. upb_msglayout_field *fields;
  3957. for (upb_msg_field_begin(&it, m);
  3958. !upb_msg_field_done(&it);
  3959. upb_msg_field_next(&it)) {
  3960. const upb_fielddef* f = upb_msg_iter_field(&it);
  3961. if (upb_fielddef_issubmsg(f)) {
  3962. submsg_count++;
  3963. }
  3964. }
  3965. memset(l, 0, sizeof(*l));
  3966. fields = upb_gmalloc(upb_msgdef_numfields(m) * sizeof(*fields));
  3967. submsgs = upb_gmalloc(submsg_count * sizeof(*submsgs));
  3968. if ((!fields && upb_msgdef_numfields(m)) ||
  3969. (!submsgs && submsg_count)) {
  3970. /* OOM. */
  3971. upb_gfree(fields);
  3972. upb_gfree(submsgs);
  3973. return false;
  3974. }
  3975. l->field_count = upb_msgdef_numfields(m);
  3976. l->fields = fields;
  3977. l->submsgs = submsgs;
  3978. /* Allocate data offsets in three stages:
  3979. *
  3980. * 1. hasbits.
  3981. * 2. regular fields.
  3982. * 3. oneof fields.
  3983. *
  3984. * OPT: There is a lot of room for optimization here to minimize the size.
  3985. */
  3986. /* Allocate hasbits and set basic field attributes. */
  3987. submsg_count = 0;
  3988. for (upb_msg_field_begin(&it, m), hasbit = 0;
  3989. !upb_msg_field_done(&it);
  3990. upb_msg_field_next(&it)) {
  3991. const upb_fielddef* f = upb_msg_iter_field(&it);
  3992. upb_msglayout_field *field = &fields[upb_fielddef_index(f)];
  3993. field->number = upb_fielddef_number(f);
  3994. field->descriptortype = upb_fielddef_descriptortype(f);
  3995. field->label = upb_fielddef_label(f);
  3996. if (upb_fielddef_issubmsg(f)) {
  3997. const upb_msglayout *sub_layout =
  3998. upb_msgfactory_getlayout(factory, upb_fielddef_msgsubdef(f));
  3999. field->submsg_index = submsg_count++;
  4000. submsgs[field->submsg_index] = sub_layout;
  4001. }
  4002. if (upb_fielddef_haspresence(f) && !upb_fielddef_containingoneof(f)) {
  4003. field->presence = (hasbit++);
  4004. } else {
  4005. field->presence = 0;
  4006. }
  4007. }
  4008. /* Account for space used by hasbits. */
  4009. l->size = div_round_up(hasbit, 8);
  4010. /* Allocate non-oneof fields. */
  4011. for (upb_msg_field_begin(&it, m); !upb_msg_field_done(&it);
  4012. upb_msg_field_next(&it)) {
  4013. const upb_fielddef* f = upb_msg_iter_field(&it);
  4014. size_t field_size = upb_msg_fielddefsize(f);
  4015. size_t index = upb_fielddef_index(f);
  4016. if (upb_fielddef_containingoneof(f)) {
  4017. /* Oneofs are handled separately below. */
  4018. continue;
  4019. }
  4020. fields[index].offset = upb_msglayout_place(l, field_size);
  4021. }
  4022. /* Allocate oneof fields. Each oneof field consists of a uint32 for the case
  4023. * and space for the actual data. */
  4024. for (upb_msg_oneof_begin(&oit, m); !upb_msg_oneof_done(&oit);
  4025. upb_msg_oneof_next(&oit)) {
  4026. const upb_oneofdef* o = upb_msg_iter_oneof(&oit);
  4027. upb_oneof_iter fit;
  4028. size_t case_size = sizeof(uint32_t); /* Could potentially optimize this. */
  4029. size_t field_size = 0;
  4030. uint32_t case_offset;
  4031. uint32_t data_offset;
  4032. /* Calculate field size: the max of all field sizes. */
  4033. for (upb_oneof_begin(&fit, o);
  4034. !upb_oneof_done(&fit);
  4035. upb_oneof_next(&fit)) {
  4036. const upb_fielddef* f = upb_oneof_iter_field(&fit);
  4037. field_size = UPB_MAX(field_size, upb_msg_fielddefsize(f));
  4038. }
  4039. /* Align and allocate case offset. */
  4040. case_offset = upb_msglayout_place(l, case_size);
  4041. data_offset = upb_msglayout_place(l, field_size);
  4042. for (upb_oneof_begin(&fit, o);
  4043. !upb_oneof_done(&fit);
  4044. upb_oneof_next(&fit)) {
  4045. const upb_fielddef* f = upb_oneof_iter_field(&fit);
  4046. fields[upb_fielddef_index(f)].offset = data_offset;
  4047. fields[upb_fielddef_index(f)].presence = ~case_offset;
  4048. }
  4049. }
  4050. /* Size of the entire structure should be a multiple of its greatest
  4051. * alignment. TODO: track overall alignment for real? */
  4052. l->size = align_up(l->size, 8);
  4053. return true;
  4054. }
  4055. /** upb_msgfactory ************************************************************/
  4056. struct upb_msgfactory {
  4057. const upb_symtab *symtab; /* We own a ref. */
  4058. upb_inttable layouts;
  4059. };
  4060. upb_msgfactory *upb_msgfactory_new(const upb_symtab *symtab) {
  4061. upb_msgfactory *ret = upb_gmalloc(sizeof(*ret));
  4062. ret->symtab = symtab;
  4063. upb_inttable_init(&ret->layouts, UPB_CTYPE_PTR);
  4064. return ret;
  4065. }
  4066. void upb_msgfactory_free(upb_msgfactory *f) {
  4067. upb_inttable_iter i;
  4068. upb_inttable_begin(&i, &f->layouts);
  4069. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  4070. upb_msglayout *l = upb_value_getptr(upb_inttable_iter_value(&i));
  4071. upb_msglayout_free(l);
  4072. }
  4073. upb_inttable_uninit(&f->layouts);
  4074. upb_gfree(f);
  4075. }
  4076. const upb_symtab *upb_msgfactory_symtab(const upb_msgfactory *f) {
  4077. return f->symtab;
  4078. }
  4079. const upb_msglayout *upb_msgfactory_getlayout(upb_msgfactory *f,
  4080. const upb_msgdef *m) {
  4081. upb_value v;
  4082. UPB_ASSERT(upb_symtab_lookupmsg(f->symtab, upb_msgdef_fullname(m)) == m);
  4083. UPB_ASSERT(!upb_msgdef_mapentry(m));
  4084. if (upb_inttable_lookupptr(&f->layouts, m, &v)) {
  4085. UPB_ASSERT(upb_value_getptr(v));
  4086. return upb_value_getptr(v);
  4087. } else {
  4088. /* In case of circular dependency, layout has to be inserted first. */
  4089. upb_msglayout *l = upb_gmalloc(sizeof(*l));
  4090. upb_msgfactory *mutable_f = (void*)f;
  4091. upb_inttable_insertptr(&mutable_f->layouts, m, upb_value_ptr(l));
  4092. UPB_ASSERT(l);
  4093. if (!upb_msglayout_init(m, l, f)) {
  4094. upb_msglayout_free(l);
  4095. }
  4096. return l;
  4097. }
  4098. }
  4099. /*
  4100. ** TODO(haberman): it's unclear whether a lot of the consistency checks should
  4101. ** UPB_ASSERT() or return false.
  4102. */
  4103. #include <string.h>
  4104. struct upb_handlers {
  4105. upb_handlercache *cache;
  4106. const upb_msgdef *msg;
  4107. const upb_handlers **sub;
  4108. const void *top_closure_type;
  4109. upb_handlers_tabent table[1]; /* Dynamically-sized field handler array. */
  4110. };
  4111. static void *upb_calloc(upb_arena *arena, size_t size) {
  4112. void *mem = upb_malloc(upb_arena_alloc(arena), size);
  4113. if (mem) {
  4114. memset(mem, 0, size);
  4115. }
  4116. return mem;
  4117. }
  4118. /* Defined for the sole purpose of having a unique pointer value for
  4119. * UPB_NO_CLOSURE. */
  4120. char _upb_noclosure;
  4121. /* Given a selector for a STARTSUBMSG handler, resolves to a pointer to the
  4122. * subhandlers for this submessage field. */
  4123. #define SUBH(h, selector) (h->sub[selector])
  4124. /* The selector for a submessage field is the field index. */
  4125. #define SUBH_F(h, f) SUBH(h, upb_fielddef_index(f))
  4126. static int32_t trygetsel(upb_handlers *h, const upb_fielddef *f,
  4127. upb_handlertype_t type) {
  4128. upb_selector_t sel;
  4129. bool ok;
  4130. ok = upb_handlers_getselector(f, type, &sel);
  4131. UPB_ASSERT(upb_handlers_msgdef(h) == upb_fielddef_containingtype(f));
  4132. UPB_ASSERT(ok);
  4133. return sel;
  4134. }
  4135. static upb_selector_t handlers_getsel(upb_handlers *h, const upb_fielddef *f,
  4136. upb_handlertype_t type) {
  4137. int32_t sel = trygetsel(h, f, type);
  4138. UPB_ASSERT(sel >= 0);
  4139. return sel;
  4140. }
  4141. static const void **returntype(upb_handlers *h, const upb_fielddef *f,
  4142. upb_handlertype_t type) {
  4143. return &h->table[handlers_getsel(h, f, type)].attr.return_closure_type;
  4144. }
  4145. static bool doset(upb_handlers *h, int32_t sel, const upb_fielddef *f,
  4146. upb_handlertype_t type, upb_func *func,
  4147. const upb_handlerattr *attr) {
  4148. upb_handlerattr set_attr = UPB_HANDLERATTR_INIT;
  4149. const void *closure_type;
  4150. const void **context_closure_type;
  4151. UPB_ASSERT(!h->table[sel].func);
  4152. if (attr) {
  4153. set_attr = *attr;
  4154. }
  4155. /* Check that the given closure type matches the closure type that has been
  4156. * established for this context (if any). */
  4157. closure_type = set_attr.closure_type;
  4158. if (type == UPB_HANDLER_STRING) {
  4159. context_closure_type = returntype(h, f, UPB_HANDLER_STARTSTR);
  4160. } else if (f && upb_fielddef_isseq(f) &&
  4161. type != UPB_HANDLER_STARTSEQ &&
  4162. type != UPB_HANDLER_ENDSEQ) {
  4163. context_closure_type = returntype(h, f, UPB_HANDLER_STARTSEQ);
  4164. } else {
  4165. context_closure_type = &h->top_closure_type;
  4166. }
  4167. if (closure_type && *context_closure_type &&
  4168. closure_type != *context_closure_type) {
  4169. return false;
  4170. }
  4171. if (closure_type)
  4172. *context_closure_type = closure_type;
  4173. /* If this is a STARTSEQ or STARTSTR handler, check that the returned pointer
  4174. * matches any pre-existing expectations about what type is expected. */
  4175. if (type == UPB_HANDLER_STARTSEQ || type == UPB_HANDLER_STARTSTR) {
  4176. const void *return_type = set_attr.return_closure_type;
  4177. const void *table_return_type = h->table[sel].attr.return_closure_type;
  4178. if (return_type && table_return_type && return_type != table_return_type) {
  4179. return false;
  4180. }
  4181. if (table_return_type && !return_type) {
  4182. set_attr.return_closure_type = table_return_type;
  4183. }
  4184. }
  4185. h->table[sel].func = (upb_func*)func;
  4186. h->table[sel].attr = set_attr;
  4187. return true;
  4188. }
  4189. /* Returns the effective closure type for this handler (which will propagate
  4190. * from outer frames if this frame has no START* handler). Not implemented for
  4191. * UPB_HANDLER_STRING at the moment since this is not needed. Returns NULL is
  4192. * the effective closure type is unspecified (either no handler was registered
  4193. * to specify it or the handler that was registered did not specify the closure
  4194. * type). */
  4195. const void *effective_closure_type(upb_handlers *h, const upb_fielddef *f,
  4196. upb_handlertype_t type) {
  4197. const void *ret;
  4198. upb_selector_t sel;
  4199. UPB_ASSERT(type != UPB_HANDLER_STRING);
  4200. ret = h->top_closure_type;
  4201. if (upb_fielddef_isseq(f) &&
  4202. type != UPB_HANDLER_STARTSEQ &&
  4203. type != UPB_HANDLER_ENDSEQ &&
  4204. h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSEQ)].func) {
  4205. ret = h->table[sel].attr.return_closure_type;
  4206. }
  4207. if (type == UPB_HANDLER_STRING &&
  4208. h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSTR)].func) {
  4209. ret = h->table[sel].attr.return_closure_type;
  4210. }
  4211. /* The effective type of the submessage; not used yet.
  4212. * if (type == SUBMESSAGE &&
  4213. * h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSUBMSG)].func) {
  4214. * ret = h->table[sel].attr.return_closure_type;
  4215. * } */
  4216. return ret;
  4217. }
  4218. /* Checks whether the START* handler specified by f & type is missing even
  4219. * though it is required to convert the established type of an outer frame
  4220. * ("closure_type") into the established type of an inner frame (represented in
  4221. * the return closure type of this handler's attr. */
  4222. bool checkstart(upb_handlers *h, const upb_fielddef *f, upb_handlertype_t type,
  4223. upb_status *status) {
  4224. const void *closure_type;
  4225. const upb_handlerattr *attr;
  4226. const void *return_closure_type;
  4227. upb_selector_t sel = handlers_getsel(h, f, type);
  4228. if (h->table[sel].func) return true;
  4229. closure_type = effective_closure_type(h, f, type);
  4230. attr = &h->table[sel].attr;
  4231. return_closure_type = attr->return_closure_type;
  4232. if (closure_type && return_closure_type &&
  4233. closure_type != return_closure_type) {
  4234. return false;
  4235. }
  4236. return true;
  4237. }
  4238. static upb_handlers *upb_handlers_new(const upb_msgdef *md,
  4239. upb_handlercache *cache,
  4240. upb_arena *arena) {
  4241. int extra;
  4242. upb_handlers *h;
  4243. extra = sizeof(upb_handlers_tabent) * (upb_msgdef_selectorcount(md) - 1);
  4244. h = upb_calloc(arena, sizeof(*h) + extra);
  4245. if (!h) return NULL;
  4246. h->cache = cache;
  4247. h->msg = md;
  4248. if (upb_msgdef_submsgfieldcount(md) > 0) {
  4249. size_t bytes = upb_msgdef_submsgfieldcount(md) * sizeof(*h->sub);
  4250. h->sub = upb_calloc(arena, bytes);
  4251. if (!h->sub) return NULL;
  4252. } else {
  4253. h->sub = 0;
  4254. }
  4255. /* calloc() above initialized all handlers to NULL. */
  4256. return h;
  4257. }
  4258. /* Public interface ***********************************************************/
  4259. #define SETTER(name, handlerctype, handlertype) \
  4260. bool upb_handlers_set##name(upb_handlers *h, const upb_fielddef *f, \
  4261. handlerctype func, \
  4262. const upb_handlerattr *attr) { \
  4263. int32_t sel = trygetsel(h, f, handlertype); \
  4264. return doset(h, sel, f, handlertype, (upb_func *)func, attr); \
  4265. }
  4266. SETTER(int32, upb_int32_handlerfunc*, UPB_HANDLER_INT32)
  4267. SETTER(int64, upb_int64_handlerfunc*, UPB_HANDLER_INT64)
  4268. SETTER(uint32, upb_uint32_handlerfunc*, UPB_HANDLER_UINT32)
  4269. SETTER(uint64, upb_uint64_handlerfunc*, UPB_HANDLER_UINT64)
  4270. SETTER(float, upb_float_handlerfunc*, UPB_HANDLER_FLOAT)
  4271. SETTER(double, upb_double_handlerfunc*, UPB_HANDLER_DOUBLE)
  4272. SETTER(bool, upb_bool_handlerfunc*, UPB_HANDLER_BOOL)
  4273. SETTER(startstr, upb_startstr_handlerfunc*, UPB_HANDLER_STARTSTR)
  4274. SETTER(string, upb_string_handlerfunc*, UPB_HANDLER_STRING)
  4275. SETTER(endstr, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSTR)
  4276. SETTER(startseq, upb_startfield_handlerfunc*, UPB_HANDLER_STARTSEQ)
  4277. SETTER(startsubmsg, upb_startfield_handlerfunc*, UPB_HANDLER_STARTSUBMSG)
  4278. SETTER(endsubmsg, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSUBMSG)
  4279. SETTER(endseq, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSEQ)
  4280. #undef SETTER
  4281. bool upb_handlers_setunknown(upb_handlers *h, upb_unknown_handlerfunc *func,
  4282. const upb_handlerattr *attr) {
  4283. return doset(h, UPB_UNKNOWN_SELECTOR, NULL, UPB_HANDLER_INT32,
  4284. (upb_func *)func, attr);
  4285. }
  4286. bool upb_handlers_setstartmsg(upb_handlers *h, upb_startmsg_handlerfunc *func,
  4287. const upb_handlerattr *attr) {
  4288. return doset(h, UPB_STARTMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
  4289. (upb_func *)func, attr);
  4290. }
  4291. bool upb_handlers_setendmsg(upb_handlers *h, upb_endmsg_handlerfunc *func,
  4292. const upb_handlerattr *attr) {
  4293. return doset(h, UPB_ENDMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
  4294. (upb_func *)func, attr);
  4295. }
  4296. bool upb_handlers_setsubhandlers(upb_handlers *h, const upb_fielddef *f,
  4297. const upb_handlers *sub) {
  4298. UPB_ASSERT(sub);
  4299. UPB_ASSERT(upb_fielddef_issubmsg(f));
  4300. if (SUBH_F(h, f)) return false; /* Can't reset. */
  4301. if (upb_handlers_msgdef(sub) != upb_fielddef_msgsubdef(f)) {
  4302. return false;
  4303. }
  4304. SUBH_F(h, f) = sub;
  4305. return true;
  4306. }
  4307. const upb_handlers *upb_handlers_getsubhandlers(const upb_handlers *h,
  4308. const upb_fielddef *f) {
  4309. UPB_ASSERT(upb_fielddef_issubmsg(f));
  4310. return SUBH_F(h, f);
  4311. }
  4312. upb_func *upb_handlers_gethandler(const upb_handlers *h, upb_selector_t s,
  4313. const void **handler_data) {
  4314. upb_func *ret = (upb_func *)h->table[s].func;
  4315. if (ret && handler_data) {
  4316. *handler_data = h->table[s].attr.handler_data;
  4317. }
  4318. return ret;
  4319. }
  4320. bool upb_handlers_getattr(const upb_handlers *h, upb_selector_t sel,
  4321. upb_handlerattr *attr) {
  4322. if (!upb_handlers_gethandler(h, sel, NULL))
  4323. return false;
  4324. *attr = h->table[sel].attr;
  4325. return true;
  4326. }
  4327. const upb_handlers *upb_handlers_getsubhandlers_sel(const upb_handlers *h,
  4328. upb_selector_t sel) {
  4329. /* STARTSUBMSG selector in sel is the field's selector base. */
  4330. return SUBH(h, sel - UPB_STATIC_SELECTOR_COUNT);
  4331. }
  4332. const upb_msgdef *upb_handlers_msgdef(const upb_handlers *h) { return h->msg; }
  4333. bool upb_handlers_addcleanup(upb_handlers *h, void *p, upb_handlerfree *func) {
  4334. return upb_handlercache_addcleanup(h->cache, p, func);
  4335. }
  4336. upb_handlertype_t upb_handlers_getprimitivehandlertype(const upb_fielddef *f) {
  4337. switch (upb_fielddef_type(f)) {
  4338. case UPB_TYPE_INT32:
  4339. case UPB_TYPE_ENUM: return UPB_HANDLER_INT32;
  4340. case UPB_TYPE_INT64: return UPB_HANDLER_INT64;
  4341. case UPB_TYPE_UINT32: return UPB_HANDLER_UINT32;
  4342. case UPB_TYPE_UINT64: return UPB_HANDLER_UINT64;
  4343. case UPB_TYPE_FLOAT: return UPB_HANDLER_FLOAT;
  4344. case UPB_TYPE_DOUBLE: return UPB_HANDLER_DOUBLE;
  4345. case UPB_TYPE_BOOL: return UPB_HANDLER_BOOL;
  4346. default: UPB_ASSERT(false); return -1; /* Invalid input. */
  4347. }
  4348. }
  4349. bool upb_handlers_getselector(const upb_fielddef *f, upb_handlertype_t type,
  4350. upb_selector_t *s) {
  4351. uint32_t selector_base = upb_fielddef_selectorbase(f);
  4352. switch (type) {
  4353. case UPB_HANDLER_INT32:
  4354. case UPB_HANDLER_INT64:
  4355. case UPB_HANDLER_UINT32:
  4356. case UPB_HANDLER_UINT64:
  4357. case UPB_HANDLER_FLOAT:
  4358. case UPB_HANDLER_DOUBLE:
  4359. case UPB_HANDLER_BOOL:
  4360. if (!upb_fielddef_isprimitive(f) ||
  4361. upb_handlers_getprimitivehandlertype(f) != type)
  4362. return false;
  4363. *s = selector_base;
  4364. break;
  4365. case UPB_HANDLER_STRING:
  4366. if (upb_fielddef_isstring(f)) {
  4367. *s = selector_base;
  4368. } else if (upb_fielddef_lazy(f)) {
  4369. *s = selector_base + 3;
  4370. } else {
  4371. return false;
  4372. }
  4373. break;
  4374. case UPB_HANDLER_STARTSTR:
  4375. if (upb_fielddef_isstring(f) || upb_fielddef_lazy(f)) {
  4376. *s = selector_base + 1;
  4377. } else {
  4378. return false;
  4379. }
  4380. break;
  4381. case UPB_HANDLER_ENDSTR:
  4382. if (upb_fielddef_isstring(f) || upb_fielddef_lazy(f)) {
  4383. *s = selector_base + 2;
  4384. } else {
  4385. return false;
  4386. }
  4387. break;
  4388. case UPB_HANDLER_STARTSEQ:
  4389. if (!upb_fielddef_isseq(f)) return false;
  4390. *s = selector_base - 2;
  4391. break;
  4392. case UPB_HANDLER_ENDSEQ:
  4393. if (!upb_fielddef_isseq(f)) return false;
  4394. *s = selector_base - 1;
  4395. break;
  4396. case UPB_HANDLER_STARTSUBMSG:
  4397. if (!upb_fielddef_issubmsg(f)) return false;
  4398. /* Selectors for STARTSUBMSG are at the beginning of the table so that the
  4399. * selector can also be used as an index into the "sub" array of
  4400. * subhandlers. The indexes for the two into these two tables are the
  4401. * same, except that in the handler table the static selectors come first. */
  4402. *s = upb_fielddef_index(f) + UPB_STATIC_SELECTOR_COUNT;
  4403. break;
  4404. case UPB_HANDLER_ENDSUBMSG:
  4405. if (!upb_fielddef_issubmsg(f)) return false;
  4406. *s = selector_base;
  4407. break;
  4408. }
  4409. UPB_ASSERT((size_t)*s < upb_msgdef_selectorcount(upb_fielddef_containingtype(f)));
  4410. return true;
  4411. }
  4412. /* upb_handlercache ***********************************************************/
  4413. struct upb_handlercache {
  4414. upb_arena *arena;
  4415. upb_inttable tab; /* maps upb_msgdef* -> upb_handlers*. */
  4416. upb_handlers_callback *callback;
  4417. const void *closure;
  4418. };
  4419. const upb_handlers *upb_handlercache_get(upb_handlercache *c,
  4420. const upb_msgdef *md) {
  4421. upb_msg_field_iter i;
  4422. upb_value v;
  4423. upb_handlers *h;
  4424. if (upb_inttable_lookupptr(&c->tab, md, &v)) {
  4425. return upb_value_getptr(v);
  4426. }
  4427. h = upb_handlers_new(md, c, c->arena);
  4428. v = upb_value_ptr(h);
  4429. if (!h) return NULL;
  4430. if (!upb_inttable_insertptr(&c->tab, md, v)) return NULL;
  4431. c->callback(c->closure, h);
  4432. /* For each submessage field, get or create a handlers object and set it as
  4433. * the subhandlers. */
  4434. for(upb_msg_field_begin(&i, md);
  4435. !upb_msg_field_done(&i);
  4436. upb_msg_field_next(&i)) {
  4437. upb_fielddef *f = upb_msg_iter_field(&i);
  4438. if (upb_fielddef_issubmsg(f)) {
  4439. const upb_msgdef *subdef = upb_fielddef_msgsubdef(f);
  4440. const upb_handlers *sub_mh = upb_handlercache_get(c, subdef);
  4441. if (!sub_mh) return NULL;
  4442. upb_handlers_setsubhandlers(h, f, sub_mh);
  4443. }
  4444. }
  4445. return h;
  4446. }
  4447. upb_handlercache *upb_handlercache_new(upb_handlers_callback *callback,
  4448. const void *closure) {
  4449. upb_handlercache *cache = upb_gmalloc(sizeof(*cache));
  4450. if (!cache) return NULL;
  4451. cache->arena = upb_arena_new();
  4452. cache->callback = callback;
  4453. cache->closure = closure;
  4454. if (!upb_inttable_init(&cache->tab, UPB_CTYPE_PTR)) goto oom;
  4455. return cache;
  4456. oom:
  4457. upb_gfree(cache);
  4458. return NULL;
  4459. }
  4460. void upb_handlercache_free(upb_handlercache *cache) {
  4461. upb_inttable_uninit(&cache->tab);
  4462. upb_arena_free(cache->arena);
  4463. upb_gfree(cache);
  4464. }
  4465. bool upb_handlercache_addcleanup(upb_handlercache *c, void *p,
  4466. upb_handlerfree *func) {
  4467. return upb_arena_addcleanup(c->arena, p, func);
  4468. }
  4469. /* upb_byteshandler ***********************************************************/
  4470. bool upb_byteshandler_setstartstr(upb_byteshandler *h,
  4471. upb_startstr_handlerfunc *func, void *d) {
  4472. h->table[UPB_STARTSTR_SELECTOR].func = (upb_func*)func;
  4473. h->table[UPB_STARTSTR_SELECTOR].attr.handler_data = d;
  4474. return true;
  4475. }
  4476. bool upb_byteshandler_setstring(upb_byteshandler *h,
  4477. upb_string_handlerfunc *func, void *d) {
  4478. h->table[UPB_STRING_SELECTOR].func = (upb_func*)func;
  4479. h->table[UPB_STRING_SELECTOR].attr.handler_data = d;
  4480. return true;
  4481. }
  4482. bool upb_byteshandler_setendstr(upb_byteshandler *h,
  4483. upb_endfield_handlerfunc *func, void *d) {
  4484. h->table[UPB_ENDSTR_SELECTOR].func = (upb_func*)func;
  4485. h->table[UPB_ENDSTR_SELECTOR].attr.handler_data = d;
  4486. return true;
  4487. }
  4488. /** Handlers for upb_msg ******************************************************/
  4489. typedef struct {
  4490. size_t offset;
  4491. int32_t hasbit;
  4492. } upb_msg_handlerdata;
  4493. /* Fallback implementation if the handler is not specialized by the producer. */
  4494. #define MSG_WRITER(type, ctype) \
  4495. bool upb_msg_set ## type (void *c, const void *hd, ctype val) { \
  4496. uint8_t *m = c; \
  4497. const upb_msg_handlerdata *d = hd; \
  4498. if (d->hasbit > 0) \
  4499. *(uint8_t*)&m[d->hasbit / 8] |= 1 << (d->hasbit % 8); \
  4500. *(ctype*)&m[d->offset] = val; \
  4501. return true; \
  4502. } \
  4503. MSG_WRITER(double, double)
  4504. MSG_WRITER(float, float)
  4505. MSG_WRITER(int32, int32_t)
  4506. MSG_WRITER(int64, int64_t)
  4507. MSG_WRITER(uint32, uint32_t)
  4508. MSG_WRITER(uint64, uint64_t)
  4509. MSG_WRITER(bool, bool)
  4510. bool upb_msg_setscalarhandler(upb_handlers *h, const upb_fielddef *f,
  4511. size_t offset, int32_t hasbit) {
  4512. upb_handlerattr attr = UPB_HANDLERATTR_INIT;
  4513. bool ok;
  4514. upb_msg_handlerdata *d = upb_gmalloc(sizeof(*d));
  4515. if (!d) return false;
  4516. d->offset = offset;
  4517. d->hasbit = hasbit;
  4518. attr.handler_data = d;
  4519. attr.alwaysok = true;
  4520. upb_handlers_addcleanup(h, d, upb_gfree);
  4521. #define TYPE(u, l) \
  4522. case UPB_TYPE_##u: \
  4523. ok = upb_handlers_set##l(h, f, upb_msg_set##l, &attr); break;
  4524. ok = false;
  4525. switch (upb_fielddef_type(f)) {
  4526. TYPE(INT64, int64);
  4527. TYPE(INT32, int32);
  4528. TYPE(ENUM, int32);
  4529. TYPE(UINT64, uint64);
  4530. TYPE(UINT32, uint32);
  4531. TYPE(DOUBLE, double);
  4532. TYPE(FLOAT, float);
  4533. TYPE(BOOL, bool);
  4534. default: UPB_ASSERT(false); break;
  4535. }
  4536. #undef TYPE
  4537. return ok;
  4538. }
  4539. bool upb_msg_getscalarhandlerdata(const upb_handlers *h,
  4540. upb_selector_t s,
  4541. upb_fieldtype_t *type,
  4542. size_t *offset,
  4543. int32_t *hasbit) {
  4544. const upb_msg_handlerdata *d;
  4545. const void *p;
  4546. upb_func *f = upb_handlers_gethandler(h, s, &p);
  4547. if ((upb_int64_handlerfunc*)f == upb_msg_setint64) {
  4548. *type = UPB_TYPE_INT64;
  4549. } else if ((upb_int32_handlerfunc*)f == upb_msg_setint32) {
  4550. *type = UPB_TYPE_INT32;
  4551. } else if ((upb_uint64_handlerfunc*)f == upb_msg_setuint64) {
  4552. *type = UPB_TYPE_UINT64;
  4553. } else if ((upb_uint32_handlerfunc*)f == upb_msg_setuint32) {
  4554. *type = UPB_TYPE_UINT32;
  4555. } else if ((upb_double_handlerfunc*)f == upb_msg_setdouble) {
  4556. *type = UPB_TYPE_DOUBLE;
  4557. } else if ((upb_float_handlerfunc*)f == upb_msg_setfloat) {
  4558. *type = UPB_TYPE_FLOAT;
  4559. } else if ((upb_bool_handlerfunc*)f == upb_msg_setbool) {
  4560. *type = UPB_TYPE_BOOL;
  4561. } else {
  4562. return false;
  4563. }
  4564. d = p;
  4565. *offset = d->offset;
  4566. *hasbit = d->hasbit;
  4567. return true;
  4568. }
  4569. bool upb_bufsrc_putbuf(const char *buf, size_t len, upb_bytessink sink) {
  4570. void *subc;
  4571. bool ret;
  4572. upb_bufhandle handle = UPB_BUFHANDLE_INIT;
  4573. handle.buf = buf;
  4574. ret = upb_bytessink_start(sink, len, &subc);
  4575. if (ret && len != 0) {
  4576. ret = (upb_bytessink_putbuf(sink, subc, buf, len, &handle) >= len);
  4577. }
  4578. if (ret) {
  4579. ret = upb_bytessink_end(sink);
  4580. }
  4581. return ret;
  4582. }
  4583. /*
  4584. ** protobuf decoder bytecode compiler
  4585. **
  4586. ** Code to compile a upb::Handlers into bytecode for decoding a protobuf
  4587. ** according to that specific schema and destination handlers.
  4588. **
  4589. ** Bytecode definition is in decoder.int.h.
  4590. */
  4591. #include <stdarg.h>
  4592. #ifdef UPB_DUMP_BYTECODE
  4593. #include <stdio.h>
  4594. #endif
  4595. #define MAXLABEL 5
  4596. #define EMPTYLABEL -1
  4597. /* upb_pbdecodermethod ********************************************************/
  4598. static void freemethod(upb_pbdecodermethod *method) {
  4599. upb_inttable_uninit(&method->dispatch);
  4600. upb_gfree(method);
  4601. }
  4602. static upb_pbdecodermethod *newmethod(const upb_handlers *dest_handlers,
  4603. mgroup *group) {
  4604. upb_pbdecodermethod *ret = upb_gmalloc(sizeof(*ret));
  4605. upb_byteshandler_init(&ret->input_handler_);
  4606. ret->group = group;
  4607. ret->dest_handlers_ = dest_handlers;
  4608. upb_inttable_init(&ret->dispatch, UPB_CTYPE_UINT64);
  4609. return ret;
  4610. }
  4611. const upb_handlers *upb_pbdecodermethod_desthandlers(
  4612. const upb_pbdecodermethod *m) {
  4613. return m->dest_handlers_;
  4614. }
  4615. const upb_byteshandler *upb_pbdecodermethod_inputhandler(
  4616. const upb_pbdecodermethod *m) {
  4617. return &m->input_handler_;
  4618. }
  4619. bool upb_pbdecodermethod_isnative(const upb_pbdecodermethod *m) {
  4620. return m->is_native_;
  4621. }
  4622. /* mgroup *********************************************************************/
  4623. static void freegroup(mgroup *g) {
  4624. upb_inttable_iter i;
  4625. upb_inttable_begin(&i, &g->methods);
  4626. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  4627. freemethod(upb_value_getptr(upb_inttable_iter_value(&i)));
  4628. }
  4629. upb_inttable_uninit(&g->methods);
  4630. upb_gfree(g->bytecode);
  4631. upb_gfree(g);
  4632. }
  4633. mgroup *newgroup(void) {
  4634. mgroup *g = upb_gmalloc(sizeof(*g));
  4635. upb_inttable_init(&g->methods, UPB_CTYPE_PTR);
  4636. g->bytecode = NULL;
  4637. g->bytecode_end = NULL;
  4638. return g;
  4639. }
  4640. /* bytecode compiler **********************************************************/
  4641. /* Data used only at compilation time. */
  4642. typedef struct {
  4643. mgroup *group;
  4644. uint32_t *pc;
  4645. int fwd_labels[MAXLABEL];
  4646. int back_labels[MAXLABEL];
  4647. /* For fields marked "lazy", parse them lazily or eagerly? */
  4648. bool lazy;
  4649. } compiler;
  4650. static compiler *newcompiler(mgroup *group, bool lazy) {
  4651. compiler *ret = upb_gmalloc(sizeof(*ret));
  4652. int i;
  4653. ret->group = group;
  4654. ret->lazy = lazy;
  4655. for (i = 0; i < MAXLABEL; i++) {
  4656. ret->fwd_labels[i] = EMPTYLABEL;
  4657. ret->back_labels[i] = EMPTYLABEL;
  4658. }
  4659. return ret;
  4660. }
  4661. static void freecompiler(compiler *c) {
  4662. upb_gfree(c);
  4663. }
  4664. const size_t ptr_words = sizeof(void*) / sizeof(uint32_t);
  4665. /* How many words an instruction is. */
  4666. static int instruction_len(uint32_t instr) {
  4667. switch (getop(instr)) {
  4668. case OP_SETDISPATCH: return 1 + ptr_words;
  4669. case OP_TAGN: return 3;
  4670. case OP_SETBIGGROUPNUM: return 2;
  4671. default: return 1;
  4672. }
  4673. }
  4674. bool op_has_longofs(int32_t instruction) {
  4675. switch (getop(instruction)) {
  4676. case OP_CALL:
  4677. case OP_BRANCH:
  4678. case OP_CHECKDELIM:
  4679. return true;
  4680. /* The "tag" instructions only have 8 bytes available for the jump target,
  4681. * but that is ok because these opcodes only require short jumps. */
  4682. case OP_TAG1:
  4683. case OP_TAG2:
  4684. case OP_TAGN:
  4685. return false;
  4686. default:
  4687. UPB_ASSERT(false);
  4688. return false;
  4689. }
  4690. }
  4691. static int32_t getofs(uint32_t instruction) {
  4692. if (op_has_longofs(instruction)) {
  4693. return (int32_t)instruction >> 8;
  4694. } else {
  4695. return (int8_t)(instruction >> 8);
  4696. }
  4697. }
  4698. static void setofs(uint32_t *instruction, int32_t ofs) {
  4699. if (op_has_longofs(*instruction)) {
  4700. *instruction = getop(*instruction) | (uint32_t)ofs << 8;
  4701. } else {
  4702. *instruction = (*instruction & ~0xff00) | ((ofs & 0xff) << 8);
  4703. }
  4704. UPB_ASSERT(getofs(*instruction) == ofs); /* Would fail in cases of overflow. */
  4705. }
  4706. static uint32_t pcofs(compiler *c) { return c->pc - c->group->bytecode; }
  4707. /* Defines a local label at the current PC location. All previous forward
  4708. * references are updated to point to this location. The location is noted
  4709. * for any future backward references. */
  4710. static void label(compiler *c, unsigned int label) {
  4711. int val;
  4712. uint32_t *codep;
  4713. UPB_ASSERT(label < MAXLABEL);
  4714. val = c->fwd_labels[label];
  4715. codep = (val == EMPTYLABEL) ? NULL : c->group->bytecode + val;
  4716. while (codep) {
  4717. int ofs = getofs(*codep);
  4718. setofs(codep, c->pc - codep - instruction_len(*codep));
  4719. codep = ofs ? codep + ofs : NULL;
  4720. }
  4721. c->fwd_labels[label] = EMPTYLABEL;
  4722. c->back_labels[label] = pcofs(c);
  4723. }
  4724. /* Creates a reference to a numbered label; either a forward reference
  4725. * (positive arg) or backward reference (negative arg). For forward references
  4726. * the value returned now is actually a "next" pointer into a linked list of all
  4727. * instructions that use this label and will be patched later when the label is
  4728. * defined with label().
  4729. *
  4730. * The returned value is the offset that should be written into the instruction.
  4731. */
  4732. static int32_t labelref(compiler *c, int label) {
  4733. UPB_ASSERT(label < MAXLABEL);
  4734. if (label == LABEL_DISPATCH) {
  4735. /* No resolving required. */
  4736. return 0;
  4737. } else if (label < 0) {
  4738. /* Backward local label. Relative to the next instruction. */
  4739. uint32_t from = (c->pc + 1) - c->group->bytecode;
  4740. return c->back_labels[-label] - from;
  4741. } else {
  4742. /* Forward local label: prepend to (possibly-empty) linked list. */
  4743. int *lptr = &c->fwd_labels[label];
  4744. int32_t ret = (*lptr == EMPTYLABEL) ? 0 : *lptr - pcofs(c);
  4745. *lptr = pcofs(c);
  4746. return ret;
  4747. }
  4748. }
  4749. static void put32(compiler *c, uint32_t v) {
  4750. mgroup *g = c->group;
  4751. if (c->pc == g->bytecode_end) {
  4752. int ofs = pcofs(c);
  4753. size_t oldsize = g->bytecode_end - g->bytecode;
  4754. size_t newsize = UPB_MAX(oldsize * 2, 64);
  4755. /* TODO(haberman): handle OOM. */
  4756. g->bytecode = upb_grealloc(g->bytecode, oldsize * sizeof(uint32_t),
  4757. newsize * sizeof(uint32_t));
  4758. g->bytecode_end = g->bytecode + newsize;
  4759. c->pc = g->bytecode + ofs;
  4760. }
  4761. *c->pc++ = v;
  4762. }
  4763. static void putop(compiler *c, int op, ...) {
  4764. va_list ap;
  4765. va_start(ap, op);
  4766. switch (op) {
  4767. case OP_SETDISPATCH: {
  4768. uintptr_t ptr = (uintptr_t)va_arg(ap, void*);
  4769. put32(c, OP_SETDISPATCH);
  4770. put32(c, ptr);
  4771. if (sizeof(uintptr_t) > sizeof(uint32_t))
  4772. put32(c, (uint64_t)ptr >> 32);
  4773. break;
  4774. }
  4775. case OP_STARTMSG:
  4776. case OP_ENDMSG:
  4777. case OP_PUSHLENDELIM:
  4778. case OP_POP:
  4779. case OP_SETDELIM:
  4780. case OP_HALT:
  4781. case OP_RET:
  4782. case OP_DISPATCH:
  4783. put32(c, op);
  4784. break;
  4785. case OP_PARSE_DOUBLE:
  4786. case OP_PARSE_FLOAT:
  4787. case OP_PARSE_INT64:
  4788. case OP_PARSE_UINT64:
  4789. case OP_PARSE_INT32:
  4790. case OP_PARSE_FIXED64:
  4791. case OP_PARSE_FIXED32:
  4792. case OP_PARSE_BOOL:
  4793. case OP_PARSE_UINT32:
  4794. case OP_PARSE_SFIXED32:
  4795. case OP_PARSE_SFIXED64:
  4796. case OP_PARSE_SINT32:
  4797. case OP_PARSE_SINT64:
  4798. case OP_STARTSEQ:
  4799. case OP_ENDSEQ:
  4800. case OP_STARTSUBMSG:
  4801. case OP_ENDSUBMSG:
  4802. case OP_STARTSTR:
  4803. case OP_STRING:
  4804. case OP_ENDSTR:
  4805. case OP_PUSHTAGDELIM:
  4806. put32(c, op | va_arg(ap, upb_selector_t) << 8);
  4807. break;
  4808. case OP_SETBIGGROUPNUM:
  4809. put32(c, op);
  4810. put32(c, va_arg(ap, int));
  4811. break;
  4812. case OP_CALL: {
  4813. const upb_pbdecodermethod *method = va_arg(ap, upb_pbdecodermethod *);
  4814. put32(c, op | (method->code_base.ofs - (pcofs(c) + 1)) << 8);
  4815. break;
  4816. }
  4817. case OP_CHECKDELIM:
  4818. case OP_BRANCH: {
  4819. uint32_t instruction = op;
  4820. int label = va_arg(ap, int);
  4821. setofs(&instruction, labelref(c, label));
  4822. put32(c, instruction);
  4823. break;
  4824. }
  4825. case OP_TAG1:
  4826. case OP_TAG2: {
  4827. int label = va_arg(ap, int);
  4828. uint64_t tag = va_arg(ap, uint64_t);
  4829. uint32_t instruction = op | (tag << 16);
  4830. UPB_ASSERT(tag <= 0xffff);
  4831. setofs(&instruction, labelref(c, label));
  4832. put32(c, instruction);
  4833. break;
  4834. }
  4835. case OP_TAGN: {
  4836. int label = va_arg(ap, int);
  4837. uint64_t tag = va_arg(ap, uint64_t);
  4838. uint32_t instruction = op | (upb_value_size(tag) << 16);
  4839. setofs(&instruction, labelref(c, label));
  4840. put32(c, instruction);
  4841. put32(c, tag);
  4842. put32(c, tag >> 32);
  4843. break;
  4844. }
  4845. }
  4846. va_end(ap);
  4847. }
  4848. #if defined(UPB_DUMP_BYTECODE)
  4849. const char *upb_pbdecoder_getopname(unsigned int op) {
  4850. #define QUOTE(x) #x
  4851. #define EXPAND_AND_QUOTE(x) QUOTE(x)
  4852. #define OPNAME(x) OP_##x
  4853. #define OP(x) case OPNAME(x): return EXPAND_AND_QUOTE(OPNAME(x));
  4854. #define T(x) OP(PARSE_##x)
  4855. /* Keep in sync with list in decoder.int.h. */
  4856. switch ((opcode)op) {
  4857. T(DOUBLE) T(FLOAT) T(INT64) T(UINT64) T(INT32) T(FIXED64) T(FIXED32)
  4858. T(BOOL) T(UINT32) T(SFIXED32) T(SFIXED64) T(SINT32) T(SINT64)
  4859. OP(STARTMSG) OP(ENDMSG) OP(STARTSEQ) OP(ENDSEQ) OP(STARTSUBMSG)
  4860. OP(ENDSUBMSG) OP(STARTSTR) OP(STRING) OP(ENDSTR) OP(CALL) OP(RET)
  4861. OP(PUSHLENDELIM) OP(PUSHTAGDELIM) OP(SETDELIM) OP(CHECKDELIM)
  4862. OP(BRANCH) OP(TAG1) OP(TAG2) OP(TAGN) OP(SETDISPATCH) OP(POP)
  4863. OP(SETBIGGROUPNUM) OP(DISPATCH) OP(HALT)
  4864. }
  4865. return "<unknown op>";
  4866. #undef OP
  4867. #undef T
  4868. }
  4869. #endif
  4870. #ifdef UPB_DUMP_BYTECODE
  4871. static void dumpbc(uint32_t *p, uint32_t *end, FILE *f) {
  4872. uint32_t *begin = p;
  4873. while (p < end) {
  4874. fprintf(f, "%p %8tx", p, p - begin);
  4875. uint32_t instr = *p++;
  4876. uint8_t op = getop(instr);
  4877. fprintf(f, " %s", upb_pbdecoder_getopname(op));
  4878. switch ((opcode)op) {
  4879. case OP_SETDISPATCH: {
  4880. const upb_inttable *dispatch;
  4881. memcpy(&dispatch, p, sizeof(void*));
  4882. p += ptr_words;
  4883. const upb_pbdecodermethod *method =
  4884. (void *)((char *)dispatch -
  4885. offsetof(upb_pbdecodermethod, dispatch));
  4886. fprintf(f, " %s", upb_msgdef_fullname(
  4887. upb_handlers_msgdef(method->dest_handlers_)));
  4888. break;
  4889. }
  4890. case OP_DISPATCH:
  4891. case OP_STARTMSG:
  4892. case OP_ENDMSG:
  4893. case OP_PUSHLENDELIM:
  4894. case OP_POP:
  4895. case OP_SETDELIM:
  4896. case OP_HALT:
  4897. case OP_RET:
  4898. break;
  4899. case OP_PARSE_DOUBLE:
  4900. case OP_PARSE_FLOAT:
  4901. case OP_PARSE_INT64:
  4902. case OP_PARSE_UINT64:
  4903. case OP_PARSE_INT32:
  4904. case OP_PARSE_FIXED64:
  4905. case OP_PARSE_FIXED32:
  4906. case OP_PARSE_BOOL:
  4907. case OP_PARSE_UINT32:
  4908. case OP_PARSE_SFIXED32:
  4909. case OP_PARSE_SFIXED64:
  4910. case OP_PARSE_SINT32:
  4911. case OP_PARSE_SINT64:
  4912. case OP_STARTSEQ:
  4913. case OP_ENDSEQ:
  4914. case OP_STARTSUBMSG:
  4915. case OP_ENDSUBMSG:
  4916. case OP_STARTSTR:
  4917. case OP_STRING:
  4918. case OP_ENDSTR:
  4919. case OP_PUSHTAGDELIM:
  4920. fprintf(f, " %d", instr >> 8);
  4921. break;
  4922. case OP_SETBIGGROUPNUM:
  4923. fprintf(f, " %d", *p++);
  4924. break;
  4925. case OP_CHECKDELIM:
  4926. case OP_CALL:
  4927. case OP_BRANCH:
  4928. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  4929. break;
  4930. case OP_TAG1:
  4931. case OP_TAG2: {
  4932. fprintf(f, " tag:0x%x", instr >> 16);
  4933. if (getofs(instr)) {
  4934. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  4935. }
  4936. break;
  4937. }
  4938. case OP_TAGN: {
  4939. uint64_t tag = *p++;
  4940. tag |= (uint64_t)*p++ << 32;
  4941. fprintf(f, " tag:0x%llx", (long long)tag);
  4942. fprintf(f, " n:%d", instr >> 16);
  4943. if (getofs(instr)) {
  4944. fprintf(f, " =>0x%tx", p + getofs(instr) - begin);
  4945. }
  4946. break;
  4947. }
  4948. }
  4949. fputs("\n", f);
  4950. }
  4951. }
  4952. #endif
  4953. static uint64_t get_encoded_tag(const upb_fielddef *f, int wire_type) {
  4954. uint32_t tag = (upb_fielddef_number(f) << 3) | wire_type;
  4955. uint64_t encoded_tag = upb_vencode32(tag);
  4956. /* No tag should be greater than 5 bytes. */
  4957. UPB_ASSERT(encoded_tag <= 0xffffffffff);
  4958. return encoded_tag;
  4959. }
  4960. static void putchecktag(compiler *c, const upb_fielddef *f,
  4961. int wire_type, int dest) {
  4962. uint64_t tag = get_encoded_tag(f, wire_type);
  4963. switch (upb_value_size(tag)) {
  4964. case 1:
  4965. putop(c, OP_TAG1, dest, tag);
  4966. break;
  4967. case 2:
  4968. putop(c, OP_TAG2, dest, tag);
  4969. break;
  4970. default:
  4971. putop(c, OP_TAGN, dest, tag);
  4972. break;
  4973. }
  4974. }
  4975. static upb_selector_t getsel(const upb_fielddef *f, upb_handlertype_t type) {
  4976. upb_selector_t selector;
  4977. bool ok = upb_handlers_getselector(f, type, &selector);
  4978. UPB_ASSERT(ok);
  4979. return selector;
  4980. }
  4981. /* Takes an existing, primary dispatch table entry and repacks it with a
  4982. * different alternate wire type. Called when we are inserting a secondary
  4983. * dispatch table entry for an alternate wire type. */
  4984. static uint64_t repack(uint64_t dispatch, int new_wt2) {
  4985. uint64_t ofs;
  4986. uint8_t wt1;
  4987. uint8_t old_wt2;
  4988. upb_pbdecoder_unpackdispatch(dispatch, &ofs, &wt1, &old_wt2);
  4989. UPB_ASSERT(old_wt2 == NO_WIRE_TYPE); /* wt2 should not be set yet. */
  4990. return upb_pbdecoder_packdispatch(ofs, wt1, new_wt2);
  4991. }
  4992. /* Marks the current bytecode position as the dispatch target for this message,
  4993. * field, and wire type. */
  4994. static void dispatchtarget(compiler *c, upb_pbdecodermethod *method,
  4995. const upb_fielddef *f, int wire_type) {
  4996. /* Offset is relative to msg base. */
  4997. uint64_t ofs = pcofs(c) - method->code_base.ofs;
  4998. uint32_t fn = upb_fielddef_number(f);
  4999. upb_inttable *d = &method->dispatch;
  5000. upb_value v;
  5001. if (upb_inttable_remove(d, fn, &v)) {
  5002. /* TODO: prioritize based on packed setting in .proto file. */
  5003. uint64_t repacked = repack(upb_value_getuint64(v), wire_type);
  5004. upb_inttable_insert(d, fn, upb_value_uint64(repacked));
  5005. upb_inttable_insert(d, fn + UPB_MAX_FIELDNUMBER, upb_value_uint64(ofs));
  5006. } else {
  5007. uint64_t val = upb_pbdecoder_packdispatch(ofs, wire_type, NO_WIRE_TYPE);
  5008. upb_inttable_insert(d, fn, upb_value_uint64(val));
  5009. }
  5010. }
  5011. static void putpush(compiler *c, const upb_fielddef *f) {
  5012. if (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE) {
  5013. putop(c, OP_PUSHLENDELIM);
  5014. } else {
  5015. uint32_t fn = upb_fielddef_number(f);
  5016. if (fn >= 1 << 24) {
  5017. putop(c, OP_PUSHTAGDELIM, 0);
  5018. putop(c, OP_SETBIGGROUPNUM, fn);
  5019. } else {
  5020. putop(c, OP_PUSHTAGDELIM, fn);
  5021. }
  5022. }
  5023. }
  5024. static upb_pbdecodermethod *find_submethod(const compiler *c,
  5025. const upb_pbdecodermethod *method,
  5026. const upb_fielddef *f) {
  5027. const upb_handlers *sub =
  5028. upb_handlers_getsubhandlers(method->dest_handlers_, f);
  5029. upb_value v;
  5030. return upb_inttable_lookupptr(&c->group->methods, sub, &v)
  5031. ? upb_value_getptr(v)
  5032. : NULL;
  5033. }
  5034. static void putsel(compiler *c, opcode op, upb_selector_t sel,
  5035. const upb_handlers *h) {
  5036. if (upb_handlers_gethandler(h, sel, NULL)) {
  5037. putop(c, op, sel);
  5038. }
  5039. }
  5040. /* Puts an opcode to call a callback, but only if a callback actually exists for
  5041. * this field and handler type. */
  5042. static void maybeput(compiler *c, opcode op, const upb_handlers *h,
  5043. const upb_fielddef *f, upb_handlertype_t type) {
  5044. putsel(c, op, getsel(f, type), h);
  5045. }
  5046. static bool haslazyhandlers(const upb_handlers *h, const upb_fielddef *f) {
  5047. if (!upb_fielddef_lazy(f))
  5048. return false;
  5049. return upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STARTSTR), NULL) ||
  5050. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STRING), NULL) ||
  5051. upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_ENDSTR), NULL);
  5052. }
  5053. /* bytecode compiler code generation ******************************************/
  5054. /* Symbolic names for our local labels. */
  5055. #define LABEL_LOOPSTART 1 /* Top of a repeated field loop. */
  5056. #define LABEL_LOOPBREAK 2 /* To jump out of a repeated loop */
  5057. #define LABEL_FIELD 3 /* Jump backward to find the most recent field. */
  5058. #define LABEL_ENDMSG 4 /* To reach the OP_ENDMSG instr for this msg. */
  5059. /* Generates bytecode to parse a single non-lazy message field. */
  5060. static void generate_msgfield(compiler *c, const upb_fielddef *f,
  5061. upb_pbdecodermethod *method) {
  5062. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  5063. const upb_pbdecodermethod *sub_m = find_submethod(c, method, f);
  5064. int wire_type;
  5065. if (!sub_m) {
  5066. /* Don't emit any code for this field at all; it will be parsed as an
  5067. * unknown field.
  5068. *
  5069. * TODO(haberman): we should change this to parse it as a string field
  5070. * instead. It will probably be faster, but more importantly, once we
  5071. * start vending unknown fields, a field shouldn't be treated as unknown
  5072. * just because it doesn't have subhandlers registered. */
  5073. return;
  5074. }
  5075. label(c, LABEL_FIELD);
  5076. wire_type =
  5077. (upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_MESSAGE)
  5078. ? UPB_WIRE_TYPE_DELIMITED
  5079. : UPB_WIRE_TYPE_START_GROUP;
  5080. if (upb_fielddef_isseq(f)) {
  5081. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5082. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  5083. dispatchtarget(c, method, f, wire_type);
  5084. putop(c, OP_PUSHTAGDELIM, 0);
  5085. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  5086. label(c, LABEL_LOOPSTART);
  5087. putpush(c, f);
  5088. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  5089. putop(c, OP_CALL, sub_m);
  5090. putop(c, OP_POP);
  5091. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  5092. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  5093. putop(c, OP_SETDELIM);
  5094. }
  5095. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5096. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  5097. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5098. label(c, LABEL_LOOPBREAK);
  5099. putop(c, OP_POP);
  5100. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  5101. } else {
  5102. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5103. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  5104. dispatchtarget(c, method, f, wire_type);
  5105. putpush(c, f);
  5106. putop(c, OP_STARTSUBMSG, getsel(f, UPB_HANDLER_STARTSUBMSG));
  5107. putop(c, OP_CALL, sub_m);
  5108. putop(c, OP_POP);
  5109. maybeput(c, OP_ENDSUBMSG, h, f, UPB_HANDLER_ENDSUBMSG);
  5110. if (wire_type == UPB_WIRE_TYPE_DELIMITED) {
  5111. putop(c, OP_SETDELIM);
  5112. }
  5113. }
  5114. }
  5115. /* Generates bytecode to parse a single string or lazy submessage field. */
  5116. static void generate_delimfield(compiler *c, const upb_fielddef *f,
  5117. upb_pbdecodermethod *method) {
  5118. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  5119. label(c, LABEL_FIELD);
  5120. if (upb_fielddef_isseq(f)) {
  5121. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5122. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  5123. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  5124. putop(c, OP_PUSHTAGDELIM, 0);
  5125. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ));
  5126. label(c, LABEL_LOOPSTART);
  5127. putop(c, OP_PUSHLENDELIM);
  5128. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  5129. /* Need to emit even if no handler to skip past the string. */
  5130. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  5131. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  5132. putop(c, OP_POP);
  5133. putop(c, OP_SETDELIM);
  5134. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5135. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_LOOPBREAK);
  5136. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5137. label(c, LABEL_LOOPBREAK);
  5138. putop(c, OP_POP);
  5139. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  5140. } else {
  5141. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5142. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  5143. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  5144. putop(c, OP_PUSHLENDELIM);
  5145. putop(c, OP_STARTSTR, getsel(f, UPB_HANDLER_STARTSTR));
  5146. putop(c, OP_STRING, getsel(f, UPB_HANDLER_STRING));
  5147. maybeput(c, OP_ENDSTR, h, f, UPB_HANDLER_ENDSTR);
  5148. putop(c, OP_POP);
  5149. putop(c, OP_SETDELIM);
  5150. }
  5151. }
  5152. /* Generates bytecode to parse a single primitive field. */
  5153. static void generate_primitivefield(compiler *c, const upb_fielddef *f,
  5154. upb_pbdecodermethod *method) {
  5155. const upb_handlers *h = upb_pbdecodermethod_desthandlers(method);
  5156. upb_descriptortype_t descriptor_type = upb_fielddef_descriptortype(f);
  5157. opcode parse_type;
  5158. upb_selector_t sel;
  5159. int wire_type;
  5160. label(c, LABEL_FIELD);
  5161. /* From a decoding perspective, ENUM is the same as INT32. */
  5162. if (descriptor_type == UPB_DESCRIPTOR_TYPE_ENUM)
  5163. descriptor_type = UPB_DESCRIPTOR_TYPE_INT32;
  5164. parse_type = (opcode)descriptor_type;
  5165. /* TODO(haberman): generate packed or non-packed first depending on "packed"
  5166. * setting in the fielddef. This will favor (in speed) whichever was
  5167. * specified. */
  5168. UPB_ASSERT((int)parse_type >= 0 && parse_type <= OP_MAX);
  5169. sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  5170. wire_type = upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  5171. if (upb_fielddef_isseq(f)) {
  5172. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5173. putchecktag(c, f, UPB_WIRE_TYPE_DELIMITED, LABEL_DISPATCH);
  5174. dispatchtarget(c, method, f, UPB_WIRE_TYPE_DELIMITED);
  5175. putop(c, OP_PUSHLENDELIM);
  5176. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); /* Packed */
  5177. label(c, LABEL_LOOPSTART);
  5178. putop(c, parse_type, sel);
  5179. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5180. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5181. dispatchtarget(c, method, f, wire_type);
  5182. putop(c, OP_PUSHTAGDELIM, 0);
  5183. putop(c, OP_STARTSEQ, getsel(f, UPB_HANDLER_STARTSEQ)); /* Non-packed */
  5184. label(c, LABEL_LOOPSTART);
  5185. putop(c, parse_type, sel);
  5186. putop(c, OP_CHECKDELIM, LABEL_LOOPBREAK);
  5187. putchecktag(c, f, wire_type, LABEL_LOOPBREAK);
  5188. putop(c, OP_BRANCH, -LABEL_LOOPSTART);
  5189. label(c, LABEL_LOOPBREAK);
  5190. putop(c, OP_POP); /* Packed and non-packed join. */
  5191. maybeput(c, OP_ENDSEQ, h, f, UPB_HANDLER_ENDSEQ);
  5192. putop(c, OP_SETDELIM); /* Could remove for non-packed by dup ENDSEQ. */
  5193. } else {
  5194. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5195. putchecktag(c, f, wire_type, LABEL_DISPATCH);
  5196. dispatchtarget(c, method, f, wire_type);
  5197. putop(c, parse_type, sel);
  5198. }
  5199. }
  5200. /* Adds bytecode for parsing the given message to the given decoderplan,
  5201. * while adding all dispatch targets to this message's dispatch table. */
  5202. static void compile_method(compiler *c, upb_pbdecodermethod *method) {
  5203. const upb_handlers *h;
  5204. const upb_msgdef *md;
  5205. uint32_t* start_pc;
  5206. upb_msg_field_iter i;
  5207. upb_value val;
  5208. UPB_ASSERT(method);
  5209. /* Clear all entries in the dispatch table. */
  5210. upb_inttable_uninit(&method->dispatch);
  5211. upb_inttable_init(&method->dispatch, UPB_CTYPE_UINT64);
  5212. h = upb_pbdecodermethod_desthandlers(method);
  5213. md = upb_handlers_msgdef(h);
  5214. method->code_base.ofs = pcofs(c);
  5215. putop(c, OP_SETDISPATCH, &method->dispatch);
  5216. putsel(c, OP_STARTMSG, UPB_STARTMSG_SELECTOR, h);
  5217. label(c, LABEL_FIELD);
  5218. start_pc = c->pc;
  5219. for(upb_msg_field_begin(&i, md);
  5220. !upb_msg_field_done(&i);
  5221. upb_msg_field_next(&i)) {
  5222. const upb_fielddef *f = upb_msg_iter_field(&i);
  5223. upb_fieldtype_t type = upb_fielddef_type(f);
  5224. if (type == UPB_TYPE_MESSAGE && !(haslazyhandlers(h, f) && c->lazy)) {
  5225. generate_msgfield(c, f, method);
  5226. } else if (type == UPB_TYPE_STRING || type == UPB_TYPE_BYTES ||
  5227. type == UPB_TYPE_MESSAGE) {
  5228. generate_delimfield(c, f, method);
  5229. } else {
  5230. generate_primitivefield(c, f, method);
  5231. }
  5232. }
  5233. /* If there were no fields, or if no handlers were defined, we need to
  5234. * generate a non-empty loop body so that we can at least dispatch for unknown
  5235. * fields and check for the end of the message. */
  5236. if (c->pc == start_pc) {
  5237. /* Check for end-of-message. */
  5238. putop(c, OP_CHECKDELIM, LABEL_ENDMSG);
  5239. /* Unconditionally dispatch. */
  5240. putop(c, OP_DISPATCH, 0);
  5241. }
  5242. /* For now we just loop back to the last field of the message (or if none,
  5243. * the DISPATCH opcode for the message). */
  5244. putop(c, OP_BRANCH, -LABEL_FIELD);
  5245. /* Insert both a label and a dispatch table entry for this end-of-msg. */
  5246. label(c, LABEL_ENDMSG);
  5247. val = upb_value_uint64(pcofs(c) - method->code_base.ofs);
  5248. upb_inttable_insert(&method->dispatch, DISPATCH_ENDMSG, val);
  5249. putsel(c, OP_ENDMSG, UPB_ENDMSG_SELECTOR, h);
  5250. putop(c, OP_RET);
  5251. upb_inttable_compact(&method->dispatch);
  5252. }
  5253. /* Populate "methods" with new upb_pbdecodermethod objects reachable from "h".
  5254. * Returns the method for these handlers.
  5255. *
  5256. * Generates a new method for every destination handlers reachable from "h". */
  5257. static void find_methods(compiler *c, const upb_handlers *h) {
  5258. upb_value v;
  5259. upb_msg_field_iter i;
  5260. const upb_msgdef *md;
  5261. upb_pbdecodermethod *method;
  5262. if (upb_inttable_lookupptr(&c->group->methods, h, &v))
  5263. return;
  5264. method = newmethod(h, c->group);
  5265. upb_inttable_insertptr(&c->group->methods, h, upb_value_ptr(method));
  5266. /* Find submethods. */
  5267. md = upb_handlers_msgdef(h);
  5268. for(upb_msg_field_begin(&i, md);
  5269. !upb_msg_field_done(&i);
  5270. upb_msg_field_next(&i)) {
  5271. const upb_fielddef *f = upb_msg_iter_field(&i);
  5272. const upb_handlers *sub_h;
  5273. if (upb_fielddef_type(f) == UPB_TYPE_MESSAGE &&
  5274. (sub_h = upb_handlers_getsubhandlers(h, f)) != NULL) {
  5275. /* We only generate a decoder method for submessages with handlers.
  5276. * Others will be parsed as unknown fields. */
  5277. find_methods(c, sub_h);
  5278. }
  5279. }
  5280. }
  5281. /* (Re-)compile bytecode for all messages in "msgs."
  5282. * Overwrites any existing bytecode in "c". */
  5283. static void compile_methods(compiler *c) {
  5284. upb_inttable_iter i;
  5285. /* Start over at the beginning of the bytecode. */
  5286. c->pc = c->group->bytecode;
  5287. upb_inttable_begin(&i, &c->group->methods);
  5288. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5289. upb_pbdecodermethod *method = upb_value_getptr(upb_inttable_iter_value(&i));
  5290. compile_method(c, method);
  5291. }
  5292. }
  5293. static void set_bytecode_handlers(mgroup *g) {
  5294. upb_inttable_iter i;
  5295. upb_inttable_begin(&i, &g->methods);
  5296. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5297. upb_pbdecodermethod *m = upb_value_getptr(upb_inttable_iter_value(&i));
  5298. upb_byteshandler *h = &m->input_handler_;
  5299. m->code_base.ptr = g->bytecode + m->code_base.ofs;
  5300. upb_byteshandler_setstartstr(h, upb_pbdecoder_startbc, m->code_base.ptr);
  5301. upb_byteshandler_setstring(h, upb_pbdecoder_decode, g);
  5302. upb_byteshandler_setendstr(h, upb_pbdecoder_end, m);
  5303. }
  5304. }
  5305. /* TODO(haberman): allow this to be constructed for an arbitrary set of dest
  5306. * handlers and other mgroups (but verify we have a transitive closure). */
  5307. const mgroup *mgroup_new(const upb_handlers *dest, bool lazy) {
  5308. mgroup *g;
  5309. compiler *c;
  5310. g = newgroup();
  5311. c = newcompiler(g, lazy);
  5312. find_methods(c, dest);
  5313. /* We compile in two passes:
  5314. * 1. all messages are assigned relative offsets from the beginning of the
  5315. * bytecode (saved in method->code_base).
  5316. * 2. forwards OP_CALL instructions can be correctly linked since message
  5317. * offsets have been previously assigned.
  5318. *
  5319. * Could avoid the second pass by linking OP_CALL instructions somehow. */
  5320. compile_methods(c);
  5321. compile_methods(c);
  5322. g->bytecode_end = c->pc;
  5323. freecompiler(c);
  5324. #ifdef UPB_DUMP_BYTECODE
  5325. {
  5326. FILE *f = fopen("/tmp/upb-bytecode", "w");
  5327. UPB_ASSERT(f);
  5328. dumpbc(g->bytecode, g->bytecode_end, stderr);
  5329. dumpbc(g->bytecode, g->bytecode_end, f);
  5330. fclose(f);
  5331. f = fopen("/tmp/upb-bytecode.bin", "wb");
  5332. UPB_ASSERT(f);
  5333. fwrite(g->bytecode, 1, g->bytecode_end - g->bytecode, f);
  5334. fclose(f);
  5335. }
  5336. #endif
  5337. set_bytecode_handlers(g);
  5338. return g;
  5339. }
  5340. /* upb_pbcodecache ************************************************************/
  5341. upb_pbcodecache *upb_pbcodecache_new(upb_handlercache *dest) {
  5342. upb_pbcodecache *c = upb_gmalloc(sizeof(*c));
  5343. if (!c) return NULL;
  5344. c->dest = dest;
  5345. c->lazy = false;
  5346. c->arena = upb_arena_new();
  5347. if (!upb_inttable_init(&c->groups, UPB_CTYPE_CONSTPTR)) return NULL;
  5348. return c;
  5349. }
  5350. void upb_pbcodecache_free(upb_pbcodecache *c) {
  5351. upb_inttable_iter i;
  5352. upb_inttable_begin(&i, &c->groups);
  5353. for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
  5354. upb_value val = upb_inttable_iter_value(&i);
  5355. freegroup((void*)upb_value_getconstptr(val));
  5356. }
  5357. upb_inttable_uninit(&c->groups);
  5358. upb_arena_free(c->arena);
  5359. upb_gfree(c);
  5360. }
  5361. void upb_pbdecodermethodopts_setlazy(upb_pbcodecache *c, bool lazy) {
  5362. UPB_ASSERT(upb_inttable_count(&c->groups) == 0);
  5363. c->lazy = lazy;
  5364. }
  5365. const upb_pbdecodermethod *upb_pbcodecache_get(upb_pbcodecache *c,
  5366. const upb_msgdef *md) {
  5367. upb_value v;
  5368. bool ok;
  5369. const upb_handlers *h;
  5370. const mgroup *g;
  5371. h = upb_handlercache_get(c->dest, md);
  5372. if (upb_inttable_lookupptr(&c->groups, md, &v)) {
  5373. g = upb_value_getconstptr(v);
  5374. } else {
  5375. g = mgroup_new(h, c->lazy);
  5376. ok = upb_inttable_insertptr(&c->groups, md, upb_value_constptr(g));
  5377. UPB_ASSERT(ok);
  5378. }
  5379. ok = upb_inttable_lookupptr(&g->methods, h, &v);
  5380. UPB_ASSERT(ok);
  5381. return upb_value_getptr(v);
  5382. }
  5383. /*
  5384. ** upb::Decoder (Bytecode Decoder VM)
  5385. **
  5386. ** Bytecode must previously have been generated using the bytecode compiler in
  5387. ** compile_decoder.c. This decoder then walks through the bytecode op-by-op to
  5388. ** parse the input.
  5389. **
  5390. ** Decoding is fully resumable; we just keep a pointer to the current bytecode
  5391. ** instruction and resume from there. A fair amount of the logic here is to
  5392. ** handle the fact that values can span buffer seams and we have to be able to
  5393. ** be capable of suspending/resuming from any byte in the stream. This
  5394. ** sometimes requires keeping a few trailing bytes from the last buffer around
  5395. ** in the "residual" buffer.
  5396. */
  5397. #include <inttypes.h>
  5398. #include <stddef.h>
  5399. #ifdef UPB_DUMP_BYTECODE
  5400. #include <stdio.h>
  5401. #endif
  5402. #define CHECK_SUSPEND(x) if (!(x)) return upb_pbdecoder_suspend(d);
  5403. /* Error messages that are shared between the bytecode and JIT decoders. */
  5404. const char *kPbDecoderStackOverflow = "Nesting too deep.";
  5405. const char *kPbDecoderSubmessageTooLong =
  5406. "Submessage end extends past enclosing submessage.";
  5407. /* Error messages shared within this file. */
  5408. static const char *kUnterminatedVarint = "Unterminated varint.";
  5409. /* upb_pbdecoder **************************************************************/
  5410. static opcode halt = OP_HALT;
  5411. /* A dummy character we can point to when the user passes us a NULL buffer.
  5412. * We need this because in C (NULL + 0) and (NULL - NULL) are undefined
  5413. * behavior, which would invalidate functions like curbufleft(). */
  5414. static const char dummy_char;
  5415. /* Whether an op consumes any of the input buffer. */
  5416. static bool consumes_input(opcode op) {
  5417. switch (op) {
  5418. case OP_SETDISPATCH:
  5419. case OP_STARTMSG:
  5420. case OP_ENDMSG:
  5421. case OP_STARTSEQ:
  5422. case OP_ENDSEQ:
  5423. case OP_STARTSUBMSG:
  5424. case OP_ENDSUBMSG:
  5425. case OP_STARTSTR:
  5426. case OP_ENDSTR:
  5427. case OP_PUSHTAGDELIM:
  5428. case OP_POP:
  5429. case OP_SETDELIM:
  5430. case OP_SETBIGGROUPNUM:
  5431. case OP_CHECKDELIM:
  5432. case OP_CALL:
  5433. case OP_RET:
  5434. case OP_BRANCH:
  5435. return false;
  5436. default:
  5437. return true;
  5438. }
  5439. }
  5440. static size_t stacksize(upb_pbdecoder *d, size_t entries) {
  5441. UPB_UNUSED(d);
  5442. return entries * sizeof(upb_pbdecoder_frame);
  5443. }
  5444. static size_t callstacksize(upb_pbdecoder *d, size_t entries) {
  5445. UPB_UNUSED(d);
  5446. return entries * sizeof(uint32_t*);
  5447. }
  5448. static bool in_residual_buf(const upb_pbdecoder *d, const char *p);
  5449. /* It's unfortunate that we have to micro-manage the compiler with
  5450. * UPB_FORCEINLINE and UPB_NOINLINE, especially since this tuning is necessarily
  5451. * specific to one hardware configuration. But empirically on a Core i7,
  5452. * performance increases 30-50% with these annotations. Every instance where
  5453. * these appear, gcc 4.2.1 made the wrong decision and degraded performance in
  5454. * benchmarks. */
  5455. static void seterr(upb_pbdecoder *d, const char *msg) {
  5456. upb_status_seterrmsg(d->status, msg);
  5457. }
  5458. void upb_pbdecoder_seterr(upb_pbdecoder *d, const char *msg) {
  5459. seterr(d, msg);
  5460. }
  5461. /* Buffering ******************************************************************/
  5462. /* We operate on one buffer at a time, which is either the user's buffer passed
  5463. * to our "decode" callback or some residual bytes from the previous buffer. */
  5464. /* How many bytes can be safely read from d->ptr without reading past end-of-buf
  5465. * or past the current delimited end. */
  5466. static size_t curbufleft(const upb_pbdecoder *d) {
  5467. UPB_ASSERT(d->data_end >= d->ptr);
  5468. return d->data_end - d->ptr;
  5469. }
  5470. /* How many bytes are available before end-of-buffer. */
  5471. static size_t bufleft(const upb_pbdecoder *d) {
  5472. return d->end - d->ptr;
  5473. }
  5474. /* Overall stream offset of d->ptr. */
  5475. uint64_t offset(const upb_pbdecoder *d) {
  5476. return d->bufstart_ofs + (d->ptr - d->buf);
  5477. }
  5478. /* How many bytes are available before the end of this delimited region. */
  5479. size_t delim_remaining(const upb_pbdecoder *d) {
  5480. return d->top->end_ofs - offset(d);
  5481. }
  5482. /* Advances d->ptr. */
  5483. static void advance(upb_pbdecoder *d, size_t len) {
  5484. UPB_ASSERT(curbufleft(d) >= len);
  5485. d->ptr += len;
  5486. }
  5487. static bool in_buf(const char *p, const char *buf, const char *end) {
  5488. return p >= buf && p <= end;
  5489. }
  5490. static bool in_residual_buf(const upb_pbdecoder *d, const char *p) {
  5491. return in_buf(p, d->residual, d->residual_end);
  5492. }
  5493. /* Calculates the delim_end value, which is affected by both the current buffer
  5494. * and the parsing stack, so must be called whenever either is updated. */
  5495. static void set_delim_end(upb_pbdecoder *d) {
  5496. size_t delim_ofs = d->top->end_ofs - d->bufstart_ofs;
  5497. if (delim_ofs <= (size_t)(d->end - d->buf)) {
  5498. d->delim_end = d->buf + delim_ofs;
  5499. d->data_end = d->delim_end;
  5500. } else {
  5501. d->data_end = d->end;
  5502. d->delim_end = NULL;
  5503. }
  5504. }
  5505. static void switchtobuf(upb_pbdecoder *d, const char *buf, const char *end) {
  5506. d->ptr = buf;
  5507. d->buf = buf;
  5508. d->end = end;
  5509. set_delim_end(d);
  5510. }
  5511. static void advancetobuf(upb_pbdecoder *d, const char *buf, size_t len) {
  5512. UPB_ASSERT(curbufleft(d) == 0);
  5513. d->bufstart_ofs += (d->end - d->buf);
  5514. switchtobuf(d, buf, buf + len);
  5515. }
  5516. static void checkpoint(upb_pbdecoder *d) {
  5517. /* The assertion here is in the interests of efficiency, not correctness.
  5518. * We are trying to ensure that we don't checkpoint() more often than
  5519. * necessary. */
  5520. UPB_ASSERT(d->checkpoint != d->ptr);
  5521. d->checkpoint = d->ptr;
  5522. }
  5523. /* Skips "bytes" bytes in the stream, which may be more than available. If we
  5524. * skip more bytes than are available, we return a long read count to the caller
  5525. * indicating how many bytes can be skipped over before passing actual data
  5526. * again. Skipped bytes can pass a NULL buffer and the decoder guarantees they
  5527. * won't actually be read.
  5528. */
  5529. static int32_t skip(upb_pbdecoder *d, size_t bytes) {
  5530. UPB_ASSERT(!in_residual_buf(d, d->ptr) || d->size_param == 0);
  5531. UPB_ASSERT(d->skip == 0);
  5532. if (bytes > delim_remaining(d)) {
  5533. seterr(d, "Skipped value extended beyond enclosing submessage.");
  5534. return upb_pbdecoder_suspend(d);
  5535. } else if (bufleft(d) >= bytes) {
  5536. /* Skipped data is all in current buffer, and more is still available. */
  5537. advance(d, bytes);
  5538. d->skip = 0;
  5539. return DECODE_OK;
  5540. } else {
  5541. /* Skipped data extends beyond currently available buffers. */
  5542. d->pc = d->last;
  5543. d->skip = bytes - curbufleft(d);
  5544. d->bufstart_ofs += (d->end - d->buf);
  5545. d->residual_end = d->residual;
  5546. switchtobuf(d, d->residual, d->residual_end);
  5547. return d->size_param + d->skip;
  5548. }
  5549. }
  5550. /* Resumes the decoder from an initial state or from a previous suspend. */
  5551. int32_t upb_pbdecoder_resume(upb_pbdecoder *d, void *p, const char *buf,
  5552. size_t size, const upb_bufhandle *handle) {
  5553. UPB_UNUSED(p); /* Useless; just for the benefit of the JIT. */
  5554. /* d->skip and d->residual_end could probably elegantly be represented
  5555. * as a single variable, to more easily represent this invariant. */
  5556. UPB_ASSERT(!(d->skip && d->residual_end > d->residual));
  5557. /* We need to remember the original size_param, so that the value we return
  5558. * is relative to it, even if we do some skipping first. */
  5559. d->size_param = size;
  5560. d->handle = handle;
  5561. /* Have to handle this case specially (ie. not with skip()) because the user
  5562. * is allowed to pass a NULL buffer here, which won't allow us to safely
  5563. * calculate a d->end or use our normal functions like curbufleft(). */
  5564. if (d->skip && d->skip >= size) {
  5565. d->skip -= size;
  5566. d->bufstart_ofs += size;
  5567. buf = &dummy_char;
  5568. size = 0;
  5569. /* We can't just return now, because we might need to execute some ops
  5570. * like CHECKDELIM, which could call some callbacks and pop the stack. */
  5571. }
  5572. /* We need to pretend that this was the actual buffer param, since some of the
  5573. * calculations assume that d->ptr/d->buf is relative to this. */
  5574. d->buf_param = buf;
  5575. if (!buf) {
  5576. /* NULL buf is ok if its entire span is covered by the "skip" above, but
  5577. * by this point we know that "skip" doesn't cover the buffer. */
  5578. seterr(d, "Passed NULL buffer over non-skippable region.");
  5579. return upb_pbdecoder_suspend(d);
  5580. }
  5581. if (d->residual_end > d->residual) {
  5582. /* We have residual bytes from the last buffer. */
  5583. UPB_ASSERT(d->ptr == d->residual);
  5584. } else {
  5585. switchtobuf(d, buf, buf + size);
  5586. }
  5587. d->checkpoint = d->ptr;
  5588. /* Handle skips that don't cover the whole buffer (as above). */
  5589. if (d->skip) {
  5590. size_t skip_bytes = d->skip;
  5591. d->skip = 0;
  5592. CHECK_RETURN(skip(d, skip_bytes));
  5593. checkpoint(d);
  5594. }
  5595. /* If we're inside an unknown group, continue to parse unknown values. */
  5596. if (d->top->groupnum < 0) {
  5597. CHECK_RETURN(upb_pbdecoder_skipunknown(d, -1, 0));
  5598. checkpoint(d);
  5599. }
  5600. return DECODE_OK;
  5601. }
  5602. /* Suspends the decoder at the last checkpoint, without saving any residual
  5603. * bytes. If there are any unconsumed bytes, returns a short byte count. */
  5604. size_t upb_pbdecoder_suspend(upb_pbdecoder *d) {
  5605. d->pc = d->last;
  5606. if (d->checkpoint == d->residual) {
  5607. /* Checkpoint was in residual buf; no user bytes were consumed. */
  5608. d->ptr = d->residual;
  5609. return 0;
  5610. } else {
  5611. size_t ret = d->size_param - (d->end - d->checkpoint);
  5612. UPB_ASSERT(!in_residual_buf(d, d->checkpoint));
  5613. UPB_ASSERT(d->buf == d->buf_param || d->buf == &dummy_char);
  5614. d->bufstart_ofs += (d->checkpoint - d->buf);
  5615. d->residual_end = d->residual;
  5616. switchtobuf(d, d->residual, d->residual_end);
  5617. return ret;
  5618. }
  5619. }
  5620. /* Suspends the decoder at the last checkpoint, and saves any unconsumed
  5621. * bytes in our residual buffer. This is necessary if we need more user
  5622. * bytes to form a complete value, which might not be contiguous in the
  5623. * user's buffers. Always consumes all user bytes. */
  5624. static size_t suspend_save(upb_pbdecoder *d) {
  5625. /* We hit end-of-buffer before we could parse a full value.
  5626. * Save any unconsumed bytes (if any) to the residual buffer. */
  5627. d->pc = d->last;
  5628. if (d->checkpoint == d->residual) {
  5629. /* Checkpoint was in residual buf; append user byte(s) to residual buf. */
  5630. UPB_ASSERT((d->residual_end - d->residual) + d->size_param <=
  5631. sizeof(d->residual));
  5632. if (!in_residual_buf(d, d->ptr)) {
  5633. d->bufstart_ofs -= (d->residual_end - d->residual);
  5634. }
  5635. memcpy(d->residual_end, d->buf_param, d->size_param);
  5636. d->residual_end += d->size_param;
  5637. } else {
  5638. /* Checkpoint was in user buf; old residual bytes not needed. */
  5639. size_t save;
  5640. UPB_ASSERT(!in_residual_buf(d, d->checkpoint));
  5641. d->ptr = d->checkpoint;
  5642. save = curbufleft(d);
  5643. UPB_ASSERT(save <= sizeof(d->residual));
  5644. memcpy(d->residual, d->ptr, save);
  5645. d->residual_end = d->residual + save;
  5646. d->bufstart_ofs = offset(d);
  5647. }
  5648. switchtobuf(d, d->residual, d->residual_end);
  5649. return d->size_param;
  5650. }
  5651. /* Copies the next "bytes" bytes into "buf" and advances the stream.
  5652. * Requires that this many bytes are available in the current buffer. */
  5653. UPB_FORCEINLINE static void consumebytes(upb_pbdecoder *d, void *buf,
  5654. size_t bytes) {
  5655. UPB_ASSERT(bytes <= curbufleft(d));
  5656. memcpy(buf, d->ptr, bytes);
  5657. advance(d, bytes);
  5658. }
  5659. /* Slow path for getting the next "bytes" bytes, regardless of whether they are
  5660. * available in the current buffer or not. Returns a status code as described
  5661. * in decoder.int.h. */
  5662. UPB_NOINLINE static int32_t getbytes_slow(upb_pbdecoder *d, void *buf,
  5663. size_t bytes) {
  5664. const size_t avail = curbufleft(d);
  5665. consumebytes(d, buf, avail);
  5666. bytes -= avail;
  5667. UPB_ASSERT(bytes > 0);
  5668. if (in_residual_buf(d, d->ptr)) {
  5669. advancetobuf(d, d->buf_param, d->size_param);
  5670. }
  5671. if (curbufleft(d) >= bytes) {
  5672. consumebytes(d, (char *)buf + avail, bytes);
  5673. return DECODE_OK;
  5674. } else if (d->data_end == d->delim_end) {
  5675. seterr(d, "Submessage ended in the middle of a value or group");
  5676. return upb_pbdecoder_suspend(d);
  5677. } else {
  5678. return suspend_save(d);
  5679. }
  5680. }
  5681. /* Gets the next "bytes" bytes, regardless of whether they are available in the
  5682. * current buffer or not. Returns a status code as described in decoder.int.h.
  5683. */
  5684. UPB_FORCEINLINE static int32_t getbytes(upb_pbdecoder *d, void *buf,
  5685. size_t bytes) {
  5686. if (curbufleft(d) >= bytes) {
  5687. /* Buffer has enough data to satisfy. */
  5688. consumebytes(d, buf, bytes);
  5689. return DECODE_OK;
  5690. } else {
  5691. return getbytes_slow(d, buf, bytes);
  5692. }
  5693. }
  5694. UPB_NOINLINE static size_t peekbytes_slow(upb_pbdecoder *d, void *buf,
  5695. size_t bytes) {
  5696. size_t ret = curbufleft(d);
  5697. memcpy(buf, d->ptr, ret);
  5698. if (in_residual_buf(d, d->ptr)) {
  5699. size_t copy = UPB_MIN(bytes - ret, d->size_param);
  5700. memcpy((char *)buf + ret, d->buf_param, copy);
  5701. ret += copy;
  5702. }
  5703. return ret;
  5704. }
  5705. UPB_FORCEINLINE static size_t peekbytes(upb_pbdecoder *d, void *buf,
  5706. size_t bytes) {
  5707. if (curbufleft(d) >= bytes) {
  5708. memcpy(buf, d->ptr, bytes);
  5709. return bytes;
  5710. } else {
  5711. return peekbytes_slow(d, buf, bytes);
  5712. }
  5713. }
  5714. /* Decoding of wire types *****************************************************/
  5715. /* Slow path for decoding a varint from the current buffer position.
  5716. * Returns a status code as described in decoder.int.h. */
  5717. UPB_NOINLINE int32_t upb_pbdecoder_decode_varint_slow(upb_pbdecoder *d,
  5718. uint64_t *u64) {
  5719. uint8_t byte = 0x80;
  5720. int bitpos;
  5721. *u64 = 0;
  5722. for(bitpos = 0; bitpos < 70 && (byte & 0x80); bitpos += 7) {
  5723. CHECK_RETURN(getbytes(d, &byte, 1));
  5724. *u64 |= (uint64_t)(byte & 0x7F) << bitpos;
  5725. }
  5726. if(bitpos == 70 && (byte & 0x80)) {
  5727. seterr(d, kUnterminatedVarint);
  5728. return upb_pbdecoder_suspend(d);
  5729. }
  5730. return DECODE_OK;
  5731. }
  5732. /* Decodes a varint from the current buffer position.
  5733. * Returns a status code as described in decoder.int.h. */
  5734. UPB_FORCEINLINE static int32_t decode_varint(upb_pbdecoder *d, uint64_t *u64) {
  5735. if (curbufleft(d) > 0 && !(*d->ptr & 0x80)) {
  5736. *u64 = *d->ptr;
  5737. advance(d, 1);
  5738. return DECODE_OK;
  5739. } else if (curbufleft(d) >= 10) {
  5740. /* Fast case. */
  5741. upb_decoderet r = upb_vdecode_fast(d->ptr);
  5742. if (r.p == NULL) {
  5743. seterr(d, kUnterminatedVarint);
  5744. return upb_pbdecoder_suspend(d);
  5745. }
  5746. advance(d, r.p - d->ptr);
  5747. *u64 = r.val;
  5748. return DECODE_OK;
  5749. } else {
  5750. /* Slow case -- varint spans buffer seam. */
  5751. return upb_pbdecoder_decode_varint_slow(d, u64);
  5752. }
  5753. }
  5754. /* Decodes a 32-bit varint from the current buffer position.
  5755. * Returns a status code as described in decoder.int.h. */
  5756. UPB_FORCEINLINE static int32_t decode_v32(upb_pbdecoder *d, uint32_t *u32) {
  5757. uint64_t u64;
  5758. int32_t ret = decode_varint(d, &u64);
  5759. if (ret >= 0) return ret;
  5760. if (u64 > UINT32_MAX) {
  5761. seterr(d, "Unterminated 32-bit varint");
  5762. /* TODO(haberman) guarantee that this function return is >= 0 somehow,
  5763. * so we know this path will always be treated as error by our caller.
  5764. * Right now the size_t -> int32_t can overflow and produce negative values.
  5765. */
  5766. *u32 = 0;
  5767. return upb_pbdecoder_suspend(d);
  5768. }
  5769. *u32 = u64;
  5770. return DECODE_OK;
  5771. }
  5772. /* Decodes a fixed32 from the current buffer position.
  5773. * Returns a status code as described in decoder.int.h.
  5774. * TODO: proper byte swapping for big-endian machines. */
  5775. UPB_FORCEINLINE static int32_t decode_fixed32(upb_pbdecoder *d, uint32_t *u32) {
  5776. return getbytes(d, u32, 4);
  5777. }
  5778. /* Decodes a fixed64 from the current buffer position.
  5779. * Returns a status code as described in decoder.int.h.
  5780. * TODO: proper byte swapping for big-endian machines. */
  5781. UPB_FORCEINLINE static int32_t decode_fixed64(upb_pbdecoder *d, uint64_t *u64) {
  5782. return getbytes(d, u64, 8);
  5783. }
  5784. /* Non-static versions of the above functions.
  5785. * These are called by the JIT for fallback paths. */
  5786. int32_t upb_pbdecoder_decode_f32(upb_pbdecoder *d, uint32_t *u32) {
  5787. return decode_fixed32(d, u32);
  5788. }
  5789. int32_t upb_pbdecoder_decode_f64(upb_pbdecoder *d, uint64_t *u64) {
  5790. return decode_fixed64(d, u64);
  5791. }
  5792. static double as_double(uint64_t n) { double d; memcpy(&d, &n, 8); return d; }
  5793. static float as_float(uint32_t n) { float f; memcpy(&f, &n, 4); return f; }
  5794. /* Pushes a frame onto the decoder stack. */
  5795. static bool decoder_push(upb_pbdecoder *d, uint64_t end) {
  5796. upb_pbdecoder_frame *fr = d->top;
  5797. if (end > fr->end_ofs) {
  5798. seterr(d, kPbDecoderSubmessageTooLong);
  5799. return false;
  5800. } else if (fr == d->limit) {
  5801. seterr(d, kPbDecoderStackOverflow);
  5802. return false;
  5803. }
  5804. fr++;
  5805. fr->end_ofs = end;
  5806. fr->dispatch = NULL;
  5807. fr->groupnum = 0;
  5808. d->top = fr;
  5809. return true;
  5810. }
  5811. static bool pushtagdelim(upb_pbdecoder *d, uint32_t arg) {
  5812. /* While we expect to see an "end" tag (either ENDGROUP or a non-sequence
  5813. * field number) prior to hitting any enclosing submessage end, pushing our
  5814. * existing delim end prevents us from continuing to parse values from a
  5815. * corrupt proto that doesn't give us an END tag in time. */
  5816. if (!decoder_push(d, d->top->end_ofs))
  5817. return false;
  5818. d->top->groupnum = arg;
  5819. return true;
  5820. }
  5821. /* Pops a frame from the decoder stack. */
  5822. static void decoder_pop(upb_pbdecoder *d) { d->top--; }
  5823. UPB_NOINLINE int32_t upb_pbdecoder_checktag_slow(upb_pbdecoder *d,
  5824. uint64_t expected) {
  5825. uint64_t data = 0;
  5826. size_t bytes = upb_value_size(expected);
  5827. size_t read = peekbytes(d, &data, bytes);
  5828. if (read == bytes && data == expected) {
  5829. /* Advance past matched bytes. */
  5830. int32_t ok = getbytes(d, &data, read);
  5831. UPB_ASSERT(ok < 0);
  5832. return DECODE_OK;
  5833. } else if (read < bytes && memcmp(&data, &expected, read) == 0) {
  5834. return suspend_save(d);
  5835. } else {
  5836. return DECODE_MISMATCH;
  5837. }
  5838. }
  5839. int32_t upb_pbdecoder_skipunknown(upb_pbdecoder *d, int32_t fieldnum,
  5840. uint8_t wire_type) {
  5841. if (fieldnum >= 0)
  5842. goto have_tag;
  5843. while (true) {
  5844. uint32_t tag;
  5845. CHECK_RETURN(decode_v32(d, &tag));
  5846. wire_type = tag & 0x7;
  5847. fieldnum = tag >> 3;
  5848. have_tag:
  5849. if (fieldnum == 0) {
  5850. seterr(d, "Saw invalid field number (0)");
  5851. return upb_pbdecoder_suspend(d);
  5852. }
  5853. switch (wire_type) {
  5854. case UPB_WIRE_TYPE_32BIT:
  5855. CHECK_RETURN(skip(d, 4));
  5856. break;
  5857. case UPB_WIRE_TYPE_64BIT:
  5858. CHECK_RETURN(skip(d, 8));
  5859. break;
  5860. case UPB_WIRE_TYPE_VARINT: {
  5861. uint64_t u64;
  5862. CHECK_RETURN(decode_varint(d, &u64));
  5863. break;
  5864. }
  5865. case UPB_WIRE_TYPE_DELIMITED: {
  5866. uint32_t len;
  5867. CHECK_RETURN(decode_v32(d, &len));
  5868. CHECK_RETURN(skip(d, len));
  5869. break;
  5870. }
  5871. case UPB_WIRE_TYPE_START_GROUP:
  5872. CHECK_SUSPEND(pushtagdelim(d, -fieldnum));
  5873. break;
  5874. case UPB_WIRE_TYPE_END_GROUP:
  5875. if (fieldnum == -d->top->groupnum) {
  5876. decoder_pop(d);
  5877. } else if (fieldnum == d->top->groupnum) {
  5878. return DECODE_ENDGROUP;
  5879. } else {
  5880. seterr(d, "Unmatched ENDGROUP tag.");
  5881. return upb_pbdecoder_suspend(d);
  5882. }
  5883. break;
  5884. default:
  5885. seterr(d, "Invalid wire type");
  5886. return upb_pbdecoder_suspend(d);
  5887. }
  5888. if (d->top->groupnum >= 0) {
  5889. /* TODO: More code needed for handling unknown groups. */
  5890. upb_sink_putunknown(d->top->sink, d->checkpoint, d->ptr - d->checkpoint);
  5891. return DECODE_OK;
  5892. }
  5893. /* Unknown group -- continue looping over unknown fields. */
  5894. checkpoint(d);
  5895. }
  5896. }
  5897. static void goto_endmsg(upb_pbdecoder *d) {
  5898. upb_value v;
  5899. bool found = upb_inttable_lookup32(d->top->dispatch, DISPATCH_ENDMSG, &v);
  5900. UPB_ASSERT(found);
  5901. d->pc = d->top->base + upb_value_getuint64(v);
  5902. }
  5903. /* Parses a tag and jumps to the corresponding bytecode instruction for this
  5904. * field.
  5905. *
  5906. * If the tag is unknown (or the wire type doesn't match), parses the field as
  5907. * unknown. If the tag is a valid ENDGROUP tag, jumps to the bytecode
  5908. * instruction for the end of message. */
  5909. static int32_t dispatch(upb_pbdecoder *d) {
  5910. upb_inttable *dispatch = d->top->dispatch;
  5911. uint32_t tag;
  5912. uint8_t wire_type;
  5913. uint32_t fieldnum;
  5914. upb_value val;
  5915. int32_t retval;
  5916. /* Decode tag. */
  5917. CHECK_RETURN(decode_v32(d, &tag));
  5918. wire_type = tag & 0x7;
  5919. fieldnum = tag >> 3;
  5920. /* Lookup tag. Because of packed/non-packed compatibility, we have to
  5921. * check the wire type against two possibilities. */
  5922. if (fieldnum != DISPATCH_ENDMSG &&
  5923. upb_inttable_lookup32(dispatch, fieldnum, &val)) {
  5924. uint64_t v = upb_value_getuint64(val);
  5925. if (wire_type == (v & 0xff)) {
  5926. d->pc = d->top->base + (v >> 16);
  5927. return DECODE_OK;
  5928. } else if (wire_type == ((v >> 8) & 0xff)) {
  5929. bool found =
  5930. upb_inttable_lookup(dispatch, fieldnum + UPB_MAX_FIELDNUMBER, &val);
  5931. UPB_ASSERT(found);
  5932. d->pc = d->top->base + upb_value_getuint64(val);
  5933. return DECODE_OK;
  5934. }
  5935. }
  5936. /* We have some unknown fields (or ENDGROUP) to parse. The DISPATCH or TAG
  5937. * bytecode that triggered this is preceded by a CHECKDELIM bytecode which
  5938. * we need to back up to, so that when we're done skipping unknown data we
  5939. * can re-check the delimited end. */
  5940. d->last--; /* Necessary if we get suspended */
  5941. d->pc = d->last;
  5942. UPB_ASSERT(getop(*d->last) == OP_CHECKDELIM);
  5943. /* Unknown field or ENDGROUP. */
  5944. retval = upb_pbdecoder_skipunknown(d, fieldnum, wire_type);
  5945. CHECK_RETURN(retval);
  5946. if (retval == DECODE_ENDGROUP) {
  5947. goto_endmsg(d);
  5948. return DECODE_OK;
  5949. }
  5950. return DECODE_OK;
  5951. }
  5952. /* Callers know that the stack is more than one deep because the opcodes that
  5953. * call this only occur after PUSH operations. */
  5954. upb_pbdecoder_frame *outer_frame(upb_pbdecoder *d) {
  5955. UPB_ASSERT(d->top != d->stack);
  5956. return d->top - 1;
  5957. }
  5958. /* The main decoding loop *****************************************************/
  5959. /* The main decoder VM function. Uses traditional bytecode dispatch loop with a
  5960. * switch() statement. */
  5961. size_t run_decoder_vm(upb_pbdecoder *d, const mgroup *group,
  5962. const upb_bufhandle* handle) {
  5963. #define VMCASE(op, code) \
  5964. case op: { code; if (consumes_input(op)) checkpoint(d); break; }
  5965. #define PRIMITIVE_OP(type, wt, name, convfunc, ctype) \
  5966. VMCASE(OP_PARSE_ ## type, { \
  5967. ctype val; \
  5968. CHECK_RETURN(decode_ ## wt(d, &val)); \
  5969. upb_sink_put ## name(d->top->sink, arg, (convfunc)(val)); \
  5970. })
  5971. while(1) {
  5972. int32_t instruction;
  5973. opcode op;
  5974. uint32_t arg;
  5975. int32_t longofs;
  5976. d->last = d->pc;
  5977. instruction = *d->pc++;
  5978. op = getop(instruction);
  5979. arg = instruction >> 8;
  5980. longofs = arg;
  5981. UPB_ASSERT(d->ptr != d->residual_end);
  5982. UPB_UNUSED(group);
  5983. #ifdef UPB_DUMP_BYTECODE
  5984. fprintf(stderr, "s_ofs=%d buf_ofs=%d data_rem=%d buf_rem=%d delim_rem=%d "
  5985. "%x %s (%d)\n",
  5986. (int)offset(d),
  5987. (int)(d->ptr - d->buf),
  5988. (int)(d->data_end - d->ptr),
  5989. (int)(d->end - d->ptr),
  5990. (int)((d->top->end_ofs - d->bufstart_ofs) - (d->ptr - d->buf)),
  5991. (int)(d->pc - 1 - group->bytecode),
  5992. upb_pbdecoder_getopname(op),
  5993. arg);
  5994. #endif
  5995. switch (op) {
  5996. /* Technically, we are losing data if we see a 32-bit varint that is not
  5997. * properly sign-extended. We could detect this and error about the data
  5998. * loss, but proto2 does not do this, so we pass. */
  5999. PRIMITIVE_OP(INT32, varint, int32, int32_t, uint64_t)
  6000. PRIMITIVE_OP(INT64, varint, int64, int64_t, uint64_t)
  6001. PRIMITIVE_OP(UINT32, varint, uint32, uint32_t, uint64_t)
  6002. PRIMITIVE_OP(UINT64, varint, uint64, uint64_t, uint64_t)
  6003. PRIMITIVE_OP(FIXED32, fixed32, uint32, uint32_t, uint32_t)
  6004. PRIMITIVE_OP(FIXED64, fixed64, uint64, uint64_t, uint64_t)
  6005. PRIMITIVE_OP(SFIXED32, fixed32, int32, int32_t, uint32_t)
  6006. PRIMITIVE_OP(SFIXED64, fixed64, int64, int64_t, uint64_t)
  6007. PRIMITIVE_OP(BOOL, varint, bool, bool, uint64_t)
  6008. PRIMITIVE_OP(DOUBLE, fixed64, double, as_double, uint64_t)
  6009. PRIMITIVE_OP(FLOAT, fixed32, float, as_float, uint32_t)
  6010. PRIMITIVE_OP(SINT32, varint, int32, upb_zzdec_32, uint64_t)
  6011. PRIMITIVE_OP(SINT64, varint, int64, upb_zzdec_64, uint64_t)
  6012. VMCASE(OP_SETDISPATCH,
  6013. d->top->base = d->pc - 1;
  6014. memcpy(&d->top->dispatch, d->pc, sizeof(void*));
  6015. d->pc += sizeof(void*) / sizeof(uint32_t);
  6016. )
  6017. VMCASE(OP_STARTMSG,
  6018. CHECK_SUSPEND(upb_sink_startmsg(d->top->sink));
  6019. )
  6020. VMCASE(OP_ENDMSG,
  6021. CHECK_SUSPEND(upb_sink_endmsg(d->top->sink, d->status));
  6022. )
  6023. VMCASE(OP_STARTSEQ,
  6024. upb_pbdecoder_frame *outer = outer_frame(d);
  6025. CHECK_SUSPEND(upb_sink_startseq(outer->sink, arg, &d->top->sink));
  6026. )
  6027. VMCASE(OP_ENDSEQ,
  6028. CHECK_SUSPEND(upb_sink_endseq(d->top->sink, arg));
  6029. )
  6030. VMCASE(OP_STARTSUBMSG,
  6031. upb_pbdecoder_frame *outer = outer_frame(d);
  6032. CHECK_SUSPEND(upb_sink_startsubmsg(outer->sink, arg, &d->top->sink));
  6033. )
  6034. VMCASE(OP_ENDSUBMSG,
  6035. CHECK_SUSPEND(upb_sink_endsubmsg(d->top->sink, arg));
  6036. )
  6037. VMCASE(OP_STARTSTR,
  6038. uint32_t len = delim_remaining(d);
  6039. upb_pbdecoder_frame *outer = outer_frame(d);
  6040. CHECK_SUSPEND(upb_sink_startstr(outer->sink, arg, len, &d->top->sink));
  6041. if (len == 0) {
  6042. d->pc++; /* Skip OP_STRING. */
  6043. }
  6044. )
  6045. VMCASE(OP_STRING,
  6046. uint32_t len = curbufleft(d);
  6047. size_t n = upb_sink_putstring(d->top->sink, arg, d->ptr, len, handle);
  6048. if (n > len) {
  6049. if (n > delim_remaining(d)) {
  6050. seterr(d, "Tried to skip past end of string.");
  6051. return upb_pbdecoder_suspend(d);
  6052. } else {
  6053. int32_t ret = skip(d, n);
  6054. /* This shouldn't return DECODE_OK, because n > len. */
  6055. UPB_ASSERT(ret >= 0);
  6056. return ret;
  6057. }
  6058. }
  6059. advance(d, n);
  6060. if (n < len || d->delim_end == NULL) {
  6061. /* We aren't finished with this string yet. */
  6062. d->pc--; /* Repeat OP_STRING. */
  6063. if (n > 0) checkpoint(d);
  6064. return upb_pbdecoder_suspend(d);
  6065. }
  6066. )
  6067. VMCASE(OP_ENDSTR,
  6068. CHECK_SUSPEND(upb_sink_endstr(d->top->sink, arg));
  6069. )
  6070. VMCASE(OP_PUSHTAGDELIM,
  6071. CHECK_SUSPEND(pushtagdelim(d, arg));
  6072. )
  6073. VMCASE(OP_SETBIGGROUPNUM,
  6074. d->top->groupnum = *d->pc++;
  6075. )
  6076. VMCASE(OP_POP,
  6077. UPB_ASSERT(d->top > d->stack);
  6078. decoder_pop(d);
  6079. )
  6080. VMCASE(OP_PUSHLENDELIM,
  6081. uint32_t len;
  6082. CHECK_RETURN(decode_v32(d, &len));
  6083. CHECK_SUSPEND(decoder_push(d, offset(d) + len));
  6084. set_delim_end(d);
  6085. )
  6086. VMCASE(OP_SETDELIM,
  6087. set_delim_end(d);
  6088. )
  6089. VMCASE(OP_CHECKDELIM,
  6090. /* We are guaranteed of this assert because we never allow ourselves to
  6091. * consume bytes beyond data_end, which covers delim_end when non-NULL.
  6092. */
  6093. UPB_ASSERT(!(d->delim_end && d->ptr > d->delim_end));
  6094. if (d->ptr == d->delim_end)
  6095. d->pc += longofs;
  6096. )
  6097. VMCASE(OP_CALL,
  6098. d->callstack[d->call_len++] = d->pc;
  6099. d->pc += longofs;
  6100. )
  6101. VMCASE(OP_RET,
  6102. UPB_ASSERT(d->call_len > 0);
  6103. d->pc = d->callstack[--d->call_len];
  6104. )
  6105. VMCASE(OP_BRANCH,
  6106. d->pc += longofs;
  6107. )
  6108. VMCASE(OP_TAG1,
  6109. uint8_t expected;
  6110. CHECK_SUSPEND(curbufleft(d) > 0);
  6111. expected = (arg >> 8) & 0xff;
  6112. if (*d->ptr == expected) {
  6113. advance(d, 1);
  6114. } else {
  6115. int8_t shortofs;
  6116. badtag:
  6117. shortofs = arg;
  6118. if (shortofs == LABEL_DISPATCH) {
  6119. CHECK_RETURN(dispatch(d));
  6120. } else {
  6121. d->pc += shortofs;
  6122. break; /* Avoid checkpoint(). */
  6123. }
  6124. }
  6125. )
  6126. VMCASE(OP_TAG2,
  6127. uint16_t expected;
  6128. CHECK_SUSPEND(curbufleft(d) > 0);
  6129. expected = (arg >> 8) & 0xffff;
  6130. if (curbufleft(d) >= 2) {
  6131. uint16_t actual;
  6132. memcpy(&actual, d->ptr, 2);
  6133. if (expected == actual) {
  6134. advance(d, 2);
  6135. } else {
  6136. goto badtag;
  6137. }
  6138. } else {
  6139. int32_t result = upb_pbdecoder_checktag_slow(d, expected);
  6140. if (result == DECODE_MISMATCH) goto badtag;
  6141. if (result >= 0) return result;
  6142. }
  6143. )
  6144. VMCASE(OP_TAGN, {
  6145. uint64_t expected;
  6146. int32_t result;
  6147. memcpy(&expected, d->pc, 8);
  6148. d->pc += 2;
  6149. result = upb_pbdecoder_checktag_slow(d, expected);
  6150. if (result == DECODE_MISMATCH) goto badtag;
  6151. if (result >= 0) return result;
  6152. })
  6153. VMCASE(OP_DISPATCH, {
  6154. CHECK_RETURN(dispatch(d));
  6155. })
  6156. VMCASE(OP_HALT, {
  6157. return d->size_param;
  6158. })
  6159. }
  6160. }
  6161. }
  6162. /* BytesHandler handlers ******************************************************/
  6163. void *upb_pbdecoder_startbc(void *closure, const void *pc, size_t size_hint) {
  6164. upb_pbdecoder *d = closure;
  6165. UPB_UNUSED(size_hint);
  6166. d->top->end_ofs = UINT64_MAX;
  6167. d->bufstart_ofs = 0;
  6168. d->call_len = 1;
  6169. d->callstack[0] = &halt;
  6170. d->pc = pc;
  6171. d->skip = 0;
  6172. return d;
  6173. }
  6174. bool upb_pbdecoder_end(void *closure, const void *handler_data) {
  6175. upb_pbdecoder *d = closure;
  6176. const upb_pbdecodermethod *method = handler_data;
  6177. uint64_t end;
  6178. char dummy;
  6179. if (d->residual_end > d->residual) {
  6180. seterr(d, "Unexpected EOF: decoder still has buffered unparsed data");
  6181. return false;
  6182. }
  6183. if (d->skip) {
  6184. seterr(d, "Unexpected EOF inside skipped data");
  6185. return false;
  6186. }
  6187. if (d->top->end_ofs != UINT64_MAX) {
  6188. seterr(d, "Unexpected EOF inside delimited string");
  6189. return false;
  6190. }
  6191. /* The user's end() call indicates that the message ends here. */
  6192. end = offset(d);
  6193. d->top->end_ofs = end;
  6194. {
  6195. const uint32_t *p = d->pc;
  6196. d->stack->end_ofs = end;
  6197. /* Check the previous bytecode, but guard against beginning. */
  6198. if (p != method->code_base.ptr) p--;
  6199. if (getop(*p) == OP_CHECKDELIM) {
  6200. /* Rewind from OP_TAG* to OP_CHECKDELIM. */
  6201. UPB_ASSERT(getop(*d->pc) == OP_TAG1 ||
  6202. getop(*d->pc) == OP_TAG2 ||
  6203. getop(*d->pc) == OP_TAGN ||
  6204. getop(*d->pc) == OP_DISPATCH);
  6205. d->pc = p;
  6206. }
  6207. upb_pbdecoder_decode(closure, handler_data, &dummy, 0, NULL);
  6208. }
  6209. if (d->call_len != 0) {
  6210. seterr(d, "Unexpected EOF inside submessage or group");
  6211. return false;
  6212. }
  6213. return true;
  6214. }
  6215. size_t upb_pbdecoder_decode(void *decoder, const void *group, const char *buf,
  6216. size_t size, const upb_bufhandle *handle) {
  6217. int32_t result = upb_pbdecoder_resume(decoder, NULL, buf, size, handle);
  6218. if (result == DECODE_ENDGROUP) goto_endmsg(decoder);
  6219. CHECK_RETURN(result);
  6220. return run_decoder_vm(decoder, group, handle);
  6221. }
  6222. /* Public API *****************************************************************/
  6223. void upb_pbdecoder_reset(upb_pbdecoder *d) {
  6224. d->top = d->stack;
  6225. d->top->groupnum = 0;
  6226. d->ptr = d->residual;
  6227. d->buf = d->residual;
  6228. d->end = d->residual;
  6229. d->residual_end = d->residual;
  6230. }
  6231. upb_pbdecoder *upb_pbdecoder_create(upb_arena *a, const upb_pbdecodermethod *m,
  6232. upb_sink sink, upb_status *status) {
  6233. const size_t default_max_nesting = 64;
  6234. #ifndef NDEBUG
  6235. size_t size_before = upb_arena_bytesallocated(a);
  6236. #endif
  6237. upb_pbdecoder *d = upb_arena_malloc(a, sizeof(upb_pbdecoder));
  6238. if (!d) return NULL;
  6239. d->method_ = m;
  6240. d->callstack = upb_arena_malloc(a, callstacksize(d, default_max_nesting));
  6241. d->stack = upb_arena_malloc(a, stacksize(d, default_max_nesting));
  6242. if (!d->stack || !d->callstack) {
  6243. return NULL;
  6244. }
  6245. d->arena = a;
  6246. d->limit = d->stack + default_max_nesting - 1;
  6247. d->stack_size = default_max_nesting;
  6248. d->status = status;
  6249. upb_pbdecoder_reset(d);
  6250. upb_bytessink_reset(&d->input_, &m->input_handler_, d);
  6251. if (d->method_->dest_handlers_) {
  6252. if (sink.handlers != d->method_->dest_handlers_)
  6253. return NULL;
  6254. }
  6255. d->top->sink = sink;
  6256. /* If this fails, increase the value in decoder.h. */
  6257. UPB_ASSERT_DEBUGVAR(upb_arena_bytesallocated(a) - size_before <=
  6258. UPB_PB_DECODER_SIZE);
  6259. return d;
  6260. }
  6261. uint64_t upb_pbdecoder_bytesparsed(const upb_pbdecoder *d) {
  6262. return offset(d);
  6263. }
  6264. const upb_pbdecodermethod *upb_pbdecoder_method(const upb_pbdecoder *d) {
  6265. return d->method_;
  6266. }
  6267. upb_bytessink upb_pbdecoder_input(upb_pbdecoder *d) {
  6268. return d->input_;
  6269. }
  6270. size_t upb_pbdecoder_maxnesting(const upb_pbdecoder *d) {
  6271. return d->stack_size;
  6272. }
  6273. bool upb_pbdecoder_setmaxnesting(upb_pbdecoder *d, size_t max) {
  6274. UPB_ASSERT(d->top >= d->stack);
  6275. if (max < (size_t)(d->top - d->stack)) {
  6276. /* Can't set a limit smaller than what we are currently at. */
  6277. return false;
  6278. }
  6279. if (max > d->stack_size) {
  6280. /* Need to reallocate stack and callstack to accommodate. */
  6281. size_t old_size = stacksize(d, d->stack_size);
  6282. size_t new_size = stacksize(d, max);
  6283. void *p = upb_arena_realloc(d->arena, d->stack, old_size, new_size);
  6284. if (!p) {
  6285. return false;
  6286. }
  6287. d->stack = p;
  6288. old_size = callstacksize(d, d->stack_size);
  6289. new_size = callstacksize(d, max);
  6290. p = upb_arena_realloc(d->arena, d->callstack, old_size, new_size);
  6291. if (!p) {
  6292. return false;
  6293. }
  6294. d->callstack = p;
  6295. d->stack_size = max;
  6296. }
  6297. d->limit = d->stack + max - 1;
  6298. return true;
  6299. }
  6300. /*
  6301. ** upb::Encoder
  6302. **
  6303. ** Since we are implementing pure handlers (ie. without any out-of-band access
  6304. ** to pre-computed lengths), we have to buffer all submessages before we can
  6305. ** emit even their first byte.
  6306. **
  6307. ** Not knowing the size of submessages also means we can't write a perfect
  6308. ** zero-copy implementation, even with buffering. Lengths are stored as
  6309. ** varints, which means that we don't know how many bytes to reserve for the
  6310. ** length until we know what the length is.
  6311. **
  6312. ** This leaves us with three main choices:
  6313. **
  6314. ** 1. buffer all submessage data in a temporary buffer, then copy it exactly
  6315. ** once into the output buffer.
  6316. **
  6317. ** 2. attempt to buffer data directly into the output buffer, estimating how
  6318. ** many bytes each length will take. When our guesses are wrong, use
  6319. ** memmove() to grow or shrink the allotted space.
  6320. **
  6321. ** 3. buffer directly into the output buffer, allocating a max length
  6322. ** ahead-of-time for each submessage length. If we overallocated, we waste
  6323. ** space, but no memcpy() or memmove() is required. This approach requires
  6324. ** defining a maximum size for submessages and rejecting submessages that
  6325. ** exceed that size.
  6326. **
  6327. ** (2) and (3) have the potential to have better performance, but they are more
  6328. ** complicated and subtle to implement:
  6329. **
  6330. ** (3) requires making an arbitrary choice of the maximum message size; it
  6331. ** wastes space when submessages are shorter than this and fails
  6332. ** completely when they are longer. This makes it more finicky and
  6333. ** requires configuration based on the input. It also makes it impossible
  6334. ** to perfectly match the output of reference encoders that always use the
  6335. ** optimal amount of space for each length.
  6336. **
  6337. ** (2) requires guessing the the size upfront, and if multiple lengths are
  6338. ** guessed wrong the minimum required number of memmove() operations may
  6339. ** be complicated to compute correctly. Implemented properly, it may have
  6340. ** a useful amortized or average cost, but more investigation is required
  6341. ** to determine this and what the optimal algorithm is to achieve it.
  6342. **
  6343. ** (1) makes you always pay for exactly one copy, but its implementation is
  6344. ** the simplest and its performance is predictable.
  6345. **
  6346. ** So for now, we implement (1) only. If we wish to optimize later, we should
  6347. ** be able to do it without affecting users.
  6348. **
  6349. ** The strategy is to buffer the segments of data that do *not* depend on
  6350. ** unknown lengths in one buffer, and keep a separate buffer of segment pointers
  6351. ** and lengths. When the top-level submessage ends, we can go beginning to end,
  6352. ** alternating the writing of lengths with memcpy() of the rest of the data.
  6353. ** At the top level though, no buffering is required.
  6354. */
  6355. /* The output buffer is divided into segments; a segment is a string of data
  6356. * that is "ready to go" -- it does not need any varint lengths inserted into
  6357. * the middle. The seams between segments are where varints will be inserted
  6358. * once they are known.
  6359. *
  6360. * We also use the concept of a "run", which is a range of encoded bytes that
  6361. * occur at a single submessage level. Every segment contains one or more runs.
  6362. *
  6363. * A segment can span messages. Consider:
  6364. *
  6365. * .--Submessage lengths---------.
  6366. * | | |
  6367. * | V V
  6368. * V | |--------------- | |-----------------
  6369. * Submessages: | |-----------------------------------------------
  6370. * Top-level msg: ------------------------------------------------------------
  6371. *
  6372. * Segments: ----- ------------------- -----------------
  6373. * Runs: *---- *--------------*--- *----------------
  6374. * (* marks the start)
  6375. *
  6376. * Note that the top-level menssage is not in any segment because it does not
  6377. * have any length preceding it.
  6378. *
  6379. * A segment is only interrupted when another length needs to be inserted. So
  6380. * observe how the second segment spans both the inner submessage and part of
  6381. * the next enclosing message. */
  6382. typedef struct {
  6383. uint32_t msglen; /* The length to varint-encode before this segment. */
  6384. uint32_t seglen; /* Length of the segment. */
  6385. } upb_pb_encoder_segment;
  6386. struct upb_pb_encoder {
  6387. upb_arena *arena;
  6388. /* Our input and output. */
  6389. upb_sink input_;
  6390. upb_bytessink output_;
  6391. /* The "subclosure" -- used as the inner closure as part of the bytessink
  6392. * protocol. */
  6393. void *subc;
  6394. /* The output buffer and limit, and our current write position. "buf"
  6395. * initially points to "initbuf", but is dynamically allocated if we need to
  6396. * grow beyond the initial size. */
  6397. char *buf, *ptr, *limit;
  6398. /* The beginning of the current run, or undefined if we are at the top
  6399. * level. */
  6400. char *runbegin;
  6401. /* The list of segments we are accumulating. */
  6402. upb_pb_encoder_segment *segbuf, *segptr, *seglimit;
  6403. /* The stack of enclosing submessages. Each entry in the stack points to the
  6404. * segment where this submessage's length is being accumulated. */
  6405. int *stack, *top, *stacklimit;
  6406. /* Depth of startmsg/endmsg calls. */
  6407. int depth;
  6408. };
  6409. /* low-level buffering ********************************************************/
  6410. /* Low-level functions for interacting with the output buffer. */
  6411. /* TODO(haberman): handle pushback */
  6412. static void putbuf(upb_pb_encoder *e, const char *buf, size_t len) {
  6413. size_t n = upb_bytessink_putbuf(e->output_, e->subc, buf, len, NULL);
  6414. UPB_ASSERT(n == len);
  6415. }
  6416. static upb_pb_encoder_segment *top(upb_pb_encoder *e) {
  6417. return &e->segbuf[*e->top];
  6418. }
  6419. /* Call to ensure that at least "bytes" bytes are available for writing at
  6420. * e->ptr. Returns false if the bytes could not be allocated. */
  6421. static bool reserve(upb_pb_encoder *e, size_t bytes) {
  6422. if ((size_t)(e->limit - e->ptr) < bytes) {
  6423. /* Grow buffer. */
  6424. char *new_buf;
  6425. size_t needed = bytes + (e->ptr - e->buf);
  6426. size_t old_size = e->limit - e->buf;
  6427. size_t new_size = old_size;
  6428. while (new_size < needed) {
  6429. new_size *= 2;
  6430. }
  6431. new_buf = upb_arena_realloc(e->arena, e->buf, old_size, new_size);
  6432. if (new_buf == NULL) {
  6433. return false;
  6434. }
  6435. e->ptr = new_buf + (e->ptr - e->buf);
  6436. e->runbegin = new_buf + (e->runbegin - e->buf);
  6437. e->limit = new_buf + new_size;
  6438. e->buf = new_buf;
  6439. }
  6440. return true;
  6441. }
  6442. /* Call when "bytes" bytes have been writte at e->ptr. The caller *must* have
  6443. * previously called reserve() with at least this many bytes. */
  6444. static void encoder_advance(upb_pb_encoder *e, size_t bytes) {
  6445. UPB_ASSERT((size_t)(e->limit - e->ptr) >= bytes);
  6446. e->ptr += bytes;
  6447. }
  6448. /* Call when all of the bytes for a handler have been written. Flushes the
  6449. * bytes if possible and necessary, returning false if this failed. */
  6450. static bool commit(upb_pb_encoder *e) {
  6451. if (!e->top) {
  6452. /* We aren't inside a delimited region. Flush our accumulated bytes to
  6453. * the output.
  6454. *
  6455. * TODO(haberman): in the future we may want to delay flushing for
  6456. * efficiency reasons. */
  6457. putbuf(e, e->buf, e->ptr - e->buf);
  6458. e->ptr = e->buf;
  6459. }
  6460. return true;
  6461. }
  6462. /* Writes the given bytes to the buffer, handling reserve/advance. */
  6463. static bool encode_bytes(upb_pb_encoder *e, const void *data, size_t len) {
  6464. if (!reserve(e, len)) {
  6465. return false;
  6466. }
  6467. memcpy(e->ptr, data, len);
  6468. encoder_advance(e, len);
  6469. return true;
  6470. }
  6471. /* Finish the current run by adding the run totals to the segment and message
  6472. * length. */
  6473. static void accumulate(upb_pb_encoder *e) {
  6474. size_t run_len;
  6475. UPB_ASSERT(e->ptr >= e->runbegin);
  6476. run_len = e->ptr - e->runbegin;
  6477. e->segptr->seglen += run_len;
  6478. top(e)->msglen += run_len;
  6479. e->runbegin = e->ptr;
  6480. }
  6481. /* Call to indicate the start of delimited region for which the full length is
  6482. * not yet known. All data will be buffered until the length is known.
  6483. * Delimited regions may be nested; their lengths will all be tracked properly. */
  6484. static bool start_delim(upb_pb_encoder *e) {
  6485. if (e->top) {
  6486. /* We are already buffering, advance to the next segment and push it on the
  6487. * stack. */
  6488. accumulate(e);
  6489. if (++e->top == e->stacklimit) {
  6490. /* TODO(haberman): grow stack? */
  6491. return false;
  6492. }
  6493. if (++e->segptr == e->seglimit) {
  6494. /* Grow segment buffer. */
  6495. size_t old_size =
  6496. (e->seglimit - e->segbuf) * sizeof(upb_pb_encoder_segment);
  6497. size_t new_size = old_size * 2;
  6498. upb_pb_encoder_segment *new_buf =
  6499. upb_arena_realloc(e->arena, e->segbuf, old_size, new_size);
  6500. if (new_buf == NULL) {
  6501. return false;
  6502. }
  6503. e->segptr = new_buf + (e->segptr - e->segbuf);
  6504. e->seglimit = new_buf + (new_size / sizeof(upb_pb_encoder_segment));
  6505. e->segbuf = new_buf;
  6506. }
  6507. } else {
  6508. /* We were previously at the top level, start buffering. */
  6509. e->segptr = e->segbuf;
  6510. e->top = e->stack;
  6511. e->runbegin = e->ptr;
  6512. }
  6513. *e->top = e->segptr - e->segbuf;
  6514. e->segptr->seglen = 0;
  6515. e->segptr->msglen = 0;
  6516. return true;
  6517. }
  6518. /* Call to indicate the end of a delimited region. We now know the length of
  6519. * the delimited region. If we are not nested inside any other delimited
  6520. * regions, we can now emit all of the buffered data we accumulated. */
  6521. static bool end_delim(upb_pb_encoder *e) {
  6522. size_t msglen;
  6523. accumulate(e);
  6524. msglen = top(e)->msglen;
  6525. if (e->top == e->stack) {
  6526. /* All lengths are now available, emit all buffered data. */
  6527. char buf[UPB_PB_VARINT_MAX_LEN];
  6528. upb_pb_encoder_segment *s;
  6529. const char *ptr = e->buf;
  6530. for (s = e->segbuf; s <= e->segptr; s++) {
  6531. size_t lenbytes = upb_vencode64(s->msglen, buf);
  6532. putbuf(e, buf, lenbytes);
  6533. putbuf(e, ptr, s->seglen);
  6534. ptr += s->seglen;
  6535. }
  6536. e->ptr = e->buf;
  6537. e->top = NULL;
  6538. } else {
  6539. /* Need to keep buffering; propagate length info into enclosing
  6540. * submessages. */
  6541. --e->top;
  6542. top(e)->msglen += msglen + upb_varint_size(msglen);
  6543. }
  6544. return true;
  6545. }
  6546. /* tag_t **********************************************************************/
  6547. /* A precomputed (pre-encoded) tag and length. */
  6548. typedef struct {
  6549. uint8_t bytes;
  6550. char tag[7];
  6551. } tag_t;
  6552. /* Allocates a new tag for this field, and sets it in these handlerattr. */
  6553. static void new_tag(upb_handlers *h, const upb_fielddef *f, upb_wiretype_t wt,
  6554. upb_handlerattr *attr) {
  6555. uint32_t n = upb_fielddef_number(f);
  6556. tag_t *tag = upb_gmalloc(sizeof(tag_t));
  6557. tag->bytes = upb_vencode64((n << 3) | wt, tag->tag);
  6558. attr->handler_data = tag;
  6559. upb_handlers_addcleanup(h, tag, upb_gfree);
  6560. }
  6561. static bool encode_tag(upb_pb_encoder *e, const tag_t *tag) {
  6562. return encode_bytes(e, tag->tag, tag->bytes);
  6563. }
  6564. /* encoding of wire types *****************************************************/
  6565. static bool encode_fixed64(upb_pb_encoder *e, uint64_t val) {
  6566. /* TODO(haberman): byte-swap for big endian. */
  6567. return encode_bytes(e, &val, sizeof(uint64_t));
  6568. }
  6569. static bool encode_fixed32(upb_pb_encoder *e, uint32_t val) {
  6570. /* TODO(haberman): byte-swap for big endian. */
  6571. return encode_bytes(e, &val, sizeof(uint32_t));
  6572. }
  6573. static bool encode_varint(upb_pb_encoder *e, uint64_t val) {
  6574. if (!reserve(e, UPB_PB_VARINT_MAX_LEN)) {
  6575. return false;
  6576. }
  6577. encoder_advance(e, upb_vencode64(val, e->ptr));
  6578. return true;
  6579. }
  6580. static uint64_t dbl2uint64(double d) {
  6581. uint64_t ret;
  6582. memcpy(&ret, &d, sizeof(uint64_t));
  6583. return ret;
  6584. }
  6585. static uint32_t flt2uint32(float d) {
  6586. uint32_t ret;
  6587. memcpy(&ret, &d, sizeof(uint32_t));
  6588. return ret;
  6589. }
  6590. /* encoding of proto types ****************************************************/
  6591. static bool startmsg(void *c, const void *hd) {
  6592. upb_pb_encoder *e = c;
  6593. UPB_UNUSED(hd);
  6594. if (e->depth++ == 0) {
  6595. upb_bytessink_start(e->output_, 0, &e->subc);
  6596. }
  6597. return true;
  6598. }
  6599. static bool endmsg(void *c, const void *hd, upb_status *status) {
  6600. upb_pb_encoder *e = c;
  6601. UPB_UNUSED(hd);
  6602. UPB_UNUSED(status);
  6603. if (--e->depth == 0) {
  6604. upb_bytessink_end(e->output_);
  6605. }
  6606. return true;
  6607. }
  6608. static void *encode_startdelimfield(void *c, const void *hd) {
  6609. bool ok = encode_tag(c, hd) && commit(c) && start_delim(c);
  6610. return ok ? c : UPB_BREAK;
  6611. }
  6612. static bool encode_unknown(void *c, const void *hd, const char *buf,
  6613. size_t len) {
  6614. UPB_UNUSED(hd);
  6615. return encode_bytes(c, buf, len) && commit(c);
  6616. }
  6617. static bool encode_enddelimfield(void *c, const void *hd) {
  6618. UPB_UNUSED(hd);
  6619. return end_delim(c);
  6620. }
  6621. static void *encode_startgroup(void *c, const void *hd) {
  6622. return (encode_tag(c, hd) && commit(c)) ? c : UPB_BREAK;
  6623. }
  6624. static bool encode_endgroup(void *c, const void *hd) {
  6625. return encode_tag(c, hd) && commit(c);
  6626. }
  6627. static void *encode_startstr(void *c, const void *hd, size_t size_hint) {
  6628. UPB_UNUSED(size_hint);
  6629. return encode_startdelimfield(c, hd);
  6630. }
  6631. static size_t encode_strbuf(void *c, const void *hd, const char *buf,
  6632. size_t len, const upb_bufhandle *h) {
  6633. UPB_UNUSED(hd);
  6634. UPB_UNUSED(h);
  6635. return encode_bytes(c, buf, len) ? len : 0;
  6636. }
  6637. #define T(type, ctype, convert, encode) \
  6638. static bool encode_scalar_##type(void *e, const void *hd, ctype val) { \
  6639. return encode_tag(e, hd) && encode(e, (convert)(val)) && commit(e); \
  6640. } \
  6641. static bool encode_packed_##type(void *e, const void *hd, ctype val) { \
  6642. UPB_UNUSED(hd); \
  6643. return encode(e, (convert)(val)); \
  6644. }
  6645. T(double, double, dbl2uint64, encode_fixed64)
  6646. T(float, float, flt2uint32, encode_fixed32)
  6647. T(int64, int64_t, uint64_t, encode_varint)
  6648. T(int32, int32_t, int64_t, encode_varint)
  6649. T(fixed64, uint64_t, uint64_t, encode_fixed64)
  6650. T(fixed32, uint32_t, uint32_t, encode_fixed32)
  6651. T(bool, bool, bool, encode_varint)
  6652. T(uint32, uint32_t, uint32_t, encode_varint)
  6653. T(uint64, uint64_t, uint64_t, encode_varint)
  6654. T(enum, int32_t, uint32_t, encode_varint)
  6655. T(sfixed32, int32_t, uint32_t, encode_fixed32)
  6656. T(sfixed64, int64_t, uint64_t, encode_fixed64)
  6657. T(sint32, int32_t, upb_zzenc_32, encode_varint)
  6658. T(sint64, int64_t, upb_zzenc_64, encode_varint)
  6659. #undef T
  6660. /* code to build the handlers *************************************************/
  6661. #include <stdio.h>
  6662. static void newhandlers_callback(const void *closure, upb_handlers *h) {
  6663. const upb_msgdef *m;
  6664. upb_msg_field_iter i;
  6665. UPB_UNUSED(closure);
  6666. upb_handlers_setstartmsg(h, startmsg, NULL);
  6667. upb_handlers_setendmsg(h, endmsg, NULL);
  6668. upb_handlers_setunknown(h, encode_unknown, NULL);
  6669. m = upb_handlers_msgdef(h);
  6670. for(upb_msg_field_begin(&i, m);
  6671. !upb_msg_field_done(&i);
  6672. upb_msg_field_next(&i)) {
  6673. const upb_fielddef *f = upb_msg_iter_field(&i);
  6674. bool packed = upb_fielddef_isseq(f) && upb_fielddef_isprimitive(f) &&
  6675. upb_fielddef_packed(f);
  6676. upb_handlerattr attr = UPB_HANDLERATTR_INIT;
  6677. upb_wiretype_t wt =
  6678. packed ? UPB_WIRE_TYPE_DELIMITED
  6679. : upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
  6680. /* Pre-encode the tag for this field. */
  6681. new_tag(h, f, wt, &attr);
  6682. if (packed) {
  6683. upb_handlers_setstartseq(h, f, encode_startdelimfield, &attr);
  6684. upb_handlers_setendseq(h, f, encode_enddelimfield, &attr);
  6685. }
  6686. #define T(upper, lower, upbtype) \
  6687. case UPB_DESCRIPTOR_TYPE_##upper: \
  6688. if (packed) { \
  6689. upb_handlers_set##upbtype(h, f, encode_packed_##lower, &attr); \
  6690. } else { \
  6691. upb_handlers_set##upbtype(h, f, encode_scalar_##lower, &attr); \
  6692. } \
  6693. break;
  6694. switch (upb_fielddef_descriptortype(f)) {
  6695. T(DOUBLE, double, double);
  6696. T(FLOAT, float, float);
  6697. T(INT64, int64, int64);
  6698. T(INT32, int32, int32);
  6699. T(FIXED64, fixed64, uint64);
  6700. T(FIXED32, fixed32, uint32);
  6701. T(BOOL, bool, bool);
  6702. T(UINT32, uint32, uint32);
  6703. T(UINT64, uint64, uint64);
  6704. T(ENUM, enum, int32);
  6705. T(SFIXED32, sfixed32, int32);
  6706. T(SFIXED64, sfixed64, int64);
  6707. T(SINT32, sint32, int32);
  6708. T(SINT64, sint64, int64);
  6709. case UPB_DESCRIPTOR_TYPE_STRING:
  6710. case UPB_DESCRIPTOR_TYPE_BYTES:
  6711. upb_handlers_setstartstr(h, f, encode_startstr, &attr);
  6712. upb_handlers_setendstr(h, f, encode_enddelimfield, &attr);
  6713. upb_handlers_setstring(h, f, encode_strbuf, &attr);
  6714. break;
  6715. case UPB_DESCRIPTOR_TYPE_MESSAGE:
  6716. upb_handlers_setstartsubmsg(h, f, encode_startdelimfield, &attr);
  6717. upb_handlers_setendsubmsg(h, f, encode_enddelimfield, &attr);
  6718. break;
  6719. case UPB_DESCRIPTOR_TYPE_GROUP: {
  6720. /* Endgroup takes a different tag (wire_type = END_GROUP). */
  6721. upb_handlerattr attr2 = UPB_HANDLERATTR_INIT;
  6722. new_tag(h, f, UPB_WIRE_TYPE_END_GROUP, &attr2);
  6723. upb_handlers_setstartsubmsg(h, f, encode_startgroup, &attr);
  6724. upb_handlers_setendsubmsg(h, f, encode_endgroup, &attr2);
  6725. break;
  6726. }
  6727. }
  6728. #undef T
  6729. }
  6730. }
  6731. void upb_pb_encoder_reset(upb_pb_encoder *e) {
  6732. e->segptr = NULL;
  6733. e->top = NULL;
  6734. e->depth = 0;
  6735. }
  6736. /* public API *****************************************************************/
  6737. upb_handlercache *upb_pb_encoder_newcache(void) {
  6738. return upb_handlercache_new(newhandlers_callback, NULL);
  6739. }
  6740. upb_pb_encoder *upb_pb_encoder_create(upb_arena *arena, const upb_handlers *h,
  6741. upb_bytessink output) {
  6742. const size_t initial_bufsize = 256;
  6743. const size_t initial_segbufsize = 16;
  6744. /* TODO(haberman): make this configurable. */
  6745. const size_t stack_size = 64;
  6746. #ifndef NDEBUG
  6747. const size_t size_before = upb_arena_bytesallocated(arena);
  6748. #endif
  6749. upb_pb_encoder *e = upb_arena_malloc(arena, sizeof(upb_pb_encoder));
  6750. if (!e) return NULL;
  6751. e->buf = upb_arena_malloc(arena, initial_bufsize);
  6752. e->segbuf = upb_arena_malloc(arena, initial_segbufsize * sizeof(*e->segbuf));
  6753. e->stack = upb_arena_malloc(arena, stack_size * sizeof(*e->stack));
  6754. if (!e->buf || !e->segbuf || !e->stack) {
  6755. return NULL;
  6756. }
  6757. e->limit = e->buf + initial_bufsize;
  6758. e->seglimit = e->segbuf + initial_segbufsize;
  6759. e->stacklimit = e->stack + stack_size;
  6760. upb_pb_encoder_reset(e);
  6761. upb_sink_reset(&e->input_, h, e);
  6762. e->arena = arena;
  6763. e->output_ = output;
  6764. e->subc = output.closure;
  6765. e->ptr = e->buf;
  6766. /* If this fails, increase the value in encoder.h. */
  6767. UPB_ASSERT_DEBUGVAR(upb_arena_bytesallocated(arena) - size_before <=
  6768. UPB_PB_ENCODER_SIZE);
  6769. return e;
  6770. }
  6771. upb_sink upb_pb_encoder_input(upb_pb_encoder *e) { return e->input_; }
  6772. /*
  6773. * upb::pb::TextPrinter
  6774. *
  6775. * OPT: This is not optimized at all. It uses printf() which parses the format
  6776. * string every time, and it allocates memory for every put.
  6777. */
  6778. #include <ctype.h>
  6779. #include <float.h>
  6780. #include <inttypes.h>
  6781. #include <stdarg.h>
  6782. #include <stdio.h>
  6783. #include <string.h>
  6784. struct upb_textprinter {
  6785. upb_sink input_;
  6786. upb_bytessink output_;
  6787. int indent_depth_;
  6788. bool single_line_;
  6789. void *subc;
  6790. };
  6791. #define CHECK(x) if ((x) < 0) goto err;
  6792. static const char *shortname(const char *longname) {
  6793. const char *last = strrchr(longname, '.');
  6794. return last ? last + 1 : longname;
  6795. }
  6796. static int indent(upb_textprinter *p) {
  6797. int i;
  6798. if (!p->single_line_)
  6799. for (i = 0; i < p->indent_depth_; i++)
  6800. upb_bytessink_putbuf(p->output_, p->subc, " ", 2, NULL);
  6801. return 0;
  6802. }
  6803. static int endfield(upb_textprinter *p) {
  6804. const char ch = (p->single_line_ ? ' ' : '\n');
  6805. upb_bytessink_putbuf(p->output_, p->subc, &ch, 1, NULL);
  6806. return 0;
  6807. }
  6808. static int putescaped(upb_textprinter *p, const char *buf, size_t len,
  6809. bool preserve_utf8) {
  6810. /* Based on CEscapeInternal() from Google's protobuf release. */
  6811. char dstbuf[4096], *dst = dstbuf, *dstend = dstbuf + sizeof(dstbuf);
  6812. const char *end = buf + len;
  6813. /* I think hex is prettier and more useful, but proto2 uses octal; should
  6814. * investigate whether it can parse hex also. */
  6815. const bool use_hex = false;
  6816. bool last_hex_escape = false; /* true if last output char was \xNN */
  6817. for (; buf < end; buf++) {
  6818. bool is_hex_escape;
  6819. if (dstend - dst < 4) {
  6820. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  6821. dst = dstbuf;
  6822. }
  6823. is_hex_escape = false;
  6824. switch (*buf) {
  6825. case '\n': *(dst++) = '\\'; *(dst++) = 'n'; break;
  6826. case '\r': *(dst++) = '\\'; *(dst++) = 'r'; break;
  6827. case '\t': *(dst++) = '\\'; *(dst++) = 't'; break;
  6828. case '\"': *(dst++) = '\\'; *(dst++) = '\"'; break;
  6829. case '\'': *(dst++) = '\\'; *(dst++) = '\''; break;
  6830. case '\\': *(dst++) = '\\'; *(dst++) = '\\'; break;
  6831. default:
  6832. /* Note that if we emit \xNN and the buf character after that is a hex
  6833. * digit then that digit must be escaped too to prevent it being
  6834. * interpreted as part of the character code by C. */
  6835. if ((!preserve_utf8 || (uint8_t)*buf < 0x80) &&
  6836. (!isprint(*buf) || (last_hex_escape && isxdigit(*buf)))) {
  6837. sprintf(dst, (use_hex ? "\\x%02x" : "\\%03o"), (uint8_t)*buf);
  6838. is_hex_escape = use_hex;
  6839. dst += 4;
  6840. } else {
  6841. *(dst++) = *buf; break;
  6842. }
  6843. }
  6844. last_hex_escape = is_hex_escape;
  6845. }
  6846. /* Flush remaining data. */
  6847. upb_bytessink_putbuf(p->output_, p->subc, dstbuf, dst - dstbuf, NULL);
  6848. return 0;
  6849. }
  6850. bool putf(upb_textprinter *p, const char *fmt, ...) {
  6851. va_list args;
  6852. va_list args_copy;
  6853. char *str;
  6854. int written;
  6855. int len;
  6856. bool ok;
  6857. va_start(args, fmt);
  6858. /* Run once to get the length of the string. */
  6859. _upb_va_copy(args_copy, args);
  6860. len = _upb_vsnprintf(NULL, 0, fmt, args_copy);
  6861. va_end(args_copy);
  6862. /* + 1 for NULL terminator (vsprintf() requires it even if we don't). */
  6863. str = upb_gmalloc(len + 1);
  6864. if (!str) return false;
  6865. written = vsprintf(str, fmt, args);
  6866. va_end(args);
  6867. UPB_ASSERT(written == len);
  6868. ok = upb_bytessink_putbuf(p->output_, p->subc, str, len, NULL);
  6869. upb_gfree(str);
  6870. return ok;
  6871. }
  6872. /* handlers *******************************************************************/
  6873. static bool textprinter_startmsg(void *c, const void *hd) {
  6874. upb_textprinter *p = c;
  6875. UPB_UNUSED(hd);
  6876. if (p->indent_depth_ == 0) {
  6877. upb_bytessink_start(p->output_, 0, &p->subc);
  6878. }
  6879. return true;
  6880. }
  6881. static bool textprinter_endmsg(void *c, const void *hd, upb_status *s) {
  6882. upb_textprinter *p = c;
  6883. UPB_UNUSED(hd);
  6884. UPB_UNUSED(s);
  6885. if (p->indent_depth_ == 0) {
  6886. upb_bytessink_end(p->output_);
  6887. }
  6888. return true;
  6889. }
  6890. #define TYPE(name, ctype, fmt) \
  6891. static bool textprinter_put ## name(void *closure, const void *handler_data, \
  6892. ctype val) { \
  6893. upb_textprinter *p = closure; \
  6894. const upb_fielddef *f = handler_data; \
  6895. CHECK(indent(p)); \
  6896. putf(p, "%s: " fmt, upb_fielddef_name(f), val); \
  6897. CHECK(endfield(p)); \
  6898. return true; \
  6899. err: \
  6900. return false; \
  6901. }
  6902. static bool textprinter_putbool(void *closure, const void *handler_data,
  6903. bool val) {
  6904. upb_textprinter *p = closure;
  6905. const upb_fielddef *f = handler_data;
  6906. CHECK(indent(p));
  6907. putf(p, "%s: %s", upb_fielddef_name(f), val ? "true" : "false");
  6908. CHECK(endfield(p));
  6909. return true;
  6910. err:
  6911. return false;
  6912. }
  6913. #define STRINGIFY_HELPER(x) #x
  6914. #define STRINGIFY_MACROVAL(x) STRINGIFY_HELPER(x)
  6915. TYPE(int32, int32_t, "%" PRId32)
  6916. TYPE(int64, int64_t, "%" PRId64)
  6917. TYPE(uint32, uint32_t, "%" PRIu32)
  6918. TYPE(uint64, uint64_t, "%" PRIu64)
  6919. TYPE(float, float, "%." STRINGIFY_MACROVAL(FLT_DIG) "g")
  6920. TYPE(double, double, "%." STRINGIFY_MACROVAL(DBL_DIG) "g")
  6921. #undef TYPE
  6922. /* Output a symbolic value from the enum if found, else just print as int32. */
  6923. static bool textprinter_putenum(void *closure, const void *handler_data,
  6924. int32_t val) {
  6925. upb_textprinter *p = closure;
  6926. const upb_fielddef *f = handler_data;
  6927. const upb_enumdef *enum_def = upb_fielddef_enumsubdef(f);
  6928. const char *label = upb_enumdef_iton(enum_def, val);
  6929. if (label) {
  6930. indent(p);
  6931. putf(p, "%s: %s", upb_fielddef_name(f), label);
  6932. endfield(p);
  6933. } else {
  6934. if (!textprinter_putint32(closure, handler_data, val))
  6935. return false;
  6936. }
  6937. return true;
  6938. }
  6939. static void *textprinter_startstr(void *closure, const void *handler_data,
  6940. size_t size_hint) {
  6941. upb_textprinter *p = closure;
  6942. const upb_fielddef *f = handler_data;
  6943. UPB_UNUSED(size_hint);
  6944. indent(p);
  6945. putf(p, "%s: \"", upb_fielddef_name(f));
  6946. return p;
  6947. }
  6948. static bool textprinter_endstr(void *closure, const void *handler_data) {
  6949. upb_textprinter *p = closure;
  6950. UPB_UNUSED(handler_data);
  6951. putf(p, "\"");
  6952. endfield(p);
  6953. return true;
  6954. }
  6955. static size_t textprinter_putstr(void *closure, const void *hd, const char *buf,
  6956. size_t len, const upb_bufhandle *handle) {
  6957. upb_textprinter *p = closure;
  6958. const upb_fielddef *f = hd;
  6959. UPB_UNUSED(handle);
  6960. CHECK(putescaped(p, buf, len, upb_fielddef_type(f) == UPB_TYPE_STRING));
  6961. return len;
  6962. err:
  6963. return 0;
  6964. }
  6965. static void *textprinter_startsubmsg(void *closure, const void *handler_data) {
  6966. upb_textprinter *p = closure;
  6967. const char *name = handler_data;
  6968. CHECK(indent(p));
  6969. putf(p, "%s {%c", name, p->single_line_ ? ' ' : '\n');
  6970. p->indent_depth_++;
  6971. return p;
  6972. err:
  6973. return UPB_BREAK;
  6974. }
  6975. static bool textprinter_endsubmsg(void *closure, const void *handler_data) {
  6976. upb_textprinter *p = closure;
  6977. UPB_UNUSED(handler_data);
  6978. p->indent_depth_--;
  6979. CHECK(indent(p));
  6980. upb_bytessink_putbuf(p->output_, p->subc, "}", 1, NULL);
  6981. CHECK(endfield(p));
  6982. return true;
  6983. err:
  6984. return false;
  6985. }
  6986. static void onmreg(const void *c, upb_handlers *h) {
  6987. const upb_msgdef *m = upb_handlers_msgdef(h);
  6988. upb_msg_field_iter i;
  6989. UPB_UNUSED(c);
  6990. upb_handlers_setstartmsg(h, textprinter_startmsg, NULL);
  6991. upb_handlers_setendmsg(h, textprinter_endmsg, NULL);
  6992. for(upb_msg_field_begin(&i, m);
  6993. !upb_msg_field_done(&i);
  6994. upb_msg_field_next(&i)) {
  6995. upb_fielddef *f = upb_msg_iter_field(&i);
  6996. upb_handlerattr attr = UPB_HANDLERATTR_INIT;
  6997. attr.handler_data = f;
  6998. switch (upb_fielddef_type(f)) {
  6999. case UPB_TYPE_INT32:
  7000. upb_handlers_setint32(h, f, textprinter_putint32, &attr);
  7001. break;
  7002. case UPB_TYPE_INT64:
  7003. upb_handlers_setint64(h, f, textprinter_putint64, &attr);
  7004. break;
  7005. case UPB_TYPE_UINT32:
  7006. upb_handlers_setuint32(h, f, textprinter_putuint32, &attr);
  7007. break;
  7008. case UPB_TYPE_UINT64:
  7009. upb_handlers_setuint64(h, f, textprinter_putuint64, &attr);
  7010. break;
  7011. case UPB_TYPE_FLOAT:
  7012. upb_handlers_setfloat(h, f, textprinter_putfloat, &attr);
  7013. break;
  7014. case UPB_TYPE_DOUBLE:
  7015. upb_handlers_setdouble(h, f, textprinter_putdouble, &attr);
  7016. break;
  7017. case UPB_TYPE_BOOL:
  7018. upb_handlers_setbool(h, f, textprinter_putbool, &attr);
  7019. break;
  7020. case UPB_TYPE_STRING:
  7021. case UPB_TYPE_BYTES:
  7022. upb_handlers_setstartstr(h, f, textprinter_startstr, &attr);
  7023. upb_handlers_setstring(h, f, textprinter_putstr, &attr);
  7024. upb_handlers_setendstr(h, f, textprinter_endstr, &attr);
  7025. break;
  7026. case UPB_TYPE_MESSAGE: {
  7027. const char *name =
  7028. upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_GROUP
  7029. ? shortname(upb_msgdef_fullname(upb_fielddef_msgsubdef(f)))
  7030. : upb_fielddef_name(f);
  7031. attr.handler_data = name;
  7032. upb_handlers_setstartsubmsg(h, f, textprinter_startsubmsg, &attr);
  7033. upb_handlers_setendsubmsg(h, f, textprinter_endsubmsg, &attr);
  7034. break;
  7035. }
  7036. case UPB_TYPE_ENUM:
  7037. upb_handlers_setint32(h, f, textprinter_putenum, &attr);
  7038. break;
  7039. }
  7040. }
  7041. }
  7042. static void textprinter_reset(upb_textprinter *p, bool single_line) {
  7043. p->single_line_ = single_line;
  7044. p->indent_depth_ = 0;
  7045. }
  7046. /* Public API *****************************************************************/
  7047. upb_textprinter *upb_textprinter_create(upb_arena *arena, const upb_handlers *h,
  7048. upb_bytessink output) {
  7049. upb_textprinter *p = upb_arena_malloc(arena, sizeof(upb_textprinter));
  7050. if (!p) return NULL;
  7051. p->output_ = output;
  7052. upb_sink_reset(&p->input_, h, p);
  7053. textprinter_reset(p, false);
  7054. return p;
  7055. }
  7056. upb_handlercache *upb_textprinter_newcache(void) {
  7057. return upb_handlercache_new(&onmreg, NULL);
  7058. }
  7059. upb_sink upb_textprinter_input(upb_textprinter *p) { return p->input_; }
  7060. void upb_textprinter_setsingleline(upb_textprinter *p, bool single_line) {
  7061. p->single_line_ = single_line;
  7062. }
  7063. /* Index is descriptor type. */
  7064. const uint8_t upb_pb_native_wire_types[] = {
  7065. UPB_WIRE_TYPE_END_GROUP, /* ENDGROUP */
  7066. UPB_WIRE_TYPE_64BIT, /* DOUBLE */
  7067. UPB_WIRE_TYPE_32BIT, /* FLOAT */
  7068. UPB_WIRE_TYPE_VARINT, /* INT64 */
  7069. UPB_WIRE_TYPE_VARINT, /* UINT64 */
  7070. UPB_WIRE_TYPE_VARINT, /* INT32 */
  7071. UPB_WIRE_TYPE_64BIT, /* FIXED64 */
  7072. UPB_WIRE_TYPE_32BIT, /* FIXED32 */
  7073. UPB_WIRE_TYPE_VARINT, /* BOOL */
  7074. UPB_WIRE_TYPE_DELIMITED, /* STRING */
  7075. UPB_WIRE_TYPE_START_GROUP, /* GROUP */
  7076. UPB_WIRE_TYPE_DELIMITED, /* MESSAGE */
  7077. UPB_WIRE_TYPE_DELIMITED, /* BYTES */
  7078. UPB_WIRE_TYPE_VARINT, /* UINT32 */
  7079. UPB_WIRE_TYPE_VARINT, /* ENUM */
  7080. UPB_WIRE_TYPE_32BIT, /* SFIXED32 */
  7081. UPB_WIRE_TYPE_64BIT, /* SFIXED64 */
  7082. UPB_WIRE_TYPE_VARINT, /* SINT32 */
  7083. UPB_WIRE_TYPE_VARINT, /* SINT64 */
  7084. };
  7085. /* A basic branch-based decoder, uses 32-bit values to get good performance
  7086. * on 32-bit architectures (but performs well on 64-bits also).
  7087. * This scheme comes from the original Google Protobuf implementation
  7088. * (proto2). */
  7089. upb_decoderet upb_vdecode_max8_branch32(upb_decoderet r) {
  7090. upb_decoderet err = {NULL, 0};
  7091. const char *p = r.p;
  7092. uint32_t low = (uint32_t)r.val;
  7093. uint32_t high = 0;
  7094. uint32_t b;
  7095. b = *(p++); low |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  7096. b = *(p++); low |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  7097. b = *(p++); low |= (b & 0x7fU) << 28;
  7098. high = (b & 0x7fU) >> 4; if (!(b & 0x80)) goto done;
  7099. b = *(p++); high |= (b & 0x7fU) << 3; if (!(b & 0x80)) goto done;
  7100. b = *(p++); high |= (b & 0x7fU) << 10; if (!(b & 0x80)) goto done;
  7101. b = *(p++); high |= (b & 0x7fU) << 17; if (!(b & 0x80)) goto done;
  7102. b = *(p++); high |= (b & 0x7fU) << 24; if (!(b & 0x80)) goto done;
  7103. b = *(p++); high |= (b & 0x7fU) << 31; if (!(b & 0x80)) goto done;
  7104. return err;
  7105. done:
  7106. r.val = ((uint64_t)high << 32) | low;
  7107. r.p = p;
  7108. return r;
  7109. }
  7110. /* Like the previous, but uses 64-bit values. */
  7111. upb_decoderet upb_vdecode_max8_branch64(upb_decoderet r) {
  7112. const char *p = r.p;
  7113. uint64_t val = r.val;
  7114. uint64_t b;
  7115. upb_decoderet err = {NULL, 0};
  7116. b = *(p++); val |= (b & 0x7fU) << 14; if (!(b & 0x80)) goto done;
  7117. b = *(p++); val |= (b & 0x7fU) << 21; if (!(b & 0x80)) goto done;
  7118. b = *(p++); val |= (b & 0x7fU) << 28; if (!(b & 0x80)) goto done;
  7119. b = *(p++); val |= (b & 0x7fU) << 35; if (!(b & 0x80)) goto done;
  7120. b = *(p++); val |= (b & 0x7fU) << 42; if (!(b & 0x80)) goto done;
  7121. b = *(p++); val |= (b & 0x7fU) << 49; if (!(b & 0x80)) goto done;
  7122. b = *(p++); val |= (b & 0x7fU) << 56; if (!(b & 0x80)) goto done;
  7123. b = *(p++); val |= (b & 0x7fU) << 63; if (!(b & 0x80)) goto done;
  7124. return err;
  7125. done:
  7126. r.val = val;
  7127. r.p = p;
  7128. return r;
  7129. }
  7130. #line 1 "upb/json/parser.rl"
  7131. /*
  7132. ** upb::json::Parser (upb_json_parser)
  7133. **
  7134. ** A parser that uses the Ragel State Machine Compiler to generate
  7135. ** the finite automata.
  7136. **
  7137. ** Ragel only natively handles regular languages, but we can manually
  7138. ** program it a bit to handle context-free languages like JSON, by using
  7139. ** the "fcall" and "fret" constructs.
  7140. **
  7141. ** This parser can handle the basics, but needs several things to be fleshed
  7142. ** out:
  7143. **
  7144. ** - handling of unicode escape sequences (including high surrogate pairs).
  7145. ** - properly check and report errors for unknown fields, stack overflow,
  7146. ** improper array nesting (or lack of nesting).
  7147. ** - handling of base64 sequences with padding characters.
  7148. ** - handling of push-back (non-success returns from sink functions).
  7149. ** - handling of keys/escape-sequences/etc that span input buffers.
  7150. */
  7151. #include <ctype.h>
  7152. #include <errno.h>
  7153. #include <float.h>
  7154. #include <math.h>
  7155. #include <stdint.h>
  7156. #include <stdio.h>
  7157. #include <stdlib.h>
  7158. #include <string.h>
  7159. #include <time.h>
  7160. #define UPB_JSON_MAX_DEPTH 64
  7161. /* Type of value message */
  7162. enum {
  7163. VALUE_NULLVALUE = 0,
  7164. VALUE_NUMBERVALUE = 1,
  7165. VALUE_STRINGVALUE = 2,
  7166. VALUE_BOOLVALUE = 3,
  7167. VALUE_STRUCTVALUE = 4,
  7168. VALUE_LISTVALUE = 5
  7169. };
  7170. /* Forward declare */
  7171. static bool is_top_level(upb_json_parser *p);
  7172. static bool is_wellknown_msg(upb_json_parser *p, upb_wellknowntype_t type);
  7173. static bool is_wellknown_field(upb_json_parser *p, upb_wellknowntype_t type);
  7174. static bool is_number_wrapper_object(upb_json_parser *p);
  7175. static bool does_number_wrapper_start(upb_json_parser *p);
  7176. static bool does_number_wrapper_end(upb_json_parser *p);
  7177. static bool is_string_wrapper_object(upb_json_parser *p);
  7178. static bool does_string_wrapper_start(upb_json_parser *p);
  7179. static bool does_string_wrapper_end(upb_json_parser *p);
  7180. static bool does_fieldmask_start(upb_json_parser *p);
  7181. static bool does_fieldmask_end(upb_json_parser *p);
  7182. static void start_fieldmask_object(upb_json_parser *p);
  7183. static void end_fieldmask_object(upb_json_parser *p);
  7184. static void start_wrapper_object(upb_json_parser *p);
  7185. static void end_wrapper_object(upb_json_parser *p);
  7186. static void start_value_object(upb_json_parser *p, int value_type);
  7187. static void end_value_object(upb_json_parser *p);
  7188. static void start_listvalue_object(upb_json_parser *p);
  7189. static void end_listvalue_object(upb_json_parser *p);
  7190. static void start_structvalue_object(upb_json_parser *p);
  7191. static void end_structvalue_object(upb_json_parser *p);
  7192. static void start_object(upb_json_parser *p);
  7193. static void end_object(upb_json_parser *p);
  7194. static void start_any_object(upb_json_parser *p, const char *ptr);
  7195. static bool end_any_object(upb_json_parser *p, const char *ptr);
  7196. static bool start_subobject(upb_json_parser *p);
  7197. static void end_subobject(upb_json_parser *p);
  7198. static void start_member(upb_json_parser *p);
  7199. static void end_member(upb_json_parser *p);
  7200. static bool end_membername(upb_json_parser *p);
  7201. static void start_any_member(upb_json_parser *p, const char *ptr);
  7202. static void end_any_member(upb_json_parser *p, const char *ptr);
  7203. static bool end_any_membername(upb_json_parser *p);
  7204. size_t parse(void *closure, const void *hd, const char *buf, size_t size,
  7205. const upb_bufhandle *handle);
  7206. static bool end(void *closure, const void *hd);
  7207. static const char eof_ch = 'e';
  7208. /* stringsink */
  7209. typedef struct {
  7210. upb_byteshandler handler;
  7211. upb_bytessink sink;
  7212. char *ptr;
  7213. size_t len, size;
  7214. } upb_stringsink;
  7215. static void *stringsink_start(void *_sink, const void *hd, size_t size_hint) {
  7216. upb_stringsink *sink = _sink;
  7217. sink->len = 0;
  7218. UPB_UNUSED(hd);
  7219. UPB_UNUSED(size_hint);
  7220. return sink;
  7221. }
  7222. static size_t stringsink_string(void *_sink, const void *hd, const char *ptr,
  7223. size_t len, const upb_bufhandle *handle) {
  7224. upb_stringsink *sink = _sink;
  7225. size_t new_size = sink->size;
  7226. UPB_UNUSED(hd);
  7227. UPB_UNUSED(handle);
  7228. while (sink->len + len > new_size) {
  7229. new_size *= 2;
  7230. }
  7231. if (new_size != sink->size) {
  7232. sink->ptr = realloc(sink->ptr, new_size);
  7233. sink->size = new_size;
  7234. }
  7235. memcpy(sink->ptr + sink->len, ptr, len);
  7236. sink->len += len;
  7237. return len;
  7238. }
  7239. void upb_stringsink_init(upb_stringsink *sink) {
  7240. upb_byteshandler_init(&sink->handler);
  7241. upb_byteshandler_setstartstr(&sink->handler, stringsink_start, NULL);
  7242. upb_byteshandler_setstring(&sink->handler, stringsink_string, NULL);
  7243. upb_bytessink_reset(&sink->sink, &sink->handler, sink);
  7244. sink->size = 32;
  7245. sink->ptr = malloc(sink->size);
  7246. sink->len = 0;
  7247. }
  7248. void upb_stringsink_uninit(upb_stringsink *sink) { free(sink->ptr); }
  7249. typedef struct {
  7250. /* For encoding Any value field in binary format. */
  7251. upb_handlercache *encoder_handlercache;
  7252. upb_stringsink stringsink;
  7253. /* For decoding Any value field in json format. */
  7254. upb_json_codecache *parser_codecache;
  7255. upb_sink sink;
  7256. upb_json_parser *parser;
  7257. /* Mark the range of uninterpreted values in json input before type url. */
  7258. const char *before_type_url_start;
  7259. const char *before_type_url_end;
  7260. /* Mark the range of uninterpreted values in json input after type url. */
  7261. const char *after_type_url_start;
  7262. } upb_jsonparser_any_frame;
  7263. typedef struct {
  7264. upb_sink sink;
  7265. /* The current message in which we're parsing, and the field whose value we're
  7266. * expecting next. */
  7267. const upb_msgdef *m;
  7268. const upb_fielddef *f;
  7269. /* The table mapping json name to fielddef for this message. */
  7270. const upb_strtable *name_table;
  7271. /* We are in a repeated-field context. We need this flag to decide whether to
  7272. * handle the array as a normal repeated field or a
  7273. * google.protobuf.ListValue/google.protobuf.Value. */
  7274. bool is_repeated;
  7275. /* We are in a repeated-field context, ready to emit mapentries as
  7276. * submessages. This flag alters the start-of-object (open-brace) behavior to
  7277. * begin a sequence of mapentry messages rather than a single submessage. */
  7278. bool is_map;
  7279. /* We are in a map-entry message context. This flag is set when parsing the
  7280. * value field of a single map entry and indicates to all value-field parsers
  7281. * (subobjects, strings, numbers, and bools) that the map-entry submessage
  7282. * should end as soon as the value is parsed. */
  7283. bool is_mapentry;
  7284. /* If |is_map| or |is_mapentry| is true, |mapfield| refers to the parent
  7285. * message's map field that we're currently parsing. This differs from |f|
  7286. * because |f| is the field in the *current* message (i.e., the map-entry
  7287. * message itself), not the parent's field that leads to this map. */
  7288. const upb_fielddef *mapfield;
  7289. /* We are in an Any message context. This flag is set when parsing the Any
  7290. * message and indicates to all field parsers (subobjects, strings, numbers,
  7291. * and bools) that the parsed field should be serialized as binary data or
  7292. * cached (type url not found yet). */
  7293. bool is_any;
  7294. /* The type of packed message in Any. */
  7295. upb_jsonparser_any_frame *any_frame;
  7296. /* True if the field to be parsed is unknown. */
  7297. bool is_unknown_field;
  7298. } upb_jsonparser_frame;
  7299. static void init_frame(upb_jsonparser_frame* frame) {
  7300. frame->m = NULL;
  7301. frame->f = NULL;
  7302. frame->name_table = NULL;
  7303. frame->is_repeated = false;
  7304. frame->is_map = false;
  7305. frame->is_mapentry = false;
  7306. frame->mapfield = NULL;
  7307. frame->is_any = false;
  7308. frame->any_frame = NULL;
  7309. frame->is_unknown_field = false;
  7310. }
  7311. struct upb_json_parser {
  7312. upb_arena *arena;
  7313. const upb_json_parsermethod *method;
  7314. upb_bytessink input_;
  7315. /* Stack to track the JSON scopes we are in. */
  7316. upb_jsonparser_frame stack[UPB_JSON_MAX_DEPTH];
  7317. upb_jsonparser_frame *top;
  7318. upb_jsonparser_frame *limit;
  7319. upb_status *status;
  7320. /* Ragel's internal parsing stack for the parsing state machine. */
  7321. int current_state;
  7322. int parser_stack[UPB_JSON_MAX_DEPTH];
  7323. int parser_top;
  7324. /* The handle for the current buffer. */
  7325. const upb_bufhandle *handle;
  7326. /* Accumulate buffer. See details in parser.rl. */
  7327. const char *accumulated;
  7328. size_t accumulated_len;
  7329. char *accumulate_buf;
  7330. size_t accumulate_buf_size;
  7331. /* Multi-part text data. See details in parser.rl. */
  7332. int multipart_state;
  7333. upb_selector_t string_selector;
  7334. /* Input capture. See details in parser.rl. */
  7335. const char *capture;
  7336. /* Intermediate result of parsing a unicode escape sequence. */
  7337. uint32_t digit;
  7338. /* For resolve type url in Any. */
  7339. const upb_symtab *symtab;
  7340. /* Whether to proceed if unknown field is met. */
  7341. bool ignore_json_unknown;
  7342. /* Cache for parsing timestamp due to base and zone are handled in different
  7343. * handlers. */
  7344. struct tm tm;
  7345. };
  7346. static upb_jsonparser_frame* start_jsonparser_frame(upb_json_parser *p) {
  7347. upb_jsonparser_frame *inner;
  7348. inner = p->top + 1;
  7349. init_frame(inner);
  7350. return inner;
  7351. }
  7352. struct upb_json_codecache {
  7353. upb_arena *arena;
  7354. upb_inttable methods; /* upb_msgdef* -> upb_json_parsermethod* */
  7355. };
  7356. struct upb_json_parsermethod {
  7357. const upb_json_codecache *cache;
  7358. upb_byteshandler input_handler_;
  7359. /* Maps json_name -> fielddef */
  7360. upb_strtable name_table;
  7361. };
  7362. #define PARSER_CHECK_RETURN(x) if (!(x)) return false
  7363. static upb_jsonparser_any_frame *json_parser_any_frame_new(
  7364. upb_json_parser *p) {
  7365. upb_jsonparser_any_frame *frame;
  7366. frame = upb_arena_malloc(p->arena, sizeof(upb_jsonparser_any_frame));
  7367. frame->encoder_handlercache = upb_pb_encoder_newcache();
  7368. frame->parser_codecache = upb_json_codecache_new();
  7369. frame->parser = NULL;
  7370. frame->before_type_url_start = NULL;
  7371. frame->before_type_url_end = NULL;
  7372. frame->after_type_url_start = NULL;
  7373. upb_stringsink_init(&frame->stringsink);
  7374. return frame;
  7375. }
  7376. static void json_parser_any_frame_set_payload_type(
  7377. upb_json_parser *p,
  7378. upb_jsonparser_any_frame *frame,
  7379. const upb_msgdef *payload_type) {
  7380. const upb_handlers *h;
  7381. const upb_json_parsermethod *parser_method;
  7382. upb_pb_encoder *encoder;
  7383. /* Initialize encoder. */
  7384. h = upb_handlercache_get(frame->encoder_handlercache, payload_type);
  7385. encoder = upb_pb_encoder_create(p->arena, h, frame->stringsink.sink);
  7386. /* Initialize parser. */
  7387. parser_method = upb_json_codecache_get(frame->parser_codecache, payload_type);
  7388. upb_sink_reset(&frame->sink, h, encoder);
  7389. frame->parser =
  7390. upb_json_parser_create(p->arena, parser_method, p->symtab, frame->sink,
  7391. p->status, p->ignore_json_unknown);
  7392. }
  7393. static void json_parser_any_frame_free(upb_jsonparser_any_frame *frame) {
  7394. upb_handlercache_free(frame->encoder_handlercache);
  7395. upb_json_codecache_free(frame->parser_codecache);
  7396. upb_stringsink_uninit(&frame->stringsink);
  7397. }
  7398. static bool json_parser_any_frame_has_type_url(
  7399. upb_jsonparser_any_frame *frame) {
  7400. return frame->parser != NULL;
  7401. }
  7402. static bool json_parser_any_frame_has_value_before_type_url(
  7403. upb_jsonparser_any_frame *frame) {
  7404. return frame->before_type_url_start != frame->before_type_url_end;
  7405. }
  7406. static bool json_parser_any_frame_has_value_after_type_url(
  7407. upb_jsonparser_any_frame *frame) {
  7408. return frame->after_type_url_start != NULL;
  7409. }
  7410. static bool json_parser_any_frame_has_value(
  7411. upb_jsonparser_any_frame *frame) {
  7412. return json_parser_any_frame_has_value_before_type_url(frame) ||
  7413. json_parser_any_frame_has_value_after_type_url(frame);
  7414. }
  7415. static void json_parser_any_frame_set_before_type_url_end(
  7416. upb_jsonparser_any_frame *frame,
  7417. const char *ptr) {
  7418. if (frame->parser == NULL) {
  7419. frame->before_type_url_end = ptr;
  7420. }
  7421. }
  7422. static void json_parser_any_frame_set_after_type_url_start_once(
  7423. upb_jsonparser_any_frame *frame,
  7424. const char *ptr) {
  7425. if (json_parser_any_frame_has_type_url(frame) &&
  7426. frame->after_type_url_start == NULL) {
  7427. frame->after_type_url_start = ptr;
  7428. }
  7429. }
  7430. /* Used to signal that a capture has been suspended. */
  7431. static char suspend_capture;
  7432. static upb_selector_t getsel_for_handlertype(upb_json_parser *p,
  7433. upb_handlertype_t type) {
  7434. upb_selector_t sel;
  7435. bool ok = upb_handlers_getselector(p->top->f, type, &sel);
  7436. UPB_ASSERT(ok);
  7437. return sel;
  7438. }
  7439. static upb_selector_t parser_getsel(upb_json_parser *p) {
  7440. return getsel_for_handlertype(
  7441. p, upb_handlers_getprimitivehandlertype(p->top->f));
  7442. }
  7443. static bool check_stack(upb_json_parser *p) {
  7444. if ((p->top + 1) == p->limit) {
  7445. upb_status_seterrmsg(p->status, "Nesting too deep");
  7446. return false;
  7447. }
  7448. return true;
  7449. }
  7450. static void set_name_table(upb_json_parser *p, upb_jsonparser_frame *frame) {
  7451. upb_value v;
  7452. const upb_json_codecache *cache = p->method->cache;
  7453. bool ok;
  7454. const upb_json_parsermethod *method;
  7455. ok = upb_inttable_lookupptr(&cache->methods, frame->m, &v);
  7456. UPB_ASSERT(ok);
  7457. method = upb_value_getconstptr(v);
  7458. frame->name_table = &method->name_table;
  7459. }
  7460. /* There are GCC/Clang built-ins for overflow checking which we could start
  7461. * using if there was any performance benefit to it. */
  7462. static bool checked_add(size_t a, size_t b, size_t *c) {
  7463. if (SIZE_MAX - a < b) return false;
  7464. *c = a + b;
  7465. return true;
  7466. }
  7467. static size_t saturating_multiply(size_t a, size_t b) {
  7468. /* size_t is unsigned, so this is defined behavior even on overflow. */
  7469. size_t ret = a * b;
  7470. if (b != 0 && ret / b != a) {
  7471. ret = SIZE_MAX;
  7472. }
  7473. return ret;
  7474. }
  7475. /* Base64 decoding ************************************************************/
  7476. /* TODO(haberman): make this streaming. */
  7477. static const signed char b64table[] = {
  7478. -1, -1, -1, -1, -1, -1, -1, -1,
  7479. -1, -1, -1, -1, -1, -1, -1, -1,
  7480. -1, -1, -1, -1, -1, -1, -1, -1,
  7481. -1, -1, -1, -1, -1, -1, -1, -1,
  7482. -1, -1, -1, -1, -1, -1, -1, -1,
  7483. -1, -1, -1, 62/*+*/, -1, -1, -1, 63/*/ */,
  7484. 52/*0*/, 53/*1*/, 54/*2*/, 55/*3*/, 56/*4*/, 57/*5*/, 58/*6*/, 59/*7*/,
  7485. 60/*8*/, 61/*9*/, -1, -1, -1, -1, -1, -1,
  7486. -1, 0/*A*/, 1/*B*/, 2/*C*/, 3/*D*/, 4/*E*/, 5/*F*/, 6/*G*/,
  7487. 07/*H*/, 8/*I*/, 9/*J*/, 10/*K*/, 11/*L*/, 12/*M*/, 13/*N*/, 14/*O*/,
  7488. 15/*P*/, 16/*Q*/, 17/*R*/, 18/*S*/, 19/*T*/, 20/*U*/, 21/*V*/, 22/*W*/,
  7489. 23/*X*/, 24/*Y*/, 25/*Z*/, -1, -1, -1, -1, -1,
  7490. -1, 26/*a*/, 27/*b*/, 28/*c*/, 29/*d*/, 30/*e*/, 31/*f*/, 32/*g*/,
  7491. 33/*h*/, 34/*i*/, 35/*j*/, 36/*k*/, 37/*l*/, 38/*m*/, 39/*n*/, 40/*o*/,
  7492. 41/*p*/, 42/*q*/, 43/*r*/, 44/*s*/, 45/*t*/, 46/*u*/, 47/*v*/, 48/*w*/,
  7493. 49/*x*/, 50/*y*/, 51/*z*/, -1, -1, -1, -1, -1,
  7494. -1, -1, -1, -1, -1, -1, -1, -1,
  7495. -1, -1, -1, -1, -1, -1, -1, -1,
  7496. -1, -1, -1, -1, -1, -1, -1, -1,
  7497. -1, -1, -1, -1, -1, -1, -1, -1,
  7498. -1, -1, -1, -1, -1, -1, -1, -1,
  7499. -1, -1, -1, -1, -1, -1, -1, -1,
  7500. -1, -1, -1, -1, -1, -1, -1, -1,
  7501. -1, -1, -1, -1, -1, -1, -1, -1,
  7502. -1, -1, -1, -1, -1, -1, -1, -1,
  7503. -1, -1, -1, -1, -1, -1, -1, -1,
  7504. -1, -1, -1, -1, -1, -1, -1, -1,
  7505. -1, -1, -1, -1, -1, -1, -1, -1,
  7506. -1, -1, -1, -1, -1, -1, -1, -1,
  7507. -1, -1, -1, -1, -1, -1, -1, -1,
  7508. -1, -1, -1, -1, -1, -1, -1, -1,
  7509. -1, -1, -1, -1, -1, -1, -1, -1
  7510. };
  7511. /* Returns the table value sign-extended to 32 bits. Knowing that the upper
  7512. * bits will be 1 for unrecognized characters makes it easier to check for
  7513. * this error condition later (see below). */
  7514. int32_t b64lookup(unsigned char ch) { return b64table[ch]; }
  7515. /* Returns true if the given character is not a valid base64 character or
  7516. * padding. */
  7517. bool nonbase64(unsigned char ch) { return b64lookup(ch) == -1 && ch != '='; }
  7518. static bool base64_push(upb_json_parser *p, upb_selector_t sel, const char *ptr,
  7519. size_t len) {
  7520. const char *limit = ptr + len;
  7521. for (; ptr < limit; ptr += 4) {
  7522. uint32_t val;
  7523. char output[3];
  7524. if (limit - ptr < 4) {
  7525. upb_status_seterrf(p->status,
  7526. "Base64 input for bytes field not a multiple of 4: %s",
  7527. upb_fielddef_name(p->top->f));
  7528. return false;
  7529. }
  7530. val = b64lookup(ptr[0]) << 18 |
  7531. b64lookup(ptr[1]) << 12 |
  7532. b64lookup(ptr[2]) << 6 |
  7533. b64lookup(ptr[3]);
  7534. /* Test the upper bit; returns true if any of the characters returned -1. */
  7535. if (val & 0x80000000) {
  7536. goto otherchar;
  7537. }
  7538. output[0] = val >> 16;
  7539. output[1] = (val >> 8) & 0xff;
  7540. output[2] = val & 0xff;
  7541. upb_sink_putstring(p->top->sink, sel, output, 3, NULL);
  7542. }
  7543. return true;
  7544. otherchar:
  7545. if (nonbase64(ptr[0]) || nonbase64(ptr[1]) || nonbase64(ptr[2]) ||
  7546. nonbase64(ptr[3]) ) {
  7547. upb_status_seterrf(p->status,
  7548. "Non-base64 characters in bytes field: %s",
  7549. upb_fielddef_name(p->top->f));
  7550. return false;
  7551. } if (ptr[2] == '=') {
  7552. uint32_t val;
  7553. char output;
  7554. /* Last group contains only two input bytes, one output byte. */
  7555. if (ptr[0] == '=' || ptr[1] == '=' || ptr[3] != '=') {
  7556. goto badpadding;
  7557. }
  7558. val = b64lookup(ptr[0]) << 18 |
  7559. b64lookup(ptr[1]) << 12;
  7560. UPB_ASSERT(!(val & 0x80000000));
  7561. output = val >> 16;
  7562. upb_sink_putstring(p->top->sink, sel, &output, 1, NULL);
  7563. return true;
  7564. } else {
  7565. uint32_t val;
  7566. char output[2];
  7567. /* Last group contains only three input bytes, two output bytes. */
  7568. if (ptr[0] == '=' || ptr[1] == '=' || ptr[2] == '=') {
  7569. goto badpadding;
  7570. }
  7571. val = b64lookup(ptr[0]) << 18 |
  7572. b64lookup(ptr[1]) << 12 |
  7573. b64lookup(ptr[2]) << 6;
  7574. output[0] = val >> 16;
  7575. output[1] = (val >> 8) & 0xff;
  7576. upb_sink_putstring(p->top->sink, sel, output, 2, NULL);
  7577. return true;
  7578. }
  7579. badpadding:
  7580. upb_status_seterrf(p->status,
  7581. "Incorrect base64 padding for field: %s (%.*s)",
  7582. upb_fielddef_name(p->top->f),
  7583. 4, ptr);
  7584. return false;
  7585. }
  7586. /* Accumulate buffer **********************************************************/
  7587. /* Functionality for accumulating a buffer.
  7588. *
  7589. * Some parts of the parser need an entire value as a contiguous string. For
  7590. * example, to look up a member name in a hash table, or to turn a string into
  7591. * a number, the relevant library routines need the input string to be in
  7592. * contiguous memory, even if the value spanned two or more buffers in the
  7593. * input. These routines handle that.
  7594. *
  7595. * In the common case we can just point to the input buffer to get this
  7596. * contiguous string and avoid any actual copy. So we optimistically begin
  7597. * this way. But there are a few cases where we must instead copy into a
  7598. * separate buffer:
  7599. *
  7600. * 1. The string was not contiguous in the input (it spanned buffers).
  7601. *
  7602. * 2. The string included escape sequences that need to be interpreted to get
  7603. * the true value in a contiguous buffer. */
  7604. static void assert_accumulate_empty(upb_json_parser *p) {
  7605. UPB_ASSERT(p->accumulated == NULL);
  7606. UPB_ASSERT(p->accumulated_len == 0);
  7607. }
  7608. static void accumulate_clear(upb_json_parser *p) {
  7609. p->accumulated = NULL;
  7610. p->accumulated_len = 0;
  7611. }
  7612. /* Used internally by accumulate_append(). */
  7613. static bool accumulate_realloc(upb_json_parser *p, size_t need) {
  7614. void *mem;
  7615. size_t old_size = p->accumulate_buf_size;
  7616. size_t new_size = UPB_MAX(old_size, 128);
  7617. while (new_size < need) {
  7618. new_size = saturating_multiply(new_size, 2);
  7619. }
  7620. mem = upb_arena_realloc(p->arena, p->accumulate_buf, old_size, new_size);
  7621. if (!mem) {
  7622. upb_status_seterrmsg(p->status, "Out of memory allocating buffer.");
  7623. return false;
  7624. }
  7625. p->accumulate_buf = mem;
  7626. p->accumulate_buf_size = new_size;
  7627. return true;
  7628. }
  7629. /* Logically appends the given data to the append buffer.
  7630. * If "can_alias" is true, we will try to avoid actually copying, but the buffer
  7631. * must be valid until the next accumulate_append() call (if any). */
  7632. static bool accumulate_append(upb_json_parser *p, const char *buf, size_t len,
  7633. bool can_alias) {
  7634. size_t need;
  7635. if (!p->accumulated && can_alias) {
  7636. p->accumulated = buf;
  7637. p->accumulated_len = len;
  7638. return true;
  7639. }
  7640. if (!checked_add(p->accumulated_len, len, &need)) {
  7641. upb_status_seterrmsg(p->status, "Integer overflow.");
  7642. return false;
  7643. }
  7644. if (need > p->accumulate_buf_size && !accumulate_realloc(p, need)) {
  7645. return false;
  7646. }
  7647. if (p->accumulated != p->accumulate_buf) {
  7648. memcpy(p->accumulate_buf, p->accumulated, p->accumulated_len);
  7649. p->accumulated = p->accumulate_buf;
  7650. }
  7651. memcpy(p->accumulate_buf + p->accumulated_len, buf, len);
  7652. p->accumulated_len += len;
  7653. return true;
  7654. }
  7655. /* Returns a pointer to the data accumulated since the last accumulate_clear()
  7656. * call, and writes the length to *len. This with point either to the input
  7657. * buffer or a temporary accumulate buffer. */
  7658. static const char *accumulate_getptr(upb_json_parser *p, size_t *len) {
  7659. UPB_ASSERT(p->accumulated);
  7660. *len = p->accumulated_len;
  7661. return p->accumulated;
  7662. }
  7663. /* Mult-part text data ********************************************************/
  7664. /* When we have text data in the input, it can often come in multiple segments.
  7665. * For example, there may be some raw string data followed by an escape
  7666. * sequence. The two segments are processed with different logic. Also buffer
  7667. * seams in the input can cause multiple segments.
  7668. *
  7669. * As we see segments, there are two main cases for how we want to process them:
  7670. *
  7671. * 1. we want to push the captured input directly to string handlers.
  7672. *
  7673. * 2. we need to accumulate all the parts into a contiguous buffer for further
  7674. * processing (field name lookup, string->number conversion, etc). */
  7675. /* This is the set of states for p->multipart_state. */
  7676. enum {
  7677. /* We are not currently processing multipart data. */
  7678. MULTIPART_INACTIVE = 0,
  7679. /* We are processing multipart data by accumulating it into a contiguous
  7680. * buffer. */
  7681. MULTIPART_ACCUMULATE = 1,
  7682. /* We are processing multipart data by pushing each part directly to the
  7683. * current string handlers. */
  7684. MULTIPART_PUSHEAGERLY = 2
  7685. };
  7686. /* Start a multi-part text value where we accumulate the data for processing at
  7687. * the end. */
  7688. static void multipart_startaccum(upb_json_parser *p) {
  7689. assert_accumulate_empty(p);
  7690. UPB_ASSERT(p->multipart_state == MULTIPART_INACTIVE);
  7691. p->multipart_state = MULTIPART_ACCUMULATE;
  7692. }
  7693. /* Start a multi-part text value where we immediately push text data to a string
  7694. * value with the given selector. */
  7695. static void multipart_start(upb_json_parser *p, upb_selector_t sel) {
  7696. assert_accumulate_empty(p);
  7697. UPB_ASSERT(p->multipart_state == MULTIPART_INACTIVE);
  7698. p->multipart_state = MULTIPART_PUSHEAGERLY;
  7699. p->string_selector = sel;
  7700. }
  7701. static bool multipart_text(upb_json_parser *p, const char *buf, size_t len,
  7702. bool can_alias) {
  7703. switch (p->multipart_state) {
  7704. case MULTIPART_INACTIVE:
  7705. upb_status_seterrmsg(
  7706. p->status, "Internal error: unexpected state MULTIPART_INACTIVE");
  7707. return false;
  7708. case MULTIPART_ACCUMULATE:
  7709. if (!accumulate_append(p, buf, len, can_alias)) {
  7710. return false;
  7711. }
  7712. break;
  7713. case MULTIPART_PUSHEAGERLY: {
  7714. const upb_bufhandle *handle = can_alias ? p->handle : NULL;
  7715. upb_sink_putstring(p->top->sink, p->string_selector, buf, len, handle);
  7716. break;
  7717. }
  7718. }
  7719. return true;
  7720. }
  7721. /* Note: this invalidates the accumulate buffer! Call only after reading its
  7722. * contents. */
  7723. static void multipart_end(upb_json_parser *p) {
  7724. UPB_ASSERT(p->multipart_state != MULTIPART_INACTIVE);
  7725. p->multipart_state = MULTIPART_INACTIVE;
  7726. accumulate_clear(p);
  7727. }
  7728. /* Input capture **************************************************************/
  7729. /* Functionality for capturing a region of the input as text. Gracefully
  7730. * handles the case where a buffer seam occurs in the middle of the captured
  7731. * region. */
  7732. static void capture_begin(upb_json_parser *p, const char *ptr) {
  7733. UPB_ASSERT(p->multipart_state != MULTIPART_INACTIVE);
  7734. UPB_ASSERT(p->capture == NULL);
  7735. p->capture = ptr;
  7736. }
  7737. static bool capture_end(upb_json_parser *p, const char *ptr) {
  7738. UPB_ASSERT(p->capture);
  7739. if (multipart_text(p, p->capture, ptr - p->capture, true)) {
  7740. p->capture = NULL;
  7741. return true;
  7742. } else {
  7743. return false;
  7744. }
  7745. }
  7746. /* This is called at the end of each input buffer (ie. when we have hit a
  7747. * buffer seam). If we are in the middle of capturing the input, this
  7748. * processes the unprocessed capture region. */
  7749. static void capture_suspend(upb_json_parser *p, const char **ptr) {
  7750. if (!p->capture) return;
  7751. if (multipart_text(p, p->capture, *ptr - p->capture, false)) {
  7752. /* We use this as a signal that we were in the middle of capturing, and
  7753. * that capturing should resume at the beginning of the next buffer.
  7754. *
  7755. * We can't use *ptr here, because we have no guarantee that this pointer
  7756. * will be valid when we resume (if the underlying memory is freed, then
  7757. * using the pointer at all, even to compare to NULL, is likely undefined
  7758. * behavior). */
  7759. p->capture = &suspend_capture;
  7760. } else {
  7761. /* Need to back up the pointer to the beginning of the capture, since
  7762. * we were not able to actually preserve it. */
  7763. *ptr = p->capture;
  7764. }
  7765. }
  7766. static void capture_resume(upb_json_parser *p, const char *ptr) {
  7767. if (p->capture) {
  7768. UPB_ASSERT(p->capture == &suspend_capture);
  7769. p->capture = ptr;
  7770. }
  7771. }
  7772. /* Callbacks from the parser **************************************************/
  7773. /* These are the functions called directly from the parser itself.
  7774. * We define these in the same order as their declarations in the parser. */
  7775. static char escape_char(char in) {
  7776. switch (in) {
  7777. case 'r': return '\r';
  7778. case 't': return '\t';
  7779. case 'n': return '\n';
  7780. case 'f': return '\f';
  7781. case 'b': return '\b';
  7782. case '/': return '/';
  7783. case '"': return '"';
  7784. case '\\': return '\\';
  7785. default:
  7786. UPB_ASSERT(0);
  7787. return 'x';
  7788. }
  7789. }
  7790. static bool escape(upb_json_parser *p, const char *ptr) {
  7791. char ch = escape_char(*ptr);
  7792. return multipart_text(p, &ch, 1, false);
  7793. }
  7794. static void start_hex(upb_json_parser *p) {
  7795. p->digit = 0;
  7796. }
  7797. static void hexdigit(upb_json_parser *p, const char *ptr) {
  7798. char ch = *ptr;
  7799. p->digit <<= 4;
  7800. if (ch >= '0' && ch <= '9') {
  7801. p->digit += (ch - '0');
  7802. } else if (ch >= 'a' && ch <= 'f') {
  7803. p->digit += ((ch - 'a') + 10);
  7804. } else {
  7805. UPB_ASSERT(ch >= 'A' && ch <= 'F');
  7806. p->digit += ((ch - 'A') + 10);
  7807. }
  7808. }
  7809. static bool end_hex(upb_json_parser *p) {
  7810. uint32_t codepoint = p->digit;
  7811. /* emit the codepoint as UTF-8. */
  7812. char utf8[3]; /* support \u0000 -- \uFFFF -- need only three bytes. */
  7813. int length = 0;
  7814. if (codepoint <= 0x7F) {
  7815. utf8[0] = codepoint;
  7816. length = 1;
  7817. } else if (codepoint <= 0x07FF) {
  7818. utf8[1] = (codepoint & 0x3F) | 0x80;
  7819. codepoint >>= 6;
  7820. utf8[0] = (codepoint & 0x1F) | 0xC0;
  7821. length = 2;
  7822. } else /* codepoint <= 0xFFFF */ {
  7823. utf8[2] = (codepoint & 0x3F) | 0x80;
  7824. codepoint >>= 6;
  7825. utf8[1] = (codepoint & 0x3F) | 0x80;
  7826. codepoint >>= 6;
  7827. utf8[0] = (codepoint & 0x0F) | 0xE0;
  7828. length = 3;
  7829. }
  7830. /* TODO(haberman): Handle high surrogates: if codepoint is a high surrogate
  7831. * we have to wait for the next escape to get the full code point). */
  7832. return multipart_text(p, utf8, length, false);
  7833. }
  7834. static void start_text(upb_json_parser *p, const char *ptr) {
  7835. capture_begin(p, ptr);
  7836. }
  7837. static bool end_text(upb_json_parser *p, const char *ptr) {
  7838. return capture_end(p, ptr);
  7839. }
  7840. static bool start_number(upb_json_parser *p, const char *ptr) {
  7841. if (is_top_level(p)) {
  7842. if (is_number_wrapper_object(p)) {
  7843. start_wrapper_object(p);
  7844. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  7845. start_value_object(p, VALUE_NUMBERVALUE);
  7846. } else {
  7847. return false;
  7848. }
  7849. } else if (does_number_wrapper_start(p)) {
  7850. if (!start_subobject(p)) {
  7851. return false;
  7852. }
  7853. start_wrapper_object(p);
  7854. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  7855. if (!start_subobject(p)) {
  7856. return false;
  7857. }
  7858. start_value_object(p, VALUE_NUMBERVALUE);
  7859. }
  7860. multipart_startaccum(p);
  7861. capture_begin(p, ptr);
  7862. return true;
  7863. }
  7864. static bool parse_number(upb_json_parser *p, bool is_quoted);
  7865. static bool end_number_nontop(upb_json_parser *p, const char *ptr) {
  7866. if (!capture_end(p, ptr)) {
  7867. return false;
  7868. }
  7869. if (p->top->f == NULL) {
  7870. multipart_end(p);
  7871. return true;
  7872. }
  7873. return parse_number(p, false);
  7874. }
  7875. static bool end_number(upb_json_parser *p, const char *ptr) {
  7876. if (!end_number_nontop(p, ptr)) {
  7877. return false;
  7878. }
  7879. if (does_number_wrapper_end(p)) {
  7880. end_wrapper_object(p);
  7881. if (!is_top_level(p)) {
  7882. end_subobject(p);
  7883. }
  7884. return true;
  7885. }
  7886. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  7887. end_value_object(p);
  7888. if (!is_top_level(p)) {
  7889. end_subobject(p);
  7890. }
  7891. return true;
  7892. }
  7893. return true;
  7894. }
  7895. /* |buf| is NULL-terminated. |buf| itself will never include quotes;
  7896. * |is_quoted| tells us whether this text originally appeared inside quotes. */
  7897. static bool parse_number_from_buffer(upb_json_parser *p, const char *buf,
  7898. bool is_quoted) {
  7899. size_t len = strlen(buf);
  7900. const char *bufend = buf + len;
  7901. char *end;
  7902. upb_fieldtype_t type = upb_fielddef_type(p->top->f);
  7903. double val;
  7904. double dummy;
  7905. double inf = UPB_INFINITY;
  7906. errno = 0;
  7907. if (len == 0 || buf[0] == ' ') {
  7908. return false;
  7909. }
  7910. /* For integer types, first try parsing with integer-specific routines.
  7911. * If these succeed, they will be more accurate for int64/uint64 than
  7912. * strtod().
  7913. */
  7914. switch (type) {
  7915. case UPB_TYPE_ENUM:
  7916. case UPB_TYPE_INT32: {
  7917. long val = strtol(buf, &end, 0);
  7918. if (errno == ERANGE || end != bufend) {
  7919. break;
  7920. } else if (val > INT32_MAX || val < INT32_MIN) {
  7921. return false;
  7922. } else {
  7923. upb_sink_putint32(p->top->sink, parser_getsel(p), val);
  7924. return true;
  7925. }
  7926. }
  7927. case UPB_TYPE_UINT32: {
  7928. unsigned long val = strtoul(buf, &end, 0);
  7929. if (end != bufend) {
  7930. break;
  7931. } else if (val > UINT32_MAX || errno == ERANGE) {
  7932. return false;
  7933. } else {
  7934. upb_sink_putuint32(p->top->sink, parser_getsel(p), val);
  7935. return true;
  7936. }
  7937. }
  7938. /* XXX: We can't handle [u]int64 properly on 32-bit machines because
  7939. * strto[u]ll isn't in C89. */
  7940. case UPB_TYPE_INT64: {
  7941. long val = strtol(buf, &end, 0);
  7942. if (errno == ERANGE || end != bufend) {
  7943. break;
  7944. } else {
  7945. upb_sink_putint64(p->top->sink, parser_getsel(p), val);
  7946. return true;
  7947. }
  7948. }
  7949. case UPB_TYPE_UINT64: {
  7950. unsigned long val = strtoul(p->accumulated, &end, 0);
  7951. if (end != bufend) {
  7952. break;
  7953. } else if (errno == ERANGE) {
  7954. return false;
  7955. } else {
  7956. upb_sink_putuint64(p->top->sink, parser_getsel(p), val);
  7957. return true;
  7958. }
  7959. }
  7960. default:
  7961. break;
  7962. }
  7963. if (type != UPB_TYPE_DOUBLE && type != UPB_TYPE_FLOAT && is_quoted) {
  7964. /* Quoted numbers for integer types are not allowed to be in double form. */
  7965. return false;
  7966. }
  7967. if (len == strlen("Infinity") && strcmp(buf, "Infinity") == 0) {
  7968. /* C89 does not have an INFINITY macro. */
  7969. val = inf;
  7970. } else if (len == strlen("-Infinity") && strcmp(buf, "-Infinity") == 0) {
  7971. val = -inf;
  7972. } else {
  7973. val = strtod(buf, &end);
  7974. if (errno == ERANGE || end != bufend) {
  7975. return false;
  7976. }
  7977. }
  7978. switch (type) {
  7979. #define CASE(capitaltype, smalltype, ctype, min, max) \
  7980. case UPB_TYPE_ ## capitaltype: { \
  7981. if (modf(val, &dummy) != 0 || val > max || val < min) { \
  7982. return false; \
  7983. } else { \
  7984. upb_sink_put ## smalltype(p->top->sink, parser_getsel(p), \
  7985. (ctype)val); \
  7986. return true; \
  7987. } \
  7988. break; \
  7989. }
  7990. case UPB_TYPE_ENUM:
  7991. CASE(INT32, int32, int32_t, INT32_MIN, INT32_MAX);
  7992. CASE(INT64, int64, int64_t, INT64_MIN, INT64_MAX);
  7993. CASE(UINT32, uint32, uint32_t, 0, UINT32_MAX);
  7994. CASE(UINT64, uint64, uint64_t, 0, UINT64_MAX);
  7995. #undef CASE
  7996. case UPB_TYPE_DOUBLE:
  7997. upb_sink_putdouble(p->top->sink, parser_getsel(p), val);
  7998. return true;
  7999. case UPB_TYPE_FLOAT:
  8000. if ((val > FLT_MAX || val < -FLT_MAX) && val != inf && val != -inf) {
  8001. return false;
  8002. } else {
  8003. upb_sink_putfloat(p->top->sink, parser_getsel(p), val);
  8004. return true;
  8005. }
  8006. default:
  8007. return false;
  8008. }
  8009. }
  8010. static bool parse_number(upb_json_parser *p, bool is_quoted) {
  8011. size_t len;
  8012. const char *buf;
  8013. /* strtol() and friends unfortunately do not support specifying the length of
  8014. * the input string, so we need to force a copy into a NULL-terminated buffer. */
  8015. if (!multipart_text(p, "\0", 1, false)) {
  8016. return false;
  8017. }
  8018. buf = accumulate_getptr(p, &len);
  8019. if (parse_number_from_buffer(p, buf, is_quoted)) {
  8020. multipart_end(p);
  8021. return true;
  8022. } else {
  8023. upb_status_seterrf(p->status, "error parsing number: %s", buf);
  8024. multipart_end(p);
  8025. return false;
  8026. }
  8027. }
  8028. static bool parser_putbool(upb_json_parser *p, bool val) {
  8029. bool ok;
  8030. if (p->top->f == NULL) {
  8031. return true;
  8032. }
  8033. if (upb_fielddef_type(p->top->f) != UPB_TYPE_BOOL) {
  8034. upb_status_seterrf(p->status,
  8035. "Boolean value specified for non-bool field: %s",
  8036. upb_fielddef_name(p->top->f));
  8037. return false;
  8038. }
  8039. ok = upb_sink_putbool(p->top->sink, parser_getsel(p), val);
  8040. UPB_ASSERT(ok);
  8041. return true;
  8042. }
  8043. static bool end_bool(upb_json_parser *p, bool val) {
  8044. if (is_top_level(p)) {
  8045. if (is_wellknown_msg(p, UPB_WELLKNOWN_BOOLVALUE)) {
  8046. start_wrapper_object(p);
  8047. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8048. start_value_object(p, VALUE_BOOLVALUE);
  8049. } else {
  8050. return false;
  8051. }
  8052. } else if (is_wellknown_field(p, UPB_WELLKNOWN_BOOLVALUE)) {
  8053. if (!start_subobject(p)) {
  8054. return false;
  8055. }
  8056. start_wrapper_object(p);
  8057. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  8058. if (!start_subobject(p)) {
  8059. return false;
  8060. }
  8061. start_value_object(p, VALUE_BOOLVALUE);
  8062. }
  8063. if (p->top->is_unknown_field) {
  8064. return true;
  8065. }
  8066. if (!parser_putbool(p, val)) {
  8067. return false;
  8068. }
  8069. if (is_wellknown_msg(p, UPB_WELLKNOWN_BOOLVALUE)) {
  8070. end_wrapper_object(p);
  8071. if (!is_top_level(p)) {
  8072. end_subobject(p);
  8073. }
  8074. return true;
  8075. }
  8076. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8077. end_value_object(p);
  8078. if (!is_top_level(p)) {
  8079. end_subobject(p);
  8080. }
  8081. return true;
  8082. }
  8083. return true;
  8084. }
  8085. static bool end_null(upb_json_parser *p) {
  8086. const char *zero_ptr = "0";
  8087. if (is_top_level(p)) {
  8088. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8089. start_value_object(p, VALUE_NULLVALUE);
  8090. } else {
  8091. return true;
  8092. }
  8093. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  8094. if (!start_subobject(p)) {
  8095. return false;
  8096. }
  8097. start_value_object(p, VALUE_NULLVALUE);
  8098. } else {
  8099. return true;
  8100. }
  8101. /* Fill null_value field. */
  8102. multipart_startaccum(p);
  8103. capture_begin(p, zero_ptr);
  8104. capture_end(p, zero_ptr + 1);
  8105. parse_number(p, false);
  8106. end_value_object(p);
  8107. if (!is_top_level(p)) {
  8108. end_subobject(p);
  8109. }
  8110. return true;
  8111. }
  8112. static bool start_any_stringval(upb_json_parser *p) {
  8113. multipart_startaccum(p);
  8114. return true;
  8115. }
  8116. static bool start_stringval(upb_json_parser *p) {
  8117. if (is_top_level(p)) {
  8118. if (is_string_wrapper_object(p) ||
  8119. is_number_wrapper_object(p)) {
  8120. start_wrapper_object(p);
  8121. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_FIELDMASK)) {
  8122. start_fieldmask_object(p);
  8123. return true;
  8124. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_TIMESTAMP) ||
  8125. is_wellknown_msg(p, UPB_WELLKNOWN_DURATION)) {
  8126. start_object(p);
  8127. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8128. start_value_object(p, VALUE_STRINGVALUE);
  8129. } else {
  8130. return false;
  8131. }
  8132. } else if (does_string_wrapper_start(p) ||
  8133. does_number_wrapper_start(p)) {
  8134. if (!start_subobject(p)) {
  8135. return false;
  8136. }
  8137. start_wrapper_object(p);
  8138. } else if (does_fieldmask_start(p)) {
  8139. if (!start_subobject(p)) {
  8140. return false;
  8141. }
  8142. start_fieldmask_object(p);
  8143. return true;
  8144. } else if (is_wellknown_field(p, UPB_WELLKNOWN_TIMESTAMP) ||
  8145. is_wellknown_field(p, UPB_WELLKNOWN_DURATION)) {
  8146. if (!start_subobject(p)) {
  8147. return false;
  8148. }
  8149. start_object(p);
  8150. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  8151. if (!start_subobject(p)) {
  8152. return false;
  8153. }
  8154. start_value_object(p, VALUE_STRINGVALUE);
  8155. }
  8156. if (p->top->f == NULL) {
  8157. multipart_startaccum(p);
  8158. return true;
  8159. }
  8160. if (p->top->is_any) {
  8161. return start_any_stringval(p);
  8162. }
  8163. if (upb_fielddef_isstring(p->top->f)) {
  8164. upb_jsonparser_frame *inner;
  8165. upb_selector_t sel;
  8166. if (!check_stack(p)) return false;
  8167. /* Start a new parser frame: parser frames correspond one-to-one with
  8168. * handler frames, and string events occur in a sub-frame. */
  8169. inner = start_jsonparser_frame(p);
  8170. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  8171. upb_sink_startstr(p->top->sink, sel, 0, &inner->sink);
  8172. inner->m = p->top->m;
  8173. inner->f = p->top->f;
  8174. p->top = inner;
  8175. if (upb_fielddef_type(p->top->f) == UPB_TYPE_STRING) {
  8176. /* For STRING fields we push data directly to the handlers as it is
  8177. * parsed. We don't do this yet for BYTES fields, because our base64
  8178. * decoder is not streaming.
  8179. *
  8180. * TODO(haberman): make base64 decoding streaming also. */
  8181. multipart_start(p, getsel_for_handlertype(p, UPB_HANDLER_STRING));
  8182. return true;
  8183. } else {
  8184. multipart_startaccum(p);
  8185. return true;
  8186. }
  8187. } else if (upb_fielddef_type(p->top->f) != UPB_TYPE_BOOL &&
  8188. upb_fielddef_type(p->top->f) != UPB_TYPE_MESSAGE) {
  8189. /* No need to push a frame -- numeric values in quotes remain in the
  8190. * current parser frame. These values must accumulate so we can convert
  8191. * them all at once at the end. */
  8192. multipart_startaccum(p);
  8193. return true;
  8194. } else {
  8195. upb_status_seterrf(p->status,
  8196. "String specified for bool or submessage field: %s",
  8197. upb_fielddef_name(p->top->f));
  8198. return false;
  8199. }
  8200. }
  8201. static bool end_any_stringval(upb_json_parser *p) {
  8202. size_t len;
  8203. const char *buf = accumulate_getptr(p, &len);
  8204. /* Set type_url */
  8205. upb_selector_t sel;
  8206. upb_jsonparser_frame *inner;
  8207. if (!check_stack(p)) return false;
  8208. inner = p->top + 1;
  8209. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  8210. upb_sink_startstr(p->top->sink, sel, 0, &inner->sink);
  8211. sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
  8212. upb_sink_putstring(inner->sink, sel, buf, len, NULL);
  8213. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  8214. upb_sink_endstr(inner->sink, sel);
  8215. multipart_end(p);
  8216. /* Resolve type url */
  8217. if (strncmp(buf, "type.googleapis.com/", 20) == 0 && len > 20) {
  8218. const upb_msgdef *payload_type = NULL;
  8219. buf += 20;
  8220. len -= 20;
  8221. payload_type = upb_symtab_lookupmsg2(p->symtab, buf, len);
  8222. if (payload_type == NULL) {
  8223. upb_status_seterrf(
  8224. p->status, "Cannot find packed type: %.*s\n", (int)len, buf);
  8225. return false;
  8226. }
  8227. json_parser_any_frame_set_payload_type(p, p->top->any_frame, payload_type);
  8228. return true;
  8229. } else {
  8230. upb_status_seterrf(
  8231. p->status, "Invalid type url: %.*s\n", (int)len, buf);
  8232. return false;
  8233. }
  8234. }
  8235. static bool end_stringval_nontop(upb_json_parser *p) {
  8236. bool ok = true;
  8237. if (is_wellknown_msg(p, UPB_WELLKNOWN_TIMESTAMP) ||
  8238. is_wellknown_msg(p, UPB_WELLKNOWN_DURATION)) {
  8239. multipart_end(p);
  8240. return true;
  8241. }
  8242. if (p->top->f == NULL) {
  8243. multipart_end(p);
  8244. return true;
  8245. }
  8246. if (p->top->is_any) {
  8247. return end_any_stringval(p);
  8248. }
  8249. switch (upb_fielddef_type(p->top->f)) {
  8250. case UPB_TYPE_BYTES:
  8251. if (!base64_push(p, getsel_for_handlertype(p, UPB_HANDLER_STRING),
  8252. p->accumulated, p->accumulated_len)) {
  8253. return false;
  8254. }
  8255. /* Fall through. */
  8256. case UPB_TYPE_STRING: {
  8257. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  8258. upb_sink_endstr(p->top->sink, sel);
  8259. p->top--;
  8260. break;
  8261. }
  8262. case UPB_TYPE_ENUM: {
  8263. /* Resolve enum symbolic name to integer value. */
  8264. const upb_enumdef *enumdef = upb_fielddef_enumsubdef(p->top->f);
  8265. size_t len;
  8266. const char *buf = accumulate_getptr(p, &len);
  8267. int32_t int_val = 0;
  8268. ok = upb_enumdef_ntoi(enumdef, buf, len, &int_val);
  8269. if (ok) {
  8270. upb_selector_t sel = parser_getsel(p);
  8271. upb_sink_putint32(p->top->sink, sel, int_val);
  8272. } else {
  8273. upb_status_seterrf(p->status, "Enum value unknown: '%.*s'", len, buf);
  8274. }
  8275. break;
  8276. }
  8277. case UPB_TYPE_INT32:
  8278. case UPB_TYPE_INT64:
  8279. case UPB_TYPE_UINT32:
  8280. case UPB_TYPE_UINT64:
  8281. case UPB_TYPE_DOUBLE:
  8282. case UPB_TYPE_FLOAT:
  8283. ok = parse_number(p, true);
  8284. break;
  8285. default:
  8286. UPB_ASSERT(false);
  8287. upb_status_seterrmsg(p->status, "Internal error in JSON decoder");
  8288. ok = false;
  8289. break;
  8290. }
  8291. multipart_end(p);
  8292. return ok;
  8293. }
  8294. static bool end_stringval(upb_json_parser *p) {
  8295. /* FieldMask's stringvals have been ended when handling them. Only need to
  8296. * close FieldMask here.*/
  8297. if (does_fieldmask_end(p)) {
  8298. end_fieldmask_object(p);
  8299. if (!is_top_level(p)) {
  8300. end_subobject(p);
  8301. }
  8302. return true;
  8303. }
  8304. if (!end_stringval_nontop(p)) {
  8305. return false;
  8306. }
  8307. if (does_string_wrapper_end(p) ||
  8308. does_number_wrapper_end(p)) {
  8309. end_wrapper_object(p);
  8310. if (!is_top_level(p)) {
  8311. end_subobject(p);
  8312. }
  8313. return true;
  8314. }
  8315. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8316. end_value_object(p);
  8317. if (!is_top_level(p)) {
  8318. end_subobject(p);
  8319. }
  8320. return true;
  8321. }
  8322. if (is_wellknown_msg(p, UPB_WELLKNOWN_TIMESTAMP) ||
  8323. is_wellknown_msg(p, UPB_WELLKNOWN_DURATION) ||
  8324. is_wellknown_msg(p, UPB_WELLKNOWN_FIELDMASK)) {
  8325. end_object(p);
  8326. if (!is_top_level(p)) {
  8327. end_subobject(p);
  8328. }
  8329. return true;
  8330. }
  8331. return true;
  8332. }
  8333. static void start_duration_base(upb_json_parser *p, const char *ptr) {
  8334. capture_begin(p, ptr);
  8335. }
  8336. static bool end_duration_base(upb_json_parser *p, const char *ptr) {
  8337. size_t len;
  8338. const char *buf;
  8339. char seconds_buf[14];
  8340. char nanos_buf[12];
  8341. char *end;
  8342. int64_t seconds = 0;
  8343. int32_t nanos = 0;
  8344. double val = 0.0;
  8345. const char *seconds_membername = "seconds";
  8346. const char *nanos_membername = "nanos";
  8347. size_t fraction_start;
  8348. if (!capture_end(p, ptr)) {
  8349. return false;
  8350. }
  8351. buf = accumulate_getptr(p, &len);
  8352. memset(seconds_buf, 0, 14);
  8353. memset(nanos_buf, 0, 12);
  8354. /* Find out base end. The maximus duration is 315576000000, which cannot be
  8355. * represented by double without losing precision. Thus, we need to handle
  8356. * fraction and base separately. */
  8357. for (fraction_start = 0; fraction_start < len && buf[fraction_start] != '.';
  8358. fraction_start++);
  8359. /* Parse base */
  8360. memcpy(seconds_buf, buf, fraction_start);
  8361. seconds = strtol(seconds_buf, &end, 10);
  8362. if (errno == ERANGE || end != seconds_buf + fraction_start) {
  8363. upb_status_seterrf(p->status, "error parsing duration: %s",
  8364. seconds_buf);
  8365. return false;
  8366. }
  8367. if (seconds > 315576000000) {
  8368. upb_status_seterrf(p->status, "error parsing duration: "
  8369. "maximum acceptable value is "
  8370. "315576000000");
  8371. return false;
  8372. }
  8373. if (seconds < -315576000000) {
  8374. upb_status_seterrf(p->status, "error parsing duration: "
  8375. "minimum acceptable value is "
  8376. "-315576000000");
  8377. return false;
  8378. }
  8379. /* Parse fraction */
  8380. nanos_buf[0] = '0';
  8381. memcpy(nanos_buf + 1, buf + fraction_start, len - fraction_start);
  8382. val = strtod(nanos_buf, &end);
  8383. if (errno == ERANGE || end != nanos_buf + len - fraction_start + 1) {
  8384. upb_status_seterrf(p->status, "error parsing duration: %s",
  8385. nanos_buf);
  8386. return false;
  8387. }
  8388. nanos = val * 1000000000;
  8389. if (seconds < 0) nanos = -nanos;
  8390. /* Clean up buffer */
  8391. multipart_end(p);
  8392. /* Set seconds */
  8393. start_member(p);
  8394. capture_begin(p, seconds_membername);
  8395. capture_end(p, seconds_membername + 7);
  8396. end_membername(p);
  8397. upb_sink_putint64(p->top->sink, parser_getsel(p), seconds);
  8398. end_member(p);
  8399. /* Set nanos */
  8400. start_member(p);
  8401. capture_begin(p, nanos_membername);
  8402. capture_end(p, nanos_membername + 5);
  8403. end_membername(p);
  8404. upb_sink_putint32(p->top->sink, parser_getsel(p), nanos);
  8405. end_member(p);
  8406. /* Continue previous arena */
  8407. multipart_startaccum(p);
  8408. return true;
  8409. }
  8410. static int parse_timestamp_number(upb_json_parser *p) {
  8411. size_t len;
  8412. const char *buf;
  8413. int val;
  8414. /* atoi() and friends unfortunately do not support specifying the length of
  8415. * the input string, so we need to force a copy into a NULL-terminated buffer. */
  8416. multipart_text(p, "\0", 1, false);
  8417. buf = accumulate_getptr(p, &len);
  8418. val = atoi(buf);
  8419. multipart_end(p);
  8420. multipart_startaccum(p);
  8421. return val;
  8422. }
  8423. static void start_year(upb_json_parser *p, const char *ptr) {
  8424. capture_begin(p, ptr);
  8425. }
  8426. static bool end_year(upb_json_parser *p, const char *ptr) {
  8427. if (!capture_end(p, ptr)) {
  8428. return false;
  8429. }
  8430. p->tm.tm_year = parse_timestamp_number(p) - 1900;
  8431. return true;
  8432. }
  8433. static void start_month(upb_json_parser *p, const char *ptr) {
  8434. capture_begin(p, ptr);
  8435. }
  8436. static bool end_month(upb_json_parser *p, const char *ptr) {
  8437. if (!capture_end(p, ptr)) {
  8438. return false;
  8439. }
  8440. p->tm.tm_mon = parse_timestamp_number(p) - 1;
  8441. return true;
  8442. }
  8443. static void start_day(upb_json_parser *p, const char *ptr) {
  8444. capture_begin(p, ptr);
  8445. }
  8446. static bool end_day(upb_json_parser *p, const char *ptr) {
  8447. if (!capture_end(p, ptr)) {
  8448. return false;
  8449. }
  8450. p->tm.tm_mday = parse_timestamp_number(p);
  8451. return true;
  8452. }
  8453. static void start_hour(upb_json_parser *p, const char *ptr) {
  8454. capture_begin(p, ptr);
  8455. }
  8456. static bool end_hour(upb_json_parser *p, const char *ptr) {
  8457. if (!capture_end(p, ptr)) {
  8458. return false;
  8459. }
  8460. p->tm.tm_hour = parse_timestamp_number(p);
  8461. return true;
  8462. }
  8463. static void start_minute(upb_json_parser *p, const char *ptr) {
  8464. capture_begin(p, ptr);
  8465. }
  8466. static bool end_minute(upb_json_parser *p, const char *ptr) {
  8467. if (!capture_end(p, ptr)) {
  8468. return false;
  8469. }
  8470. p->tm.tm_min = parse_timestamp_number(p);
  8471. return true;
  8472. }
  8473. static void start_second(upb_json_parser *p, const char *ptr) {
  8474. capture_begin(p, ptr);
  8475. }
  8476. static bool end_second(upb_json_parser *p, const char *ptr) {
  8477. if (!capture_end(p, ptr)) {
  8478. return false;
  8479. }
  8480. p->tm.tm_sec = parse_timestamp_number(p);
  8481. return true;
  8482. }
  8483. static void start_timestamp_base(upb_json_parser *p) {
  8484. memset(&p->tm, 0, sizeof(struct tm));
  8485. }
  8486. static void start_timestamp_fraction(upb_json_parser *p, const char *ptr) {
  8487. capture_begin(p, ptr);
  8488. }
  8489. static bool end_timestamp_fraction(upb_json_parser *p, const char *ptr) {
  8490. size_t len;
  8491. const char *buf;
  8492. char nanos_buf[12];
  8493. char *end;
  8494. double val = 0.0;
  8495. int32_t nanos;
  8496. const char *nanos_membername = "nanos";
  8497. memset(nanos_buf, 0, 12);
  8498. if (!capture_end(p, ptr)) {
  8499. return false;
  8500. }
  8501. buf = accumulate_getptr(p, &len);
  8502. if (len > 10) {
  8503. upb_status_seterrf(p->status,
  8504. "error parsing timestamp: at most 9-digit fraction.");
  8505. return false;
  8506. }
  8507. /* Parse nanos */
  8508. nanos_buf[0] = '0';
  8509. memcpy(nanos_buf + 1, buf, len);
  8510. val = strtod(nanos_buf, &end);
  8511. if (errno == ERANGE || end != nanos_buf + len + 1) {
  8512. upb_status_seterrf(p->status, "error parsing timestamp nanos: %s",
  8513. nanos_buf);
  8514. return false;
  8515. }
  8516. nanos = val * 1000000000;
  8517. /* Clean up previous environment */
  8518. multipart_end(p);
  8519. /* Set nanos */
  8520. start_member(p);
  8521. capture_begin(p, nanos_membername);
  8522. capture_end(p, nanos_membername + 5);
  8523. end_membername(p);
  8524. upb_sink_putint32(p->top->sink, parser_getsel(p), nanos);
  8525. end_member(p);
  8526. /* Continue previous environment */
  8527. multipart_startaccum(p);
  8528. return true;
  8529. }
  8530. static void start_timestamp_zone(upb_json_parser *p, const char *ptr) {
  8531. capture_begin(p, ptr);
  8532. }
  8533. /* epoch_days(1970, 1, 1) == 1970-01-01 == 0. */
  8534. static int epoch_days(int year, int month, int day) {
  8535. static const uint16_t month_yday[12] = {0, 31, 59, 90, 120, 151,
  8536. 181, 212, 243, 273, 304, 334};
  8537. int febs_since_0 = month > 2 ? year + 1 : year;
  8538. int leap_days_since_0 = div_round_up(febs_since_0, 4) -
  8539. div_round_up(febs_since_0, 100) +
  8540. div_round_up(febs_since_0, 400);
  8541. int days_since_0 =
  8542. 365 * year + month_yday[month - 1] + (day - 1) + leap_days_since_0;
  8543. /* Convert from 0-epoch (0001-01-01 BC) to Unix Epoch (1970-01-01 AD).
  8544. * Since the "BC" system does not have a year zero, 1 BC == year zero. */
  8545. return days_since_0 - 719528;
  8546. }
  8547. static int64_t upb_timegm(const struct tm *tp) {
  8548. int64_t ret = epoch_days(tp->tm_year + 1900, tp->tm_mon + 1, tp->tm_mday);
  8549. ret = (ret * 24) + tp->tm_hour;
  8550. ret = (ret * 60) + tp->tm_min;
  8551. ret = (ret * 60) + tp->tm_sec;
  8552. return ret;
  8553. }
  8554. static bool end_timestamp_zone(upb_json_parser *p, const char *ptr) {
  8555. size_t len;
  8556. const char *buf;
  8557. int hours;
  8558. int64_t seconds;
  8559. const char *seconds_membername = "seconds";
  8560. if (!capture_end(p, ptr)) {
  8561. return false;
  8562. }
  8563. buf = accumulate_getptr(p, &len);
  8564. if (buf[0] != 'Z') {
  8565. if (sscanf(buf + 1, "%2d:00", &hours) != 1) {
  8566. upb_status_seterrf(p->status, "error parsing timestamp offset");
  8567. return false;
  8568. }
  8569. if (buf[0] == '+') {
  8570. hours = -hours;
  8571. }
  8572. p->tm.tm_hour += hours;
  8573. }
  8574. /* Normalize tm */
  8575. seconds = upb_timegm(&p->tm);
  8576. /* Check timestamp boundary */
  8577. if (seconds < -62135596800) {
  8578. upb_status_seterrf(p->status, "error parsing timestamp: "
  8579. "minimum acceptable value is "
  8580. "0001-01-01T00:00:00Z");
  8581. return false;
  8582. }
  8583. /* Clean up previous environment */
  8584. multipart_end(p);
  8585. /* Set seconds */
  8586. start_member(p);
  8587. capture_begin(p, seconds_membername);
  8588. capture_end(p, seconds_membername + 7);
  8589. end_membername(p);
  8590. upb_sink_putint64(p->top->sink, parser_getsel(p), seconds);
  8591. end_member(p);
  8592. /* Continue previous environment */
  8593. multipart_startaccum(p);
  8594. return true;
  8595. }
  8596. static void start_fieldmask_path_text(upb_json_parser *p, const char *ptr) {
  8597. capture_begin(p, ptr);
  8598. }
  8599. static bool end_fieldmask_path_text(upb_json_parser *p, const char *ptr) {
  8600. return capture_end(p, ptr);
  8601. }
  8602. static bool start_fieldmask_path(upb_json_parser *p) {
  8603. upb_jsonparser_frame *inner;
  8604. upb_selector_t sel;
  8605. if (!check_stack(p)) return false;
  8606. /* Start a new parser frame: parser frames correspond one-to-one with
  8607. * handler frames, and string events occur in a sub-frame. */
  8608. inner = start_jsonparser_frame(p);
  8609. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  8610. upb_sink_startstr(p->top->sink, sel, 0, &inner->sink);
  8611. inner->m = p->top->m;
  8612. inner->f = p->top->f;
  8613. p->top = inner;
  8614. multipart_startaccum(p);
  8615. return true;
  8616. }
  8617. static bool lower_camel_push(
  8618. upb_json_parser *p, upb_selector_t sel, const char *ptr, size_t len) {
  8619. const char *limit = ptr + len;
  8620. bool first = true;
  8621. for (;ptr < limit; ptr++) {
  8622. if (*ptr >= 'A' && *ptr <= 'Z' && !first) {
  8623. char lower = tolower(*ptr);
  8624. upb_sink_putstring(p->top->sink, sel, "_", 1, NULL);
  8625. upb_sink_putstring(p->top->sink, sel, &lower, 1, NULL);
  8626. } else {
  8627. upb_sink_putstring(p->top->sink, sel, ptr, 1, NULL);
  8628. }
  8629. first = false;
  8630. }
  8631. return true;
  8632. }
  8633. static bool end_fieldmask_path(upb_json_parser *p) {
  8634. upb_selector_t sel;
  8635. if (!lower_camel_push(
  8636. p, getsel_for_handlertype(p, UPB_HANDLER_STRING),
  8637. p->accumulated, p->accumulated_len)) {
  8638. return false;
  8639. }
  8640. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  8641. upb_sink_endstr(p->top->sink, sel);
  8642. p->top--;
  8643. multipart_end(p);
  8644. return true;
  8645. }
  8646. static void start_member(upb_json_parser *p) {
  8647. UPB_ASSERT(!p->top->f);
  8648. multipart_startaccum(p);
  8649. }
  8650. /* Helper: invoked during parse_mapentry() to emit the mapentry message's key
  8651. * field based on the current contents of the accumulate buffer. */
  8652. static bool parse_mapentry_key(upb_json_parser *p) {
  8653. size_t len;
  8654. const char *buf = accumulate_getptr(p, &len);
  8655. /* Emit the key field. We do a bit of ad-hoc parsing here because the
  8656. * parser state machine has already decided that this is a string field
  8657. * name, and we are reinterpreting it as some arbitrary key type. In
  8658. * particular, integer and bool keys are quoted, so we need to parse the
  8659. * quoted string contents here. */
  8660. p->top->f = upb_msgdef_itof(p->top->m, UPB_MAPENTRY_KEY);
  8661. if (p->top->f == NULL) {
  8662. upb_status_seterrmsg(p->status, "mapentry message has no key");
  8663. return false;
  8664. }
  8665. switch (upb_fielddef_type(p->top->f)) {
  8666. case UPB_TYPE_INT32:
  8667. case UPB_TYPE_INT64:
  8668. case UPB_TYPE_UINT32:
  8669. case UPB_TYPE_UINT64:
  8670. /* Invoke end_number. The accum buffer has the number's text already. */
  8671. if (!parse_number(p, true)) {
  8672. return false;
  8673. }
  8674. break;
  8675. case UPB_TYPE_BOOL:
  8676. if (len == 4 && !strncmp(buf, "true", 4)) {
  8677. if (!parser_putbool(p, true)) {
  8678. return false;
  8679. }
  8680. } else if (len == 5 && !strncmp(buf, "false", 5)) {
  8681. if (!parser_putbool(p, false)) {
  8682. return false;
  8683. }
  8684. } else {
  8685. upb_status_seterrmsg(p->status,
  8686. "Map bool key not 'true' or 'false'");
  8687. return false;
  8688. }
  8689. multipart_end(p);
  8690. break;
  8691. case UPB_TYPE_STRING:
  8692. case UPB_TYPE_BYTES: {
  8693. upb_sink subsink;
  8694. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  8695. upb_sink_startstr(p->top->sink, sel, len, &subsink);
  8696. sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
  8697. upb_sink_putstring(subsink, sel, buf, len, NULL);
  8698. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  8699. upb_sink_endstr(subsink, sel);
  8700. multipart_end(p);
  8701. break;
  8702. }
  8703. default:
  8704. upb_status_seterrmsg(p->status, "Invalid field type for map key");
  8705. return false;
  8706. }
  8707. return true;
  8708. }
  8709. /* Helper: emit one map entry (as a submessage in the map field sequence). This
  8710. * is invoked from end_membername(), at the end of the map entry's key string,
  8711. * with the map key in the accumulate buffer. It parses the key from that
  8712. * buffer, emits the handler calls to start the mapentry submessage (setting up
  8713. * its subframe in the process), and sets up state in the subframe so that the
  8714. * value parser (invoked next) will emit the mapentry's value field and then
  8715. * end the mapentry message. */
  8716. static bool handle_mapentry(upb_json_parser *p) {
  8717. const upb_fielddef *mapfield;
  8718. const upb_msgdef *mapentrymsg;
  8719. upb_jsonparser_frame *inner;
  8720. upb_selector_t sel;
  8721. /* Map entry: p->top->sink is the seq frame, so we need to start a frame
  8722. * for the mapentry itself, and then set |f| in that frame so that the map
  8723. * value field is parsed, and also set a flag to end the frame after the
  8724. * map-entry value is parsed. */
  8725. if (!check_stack(p)) return false;
  8726. mapfield = p->top->mapfield;
  8727. mapentrymsg = upb_fielddef_msgsubdef(mapfield);
  8728. inner = start_jsonparser_frame(p);
  8729. p->top->f = mapfield;
  8730. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
  8731. upb_sink_startsubmsg(p->top->sink, sel, &inner->sink);
  8732. inner->m = mapentrymsg;
  8733. inner->mapfield = mapfield;
  8734. /* Don't set this to true *yet* -- we reuse parsing handlers below to push
  8735. * the key field value to the sink, and these handlers will pop the frame
  8736. * if they see is_mapentry (when invoked by the parser state machine, they
  8737. * would have just seen the map-entry value, not key). */
  8738. inner->is_mapentry = false;
  8739. p->top = inner;
  8740. /* send STARTMSG in submsg frame. */
  8741. upb_sink_startmsg(p->top->sink);
  8742. parse_mapentry_key(p);
  8743. /* Set up the value field to receive the map-entry value. */
  8744. p->top->f = upb_msgdef_itof(p->top->m, UPB_MAPENTRY_VALUE);
  8745. p->top->is_mapentry = true; /* set up to pop frame after value is parsed. */
  8746. p->top->mapfield = mapfield;
  8747. if (p->top->f == NULL) {
  8748. upb_status_seterrmsg(p->status, "mapentry message has no value");
  8749. return false;
  8750. }
  8751. return true;
  8752. }
  8753. static bool end_membername(upb_json_parser *p) {
  8754. UPB_ASSERT(!p->top->f);
  8755. if (!p->top->m) {
  8756. p->top->is_unknown_field = true;
  8757. multipart_end(p);
  8758. return true;
  8759. }
  8760. if (p->top->is_any) {
  8761. return end_any_membername(p);
  8762. } else if (p->top->is_map) {
  8763. return handle_mapentry(p);
  8764. } else {
  8765. size_t len;
  8766. const char *buf = accumulate_getptr(p, &len);
  8767. upb_value v;
  8768. if (upb_strtable_lookup2(p->top->name_table, buf, len, &v)) {
  8769. p->top->f = upb_value_getconstptr(v);
  8770. multipart_end(p);
  8771. return true;
  8772. } else if (p->ignore_json_unknown) {
  8773. p->top->is_unknown_field = true;
  8774. multipart_end(p);
  8775. return true;
  8776. } else {
  8777. upb_status_seterrf(p->status, "No such field: %.*s\n", (int)len, buf);
  8778. return false;
  8779. }
  8780. }
  8781. }
  8782. static bool end_any_membername(upb_json_parser *p) {
  8783. size_t len;
  8784. const char *buf = accumulate_getptr(p, &len);
  8785. upb_value v;
  8786. if (len == 5 && strncmp(buf, "@type", len) == 0) {
  8787. upb_strtable_lookup2(p->top->name_table, "type_url", 8, &v);
  8788. p->top->f = upb_value_getconstptr(v);
  8789. multipart_end(p);
  8790. return true;
  8791. } else {
  8792. p->top->is_unknown_field = true;
  8793. multipart_end(p);
  8794. return true;
  8795. }
  8796. }
  8797. static void end_member(upb_json_parser *p) {
  8798. /* If we just parsed a map-entry value, end that frame too. */
  8799. if (p->top->is_mapentry) {
  8800. upb_selector_t sel;
  8801. bool ok;
  8802. const upb_fielddef *mapfield;
  8803. UPB_ASSERT(p->top > p->stack);
  8804. /* send ENDMSG on submsg. */
  8805. upb_sink_endmsg(p->top->sink, p->status);
  8806. mapfield = p->top->mapfield;
  8807. /* send ENDSUBMSG in repeated-field-of-mapentries frame. */
  8808. p->top--;
  8809. ok = upb_handlers_getselector(mapfield, UPB_HANDLER_ENDSUBMSG, &sel);
  8810. UPB_ASSERT(ok);
  8811. upb_sink_endsubmsg(p->top->sink, sel);
  8812. }
  8813. p->top->f = NULL;
  8814. p->top->is_unknown_field = false;
  8815. }
  8816. static void start_any_member(upb_json_parser *p, const char *ptr) {
  8817. start_member(p);
  8818. json_parser_any_frame_set_after_type_url_start_once(p->top->any_frame, ptr);
  8819. }
  8820. static void end_any_member(upb_json_parser *p, const char *ptr) {
  8821. json_parser_any_frame_set_before_type_url_end(p->top->any_frame, ptr);
  8822. end_member(p);
  8823. }
  8824. static bool start_subobject(upb_json_parser *p) {
  8825. if (p->top->is_unknown_field) {
  8826. if (!check_stack(p)) return false;
  8827. p->top = start_jsonparser_frame(p);
  8828. return true;
  8829. }
  8830. if (upb_fielddef_ismap(p->top->f)) {
  8831. upb_jsonparser_frame *inner;
  8832. upb_selector_t sel;
  8833. /* Beginning of a map. Start a new parser frame in a repeated-field
  8834. * context. */
  8835. if (!check_stack(p)) return false;
  8836. inner = start_jsonparser_frame(p);
  8837. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
  8838. upb_sink_startseq(p->top->sink, sel, &inner->sink);
  8839. inner->m = upb_fielddef_msgsubdef(p->top->f);
  8840. inner->mapfield = p->top->f;
  8841. inner->is_map = true;
  8842. p->top = inner;
  8843. return true;
  8844. } else if (upb_fielddef_issubmsg(p->top->f)) {
  8845. upb_jsonparser_frame *inner;
  8846. upb_selector_t sel;
  8847. /* Beginning of a subobject. Start a new parser frame in the submsg
  8848. * context. */
  8849. if (!check_stack(p)) return false;
  8850. inner = start_jsonparser_frame(p);
  8851. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
  8852. upb_sink_startsubmsg(p->top->sink, sel, &inner->sink);
  8853. inner->m = upb_fielddef_msgsubdef(p->top->f);
  8854. set_name_table(p, inner);
  8855. p->top = inner;
  8856. if (is_wellknown_msg(p, UPB_WELLKNOWN_ANY)) {
  8857. p->top->is_any = true;
  8858. p->top->any_frame = json_parser_any_frame_new(p);
  8859. } else {
  8860. p->top->is_any = false;
  8861. p->top->any_frame = NULL;
  8862. }
  8863. return true;
  8864. } else {
  8865. upb_status_seterrf(p->status,
  8866. "Object specified for non-message/group field: %s",
  8867. upb_fielddef_name(p->top->f));
  8868. return false;
  8869. }
  8870. }
  8871. static bool start_subobject_full(upb_json_parser *p) {
  8872. if (is_top_level(p)) {
  8873. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8874. start_value_object(p, VALUE_STRUCTVALUE);
  8875. if (!start_subobject(p)) return false;
  8876. start_structvalue_object(p);
  8877. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_STRUCT)) {
  8878. start_structvalue_object(p);
  8879. } else {
  8880. return true;
  8881. }
  8882. } else if (is_wellknown_field(p, UPB_WELLKNOWN_STRUCT)) {
  8883. if (!start_subobject(p)) return false;
  8884. start_structvalue_object(p);
  8885. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  8886. if (!start_subobject(p)) return false;
  8887. start_value_object(p, VALUE_STRUCTVALUE);
  8888. if (!start_subobject(p)) return false;
  8889. start_structvalue_object(p);
  8890. }
  8891. return start_subobject(p);
  8892. }
  8893. static void end_subobject(upb_json_parser *p) {
  8894. if (is_top_level(p)) {
  8895. return;
  8896. }
  8897. if (p->top->is_map) {
  8898. upb_selector_t sel;
  8899. p->top--;
  8900. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
  8901. upb_sink_endseq(p->top->sink, sel);
  8902. } else {
  8903. upb_selector_t sel;
  8904. bool is_unknown = p->top->m == NULL;
  8905. p->top--;
  8906. if (!is_unknown) {
  8907. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSUBMSG);
  8908. upb_sink_endsubmsg(p->top->sink, sel);
  8909. }
  8910. }
  8911. }
  8912. static void end_subobject_full(upb_json_parser *p) {
  8913. end_subobject(p);
  8914. if (is_wellknown_msg(p, UPB_WELLKNOWN_STRUCT)) {
  8915. end_structvalue_object(p);
  8916. if (!is_top_level(p)) {
  8917. end_subobject(p);
  8918. }
  8919. }
  8920. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8921. end_value_object(p);
  8922. if (!is_top_level(p)) {
  8923. end_subobject(p);
  8924. }
  8925. }
  8926. }
  8927. static bool start_array(upb_json_parser *p) {
  8928. upb_jsonparser_frame *inner;
  8929. upb_selector_t sel;
  8930. if (is_top_level(p)) {
  8931. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8932. start_value_object(p, VALUE_LISTVALUE);
  8933. if (!start_subobject(p)) return false;
  8934. start_listvalue_object(p);
  8935. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_LISTVALUE)) {
  8936. start_listvalue_object(p);
  8937. } else {
  8938. return false;
  8939. }
  8940. } else if (is_wellknown_field(p, UPB_WELLKNOWN_LISTVALUE) &&
  8941. (!upb_fielddef_isseq(p->top->f) ||
  8942. p->top->is_repeated)) {
  8943. if (!start_subobject(p)) return false;
  8944. start_listvalue_object(p);
  8945. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE) &&
  8946. (!upb_fielddef_isseq(p->top->f) ||
  8947. p->top->is_repeated)) {
  8948. if (!start_subobject(p)) return false;
  8949. start_value_object(p, VALUE_LISTVALUE);
  8950. if (!start_subobject(p)) return false;
  8951. start_listvalue_object(p);
  8952. }
  8953. if (p->top->is_unknown_field) {
  8954. inner = start_jsonparser_frame(p);
  8955. inner->is_unknown_field = true;
  8956. p->top = inner;
  8957. return true;
  8958. }
  8959. if (!upb_fielddef_isseq(p->top->f)) {
  8960. upb_status_seterrf(p->status,
  8961. "Array specified for non-repeated field: %s",
  8962. upb_fielddef_name(p->top->f));
  8963. return false;
  8964. }
  8965. if (!check_stack(p)) return false;
  8966. inner = start_jsonparser_frame(p);
  8967. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
  8968. upb_sink_startseq(p->top->sink, sel, &inner->sink);
  8969. inner->m = p->top->m;
  8970. inner->f = p->top->f;
  8971. inner->is_repeated = true;
  8972. p->top = inner;
  8973. return true;
  8974. }
  8975. static void end_array(upb_json_parser *p) {
  8976. upb_selector_t sel;
  8977. UPB_ASSERT(p->top > p->stack);
  8978. p->top--;
  8979. if (p->top->is_unknown_field) {
  8980. return;
  8981. }
  8982. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
  8983. upb_sink_endseq(p->top->sink, sel);
  8984. if (is_wellknown_msg(p, UPB_WELLKNOWN_LISTVALUE)) {
  8985. end_listvalue_object(p);
  8986. if (!is_top_level(p)) {
  8987. end_subobject(p);
  8988. }
  8989. }
  8990. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  8991. end_value_object(p);
  8992. if (!is_top_level(p)) {
  8993. end_subobject(p);
  8994. }
  8995. }
  8996. }
  8997. static void start_object(upb_json_parser *p) {
  8998. if (!p->top->is_map && p->top->m != NULL) {
  8999. upb_sink_startmsg(p->top->sink);
  9000. }
  9001. }
  9002. static void end_object(upb_json_parser *p) {
  9003. if (!p->top->is_map && p->top->m != NULL) {
  9004. upb_sink_endmsg(p->top->sink, p->status);
  9005. }
  9006. }
  9007. static void start_any_object(upb_json_parser *p, const char *ptr) {
  9008. start_object(p);
  9009. p->top->any_frame->before_type_url_start = ptr;
  9010. p->top->any_frame->before_type_url_end = ptr;
  9011. }
  9012. static bool end_any_object(upb_json_parser *p, const char *ptr) {
  9013. const char *value_membername = "value";
  9014. bool is_well_known_packed = false;
  9015. const char *packed_end = ptr + 1;
  9016. upb_selector_t sel;
  9017. upb_jsonparser_frame *inner;
  9018. if (json_parser_any_frame_has_value(p->top->any_frame) &&
  9019. !json_parser_any_frame_has_type_url(p->top->any_frame)) {
  9020. upb_status_seterrmsg(p->status, "No valid type url");
  9021. return false;
  9022. }
  9023. /* Well known types data is represented as value field. */
  9024. if (upb_msgdef_wellknowntype(p->top->any_frame->parser->top->m) !=
  9025. UPB_WELLKNOWN_UNSPECIFIED) {
  9026. is_well_known_packed = true;
  9027. if (json_parser_any_frame_has_value_before_type_url(p->top->any_frame)) {
  9028. p->top->any_frame->before_type_url_start =
  9029. memchr(p->top->any_frame->before_type_url_start, ':',
  9030. p->top->any_frame->before_type_url_end -
  9031. p->top->any_frame->before_type_url_start);
  9032. if (p->top->any_frame->before_type_url_start == NULL) {
  9033. upb_status_seterrmsg(p->status, "invalid data for well known type.");
  9034. return false;
  9035. }
  9036. p->top->any_frame->before_type_url_start++;
  9037. }
  9038. if (json_parser_any_frame_has_value_after_type_url(p->top->any_frame)) {
  9039. p->top->any_frame->after_type_url_start =
  9040. memchr(p->top->any_frame->after_type_url_start, ':',
  9041. (ptr + 1) -
  9042. p->top->any_frame->after_type_url_start);
  9043. if (p->top->any_frame->after_type_url_start == NULL) {
  9044. upb_status_seterrmsg(p->status, "Invalid data for well known type.");
  9045. return false;
  9046. }
  9047. p->top->any_frame->after_type_url_start++;
  9048. packed_end = ptr;
  9049. }
  9050. }
  9051. if (json_parser_any_frame_has_value_before_type_url(p->top->any_frame)) {
  9052. if (!parse(p->top->any_frame->parser, NULL,
  9053. p->top->any_frame->before_type_url_start,
  9054. p->top->any_frame->before_type_url_end -
  9055. p->top->any_frame->before_type_url_start, NULL)) {
  9056. return false;
  9057. }
  9058. } else {
  9059. if (!is_well_known_packed) {
  9060. if (!parse(p->top->any_frame->parser, NULL, "{", 1, NULL)) {
  9061. return false;
  9062. }
  9063. }
  9064. }
  9065. if (json_parser_any_frame_has_value_before_type_url(p->top->any_frame) &&
  9066. json_parser_any_frame_has_value_after_type_url(p->top->any_frame)) {
  9067. if (!parse(p->top->any_frame->parser, NULL, ",", 1, NULL)) {
  9068. return false;
  9069. }
  9070. }
  9071. if (json_parser_any_frame_has_value_after_type_url(p->top->any_frame)) {
  9072. if (!parse(p->top->any_frame->parser, NULL,
  9073. p->top->any_frame->after_type_url_start,
  9074. packed_end - p->top->any_frame->after_type_url_start, NULL)) {
  9075. return false;
  9076. }
  9077. } else {
  9078. if (!is_well_known_packed) {
  9079. if (!parse(p->top->any_frame->parser, NULL, "}", 1, NULL)) {
  9080. return false;
  9081. }
  9082. }
  9083. }
  9084. if (!end(p->top->any_frame->parser, NULL)) {
  9085. return false;
  9086. }
  9087. p->top->is_any = false;
  9088. /* Set value */
  9089. start_member(p);
  9090. capture_begin(p, value_membername);
  9091. capture_end(p, value_membername + 5);
  9092. end_membername(p);
  9093. if (!check_stack(p)) return false;
  9094. inner = p->top + 1;
  9095. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  9096. upb_sink_startstr(p->top->sink, sel, 0, &inner->sink);
  9097. sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
  9098. upb_sink_putstring(inner->sink, sel, p->top->any_frame->stringsink.ptr,
  9099. p->top->any_frame->stringsink.len, NULL);
  9100. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  9101. upb_sink_endstr(inner->sink, sel);
  9102. end_member(p);
  9103. end_object(p);
  9104. /* Deallocate any parse frame. */
  9105. json_parser_any_frame_free(p->top->any_frame);
  9106. return true;
  9107. }
  9108. static bool is_string_wrapper(const upb_msgdef *m) {
  9109. upb_wellknowntype_t type = upb_msgdef_wellknowntype(m);
  9110. return type == UPB_WELLKNOWN_STRINGVALUE ||
  9111. type == UPB_WELLKNOWN_BYTESVALUE;
  9112. }
  9113. static bool is_fieldmask(const upb_msgdef *m) {
  9114. upb_wellknowntype_t type = upb_msgdef_wellknowntype(m);
  9115. return type == UPB_WELLKNOWN_FIELDMASK;
  9116. }
  9117. static void start_fieldmask_object(upb_json_parser *p) {
  9118. const char *membername = "paths";
  9119. start_object(p);
  9120. /* Set up context for parsing value */
  9121. start_member(p);
  9122. capture_begin(p, membername);
  9123. capture_end(p, membername + 5);
  9124. end_membername(p);
  9125. start_array(p);
  9126. }
  9127. static void end_fieldmask_object(upb_json_parser *p) {
  9128. end_array(p);
  9129. end_member(p);
  9130. end_object(p);
  9131. }
  9132. static void start_wrapper_object(upb_json_parser *p) {
  9133. const char *membername = "value";
  9134. start_object(p);
  9135. /* Set up context for parsing value */
  9136. start_member(p);
  9137. capture_begin(p, membername);
  9138. capture_end(p, membername + 5);
  9139. end_membername(p);
  9140. }
  9141. static void end_wrapper_object(upb_json_parser *p) {
  9142. end_member(p);
  9143. end_object(p);
  9144. }
  9145. static void start_value_object(upb_json_parser *p, int value_type) {
  9146. const char *nullmember = "null_value";
  9147. const char *numbermember = "number_value";
  9148. const char *stringmember = "string_value";
  9149. const char *boolmember = "bool_value";
  9150. const char *structmember = "struct_value";
  9151. const char *listmember = "list_value";
  9152. const char *membername = "";
  9153. switch (value_type) {
  9154. case VALUE_NULLVALUE:
  9155. membername = nullmember;
  9156. break;
  9157. case VALUE_NUMBERVALUE:
  9158. membername = numbermember;
  9159. break;
  9160. case VALUE_STRINGVALUE:
  9161. membername = stringmember;
  9162. break;
  9163. case VALUE_BOOLVALUE:
  9164. membername = boolmember;
  9165. break;
  9166. case VALUE_STRUCTVALUE:
  9167. membername = structmember;
  9168. break;
  9169. case VALUE_LISTVALUE:
  9170. membername = listmember;
  9171. break;
  9172. }
  9173. start_object(p);
  9174. /* Set up context for parsing value */
  9175. start_member(p);
  9176. capture_begin(p, membername);
  9177. capture_end(p, membername + strlen(membername));
  9178. end_membername(p);
  9179. }
  9180. static void end_value_object(upb_json_parser *p) {
  9181. end_member(p);
  9182. end_object(p);
  9183. }
  9184. static void start_listvalue_object(upb_json_parser *p) {
  9185. const char *membername = "values";
  9186. start_object(p);
  9187. /* Set up context for parsing value */
  9188. start_member(p);
  9189. capture_begin(p, membername);
  9190. capture_end(p, membername + strlen(membername));
  9191. end_membername(p);
  9192. }
  9193. static void end_listvalue_object(upb_json_parser *p) {
  9194. end_member(p);
  9195. end_object(p);
  9196. }
  9197. static void start_structvalue_object(upb_json_parser *p) {
  9198. const char *membername = "fields";
  9199. start_object(p);
  9200. /* Set up context for parsing value */
  9201. start_member(p);
  9202. capture_begin(p, membername);
  9203. capture_end(p, membername + strlen(membername));
  9204. end_membername(p);
  9205. }
  9206. static void end_structvalue_object(upb_json_parser *p) {
  9207. end_member(p);
  9208. end_object(p);
  9209. }
  9210. static bool is_top_level(upb_json_parser *p) {
  9211. return p->top == p->stack && p->top->f == NULL && !p->top->is_unknown_field;
  9212. }
  9213. static bool is_wellknown_msg(upb_json_parser *p, upb_wellknowntype_t type) {
  9214. return p->top->m != NULL && upb_msgdef_wellknowntype(p->top->m) == type;
  9215. }
  9216. static bool is_wellknown_field(upb_json_parser *p, upb_wellknowntype_t type) {
  9217. return p->top->f != NULL &&
  9218. upb_fielddef_issubmsg(p->top->f) &&
  9219. (upb_msgdef_wellknowntype(upb_fielddef_msgsubdef(p->top->f))
  9220. == type);
  9221. }
  9222. static bool does_number_wrapper_start(upb_json_parser *p) {
  9223. return p->top->f != NULL &&
  9224. upb_fielddef_issubmsg(p->top->f) &&
  9225. upb_msgdef_isnumberwrapper(upb_fielddef_msgsubdef(p->top->f));
  9226. }
  9227. static bool does_number_wrapper_end(upb_json_parser *p) {
  9228. return p->top->m != NULL && upb_msgdef_isnumberwrapper(p->top->m);
  9229. }
  9230. static bool is_number_wrapper_object(upb_json_parser *p) {
  9231. return p->top->m != NULL && upb_msgdef_isnumberwrapper(p->top->m);
  9232. }
  9233. static bool does_string_wrapper_start(upb_json_parser *p) {
  9234. return p->top->f != NULL &&
  9235. upb_fielddef_issubmsg(p->top->f) &&
  9236. is_string_wrapper(upb_fielddef_msgsubdef(p->top->f));
  9237. }
  9238. static bool does_string_wrapper_end(upb_json_parser *p) {
  9239. return p->top->m != NULL && is_string_wrapper(p->top->m);
  9240. }
  9241. static bool is_string_wrapper_object(upb_json_parser *p) {
  9242. return p->top->m != NULL && is_string_wrapper(p->top->m);
  9243. }
  9244. static bool does_fieldmask_start(upb_json_parser *p) {
  9245. return p->top->f != NULL &&
  9246. upb_fielddef_issubmsg(p->top->f) &&
  9247. is_fieldmask(upb_fielddef_msgsubdef(p->top->f));
  9248. }
  9249. static bool does_fieldmask_end(upb_json_parser *p) {
  9250. return p->top->m != NULL && is_fieldmask(p->top->m);
  9251. }
  9252. #define CHECK_RETURN_TOP(x) if (!(x)) goto error
  9253. /* The actual parser **********************************************************/
  9254. /* What follows is the Ragel parser itself. The language is specified in Ragel
  9255. * and the actions call our C functions above.
  9256. *
  9257. * Ragel has an extensive set of functionality, and we use only a small part of
  9258. * it. There are many action types but we only use a few:
  9259. *
  9260. * ">" -- transition into a machine
  9261. * "%" -- transition out of a machine
  9262. * "@" -- transition into a final state of a machine.
  9263. *
  9264. * "@" transitions are tricky because a machine can transition into a final
  9265. * state repeatedly. But in some cases we know this can't happen, for example
  9266. * a string which is delimited by a final '"' can only transition into its
  9267. * final state once, when the closing '"' is seen. */
  9268. #line 2794 "upb/json/parser.rl"
  9269. #line 2597 "upb/json/parser.c"
  9270. static const char _json_actions[] = {
  9271. 0, 1, 0, 1, 1, 1, 3, 1,
  9272. 4, 1, 6, 1, 7, 1, 8, 1,
  9273. 9, 1, 11, 1, 12, 1, 13, 1,
  9274. 14, 1, 15, 1, 16, 1, 17, 1,
  9275. 18, 1, 19, 1, 20, 1, 22, 1,
  9276. 23, 1, 24, 1, 35, 1, 37, 1,
  9277. 39, 1, 40, 1, 42, 1, 43, 1,
  9278. 44, 1, 46, 1, 48, 1, 49, 1,
  9279. 50, 1, 51, 1, 53, 1, 54, 2,
  9280. 4, 9, 2, 5, 6, 2, 7, 3,
  9281. 2, 7, 9, 2, 21, 26, 2, 25,
  9282. 10, 2, 27, 28, 2, 29, 30, 2,
  9283. 32, 34, 2, 33, 31, 2, 38, 36,
  9284. 2, 40, 42, 2, 45, 2, 2, 46,
  9285. 54, 2, 47, 36, 2, 49, 54, 2,
  9286. 50, 54, 2, 51, 54, 2, 52, 41,
  9287. 2, 53, 54, 3, 32, 34, 35, 4,
  9288. 21, 26, 27, 28
  9289. };
  9290. static const short _json_key_offsets[] = {
  9291. 0, 0, 12, 13, 18, 23, 28, 29,
  9292. 30, 31, 32, 33, 34, 35, 36, 37,
  9293. 38, 43, 44, 48, 53, 58, 63, 67,
  9294. 71, 74, 77, 79, 83, 87, 89, 91,
  9295. 96, 98, 100, 109, 115, 121, 127, 133,
  9296. 135, 139, 142, 144, 146, 149, 150, 154,
  9297. 156, 158, 160, 162, 163, 165, 167, 168,
  9298. 170, 172, 173, 175, 177, 178, 180, 182,
  9299. 183, 185, 187, 191, 193, 195, 196, 197,
  9300. 198, 199, 201, 206, 208, 210, 212, 221,
  9301. 222, 222, 222, 227, 232, 237, 238, 239,
  9302. 240, 241, 241, 242, 243, 244, 244, 245,
  9303. 246, 247, 247, 252, 253, 257, 262, 267,
  9304. 272, 276, 276, 279, 282, 285, 288, 291,
  9305. 294, 294, 294, 294, 294, 294
  9306. };
  9307. static const char _json_trans_keys[] = {
  9308. 32, 34, 45, 91, 102, 110, 116, 123,
  9309. 9, 13, 48, 57, 34, 32, 93, 125,
  9310. 9, 13, 32, 44, 93, 9, 13, 32,
  9311. 93, 125, 9, 13, 97, 108, 115, 101,
  9312. 117, 108, 108, 114, 117, 101, 32, 34,
  9313. 125, 9, 13, 34, 32, 58, 9, 13,
  9314. 32, 93, 125, 9, 13, 32, 44, 125,
  9315. 9, 13, 32, 44, 125, 9, 13, 32,
  9316. 34, 9, 13, 45, 48, 49, 57, 48,
  9317. 49, 57, 46, 69, 101, 48, 57, 69,
  9318. 101, 48, 57, 43, 45, 48, 57, 48,
  9319. 57, 48, 57, 46, 69, 101, 48, 57,
  9320. 34, 92, 34, 92, 34, 47, 92, 98,
  9321. 102, 110, 114, 116, 117, 48, 57, 65,
  9322. 70, 97, 102, 48, 57, 65, 70, 97,
  9323. 102, 48, 57, 65, 70, 97, 102, 48,
  9324. 57, 65, 70, 97, 102, 34, 92, 45,
  9325. 48, 49, 57, 48, 49, 57, 46, 115,
  9326. 48, 57, 115, 48, 57, 34, 46, 115,
  9327. 48, 57, 48, 57, 48, 57, 48, 57,
  9328. 48, 57, 45, 48, 57, 48, 57, 45,
  9329. 48, 57, 48, 57, 84, 48, 57, 48,
  9330. 57, 58, 48, 57, 48, 57, 58, 48,
  9331. 57, 48, 57, 43, 45, 46, 90, 48,
  9332. 57, 48, 57, 58, 48, 48, 34, 48,
  9333. 57, 43, 45, 90, 48, 57, 34, 44,
  9334. 34, 44, 34, 44, 34, 45, 91, 102,
  9335. 110, 116, 123, 48, 57, 34, 32, 93,
  9336. 125, 9, 13, 32, 44, 93, 9, 13,
  9337. 32, 93, 125, 9, 13, 97, 108, 115,
  9338. 101, 117, 108, 108, 114, 117, 101, 32,
  9339. 34, 125, 9, 13, 34, 32, 58, 9,
  9340. 13, 32, 93, 125, 9, 13, 32, 44,
  9341. 125, 9, 13, 32, 44, 125, 9, 13,
  9342. 32, 34, 9, 13, 32, 9, 13, 32,
  9343. 9, 13, 32, 9, 13, 32, 9, 13,
  9344. 32, 9, 13, 32, 9, 13, 0
  9345. };
  9346. static const char _json_single_lengths[] = {
  9347. 0, 8, 1, 3, 3, 3, 1, 1,
  9348. 1, 1, 1, 1, 1, 1, 1, 1,
  9349. 3, 1, 2, 3, 3, 3, 2, 2,
  9350. 1, 3, 0, 2, 2, 0, 0, 3,
  9351. 2, 2, 9, 0, 0, 0, 0, 2,
  9352. 2, 1, 2, 0, 1, 1, 2, 0,
  9353. 0, 0, 0, 1, 0, 0, 1, 0,
  9354. 0, 1, 0, 0, 1, 0, 0, 1,
  9355. 0, 0, 4, 0, 0, 1, 1, 1,
  9356. 1, 0, 3, 2, 2, 2, 7, 1,
  9357. 0, 0, 3, 3, 3, 1, 1, 1,
  9358. 1, 0, 1, 1, 1, 0, 1, 1,
  9359. 1, 0, 3, 1, 2, 3, 3, 3,
  9360. 2, 0, 1, 1, 1, 1, 1, 1,
  9361. 0, 0, 0, 0, 0, 0
  9362. };
  9363. static const char _json_range_lengths[] = {
  9364. 0, 2, 0, 1, 1, 1, 0, 0,
  9365. 0, 0, 0, 0, 0, 0, 0, 0,
  9366. 1, 0, 1, 1, 1, 1, 1, 1,
  9367. 1, 0, 1, 1, 1, 1, 1, 1,
  9368. 0, 0, 0, 3, 3, 3, 3, 0,
  9369. 1, 1, 0, 1, 1, 0, 1, 1,
  9370. 1, 1, 1, 0, 1, 1, 0, 1,
  9371. 1, 0, 1, 1, 0, 1, 1, 0,
  9372. 1, 1, 0, 1, 1, 0, 0, 0,
  9373. 0, 1, 1, 0, 0, 0, 1, 0,
  9374. 0, 0, 1, 1, 1, 0, 0, 0,
  9375. 0, 0, 0, 0, 0, 0, 0, 0,
  9376. 0, 0, 1, 0, 1, 1, 1, 1,
  9377. 1, 0, 1, 1, 1, 1, 1, 1,
  9378. 0, 0, 0, 0, 0, 0
  9379. };
  9380. static const short _json_index_offsets[] = {
  9381. 0, 0, 11, 13, 18, 23, 28, 30,
  9382. 32, 34, 36, 38, 40, 42, 44, 46,
  9383. 48, 53, 55, 59, 64, 69, 74, 78,
  9384. 82, 85, 89, 91, 95, 99, 101, 103,
  9385. 108, 111, 114, 124, 128, 132, 136, 140,
  9386. 143, 147, 150, 153, 155, 158, 160, 164,
  9387. 166, 168, 170, 172, 174, 176, 178, 180,
  9388. 182, 184, 186, 188, 190, 192, 194, 196,
  9389. 198, 200, 202, 207, 209, 211, 213, 215,
  9390. 217, 219, 221, 226, 229, 232, 235, 244,
  9391. 246, 247, 248, 253, 258, 263, 265, 267,
  9392. 269, 271, 272, 274, 276, 278, 279, 281,
  9393. 283, 285, 286, 291, 293, 297, 302, 307,
  9394. 312, 316, 317, 320, 323, 326, 329, 332,
  9395. 335, 336, 337, 338, 339, 340
  9396. };
  9397. static const unsigned char _json_indicies[] = {
  9398. 0, 2, 3, 4, 5, 6, 7, 8,
  9399. 0, 3, 1, 9, 1, 11, 12, 1,
  9400. 11, 10, 13, 14, 12, 13, 1, 14,
  9401. 1, 1, 14, 10, 15, 1, 16, 1,
  9402. 17, 1, 18, 1, 19, 1, 20, 1,
  9403. 21, 1, 22, 1, 23, 1, 24, 1,
  9404. 25, 26, 27, 25, 1, 28, 1, 29,
  9405. 30, 29, 1, 30, 1, 1, 30, 31,
  9406. 32, 33, 34, 32, 1, 35, 36, 27,
  9407. 35, 1, 36, 26, 36, 1, 37, 38,
  9408. 39, 1, 38, 39, 1, 41, 42, 42,
  9409. 40, 43, 1, 42, 42, 43, 40, 44,
  9410. 44, 45, 1, 45, 1, 45, 40, 41,
  9411. 42, 42, 39, 40, 47, 48, 46, 50,
  9412. 51, 49, 52, 52, 52, 52, 52, 52,
  9413. 52, 52, 53, 1, 54, 54, 54, 1,
  9414. 55, 55, 55, 1, 56, 56, 56, 1,
  9415. 57, 57, 57, 1, 59, 60, 58, 61,
  9416. 62, 63, 1, 64, 65, 1, 66, 67,
  9417. 1, 68, 1, 67, 68, 1, 69, 1,
  9418. 66, 67, 65, 1, 70, 1, 71, 1,
  9419. 72, 1, 73, 1, 74, 1, 75, 1,
  9420. 76, 1, 77, 1, 78, 1, 79, 1,
  9421. 80, 1, 81, 1, 82, 1, 83, 1,
  9422. 84, 1, 85, 1, 86, 1, 87, 1,
  9423. 88, 1, 89, 89, 90, 91, 1, 92,
  9424. 1, 93, 1, 94, 1, 95, 1, 96,
  9425. 1, 97, 1, 98, 1, 99, 99, 100,
  9426. 98, 1, 102, 1, 101, 104, 105, 103,
  9427. 1, 1, 101, 106, 107, 108, 109, 110,
  9428. 111, 112, 107, 1, 113, 1, 114, 115,
  9429. 117, 118, 1, 117, 116, 119, 120, 118,
  9430. 119, 1, 120, 1, 1, 120, 116, 121,
  9431. 1, 122, 1, 123, 1, 124, 1, 125,
  9432. 126, 1, 127, 1, 128, 1, 129, 130,
  9433. 1, 131, 1, 132, 1, 133, 134, 135,
  9434. 136, 134, 1, 137, 1, 138, 139, 138,
  9435. 1, 139, 1, 1, 139, 140, 141, 142,
  9436. 143, 141, 1, 144, 145, 136, 144, 1,
  9437. 145, 135, 145, 1, 146, 147, 147, 1,
  9438. 148, 148, 1, 149, 149, 1, 150, 150,
  9439. 1, 151, 151, 1, 152, 152, 1, 1,
  9440. 1, 1, 1, 1, 1, 0
  9441. };
  9442. static const char _json_trans_targs[] = {
  9443. 1, 0, 2, 107, 3, 6, 10, 13,
  9444. 16, 106, 4, 3, 106, 4, 5, 7,
  9445. 8, 9, 108, 11, 12, 109, 14, 15,
  9446. 110, 16, 17, 111, 18, 18, 19, 20,
  9447. 21, 22, 111, 21, 22, 24, 25, 31,
  9448. 112, 26, 28, 27, 29, 30, 33, 113,
  9449. 34, 33, 113, 34, 32, 35, 36, 37,
  9450. 38, 39, 33, 113, 34, 41, 42, 46,
  9451. 42, 46, 43, 45, 44, 114, 48, 49,
  9452. 50, 51, 52, 53, 54, 55, 56, 57,
  9453. 58, 59, 60, 61, 62, 63, 64, 65,
  9454. 66, 67, 73, 72, 68, 69, 70, 71,
  9455. 72, 115, 74, 67, 72, 76, 116, 76,
  9456. 116, 77, 79, 81, 82, 85, 90, 94,
  9457. 98, 80, 117, 117, 83, 82, 80, 83,
  9458. 84, 86, 87, 88, 89, 117, 91, 92,
  9459. 93, 117, 95, 96, 97, 117, 98, 99,
  9460. 105, 100, 100, 101, 102, 103, 104, 105,
  9461. 103, 104, 117, 106, 106, 106, 106, 106,
  9462. 106
  9463. };
  9464. static const unsigned char _json_trans_actions[] = {
  9465. 0, 0, 113, 107, 53, 0, 0, 0,
  9466. 125, 59, 45, 0, 55, 0, 0, 0,
  9467. 0, 0, 0, 0, 0, 0, 0, 0,
  9468. 0, 0, 101, 51, 47, 0, 0, 45,
  9469. 49, 49, 104, 0, 0, 0, 0, 0,
  9470. 3, 0, 0, 0, 0, 0, 5, 15,
  9471. 0, 0, 71, 7, 13, 0, 74, 9,
  9472. 9, 9, 77, 80, 11, 37, 37, 37,
  9473. 0, 0, 0, 39, 0, 41, 86, 0,
  9474. 0, 0, 17, 19, 0, 21, 23, 0,
  9475. 25, 27, 0, 29, 31, 0, 33, 35,
  9476. 0, 135, 83, 135, 0, 0, 0, 0,
  9477. 0, 92, 0, 89, 89, 98, 43, 0,
  9478. 131, 95, 113, 107, 53, 0, 0, 0,
  9479. 125, 59, 69, 110, 45, 0, 55, 0,
  9480. 0, 0, 0, 0, 0, 119, 0, 0,
  9481. 0, 122, 0, 0, 0, 116, 0, 101,
  9482. 51, 47, 0, 0, 45, 49, 49, 104,
  9483. 0, 0, 128, 0, 57, 63, 65, 61,
  9484. 67
  9485. };
  9486. static const unsigned char _json_eof_actions[] = {
  9487. 0, 0, 0, 0, 0, 0, 0, 0,
  9488. 0, 0, 0, 0, 0, 0, 0, 0,
  9489. 0, 0, 0, 0, 0, 0, 0, 0,
  9490. 0, 1, 0, 1, 0, 0, 1, 1,
  9491. 0, 0, 0, 0, 0, 0, 0, 0,
  9492. 0, 0, 0, 0, 0, 0, 0, 0,
  9493. 0, 0, 0, 0, 0, 0, 0, 0,
  9494. 0, 0, 0, 0, 0, 0, 0, 0,
  9495. 0, 0, 0, 0, 0, 0, 0, 0,
  9496. 0, 0, 0, 0, 0, 0, 0, 0,
  9497. 0, 0, 0, 0, 0, 0, 0, 0,
  9498. 0, 0, 0, 0, 0, 0, 0, 0,
  9499. 0, 0, 0, 0, 0, 0, 0, 0,
  9500. 0, 0, 0, 57, 63, 65, 61, 67,
  9501. 0, 0, 0, 0, 0, 0
  9502. };
  9503. static const int json_start = 1;
  9504. static const int json_en_number_machine = 23;
  9505. static const int json_en_string_machine = 32;
  9506. static const int json_en_duration_machine = 40;
  9507. static const int json_en_timestamp_machine = 47;
  9508. static const int json_en_fieldmask_machine = 75;
  9509. static const int json_en_value_machine = 78;
  9510. static const int json_en_main = 1;
  9511. #line 2797 "upb/json/parser.rl"
  9512. size_t parse(void *closure, const void *hd, const char *buf, size_t size,
  9513. const upb_bufhandle *handle) {
  9514. upb_json_parser *parser = closure;
  9515. /* Variables used by Ragel's generated code. */
  9516. int cs = parser->current_state;
  9517. int *stack = parser->parser_stack;
  9518. int top = parser->parser_top;
  9519. const char *p = buf;
  9520. const char *pe = buf + size;
  9521. const char *eof = &eof_ch;
  9522. parser->handle = handle;
  9523. UPB_UNUSED(hd);
  9524. UPB_UNUSED(handle);
  9525. capture_resume(parser, buf);
  9526. #line 2875 "upb/json/parser.c"
  9527. {
  9528. int _klen;
  9529. unsigned int _trans;
  9530. const char *_acts;
  9531. unsigned int _nacts;
  9532. const char *_keys;
  9533. if ( p == pe )
  9534. goto _test_eof;
  9535. if ( cs == 0 )
  9536. goto _out;
  9537. _resume:
  9538. _keys = _json_trans_keys + _json_key_offsets[cs];
  9539. _trans = _json_index_offsets[cs];
  9540. _klen = _json_single_lengths[cs];
  9541. if ( _klen > 0 ) {
  9542. const char *_lower = _keys;
  9543. const char *_mid;
  9544. const char *_upper = _keys + _klen - 1;
  9545. while (1) {
  9546. if ( _upper < _lower )
  9547. break;
  9548. _mid = _lower + ((_upper-_lower) >> 1);
  9549. if ( (*p) < *_mid )
  9550. _upper = _mid - 1;
  9551. else if ( (*p) > *_mid )
  9552. _lower = _mid + 1;
  9553. else {
  9554. _trans += (unsigned int)(_mid - _keys);
  9555. goto _match;
  9556. }
  9557. }
  9558. _keys += _klen;
  9559. _trans += _klen;
  9560. }
  9561. _klen = _json_range_lengths[cs];
  9562. if ( _klen > 0 ) {
  9563. const char *_lower = _keys;
  9564. const char *_mid;
  9565. const char *_upper = _keys + (_klen<<1) - 2;
  9566. while (1) {
  9567. if ( _upper < _lower )
  9568. break;
  9569. _mid = _lower + (((_upper-_lower) >> 1) & ~1);
  9570. if ( (*p) < _mid[0] )
  9571. _upper = _mid - 2;
  9572. else if ( (*p) > _mid[1] )
  9573. _lower = _mid + 2;
  9574. else {
  9575. _trans += (unsigned int)((_mid - _keys)>>1);
  9576. goto _match;
  9577. }
  9578. }
  9579. _trans += _klen;
  9580. }
  9581. _match:
  9582. _trans = _json_indicies[_trans];
  9583. cs = _json_trans_targs[_trans];
  9584. if ( _json_trans_actions[_trans] == 0 )
  9585. goto _again;
  9586. _acts = _json_actions + _json_trans_actions[_trans];
  9587. _nacts = (unsigned int) *_acts++;
  9588. while ( _nacts-- > 0 )
  9589. {
  9590. switch ( *_acts++ )
  9591. {
  9592. case 1:
  9593. #line 2602 "upb/json/parser.rl"
  9594. { p--; {cs = stack[--top]; goto _again;} }
  9595. break;
  9596. case 2:
  9597. #line 2604 "upb/json/parser.rl"
  9598. { p--; {stack[top++] = cs; cs = 23;goto _again;} }
  9599. break;
  9600. case 3:
  9601. #line 2608 "upb/json/parser.rl"
  9602. { start_text(parser, p); }
  9603. break;
  9604. case 4:
  9605. #line 2609 "upb/json/parser.rl"
  9606. { CHECK_RETURN_TOP(end_text(parser, p)); }
  9607. break;
  9608. case 5:
  9609. #line 2615 "upb/json/parser.rl"
  9610. { start_hex(parser); }
  9611. break;
  9612. case 6:
  9613. #line 2616 "upb/json/parser.rl"
  9614. { hexdigit(parser, p); }
  9615. break;
  9616. case 7:
  9617. #line 2617 "upb/json/parser.rl"
  9618. { CHECK_RETURN_TOP(end_hex(parser)); }
  9619. break;
  9620. case 8:
  9621. #line 2623 "upb/json/parser.rl"
  9622. { CHECK_RETURN_TOP(escape(parser, p)); }
  9623. break;
  9624. case 9:
  9625. #line 2629 "upb/json/parser.rl"
  9626. { p--; {cs = stack[--top]; goto _again;} }
  9627. break;
  9628. case 10:
  9629. #line 2634 "upb/json/parser.rl"
  9630. { start_year(parser, p); }
  9631. break;
  9632. case 11:
  9633. #line 2635 "upb/json/parser.rl"
  9634. { CHECK_RETURN_TOP(end_year(parser, p)); }
  9635. break;
  9636. case 12:
  9637. #line 2639 "upb/json/parser.rl"
  9638. { start_month(parser, p); }
  9639. break;
  9640. case 13:
  9641. #line 2640 "upb/json/parser.rl"
  9642. { CHECK_RETURN_TOP(end_month(parser, p)); }
  9643. break;
  9644. case 14:
  9645. #line 2644 "upb/json/parser.rl"
  9646. { start_day(parser, p); }
  9647. break;
  9648. case 15:
  9649. #line 2645 "upb/json/parser.rl"
  9650. { CHECK_RETURN_TOP(end_day(parser, p)); }
  9651. break;
  9652. case 16:
  9653. #line 2649 "upb/json/parser.rl"
  9654. { start_hour(parser, p); }
  9655. break;
  9656. case 17:
  9657. #line 2650 "upb/json/parser.rl"
  9658. { CHECK_RETURN_TOP(end_hour(parser, p)); }
  9659. break;
  9660. case 18:
  9661. #line 2654 "upb/json/parser.rl"
  9662. { start_minute(parser, p); }
  9663. break;
  9664. case 19:
  9665. #line 2655 "upb/json/parser.rl"
  9666. { CHECK_RETURN_TOP(end_minute(parser, p)); }
  9667. break;
  9668. case 20:
  9669. #line 2659 "upb/json/parser.rl"
  9670. { start_second(parser, p); }
  9671. break;
  9672. case 21:
  9673. #line 2660 "upb/json/parser.rl"
  9674. { CHECK_RETURN_TOP(end_second(parser, p)); }
  9675. break;
  9676. case 22:
  9677. #line 2665 "upb/json/parser.rl"
  9678. { start_duration_base(parser, p); }
  9679. break;
  9680. case 23:
  9681. #line 2666 "upb/json/parser.rl"
  9682. { CHECK_RETURN_TOP(end_duration_base(parser, p)); }
  9683. break;
  9684. case 24:
  9685. #line 2668 "upb/json/parser.rl"
  9686. { p--; {cs = stack[--top]; goto _again;} }
  9687. break;
  9688. case 25:
  9689. #line 2673 "upb/json/parser.rl"
  9690. { start_timestamp_base(parser); }
  9691. break;
  9692. case 26:
  9693. #line 2675 "upb/json/parser.rl"
  9694. { start_timestamp_fraction(parser, p); }
  9695. break;
  9696. case 27:
  9697. #line 2676 "upb/json/parser.rl"
  9698. { CHECK_RETURN_TOP(end_timestamp_fraction(parser, p)); }
  9699. break;
  9700. case 28:
  9701. #line 2678 "upb/json/parser.rl"
  9702. { start_timestamp_zone(parser, p); }
  9703. break;
  9704. case 29:
  9705. #line 2679 "upb/json/parser.rl"
  9706. { CHECK_RETURN_TOP(end_timestamp_zone(parser, p)); }
  9707. break;
  9708. case 30:
  9709. #line 2681 "upb/json/parser.rl"
  9710. { p--; {cs = stack[--top]; goto _again;} }
  9711. break;
  9712. case 31:
  9713. #line 2686 "upb/json/parser.rl"
  9714. { start_fieldmask_path_text(parser, p); }
  9715. break;
  9716. case 32:
  9717. #line 2687 "upb/json/parser.rl"
  9718. { end_fieldmask_path_text(parser, p); }
  9719. break;
  9720. case 33:
  9721. #line 2692 "upb/json/parser.rl"
  9722. { start_fieldmask_path(parser); }
  9723. break;
  9724. case 34:
  9725. #line 2693 "upb/json/parser.rl"
  9726. { end_fieldmask_path(parser); }
  9727. break;
  9728. case 35:
  9729. #line 2699 "upb/json/parser.rl"
  9730. { p--; {cs = stack[--top]; goto _again;} }
  9731. break;
  9732. case 36:
  9733. #line 2704 "upb/json/parser.rl"
  9734. {
  9735. if (is_wellknown_msg(parser, UPB_WELLKNOWN_TIMESTAMP)) {
  9736. {stack[top++] = cs; cs = 47;goto _again;}
  9737. } else if (is_wellknown_msg(parser, UPB_WELLKNOWN_DURATION)) {
  9738. {stack[top++] = cs; cs = 40;goto _again;}
  9739. } else if (is_wellknown_msg(parser, UPB_WELLKNOWN_FIELDMASK)) {
  9740. {stack[top++] = cs; cs = 75;goto _again;}
  9741. } else {
  9742. {stack[top++] = cs; cs = 32;goto _again;}
  9743. }
  9744. }
  9745. break;
  9746. case 37:
  9747. #line 2717 "upb/json/parser.rl"
  9748. { p--; {stack[top++] = cs; cs = 78;goto _again;} }
  9749. break;
  9750. case 38:
  9751. #line 2722 "upb/json/parser.rl"
  9752. {
  9753. if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
  9754. start_any_member(parser, p);
  9755. } else {
  9756. start_member(parser);
  9757. }
  9758. }
  9759. break;
  9760. case 39:
  9761. #line 2729 "upb/json/parser.rl"
  9762. { CHECK_RETURN_TOP(end_membername(parser)); }
  9763. break;
  9764. case 40:
  9765. #line 2732 "upb/json/parser.rl"
  9766. {
  9767. if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
  9768. end_any_member(parser, p);
  9769. } else {
  9770. end_member(parser);
  9771. }
  9772. }
  9773. break;
  9774. case 41:
  9775. #line 2743 "upb/json/parser.rl"
  9776. {
  9777. if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
  9778. start_any_object(parser, p);
  9779. } else {
  9780. start_object(parser);
  9781. }
  9782. }
  9783. break;
  9784. case 42:
  9785. #line 2752 "upb/json/parser.rl"
  9786. {
  9787. if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
  9788. CHECK_RETURN_TOP(end_any_object(parser, p));
  9789. } else {
  9790. end_object(parser);
  9791. }
  9792. }
  9793. break;
  9794. case 43:
  9795. #line 2764 "upb/json/parser.rl"
  9796. { CHECK_RETURN_TOP(start_array(parser)); }
  9797. break;
  9798. case 44:
  9799. #line 2768 "upb/json/parser.rl"
  9800. { end_array(parser); }
  9801. break;
  9802. case 45:
  9803. #line 2773 "upb/json/parser.rl"
  9804. { CHECK_RETURN_TOP(start_number(parser, p)); }
  9805. break;
  9806. case 46:
  9807. #line 2774 "upb/json/parser.rl"
  9808. { CHECK_RETURN_TOP(end_number(parser, p)); }
  9809. break;
  9810. case 47:
  9811. #line 2776 "upb/json/parser.rl"
  9812. { CHECK_RETURN_TOP(start_stringval(parser)); }
  9813. break;
  9814. case 48:
  9815. #line 2777 "upb/json/parser.rl"
  9816. { CHECK_RETURN_TOP(end_stringval(parser)); }
  9817. break;
  9818. case 49:
  9819. #line 2779 "upb/json/parser.rl"
  9820. { CHECK_RETURN_TOP(end_bool(parser, true)); }
  9821. break;
  9822. case 50:
  9823. #line 2781 "upb/json/parser.rl"
  9824. { CHECK_RETURN_TOP(end_bool(parser, false)); }
  9825. break;
  9826. case 51:
  9827. #line 2783 "upb/json/parser.rl"
  9828. { CHECK_RETURN_TOP(end_null(parser)); }
  9829. break;
  9830. case 52:
  9831. #line 2785 "upb/json/parser.rl"
  9832. { CHECK_RETURN_TOP(start_subobject_full(parser)); }
  9833. break;
  9834. case 53:
  9835. #line 2786 "upb/json/parser.rl"
  9836. { end_subobject_full(parser); }
  9837. break;
  9838. case 54:
  9839. #line 2791 "upb/json/parser.rl"
  9840. { p--; {cs = stack[--top]; goto _again;} }
  9841. break;
  9842. #line 3199 "upb/json/parser.c"
  9843. }
  9844. }
  9845. _again:
  9846. if ( cs == 0 )
  9847. goto _out;
  9848. if ( ++p != pe )
  9849. goto _resume;
  9850. _test_eof: {}
  9851. if ( p == eof )
  9852. {
  9853. const char *__acts = _json_actions + _json_eof_actions[cs];
  9854. unsigned int __nacts = (unsigned int) *__acts++;
  9855. while ( __nacts-- > 0 ) {
  9856. switch ( *__acts++ ) {
  9857. case 0:
  9858. #line 2600 "upb/json/parser.rl"
  9859. { p--; {cs = stack[--top]; if ( p == pe )
  9860. goto _test_eof;
  9861. goto _again;} }
  9862. break;
  9863. case 46:
  9864. #line 2774 "upb/json/parser.rl"
  9865. { CHECK_RETURN_TOP(end_number(parser, p)); }
  9866. break;
  9867. case 49:
  9868. #line 2779 "upb/json/parser.rl"
  9869. { CHECK_RETURN_TOP(end_bool(parser, true)); }
  9870. break;
  9871. case 50:
  9872. #line 2781 "upb/json/parser.rl"
  9873. { CHECK_RETURN_TOP(end_bool(parser, false)); }
  9874. break;
  9875. case 51:
  9876. #line 2783 "upb/json/parser.rl"
  9877. { CHECK_RETURN_TOP(end_null(parser)); }
  9878. break;
  9879. case 53:
  9880. #line 2786 "upb/json/parser.rl"
  9881. { end_subobject_full(parser); }
  9882. break;
  9883. #line 3241 "upb/json/parser.c"
  9884. }
  9885. }
  9886. }
  9887. _out: {}
  9888. }
  9889. #line 2819 "upb/json/parser.rl"
  9890. if (p != pe) {
  9891. upb_status_seterrf(parser->status, "Parse error at '%.*s'\n", pe - p, p);
  9892. } else {
  9893. capture_suspend(parser, &p);
  9894. }
  9895. error:
  9896. /* Save parsing state back to parser. */
  9897. parser->current_state = cs;
  9898. parser->parser_top = top;
  9899. return p - buf;
  9900. }
  9901. static bool end(void *closure, const void *hd) {
  9902. upb_json_parser *parser = closure;
  9903. /* Prevent compile warning on unused static constants. */
  9904. UPB_UNUSED(json_start);
  9905. UPB_UNUSED(json_en_duration_machine);
  9906. UPB_UNUSED(json_en_fieldmask_machine);
  9907. UPB_UNUSED(json_en_number_machine);
  9908. UPB_UNUSED(json_en_string_machine);
  9909. UPB_UNUSED(json_en_timestamp_machine);
  9910. UPB_UNUSED(json_en_value_machine);
  9911. UPB_UNUSED(json_en_main);
  9912. parse(parser, hd, &eof_ch, 0, NULL);
  9913. return parser->current_state >= 106;
  9914. }
  9915. static void json_parser_reset(upb_json_parser *p) {
  9916. int cs;
  9917. int top;
  9918. p->top = p->stack;
  9919. init_frame(p->top);
  9920. /* Emit Ragel initialization of the parser. */
  9921. #line 3292 "upb/json/parser.c"
  9922. {
  9923. cs = json_start;
  9924. top = 0;
  9925. }
  9926. #line 2861 "upb/json/parser.rl"
  9927. p->current_state = cs;
  9928. p->parser_top = top;
  9929. accumulate_clear(p);
  9930. p->multipart_state = MULTIPART_INACTIVE;
  9931. p->capture = NULL;
  9932. p->accumulated = NULL;
  9933. }
  9934. static upb_json_parsermethod *parsermethod_new(upb_json_codecache *c,
  9935. const upb_msgdef *md) {
  9936. upb_msg_field_iter i;
  9937. upb_alloc *alloc = upb_arena_alloc(c->arena);
  9938. upb_json_parsermethod *m = upb_malloc(alloc, sizeof(*m));
  9939. m->cache = c;
  9940. upb_byteshandler_init(&m->input_handler_);
  9941. upb_byteshandler_setstring(&m->input_handler_, parse, m);
  9942. upb_byteshandler_setendstr(&m->input_handler_, end, m);
  9943. upb_strtable_init2(&m->name_table, UPB_CTYPE_CONSTPTR, alloc);
  9944. /* Build name_table */
  9945. for(upb_msg_field_begin(&i, md);
  9946. !upb_msg_field_done(&i);
  9947. upb_msg_field_next(&i)) {
  9948. const upb_fielddef *f = upb_msg_iter_field(&i);
  9949. upb_value v = upb_value_constptr(f);
  9950. char *buf;
  9951. /* Add an entry for the JSON name. */
  9952. size_t len = upb_fielddef_getjsonname(f, NULL, 0);
  9953. buf = upb_malloc(alloc, len);
  9954. upb_fielddef_getjsonname(f, buf, len);
  9955. upb_strtable_insert3(&m->name_table, buf, strlen(buf), v, alloc);
  9956. if (strcmp(buf, upb_fielddef_name(f)) != 0) {
  9957. /* Since the JSON name is different from the regular field name, add an
  9958. * entry for the raw name (compliant proto3 JSON parsers must accept
  9959. * both). */
  9960. const char *name = upb_fielddef_name(f);
  9961. upb_strtable_insert3(&m->name_table, name, strlen(name), v, alloc);
  9962. }
  9963. }
  9964. return m;
  9965. }
  9966. /* Public API *****************************************************************/
  9967. upb_json_parser *upb_json_parser_create(upb_arena *arena,
  9968. const upb_json_parsermethod *method,
  9969. const upb_symtab* symtab,
  9970. upb_sink output,
  9971. upb_status *status,
  9972. bool ignore_json_unknown) {
  9973. #ifndef NDEBUG
  9974. const size_t size_before = upb_arena_bytesallocated(arena);
  9975. #endif
  9976. upb_json_parser *p = upb_arena_malloc(arena, sizeof(upb_json_parser));
  9977. if (!p) return false;
  9978. p->arena = arena;
  9979. p->method = method;
  9980. p->status = status;
  9981. p->limit = p->stack + UPB_JSON_MAX_DEPTH;
  9982. p->accumulate_buf = NULL;
  9983. p->accumulate_buf_size = 0;
  9984. upb_bytessink_reset(&p->input_, &method->input_handler_, p);
  9985. json_parser_reset(p);
  9986. p->top->sink = output;
  9987. p->top->m = upb_handlers_msgdef(output.handlers);
  9988. if (is_wellknown_msg(p, UPB_WELLKNOWN_ANY)) {
  9989. p->top->is_any = true;
  9990. p->top->any_frame = json_parser_any_frame_new(p);
  9991. } else {
  9992. p->top->is_any = false;
  9993. p->top->any_frame = NULL;
  9994. }
  9995. set_name_table(p, p->top);
  9996. p->symtab = symtab;
  9997. p->ignore_json_unknown = ignore_json_unknown;
  9998. /* If this fails, uncomment and increase the value in parser.h. */
  9999. /* fprintf(stderr, "%zd\n", upb_arena_bytesallocated(arena) - size_before); */
  10000. UPB_ASSERT_DEBUGVAR(upb_arena_bytesallocated(arena) - size_before <=
  10001. UPB_JSON_PARSER_SIZE);
  10002. return p;
  10003. }
  10004. upb_bytessink upb_json_parser_input(upb_json_parser *p) {
  10005. return p->input_;
  10006. }
  10007. const upb_byteshandler *upb_json_parsermethod_inputhandler(
  10008. const upb_json_parsermethod *m) {
  10009. return &m->input_handler_;
  10010. }
  10011. upb_json_codecache *upb_json_codecache_new(void) {
  10012. upb_alloc *alloc;
  10013. upb_json_codecache *c;
  10014. c = upb_gmalloc(sizeof(*c));
  10015. c->arena = upb_arena_new();
  10016. alloc = upb_arena_alloc(c->arena);
  10017. upb_inttable_init2(&c->methods, UPB_CTYPE_CONSTPTR, alloc);
  10018. return c;
  10019. }
  10020. void upb_json_codecache_free(upb_json_codecache *c) {
  10021. upb_arena_free(c->arena);
  10022. upb_gfree(c);
  10023. }
  10024. const upb_json_parsermethod *upb_json_codecache_get(upb_json_codecache *c,
  10025. const upb_msgdef *md) {
  10026. upb_json_parsermethod *m;
  10027. upb_value v;
  10028. upb_msg_field_iter i;
  10029. upb_alloc *alloc = upb_arena_alloc(c->arena);
  10030. if (upb_inttable_lookupptr(&c->methods, md, &v)) {
  10031. return upb_value_getconstptr(v);
  10032. }
  10033. m = parsermethod_new(c, md);
  10034. v = upb_value_constptr(m);
  10035. if (!m) return NULL;
  10036. if (!upb_inttable_insertptr2(&c->methods, md, v, alloc)) return NULL;
  10037. /* Populate parser methods for all submessages, so the name tables will
  10038. * be available during parsing. */
  10039. for(upb_msg_field_begin(&i, md);
  10040. !upb_msg_field_done(&i);
  10041. upb_msg_field_next(&i)) {
  10042. upb_fielddef *f = upb_msg_iter_field(&i);
  10043. if (upb_fielddef_issubmsg(f)) {
  10044. const upb_msgdef *subdef = upb_fielddef_msgsubdef(f);
  10045. const upb_json_parsermethod *sub_method =
  10046. upb_json_codecache_get(c, subdef);
  10047. if (!sub_method) return NULL;
  10048. }
  10049. }
  10050. return m;
  10051. }
  10052. /*
  10053. ** This currently uses snprintf() to format primitives, and could be optimized
  10054. ** further.
  10055. */
  10056. #include <ctype.h>
  10057. #include <stdint.h>
  10058. #include <string.h>
  10059. #include <time.h>
  10060. struct upb_json_printer {
  10061. upb_sink input_;
  10062. /* BytesSink closure. */
  10063. void *subc_;
  10064. upb_bytessink output_;
  10065. /* We track the depth so that we know when to emit startstr/endstr on the
  10066. * output. */
  10067. int depth_;
  10068. /* Have we emitted the first element? This state is necessary to emit commas
  10069. * without leaving a trailing comma in arrays/maps. We keep this state per
  10070. * frame depth.
  10071. *
  10072. * Why max_depth * 2? UPB_MAX_HANDLER_DEPTH counts depth as nested messages.
  10073. * We count frames (contexts in which we separate elements by commas) as both
  10074. * repeated fields and messages (maps), and the worst case is a
  10075. * message->repeated field->submessage->repeated field->... nesting. */
  10076. bool first_elem_[UPB_MAX_HANDLER_DEPTH * 2];
  10077. /* To print timestamp, printer needs to cache its seconds and nanos values
  10078. * and convert them when ending timestamp message. See comments of
  10079. * printer_sethandlers_timestamp for more detail. */
  10080. int64_t seconds;
  10081. int32_t nanos;
  10082. };
  10083. /* StringPiece; a pointer plus a length. */
  10084. typedef struct {
  10085. char *ptr;
  10086. size_t len;
  10087. } strpc;
  10088. void freestrpc(void *ptr) {
  10089. strpc *pc = ptr;
  10090. upb_gfree(pc->ptr);
  10091. upb_gfree(pc);
  10092. }
  10093. typedef struct {
  10094. bool preserve_fieldnames;
  10095. } upb_json_printercache;
  10096. /* Convert fielddef name to JSON name and return as a string piece. */
  10097. strpc *newstrpc(upb_handlers *h, const upb_fielddef *f,
  10098. bool preserve_fieldnames) {
  10099. /* TODO(haberman): handle malloc failure. */
  10100. strpc *ret = upb_gmalloc(sizeof(*ret));
  10101. if (preserve_fieldnames) {
  10102. ret->ptr = upb_gstrdup(upb_fielddef_name(f));
  10103. ret->len = strlen(ret->ptr);
  10104. } else {
  10105. size_t len;
  10106. ret->len = upb_fielddef_getjsonname(f, NULL, 0);
  10107. ret->ptr = upb_gmalloc(ret->len);
  10108. len = upb_fielddef_getjsonname(f, ret->ptr, ret->len);
  10109. UPB_ASSERT(len == ret->len);
  10110. ret->len--; /* NULL */
  10111. }
  10112. upb_handlers_addcleanup(h, ret, freestrpc);
  10113. return ret;
  10114. }
  10115. /* Convert a null-terminated const char* to a string piece. */
  10116. strpc *newstrpc_str(upb_handlers *h, const char * str) {
  10117. strpc * ret = upb_gmalloc(sizeof(*ret));
  10118. ret->ptr = upb_gstrdup(str);
  10119. ret->len = strlen(str);
  10120. upb_handlers_addcleanup(h, ret, freestrpc);
  10121. return ret;
  10122. }
  10123. /* ------------ JSON string printing: values, maps, arrays ------------------ */
  10124. static void print_data(
  10125. upb_json_printer *p, const char *buf, unsigned int len) {
  10126. /* TODO: Will need to change if we support pushback from the sink. */
  10127. size_t n = upb_bytessink_putbuf(p->output_, p->subc_, buf, len, NULL);
  10128. UPB_ASSERT(n == len);
  10129. }
  10130. static void print_comma(upb_json_printer *p) {
  10131. if (!p->first_elem_[p->depth_]) {
  10132. print_data(p, ",", 1);
  10133. }
  10134. p->first_elem_[p->depth_] = false;
  10135. }
  10136. /* Helpers that print properly formatted elements to the JSON output stream. */
  10137. /* Used for escaping control chars in strings. */
  10138. static const char kControlCharLimit = 0x20;
  10139. UPB_INLINE bool is_json_escaped(char c) {
  10140. /* See RFC 4627. */
  10141. unsigned char uc = (unsigned char)c;
  10142. return uc < kControlCharLimit || uc == '"' || uc == '\\';
  10143. }
  10144. UPB_INLINE const char* json_nice_escape(char c) {
  10145. switch (c) {
  10146. case '"': return "\\\"";
  10147. case '\\': return "\\\\";
  10148. case '\b': return "\\b";
  10149. case '\f': return "\\f";
  10150. case '\n': return "\\n";
  10151. case '\r': return "\\r";
  10152. case '\t': return "\\t";
  10153. default: return NULL;
  10154. }
  10155. }
  10156. /* Write a properly escaped string chunk. The surrounding quotes are *not*
  10157. * printed; this is so that the caller has the option of emitting the string
  10158. * content in chunks. */
  10159. static void putstring(upb_json_printer *p, const char *buf, unsigned int len) {
  10160. const char* unescaped_run = NULL;
  10161. unsigned int i;
  10162. for (i = 0; i < len; i++) {
  10163. char c = buf[i];
  10164. /* Handle escaping. */
  10165. if (is_json_escaped(c)) {
  10166. /* Use a "nice" escape, like \n, if one exists for this character. */
  10167. const char* escape = json_nice_escape(c);
  10168. /* If we don't have a specific 'nice' escape code, use a \uXXXX-style
  10169. * escape. */
  10170. char escape_buf[8];
  10171. if (!escape) {
  10172. unsigned char byte = (unsigned char)c;
  10173. _upb_snprintf(escape_buf, sizeof(escape_buf), "\\u%04x", (int)byte);
  10174. escape = escape_buf;
  10175. }
  10176. /* N.B. that we assume that the input encoding is equal to the output
  10177. * encoding (both UTF-8 for now), so for chars >= 0x20 and != \, ", we
  10178. * can simply pass the bytes through. */
  10179. /* If there's a current run of unescaped chars, print that run first. */
  10180. if (unescaped_run) {
  10181. print_data(p, unescaped_run, &buf[i] - unescaped_run);
  10182. unescaped_run = NULL;
  10183. }
  10184. /* Then print the escape code. */
  10185. print_data(p, escape, strlen(escape));
  10186. } else {
  10187. /* Add to the current unescaped run of characters. */
  10188. if (unescaped_run == NULL) {
  10189. unescaped_run = &buf[i];
  10190. }
  10191. }
  10192. }
  10193. /* If the string ended in a run of unescaped characters, print that last run. */
  10194. if (unescaped_run) {
  10195. print_data(p, unescaped_run, &buf[len] - unescaped_run);
  10196. }
  10197. }
  10198. #define CHKLENGTH(x) if (!(x)) return -1;
  10199. /* Helpers that format floating point values according to our custom formats.
  10200. * Right now we use %.8g and %.17g for float/double, respectively, to match
  10201. * proto2::util::JsonFormat's defaults. May want to change this later. */
  10202. const char neginf[] = "\"-Infinity\"";
  10203. const char inf[] = "\"Infinity\"";
  10204. static size_t fmt_double(double val, char* buf, size_t length) {
  10205. if (val == UPB_INFINITY) {
  10206. CHKLENGTH(length >= strlen(inf));
  10207. strcpy(buf, inf);
  10208. return strlen(inf);
  10209. } else if (val == -UPB_INFINITY) {
  10210. CHKLENGTH(length >= strlen(neginf));
  10211. strcpy(buf, neginf);
  10212. return strlen(neginf);
  10213. } else {
  10214. size_t n = _upb_snprintf(buf, length, "%.17g", val);
  10215. CHKLENGTH(n > 0 && n < length);
  10216. return n;
  10217. }
  10218. }
  10219. static size_t fmt_float(float val, char* buf, size_t length) {
  10220. size_t n = _upb_snprintf(buf, length, "%.8g", val);
  10221. CHKLENGTH(n > 0 && n < length);
  10222. return n;
  10223. }
  10224. static size_t fmt_bool(bool val, char* buf, size_t length) {
  10225. size_t n = _upb_snprintf(buf, length, "%s", (val ? "true" : "false"));
  10226. CHKLENGTH(n > 0 && n < length);
  10227. return n;
  10228. }
  10229. static size_t fmt_int64_as_number(long long val, char* buf, size_t length) {
  10230. size_t n = _upb_snprintf(buf, length, "%lld", val);
  10231. CHKLENGTH(n > 0 && n < length);
  10232. return n;
  10233. }
  10234. static size_t fmt_uint64_as_number(
  10235. unsigned long long val, char* buf, size_t length) {
  10236. size_t n = _upb_snprintf(buf, length, "%llu", val);
  10237. CHKLENGTH(n > 0 && n < length);
  10238. return n;
  10239. }
  10240. static size_t fmt_int64_as_string(long long val, char* buf, size_t length) {
  10241. size_t n = _upb_snprintf(buf, length, "\"%lld\"", val);
  10242. CHKLENGTH(n > 0 && n < length);
  10243. return n;
  10244. }
  10245. static size_t fmt_uint64_as_string(
  10246. unsigned long long val, char* buf, size_t length) {
  10247. size_t n = _upb_snprintf(buf, length, "\"%llu\"", val);
  10248. CHKLENGTH(n > 0 && n < length);
  10249. return n;
  10250. }
  10251. /* Print a map key given a field name. Called by scalar field handlers and by
  10252. * startseq for repeated fields. */
  10253. static bool putkey(void *closure, const void *handler_data) {
  10254. upb_json_printer *p = closure;
  10255. const strpc *key = handler_data;
  10256. print_comma(p);
  10257. print_data(p, "\"", 1);
  10258. putstring(p, key->ptr, key->len);
  10259. print_data(p, "\":", 2);
  10260. return true;
  10261. }
  10262. #define CHKFMT(val) if ((val) == (size_t)-1) return false;
  10263. #define CHK(val) if (!(val)) return false;
  10264. #define TYPE_HANDLERS(type, fmt_func) \
  10265. static bool put##type(void *closure, const void *handler_data, type val) { \
  10266. upb_json_printer *p = closure; \
  10267. char data[64]; \
  10268. size_t length = fmt_func(val, data, sizeof(data)); \
  10269. UPB_UNUSED(handler_data); \
  10270. CHKFMT(length); \
  10271. print_data(p, data, length); \
  10272. return true; \
  10273. } \
  10274. static bool scalar_##type(void *closure, const void *handler_data, \
  10275. type val) { \
  10276. CHK(putkey(closure, handler_data)); \
  10277. CHK(put##type(closure, handler_data, val)); \
  10278. return true; \
  10279. } \
  10280. static bool repeated_##type(void *closure, const void *handler_data, \
  10281. type val) { \
  10282. upb_json_printer *p = closure; \
  10283. print_comma(p); \
  10284. CHK(put##type(closure, handler_data, val)); \
  10285. return true; \
  10286. }
  10287. #define TYPE_HANDLERS_MAPKEY(type, fmt_func) \
  10288. static bool putmapkey_##type(void *closure, const void *handler_data, \
  10289. type val) { \
  10290. upb_json_printer *p = closure; \
  10291. char data[64]; \
  10292. size_t length = fmt_func(val, data, sizeof(data)); \
  10293. UPB_UNUSED(handler_data); \
  10294. print_data(p, "\"", 1); \
  10295. print_data(p, data, length); \
  10296. print_data(p, "\":", 2); \
  10297. return true; \
  10298. }
  10299. TYPE_HANDLERS(double, fmt_double)
  10300. TYPE_HANDLERS(float, fmt_float)
  10301. TYPE_HANDLERS(bool, fmt_bool)
  10302. TYPE_HANDLERS(int32_t, fmt_int64_as_number)
  10303. TYPE_HANDLERS(uint32_t, fmt_int64_as_number)
  10304. TYPE_HANDLERS(int64_t, fmt_int64_as_string)
  10305. TYPE_HANDLERS(uint64_t, fmt_uint64_as_string)
  10306. /* double and float are not allowed to be map keys. */
  10307. TYPE_HANDLERS_MAPKEY(bool, fmt_bool)
  10308. TYPE_HANDLERS_MAPKEY(int32_t, fmt_int64_as_number)
  10309. TYPE_HANDLERS_MAPKEY(uint32_t, fmt_int64_as_number)
  10310. TYPE_HANDLERS_MAPKEY(int64_t, fmt_int64_as_number)
  10311. TYPE_HANDLERS_MAPKEY(uint64_t, fmt_uint64_as_number)
  10312. #undef TYPE_HANDLERS
  10313. #undef TYPE_HANDLERS_MAPKEY
  10314. typedef struct {
  10315. void *keyname;
  10316. const upb_enumdef *enumdef;
  10317. } EnumHandlerData;
  10318. static bool scalar_enum(void *closure, const void *handler_data,
  10319. int32_t val) {
  10320. const EnumHandlerData *hd = handler_data;
  10321. upb_json_printer *p = closure;
  10322. const char *symbolic_name;
  10323. CHK(putkey(closure, hd->keyname));
  10324. symbolic_name = upb_enumdef_iton(hd->enumdef, val);
  10325. if (symbolic_name) {
  10326. print_data(p, "\"", 1);
  10327. putstring(p, symbolic_name, strlen(symbolic_name));
  10328. print_data(p, "\"", 1);
  10329. } else {
  10330. putint32_t(closure, NULL, val);
  10331. }
  10332. return true;
  10333. }
  10334. static void print_enum_symbolic_name(upb_json_printer *p,
  10335. const upb_enumdef *def,
  10336. int32_t val) {
  10337. const char *symbolic_name = upb_enumdef_iton(def, val);
  10338. if (symbolic_name) {
  10339. print_data(p, "\"", 1);
  10340. putstring(p, symbolic_name, strlen(symbolic_name));
  10341. print_data(p, "\"", 1);
  10342. } else {
  10343. putint32_t(p, NULL, val);
  10344. }
  10345. }
  10346. static bool repeated_enum(void *closure, const void *handler_data,
  10347. int32_t val) {
  10348. const EnumHandlerData *hd = handler_data;
  10349. upb_json_printer *p = closure;
  10350. print_comma(p);
  10351. print_enum_symbolic_name(p, hd->enumdef, val);
  10352. return true;
  10353. }
  10354. static bool mapvalue_enum(void *closure, const void *handler_data,
  10355. int32_t val) {
  10356. const EnumHandlerData *hd = handler_data;
  10357. upb_json_printer *p = closure;
  10358. print_enum_symbolic_name(p, hd->enumdef, val);
  10359. return true;
  10360. }
  10361. static void *scalar_startsubmsg(void *closure, const void *handler_data) {
  10362. return putkey(closure, handler_data) ? closure : UPB_BREAK;
  10363. }
  10364. static void *repeated_startsubmsg(void *closure, const void *handler_data) {
  10365. upb_json_printer *p = closure;
  10366. UPB_UNUSED(handler_data);
  10367. print_comma(p);
  10368. return closure;
  10369. }
  10370. static void start_frame(upb_json_printer *p) {
  10371. p->depth_++;
  10372. p->first_elem_[p->depth_] = true;
  10373. print_data(p, "{", 1);
  10374. }
  10375. static void end_frame(upb_json_printer *p) {
  10376. print_data(p, "}", 1);
  10377. p->depth_--;
  10378. }
  10379. static bool printer_startmsg(void *closure, const void *handler_data) {
  10380. upb_json_printer *p = closure;
  10381. UPB_UNUSED(handler_data);
  10382. if (p->depth_ == 0) {
  10383. upb_bytessink_start(p->output_, 0, &p->subc_);
  10384. }
  10385. start_frame(p);
  10386. return true;
  10387. }
  10388. static bool printer_endmsg(void *closure, const void *handler_data, upb_status *s) {
  10389. upb_json_printer *p = closure;
  10390. UPB_UNUSED(handler_data);
  10391. UPB_UNUSED(s);
  10392. end_frame(p);
  10393. if (p->depth_ == 0) {
  10394. upb_bytessink_end(p->output_);
  10395. }
  10396. return true;
  10397. }
  10398. static void *startseq(void *closure, const void *handler_data) {
  10399. upb_json_printer *p = closure;
  10400. CHK(putkey(closure, handler_data));
  10401. p->depth_++;
  10402. p->first_elem_[p->depth_] = true;
  10403. print_data(p, "[", 1);
  10404. return closure;
  10405. }
  10406. static bool endseq(void *closure, const void *handler_data) {
  10407. upb_json_printer *p = closure;
  10408. UPB_UNUSED(handler_data);
  10409. print_data(p, "]", 1);
  10410. p->depth_--;
  10411. return true;
  10412. }
  10413. static void *startmap(void *closure, const void *handler_data) {
  10414. upb_json_printer *p = closure;
  10415. CHK(putkey(closure, handler_data));
  10416. p->depth_++;
  10417. p->first_elem_[p->depth_] = true;
  10418. print_data(p, "{", 1);
  10419. return closure;
  10420. }
  10421. static bool endmap(void *closure, const void *handler_data) {
  10422. upb_json_printer *p = closure;
  10423. UPB_UNUSED(handler_data);
  10424. print_data(p, "}", 1);
  10425. p->depth_--;
  10426. return true;
  10427. }
  10428. static size_t putstr(void *closure, const void *handler_data, const char *str,
  10429. size_t len, const upb_bufhandle *handle) {
  10430. upb_json_printer *p = closure;
  10431. UPB_UNUSED(handler_data);
  10432. UPB_UNUSED(handle);
  10433. putstring(p, str, len);
  10434. return len;
  10435. }
  10436. /* This has to Base64 encode the bytes, because JSON has no "bytes" type. */
  10437. static size_t putbytes(void *closure, const void *handler_data, const char *str,
  10438. size_t len, const upb_bufhandle *handle) {
  10439. upb_json_printer *p = closure;
  10440. /* This is the regular base64, not the "web-safe" version. */
  10441. static const char base64[] =
  10442. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  10443. /* Base64-encode. */
  10444. char data[16000];
  10445. const char *limit = data + sizeof(data);
  10446. const unsigned char *from = (const unsigned char*)str;
  10447. char *to = data;
  10448. size_t remaining = len;
  10449. size_t bytes;
  10450. UPB_UNUSED(handler_data);
  10451. UPB_UNUSED(handle);
  10452. print_data(p, "\"", 1);
  10453. while (remaining > 2) {
  10454. if (limit - to < 4) {
  10455. bytes = to - data;
  10456. putstring(p, data, bytes);
  10457. to = data;
  10458. }
  10459. to[0] = base64[from[0] >> 2];
  10460. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  10461. to[2] = base64[((from[1] & 0xf) << 2) | (from[2] >> 6)];
  10462. to[3] = base64[from[2] & 0x3f];
  10463. remaining -= 3;
  10464. to += 4;
  10465. from += 3;
  10466. }
  10467. switch (remaining) {
  10468. case 2:
  10469. to[0] = base64[from[0] >> 2];
  10470. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  10471. to[2] = base64[(from[1] & 0xf) << 2];
  10472. to[3] = '=';
  10473. to += 4;
  10474. from += 2;
  10475. break;
  10476. case 1:
  10477. to[0] = base64[from[0] >> 2];
  10478. to[1] = base64[((from[0] & 0x3) << 4)];
  10479. to[2] = '=';
  10480. to[3] = '=';
  10481. to += 4;
  10482. from += 1;
  10483. break;
  10484. }
  10485. bytes = to - data;
  10486. putstring(p, data, bytes);
  10487. print_data(p, "\"", 1);
  10488. return len;
  10489. }
  10490. static void *scalar_startstr(void *closure, const void *handler_data,
  10491. size_t size_hint) {
  10492. upb_json_printer *p = closure;
  10493. UPB_UNUSED(handler_data);
  10494. UPB_UNUSED(size_hint);
  10495. CHK(putkey(closure, handler_data));
  10496. print_data(p, "\"", 1);
  10497. return p;
  10498. }
  10499. static size_t scalar_str(void *closure, const void *handler_data,
  10500. const char *str, size_t len,
  10501. const upb_bufhandle *handle) {
  10502. CHK(putstr(closure, handler_data, str, len, handle));
  10503. return len;
  10504. }
  10505. static bool scalar_endstr(void *closure, const void *handler_data) {
  10506. upb_json_printer *p = closure;
  10507. UPB_UNUSED(handler_data);
  10508. print_data(p, "\"", 1);
  10509. return true;
  10510. }
  10511. static void *repeated_startstr(void *closure, const void *handler_data,
  10512. size_t size_hint) {
  10513. upb_json_printer *p = closure;
  10514. UPB_UNUSED(handler_data);
  10515. UPB_UNUSED(size_hint);
  10516. print_comma(p);
  10517. print_data(p, "\"", 1);
  10518. return p;
  10519. }
  10520. static size_t repeated_str(void *closure, const void *handler_data,
  10521. const char *str, size_t len,
  10522. const upb_bufhandle *handle) {
  10523. CHK(putstr(closure, handler_data, str, len, handle));
  10524. return len;
  10525. }
  10526. static bool repeated_endstr(void *closure, const void *handler_data) {
  10527. upb_json_printer *p = closure;
  10528. UPB_UNUSED(handler_data);
  10529. print_data(p, "\"", 1);
  10530. return true;
  10531. }
  10532. static void *mapkeyval_startstr(void *closure, const void *handler_data,
  10533. size_t size_hint) {
  10534. upb_json_printer *p = closure;
  10535. UPB_UNUSED(handler_data);
  10536. UPB_UNUSED(size_hint);
  10537. print_data(p, "\"", 1);
  10538. return p;
  10539. }
  10540. static size_t mapkey_str(void *closure, const void *handler_data,
  10541. const char *str, size_t len,
  10542. const upb_bufhandle *handle) {
  10543. CHK(putstr(closure, handler_data, str, len, handle));
  10544. return len;
  10545. }
  10546. static bool mapkey_endstr(void *closure, const void *handler_data) {
  10547. upb_json_printer *p = closure;
  10548. UPB_UNUSED(handler_data);
  10549. print_data(p, "\":", 2);
  10550. return true;
  10551. }
  10552. static bool mapvalue_endstr(void *closure, const void *handler_data) {
  10553. upb_json_printer *p = closure;
  10554. UPB_UNUSED(handler_data);
  10555. print_data(p, "\"", 1);
  10556. return true;
  10557. }
  10558. static size_t scalar_bytes(void *closure, const void *handler_data,
  10559. const char *str, size_t len,
  10560. const upb_bufhandle *handle) {
  10561. CHK(putkey(closure, handler_data));
  10562. CHK(putbytes(closure, handler_data, str, len, handle));
  10563. return len;
  10564. }
  10565. static size_t repeated_bytes(void *closure, const void *handler_data,
  10566. const char *str, size_t len,
  10567. const upb_bufhandle *handle) {
  10568. upb_json_printer *p = closure;
  10569. print_comma(p);
  10570. CHK(putbytes(closure, handler_data, str, len, handle));
  10571. return len;
  10572. }
  10573. static size_t mapkey_bytes(void *closure, const void *handler_data,
  10574. const char *str, size_t len,
  10575. const upb_bufhandle *handle) {
  10576. upb_json_printer *p = closure;
  10577. CHK(putbytes(closure, handler_data, str, len, handle));
  10578. print_data(p, ":", 1);
  10579. return len;
  10580. }
  10581. static void set_enum_hd(upb_handlers *h,
  10582. const upb_fielddef *f,
  10583. bool preserve_fieldnames,
  10584. upb_handlerattr *attr) {
  10585. EnumHandlerData *hd = upb_gmalloc(sizeof(EnumHandlerData));
  10586. hd->enumdef = upb_fielddef_enumsubdef(f);
  10587. hd->keyname = newstrpc(h, f, preserve_fieldnames);
  10588. upb_handlers_addcleanup(h, hd, upb_gfree);
  10589. attr->handler_data = hd;
  10590. }
  10591. /* Set up handlers for a mapentry submessage (i.e., an individual key/value pair
  10592. * in a map).
  10593. *
  10594. * TODO: Handle missing key, missing value, out-of-order key/value, or repeated
  10595. * key or value cases properly. The right way to do this is to allocate a
  10596. * temporary structure at the start of a mapentry submessage, store key and
  10597. * value data in it as key and value handlers are called, and then print the
  10598. * key/value pair once at the end of the submessage. If we don't do this, we
  10599. * should at least detect the case and throw an error. However, so far all of
  10600. * our sources that emit mapentry messages do so canonically (with one key
  10601. * field, and then one value field), so this is not a pressing concern at the
  10602. * moment. */
  10603. void printer_sethandlers_mapentry(const void *closure, bool preserve_fieldnames,
  10604. upb_handlers *h) {
  10605. const upb_msgdef *md = upb_handlers_msgdef(h);
  10606. /* A mapentry message is printed simply as '"key": value'. Rather than
  10607. * special-case key and value for every type below, we just handle both
  10608. * fields explicitly here. */
  10609. const upb_fielddef* key_field = upb_msgdef_itof(md, UPB_MAPENTRY_KEY);
  10610. const upb_fielddef* value_field = upb_msgdef_itof(md, UPB_MAPENTRY_VALUE);
  10611. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  10612. UPB_UNUSED(closure);
  10613. switch (upb_fielddef_type(key_field)) {
  10614. case UPB_TYPE_INT32:
  10615. upb_handlers_setint32(h, key_field, putmapkey_int32_t, &empty_attr);
  10616. break;
  10617. case UPB_TYPE_INT64:
  10618. upb_handlers_setint64(h, key_field, putmapkey_int64_t, &empty_attr);
  10619. break;
  10620. case UPB_TYPE_UINT32:
  10621. upb_handlers_setuint32(h, key_field, putmapkey_uint32_t, &empty_attr);
  10622. break;
  10623. case UPB_TYPE_UINT64:
  10624. upb_handlers_setuint64(h, key_field, putmapkey_uint64_t, &empty_attr);
  10625. break;
  10626. case UPB_TYPE_BOOL:
  10627. upb_handlers_setbool(h, key_field, putmapkey_bool, &empty_attr);
  10628. break;
  10629. case UPB_TYPE_STRING:
  10630. upb_handlers_setstartstr(h, key_field, mapkeyval_startstr, &empty_attr);
  10631. upb_handlers_setstring(h, key_field, mapkey_str, &empty_attr);
  10632. upb_handlers_setendstr(h, key_field, mapkey_endstr, &empty_attr);
  10633. break;
  10634. case UPB_TYPE_BYTES:
  10635. upb_handlers_setstring(h, key_field, mapkey_bytes, &empty_attr);
  10636. break;
  10637. default:
  10638. UPB_ASSERT(false);
  10639. break;
  10640. }
  10641. switch (upb_fielddef_type(value_field)) {
  10642. case UPB_TYPE_INT32:
  10643. upb_handlers_setint32(h, value_field, putint32_t, &empty_attr);
  10644. break;
  10645. case UPB_TYPE_INT64:
  10646. upb_handlers_setint64(h, value_field, putint64_t, &empty_attr);
  10647. break;
  10648. case UPB_TYPE_UINT32:
  10649. upb_handlers_setuint32(h, value_field, putuint32_t, &empty_attr);
  10650. break;
  10651. case UPB_TYPE_UINT64:
  10652. upb_handlers_setuint64(h, value_field, putuint64_t, &empty_attr);
  10653. break;
  10654. case UPB_TYPE_BOOL:
  10655. upb_handlers_setbool(h, value_field, putbool, &empty_attr);
  10656. break;
  10657. case UPB_TYPE_FLOAT:
  10658. upb_handlers_setfloat(h, value_field, putfloat, &empty_attr);
  10659. break;
  10660. case UPB_TYPE_DOUBLE:
  10661. upb_handlers_setdouble(h, value_field, putdouble, &empty_attr);
  10662. break;
  10663. case UPB_TYPE_STRING:
  10664. upb_handlers_setstartstr(h, value_field, mapkeyval_startstr, &empty_attr);
  10665. upb_handlers_setstring(h, value_field, putstr, &empty_attr);
  10666. upb_handlers_setendstr(h, value_field, mapvalue_endstr, &empty_attr);
  10667. break;
  10668. case UPB_TYPE_BYTES:
  10669. upb_handlers_setstring(h, value_field, putbytes, &empty_attr);
  10670. break;
  10671. case UPB_TYPE_ENUM: {
  10672. upb_handlerattr enum_attr = UPB_HANDLERATTR_INIT;
  10673. set_enum_hd(h, value_field, preserve_fieldnames, &enum_attr);
  10674. upb_handlers_setint32(h, value_field, mapvalue_enum, &enum_attr);
  10675. break;
  10676. }
  10677. case UPB_TYPE_MESSAGE:
  10678. /* No handler necessary -- the submsg handlers will print the message
  10679. * as appropriate. */
  10680. break;
  10681. }
  10682. }
  10683. static bool putseconds(void *closure, const void *handler_data,
  10684. int64_t seconds) {
  10685. upb_json_printer *p = closure;
  10686. p->seconds = seconds;
  10687. UPB_UNUSED(handler_data);
  10688. return true;
  10689. }
  10690. static bool putnanos(void *closure, const void *handler_data,
  10691. int32_t nanos) {
  10692. upb_json_printer *p = closure;
  10693. p->nanos = nanos;
  10694. UPB_UNUSED(handler_data);
  10695. return true;
  10696. }
  10697. static void *scalar_startstr_nokey(void *closure, const void *handler_data,
  10698. size_t size_hint) {
  10699. upb_json_printer *p = closure;
  10700. UPB_UNUSED(handler_data);
  10701. UPB_UNUSED(size_hint);
  10702. print_data(p, "\"", 1);
  10703. return p;
  10704. }
  10705. static size_t putstr_nokey(void *closure, const void *handler_data,
  10706. const char *str, size_t len,
  10707. const upb_bufhandle *handle) {
  10708. upb_json_printer *p = closure;
  10709. UPB_UNUSED(handler_data);
  10710. UPB_UNUSED(handle);
  10711. print_data(p, "\"", 1);
  10712. putstring(p, str, len);
  10713. print_data(p, "\"", 1);
  10714. return len + 2;
  10715. }
  10716. static void *startseq_nokey(void *closure, const void *handler_data) {
  10717. upb_json_printer *p = closure;
  10718. UPB_UNUSED(handler_data);
  10719. p->depth_++;
  10720. p->first_elem_[p->depth_] = true;
  10721. print_data(p, "[", 1);
  10722. return closure;
  10723. }
  10724. static void *startseq_fieldmask(void *closure, const void *handler_data) {
  10725. upb_json_printer *p = closure;
  10726. UPB_UNUSED(handler_data);
  10727. p->depth_++;
  10728. p->first_elem_[p->depth_] = true;
  10729. return closure;
  10730. }
  10731. static bool endseq_fieldmask(void *closure, const void *handler_data) {
  10732. upb_json_printer *p = closure;
  10733. UPB_UNUSED(handler_data);
  10734. p->depth_--;
  10735. return true;
  10736. }
  10737. static void *repeated_startstr_fieldmask(
  10738. void *closure, const void *handler_data,
  10739. size_t size_hint) {
  10740. upb_json_printer *p = closure;
  10741. UPB_UNUSED(handler_data);
  10742. UPB_UNUSED(size_hint);
  10743. print_comma(p);
  10744. return p;
  10745. }
  10746. static size_t repeated_str_fieldmask(
  10747. void *closure, const void *handler_data,
  10748. const char *str, size_t len,
  10749. const upb_bufhandle *handle) {
  10750. const char* limit = str + len;
  10751. bool upper = false;
  10752. size_t result_len = 0;
  10753. for (; str < limit; str++) {
  10754. if (*str == '_') {
  10755. upper = true;
  10756. continue;
  10757. }
  10758. if (upper && *str >= 'a' && *str <= 'z') {
  10759. char upper_char = toupper(*str);
  10760. CHK(putstr(closure, handler_data, &upper_char, 1, handle));
  10761. } else {
  10762. CHK(putstr(closure, handler_data, str, 1, handle));
  10763. }
  10764. upper = false;
  10765. result_len++;
  10766. }
  10767. return result_len;
  10768. }
  10769. static void *startmap_nokey(void *closure, const void *handler_data) {
  10770. upb_json_printer *p = closure;
  10771. UPB_UNUSED(handler_data);
  10772. p->depth_++;
  10773. p->first_elem_[p->depth_] = true;
  10774. print_data(p, "{", 1);
  10775. return closure;
  10776. }
  10777. static bool putnull(void *closure, const void *handler_data,
  10778. int32_t null) {
  10779. upb_json_printer *p = closure;
  10780. print_data(p, "null", 4);
  10781. UPB_UNUSED(handler_data);
  10782. UPB_UNUSED(null);
  10783. return true;
  10784. }
  10785. static bool printer_startdurationmsg(void *closure, const void *handler_data) {
  10786. upb_json_printer *p = closure;
  10787. UPB_UNUSED(handler_data);
  10788. if (p->depth_ == 0) {
  10789. upb_bytessink_start(p->output_, 0, &p->subc_);
  10790. }
  10791. return true;
  10792. }
  10793. #define UPB_DURATION_MAX_JSON_LEN 23
  10794. #define UPB_DURATION_MAX_NANO_LEN 9
  10795. static bool printer_enddurationmsg(void *closure, const void *handler_data,
  10796. upb_status *s) {
  10797. upb_json_printer *p = closure;
  10798. char buffer[UPB_DURATION_MAX_JSON_LEN];
  10799. size_t base_len;
  10800. size_t curr;
  10801. size_t i;
  10802. memset(buffer, 0, UPB_DURATION_MAX_JSON_LEN);
  10803. if (p->seconds < -315576000000) {
  10804. upb_status_seterrf(s, "error parsing duration: "
  10805. "minimum acceptable value is "
  10806. "-315576000000");
  10807. return false;
  10808. }
  10809. if (p->seconds > 315576000000) {
  10810. upb_status_seterrf(s, "error serializing duration: "
  10811. "maximum acceptable value is "
  10812. "315576000000");
  10813. return false;
  10814. }
  10815. _upb_snprintf(buffer, sizeof(buffer), "%ld", (long)p->seconds);
  10816. base_len = strlen(buffer);
  10817. if (p->nanos != 0) {
  10818. char nanos_buffer[UPB_DURATION_MAX_NANO_LEN + 3];
  10819. _upb_snprintf(nanos_buffer, sizeof(nanos_buffer), "%.9f",
  10820. p->nanos / 1000000000.0);
  10821. /* Remove trailing 0. */
  10822. for (i = UPB_DURATION_MAX_NANO_LEN + 2;
  10823. nanos_buffer[i] == '0'; i--) {
  10824. nanos_buffer[i] = 0;
  10825. }
  10826. strcpy(buffer + base_len, nanos_buffer + 1);
  10827. }
  10828. curr = strlen(buffer);
  10829. strcpy(buffer + curr, "s");
  10830. p->seconds = 0;
  10831. p->nanos = 0;
  10832. print_data(p, "\"", 1);
  10833. print_data(p, buffer, strlen(buffer));
  10834. print_data(p, "\"", 1);
  10835. if (p->depth_ == 0) {
  10836. upb_bytessink_end(p->output_);
  10837. }
  10838. UPB_UNUSED(handler_data);
  10839. return true;
  10840. }
  10841. static bool printer_starttimestampmsg(void *closure, const void *handler_data) {
  10842. upb_json_printer *p = closure;
  10843. UPB_UNUSED(handler_data);
  10844. if (p->depth_ == 0) {
  10845. upb_bytessink_start(p->output_, 0, &p->subc_);
  10846. }
  10847. return true;
  10848. }
  10849. #define UPB_TIMESTAMP_MAX_JSON_LEN 31
  10850. #define UPB_TIMESTAMP_BEFORE_NANO_LEN 19
  10851. #define UPB_TIMESTAMP_MAX_NANO_LEN 9
  10852. static bool printer_endtimestampmsg(void *closure, const void *handler_data,
  10853. upb_status *s) {
  10854. upb_json_printer *p = closure;
  10855. char buffer[UPB_TIMESTAMP_MAX_JSON_LEN];
  10856. time_t time = p->seconds;
  10857. size_t curr;
  10858. size_t i;
  10859. size_t year_length =
  10860. strftime(buffer, UPB_TIMESTAMP_MAX_JSON_LEN, "%Y", gmtime(&time));
  10861. if (p->seconds < -62135596800) {
  10862. upb_status_seterrf(s, "error parsing timestamp: "
  10863. "minimum acceptable value is "
  10864. "0001-01-01T00:00:00Z");
  10865. return false;
  10866. }
  10867. if (p->seconds > 253402300799) {
  10868. upb_status_seterrf(s, "error parsing timestamp: "
  10869. "maximum acceptable value is "
  10870. "9999-12-31T23:59:59Z");
  10871. return false;
  10872. }
  10873. /* strftime doesn't guarantee 4 digits for year. Prepend 0 by ourselves. */
  10874. for (i = 0; i < 4 - year_length; i++) {
  10875. buffer[i] = '0';
  10876. }
  10877. strftime(buffer + (4 - year_length), UPB_TIMESTAMP_MAX_JSON_LEN,
  10878. "%Y-%m-%dT%H:%M:%S", gmtime(&time));
  10879. if (p->nanos != 0) {
  10880. char nanos_buffer[UPB_TIMESTAMP_MAX_NANO_LEN + 3];
  10881. _upb_snprintf(nanos_buffer, sizeof(nanos_buffer), "%.9f",
  10882. p->nanos / 1000000000.0);
  10883. /* Remove trailing 0. */
  10884. for (i = UPB_TIMESTAMP_MAX_NANO_LEN + 2;
  10885. nanos_buffer[i] == '0'; i--) {
  10886. nanos_buffer[i] = 0;
  10887. }
  10888. strcpy(buffer + UPB_TIMESTAMP_BEFORE_NANO_LEN, nanos_buffer + 1);
  10889. }
  10890. curr = strlen(buffer);
  10891. strcpy(buffer + curr, "Z");
  10892. p->seconds = 0;
  10893. p->nanos = 0;
  10894. print_data(p, "\"", 1);
  10895. print_data(p, buffer, strlen(buffer));
  10896. print_data(p, "\"", 1);
  10897. if (p->depth_ == 0) {
  10898. upb_bytessink_end(p->output_);
  10899. }
  10900. UPB_UNUSED(handler_data);
  10901. UPB_UNUSED(s);
  10902. return true;
  10903. }
  10904. static bool printer_startmsg_noframe(void *closure, const void *handler_data) {
  10905. upb_json_printer *p = closure;
  10906. UPB_UNUSED(handler_data);
  10907. if (p->depth_ == 0) {
  10908. upb_bytessink_start(p->output_, 0, &p->subc_);
  10909. }
  10910. return true;
  10911. }
  10912. static bool printer_endmsg_noframe(
  10913. void *closure, const void *handler_data, upb_status *s) {
  10914. upb_json_printer *p = closure;
  10915. UPB_UNUSED(handler_data);
  10916. UPB_UNUSED(s);
  10917. if (p->depth_ == 0) {
  10918. upb_bytessink_end(p->output_);
  10919. }
  10920. return true;
  10921. }
  10922. static bool printer_startmsg_fieldmask(
  10923. void *closure, const void *handler_data) {
  10924. upb_json_printer *p = closure;
  10925. UPB_UNUSED(handler_data);
  10926. if (p->depth_ == 0) {
  10927. upb_bytessink_start(p->output_, 0, &p->subc_);
  10928. }
  10929. print_data(p, "\"", 1);
  10930. return true;
  10931. }
  10932. static bool printer_endmsg_fieldmask(
  10933. void *closure, const void *handler_data, upb_status *s) {
  10934. upb_json_printer *p = closure;
  10935. UPB_UNUSED(handler_data);
  10936. UPB_UNUSED(s);
  10937. print_data(p, "\"", 1);
  10938. if (p->depth_ == 0) {
  10939. upb_bytessink_end(p->output_);
  10940. }
  10941. return true;
  10942. }
  10943. static void *scalar_startstr_onlykey(
  10944. void *closure, const void *handler_data, size_t size_hint) {
  10945. upb_json_printer *p = closure;
  10946. UPB_UNUSED(size_hint);
  10947. CHK(putkey(closure, handler_data));
  10948. return p;
  10949. }
  10950. /* Set up handlers for an Any submessage. */
  10951. void printer_sethandlers_any(const void *closure, upb_handlers *h) {
  10952. const upb_msgdef *md = upb_handlers_msgdef(h);
  10953. const upb_fielddef* type_field = upb_msgdef_itof(md, UPB_ANY_TYPE);
  10954. const upb_fielddef* value_field = upb_msgdef_itof(md, UPB_ANY_VALUE);
  10955. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  10956. /* type_url's json name is "@type" */
  10957. upb_handlerattr type_name_attr = UPB_HANDLERATTR_INIT;
  10958. upb_handlerattr value_name_attr = UPB_HANDLERATTR_INIT;
  10959. strpc *type_url_json_name = newstrpc_str(h, "@type");
  10960. strpc *value_json_name = newstrpc_str(h, "value");
  10961. type_name_attr.handler_data = type_url_json_name;
  10962. value_name_attr.handler_data = value_json_name;
  10963. /* Set up handlers. */
  10964. upb_handlers_setstartmsg(h, printer_startmsg, &empty_attr);
  10965. upb_handlers_setendmsg(h, printer_endmsg, &empty_attr);
  10966. upb_handlers_setstartstr(h, type_field, scalar_startstr, &type_name_attr);
  10967. upb_handlers_setstring(h, type_field, scalar_str, &empty_attr);
  10968. upb_handlers_setendstr(h, type_field, scalar_endstr, &empty_attr);
  10969. /* This is not the full and correct JSON encoding for the Any value field. It
  10970. * requires further processing by the wrapper code based on the type URL.
  10971. */
  10972. upb_handlers_setstartstr(h, value_field, scalar_startstr_onlykey,
  10973. &value_name_attr);
  10974. UPB_UNUSED(closure);
  10975. }
  10976. /* Set up handlers for a fieldmask submessage. */
  10977. void printer_sethandlers_fieldmask(const void *closure, upb_handlers *h) {
  10978. const upb_msgdef *md = upb_handlers_msgdef(h);
  10979. const upb_fielddef* f = upb_msgdef_itof(md, 1);
  10980. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  10981. upb_handlers_setstartseq(h, f, startseq_fieldmask, &empty_attr);
  10982. upb_handlers_setendseq(h, f, endseq_fieldmask, &empty_attr);
  10983. upb_handlers_setstartmsg(h, printer_startmsg_fieldmask, &empty_attr);
  10984. upb_handlers_setendmsg(h, printer_endmsg_fieldmask, &empty_attr);
  10985. upb_handlers_setstartstr(h, f, repeated_startstr_fieldmask, &empty_attr);
  10986. upb_handlers_setstring(h, f, repeated_str_fieldmask, &empty_attr);
  10987. UPB_UNUSED(closure);
  10988. }
  10989. /* Set up handlers for a duration submessage. */
  10990. void printer_sethandlers_duration(const void *closure, upb_handlers *h) {
  10991. const upb_msgdef *md = upb_handlers_msgdef(h);
  10992. const upb_fielddef* seconds_field =
  10993. upb_msgdef_itof(md, UPB_DURATION_SECONDS);
  10994. const upb_fielddef* nanos_field =
  10995. upb_msgdef_itof(md, UPB_DURATION_NANOS);
  10996. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  10997. upb_handlers_setstartmsg(h, printer_startdurationmsg, &empty_attr);
  10998. upb_handlers_setint64(h, seconds_field, putseconds, &empty_attr);
  10999. upb_handlers_setint32(h, nanos_field, putnanos, &empty_attr);
  11000. upb_handlers_setendmsg(h, printer_enddurationmsg, &empty_attr);
  11001. UPB_UNUSED(closure);
  11002. }
  11003. /* Set up handlers for a timestamp submessage. Instead of printing fields
  11004. * separately, the json representation of timestamp follows RFC 3339 */
  11005. void printer_sethandlers_timestamp(const void *closure, upb_handlers *h) {
  11006. const upb_msgdef *md = upb_handlers_msgdef(h);
  11007. const upb_fielddef* seconds_field =
  11008. upb_msgdef_itof(md, UPB_TIMESTAMP_SECONDS);
  11009. const upb_fielddef* nanos_field =
  11010. upb_msgdef_itof(md, UPB_TIMESTAMP_NANOS);
  11011. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11012. upb_handlers_setstartmsg(h, printer_starttimestampmsg, &empty_attr);
  11013. upb_handlers_setint64(h, seconds_field, putseconds, &empty_attr);
  11014. upb_handlers_setint32(h, nanos_field, putnanos, &empty_attr);
  11015. upb_handlers_setendmsg(h, printer_endtimestampmsg, &empty_attr);
  11016. UPB_UNUSED(closure);
  11017. }
  11018. void printer_sethandlers_value(const void *closure, upb_handlers *h) {
  11019. const upb_msgdef *md = upb_handlers_msgdef(h);
  11020. upb_msg_field_iter i;
  11021. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11022. upb_handlers_setstartmsg(h, printer_startmsg_noframe, &empty_attr);
  11023. upb_handlers_setendmsg(h, printer_endmsg_noframe, &empty_attr);
  11024. upb_msg_field_begin(&i, md);
  11025. for(; !upb_msg_field_done(&i); upb_msg_field_next(&i)) {
  11026. const upb_fielddef *f = upb_msg_iter_field(&i);
  11027. switch (upb_fielddef_type(f)) {
  11028. case UPB_TYPE_ENUM:
  11029. upb_handlers_setint32(h, f, putnull, &empty_attr);
  11030. break;
  11031. case UPB_TYPE_DOUBLE:
  11032. upb_handlers_setdouble(h, f, putdouble, &empty_attr);
  11033. break;
  11034. case UPB_TYPE_STRING:
  11035. upb_handlers_setstartstr(h, f, scalar_startstr_nokey, &empty_attr);
  11036. upb_handlers_setstring(h, f, scalar_str, &empty_attr);
  11037. upb_handlers_setendstr(h, f, scalar_endstr, &empty_attr);
  11038. break;
  11039. case UPB_TYPE_BOOL:
  11040. upb_handlers_setbool(h, f, putbool, &empty_attr);
  11041. break;
  11042. case UPB_TYPE_MESSAGE:
  11043. break;
  11044. default:
  11045. UPB_ASSERT(false);
  11046. break;
  11047. }
  11048. }
  11049. UPB_UNUSED(closure);
  11050. }
  11051. #define WRAPPER_SETHANDLERS(wrapper, type, putmethod) \
  11052. void printer_sethandlers_##wrapper(const void *closure, upb_handlers *h) { \
  11053. const upb_msgdef *md = upb_handlers_msgdef(h); \
  11054. const upb_fielddef* f = upb_msgdef_itof(md, 1); \
  11055. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT; \
  11056. upb_handlers_setstartmsg(h, printer_startmsg_noframe, &empty_attr); \
  11057. upb_handlers_setendmsg(h, printer_endmsg_noframe, &empty_attr); \
  11058. upb_handlers_set##type(h, f, putmethod, &empty_attr); \
  11059. UPB_UNUSED(closure); \
  11060. }
  11061. WRAPPER_SETHANDLERS(doublevalue, double, putdouble)
  11062. WRAPPER_SETHANDLERS(floatvalue, float, putfloat)
  11063. WRAPPER_SETHANDLERS(int64value, int64, putint64_t)
  11064. WRAPPER_SETHANDLERS(uint64value, uint64, putuint64_t)
  11065. WRAPPER_SETHANDLERS(int32value, int32, putint32_t)
  11066. WRAPPER_SETHANDLERS(uint32value, uint32, putuint32_t)
  11067. WRAPPER_SETHANDLERS(boolvalue, bool, putbool)
  11068. WRAPPER_SETHANDLERS(stringvalue, string, putstr_nokey)
  11069. WRAPPER_SETHANDLERS(bytesvalue, string, putbytes)
  11070. #undef WRAPPER_SETHANDLERS
  11071. void printer_sethandlers_listvalue(const void *closure, upb_handlers *h) {
  11072. const upb_msgdef *md = upb_handlers_msgdef(h);
  11073. const upb_fielddef* f = upb_msgdef_itof(md, 1);
  11074. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11075. upb_handlers_setstartseq(h, f, startseq_nokey, &empty_attr);
  11076. upb_handlers_setendseq(h, f, endseq, &empty_attr);
  11077. upb_handlers_setstartmsg(h, printer_startmsg_noframe, &empty_attr);
  11078. upb_handlers_setendmsg(h, printer_endmsg_noframe, &empty_attr);
  11079. upb_handlers_setstartsubmsg(h, f, repeated_startsubmsg, &empty_attr);
  11080. UPB_UNUSED(closure);
  11081. }
  11082. void printer_sethandlers_structvalue(const void *closure, upb_handlers *h) {
  11083. const upb_msgdef *md = upb_handlers_msgdef(h);
  11084. const upb_fielddef* f = upb_msgdef_itof(md, 1);
  11085. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11086. upb_handlers_setstartseq(h, f, startmap_nokey, &empty_attr);
  11087. upb_handlers_setendseq(h, f, endmap, &empty_attr);
  11088. upb_handlers_setstartmsg(h, printer_startmsg_noframe, &empty_attr);
  11089. upb_handlers_setendmsg(h, printer_endmsg_noframe, &empty_attr);
  11090. upb_handlers_setstartsubmsg(h, f, repeated_startsubmsg, &empty_attr);
  11091. UPB_UNUSED(closure);
  11092. }
  11093. void printer_sethandlers(const void *closure, upb_handlers *h) {
  11094. const upb_msgdef *md = upb_handlers_msgdef(h);
  11095. bool is_mapentry = upb_msgdef_mapentry(md);
  11096. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  11097. upb_msg_field_iter i;
  11098. const upb_json_printercache *cache = closure;
  11099. const bool preserve_fieldnames = cache->preserve_fieldnames;
  11100. if (is_mapentry) {
  11101. /* mapentry messages are sufficiently different that we handle them
  11102. * separately. */
  11103. printer_sethandlers_mapentry(closure, preserve_fieldnames, h);
  11104. return;
  11105. }
  11106. switch (upb_msgdef_wellknowntype(md)) {
  11107. case UPB_WELLKNOWN_UNSPECIFIED:
  11108. break;
  11109. case UPB_WELLKNOWN_ANY:
  11110. printer_sethandlers_any(closure, h);
  11111. return;
  11112. case UPB_WELLKNOWN_FIELDMASK:
  11113. printer_sethandlers_fieldmask(closure, h);
  11114. return;
  11115. case UPB_WELLKNOWN_DURATION:
  11116. printer_sethandlers_duration(closure, h);
  11117. return;
  11118. case UPB_WELLKNOWN_TIMESTAMP:
  11119. printer_sethandlers_timestamp(closure, h);
  11120. return;
  11121. case UPB_WELLKNOWN_VALUE:
  11122. printer_sethandlers_value(closure, h);
  11123. return;
  11124. case UPB_WELLKNOWN_LISTVALUE:
  11125. printer_sethandlers_listvalue(closure, h);
  11126. return;
  11127. case UPB_WELLKNOWN_STRUCT:
  11128. printer_sethandlers_structvalue(closure, h);
  11129. return;
  11130. #define WRAPPER(wellknowntype, name) \
  11131. case wellknowntype: \
  11132. printer_sethandlers_##name(closure, h); \
  11133. return; \
  11134. WRAPPER(UPB_WELLKNOWN_DOUBLEVALUE, doublevalue);
  11135. WRAPPER(UPB_WELLKNOWN_FLOATVALUE, floatvalue);
  11136. WRAPPER(UPB_WELLKNOWN_INT64VALUE, int64value);
  11137. WRAPPER(UPB_WELLKNOWN_UINT64VALUE, uint64value);
  11138. WRAPPER(UPB_WELLKNOWN_INT32VALUE, int32value);
  11139. WRAPPER(UPB_WELLKNOWN_UINT32VALUE, uint32value);
  11140. WRAPPER(UPB_WELLKNOWN_BOOLVALUE, boolvalue);
  11141. WRAPPER(UPB_WELLKNOWN_STRINGVALUE, stringvalue);
  11142. WRAPPER(UPB_WELLKNOWN_BYTESVALUE, bytesvalue);
  11143. #undef WRAPPER
  11144. }
  11145. upb_handlers_setstartmsg(h, printer_startmsg, &empty_attr);
  11146. upb_handlers_setendmsg(h, printer_endmsg, &empty_attr);
  11147. #define TYPE(type, name, ctype) \
  11148. case type: \
  11149. if (upb_fielddef_isseq(f)) { \
  11150. upb_handlers_set##name(h, f, repeated_##ctype, &empty_attr); \
  11151. } else { \
  11152. upb_handlers_set##name(h, f, scalar_##ctype, &name_attr); \
  11153. } \
  11154. break;
  11155. upb_msg_field_begin(&i, md);
  11156. for(; !upb_msg_field_done(&i); upb_msg_field_next(&i)) {
  11157. const upb_fielddef *f = upb_msg_iter_field(&i);
  11158. upb_handlerattr name_attr = UPB_HANDLERATTR_INIT;
  11159. name_attr.handler_data = newstrpc(h, f, preserve_fieldnames);
  11160. if (upb_fielddef_ismap(f)) {
  11161. upb_handlers_setstartseq(h, f, startmap, &name_attr);
  11162. upb_handlers_setendseq(h, f, endmap, &name_attr);
  11163. } else if (upb_fielddef_isseq(f)) {
  11164. upb_handlers_setstartseq(h, f, startseq, &name_attr);
  11165. upb_handlers_setendseq(h, f, endseq, &empty_attr);
  11166. }
  11167. switch (upb_fielddef_type(f)) {
  11168. TYPE(UPB_TYPE_FLOAT, float, float);
  11169. TYPE(UPB_TYPE_DOUBLE, double, double);
  11170. TYPE(UPB_TYPE_BOOL, bool, bool);
  11171. TYPE(UPB_TYPE_INT32, int32, int32_t);
  11172. TYPE(UPB_TYPE_UINT32, uint32, uint32_t);
  11173. TYPE(UPB_TYPE_INT64, int64, int64_t);
  11174. TYPE(UPB_TYPE_UINT64, uint64, uint64_t);
  11175. case UPB_TYPE_ENUM: {
  11176. /* For now, we always emit symbolic names for enums. We may want an
  11177. * option later to control this behavior, but we will wait for a real
  11178. * need first. */
  11179. upb_handlerattr enum_attr = UPB_HANDLERATTR_INIT;
  11180. set_enum_hd(h, f, preserve_fieldnames, &enum_attr);
  11181. if (upb_fielddef_isseq(f)) {
  11182. upb_handlers_setint32(h, f, repeated_enum, &enum_attr);
  11183. } else {
  11184. upb_handlers_setint32(h, f, scalar_enum, &enum_attr);
  11185. }
  11186. break;
  11187. }
  11188. case UPB_TYPE_STRING:
  11189. if (upb_fielddef_isseq(f)) {
  11190. upb_handlers_setstartstr(h, f, repeated_startstr, &empty_attr);
  11191. upb_handlers_setstring(h, f, repeated_str, &empty_attr);
  11192. upb_handlers_setendstr(h, f, repeated_endstr, &empty_attr);
  11193. } else {
  11194. upb_handlers_setstartstr(h, f, scalar_startstr, &name_attr);
  11195. upb_handlers_setstring(h, f, scalar_str, &empty_attr);
  11196. upb_handlers_setendstr(h, f, scalar_endstr, &empty_attr);
  11197. }
  11198. break;
  11199. case UPB_TYPE_BYTES:
  11200. /* XXX: this doesn't support strings that span buffers yet. The base64
  11201. * encoder will need to be made resumable for this to work properly. */
  11202. if (upb_fielddef_isseq(f)) {
  11203. upb_handlers_setstring(h, f, repeated_bytes, &empty_attr);
  11204. } else {
  11205. upb_handlers_setstring(h, f, scalar_bytes, &name_attr);
  11206. }
  11207. break;
  11208. case UPB_TYPE_MESSAGE:
  11209. if (upb_fielddef_isseq(f)) {
  11210. upb_handlers_setstartsubmsg(h, f, repeated_startsubmsg, &name_attr);
  11211. } else {
  11212. upb_handlers_setstartsubmsg(h, f, scalar_startsubmsg, &name_attr);
  11213. }
  11214. break;
  11215. }
  11216. }
  11217. #undef TYPE
  11218. }
  11219. static void json_printer_reset(upb_json_printer *p) {
  11220. p->depth_ = 0;
  11221. }
  11222. /* Public API *****************************************************************/
  11223. upb_json_printer *upb_json_printer_create(upb_arena *a, const upb_handlers *h,
  11224. upb_bytessink output) {
  11225. #ifndef NDEBUG
  11226. size_t size_before = upb_arena_bytesallocated(a);
  11227. #endif
  11228. upb_json_printer *p = upb_arena_malloc(a, sizeof(upb_json_printer));
  11229. if (!p) return NULL;
  11230. p->output_ = output;
  11231. json_printer_reset(p);
  11232. upb_sink_reset(&p->input_, h, p);
  11233. p->seconds = 0;
  11234. p->nanos = 0;
  11235. /* If this fails, increase the value in printer.h. */
  11236. UPB_ASSERT_DEBUGVAR(upb_arena_bytesallocated(a) - size_before <=
  11237. UPB_JSON_PRINTER_SIZE);
  11238. return p;
  11239. }
  11240. upb_sink upb_json_printer_input(upb_json_printer *p) {
  11241. return p->input_;
  11242. }
  11243. upb_handlercache *upb_json_printer_newcache(bool preserve_proto_fieldnames) {
  11244. upb_json_printercache *cache = upb_gmalloc(sizeof(*cache));
  11245. upb_handlercache *ret = upb_handlercache_new(printer_sethandlers, cache);
  11246. cache->preserve_fieldnames = preserve_proto_fieldnames;
  11247. upb_handlercache_addcleanup(ret, cache, upb_gfree);
  11248. return ret;
  11249. }
  11250. /* See port_def.inc. This should #undef all macros #defined there. */
  11251. #undef UPB_SIZE
  11252. #undef UPB_FIELD_AT
  11253. #undef UPB_READ_ONEOF
  11254. #undef UPB_WRITE_ONEOF
  11255. #undef UPB_INLINE
  11256. #undef UPB_FORCEINLINE
  11257. #undef UPB_NOINLINE
  11258. #undef UPB_NORETURN
  11259. #undef UPB_MAX
  11260. #undef UPB_MIN
  11261. #undef UPB_UNUSED
  11262. #undef UPB_ASSERT
  11263. #undef UPB_ASSERT_DEBUGVAR
  11264. #undef UPB_UNREACHABLE
  11265. #undef UPB_INFINITY
  11266. #undef UPB_MSVC_VSNPRINTF
  11267. #undef _upb_snprintf
  11268. #undef _upb_vsnprintf
  11269. #undef _upb_va_copy